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