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