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