]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Merge remote branch 'origin/terencehill/powerups_respawntime_fix'
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 entity pingplreport;
2 void PingPLReport_Think()
3 {
4         float delta;
5         entity e;
6
7         delta = 3 / maxclients;
8         if(delta < sys_frametime)
9                 delta = 0;
10         self.nextthink = time + delta;
11
12         e = edict_num(self.cnt + 1);
13         if(clienttype(e) == CLIENTTYPE_REAL)
14         {
15                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
16                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
17                 WriteByte(MSG_BROADCAST, self.cnt);
18                 WriteShort(MSG_BROADCAST, max(1, e.ping));
19                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
20                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
21         }
22         else
23         {
24                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
25                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
26                 WriteByte(MSG_BROADCAST, self.cnt);
27                 WriteShort(MSG_BROADCAST, 0);
28                 WriteByte(MSG_BROADCAST, 0);
29                 WriteByte(MSG_BROADCAST, 0);
30         }
31         self.cnt = mod(self.cnt + 1, maxclients);
32 }
33 void PingPLReport_Spawn()
34 {
35         pingplreport = spawn();
36         pingplreport.classname = "pingplreport";
37         pingplreport.think = PingPLReport_Think;
38         pingplreport.nextthink = time;
39 }
40
41 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
42 string redirection_target;
43 float world_initialized;
44
45 string GetMapname();
46 string GetGametype();
47 void GotoNextMap(float reinit);
48 void ShuffleMaplist()
49 float(float reinit) DoNextMapOverride;
50
51 void SetDefaultAlpha()
52 {
53         if(autocvar_g_running_guns)
54         {
55                 default_player_alpha = -1;
56                 default_weapon_alpha = +1;
57         }
58         else if(g_cloaked)
59         {
60                 default_player_alpha = autocvar_g_balance_cloaked_alpha;
61                 default_weapon_alpha = default_player_alpha;
62         }
63         else
64         {
65                 default_player_alpha = autocvar_g_player_alpha;
66                 if(default_player_alpha == 0)
67                         default_player_alpha = 1;
68                 default_weapon_alpha = default_player_alpha;
69         }
70 }
71
72 void fteqcc_testbugs()
73 {
74         float a, b;
75
76         if(!autocvar_developer_fteqccbugs)
77                 return;
78
79         dprint("*** fteqcc test: checking for bugs...\n");
80
81         a = 1;
82         b = 5;
83         if(sqrt(a) - sqrt(b - a) == 0)
84                 dprint("*** fteqcc test: found same-function-twice bug\n");
85         else
86                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
87
88         world.cnt = -10;
89         world.enemy = world;
90         world.enemy.cnt += 10;
91         if(world.cnt > 0.2 || world.cnt < -0.2) // don't error out if it's just roundoff errors
92                 dprint("*** fteqcc test: found += bug\n");
93         else
94                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
95         world.cnt = 0;
96 }
97
98 void GotoFirstMap()
99 {
100         float n;
101         if(autocvar__sv_init)
102         {
103                 // cvar_set("_sv_init", "0");
104                 // we do NOT set this to 0 any more, so someone "accidentally" changing
105                 // to this "init" map on a dedicated server will cause no permanent
106                 // harm
107                 if(autocvar_g_maplist_shuffle)
108                         ShuffleMaplist();
109                 n = tokenizebyseparator(autocvar_g_maplist, " ");
110                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
111
112                 MapInfo_Enumerate();
113                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
114
115                 if(!DoNextMapOverride(1))
116                         GotoNextMap(1);
117
118                 return;
119         }
120
121         if(time < 5)
122         {
123                 self.nextthink = time;
124         }
125         else
126         {
127                 self.nextthink = time + 1;
128                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
129         }
130 }
131
132 void cvar_changes_init()
133 {
134         float h;
135         string k, v, d;
136         float n, i, adding, pureadding;
137
138         if(cvar_changes)
139                 strunzone(cvar_changes);
140         cvar_changes = string_null;
141         if(cvar_purechanges)
142                 strunzone(cvar_purechanges);
143         cvar_purechanges = string_null;
144         cvar_purechanges_count = 0;
145
146         h = buf_create();
147         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
148         n = buf_getsize(h);
149
150         adding = TRUE;
151         pureadding = TRUE;
152
153         for(i = 0; i < n; ++i)
154         {
155                 k = bufstr_get(h, i);
156
157 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
158 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
159 #define BADCVAR(p) if(k == p) continue
160
161                 // general excludes and namespaces for server admin used cvars
162                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
163
164                 // internal
165                 BADPREFIX("csqc_");
166                 BADPREFIX("cvar_check_");
167                 BADCVAR("gamecfg");
168                 BADCVAR("g_configversion");
169                 BADCVAR("g_maplist_index");
170                 BADCVAR("halflifebsp");
171                 BADPREFIX("sv_world");
172
173                 // client
174                 BADPREFIX("chase_");
175                 BADPREFIX("cl_");
176                 BADPREFIX("con_");
177                 BADPREFIX("scoreboard_");
178                 BADPREFIX("g_campaign");
179                 BADPREFIX("g_waypointsprite_");
180                 BADPREFIX("gl_");
181                 BADPREFIX("joy");
182                 BADPREFIX("hud_");
183                 BADPREFIX("m_");
184                 BADPREFIX("menu_");
185                 BADPREFIX("net_slist_");
186                 BADPREFIX("r_");
187                 BADPREFIX("sbar_");
188                 BADPREFIX("scr_");
189                 BADPREFIX("snd_");
190                 BADPREFIX("show");
191                 BADPREFIX("sensitivity");
192                 BADPREFIX("userbind");
193                 BADPREFIX("v_");
194                 BADPREFIX("vid_");
195                 BADPREFIX("crosshair");
196                 BADCVAR("mod_q3bsp_lightmapmergepower");
197                 BADCVAR("mod_q3bsp_nolightmaps");
198                 BADCVAR("fov");
199                 BADCVAR("mastervolume");
200                 BADCVAR("volume");
201                 BADCVAR("bgmvolume");
202
203                 // private
204                 BADCVAR("developer");
205                 BADCVAR("log_dest_udp");
206                 BADCVAR("log_file");
207                 BADCVAR("net_address");
208                 BADCVAR("net_address_ipv6");
209                 BADCVAR("port");
210                 BADCVAR("savedgamecfg");
211                 BADCVAR("serverconfig");
212                 BADCVAR("sv_autoscreenshot");
213                 BADCVAR("sv_heartbeatperiod");
214                 BADCVAR("sv_vote_master_password");
215                 BADCVAR("sys_colortranslation");
216                 BADCVAR("sys_specialcharactertranslation");
217                 BADCVAR("timeformat");
218                 BADCVAR("timestamps");
219                 BADPREFIX("developer_");
220                 BADPREFIX("g_ban_");
221                 BADPREFIX("g_banned_list");
222                 BADPREFIX("g_chat_flood_");
223                 BADPREFIX("g_ghost_items");
224                 BADPREFIX("g_playerstats_");
225                 BADPREFIX("g_respawn_ghosts");
226                 BADPREFIX("g_voice_flood_");
227                 BADPREFIX("rcon_");
228                 BADPREFIX("sv_allowdownloads");
229                 BADPREFIX("sv_autodemo");
230                 BADPREFIX("sv_curl_");
231                 BADPREFIX("sv_eventlog");
232                 BADPREFIX("sv_logscores_");
233                 BADPREFIX("sv_master");
234                 BADPREFIX("sv_weaponstats_");
235                 BADPREFIX("sv_waypointsprite_");
236                 BADCVAR("rescan_pending");
237
238                 // these can contain player IDs, so better hide
239                 BADPREFIX("g_forced_team_");
240
241                 // mapinfo
242                 BADCVAR("fraglimit");
243                 BADCVAR("g_arena");
244                 BADCVAR("g_assault");
245                 BADCVAR("g_ca");
246                 BADCVAR("g_ctf");
247                 BADCVAR("g_cts");
248                 BADCVAR("g_dm");
249                 BADCVAR("g_domination");
250                 BADCVAR("g_domination_default_teams");
251                 BADCVAR("g_freezetag");
252                 BADCVAR("g_keepaway");
253                 BADCVAR("g_keyhunt");
254                 BADCVAR("g_keyhunt_teams");
255                 BADCVAR("g_keyhunt_teams");
256                 BADCVAR("g_lms");
257                 BADCVAR("g_nexball");
258                 BADCVAR("g_onslaught");
259                 BADCVAR("g_race");
260                 BADCVAR("g_race_qualifying_timelimit");
261                 BADCVAR("g_runematch");
262                 BADCVAR("g_tdm");
263                 BADCVAR("g_tdm_teams");
264                 BADCVAR("leadlimit");
265                 BADCVAR("nextmap");
266                 BADCVAR("teamplay");
267                 BADCVAR("timelimit");
268
269                 // long
270                 BADCVAR("hostname");
271                 BADCVAR("g_maplist");
272                 BADCVAR("g_maplist_mostrecent");
273                 BADCVAR("sv_motd");
274
275                 v = cvar_string(k);
276                 d = cvar_defstring(k);
277                 if(v == d)
278                         continue;
279
280                 if(adding)
281                 {
282                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
283                         if(strlen(cvar_changes) > 16384)
284                         {
285                                 cvar_changes = "// too many settings have been changed to show them here\n";
286                                 adding = 0;
287                         }
288                 }
289
290                 // now check if the changes are actually gameplay relevant
291
292                 // does nothing visible
293                 BADCVAR("captureleadlimit_override");
294                 BADCVAR("g_arena_point_leadlimit");
295                 BADCVAR("g_balance_kill_delay");
296                 BADCVAR("g_ca_point_leadlimit");
297                 BADCVAR("g_ctf_captimerecord_always");
298                 BADCVAR("g_ctf_flag_capture_effects");
299                 BADCVAR("g_ctf_flag_glowtrails");
300                 BADCVAR("g_ctf_flag_pickup_effects");
301                 BADCVAR("g_domination_point_leadlimit");
302                 BADCVAR("g_forced_respawn");
303                 BADCVAR("g_keyhunt_point_leadlimit");
304                 BADPREFIX("g_mod_");
305                 BADCVAR("g_nexball_goalleadlimit");
306                 BADCVAR("g_runematch_point_leadlimit");
307                 BADCVAR("leadlimit_and_fraglimit");
308                 BADCVAR("leadlimit_override");
309                 BADCVAR("pausable");
310                 BADCVAR("sv_allow_fullbright");
311                 BADCVAR("sv_checkforpacketsduringsleep");
312                 BADCVAR("sv_fraginfo");
313                 BADCVAR("sv_timeout");
314                 BADPREFIX("sv_timeout_");
315                 BADCVAR("welcome_message_time");
316                 BADPREFIX("crypto_");
317                 BADPREFIX("g_chat_");
318                 BADPREFIX("g_ctf_captimerecord_");
319                 BADPREFIX("g_maplist_votable_");
320                 BADPREFIX("net_");
321                 BADPREFIX("prvm_");
322                 BADPREFIX("skill_");
323                 BADPREFIX("sv_cullentities_");
324                 BADPREFIX("sv_fraginfo_");
325                 BADPREFIX("sv_maxidle_");
326                 BADPREFIX("sv_vote_");
327                 BADPREFIX("timelimit_");
328                 BADCVAR("gameversion");
329                 BADPREFIX("gameversion_");
330                 BADCVAR("sv_namechangetimer");
331 #ifndef NO_LEGACY_NETWORKING
332                 BADCVAR("sv_use_csqc_players"); // transition
333 #endif
334
335                 // allowed changes to server admins (please sync this to server.cfg)
336                 // vi commands:
337                 //   :/"impure"/,$d
338                 //   :g!,^\/\/[^ /],d
339                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
340                 //   :%!sort
341                 // yes, this does contain some redundant stuff, don't really care
342                 BADCVAR("bot_config_file");
343                 BADCVAR("bot_number");
344                 BADCVAR("bot_prefix");
345                 BADCVAR("bot_suffix");
346                 BADCVAR("capturelimit_override");
347                 BADCVAR("fraglimit_override");
348                 BADCVAR("gametype");
349                 BADCVAR("g_antilag");
350                 BADCVAR("g_balance_teams");
351                 BADCVAR("g_balance_teams_force");
352                 BADCVAR("g_ban_sync_trusted_servers");
353                 BADCVAR("g_ban_sync_uri");
354                 BADCVAR("g_ctf_ignore_frags");
355                 BADCVAR("g_domination_point_limit");
356                 BADCVAR("g_friendlyfire");
357                 BADCVAR("g_fullbrightitems");
358                 BADCVAR("g_fullbrightplayers");
359                 BADCVAR("g_keyhunt_point_limit");
360                 BADCVAR("g_keyhunt_teams_override");
361                 BADCVAR("g_lms_lives_override");
362                 BADCVAR("g_maplist");
363                 BADCVAR("g_maplist_check_waypoints");
364                 BADCVAR("g_maplist_mostrecent_count");
365                 BADCVAR("g_maplist_shuffle");
366                 BADCVAR("g_maplist_votable");
367                 BADCVAR("g_maplist_votable_abstain");
368                 BADCVAR("g_maplist_votable_nodetail");
369                 BADCVAR("g_maplist_votable_suggestions");
370                 BADCVAR("g_maxplayers");
371                 BADCVAR("g_minstagib");
372                 BADCVAR("g_mirrordamage");
373                 BADCVAR("g_nexball_goallimit");
374                 BADCVAR("g_powerups");
375                 BADCVAR("g_runematch_point_limit");
376                 BADCVAR("g_start_delay");
377                 BADCVAR("g_warmup");
378                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
379                 BADCVAR("hostname");
380                 BADCVAR("log_file");
381                 BADCVAR("maxplayers");
382                 BADCVAR("minplayers");
383                 BADCVAR("net_address");
384                 BADCVAR("port");
385                 BADCVAR("rcon_password");
386                 BADCVAR("rcon_restricted_commands");
387                 BADCVAR("rcon_restricted_password");
388                 BADCVAR("skill");
389                 BADCVAR("sv_adminnick");
390                 BADCVAR("sv_autoscreenshot");
391                 BADCVAR("sv_autotaunt");
392                 BADCVAR("sv_curl_defaulturl");
393                 BADCVAR("sv_defaultcharacter");
394                 BADCVAR("sv_defaultplayercolors");
395                 BADCVAR("sv_defaultplayermodel");
396                 BADCVAR("sv_defaultplayerskin");
397                 BADCVAR("sv_maxidle");
398                 BADCVAR("sv_maxrate");
399                 BADCVAR("sv_motd");
400                 BADCVAR("sv_public");
401                 BADCVAR("sv_ready_restart");
402                 BADCVAR("sv_status_privacy");
403                 BADCVAR("sv_taunt");
404                 BADCVAR("sv_vote_call");
405                 BADCVAR("sv_vote_commands");
406                 BADCVAR("sv_vote_majority_factor");
407                 BADCVAR("sv_vote_master");
408                 BADCVAR("sv_vote_master_commands");
409                 BADCVAR("sv_vote_master_password");
410                 BADCVAR("sv_vote_simple_majority_factor");
411                 BADCVAR("sys_ticrate");
412                 BADCVAR("teamplay_mode");
413                 BADCVAR("timelimit_override");
414                 BADCVAR("g_spawnshieldtime");
415                 BADPREFIX("g_warmup_");
416                 BADPREFIX("sv_ready_restart_");
417
418                 if(autocvar_g_minstagib)
419                 {
420                         BADCVAR("g_grappling_hook");
421                         BADCVAR("g_jetpack");
422                 }
423 #undef BADPREFIX
424 #undef BADCVAR
425
426                 if(pureadding)
427                 {
428                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
429                         if(strlen(cvar_purechanges) > 16384)
430                         {
431                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
432                                 pureadding = 0;
433                         }
434                 }
435                 ++cvar_purechanges_count;
436                 // WARNING: this variable is used for the server list
437                 // NEVER dare to skip this code!
438                 // Hacks to intentionally appearing as "pure server" even though you DO have
439                 // modified settings may be punished by removal from the server list.
440                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
441                 // though.
442         }
443         buf_del(h);
444         if(cvar_changes == "")
445                 cvar_changes = "// this server runs at default server settings\n";
446         else
447                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
448         cvar_changes = strzone(cvar_changes);
449         if(cvar_purechanges == "")
450                 cvar_purechanges = "// this server runs at default gameplay settings\n";
451         else
452                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
453         cvar_purechanges = strzone(cvar_purechanges);
454 }
455
456 void detect_maptype()
457 {
458 #if 0
459         vector o, v;
460         float i;
461
462         for(;;)
463         {
464                 o = world.mins;
465                 o_x += random() * (world.maxs_x - world.mins_x);
466                 o_y += random() * (world.maxs_y - world.mins_y);
467                 o_z += random() * (world.maxs_z - world.mins_z);
468
469                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
470                 if(trace_fraction == 1)
471                         continue;
472
473                 v = trace_endpos;
474
475                 for(i = 0; i < 64; i += 4)
476                 {
477                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
478         if(trace_fraction == 1)
479                 continue;
480                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
481                 }
482
483                 break;
484         }
485 #endif
486 }
487
488 entity randomseed;
489 float RandomSeed_Send(entity to, float sf)
490 {
491         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
492         WriteShort(MSG_ENTITY, self.cnt);
493         return TRUE;
494 }
495 void RandomSeed_Think()
496 {
497         self.cnt = bound(0, floor(random() * 65536), 65535);
498         self.nextthink = time + 5;
499
500         self.SendFlags |= 1;
501 }
502 void RandomSeed_Spawn()
503 {
504         randomseed = spawn();
505         randomseed.think = RandomSeed_Think;
506         Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
507
508         entity oldself;
509         oldself = self;
510         self = randomseed;
511         self.think(); // sets random seed and nextthink
512         self = oldself;
513 }
514
515 void spawnfunc___init_dedicated_server(void)
516 {
517         // handler for _init/_init map (only for dedicated server initialization)
518
519         world_initialized = -1; // don't complain
520         cvar = cvar_normal;
521         cvar_string = cvar_string_normal;
522         cvar_set = cvar_set_normal;
523
524         remove = remove_unsafely;
525
526         entity e;
527         e = spawn();
528         e.think = GotoFirstMap;
529         e.nextthink = time; // this is usually 1 at this point
530
531         e = spawn();
532         e.classname = "info_player_deathmatch"; // safeguard against player joining
533
534         self.classname = "worldspawn"; // safeguard against various stuff ;)
535
536         // needs to be done so early because of the constants they create
537         RegisterWeapons();
538         RegisterGametypes();
539
540         MapInfo_Enumerate();
541         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
542 }
543
544 void Map_MarkAsRecent(string m);
545 float world_already_spawned;
546 void RegisterWeapons();
547 void Nagger_Init();
548 void ClientInit_Spawn();
549 void WeaponStats_Init();
550 void WeaponStats_Shutdown();
551 void spawnfunc_worldspawn (void)
552 {
553         float fd, l, i, j, n;
554         string s, col;
555
556         cvar = cvar_normal;
557         cvar_string = cvar_string_normal;
558         cvar_set = cvar_set_normal;
559
560         if(world_already_spawned)
561                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
562         world_already_spawned = TRUE;
563
564         remove = remove_safely; // during spawning, watch what you remove!
565
566         check_unacceptable_compiler_bugs();
567
568         cvar_changes_init(); // do this very early now so it REALLY matches the server config
569
570         compressShortVector_init();
571
572         allowed_to_spawn = TRUE;
573
574         entity head;
575         head = nextent(world);
576         maxclients = 0;
577         while(head)
578         {
579                 ++maxclients;
580                 head = nextent(head);
581         }
582
583         // needs to be done so early because of the constants they create
584         RegisterWeapons();
585         RegisterGametypes();
586
587         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
588
589         TemporaryDB = db_create();
590
591         // 0 normal
592         lightstyle(0, "m");
593
594         // 1 FLICKER (first variety)
595         lightstyle(1, "mmnmmommommnonmmonqnmmo");
596
597         // 2 SLOW STRONG PULSE
598         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
599
600         // 3 CANDLE (first variety)
601         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
602
603         // 4 FAST STROBE
604         lightstyle(4, "mamamamamama");
605
606         // 5 GENTLE PULSE 1
607         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
608
609         // 6 FLICKER (second variety)
610         lightstyle(6, "nmonqnmomnmomomno");
611
612         // 7 CANDLE (second variety)
613         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
614
615         // 8 CANDLE (third variety)
616         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
617
618         // 9 SLOW STROBE (fourth variety)
619         lightstyle(9, "aaaaaaaazzzzzzzz");
620
621         // 10 FLUORESCENT FLICKER
622         lightstyle(10, "mmamammmmammamamaaamammma");
623
624         // 11 SLOW PULSE NOT FADE TO BLACK
625         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
626
627         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
628
629         // 63 testing
630         lightstyle(63, "a");
631
632         if(autocvar_g_campaign)
633                 CampaignPreInit();
634
635         Map_MarkAsRecent(mapname);
636
637         precache_model ("null"); // we need this one before InitGameplayMode
638         InitGameplayMode();
639         readlevelcvars();
640         GrappleHookInit();
641         ElectroInit();
642         LaserInit();
643
644         player_count = 0;
645         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
646         if(bot_waypoints_for_items == 1)
647                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
648                         bot_waypoints_for_items = 0;
649
650         precache();
651
652         WaypointSprite_Init();
653
654         //if (g_domination)
655         //      dom_init();
656
657         GameLogInit(); // prepare everything
658         // NOTE for matchid:
659         // changing the logic generating it is okay. But:
660         // it HAS to stay <= 64 chars
661         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
662         if(autocvar_sv_eventlog)
663         {
664                 s = sprintf("%d.%s.%06d", ftos(autocvar_sv_eventlog_files_counter), strftime(FALSE, "%s"), floor(random() * 1000000));
665                 matchid = strzone(s);
666
667                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
668                 s = ":gameinfo:mutators:LIST";
669
670                 ret_string = s;
671                 MUTATOR_CALLHOOK(BuildMutatorsString);
672                 s = ret_string;
673
674                 // simple, probably not good in the mutator system
675                 if(autocvar_g_grappling_hook)
676                         s = strcat(s, ":grappling_hook");
677
678                 // initialiation stuff, not good in the mutator system
679                 if(!autocvar_g_use_ammunition)
680                         s = strcat(s, ":no_use_ammunition");
681
682                 // initialiation stuff, not good in the mutator system
683                 if(autocvar_g_pickup_items == 0)
684                         s = strcat(s, ":no_pickup_items");
685                 if(autocvar_g_pickup_items > 0)
686                         s = strcat(s, ":pickup_items");
687
688                 // initialiation stuff, not good in the mutator system
689                 if(autocvar_g_weaponarena != "0")
690                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
691
692                 // TODO to mutator system
693                 if(autocvar_g_norecoil)
694                         s = strcat(s, ":norecoil");
695
696                 // TODO to mutator system
697                 if(autocvar_g_midair)
698                         s = strcat(s, ":midair");
699
700                 // TODO to mutator system
701                 if(autocvar_g_minstagib)
702                         s = strcat(s, ":minstagib");
703
704                 // TODO to mutator system
705                 if(autocvar_g_powerups == 0)
706                         s = strcat(s, ":no_powerups");
707                 if(autocvar_g_powerups > 0)
708                         s = strcat(s, ":powerups");
709
710                 GameLogEcho(s);
711                 GameLogEcho(":gameinfo:end");
712         }
713         else
714                 matchid = strzone(ftos(random()));
715
716         cvar_set("nextmap", "");
717
718         SetDefaultAlpha();
719
720         if(autocvar_g_campaign)
721                 CampaignPostInit();
722
723         fteqcc_testbugs();
724
725         Ban_LoadBans();
726
727         MapInfo_Enumerate();
728         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
729
730         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
731         {
732                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
733                 if(fd != -1)
734                 {
735                         while((s = fgets(fd)))
736                         {
737                                 l = tokenize_console(s);
738                                 if(l < 2)
739                                         continue;
740                                 if(argv(0) == "cd")
741                                 {
742                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
743                                         print("  cdtrack ", argv(2), "\n");
744                                 }
745                                 else if(argv(0) == "fog")
746                                 {
747                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
748                                         print("  \"fog\" \"", s, "\"\n");
749                                 }
750                                 else if(argv(0) == "set")
751                                 {
752                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
753                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
754                                 }
755                                 else if(argv(0) != "//")
756                                 {
757                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
758                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
759                                 }
760                         }
761                         fclose(fd);
762                 }
763         }
764
765         WeaponStats_Init();
766
767         addstat(STAT_WEAPONS, AS_INT, weapons);
768         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
769         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
770         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
771         addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
772         Nagger_Init();
773
774         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
775         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
776         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
777         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
778         addstat(STAT_FUEL, AS_INT, ammo_fuel);
779         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
780         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
781         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
782         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
783         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
784         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
785         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
786         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
787
788         addstat(STAT_NEX_CHARGE, AS_FLOAT, nex_charge);
789         addstat(STAT_NEX_CHARGEPOOL, AS_FLOAT, nex_chargepool_ammo);
790
791         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
792
793         if(g_ca || g_freezetag)
794         {
795                 addstat(STAT_REDALIVE, AS_INT, redalive_stat);
796                 addstat(STAT_BLUEALIVE, AS_INT, bluealive_stat);
797                 addstat(STAT_YELLOWALIVE, AS_INT, yellowalive_stat);
798                 addstat(STAT_PINKALIVE, AS_INT, pinkalive_stat);
799         }
800         if(g_freezetag)
801         {
802                 addstat(STAT_FROZEN, AS_INT, freezetag_frozen);
803                 addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, freezetag_revive_progress);
804         }
805
806         // g_movementspeed hack
807         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
808         addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
809         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
810         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
811         
812         // secrets
813         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
814         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
815         
816         next_pingtime = time + 5;
817
818         detect_maptype();
819         
820         // set up information replies for clients and server to use
821         lsmaps_reply = "^7Maps available: ";
822         lsnewmaps_reply = "^7Maps without a record set: ";
823         for(i = 0, j = 0; i < MapInfo_count; ++i)
824         {
825                 if(MapInfo_Get_ByID(i))
826                         if not(MapInfo_Map_flags & (MAPINFO_FLAG_HIDDEN | MAPINFO_FLAG_FORBIDDEN))
827                         {
828                                 if(mod(i, 2))
829                                         col = "^2";
830                                 else
831                                         col = "^3";
832                                         
833                                 ++j;
834                                 
835                                 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
836                                 
837                                 if(g_race && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, RACE_RECORD, "time"))))
838                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
839                                 else if(g_cts && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, CTS_RECORD, "time"))))
840                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
841                         }
842         }
843         
844         lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
845         lsnewmaps_reply = strzone(strcat(((!g_race && !g_cts) ? "Need to be playing race or CTS for lsnewmaps to work." : lsnewmaps_reply), "\n"));
846
847         maplist_reply = "^7Maps in list: ";
848         n = tokenize_console(autocvar_g_maplist);
849         for(i = 0, j = 0; i < n; ++i)
850         {
851                 if(MapInfo_CheckMap(argv(i)))
852                 {
853                         if(mod(j, 2))
854                                 col = "^2";
855                         else
856                                 col = "^3";
857                         maplist_reply = strcat(maplist_reply, col, argv(i), " ");
858                         ++j;
859                 }
860         }
861         maplist_reply = strzone(strcat(maplist_reply, "\n"));
862         MapInfo_ClearTemps();
863
864         for(i = 0; i < 10; ++i)
865         {
866                 records_reply[i] = strzone(getrecords(i));
867         }
868         
869         ladder_reply = strzone(getladder());
870
871         rankings_reply = strzone(getrankings());
872
873         // begin other init
874         ClientInit_Spawn();
875         RandomSeed_Spawn();
876         PingPLReport_Spawn();
877
878         CheatInit();
879
880         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
881
882         // fill sv_curl_serverpackages from .serverpackage files
883         if(autocvar_sv_curl_serverpackages_auto)
884         {
885                 s = "";
886                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
887                 for(i = 0; i < n; ++i)
888                         if(substring(argv(i), -14, -1) != "-serverpackage.txt")
889                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
890                                 s = strcat(s, " ", argv(i));
891                 fd = search_begin("*-serverpackage.txt", TRUE, FALSE);
892                 if(fd >= 0)
893                 {
894                         j = search_getsize(fd);
895                         for(i = 0; i < j; ++i)
896                                 s = strcat(s, " ", search_getfilename(fd, i));
897                         search_end(fd);
898                 }
899                 fd = search_begin("*.serverpackage", TRUE, FALSE);
900                 if(fd >= 0)
901                 {
902                         j = search_getsize(fd);
903                         for(i = 0; i < j; ++i)
904                                 s = strcat(s, " ", search_getfilename(fd, i));
905                         search_end(fd);
906                 }
907                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
908         }
909
910         PlayerStats_Init();
911
912         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
913         modname = "Xonotic";
914         // physics/balance/config changes that count as mod
915         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
916                 modname = cvar_string("g_mod_physics");
917         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
918                 modname = cvar_string("g_mod_balance");
919         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
920                 modname = cvar_string("g_mod_config");
921         // weird mutators that deserve to count as mod
922         if(autocvar_g_minstagib)
923                 modname = "MinstaGib";
924         // extra mutators that deserve to count as mod
925         MUTATOR_CALLHOOK(SetModname);
926         // weird game types that deserve to count as mod
927         if(g_cts)
928                 modname = "CTS";
929         // save it for later
930         modname = strzone(modname);
931
932         WinningConditionHelper(); // set worldstatus
933
934         world_initialized = 1;
935 }
936
937 void spawnfunc_light (void)
938 {
939         //makestatic (self); // Who the f___ did that?
940         remove(self);
941 }
942
943 string GetGametype()
944 {
945         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
946 }
947
948 string getmapname_stored;
949 string GetMapname()
950 {
951         return mapname;
952 }
953
954 float Map_Count, Map_Current;
955 string Map_Current_Name;
956
957 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
958 float GetMaplistPosition()
959 {
960         float pos, idx;
961         string map;
962
963         map = GetMapname();
964         idx = autocvar_g_maplist_index;
965
966         if(idx >= 0)
967                 if(idx < Map_Count)
968                         if(map == argv(idx))
969                                 return idx;
970
971         for(pos = 0; pos < Map_Count; ++pos)
972                 if(map == argv(pos))
973                         return pos;
974
975         // resume normal maplist rotation if current map is not in g_maplist
976         return idx;
977 }
978
979 float MapHasRightSize(string map)
980 {
981         float fh;
982         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
983         if(autocvar_g_maplist_check_waypoints)
984         {
985                 dprint("checkwp "); dprint(map);
986                 if(!fexists(strcat("maps/", map, ".waypoints")))
987                 {
988                         dprint(": no waypoints\n");
989                         return FALSE;
990                 }
991                 dprint(": has waypoints\n");
992         }
993
994         // open map size restriction file
995         dprint("opensize "); dprint(map);
996         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
997         if(fh >= 0)
998         {
999                 float mapmin, mapmax;
1000                 dprint(": ok, ");
1001                 mapmin = stof(fgets(fh));
1002                 mapmax = stof(fgets(fh));
1003                 fclose(fh);
1004                 if(player_count < mapmin)
1005                 {
1006                         dprint("not enough\n");
1007                         return FALSE;
1008                 }
1009                 if(player_count > mapmax)
1010                 {
1011                         dprint("too many\n");
1012                         return FALSE;
1013                 }
1014                 dprint("right size\n");
1015                 return TRUE;
1016         }
1017         dprint(": not found\n");
1018         return TRUE;
1019 }
1020
1021 string Map_Filename(float position)
1022 {
1023         return strcat("maps/", argv(position), ".bsp");
1024 }
1025
1026 string strwords(string s, float w)
1027 {
1028         float endpos;
1029         for(endpos = 0; w && endpos >= 0; --w)
1030                 endpos = strstrofs(s, " ", endpos + 1);
1031         if(endpos < 0)
1032                 return s;
1033         else
1034                 return substring(s, 0, endpos);
1035 }
1036
1037 float strhasword(string s, string w)
1038 {
1039         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
1040 }
1041
1042 void Map_MarkAsRecent(string m)
1043 {
1044         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1045 }
1046
1047 float Map_IsRecent(string m)
1048 {
1049         return strhasword(autocvar_g_maplist_mostrecent, m);
1050 }
1051
1052 float Map_Check(float position, float pass)
1053 {
1054         string filename;
1055         string map_next;
1056         map_next = argv(position);
1057         if(pass <= 1)
1058         {
1059                 if(Map_IsRecent(map_next))
1060                         return 0;
1061         }
1062         filename = Map_Filename(position);
1063         if(MapInfo_CheckMap(map_next))
1064         {
1065                 if(pass == 2)
1066                         return 1;
1067                 if(MapHasRightSize(map_next))
1068                         return 1;
1069                 return 0;
1070         }
1071         else
1072                 dprint( "Couldn't select '", filename, "'..\n" );
1073
1074         return 0;
1075 }
1076
1077 void Map_Goto_SetStr(string nextmapname)
1078 {
1079         if(getmapname_stored != "")
1080                 strunzone(getmapname_stored);
1081         if(nextmapname == "")
1082                 getmapname_stored = "";
1083         else
1084                 getmapname_stored = strzone(nextmapname);
1085 }
1086
1087 void Map_Goto_SetFloat(float position)
1088 {
1089         cvar_set("g_maplist_index", ftos(position));
1090         Map_Goto_SetStr(argv(position));
1091 }
1092
1093 void Map_Goto(float reinit)
1094 {
1095         MapInfo_LoadMap(getmapname_stored, reinit);
1096 }
1097
1098 // return codes of map selectors:
1099 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1100 //   -2 = permanent failure
1101 float() MaplistMethod_Iterate = // usual method
1102 {
1103         float pass, i;
1104
1105         for(pass = 1; pass <= 2; ++pass)
1106         {
1107                 for(i = 1; i < Map_Count; ++i)
1108                 {
1109                         float mapindex;
1110                         mapindex = mod(i + Map_Current, Map_Count);
1111                         if(Map_Check(mapindex, pass))
1112                                 return mapindex;
1113                 }
1114         }
1115         return -1;
1116 }
1117
1118 float() MaplistMethod_Repeat = // fallback method
1119 {
1120         if(Map_Check(Map_Current, 2))
1121                 return Map_Current;
1122         return -2;
1123 }
1124
1125 float() MaplistMethod_Random = // random map selection
1126 {
1127         float i, imax;
1128
1129         imax = 42;
1130
1131         for(i = 0; i <= imax; ++i)
1132         {
1133                 float mapindex;
1134                 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
1135                 if(Map_Check(mapindex, 1))
1136                         return mapindex;
1137         }
1138         return -1;
1139 }
1140
1141 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1142 // the exponent sets a bias on the map selection:
1143 // the higher the exponent, the less likely "shortly repeated" same maps are
1144 {
1145         float i, j, imax, insertpos;
1146
1147         imax = 42;
1148
1149         for(i = 0; i <= imax; ++i)
1150         {
1151                 string newlist;
1152
1153                 // now reinsert this at another position
1154                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1155                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1156                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1157                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1158
1159                 // insert the current map there
1160                 newlist = "";
1161                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1162                         newlist = strcat(newlist, " ", argv(j));
1163                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1164                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1165                         newlist = strcat(newlist, " ", argv(j));
1166                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1167                 cvar_set("g_maplist", newlist);
1168                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1169
1170                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1171                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1172                 if(Map_Check(Map_Current, 1))
1173                         return Map_Current;
1174         }
1175         return -1;
1176 }
1177
1178 void Maplist_Init()
1179 {
1180         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1181         if(Map_Count == 0)
1182         {
1183                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
1184                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1185                 if(autocvar_g_maplist_shuffle)
1186                         ShuffleMaplist();
1187                 localcmd("\nmenu_cmd sync\n");
1188                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1189         }
1190         if(Map_Count == 0)
1191                 error("empty maplist, cannot select a new map");
1192         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1193
1194         if(Map_Current_Name)
1195                 strunzone(Map_Current_Name);
1196         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1197         // this may or may not be correct, but who cares, in the worst case a map
1198         // isn't chosen in the first pass that should have been
1199 }
1200
1201 string GetNextMap()
1202 {
1203         float nextMap;
1204
1205         Maplist_Init();
1206         nextMap = -1;
1207
1208         if(nextMap == -1)
1209                 if(autocvar_g_maplist_shuffle > 0)
1210                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1211
1212         if(nextMap == -1)
1213                 if(autocvar_g_maplist_selectrandom)
1214                         nextMap = MaplistMethod_Random();
1215
1216         if(nextMap == -1)
1217                 nextMap = MaplistMethod_Iterate();
1218
1219         if(nextMap == -1)
1220                 nextMap = MaplistMethod_Repeat();
1221
1222         if(nextMap >= 0)
1223         {
1224                 Map_Goto_SetFloat(nextMap);
1225                 return getmapname_stored;
1226         }
1227
1228         return "";
1229 }
1230
1231 float DoNextMapOverride(float reinit)
1232 {
1233         if(autocvar_g_campaign)
1234         {
1235                 CampaignPostIntermission();
1236                 alreadychangedlevel = TRUE;
1237                 return TRUE;
1238         }
1239         if(autocvar_quit_when_empty)
1240         {
1241                 if(player_count <= currentbots)
1242                 {
1243                         localcmd("quit\n");
1244                         alreadychangedlevel = TRUE;
1245                         return TRUE;
1246                 }
1247         }
1248         if(autocvar_quit_and_redirect != "")
1249         {
1250                 redirection_target = strzone(autocvar_quit_and_redirect);
1251                 alreadychangedlevel = TRUE;
1252                 return TRUE;
1253         }
1254         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1255         {
1256                 localcmd("restart\n");
1257                 alreadychangedlevel = TRUE;
1258                 return TRUE;
1259         }
1260         if(autocvar_nextmap != "")
1261                 if(MapInfo_CheckMap(autocvar_nextmap))
1262                 {
1263                         Map_Goto_SetStr(autocvar_nextmap);
1264                         Map_Goto(reinit);
1265                         alreadychangedlevel = TRUE;
1266                         return TRUE;
1267                 }
1268         if(!reinit && autocvar_lastlevel)
1269         {
1270                 cvar_settemp_restore();
1271                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1272                 alreadychangedlevel = TRUE;
1273                 return TRUE;
1274         }
1275         return FALSE;
1276 }
1277
1278 void GotoNextMap(float reinit)
1279 {
1280         //string nextmap;
1281         //float n, nummaps;
1282         //string s;
1283         if (alreadychangedlevel)
1284                 return;
1285         alreadychangedlevel = TRUE;
1286
1287         {
1288                 string nextMap;
1289                 float allowReset;
1290
1291                 for(allowReset = 1; allowReset >= 0; --allowReset)
1292                 {
1293                         nextMap = GetNextMap();
1294                         if(nextMap != "")
1295                                 break;
1296
1297                         if(allowReset)
1298                         {
1299                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1300                                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1301                                 if(autocvar_g_maplist_shuffle)
1302                                         ShuffleMaplist();
1303                                 localcmd("\nmenu_cmd sync\n");
1304                         }
1305                         else
1306                         {
1307                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1308                         }
1309                 }
1310                 Map_Goto(reinit);
1311         }
1312 }
1313
1314
1315 /*
1316 ============
1317 IntermissionThink
1318
1319 When the player presses attack or jump, change to the next level
1320 ============
1321 */
1322 .float autoscreenshot;
1323 void() MapVote_Start;
1324 void() MapVote_Think;
1325 float mapvote_initialized;
1326 void IntermissionThink()
1327 {
1328         FixIntermissionClient(self);
1329         
1330         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1331         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1332         
1333         if( (server_screenshot || client_screenshot)
1334                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1335         {
1336                 self.autoscreenshot = -1;
1337                 if(clienttype(self) == CLIENTTYPE_REAL) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"", GetMapname(), strftime(FALSE, "%s"))); }
1338                 return;
1339         }
1340
1341         if (time < intermission_exittime)
1342                 return;
1343
1344         if(!mapvote_initialized)
1345                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1346                         return;
1347
1348         MapVote_Start();
1349 }
1350
1351 /*
1352 ============
1353 FindIntermission
1354
1355 Returns the entity to view from
1356 ============
1357 */
1358 /*
1359 entity FindIntermission()
1360 {
1361         local   entity spot;
1362         local   float cyc;
1363
1364 // look for info_intermission first
1365         spot = find (world, classname, "info_intermission");
1366         if (spot)
1367         {       // pick a random one
1368                 cyc = random() * 4;
1369                 while (cyc > 1)
1370                 {
1371                         spot = find (spot, classname, "info_intermission");
1372                         if (!spot)
1373                                 spot = find (spot, classname, "info_intermission");
1374                         cyc = cyc - 1;
1375                 }
1376                 return spot;
1377         }
1378
1379 // then look for the start position
1380         spot = find (world, classname, "info_player_start");
1381         if (spot)
1382                 return spot;
1383
1384 // testinfo_player_start is only found in regioned levels
1385         spot = find (world, classname, "testplayerstart");
1386         if (spot)
1387                 return spot;
1388
1389 // then look for the start position
1390         spot = find (world, classname, "info_player_deathmatch");
1391         if (spot)
1392                 return spot;
1393
1394         //objerror ("FindIntermission: no spot");
1395         return world;
1396 }
1397 */
1398
1399 /*
1400 ===============================================================================
1401
1402 RULES
1403
1404 ===============================================================================
1405 */
1406
1407 void DumpStats(float final)
1408 {
1409         float file;
1410         string s;
1411         float to_console;
1412         float to_eventlog;
1413         float to_file;
1414         float i;
1415
1416         to_console = autocvar_sv_logscores_console;
1417         to_eventlog = autocvar_sv_eventlog;
1418         to_file = autocvar_sv_logscores_file;
1419
1420         if(!final)
1421         {
1422                 to_console = TRUE; // always print printstats replies
1423                 to_eventlog = FALSE; // but never print them to the event log
1424         }
1425
1426         if(to_eventlog)
1427                 if(autocvar_sv_eventlog_console)
1428                         to_console = FALSE; // otherwise we get the output twice
1429
1430         if(final)
1431                 s = ":scores:";
1432         else
1433                 s = ":status:";
1434         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1435
1436         if(to_console)
1437                 print(s, "\n");
1438         if(to_eventlog)
1439                 GameLogEcho(s);
1440         if(to_file)
1441         {
1442                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1443                 if(file == -1)
1444                         to_file = FALSE;
1445                 else
1446                         fputs(file, strcat(s, "\n"));
1447         }
1448
1449         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1450         if(to_console)
1451                 print(s, "\n");
1452         if(to_eventlog)
1453                 GameLogEcho(s);
1454         if(to_file)
1455                 fputs(file, strcat(s, "\n"));
1456
1457         FOR_EACH_CLIENT(other)
1458         {
1459                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && autocvar_sv_logscores_bots))
1460                 {
1461                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1462                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1463                         if(other.classname == "player" || g_arena || g_ca || g_lms)
1464                                 s = strcat(s, ftos(other.team), ":");
1465                         else
1466                                 s = strcat(s, "spectator:");
1467
1468                         if(to_console)
1469                                 print(s, other.netname, "\n");
1470                         if(to_eventlog)
1471                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1472                         if(to_file)
1473                                 fputs(file, strcat(s, other.netname, "\n"));
1474                 }
1475         }
1476
1477         if(teamplay)
1478         {
1479                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1480                 if(to_console)
1481                         print(s, "\n");
1482                 if(to_eventlog)
1483                         GameLogEcho(s);
1484                 if(to_file)
1485                         fputs(file, strcat(s, "\n"));
1486
1487                 for(i = 1; i < 16; ++i)
1488                 {
1489                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1490                         s = strcat(s, ":", ftos(i));
1491                         if(to_console)
1492                                 print(s, "\n");
1493                         if(to_eventlog)
1494                                 GameLogEcho(s);
1495                         if(to_file)
1496                                 fputs(file, strcat(s, "\n"));
1497                 }
1498         }
1499
1500         if(to_console)
1501                 print(":end\n");
1502         if(to_eventlog)
1503                 GameLogEcho(":end");
1504         if(to_file)
1505         {
1506                 fputs(file, ":end\n");
1507                 fclose(file);
1508         }
1509 }
1510
1511 void FixIntermissionClient(entity e)
1512 {
1513         string s;
1514         if(!e.autoscreenshot) // initial call
1515         {
1516                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1517                 e.health = -2342;
1518                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1519                 e.solid = SOLID_NOT;
1520                 e.movetype = MOVETYPE_NONE;
1521                 e.takedamage = DAMAGE_NO;
1522                 if(e.weaponentity)
1523                 {
1524                         e.weaponentity.effects = EF_NODRAW;
1525                         if (e.weaponentity.weaponentity)
1526                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1527                 }
1528                 if(clienttype(e) == CLIENTTYPE_REAL)
1529                 {
1530                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1531                         s = autocvar_sv_intermission_cdtrack;
1532                         if(s != "")
1533                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1534                         msg_entity = e;
1535                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1536                 }
1537         }
1538 }
1539
1540
1541 /*
1542 go to the next level for deathmatch
1543 only called if a time or frag limit has expired
1544 */
1545 void NextLevel()
1546 {
1547         gameover = TRUE;
1548
1549         intermission_running = 1;
1550
1551 // enforce a wait time before allowing changelevel
1552         if(player_count > 0)
1553                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1554         else
1555                 intermission_exittime = -1;
1556
1557         /*
1558         WriteByte (MSG_ALL, SVC_CDTRACK);
1559         WriteByte (MSG_ALL, 3);
1560         WriteByte (MSG_ALL, 3);
1561         // done in FixIntermission
1562         */
1563
1564         //pos = FindIntermission ();
1565
1566         VoteReset();
1567
1568         DumpStats(TRUE);
1569
1570         // send statistics
1571         entity e;
1572         PlayerStats_EndMatch(1);
1573         FOR_EACH_CLIENT(e)
1574                 PlayerStats_AddGlobalInfo(e);
1575         PlayerStats_Shutdown();
1576         WeaponStats_Shutdown();
1577
1578         if(autocvar_sv_eventlog)
1579                 GameLogEcho(":gameover");
1580
1581         GameLogClose();
1582
1583         FOR_EACH_PLAYER(other) {
1584                 FixIntermissionClient(other);
1585                 if(other.winning)
1586                         bprint(other.netname, " ^7wins.\n");
1587         }
1588
1589         if(autocvar_g_campaign)
1590                 CampaignPreIntermission();
1591
1592         localcmd("\nsv_hook_gameend\n");
1593 }
1594
1595 /*
1596 ============
1597 CheckRules_Player
1598
1599 Exit deathmatch games upon conditions
1600 ============
1601 */
1602 void CheckRules_Player()
1603 {
1604         if (gameover)   // someone else quit the game already
1605                 return;
1606
1607         if(self.deadflag == DEAD_NO)
1608                 self.play_time += frametime;
1609
1610         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1611         //   (div0: and that in CheckRules_World please)
1612 }
1613
1614 float checkrules_equality;
1615 float checkrules_suddendeathwarning;
1616 float checkrules_suddendeathend;
1617 float checkrules_overtimesadded; //how many overtimes have been already added
1618
1619 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1620 float WINNING_YES = 1; // winner found
1621 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1622 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1623
1624 float InitiateSuddenDeath()
1625 {
1626         // Check first whether normal overtimes could be added before initiating suddendeath mode
1627         // - for this timelimit_overtime needs to be >0 of course
1628         // - also check the winning condition calculated in the previous frame and only add normal overtime
1629         //   again, if at the point at which timelimit would be extended again, still no winner was found
1630         if ((checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1631         {
1632                 return 1; // need to call InitiateOvertime later
1633         }
1634         else
1635         {
1636                 if(!checkrules_suddendeathend)
1637                 {
1638                         checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1639                         if(g_race && !g_race_qualifying)
1640                                 race_StartCompleting();
1641                 }
1642                 return 0;
1643         }
1644 }
1645
1646 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1647 {
1648         ++checkrules_overtimesadded;
1649         //add one more overtime by simply extending the timelimit
1650         float tl;
1651         tl = autocvar_timelimit;
1652         tl += autocvar_timelimit_overtime;
1653         cvar_set("timelimit", ftos(tl));
1654         string minutesPlural;
1655         if (autocvar_timelimit_overtime == 1)
1656                 minutesPlural = " ^3minute";
1657         else
1658                 minutesPlural = " ^3minutes";
1659
1660         bcenterprint(
1661                 strcat(
1662                         "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1663                         ftos(autocvar_timelimit_overtime),
1664                         minutesPlural,
1665                         " to the game!"
1666                 )
1667         );
1668 }
1669
1670 float GetWinningCode(float fraglimitreached, float equality)
1671 {
1672         if(autocvar_g_campaign == 1)
1673                 if(fraglimitreached)
1674                         return WINNING_YES;
1675                 else
1676                         return WINNING_NO;
1677
1678         else
1679                 if(equality)
1680                         if(fraglimitreached)
1681                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1682                         else
1683                                 return WINNING_NEVER;
1684                 else
1685                         if(fraglimitreached)
1686                                 return WINNING_YES;
1687                         else
1688                                 return WINNING_NO;
1689 }
1690
1691 // set the .winning flag for exactly those players with a given field value
1692 void SetWinners(.float field, float value)
1693 {
1694         entity head;
1695         FOR_EACH_PLAYER(head)
1696                 head.winning = (head.field == value);
1697 }
1698
1699 // set the .winning flag for those players with a given field value
1700 void AddWinners(.float field, float value)
1701 {
1702         entity head;
1703         FOR_EACH_PLAYER(head)
1704                 if(head.field == value)
1705                         head.winning = 1;
1706 }
1707
1708 // clear the .winning flags
1709 void ClearWinners(void)
1710 {
1711         entity head;
1712         FOR_EACH_PLAYER(head)
1713                 head.winning = 0;
1714 }
1715
1716 // Onslaught winning condition:
1717 // game terminates if only one team has a working generator (or none)
1718 float WinningCondition_Onslaught()
1719 {
1720         entity head;
1721         float t1, t2, t3, t4;
1722
1723         WinningConditionHelper(); // set worldstatus
1724
1725         if(inWarmupStage)
1726                 return WINNING_NO;
1727
1728         // first check if the game has ended
1729         t1 = t2 = t3 = t4 = 0;
1730         head = find(world, classname, "onslaught_generator");
1731         while (head)
1732         {
1733                 if (head.health > 0)
1734                 {
1735                         if (head.team == COLOR_TEAM1) t1 = 1;
1736                         if (head.team == COLOR_TEAM2) t2 = 1;
1737                         if (head.team == COLOR_TEAM3) t3 = 1;
1738                         if (head.team == COLOR_TEAM4) t4 = 1;
1739                 }
1740                 head = find(head, classname, "onslaught_generator");
1741         }
1742         if (t1 + t2 + t3 + t4 < 2)
1743         {
1744                 // game over, only one team remains (or none)
1745                 ClearWinners();
1746                 if (t1) SetWinners(team, COLOR_TEAM1);
1747                 if (t2) SetWinners(team, COLOR_TEAM2);
1748                 if (t3) SetWinners(team, COLOR_TEAM3);
1749                 if (t4) SetWinners(team, COLOR_TEAM4);
1750                 dprint("Have a winner, ending game.\n");
1751                 return WINNING_YES;
1752         }
1753
1754         // Two or more teams remain
1755         return WINNING_NO;
1756 }
1757
1758 float LMS_NewPlayerLives()
1759 {
1760         float fl;
1761         fl = autocvar_fraglimit;
1762         if(fl == 0)
1763                 fl = 999;
1764
1765         // first player has left the game for dying too much? Nobody else can get in.
1766         if(lms_lowest_lives < 1)
1767                 return 0;
1768
1769         if(!autocvar_g_lms_join_anytime)
1770                 if(lms_lowest_lives < fl - autocvar_g_lms_last_join)
1771                         return 0;
1772
1773         return bound(1, lms_lowest_lives, fl);
1774 }
1775
1776 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1777 // they win. Otherwise the defending team wins once the timelimit passes.
1778 void assault_new_round();
1779 float WinningCondition_Assault()
1780 {
1781         float status;
1782
1783         WinningConditionHelper(); // set worldstatus
1784
1785         status = WINNING_NO;
1786         // as the timelimit has not yet passed just assume the defending team will win
1787         if(assault_attacker_team == COLOR_TEAM1)
1788         {
1789                 SetWinners(team, COLOR_TEAM2);
1790         }
1791         else
1792         {
1793                 SetWinners(team, COLOR_TEAM1);
1794         }
1795
1796         entity ent;
1797         ent = find(world, classname, "target_assault_roundend");
1798         if(ent)
1799         {
1800                 if(ent.winning) // round end has been triggered by attacking team
1801                 {
1802                         bprint("ASSAULT: round completed...\n");
1803                         SetWinners(team, assault_attacker_team);
1804
1805                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1806
1807                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1808                         {
1809                                 status = WINNING_YES;
1810                         }
1811                         else
1812                         {
1813                                 entity oldself;
1814                                 oldself = self;
1815                                 self = ent;
1816                                 assault_new_round();
1817                                 self = oldself;
1818                         }
1819                 }
1820         }
1821
1822         return status;
1823 }
1824
1825 // LMS winning condition: game terminates if and only if there's at most one
1826 // one player who's living lives. Top two scores being equal cancels the time
1827 // limit.
1828 float WinningCondition_LMS()
1829 {
1830         entity head, head2;
1831         float have_player;
1832         float have_players;
1833         float l;
1834
1835         have_player = FALSE;
1836         have_players = FALSE;
1837         l = LMS_NewPlayerLives();
1838
1839         head = find(world, classname, "player");
1840         if(head)
1841                 have_player = TRUE;
1842         head2 = find(head, classname, "player");
1843         if(head2)
1844                 have_players = TRUE;
1845
1846         if(have_player)
1847         {
1848                 // we have at least one player
1849                 if(have_players)
1850                 {
1851                         // two or more active players - continue with the game
1852                 }
1853                 else
1854                 {
1855                         // exactly one player?
1856
1857                         ClearWinners();
1858                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1859
1860                         if(l)
1861                         {
1862                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1863                                 return WINNING_NO;
1864                         }
1865                         else
1866                         {
1867                                 // a winner!
1868                                 // and assign him his first place
1869                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1870                                 return WINNING_YES;
1871                         }
1872                 }
1873         }
1874         else
1875         {
1876                 // nobody is playing at all...
1877                 if(l)
1878                 {
1879                         // wait for players...
1880                 }
1881                 else
1882                 {
1883                         // SNAFU (maybe a draw game?)
1884                         ClearWinners();
1885                         dprint("No players, ending game.\n");
1886                         return WINNING_YES;
1887                 }
1888         }
1889
1890         // When we get here, we have at least two players who are actually LIVING,
1891         // now check if the top two players have equal score.
1892         WinningConditionHelper();
1893
1894         ClearWinners();
1895         if(WinningConditionHelper_winner)
1896                 WinningConditionHelper_winner.winning = TRUE;
1897         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1898                 return WINNING_NEVER;
1899
1900         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1901         return WINNING_NO;
1902 }
1903
1904 void ShuffleMaplist()
1905 {
1906         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1907 }
1908
1909 float leaderfrags;
1910 float WinningCondition_Scores(float limit, float leadlimit)
1911 {
1912         float limitreached;
1913
1914         // TODO make everything use THIS winning condition (except LMS)
1915         WinningConditionHelper();
1916
1917         if(teamplay)
1918         {
1919                 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1920                 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1921                 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1922                 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1923         }
1924
1925         ClearWinners();
1926         if(WinningConditionHelper_winner)
1927                 WinningConditionHelper_winner.winning = 1;
1928         if(WinningConditionHelper_winnerteam >= 0)
1929                 SetWinners(team, WinningConditionHelper_winnerteam);
1930
1931         if(WinningConditionHelper_lowerisbetter)
1932         {
1933                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1934                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1935                 limit = -limit;
1936         }
1937
1938         if(WinningConditionHelper_zeroisworst)
1939                 leadlimit = 0; // not supported in this mode
1940
1941         if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1942         // these modes always score in increments of 1, thus this makes sense
1943         {
1944                 if(leaderfrags != WinningConditionHelper_topscore)
1945                 {
1946                         leaderfrags = WinningConditionHelper_topscore;
1947
1948                         if (limit)
1949                         if (leaderfrags == limit - 1)
1950                                 Announce("1fragleft");
1951                         else if (leaderfrags == limit - 2)
1952                                 Announce("2fragsleft");
1953                         else if (leaderfrags == limit - 3)
1954                                 Announce("3fragsleft");
1955                 }
1956         }
1957
1958         limitreached = FALSE;
1959         if(limit)
1960                 if(WinningConditionHelper_topscore >= limit)
1961                         limitreached = TRUE;
1962         if(leadlimit)
1963         {
1964                 float leadlimitreached;
1965                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1966                 if(autocvar_leadlimit_and_fraglimit)
1967                         limitreached = (limitreached && leadlimitreached);
1968                 else
1969                         limitreached = (limitreached || leadlimitreached);
1970         }
1971
1972         return GetWinningCode(
1973                 WinningConditionHelper_topscore && limitreached,
1974                 WinningConditionHelper_equality
1975         );
1976 }
1977
1978 float WinningCondition_Race(float fraglimit)
1979 {
1980         float wc;
1981         entity p;
1982         float n, c;
1983
1984         n = 0;
1985         c = 0;
1986         FOR_EACH_PLAYER(p)
1987         {
1988                 ++n;
1989                 if(p.race_completed)
1990                         ++c;
1991         }
1992         if(n && (n == c))
1993                 return WINNING_YES;
1994         wc = WinningCondition_Scores(fraglimit, 0);
1995
1996         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1997         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1998         // do NOT support equality when the laps are all raced!
1999                 return WINNING_STARTSUDDENDEATHOVERTIME;
2000         else
2001                 return WINNING_NEVER;
2002         return wc;
2003 }
2004
2005 float WinningCondition_QualifyingThenRace(float limit)
2006 {
2007         float wc;
2008         wc = WinningCondition_Scores(limit, 0);
2009
2010         // NEVER initiate overtime
2011         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
2012         {
2013                 return WINNING_YES;
2014         }
2015
2016         return wc;
2017 }
2018
2019 float WinningCondition_RanOutOfSpawns()
2020 {
2021         entity head;
2022
2023         if(have_team_spawns <= 0)
2024                 return WINNING_NO;
2025
2026         if(autocvar_g_spawn_useallspawns <= 0)
2027                 return WINNING_NO;
2028
2029         if(!some_spawn_has_been_used)
2030                 return WINNING_NO;
2031
2032         team1_score = team2_score = team3_score = team4_score = 0;
2033
2034         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
2035         {
2036                 if(head.team == COLOR_TEAM1)
2037                         team1_score = 1;
2038                 else if(head.team == COLOR_TEAM2)
2039                         team2_score = 1;
2040                 else if(head.team == COLOR_TEAM3)
2041                         team3_score = 1;
2042                 else if(head.team == COLOR_TEAM4)
2043                         team4_score = 1;
2044         }
2045
2046         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
2047         {
2048                 if(head.team == COLOR_TEAM1)
2049                         team1_score = 1;
2050                 else if(head.team == COLOR_TEAM2)
2051                         team2_score = 1;
2052                 else if(head.team == COLOR_TEAM3)
2053                         team3_score = 1;
2054                 else if(head.team == COLOR_TEAM4)
2055                         team4_score = 1;
2056         }
2057
2058         ClearWinners();
2059         if(team1_score + team2_score + team3_score + team4_score == 0)
2060         {
2061                 checkrules_equality = TRUE;
2062                 return WINNING_YES;
2063         }
2064         else if(team1_score + team2_score + team3_score + team4_score == 1)
2065         {
2066                 float t, i;
2067                 if(team1_score) t = COLOR_TEAM1;
2068                 if(team2_score) t = COLOR_TEAM2;
2069                 if(team3_score) t = COLOR_TEAM3;
2070                 if(team4_score) t = COLOR_TEAM4;
2071                 CheckAllowedTeams(world);
2072                 for(i = 0; i < MAX_TEAMSCORE; ++i)
2073                 {
2074                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
2075                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
2076                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
2077                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
2078                 }
2079
2080                 AddWinners(team, t);
2081                 return WINNING_YES;
2082         }
2083         else
2084                 return WINNING_NO;
2085 }
2086
2087 /*
2088 ============
2089 CheckRules_World
2090
2091 Exit deathmatch games upon conditions
2092 ============
2093 */
2094 void ReadyRestart();
2095 void CheckRules_World()
2096 {
2097         float timelimit;
2098         float fraglimit;
2099         float leadlimit;
2100
2101         VoteThink();
2102         MapVote_Think();
2103
2104         SetDefaultAlpha();
2105
2106         /*
2107         MapVote_Think should now do that part
2108         if (intermission_running)
2109                 if (time >= intermission_exittime + 60)
2110                 {
2111                         if(!DoNextMapOverride())
2112                                 GotoNextMap();
2113                         return;
2114                 }
2115         */
2116
2117         if (gameover)   // someone else quit the game already
2118         {
2119                 if(player_count == 0) // Nobody there? Then let's go to the next map
2120                         MapVote_Start();
2121                         // this will actually check the player count in the next frame
2122                         // again, but this shouldn't hurt
2123                 return;
2124         }
2125
2126         timelimit = autocvar_timelimit * 60;
2127         fraglimit = autocvar_fraglimit;
2128         leadlimit = autocvar_leadlimit;
2129
2130         if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2131         {
2132                 if(timelimit > 0)
2133                         timelimit = 0; // timelimit is not made for warmup
2134                 if(fraglimit > 0)
2135                         fraglimit = 0; // no fraglimit for now
2136                 leadlimit = 0; // no leadlimit for now
2137         }
2138
2139         if(g_onslaught)
2140                 timelimit = 0; // ONS has its own overtime rule
2141
2142         if(timelimit > 0)
2143         {
2144                 timelimit += game_starttime;
2145         }
2146         else if (timelimit < 0)
2147         {
2148                 // endmatch
2149                 NextLevel();
2150                 return;
2151         }
2152
2153         float wantovertime;
2154         wantovertime = 0;
2155
2156         if(checkrules_suddendeathend)
2157         {
2158                 if(!checkrules_suddendeathwarning)
2159                 {
2160                         checkrules_suddendeathwarning = TRUE;
2161                         if(g_race && !g_race_qualifying)
2162                                 bcenterprint("^3Everyone, finish your lap! The race is over!");
2163                         else
2164                                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
2165                 }
2166         }
2167         else
2168         {
2169                 if (timelimit && time >= timelimit)
2170                 {
2171                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2172                         {
2173                                 float totalplayers;
2174                                 float playerswithlaps;
2175                                 float readyplayers;
2176                                 entity head;
2177                                 totalplayers = playerswithlaps = readyplayers = 0;
2178                                 FOR_EACH_PLAYER(head)
2179                                 {
2180                                         ++totalplayers;
2181                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2182                                                 ++playerswithlaps;
2183                                         if(head.ready)
2184                                                 ++readyplayers;
2185                                 }
2186
2187                                 // at least 2 of the players have completed a lap: start the RACE
2188                                 // otherwise, the players should end the qualifying on their own
2189                                 if(readyplayers || playerswithlaps >= 2)
2190                                 {
2191                                         checkrules_suddendeathend = 0;
2192                                         ReadyRestart(); // go to race
2193                                         return;
2194                                 }
2195                                 else
2196                                         wantovertime |= InitiateSuddenDeath();
2197                         }
2198                         else
2199                                 wantovertime |= InitiateSuddenDeath();
2200                 }
2201         }
2202
2203         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2204         {
2205                 NextLevel();
2206                 return;
2207         }
2208
2209         float checkrules_status;
2210         checkrules_status = WinningCondition_RanOutOfSpawns();
2211         if(checkrules_status == WINNING_YES)
2212         {
2213                 bprint("Hey! Someone ran out of spawns!\n");
2214         }
2215         else if(g_race && !g_race_qualifying && timelimit >= 0)
2216         {
2217                 checkrules_status = WinningCondition_Race(fraglimit);
2218                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2219         }
2220         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2221         {
2222                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2223                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2224         }
2225         else if(g_assault)
2226         {
2227                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2228         }
2229         else if(g_lms)
2230         {
2231                 checkrules_status = WinningCondition_LMS();
2232         }
2233         else if (g_onslaught)
2234         {
2235                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2236         }
2237         else
2238         {
2239                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2240                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2241         }
2242
2243         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2244         {
2245                 checkrules_status = WINNING_NEVER;
2246                 checkrules_overtimesadded = -1;
2247                 wantovertime |= InitiateSuddenDeath();
2248         }
2249
2250         if(checkrules_status == WINNING_NEVER)
2251                 // equality cases! Nobody wins if the overtime ends in a draw.
2252                 ClearWinners();
2253
2254         if(wantovertime)
2255         {
2256                 if(checkrules_status == WINNING_NEVER)
2257                         InitiateOvertime();
2258                 else
2259                         checkrules_status = WINNING_YES;
2260         }
2261
2262         if(checkrules_suddendeathend)
2263                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2264                         checkrules_status = WINNING_YES;
2265
2266         if(checkrules_status == WINNING_YES)
2267         {
2268                 //print("WINNING\n");
2269                 NextLevel();
2270         }
2271 }
2272
2273 float mapvote_nextthink;
2274 float mapvote_initialized;
2275 float mapvote_keeptwotime;
2276 float mapvote_timeout;
2277 string mapvote_message;
2278 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2279 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2280 float mapvote_screenshot_dirs_count;
2281
2282 float mapvote_count;
2283 float mapvote_count_real;
2284 string mapvote_maps[MAPVOTE_COUNT];
2285 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2286 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2287 float mapvote_maps_suggested[MAPVOTE_COUNT];
2288 string mapvote_suggestions[MAPVOTE_COUNT];
2289 float mapvote_suggestion_ptr;
2290 float mapvote_voters;
2291 float mapvote_selections[MAPVOTE_COUNT];
2292 float mapvote_run;
2293 float mapvote_detail;
2294 float mapvote_abstain;
2295 .float mapvote;
2296
2297 void MapVote_ClearAllVotes()
2298 {
2299         FOR_EACH_CLIENT(other)
2300                 other.mapvote = 0;
2301 }
2302
2303 string MapVote_Suggest(string m)
2304 {
2305         float i;
2306         if(m == "")
2307                 return "That's not how to use this command.";
2308         if(!autocvar_g_maplist_votable_suggestions)
2309                 return "Suggestions are not accepted on this server.";
2310         if(mapvote_initialized)
2311                 return "Can't suggest - voting is already in progress!";
2312         m = MapInfo_FixName(m);
2313         if(!m)
2314                 return "The map you suggested is not available on this server.";
2315         if(!autocvar_g_maplist_votable_suggestions_override_mostrecent)
2316                 if(Map_IsRecent(m))
2317                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2318
2319         if(!MapInfo_CheckMap(m))
2320                 return "The map you suggested does not support the current game mode.";
2321         for(i = 0; i < mapvote_suggestion_ptr; ++i)
2322                 if(mapvote_suggestions[i] == m)
2323                         return "This map was already suggested.";
2324         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2325         {
2326                 i = floor(random() * mapvote_suggestion_ptr);
2327         }
2328         else
2329         {
2330                 i = mapvote_suggestion_ptr;
2331                 mapvote_suggestion_ptr += 1;
2332         }
2333         if(mapvote_suggestions[i] != "")
2334                 strunzone(mapvote_suggestions[i]);
2335         mapvote_suggestions[i] = strzone(m);
2336         if(autocvar_sv_eventlog)
2337                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2338         return strcat("Suggestion of ", m, " accepted.");
2339 }
2340
2341 void MapVote_AddVotable(string nextMap, float isSuggestion)
2342 {
2343         float j, i, o;
2344         string pakfile, mapfile;
2345
2346         if(nextMap == "")
2347                 return;
2348         for(j = 0; j < mapvote_count; ++j)
2349                 if(mapvote_maps[j] == nextMap)
2350                         return;
2351         // suggestions might be no longer valid/allowed after gametype switch!
2352         if(isSuggestion)
2353                 if(!MapInfo_CheckMap(nextMap))
2354                         return;
2355         mapvote_maps[mapvote_count] = strzone(nextMap);
2356         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2357
2358         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2359         {
2360                 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2361                 pakfile = whichpack(strcat(mapfile, ".tga"));
2362                 if(pakfile == "")
2363                         pakfile = whichpack(strcat(mapfile, ".jpg"));
2364                 if(pakfile == "")
2365                         pakfile = whichpack(strcat(mapfile, ".png"));
2366                 if(pakfile != "")
2367                         break;
2368         }
2369         if(i >= mapvote_screenshot_dirs_count)
2370                 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2371         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2372                 pakfile = substring(pakfile, o, -1);
2373
2374         mapvote_maps_screenshot_dir[mapvote_count] = i;
2375         mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2376
2377         mapvote_count += 1;
2378 }
2379
2380 void MapVote_Spawn();
2381 void MapVote_Init()
2382 {
2383         float i;
2384         float nmax, smax;
2385
2386         MapVote_ClearAllVotes();
2387
2388         mapvote_count = 0;
2389         mapvote_detail = !autocvar_g_maplist_votable_nodetail;
2390         mapvote_abstain = autocvar_g_maplist_votable_abstain;
2391
2392         if(mapvote_abstain)
2393                 nmax = min(MAPVOTE_COUNT - 1, autocvar_g_maplist_votable);
2394         else
2395                 nmax = min(MAPVOTE_COUNT, autocvar_g_maplist_votable);
2396         smax = min3(nmax, autocvar_g_maplist_votable_suggestions, mapvote_suggestion_ptr);
2397
2398         // we need this for AddVotable, as that cycles through the screenshot dirs
2399         mapvote_screenshot_dirs_count = tokenize_console(autocvar_g_maplist_votable_screenshot_dir);
2400         if(mapvote_screenshot_dirs_count == 0)
2401                 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2402         mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2403         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2404                 mapvote_screenshot_dirs[i] = strzone(argv(i));
2405
2406         if(mapvote_suggestion_ptr)
2407                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2408                         MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2409
2410         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2411                 MapVote_AddVotable(GetNextMap(), FALSE);
2412
2413         if(mapvote_count == 0)
2414         {
2415                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2416                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2417                 if(autocvar_g_maplist_shuffle)
2418                         ShuffleMaplist();
2419                 localcmd("\nmenu_cmd sync\n");
2420                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2421                         MapVote_AddVotable(GetNextMap(), FALSE);
2422         }
2423
2424         mapvote_count_real = mapvote_count;
2425         if(mapvote_abstain)
2426                 MapVote_AddVotable("don't care", 0);
2427
2428         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2429
2430         mapvote_keeptwotime = time + autocvar_g_maplist_votable_keeptwotime;
2431         mapvote_timeout = time + autocvar_g_maplist_votable_timeout;
2432         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2433                 mapvote_keeptwotime = 0;
2434         mapvote_message = "Choose a map and press its key!";
2435
2436         MapVote_Spawn();
2437 }
2438
2439 void MapVote_SendPicture(float id)
2440 {
2441         msg_entity = self;
2442         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2443         WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2444         WriteByte(MSG_ONE, id);
2445         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2446 }
2447
2448 float MapVote_GetMapMask()
2449 {
2450         float mask, i, power;
2451         mask = 0;
2452         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2453                 if(mapvote_maps[i] != "")
2454                         mask |= power;
2455         return mask;
2456 }
2457
2458 entity mapvote_ent;
2459 float MapVote_SendEntity(entity to, float sf)
2460 {
2461         float i;
2462
2463         if(sf & 1)
2464                 sf &~= 2; // if we send 1, we don't need to also send 2
2465
2466         WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2467         WriteByte(MSG_ENTITY, sf);
2468
2469         if(sf & 1)
2470         {
2471                 // flag 1 == initialization
2472                 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2473                         WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2474                 WriteString(MSG_ENTITY, "");
2475                 WriteByte(MSG_ENTITY, mapvote_count);
2476                 WriteByte(MSG_ENTITY, mapvote_abstain);
2477                 WriteByte(MSG_ENTITY, mapvote_detail);
2478                 WriteCoord(MSG_ENTITY, mapvote_timeout);
2479                 if(mapvote_count <= 8)
2480                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2481                 else
2482                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2483                 for(i = 0; i < mapvote_count; ++i)
2484                         if(mapvote_maps[i] != "")
2485                         {
2486                                 if(mapvote_abstain && i == mapvote_count - 1)
2487                                 {
2488                                         WriteString(MSG_ENTITY, ""); // abstain needs no text
2489                                         WriteString(MSG_ENTITY, ""); // abstain needs no pack
2490                                         WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2491                                 }
2492                                 else
2493                                 {
2494                                         WriteString(MSG_ENTITY, mapvote_maps[i]);
2495                                         WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2496                                         WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2497                                 }
2498                         }
2499         }
2500
2501         if(sf & 2)
2502         {
2503                 // flag 2 == update of mask
2504                 if(mapvote_count <= 8)
2505                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2506                 else
2507                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2508         }
2509
2510         if(sf & 4)
2511         {
2512                 if(mapvote_detail)
2513                         for(i = 0; i < mapvote_count; ++i)
2514                                 if(mapvote_maps[i] != "")
2515                                         WriteByte(MSG_ENTITY, mapvote_selections[i]);
2516
2517                 WriteByte(MSG_ENTITY, to.mapvote);
2518         }
2519
2520         return TRUE;
2521 }
2522
2523 void MapVote_Spawn()
2524 {
2525         Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2526 }
2527
2528 void MapVote_TouchMask()
2529 {
2530         mapvote_ent.SendFlags |= 2;
2531 }
2532
2533 void MapVote_TouchVotes(entity voter)
2534 {
2535         mapvote_ent.SendFlags |= 4;
2536 }
2537
2538 float MapVote_Finished(float mappos)
2539 {
2540         string result;
2541         float i;
2542         float didntvote;
2543
2544         if(autocvar_sv_eventlog)
2545         {
2546                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2547                 result = strcat(result, ":", ftos(mapvote_selections[mappos]), "::");
2548                 didntvote = mapvote_voters;
2549                 for(i = 0; i < mapvote_count; ++i)
2550                         if(mapvote_maps[i] != "")
2551                         {
2552                                 didntvote -= mapvote_selections[i];
2553                                 if(i != mappos)
2554                                 {
2555                                         result = strcat(result, ":", mapvote_maps[i]);
2556                                         result = strcat(result, ":", ftos(mapvote_selections[i]));
2557                                 }
2558                         }
2559                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2560
2561                 GameLogEcho(result);
2562                 if(mapvote_maps_suggested[mappos])
2563                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2564         }
2565
2566         FOR_EACH_REALCLIENT(other)
2567                 FixClientCvars(other);
2568
2569         Map_Goto_SetStr(mapvote_maps[mappos]);
2570         Map_Goto(0);
2571         alreadychangedlevel = TRUE;
2572         return TRUE;
2573 }
2574 void MapVote_CheckRules_1()
2575 {
2576         float i;
2577
2578         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2579         {
2580                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2581                 mapvote_selections[i] = 0;
2582         }
2583
2584         mapvote_voters = 0;
2585         FOR_EACH_REALCLIENT(other)
2586         {
2587                 ++mapvote_voters;
2588                 if(other.mapvote)
2589                 {
2590                         i = other.mapvote - 1;
2591                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2592                         mapvote_selections[i] = mapvote_selections[i] + 1;
2593                 }
2594         }
2595 }
2596
2597 float MapVote_CheckRules_2()
2598 {
2599         float i;
2600         float firstPlace, secondPlace;
2601         float firstPlaceVotes, secondPlaceVotes;
2602         float mapvote_voters_real;
2603         string result;
2604
2605         if(mapvote_count_real == 1)
2606                 return MapVote_Finished(0);
2607
2608         mapvote_voters_real = mapvote_voters;
2609         if(mapvote_abstain)
2610                 mapvote_voters_real -= mapvote_selections[mapvote_count - 1];
2611
2612         RandomSelection_Init();
2613         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2614                 RandomSelection_Add(world, i, string_null, 1, mapvote_selections[i]);
2615         firstPlace = RandomSelection_chosen_float;
2616         firstPlaceVotes = RandomSelection_best_priority;
2617         //dprint("First place: ", ftos(firstPlace), "\n");
2618         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2619
2620         RandomSelection_Init();
2621         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2622                 if(i != firstPlace)
2623                         RandomSelection_Add(world, i, string_null, 1, mapvote_selections[i]);
2624         secondPlace = RandomSelection_chosen_float;
2625         secondPlaceVotes = RandomSelection_best_priority;
2626         //dprint("Second place: ", ftos(secondPlace), "\n");
2627         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2628
2629         if(firstPlace == -1)
2630                 error("No first place in map vote... WTF?");
2631
2632         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2633                 return MapVote_Finished(firstPlace);
2634
2635         if(mapvote_keeptwotime)
2636                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2637                 {
2638                         float didntvote;
2639                         MapVote_TouchMask();
2640                         mapvote_message = "Now decide between the TOP TWO!";
2641                         mapvote_keeptwotime = 0;
2642                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2643                         result = strcat(result, ":", ftos(firstPlaceVotes));
2644                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2645                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2646                         didntvote = mapvote_voters;
2647                         for(i = 0; i < mapvote_count; ++i)
2648                                 if(mapvote_maps[i] != "")
2649                                 {
2650                                         didntvote -= mapvote_selections[i];
2651                                         if(i != firstPlace)
2652                                                 if(i != secondPlace)
2653                                                 {
2654                                                         result = strcat(result, ":", mapvote_maps[i]);
2655                                                         result = strcat(result, ":", ftos(mapvote_selections[i]));
2656                                                         if(i < mapvote_count_real)
2657                                                         {
2658                                                                 strunzone(mapvote_maps[i]);
2659                                                                 mapvote_maps[i] = "";
2660                                                                 strunzone(mapvote_maps_pakfile[i]);
2661                                                                 mapvote_maps_pakfile[i] = "";
2662                                                         }
2663                                                 }
2664                                 }
2665                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2666                         if(autocvar_sv_eventlog)
2667                                 GameLogEcho(result);
2668                 }
2669
2670         return FALSE;
2671 }
2672 void MapVote_Tick()
2673 {
2674         float keeptwo;
2675         float totalvotes;
2676
2677         keeptwo = mapvote_keeptwotime;
2678         MapVote_CheckRules_1(); // count
2679         if(MapVote_CheckRules_2()) // decide
2680                 return;
2681
2682         totalvotes = 0;
2683         FOR_EACH_REALCLIENT(other)
2684         {
2685                 // hide scoreboard again
2686                 if(other.health != 2342)
2687                 {
2688                         other.health = 2342;
2689                         other.impulse = 0;
2690                         if(clienttype(other) == CLIENTTYPE_REAL)
2691                         {
2692                                 msg_entity = other;
2693                                 WriteByte(MSG_ONE, SVC_FINALE);
2694                                 WriteString(MSG_ONE, "");
2695                         }
2696                 }
2697
2698                 // clear possibly invalid votes
2699                 if(mapvote_maps[other.mapvote - 1] == "")
2700                         other.mapvote = 0;
2701                 // use impulses as new vote
2702                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2703                         if(mapvote_maps[other.impulse - 1] != "")
2704                         {
2705                                 other.mapvote = other.impulse;
2706                                 MapVote_TouchVotes(other);
2707                         }
2708                 other.impulse = 0;
2709
2710                 if(other.mapvote)
2711                         ++totalvotes;
2712         }
2713
2714         MapVote_CheckRules_1(); // just count
2715 }
2716 void MapVote_Start()
2717 {
2718         if(mapvote_run)
2719                 return;
2720
2721         // wait for stats to be sent first
2722         if(!playerstats_waitforme)
2723                 return;
2724
2725         MapInfo_Enumerate();
2726         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2727                 mapvote_run = TRUE;
2728 }
2729 void MapVote_Think()
2730 {
2731         if(!mapvote_run)
2732                 return;
2733
2734         if(alreadychangedlevel)
2735                 return;
2736
2737         if(time < mapvote_nextthink)
2738                 return;
2739         //dprint("tick\n");
2740
2741         mapvote_nextthink = time + 0.5;
2742
2743         if(!mapvote_initialized)
2744         {
2745                 if(autocvar_rescan_pending == 1)
2746                 {
2747                         cvar_set("rescan_pending", "2");
2748                         localcmd("fs_rescan\nrescan_pending 3\n");
2749                         return;
2750                 }
2751                 else if(autocvar_rescan_pending == 2)
2752                 {
2753                         return;
2754                 }
2755                 else if(autocvar_rescan_pending == 3)
2756                 {
2757                         // now build missing mapinfo files
2758                         if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2759                                 return;
2760
2761                         // we're done, start the timer
2762                         cvar_set("rescan_pending", "0");
2763                 }
2764
2765                 mapvote_initialized = TRUE;
2766                 if(DoNextMapOverride(0))
2767                         return;
2768                 if(!autocvar_g_maplist_votable || player_count <= 0)
2769                 {
2770                         GotoNextMap(0);
2771                         return;
2772                 }
2773                 MapVote_Init();
2774         }
2775
2776         MapVote_Tick();
2777 }
2778
2779 string GotoMap(string m)
2780 {
2781         if(!MapInfo_CheckMap(m))
2782                 return "The map you chose is not available on this server.";
2783         cvar_set("nextmap", m);
2784         cvar_set("timelimit", "-1");
2785         if(mapvote_initialized || alreadychangedlevel)
2786         {
2787                 if(DoNextMapOverride(0))
2788                         return "Map switch initiated.";
2789                 else
2790                         return "Hm... no. For some reason I like THIS map more.";
2791         }
2792         else
2793                 return "Map switch will happen after scoreboard.";
2794 }
2795
2796
2797 void EndFrame()
2798 {
2799         float altime;
2800         FOR_EACH_REALCLIENT(self)
2801         {
2802                 if(self.classname == "spectator")
2803                 {
2804                         if(self.enemy.typehitsound)
2805                                 self.typehit_time = time;
2806                         else if(self.enemy.hitsound)
2807                                 self.hit_time = time;
2808                 }
2809                 else
2810                 {
2811                         if(self.typehitsound)
2812                                 self.typehit_time = time;
2813                         else if(self.hitsound)
2814                                 self.hit_time = time;
2815                 }
2816         }
2817         altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2818         // add 1 frametime because after this, engine SV_Physics
2819         // increases time by a frametime and then networks the frame
2820         // add another frametime because client shows everything with
2821         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2822         // needed!
2823         FOR_EACH_CLIENT(self)
2824         {
2825                 self.hitsound = FALSE;
2826                 self.typehitsound = FALSE;
2827                 antilag_record(self, altime);
2828         }
2829 }
2830
2831
2832 /*
2833  * RedirectionThink:
2834  * returns TRUE if redirecting
2835  */
2836 float redirection_timeout;
2837 float redirection_nextthink;
2838 float RedirectionThink()
2839 {
2840         float clients_found;
2841
2842         if(redirection_target == "")
2843                 return FALSE;
2844
2845         if(!redirection_timeout)
2846         {
2847                 cvar_set("sv_public", "-2");
2848                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2849                 if(redirection_target == "self")
2850                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2851                 else
2852                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2853         }
2854
2855         if(time < redirection_nextthink)
2856                 return TRUE;
2857
2858         redirection_nextthink = time + 1;
2859
2860         clients_found = 0;
2861         FOR_EACH_REALCLIENT(self)
2862         {
2863                 // TODO add timer
2864                 print("Redirecting: sending connect command to ", self.netname, "\n");
2865                 if(redirection_target == "self")
2866                         stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2867                 else
2868                         stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2869                 ++clients_found;
2870         }
2871
2872         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2873
2874         if(time > redirection_timeout || clients_found == 0)
2875                 localcmd("\nwait; wait; wait; quit\n");
2876
2877         return TRUE;
2878 }
2879
2880 void TargetMusic_RestoreGame();
2881 void RestoreGame()
2882 {
2883         // Loaded from a save game
2884         // some things then break, so let's work around them...
2885
2886         // Progs DB (capture records)
2887         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2888
2889         // Mapinfo
2890         MapInfo_Shutdown();
2891         MapInfo_Enumerate();
2892         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2893         WeaponStats_Init();
2894
2895         TargetMusic_RestoreGame();
2896 }
2897
2898 void Shutdown()
2899 {
2900         entity e;
2901
2902         gameover = 2;
2903
2904         if(world_initialized > 0)
2905         {
2906                 world_initialized = 0;
2907                 print("Saving persistent data...\n");
2908                 Ban_SaveBans();
2909
2910                 PlayerStats_EndMatch(0);
2911                 FOR_EACH_CLIENT(e)
2912                         PlayerStats_AddGlobalInfo(e);
2913                 PlayerStats_Shutdown();
2914
2915                 if(!cheatcount_total)
2916                 {
2917                         if(autocvar_sv_db_saveasdump)
2918                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2919                         else
2920                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2921                 }
2922                 if(autocvar_developer)
2923                 {
2924                         if(autocvar_sv_db_saveasdump)
2925                                 db_dump(TemporaryDB, "server-temp.db");
2926                         else
2927                                 db_save(TemporaryDB, "server-temp.db");
2928                 }
2929                 CheatShutdown(); // must be after cheatcount check
2930                 db_close(ServerProgsDB);
2931                 db_close(TemporaryDB);
2932                 print("done!\n");
2933                 // tell the bot system the game is ending now
2934                 bot_endgame();
2935
2936                 WeaponStats_Shutdown();
2937                 MapInfo_Shutdown();
2938         }
2939         else if(world_initialized == 0)
2940         {
2941                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2942         }
2943 }