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