]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
reverted that last checking as it will not work with maps/0.mapcfg
[divverent/nexuiz.git] / data / qcsrc / server / g_world.qc
1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2
3 string GetMapname();
4 void GotoNextMap();
5 void HandleMaplistShuffleCommands();
6
7 void SetDefaultAlpha()
8 {
9         if(cvar("g_running_guns"))
10         {
11                 default_player_alpha = -1;
12                 default_weapon_alpha = +1;
13         }
14         else if(cvar("g_cloaked"))
15         {
16                 default_player_alpha = cvar("g_balance_cloaked_alpha");
17                 default_weapon_alpha = default_player_alpha;
18         }
19         else
20         {
21                 default_player_alpha = cvar("g_player_alpha");
22                 if(default_player_alpha <= 0)
23                         default_player_alpha = 1;
24                 default_weapon_alpha = default_player_alpha;
25         }
26 }
27
28 void fteqcc_testbugs()
29 {
30         float a, b;
31
32         if(!cvar("developer_fteqccbugs"))
33                 return;
34
35         dprint("*** fteqcc test: checking for bugs...\n");
36
37         a = 1;
38         b = 5;
39         if(sqrt(a) - sqrt(b - a) == 0)
40                 dprint("*** fteqcc test: found same-function-twice bug\n");
41         else
42                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
43
44         world.frags = -10;
45         world.enemy = world;
46         world.enemy.frags += 10;
47         if(world.frags > 0.2 || world.frags < -0.2) // don't error out if it's just roundoff errors
48                 dprint("*** fteqcc test: found += bug\n");
49         else
50                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
51         world.frags = 0;
52 }
53
54 void GotoFirstMap()
55 {
56         if(cvar("_sv_init"))
57         {
58                 cvar_set("_sv_init", "0");
59                 HandleMaplistShuffleCommands();
60                 tokenize(cvar_string("g_maplist"));
61                 if(argv(0) != GetMapname())
62                 {
63                         cvar_set("nextmap", argv(0));
64                         GotoNextMap();
65                 }
66         }
67 }
68
69 float world_already_spawned;
70 void worldspawn (void)
71 {
72         if(world_already_spawned)
73                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
74         world_already_spawned = TRUE;
75         // Precache all player models
76         // Workaround for "invisible players"
77         precache_model("models/player/carni.zym");
78         precache_model("models/player/crash.zym");
79         precache_model("models/player/grunt.zym");
80         precache_model("models/player/headhunter.zym");
81         precache_model("models/player/insurrectionist.zym");
82         precache_model("models/player/jeandarc.zym");
83         precache_model("models/player/lurk.zym");
84         precache_model("models/player/lycanthrope.zym");
85         precache_model("models/player/marine.zym");
86         precache_model("models/player/nexus.zym");
87         precache_model("models/player/pyria.zym");
88         precache_model("models/player/shock.zym");
89         precache_model("models/player/skadi.zym");
90         precache_model("models/player/specop.zym");
91         precache_model("models/player/visitant.zym");
92
93         //precache_model ("progs/beam.mdl");
94         precache_model ("models/bullet.mdl");
95         precache_model ("models/casing_bronze.mdl");
96         precache_model ("models/casing_shell.mdl");
97         precache_model ("models/casing_steel.mdl");
98         precache_model ("models/ebomb.mdl");
99         precache_model ("models/elaser.mdl");
100         precache_model ("models/flash.md3");
101         precache_model ("models/gibs/bloodyskull.md3");
102         precache_model ("models/gibs/chunk.mdl");
103         precache_model ("models/gibs/eye.md3");
104         precache_model ("models/gibs/gib1.md3");
105         //precache_model ("models/gibs/gib2.md3");
106         //precache_model ("models/gibs/gib3.md3");
107         //precache_model ("models/gibs/gib4.md3");
108         precache_model ("models/gibs/gib5.md3");
109         //precache_model ("models/gibs/gib6.md3");
110         precache_model ("models/gibs/gib1.mdl");
111         precache_model ("models/gibs/gib2.mdl");
112         precache_model ("models/gibs/gib3.mdl");
113         precache_model ("models/grenademodel.md3");
114         precache_model ("models/hagarmissile.mdl");
115         precache_model ("models/items/a_bullets.mdl");
116         precache_model ("models/items/a_cells.md3");
117         precache_model ("models/items/a_rockets.md3");
118         precache_model ("models/items/a_shells.md3");
119         precache_model ("models/items/g_a1.md3");
120         precache_model ("models/items/g_a25.md3");
121         precache_model ("models/items/g_h1.md3");
122         precache_model ("models/items/g_h25.md3");
123         precache_model ("models/items/g_h100.md3");
124         precache_model ("models/items/g_invincible.md3");
125         precache_model ("models/items/g_strength.md3");
126         precache_model ("models/laser.mdl");
127         precache_model ("models/misc/chatbubble.spr");
128         precache_model ("models/misc/teambubble.spr");
129         precache_model ("models/nexflash.md3");
130         precache_model ("models/plasma.mdl");
131         precache_model ("models/plasmatrail.mdl");
132         precache_model ("models/rocket.md3");
133         //precache_model ("models/sprites/grenexpl.spr");
134         precache_model ("models/runematch/rune.mdl");
135         precache_model ("models/runematch/curse.mdl");
136         //precache_model ("models/sprites/hagar.spr");
137         //precache_model ("models/sprites/muzzleflash.spr32");
138         //precache_model ("models/sprites/electrocombo.spr32");
139         //precache_model ("models/sprites/plasmahitwall.spr32");
140         //precache_model ("models/sprites/plasmashot.spr32");
141         //precache_model ("models/sprites/rockexpl.spr");
142         precache_model ("models/tracer.mdl");
143         precache_model ("models/uziflash.md3");
144         precache_model ("models/weapons/g_crylink.md3");
145         precache_model ("models/weapons/g_electro.md3");
146         precache_model ("models/weapons/g_gl.md3");
147         precache_model ("models/weapons/g_hagar.md3");
148         precache_model ("models/weapons/g_nex.md3");
149         precache_model ("models/weapons/g_rl.md3");
150         precache_model ("models/weapons/g_shotgun.md3");
151         precache_model ("models/weapons/g_uzi.md3");
152         precache_model ("models/weapons/v_crylink.md3");
153         precache_model ("models/weapons/v_electro.md3");
154         precache_model ("models/weapons/v_gl.md3");
155         precache_model ("models/weapons/v_hagar.md3");
156         precache_model ("models/weapons/v_laser.md3");
157         precache_model ("models/weapons/v_nex.md3");
158         precache_model ("models/weapons/v_rl.md3");
159         precache_model ("models/weapons/v_shotgun.md3");
160         precache_model ("models/weapons/v_uzi.md3");
161         precache_model ("models/weapons/w_crylink.zym");
162         precache_model ("models/weapons/w_electro.zym");
163         precache_model ("models/weapons/w_gl.zym");
164         precache_model ("models/weapons/w_hagar.zym");
165         precache_model ("models/weapons/w_laser.zym");
166         precache_model ("models/weapons/w_nex.zym");
167         precache_model ("models/weapons/w_rl.zym");
168         precache_model ("models/weapons/w_shotgun.zym");
169         precache_model ("models/weapons/w_uzi.zym");
170
171         // laser for laser-guided weapons
172         precache_model ("models/laser_dot.mdl");
173
174         precache_sound ("misc/null.wav");
175         precache_sound ("misc/armor1.wav");
176         precache_sound ("misc/armor25.wav");
177         precache_sound ("misc/armorimpact.wav");
178         precache_sound ("misc/bodyimpact1.wav");
179         precache_sound ("misc/bodyimpact2.wav");
180         precache_sound ("misc/gib.wav");
181         precache_sound ("misc/gib_splat01.wav");
182         precache_sound ("misc/gib_splat02.wav");
183         precache_sound ("misc/gib_splat03.wav");
184         precache_sound ("misc/gib_splat04.wav");
185         //precache_sound ("misc/h2ohit.wav");
186         precache_sound ("misc/hit.wav");
187         precache_sound ("misc/footstep01.wav");
188         precache_sound ("misc/footstep02.wav");
189         precache_sound ("misc/footstep03.wav");
190         precache_sound ("misc/footstep04.wav");
191         precache_sound ("misc/footstep05.wav");
192         precache_sound ("misc/footstep06.wav");
193         precache_sound ("misc/hitground1.ogg");
194         precache_sound ("misc/hitground2.ogg");
195         precache_sound ("misc/hitground3.ogg");
196         precache_sound ("misc/hitground4.ogg");
197         precache_sound ("misc/itempickup.ogg");
198         precache_sound ("misc/itemrespawn.ogg");
199         precache_sound ("misc/jumppad.ogg");
200         precache_sound ("misc/mediumhealth.ogg");
201         precache_sound ("misc/megahealth.ogg");
202         precache_sound ("misc/minihealth.ogg");
203         precache_sound ("misc/powerup.ogg");
204         precache_sound ("misc/powerup_shield.ogg");
205         precache_sound ("misc/talk.wav");
206         precache_sound ("misc/teleport.ogg");
207         precache_sound ("plats/medplat1.wav");
208         precache_sound ("plats/medplat2.wav");
209         precache_sound ("player/lava.wav");
210         precache_sound ("player/slime.wav");
211         precache_sound ("weapons/crylink_fire.ogg");
212         precache_sound ("weapons/electro_bounce.ogg");
213         precache_sound ("weapons/electro_fire.ogg");
214         precache_sound ("weapons/electro_fire2.ogg");
215         precache_sound ("weapons/electro_fly.wav");
216         precache_sound ("weapons/electro_impact.ogg");
217         precache_sound ("weapons/electro_impact_combo.ogg");
218         //precache_sound ("weapons/grenade_bounce.ogg");
219         precache_sound ("weapons/grenade_bounce1.ogg");
220         precache_sound ("weapons/grenade_bounce2.ogg");
221         precache_sound ("weapons/grenade_bounce3.ogg");
222         precache_sound ("weapons/grenade_fire.ogg");
223         precache_sound ("weapons/grenade_impact.ogg");
224         precache_sound ("weapons/hagar_fire.ogg");
225         precache_sound ("weapons/hagexp1.ogg");
226         precache_sound ("weapons/hagexp2.ogg");
227         precache_sound ("weapons/hagexp3.ogg");
228         precache_sound ("weapons/hook_fire.ogg");
229         precache_sound ("weapons/hook_impact.ogg");
230         precache_sound ("weapons/lasergun_fire.ogg");
231         precache_sound ("weapons/laserimpact.ogg");
232         precache_sound ("weapons/nexfire.ogg");
233         precache_sound ("weapons/neximpact.ogg");
234         precache_sound ("weapons/ric1.ogg");
235         precache_sound ("weapons/ric2.ogg");
236         precache_sound ("weapons/ric3.ogg");
237         precache_sound ("weapons/rocket_fire.ogg");
238         precache_sound ("weapons/rocket_fly.wav");
239         precache_sound ("weapons/rocket_impact.ogg");
240         precache_sound ("weapons/rocket_det.ogg");
241         precache_sound ("weapons/shotgun_fire.ogg");
242         precache_sound ("weapons/tink1.ogg");
243         precache_sound ("weapons/uzi_fire.ogg");
244         precache_sound ("weapons/weapon_switch.ogg");
245         precache_sound ("weapons/weaponpickup.ogg");
246         precache_sound ("weapons/strength_fire.ogg");
247
248         //precache_sound ("announce/male/kill10.ogg");
249         //precache_sound ("announce/male/kill15.ogg");
250         //precache_sound ("announce/male/kill20.ogg");
251         //precache_sound ("announce/male/kill25.ogg");
252         //precache_sound ("announce/male/kill3.ogg");
253         //precache_sound ("announce/male/kill30.ogg");
254         //precache_sound ("announce/male/kill4.ogg");
255         //precache_sound ("announce/male/kill5.ogg");
256         //precache_sound ("announce/male/kill6.ogg");
257         //precache_sound ("announce/male/mapkill1.ogg");
258         //precache_sound ("announce/robotic/last_second_save.ogg");
259         //precache_sound ("announce/robotic/narrowly_averted.ogg");
260         //precache_sound ("minstagib/mockery.ogg");
261
262         // announcer sounds - male
263         precache_sound ("announcer/male/03kills.ogg");
264         precache_sound ("announcer/male/05kills.ogg");
265         precache_sound ("announcer/male/10kills.ogg");
266         precache_sound ("announcer/male/15kills.ogg");
267         precache_sound ("announcer/male/20kills.ogg");
268         precache_sound ("announcer/male/25kills.ogg");
269         precache_sound ("announcer/male/30kills.ogg");
270         precache_sound ("announcer/male/botlike.ogg");
271         precache_sound ("announcer/male/electrobitch.ogg");
272         precache_sound ("announcer/male/welcome.ogg");
273         precache_sound ("announcer/male/yoda.ogg");
274
275         // announcer sounds - robotic
276         precache_sound ("announcer/robotic/1fragleft.ogg");
277         precache_sound ("announcer/robotic/1minuteremains.ogg");
278         precache_sound ("announcer/robotic/2fragsleft.ogg");
279         precache_sound ("announcer/robotic/3fragsleft.ogg");
280         precache_sound ("announcer/robotic/lastsecond.ogg");
281         precache_sound ("announcer/robotic/narrowly.ogg");
282         precache_sound ("announcer/robotic/1.ogg");
283         precache_sound ("announcer/robotic/2.ogg");
284         precache_sound ("announcer/robotic/3.ogg");
285         precache_sound ("announcer/robotic/4.ogg");
286         precache_sound ("announcer/robotic/5.ogg");
287         precache_sound ("announcer/robotic/6.ogg");
288         precache_sound ("announcer/robotic/7.ogg");
289         precache_sound ("announcer/robotic/8.ogg");
290         precache_sound ("announcer/robotic/9.ogg");
291         precache_sound ("announcer/robotic/10.ogg");
292
293         // plays music for the level if there is any
294         if (self.noise)
295         {
296                 precache_sound (self.noise);
297                 ambientsound ('0 0 0', self.noise, 1.00, ATTN_NONE);
298         }
299
300         // 0 normal
301         lightstyle(0, "m");
302
303         // 1 FLICKER (first variety)
304         lightstyle(1, "mmnmmommommnonmmonqnmmo");
305
306         // 2 SLOW STRONG PULSE
307         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
308
309         // 3 CANDLE (first variety)
310         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
311
312         // 4 FAST STROBE
313         lightstyle(4, "mamamamamama");
314
315         // 5 GENTLE PULSE 1
316         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
317
318         // 6 FLICKER (second variety)
319         lightstyle(6, "nmonqnmomnmomomno");
320
321         // 7 CANDLE (second variety)
322         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
323
324         // 8 CANDLE (third variety)
325         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
326
327         // 9 SLOW STROBE (fourth variety)
328         lightstyle(9, "aaaaaaaazzzzzzzz");
329
330         // 10 FLUORESCENT FLICKER
331         lightstyle(10, "mmamammmmammamamaaamammma");
332
333         // 11 SLOW PULSE NOT FADE TO BLACK
334         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
335
336         // styles 32-62 are assigned by the light program for switchable lights
337
338         // 63 testing
339         lightstyle(63, "a");
340
341         registercvar("_g_maplist_shufflenow", "0");
342         registercvar("_g_maplist_have_shuffled", "0");
343
344         player_count = 0;
345         lms_lowest_lives = 0;
346         lms_next_place = 0;
347
348         GotoFirstMap();
349
350         bot_waypoints_for_items = cvar("g_waypoints_for_items");
351         if(bot_waypoints_for_items == 1)
352                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
353                         bot_waypoints_for_items = 0;
354
355         if(cvar("g_campaign"))
356                 CampaignPreInit();
357
358         InitGameplayMode();
359         //if (cvar("g_domination"))
360         //      dom_init();
361
362         local entity head;
363         head = nextent(world);
364         maxclients = 0;
365         while(head)
366         {
367                 maxclients++;
368                 head = nextent(head);
369         }
370
371         GameLogInit(); // prepare everything
372         if(cvar("sv_eventlog"))
373         {
374                 local string s;
375                 GameLogEcho(":logversion:2", FALSE);
376                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
377                 s = strcat(s, ftos(random()));
378                 GameLogEcho(strcat(":gamestart:", GetMapname(), ":", s), FALSE);
379                 s = ":gameinfo:mutators:LIST";
380                 if(cvar("g_grappling_hook"))
381                         s = strcat(s, ":grappling_hook");
382                 if(!cvar("g_use_ammunition"))
383                         s = strcat(s, ":no_use_ammunition");
384                 if(!cvar("g_pickup_items"))
385                         s = strcat(s, ":no_pickup_items");
386                 if(cvar("g_instagib"))
387                         s = strcat(s, ":instagib");
388                 if(cvar("g_rocketarena"))
389                         s = strcat(s, ":rockerarena");
390                 if(cvar("g_nixnex"))
391                         s = strcat(s, ":nixnex");
392                 if(cvar("g_vampire"))
393                         s = strcat(s, ":vampire");
394                 if(cvar("g_laserguided_missile"))
395                         s = strcat(s, ":laserguided_missile");
396                 if(cvar("g_norecoil"))
397                         s = strcat(s, ":norecoil");
398                 if(cvar("g_midair"))
399                         s = strcat(s, ":midair");
400                 if(cvar("g_minstagib"))
401                         s = strcat(s, ":minstagib");
402                 GameLogEcho(s, FALSE);
403                 GameLogEcho(":gameinfo:end", FALSE);
404         }
405
406         cvar_set("nextmap", "");
407
408         SetDefaultAlpha();
409
410         if(cvar("g_campaign"))
411                 CampaignPostInit();
412
413         // fteqcc_testbugs();
414 }
415
416 void light (void)
417 {
418         //makestatic (self); // Who the f___ did that?
419         remove(self);
420 }
421
422 float( string pFilename ) TryFile =
423 {
424         local float lHandle;
425         dprint("TryFile(\"", pFilename, "\")\n");
426         lHandle = fopen( pFilename, FILE_READ );
427         if( lHandle != -1 ) {
428                 fclose( lHandle );
429                 return TRUE;
430         } else {
431                 return FALSE;
432         }
433 };
434
435 string GetGametype()
436 {
437         if (game == GAME_DEATHMATCH)
438                 return "dm";
439         else if (game == GAME_TEAM_DEATHMATCH)
440                 return "tdm";
441         else if (game == GAME_DOMINATION)
442                 return "dom";
443         else if (game == GAME_CTF)
444                 return "ctf";
445         else if (game == GAME_RUNEMATCH)
446                 return "rune";
447         else if (game == GAME_LMS)
448                 return "lms";
449         return "dm";
450 }
451
452 string GetMapname()
453 {
454         return strcat(GetGametype(), "_", mapname);
455 }
456
457 float Map_Count, Map_Current;
458 string Map_Current_Name;
459
460 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
461 float GetMaplistPosition()
462 {
463         float pos, idx;
464         string map;
465
466         map = GetMapname();
467         idx = cvar("g_maplist_index");
468
469         if(idx >= 0)
470                 if(idx < Map_Count)
471                         if(map == argv(idx))
472                                 return idx;
473
474         for(pos = 0; pos < Map_Count; ++pos)
475                 if(map == argv(pos))
476                         return pos;
477
478         // resume normal maplist rotation if current map is not in g_maplist
479         return idx;
480 }
481
482 float MapHasRightSize(string map)
483 {
484         // open map size restriction file
485         float fh;
486         dprint("opensize "); dprint(map);
487         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
488         if(fh >= 0)
489         {
490                 float mapmin, mapmax;
491                 dprint(": ok, ");
492                 mapmin = stof(fgets(fh));
493                 mapmax = stof(fgets(fh));
494                 fclose(fh);
495                 if(player_count < mapmin)
496                 {
497                         dprint("not enough\n");
498                         return FALSE;
499                 }
500                 if(player_count > mapmax)
501                 {
502                         dprint("too many\n");
503                         return FALSE;
504                 }
505                 dprint("right size\n");
506                 return TRUE;
507         }
508         dprint(": not found\n");
509         return TRUE;
510 }
511
512 string Map_Filename(float position)
513 {
514         return strcat("maps/", argv(position), ".mapcfg");
515 }
516
517 float(float position, float pass) Map_Check =
518 {
519         string filename;
520         string map_next;
521         map_next = argv(position);
522         if(pass <= 1)
523                 if(map_next == Map_Current_Name) // same map again in first pass?
524                         return 0;
525         filename = Map_Filename(position);
526         if(TryFile(filename))
527         {
528                 if(pass == 2)
529                         return 1;
530                 if(MapHasRightSize(argv(position)))
531                         return 1;
532                 return 0;
533         }
534         else
535                 dprint( "Couldn't find '", filename, "'..\n" );
536
537         return 0;
538 }
539
540 void(float position) Map_Goto =
541 {
542         cvar_set("g_maplist_index", ftos(position));
543         localcmd(strcat("exec \"", Map_Filename(position) ,"\"\n"));
544 }
545
546 // return codes of map selectors:
547 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
548 //   -2 = permanent failure
549 float() MaplistMethod_Iterate = // usual method
550 {
551         float pass, i;
552
553         for(pass = 1; pass <= 2; ++pass)
554         {
555                 for(i = 1; i < Map_Count; ++i)
556                 {
557                         float mapindex;
558                         mapindex = math_mod(i + Map_Current, Map_Count);
559                         if(Map_Check(mapindex, pass))
560                                 return mapindex;
561                 }
562         }
563         return -1;
564 }
565
566 float() MaplistMethod_Repeat = // fallback method
567 {
568         if(Map_Check(Map_Current, 2))
569                 return Map_Current;
570         return -2;
571 }
572
573 float() MaplistMethod_Random = // random map selection
574 {
575         float i, imax;
576
577         imax = 42;
578
579         for(i = 0; i <= imax; ++i)
580         {
581                 float mapindex;
582                 mapindex = math_mod(Map_Current + ceil(random() * (Map_Count - 1)), Map_Count); // any OTHER map
583                 if(Map_Check(mapindex, 1))
584                         return mapindex;
585         }
586         return -1;
587 }
588
589 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
590 // the exponent sets a bias on the map selection:
591 // the higher the exponent, the 
592 {
593         float i, j, imax, insertpos;
594
595         imax = 42;
596
597         if(Map_Count <= 1)
598                 return 0; // only one map, then always play this one
599
600         for(i = 0; i <= imax; ++i)
601         {
602                 string newlist;
603
604                 // now reinsert this at another position
605                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
606                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
607                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
608                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
609
610                 // insert the current map there
611                 newlist = "";
612                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
613                         newlist = strcat(newlist, "'", argv(j), "'");
614                 newlist = strcat(newlist, "'", argv(0), "'");  // now insert the just selected map
615                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
616                         newlist = strcat(newlist, "'", argv(j), "'");
617                 cvar_set("g_maplist", newlist);
618                 Map_Count = tokenize(newlist);
619
620                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
621                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
622                 if(Map_Check(Map_Current, 1))
623                         return Map_Current;
624         }
625         return -1;
626 }
627
628 void() Maplist_Init =
629 {
630         string temp;
631         temp = cvar_string("g_maplist");
632         Map_Count = tokenize(temp);
633         if(Map_Count == 0)
634         {
635                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
636                 cvar_set("g_maplist", temp = cvar_string("g_maplist_defaultlist"));
637                 Map_Count = tokenize(temp);
638         }
639         if(Map_Count == 0)
640                 error("empty maplist, cannot select a new map");
641         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
642
643         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
644         // this may or may not be correct, but who cares, in the worst case a map
645         // isn't chosen in the first pass that should have been
646 }
647
648 void() GotoNextMap =
649 {
650         //local string nextmap;
651         //local float n, nummaps;
652         //local string s;
653         string exit_cfg;
654         if (alreadychangedlevel)
655                 return;
656         alreadychangedlevel = TRUE;
657
658         if(cvar("g_campaign"))
659         {
660                 CampaignPostIntermission();
661                 return;
662         }
663
664         if(cvar("quit_when_empty"))
665         {
666                 if(player_count <= currentbots)
667                 {
668                         localcmd("quit\n");
669                         return;
670                 }
671         }
672
673         if (cvar("samelevel")) // if samelevel is set, stay on same level
674         {
675                 // this does not work because it tries to exec maps/nexdm01.mapcfg (which doesn't exist, it should be trying maps/dm_nexdm01.mapcfg for example)
676                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
677                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
678                 localcmd("restart\n");
679                 //changelevel (mapname);
680                 return;
681         }
682
683         // if an exit cfg is defined by exiting map, exec it.
684         exit_cfg = cvar_string("exit_cfg");
685         if(exit_cfg != "")
686                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
687
688         localcmd("exec game_reset.cfg\n");
689
690
691         if (cvar("lastlevel"))
692         {
693                 localcmd(strcat("set lastlevel 0\n"));
694                 localcmd(strcat("togglemenu\n"));
695         }
696         else
697         {
698                 float nextMap;
699                 float allowReset;
700
701                 // cvar "nextmap" always gets priority
702                 if(cvar_string("nextmap") != "")
703                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
704                 {
705                         localcmd(strcat("exec \"maps/", cvar_string("nextmap"), ".mapcfg\"\n"));
706                         return;
707                 }
708
709                 for(allowReset = 1; allowReset >= 0; --allowReset)
710                 {
711                         Maplist_Init();
712                         nextMap = -1;
713
714                         if(nextMap == -1)
715                                 if(cvar("g_maplist_shuffle") > 0)
716                                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
717
718                         if(nextMap == -1)
719                                 if(cvar("g_maplist_selectrandom"))
720                                         nextMap = MaplistMethod_Random();
721
722                         if(nextMap == -1)
723                                 nextMap = MaplistMethod_Iterate();
724
725                         if(nextMap == -1)
726                                 nextMap = MaplistMethod_Repeat();
727
728                         if(nextMap >= 0)
729                         {
730                                 Map_Goto(nextMap);
731                                 break;
732                         }
733                         else // PERMANENT FAILURE
734                         {
735                                 if(allowReset)
736                                 {
737                                         bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
738                                         cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
739                                 }
740                                 else
741                                 {
742                                         error("Everything is broken - not even the default map list works. Please report this to the developers.");
743                                 }
744                         }
745                 }
746         }
747 };
748
749
750 /*
751 ============
752 IntermissionThink
753
754 When the player presses attack or jump, change to the next level
755 ============
756 */
757 .float autoscreenshot;
758 void() IntermissionThink =
759 {
760         if(cvar("sv_autoscreenshot"))
761         if(self.autoscreenshot)
762         if(time > self.autoscreenshot)
763         {
764                 self.autoscreenshot = FALSE;
765                 if(clienttype(self) == CLIENTTYPE_REAL)
766                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
767                 return;
768         }
769
770         if (time < intermission_exittime)
771                 return;
772
773         if (time < intermission_exittime + 10 && !self.button0 && !self.button2 && !self.button3 && !self.button6 && !self.buttonuse)
774                 return;
775
776         GotoNextMap ();
777 };
778
779 /*
780 ============
781 FindIntermission
782
783 Returns the entity to view from
784 ============
785 */
786 /*
787 entity() FindIntermission =
788 {
789         local   entity spot;
790         local   float cyc;
791
792 // look for info_intermission first
793         spot = find (world, classname, "info_intermission");
794         if (spot)
795         {       // pick a random one
796                 cyc = random() * 4;
797                 while (cyc > 1)
798                 {
799                         spot = find (spot, classname, "info_intermission");
800                         if (!spot)
801                                 spot = find (spot, classname, "info_intermission");
802                         cyc = cyc - 1;
803                 }
804                 return spot;
805         }
806
807 // then look for the start position
808         spot = find (world, classname, "info_player_start");
809         if (spot)
810                 return spot;
811
812 // testinfo_player_start is only found in regioned levels
813         spot = find (world, classname, "testplayerstart");
814         if (spot)
815                 return spot;
816
817 // then look for the start position
818         spot = find (world, classname, "info_player_deathmatch");
819         if (spot)
820                 return spot;
821
822         //objerror ("FindIntermission: no spot");
823         return world;
824 };
825 */
826
827 /*
828 ===============================================================================
829
830 RULES
831
832 ===============================================================================
833 */
834
835 void() DumpStats =
836 {
837         local float file;
838         local string s;
839
840         if(cvar("_printstats"))
841                 cvar_set("_printstats", "0");
842         else if(!gameover)
843                 return;
844
845         if(gameover)
846                 s = ":scores:";
847         else
848                 s = ":status:";
849
850         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
851
852         if(cvar("sv_eventlog") && gameover)
853                 GameLogEcho(s, FALSE);
854         else if(cvar("sv_logscores_console"))
855                 ServerConsoleEcho(s, FALSE);
856         if(cvar("sv_logscores_file"))
857         {
858                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
859                 fputs(file, strcat(s, "\n"));
860         }
861
862         other = findchainflags(flags, FL_CLIENT);
863         while (other)
864         {
865                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
866                 {
867                         s = strcat(":player:", ftos(other.frags), ":");
868                         s = strcat(s, ftos(other.deaths), ":");
869                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
870                         s = strcat(s, ftos(other.team), ":");
871
872                         if(cvar("sv_logscores_file"))
873                                 fputs(file, strcat(s, other.netname, "\n"));
874                         if(cvar("sv_eventlog") && gameover)
875                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
876                         else if(cvar("sv_logscores_console"))
877                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
878                 }
879                 other = other.chain;
880         }
881
882         if(cvar("sv_eventlog") && gameover)
883                 GameLogEcho(":end", FALSE);
884         else if(cvar("sv_logscores_console"))
885                 ServerConsoleEcho(":end", FALSE);
886         if(cvar("sv_logscores_file"))
887         {
888                 fputs(file, ":end\n");
889                 fclose(file);
890         }
891 }
892
893
894 /*
895 go to the next level for deathmatch
896 only called if a time or frag limit has expired
897 */
898 void() NextLevel =
899 {
900         gameover = TRUE;
901
902         intermission_running = 1;
903
904 // enforce a wait time before allowing changelevel
905         if(player_count > 0)
906                 intermission_exittime = time + cvar("sv_mapchange_delay");
907         else
908                 intermission_exittime = -60;
909
910         WriteByte (MSG_ALL, SVC_CDTRACK);
911         WriteByte (MSG_ALL, 3);
912         WriteByte (MSG_ALL, 3);
913
914         //pos = FindIntermission ();
915
916         VoteReset();
917
918         DumpStats();
919
920         if(cvar("sv_eventlog"))
921                 GameLogEcho(":gameover", FALSE);
922
923         GameLogClose();
924
925         other = findchainflags(flags, FL_CLIENT);
926         while (other != world)
927         {
928                 //other.nextthink = time + 0.5;
929                 other.takedamage = DAMAGE_NO;
930                 other.solid = SOLID_NOT;
931                 other.movetype = MOVETYPE_NONE;
932                 other.angles = other.v_angle;
933                 other.angles_x = other.angles_x * -1;
934                 other.autoscreenshot = time + 0.8;      // used for autoscreenshot
935
936                 self = other;
937
938                 if(other.winning)
939                         bprint(strcat(other.netname, " ^7wins.\n"));
940
941                 /*
942                 if (pos != world);
943                 {
944                         other.modelindex = 0;
945                         other.weaponentity = world; // remove weapon model
946                         other.view_ofs = '0 0 0';
947                         other.angles = other.v_angle = pos.mangle;
948                         if (!other.angles)
949                         {
950                                 other.angles = other.v_angle = pos.angles;
951                                 other.v_angle_x = other.v_angle_x * -1;
952                         }
953                         other.fixangle = TRUE;          // turn this way immediately
954                         setorigin (other, pos.origin);
955                 }
956                 */
957                 other = other.chain;
958         }
959
960         if(cvar("g_campaign"))
961                 CampaignPreIntermission();
962
963         WriteByte (MSG_ALL, SVC_INTERMISSION);
964 };
965
966 /*
967 ============
968 CheckRules_Player
969
970 Exit deathmatch games upon conditions
971 ============
972 */
973 void() CheckRules_Player =
974 {
975         if (gameover)   // someone else quit the game already
976                 return;
977
978         // fixme: don't check players; instead check dom_team and ctf_team entities
979         //   (div0: and that in CheckRules_World please)
980 };
981
982 float checkrules_oneminutewarning;
983 float checkrules_leaderfrags;
984 float tdm_max_score, tdm_old_score;
985
986 float checkrules_equality;
987 float checkrules_overtimewarning;
988 float checkrules_overtimeend;
989
990 void() InitiateOvertime =
991 {
992         if(!checkrules_overtimeend)
993                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
994 }
995
996 float WINNING_NO = 0; // no winner, but time limits may terminate the game
997 float WINNING_YES = 1; // winner found
998 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
999 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1000
1001 float(float fraglimitreached, float equality) GetWinningCode =
1002 {
1003         if(equality)
1004                 if(fraglimitreached)
1005                         return WINNING_STARTOVERTIME;
1006                 else
1007                         return WINNING_NEVER;
1008         else
1009                 if(fraglimitreached)
1010                         return WINNING_YES;
1011                 else
1012                         return WINNING_NO;
1013 }
1014
1015 // set the .winning flag for exactly those players with a given field value
1016 void(.float field, float value) SetWinners =
1017 {
1018         entity head;
1019         head = findchain(classname, "player");
1020         while (head)
1021         {
1022                 head.winning = (head.field == value);
1023                 head = head.chain;
1024         }
1025 }
1026
1027 // set the .winning flag for those players with a given field value
1028 void(.float field, float value) AddWinners =
1029 {
1030         entity head;
1031         head = findchain(classname, "player");
1032         while (head)
1033         {
1034                 if(head.field == value)
1035                         head.winning = 1;
1036                 head = head.chain;
1037         }
1038 }
1039
1040 // clear the .winning flags
1041 void(void) ClearWinners =
1042 {
1043         entity head;
1044         head = findchain(classname, "player");
1045         while (head)
1046         {
1047                 head.winning = 0;
1048                 head = head.chain;
1049         }
1050 }
1051
1052 float() LMS_NewPlayerLives =
1053 {
1054         float fl;
1055         fl = cvar("fraglimit");
1056         if(fl == 0)
1057                 fl = 999;
1058
1059         // first player has left the game for dying too much? Nobody else can get in.
1060         if(lms_lowest_lives < 1)
1061                 return FALSE;
1062
1063         if(!cvar("g_lms_join_anytime"))
1064                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1065                         return FALSE;
1066
1067         return bound(1, lms_lowest_lives, fl);
1068 }
1069
1070 // LMS winning condition: game terminates if and only if there's at most one
1071 // one player who's living lives. Top two scores being equal cancels the time
1072 // limit.
1073 float() WinningCondition_LMS =
1074 {
1075         entity head;
1076         float have_player;
1077         float have_players;
1078         float l;
1079
1080         have_player = FALSE;
1081         have_players = FALSE;
1082         l = LMS_NewPlayerLives();
1083
1084         head = find(world, classname, "player");
1085         if(head)
1086                 have_player = TRUE;
1087         head = find(head, classname, "player");
1088         if(head)
1089                 have_players = TRUE;
1090
1091         if(have_player)
1092         {
1093                 // we have at least one player
1094                 if(have_players)
1095                 {
1096                         // two or more active players - continue with the game
1097                 }
1098                 else
1099                 {
1100                         // exactly one player?
1101                         if(l)
1102                         {
1103                                 // but no game has taken place yet
1104                         }
1105                         else
1106                         {
1107                                 // a winner!
1108                                 ClearWinners(); SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1109                                 dprint("Have a winner, ending game.\n");
1110                                 return WINNING_YES;
1111                         }
1112                 }
1113         }
1114         else
1115         {
1116                 // nobody is playing at all...
1117                 if(l)
1118                 {
1119                         // wait for players...
1120                 }
1121                 else
1122                 {
1123                         // SNAFU (maybe a draw game?)
1124                         ClearWinners();
1125                         dprint("No players, ending game.\n");
1126                         return WINNING_YES;
1127                 }
1128         }
1129
1130         // When we get here, we have at least two players who are actually LIVING,
1131         // or one player who is still waiting for a victim to join the server. Now
1132         // check if the top two players have equal score.
1133
1134         checkrules_leaderfrags = 0;
1135         head = findchain(classname, "player");
1136         checkrules_equality = FALSE;
1137         while (head)
1138         {
1139                 if(head.frags > checkrules_leaderfrags)
1140                 {
1141                         checkrules_leaderfrags = head.frags;
1142                         checkrules_equality = FALSE;
1143                 }
1144                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1145                         checkrules_equality = TRUE;
1146                 head = head.chain;
1147         }
1148
1149         SetWinners(frags, checkrules_leaderfrags);
1150
1151         // The top two players have the same amount of lives? No timelimit then,
1152         // enter overtime...
1153
1154         if(checkrules_equality)
1155                 return WINNING_NEVER;
1156
1157         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1158         return WINNING_NO;
1159 }
1160
1161 // DM winning condition: game terminates if a player reached the fraglimit,
1162 // unless the first two players have the same score. The latter case also
1163 // breaks the time limit.
1164 float(float fraglimit) WinningCondition_MaxIndividualScore =
1165 {
1166         float checkrules_oldleaderfrags;
1167         entity head;
1168
1169         checkrules_oldleaderfrags = checkrules_leaderfrags;
1170         checkrules_leaderfrags = 0;
1171         head = findchain(classname, "player");
1172         checkrules_equality = FALSE;
1173         while (head)
1174         {
1175                 if(head.frags > checkrules_leaderfrags)
1176                 {
1177                         checkrules_leaderfrags = head.frags;
1178                         checkrules_equality = FALSE;
1179                 }
1180                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1181                         checkrules_equality = TRUE;
1182                 head = head.chain;
1183         }
1184
1185         if(checkrules_leaderfrags > 0)
1186                 SetWinners(frags, checkrules_leaderfrags);
1187         else
1188                 ClearWinners();
1189
1190         if (!cvar("g_runematch"))
1191                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1192                 {
1193                         if (checkrules_leaderfrags == fraglimit - 1)
1194                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.ogg", 1, ATTN_NONE);
1195                         else if (checkrules_leaderfrags == fraglimit - 2)
1196                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.ogg", 1, ATTN_NONE);
1197                         else if (checkrules_leaderfrags == fraglimit - 3)
1198                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.ogg", 1, ATTN_NONE);
1199                 }
1200
1201         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1202 }
1203
1204 float(float fraglimit) WinningConditionBase_Teamplay =
1205 {
1206         tdm_old_score = tdm_max_score;
1207         tdm_max_score = max(team1_score, team2_score, team3_score, team4_score);
1208
1209         checkrules_equality =
1210         (
1211                 (tdm_max_score > 0)
1212                 &&
1213                 (
1214                           (team1_score == tdm_max_score)
1215                         + (team2_score == tdm_max_score)
1216                         + (team3_score == tdm_max_score)
1217                         + (team4_score == tdm_max_score)
1218                         >= 2));
1219
1220         ClearWinners();
1221         if(tdm_max_score > 0)
1222         {
1223                 if(team1_score == tdm_max_score)
1224                         AddWinners(team, COLOR_TEAM1);
1225                 if(team2_score == tdm_max_score)
1226                         AddWinners(team, COLOR_TEAM2);
1227                 if(team3_score == tdm_max_score)
1228                         AddWinners(team, COLOR_TEAM3);
1229                 if(team4_score == tdm_max_score)
1230                         AddWinners(team, COLOR_TEAM4);
1231         }
1232
1233         if(!cvar("g_runematch") && !cvar("g_domination"))
1234                 if(tdm_max_score != tdm_old_score)
1235                 {
1236                         if(tdm_max_score == fraglimit - 1)
1237                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.ogg", 1, ATTN_NONE);
1238                         else if(tdm_max_score == fraglimit - 2)
1239                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.ogg", 1, ATTN_NONE);
1240                         else if(tdm_max_score == fraglimit - 3)
1241                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.ogg", 1, ATTN_NONE);
1242                 }
1243
1244         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1245 }
1246
1247 // TDM winning condition: game terminates if a team's score sum reached the
1248 // fraglimit, unless the first two teams have the same total score. The latter
1249 // case also breaks the time limit.
1250 float(float fraglimit) WinningCondition_MaxTeamSum =
1251 {
1252         entity head;
1253
1254         team1_score = team2_score = team3_score = team4_score = 0;
1255
1256         head = findchain(classname, "player");
1257         while (head)
1258         {
1259                 if(head.team == COLOR_TEAM1)
1260                         team1_score += head.frags;
1261                 else if(head.team == COLOR_TEAM2)
1262                         team2_score += head.frags;
1263                 else if(head.team == COLOR_TEAM3)
1264                         team3_score += head.frags;
1265                 else if(head.team == COLOR_TEAM4)
1266                         team4_score += head.frags;
1267                 head = head.chain;
1268         }
1269
1270         return WinningConditionBase_Teamplay(fraglimit);
1271 }
1272
1273 // DOM/CTF winning condition: game terminates if the max of a team's players'
1274 // score reached the fraglimit, unless the first two teams have the same
1275 // maximum score. The latter case also breaks the time limit.
1276 float(float fraglimit) WinningCondition_MaxTeamMax =
1277 {
1278         entity head;
1279
1280         team1_score = team2_score = team3_score = team4_score = 0;
1281
1282         head = findchain(classname, "player");
1283         while (head)
1284         {
1285                 if(head.team == COLOR_TEAM1)
1286                 {
1287                         if(head.frags > team1_score)
1288                                 team1_score = head.frags;
1289                 }
1290                 else if(head.team == COLOR_TEAM2)
1291                 {
1292                         if(head.frags > team2_score)
1293                                 team2_score = head.frags;
1294                 }
1295                 else if(head.team == COLOR_TEAM3)
1296                 {
1297                         if(head.frags > team3_score)
1298                                 team3_score = head.frags;
1299                 }
1300                 else if(head.team == COLOR_TEAM4)
1301                 {
1302                         if(head.frags > team4_score)
1303                                 team4_score = head.frags;
1304                 }
1305                 head = head.chain;
1306         }
1307
1308         return WinningConditionBase_Teamplay(fraglimit);
1309 }
1310
1311 void PrintScoreboardFor(string name, string colorcode, float whichteam)
1312 {
1313         entity head;
1314         float fragtotal;
1315         string s;
1316         float found;
1317         found = FALSE;
1318         head = find(world, classname, "player");
1319         while(head)
1320         {
1321                 if(!whichteam || head.team == whichteam)
1322                 {
1323                         if(name != "")
1324                                 if(!found)
1325                                         ServerConsoleEcho(strcat(" ", colorcode, name, ":"), FALSE);
1326                         found = TRUE;
1327                         fragtotal = fragtotal + head.frags;
1328                         s = ftos(head.frags);
1329                         s = strcat(s, "/", ftos(head.deaths));
1330                         s = strcat(s, " @ ", ftos(head.ping));
1331                         if(clienttype(head) == CLIENTTYPE_BOT)
1332                                 s = strcat(s, "botms");
1333                         else
1334                                 s = strcat(s, "ms");
1335                         ServerConsoleEcho(strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"), TRUE);
1336                 }
1337                 head = find(head, classname, "player");
1338         }
1339         if(whichteam && found)
1340                 ServerConsoleEcho(strcat(colorcode, "  (total: ", ftos(fragtotal), ")"), FALSE);
1341 }
1342
1343 void PrintScoreboard()
1344 {
1345         ServerConsoleEcho("Scoreboard:", FALSE);
1346         if(teams_matter)
1347         {
1348                 PrintScoreboardFor("Red", "^1", COLOR_TEAM1);
1349                 PrintScoreboardFor("Blue", "^4", COLOR_TEAM2);
1350                 PrintScoreboardFor("Pink", "^6", COLOR_TEAM3);
1351                 PrintScoreboardFor("Yellow", "^3", COLOR_TEAM4);
1352         }
1353         else
1354         {
1355                 PrintScoreboardFor("", "^7", 0);
1356         }
1357         ServerConsoleEcho(".", FALSE);
1358 }
1359
1360 void RemoveFromMaplist(string m)
1361 {
1362         string result;
1363         float litems;
1364         float i;
1365         float found;
1366
1367         litems = tokenize(cvar_string("g_maplist"));
1368         found = 0;
1369         result = "";
1370         for(i = 0; i < litems; ++i)
1371         {
1372                 m = strcat(m);
1373                 result = strcat(result);
1374                 if(argv(i) == m)
1375                         found += 1;
1376                 else
1377                         result = strcat(result, "'", argv(i), "'");
1378         }
1379         if(found)
1380                 cvar_set("g_maplist", result);
1381         ServerConsoleEcho(strcat("Removed ", ftos(found), " items."), FALSE);
1382 }
1383
1384 void AddToMaplist(string m)
1385 {
1386         string result;
1387         float found;
1388         float litems;
1389         float i;
1390         float ipos;
1391         float inserted;
1392
1393         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1394         {
1395                 ServerConsoleEcho("Map not found.", FALSE);
1396                 return;
1397         }
1398
1399         litems = tokenize(cvar_string("g_maplist"));
1400         if(cvar("g_maplist_shuffle"))
1401                 ipos = ceil(random() * (litems + 1)) - 1;
1402         else
1403                 ipos = litems;
1404         found = 0;
1405         inserted = 0;
1406         for(i = 0; i < litems; ++i)
1407         {
1408                 m = strcat(m);
1409                 if(i == ipos)
1410                 {
1411                         result = strcat(result, "'", m, "'");
1412                         inserted = 1;
1413                 }
1414                 result = strcat(result, "'", argv(i), "'");
1415                 if(argv(i) == m)
1416                         found += 1;
1417         }
1418         if(!inserted)
1419                 result = strcat(result, "'", m, "'");
1420         if(!found)
1421         {
1422                 cvar_set("g_maplist", result);
1423                 ServerConsoleEcho("Map added.", FALSE);
1424         }
1425         else
1426                 ServerConsoleEcho("Map already in list.", FALSE);
1427 }
1428
1429 void ShuffleMaplist()
1430 {
1431         string result;
1432         float start;
1433         float litems;
1434         float selected;
1435         float i;
1436
1437         result = cvar_string("g_maplist");
1438         litems = tokenize(result);
1439
1440         for(start = 0; start < litems - 1; ++start)
1441         {
1442                 result = "";
1443
1444                 // select a random item
1445                 selected = ceil(random() * (litems - start) + start) - 1;
1446
1447                 // shift this item to the place start
1448                 for(i = 0; i < start; ++i)
1449                         result = strcat(result, "'", argv(i), "'");
1450                 result = strcat(result, "'", argv(selected), "'");
1451                 for(i = start; i < litems; ++i)
1452                         if(i != selected)
1453                                 result = strcat(result, "'", argv(i), "'");
1454
1455                 litems = tokenize(result);
1456
1457                 //dprint(result, "\n");
1458         }
1459
1460         cvar_set("g_maplist", result);
1461 }
1462
1463 void() HandleMaplistShuffleCommands =
1464 {
1465         // automatically shuffle when setting g_maplist_shuffle
1466         if(cvar_string("_g_maplist_add") != "")
1467         {
1468                 AddToMaplist(cvar_string("_g_maplist_add"));
1469                 cvar_set("_g_maplist_add", "");
1470         }
1471         if(cvar_string("_g_maplist_remove") != "")
1472         {
1473                 RemoveFromMaplist(cvar_string("_g_maplist_remove"));
1474                 cvar_set("_g_maplist_remove", "");
1475         }
1476         if(cvar("_g_maplist_shufflenow") || (cvar("g_maplist_shuffle") && !cvar("_g_maplist_have_shuffled")))
1477         {
1478                 ShuffleMaplist();
1479                 cvar_set("_g_maplist_shufflenow", "0");
1480                 cvar_set("_g_maplist_have_shuffled", "1");
1481                 ServerConsoleEcho("Shuffled map list.", FALSE);
1482         }
1483         if(cvar("_g_maplist_have_shuffled"))
1484                 if(!cvar("g_maplist_shuffle"))
1485                         cvar_set("_g_maplist_have_shuffled", "0");
1486 }
1487
1488 /*
1489 ============
1490 CheckRules_World
1491
1492 Exit deathmatch games upon conditions
1493 ============
1494 */
1495 void() CheckRules_World =
1496 {
1497         local float status;
1498         local float timelimit;
1499         local float fraglimit;
1500
1501         VoteThink();
1502
1503         SetDefaultAlpha();
1504
1505         if (intermission_running)
1506                 if (time >= intermission_exittime + 60)
1507                 {
1508                         GotoNextMap();
1509                         return;
1510                 }
1511
1512         if (gameover)   // someone else quit the game already
1513                 return;
1514
1515         DumpStats();
1516
1517         if(cvar("_scoreboard"))
1518         {
1519                 cvar_set("_scoreboard", "0");
1520                 PrintScoreboard();
1521         }
1522
1523         HandleMaplistShuffleCommands();
1524
1525         timelimit = cvar("timelimit") * 60;
1526         fraglimit = cvar("fraglimit");
1527
1528         if (timelimit && time >= timelimit)
1529                 InitiateOvertime();
1530
1531         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1532         {
1533                 NextLevel();
1534                 return;
1535         }
1536
1537         if(!checkrules_overtimewarning && checkrules_overtimeend)
1538         {
1539                 checkrules_overtimewarning = TRUE;
1540                 //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.ogg", 1, ATTN_NONE);
1541                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1542         }
1543
1544         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1545         {
1546                 checkrules_oneminutewarning = TRUE;
1547                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.ogg", 1, ATTN_NONE);
1548         }
1549
1550         status = WINNING_NO;
1551         if(cvar("g_lms"))
1552         {
1553                 status = WinningCondition_LMS();
1554         }
1555         else
1556         {
1557                 if(teams_matter)
1558                 {
1559                         if(cvar("g_tdm") || cvar("g_runematch") || cvar("g_ctf") || cvar("g_domination"))
1560                                 status = WinningCondition_MaxTeamSum(fraglimit);
1561                         //else if()
1562                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1563                         else
1564                         {
1565                                 dprint("div0: How can this happen?\n");
1566                                 status = WinningCondition_MaxTeamMax(fraglimit);
1567                         }
1568                 }
1569                 else
1570                         status = WinningCondition_MaxIndividualScore(fraglimit);
1571         }
1572
1573         if(status == WINNING_STARTOVERTIME)
1574         {
1575                 status = WINNING_NEVER;
1576                 InitiateOvertime();
1577         }
1578
1579         if(status == WINNING_NEVER)
1580                 // equality cases! Nobody wins if the overtime ends in a draw.
1581                 ClearWinners();
1582
1583         if(checkrules_overtimeend)
1584                 if(status != WINNING_NEVER)
1585                         status = WINNING_YES;
1586
1587         if(status == WINNING_YES)
1588                 NextLevel();
1589 };