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