]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/world.qc
Merge branch 'terencehill/ft_froze_by_space_fix' into 'master'
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / world.qc
1 #include "world.qh"
2
3 #include <common/constants.qh>
4 #include <common/deathtypes/all.qh>
5 #include <common/gamemodes/_mod.qh>
6 #include <common/gamemodes/sv_rules.qh>
7 #include <common/items/_mod.qh>
8 #include <common/mapinfo.qh>
9 #include <common/mapobjects/target/music.qh>
10 #include <common/mapobjects/trigger/hurt.qh>
11 #include <common/mapobjects/trigger/secret.qh>
12 #include <common/mapobjects/triggers.qh>
13 #include <common/monsters/_mod.qh>
14 #include <common/monsters/sv_monsters.qh>
15 #include <common/net_linked.qh>
16 #include <common/notifications/all.qh>
17 #include <common/physics/player.qh>
18 #include <common/playerstats.qh>
19 #include <common/state.qh>
20 #include <common/stats.qh>
21 #include <common/teams.qh>
22 #include <common/util.qh>
23 #include <common/vehicles/all.qh>
24 #include <common/weapons/_all.qh>
25 #include <lib/warpzone/common.qh>
26 #include <server/anticheat.qh>
27 #include <server/antilag.qh>
28 #include <server/bot/api.qh>
29 #include <server/campaign.qh>
30 #include <server/cheats.qh>
31 #include <server/client.qh>
32 #include <server/command/common.qh>
33 #include <server/command/getreplies.qh>
34 #include <server/command/sv_cmd.qh>
35 #include <server/command/vote.qh>
36 #include <server/damage.qh>
37 #include <server/gamelog.qh>
38 #include <server/hook.qh>
39 #include <server/ipban.qh>
40 #include <server/items/items.qh>
41 #include <server/main.qh>
42 #include <server/mapvoting.qh>
43 #include <server/mutators/_mod.qh>
44 #include <server/race.qh>
45 #include <server/scores.qh>
46 #include <server/scores_rules.qh>
47 #include <server/spawnpoints.qh>
48 #include <server/teamplay.qh>
49 #include <server/weapons/weaponstats.qh>
50
51 const float LATENCY_THINKRATE = 10;
52 .float latency_sum;
53 .float latency_cnt;
54 .float latency_time;
55 entity pingplreport;
56 void PingPLReport_Think(entity this)
57 {
58         float delta;
59         entity e;
60
61         delta = 3 / maxclients;
62         if(delta < sys_frametime)
63                 delta = 0;
64         this.nextthink = time + delta;
65
66         e = edict_num(this.cnt + 1);
67         if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
68         {
69                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
70                 WriteByte(MSG_BROADCAST, this.cnt);
71                 WriteShort(MSG_BROADCAST, bound(1, rint(CS(e).ping), 32767));
72                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
73                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
74
75                 // record latency times for clients throughout the match so we can report it to playerstats
76                 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
77                 {
78                         CS(e).latency_sum += CS(e).ping;
79                         CS(e).latency_cnt += 1;
80                         CS(e).latency_time = time;
81                         //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
82                 }
83         }
84         else
85         {
86                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
87                 WriteByte(MSG_BROADCAST, this.cnt);
88                 WriteShort(MSG_BROADCAST, 0);
89                 WriteByte(MSG_BROADCAST, 0);
90                 WriteByte(MSG_BROADCAST, 0);
91         }
92         this.cnt = (this.cnt + 1) % maxclients;
93 }
94 void PingPLReport_Spawn()
95 {
96         pingplreport = new_pure(pingplreport);
97         setthink(pingplreport, PingPLReport_Think);
98         pingplreport.nextthink = time;
99 }
100
101 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
102
103 void SetDefaultAlpha()
104 {
105         if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
106         {
107                 default_player_alpha = autocvar_g_player_alpha;
108                 if(default_player_alpha == 0)
109                         default_player_alpha = 1;
110                 default_weapon_alpha = default_player_alpha;
111         }
112 }
113
114 void GotoFirstMap(entity this)
115 {
116         float n;
117         if(autocvar__sv_init)
118         {
119                 // cvar_set("_sv_init", "0");
120                 // we do NOT set this to 0 any more, so someone "accidentally" changing
121                 // to this "init" map on a dedicated server will cause no permanent
122                 // harm
123                 if(autocvar_g_maplist_shuffle)
124                         ShuffleMaplist();
125                 n = tokenizebyseparator(autocvar_g_maplist, " ");
126                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
127
128                 MapInfo_Enumerate();
129                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
130
131                 if(!DoNextMapOverride(1))
132                         GotoNextMap(1);
133
134                 return;
135         }
136
137         if(time < 5)
138         {
139                 this.nextthink = time;
140         }
141         else
142         {
143                 this.nextthink = time + 1;
144                 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
145         }
146 }
147
148 void cvar_changes_init()
149 {
150         float h;
151         string k, v, d;
152         float n, i, adding, pureadding;
153
154         strfree(cvar_changes);
155         strfree(cvar_purechanges);
156         cvar_purechanges_count = 0;
157
158         h = buf_create();
159         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
160         n = buf_getsize(h);
161
162         adding = true;
163         pureadding = true;
164
165         for(i = 0; i < n; ++i)
166         {
167                 k = bufstr_get(h, i);
168
169 #define BADPREFIX_COND(p) (substring(k, 0, strlen(p)) == p)
170 #define BADSUFFIX_COND(s) (substring(k, -strlen(s), -1) == s)
171
172 #define BADPREFIX(p) if(BADPREFIX_COND(p)) continue
173 #define BADPRESUFFIX(p, s) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s)) continue
174 #define BADCVAR(p) if(k == p) continue
175 #define BADVALUE(p, val) if (k == p && v == val) continue
176 #define BADPRESUFFIXVALUE(p, s, val) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s) && v == val) continue
177
178                 // general excludes and namespaces for server admin used cvars
179                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
180
181                 // internal
182                 BADPREFIX("csqc_");
183                 BADPREFIX("cvar_check_");
184                 BADCVAR("gamecfg");
185                 BADCVAR("g_configversion");
186                 BADCVAR("halflifebsp");
187                 BADCVAR("sv_mapformat_is_quake2");
188                 BADCVAR("sv_mapformat_is_quake3");
189                 BADPREFIX("sv_world");
190
191                 // client
192                 BADPREFIX("chase_");
193                 BADPREFIX("cl_");
194                 BADPREFIX("con_");
195                 BADPREFIX("scoreboard_");
196                 BADPREFIX("g_campaign");
197                 BADPREFIX("g_waypointsprite_");
198                 BADPREFIX("gl_");
199                 BADPREFIX("joy");
200                 BADPREFIX("hud_");
201                 BADPREFIX("m_");
202                 BADPREFIX("menu_");
203                 BADPREFIX("net_slist_");
204                 BADPREFIX("r_");
205                 BADPREFIX("sbar_");
206                 BADPREFIX("scr_");
207                 BADPREFIX("snd_");
208                 BADPREFIX("show");
209                 BADPREFIX("sensitivity");
210                 BADPREFIX("userbind");
211                 BADPREFIX("v_");
212                 BADPREFIX("vid_");
213                 BADPREFIX("crosshair");
214                 BADCVAR("mod_q3bsp_lightmapmergepower");
215                 BADCVAR("mod_q3bsp_nolightmaps");
216                 BADCVAR("fov");
217                 BADCVAR("mastervolume");
218                 BADCVAR("volume");
219                 BADCVAR("bgmvolume");
220                 BADCVAR("in_pitch_min");
221                 BADCVAR("in_pitch_max");
222
223                 // private
224                 BADCVAR("developer");
225                 BADCVAR("log_dest_udp");
226                 BADCVAR("net_address");
227                 BADCVAR("net_address_ipv6");
228                 BADCVAR("port");
229                 BADCVAR("savedgamecfg");
230                 BADCVAR("serverconfig");
231                 BADCVAR("sv_autoscreenshot");
232                 BADCVAR("sv_heartbeatperiod");
233                 BADCVAR("sv_vote_master_password");
234                 BADCVAR("sys_colortranslation");
235                 BADCVAR("sys_specialcharactertranslation");
236                 BADCVAR("timeformat");
237                 BADCVAR("timestamps");
238                 BADCVAR("g_require_stats");
239                 BADCVAR("g_muteban_list");
240                 BADCVAR("g_playban_list");
241                 BADCVAR("g_voteban_list");
242                 BADPREFIX("developer_");
243                 BADPREFIX("g_ban_");
244                 BADPREFIX("g_banned_list");
245                 BADPREFIX("g_require_stats_");
246                 BADPREFIX("g_chat_flood_");
247                 BADPREFIX("g_ghost_items");
248                 BADPREFIX("g_playerstats_");
249                 BADPREFIX("g_voice_flood_");
250                 BADPREFIX("log_file");
251                 BADPREFIX("quit_");
252                 BADPREFIX("rcon_");
253                 BADPREFIX("sv_allowdownloads");
254                 BADPREFIX("sv_autodemo");
255                 BADPREFIX("sv_curl_");
256                 BADPREFIX("sv_eventlog");
257                 BADPREFIX("sv_logscores_");
258                 BADPREFIX("sv_master");
259                 BADPREFIX("sv_weaponstats_");
260                 BADPREFIX("sv_waypointsprite_");
261                 BADCVAR("rescan_pending");
262
263                 // these can contain player IDs, so better hide
264                 BADPREFIX("g_forced_team_");
265                 BADCVAR("sv_allow_customplayermodels_idlist");
266                 BADCVAR("sv_allow_customplayermodels_speciallist");
267
268                 // mapinfo
269                 BADCVAR("fraglimit");
270                 BADCVAR("g_arena");
271                 BADCVAR("g_assault");
272                 BADCVAR("g_ca");
273                 BADCVAR("g_ca_teams");
274                 BADCVAR("g_conquest");
275                 BADCVAR("g_conquest_teams");
276                 BADCVAR("g_ctf");
277                 BADCVAR("g_cts");
278                 BADCVAR("g_dotc");
279                 BADCVAR("g_dm");
280                 BADCVAR("g_domination");
281                 BADCVAR("g_domination_default_teams");
282                 BADCVAR("g_duel");
283                 BADCVAR("g_duel_not_dm_maps");
284                 BADCVAR("g_freezetag");
285                 BADCVAR("g_freezetag_teams");
286                 BADCVAR("g_invasion_type");
287                 BADCVAR("g_jailbreak");
288                 BADCVAR("g_jailbreak_teams");
289                 BADCVAR("g_keepaway");
290                 BADCVAR("g_keyhunt");
291                 BADCVAR("g_keyhunt_teams");
292                 BADCVAR("g_lms");
293                 BADCVAR("g_mayhem");
294                 BADCVAR("g_nexball");
295                 BADCVAR("g_onslaught");
296                 BADCVAR("g_race");
297                 BADCVAR("g_race_laps_limit");
298                 BADCVAR("g_race_qualifying_timelimit");
299                 BADCVAR("g_race_qualifying_timelimit_override");
300                 BADCVAR("g_runematch");
301                 BADCVAR("g_shootfromeye");
302                 BADCVAR("g_snafu");
303                 BADCVAR("g_survival");
304                 BADCVAR("g_survival_not_dm_maps");
305                 BADCVAR("g_tdm");
306                 BADCVAR("g_tdm_on_dm_maps");
307                 BADCVAR("g_tdm_teams");
308                 BADCVAR("g_tmayhem");
309                 BADCVAR("g_tmayhem_teams");
310                 BADCVAR("g_vip");
311                 BADCVAR("leadlimit");
312                 BADCVAR("nextmap");
313                 BADCVAR("teamplay");
314                 BADCVAR("timelimit");
315                 BADCVAR("g_mapinfo_q3compat");
316                 BADCVAR("g_mapinfo_settemp_acl");
317                 BADCVAR("g_mapinfo_ignore_warnings");
318                 BADCVAR("g_maplist_ignore_sizes");
319                 BADCVAR("g_maplist_sizes_count_bots");
320
321                 // long
322                 BADCVAR("hostname");
323                 BADCVAR("g_maplist");
324                 BADCVAR("g_maplist_mostrecent");
325                 BADCVAR("sv_motd");
326                 BADCVAR("sv_termsofservice_url");
327
328                 v = cvar_string(k);
329                 d = cvar_defstring(k);
330                 if(v == d)
331                         continue;
332
333                 if(adding)
334                 {
335                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
336                         if(strlen(cvar_changes) > 16384)
337                         {
338                                 cvar_changes = "// too many settings have been changed to show them here\n";
339                                 adding = 0;
340                         }
341                 }
342
343                 // now check if the changes are actually gameplay relevant
344
345                 // does nothing gameplay relevant
346                 BADCVAR("captureleadlimit_override");
347                 BADCVAR("condump_stripcolors");
348                 BADCVAR("fs_gamedir");
349                 BADCVAR("g_allow_oldvortexbeam");
350                 BADCVAR("g_balance_kill_delay");
351                 BADCVAR("g_buffs_pickup_anyway");
352                 BADCVAR("g_buffs_randomize");
353                 BADCVAR("g_buffs_randomize_teamplay");
354                 BADCVAR("g_campcheck_distance");
355                 BADCVAR("g_chatsounds");
356                 BADCVAR("g_ca_point_leadlimit");
357                 BADCVAR("g_ca_point_limit");
358                 BADCVAR("g_ca_spectate_enemies");
359                 BADCVAR("g_ctf_captimerecord_always");
360                 BADCVAR("g_ctf_flag_glowtrails");
361                 BADCVAR("g_ctf_dynamiclights");
362                 BADCVAR("g_ctf_flag_pickup_verbosename");
363                 BADCVAR("g_ctf_flagcarrier_auto_helpme_damage");
364                 BADPRESUFFIX("g_ctf_flag_", "_model");
365                 BADPRESUFFIX("g_ctf_flag_", "_skin");
366                 BADCVAR("g_domination_point_leadlimit");
367                 BADCVAR("g_forced_respawn");
368                 BADCVAR("g_freezetag_point_leadlimit");
369                 BADCVAR("g_freezetag_point_limit");
370                 BADCVAR("g_glowtrails");
371                 BADCVAR("g_hats");
372                 BADCVAR("g_casings");
373                 BADCVAR("g_invasion_point_limit");
374                 BADCVAR("g_jump_grunt");
375                 BADCVAR("g_keepaway_ballcarrier_effects");
376                 BADCVAR("g_keepawayball_effects");
377                 BADCVAR("g_keyhunt_point_leadlimit");
378                 BADCVAR("g_nexball_goalleadlimit");
379                 BADCVAR("g_new_toys_autoreplace");
380                 BADCVAR("g_new_toys_use_pickupsound");
381                 BADCVAR("g_physics_predictall");
382                 BADCVAR("g_piggyback");
383                 BADCVAR("g_playerclip_collisions");
384                 BADCVAR("g_spawn_alloweffects");
385                 BADCVAR("g_tdm_point_leadlimit");
386                 BADCVAR("g_tdm_point_limit");
387                 BADCVAR("g_mayhem_point_limit");
388                 BADCVAR("g_mayhem_point_leadlimit");
389                 BADCVAR("g_tmayhem_point_limit");
390                 BADCVAR("g_tmayhem_point_leadlimit");
391                 BADCVAR("leadlimit_and_fraglimit");
392                 BADCVAR("leadlimit_override");
393                 BADCVAR("pausable");
394                 BADCVAR("sv_announcer");
395                 BADCVAR("sv_autopause");
396                 BADCVAR("sv_checkforpacketsduringsleep");
397                 BADCVAR("sv_damagetext");
398                 BADCVAR("sv_db_saveasdump");
399                 BADCVAR("sv_intermission_cdtrack");
400                 BADCVAR("sv_mapchange_delay");
401                 BADCVAR("sv_minigames");
402                 BADCVAR("sv_namechangetimer");
403                 BADCVAR("sv_precacheplayermodels");
404                 BADCVAR("sv_qcphysics");
405                 BADCVAR("sv_radio");
406                 BADCVAR("sv_stepheight");
407                 BADCVAR("sv_timeout");
408                 BADCVAR("sv_weapons_modeloverride");
409                 BADCVAR("w_prop_interval");
410                 BADPREFIX("chat_");
411                 BADPREFIX("crypto_");
412                 BADPREFIX("gameversion");
413                 BADPREFIX("g_chat_");
414                 BADPREFIX("g_ctf_captimerecord_");
415                 BADPREFIX("g_hats_");
416                 BADPREFIX("g_maplist_");
417                 BADPREFIX("g_mod_");
418                 BADPREFIX("g_respawn_");
419                 BADPREFIX("net_");
420                 BADPREFIX("notification_");
421                 BADPREFIX("prvm_");
422                 BADPREFIX("skill_");
423                 BADPREFIX("sv_allow_");
424                 BADPREFIX("sv_cullentities_");
425                 BADPREFIX("sv_maxidle");
426                 BADPREFIX("sv_minigames_");
427                 BADPREFIX("sv_radio_");
428                 BADPREFIX("sv_timeout_");
429                 BADPREFIX("sv_vote_");
430                 BADPREFIX("timelimit_");
431                 BADPRESUFFIX("g_", "_round_timelimit");
432
433                 // allowed changes to server admins (please sync this to server.cfg)
434                 // vi commands:
435                 //   :/"impure"/,$d
436                 //   :g!,^\/\/[^ /],d
437                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
438                 //   :%!sort
439                 // yes, this does contain some redundant stuff, don't really care
440                 BADPREFIX("bot_ai_");
441                 BADCVAR("bot_config_file");
442                 BADCVAR("bot_number");
443                 BADCVAR("bot_prefix");
444                 BADCVAR("bot_suffix");
445                 BADCVAR("capturelimit_override");
446                 BADCVAR("fraglimit_override");
447                 BADCVAR("gametype");
448                 BADCVAR("g_antilag");
449                 BADCVAR("g_balance_teams");
450                 BADCVAR("g_balance_teams_prevent_imbalance");
451                 BADCVAR("g_balance_teams_scorefactor");
452                 BADCVAR("g_ban_sync_trusted_servers");
453                 BADCVAR("g_ban_sync_uri");
454                 BADCVAR("g_buffs");
455                 BADCVAR("g_ca_teams_override");
456                 BADCVAR("g_ctf_fullbrightflags");
457                 BADCVAR("g_ctf_ignore_frags");
458                 BADCVAR("g_ctf_leaderboard");
459                 BADCVAR("g_domination_point_limit");
460                 BADCVAR("g_domination_teams_override");
461                 BADCVAR("g_freezetag_revive_spawnshield");
462                 BADCVAR("g_freezetag_teams_override");
463                 BADCVAR("g_friendlyfire");
464                 BADCVAR("g_fullbrightitems");
465                 BADCVAR("g_fullbrightplayers");
466                 BADCVAR("g_keyhunt_point_limit");
467                 BADCVAR("g_keyhunt_teams_override");
468                 BADCVAR("g_lms_lives_override");
469                 BADCVAR("g_mayhem_powerups");
470                 BADCVAR("g_maplist");
471                 BADCVAR("g_maxplayers");
472                 BADCVAR("g_mirrordamage");
473                 BADCVAR("g_nexball_goallimit");
474                 BADCVAR("g_norecoil");
475                 BADCVAR("g_physics_clientselect");
476                 BADCVAR("g_pinata");
477                 BADCVAR("g_powerups");
478                 BADCVAR("g_powerups_drop_ondeath");
479                 BADCVAR("g_player_brightness");
480                 BADCVAR("g_rocket_flying");
481                 BADCVAR("g_rocket_flying_disabledelays");
482                 BADPREFIX("g_spawnshield");
483                 BADCVAR("g_start_delay");
484                 BADCVAR("g_superspectate");
485                 BADCVAR("g_tdm_teams_override");
486                 BADCVAR("g_tmayhem_teams_override");
487                 BADCVAR("g_tmayhem_powerups");
488                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
489                 BADCVAR("hostname");
490                 BADCVAR("log_file");
491                 BADCVAR("maxplayers");
492                 BADCVAR("minplayers");
493                 BADCVAR("minplayers_per_team");
494                 BADCVAR("net_address");
495                 BADCVAR("port");
496                 BADCVAR("rcon_password");
497                 BADCVAR("rcon_restricted_commands");
498                 BADCVAR("rcon_restricted_password");
499                 BADCVAR("skill");
500                 BADCVAR("sv_adminnick");
501                 BADCVAR("sv_autoscreenshot");
502                 BADCVAR("sv_autotaunt");
503                 BADCVAR("sv_curl_defaulturl");
504                 BADCVAR("sv_defaultcharacter");
505                 BADCVAR("sv_defaultcharacterskin");
506                 BADCVAR("sv_defaultplayercolors");
507                 BADCVAR("sv_defaultplayermodel");
508                 BADCVAR("sv_defaultplayerskin");
509                 BADCVAR("sv_maxrate");
510                 BADCVAR("sv_motd");
511                 BADCVAR("sv_public");
512                 BADCVAR("sv_showfps");
513                 BADCVAR("sv_showspectators");
514                 BADCVAR("sv_status_privacy");
515                 BADCVAR("sv_taunt");
516                 BADCVAR("sv_vote_call");
517                 BADCVAR("sv_vote_commands");
518                 BADCVAR("sv_vote_majority_factor");
519                 BADCVAR("sv_vote_master");
520                 BADCVAR("sv_vote_master_commands");
521                 BADCVAR("sv_vote_master_password");
522                 BADCVAR("sv_vote_simple_majority_factor");
523                 BADVALUE("sys_ticrate", "0.0166667");
524                 BADVALUE("sys_ticrate", "0.0333333");
525                 BADCVAR("teamplay_mode");
526                 BADCVAR("timelimit_override");
527                 BADPREFIX("g_warmup");
528                 BADPREFIX("sv_info_");
529                 BADPREFIX("sv_ready_restart_");
530
531                 BADPRESUFFIXVALUE("g_", "_weaponarena", "most");
532                 BADPRESUFFIXVALUE("g_", "_weaponarena", "most_available");
533
534                 // mutators that announce themselves properly to the server browser
535                 BADCVAR("g_instagib");
536                 BADCVAR("g_new_toys");
537                 BADCVAR("g_nix");
538                 BADCVAR("g_grappling_hook");
539                 BADCVAR("g_jetpack");
540
541 #undef BADPRESUFFIX
542 #undef BADPREFIX
543 #undef BADCVAR
544 #undef BADVALUE
545 #undef BADPRESUFFIXVALUE
546
547                 if(pureadding)
548                 {
549                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
550                         if(strlen(cvar_purechanges) > 16384)
551                         {
552                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
553                                 pureadding = 0;
554                         }
555                 }
556                 ++cvar_purechanges_count;
557                 // WARNING: this variable is used for the server list
558                 // NEVER dare to skip this code!
559                 // Hacks to intentionally appearing as "pure server" even though you DO have
560                 // modified settings may be punished by removal from the server list.
561                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
562                 // though.
563         }
564         buf_del(h);
565         if(cvar_changes == "")
566                 cvar_changes = "// this server runs at default server settings\n";
567         else
568                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
569         cvar_changes = strzone(cvar_changes);
570         if(cvar_purechanges == "")
571                 cvar_purechanges = "// this server runs at default gameplay settings\n";
572         else
573                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
574         cvar_purechanges = strzone(cvar_purechanges);
575 }
576
577 entity randomseed;
578 bool RandomSeed_Send(entity this, entity to, int sf)
579 {
580         WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
581         WriteShort(MSG_ENTITY, this.cnt);
582         return true;
583 }
584 void RandomSeed_Think(entity this)
585 {
586         this.cnt = bound(0, floor(random() * 65536), 65535);
587         this.nextthink = time + 5;
588
589         this.SendFlags |= 1;
590 }
591 void RandomSeed_Spawn()
592 {
593         randomseed = new_pure(randomseed);
594         setthink(randomseed, RandomSeed_Think);
595         Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
596
597         getthink(randomseed)(randomseed); // sets random seed and nextthink
598 }
599
600 spawnfunc(__init_dedicated_server)
601 {
602         // handler for _init/_init map (only for dedicated server initialization)
603
604         world_initialized = -1; // don't complain
605
606         delete_fn = remove_unsafely;
607
608         entity e = new(GotoFirstMap);
609         setthink(e, GotoFirstMap);
610         e.nextthink = time; // this is usually 1 at this point
611
612         e = new(info_player_deathmatch);  // safeguard against player joining
613
614         // assign reflectively to avoid "assignment to world" warning
615         for (int i = 0, n = numentityfields(); i < n; ++i)
616         {
617                 string k = entityfieldname(i);
618                 if (k == "classname")
619                 {
620                         // safeguard against various stuff ;)
621                         putentityfieldstring(i, this, "worldspawn");
622                         break;
623                 }
624         }
625
626         // needs to be done so early because of the constants they create
627         static_init();
628         static_init_late();
629         static_init_precache();
630
631         IL_PUSH(g_spawnpoints, e); // just incase
632
633         MapInfo_Enumerate();
634         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
635 }
636
637 void __init_dedicated_server_shutdown() {
638         MapInfo_Shutdown();
639 }
640
641 STATIC_INIT_EARLY(maxclients)
642 {
643         maxclients = 0;
644         for (entity head = nextent(NULL); head; head = nextent(head)) {
645                 ++maxclients;
646         }
647 }
648
649 void GameplayMode_DelayedInit(entity this)
650 {
651         // at this stage team entities are spawned, teamplay contains the number of them
652
653         if(!scores_initialized)
654                 ScoreRules_generic();
655
656         if (warmup_stage >= 0 && autocvar_g_maxplayers >= 0)
657                 return;
658         if (!g_duel)
659                 MapReadSizes(mapname);
660
661         if (autocvar_g_maxplayers < 0 && teamplay)
662         {
663                 // automatic maxplayers should be a multiple of team count
664                 if (map_maxplayers == 0 || map_maxplayers > maxclients)
665                         map_maxplayers = maxclients; // unlimited, but may need rounding
666                 int d = map_maxplayers % AVAILABLE_TEAMS;
667                 int u = AVAILABLE_TEAMS - d;
668                 map_maxplayers += (u <= d && u + map_maxplayers <= maxclients) ? u : -d;
669         }
670
671         if (warmup_stage < 0)
672         {
673                 int m = GetPlayerLimit();
674                 if (m <= 0) m = maxclients;
675                 map_minplayers = bound(max(2, AVAILABLE_TEAMS * 2), map_minplayers, m);
676                 if (teamplay)
677                 {
678                         // automatic minplayers should be a multiple of team count
679                         int d = map_minplayers % AVAILABLE_TEAMS;
680                         int u = AVAILABLE_TEAMS - d;
681                         map_minplayers += (u < d && u + map_minplayers <= m) ? u : -d;
682                 }
683         }
684         else
685                 map_minplayers = 0; // don't display a minimum if it's not used (g_maxplayers < 0 && g_warmup >= 0)
686 }
687
688 void InitGameplayMode()
689 {
690         VoteReset();
691
692         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
693         get_mi_min_max(1);
694         // assign reflectively to avoid "assignment to world" warning
695         for (int i = 0, done = 0, n = numentityfields(); i < n; ++i)
696         {
697                 string k = entityfieldname(i);
698                 vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
699                 if (v)
700                 {
701                         putentityfieldstring(i, world, sprintf("%v", v));
702                         if (++done == 2) break;
703                 }
704         }
705         // currently, NetRadiant's limit is 131072 qu for each side
706         // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
707         // set the distance according to map size but don't go over the limit to avoid issues with float precision
708         // in case somebody makes extremely large maps
709         max_shot_distance = min(230000, vlen(world.maxs - world.mins));
710
711         MapInfo_LoadMapSettings(mapname);
712         GameRules_teams(false);
713
714         if (!cvar_value_issafe(world.fog))
715         {
716                 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
717                 world.fog = string_null;
718         }
719         if(MapInfo_Map_fog != "")
720         {
721                 if(MapInfo_Map_fog == "none")
722                         world.fog = string_null;
723                 else
724                         world.fog = strzone(MapInfo_Map_fog);
725         }
726         clientstuff = strzone(MapInfo_Map_clientstuff);
727
728         MapInfo_ClearTemps();
729
730         gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
731
732         cache_mutatormsg = strzone("");
733         cache_lastmutatormsg = strzone("");
734
735         InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
736 }
737
738 bool world_already_spawned;
739 spawnfunc(worldspawn)
740 {
741         cvar_set("_endmatch", "0");
742         server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
743
744         if (autocvar_sv_termsofservice_url && autocvar_sv_termsofservice_url != "")
745         {
746                 strcpy(sv_termsofservice_url_escaped, strreplace(":", "|", autocvar_sv_termsofservice_url));
747         }
748         else
749         {
750                 strcpy(sv_termsofservice_url_escaped, "INVALID");
751         }
752
753         bool wantrestart = false;
754         {
755                 if (!server_is_dedicated)
756                 {
757                         // DP unloads dlcache pk3s before starting a listen server since https://gitlab.com/xonotic/darkplaces/-/merge_requests/134
758                         // restore csqc_progname too
759                         string expect = "csprogs.dat";
760                         wantrestart = cvar_string("csqc_progname") != expect;
761                         cvar_set("csqc_progname", expect);
762                 }
763                 else
764                 {
765                         // Try to use versioned csprogs from pk3
766                         // Only ever use versioned csprogs.dat files on dedicated servers;
767                         // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
768                         string pk3csprogs = "csprogs-" WATERMARK ".dat";
769                         // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
770                         string select = "csprogs.dat";
771                         if (fexists(pk3csprogs)) select = pk3csprogs;
772                         if (cvar_string("csqc_progname") != select)
773                         {
774                                 cvar_set("csqc_progname", select);
775                                 wantrestart = true;
776                         }
777                         // Check for updates on startup
778                         // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
779                         int sentinel = fopen("progs.txt", FILE_READ);
780                         if (sentinel >= 0)
781                         {
782                                 string switchversion = fgets(sentinel);
783                                 fclose(sentinel);
784                                 if (switchversion != "" && switchversion != WATERMARK)
785                                 {
786                                         LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
787                                         // if it doesn't exist, assume either:
788                                         //   a) the current program was overwritten
789                                         //   b) this is a client only update
790                                         string newprogs = sprintf("progs-%s.dat", switchversion);
791                                         if (fexists(newprogs))
792                                         {
793                                                 cvar_set("sv_progs", newprogs);
794                                                 wantrestart = true;
795                                         }
796                                         string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
797                                         if (fexists(newcsprogs))
798                                         {
799                                                 cvar_set("csqc_progname", newcsprogs);
800                                                 wantrestart = true;
801                                         }
802                                 }
803                         }
804                 }
805                 if (wantrestart)
806                 {
807                         LOG_INFO("Restart requested");
808                         changelevel(mapname);
809                         // let initialization continue, shutdown depends on it
810                 }
811         }
812
813         if(world_already_spawned)
814                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
815         world_already_spawned = true;
816
817         delete_fn = remove_safely; // during spawning, watch what you remove!
818
819         cvar_changes_init(); // do this very early now so it REALLY matches the server config
820
821         // default to RACE_RECORD, can be overwritten by gamemodes
822         record_type = RACE_RECORD;
823
824         // needs to be done so early because of the constants they create
825         static_init();
826
827         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
828
829         TemporaryDB = db_create();
830
831         // 0 normal
832         lightstyle(0, "m");
833
834         // 1 FLICKER (first variety)
835         lightstyle(1, "mmnmmommommnonmmonqnmmo");
836
837         // 2 SLOW STRONG PULSE
838         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
839
840         // 3 CANDLE (first variety)
841         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
842
843         // 4 FAST STROBE
844         lightstyle(4, "mamamamamama");
845
846         // 5 GENTLE PULSE 1
847         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
848
849         // 6 FLICKER (second variety)
850         lightstyle(6, "nmonqnmomnmomomno");
851
852         // 7 CANDLE (second variety)
853         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
854
855         // 8 CANDLE (third variety)
856         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
857
858         // 9 SLOW STROBE (fourth variety)
859         lightstyle(9, "aaaaaaaazzzzzzzz");
860
861         // 10 FLUORESCENT FLICKER
862         lightstyle(10, "mmamammmmammamamaaamammma");
863
864         // 11 SLOW PULSE NOT FADE TO BLACK
865         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
866
867         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
868
869         // 63 testing
870         lightstyle(63, "a");
871
872         if(autocvar_g_campaign)
873                 CampaignPreInit();
874         else
875                 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
876
877         Map_MarkAsRecent(mapname);
878
879         InitGameplayMode();
880         static_init_late();
881         static_init_precache();
882         readlevelcvars();
883
884         GameRules_limit_fallbacks();
885
886         player_count = 0;
887         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
888         if(bot_waypoints_for_items == 1)
889                 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
890                         bot_waypoints_for_items = 0;
891
892         WaypointSprite_Init();
893
894         // NOTE for matchid:
895         // changing the logic generating it is okay. But:
896         // it HAS to stay <= 64 chars
897         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
898         // strftime(false, "%s") isn't reliable, see strftime_s description
899         matchid = strzone(sprintf("%d.%s.%06d", autocvar_sv_eventlog_files_counter, strftime_s(), random() * 1000000));
900
901         if(autocvar_sv_eventlog)
902                 GameLogInit(); // requires matchid to be set
903
904         cvar_set("nextmap", "");
905
906         SetDefaultAlpha();
907
908         if(autocvar_g_campaign)
909                 CampaignPostInit();
910
911         Ban_LoadBans();
912
913         MapInfo_Enumerate();
914         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
915
916         q3compat = BITSET(q3compat, Q3COMPAT_ARENA, _MapInfo_FindArenaFile(mapname, ".arena") != "");
917         q3compat = BITSET(q3compat, Q3COMPAT_DEFI, _MapInfo_FindArenaFile(mapname, ".defi") != "");
918
919         // quake 3 music support
920         if(world.music || world.noise)
921         {
922                 // prefer .music over .noise
923                 string chosen_music;
924                 if(world.music)
925                         chosen_music = world.music;
926                 else
927                         chosen_music = world.noise;
928
929                 string newstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
930                 strcpy(clientstuff, newstuff);
931         }
932
933         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
934         {
935                 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
936                 if(fd != -1)
937                 {
938                         string s;
939                         while((s = fgets(fd)))
940                         {
941                                 int l = tokenize_console(s);
942                                 if(l < 2)
943                                         continue;
944                                 if(argv(0) == "cd")
945                                 {
946                                         string trackname = argv(2);
947                                         LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
948                                         LOG_INFO("  cdtrack ", trackname);
949                                         if (cvar_value_issafe(trackname))
950                                         {
951                                                 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
952                                                 strcpy(clientstuff, newstuff);
953                                         }
954                                 }
955                                 else if(argv(0) == "fog")
956                                 {
957                                         LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
958                                         LOG_INFO("  \"fog\" \"", s, "\"");
959                                 }
960                                 else if(argv(0) == "set")
961                                 {
962                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
963                                         LOG_INFO("  clientsettemp_for_type all ", argv(1), " ", argv(2));
964                                 }
965                                 else if(argv(0) != "//")
966                                 {
967                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
968                                         LOG_INFO("  clientsettemp_for_type all ", argv(0), " ", argv(1));
969                                 }
970                         }
971                         fclose(fd);
972                 }
973         }
974
975         WeaponStats_Init();
976
977         Nagger_Init();
978
979         // set up information replies for clients and server to use
980         maplist_reply = strzone(getmaplist());
981         lsmaps_reply = strzone(getlsmaps());
982         monsterlist_reply = strzone(getmonsterlist());
983         bool records_available = false;
984         for(int i = 0; i < 10; ++i)
985         {
986                 string s = getrecords(i);
987                 if (s != "")
988                 {
989                         records_reply[i] = strzone(s);
990                         records_available = true;
991                 }
992         }
993         if (!records_available)
994                 records_reply[0] = "No records available for the current game mode.\n";
995         ladder_reply = strzone(getladder());
996         rankings_reply = strzone(getrankings());
997
998         // begin other init
999         ClientInit_Spawn();
1000         RandomSeed_Spawn();
1001         PingPLReport_Spawn();
1002
1003         CheatInit();
1004
1005         if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
1006
1007         // fill sv_curl_serverpackages from .serverpackage files
1008         if (autocvar_sv_curl_serverpackages_auto)
1009         {
1010                 string s = "csprogs-" WATERMARK ".dat";
1011                 // remove automatically managed files from the list to prevent duplicates
1012                 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
1013                 {
1014                         string pkg = argv(i);
1015                         if (startsWith(pkg, "csprogs-")) continue;
1016                         if (endsWith(pkg, "-serverpackage.txt")) continue;
1017                         if (endsWith(pkg, ".serverpackage")) continue;  // OLD legacy
1018                         s = cons(s, pkg);
1019                 }
1020                 // add automatically managed files to the list
1021                 #define X(match) MACRO_BEGIN \
1022                         int fd = search_begin(match, true, false); \
1023                         if (fd >= 0) \
1024                         { \
1025                                 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1026                                 { \
1027                                         s = cons(s, search_getfilename(fd, i)); \
1028                                 } \
1029                                 search_end(fd); \
1030                         } \
1031                 MACRO_END
1032                 X("*-serverpackage.txt");
1033                 X("*.serverpackage");
1034                 #undef X
1035                 cvar_set("sv_curl_serverpackages", s);
1036         }
1037
1038         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1039         modname = "Xonotic";
1040         // physics/balance/config changes that count as mod
1041         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1042                 modname = cvar_string("g_mod_physics");
1043         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1044                 modname = cvar_string("g_mod_balance");
1045         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1046                 modname = cvar_string("g_mod_config");
1047         // extra mutators that deserve to count as mod
1048         MUTATOR_CALLHOOK(SetModname, modname);
1049         modname = M_ARGV(0, string);
1050
1051         // save it for later
1052         modname = strzone(modname);
1053
1054         WinningConditionHelper(this); // set worldstatus
1055
1056         if (autocvar_sv_autopause && server_is_dedicated && !wantrestart)
1057                 // INITPRIO_LAST is to soon: bots either didn't join yet or didn't leave yet, see: bot_fixcount()
1058                 defer(this, 5, Pause_TryPause_Dedicated);
1059
1060         world_initialized = 1;
1061         __spawnfunc_spawn_all();
1062 }
1063
1064 spawnfunc(light)
1065 {
1066         //makestatic (this); // Who the f___ did that?
1067         delete(this);
1068 }
1069
1070 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance, bool frompos)
1071 {
1072         float m = e.dphitcontentsmask;
1073         e.dphitcontentsmask = goodcontents | badcontents;
1074
1075         vector org = boundmin;
1076         vector delta = boundmax - boundmin;
1077
1078         vector start, end;
1079         start = end = org;
1080         int j; // used after the loop
1081         for(j = 0; j < attempts; ++j)
1082         {
1083                 start.x = org.x + random() * delta.x;
1084                 start.y = org.y + random() * delta.y;
1085                 start.z = org.z + random() * delta.z;
1086
1087                 // rule 1: start inside world bounds, and outside
1088                 // solid, and don't start from somewhere where you can
1089                 // fall down to evil
1090                 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1091                 if (trace_fraction >= 1)
1092                         continue;
1093                 if (trace_startsolid)
1094                         continue;
1095                 if (trace_dphitcontents & badcontents)
1096                         continue;
1097                 if (trace_dphitq3surfaceflags & badsurfaceflags)
1098                         continue;
1099
1100                 // rule 2: if we are too high, lower the point
1101                 if (trace_fraction * delta.z > maxaboveground)
1102                         start = trace_endpos + '0 0 1' * maxaboveground;
1103                 vector enddown = trace_endpos;
1104
1105                 // rule 3: make sure we aren't outside the map. This only works
1106                 // for somewhat well formed maps. A good rule of thumb is that
1107                 // the map should have a convex outside hull.
1108                 // these can be traceLINES as we already verified the starting box
1109                 vector mstart = start + 0.5 * (e.mins + e.maxs);
1110                 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1111                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1112                         continue;
1113                 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1114                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1115                         continue;
1116                 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1117                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1118                         continue;
1119                 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1120                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1121                         continue;
1122                 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1123                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1124                         continue;
1125
1126                 // rule 4: we must "see" some spawnpoint or item
1127                 entity sp = NULL;
1128                 if(frompos)
1129                 {
1130                         if((traceline(mstart, e.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1131                                 sp = e;
1132                 }
1133                 if(!sp)
1134                 {
1135                         IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1136                         {
1137                                 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1138                                 {
1139                                         sp = it;
1140                                         break;
1141                                 }
1142                         });
1143                 }
1144                 if(!sp)
1145                 {
1146                         int items_checked = 0;
1147                         IL_EACH(g_items, checkpvs(mstart, it),
1148                         {
1149                                 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1150                                 {
1151                                         sp = it;
1152                                         break;
1153                                 }
1154
1155                                 ++items_checked;
1156                                 if(items_checked >= attempts)
1157                                         break; // sanity
1158                         });
1159
1160                         if(!sp)
1161                                 continue;
1162                 }
1163
1164                 // find a random vector to "look at"
1165                 end.x = org.x + random() * delta.x;
1166                 end.y = org.y + random() * delta.y;
1167                 end.z = org.z + random() * delta.z;
1168                 end = start + normalize(end - start) * vlen(delta);
1169
1170                 // rule 4: start TO end must not be too short
1171                 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1172                 if(trace_startsolid)
1173                         continue;
1174                 if(trace_fraction < minviewdistance / vlen(delta))
1175                         continue;
1176
1177                 // rule 5: don't want to look at sky
1178                 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1179                         continue;
1180
1181                 // rule 6: we must not end up in trigger_hurt
1182                 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1183                         continue;
1184
1185                 break;
1186         }
1187
1188         e.dphitcontentsmask = m;
1189
1190         if(j < attempts)
1191         {
1192                 setorigin(e, start);
1193                 e.angles = vectoangles(end - start);
1194                 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1195                 return true;
1196         }
1197         return false;
1198 }
1199
1200 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1201 {
1202         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance, false);
1203 }
1204
1205 /*
1206 ===============================================================================
1207
1208 RULES
1209
1210 ===============================================================================
1211 */
1212
1213 void DumpStats(float final)
1214 {
1215         float file;
1216         string s;
1217         float to_console;
1218         float to_eventlog;
1219         float to_file;
1220         float i;
1221
1222         to_console = autocvar_sv_logscores_console;
1223         to_eventlog = autocvar_sv_eventlog;
1224         to_file = autocvar_sv_logscores_file;
1225
1226         if(!final)
1227         {
1228                 to_console = true; // always print printstats replies
1229                 to_eventlog = false; // but never print them to the event log
1230         }
1231
1232         if(to_eventlog)
1233                 if(autocvar_sv_eventlog_console)
1234                         to_console = false; // otherwise we get the output twice
1235
1236         if(final)
1237                 s = ":scores:";
1238         else
1239                 s = ":status:";
1240         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1241
1242         if(to_console)
1243                 LOG_HELP(s);
1244         if(to_eventlog)
1245                 GameLogEcho(s);
1246
1247         file = -1;
1248         if(to_file)
1249         {
1250                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1251                 if(file == -1)
1252                         to_file = false;
1253                 else
1254                         fputs(file, strcat(s, "\n"));
1255         }
1256
1257         s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1258         if(to_console)
1259                 LOG_HELP(s);
1260         if(to_eventlog)
1261                 GameLogEcho(s);
1262         if(to_file)
1263                 fputs(file, strcat(s, "\n"));
1264
1265         FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1266                 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1267                 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1268                 if(IS_PLAYER(it) || INGAME_JOINED(it))
1269                         s = strcat(s, ftos(it.team), ":");
1270                 else
1271                         s = strcat(s, "spectator:");
1272
1273                 if(to_console)
1274                         LOG_HELP(s, playername(it.netname, it.team, false));
1275                 if(to_eventlog)
1276                         GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1277                 if(to_file)
1278                         fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1279         });
1280
1281         if(teamplay)
1282         {
1283                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1284                 if(to_console)
1285                         LOG_HELP(s);
1286                 if(to_eventlog)
1287                         GameLogEcho(s);
1288                 if(to_file)
1289                         fputs(file, strcat(s, "\n"));
1290
1291                 for(i = 1; i < 16; ++i)
1292                 {
1293                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1294                         s = strcat(s, ":", ftos(i));
1295                         if(to_console)
1296                                 LOG_HELP(s);
1297                         if(to_eventlog)
1298                                 GameLogEcho(s);
1299                         if(to_file)
1300                                 fputs(file, strcat(s, "\n"));
1301                 }
1302         }
1303
1304         if(to_console)
1305                 LOG_HELP(":end");
1306         if(to_eventlog)
1307                 GameLogEcho(":end");
1308         if(to_file)
1309         {
1310                 fputs(file, ":end\n");
1311                 fclose(file);
1312         }
1313 }
1314
1315 /*
1316 go to the next level for deathmatch
1317 only called if a time or frag limit has expired
1318 */
1319 void NextLevel()
1320 {
1321         cvar_set("_endmatch", "0");
1322         game_stopped = true;
1323         intermission_running = true; // game over
1324
1325         // enforce a wait time before allowing changelevel
1326         if(player_count > 0)
1327                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1328         else
1329                 intermission_exittime = -1;
1330
1331         /*
1332         WriteByte (MSG_ALL, SVC_CDTRACK);
1333         WriteByte (MSG_ALL, 3);
1334         WriteByte (MSG_ALL, 3);
1335         // done in FixIntermission
1336         */
1337
1338         //pos = FindIntermission ();
1339
1340         VoteReset();
1341
1342         DumpStats(true);
1343
1344         // send statistics
1345         PlayerStats_GameReport(true);
1346         WeaponStats_Shutdown();
1347
1348         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1349
1350         if(autocvar_sv_eventlog)
1351                 GameLogEcho(":gameover");
1352
1353         GameLogClose();
1354
1355         int winner_team = 0;
1356         FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1357                 FixIntermissionClient(it);
1358                 if(it.winning)
1359                 {
1360                         if (teamplay && !winner_team)
1361                         {
1362                                 winner_team = it.team;
1363                                 bprint(Team_ColorCode(winner_team), Team_ColorName_Upper(winner_team), "^7 team wins the match\n");
1364                         }
1365                         bprint(playername(it.netname, it.team, false), " ^7wins\n");
1366                 }
1367         });
1368
1369         target_music_kill();
1370
1371         if(autocvar_g_campaign)
1372                 CampaignPreIntermission();
1373
1374         MUTATOR_CALLHOOK(MatchEnd);
1375
1376         localcmd("\nsv_hook_gameend\n");
1377 }
1378
1379
1380 int InitiateSuddenDeath()
1381 {
1382         // Check first whether normal overtimes could be added before initiating suddendeath mode
1383         // - for this timelimit_overtime needs to be >0 of course
1384         // - also check the winning condition calculated in the previous frame and only add normal overtime
1385         //   again, if at the point at which timelimit would be extended again, still no winner was found
1386         if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1387                 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1388                 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1389         {
1390                 return 1; // need to call InitiateOvertime later
1391         }
1392         else
1393         {
1394                 if(!checkrules_suddendeathend)
1395                 {
1396                         if(autocvar_g_campaign)
1397                         {
1398                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1399                         }
1400                         else
1401                         {
1402                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1403                                 overtimes = -1;
1404                         }
1405                         if(g_race && !g_race_qualifying)
1406                                 race_StartCompleting();
1407                 }
1408                 return 0;
1409         }
1410 }
1411
1412 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1413 {
1414         ++checkrules_overtimesadded;
1415         overtimes = checkrules_overtimesadded;
1416         //add one more overtime by simply extending the timelimit
1417         cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1418         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1419 }
1420
1421 float GetWinningCode(float fraglimitreached, float equality)
1422 {
1423         if(autocvar_g_campaign == 1)
1424         {
1425                 if(fraglimitreached)
1426                         return WINNING_YES;
1427                 else
1428                         return WINNING_NO;
1429         }
1430         else
1431         {
1432                 if(equality)
1433                 {
1434                         if(fraglimitreached)
1435                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1436                         else
1437                                 return WINNING_NEVER;
1438                 }
1439                 else
1440                 {
1441                         if(fraglimitreached)
1442                                 return WINNING_YES;
1443                         else
1444                                 return WINNING_NO;
1445                 }
1446         }
1447 }
1448
1449 // set the .winning flag for exactly those players with a given field value
1450 void SetWinners(.float field, float value)
1451 {
1452         FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = (it.(field) == value); });
1453 }
1454
1455 // set the .winning flag for those players with a given field value
1456 void AddWinners(.float field, float value)
1457 {
1458         FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1459                 if(it.(field) == value)
1460                         it.winning = 1;
1461         });
1462 }
1463
1464 // clear the .winning flags
1465 void ClearWinners()
1466 {
1467         FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = 0; });
1468 }
1469
1470 int fragsleft_last;
1471 float WinningCondition_Scores(float limit, float leadlimit)
1472 {
1473         // TODO make everything use THIS winning condition (except LMS)
1474         WinningConditionHelper(NULL);
1475
1476         if(teamplay)
1477         {
1478                 for (int i = 1; i < 5; ++i)
1479                 {
1480                         Team_SetTeamScore(Team_GetTeamFromIndex(i),
1481                                 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1482                 }
1483         }
1484
1485         ClearWinners();
1486         if(WinningConditionHelper_winner)
1487                 WinningConditionHelper_winner.winning = 1;
1488         if(WinningConditionHelper_winnerteam >= 0)
1489                 SetWinners(team, WinningConditionHelper_winnerteam);
1490
1491         if(WinningConditionHelper_lowerisbetter)
1492         {
1493                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1494                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1495                 limit = -limit;
1496         }
1497
1498         if(WinningConditionHelper_zeroisworst)
1499                 leadlimit = 0; // not supported in this mode
1500
1501         if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1502         {
1503                 float fragsleft;
1504                 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1505                 {
1506                         fragsleft = 1;
1507                 }
1508                 else
1509                 {
1510                         fragsleft = FLOAT_MAX;
1511                         float leadingfragsleft = FLOAT_MAX;
1512                         if (limit)
1513                                 fragsleft = limit - WinningConditionHelper_topscore;
1514                         if (leadlimit)
1515                                 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1516
1517                         if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1518                                 fragsleft = max(fragsleft, leadingfragsleft);
1519                         else
1520                                 fragsleft = min(fragsleft, leadingfragsleft);
1521                 }
1522
1523                 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1524                 {
1525                         if (fragsleft == 1)
1526                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1527                         else if (fragsleft == 2)
1528                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1529                         else if (fragsleft == 3)
1530                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1531
1532                         fragsleft_last = fragsleft;
1533                 }
1534         }
1535
1536         bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1537         bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1538
1539         bool limit_reached;
1540         // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1541         if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1542                 limit_reached = (fraglimit_reached && leadlimit_reached);
1543         else
1544                 limit_reached = (fraglimit_reached || leadlimit_reached);
1545
1546         return GetWinningCode(
1547                 WinningConditionHelper_topscore && limit_reached,
1548                 WinningConditionHelper_equality
1549         );
1550 }
1551
1552 float WinningCondition_RanOutOfSpawns()
1553 {
1554         if(have_team_spawns <= 0)
1555                 return WINNING_NO;
1556
1557         if(!autocvar_g_spawn_useallspawns)
1558                 return WINNING_NO;
1559
1560         if(!some_spawn_has_been_used)
1561                 return WINNING_NO;
1562
1563         for (int i = 1; i < 5; ++i)
1564         {
1565                 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1566         }
1567
1568         FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1569         {
1570                 if (Team_IsValidTeam(it.team))
1571                 {
1572                         Team_SetTeamScore(Team_GetTeam(it.team), 1);
1573                 }
1574         });
1575
1576         IL_EACH(g_spawnpoints, true,
1577         {
1578                 if (Team_IsValidTeam(it.team))
1579                 {
1580                         Team_SetTeamScore(Team_GetTeam(it.team), 1);
1581                 }
1582         });
1583
1584         ClearWinners();
1585         float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1586         float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1587         float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1588         float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1589         if(team1_score + team2_score + team3_score + team4_score == 0)
1590         {
1591                 checkrules_equality = true;
1592                 return WINNING_YES;
1593         }
1594         else if(team1_score + team2_score + team3_score + team4_score == 1)
1595         {
1596                 float t, i;
1597                 if(team1_score)
1598                         t = 1;
1599                 else if(team2_score)
1600                         t = 2;
1601                 else if(team3_score)
1602                         t = 3;
1603                 else // if(team4_score)
1604                         t = 4;
1605                 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1606                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1607                 {
1608                         for (int j = 1; j <= NUM_TEAMS; ++j)
1609                         {
1610                                 if (t == j)
1611                                 {
1612                                         continue;
1613                                 }
1614                                 if (!TeamBalance_IsTeamAllowed(balance, j))
1615                                 {
1616                                         continue;
1617                                 }
1618                                 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1619                         }
1620                 }
1621
1622                 AddWinners(team, t);
1623                 return WINNING_YES;
1624         }
1625         else
1626                 return WINNING_NO;
1627 }
1628
1629 /*
1630 ============
1631 CheckRules_World
1632
1633 Exit deathmatch games upon conditions
1634 ============
1635 */
1636 void CheckRules_World()
1637 {
1638         VoteThink();
1639         MapVote_Think();
1640
1641         SetDefaultAlpha();
1642
1643         if (intermission_running) // someone else quit the game already
1644         {
1645                 if(player_count == 0) // Nobody there? Then let's go to the next map
1646                         MapVote_Start();
1647                         // this will actually check the player count in the next frame
1648                         // again, but this shouldn't hurt
1649                 return;
1650         }
1651
1652         float timelimit = autocvar_timelimit * 60;
1653         float fraglimit = autocvar_fraglimit;
1654         float leadlimit = autocvar_leadlimit;
1655         if (leadlimit < 0) leadlimit = 0;
1656
1657         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1658         {
1659                 if(timelimit > 0)
1660                         timelimit = 0; // timelimit is not made for warmup
1661                 if(fraglimit > 0)
1662                         fraglimit = 0; // no fraglimit for now
1663                 leadlimit = 0; // no leadlimit for now
1664         }
1665
1666         if (autocvar__endmatch || timelimit < 0)
1667         {
1668                 // endmatch
1669                 NextLevel();
1670                 return;
1671         }
1672
1673         if(timelimit > 0)
1674                 timelimit += game_starttime;
1675
1676         int overtimes_prev = overtimes;
1677         int wantovertime = 0;
1678
1679         if(checkrules_suddendeathend)
1680         {
1681                 if(!checkrules_suddendeathwarning)
1682                 {
1683                         checkrules_suddendeathwarning = true;
1684                         if(g_race && !g_race_qualifying)
1685                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1686                         else
1687                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1688                 }
1689         }
1690         else
1691         {
1692                 if (timelimit && time >= timelimit)
1693                 {
1694                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1695                         {
1696                                 float totalplayers;
1697                                 float playerswithlaps;
1698                                 float readyplayers;
1699                                 totalplayers = playerswithlaps = readyplayers = 0;
1700                                 FOREACH_CLIENT(IS_PLAYER(it), {
1701                                         ++totalplayers;
1702                                         if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1703                                                 ++playerswithlaps;
1704                                         if(it.ready)
1705                                                 ++readyplayers;
1706                                 });
1707
1708                                 // at least 2 of the players have completed a lap: start the RACE
1709                                 // otherwise, the players should end the qualifying on their own
1710                                 if(readyplayers || playerswithlaps >= 2)
1711                                 {
1712                                         checkrules_suddendeathend = 0;
1713                                         ReadyRestart(true); // go to race
1714                                         return;
1715                                 }
1716                                 else
1717                                         wantovertime |= InitiateSuddenDeath();
1718                         }
1719                         else
1720                                 wantovertime |= InitiateSuddenDeath();
1721                 }
1722         }
1723
1724         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1725         {
1726                 NextLevel();
1727                 return;
1728         }
1729
1730         int checkrules_status = WinningCondition_RanOutOfSpawns();
1731         if(checkrules_status == WINNING_YES)
1732                 bprint("Hey! Someone ran out of spawns!\n");
1733         else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1734                 checkrules_status = M_ARGV(0, float);
1735         else
1736                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1737
1738         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1739         {
1740                 checkrules_status = WINNING_NEVER;
1741                 checkrules_overtimesadded = -1;
1742                 wantovertime |= InitiateSuddenDeath();
1743         }
1744
1745         if(checkrules_status == WINNING_NEVER)
1746                 // equality cases! Nobody wins if the overtime ends in a draw.
1747                 ClearWinners();
1748
1749         if(wantovertime)
1750         {
1751                 if(checkrules_status == WINNING_NEVER)
1752                         InitiateOvertime();
1753                 else
1754                         checkrules_status = WINNING_YES;
1755         }
1756
1757         if(checkrules_suddendeathend)
1758                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1759                         checkrules_status = WINNING_YES;
1760
1761         if(checkrules_status == WINNING_YES)
1762         {
1763                 if (overtimes == -1 && overtimes != overtimes_prev)
1764                 {
1765                         // if suddendeathend overtime has just begun, revert it
1766                         checkrules_suddendeathend = 0;
1767                         overtimes = overtimes_prev;
1768                 }
1769                 //print("WINNING\n");
1770                 NextLevel();
1771         }
1772 }
1773
1774 float want_weapon(entity weaponinfo, float allguns)
1775 {
1776         int d = 0;
1777         bool allow_mutatorblocked = false;
1778
1779         if(!weaponinfo.m_id)
1780                 return 0;
1781
1782         bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1783         d = M_ARGV(1, float);
1784         allguns = M_ARGV(2, bool);
1785         allow_mutatorblocked = M_ARGV(3, bool);
1786
1787         if(allguns)
1788                 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1789         else if(!mutator_returnvalue)
1790                 d = !(!weaponinfo.weaponstart);
1791
1792         if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1793                 d = 0;
1794
1795         float t = weaponinfo.weaponstartoverride;
1796
1797         //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1798
1799         // bit order in t:
1800         // 1: want or not
1801         // 2: is default?
1802         // 4: is set by default?
1803         if(t < 0)
1804                 t = 4 | (3 * d);
1805         else
1806                 t |= (2 * d);
1807
1808         return t;
1809 }
1810
1811 /// Weapons the player normally starts with outside weapon arena.
1812 WepSet weapons_start()
1813 {
1814         WepSet ret = '0 0 0';
1815         FOREACH(Weapons, it != WEP_Null, {
1816                 int w = want_weapon(it, false);
1817                 if (w & 1)
1818                         ret |= it.m_wepset;
1819         });
1820         return ret;
1821 }
1822
1823 WepSet weapons_all()
1824 {
1825         WepSet ret = '0 0 0';
1826         FOREACH(Weapons, it != WEP_Null, {
1827                 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1828                         ret |= it.m_wepset;
1829         });
1830         return ret;
1831 }
1832
1833 WepSet weapons_devall()
1834 {
1835         WepSet ret = '0 0 0';
1836         FOREACH(Weapons, it != WEP_Null,
1837         {
1838                 ret |= it.m_wepset;
1839         });
1840         return ret;
1841 }
1842
1843 WepSet weapons_most()
1844 {
1845         WepSet ret = '0 0 0';
1846         FOREACH(Weapons, it != WEP_Null, {
1847                 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
1848                         ret |= it.m_wepset;
1849         });
1850         return ret;
1851 }
1852
1853 void weaponarena_available_all_update(entity this)
1854 {
1855         if (weaponsInMapAll)
1856         {
1857                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
1858         }
1859         else
1860         {
1861                 // if no weapons are available on the map, just fall back to all weapons arena
1862                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
1863         }
1864 }
1865
1866 void weaponarena_available_devall_update(entity this)
1867 {
1868         if (weaponsInMapAll)
1869         {
1870                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
1871         }
1872         else
1873         {
1874                 // if no weapons are available on the map, just fall back to devall weapons arena
1875                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
1876         }
1877 }
1878
1879 void weaponarena_available_most_update(entity this)
1880 {
1881         if (weaponsInMapAll)
1882         {
1883                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
1884         }
1885         else
1886         {
1887                 // if no weapons are available on the map, just fall back to most weapons arena
1888                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
1889         }
1890 }
1891
1892 void readplayerstartcvars()
1893 {
1894         // initialize starting values for players
1895         start_weapons = '0 0 0';
1896         start_weapons_default = '0 0 0';
1897         start_weapons_defaultmask = '0 0 0';
1898         start_items = 0;
1899         start_ammo_shells = 0;
1900         start_ammo_nails = 0;
1901         start_ammo_rockets = 0;
1902         start_ammo_cells = 0;
1903         start_ammo_plasma = 0;
1904         if (random_start_ammo == NULL)
1905         {
1906                 random_start_ammo = new_pure(random_start_ammo);
1907         }
1908         start_health = cvar("g_balance_health_start");
1909         start_armorvalue = cvar("g_balance_armor_start");
1910
1911         g_weaponarena = 0;
1912         g_weaponarena_weapons = '0 0 0';
1913
1914         string s = cvar_string("g_weaponarena");
1915
1916         MUTATOR_CALLHOOK(SetWeaponArena, s);
1917         s = M_ARGV(0, string);
1918
1919         if (s == "0" || s == "")
1920         {
1921                 // no arena
1922         }
1923         else if (s == "off")
1924         {
1925                 // forcibly turn off weaponarena
1926         }
1927         else if (s == "all" || s == "1")
1928         {
1929                 g_weaponarena = 1;
1930                 g_weaponarena_list = "All Weapons Arena";
1931                 g_weaponarena_weapons = weapons_all();
1932         }
1933         else if (s == "devall")
1934         {
1935                 g_weaponarena = 1;
1936                 g_weaponarena_list = "Dev All Weapons Arena";
1937                 g_weaponarena_weapons = weapons_devall();
1938         }
1939         else if (s == "most")
1940         {
1941                 g_weaponarena = 1;
1942                 g_weaponarena_list = "Most Weapons Arena";
1943                 g_weaponarena_weapons = weapons_most();
1944         }
1945         else if (s == "all_available")
1946         {
1947                 g_weaponarena = 1;
1948                 g_weaponarena_list = "All Available Weapons Arena";
1949
1950                 // this needs to run after weaponsInMapAll is initialized
1951                 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
1952         }
1953         else if (s == "devall_available")
1954         {
1955                 g_weaponarena = 1;
1956                 g_weaponarena_list = "Dev All Available Weapons Arena";
1957
1958                 // this needs to run after weaponsInMapAll is initialized
1959                 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
1960         }
1961         else if (s == "most_available")
1962         {
1963                 g_weaponarena = 1;
1964                 g_weaponarena_list = "Most Available Weapons Arena";
1965
1966                 // this needs to run after weaponsInMapAll is initialized
1967                 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
1968         }
1969         else if (s == "none")
1970         {
1971                 g_weaponarena = 1;
1972                 g_weaponarena_list = "No Weapons Arena";
1973         }
1974         else
1975         {
1976                 g_weaponarena = 1;
1977                 float t = tokenize_console(s);
1978                 g_weaponarena_list = "";
1979                 for (int j = 0; j < t; ++j)
1980                 {
1981                         s = argv(j);
1982                         Weapon wep = Weapon_from_name(s);
1983                         if(wep != WEP_Null)
1984                         {
1985                                 g_weaponarena_weapons |= (wep.m_wepset);
1986                                 g_weaponarena_list = strcat(g_weaponarena_list, wep.netname, " & ");
1987                         }
1988                 }
1989                 if (g_weaponarena_list != "") // remove trailing " & "
1990                         g_weaponarena_list = substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3);
1991                 else // no valid weapon found
1992                         g_weaponarena_list = "No Weapons Arena";
1993         }
1994
1995         if (g_weaponarena)
1996         {
1997                 g_weapon_stay = 0; // incompatible
1998                 start_weapons = g_weaponarena_weapons;
1999                 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
2000                 g_weaponarena_list = strzone(g_weaponarena_list);
2001         }
2002         else
2003         {
2004                 FOREACH(Weapons, it != WEP_Null, {
2005                         int w = want_weapon(it, false);
2006                         WepSet s = it.m_wepset;
2007                         if(w & 1)
2008                                 start_weapons |= s;
2009                         if(w & 2)
2010                                 start_weapons_default |= s;
2011                         if(w & 4)
2012                                 start_weapons_defaultmask |= s;
2013                 });
2014         }
2015
2016         if(cvar("g_balance_superweapons_time") < 0)
2017                 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2018
2019         if(!cvar("g_use_ammunition"))
2020                 start_items |= IT_UNLIMITED_AMMO;
2021
2022         if(start_items & IT_UNLIMITED_AMMO)
2023         {
2024                 start_ammo_shells = 999;
2025                 start_ammo_nails = 999;
2026                 start_ammo_rockets = 999;
2027                 start_ammo_cells = 999;
2028                 start_ammo_plasma = 999;
2029                 start_ammo_fuel = 999;
2030         }
2031         else
2032         {
2033                 start_ammo_shells = cvar("g_start_ammo_shells");
2034                 start_ammo_nails = cvar("g_start_ammo_nails");
2035                 start_ammo_rockets = cvar("g_start_ammo_rockets");
2036                 start_ammo_cells = cvar("g_start_ammo_cells");
2037                 start_ammo_plasma = cvar("g_start_ammo_plasma");
2038                 start_ammo_fuel = cvar("g_start_ammo_fuel");
2039                 random_start_weapons_count = cvar("g_random_start_weapons_count");
2040                 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2041                 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2042                 SetResource(random_start_ammo, RES_ROCKETS, cvar("g_random_start_rockets"));
2043                 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2044                 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2045         }
2046
2047         warmup_start_ammo_shells = start_ammo_shells;
2048         warmup_start_ammo_nails = start_ammo_nails;
2049         warmup_start_ammo_rockets = start_ammo_rockets;
2050         warmup_start_ammo_cells = start_ammo_cells;
2051         warmup_start_ammo_plasma = start_ammo_plasma;
2052         warmup_start_ammo_fuel = start_ammo_fuel;
2053         warmup_start_health = start_health;
2054         warmup_start_armorvalue = start_armorvalue;
2055         warmup_start_weapons = start_weapons;
2056         warmup_start_weapons_default = start_weapons_default;
2057         warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2058
2059         if (!g_weaponarena)
2060         {
2061                 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2062                 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2063                 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2064                 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2065                 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2066                 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2067                 warmup_start_health = cvar("g_warmup_start_health");
2068                 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2069                 warmup_start_weapons = '0 0 0';
2070                 warmup_start_weapons_default = '0 0 0';
2071                 warmup_start_weapons_defaultmask = '0 0 0';
2072                 FOREACH(Weapons, it != WEP_Null, {
2073                         int w = want_weapon(it, autocvar_g_warmup_allguns);
2074                         WepSet s = it.m_wepset;
2075                         if(w & 1)
2076                                 warmup_start_weapons |= s;
2077                         if(w & 2)
2078                                 warmup_start_weapons_default |= s;
2079                         if(w & 4)
2080                                 warmup_start_weapons_defaultmask |= s;
2081                 });
2082         }
2083
2084         if (autocvar_g_jetpack)
2085                 start_items |= ITEM_Jetpack.m_itemid;
2086
2087         MUTATOR_CALLHOOK(SetStartItems);
2088
2089         if (start_items & ITEM_Jetpack.m_itemid)
2090         {
2091                 start_items |= ITEM_JetpackRegen.m_itemid;
2092                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2093                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2094         }
2095
2096         start_ammo_shells = max(0, start_ammo_shells);
2097         start_ammo_nails = max(0, start_ammo_nails);
2098         start_ammo_rockets = max(0, start_ammo_rockets);
2099         start_ammo_cells = max(0, start_ammo_cells);
2100         start_ammo_plasma = max(0, start_ammo_plasma);
2101         start_ammo_fuel = max(0, start_ammo_fuel);
2102         SetResource(random_start_ammo, RES_SHELLS, max(0, GetResource(random_start_ammo, RES_SHELLS)));
2103         SetResource(random_start_ammo, RES_BULLETS, max(0, GetResource(random_start_ammo, RES_BULLETS)));
2104         SetResource(random_start_ammo, RES_ROCKETS, max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2105         SetResource(random_start_ammo, RES_CELLS, max(0, GetResource(random_start_ammo, RES_CELLS)));
2106         SetResource(random_start_ammo, RES_PLASMA, max(0, GetResource(random_start_ammo, RES_PLASMA)));
2107
2108         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2109         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2110         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2111         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2112         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2113         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2114 }
2115
2116 void readlevelcvars()
2117 {
2118         serverflags &= ~SERVERFLAG_ALLOW_FULLBRIGHT;
2119         if(cvar("sv_allow_fullbright"))
2120                 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2121
2122         serverflags &= ~SERVERFLAG_FORBID_PICKUPTIMER;
2123         if(cvar("sv_forbid_pickuptimer"))
2124                 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2125
2126         sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2127
2128         if(cvar("g_campaign"))
2129                 warmup_stage = 0; // no warmup during campaign
2130         else
2131         {
2132                 warmup_stage = autocvar_g_warmup;
2133                 if (warmup_stage < 0 || warmup_stage > 1)
2134                         warmup_limit = -1; // don't start until there's enough players
2135                 else if (warmup_stage == 1)
2136                 {
2137                         // this code is duplicated in ReadyCount()
2138                         warmup_limit = cvar("g_warmup_limit");
2139                         if(warmup_limit == 0)
2140                                 warmup_limit = autocvar_timelimit * 60;
2141                 }
2142         }
2143
2144         g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2145         g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2146         g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2147         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
2148         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
2149         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
2150         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2151         g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2152         g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2153         g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2154         g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
2155         g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
2156         g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
2157         g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2158
2159         g_pickup_shells = cvar("g_pickup_shells");
2160         g_pickup_shells_max = cvar("g_pickup_shells_max");
2161         g_pickup_nails = cvar("g_pickup_nails");
2162         g_pickup_nails_max = cvar("g_pickup_nails_max");
2163         g_pickup_rockets = cvar("g_pickup_rockets");
2164         g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2165         g_pickup_cells = cvar("g_pickup_cells");
2166         g_pickup_cells_max = cvar("g_pickup_cells_max");
2167         g_pickup_plasma = cvar("g_pickup_plasma");
2168         g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2169         g_pickup_fuel = cvar("g_pickup_fuel");
2170         g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2171         g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2172         g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2173         g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2174         g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2175         g_pickup_armormedium = cvar("g_pickup_armormedium");
2176         g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2177         g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2178         g_pickup_armorbig = cvar("g_pickup_armorbig");
2179         g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2180         g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2181         g_pickup_armormega = cvar("g_pickup_armormega");
2182         g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2183         g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2184         g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2185         g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2186         g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2187         g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2188         g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2189         g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2190         g_pickup_healthbig = cvar("g_pickup_healthbig");
2191         g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2192         g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2193         g_pickup_healthmega = cvar("g_pickup_healthmega");
2194         g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2195         g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2196
2197         g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2198         g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2199
2200         g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2201         if(!g_weapon_stay)
2202                 g_weapon_stay = cvar("g_weapon_stay");
2203
2204         MUTATOR_CALLHOOK(ReadLevelCvars);
2205
2206         if (!warmup_stage && !autocvar_g_campaign)
2207                 game_starttime = time + cvar("g_start_delay");
2208
2209         FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2210
2211         readplayerstartcvars();
2212 }
2213
2214 void InitializeEntity(entity e, void(entity this) func, int order)
2215 {
2216         entity prev, cur;
2217
2218         if (!e || e.initialize_entity)
2219         {
2220                 // make a proxy initializer entity
2221                 entity e_old = e;
2222                 e = new(initialize_entity);
2223                 e.enemy = e_old;
2224         }
2225
2226         e.initialize_entity = func;
2227         e.initialize_entity_order = order;
2228
2229         cur = initialize_entity_first;
2230         prev = NULL;
2231         for (;;)
2232         {
2233                 if (!cur || cur.initialize_entity_order > order)
2234                 {
2235                         // insert between prev and cur
2236                         if (prev)
2237                                 prev.initialize_entity_next = e;
2238                         else
2239                                 initialize_entity_first = e;
2240                         e.initialize_entity_next = cur;
2241                         return;
2242                 }
2243                 prev = cur;
2244                 cur = cur.initialize_entity_next;
2245         }
2246 }
2247 void InitializeEntitiesRun()
2248 {
2249         entity startoflist = initialize_entity_first;
2250         initialize_entity_first = NULL;
2251         delete_fn = remove_except_protected;
2252         for (entity e = startoflist; e; e = e.initialize_entity_next)
2253         {
2254                 e.remove_except_protected_forbidden = 1;
2255         }
2256         for (entity e = startoflist; e; )
2257         {
2258                 e.remove_except_protected_forbidden = 0;
2259                 e.initialize_entity_order = 0;
2260                 entity next = e.initialize_entity_next;
2261                 e.initialize_entity_next = NULL;
2262                 var void(entity this) func = e.initialize_entity;
2263                 e.initialize_entity = func_null;
2264                 if (e.classname == "initialize_entity")
2265                 {
2266                         entity wrappee = e.enemy;
2267                         builtin_remove(e);
2268                         e = wrappee;
2269                 }
2270                 //dprint("Delayed initialization: ", e.classname, "\n");
2271                 if (func)
2272                 {
2273                         func(e);
2274                 }
2275                 else
2276                 {
2277                         eprint(e);
2278                         backtrace(strcat("Null function in: ", e.classname, "\n"));
2279                 }
2280                 e = next;
2281         }
2282         delete_fn = remove_unsafely;
2283 }
2284
2285 // deferred dropping
2286 // ported from VM_SV_droptofloor TODO: make a common function for the client-side?
2287 void DropToFloor_Handler(entity this)
2288 {
2289         if(!this || wasfreed(this))
2290         {
2291                 // no modifying free entities
2292                 return;
2293         }
2294
2295         vector end = this.origin;
2296         if (autocvar_sv_mapformat_is_quake3)
2297                 end.z -= 4096;
2298         else if (autocvar_sv_mapformat_is_quake2)
2299                 end.z -= 128;
2300         else
2301                 end.z -= 256; // Quake, QuakeWorld
2302
2303         // NOTE: SV_NudgeOutOfSolid is used in the engine here
2304         if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2305         {
2306                 _Movetype_UnstickEntity(this);
2307                 move_out_of_solid(this);
2308         }
2309
2310         tracebox(this.origin, this.mins, this.maxs, end, MOVE_NORMAL, this);
2311
2312         if(trace_startsolid && autocvar_sv_gameplayfix_droptofloorstartsolid)
2313         {
2314                 vector offset, org;
2315                 offset = 0.5 * (this.mins + this.maxs);
2316                 offset.z = this.mins.z;
2317                 org = this.origin + offset;
2318                 traceline(org, end, MOVE_NORMAL, this);
2319                 trace_endpos = trace_endpos - offset;
2320                 if(trace_startsolid)
2321                 {
2322                         LOG_DEBUGF("DropToFloor_Handler: %v could not fix badly placed entity", this.origin);
2323                         _Movetype_LinkEdict(this, false);
2324                         SET_ONGROUND(this);
2325                         this.groundentity = NULL;
2326                 }
2327                 else if(trace_fraction < 1)
2328                 {
2329                         LOG_DEBUGF("DropToFloor_Handler: %v fixed badly placed entity", this.origin);
2330                         setorigin(this, trace_endpos);
2331                         if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2332                         {
2333                                 _Movetype_UnstickEntity(this);
2334                                 move_out_of_solid(this);
2335                         }
2336                         SET_ONGROUND(this);
2337                         this.groundentity = trace_ent;
2338                         // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2339                         this.move_suspendedinair = true;
2340                 }
2341         }
2342         else
2343         {
2344                 if(!trace_allsolid && trace_fraction < 1)
2345                 {
2346                         setorigin(this, trace_endpos);
2347                         SET_ONGROUND(this);
2348                         this.groundentity = trace_ent;
2349                         // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2350                         this.move_suspendedinair = true;
2351                 }
2352                 else
2353                 {
2354                         // if we can't get the entity out of solid, mark it as on ground so physics doesn't attempt to drop it
2355                         // hacky workaround for #2774
2356                         SET_ONGROUND(this);
2357                 }
2358         }
2359         this.dropped_origin = this.origin;
2360 }
2361
2362 void droptofloor(entity this)
2363 {
2364         InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2365 }
2366
2367 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2368 void RunThink(entity this, float dt)
2369 {
2370         // don't let things stay in the past.
2371         // it is possible to start that way by a trigger with a local time.
2372         if(this.nextthink <= 0 || this.nextthink > time + dt)
2373                 return;
2374
2375         float oldtime = time; // do we need to save this?
2376
2377         for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2378         {
2379                 time = max(oldtime, this.nextthink);
2380                 this.nextthink = 0;
2381
2382                 if(getthink(this))
2383                         getthink(this)(this);
2384                 // mods often set nextthink to time to cause a think every frame,
2385                 // we don't want to loop in that case, so exit if the new nextthink is
2386                 // <= the time the qc was told, also exit if it is past the end of the
2387                 // frame
2388                 if(this.nextthink <= time || this.nextthink > oldtime + dt || !autocvar_sv_gameplayfix_multiplethinksperframe)
2389                         break;
2390         }
2391
2392         time = oldtime;
2393 }
2394
2395 bool autocvar_sv_freezenonclients;
2396 void Physics_Frame()
2397 {
2398         if(autocvar_sv_freezenonclients)
2399                 return;
2400
2401         IL_EACH(g_moveables, true,
2402         {
2403                 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2404                         continue;
2405
2406                 //set_movetype(it, it.move_movetype);
2407                 // inline the set_movetype function, since this is called a lot
2408                 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2409
2410                 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2411                         Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2412
2413                 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2414                 {
2415                         if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2416                                 continue; // these movetypes have no regular think function
2417                         // handle thinking here
2418                         if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + PHYS_INPUT_TIMELENGTH)
2419                                 RunThink(it, PHYS_INPUT_TIMELENGTH);
2420                 }
2421         });
2422
2423         if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2424                 return;
2425
2426         // make a second pass to see if any ents spawned this frame and make
2427         // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2428         // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2429         IL_EACH(g_moveables, it.move_qcphysics,
2430         {
2431                 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2432                         continue;
2433                 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2434         });
2435 }
2436
2437 void systems_update();
2438 void EndFrame()
2439 {
2440         anticheat_endframe();
2441
2442         Physics_Frame();
2443
2444         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2445                 entity e = IS_SPEC(it) ? it.enemy : it;
2446                 if (e.typehitsound) {
2447                         STAT(TYPEHIT_TIME, it) = time;
2448                 } else if (e.killsound) {
2449                         STAT(KILL_TIME, it) = time;
2450                 } else if (e.hitsound_damage_dealt) {
2451                         STAT(HIT_TIME, it) = time;
2452                         // NOTE: this is not accurate as client code doesn't need so much accuracy for its purposes
2453                         STAT(HITSOUND_DAMAGE_DEALT_TOTAL, it) += ceil(e.hitsound_damage_dealt);
2454                 }
2455         });
2456         // add 1 frametime because after this, engine SV_Physics
2457         // increases time by a frametime and then networks the frame
2458         // add another frametime because client shows everything with
2459         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2460         // needed!
2461         float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2462         FOREACH_CLIENT(true, {
2463                 it.typehitsound = false;
2464                 it.hitsound_damage_dealt = 0;
2465                 it.killsound = false;
2466                 antilag_record(it, CS(it), altime);
2467         });
2468         IL_EACH(g_monsters, true,
2469         {
2470                 antilag_record(it, it, altime);
2471         });
2472         IL_EACH(g_projectiles, it.classname == "nade",
2473         {
2474                 antilag_record(it, it, altime);
2475         });
2476         systems_update();
2477         IL_ENDFRAME();
2478 }
2479
2480
2481 /*
2482  * RedirectionThink:
2483  * returns true if redirecting
2484  */
2485 float redirection_timeout;
2486 float redirection_nextthink;
2487 float RedirectionThink()
2488 {
2489         float clients_found;
2490
2491         if(redirection_target == "")
2492                 return false;
2493
2494         if(!redirection_timeout)
2495         {
2496                 cvar_set("sv_public", "-2");
2497                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2498                 if(redirection_target == "self")
2499                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2500                 else
2501                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2502         }
2503
2504         if(time < redirection_nextthink)
2505                 return true;
2506
2507         redirection_nextthink = time + 1;
2508
2509         clients_found = 0;
2510         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2511                 // TODO add timer
2512                 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2513                 if(redirection_target == "self")
2514                         stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2515                 else
2516                         stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2517                 ++clients_found;
2518         });
2519
2520         LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2521
2522         if(time > redirection_timeout || clients_found == 0)
2523                 localcmd("\nwait; wait; wait; quit\n");
2524
2525         return true;
2526 }
2527
2528 void RestoreGame()
2529 {
2530         // Loaded from a save game
2531         // some things then break, so let's work around them...
2532
2533         // Progs DB (capture records)
2534         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2535
2536         // Mapinfo
2537         MapInfo_Shutdown();
2538         MapInfo_Enumerate();
2539         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2540         WeaponStats_Init();
2541
2542         TargetMusic_RestoreGame();
2543 }
2544
2545 void Shutdown()
2546 {
2547         game_stopped = 2;
2548
2549         if(world_initialized > 0)
2550         {
2551                 world_initialized = 0;
2552
2553                 // if a timeout is active, reset the slowmo value to normal
2554                 if(timeout_status == TIMEOUT_ACTIVE)
2555                         cvar_set("slowmo", ftos(orig_slowmo));
2556
2557                 LOG_TRACE("Saving persistent data...");
2558                 Ban_SaveBans();
2559
2560                 // playerstats with unfinished match
2561                 PlayerStats_GameReport(false);
2562
2563                 if(!cheatcount_total)
2564                 {
2565                         if(autocvar_sv_db_saveasdump)
2566                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2567                         else
2568                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2569                 }
2570                 if(autocvar_developer > 0)
2571                 {
2572                         if(autocvar_sv_db_saveasdump)
2573                                 db_dump(TemporaryDB, "server-temp.db");
2574                         else
2575                                 db_save(TemporaryDB, "server-temp.db");
2576                 }
2577                 CheatShutdown(); // must be after cheatcount check
2578                 db_close(ServerProgsDB);
2579                 db_close(TemporaryDB);
2580                 LOG_TRACE("Saving persistent data... done!");
2581                 // tell the bot system the game is ending now
2582                 bot_endgame();
2583
2584                 WeaponStats_Shutdown();
2585                 MapInfo_Shutdown();
2586
2587                 strfree(sv_termsofservice_url_escaped);
2588         }
2589         else if(world_initialized == 0)
2590         {
2591                 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2592         }
2593         else
2594         {
2595                 __init_dedicated_server_shutdown();
2596         }
2597 }