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