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