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