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