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