]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
some fixes against extreme CPU load and not loading the maplist
[divverent/nexuiz.git] / data / qcsrc / server / g_world.qc
1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2 string redirection_target;
3
4 string GetMapname();
5 void GotoNextMap();
6 void ShuffleMaplist()
7 float() DoNextMapOverride;
8
9 void SetDefaultAlpha()
10 {
11         if(cvar("g_running_guns"))
12         {
13                 default_player_alpha = -1;
14                 default_weapon_alpha = +1;
15         }
16         else if(g_cloaked)
17         {
18                 default_player_alpha = cvar("g_balance_cloaked_alpha");
19                 default_weapon_alpha = default_player_alpha;
20         }
21         else
22         {
23                 default_player_alpha = cvar("g_player_alpha");
24                 if(default_player_alpha <= 0)
25                         default_player_alpha = 1;
26                 default_weapon_alpha = default_player_alpha;
27         }
28 }
29
30 void fteqcc_testbugs()
31 {
32         float a, b;
33
34         if(!cvar("developer_fteqccbugs"))
35                 return;
36
37         dprint("*** fteqcc test: checking for bugs...\n");
38
39         a = 1;
40         b = 5;
41         if(sqrt(a) - sqrt(b - a) == 0)
42                 dprint("*** fteqcc test: found same-function-twice bug\n");
43         else
44                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
45
46         world.frags = -10;
47         world.enemy = world;
48         world.enemy.frags += 10;
49         if(world.frags > 0.2 || world.frags < -0.2) // don't error out if it's just roundoff errors
50                 dprint("*** fteqcc test: found += bug\n");
51         else
52                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
53         world.frags = 0;
54 }
55
56 void GotoFirstMap()
57 {
58         if(cvar("_sv_init"))
59         {
60                 cvar_set("_sv_init", "0");
61                 if(cvar("g_maplist_shuffle"))
62                         ShuffleMaplist();
63                 tokenize(cvar_string("g_maplist"));
64                 if(argv(0) != GetMapname())
65                 {
66                         cvar_set("nextmap", argv(0));
67                         if(!DoNextMapOverride())
68                                 GotoNextMap();
69                 }
70         }
71 }
72
73 float world_already_spawned;
74 void worldspawn (void)
75 {
76         float globhandle, i, n;
77
78         dprint_load(); // load dprint status from cvar
79
80         if(world_already_spawned)
81                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
82         world_already_spawned = TRUE;
83
84         sv_cheats = cvar("sv_cheats");
85
86         /*
87         TODO sound pack system
88         // initialize sound pack system
89         soundpack = cvar_string("g_soundpack");
90         if(soundpack != "")
91                 soundpack = strcat(soundpack, "/");
92         soundpack = strzone(soundpack);
93         */
94
95         // gamemode related things
96         precache_model ("models/misc/chatbubble.spr");
97         precache_model ("models/misc/teambubble.spr");
98         if (cvar("g_runematch"))
99         {
100                 precache_model ("models/runematch/curse.mdl");
101                 precache_model ("models/runematch/rune.mdl");
102         }
103
104         // Precache all player models if desired
105         if (cvar("sv_precacheplayermodels"))
106         {
107                 globhandle = search_begin("models/player/*.zym", TRUE, FALSE);
108                 n = search_getsize(globhandle);
109                 for(i = 0; i < n; ++i)
110                 {
111                         //print(search_getfilename(globhandle, i), "\n");
112                         precache_model(search_getfilename(globhandle, i));
113                 }
114                 search_end(globhandle);
115                 //precache_model("models/player/carni.zym");
116                 //precache_model("models/player/crash.zym");
117                 //precache_model("models/player/grunt.zym");
118                 //precache_model("models/player/headhunter.zym");
119                 //precache_model("models/player/insurrectionist.zym");
120                 //precache_model("models/player/jeandarc.zym");
121                 //precache_model("models/player/lurk.zym");
122                 //precache_model("models/player/lycanthrope.zym");
123                 //precache_model("models/player/marine.zym");
124                 //precache_model("models/player/nexus.zym");
125                 //precache_model("models/player/pyria.zym");
126                 //precache_model("models/player/shock.zym");
127                 //precache_model("models/player/skadi.zym");
128                 //precache_model("models/player/specop.zym");
129                 //precache_model("models/player/visitant.zym");
130         }
131
132         if (g_footsteps)
133         {
134                 precache_sound ("misc/footstep01.wav");
135                 precache_sound ("misc/footstep02.wav");
136                 precache_sound ("misc/footstep03.wav");
137                 precache_sound ("misc/footstep04.wav");
138                 precache_sound ("misc/footstep05.wav");
139                 precache_sound ("misc/footstep06.wav");
140         }
141
142         // gore and miscellaneous sounds
143         //precache_sound ("misc/h2ohit.wav");
144         precache_model ("models/gibs/bloodyskull.md3");
145         precache_model ("models/gibs/chunk.mdl");
146         precache_model ("models/gibs/eye.md3");
147         precache_model ("models/gibs/gib1.md3");
148         precache_model ("models/gibs/gib1.mdl");
149         precache_model ("models/gibs/gib2.mdl");
150         precache_model ("models/gibs/gib3.mdl");
151         precache_model ("models/gibs/gib5.md3");
152         precache_model ("models/hook.md3");
153         precache_sound ("misc/armorimpact.wav");
154         precache_sound ("misc/bodyimpact1.wav");
155         precache_sound ("misc/bodyimpact2.wav");
156         precache_sound ("misc/gib.wav");
157         precache_sound ("misc/gib_splat01.wav");
158         precache_sound ("misc/gib_splat02.wav");
159         precache_sound ("misc/gib_splat03.wav");
160         precache_sound ("misc/gib_splat04.wav");
161         precache_sound ("misc/hit.wav");
162         precache_sound ("misc/hitground1.wav");
163         precache_sound ("misc/hitground2.wav");
164         precache_sound ("misc/hitground3.wav");
165         precache_sound ("misc/hitground4.wav");
166         precache_sound ("misc/null.wav");
167         precache_sound ("misc/spawn.wav");
168         precache_sound ("misc/talk.wav");
169         precache_sound ("misc/teleport.wav");
170         precache_sound ("player/lava.wav");
171         precache_sound ("player/slime.wav");
172
173         // announcer sounds - male
174         //precache_sound ("announcer/male/electrobitch.wav");
175         precache_sound ("announcer/male/03kills.wav");
176         precache_sound ("announcer/male/05kills.wav");
177         precache_sound ("announcer/male/10kills.wav");
178         precache_sound ("announcer/male/15kills.wav");
179         precache_sound ("announcer/male/20kills.wav");
180         precache_sound ("announcer/male/25kills.wav");
181         precache_sound ("announcer/male/30kills.wav");
182         precache_sound ("announcer/male/botlike.wav");
183         precache_sound ("announcer/male/yoda.wav");
184
185         // announcer sounds - robotic
186         precache_sound ("announcer/robotic/1fragleft.wav");
187         precache_sound ("announcer/robotic/1minuteremains.wav");
188         precache_sound ("announcer/robotic/2fragsleft.wav");
189         precache_sound ("announcer/robotic/3fragsleft.wav");
190         if (g_minstagib)
191         {
192                 precache_sound ("announcer/robotic/lastsecond.wav");
193                 precache_sound ("announcer/robotic/narrowly.wav");
194                 precache_sound ("announcer/robotic/1.wav");
195                 precache_sound ("announcer/robotic/2.wav");
196                 precache_sound ("announcer/robotic/3.wav");
197                 precache_sound ("announcer/robotic/4.wav");
198                 precache_sound ("announcer/robotic/5.wav");
199                 precache_sound ("announcer/robotic/6.wav");
200                 precache_sound ("announcer/robotic/7.wav");
201                 precache_sound ("announcer/robotic/8.wav");
202                 precache_sound ("announcer/robotic/9.wav");
203                 precache_sound ("announcer/robotic/10.wav");
204         }
205
206         // common weapon precaches
207         precache_sound ("weapons/weapon_switch.wav");
208         precache_sound ("weapons/weaponpickup.wav");
209         if (g_grappling_hook)
210         {
211                 precache_sound ("weapons/hook_fire.wav"); // hook
212                 precache_sound ("weapons/hook_impact.wav"); // hook
213         }
214
215         if (cvar("sv_precacheweapons") || g_nixnex)
216         {
217                 //precache weapon models/sounds
218                 local float wep;
219                 wep = WEP_FIRST;
220                 while (wep <= WEP_LAST)
221                 {
222                         weapon_action(wep, WR_PRECACHE);
223                         wep = wep + 1;
224                 }
225         }
226
227         // plays music for the level if there is any
228         if (self.noise)
229         {
230                 precache_sound (self.noise);
231                 ambientsound ('0 0 0', self.noise, 1.00, ATTN_NONE);
232         }
233
234         // 0 normal
235         lightstyle(0, "m");
236
237         // 1 FLICKER (first variety)
238         lightstyle(1, "mmnmmommommnonmmonqnmmo");
239
240         // 2 SLOW STRONG PULSE
241         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
242
243         // 3 CANDLE (first variety)
244         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
245
246         // 4 FAST STROBE
247         lightstyle(4, "mamamamamama");
248
249         // 5 GENTLE PULSE 1
250         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
251
252         // 6 FLICKER (second variety)
253         lightstyle(6, "nmonqnmomnmomomno");
254
255         // 7 CANDLE (second variety)
256         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
257
258         // 8 CANDLE (third variety)
259         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
260
261         // 9 SLOW STROBE (fourth variety)
262         lightstyle(9, "aaaaaaaazzzzzzzz");
263
264         // 10 FLUORESCENT FLICKER
265         lightstyle(10, "mmamammmmammamamaaamammma");
266
267         // 11 SLOW PULSE NOT FADE TO BLACK
268         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
269
270         // styles 32-62 are assigned by the light program for switchable lights
271
272         // 63 testing
273         lightstyle(63, "a");
274
275         player_count = 0;
276         lms_lowest_lives = 0;
277         lms_next_place = 0;
278
279         GotoFirstMap();
280
281         bot_waypoints_for_items = cvar("g_waypoints_for_items");
282         if(bot_waypoints_for_items == 1)
283                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
284                         bot_waypoints_for_items = 0;
285
286         if(cvar("g_campaign"))
287                 CampaignPreInit();
288
289         InitGameplayMode();
290
291         WaypointSprite_Init();
292
293         //if (cvar("g_domination"))
294         //      dom_init();
295
296         local entity head;
297         head = nextent(world);
298         maxclients = 0;
299         while(head)
300         {
301                 maxclients++;
302                 head = nextent(head);
303         }
304
305         GameLogInit(); // prepare everything
306         if(cvar("sv_eventlog"))
307         {
308                 local string s;
309                 GameLogEcho(":logversion:2", FALSE);
310                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
311                 s = strcat(s, ftos(random()));
312                 GameLogEcho(strcat(":gamestart:", GetMapname(), ":", s), FALSE);
313                 s = ":gameinfo:mutators:LIST";
314                 if(g_grappling_hook)
315                         s = strcat(s, ":grappling_hook");
316                 if(!cvar("g_use_ammunition"))
317                         s = strcat(s, ":no_use_ammunition");
318                 if(!cvar("g_pickup_items"))
319                         s = strcat(s, ":no_pickup_items");
320                 if(g_instagib)
321                         s = strcat(s, ":instagib");
322                 if(g_rocketarena)
323                         s = strcat(s, ":rockerarena");
324                 if(g_nixnex)
325                         s = strcat(s, ":nixnex");
326                 if(g_vampire)
327                         s = strcat(s, ":vampire");
328                 if(g_laserguided_missile)
329                         s = strcat(s, ":laserguided_missile");
330                 if(g_norecoil)
331                         s = strcat(s, ":norecoil");
332                 if(g_midair)
333                         s = strcat(s, ":midair");
334                 if(g_minstagib)
335                         s = strcat(s, ":minstagib");
336                 GameLogEcho(s, FALSE);
337                 GameLogEcho(":gameinfo:end", FALSE);
338         }
339
340         cvar_set("nextmap", "");
341
342         SetDefaultAlpha();
343
344         if(cvar("g_campaign"))
345                 CampaignPostInit();
346
347         fteqcc_testbugs();
348
349         readlevelcvars();
350
351         Ban_LoadBans();
352
353 #ifdef MAPINFO
354         MapInfo_Enumerate();
355         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures());
356 #endif
357 }
358
359 void light (void)
360 {
361         //makestatic (self); // Who the f___ did that?
362         remove(self);
363 }
364
365 float( string pFilename ) TryFile =
366 {
367         local float lHandle;
368         dprint("TryFile(\"", pFilename, "\")\n");
369         lHandle = fopen( pFilename, FILE_READ );
370         if( lHandle != -1 ) {
371                 fclose( lHandle );
372                 return TRUE;
373         } else {
374                 return FALSE;
375         }
376 };
377
378 string GetGametype()
379 {
380         if (game == GAME_DEATHMATCH)
381                 return "dm";
382         else if (game == GAME_TEAM_DEATHMATCH)
383                 return "tdm";
384         else if (game == GAME_DOMINATION)
385                 return "dom";
386         else if (game == GAME_CTF)
387                 return "ctf";
388         else if (game == GAME_RUNEMATCH)
389                 return "rune";
390         else if (game == GAME_LMS)
391                 return "lms";
392         else if (game == GAME_KEYHUNT)
393                 return "kh";
394         else if (game == GAME_ONSLAUGHT)
395                 return "ons";
396         else if (game == GAME_ASSAULT)
397                 return "as";
398         return "dm";
399 }
400
401 float IsSameGametype(string mapcfgname)
402 {
403 #ifdef MAPINFO
404         return TRUE; // can't change game type by map name here
405 #else
406         string gt;
407         gt = GetGametype();
408         if(substring(mapcfgname, 0, strlen(gt) + 1) == strcat(gt, "_"))
409                 return TRUE;
410         return FALSE;
411 #endif
412 }
413
414 string getmapname_stored;
415 string GetMapname()
416 {
417 #ifdef MAPINFO
418         return mapname;
419 #else
420         if(getmapname_stored == "")
421                 getmapname_stored = strzone(strcat(GetGametype(), "_", mapname));
422         return getmapname_stored;
423 #endif
424 }
425
426 float Map_Count, Map_Current;
427 string Map_Current_Name;
428
429 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
430 float GetMaplistPosition()
431 {
432         float pos, idx;
433         string map;
434
435         map = GetMapname();
436         idx = cvar("g_maplist_index");
437
438         if(idx >= 0)
439                 if(idx < Map_Count)
440                         if(map == argv(idx))
441                                 return idx;
442
443         for(pos = 0; pos < Map_Count; ++pos)
444                 if(map == argv(pos))
445                         return pos;
446
447         // resume normal maplist rotation if current map is not in g_maplist
448         return idx;
449 }
450
451 float MapHasRightSize(string map)
452 {
453         // open map size restriction file
454         float fh;
455         dprint("opensize "); dprint(map);
456         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
457         if(fh >= 0)
458         {
459                 float mapmin, mapmax;
460                 dprint(": ok, ");
461                 mapmin = stof(fgets(fh));
462                 mapmax = stof(fgets(fh));
463                 fclose(fh);
464                 if(player_count < mapmin)
465                 {
466                         dprint("not enough\n");
467                         return FALSE;
468                 }
469                 if(player_count > mapmax)
470                 {
471                         dprint("too many\n");
472                         return FALSE;
473                 }
474                 dprint("right size\n");
475                 return TRUE;
476         }
477         dprint(": not found\n");
478         return TRUE;
479 }
480
481 #ifdef MAPINFO
482 #else
483 string Map_Filename(float position)
484 {
485         // FIXME unused
486         return strcat("maps/", argv(position), ".mapcfg");
487 }
488 #endif
489
490 string strwords(string s, float w)
491 {
492         float endpos;
493         for(endpos = 0; w && endpos >= 0; --w)
494                 endpos = strstrofs(s, " ", endpos + 1);
495         if(endpos < 0)
496                 return s;
497         else
498                 return substring(s, 0, endpos);
499 }
500
501 float strhasword(string s, string w)
502 {
503         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
504 }
505
506 void Map_MarkAsRecent(string m)
507 {
508         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), cvar("g_maplist_mostrecent_count")));
509 }
510
511 float Map_IsRecent(string m)
512 {
513         return strhasword(cvar_string("g_maplist_mostrecent"), m);
514 }
515
516 float(float position, float pass) Map_Check =
517 {
518         string filename;
519         string map_next;
520         map_next = argv(position);
521         if(pass <= 1)
522         {
523                 if(map_next == Map_Current_Name) // same map again in first pass?
524                         return 0;
525                 if(Map_IsRecent(map_next))
526                         return 0;
527         }
528 #ifdef MAPINFO
529         if(MapInfo_CheckMap(argv(position)))
530 #else
531         filename = Map_Filename(position);
532         if(TryFile(filename))
533 #endif
534         {
535                 if(pass == 2)
536                         return 1;
537                 if(MapHasRightSize(argv(position)))
538                         return 1;
539                 return 0;
540         }
541         else
542                 dprint( "Couldn't find '", filename, "'..\n" );
543
544         return 0;
545 }
546
547 void(string nextmapname) Map_Goto_SetStr =
548 {
549         if(getmapname_stored != "")
550                 strunzone(getmapname_stored);
551         if(nextmapname == "")
552                 getmapname_stored = "";
553         else
554                 getmapname_stored = strzone(nextmapname);
555 }
556
557 void(float position) Map_Goto_SetFloat =
558 {
559         cvar_set("g_maplist_index", ftos(position));
560         Map_Goto_SetStr(argv(position));
561 }
562
563 void() GameResetCfg =
564 {
565 #ifdef MAPINFO
566         // settings persist, except...
567         if(cvar("g_campaign"))
568                 localcmd("\nexec mutator_reset.cfg\n");
569         localcmd("\nsettemp_restore\n");
570 #else
571         // if an exit cfg is defined by exiting map, exec it.
572         string exit_cfg;
573         exit_cfg = cvar_string("exit_cfg");
574         if(exit_cfg != "")
575                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
576
577         localcmd("exec game_reset.cfg\n");
578 #endif
579
580         Ban_SaveBans();
581 };
582
583 void() Map_Goto =
584 {
585         Map_MarkAsRecent(getmapname_stored);
586         GameResetCfg();
587 #ifdef MAPINFO
588         MapInfo_LoadMap(getmapname_stored);
589 #else
590         localcmd(strcat("exec \"maps/", getmapname_stored ,".mapcfg\"\n"));
591 #endif
592 }
593
594 // return codes of map selectors:
595 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
596 //   -2 = permanent failure
597 float() MaplistMethod_Iterate = // usual method
598 {
599         float pass, i;
600
601         for(pass = 1; pass <= 2; ++pass)
602         {
603                 for(i = 1; i < Map_Count; ++i)
604                 {
605                         float mapindex;
606                         mapindex = math_mod(i + Map_Current, Map_Count);
607                         if(Map_Check(mapindex, pass))
608                                 return mapindex;
609                 }
610         }
611         return -1;
612 }
613
614 float() MaplistMethod_Repeat = // fallback method
615 {
616         if(Map_Check(Map_Current, 2))
617                 return Map_Current;
618         return -2;
619 }
620
621 float() MaplistMethod_Random = // random map selection
622 {
623         float i, imax;
624
625         imax = 42;
626
627         for(i = 0; i <= imax; ++i)
628         {
629                 float mapindex;
630                 mapindex = math_mod(Map_Current + ceil(random() * (Map_Count - 1)), Map_Count); // any OTHER map
631                 if(Map_Check(mapindex, 1))
632                         return mapindex;
633         }
634         return -1;
635 }
636
637 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
638 // the exponent sets a bias on the map selection:
639 // the higher the exponent, the less likely "shortly repeated" same maps are
640 {
641         float i, j, imax, insertpos;
642
643         imax = 42;
644
645         if(Map_Count <= 1)
646                 return 0; // only one map, then always play this one
647
648         for(i = 0; i <= imax; ++i)
649         {
650                 string newlist;
651
652                 // now reinsert this at another position
653                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
654                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
655                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
656                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
657
658                 // insert the current map there
659                 newlist = "";
660 #ifdef MAPINFO
661                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
662                         newlist = strcat(newlist, " ", argv(j));
663                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
664                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
665                         newlist = strcat(newlist, " ", argv(j));
666                 newlist = substring(newlist, 1, strlen(newlist) - 1);
667 #else
668                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
669                         newlist = strcat(newlist, "'", argv(j), "'");
670                 newlist = strcat(newlist, "'", argv(0), "'");  // now insert the just selected map
671                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
672                         newlist = strcat(newlist, "'", argv(j), "'");
673 #endif
674                 cvar_set("g_maplist", newlist);
675                 Map_Count = tokenize(newlist);
676
677                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
678                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
679                 if(Map_Check(Map_Current, 1))
680                         return Map_Current;
681         }
682         return -1;
683 }
684
685 void() Maplist_Init =
686 {
687         string temp;
688         temp = cvar_string("g_maplist");
689         Map_Count = tokenize(temp);
690         if(Map_Count == 0)
691         {
692                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
693 #ifdef MAPINFO
694                 cvar_set("g_maplist", temp = MapInfo_ListAllowedMaps());
695 #else
696                 cvar_set("g_maplist", temp = cvar_string("g_maplist_defaultlist"));
697 #endif
698                 Map_Count = tokenize(temp);
699         }
700         if(Map_Count == 0)
701                 error("empty maplist, cannot select a new map");
702         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
703
704         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
705         // this may or may not be correct, but who cares, in the worst case a map
706         // isn't chosen in the first pass that should have been
707 }
708
709 string() GetNextMap =
710 {
711         float nextMap;
712
713         Maplist_Init();
714         nextMap = -1;
715
716         if(nextMap == -1)
717                 if(cvar("g_maplist_shuffle") > 0)
718                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
719
720         if(nextMap == -1)
721                 if(cvar("g_maplist_selectrandom"))
722                         nextMap = MaplistMethod_Random();
723
724         if(nextMap == -1)
725                 nextMap = MaplistMethod_Iterate();
726
727         if(nextMap == -1)
728                 nextMap = MaplistMethod_Repeat();
729
730         if(nextMap >= 0)
731         {
732                 Map_Goto_SetFloat(nextMap);
733                 return getmapname_stored;
734         }
735
736         return "";
737 };
738
739 float() DoNextMapOverride =
740 {
741         Ban_SaveBans();
742
743         if(cvar("g_campaign"))
744         {
745                 CampaignPostIntermission();
746                 alreadychangedlevel = TRUE;
747                 return TRUE;
748         }
749         if(cvar("quit_when_empty"))
750         {
751                 if(player_count <= currentbots)
752                 {
753                         localcmd("quit\n");
754                         alreadychangedlevel = TRUE;
755                         return TRUE;
756                 }
757         }
758         if(cvar_string("quit_and_redirect") != "")
759         {
760                 redirection_target = strzone(cvar_string("quit_and_redirect"));
761                 alreadychangedlevel = TRUE;
762                 return TRUE;
763         }
764         if (cvar("samelevel")) // if samelevel is set, stay on same level
765         {
766                 // 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)
767                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
768                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
769                 localcmd("restart\n");
770                 //changelevel (mapname);
771                 alreadychangedlevel = TRUE;
772                 return TRUE;
773         }
774         if(cvar_string("nextmap") != "")
775 #ifdef MAPINFO
776                 if(MapInfo_CheckMap(cvar_string("nextmap")))
777 #else
778                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
779 #endif
780                 {
781                         Map_Goto_SetStr(cvar_string("nextmap"));
782                         Map_Goto();
783                         alreadychangedlevel = TRUE;
784                         return TRUE;
785                 }
786         if(cvar("lastlevel"))
787         {
788                 GameResetCfg();
789                 localcmd("set lastlevel 0\ntogglemenu\n");
790                 alreadychangedlevel = TRUE;
791                 return TRUE;
792         }
793         return FALSE;
794 };
795
796 void() GotoNextMap =
797 {
798         //local string nextmap;
799         //local float n, nummaps;
800         //local string s;
801         if (alreadychangedlevel)
802                 return;
803         alreadychangedlevel = TRUE;
804
805         {
806                 string nextMap;
807                 float allowReset;
808
809                 for(allowReset = 1; allowReset >= 0; --allowReset)
810                 {
811                         nextMap = GetNextMap();
812                         if(nextMap != "")
813                                 break;
814
815                         if(allowReset)
816                         {
817                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
818 #ifdef MAPINFO
819                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
820 #else
821                                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
822 #endif
823                         }
824                         else
825                         {
826                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
827                         }
828                 }
829                 Map_Goto();
830         }
831 };
832
833
834 /*
835 ============
836 IntermissionThink
837
838 When the player presses attack or jump, change to the next level
839 ============
840 */
841 .float autoscreenshot;
842 void() MapVote_Start;
843 void() MapVote_Think;
844 float mapvote_initialized;
845 void() IntermissionThink =
846 {
847         FixIntermissionClient(self);
848
849         if(cvar("sv_autoscreenshot"))
850         if(self.autoscreenshot > 0)
851         if(time > self.autoscreenshot)
852         {
853                 self.autoscreenshot = -1;
854                 if(clienttype(self) == CLIENTTYPE_REAL)
855                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
856                 return;
857         }
858
859         if (time < intermission_exittime)
860                 return;
861
862         if(!mapvote_initialized)
863                 if (time < intermission_exittime + 10 && !self.button0 && !self.button2 && !self.button3 && !self.button6 && !self.buttonuse)
864                         return;
865
866         MapVote_Start();
867 };
868
869 /*
870 ============
871 FindIntermission
872
873 Returns the entity to view from
874 ============
875 */
876 /*
877 entity() FindIntermission =
878 {
879         local   entity spot;
880         local   float cyc;
881
882 // look for info_intermission first
883         spot = find (world, classname, "info_intermission");
884         if (spot)
885         {       // pick a random one
886                 cyc = random() * 4;
887                 while (cyc > 1)
888                 {
889                         spot = find (spot, classname, "info_intermission");
890                         if (!spot)
891                                 spot = find (spot, classname, "info_intermission");
892                         cyc = cyc - 1;
893                 }
894                 return spot;
895         }
896
897 // then look for the start position
898         spot = find (world, classname, "info_player_start");
899         if (spot)
900                 return spot;
901
902 // testinfo_player_start is only found in regioned levels
903         spot = find (world, classname, "testplayerstart");
904         if (spot)
905                 return spot;
906
907 // then look for the start position
908         spot = find (world, classname, "info_player_deathmatch");
909         if (spot)
910                 return spot;
911
912         //objerror ("FindIntermission: no spot");
913         return world;
914 };
915 */
916
917 /*
918 ===============================================================================
919
920 RULES
921
922 ===============================================================================
923 */
924
925 void(float final) DumpStats =
926 {
927         local float file;
928         local string s;
929         local float to_console;
930         local float to_eventlog;
931         local float to_file;
932
933         to_console = cvar("sv_logscores_console");
934         to_eventlog = cvar("sv_eventlog");
935         to_file = cvar("sv_logscores_file");
936
937         if(!final)
938         {
939                 to_console = TRUE; // always print printstats replies
940                 to_eventlog = FALSE; // but never print them to the event log
941         }
942
943         if(to_eventlog)
944                 if(cvar("sv_eventlog_console"))
945                         to_console = FALSE; // otherwise we get the output twice
946
947         if(final)
948                 s = ":scores:";
949         else
950                 s = ":status:";
951         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
952
953         if(to_console)
954                 ServerConsoleEcho(s, FALSE);
955         if(to_eventlog)
956                 GameLogEcho(s, FALSE);
957         if(to_file)
958         {
959                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
960                 if(file == -1)
961                         to_file = FALSE;
962                 else
963                         fputs(file, strcat(s, "\n"));
964         }
965
966         FOR_EACH_CLIENT(other)
967         {
968                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
969                 {
970                         s = strcat(":player:", ftos(other.frags), ":");
971                         s = strcat(s, ftos(other.deaths), ":");
972                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
973                         s = strcat(s, ftos(other.team), ":");
974
975                         if(to_console)
976                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
977                         if(to_eventlog)
978                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
979                         if(to_file)
980                                 fputs(file, strcat(s, other.netname, "\n"));
981                 }
982         }
983
984         if(to_console)
985                 ServerConsoleEcho(":end", FALSE);
986         if(to_eventlog)
987                 GameLogEcho(":end", FALSE);
988         if(to_file)
989         {
990                 fputs(file, ":end\n");
991                 fclose(file);
992         }
993 }
994
995 void FixIntermissionClient(entity e)
996 {
997         if(!e.autoscreenshot) // initial call
998         {
999                 e.angles = e.v_angle;
1000                 e.angles_x = -e.angles_x;
1001                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1002                 e.health = -2342;
1003                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1004                 e.solid = SOLID_NOT;
1005                 e.movetype = MOVETYPE_NONE;
1006                 e.takedamage = DAMAGE_NO;
1007                 if(e.weaponentity)
1008                         e.weaponentity.effects = EF_NODRAW;
1009                 stuffcmd(e, "\nscr_printspeed 1000000\n");
1010                 if(clienttype(e) == CLIENTTYPE_REAL)
1011                 {
1012                         msg_entity = e;
1013                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1014                 }
1015         }
1016
1017         //e.velocity = '0 0 0';
1018         //e.fixangle = TRUE;
1019
1020         // TODO halt weapon animation
1021 }
1022
1023
1024 /*
1025 go to the next level for deathmatch
1026 only called if a time or frag limit has expired
1027 */
1028 void() NextLevel =
1029 {
1030         float minTotalFrags;
1031         float maxTotalFrags;
1032         float score;
1033         float f;
1034
1035         gameover = TRUE;
1036
1037         intermission_running = 1;
1038
1039 // enforce a wait time before allowing changelevel
1040         if(player_count > 0)
1041                 intermission_exittime = time + cvar("sv_mapchange_delay");
1042         else
1043                 intermission_exittime = -1;
1044
1045         WriteByte (MSG_ALL, SVC_CDTRACK);
1046         WriteByte (MSG_ALL, 3);
1047         WriteByte (MSG_ALL, 3);
1048
1049         //pos = FindIntermission ();
1050
1051         VoteReset();
1052
1053         DumpStats(TRUE);
1054
1055         if(cvar("sv_eventlog"))
1056                 GameLogEcho(":gameover", FALSE);
1057
1058         GameLogClose();
1059
1060         FOR_EACH_CLIENT(other)
1061         {
1062                 FixIntermissionClient(other);
1063
1064                 if(other.winning)
1065                         bprint(other.netname, " ^7wins.\n");
1066         }
1067
1068         minTotalFrags = 0;
1069         maxTotalFrags = 0;
1070         FOR_EACH_PLAYER(other)
1071         {
1072                 if(maxTotalFrags < other.totalfrags)
1073                         maxTotalFrags = other.totalfrags;
1074                 if(minTotalFrags > other.totalfrags)
1075                         minTotalFrags = other.totalfrags;
1076         }
1077
1078         if(!currentbots)
1079         {
1080                 FOR_EACH_PLAYER(other)
1081                 {
1082                         score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1083                         f = bound(0, other.play_time / max(time, 1), 1);
1084                         // store some statistics?
1085                 }
1086         }
1087
1088         if(cvar("g_campaign"))
1089                 CampaignPreIntermission();
1090
1091         // WriteByte (MSG_ALL, SVC_INTERMISSION);
1092 };
1093
1094 /*
1095 ============
1096 CheckRules_Player
1097
1098 Exit deathmatch games upon conditions
1099 ============
1100 */
1101 void() CheckRules_Player =
1102 {
1103         if (gameover)   // someone else quit the game already
1104                 return;
1105
1106         if(self.deadflag == DEAD_NO)
1107                 self.play_time += frametime;
1108
1109         // fixme: don't check players; instead check dom_team and ctf_team entities
1110         //   (div0: and that in CheckRules_World please)
1111 };
1112
1113 float checkrules_oneminutewarning;
1114 float checkrules_leaderfrags;
1115 float tdm_max_score, tdm_old_score;
1116
1117 float checkrules_equality;
1118 float checkrules_overtimewarning;
1119 float checkrules_overtimeend;
1120
1121 void() InitiateOvertime =
1122 {
1123         if(!checkrules_overtimeend)
1124                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1125 }
1126
1127 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1128 float WINNING_YES = 1; // winner found
1129 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1130 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1131
1132 float(float fraglimitreached, float equality) GetWinningCode =
1133 {
1134         if(equality)
1135                 if(fraglimitreached)
1136                         return WINNING_STARTOVERTIME;
1137                 else
1138                         return WINNING_NEVER;
1139         else
1140                 if(fraglimitreached)
1141                         return WINNING_YES;
1142                 else
1143                         return WINNING_NO;
1144 }
1145
1146 // set the .winning flag for exactly those players with a given field value
1147 void(.float field, float value) SetWinners =
1148 {
1149         entity head;
1150         FOR_EACH_PLAYER(head)
1151                 head.winning = (head.field == value);
1152 }
1153
1154 // set the .winning flag for those players with a given field value
1155 void(.float field, float value) AddWinners =
1156 {
1157         entity head;
1158         FOR_EACH_PLAYER(head)
1159                 if(head.field == value)
1160                         head.winning = 1;
1161 }
1162
1163 // clear the .winning flags
1164 void(void) ClearWinners =
1165 {
1166         entity head;
1167         FOR_EACH_PLAYER(head)
1168                 head.winning = 0;
1169 }
1170
1171 // Onslaught winning condition:
1172 // game terminates if only one team has a working generator (or none)
1173 float() WinningCondition_Onslaught =
1174 {
1175         entity head;
1176         local float t1, t2, t3, t4;
1177         // first check if the game has ended
1178         t1 = t2 = t3 = t4 = 0;
1179         head = find(world, classname, "onslaught_generator");
1180         while (head)
1181         {
1182                 if (head.health > 0)
1183                 {
1184                         if (head.team == COLOR_TEAM1) t1 = 1;
1185                         if (head.team == COLOR_TEAM2) t2 = 1;
1186                         if (head.team == COLOR_TEAM3) t3 = 1;
1187                         if (head.team == COLOR_TEAM4) t4 = 1;
1188                 }
1189                 head = find(head, classname, "onslaught_generator");
1190         }
1191         if (t1 + t2 + t3 + t4 < 2)
1192         {
1193                 // game over, only one team remains (or none)
1194                 ClearWinners();
1195                 if (t1) SetWinners(team, COLOR_TEAM1);
1196                 if (t2) SetWinners(team, COLOR_TEAM2);
1197                 if (t3) SetWinners(team, COLOR_TEAM3);
1198                 if (t4) SetWinners(team, COLOR_TEAM4);
1199                 dprint("Have a winner, ending game.\n");
1200                 return WINNING_YES;
1201         }
1202
1203         // Two or more teams remain
1204         return WINNING_NO;
1205 }
1206
1207 float() LMS_NewPlayerLives =
1208 {
1209         float fl;
1210         fl = cvar("fraglimit");
1211         if(fl == 0)
1212                 fl = 999;
1213
1214         // first player has left the game for dying too much? Nobody else can get in.
1215         if(lms_lowest_lives < 1)
1216                 return FALSE;
1217
1218         if(!cvar("g_lms_join_anytime"))
1219                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1220                         return FALSE;
1221
1222         return bound(1, lms_lowest_lives, fl);
1223 }
1224
1225 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1226 // they win. Otherwise the defending team wins once the timelimit passes.
1227 void assault_new_round();
1228 float() WinningCondition_Assault =
1229 {
1230         local float status;
1231         status = WINNING_NO;
1232
1233         // as the timelimit has not yet passed just assume the defending team will win
1234         if(assault_attacker_team == COLOR_TEAM1)
1235         {
1236                 SetWinners(team, COLOR_TEAM2);
1237         }
1238         else
1239         {
1240                 SetWinners(team, COLOR_TEAM1);
1241         }       
1242                 
1243         local entity ent;
1244         ent = find(world, classname, "target_assault_roundend");
1245         if(ent)
1246         {
1247                 if(ent.winning) // round end has been triggered by attacking team
1248                 {
1249                         SetWinners(team, assault_attacker_team);
1250                         if(assault_attacker_team == COLOR_TEAM1)
1251                         {
1252                                 team1_score = team1_score + 50;
1253                         }
1254                         else
1255                         {
1256                                 team2_score = team2_score + 50;
1257                         }
1258
1259                         if(ent.cnt == 1) // this was the second round
1260                         {
1261                                 status = WINNING_YES;
1262                         }
1263                         else
1264                         {
1265                                 cvar_set("timelimit", ftos((2*time)/60));
1266                                 assault_new_round();
1267                         }
1268                 }               
1269         }
1270
1271         return status;
1272
1273 }
1274
1275
1276 // LMS winning condition: game terminates if and only if there's at most one
1277 // one player who's living lives. Top two scores being equal cancels the time
1278 // limit.
1279 float() WinningCondition_LMS =
1280 {
1281         entity head;
1282         float have_player;
1283         float have_players;
1284         float l;
1285
1286         have_player = FALSE;
1287         have_players = FALSE;
1288         l = LMS_NewPlayerLives();
1289
1290         head = find(world, classname, "player");
1291         if(head)
1292                 have_player = TRUE;
1293         head = find(head, classname, "player");
1294         if(head)
1295                 have_players = TRUE;
1296
1297         if(have_player)
1298         {
1299                 // we have at least one player
1300                 if(have_players)
1301                 {
1302                         // two or more active players - continue with the game
1303                 }
1304                 else
1305                 {
1306                         // exactly one player?
1307                         if(l)
1308                         {
1309                                 // but no game has taken place yet
1310                         }
1311                         else
1312                         {
1313                                 // a winner!
1314                                 ClearWinners(); SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1315                                 dprint("Have a winner, ending game.\n");
1316                                 return WINNING_YES;
1317                         }
1318                 }
1319         }
1320         else
1321         {
1322                 // nobody is playing at all...
1323                 if(l)
1324                 {
1325                         // wait for players...
1326                 }
1327                 else
1328                 {
1329                         // SNAFU (maybe a draw game?)
1330                         ClearWinners();
1331                         dprint("No players, ending game.\n");
1332                         return WINNING_YES;
1333                 }
1334         }
1335
1336         // When we get here, we have at least two players who are actually LIVING,
1337         // or one player who is still waiting for a victim to join the server. Now
1338         // check if the top two players have equal score.
1339
1340         checkrules_leaderfrags = 0;
1341         checkrules_equality = FALSE;
1342         FOR_EACH_PLAYER(head)
1343         {
1344                 if(head.frags > checkrules_leaderfrags)
1345                 {
1346                         checkrules_leaderfrags = head.frags;
1347                         checkrules_equality = FALSE;
1348                 }
1349                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1350                         checkrules_equality = TRUE;
1351         }
1352
1353         SetWinners(frags, checkrules_leaderfrags);
1354
1355         // The top two players have the same amount of lives? No timelimit then,
1356         // enter overtime...
1357
1358         if(checkrules_equality)
1359                 return WINNING_NEVER;
1360
1361         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1362         return WINNING_NO;
1363 }
1364
1365 // DM winning condition: game terminates if a player reached the fraglimit,
1366 // unless the first two players have the same score. The latter case also
1367 // breaks the time limit.
1368 float(float fraglimit) WinningCondition_MaxIndividualScore =
1369 {
1370         float checkrules_oldleaderfrags;
1371         entity head;
1372
1373         checkrules_oldleaderfrags = checkrules_leaderfrags;
1374         checkrules_leaderfrags = 0;
1375         checkrules_equality = FALSE;
1376         FOR_EACH_PLAYER(head)
1377         {
1378                 if(head.frags > checkrules_leaderfrags)
1379                 {
1380                         checkrules_leaderfrags = head.frags;
1381                         checkrules_equality = FALSE;
1382                 }
1383                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1384                         checkrules_equality = TRUE;
1385         }
1386
1387         if(checkrules_leaderfrags > 0)
1388                 SetWinners(frags, checkrules_leaderfrags);
1389         else
1390                 ClearWinners();
1391
1392         if (!cvar("g_runematch"))
1393                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1394                 {
1395                         if (checkrules_leaderfrags == fraglimit - 1)
1396                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1397                         else if (checkrules_leaderfrags == fraglimit - 2)
1398                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1399                         else if (checkrules_leaderfrags == fraglimit - 3)
1400                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1401                 }
1402
1403         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1404 }
1405
1406 float(float fraglimit) WinningConditionBase_Teamplay =
1407 {
1408         tdm_old_score = tdm_max_score;
1409         tdm_max_score = max4(team1_score, team2_score, team3_score, team4_score);
1410
1411         checkrules_equality =
1412         (
1413                 (tdm_max_score > 0)
1414                 &&
1415                 (
1416                           (team1_score == tdm_max_score)
1417                         + (team2_score == tdm_max_score)
1418                         + (team3_score == tdm_max_score)
1419                         + (team4_score == tdm_max_score)
1420                         >= 2));
1421
1422         ClearWinners();
1423         if(tdm_max_score > 0)
1424         {
1425                 if(team1_score == tdm_max_score)
1426                         AddWinners(team, COLOR_TEAM1);
1427                 if(team2_score == tdm_max_score)
1428                         AddWinners(team, COLOR_TEAM2);
1429                 if(team3_score == tdm_max_score)
1430                         AddWinners(team, COLOR_TEAM3);
1431                 if(team4_score == tdm_max_score)
1432                         AddWinners(team, COLOR_TEAM4);
1433         }
1434
1435         if(!cvar("g_runematch") && !cvar("g_domination"))
1436                 if(tdm_max_score != tdm_old_score)
1437                 {
1438                         if(tdm_max_score == fraglimit - 1)
1439                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1440                         else if(tdm_max_score == fraglimit - 2)
1441                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1442                         else if(tdm_max_score == fraglimit - 3)
1443                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1444                 }
1445
1446         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1447 }
1448
1449 // TDM winning condition: game terminates if a team's score sum reached the
1450 // fraglimit, unless the first two teams have the same total score. The latter
1451 // case also breaks the time limit.
1452 float(float fraglimit) WinningCondition_MaxTeamSum =
1453 {
1454         entity head;
1455
1456         team1_score = team2_score = team3_score = team4_score = 0;
1457
1458         FOR_EACH_PLAYER(head)
1459         {
1460                 if(head.team == COLOR_TEAM1)
1461                         team1_score += head.frags;
1462                 else if(head.team == COLOR_TEAM2)
1463                         team2_score += head.frags;
1464                 else if(head.team == COLOR_TEAM3)
1465                         team3_score += head.frags;
1466                 else if(head.team == COLOR_TEAM4)
1467                         team4_score += head.frags;
1468         }
1469
1470         return WinningConditionBase_Teamplay(fraglimit);
1471 }
1472
1473 // DOM/CTF winning condition: game terminates if the max of a team's players'
1474 // score reached the fraglimit, unless the first two teams have the same
1475 // maximum score. The latter case also breaks the time limit.
1476 float(float fraglimit) WinningCondition_MaxTeamMax =
1477 {
1478         entity head;
1479
1480         team1_score = team2_score = team3_score = team4_score = 0;
1481
1482         FOR_EACH_PLAYER(head)
1483         {
1484                 if(head.team == COLOR_TEAM1)
1485                 {
1486                         if(head.frags > team1_score)
1487                                 team1_score = head.frags;
1488                 }
1489                 else if(head.team == COLOR_TEAM2)
1490                 {
1491                         if(head.frags > team2_score)
1492                                 team2_score = head.frags;
1493                 }
1494                 else if(head.team == COLOR_TEAM3)
1495                 {
1496                         if(head.frags > team3_score)
1497                                 team3_score = head.frags;
1498                 }
1499                 else if(head.team == COLOR_TEAM4)
1500                 {
1501                         if(head.frags > team4_score)
1502                                 team4_score = head.frags;
1503                 }
1504         }
1505
1506         return WinningConditionBase_Teamplay(fraglimit);
1507 }
1508
1509 void print_to(entity e, string s)
1510 {
1511         if(e)
1512                 sprint(e, strcat(s, "\n"));
1513         else
1514                 ServerConsoleEcho(s, TRUE);
1515 }
1516
1517 void PrintScoreboardFor(entity e, string name, string colorcode, float whichteam)
1518 {
1519         entity head;
1520         float v;
1521         float teamvalue;
1522         float fragtotal;
1523         string s;
1524         float found;
1525         found = FALSE;
1526         teamvalue = 0;
1527         FOR_EACH_PLAYER(head)
1528         {
1529                 if(!whichteam || head.team == whichteam)
1530                 {
1531                         if(name != "")
1532                                 if(!found)
1533                                         print_to(e, strcat(" ", colorcode, name, ":"));
1534                         found = TRUE;
1535                         fragtotal = fragtotal + head.frags;
1536                         s = ftos(head.frags);
1537                         s = strcat(s, "/", ftos(head.deaths));
1538                         s = strcat(s, " @ ", ftos(head.ping));
1539                         if(clienttype(head) == CLIENTTYPE_BOT)
1540                                 s = strcat(s, "botms");
1541                         else
1542                                 s = strcat(s, "ms");
1543                         v = PlayerValue(head);
1544                         teamvalue += v;
1545                         s = strcat(s, " / ", ftos(v));
1546                         print_to(e, strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"));
1547                 }
1548         }
1549         if(whichteam && found)
1550         {
1551                 s = ftos(fragtotal);
1552                 s = strcat(s, " / ", ftos(teamvalue));
1553                 print_to(e, strcat(colorcode, "  (total: ", s, ")"));
1554         }
1555 }
1556
1557 void PrintScoreboard(entity e)
1558 {
1559         print_to(e, strcat("Time:      ", ftos(time / 60)));
1560         print_to(e, strcat("Timelimit: ", ftos(cvar("timelimit"))));
1561         print_to(e, strcat("Fraglimit: ", ftos(cvar("fraglimit"))));
1562         print_to(e, "Scoreboard:");
1563         if(teams_matter)
1564         {
1565                 PrintScoreboardFor(e, "Red", "^1", COLOR_TEAM1);
1566                 PrintScoreboardFor(e, "Blue", "^4", COLOR_TEAM2);
1567                 PrintScoreboardFor(e, "Yellow", "^3", COLOR_TEAM3);
1568                 PrintScoreboardFor(e, "Pink", "^6", COLOR_TEAM4);
1569         }
1570         else
1571         {
1572                 PrintScoreboardFor(e, "", "^7", 0);
1573         }
1574         print_to(e, ".");
1575 }
1576
1577 void ShuffleMaplist()
1578 {
1579         string result;
1580         float start;
1581         float litems;
1582         float selected;
1583         float i;
1584
1585         result = cvar_string("g_maplist");
1586         litems = tokenize(result);
1587
1588         for(start = 0; start < litems - 1; ++start)
1589         {
1590                 result = "";
1591
1592                 // select a random item
1593                 selected = ceil(random() * (litems - start) + start) - 1;
1594
1595                 // shift this item to the place start
1596 #ifdef MAPINFO
1597                 for(i = 0; i < start; ++i)
1598                         result = strcat(result, " ", argv(i));
1599                 result = strcat(result, " ", argv(selected));
1600                 for(i = start; i < litems; ++i)
1601                         if(i != selected)
1602                                 result = strcat(result, " ", argv(i));
1603                 result = substring(result, 1, strlen(result) - 1);
1604 #else
1605                 for(i = 0; i < start; ++i)
1606                         result = strcat(result, "'", argv(i), "'");
1607                 result = strcat(result, "'", argv(selected), "'");
1608                 for(i = start; i < litems; ++i)
1609                         if(i != selected)
1610                                 result = strcat(result, "'", argv(i), "'");
1611 #endif
1612
1613                 litems = tokenize(result);
1614
1615                 //dprint(result, "\n");
1616         }
1617
1618         cvar_set("g_maplist", result);
1619 }
1620
1621 /*
1622 ============
1623 CheckRules_World
1624
1625 Exit deathmatch games upon conditions
1626 ============
1627 */
1628 void() CheckRules_World =
1629 {
1630         local float status;
1631         local float timelimit;
1632         local float fraglimit;
1633
1634         VoteThink();
1635         MapVote_Think();
1636
1637         SetDefaultAlpha();
1638
1639         /*
1640         MapVote_Think should now do that part
1641         if (intermission_running)
1642                 if (time >= intermission_exittime + 60)
1643                 {
1644                         if(!DoNextMapOverride())
1645                                 GotoNextMap();
1646                         return;
1647                 }
1648         */
1649
1650         if (gameover)   // someone else quit the game already
1651         {
1652                 if(player_count == 0) // Nobody there? Then let's go to the next map
1653                         MapVote_Start();
1654                         // this will actually check the player count in the next frame
1655                         // again, but this shouldn't hurt
1656                 return;
1657         }
1658
1659         timelimit = cvar("timelimit") * 60;
1660         fraglimit = cvar("fraglimit");
1661
1662         if(checkrules_overtimeend)
1663         {
1664                 if(!checkrules_overtimewarning)
1665                 {
1666                         checkrules_overtimewarning = TRUE;
1667                         //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1668                         bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1669                 }
1670         }
1671         else
1672         {
1673                 if (timelimit && time >= timelimit)
1674                         InitiateOvertime();
1675         }
1676
1677         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1678         {
1679                 NextLevel();
1680                 return;
1681         }
1682
1683         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1684         {
1685                 checkrules_oneminutewarning = TRUE;
1686                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1687         }
1688
1689         status = WINNING_NO;
1690         if(g_assault)
1691         {
1692                 status = WinningCondition_Assault();
1693         }
1694         else if(g_lms)
1695         {
1696                 status = WinningCondition_LMS();
1697         }
1698         else if (g_onslaught)
1699         {
1700                 status = WinningCondition_Onslaught();
1701         }
1702         else
1703         {
1704                 if(teams_matter)
1705                 {
1706                         if(g_tdm || cvar("g_runematch") || g_ctf || cvar("g_domination") || g_keyhunt)
1707                                 status = WinningCondition_MaxTeamSum(fraglimit);
1708                         //else if()
1709                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1710                         else
1711                         {
1712                                 dprint("div0: How can this happen?\n");
1713                                 status = WinningCondition_MaxTeamMax(fraglimit);
1714                         }
1715                 }
1716                 else
1717                         status = WinningCondition_MaxIndividualScore(fraglimit);
1718         }
1719
1720         if(status == WINNING_STARTOVERTIME)
1721         {
1722                 status = WINNING_NEVER;
1723                 InitiateOvertime();
1724         }
1725
1726         if(status == WINNING_NEVER)
1727                 // equality cases! Nobody wins if the overtime ends in a draw.
1728                 ClearWinners();
1729
1730         if(checkrules_overtimeend)
1731                 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1732                         status = WINNING_YES;
1733
1734         if(status == WINNING_YES)
1735                 NextLevel();
1736 };
1737
1738 float randsel_value;
1739 float randsel_priority;
1740 float randsel_count;
1741 void RandSel_Init()
1742 {
1743         randsel_value = -1;
1744         randsel_priority = -1;
1745         randsel_count = -1;
1746 }
1747 void RandSel_Add(float priority, float value)
1748 {
1749         if(priority > randsel_priority)
1750         {
1751                 randsel_priority = priority;
1752                 randsel_value = value;
1753                 randsel_count = 1;
1754         }
1755         else if(priority == randsel_priority)
1756         {
1757                 randsel_count += 1;
1758                 if(ceil(random() * randsel_count) == 1)
1759                         randsel_value = value;
1760         }
1761 }
1762
1763 float mapvote_nextthink;
1764 float mapvote_initialized;
1765 float mapvote_keeptwotime;
1766 float mapvote_timeout;
1767 string mapvote_message;
1768
1769 #define MAPVOTE_COUNT 10
1770 float mapvote_count;
1771 string mapvote_maps[MAPVOTE_COUNT];
1772 float mapvote_maps_suggested[MAPVOTE_COUNT];
1773 string mapvote_suggestions[MAPVOTE_COUNT];
1774 float mapvote_suggestion_ptr;
1775 float mapvote_maxlen;
1776 float mapvote_voters;
1777 float mapvote_votes[MAPVOTE_COUNT];
1778 float mapvote_run;
1779 .float mapvote;
1780
1781 void MapVote_ClearAllVotes()
1782 {
1783         FOR_EACH_CLIENT(other)
1784                 other.mapvote = 0;
1785 }
1786
1787 string MapVote_Suggest(string m)
1788 {
1789         float i;
1790         if(m == "")
1791                 return "That's not how to use this command.";
1792         if(!cvar("g_maplist_votable_suggestions"))
1793                 return "Suggestions are not accepted on this server.";
1794         if(mapvote_initialized)
1795                 return "Can't suggest - voting is already in progress!";
1796 #ifdef MAPINFO
1797         m = MapInfo_FixName(m);
1798         if(!m)
1799                 return "The map you suggested is not available on this server.";
1800 #endif
1801         if(!cvar("g_maplist_votable_suggestions_change_gametype"))
1802                 if(!IsSameGametype(m))
1803                         return "This server does not allow changing the game type by map suggestions.";
1804         if(!cvar("g_maplist_votable_override_mostrecent"))
1805                 if(Map_IsRecent(m))
1806                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1807
1808 #ifdef MAPINFO
1809         if(!MapInfo_CheckMap(m))
1810                 return "The map you suggested does not support the current game mode.";
1811 #else
1812         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1813                 return "The map you suggested is not available on this server.";
1814 #endif
1815         for(i = 0; i < mapvote_suggestion_ptr; ++i)
1816                 if(mapvote_suggestions[i] == m)
1817                         return "This map was already suggested.";
1818         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1819         {
1820                 i = ceil(random() * mapvote_suggestion_ptr) - 1;
1821         }
1822         else
1823         {
1824                 i = mapvote_suggestion_ptr;
1825                 mapvote_suggestion_ptr += 1;
1826         }
1827         if(mapvote_suggestions[i] != "")
1828                 strunzone(mapvote_suggestions[i]);
1829         mapvote_suggestions[i] = strzone(m);
1830         GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid), ":", self.netname), TRUE);
1831         return "Suggestion accepted.";
1832 }
1833
1834 void MapVote_AddVotable(string nextMap, float isSuggestion)
1835 {
1836         float j;
1837         if(nextMap == "")
1838                 return;
1839         for(j = 0; j < mapvote_count; ++j)
1840                 if(mapvote_maps[j] == nextMap)
1841                         return;
1842         if(strlen(nextMap) > mapvote_maxlen)
1843                 mapvote_maxlen = strlen(nextMap);
1844         mapvote_maps[mapvote_count] = strzone(nextMap);
1845         mapvote_maps_suggested[mapvote_count] = isSuggestion;
1846         mapvote_count += 1;
1847 }
1848
1849 void MapVote_Init()
1850 {
1851         float i;
1852         float nmax, smax;
1853
1854         MapVote_ClearAllVotes();
1855
1856         nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
1857         smax = min(nmax, cvar("g_maplist_votable_suggestions"));
1858         mapvote_count = 0;
1859
1860         for(i = 0; i < 100 && mapvote_count < smax; ++i)
1861                 MapVote_AddVotable(mapvote_suggestions[ceil(random() * mapvote_suggestion_ptr) - 1], TRUE);
1862
1863         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1864                 MapVote_AddVotable(GetNextMap(), FALSE);
1865
1866         if(mapvote_count == 0)
1867         {
1868                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1869 #ifdef MAPINFO
1870                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
1871 #else
1872                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
1873 #endif
1874                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1875                         MapVote_AddVotable(GetNextMap(), FALSE);
1876         }
1877
1878         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
1879
1880         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
1881         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
1882         if(mapvote_count < 3 || mapvote_keeptwotime <= time)
1883                 mapvote_keeptwotime = 0;
1884         mapvote_message = "Choose a map and press its key!";
1885 }
1886 float MapVote_Finished(float mappos)
1887 {
1888         string result;
1889         float i;
1890
1891         result = strcat(":vote:finished:", mapvote_maps[mappos]);
1892         result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
1893         for(i = 0; i < mapvote_count; ++i)
1894                 if(i != mappos)
1895                         if(mapvote_maps[i] != "")
1896                         {
1897                                 result = strcat(result, ":", mapvote_maps[i]);
1898                                 result = strcat(result, ":", ftos(mapvote_votes[i]));
1899                         }
1900         GameLogEcho(result, FALSE);
1901         if(mapvote_maps_suggested[mappos])
1902                 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]), FALSE);
1903
1904         FOR_EACH_REALCLIENT(other)
1905                 FixClientCvars(other);
1906
1907         Map_Goto_SetStr(mapvote_maps[mappos]);
1908         Map_Goto();
1909         alreadychangedlevel = TRUE;
1910         return TRUE;
1911 }
1912 void MapVote_CheckRules_1()
1913 {
1914         float i;
1915
1916         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1917         {
1918                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
1919                 mapvote_votes[i] = 0;
1920         }
1921
1922         mapvote_voters = 0;
1923         FOR_EACH_REALCLIENT(other)
1924         {
1925                 ++mapvote_voters;
1926                 if(other.mapvote)
1927                 {
1928                         i = other.mapvote - 1;
1929                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
1930                         mapvote_votes[i] = mapvote_votes[i] + 1;
1931                 }
1932         }
1933 }
1934
1935 float MapVote_CheckRules_2()
1936 {
1937         float i;
1938         float firstPlace, secondPlace;
1939         float firstPlaceVotes, secondPlaceVotes;
1940         string result;
1941
1942         RandSel_Init();
1943         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1944                 RandSel_Add(mapvote_votes[i], i);
1945         firstPlace = randsel_value;
1946         firstPlaceVotes = randsel_priority;
1947         //dprint("First place: ", ftos(firstPlace), "\n");
1948         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
1949
1950         RandSel_Init();
1951         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1952                 if(i != firstPlace)
1953                         RandSel_Add(mapvote_votes[i], i);
1954         secondPlace = randsel_value;
1955         secondPlaceVotes = randsel_priority;
1956         //dprint("Second place: ", ftos(secondPlace), "\n");
1957         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
1958
1959         if(firstPlace == -1)
1960                 error("No first place in map vote... WTF?");
1961
1962         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters - firstPlaceVotes) < firstPlaceVotes)
1963                 return MapVote_Finished(firstPlace);
1964
1965         if(mapvote_keeptwotime)
1966                 if(time > mapvote_keeptwotime || (mapvote_voters - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
1967                 {
1968                         mapvote_message = "Now decide between the TOP TWO!";
1969                         mapvote_keeptwotime = 0;
1970                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
1971                         result = strcat(result, ":", ftos(firstPlaceVotes));
1972                         result = strcat(result, ":", mapvote_maps[secondPlace]);
1973                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
1974                         for(i = 0; i < mapvote_count; ++i)
1975                                 if(i != firstPlace)
1976                                         if(i != secondPlace)
1977                                                 if(mapvote_maps[i] != "")
1978                                                 {
1979                                                         result = strcat(result, ":", mapvote_maps[i]);
1980                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
1981                                                         strunzone(mapvote_maps[i]);
1982                                                         mapvote_maps[i] = "";
1983                                                 }
1984                         GameLogEcho(result, FALSE);
1985                 }
1986
1987         return FALSE;
1988 }
1989 void MapVote_Tick()
1990 {
1991         string msgstr;
1992         string tmp;
1993         float i;
1994         float keeptwo;
1995
1996         keeptwo = mapvote_keeptwotime;
1997         MapVote_CheckRules_1(); // count
1998         if(MapVote_CheckRules_2()) // decide
1999                 return;
2000
2001         FOR_EACH_REALCLIENT(other)
2002         {
2003                 // hide scoreboard again
2004                 if(other.health != 2342)
2005                 {
2006                         other.health = 2342;
2007                         other.impulse = 0;
2008                         if(clienttype(other) == CLIENTTYPE_REAL)
2009                         {
2010                                 stuffcmd(other, "\nin_bind 7 1 \"impulse 1\"; in_bind 7 2 \"impulse 2\"; in_bind 7 3 \"impulse 3\"; in_bind 7 4 \"impulse 4\"; in_bind 7 5 \"impulse 5\"; in_bind 7 6 \"impulse 6\"; in_bind 7 7 \"impulse 7\"; in_bind 7 8 \"impulse 8\"; in_bind 7 9 \"impulse 9\"; in_bind 7 0 \"impulse 10\"; in_bind 7 KP_1 \"impulse 1\"; in_bind 7 KP_2 \"impulse 2\"; in_bind 7 KP_3 \"impulse 3\"; in_bind 7 KP_4 \"impulse 4\"; in_bind 7 KP_5 \"impulse 5\"; in_bind 7 KP_6 \"impulse 6\"; in_bind 7 KP_7 \"impulse 7\"; in_bind 7 KP_8 \"impulse 8\"; in_bind 7 KP_9 \"impulse 9\"; in_bind 7 KP_0 \"impulse 10\"; in_bindmap 7 0\n");
2011                                 msg_entity = other;
2012                                 WriteByte(MSG_ONE, SVC_FINALE);
2013                                 WriteString(MSG_ONE, "");
2014                                 /*
2015                                 for(i = 0; i < mapvote_count; ++i)
2016                                         if(mapvote_maps[i] != "")
2017                                         {
2018                                                 tmp = mapvote_maps[i];
2019                                                 sprint(other, strcat("map voting: type ^1impulse ", ftos(i+1), "^7 to vote for ", tmp, "\n"));
2020                                         }
2021                                 */
2022                         }
2023                 }
2024
2025                 // notify about keep-two
2026                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2027                         play2(other, "misc/invshot.wav");
2028
2029                 // clear possibly invalid votes
2030                 if(mapvote_maps[other.mapvote - 1] == "")
2031                         other.mapvote = 0;
2032                 // use impulses as new vote
2033                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2034                         if(mapvote_maps[other.impulse - 1] != "")
2035                                 other.mapvote = other.impulse;
2036                 other.impulse = 0;
2037         }
2038
2039         MapVote_CheckRules_1(); // just count
2040
2041         FOR_EACH_REALCLIENT(other)
2042         {
2043                 // display voting screen
2044                 msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
2045                 msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
2046                 msgstr = strcat(msgstr, mapvote_message);
2047                 msgstr = strcat(msgstr, "\n\n");
2048                 for(i = 0; i < mapvote_count; ++i)
2049                         if(mapvote_maps[i] == "")
2050                                 msgstr = strcat(msgstr, "\n");
2051                         else
2052                         {
2053                                 tmp = mapvote_maps[i];
2054                                 tmp = strpad(mapvote_maxlen, tmp);
2055                                 tmp = strcat(ftos(math_mod(i + 1, 10)), ": ", tmp);
2056                                 tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
2057                                 if(mapvote_votes[i] != 1)
2058                                         tmp = strcat(tmp, "s");
2059                                 tmp = strcat(tmp, ")");
2060                                 tmp = strpad(mapvote_maxlen + 15, tmp);
2061                                 if(other.mapvote == i + 1)
2062                                         msgstr = strcat(msgstr, "^3> ", tmp, "\n");
2063                                 else
2064                                         msgstr = strcat(msgstr, "^7  ", tmp, "\n");
2065                         }
2066                 i = ceil(mapvote_timeout - time);
2067                 msgstr = strcat(msgstr, "\n\n", ftos(i), " second");
2068                 if(i != 1)
2069                         msgstr = strcat(msgstr, "s");
2070                 msgstr = strcat(msgstr, " left");
2071
2072                 centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
2073         }
2074 }
2075 void MapVote_Start()
2076 {
2077         if(mapvote_run)
2078                 return;
2079
2080 #ifdef MAPINFO
2081         MapInfo_Enumerate();
2082         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures()))
2083 #endif
2084                 mapvote_run = TRUE;
2085 }
2086 void MapVote_Think()
2087 {
2088         if(!mapvote_run)
2089                 return;
2090
2091         if(alreadychangedlevel)
2092                 return;
2093
2094         if(time < mapvote_nextthink)
2095                 return;
2096         //dprint("tick\n");
2097
2098         mapvote_nextthink = time + 0.5;
2099
2100         if(!mapvote_initialized)
2101         {
2102                 mapvote_initialized = TRUE;
2103                 if(DoNextMapOverride())
2104                         return;
2105                 if(!cvar("g_maplist_votable") || player_count <= 0)
2106                 {
2107                         GotoNextMap();
2108                         return;
2109                 }
2110                 MapVote_Init();
2111         }
2112
2113         MapVote_Tick();
2114 };
2115
2116 string GotoMap(string m)
2117 {
2118 #ifdef MAPINFO
2119         if(!MapInfo_CheckMap(m))
2120 #else
2121         if(!TryFile(strcat("maps/", m, ".mapcfg")))
2122 #endif
2123                 return "The map you chose is not available on this server.";
2124         cvar_set("nextmap", m);
2125         cvar_set("timelimit", "-1");
2126         if(mapvote_initialized || alreadychangedlevel)
2127         {
2128                 if(DoNextMapOverride())
2129                         return "Map switch initiated.";
2130                 else
2131                         return "Hm... no. For some reason I like THIS map more.";
2132         }
2133         else
2134                 return "Map switch will happen after scoreboard.";
2135 }
2136
2137
2138 void EndFrame()
2139 {
2140         FOR_EACH_REALCLIENT(self)
2141         {
2142                 if(self.classname == "spectator")
2143                 {
2144                         if(self.enemy.hitsound)
2145                                 play2(self, "misc/hit.wav");
2146                 }
2147                 else
2148                 {
2149                         if(self.hitsound)
2150                                 play2(self, "misc/hit.wav");
2151                 }
2152         }
2153         FOR_EACH_CLIENT(self)
2154                 self.hitsound = FALSE;
2155 }
2156
2157
2158 /*
2159  * RedirectionThink:
2160  * returns TRUE if redirecting
2161  */
2162 float redirection_timeout;
2163 float redirection_nextthink;
2164 float RedirectionThink()
2165 {
2166         float clients_found;
2167
2168         if(redirection_target == "")
2169                 return FALSE;
2170
2171         if(!redirection_timeout)
2172         {
2173                 cvar_set("sv_public", "-2");
2174                 redirection_timeout = time + 0.5; // this will only try twice... should be able to keep more clients
2175                 if(redirection_target == "self")
2176                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2177                 else
2178                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2179         }
2180
2181         if(time < redirection_nextthink)
2182                 return TRUE;
2183
2184         redirection_nextthink = time + 1;
2185
2186         clients_found = 0;
2187         FOR_EACH_REALCLIENT(self)
2188         {
2189                 ServerConsoleEcho(strcat("Redirecting: sending connect command to ", self.netname), FALSE);
2190                 if(redirection_target == "self")
2191                         stuffcmd(self, "\ndisconnect; reconnect\n");
2192                 else
2193                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2194                 ++clients_found;
2195         }
2196
2197         ServerConsoleEcho(strcat("Redirecting: ", ftos(clients_found), " clients left."), FALSE);
2198
2199         if(time > redirection_timeout || clients_found == 0)
2200                 localcmd("\nwait; wait; wait; quit\n");
2201
2202         return TRUE;
2203 }