Split the gamelog code out of miscfunctions and into its own file
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 #include "g_world.qh"
2
3 #include "anticheat.qh"
4 #include "antilag.qh"
5 #include "bot/api.qh"
6 #include "campaign.qh"
7 #include "cheats.qh"
8 #include "client.qh"
9 #include "command/common.qh"
10 #include "command/getreplies.qh"
11 #include "command/sv_cmd.qh"
12 #include "command/vote.qh"
13 #include "g_hook.qh"
14 #include <server/gamelog.qh>
15 #include "ipban.qh"
16 #include "mapvoting.qh"
17 #include <server/mutators/_mod.qh>
18 #include "race.qh"
19 #include "scores.qh"
20 #include "scores_rules.qh"
21 #include "teamplay.qh"
22 #include "weapons/weaponstats.qh"
23 #include "../common/constants.qh"
24 #include <common/net_linked.qh>
25 #include "../common/deathtypes/all.qh"
26 #include "../common/gamemodes/sv_rules.qh"
27 #include "../common/mapinfo.qh"
28 #include "../common/monsters/_mod.qh"
29 #include "../common/monsters/sv_monsters.qh"
30 #include "../common/vehicles/all.qh"
31 #include "../common/notifications/all.qh"
32 #include "../common/physics/player.qh"
33 #include "../common/playerstats.qh"
34 #include "../common/stats.qh"
35 #include "../common/teams.qh"
36 #include "../common/mapobjects/trigger/secret.qh"
37 #include "../common/mapobjects/target/music.qh"
38 #include "../common/util.qh"
39 #include "../common/items/_mod.qh"
40 #include <common/weapons/_all.qh>
41 #include "../common/state.qh"
42
43 const float LATENCY_THINKRATE = 10;
44 .float latency_sum;
45 .float latency_cnt;
46 .float latency_time;
47 entity pingplreport;
48 void PingPLReport_Think(entity this)
49 {
50         float delta;
51         entity e;
52
53         delta = 3 / maxclients;
54         if(delta < sys_frametime)
55                 delta = 0;
56         this.nextthink = time + delta;
57
58         e = edict_num(this.cnt + 1);
59         if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
60         {
61                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
62                 WriteByte(MSG_BROADCAST, this.cnt);
63                 WriteShort(MSG_BROADCAST, bound(1, CS(e).ping, 65535));
64                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
65                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
66
67                 // record latency times for clients throughout the match so we can report it to playerstats
68                 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
69                 {
70                         CS(e).latency_sum += CS(e).ping;
71                         CS(e).latency_cnt += 1;
72                         CS(e).latency_time = time;
73                         //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
74                 }
75         }
76         else
77         {
78                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
79                 WriteByte(MSG_BROADCAST, this.cnt);
80                 WriteShort(MSG_BROADCAST, 0);
81                 WriteByte(MSG_BROADCAST, 0);
82                 WriteByte(MSG_BROADCAST, 0);
83         }
84         this.cnt = (this.cnt + 1) % maxclients;
85 }
86 void PingPLReport_Spawn()
87 {
88         pingplreport = new_pure(pingplreport);
89         setthink(pingplreport, PingPLReport_Think);
90         pingplreport.nextthink = time;
91 }
92
93 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
94 string redirection_target;
95 float world_initialized;
96
97 void SetDefaultAlpha()
98 {
99         if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
100         {
101                 default_player_alpha = autocvar_g_player_alpha;
102                 if(default_player_alpha == 0)
103                         default_player_alpha = 1;
104                 default_weapon_alpha = default_player_alpha;
105         }
106 }
107
108 void GotoFirstMap(entity this)
109 {
110         float n;
111         if(autocvar__sv_init)
112         {
113                 // cvar_set("_sv_init", "0");
114                 // we do NOT set this to 0 any more, so someone "accidentally" changing
115                 // to this "init" map on a dedicated server will cause no permanent
116                 // harm
117                 if(autocvar_g_maplist_shuffle)
118                         ShuffleMaplist();
119                 n = tokenizebyseparator(autocvar_g_maplist, " ");
120                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
121
122                 MapInfo_Enumerate();
123                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
124
125                 if(!DoNextMapOverride(1))
126                         GotoNextMap(1);
127
128                 return;
129         }
130
131         if(time < 5)
132         {
133                 this.nextthink = time;
134         }
135         else
136         {
137                 this.nextthink = time + 1;
138                 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
139         }
140 }
141
142 void cvar_changes_init()
143 {
144         float h;
145         string k, v, d;
146         float n, i, adding, pureadding;
147
148         strfree(cvar_changes);
149         strfree(cvar_purechanges);
150         cvar_purechanges_count = 0;
151
152         h = buf_create();
153         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
154         n = buf_getsize(h);
155
156         adding = true;
157         pureadding = true;
158
159         for(i = 0; i < n; ++i)
160         {
161                 k = bufstr_get(h, i);
162
163 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
164 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
165 #define BADCVAR(p) if(k == p) continue
166
167                 // general excludes and namespaces for server admin used cvars
168                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
169
170                 // internal
171                 BADPREFIX("csqc_");
172                 BADPREFIX("cvar_check_");
173                 BADCVAR("gamecfg");
174                 BADCVAR("g_configversion");
175                 BADCVAR("halflifebsp");
176                 BADCVAR("sv_mapformat_is_quake2");
177                 BADCVAR("sv_mapformat_is_quake3");
178                 BADPREFIX("sv_world");
179
180                 // client
181                 BADPREFIX("chase_");
182                 BADPREFIX("cl_");
183                 BADPREFIX("con_");
184                 BADPREFIX("scoreboard_");
185                 BADPREFIX("g_campaign");
186                 BADPREFIX("g_waypointsprite_");
187                 BADPREFIX("gl_");
188                 BADPREFIX("joy");
189                 BADPREFIX("hud_");
190                 BADPREFIX("m_");
191                 BADPREFIX("menu_");
192                 BADPREFIX("net_slist_");
193                 BADPREFIX("r_");
194                 BADPREFIX("sbar_");
195                 BADPREFIX("scr_");
196                 BADPREFIX("snd_");
197                 BADPREFIX("show");
198                 BADPREFIX("sensitivity");
199                 BADPREFIX("userbind");
200                 BADPREFIX("v_");
201                 BADPREFIX("vid_");
202                 BADPREFIX("crosshair");
203                 BADCVAR("mod_q3bsp_lightmapmergepower");
204                 BADCVAR("mod_q3bsp_nolightmaps");
205                 BADCVAR("fov");
206                 BADCVAR("mastervolume");
207                 BADCVAR("volume");
208                 BADCVAR("bgmvolume");
209                 BADCVAR("in_pitch_min");
210                 BADCVAR("in_pitch_max");
211
212                 // private
213                 BADCVAR("developer");
214                 BADCVAR("log_dest_udp");
215                 BADCVAR("net_address");
216                 BADCVAR("net_address_ipv6");
217                 BADCVAR("port");
218                 BADCVAR("savedgamecfg");
219                 BADCVAR("serverconfig");
220                 BADCVAR("sv_autoscreenshot");
221                 BADCVAR("sv_heartbeatperiod");
222                 BADCVAR("sv_vote_master_password");
223                 BADCVAR("sys_colortranslation");
224                 BADCVAR("sys_specialcharactertranslation");
225                 BADCVAR("timeformat");
226                 BADCVAR("timestamps");
227                 BADCVAR("g_require_stats");
228                 BADPREFIX("developer_");
229                 BADPREFIX("g_ban_");
230                 BADPREFIX("g_banned_list");
231                 BADPREFIX("g_require_stats_");
232                 BADPREFIX("g_chat_flood_");
233                 BADPREFIX("g_ghost_items");
234                 BADPREFIX("g_playerstats_");
235                 BADPREFIX("g_voice_flood_");
236                 BADPREFIX("log_file");
237                 BADPREFIX("quit_");
238                 BADPREFIX("rcon_");
239                 BADPREFIX("sv_allowdownloads");
240                 BADPREFIX("sv_autodemo");
241                 BADPREFIX("sv_curl_");
242                 BADPREFIX("sv_eventlog");
243                 BADPREFIX("sv_logscores_");
244                 BADPREFIX("sv_master");
245                 BADPREFIX("sv_weaponstats_");
246                 BADPREFIX("sv_waypointsprite_");
247                 BADCVAR("rescan_pending");
248
249                 // these can contain player IDs, so better hide
250                 BADPREFIX("g_forced_team_");
251                 BADCVAR("sv_muteban_list");
252                 BADCVAR("sv_voteban_list");
253                 BADCVAR("sv_allow_customplayermodels_idlist");
254                 BADCVAR("sv_allow_customplayermodels_speciallist");
255
256                 // mapinfo
257                 BADCVAR("fraglimit");
258                 BADCVAR("g_arena");
259                 BADCVAR("g_assault");
260                 BADCVAR("g_ca");
261                 BADCVAR("g_ca_teams");
262                 BADCVAR("g_conquest");
263                 BADCVAR("g_ctf");
264                 BADCVAR("g_cts");
265                 BADCVAR("g_dotc");
266                 BADCVAR("g_dm");
267                 BADCVAR("g_domination");
268                 BADCVAR("g_domination_default_teams");
269                 BADCVAR("g_duel");
270                 BADCVAR("g_duel_not_dm_maps");
271                 BADCVAR("g_freezetag");
272                 BADCVAR("g_freezetag_teams");
273                 BADCVAR("g_invasion_teams");
274                 BADCVAR("g_invasion_type");
275                 BADCVAR("g_jailbreak");
276                 BADCVAR("g_jailbreak_teams");
277                 BADCVAR("g_keepaway");
278                 BADCVAR("g_keyhunt");
279                 BADCVAR("g_keyhunt_teams");
280                 BADCVAR("g_lms");
281                 BADCVAR("g_nexball");
282                 BADCVAR("g_onslaught");
283                 BADCVAR("g_race");
284                 BADCVAR("g_race_laps_limit");
285                 BADCVAR("g_race_qualifying_timelimit");
286                 BADCVAR("g_race_qualifying_timelimit_override");
287                 BADCVAR("g_runematch");
288                 BADCVAR("g_shootfromeye");
289                 BADCVAR("g_snafu");
290                 BADCVAR("g_tdm");
291                 BADCVAR("g_tdm_on_dm_maps");
292                 BADCVAR("g_tdm_teams");
293                 BADCVAR("g_vip");
294                 BADCVAR("leadlimit");
295                 BADCVAR("nextmap");
296                 BADCVAR("teamplay");
297                 BADCVAR("timelimit");
298                 BADCVAR("g_mapinfo_settemp_acl");
299                 BADCVAR("g_mapinfo_ignore_warnings");
300                 BADCVAR("g_maplist_ignore_sizes");
301                 BADCVAR("g_maplist_sizes_count_bots");
302
303                 // long
304                 BADCVAR("hostname");
305                 BADCVAR("g_maplist");
306                 BADCVAR("g_maplist_mostrecent");
307                 BADCVAR("sv_motd");
308
309                 v = cvar_string(k);
310                 d = cvar_defstring(k);
311                 if(v == d)
312                         continue;
313
314                 if(adding)
315                 {
316                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
317                         if(strlen(cvar_changes) > 16384)
318                         {
319                                 cvar_changes = "// too many settings have been changed to show them here\n";
320                                 adding = 0;
321                         }
322                 }
323
324                 // now check if the changes are actually gameplay relevant
325
326                 // does nothing gameplay relevant
327                 BADCVAR("captureleadlimit_override");
328                 BADCVAR("condump_stripcolors");
329                 BADCVAR("gameversion");
330                 BADCVAR("fs_gamedir");
331                 BADCVAR("g_allow_oldvortexbeam");
332                 BADCVAR("g_balance_kill_delay");
333                 BADCVAR("g_buffs_pickup_anyway");
334                 BADCVAR("g_buffs_randomize");
335                 BADCVAR("g_buffs_randomize_teamplay");
336                 BADCVAR("g_campcheck_distance");
337                 BADCVAR("g_chatsounds");
338                 BADCVAR("g_ca_point_leadlimit");
339                 BADCVAR("g_ca_point_limit");
340                 BADCVAR("g_ctf_captimerecord_always");
341                 BADCVAR("g_ctf_flag_glowtrails");
342                 BADCVAR("g_ctf_dynamiclights");
343                 BADCVAR("g_ctf_flag_pickup_verbosename");
344                 BADPRESUFFIX("g_ctf_flag_", "_model");
345                 BADPRESUFFIX("g_ctf_flag_", "_skin");
346                 BADCVAR("g_domination_point_leadlimit");
347                 BADCVAR("g_forced_respawn");
348                 BADCVAR("g_freezetag_point_leadlimit");
349                 BADCVAR("g_freezetag_point_limit");
350                 BADCVAR("g_glowtrails");
351                 BADCVAR("g_hats");
352                 BADCVAR("g_casings");
353                 BADCVAR("g_invasion_point_limit");
354                 BADCVAR("g_jump_grunt");
355                 BADCVAR("g_keepaway_ballcarrier_effects");
356                 BADCVAR("g_keepawayball_effects");
357                 BADCVAR("g_keyhunt_point_leadlimit");
358                 BADCVAR("g_nexball_goalleadlimit");
359                 BADCVAR("g_new_toys_autoreplace");
360                 BADCVAR("g_new_toys_use_pickupsound");
361                 BADCVAR("g_physics_predictall");
362                 BADCVAR("g_piggyback");
363                 BADCVAR("g_playerclip_collisions");
364                 BADCVAR("g_spawn_alloweffects");
365                 BADCVAR("g_tdm_point_leadlimit");
366                 BADCVAR("g_tdm_point_limit");
367                 BADCVAR("leadlimit_and_fraglimit");
368                 BADCVAR("leadlimit_override");
369                 BADCVAR("pausable");
370                 BADCVAR("sv_announcer");
371                 BADCVAR("sv_checkforpacketsduringsleep");
372                 BADCVAR("sv_damagetext");
373                 BADCVAR("sv_db_saveasdump");
374                 BADCVAR("sv_intermission_cdtrack");
375                 BADCVAR("sv_mapchange_delay");
376                 BADCVAR("sv_minigames");
377                 BADCVAR("sv_namechangetimer");
378                 BADCVAR("sv_precacheplayermodels");
379                 BADCVAR("sv_radio");
380                 BADCVAR("sv_stepheight");
381                 BADCVAR("sv_timeout");
382                 BADCVAR("sv_weapons_modeloverride");
383                 BADCVAR("w_prop_interval");
384                 BADPREFIX("chat_");
385                 BADPREFIX("crypto_");
386                 BADPREFIX("gameversion_");
387                 BADPREFIX("g_chat_");
388                 BADPREFIX("g_ctf_captimerecord_");
389                 BADPREFIX("g_hats_");
390                 BADPREFIX("g_maplist_");
391                 BADPREFIX("g_mod_");
392                 BADPREFIX("g_respawn_");
393                 BADPREFIX("net_");
394                 BADPREFIX("notification_");
395                 BADPREFIX("prvm_");
396                 BADPREFIX("skill_");
397                 BADPREFIX("sv_allow_");
398                 BADPREFIX("sv_cullentities_");
399                 BADPREFIX("sv_maxidle_");
400                 BADPREFIX("sv_minigames_");
401                 BADPREFIX("sv_radio_");
402                 BADPREFIX("sv_timeout_");
403                 BADPREFIX("sv_vote_");
404                 BADPREFIX("timelimit_");
405
406                 // allowed changes to server admins (please sync this to server.cfg)
407                 // vi commands:
408                 //   :/"impure"/,$d
409                 //   :g!,^\/\/[^ /],d
410                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
411                 //   :%!sort
412                 // yes, this does contain some redundant stuff, don't really care
413                 BADPREFIX("bot_ai_");
414                 BADCVAR("bot_config_file");
415                 BADCVAR("bot_number");
416                 BADCVAR("bot_prefix");
417                 BADCVAR("bot_suffix");
418                 BADCVAR("capturelimit_override");
419                 BADCVAR("fraglimit_override");
420                 BADCVAR("gametype");
421                 BADCVAR("g_antilag");
422                 BADCVAR("g_balance_teams");
423                 BADCVAR("g_balance_teams_prevent_imbalance");
424                 BADCVAR("g_balance_teams_scorefactor");
425                 BADCVAR("g_ban_sync_trusted_servers");
426                 BADCVAR("g_ban_sync_uri");
427                 BADCVAR("g_buffs");
428                 BADCVAR("g_ca_teams_override");
429                 BADCVAR("g_ctf_fullbrightflags");
430                 BADCVAR("g_ctf_ignore_frags");
431                 BADCVAR("g_ctf_leaderboard");
432                 BADCVAR("g_domination_point_limit");
433                 BADCVAR("g_domination_teams_override");
434                 BADCVAR("g_freezetag_teams_override");
435                 BADCVAR("g_friendlyfire");
436                 BADCVAR("g_fullbrightitems");
437                 BADCVAR("g_fullbrightplayers");
438                 BADCVAR("g_keyhunt_point_limit");
439                 BADCVAR("g_keyhunt_teams_override");
440                 BADCVAR("g_lms_lives_override");
441                 BADCVAR("g_maplist");
442                 BADCVAR("g_maxplayers");
443                 BADCVAR("g_mirrordamage");
444                 BADCVAR("g_nexball_goallimit");
445                 BADCVAR("g_norecoil");
446                 BADCVAR("g_physics_clientselect");
447                 BADCVAR("g_pinata");
448                 BADCVAR("g_powerups");
449                 BADCVAR("g_player_brightness");
450                 BADCVAR("g_rocket_flying");
451                 BADCVAR("g_rocket_flying_disabledelays");
452                 BADCVAR("g_spawnshieldtime");
453                 BADCVAR("g_start_delay");
454                 BADCVAR("g_superspectate");
455                 BADCVAR("g_tdm_teams_override");
456                 BADCVAR("g_warmup");
457                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
458                 BADCVAR("hostname");
459                 BADCVAR("log_file");
460                 BADCVAR("maxplayers");
461                 BADCVAR("minplayers");
462                 BADCVAR("minplayers_per_team");
463                 BADCVAR("net_address");
464                 BADCVAR("port");
465                 BADCVAR("rcon_password");
466                 BADCVAR("rcon_restricted_commands");
467                 BADCVAR("rcon_restricted_password");
468                 BADCVAR("skill");
469                 BADCVAR("sv_adminnick");
470                 BADCVAR("sv_autoscreenshot");
471                 BADCVAR("sv_autotaunt");
472                 BADCVAR("sv_curl_defaulturl");
473                 BADCVAR("sv_defaultcharacter");
474                 BADCVAR("sv_defaultcharacterskin");
475                 BADCVAR("sv_defaultplayercolors");
476                 BADCVAR("sv_defaultplayermodel");
477                 BADCVAR("sv_defaultplayerskin");
478                 BADCVAR("sv_maxidle");
479                 BADCVAR("sv_maxrate");
480                 BADCVAR("sv_motd");
481                 BADCVAR("sv_public");
482                 BADCVAR("sv_ready_restart");
483                 BADCVAR("sv_status_privacy");
484                 BADCVAR("sv_taunt");
485                 BADCVAR("sv_vote_call");
486                 BADCVAR("sv_vote_commands");
487                 BADCVAR("sv_vote_majority_factor");
488                 BADCVAR("sv_vote_master");
489                 BADCVAR("sv_vote_master_commands");
490                 BADCVAR("sv_vote_master_password");
491                 BADCVAR("sv_vote_simple_majority_factor");
492                 BADCVAR("teamplay_mode");
493                 BADCVAR("timelimit_override");
494                 BADPREFIX("g_warmup_");
495                 BADPREFIX("sv_info_");
496                 BADPREFIX("sv_ready_restart_");
497
498                 // mutators that announce themselves properly to the server browser
499                 BADCVAR("g_instagib");
500                 BADCVAR("g_new_toys");
501                 BADCVAR("g_nix");
502                 BADCVAR("g_grappling_hook");
503                 BADCVAR("g_jetpack");
504
505                 // temporary for testing
506                 // TODO remove before 0.8.3 release
507                 BADCVAR("g_ca_weaponarena");
508                 BADCVAR("g_freezetag_weaponarena");
509                 BADCVAR("g_lms_weaponarena");
510                 BADCVAR("g_ctf_stalemate_time");
511
512                 if(cvar_string("g_mod_balance") == "Testing")
513                 {
514                         // (temporary) while using the Testing balance, any weapon balance cvars are allowed to be changed
515                         BADPREFIX("g_balance_");
516                 }
517
518 #undef BADPRESUFFIX
519 #undef BADPREFIX
520 #undef BADCVAR
521
522                 if(pureadding)
523                 {
524                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
525                         if(strlen(cvar_purechanges) > 16384)
526                         {
527                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
528                                 pureadding = 0;
529                         }
530                 }
531                 ++cvar_purechanges_count;
532                 // WARNING: this variable is used for the server list
533                 // NEVER dare to skip this code!
534                 // Hacks to intentionally appearing as "pure server" even though you DO have
535                 // modified settings may be punished by removal from the server list.
536                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
537                 // though.
538         }
539         buf_del(h);
540         if(cvar_changes == "")
541                 cvar_changes = "// this server runs at default server settings\n";
542         else
543                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
544         cvar_changes = strzone(cvar_changes);
545         if(cvar_purechanges == "")
546                 cvar_purechanges = "// this server runs at default gameplay settings\n";
547         else
548                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
549         cvar_purechanges = strzone(cvar_purechanges);
550 }
551
552 entity randomseed;
553 bool RandomSeed_Send(entity this, entity to, int sf)
554 {
555         WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
556         WriteShort(MSG_ENTITY, this.cnt);
557         return true;
558 }
559 void RandomSeed_Think(entity this)
560 {
561         this.cnt = bound(0, floor(random() * 65536), 65535);
562         this.nextthink = time + 5;
563
564         this.SendFlags |= 1;
565 }
566 void RandomSeed_Spawn()
567 {
568         randomseed = new_pure(randomseed);
569         setthink(randomseed, RandomSeed_Think);
570         Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
571
572         getthink(randomseed)(randomseed); // sets random seed and nextthink
573 }
574
575 spawnfunc(__init_dedicated_server)
576 {
577         // handler for _init/_init map (only for dedicated server initialization)
578
579         world_initialized = -1; // don't complain
580
581         delete_fn = remove_unsafely;
582
583         entity e = spawn();
584         setthink(e, GotoFirstMap);
585         e.nextthink = time; // this is usually 1 at this point
586
587         e = new(info_player_deathmatch);  // safeguard against player joining
588
589     // assign reflectively to avoid "assignment to world" warning
590     for (int i = 0, n = numentityfields(); i < n; ++i) {
591         string k = entityfieldname(i);
592         if (k == "classname") {
593             // safeguard against various stuff ;)
594             putentityfieldstring(i, this, "worldspawn");
595             break;
596         }
597     }
598
599         // needs to be done so early because of the constants they create
600         static_init();
601         static_init_late();
602         static_init_precache();
603
604         IL_PUSH(g_spawnpoints, e); // just incase
605
606         MapInfo_Enumerate();
607         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
608 }
609
610 void __init_dedicated_server_shutdown() {
611         MapInfo_Shutdown();
612 }
613
614 STATIC_INIT_EARLY(maxclients)
615 {
616         maxclients = 0;
617         for (entity head = nextent(NULL); head; head = nextent(head)) {
618                 ++maxclients;
619         }
620 }
621
622 void default_delayedinit(entity this)
623 {
624         if(!scores_initialized)
625                 ScoreRules_generic();
626 }
627
628 void InitGameplayMode()
629 {
630         VoteReset();
631
632         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
633         get_mi_min_max(1);
634         // assign reflectively to avoid "assignment to world" warning
635         int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
636             string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
637             if (v) {
638             putentityfieldstring(i, world, sprintf("%v", v));
639             if (++done == 2) break;
640         }
641         }
642         // currently, NetRadiant's limit is 131072 qu for each side
643         // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
644         // set the distance according to map size but don't go over the limit to avoid issues with float precision
645         // in case somebody makes extremely large maps
646         max_shot_distance = min(230000, vlen(world.maxs - world.mins));
647
648         MapInfo_LoadMapSettings(mapname);
649         GameRules_teams(false);
650
651         if (!cvar_value_issafe(world.fog))
652         {
653                 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
654                 world.fog = string_null;
655         }
656         if(MapInfo_Map_fog != "")
657         {
658                 if(MapInfo_Map_fog == "none")
659                         world.fog = string_null;
660                 else
661                         world.fog = strzone(MapInfo_Map_fog);
662         }
663         clientstuff = strzone(MapInfo_Map_clientstuff);
664
665         MapInfo_ClearTemps();
666
667         gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
668
669         cache_mutatormsg = strzone("");
670         cache_lastmutatormsg = strzone("");
671
672         InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
673 }
674
675 void Map_MarkAsRecent(string m);
676 float world_already_spawned;
677 spawnfunc(worldspawn)
678 {
679         server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
680
681         bool wantrestart = false;
682         {
683                 if (!server_is_dedicated)
684                 {
685                         // force unloading of server pk3 files when starting a listen server
686                         // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
687                         // restore csqc_progname too
688                         string expect = "csprogs.dat";
689                         wantrestart = cvar_string("csqc_progname") != expect;
690                         cvar_set("csqc_progname", expect);
691                 }
692                 else
693                 {
694                         // Try to use versioned csprogs from pk3
695                         // Only ever use versioned csprogs.dat files on dedicated servers;
696                         // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
697                         string pk3csprogs = "csprogs-" WATERMARK ".dat";
698                         // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
699                         string select = "csprogs.dat";
700                         if (fexists(pk3csprogs)) select = pk3csprogs;
701                         if (cvar_string("csqc_progname") != select)
702                         {
703                                 cvar_set("csqc_progname", select);
704                                 wantrestart = true;
705                         }
706                         // Check for updates on startup
707                         // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
708                         int sentinel = fopen("progs.txt", FILE_READ);
709                         if (sentinel >= 0)
710                         {
711                                 string switchversion = fgets(sentinel);
712                                 fclose(sentinel);
713                                 if (switchversion != "" && switchversion != WATERMARK)
714                                 {
715                                         LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
716                                         // if it doesn't exist, assume either:
717                                         //   a) the current program was overwritten
718                                         //   b) this is a client only update
719                                         string newprogs = sprintf("progs-%s.dat", switchversion);
720                                         if (fexists(newprogs))
721                                         {
722                                                 cvar_set("sv_progs", newprogs);
723                                                 wantrestart = true;
724                                         }
725                                         string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
726                                         if (fexists(newcsprogs))
727                                         {
728                                                 cvar_set("csqc_progname", newcsprogs);
729                                                 wantrestart = true;
730                                         }
731                                 }
732                         }
733                 }
734                 if (wantrestart)
735                 {
736                         LOG_INFO("Restart requested");
737                         changelevel(mapname);
738                         // let initialization continue, shutdown depends on it
739                 }
740         }
741
742         if(world_already_spawned)
743                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
744         world_already_spawned = true;
745
746         delete_fn = remove_safely; // during spawning, watch what you remove!
747
748         cvar_changes_init(); // do this very early now so it REALLY matches the server config
749
750         // needs to be done so early because of the constants they create
751         static_init();
752
753         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
754
755         TemporaryDB = db_create();
756
757         // 0 normal
758         lightstyle(0, "m");
759
760         // 1 FLICKER (first variety)
761         lightstyle(1, "mmnmmommommnonmmonqnmmo");
762
763         // 2 SLOW STRONG PULSE
764         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
765
766         // 3 CANDLE (first variety)
767         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
768
769         // 4 FAST STROBE
770         lightstyle(4, "mamamamamama");
771
772         // 5 GENTLE PULSE 1
773         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
774
775         // 6 FLICKER (second variety)
776         lightstyle(6, "nmonqnmomnmomomno");
777
778         // 7 CANDLE (second variety)
779         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
780
781         // 8 CANDLE (third variety)
782         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
783
784         // 9 SLOW STROBE (fourth variety)
785         lightstyle(9, "aaaaaaaazzzzzzzz");
786
787         // 10 FLUORESCENT FLICKER
788         lightstyle(10, "mmamammmmammamamaaamammma");
789
790         // 11 SLOW PULSE NOT FADE TO BLACK
791         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
792
793         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
794
795         // 63 testing
796         lightstyle(63, "a");
797
798         if(autocvar_g_campaign)
799                 CampaignPreInit();
800
801         Map_MarkAsRecent(mapname);
802
803         PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
804
805         InitGameplayMode();
806         static_init_late();
807         static_init_precache();
808         readlevelcvars();
809         GrappleHookInit();
810
811         GameRules_limit_fallbacks();
812
813         if(warmup_limit == 0)
814                 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
815
816         player_count = 0;
817         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
818         if(bot_waypoints_for_items == 1)
819                 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
820                         bot_waypoints_for_items = 0;
821
822         WaypointSprite_Init();
823
824         GameLogInit(); // prepare everything
825         // NOTE for matchid:
826         // changing the logic generating it is okay. But:
827         // it HAS to stay <= 64 chars
828         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
829         if(autocvar_sv_eventlog)
830         {
831                 string s = sprintf("%s.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
832                 matchid = strzone(s);
833
834                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
835                 s = ":gameinfo:mutators:LIST";
836
837                 MUTATOR_CALLHOOK(BuildMutatorsString, s);
838                 s = M_ARGV(0, string);
839
840                 // initialiation stuff, not good in the mutator system
841                 if(!autocvar_g_use_ammunition)
842                         s = strcat(s, ":no_use_ammunition");
843
844                 // initialiation stuff, not good in the mutator system
845                 if(autocvar_g_pickup_items == 0)
846                         s = strcat(s, ":no_pickup_items");
847                 if(autocvar_g_pickup_items > 0)
848                         s = strcat(s, ":pickup_items");
849
850                 // initialiation stuff, not good in the mutator system
851                 if(autocvar_g_weaponarena != "0")
852                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
853
854                 // TODO to mutator system
855                 if(autocvar_g_norecoil)
856                         s = strcat(s, ":norecoil");
857
858                 // TODO to mutator system
859                 if(autocvar_g_powerups == 0)
860                         s = strcat(s, ":no_powerups");
861                 if(autocvar_g_powerups > 0)
862                         s = strcat(s, ":powerups");
863
864                 GameLogEcho(s);
865                 GameLogEcho(":gameinfo:end");
866         }
867         else
868                 matchid = strzone(ftos(random()));
869
870         cvar_set("nextmap", "");
871
872         SetDefaultAlpha();
873
874         if(autocvar_g_campaign)
875                 CampaignPostInit();
876
877         Ban_LoadBans();
878
879         MapInfo_Enumerate();
880         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
881
882         if(fexists(strcat("scripts/", mapname, ".arena")))
883                 cvar_settemp("sv_q3acompat_machineshotgunswap", "1");
884
885         if(fexists(strcat("scripts/", mapname, ".defi")))
886                 cvar_settemp("sv_q3defragcompat", "1");
887
888         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
889         {
890                 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
891                 if(fd != -1)
892                 {
893                         string s;
894                         while((s = fgets(fd)))
895                         {
896                                 int l = tokenize_console(s);
897                                 if(l < 2)
898                                         continue;
899                                 if(argv(0) == "cd")
900                                 {
901                                         string trackname = argv(2);
902                                         LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
903                                         LOG_INFO("  cdtrack ", trackname);
904                                         if (cvar_value_issafe(trackname))
905                                         {
906                                                 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
907                                                 strcpy(clientstuff, newstuff);
908                                         }
909                                 }
910                                 else if(argv(0) == "fog")
911                                 {
912                                         LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
913                                         LOG_INFO("  \"fog\" \"", s, "\"");
914                                 }
915                                 else if(argv(0) == "set")
916                                 {
917                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
918                                         LOG_INFO("  clientsettemp_for_type all ", argv(1), " ", argv(2));
919                                 }
920                                 else if(argv(0) != "//")
921                                 {
922                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
923                                         LOG_INFO("  clientsettemp_for_type all ", argv(0), " ", argv(1));
924                                 }
925                         }
926                         fclose(fd);
927                 }
928         }
929
930         WeaponStats_Init();
931
932         Nagger_Init();
933
934         next_pingtime = time + 5;
935
936         // set up information replies for clients and server to use
937         maplist_reply = strzone(getmaplist());
938         lsmaps_reply = strzone(getlsmaps());
939         monsterlist_reply = strzone(getmonsterlist());
940         for(int i = 0; i < 10; ++i)
941         {
942                 string s = getrecords(i);
943                 if (s)
944                         records_reply[i] = strzone(s);
945         }
946         ladder_reply = strzone(getladder());
947         rankings_reply = strzone(getrankings());
948
949         // begin other init
950         ClientInit_Spawn();
951         RandomSeed_Spawn();
952         PingPLReport_Spawn();
953
954         CheatInit();
955
956         if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
957
958         // fill sv_curl_serverpackages from .serverpackage files
959         if (autocvar_sv_curl_serverpackages_auto)
960         {
961                 string s = "csprogs-" WATERMARK ".txt";
962                 // remove automatically managed files from the list to prevent duplicates
963                 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
964                 {
965                         string pkg = argv(i);
966                         if (startsWith(pkg, "csprogs-")) continue;
967                         if (endsWith(pkg, "-serverpackage.txt")) continue;
968                         if (endsWith(pkg, ".serverpackage")) continue;  // OLD legacy
969                         s = cons(s, pkg);
970                 }
971                 // add automatically managed files to the list
972                 #define X(match) MACRO_BEGIN \
973                         int fd = search_begin(match, true, false); \
974                         if (fd >= 0) \
975                         { \
976                                 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
977                                 { \
978                                         s = cons(s, search_getfilename(fd, i)); \
979                                 } \
980                                 search_end(fd); \
981                         } \
982                 MACRO_END
983                 X("*-serverpackage.txt");
984                 X("*.serverpackage");
985                 #undef X
986                 cvar_set("sv_curl_serverpackages", s);
987         }
988
989         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
990         modname = "Xonotic";
991         // physics/balance/config changes that count as mod
992         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
993                 modname = cvar_string("g_mod_physics");
994         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
995                 modname = cvar_string("g_mod_balance");
996         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
997                 modname = cvar_string("g_mod_config");
998         // extra mutators that deserve to count as mod
999         MUTATOR_CALLHOOK(SetModname, modname);
1000         modname = M_ARGV(0, string);
1001
1002         // save it for later
1003         modname = strzone(modname);
1004
1005         WinningConditionHelper(this); // set worldstatus
1006
1007         world_initialized = 1;
1008         __spawnfunc_spawn_all();
1009 }
1010
1011 spawnfunc(light)
1012 {
1013         //makestatic (this); // Who the f___ did that?
1014         delete(this);
1015 }
1016
1017 string GetGametype()
1018 {
1019         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
1020 }
1021
1022 string GetMapname()
1023 {
1024         return mapname;
1025 }
1026
1027 float Map_Count, Map_Current;
1028 string Map_Current_Name;
1029
1030 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
1031 int GetMaplistPosition()
1032 {
1033         string map = GetMapname();
1034         int idx = autocvar_g_maplist_index;
1035
1036         if(idx >= 0)
1037         {
1038                 if(idx < Map_Count)
1039                 {
1040                         if(map == argv(idx))
1041                         {
1042                                 return idx;
1043                         }
1044                 }
1045         }
1046
1047         for(int pos = 0; pos < Map_Count; ++pos)
1048         {
1049                 if(map == argv(pos))
1050                         return pos;
1051         }
1052
1053         // resume normal maplist rotation if current map is not in g_maplist
1054         return idx;
1055 }
1056
1057 bool MapHasRightSize(string map)
1058 {
1059         int minplayers = max(0, floor(autocvar_minplayers));
1060         if (teamplay)
1061                 minplayers = max(0, floor(autocvar_minplayers_per_team) * AvailableTeams());
1062         if (autocvar_g_maplist_check_waypoints
1063                 && (currentbots || autocvar_bot_number || player_count < minplayers))
1064         {
1065                 string checkwp_msg = strcat("checkwp ", map);
1066                 if(!fexists(strcat("maps/", map, ".waypoints")))
1067                 {
1068                         LOG_TRACE(checkwp_msg, ": no waypoints");
1069                         return false;
1070                 }
1071                 LOG_TRACE(checkwp_msg, ": has waypoints");
1072         }
1073
1074         if(autocvar_g_maplist_ignore_sizes)
1075                 return true;
1076
1077         // open map size restriction file
1078         string opensize_msg = strcat("opensize ", map);
1079         float fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1080         int player_limit = ((autocvar_g_maplist_sizes_count_maxplayers) ? GetPlayerLimit() : 0);
1081         int pcount = ((player_limit > 0) ? min(player_count, player_limit) : player_count); // bind it to the player limit so that forced spectators don't influence the limits
1082         if(!autocvar_g_maplist_sizes_count_bots)
1083                 pcount -= currentbots;
1084         if(fh >= 0)
1085         {
1086                 opensize_msg = strcat(opensize_msg, ": ok, ");
1087                 int mapmin = stoi(fgets(fh));
1088                 int mapmax = stoi(fgets(fh));
1089                 fclose(fh);
1090                 if(pcount < mapmin)
1091                 {
1092                         LOG_TRACE(opensize_msg, "not enough");
1093                         return false;
1094                 }
1095                 if(mapmax && pcount > mapmax)
1096                 {
1097                         LOG_TRACE(opensize_msg, "too many");
1098                         return false;
1099                 }
1100                 LOG_TRACE(opensize_msg, "right size");
1101                 return true;
1102         }
1103         LOG_TRACE(opensize_msg, ": not found");
1104         return true;
1105 }
1106
1107 string Map_Filename(float position)
1108 {
1109         return strcat("maps/", argv(position), ".bsp");
1110 }
1111
1112 void Map_MarkAsRecent(string m)
1113 {
1114         cvar_set("g_maplist_mostrecent", strwords(cons(m, autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1115 }
1116
1117 float Map_IsRecent(string m)
1118 {
1119         return strhasword(autocvar_g_maplist_mostrecent, m);
1120 }
1121
1122 float Map_Check(float position, float pass)
1123 {
1124         string filename;
1125         string map_next;
1126         map_next = argv(position);
1127         if(pass <= 1)
1128         {
1129                 if(Map_IsRecent(map_next))
1130                         return 0;
1131         }
1132         filename = Map_Filename(position);
1133         if(MapInfo_CheckMap(map_next))
1134         {
1135                 if(pass == 2)
1136                         return 1;
1137                 if(MapHasRightSize(map_next))
1138                         return 1;
1139                 return 0;
1140         }
1141         else
1142                 LOG_DEBUG( "Couldn't select '", filename, "'..." );
1143
1144         return 0;
1145 }
1146
1147 void Map_Goto_SetStr(string nextmapname)
1148 {
1149         if(getmapname_stored != "")
1150                 strunzone(getmapname_stored);
1151         if(nextmapname == "")
1152                 getmapname_stored = "";
1153         else
1154                 getmapname_stored = strzone(nextmapname);
1155 }
1156
1157 void Map_Goto_SetFloat(float position)
1158 {
1159         cvar_set("g_maplist_index", ftos(position));
1160         Map_Goto_SetStr(argv(position));
1161 }
1162
1163 void Map_Goto(float reinit)
1164 {
1165         MapInfo_LoadMap(getmapname_stored, reinit);
1166 }
1167
1168 // return codes of map selectors:
1169 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1170 //   -2 = permanent failure
1171 float MaplistMethod_Iterate() // usual method
1172 {
1173         float pass, i;
1174
1175         LOG_TRACE("Trying MaplistMethod_Iterate");
1176
1177         for(pass = 1; pass <= 2; ++pass)
1178         {
1179                 for(i = 1; i < Map_Count; ++i)
1180                 {
1181                         float mapindex;
1182                         mapindex = (i + Map_Current) % Map_Count;
1183                         if(Map_Check(mapindex, pass))
1184                                 return mapindex;
1185                 }
1186         }
1187         return -1;
1188 }
1189
1190 float MaplistMethod_Repeat() // fallback method
1191 {
1192         LOG_TRACE("Trying MaplistMethod_Repeat");
1193
1194         if(Map_Check(Map_Current, 2))
1195                 return Map_Current;
1196         return -2;
1197 }
1198
1199 float MaplistMethod_Random() // random map selection
1200 {
1201         float i, imax;
1202
1203         LOG_TRACE("Trying MaplistMethod_Random");
1204
1205         imax = 42;
1206
1207         for(i = 0; i <= imax; ++i)
1208         {
1209                 float mapindex;
1210                 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1211                 if(Map_Check(mapindex, 1))
1212                         return mapindex;
1213         }
1214         return -1;
1215 }
1216
1217 float MaplistMethod_Shuffle(float exponent) // more clever shuffling
1218 // the exponent sets a bias on the map selection:
1219 // the higher the exponent, the less likely "shortly repeated" same maps are
1220 {
1221         float i, j, imax, insertpos;
1222
1223         LOG_TRACE("Trying MaplistMethod_Shuffle");
1224
1225         imax = 42;
1226
1227         for(i = 0; i <= imax; ++i)
1228         {
1229                 string newlist;
1230
1231                 // now reinsert this at another position
1232                 insertpos = (random() ** (1 / exponent));       // ]0, 1]
1233                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1234                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1235                 LOG_TRACE("SHUFFLE: insert pos = ", ftos(insertpos));
1236
1237                 // insert the current map there
1238                 newlist = "";
1239                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1240                         newlist = strcat(newlist, " ", argv(j));
1241                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1242                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1243                         newlist = strcat(newlist, " ", argv(j));
1244                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1245                 cvar_set("g_maplist", newlist);
1246                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1247
1248                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1249                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1250                 if(Map_Check(Map_Current, 1))
1251                         return Map_Current;
1252         }
1253         return -1;
1254 }
1255
1256 void Maplist_Init()
1257 {
1258         float i = Map_Count = 0;
1259         if(autocvar_g_maplist != "")
1260         {
1261                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1262                 for (i = 0; i < Map_Count; ++i)
1263                 {
1264                         if (Map_Check(i, 2))
1265                                 break;
1266                 }
1267         }
1268
1269         if (i == Map_Count)
1270         {
1271                 bprint( "Maplist contains no usable maps!  Resetting it to default map list.\n" );
1272                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1273                 if(autocvar_g_maplist_shuffle)
1274                         ShuffleMaplist();
1275                 if(!server_is_dedicated)
1276                         localcmd("\nmenu_cmd sync\n");
1277                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1278         }
1279         if(Map_Count == 0)
1280                 error("empty maplist, cannot select a new map");
1281         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1282
1283         strcpy(Map_Current_Name, argv(Map_Current)); // will be automatically freed on exit thanks to DP
1284         // this may or may not be correct, but who cares, in the worst case a map
1285         // isn't chosen in the first pass that should have been
1286 }
1287
1288 string GetNextMap()
1289 {
1290         Maplist_Init();
1291         float nextMap = -1;
1292
1293         if(nextMap == -1)
1294                 if(autocvar_g_maplist_shuffle > 0)
1295                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1296
1297         if(nextMap == -1)
1298                 if(autocvar_g_maplist_selectrandom)
1299                         nextMap = MaplistMethod_Random();
1300
1301         if(nextMap == -1)
1302                 nextMap = MaplistMethod_Iterate();
1303
1304         if(nextMap == -1)
1305                 nextMap = MaplistMethod_Repeat();
1306
1307         if(nextMap >= 0)
1308         {
1309                 Map_Goto_SetFloat(nextMap);
1310                 return getmapname_stored;
1311         }
1312
1313         return "";
1314 }
1315
1316 float DoNextMapOverride(float reinit)
1317 {
1318         if(autocvar_g_campaign)
1319         {
1320                 CampaignPostIntermission();
1321                 alreadychangedlevel = true;
1322                 return true;
1323         }
1324         if(autocvar_quit_when_empty)
1325         {
1326                 if(player_count <= currentbots)
1327                 {
1328                         localcmd("quit\n");
1329                         alreadychangedlevel = true;
1330                         return true;
1331                 }
1332         }
1333         if(autocvar_quit_and_redirect != "")
1334         {
1335                 redirection_target = strzone(autocvar_quit_and_redirect);
1336                 alreadychangedlevel = true;
1337                 return true;
1338         }
1339         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1340         {
1341                 localcmd("restart\n");
1342                 alreadychangedlevel = true;
1343                 return true;
1344         }
1345         if(autocvar_nextmap != "")
1346         {
1347                 string m;
1348                 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1349                 cvar_set("nextmap",m);
1350
1351                 if(!m || gametypevote)
1352                         return false;
1353                 if(autocvar_sv_vote_gametype)
1354                 {
1355                         Map_Goto_SetStr(m);
1356                         return false;
1357                 }
1358
1359                 if(MapInfo_CheckMap(m))
1360                 {
1361                         Map_Goto_SetStr(m);
1362                         Map_Goto(reinit);
1363                         alreadychangedlevel = true;
1364                         return true;
1365                 }
1366         }
1367         if(!reinit && autocvar_lastlevel)
1368         {
1369                 cvar_settemp_restore();
1370                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1371                 alreadychangedlevel = true;
1372                 return true;
1373         }
1374         return false;
1375 }
1376
1377 void GotoNextMap(float reinit)
1378 {
1379         //string nextmap;
1380         //float n, nummaps;
1381         //string s;
1382         if (alreadychangedlevel)
1383                 return;
1384         alreadychangedlevel = true;
1385
1386         string nextMap = GetNextMap();
1387         if(nextMap == "")
1388                 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1389         Map_Goto(reinit);
1390 }
1391
1392
1393 /*
1394 ============
1395 IntermissionThink
1396
1397 When the player presses attack or jump, change to the next level
1398 ============
1399 */
1400 .float autoscreenshot;
1401 void IntermissionThink(entity this)
1402 {
1403         FixIntermissionClient(this);
1404
1405         float server_screenshot = (autocvar_sv_autoscreenshot && CS(this).cvar_cl_autoscreenshot);
1406         float client_screenshot = (CS(this).cvar_cl_autoscreenshot == 2);
1407
1408         if( (server_screenshot || client_screenshot)
1409                 && ((this.autoscreenshot > 0) && (time > this.autoscreenshot)) )
1410         {
1411                 this.autoscreenshot = -1;
1412                 if(IS_REAL_CLIENT(this)) { stuffcmd(this, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(false, "%s"))); }
1413                 return;
1414         }
1415
1416         if (time < intermission_exittime)
1417                 return;
1418
1419         if(!mapvote_initialized)
1420                 if (time < intermission_exittime + 10 && !(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_JUMP(this) || PHYS_INPUT_BUTTON_ATCK2(this) || PHYS_INPUT_BUTTON_HOOK(this) || PHYS_INPUT_BUTTON_USE(this)))
1421                         return;
1422
1423         MapVote_Start();
1424 }
1425
1426 /*
1427 ===============================================================================
1428
1429 RULES
1430
1431 ===============================================================================
1432 */
1433
1434 void DumpStats(float final)
1435 {
1436         float file;
1437         string s;
1438         float to_console;
1439         float to_eventlog;
1440         float to_file;
1441         float i;
1442
1443         to_console = autocvar_sv_logscores_console;
1444         to_eventlog = autocvar_sv_eventlog;
1445         to_file = autocvar_sv_logscores_file;
1446
1447         if(!final)
1448         {
1449                 to_console = true; // always print printstats replies
1450                 to_eventlog = false; // but never print them to the event log
1451         }
1452
1453         if(to_eventlog)
1454                 if(autocvar_sv_eventlog_console)
1455                         to_console = false; // otherwise we get the output twice
1456
1457         if(final)
1458                 s = ":scores:";
1459         else
1460                 s = ":status:";
1461         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1462
1463         if(to_console)
1464                 LOG_INFO(s);
1465         if(to_eventlog)
1466                 GameLogEcho(s);
1467
1468         file = -1;
1469         if(to_file)
1470         {
1471                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1472                 if(file == -1)
1473                         to_file = false;
1474                 else
1475                         fputs(file, strcat(s, "\n"));
1476         }
1477
1478         s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1479         if(to_console)
1480                 LOG_INFO(s);
1481         if(to_eventlog)
1482                 GameLogEcho(s);
1483         if(to_file)
1484                 fputs(file, strcat(s, "\n"));
1485
1486         FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1487                 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1488                 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1489                 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1490                         s = strcat(s, ftos(it.team), ":");
1491                 else
1492                         s = strcat(s, "spectator:");
1493
1494                 if(to_console)
1495                         LOG_INFO(s, playername(it, false));
1496                 if(to_eventlog)
1497                         GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it, false)));
1498                 if(to_file)
1499                         fputs(file, strcat(s, playername(it, false), "\n"));
1500         });
1501
1502         if(teamplay)
1503         {
1504                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1505                 if(to_console)
1506                         LOG_INFO(s);
1507                 if(to_eventlog)
1508                         GameLogEcho(s);
1509                 if(to_file)
1510                         fputs(file, strcat(s, "\n"));
1511
1512                 for(i = 1; i < 16; ++i)
1513                 {
1514                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1515                         s = strcat(s, ":", ftos(i));
1516                         if(to_console)
1517                                 LOG_INFO(s);
1518                         if(to_eventlog)
1519                                 GameLogEcho(s);
1520                         if(to_file)
1521                                 fputs(file, strcat(s, "\n"));
1522                 }
1523         }
1524
1525         if(to_console)
1526                 LOG_INFO(":end");
1527         if(to_eventlog)
1528                 GameLogEcho(":end");
1529         if(to_file)
1530         {
1531                 fputs(file, ":end\n");
1532                 fclose(file);
1533         }
1534 }
1535
1536 void FixIntermissionClient(entity e)
1537 {
1538         if(!e.autoscreenshot) // initial call
1539         {
1540                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1541                 SetResourceExplicit(e, RES_HEALTH, -2342);
1542                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1543                 for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1544                 {
1545                     .entity weaponentity = weaponentities[slot];
1546                         if(e.(weaponentity))
1547                         {
1548                                 e.(weaponentity).effects = EF_NODRAW;
1549                                 if (e.(weaponentity).weaponchild)
1550                                         e.(weaponentity).weaponchild.effects = EF_NODRAW;
1551                         }
1552                 }
1553                 if(IS_REAL_CLIENT(e))
1554                 {
1555                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1556                         RandomSelection_Init();
1557                         FOREACH_WORD(autocvar_sv_intermission_cdtrack, true, {
1558                                 RandomSelection_AddString(it, 1, 1);
1559                         });
1560                         if (RandomSelection_chosen_string != "")
1561                         {
1562                                 stuffcmd(e, sprintf("\ncd loop %s\n", RandomSelection_chosen_string));
1563                         }
1564                         msg_entity = e;
1565                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1566                 }
1567         }
1568 }
1569
1570 /*
1571 go to the next level for deathmatch
1572 only called if a time or frag limit has expired
1573 */
1574 void NextLevel()
1575 {
1576         game_stopped = true;
1577         intermission_running = 1; // game over
1578
1579         // enforce a wait time before allowing changelevel
1580         if(player_count > 0)
1581                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1582         else
1583                 intermission_exittime = -1;
1584
1585         /*
1586         WriteByte (MSG_ALL, SVC_CDTRACK);
1587         WriteByte (MSG_ALL, 3);
1588         WriteByte (MSG_ALL, 3);
1589         // done in FixIntermission
1590         */
1591
1592         //pos = FindIntermission ();
1593
1594         VoteReset();
1595
1596         DumpStats(true);
1597
1598         // send statistics
1599         PlayerStats_GameReport(true);
1600         WeaponStats_Shutdown();
1601
1602         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1603
1604         if(autocvar_sv_eventlog)
1605                 GameLogEcho(":gameover");
1606
1607         GameLogClose();
1608
1609         FOREACH_CLIENT(IS_PLAYER(it), {
1610                 FixIntermissionClient(it);
1611                 if(it.winning)
1612                         bprint(playername(it, false), " ^7wins.\n");
1613         });
1614
1615         target_music_kill();
1616
1617         if(autocvar_g_campaign)
1618                 CampaignPreIntermission();
1619
1620         MUTATOR_CALLHOOK(MatchEnd);
1621
1622         localcmd("\nsv_hook_gameend\n");
1623 }
1624
1625
1626 float InitiateSuddenDeath()
1627 {
1628         // Check first whether normal overtimes could be added before initiating suddendeath mode
1629         // - for this timelimit_overtime needs to be >0 of course
1630         // - also check the winning condition calculated in the previous frame and only add normal overtime
1631         //   again, if at the point at which timelimit would be extended again, still no winner was found
1632         if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1633                 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1634                 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1635         {
1636                 return 1; // need to call InitiateOvertime later
1637         }
1638         else
1639         {
1640                 if(!checkrules_suddendeathend)
1641                 {
1642                         if(autocvar_g_campaign)
1643                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1644                         else
1645                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1646                         if(g_race && !g_race_qualifying)
1647                                 race_StartCompleting();
1648                 }
1649                 return 0;
1650         }
1651 }
1652
1653 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1654 {
1655         ++checkrules_overtimesadded;
1656         //add one more overtime by simply extending the timelimit
1657         cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1658         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1659 }
1660
1661 float GetWinningCode(float fraglimitreached, float equality)
1662 {
1663         if(autocvar_g_campaign == 1)
1664         {
1665                 if(fraglimitreached)
1666                         return WINNING_YES;
1667                 else
1668                         return WINNING_NO;
1669         }
1670         else
1671         {
1672                 if(equality)
1673                 {
1674                         if(fraglimitreached)
1675                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1676                         else
1677                                 return WINNING_NEVER;
1678                 }
1679                 else
1680                 {
1681                         if(fraglimitreached)
1682                                 return WINNING_YES;
1683                         else
1684                                 return WINNING_NO;
1685                 }
1686         }
1687 }
1688
1689 // set the .winning flag for exactly those players with a given field value
1690 void SetWinners(.float field, float value)
1691 {
1692         FOREACH_CLIENT(IS_PLAYER(it), { it.winning = (it.(field) == value); });
1693 }
1694
1695 // set the .winning flag for those players with a given field value
1696 void AddWinners(.float field, float value)
1697 {
1698         FOREACH_CLIENT(IS_PLAYER(it), {
1699                 if(it.(field) == value)
1700                         it.winning = 1;
1701         });
1702 }
1703
1704 // clear the .winning flags
1705 void ClearWinners()
1706 {
1707         FOREACH_CLIENT(IS_PLAYER(it), { it.winning = 0; });
1708 }
1709
1710 void ShuffleMaplist()
1711 {
1712         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1713 }
1714
1715 int fragsleft_last;
1716 float WinningCondition_Scores(float limit, float leadlimit)
1717 {
1718         // TODO make everything use THIS winning condition (except LMS)
1719         WinningConditionHelper(NULL);
1720
1721         if(teamplay)
1722         {
1723                 for (int i = 1; i < 5; ++i)
1724                 {
1725                         Team_SetTeamScore(Team_GetTeamFromIndex(i),
1726                                 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1727                 }
1728         }
1729
1730         ClearWinners();
1731         if(WinningConditionHelper_winner)
1732                 WinningConditionHelper_winner.winning = 1;
1733         if(WinningConditionHelper_winnerteam >= 0)
1734                 SetWinners(team, WinningConditionHelper_winnerteam);
1735
1736         if(WinningConditionHelper_lowerisbetter)
1737         {
1738                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1739                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1740                 limit = -limit;
1741         }
1742
1743         if(WinningConditionHelper_zeroisworst)
1744                 leadlimit = 0; // not supported in this mode
1745
1746         if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1747         {
1748                 float fragsleft;
1749                 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1750                 {
1751                         fragsleft = 1;
1752                 }
1753                 else
1754                 {
1755                         fragsleft = FLOAT_MAX;
1756                         float leadingfragsleft = FLOAT_MAX;
1757                         if (limit)
1758                                 fragsleft = limit - WinningConditionHelper_topscore;
1759                         if (leadlimit)
1760                                 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1761
1762                         if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1763                                 fragsleft = max(fragsleft, leadingfragsleft);
1764                         else
1765                                 fragsleft = min(fragsleft, leadingfragsleft);
1766                 }
1767
1768                 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1769                 {
1770                         if (fragsleft == 1)
1771                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1772                         else if (fragsleft == 2)
1773                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1774                         else if (fragsleft == 3)
1775                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1776
1777                         fragsleft_last = fragsleft;
1778                 }
1779         }
1780
1781         bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1782         bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1783
1784         bool limit_reached;
1785         // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1786         if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1787                 limit_reached = (fraglimit_reached && leadlimit_reached);
1788         else
1789                 limit_reached = (fraglimit_reached || leadlimit_reached);
1790
1791         return GetWinningCode(
1792                 WinningConditionHelper_topscore && limit_reached,
1793                 WinningConditionHelper_equality
1794         );
1795 }
1796
1797 float WinningCondition_RanOutOfSpawns()
1798 {
1799         if(have_team_spawns <= 0)
1800                 return WINNING_NO;
1801
1802         if(!autocvar_g_spawn_useallspawns)
1803                 return WINNING_NO;
1804
1805         if(!some_spawn_has_been_used)
1806                 return WINNING_NO;
1807
1808         for (int i = 1; i < 5; ++i)
1809         {
1810                 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1811         }
1812
1813         FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1814         {
1815                 if (Team_IsValidTeam(it.team))
1816                 {
1817                         Team_SetTeamScore(Team_GetTeam(it.team), 1);
1818                 }
1819         });
1820
1821         IL_EACH(g_spawnpoints, true,
1822         {
1823                 if (Team_IsValidTeam(it.team))
1824                 {
1825                         Team_SetTeamScore(Team_GetTeam(it.team), 1);
1826                 }
1827         });
1828
1829         ClearWinners();
1830         float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1831         float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1832         float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1833         float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1834         if(team1_score + team2_score + team3_score + team4_score == 0)
1835         {
1836                 checkrules_equality = true;
1837                 return WINNING_YES;
1838         }
1839         else if(team1_score + team2_score + team3_score + team4_score == 1)
1840         {
1841                 float t, i;
1842                 if(team1_score)
1843                         t = 1;
1844                 else if(team2_score)
1845                         t = 2;
1846                 else if(team3_score)
1847                         t = 3;
1848                 else // if(team4_score)
1849                         t = 4;
1850                 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1851                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1852                 {
1853                         for (int j = 1; j <= NUM_TEAMS; ++j)
1854                         {
1855                                 if (t == j)
1856                                 {
1857                                         continue;
1858                                 }
1859                                 if (!TeamBalance_IsTeamAllowed(balance, j))
1860                                 {
1861                                         continue;
1862                                 }
1863                                 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1864                         }
1865                 }
1866
1867                 AddWinners(team, t);
1868                 return WINNING_YES;
1869         }
1870         else
1871                 return WINNING_NO;
1872 }
1873
1874 /*
1875 ============
1876 CheckRules_World
1877
1878 Exit deathmatch games upon conditions
1879 ============
1880 */
1881 void CheckRules_World()
1882 {
1883         VoteThink();
1884         MapVote_Think();
1885
1886         SetDefaultAlpha();
1887
1888         if (intermission_running) // someone else quit the game already
1889         {
1890                 if(player_count == 0) // Nobody there? Then let's go to the next map
1891                         MapVote_Start();
1892                         // this will actually check the player count in the next frame
1893                         // again, but this shouldn't hurt
1894                 return;
1895         }
1896
1897         float timelimit = autocvar_timelimit * 60;
1898         float fraglimit = autocvar_fraglimit;
1899         float leadlimit = autocvar_leadlimit;
1900         if (leadlimit < 0) leadlimit = 0;
1901
1902         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1903         {
1904                 if(timelimit > 0)
1905                         timelimit = 0; // timelimit is not made for warmup
1906                 if(fraglimit > 0)
1907                         fraglimit = 0; // no fraglimit for now
1908                 leadlimit = 0; // no leadlimit for now
1909         }
1910
1911         if(timelimit > 0)
1912         {
1913                 timelimit += game_starttime;
1914         }
1915         else if (timelimit < 0)
1916         {
1917                 // endmatch
1918                 NextLevel();
1919                 return;
1920         }
1921
1922         float wantovertime;
1923         wantovertime = 0;
1924
1925         if(checkrules_suddendeathend)
1926         {
1927                 if(!checkrules_suddendeathwarning)
1928                 {
1929                         checkrules_suddendeathwarning = true;
1930                         if(g_race && !g_race_qualifying)
1931                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1932                         else
1933                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1934                 }
1935         }
1936         else
1937         {
1938                 if (timelimit && time >= timelimit)
1939                 {
1940                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1941                         {
1942                                 float totalplayers;
1943                                 float playerswithlaps;
1944                                 float readyplayers;
1945                                 totalplayers = playerswithlaps = readyplayers = 0;
1946                                 FOREACH_CLIENT(IS_PLAYER(it), {
1947                                         ++totalplayers;
1948                                         if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1949                                                 ++playerswithlaps;
1950                                         if(it.ready)
1951                                                 ++readyplayers;
1952                                 });
1953
1954                                 // at least 2 of the players have completed a lap: start the RACE
1955                                 // otherwise, the players should end the qualifying on their own
1956                                 if(readyplayers || playerswithlaps >= 2)
1957                                 {
1958                                         checkrules_suddendeathend = 0;
1959                                         ReadyRestart(); // go to race
1960                                         return;
1961                                 }
1962                                 else
1963                                         wantovertime |= InitiateSuddenDeath();
1964                         }
1965                         else
1966                                 wantovertime |= InitiateSuddenDeath();
1967                 }
1968         }
1969
1970         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1971         {
1972                 NextLevel();
1973                 return;
1974         }
1975
1976         int checkrules_status = WinningCondition_RanOutOfSpawns();
1977         if(checkrules_status == WINNING_YES)
1978                 bprint("Hey! Someone ran out of spawns!\n");
1979         else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1980                 checkrules_status = M_ARGV(0, float);
1981         else
1982                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1983
1984         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1985         {
1986                 checkrules_status = WINNING_NEVER;
1987                 checkrules_overtimesadded = -1;
1988                 wantovertime |= InitiateSuddenDeath();
1989         }
1990
1991         if(checkrules_status == WINNING_NEVER)
1992                 // equality cases! Nobody wins if the overtime ends in a draw.
1993                 ClearWinners();
1994
1995         if(wantovertime)
1996         {
1997                 if(checkrules_status == WINNING_NEVER)
1998                         InitiateOvertime();
1999                 else
2000                         checkrules_status = WINNING_YES;
2001         }
2002
2003         if(checkrules_suddendeathend)
2004                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2005                         checkrules_status = WINNING_YES;
2006
2007         if(checkrules_status == WINNING_YES)
2008         {
2009                 //print("WINNING\n");
2010                 NextLevel();
2011         }
2012 }
2013
2014 string GotoMap(string m)
2015 {
2016         m = GameTypeVote_MapInfo_FixName(m);
2017         if (!m)
2018                 return "The map you suggested is not available on this server.";
2019         if (!autocvar_sv_vote_gametype)
2020         if(!MapInfo_CheckMap(m))
2021                 return "The map you suggested does not support the current game mode.";
2022         cvar_set("nextmap", m);
2023         cvar_set("timelimit", "-1");
2024         if(mapvote_initialized || alreadychangedlevel)
2025         {
2026                 if(DoNextMapOverride(0))
2027                         return "Map switch initiated.";
2028                 else
2029                         return "Hm... no. For some reason I like THIS map more.";
2030         }
2031         else
2032                 return "Map switch will happen after scoreboard.";
2033 }
2034
2035 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2036 void RunThink(entity this)
2037 {
2038         // don't let things stay in the past.
2039         // it is possible to start that way by a trigger with a local time.
2040         if(this.nextthink <= 0 || this.nextthink > time + frametime)
2041                 return;
2042
2043         float oldtime = time; // do we need to save this?
2044
2045         for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2046         {
2047                 time = max(oldtime, this.nextthink);
2048                 this.nextthink = 0;
2049
2050                 if(getthink(this))
2051                         getthink(this)(this);
2052                 // mods often set nextthink to time to cause a think every frame,
2053                 // we don't want to loop in that case, so exit if the new nextthink is
2054                 // <= the time the qc was told, also exit if it is past the end of the
2055                 // frame
2056                 if(this.nextthink <= time || this.nextthink > oldtime + frametime || !autocvar_sv_gameplayfix_multiplethinksperframe)
2057                         break;
2058         }
2059
2060         time = oldtime;
2061 }
2062
2063 bool autocvar_sv_freezenonclients;
2064 bool autocvar_sv_gameplayfix_delayprojectiles = false;
2065 void Physics_Frame()
2066 {
2067         if(autocvar_sv_freezenonclients)
2068                 return;
2069
2070         IL_EACH(g_moveables, true,
2071         {
2072                 if(IS_CLIENT(it) || it.classname == "" || it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH || it.move_movetype == MOVETYPE_PHYSICS)
2073                         continue;
2074
2075                 //set_movetype(it, it.move_movetype);
2076                 // inline the set_movetype function, since this is called a lot
2077                 it.movetype = (it.move_qcphysics) ? MOVETYPE_NONE : it.move_movetype;
2078
2079                 if(it.move_movetype == MOVETYPE_NONE)
2080                         continue;
2081
2082                 if(it.move_qcphysics)
2083                         Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2084
2085                 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2086                 {
2087                         // handle thinking here
2088                         if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + frametime)
2089                                 RunThink(it);
2090                 }
2091         });
2092
2093         if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2094                 return;
2095
2096         IL_EACH(g_moveables, it.move_qcphysics,
2097         {
2098                 if(IS_CLIENT(it) || is_pure(it) || it.classname == "" || it.move_movetype == MOVETYPE_NONE)
2099                         continue;
2100                 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2101         });
2102 }
2103
2104 void systems_update();
2105 void EndFrame()
2106 {
2107         anticheat_endframe();
2108
2109         Physics_Frame();
2110
2111         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2112                 entity e = IS_SPEC(it) ? it.enemy : it;
2113                 if (e.typehitsound) {
2114                         STAT(TYPEHIT_TIME, it) = time;
2115                 } else if (e.killsound) {
2116                         STAT(KILL_TIME, it) = time;
2117                 } else if (e.damage_dealt) {
2118                         STAT(HIT_TIME, it) = time;
2119                         STAT(DAMAGE_DEALT_TOTAL, it) += ceil(e.damage_dealt);
2120                 }
2121         });
2122         // add 1 frametime because after this, engine SV_Physics
2123         // increases time by a frametime and then networks the frame
2124         // add another frametime because client shows everything with
2125         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2126         // needed!
2127         float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2128         FOREACH_CLIENT(true, {
2129                 it.typehitsound = false;
2130                 it.damage_dealt = 0;
2131                 it.killsound = false;
2132                 antilag_record(it, CS(it), altime);
2133         });
2134         IL_EACH(g_monsters, true,
2135         {
2136                 antilag_record(it, it, altime);
2137         });
2138         IL_EACH(g_projectiles, it.classname == "nade",
2139         {
2140                 antilag_record(it, it, altime);
2141         });
2142         systems_update();
2143         IL_ENDFRAME();
2144 }
2145
2146
2147 /*
2148  * RedirectionThink:
2149  * returns true if redirecting
2150  */
2151 float redirection_timeout;
2152 float redirection_nextthink;
2153 float RedirectionThink()
2154 {
2155         float clients_found;
2156
2157         if(redirection_target == "")
2158                 return false;
2159
2160         if(!redirection_timeout)
2161         {
2162                 cvar_set("sv_public", "-2");
2163                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2164                 if(redirection_target == "self")
2165                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2166                 else
2167                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2168         }
2169
2170         if(time < redirection_nextthink)
2171                 return true;
2172
2173         redirection_nextthink = time + 1;
2174
2175         clients_found = 0;
2176         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2177                 // TODO add timer
2178                 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2179                 if(redirection_target == "self")
2180                         stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2181                 else
2182                         stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2183                 ++clients_found;
2184         });
2185
2186         LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2187
2188         if(time > redirection_timeout || clients_found == 0)
2189                 localcmd("\nwait; wait; wait; quit\n");
2190
2191         return true;
2192 }
2193
2194 void RestoreGame()
2195 {
2196         // Loaded from a save game
2197         // some things then break, so let's work around them...
2198
2199         // Progs DB (capture records)
2200         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2201
2202         // Mapinfo
2203         MapInfo_Shutdown();
2204         MapInfo_Enumerate();
2205         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2206         WeaponStats_Init();
2207
2208         TargetMusic_RestoreGame();
2209 }
2210
2211 void Shutdown()
2212 {
2213         game_stopped = 2;
2214
2215         if(world_initialized > 0)
2216         {
2217                 world_initialized = 0;
2218
2219                 // if a timeout is active, reset the slowmo value to normal
2220                 if(timeout_status == TIMEOUT_ACTIVE)
2221                         cvar_set("slowmo", ftos(orig_slowmo));
2222
2223                 LOG_TRACE("Saving persistent data...");
2224                 Ban_SaveBans();
2225
2226                 // playerstats with unfinished match
2227                 PlayerStats_GameReport(false);
2228
2229                 if(!cheatcount_total)
2230                 {
2231                         if(autocvar_sv_db_saveasdump)
2232                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2233                         else
2234                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2235                 }
2236                 if(autocvar_developer > 0)
2237                 {
2238                         if(autocvar_sv_db_saveasdump)
2239                                 db_dump(TemporaryDB, "server-temp.db");
2240                         else
2241                                 db_save(TemporaryDB, "server-temp.db");
2242                 }
2243                 CheatShutdown(); // must be after cheatcount check
2244                 db_close(ServerProgsDB);
2245                 db_close(TemporaryDB);
2246                 LOG_TRACE("Saving persistent data... done!");
2247                 // tell the bot system the game is ending now
2248                 bot_endgame();
2249
2250                 WeaponStats_Shutdown();
2251                 MapInfo_Shutdown();
2252         }
2253         else if(world_initialized == 0)
2254         {
2255                 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2256         }
2257         else
2258         {
2259                 __init_dedicated_server_shutdown();
2260         }
2261 }