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