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