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