]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
new vote/ready nagger display (untested, can't test this alone)
[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 Nagger_Init();
160 void spawnfunc_worldspawn (void)
161 {
162         float fd, l;
163         string s;
164
165         dprint_load(); // load dprint status from cvar
166
167         if(world_already_spawned)
168                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
169         world_already_spawned = TRUE;
170
171         compressShortVector_init();
172
173         local entity head;
174         head = nextent(world);
175         maxclients = 0;
176         while(head)
177         {
178                 ++maxclients;
179                 head = nextent(head);
180         }
181
182         // needs to be done so early as they would still spawn
183         RegisterWeapons();
184
185         if(GotoFirstMap())
186                 return;
187
188         if(sv_cheats)
189                 ServerProgsDB = db_create();
190         else
191                 ServerProgsDB = db_load("server.db");
192
193         /*
194         TODO sound pack system
195         // initialize sound pack system
196         soundpack = cvar_string("g_soundpack");
197         if(soundpack != "")
198                 soundpack = strcat(soundpack, "/");
199         soundpack = strzone(soundpack);
200         */
201
202         // 0 normal
203         lightstyle(0, "m");
204
205         // 1 FLICKER (first variety)
206         lightstyle(1, "mmnmmommommnonmmonqnmmo");
207
208         // 2 SLOW STRONG PULSE
209         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
210
211         // 3 CANDLE (first variety)
212         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
213
214         // 4 FAST STROBE
215         lightstyle(4, "mamamamamama");
216
217         // 5 GENTLE PULSE 1
218         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
219
220         // 6 FLICKER (second variety)
221         lightstyle(6, "nmonqnmomnmomomno");
222
223         // 7 CANDLE (second variety)
224         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
225
226         // 8 CANDLE (third variety)
227         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
228
229         // 9 SLOW STROBE (fourth variety)
230         lightstyle(9, "aaaaaaaazzzzzzzz");
231
232         // 10 FLUORESCENT FLICKER
233         lightstyle(10, "mmamammmmammamamaaamammma");
234
235         // 11 SLOW PULSE NOT FADE TO BLACK
236         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
237
238         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
239
240         // 63 testing
241         lightstyle(63, "a");
242
243         if(cvar("g_campaign"))
244                 CampaignPreInit();
245
246         InitGameplayMode();
247         readlevelcvars();
248
249         player_count = 0;
250         bot_waypoints_for_items = cvar("g_waypoints_for_items");
251         if(bot_waypoints_for_items == 1)
252                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
253                         bot_waypoints_for_items = 0;
254
255         // for setting by mapinfo
256         q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
257         cvar_set("sv_q3acompat_machineshotgunswap", "0");
258
259         precache();
260
261         WaypointSprite_Init();
262
263         //if (g_domination)
264         //      dom_init();
265
266         GameLogInit(); // prepare everything
267         if(cvar("sv_eventlog"))
268         {
269                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
270                 s = strcat(s, ftos(random()));
271                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
272                 s = ":gameinfo:mutators:LIST";
273                 if(cvar("g_grappling_hook"))
274                         s = strcat(s, ":grappling_hook");
275                 if(!cvar("g_use_ammunition"))
276                         s = strcat(s, ":no_use_ammunition");
277                 if(!cvar("g_pickup_items"))
278                         s = strcat(s, ":no_pickup_items");
279                 if(cvar("g_instagib"))
280                         s = strcat(s, ":instagib");
281                 if(cvar("g_rocketarena"))
282                         s = strcat(s, ":rockerarena");
283                 if(cvar("g_nixnex"))
284                         s = strcat(s, ":nixnex");
285                 if(cvar("g_vampire"))
286                         s = strcat(s, ":vampire");
287                 if(cvar("g_laserguided_missile"))
288                         s = strcat(s, ":laserguided_missile");
289                 if(cvar("g_norecoil"))
290                         s = strcat(s, ":norecoil");
291                 if(cvar("g_midair"))
292                         s = strcat(s, ":midair");
293                 if(cvar("g_minstagib"))
294                         s = strcat(s, ":minstagib");
295                 GameLogEcho(s);
296                 GameLogEcho(":gameinfo:end");
297         }
298
299         cvar_set("nextmap", "");
300
301         SetDefaultAlpha();
302
303         if(cvar("g_campaign"))
304                 CampaignPostInit();
305
306         fteqcc_testbugs();
307
308         Ban_LoadBans();
309
310         //initialise globals related to sv_timeout
311         sys_ticrate = cvar("sys_ticrate");
312         orig_slowmo = cvar("slowmo");
313
314         MapInfo_Enumerate();
315         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1);
316
317         //if tourney is used map starts in warmup mode. if this mode shall stay unlimited, reset timelimit, but save the original one
318         if(inWarmupStage) {
319                 timelimit_orig = cvar("timelimit");
320                 cvar_set("timelimit", "0");
321         }
322
323         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
324         {
325                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
326                 if(fd != -1)
327                 {
328                         while((s = fgets(fd)))
329                         {
330                                 l = tokenize(s);
331                                 if(l < 2)
332                                         continue;
333                                 if(argv(0) == "cd")
334                                 {
335                                         print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
336                                         print("  cdtrack ", argv(2), "\n");
337                                 }
338                                 else if(argv(0) == "fog")
339                                 {
340                                         print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
341                                         print("  \"fog\" \"", s, "\"\n");
342                                 }
343                                 else if(argv(0) == "set")
344                                 {
345                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
346                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
347                                 }
348                                 else if(argv(0) != "//")
349                                 {
350                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
351                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
352                                 }
353                         }
354                         fclose(fd);
355                 }
356         }
357
358         addstat(STAT_SYS_TICRATE, AS_FLOAT, stat_sys_ticrate);
359         addstat(STAT_WEAPONS, AS_INT, weapons);
360         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
361         Nagger_Init();
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 void CheckRules_Player()
1082 {
1083         if (gameover)   // someone else quit the game already
1084                 return;
1085
1086         if(self.deadflag == DEAD_NO)
1087                 self.play_time += frametime;
1088
1089         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1090         //   (div0: and that in CheckRules_World please)
1091 };
1092
1093 float checkrules_oneminutewarning;
1094
1095 float checkrules_equality;
1096 float checkrules_overtimewarning;
1097 float checkrules_overtimeend;
1098
1099 void InitiateOvertime()
1100 {
1101         if(!checkrules_overtimeend)
1102                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1103 }
1104
1105 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1106 float WINNING_YES = 1; // winner found
1107 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1108 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1109
1110 float GetWinningCode(float fraglimitreached, float equality)
1111 {
1112         if(equality)
1113                 if(fraglimitreached)
1114                         return WINNING_STARTOVERTIME;
1115                 else
1116                         return WINNING_NEVER;
1117         else
1118                 if(fraglimitreached)
1119                         return WINNING_YES;
1120                 else
1121                         return WINNING_NO;
1122 }
1123
1124 // set the .winning flag for exactly those players with a given field value
1125 void SetWinners(.float field, float value)
1126 {
1127         entity head;
1128         FOR_EACH_PLAYER(head)
1129                 head.winning = (head.field == value);
1130 }
1131
1132 // set the .winning flag for those players with a given field value
1133 void AddWinners(.float field, float value)
1134 {
1135         entity head;
1136         FOR_EACH_PLAYER(head)
1137                 if(head.field == value)
1138                         head.winning = 1;
1139 }
1140
1141 // clear the .winning flags
1142 void ClearWinners(void)
1143 {
1144         entity head;
1145         FOR_EACH_PLAYER(head)
1146                 head.winning = 0;
1147 }
1148
1149 // Onslaught winning condition:
1150 // game terminates if only one team has a working generator (or none)
1151 float WinningCondition_Onslaught()
1152 {
1153         entity head;
1154         local float t1, t2, t3, t4;
1155         // first check if the game has ended
1156         t1 = t2 = t3 = t4 = 0;
1157         head = find(world, classname, "onslaught_generator");
1158         while (head)
1159         {
1160                 if (head.health > 0)
1161                 {
1162                         if (head.team == COLOR_TEAM1) t1 = 1;
1163                         if (head.team == COLOR_TEAM2) t2 = 1;
1164                         if (head.team == COLOR_TEAM3) t3 = 1;
1165                         if (head.team == COLOR_TEAM4) t4 = 1;
1166                 }
1167                 head = find(head, classname, "onslaught_generator");
1168         }
1169         if (t1 + t2 + t3 + t4 < 2)
1170         {
1171                 // game over, only one team remains (or none)
1172                 ClearWinners();
1173                 if (t1) SetWinners(team, COLOR_TEAM1);
1174                 if (t2) SetWinners(team, COLOR_TEAM2);
1175                 if (t3) SetWinners(team, COLOR_TEAM3);
1176                 if (t4) SetWinners(team, COLOR_TEAM4);
1177                 dprint("Have a winner, ending game.\n");
1178                 return WINNING_YES;
1179         }
1180
1181         // Two or more teams remain
1182         return WINNING_NO;
1183 }
1184
1185 float LMS_NewPlayerLives()
1186 {
1187         float fl;
1188         fl = cvar("fraglimit");
1189         if(fl == 0)
1190                 fl = 999;
1191
1192         // first player has left the game for dying too much? Nobody else can get in.
1193         if(lms_lowest_lives < 1)
1194                 return 0;
1195
1196         if(!cvar("g_lms_join_anytime"))
1197                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1198                         return 0;
1199
1200         return bound(1, lms_lowest_lives, fl);
1201 }
1202
1203 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1204 // they win. Otherwise the defending team wins once the timelimit passes.
1205 void assault_new_round();
1206 float WinningCondition_Assault()
1207 {
1208         local float status;
1209         status = WINNING_NO;
1210
1211         // as the timelimit has not yet passed just assume the defending team will win
1212         if(assault_attacker_team == COLOR_TEAM1)
1213         {
1214                 SetWinners(team, COLOR_TEAM2);
1215         }
1216         else
1217         {
1218                 SetWinners(team, COLOR_TEAM1);
1219         }
1220
1221         local entity ent;
1222         ent = find(world, classname, "target_assault_roundend");
1223         if(ent)
1224         {
1225                 if(ent.winning) // round end has been triggered by attacking team
1226                 {
1227                         SetWinners(team, assault_attacker_team);
1228                         if(assault_attacker_team == COLOR_TEAM1)
1229                         {
1230                                 team1_score = team1_score + 50;
1231                         }
1232                         else
1233                         {
1234                                 team2_score = team2_score + 50;
1235                         }
1236
1237                         if(ent.cnt == 1) // this was the second round
1238                         {
1239                                 status = WINNING_YES;
1240                         }
1241                         else
1242                         {
1243                                 local entity oldself;
1244                                 oldself = self;
1245                                 self = ent;
1246                                 cvar_set("timelimit", ftos((2*time)/60));
1247                                 assault_new_round();
1248                                 self = oldself;
1249                         }
1250                 }
1251         }
1252
1253         return status;
1254
1255 }
1256
1257 // LMS winning condition: game terminates if and only if there's at most one
1258 // one player who's living lives. Top two scores being equal cancels the time
1259 // limit.
1260 float WinningCondition_LMS()
1261 {
1262         entity head, head2;
1263         float have_player;
1264         float have_players;
1265         float l;
1266
1267         have_player = FALSE;
1268         have_players = FALSE;
1269         l = LMS_NewPlayerLives();
1270
1271         head = find(world, classname, "player");
1272         if(head)
1273                 have_player = TRUE;
1274         head2 = find(head, classname, "player");
1275         if(head2)
1276                 have_players = TRUE;
1277
1278         if(have_player)
1279         {
1280                 // we have at least one player
1281                 if(have_players)
1282                 {
1283                         // two or more active players - continue with the game
1284                 }
1285                 else
1286                 {
1287                         // exactly one player?
1288
1289                         ClearWinners();
1290                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1291
1292                         if(l)
1293                         {
1294                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1295                                 return WINNING_NO;
1296                         }
1297                         else
1298                         {
1299                                 // a winner!
1300                                 // and assign him his first place
1301                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1302                                 return WINNING_YES;
1303                         }
1304                 }
1305         }
1306         else
1307         {
1308                 // nobody is playing at all...
1309                 if(l)
1310                 {
1311                         // wait for players...
1312                 }
1313                 else
1314                 {
1315                         // SNAFU (maybe a draw game?)
1316                         ClearWinners();
1317                         dprint("No players, ending game.\n");
1318                         return WINNING_YES;
1319                 }
1320         }
1321
1322         // When we get here, we have at least two players who are actually LIVING,
1323         // now check if the top two players have equal score.
1324         WinningConditionHelper();
1325
1326         ClearWinners();
1327         if(WinningConditionHelper_winner)
1328                 WinningConditionHelper_winner.winning = TRUE;
1329         if(WinningConditionHelper_equality)
1330                 return WINNING_NEVER;
1331
1332         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1333         return WINNING_NO;
1334 }
1335
1336 void print_to(entity e, string s)
1337 {
1338         if(e)
1339                 sprint(e, strcat(s, "\n"));
1340         else
1341                 print(s, "\n");
1342 }
1343
1344 void ShuffleMaplist()
1345 {
1346         string result;
1347         float start;
1348         float litems;
1349         float selected;
1350         float i;
1351
1352         result = cvar_string("g_maplist");
1353         litems = tokenizebyseparator(result, " ");
1354
1355         for(start = 0; start < litems - 1; ++start)
1356         {
1357                 result = "";
1358
1359                 // select a random item
1360                 selected = ceil(random() * (litems - start) + start) - 1;
1361
1362                 // shift this item to the place start
1363                 for(i = 0; i < start; ++i)
1364                         result = strcat(result, " ", argv(i));
1365                 result = strcat(result, " ", argv(selected));
1366                 for(i = start; i < litems; ++i)
1367                         if(i != selected)
1368                                 result = strcat(result, " ", argv(i));
1369                 result = substring(result, 1, strlen(result) - 1);
1370
1371                 litems = tokenizebyseparator(result, " ");
1372
1373                 //dprint(result, "\n");
1374         }
1375
1376         cvar_set("g_maplist", result);
1377 }
1378
1379 float WinningCondition_Scores(float limit)
1380 {
1381         // TODO make everything use THIS winning condition (except LMS)
1382         WinningConditionHelper();
1383         
1384         if(teams_matter)
1385         {
1386                 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1387                 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1388                 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1389                 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1390         }
1391         
1392         ClearWinners();
1393         if(WinningConditionHelper_winner)
1394                 WinningConditionHelper_winner.winning = 1;
1395         if(WinningConditionHelper_winnerteam >= 0)
1396                 SetWinners(team, WinningConditionHelper_winnerteam);
1397
1398         if(WinningConditionHelper_lowerisbetter)
1399         {
1400                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1401                 limit = -limit;
1402         }
1403
1404         return GetWinningCode(limit && WinningConditionHelper_topscore && (WinningConditionHelper_topscore >= limit), WinningConditionHelper_equality);
1405 }
1406
1407 float WinningCondition_Race(float fraglimit)
1408 {
1409         float wc;
1410         entity p;
1411         wc = WinningCondition_Scores(fraglimit);
1412
1413         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1414         if(wc == WINNING_YES || wc == WINNING_STARTOVERTIME)
1415         // do NOT support equality when the laps are all raced!
1416         {
1417                 FOR_EACH_PLAYER(p)
1418                         if not(p.race_completed)
1419                                 return WINNING_STARTOVERTIME;
1420                 return WINNING_YES;
1421         }
1422         return wc;
1423 }
1424
1425 void ReadyRestart();
1426 float WinningCondition_QualifyingThenRace(float limit)
1427 {
1428         float wc;
1429         wc = WinningCondition_Scores(limit);
1430
1431         // NEVER initiate overtime
1432         if(wc == WINNING_YES || wc == WINNING_STARTOVERTIME)
1433         // do NOT support equality when the laps are all raced!
1434         {
1435                 float totalplayers;
1436                 float playerswithlaps;
1437                 float readyplayers;
1438                 entity head;
1439                 totalplayers = playerswithlaps = readyplayers = 0;
1440                 FOR_EACH_PLAYER(head)
1441                 {
1442                         ++totalplayers;
1443                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
1444                                 ++playerswithlaps;
1445                         if(head.ready)
1446                                 ++readyplayers;
1447                 }
1448
1449                 // at least 2/3 of the players have completed a lap: start the RACE
1450                 // otherwise, the players should end the qualifying on their own
1451                 if(readyplayers || ((totalplayers >= 3) && (playerswithlaps * 3 >= totalplayers * 2)))
1452                 {
1453                         checkrules_overtimeend = 0;
1454                         ReadyRestart();
1455                         return WINNING_NEVER;
1456                 }
1457
1458                 return WINNING_YES;
1459         }
1460
1461         return wc;
1462 }
1463
1464 float WinningCondition_RanOutOfSpawns()
1465 {
1466         entity head;
1467
1468         if(!have_team_spawns)
1469                 return WINNING_NO;
1470
1471         if(!some_spawn_has_been_used)
1472                 return WINNING_NO;
1473
1474         team1_score = team2_score = team3_score = team4_score = 0;
1475
1476         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1477         {
1478                 if(head.team == COLOR_TEAM1)
1479                         team1_score = 1;
1480                 else if(head.team == COLOR_TEAM2)
1481                         team2_score = 1;
1482                 else if(head.team == COLOR_TEAM3)
1483                         team3_score = 1;
1484                 else if(head.team == COLOR_TEAM4)
1485                         team4_score = 1;
1486         }
1487
1488         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1489         {
1490                 if(head.team == COLOR_TEAM1)
1491                         team1_score = 1;
1492                 else if(head.team == COLOR_TEAM2)
1493                         team2_score = 1;
1494                 else if(head.team == COLOR_TEAM3)
1495                         team3_score = 1;
1496                 else if(head.team == COLOR_TEAM4)
1497                         team4_score = 1;
1498         }
1499
1500         ClearWinners();
1501         if(team1_score + team2_score + team3_score + team4_score == 0)
1502         {
1503                 checkrules_equality = TRUE;
1504                 return WINNING_YES;
1505         }
1506         else if(team1_score + team2_score + team3_score + team4_score == 1)
1507         {
1508                 float t, i;
1509                 if(team1_score) t = COLOR_TEAM1;
1510                 if(team2_score) t = COLOR_TEAM2;
1511                 if(team3_score) t = COLOR_TEAM3;
1512                 if(team4_score) t = COLOR_TEAM4;
1513                 CheckAllowedTeams(world);
1514                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1515                 {
1516                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1517                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1518                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1519                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1520                 }
1521
1522                 AddWinners(team, t);
1523                 return WINNING_YES;
1524         }
1525         else
1526                 return WINNING_NO;
1527 }
1528
1529 /*
1530 ============
1531 CheckRules_World
1532
1533 Exit deathmatch games upon conditions
1534 ============
1535 */
1536 void CheckRules_World()
1537 {
1538         local float status;
1539         local float timelimit;
1540         local float fraglimit;
1541
1542         VoteThink();
1543         MapVote_Think();
1544
1545         SetDefaultAlpha();
1546
1547         /*
1548         MapVote_Think should now do that part
1549         if (intermission_running)
1550                 if (time >= intermission_exittime + 60)
1551                 {
1552                         if(!DoNextMapOverride())
1553                                 GotoNextMap();
1554                         return;
1555                 }
1556         */
1557
1558         if (gameover)   // someone else quit the game already
1559         {
1560                 if(player_count == 0) // Nobody there? Then let's go to the next map
1561                         MapVote_Start();
1562                         // this will actually check the player count in the next frame
1563                         // again, but this shouldn't hurt
1564                 return;
1565         }
1566
1567         timelimit = cvar("timelimit") * 60;
1568         fraglimit = cvar("fraglimit");
1569
1570         if(inWarmupStage)
1571                 fraglimit = 0; // no fraglimit for now
1572
1573         if(checkrules_overtimeend)
1574         {
1575                 if(!checkrules_overtimewarning)
1576                 {
1577                         checkrules_overtimewarning = TRUE;
1578                         //announceall("announcer/robotic/1minuteremains.wav");
1579                         if(!g_race_qualifying)
1580                                 bcenterprint("^3Everyone, finish your lap! The race is over!");
1581                         else
1582                                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1583                 }
1584         }
1585         else
1586         {
1587                 if (timelimit && time >= timelimit)
1588                         InitiateOvertime();
1589         }
1590
1591         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1592         {
1593                 NextLevel();
1594                 return;
1595         }
1596
1597         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1598         {
1599                 checkrules_oneminutewarning = TRUE;
1600                 play2all("announcer/robotic/1minuteremains.wav");
1601         }
1602
1603         status = WinningCondition_RanOutOfSpawns();
1604         if(status == WINNING_YES)
1605         {
1606                 bprint("Hey! Someone ran out of spawns!\n");
1607         }
1608         else if(g_race && !g_race_qualifying && timelimit >= 0)
1609         {
1610                 status = WinningCondition_Race(fraglimit);
1611         }
1612         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
1613         {
1614                 status = WinningCondition_QualifyingThenRace(fraglimit);
1615         }
1616         else if(g_assault)
1617         {
1618                 status = WinningCondition_Assault(); // TODO remove this?
1619         }
1620         else if(g_lms)
1621         {
1622                 status = WinningCondition_LMS();
1623         }
1624         else if (g_onslaught)
1625         {
1626                 status = WinningCondition_Onslaught(); // TODO remove this?
1627         }
1628         else
1629         {
1630                 status = WinningCondition_Scores(fraglimit);
1631         }
1632
1633         if(status == WINNING_STARTOVERTIME)
1634         {
1635                 status = WINNING_NEVER;
1636                 InitiateOvertime();
1637         }
1638
1639         if(status == WINNING_NEVER)
1640                 // equality cases! Nobody wins if the overtime ends in a draw.
1641                 ClearWinners();
1642
1643         if(checkrules_overtimeend)
1644                 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1645                         status = WINNING_YES;
1646
1647         if(status == WINNING_YES)
1648                 NextLevel();
1649 };
1650
1651 float mapvote_nextthink;
1652 float mapvote_initialized;
1653 float mapvote_keeptwotime;
1654 float mapvote_timeout;
1655 string mapvote_message;
1656 string mapvote_screenshot_dir;
1657
1658 float mapvote_count;
1659 float mapvote_count_real;
1660 string mapvote_maps[MAPVOTE_COUNT];
1661 float mapvote_maps_suggested[MAPVOTE_COUNT];
1662 string mapvote_suggestions[MAPVOTE_COUNT];
1663 float mapvote_suggestion_ptr;
1664 float mapvote_maxlen;
1665 float mapvote_voters;
1666 float mapvote_votes[MAPVOTE_COUNT];
1667 float mapvote_run;
1668 float mapvote_detail;
1669 float mapvote_abstain;
1670 float mapvote_dirty;
1671 .float mapvote;
1672
1673 void MapVote_ClearAllVotes()
1674 {
1675         FOR_EACH_CLIENT(other)
1676                 other.mapvote = 0;
1677 }
1678
1679 string MapVote_Suggest(string m)
1680 {
1681         float i;
1682         if(m == "")
1683                 return "That's not how to use this command.";
1684         if(!cvar("g_maplist_votable_suggestions"))
1685                 return "Suggestions are not accepted on this server.";
1686         if(mapvote_initialized)
1687                 return "Can't suggest - voting is already in progress!";
1688         m = MapInfo_FixName(m);
1689         if(!m)
1690                 return "The map you suggested is not available on this server.";
1691         if(!cvar("g_maplist_votable_override_mostrecent"))
1692                 if(Map_IsRecent(m))
1693                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1694
1695         if(!MapInfo_CheckMap(m))
1696                 return "The map you suggested does not support the current game mode.";
1697         for(i = 0; i < mapvote_suggestion_ptr; ++i)
1698                 if(mapvote_suggestions[i] == m)
1699                         return "This map was already suggested.";
1700         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1701         {
1702                 i = ceil(random() * mapvote_suggestion_ptr) - 1;
1703         }
1704         else
1705         {
1706                 i = mapvote_suggestion_ptr;
1707                 mapvote_suggestion_ptr += 1;
1708         }
1709         if(mapvote_suggestions[i] != "")
1710                 strunzone(mapvote_suggestions[i]);
1711         mapvote_suggestions[i] = strzone(m);
1712         if(cvar("sv_eventlog"))
1713                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
1714         return strcat("Suggestion of ", m, " accepted.");
1715 }
1716
1717 void MapVote_AddVotable(string nextMap, float isSuggestion)
1718 {
1719         float j;
1720         if(nextMap == "")
1721                 return;
1722         for(j = 0; j < mapvote_count; ++j)
1723                 if(mapvote_maps[j] == nextMap)
1724                         return;
1725         if(strlen(nextMap) > mapvote_maxlen)
1726                 mapvote_maxlen = strlen(nextMap);
1727         mapvote_maps[mapvote_count] = strzone(nextMap);
1728         mapvote_maps_suggested[mapvote_count] = isSuggestion;
1729         mapvote_count += 1;
1730 }
1731
1732 void MapVote_SendData(float target);
1733 void MapVote_Init()
1734 {
1735         float i;
1736         float nmax, smax;
1737
1738         MapVote_ClearAllVotes();
1739
1740         mapvote_count = 0;
1741         mapvote_detail = !cvar("g_maplist_votable_nodetail");
1742         mapvote_abstain = cvar("g_maplist_votable_abstain");
1743
1744         if(mapvote_abstain)
1745                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
1746         else
1747                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
1748         smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
1749
1750         if(mapvote_suggestion_ptr)
1751                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
1752                         MapVote_AddVotable(mapvote_suggestions[ceil(random() * mapvote_suggestion_ptr) - 1], TRUE);
1753
1754         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1755                 MapVote_AddVotable(GetNextMap(), FALSE);
1756
1757         if(mapvote_count == 0)
1758         {
1759                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1760                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
1761                 localcmd("\nmenu_cmd sync\n");
1762                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1763                         MapVote_AddVotable(GetNextMap(), FALSE);
1764         }
1765
1766         mapvote_count_real = mapvote_count;
1767         if(mapvote_abstain)
1768                 MapVote_AddVotable("don't care", 0);
1769
1770         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
1771
1772         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
1773         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
1774         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
1775                 mapvote_keeptwotime = 0;
1776         mapvote_message = "Choose a map and press its key!";
1777
1778         mapvote_screenshot_dir = cvar_string("g_maplist_votable_screenshot_dir");
1779         if(mapvote_screenshot_dir == "")
1780                 mapvote_screenshot_dir = "maps";
1781         mapvote_screenshot_dir = strzone(mapvote_screenshot_dir);
1782
1783         if(!cvar("g_maplist_textonly"))
1784                 MapVote_SendData(MSG_ALL);
1785 }
1786
1787 void MapVote_SendPicture(float id)
1788 {
1789         msg_entity = self;
1790         WriteByte(MSG_ONE, SVC_TEMPENTITY);
1791         WriteByte(MSG_ONE, TE_CSQC_MAPVOTE);
1792         WriteByte(MSG_ONE, MAPVOTE_NET_PIC);
1793         WriteByte(MSG_ONE, id);
1794         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dir, "/", mapvote_maps[id]), 3072);
1795 }
1796
1797 float GameCommand_MapVote(string cmd)
1798 {
1799         if(!intermission_running)
1800                 return FALSE;
1801         if(!cvar("g_maplist_textonly"))
1802         {
1803                 if(cmd == "mv_getpic")
1804                 {
1805                         MapVote_SendPicture(stof(argv(1)));
1806                         return TRUE;
1807                 }
1808         }
1809
1810         return FALSE;
1811 }
1812
1813 float MapVote_GetMapMask()
1814 {
1815         float mask, i, power;
1816         mask = 0;
1817         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
1818                 if(mapvote_maps[i] != "")
1819                         mask |= power;
1820         return mask;
1821 }
1822
1823 void MapVote_SendData(float targ)
1824 {
1825         string mapfile, pakfile;
1826         float i, o;
1827         WriteByte(targ, SVC_TEMPENTITY);
1828         WriteByte(targ, TE_CSQC_CONFIG);
1829         WriteString(targ, "mv_screenshot_dir");
1830         WriteString(targ, mapvote_screenshot_dir);
1831
1832         WriteByte(targ, SVC_TEMPENTITY);
1833         WriteByte(targ, TE_CSQC_MAPVOTE);
1834         WriteByte(targ, MAPVOTE_NET_INIT);
1835
1836         WriteByte(targ, mapvote_count);
1837         WriteByte(targ, mapvote_abstain);
1838         WriteByte(targ, mapvote_detail);
1839         WriteCoord(targ, mapvote_timeout);
1840         if(mapvote_count <= 8)
1841                 WriteByte(targ, MapVote_GetMapMask());
1842         else
1843                 WriteShort(targ, MapVote_GetMapMask());
1844         for(i = 0; i < mapvote_count; ++i)
1845                 if(mapvote_maps[i] != "")
1846                 {
1847                         WriteString(targ, mapvote_maps[i]);
1848                         mapfile = strcat(mapvote_screenshot_dir, "/", mapvote_maps[i]);
1849                         pakfile = whichpack(strcat(mapfile, ".tga"));
1850                         if(pakfile == "")
1851                                 pakfile = whichpack(strcat(mapfile, ".jpg"));
1852                         if(pakfile == "")
1853                                 pakfile = whichpack(strcat(mapfile, ".png"));
1854                         print("pakfile is ", pakfile, "\n");
1855                         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
1856                                 pakfile = substring(pakfile, o, 999);
1857                         WriteString(targ, pakfile);
1858                 }
1859 }
1860
1861 void MapVote_UpdateData(float targ)
1862 {
1863         float i;
1864         WriteByte(targ, SVC_TEMPENTITY);
1865         WriteByte(targ, TE_CSQC_MAPVOTE);
1866         WriteByte(targ, MAPVOTE_NET_UPDATE);
1867         if(mapvote_count <= 8)
1868                 WriteByte(targ, MapVote_GetMapMask());
1869         else
1870                 WriteShort(targ, MapVote_GetMapMask());
1871         if(mapvote_detail)
1872                 for(i = 0; i < mapvote_count; ++i)
1873                         if(mapvote_maps[i] != "")
1874                                 WriteByte(targ, mapvote_votes[i]);
1875 }
1876
1877 void MapVote_TellVote(float targ, float vote)
1878 {
1879         WriteByte(targ, SVC_TEMPENTITY);
1880         WriteByte(targ, TE_CSQC_MAPVOTE);
1881         WriteByte(targ, MAPVOTE_NET_OWNVOTE);
1882         WriteByte(targ, vote);
1883 }
1884
1885 float MapVote_Finished(float mappos)
1886 {
1887         string result;
1888         float i;
1889         float didntvote;
1890
1891         if(cvar("sv_eventlog"))
1892         {
1893                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
1894                 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
1895                 didntvote = mapvote_voters;
1896                 for(i = 0; i < mapvote_count; ++i)
1897                         if(mapvote_maps[i] != "")
1898                         {
1899                                 didntvote -= mapvote_votes[i];
1900                                 if(i != mappos)
1901                                 {
1902                                         result = strcat(result, ":", mapvote_maps[i]);
1903                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
1904                                 }
1905                         }
1906                 result = strcat(result, ":didn't vote:", ftos(didntvote));
1907
1908                 GameLogEcho(result);
1909                 if(mapvote_maps_suggested[mappos])
1910                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
1911         }
1912
1913         FOR_EACH_REALCLIENT(other)
1914                 FixClientCvars(other);
1915
1916         Map_Goto_SetStr(mapvote_maps[mappos]);
1917         Map_Goto();
1918         alreadychangedlevel = TRUE;
1919         return TRUE;
1920 }
1921 void MapVote_CheckRules_1()
1922 {
1923         float i;
1924
1925         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1926         {
1927                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
1928                 mapvote_votes[i] = 0;
1929         }
1930
1931         mapvote_voters = 0;
1932         FOR_EACH_REALCLIENT(other)
1933         {
1934                 ++mapvote_voters;
1935                 if(other.mapvote)
1936                 {
1937                         i = other.mapvote - 1;
1938                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
1939                         mapvote_votes[i] = mapvote_votes[i] + 1;
1940                 }
1941         }
1942 }
1943
1944 float MapVote_CheckRules_2()
1945 {
1946         float i;
1947         float firstPlace, secondPlace;
1948         float firstPlaceVotes, secondPlaceVotes;
1949         float mapvote_voters_real;
1950         string result;
1951
1952         mapvote_voters_real = mapvote_voters;
1953         if(mapvote_abstain)
1954                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
1955
1956         RandomSelection_Init();
1957         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
1958                 RandomSelection_Add(world, i, 1, mapvote_votes[i]);
1959         firstPlace = RandomSelection_chosen_float;
1960         firstPlaceVotes = RandomSelection_best_priority;
1961         //dprint("First place: ", ftos(firstPlace), "\n");
1962         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
1963
1964         RandomSelection_Init();
1965         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
1966                 if(i != firstPlace)
1967                         RandomSelection_Add(world, i, 1, mapvote_votes[i]);
1968         secondPlace = RandomSelection_chosen_float;
1969         secondPlaceVotes = RandomSelection_best_priority;
1970         //dprint("Second place: ", ftos(secondPlace), "\n");
1971         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
1972
1973         if(firstPlace == -1)
1974                 error("No first place in map vote... WTF?");
1975
1976         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
1977                 return MapVote_Finished(firstPlace);
1978
1979         if(mapvote_keeptwotime)
1980                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
1981                 {
1982                         float didntvote;
1983                         mapvote_dirty = TRUE;
1984                         mapvote_message = "Now decide between the TOP TWO!";
1985                         mapvote_keeptwotime = 0;
1986                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
1987                         result = strcat(result, ":", ftos(firstPlaceVotes));
1988                         result = strcat(result, ":", mapvote_maps[secondPlace]);
1989                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
1990                         didntvote = mapvote_voters;
1991                         for(i = 0; i < mapvote_count; ++i)
1992                                 if(mapvote_maps[i] != "")
1993                                 {
1994                                         didntvote -= mapvote_votes[i];
1995                                         if(i != firstPlace)
1996                                                 if(i != secondPlace)
1997                                                 {
1998                                                         result = strcat(result, ":", mapvote_maps[i]);
1999                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2000                                                         if(i < mapvote_count_real)
2001                                                         {
2002                                                                 strunzone(mapvote_maps[i]);
2003                                                                 mapvote_maps[i] = "";
2004                                                         }
2005                                                 }
2006                                 }
2007                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2008                         if(cvar("sv_eventlog"))
2009                                 GameLogEcho(result);
2010                 }
2011
2012         return FALSE;
2013 }
2014 void MapVote_Tick()
2015 {
2016         string msgstr;
2017         string tmp;
2018         float i;
2019         float keeptwo;
2020         float totalvotes;
2021
2022         keeptwo = mapvote_keeptwotime;
2023         MapVote_CheckRules_1(); // count
2024         if(MapVote_CheckRules_2()) // decide
2025                 return;
2026
2027         totalvotes = 0;
2028         FOR_EACH_REALCLIENT(other)
2029         {
2030                 // hide scoreboard again
2031                 if(other.health != 2342)
2032                 {
2033                         other.health = 2342;
2034                         other.impulse = 0;
2035                         if(clienttype(other) == CLIENTTYPE_REAL)
2036                         {
2037                                 if(cvar("g_maplist_textonly"))
2038                                         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");
2039
2040                                 msg_entity = other;
2041                                 WriteByte(MSG_ONE, SVC_FINALE);
2042                                 WriteString(MSG_ONE, "");
2043                         }
2044                 }
2045
2046                 // notify about keep-two
2047                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2048                         play2(other, "misc/invshot.wav");
2049
2050                 // clear possibly invalid votes
2051                 if(mapvote_maps[other.mapvote - 1] == "")
2052                         other.mapvote = 0;
2053                 // use impulses as new vote
2054                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2055                         if(mapvote_maps[other.impulse - 1] != "")
2056                         {
2057                                 other.mapvote = other.impulse;
2058                                 if(mapvote_detail)
2059                                         mapvote_dirty = TRUE;
2060
2061                                 msg_entity = other;
2062                                 MapVote_TellVote(MSG_ONE, other.mapvote);
2063                         }
2064                 other.impulse = 0;
2065
2066                 if(other.mapvote)
2067                         ++totalvotes;
2068         }
2069
2070         MapVote_CheckRules_1(); // just count
2071
2072         if(!cvar("g_maplist_textonly"))
2073         if(mapvote_dirty) // 1 if "keeptwo" or "impulse" happened before
2074         {
2075                 MapVote_UpdateData(MSG_BROADCAST);
2076                 mapvote_dirty = FALSE;
2077         }
2078
2079         if(cvar("g_maplist_textonly"))
2080         {
2081                 FOR_EACH_REALCLIENT(other)
2082                 {
2083                         // display voting screen
2084                         msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
2085                         msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
2086                         if(mapvote_abstain)
2087                                 msgstr = substring(msgstr, 1, strlen(msgstr) - 1);
2088                         msgstr = strcat(msgstr, mapvote_message);
2089                         msgstr = strcat(msgstr, "\n\n");
2090                         for(i = 0; i < mapvote_count; ++i)
2091                                 if(mapvote_maps[i] == "")
2092                                         msgstr = strcat(msgstr, "\n");
2093                                 else
2094                                 {
2095                                         tmp = mapvote_maps[i];
2096                                         tmp = strpad(mapvote_maxlen, tmp);
2097                                         tmp = strcat(ftos(mod(i + 1, 10)), ": ", tmp);
2098                                         if(mapvote_detail)
2099                                         {
2100                                                 tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
2101                                                 if(mapvote_votes[i] != 1)
2102                                                         tmp = strcat(tmp, "s");
2103                                                 tmp = strcat(tmp, ")");
2104                                                 tmp = strpad(mapvote_maxlen + 15, tmp);
2105                                         }
2106                                         if(mapvote_abstain)
2107                                                 if(i == mapvote_count - 1)
2108                                                         msgstr = strcat(msgstr, "\n");
2109                                         if(other.mapvote == i + 1)
2110                                                 msgstr = strcat(msgstr, "^3> ", tmp, "\n");
2111                                         else
2112                                                 msgstr = strcat(msgstr, "^7  ", tmp, "\n");
2113                                 }
2114
2115                         msgstr = strcat(msgstr, "\n\n^2", ftos(totalvotes), " vote");
2116                         if(totalvotes != 1)
2117                                 msgstr = strcat(msgstr, "s");
2118                         msgstr = strcat(msgstr, " cast");
2119                         i = ceil(mapvote_timeout - time);
2120                         msgstr = strcat(msgstr, "\n", ftos(i), " second");
2121                         if(i != 1)
2122                                 msgstr = strcat(msgstr, "s");
2123                         msgstr = strcat(msgstr, " left");
2124
2125                         centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
2126                 }
2127         }
2128 }
2129 void MapVote_Start()
2130 {
2131         if(mapvote_run)
2132                 return;
2133
2134         MapInfo_Enumerate();
2135         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1))
2136                 mapvote_run = TRUE;
2137 }
2138 void MapVote_Think()
2139 {
2140         if(!mapvote_run)
2141                 return;
2142
2143         if(alreadychangedlevel)
2144                 return;
2145
2146         if(time < mapvote_nextthink)
2147                 return;
2148         //dprint("tick\n");
2149
2150         mapvote_nextthink = time + 0.5;
2151
2152         if(!mapvote_initialized)
2153         {
2154                 mapvote_initialized = TRUE;
2155                 if(DoNextMapOverride())
2156                         return;
2157                 if(!cvar("g_maplist_votable") || player_count <= 0)
2158                 {
2159                         GotoNextMap();
2160                         return;
2161                 }
2162                 MapVote_Init();
2163         }
2164
2165         MapVote_Tick();
2166 };
2167
2168 string GotoMap(string m)
2169 {
2170         if(!MapInfo_CheckMap(m))
2171                 return "The map you chose is not available on this server.";
2172         cvar_set("nextmap", m);
2173         cvar_set("timelimit", "-1");
2174         if(mapvote_initialized || alreadychangedlevel)
2175         {
2176                 if(DoNextMapOverride())
2177                         return "Map switch initiated.";
2178                 else
2179                         return "Hm... no. For some reason I like THIS map more.";
2180         }
2181         else
2182                 return "Map switch will happen after scoreboard.";
2183 }
2184
2185
2186 void EndFrame()
2187 {
2188         FOR_EACH_REALCLIENT(self)
2189         {
2190                 if(self.classname == "spectator")
2191                 {
2192                         if(self.enemy.hitsound)
2193                                 play2(self, "misc/hit.wav");
2194                 }
2195                 else
2196                 {
2197                         if(self.hitsound)
2198                                 play2(self, "misc/hit.wav");
2199                 }
2200         }
2201         FOR_EACH_CLIENT(self)
2202                 self.hitsound = FALSE;
2203 }
2204
2205
2206 /*
2207  * RedirectionThink:
2208  * returns TRUE if redirecting
2209  */
2210 float redirection_timeout;
2211 float redirection_nextthink;
2212 float RedirectionThink()
2213 {
2214         float clients_found;
2215
2216         if(redirection_target == "")
2217                 return FALSE;
2218
2219         if(!redirection_timeout)
2220         {
2221                 cvar_set("sv_public", "-2");
2222                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2223                 if(redirection_target == "self")
2224                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2225                 else
2226                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2227         }
2228
2229         if(time < redirection_nextthink)
2230                 return TRUE;
2231
2232         redirection_nextthink = time + 1;
2233
2234         clients_found = 0;
2235         FOR_EACH_REALCLIENT(self)
2236         {
2237                 print("Redirecting: sending connect command to ", self.netname, "\n");
2238                 if(redirection_target == "self")
2239                         stuffcmd(self, "\ndisconnect; reconnect\n");
2240                 else
2241                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2242                 ++clients_found;
2243         }
2244
2245         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2246
2247         if(time > redirection_timeout || clients_found == 0)
2248                 localcmd("\nwait; wait; wait; quit\n");
2249
2250         return TRUE;
2251 }
2252
2253 void RestoreGame()
2254 {
2255         // Loaded from a save game
2256         // some things then break, so let's work around them...
2257
2258         // Progs DB (capture records)
2259         if(sv_cheats)
2260                 ServerProgsDB = db_create();
2261         else
2262                 ServerProgsDB = db_load("server.db");
2263
2264         // Mapinfo
2265         MapInfo_Shutdown();
2266         MapInfo_Enumerate();
2267         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1);
2268 }
2269
2270 void SV_Shutdown()
2271 {
2272         if(world_initialized)
2273         {
2274                 world_initialized = 0;
2275                 print("Saving persistent data...\n");
2276                 Ban_SaveBans();
2277                 if(!sv_cheats)
2278                         db_save(ServerProgsDB, "server.db");
2279                 db_close(ServerProgsDB);
2280                 print("done!\n");
2281                 // tell the bot system the game is ending now
2282                 bot_endgame();
2283
2284                 MapInfo_Shutdown();
2285         }
2286         else
2287         {
2288                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2289         }
2290 }