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