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