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>
51 const float LATENCY_THINKRATE = 10;
56 void PingPLReport_Think(entity this)
61 delta = 3 / maxclients;
62 if(delta < sys_frametime)
64 this.nextthink = time + delta;
66 e = edict_num(this.cnt + 1);
67 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
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));
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))
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");
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);
92 this.cnt = (this.cnt + 1) % maxclients;
94 void PingPLReport_Spawn()
96 pingplreport = new_pure(pingplreport);
97 setthink(pingplreport, PingPLReport_Think);
98 pingplreport.nextthink = time;
101 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
103 void SetDefaultAlpha()
105 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
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;
114 void GotoFirstMap(entity this)
117 if(autocvar__sv_init)
119 // cvar_set("_sv_init", "0");
120 // we do NOT set this to 0 any more, so someone "accidentally" changing
121 // to this "init" map on a dedicated server will cause no permanent harm
124 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
126 if(!DoNextMapOverride(1))
134 this.nextthink = time;
138 this.nextthink = time + 1;
139 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
143 void cvar_changes_init()
147 float n, i, adding, pureadding;
149 strfree(cvar_changes);
150 strfree(cvar_purechanges);
151 cvar_purechanges_count = 0;
154 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
160 for(i = 0; i < n; ++i)
162 k = bufstr_get(h, i);
164 #define BADPREFIX_COND(p) (substring(k, 0, strlen(p)) == p)
165 #define BADSUFFIX_COND(s) (substring(k, -strlen(s), -1) == s)
167 #define BADPREFIX(p) if(BADPREFIX_COND(p)) continue
168 #define BADPRESUFFIX(p, s) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s)) continue
169 #define BADCVAR(p) if(k == p) continue
170 #define BADVALUE(p, val) if (k == p && v == val) continue
171 #define BADPRESUFFIXVALUE(p, s, val) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s) && v == val) continue
173 // general excludes and namespaces for server admin used cvars
174 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
178 BADPREFIX("cvar_check_");
180 BADCVAR("g_configversion");
181 BADCVAR("halflifebsp");
182 BADCVAR("sv_mapformat_is_quake2");
183 BADCVAR("sv_mapformat_is_quake3");
184 BADPREFIX("sv_world");
190 BADPREFIX("scoreboard_");
191 BADPREFIX("g_campaign");
192 BADPREFIX("g_waypointsprite_");
198 BADPREFIX("net_slist_");
204 BADPREFIX("sensitivity");
205 BADPREFIX("userbind");
208 BADPREFIX("crosshair");
209 BADCVAR("mod_q3bsp_lightmapmergepower");
210 BADCVAR("mod_q3bsp_nolightmaps");
212 BADCVAR("mastervolume");
214 BADCVAR("bgmvolume");
215 BADCVAR("in_pitch_min");
216 BADCVAR("in_pitch_max");
219 BADCVAR("developer");
220 BADCVAR("log_dest_udp");
221 BADCVAR("net_address");
222 BADCVAR("net_address_ipv6");
224 BADCVAR("savedgamecfg");
225 BADCVAR("serverconfig");
226 BADCVAR("sv_autoscreenshot");
227 BADCVAR("sv_heartbeatperiod");
228 BADCVAR("sv_vote_master_password");
229 BADCVAR("sys_colortranslation");
230 BADCVAR("sys_specialcharactertranslation");
231 BADCVAR("timeformat");
232 BADCVAR("timestamps");
233 BADCVAR("g_require_stats");
234 BADCVAR("g_chatban_list");
235 BADCVAR("g_playban_list");
236 BADCVAR("g_playban_minigames");
237 BADCVAR("g_voteban_list");
238 BADPREFIX("developer_");
240 BADPREFIX("g_banned_list");
241 BADPREFIX("g_require_stats_");
242 BADPREFIX("g_chat_flood_");
243 BADPREFIX("g_ghost_items");
244 BADPREFIX("g_playerstats_");
245 BADPREFIX("g_voice_flood_");
246 BADPREFIX("log_file");
249 BADPREFIX("sv_allowdownloads");
250 BADPREFIX("sv_autodemo");
251 BADPREFIX("sv_curl_");
252 BADPREFIX("sv_eventlog");
253 BADPREFIX("sv_logscores_");
254 BADPREFIX("sv_master");
255 BADPREFIX("sv_weaponstats_");
256 BADPREFIX("sv_waypointsprite_");
257 BADCVAR("rescan_pending");
259 // these can contain player IDs, so better hide
260 BADPREFIX("g_forced_team_");
261 BADCVAR("sv_allow_customplayermodels_idlist");
262 BADCVAR("sv_allow_customplayermodels_speciallist");
265 BADCVAR("fraglimit");
267 BADCVAR("g_assault");
269 BADCVAR("g_ca_teams");
270 BADCVAR("g_conquest");
271 BADCVAR("g_conquest_teams");
276 BADCVAR("g_domination");
277 BADCVAR("g_domination_default_teams");
279 BADCVAR("g_duel_not_dm_maps");
280 BADCVAR("g_freezetag");
281 BADCVAR("g_freezetag_teams");
282 BADCVAR("g_invasion_type");
283 BADCVAR("g_jailbreak");
284 BADCVAR("g_jailbreak_teams");
285 BADCVAR("g_keepaway");
286 BADCVAR("g_keyhunt");
287 BADCVAR("g_keyhunt_teams");
290 BADCVAR("g_nexball");
291 BADCVAR("g_onslaught");
293 BADCVAR("g_race_laps_limit");
294 BADCVAR("g_race_qualifying_timelimit");
295 BADCVAR("g_race_qualifying_timelimit_override");
296 BADCVAR("g_runematch");
297 BADCVAR("g_shootfromeye");
299 BADCVAR("g_survival");
300 BADCVAR("g_survival_not_dm_maps");
302 BADCVAR("g_tdm_on_dm_maps");
303 BADCVAR("g_tdm_teams");
305 BADCVAR("g_tka_on_ka_maps");
306 BADCVAR("g_tka_on_tdm_maps");
307 BADCVAR("g_tka_teams");
308 BADCVAR("g_tmayhem");
309 BADCVAR("g_tmayhem_teams");
311 BADCVAR("leadlimit");
314 BADCVAR("timelimit");
315 BADCVAR("g_mapinfo_q3compat");
316 BADCVAR("g_mapinfo_settemp_acl");
317 BADCVAR("g_mapinfo_ignore_warnings");
318 BADCVAR("g_maplist_ignore_sizes");
319 BADCVAR("g_maplist_sizes_count_bots");
323 BADCVAR("g_maplist");
324 BADCVAR("g_maplist_mostrecent");
326 BADCVAR("sv_termsofservice_url");
329 d = cvar_defstring(k);
335 if (cvar_changes == "")
336 cvar_changes = "// this server runs at modified server settings:\n";
338 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
339 if(strlen(cvar_changes) >= VM_TEMPSTRING_MAXSIZE)
341 cvar_changes = "// too many settings have been changed to show them here\n";
346 // now check if the changes are actually gameplay relevant
348 // does nothing gameplay relevant
349 BADCVAR("captureleadlimit_override");
350 BADCVAR("condump_stripcolors");
351 BADCVAR("fs_gamedir");
352 BADCVAR("g_allow_oldvortexbeam");
353 BADCVAR("g_balance_kill_delay");
354 BADCVAR("g_buffs_pickup_anyway");
355 BADCVAR("g_buffs_randomize");
356 BADCVAR("g_buffs_randomize_teamplay");
357 BADCVAR("g_campcheck_distance");
358 BADCVAR("g_chatsounds");
359 BADCVAR("g_ca_point_leadlimit");
360 BADCVAR("g_ca_point_limit");
361 BADCVAR("g_ca_spectate_enemies");
362 BADCVAR("g_ctf_captimerecord_always");
363 BADCVAR("g_ctf_flag_glowtrails");
364 BADCVAR("g_ctf_dynamiclights");
365 BADCVAR("g_ctf_flag_pickup_verbosename");
366 BADCVAR("g_ctf_flagcarrier_auto_helpme_damage");
367 BADPRESUFFIX("g_ctf_flag_", "_model");
368 BADPRESUFFIX("g_ctf_flag_", "_skin");
369 BADCVAR("g_domination_point_leadlimit");
370 BADCVAR("g_forced_respawn");
371 BADCVAR("g_freezetag_point_leadlimit");
372 BADCVAR("g_freezetag_point_limit");
373 BADCVAR("g_glowtrails");
375 BADCVAR("g_casings");
376 BADCVAR("g_invasion_point_limit");
377 BADCVAR("g_jump_grunt");
378 BADCVAR("g_keepaway_ballcarrier_effects");
379 BADCVAR("g_keepawayball_effects");
380 BADCVAR("g_keyhunt_point_leadlimit");
381 BADCVAR("g_nexball_goalleadlimit");
382 BADCVAR("g_new_toys_autoreplace");
383 BADCVAR("g_new_toys_use_pickupsound");
384 BADCVAR("g_physics_predictall");
385 BADCVAR("g_piggyback");
386 BADCVAR("g_playerclip_collisions");
387 BADCVAR("g_spawn_alloweffects");
388 BADCVAR("g_tdm_point_leadlimit");
389 BADCVAR("g_tdm_point_limit");
390 BADCVAR("g_mayhem_point_limit");
391 BADCVAR("g_mayhem_point_leadlimit");
392 BADCVAR("g_tmayhem_point_limit");
393 BADCVAR("g_tmayhem_point_leadlimit");
394 BADCVAR("leadlimit_and_fraglimit");
395 BADCVAR("leadlimit_override");
397 BADCVAR("sv_announcer");
398 BADCVAR("sv_autopause");
399 BADCVAR("sv_checkforpacketsduringsleep");
400 BADCVAR("sv_damagetext");
401 BADCVAR("sv_db_saveasdump");
402 BADCVAR("sv_intermission_cdtrack");
403 BADCVAR("sv_mapchange_delay");
404 BADCVAR("sv_minigames");
405 BADCVAR("sv_namechangetimer");
406 BADCVAR("sv_precacheplayermodels");
407 BADCVAR("sv_qcphysics");
409 BADCVAR("sv_stepheight");
410 BADCVAR("sv_timeout");
411 BADCVAR("sv_weapons_modeloverride");
412 BADCVAR("w_prop_interval");
414 BADPREFIX("crypto_");
415 BADPREFIX("g_chat_");
416 BADPREFIX("g_ctf_captimerecord_");
417 BADPREFIX("g_hats_");
418 BADPREFIX("g_maplist_");
420 BADPREFIX("g_respawn_");
422 BADPREFIX("notification_");
425 BADPREFIX("sv_allow_");
426 BADPREFIX("sv_cullentities_");
427 BADPREFIX("sv_maxidle");
428 BADPREFIX("sv_minigames_");
429 BADPREFIX("sv_radio_");
430 BADPREFIX("sv_timeout_");
431 BADPREFIX("sv_vote_");
432 BADPREFIX("timelimit_");
433 BADPRESUFFIX("g_", "_round_timelimit");
435 // allowed changes to server admins (please sync this to server.cfg)
439 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
441 // yes, this does contain some redundant stuff, don't really care
442 BADPREFIX("bot_ai_");
443 BADCVAR("bot_config_file");
444 BADCVAR("bot_number");
445 BADCVAR("bot_prefix");
446 BADCVAR("bot_suffix");
447 BADCVAR("capturelimit_override");
448 BADCVAR("fraglimit_override");
450 BADCVAR("g_antilag");
451 BADCVAR("g_balance_teams");
452 BADCVAR("g_balance_teams_prevent_imbalance");
453 BADCVAR("g_balance_teams_scorefactor");
454 BADCVAR("g_ban_sync_trusted_servers");
455 BADCVAR("g_ban_sync_uri");
457 BADCVAR("g_ca_teams_override");
458 BADCVAR("g_ca_prevent_stalemate");
459 BADCVAR("g_ctf_fullbrightflags");
460 BADCVAR("g_ctf_ignore_frags");
461 BADCVAR("g_ctf_leaderboard");
462 BADCVAR("g_domination_point_limit");
463 BADCVAR("g_domination_teams_override");
464 BADCVAR("g_freezetag_revive_spawnshield");
465 BADCVAR("g_freezetag_teams_override");
466 BADCVAR("g_friendlyfire");
467 BADCVAR("g_fullbrightitems");
468 BADCVAR("g_fullbrightplayers");
469 BADCVAR("g_keyhunt_point_limit");
470 BADCVAR("g_keyhunt_teams_override");
471 BADCVAR("g_lms_lives_override");
472 BADCVAR("g_mayhem_powerups");
473 BADCVAR("g_maplist");
474 BADCVAR("g_maxplayers");
475 BADCVAR("g_mirrordamage");
476 BADCVAR("g_nexball_goallimit");
477 BADCVAR("g_norecoil");
478 BADCVAR("g_physics_clientselect");
480 BADCVAR("g_powerups");
481 BADCVAR("g_powerups_drop_ondeath");
482 BADCVAR("g_player_brightness");
483 BADCVAR("g_rocket_flying");
484 BADCVAR("g_rocket_flying_disabledelays");
485 BADPREFIX("g_spawnshield");
486 BADCVAR("g_start_delay");
487 BADCVAR("g_superspectate");
488 BADCVAR("g_tdm_teams_override");
489 BADCVAR("g_tmayhem_teams_override");
490 BADCVAR("g_tmayhem_powerups");
491 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
494 BADCVAR("maxplayers");
495 BADCVAR("minplayers");
496 BADCVAR("minplayers_per_team");
497 BADCVAR("net_address");
499 BADCVAR("rcon_password");
500 BADCVAR("rcon_restricted_commands");
501 BADCVAR("rcon_restricted_password");
503 BADCVAR("sv_adminnick");
504 BADCVAR("sv_autoscreenshot");
505 BADCVAR("sv_autotaunt");
506 BADCVAR("sv_curl_defaulturl");
507 BADCVAR("sv_defaultcharacter");
508 BADCVAR("sv_defaultcharacterskin");
509 BADCVAR("sv_defaultplayercolors");
510 BADCVAR("sv_defaultplayermodel");
511 BADCVAR("sv_defaultplayerskin");
512 BADCVAR("sv_maxrate");
514 BADCVAR("sv_public");
515 BADCVAR("sv_showfps");
516 BADCVAR("sv_showspectators");
517 BADCVAR("sv_status_privacy");
519 BADCVAR("sv_vote_call");
520 BADCVAR("sv_vote_commands");
521 BADCVAR("sv_vote_majority_factor");
522 BADCVAR("sv_vote_master");
523 BADCVAR("sv_vote_master_commands");
524 BADCVAR("sv_vote_master_password");
525 BADCVAR("sv_vote_simple_majority_factor");
526 BADVALUE("sys_ticrate", "0.0166667");
527 BADVALUE("sys_ticrate", "0.0333333");
528 BADCVAR("teamplay_mode");
529 BADCVAR("timelimit_override");
530 BADPREFIX("g_warmup");
531 BADPREFIX("sv_info_");
532 BADPREFIX("sv_ready_restart_");
534 BADPRESUFFIXVALUE("g_", "_weaponarena", "most");
535 BADPRESUFFIXVALUE("g_", "_weaponarena", "most_available");
537 // mutators that announce themselves properly to the server browser
538 BADCVAR("g_instagib");
539 BADCVAR("g_new_toys");
541 BADCVAR("g_grappling_hook");
542 BADCVAR("g_jetpack");
548 #undef BADPRESUFFIXVALUE
552 if (cvar_purechanges == "")
553 cvar_purechanges = "// this server runs at modified gameplay settings:\n";
555 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
556 if(strlen(cvar_purechanges) >= VM_TEMPSTRING_MAXSIZE)
558 cvar_purechanges = "// too many settings have been changed to show them here\n";
562 ++cvar_purechanges_count;
563 // WARNING: this variable is used for the server list
564 // NEVER dare to skip this code!
565 // Hacks to intentionally appearing as "pure server" even though you DO have
566 // modified settings may be punished by removal from the server list.
567 // You can do to the variables cvar_changes and cvar_purechanges all you want,
572 if(cvar_changes == "")
573 cvar_changes = "// this server runs at default server settings\n";
574 cvar_changes = strzone(cvar_changes);
576 if(cvar_purechanges == "")
577 cvar_purechanges = "// this server runs at default gameplay settings\n";
578 cvar_purechanges = strzone(cvar_purechanges);
582 bool RandomSeed_Send(entity this, entity to, int sf)
584 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
585 WriteShort(MSG_ENTITY, this.cnt);
588 void RandomSeed_Think(entity this)
590 this.cnt = bound(0, floor(random() * 65536), 65535);
591 this.nextthink = time + 5;
595 void RandomSeed_Spawn()
597 randomseed = new_pure(randomseed);
598 setthink(randomseed, RandomSeed_Think);
599 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
601 getthink(randomseed)(randomseed); // sets random seed and nextthink
604 spawnfunc(__init_dedicated_server)
606 // handler for _init/_init map (only for dedicated server initialization)
608 world_initialized = -1; // don't complain
610 delete_fn = remove_unsafely;
612 entity e = new(GotoFirstMap);
613 setthink(e, GotoFirstMap);
614 e.nextthink = time; // this is usually 1 at this point
616 e = new(info_player_deathmatch); // safeguard against player joining
618 // assign reflectively to avoid "assignment to world" warning
619 for (int i = 0, n = numentityfields(); i < n; ++i)
621 string k = entityfieldname(i);
622 if (k == "classname")
624 // safeguard against various stuff ;)
625 putentityfieldstring(i, this, "worldspawn");
630 // needs to be done so early because of the constants they create
633 static_init_precache();
635 IL_PUSH(g_spawnpoints, e); // just incase
638 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
641 void __init_dedicated_server_shutdown() {
645 STATIC_INIT_EARLY(maxclients)
648 for (entity head = nextent(NULL); head; head = nextent(head)) {
653 void GameplayMode_DelayedInit(entity this)
655 // at this stage team entities are spawned, teamplay contains the number of them
657 if(!scores_initialized)
658 ScoreRules_generic();
660 if (warmup_stage >= 0 && autocvar_g_maxplayers >= 0)
663 MapReadSizes(mapname);
665 if (autocvar_g_maxplayers < 0)
667 if (map_maxplayers <= 0)
668 map_maxplayers = maxclients; // unlimited, but may need rounding
669 map_maxplayers = bound(max(2, AVAILABLE_TEAMS * 2), map_maxplayers, maxclients);
672 // automatic maxplayers should be a multiple of team count
673 int down = map_maxplayers % AVAILABLE_TEAMS;
674 int up = AVAILABLE_TEAMS - down;
675 map_maxplayers += (up < down && up + map_maxplayers <= maxclients) ? up : -down;
679 if (warmup_stage < 0)
681 int m = GetPlayerLimit();
682 if (m <= 0) m = maxclients;
683 map_minplayers = bound(max(2, AVAILABLE_TEAMS * 2), map_minplayers, m);
686 // automatic minplayers should be a multiple of team count
687 int down = map_minplayers % AVAILABLE_TEAMS;
688 int up = AVAILABLE_TEAMS - down;
689 map_minplayers += (up < down && up + map_minplayers <= m) ? up : -down;
693 map_minplayers = 0; // don't display a minimum if it's not used (g_maxplayers < 0 && g_warmup >= 0)
696 void InitGameplayMode()
700 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
702 // assign reflectively to avoid "assignment to world" warning
703 for (int i = 0, done = 0, n = numentityfields(); i < n; ++i)
705 string k = entityfieldname(i);
706 vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
709 putentityfieldstring(i, world, sprintf("%v", v));
710 if (++done == 2) break;
713 // currently, NetRadiant's limit is 131072 qu for each side
714 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
715 // set the distance according to map size but don't go over the limit to avoid issues with float precision
716 // in case somebody makes extremely large maps
717 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
719 MapInfo_LoadMapSettings(mapname);
720 GameRules_teams(false);
722 if (!cvar_value_issafe(world.fog))
724 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
725 world.fog = string_null;
727 if(MapInfo_Map_fog != "")
729 if(MapInfo_Map_fog == "none")
730 world.fog = string_null;
732 world.fog = strzone(MapInfo_Map_fog);
734 clientstuff = strzone(MapInfo_Map_clientstuff);
736 MapInfo_ClearTemps();
738 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
740 cache_mutatormsg = strzone("");
741 cache_lastmutatormsg = strzone("");
743 InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
746 bool world_already_spawned;
747 spawnfunc(worldspawn)
749 cvar_set("_endmatch", "0");
750 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
752 if (autocvar_sv_termsofservice_url && autocvar_sv_termsofservice_url != "")
754 strcpy(sv_termsofservice_url_escaped, strreplace(":", "|", autocvar_sv_termsofservice_url));
758 strcpy(sv_termsofservice_url_escaped, "INVALID");
761 bool wantrestart = false;
763 if (!server_is_dedicated)
765 // DP unloads dlcache pk3s before starting a listen server since https://gitlab.com/xonotic/darkplaces/-/merge_requests/134
766 // restore csqc_progname too
767 string expect = "csprogs.dat";
768 wantrestart = cvar_string("csqc_progname") != expect;
769 cvar_set("csqc_progname", expect);
773 // Try to use versioned csprogs from pk3
774 // Only ever use versioned csprogs.dat files on dedicated servers;
775 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
776 string pk3csprogs = "csprogs-" WATERMARK ".dat";
777 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
778 string select = "csprogs.dat";
779 if (fexists(pk3csprogs)) select = pk3csprogs;
780 if (cvar_string("csqc_progname") != select)
782 cvar_set("csqc_progname", select);
785 // Check for updates on startup
786 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
787 int sentinel = fopen("progs.txt", FILE_READ);
790 string switchversion = fgets(sentinel);
792 if (switchversion != "" && switchversion != WATERMARK)
794 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
795 // if it doesn't exist, assume either:
796 // a) the current program was overwritten
797 // b) this is a client only update
798 string newprogs = sprintf("progs-%s.dat", switchversion);
799 if (fexists(newprogs))
801 cvar_set("sv_progs", newprogs);
804 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
805 if (fexists(newcsprogs))
807 cvar_set("csqc_progname", newcsprogs);
815 LOG_INFO("Restart requested");
816 changelevel(mapname);
817 // let initialization continue, shutdown depends on it
821 if(world_already_spawned)
822 error("world already spawned - you may have EXACTLY ONE worldspawn!");
823 world_already_spawned = true;
825 delete_fn = remove_safely; // during spawning, watch what you remove!
827 cvar_changes_init(); // do this very early now so it REALLY matches the server config
829 // default to RACE_RECORD, can be overwritten by gamemodes
830 record_type = RACE_RECORD;
832 // needs to be done so early because of the constants they create
835 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
837 TemporaryDB = db_create();
842 // 1 FLICKER (first variety)
843 lightstyle(1, "mmnmmommommnonmmonqnmmo");
845 // 2 SLOW STRONG PULSE
846 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
848 // 3 CANDLE (first variety)
849 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
852 lightstyle(4, "mamamamamama");
855 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
857 // 6 FLICKER (second variety)
858 lightstyle(6, "nmonqnmomnmomomno");
860 // 7 CANDLE (second variety)
861 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
863 // 8 CANDLE (third variety)
864 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
866 // 9 SLOW STROBE (fourth variety)
867 lightstyle(9, "aaaaaaaazzzzzzzz");
869 // 10 FLUORESCENT FLICKER
870 lightstyle(10, "mmamammmmammamamaaamammma");
872 // 11 SLOW PULSE NOT FADE TO BLACK
873 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
875 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
880 if(autocvar_g_campaign)
883 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
885 Map_MarkAsRecent(mapname);
889 static_init_precache();
892 GameRules_limit_fallbacks();
895 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
896 if(bot_waypoints_for_items == 1)
897 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
898 bot_waypoints_for_items = 0;
900 WaypointSprite_Init();
903 // changing the logic generating it is okay. But:
904 // it HAS to stay <= 64 chars
905 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
906 // strftime(false, "%s") isn't reliable, see strftime_s description
907 matchid = strzone(sprintf("%d.%s.%06d", autocvar_sv_eventlog_files_counter, strftime_s(), random() * 1000000));
909 if(autocvar_sv_eventlog)
910 GameLogInit(); // requires matchid to be set
912 cvar_set("nextmap", "");
916 if(autocvar_g_campaign)
922 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
924 q3compat = BITSET(q3compat, Q3COMPAT_ARENA, _MapInfo_FindArenaFile(mapname, ".arena") != "");
925 q3compat = BITSET(q3compat, Q3COMPAT_DEFI, _MapInfo_FindArenaFile(mapname, ".defi") != "");
927 // quake 3 music support
928 if(world.music || world.noise)
930 // prefer .music over .noise
933 chosen_music = world.music;
935 chosen_music = world.noise;
937 string newstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
938 strcpy(clientstuff, newstuff);
941 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
943 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
947 while((s = fgets(fd)))
949 int l = tokenize_console(s);
954 string trackname = argv(2);
955 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
956 LOG_INFO(" cdtrack ", trackname);
957 if (cvar_value_issafe(trackname))
959 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
960 strcpy(clientstuff, newstuff);
963 else if(argv(0) == "fog")
965 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
966 LOG_INFO(" \"fog\" \"", s, "\"");
968 else if(argv(0) == "set")
970 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
971 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
973 else if(argv(0) != "//")
975 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
976 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
987 // set up information replies for clients and server to use
988 maplist_reply = strzone(getmaplist());
989 lsmaps_reply = strzone(getlsmaps());
990 monsterlist_reply = strzone(getmonsterlist());
991 bool records_available = false;
992 for(int i = 0; i < 10; ++i)
994 string s = getrecords(i);
997 records_reply[i] = strzone(s);
998 records_available = true;
1001 if (!records_available)
1002 records_reply[0] = "No records available for the current game mode.\n";
1003 ladder_reply = strzone(getladder());
1004 rankings_reply = strzone(getrankings());
1009 PingPLReport_Spawn();
1013 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
1015 // fill sv_curl_serverpackages from .serverpackage files
1016 if (autocvar_sv_curl_serverpackages_auto)
1018 string s = "csprogs-" WATERMARK ".dat";
1019 // remove automatically managed files from the list to prevent duplicates
1020 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
1022 string pkg = argv(i);
1023 if (startsWith(pkg, "csprogs-")) continue;
1024 if (endsWith(pkg, "-serverpackage.txt")) continue;
1025 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
1028 // add automatically managed files to the list
1029 #define X(match) MACRO_BEGIN \
1030 int fd = search_begin(match, true, false); \
1033 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1035 s = cons(s, search_getfilename(fd, i)); \
1040 X("*-serverpackage.txt");
1041 X("*.serverpackage");
1043 cvar_set("sv_curl_serverpackages", s);
1046 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1047 modname = "Xonotic";
1048 // physics/balance/config changes that count as mod
1049 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1050 modname = cvar_string("g_mod_physics");
1051 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1052 modname = cvar_string("g_mod_balance");
1053 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1054 modname = cvar_string("g_mod_config");
1055 // extra mutators that deserve to count as mod
1056 MUTATOR_CALLHOOK(SetModname, modname);
1057 modname = M_ARGV(0, string);
1059 // save it for later
1060 modname = strzone(modname);
1062 WinningConditionHelper(this); // set worldstatus
1064 if (autocvar_sv_autopause && server_is_dedicated && !wantrestart)
1065 // INITPRIO_LAST is too soon: bots either didn't join yet or didn't leave yet, see: bot_fixcount()
1066 defer(this, 5, Pause_TryPause_Dedicated);
1068 world_initialized = 1;
1069 __spawnfunc_spawn_all();
1074 //makestatic (this); // Who the f___ did that?
1078 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance, bool frompos)
1080 float m = e.dphitcontentsmask;
1081 e.dphitcontentsmask = goodcontents | badcontents;
1083 vector org = boundmin;
1084 vector delta = boundmax - boundmin;
1088 int j; // used after the loop
1089 for(j = 0; j < attempts; ++j)
1091 start.x = org.x + random() * delta.x;
1092 start.y = org.y + random() * delta.y;
1093 start.z = org.z + random() * delta.z;
1095 // rule 1: start inside world bounds, and outside
1096 // solid, and don't start from somewhere where you can
1097 // fall down to evil
1098 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1099 if (trace_fraction >= 1)
1101 if (trace_startsolid)
1103 if (trace_dphitcontents & badcontents)
1105 if (trace_dphitq3surfaceflags & badsurfaceflags)
1108 // rule 2: if we are too high, lower the point
1109 if (trace_fraction * delta.z > maxaboveground)
1110 start = trace_endpos + '0 0 1' * maxaboveground;
1111 vector enddown = trace_endpos;
1113 // rule 3: make sure we aren't outside the map. This only works
1114 // for somewhat well formed maps. A good rule of thumb is that
1115 // the map should have a convex outside hull.
1116 // these can be traceLINES as we already verified the starting box
1117 vector mstart = start + 0.5 * (e.mins + e.maxs);
1118 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1119 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1121 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1122 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1124 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1125 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1127 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1128 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1130 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1131 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1134 // rule 4: we must "see" some spawnpoint or item
1138 if((traceline(mstart, e.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1143 IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1145 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1154 int items_checked = 0;
1155 IL_EACH(g_items, checkpvs(mstart, it),
1157 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1164 if(items_checked >= attempts)
1172 // find a random vector to "look at"
1173 end.x = org.x + random() * delta.x;
1174 end.y = org.y + random() * delta.y;
1175 end.z = org.z + random() * delta.z;
1176 end = start + normalize(end - start) * vlen(delta);
1178 // rule 4: start TO end must not be too short
1179 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1180 if(trace_startsolid)
1182 if(trace_fraction < minviewdistance / vlen(delta))
1185 // rule 5: don't want to look at sky
1186 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1189 // rule 6: we must not end up in trigger_hurt
1190 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1196 e.dphitcontentsmask = m;
1200 setorigin(e, start);
1201 e.angles = vectoangles(end - start);
1202 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1208 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1210 return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance, false);
1214 ===============================================================================
1218 ===============================================================================
1221 void DumpStats(float final)
1230 to_console = autocvar_sv_logscores_console;
1231 to_eventlog = autocvar_sv_eventlog;
1232 to_file = autocvar_sv_logscores_file;
1236 to_console = true; // always print printstats replies
1237 to_eventlog = false; // but never print them to the event log
1241 if(autocvar_sv_eventlog_console)
1242 to_console = false; // otherwise we get the output twice
1248 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1258 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1262 fputs(file, strcat(s, "\n"));
1265 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1271 fputs(file, strcat(s, "\n"));
1273 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1274 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1275 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1276 if(IS_PLAYER(it) || INGAME_JOINED(it))
1277 s = strcat(s, ftos(it.team), ":");
1279 s = strcat(s, "spectator:");
1282 LOG_HELP(s, playername(it.netname, it.team, false));
1284 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1286 fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1291 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1297 fputs(file, strcat(s, "\n"));
1299 for(i = 1; i < 16; ++i)
1301 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1302 s = strcat(s, ":", ftos(i));
1308 fputs(file, strcat(s, "\n"));
1315 GameLogEcho(":end");
1318 fputs(file, ":end\n");
1324 go to the next level for deathmatch
1325 only called if a time or frag limit has expired
1329 cvar_set("_endmatch", "0");
1330 game_stopped = true;
1331 intermission_running = true; // game over
1333 // enforce a wait time before allowing changelevel
1334 if(player_count > 0)
1335 intermission_exittime = time + autocvar_sv_mapchange_delay;
1337 intermission_exittime = -1;
1340 WriteByte (MSG_ALL, SVC_CDTRACK);
1341 WriteByte (MSG_ALL, 3);
1342 WriteByte (MSG_ALL, 3);
1343 // done in FixIntermission
1346 //pos = FindIntermission ();
1353 PlayerStats_GameReport(true);
1354 WeaponStats_Shutdown();
1356 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1358 if(autocvar_sv_eventlog)
1359 GameLogEcho(":gameover");
1363 int winner_team = 0;
1364 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1365 FixIntermissionClient(it);
1368 if (teamplay && !winner_team)
1370 winner_team = it.team;
1371 bprint(Team_ColorCode(winner_team), Team_ColorName_Upper(winner_team), "^7 team wins the match\n");
1373 bprint(playername(it.netname, it.team, false), " ^7wins\n");
1377 target_music_kill();
1379 if(autocvar_g_campaign)
1380 CampaignPreIntermission();
1382 MUTATOR_CALLHOOK(MatchEnd);
1384 localcmd("\nsv_hook_gameend\n");
1388 int InitiateSuddenDeath()
1390 // Check first whether normal overtimes could be added before initiating suddendeath mode
1391 // - for this timelimit_overtime needs to be >0 of course
1392 // - also check the winning condition calculated in the previous frame and only add normal overtime
1393 // again, if at the point at which timelimit would be extended again, still no winner was found
1394 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1395 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1396 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1398 return 1; // need to call InitiateOvertime later
1402 if(!checkrules_suddendeathend)
1404 if(autocvar_g_campaign)
1406 checkrules_suddendeathend = time; // no suddendeath in campaign
1410 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1413 if(g_race && !g_race_qualifying)
1414 race_StartCompleting();
1420 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1422 ++checkrules_overtimesadded;
1423 overtimes = checkrules_overtimesadded;
1424 //add one more overtime by simply extending the timelimit
1425 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1426 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1429 float GetWinningCode(float fraglimitreached, float equality)
1431 if(autocvar_g_campaign == 1)
1433 if(fraglimitreached)
1442 if(fraglimitreached)
1443 return WINNING_STARTSUDDENDEATHOVERTIME;
1445 return WINNING_NEVER;
1449 if(fraglimitreached)
1457 // set the .winning flag for exactly those players with a given field value
1458 void SetWinners(.float field, float value)
1460 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = (it.(field) == value); });
1463 // set the .winning flag for those players with a given field value
1464 void AddWinners(.float field, float value)
1466 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1467 if(it.(field) == value)
1472 // clear the .winning flags
1475 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = 0; });
1479 float WinningCondition_Scores(float limit, float leadlimit)
1481 // TODO make everything use THIS winning condition (except LMS)
1482 WinningConditionHelper(NULL);
1486 for (int i = 1; i < 5; ++i)
1488 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1489 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1494 if(WinningConditionHelper_winner)
1495 WinningConditionHelper_winner.winning = 1;
1496 if(WinningConditionHelper_winnerteam >= 0)
1497 SetWinners(team, WinningConditionHelper_winnerteam);
1499 if(WinningConditionHelper_lowerisbetter)
1501 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1502 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1506 if(WinningConditionHelper_zeroisworst)
1507 leadlimit = 0; // not supported in this mode
1509 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1512 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1518 fragsleft = FLOAT_MAX;
1519 float leadingfragsleft = FLOAT_MAX;
1521 fragsleft = limit - WinningConditionHelper_topscore;
1523 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1525 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1526 fragsleft = max(fragsleft, leadingfragsleft);
1528 fragsleft = min(fragsleft, leadingfragsleft);
1531 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1534 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1535 else if (fragsleft == 2)
1536 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1537 else if (fragsleft == 3)
1538 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1540 fragsleft_last = fragsleft;
1544 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1545 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1548 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1549 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1550 limit_reached = (fraglimit_reached && leadlimit_reached);
1552 limit_reached = (fraglimit_reached || leadlimit_reached);
1554 return GetWinningCode(
1555 WinningConditionHelper_topscore && limit_reached,
1556 WinningConditionHelper_equality
1560 float WinningCondition_RanOutOfSpawns()
1562 if(have_team_spawns <= 0)
1565 if(!autocvar_g_spawn_useallspawns)
1568 if(!some_spawn_has_been_used)
1571 for (int i = 1; i < 5; ++i)
1573 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1576 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1578 if (Team_IsValidTeam(it.team))
1580 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1584 IL_EACH(g_spawnpoints, true,
1586 if (Team_IsValidTeam(it.team))
1588 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1593 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1594 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1595 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1596 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1597 if(team1_score + team2_score + team3_score + team4_score == 0)
1599 checkrules_equality = true;
1602 else if(team1_score + team2_score + team3_score + team4_score == 1)
1607 else if(team2_score)
1609 else if(team3_score)
1611 else // if(team4_score)
1613 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1614 for(i = 0; i < MAX_TEAMSCORE; ++i)
1616 for (int j = 1; j <= NUM_TEAMS; ++j)
1622 if (!TeamBalance_IsTeamAllowed(balance, j))
1626 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1630 AddWinners(team, t);
1641 Exit deathmatch games upon conditions
1644 void CheckRules_World()
1651 if (intermission_running) // someone else quit the game already
1653 if(player_count == 0) // Nobody there? Then let's go to the next map
1655 // this will actually check the player count in the next frame
1656 // again, but this shouldn't hurt
1660 float timelimit = autocvar_timelimit * 60;
1661 float fraglimit = autocvar_fraglimit;
1662 float leadlimit = autocvar_leadlimit;
1663 if (leadlimit < 0) leadlimit = 0;
1665 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1668 timelimit = 0; // timelimit is not made for warmup
1670 fraglimit = 0; // no fraglimit for now
1671 leadlimit = 0; // no leadlimit for now
1674 if (autocvar__endmatch || timelimit < 0)
1682 timelimit += game_starttime;
1684 int overtimes_prev = overtimes;
1685 int wantovertime = 0;
1687 if(checkrules_suddendeathend)
1689 if(!checkrules_suddendeathwarning)
1691 checkrules_suddendeathwarning = true;
1692 if(g_race && !g_race_qualifying)
1693 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1695 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1700 if (timelimit && time >= timelimit)
1702 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1705 float playerswithlaps;
1707 totalplayers = playerswithlaps = readyplayers = 0;
1708 FOREACH_CLIENT(IS_PLAYER(it), {
1710 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1716 // at least 2 of the players have completed a lap: start the RACE
1717 // otherwise, the players should end the qualifying on their own
1718 if(readyplayers || playerswithlaps >= 2)
1720 checkrules_suddendeathend = 0;
1721 ReadyRestart(true); // go to race
1725 wantovertime |= InitiateSuddenDeath();
1728 wantovertime |= InitiateSuddenDeath();
1732 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1738 int checkrules_status = WinningCondition_RanOutOfSpawns();
1739 if(checkrules_status == WINNING_YES)
1740 bprint("Hey! Someone ran out of spawns!\n");
1741 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1742 checkrules_status = M_ARGV(0, float);
1744 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1746 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1748 checkrules_status = WINNING_NEVER;
1749 checkrules_overtimesadded = -1;
1750 wantovertime |= InitiateSuddenDeath();
1753 if(checkrules_status == WINNING_NEVER)
1754 // equality cases! Nobody wins if the overtime ends in a draw.
1759 if(checkrules_status == WINNING_NEVER)
1762 checkrules_status = WINNING_YES;
1765 if(checkrules_suddendeathend)
1766 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1767 checkrules_status = WINNING_YES;
1769 if(checkrules_status == WINNING_YES)
1771 if (overtimes == -1 && overtimes != overtimes_prev)
1773 // if suddendeathend overtime has just begun, revert it
1774 checkrules_suddendeathend = 0;
1775 overtimes = overtimes_prev;
1777 //print("WINNING\n");
1782 float want_weapon(entity weaponinfo, float allguns)
1785 bool allow_mutatorblocked = false;
1787 if(!weaponinfo.m_id)
1790 bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1791 d = M_ARGV(1, float);
1792 allguns = M_ARGV(2, bool);
1793 allow_mutatorblocked = M_ARGV(3, bool);
1796 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1797 else if(!mutator_returnvalue)
1798 d = !(!weaponinfo.weaponstart);
1800 if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1803 float t = weaponinfo.weaponstartoverride;
1805 //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1810 // 4: is set by default?
1819 /// Weapons the player normally starts with outside weapon arena.
1820 WepSet weapons_start()
1822 WepSet ret = '0 0 0';
1823 FOREACH(Weapons, it != WEP_Null, {
1824 int w = want_weapon(it, false);
1831 WepSet weapons_all()
1833 WepSet ret = '0 0 0';
1834 FOREACH(Weapons, it != WEP_Null, {
1835 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1841 WepSet weapons_devall()
1843 WepSet ret = '0 0 0';
1844 FOREACH(Weapons, it != WEP_Null,
1851 WepSet weapons_most()
1853 WepSet ret = '0 0 0';
1854 FOREACH(Weapons, it != WEP_Null, {
1855 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
1861 void weaponarena_available_all_update(entity this)
1863 if (weaponsInMapAll)
1865 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
1869 // if no weapons are available on the map, just fall back to all weapons arena
1870 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
1874 void weaponarena_available_devall_update(entity this)
1876 if (weaponsInMapAll)
1878 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
1882 // if no weapons are available on the map, just fall back to devall weapons arena
1883 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
1887 void weaponarena_available_most_update(entity this)
1889 if (weaponsInMapAll)
1891 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
1895 // if no weapons are available on the map, just fall back to most weapons arena
1896 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
1900 void readplayerstartcvars()
1902 // initialize starting values for players
1903 start_weapons = '0 0 0';
1904 start_weapons_default = '0 0 0';
1905 start_weapons_defaultmask = '0 0 0';
1907 start_ammo_shells = 0;
1908 start_ammo_nails = 0;
1909 start_ammo_rockets = 0;
1910 start_ammo_cells = 0;
1911 start_ammo_plasma = 0;
1912 if (random_start_ammo == NULL)
1914 random_start_ammo = new_pure(random_start_ammo);
1916 start_health = cvar("g_balance_health_start");
1917 start_armorvalue = cvar("g_balance_armor_start");
1920 g_weaponarena_weapons = '0 0 0';
1922 string s = cvar_string("g_weaponarena");
1924 MUTATOR_CALLHOOK(SetWeaponArena, s);
1925 s = M_ARGV(0, string);
1927 if (s == "0" || s == "")
1931 else if (s == "off")
1933 // forcibly turn off weaponarena
1935 else if (s == "all" || s == "1")
1938 g_weaponarena_list = "All Weapons Arena";
1939 g_weaponarena_weapons = weapons_all();
1941 else if (s == "devall")
1944 g_weaponarena_list = "Dev All Weapons Arena";
1945 g_weaponarena_weapons = weapons_devall();
1947 else if (s == "most")
1950 g_weaponarena_list = "Most Weapons Arena";
1951 g_weaponarena_weapons = weapons_most();
1953 else if (s == "all_available")
1956 g_weaponarena_list = "All Available Weapons Arena";
1958 // this needs to run after weaponsInMapAll is initialized
1959 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
1961 else if (s == "devall_available")
1964 g_weaponarena_list = "Dev All Available Weapons Arena";
1966 // this needs to run after weaponsInMapAll is initialized
1967 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
1969 else if (s == "most_available")
1972 g_weaponarena_list = "Most Available Weapons Arena";
1974 // this needs to run after weaponsInMapAll is initialized
1975 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
1977 else if (s == "none")
1980 g_weaponarena_list = "No Weapons Arena";
1985 float t = tokenize_console(s);
1986 g_weaponarena_list = "";
1987 for (int j = 0; j < t; ++j)
1990 Weapon wep = Weapon_from_name(s);
1993 g_weaponarena_weapons |= (wep.m_wepset);
1994 g_weaponarena_list = strcat(g_weaponarena_list, wep.netname, " & ");
1997 if (g_weaponarena_list != "") // remove trailing " & "
1998 g_weaponarena_list = substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3);
1999 else // no valid weapon found
2000 g_weaponarena_list = "No Weapons Arena";
2005 g_weapon_stay = 0; // incompatible
2006 start_weapons = g_weaponarena_weapons;
2007 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
2008 g_weaponarena_list = strzone(g_weaponarena_list);
2012 FOREACH(Weapons, it != WEP_Null, {
2013 int w = want_weapon(it, false);
2014 WepSet s = it.m_wepset;
2018 start_weapons_default |= s;
2020 start_weapons_defaultmask |= s;
2024 if(cvar("g_balance_superweapons_time") < 0)
2025 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2027 if(!cvar("g_use_ammunition"))
2028 start_items |= IT_UNLIMITED_AMMO;
2030 if(start_items & IT_UNLIMITED_AMMO)
2032 start_ammo_shells = 999;
2033 start_ammo_nails = 999;
2034 start_ammo_rockets = 999;
2035 start_ammo_cells = 999;
2036 start_ammo_plasma = 999;
2037 start_ammo_fuel = 999;
2041 start_ammo_shells = cvar("g_start_ammo_shells");
2042 start_ammo_nails = cvar("g_start_ammo_nails");
2043 start_ammo_rockets = cvar("g_start_ammo_rockets");
2044 start_ammo_cells = cvar("g_start_ammo_cells");
2045 start_ammo_plasma = cvar("g_start_ammo_plasma");
2046 start_ammo_fuel = cvar("g_start_ammo_fuel");
2047 random_start_weapons_count = cvar("g_random_start_weapons_count");
2048 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2049 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2050 SetResource(random_start_ammo, RES_ROCKETS, cvar("g_random_start_rockets"));
2051 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2052 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2055 warmup_start_ammo_shells = start_ammo_shells;
2056 warmup_start_ammo_nails = start_ammo_nails;
2057 warmup_start_ammo_rockets = start_ammo_rockets;
2058 warmup_start_ammo_cells = start_ammo_cells;
2059 warmup_start_ammo_plasma = start_ammo_plasma;
2060 warmup_start_ammo_fuel = start_ammo_fuel;
2061 warmup_start_health = start_health;
2062 warmup_start_armorvalue = start_armorvalue;
2063 warmup_start_weapons = start_weapons;
2064 warmup_start_weapons_default = start_weapons_default;
2065 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2069 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2070 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2071 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2072 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2073 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2074 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2075 warmup_start_health = cvar("g_warmup_start_health");
2076 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2077 warmup_start_weapons = '0 0 0';
2078 warmup_start_weapons_default = '0 0 0';
2079 warmup_start_weapons_defaultmask = '0 0 0';
2080 FOREACH(Weapons, it != WEP_Null, {
2081 int w = want_weapon(it, autocvar_g_warmup_allguns);
2082 WepSet s = it.m_wepset;
2084 warmup_start_weapons |= s;
2086 warmup_start_weapons_default |= s;
2088 warmup_start_weapons_defaultmask |= s;
2092 if (autocvar_g_jetpack)
2093 start_items |= ITEM_Jetpack.m_itemid;
2095 MUTATOR_CALLHOOK(SetStartItems);
2097 if (start_items & ITEM_Jetpack.m_itemid)
2099 start_items |= ITEM_JetpackRegen.m_itemid;
2100 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2101 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2104 start_ammo_shells = max(0, start_ammo_shells);
2105 start_ammo_nails = max(0, start_ammo_nails);
2106 start_ammo_rockets = max(0, start_ammo_rockets);
2107 start_ammo_cells = max(0, start_ammo_cells);
2108 start_ammo_plasma = max(0, start_ammo_plasma);
2109 start_ammo_fuel = max(0, start_ammo_fuel);
2110 SetResource(random_start_ammo, RES_SHELLS, max(0, GetResource(random_start_ammo, RES_SHELLS)));
2111 SetResource(random_start_ammo, RES_BULLETS, max(0, GetResource(random_start_ammo, RES_BULLETS)));
2112 SetResource(random_start_ammo, RES_ROCKETS, max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2113 SetResource(random_start_ammo, RES_CELLS, max(0, GetResource(random_start_ammo, RES_CELLS)));
2114 SetResource(random_start_ammo, RES_PLASMA, max(0, GetResource(random_start_ammo, RES_PLASMA)));
2116 warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2117 warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2118 warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2119 warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2120 warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2121 warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2124 void readlevelcvars()
2126 serverflags &= ~SERVERFLAG_ALLOW_FULLBRIGHT;
2127 if(cvar("sv_allow_fullbright"))
2128 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2130 serverflags &= ~SERVERFLAG_FORBID_PICKUPTIMER;
2131 if(cvar("sv_forbid_pickuptimer"))
2132 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2134 sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2136 if(cvar("g_campaign"))
2137 warmup_stage = 0; // no warmup during campaign
2140 warmup_stage = autocvar_g_warmup;
2141 if (warmup_stage < 0 || warmup_stage > 1)
2142 warmup_limit = -1; // don't start until there's enough players
2143 else if (warmup_stage == 1)
2145 // this code is duplicated in ReadyCount()
2146 warmup_limit = cvar("g_warmup_limit");
2147 if(warmup_limit == 0)
2148 warmup_limit = autocvar_timelimit * 60;
2152 g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2153 g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2154 g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2155 g_pickup_respawntime_armor_small = cvar("g_pickup_respawntime_armor_small");
2156 g_pickup_respawntime_armor_medium = cvar("g_pickup_respawntime_armor_medium");
2157 g_pickup_respawntime_armor_big = cvar("g_pickup_respawntime_armor_big");
2158 g_pickup_respawntime_armor_mega = cvar("g_pickup_respawntime_armor_mega");
2159 g_pickup_respawntime_health_small = cvar("g_pickup_respawntime_health_small");
2160 g_pickup_respawntime_health_medium = cvar("g_pickup_respawntime_health_medium");
2161 g_pickup_respawntime_health_big = cvar("g_pickup_respawntime_health_big");
2162 g_pickup_respawntime_health_mega = cvar("g_pickup_respawntime_health_mega");
2163 g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2164 g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2165 g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2166 g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2167 g_pickup_respawntimejitter_armor_small = cvar("g_pickup_respawntimejitter_armor_small");
2168 g_pickup_respawntimejitter_armor_medium = cvar("g_pickup_respawntimejitter_armor_medium");
2169 g_pickup_respawntimejitter_armor_big = cvar("g_pickup_respawntimejitter_armor_big");
2170 g_pickup_respawntimejitter_armor_mega = cvar("g_pickup_respawntimejitter_armor_mega");
2171 g_pickup_respawntimejitter_health_small = cvar("g_pickup_respawntimejitter_health_small");
2172 g_pickup_respawntimejitter_health_medium = cvar("g_pickup_respawntimejitter_health_medium");
2173 g_pickup_respawntimejitter_health_big = cvar("g_pickup_respawntimejitter_health_big");
2174 g_pickup_respawntimejitter_health_mega = cvar("g_pickup_respawntimejitter_health_mega");
2175 g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2177 g_pickup_shells = cvar("g_pickup_shells");
2178 g_pickup_shells_max = cvar("g_pickup_shells_max");
2179 g_pickup_nails = cvar("g_pickup_nails");
2180 g_pickup_nails_max = cvar("g_pickup_nails_max");
2181 g_pickup_rockets = cvar("g_pickup_rockets");
2182 g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2183 g_pickup_cells = cvar("g_pickup_cells");
2184 g_pickup_cells_max = cvar("g_pickup_cells_max");
2185 g_pickup_plasma = cvar("g_pickup_plasma");
2186 g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2187 g_pickup_fuel = cvar("g_pickup_fuel");
2188 g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2189 g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2190 g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2191 g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2192 g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2193 g_pickup_armormedium = cvar("g_pickup_armormedium");
2194 g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2195 g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2196 g_pickup_armorbig = cvar("g_pickup_armorbig");
2197 g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2198 g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2199 g_pickup_armormega = cvar("g_pickup_armormega");
2200 g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2201 g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2202 g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2203 g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2204 g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2205 g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2206 g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2207 g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2208 g_pickup_healthbig = cvar("g_pickup_healthbig");
2209 g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2210 g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2211 g_pickup_healthmega = cvar("g_pickup_healthmega");
2212 g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2213 g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2215 g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2216 g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2218 g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2220 g_weapon_stay = cvar("g_weapon_stay");
2222 MUTATOR_CALLHOOK(ReadLevelCvars);
2224 if (!warmup_stage && !autocvar_g_campaign)
2225 game_starttime = time + cvar("g_start_delay");
2227 FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2229 readplayerstartcvars();
2232 void InitializeEntity(entity e, void(entity this) func, int order)
2236 if (!e || e.initialize_entity)
2238 // make a proxy initializer entity
2240 e = new(initialize_entity);
2244 e.initialize_entity = func;
2245 e.initialize_entity_order = order;
2247 cur = initialize_entity_first;
2251 if (!cur || cur.initialize_entity_order > order)
2253 // insert between prev and cur
2255 prev.initialize_entity_next = e;
2257 initialize_entity_first = e;
2258 e.initialize_entity_next = cur;
2262 cur = cur.initialize_entity_next;
2265 void InitializeEntitiesRun()
2267 entity startoflist = initialize_entity_first;
2268 initialize_entity_first = NULL;
2269 delete_fn = remove_except_protected;
2270 for (entity e = startoflist; e; e = e.initialize_entity_next)
2272 e.remove_except_protected_forbidden = 1;
2274 for (entity e = startoflist; e; )
2276 e.remove_except_protected_forbidden = 0;
2277 e.initialize_entity_order = 0;
2278 entity next = e.initialize_entity_next;
2279 e.initialize_entity_next = NULL;
2280 var void(entity this) func = e.initialize_entity;
2281 e.initialize_entity = func_null;
2282 if (e.classname == "initialize_entity")
2284 entity wrappee = e.enemy;
2288 //dprint("Delayed initialization: ", e.classname, "\n");
2296 backtrace(strcat("Null function in: ", e.classname, "\n"));
2300 delete_fn = remove_unsafely;
2303 // deferred dropping
2304 // ported from VM_SV_droptofloor TODO: make a common function for the client-side?
2305 void DropToFloor_Handler(entity this)
2307 if(!this || wasfreed(this))
2309 // no modifying free entities
2313 vector end = this.origin;
2314 if (autocvar_sv_mapformat_is_quake3)
2316 else if (autocvar_sv_mapformat_is_quake2)
2319 end.z -= 256; // Quake, QuakeWorld
2321 // NOTE: SV_NudgeOutOfSolid is used in the engine here
2322 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2324 _Movetype_UnstickEntity(this);
2325 move_out_of_solid(this);
2328 tracebox(this.origin, this.mins, this.maxs, end, MOVE_NORMAL, this);
2330 if(trace_startsolid && autocvar_sv_gameplayfix_droptofloorstartsolid)
2333 offset = 0.5 * (this.mins + this.maxs);
2334 offset.z = this.mins.z;
2335 org = this.origin + offset;
2336 traceline(org, end, MOVE_NORMAL, this);
2337 trace_endpos = trace_endpos - offset;
2338 if(trace_startsolid)
2340 LOG_DEBUGF("DropToFloor_Handler: %v could not fix badly placed entity", this.origin);
2341 _Movetype_LinkEdict(this, false);
2343 this.groundentity = NULL;
2345 else if(trace_fraction < 1)
2347 LOG_DEBUGF("DropToFloor_Handler: %v fixed badly placed entity", this.origin);
2348 setorigin(this, trace_endpos);
2349 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2351 _Movetype_UnstickEntity(this);
2352 move_out_of_solid(this);
2355 this.groundentity = trace_ent;
2356 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2357 this.move_suspendedinair = true;
2362 if(!trace_allsolid && trace_fraction < 1)
2364 setorigin(this, trace_endpos);
2366 this.groundentity = trace_ent;
2367 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2368 this.move_suspendedinair = true;
2372 // if we can't get the entity out of solid, mark it as on ground so physics doesn't attempt to drop it
2373 // hacky workaround for #2774
2377 this.dropped_origin = this.origin;
2380 void droptofloor(entity this)
2382 InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2385 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2386 void RunThink(entity this, float dt)
2388 // don't let things stay in the past.
2389 // it is possible to start that way by a trigger with a local time.
2390 if(this.nextthink <= 0 || this.nextthink > time + dt)
2393 float oldtime = time; // do we need to save this?
2395 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2397 time = max(oldtime, this.nextthink);
2401 getthink(this)(this);
2402 // mods often set nextthink to time to cause a think every frame,
2403 // we don't want to loop in that case, so exit if the new nextthink is
2404 // <= the time the qc was told, also exit if it is past the end of the
2406 if(this.nextthink <= time || this.nextthink > oldtime + dt || !autocvar_sv_gameplayfix_multiplethinksperframe)
2413 bool autocvar_sv_freezenonclients;
2414 void Physics_Frame()
2416 if(autocvar_sv_freezenonclients)
2419 IL_EACH(g_moveables, true,
2421 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2424 //set_movetype(it, it.move_movetype);
2425 // inline the set_movetype function, since this is called a lot
2426 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2428 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2429 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2431 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2433 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2434 continue; // these movetypes have no regular think function
2435 // handle thinking here
2436 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + PHYS_INPUT_TIMELENGTH)
2437 RunThink(it, PHYS_INPUT_TIMELENGTH);
2441 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2444 // make a second pass to see if any ents spawned this frame and make
2445 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2446 // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2447 IL_EACH(g_moveables, it.move_qcphysics,
2449 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2451 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2455 void systems_update();
2458 anticheat_endframe();
2462 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2463 entity e = IS_SPEC(it) ? it.enemy : it;
2464 if (e.typehitsound) {
2465 STAT(TYPEHIT_TIME, it) = time;
2466 } else if (e.killsound) {
2467 STAT(KILL_TIME, it) = time;
2468 } else if (e.hitsound_damage_dealt) {
2469 STAT(HIT_TIME, it) = time;
2470 // NOTE: this is not accurate as client code doesn't need so much accuracy for its purposes
2471 STAT(HITSOUND_DAMAGE_DEALT_TOTAL, it) += ceil(e.hitsound_damage_dealt);
2474 // add 1 frametime because after this, engine SV_Physics
2475 // increases time by a frametime and then networks the frame
2476 // add another frametime because client shows everything with
2477 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2479 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2480 FOREACH_CLIENT(true, {
2481 it.typehitsound = false;
2482 it.hitsound_damage_dealt = 0;
2483 it.killsound = false;
2484 antilag_record(it, CS(it), altime);
2486 IL_EACH(g_monsters, true,
2488 antilag_record(it, it, altime);
2490 IL_EACH(g_projectiles, it.classname == "nade",
2492 antilag_record(it, it, altime);
2501 * returns true if redirecting
2503 float redirection_timeout;
2504 float redirection_nextthink;
2505 float RedirectionThink()
2507 float clients_found;
2509 if(redirection_target == "")
2512 if(!redirection_timeout)
2514 cvar_set("sv_public", "-2");
2515 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2516 if(redirection_target == "self")
2517 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2519 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2522 if(time < redirection_nextthink)
2525 redirection_nextthink = time + 1;
2528 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2530 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2531 if(redirection_target == "self")
2532 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2534 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2538 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2540 if(time > redirection_timeout || clients_found == 0)
2541 localcmd("\nwait; wait; wait; quit\n");
2548 // Loaded from a save game
2549 // some things then break, so let's work around them...
2551 // Progs DB (capture records)
2552 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2556 MapInfo_Enumerate();
2557 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2560 TargetMusic_RestoreGame();
2567 if(world_initialized > 0)
2569 world_initialized = 0;
2571 // if a timeout is active, reset the slowmo value to normal
2572 if(timeout_status == TIMEOUT_ACTIVE)
2573 cvar_set("slowmo", ftos(orig_slowmo));
2575 LOG_TRACE("Saving persistent data...");
2578 // playerstats with unfinished match
2579 PlayerStats_GameReport(false);
2581 if(!cheatcount_total)
2583 if(autocvar_sv_db_saveasdump)
2584 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2586 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2588 if(autocvar_developer > 0)
2590 if(autocvar_sv_db_saveasdump)
2591 db_dump(TemporaryDB, "server-temp.db");
2593 db_save(TemporaryDB, "server-temp.db");
2595 CheatShutdown(); // must be after cheatcount check
2596 db_close(ServerProgsDB);
2597 db_close(TemporaryDB);
2598 LOG_TRACE("Saving persistent data... done!");
2599 // tell the bot system the game is ending now
2602 WeaponStats_Shutdown();
2605 strfree(sv_termsofservice_url_escaped);
2607 else if(world_initialized == 0)
2609 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2613 __init_dedicated_server_shutdown();