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
123 if(autocvar_g_maplist_shuffle)
125 n = tokenizebyseparator(autocvar_g_maplist, " ");
126 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
129 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
131 if(!DoNextMapOverride(1))
139 this.nextthink = time;
143 this.nextthink = time + 1;
144 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
148 void cvar_changes_init()
152 float n, i, adding, pureadding;
154 strfree(cvar_changes);
155 strfree(cvar_purechanges);
156 cvar_purechanges_count = 0;
159 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
165 for(i = 0; i < n; ++i)
167 k = bufstr_get(h, i);
169 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
170 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
171 #define BADCVAR(p) if(k == p) continue
172 #define BADVALUE(p, val) if (k == p && v == val) continue
174 // general excludes and namespaces for server admin used cvars
175 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
179 BADPREFIX("cvar_check_");
181 BADCVAR("g_configversion");
182 BADCVAR("halflifebsp");
183 BADCVAR("sv_mapformat_is_quake2");
184 BADCVAR("sv_mapformat_is_quake3");
185 BADPREFIX("sv_world");
191 BADPREFIX("scoreboard_");
192 BADPREFIX("g_campaign");
193 BADPREFIX("g_waypointsprite_");
199 BADPREFIX("net_slist_");
205 BADPREFIX("sensitivity");
206 BADPREFIX("userbind");
209 BADPREFIX("crosshair");
210 BADCVAR("mod_q3bsp_lightmapmergepower");
211 BADCVAR("mod_q3bsp_nolightmaps");
213 BADCVAR("mastervolume");
215 BADCVAR("bgmvolume");
216 BADCVAR("in_pitch_min");
217 BADCVAR("in_pitch_max");
220 BADCVAR("developer");
221 BADCVAR("log_dest_udp");
222 BADCVAR("net_address");
223 BADCVAR("net_address_ipv6");
225 BADCVAR("savedgamecfg");
226 BADCVAR("serverconfig");
227 BADCVAR("sv_autoscreenshot");
228 BADCVAR("sv_heartbeatperiod");
229 BADCVAR("sv_vote_master_password");
230 BADCVAR("sys_colortranslation");
231 BADCVAR("sys_specialcharactertranslation");
232 BADCVAR("timeformat");
233 BADCVAR("timestamps");
234 BADCVAR("g_require_stats");
235 BADPREFIX("developer_");
237 BADPREFIX("g_banned_list");
238 BADPREFIX("g_require_stats_");
239 BADPREFIX("g_chat_flood_");
240 BADPREFIX("g_ghost_items");
241 BADPREFIX("g_playerstats_");
242 BADPREFIX("g_voice_flood_");
243 BADPREFIX("log_file");
246 BADPREFIX("sv_allowdownloads");
247 BADPREFIX("sv_autodemo");
248 BADPREFIX("sv_curl_");
249 BADPREFIX("sv_eventlog");
250 BADPREFIX("sv_logscores_");
251 BADPREFIX("sv_master");
252 BADPREFIX("sv_weaponstats_");
253 BADPREFIX("sv_waypointsprite_");
254 BADCVAR("rescan_pending");
256 // these can contain player IDs, so better hide
257 BADPREFIX("g_forced_team_");
258 BADCVAR("sv_muteban_list");
259 BADCVAR("sv_voteban_list");
260 BADCVAR("sv_allow_customplayermodels_idlist");
261 BADCVAR("sv_allow_customplayermodels_speciallist");
264 BADCVAR("fraglimit");
266 BADCVAR("g_assault");
268 BADCVAR("g_ca_teams");
269 BADCVAR("g_conquest");
270 BADCVAR("g_conquest_teams");
275 BADCVAR("g_domination");
276 BADCVAR("g_domination_default_teams");
278 BADCVAR("g_duel_not_dm_maps");
279 BADCVAR("g_freezetag");
280 BADCVAR("g_freezetag_teams");
281 BADCVAR("g_invasion_type");
282 BADCVAR("g_jailbreak");
283 BADCVAR("g_jailbreak_teams");
284 BADCVAR("g_keepaway");
285 BADCVAR("g_keyhunt");
286 BADCVAR("g_keyhunt_teams");
289 BADCVAR("g_nexball");
290 BADCVAR("g_onslaught");
292 BADCVAR("g_race_laps_limit");
293 BADCVAR("g_race_qualifying_timelimit");
294 BADCVAR("g_race_qualifying_timelimit_override");
295 BADCVAR("g_runematch");
296 BADCVAR("g_shootfromeye");
298 BADCVAR("g_survival");
299 BADCVAR("g_survival_not_dm_maps");
301 BADCVAR("g_tdm_on_dm_maps");
302 BADCVAR("g_tdm_teams");
303 BADCVAR("g_tmayhem");
304 BADCVAR("g_tmayhem_teams");
306 BADCVAR("leadlimit");
309 BADCVAR("timelimit");
310 BADCVAR("g_mapinfo_q3compat");
311 BADCVAR("g_mapinfo_settemp_acl");
312 BADCVAR("g_mapinfo_ignore_warnings");
313 BADCVAR("g_maplist_ignore_sizes");
314 BADCVAR("g_maplist_sizes_count_bots");
318 BADCVAR("g_maplist");
319 BADCVAR("g_maplist_mostrecent");
321 BADCVAR("sv_termsofservice_url");
324 d = cvar_defstring(k);
330 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
331 if(strlen(cvar_changes) > 16384)
333 cvar_changes = "// too many settings have been changed to show them here\n";
338 // now check if the changes are actually gameplay relevant
340 // does nothing gameplay relevant
341 BADCVAR("captureleadlimit_override");
342 BADCVAR("condump_stripcolors");
343 BADCVAR("fs_gamedir");
344 BADCVAR("g_allow_oldvortexbeam");
345 BADCVAR("g_balance_kill_delay");
346 BADCVAR("g_buffs_pickup_anyway");
347 BADCVAR("g_buffs_randomize");
348 BADCVAR("g_buffs_randomize_teamplay");
349 BADCVAR("g_campcheck_distance");
350 BADCVAR("g_chatsounds");
351 BADCVAR("g_ca_point_leadlimit");
352 BADCVAR("g_ca_point_limit");
353 BADCVAR("g_ca_spectate_enemies");
354 BADCVAR("g_ctf_captimerecord_always");
355 BADCVAR("g_ctf_flag_glowtrails");
356 BADCVAR("g_ctf_dynamiclights");
357 BADCVAR("g_ctf_flag_pickup_verbosename");
358 BADCVAR("g_ctf_flagcarrier_auto_helpme_damage");
359 BADPRESUFFIX("g_ctf_flag_", "_model");
360 BADPRESUFFIX("g_ctf_flag_", "_skin");
361 BADCVAR("g_domination_point_leadlimit");
362 BADCVAR("g_forced_respawn");
363 BADCVAR("g_freezetag_point_leadlimit");
364 BADCVAR("g_freezetag_point_limit");
365 BADCVAR("g_glowtrails");
367 BADCVAR("g_casings");
368 BADCVAR("g_invasion_point_limit");
369 BADCVAR("g_jump_grunt");
370 BADCVAR("g_keepaway_ballcarrier_effects");
371 BADCVAR("g_keepawayball_effects");
372 BADCVAR("g_keyhunt_point_leadlimit");
373 BADCVAR("g_nexball_goalleadlimit");
374 BADCVAR("g_new_toys_autoreplace");
375 BADCVAR("g_new_toys_use_pickupsound");
376 BADCVAR("g_physics_predictall");
377 BADCVAR("g_piggyback");
378 BADCVAR("g_playerclip_collisions");
379 BADCVAR("g_spawn_alloweffects");
380 BADCVAR("g_tdm_point_leadlimit");
381 BADCVAR("g_tdm_point_limit");
382 BADCVAR("g_mayhem_point_limit");
383 BADCVAR("g_mayhem_point_leadlimit");
384 BADCVAR("g_tmayhem_point_limit");
385 BADCVAR("g_tmayhem_point_leadlimit");
386 BADCVAR("leadlimit_and_fraglimit");
387 BADCVAR("leadlimit_override");
389 BADCVAR("sv_announcer");
390 BADCVAR("sv_checkforpacketsduringsleep");
391 BADCVAR("sv_damagetext");
392 BADCVAR("sv_db_saveasdump");
393 BADCVAR("sv_intermission_cdtrack");
394 BADCVAR("sv_mapchange_delay");
395 BADCVAR("sv_minigames");
396 BADCVAR("sv_namechangetimer");
397 BADCVAR("sv_precacheplayermodels");
398 BADCVAR("sv_qcphysics");
400 BADCVAR("sv_stepheight");
401 BADCVAR("sv_timeout");
402 BADCVAR("sv_weapons_modeloverride");
403 BADCVAR("w_prop_interval");
405 BADPREFIX("crypto_");
406 BADPREFIX("gameversion");
407 BADPREFIX("g_chat_");
408 BADPREFIX("g_ctf_captimerecord_");
409 BADPREFIX("g_hats_");
410 BADPREFIX("g_maplist_");
412 BADPREFIX("g_respawn_");
414 BADPREFIX("notification_");
417 BADPREFIX("sv_allow_");
418 BADPREFIX("sv_cullentities_");
419 BADPREFIX("sv_maxidle");
420 BADPREFIX("sv_minigames_");
421 BADPREFIX("sv_radio_");
422 BADPREFIX("sv_timeout_");
423 BADPREFIX("sv_vote_");
424 BADPREFIX("timelimit_");
425 BADPRESUFFIX("g_", "_round_timelimit");
427 // allowed changes to server admins (please sync this to server.cfg)
431 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
433 // yes, this does contain some redundant stuff, don't really care
434 BADPREFIX("bot_ai_");
435 BADCVAR("bot_config_file");
436 BADCVAR("bot_number");
437 BADCVAR("bot_prefix");
438 BADCVAR("bot_suffix");
439 BADCVAR("capturelimit_override");
440 BADCVAR("fraglimit_override");
442 BADCVAR("g_antilag");
443 BADCVAR("g_balance_teams");
444 BADCVAR("g_balance_teams_prevent_imbalance");
445 BADCVAR("g_balance_teams_scorefactor");
446 BADCVAR("g_ban_sync_trusted_servers");
447 BADCVAR("g_ban_sync_uri");
449 BADCVAR("g_ca_teams_override");
450 BADCVAR("g_ctf_fullbrightflags");
451 BADCVAR("g_ctf_ignore_frags");
452 BADCVAR("g_ctf_leaderboard");
453 BADCVAR("g_domination_point_limit");
454 BADCVAR("g_domination_teams_override");
455 BADCVAR("g_freezetag_revive_spawnshield");
456 BADCVAR("g_freezetag_teams_override");
457 BADCVAR("g_friendlyfire");
458 BADCVAR("g_fullbrightitems");
459 BADCVAR("g_fullbrightplayers");
460 BADCVAR("g_keyhunt_point_limit");
461 BADCVAR("g_keyhunt_teams_override");
462 BADCVAR("g_lms_lives_override");
463 BADCVAR("g_mayhem_powerups");
464 BADCVAR("g_maplist");
465 BADCVAR("g_maxplayers");
466 BADCVAR("g_mirrordamage");
467 BADCVAR("g_nexball_goallimit");
468 BADCVAR("g_norecoil");
469 BADCVAR("g_physics_clientselect");
471 BADCVAR("g_powerups");
472 BADCVAR("g_powerups_drop_ondeath");
473 BADCVAR("g_player_brightness");
474 BADCVAR("g_rocket_flying");
475 BADCVAR("g_rocket_flying_disabledelays");
476 BADPREFIX("g_spawnshield");
477 BADCVAR("g_start_delay");
478 BADCVAR("g_superspectate");
479 BADCVAR("g_tdm_teams_override");
480 BADCVAR("g_tmayhem_teams_override");
481 BADCVAR("g_tmayhem_powerups");
482 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
485 BADCVAR("maxplayers");
486 BADCVAR("minplayers");
487 BADCVAR("minplayers_per_team");
488 BADCVAR("net_address");
490 BADCVAR("rcon_password");
491 BADCVAR("rcon_restricted_commands");
492 BADCVAR("rcon_restricted_password");
494 BADCVAR("sv_adminnick");
495 BADCVAR("sv_autoscreenshot");
496 BADCVAR("sv_autotaunt");
497 BADCVAR("sv_curl_defaulturl");
498 BADCVAR("sv_defaultcharacter");
499 BADCVAR("sv_defaultcharacterskin");
500 BADCVAR("sv_defaultplayercolors");
501 BADCVAR("sv_defaultplayermodel");
502 BADCVAR("sv_defaultplayerskin");
503 BADCVAR("sv_maxrate");
505 BADCVAR("sv_public");
506 BADCVAR("sv_showfps");
507 BADCVAR("sv_showspectators");
508 BADCVAR("sv_status_privacy");
510 BADCVAR("sv_vote_call");
511 BADCVAR("sv_vote_commands");
512 BADCVAR("sv_vote_majority_factor");
513 BADCVAR("sv_vote_master");
514 BADCVAR("sv_vote_master_commands");
515 BADCVAR("sv_vote_master_password");
516 BADCVAR("sv_vote_simple_majority_factor");
517 BADVALUE("sys_ticrate", "0.0166667");
518 BADVALUE("sys_ticrate", "0.0333333");
519 BADCVAR("teamplay_mode");
520 BADCVAR("timelimit_override");
521 BADPREFIX("g_warmup");
522 BADPREFIX("sv_info_");
523 BADPREFIX("sv_ready_restart_");
525 // mutators that announce themselves properly to the server browser
526 BADCVAR("g_instagib");
527 BADCVAR("g_new_toys");
529 BADCVAR("g_grappling_hook");
530 BADCVAR("g_jetpack");
539 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
540 if(strlen(cvar_purechanges) > 16384)
542 cvar_purechanges = "// too many settings have been changed to show them here\n";
546 ++cvar_purechanges_count;
547 // WARNING: this variable is used for the server list
548 // NEVER dare to skip this code!
549 // Hacks to intentionally appearing as "pure server" even though you DO have
550 // modified settings may be punished by removal from the server list.
551 // You can do to the variables cvar_changes and cvar_purechanges all you want,
555 if(cvar_changes == "")
556 cvar_changes = "// this server runs at default server settings\n";
558 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
559 cvar_changes = strzone(cvar_changes);
560 if(cvar_purechanges == "")
561 cvar_purechanges = "// this server runs at default gameplay settings\n";
563 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
564 cvar_purechanges = strzone(cvar_purechanges);
568 bool RandomSeed_Send(entity this, entity to, int sf)
570 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
571 WriteShort(MSG_ENTITY, this.cnt);
574 void RandomSeed_Think(entity this)
576 this.cnt = bound(0, floor(random() * 65536), 65535);
577 this.nextthink = time + 5;
581 void RandomSeed_Spawn()
583 randomseed = new_pure(randomseed);
584 setthink(randomseed, RandomSeed_Think);
585 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
587 getthink(randomseed)(randomseed); // sets random seed and nextthink
590 spawnfunc(__init_dedicated_server)
592 // handler for _init/_init map (only for dedicated server initialization)
594 world_initialized = -1; // don't complain
596 delete_fn = remove_unsafely;
598 entity e = new(GotoFirstMap);
599 setthink(e, GotoFirstMap);
600 e.nextthink = time; // this is usually 1 at this point
602 e = new(info_player_deathmatch); // safeguard against player joining
604 // assign reflectively to avoid "assignment to world" warning
605 for (int i = 0, n = numentityfields(); i < n; ++i)
607 string k = entityfieldname(i);
608 if (k == "classname")
610 // safeguard against various stuff ;)
611 putentityfieldstring(i, this, "worldspawn");
616 // needs to be done so early because of the constants they create
619 static_init_precache();
621 IL_PUSH(g_spawnpoints, e); // just incase
624 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
627 void __init_dedicated_server_shutdown() {
631 STATIC_INIT_EARLY(maxclients)
634 for (entity head = nextent(NULL); head; head = nextent(head)) {
639 void GameplayMode_DelayedInit(entity this)
641 // at this stage team entities are spawned, teamplay contains the number of them
643 if(!scores_initialized)
644 ScoreRules_generic();
646 if (warmup_stage >= 0 && autocvar_g_maxplayers >= 0)
649 MapReadSizes(mapname);
651 if (autocvar_g_maxplayers < 0 && teamplay)
653 // automatic maxplayers should be a multiple of team count
654 if (map_maxplayers == 0 || map_maxplayers > maxclients)
655 map_maxplayers = maxclients; // unlimited, but may need rounding
656 int d = map_maxplayers % AVAILABLE_TEAMS;
657 int u = AVAILABLE_TEAMS - d;
658 map_maxplayers += (u <= d && u + map_maxplayers <= maxclients) ? u : -d;
661 if (warmup_stage < 0)
663 int m = GetPlayerLimit();
664 if (m <= 0) m = maxclients;
665 map_minplayers = bound(max(2, AVAILABLE_TEAMS * 2), map_minplayers, m);
668 // automatic minplayers should be a multiple of team count
669 int d = map_minplayers % AVAILABLE_TEAMS;
670 int u = AVAILABLE_TEAMS - d;
671 map_minplayers += (u < d && u + map_minplayers <= m) ? u : -d;
675 map_minplayers = 0; // don't display a minimum if it's not used (g_maxplayers < 0 && g_warmup >= 0)
678 void InitGameplayMode()
682 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
684 // assign reflectively to avoid "assignment to world" warning
685 for (int i = 0, done = 0, n = numentityfields(); i < n; ++i)
687 string k = entityfieldname(i);
688 vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
691 putentityfieldstring(i, world, sprintf("%v", v));
692 if (++done == 2) break;
695 // currently, NetRadiant's limit is 131072 qu for each side
696 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
697 // set the distance according to map size but don't go over the limit to avoid issues with float precision
698 // in case somebody makes extremely large maps
699 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
701 MapInfo_LoadMapSettings(mapname);
702 GameRules_teams(false);
704 if (!cvar_value_issafe(world.fog))
706 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
707 world.fog = string_null;
709 if(MapInfo_Map_fog != "")
711 if(MapInfo_Map_fog == "none")
712 world.fog = string_null;
714 world.fog = strzone(MapInfo_Map_fog);
716 clientstuff = strzone(MapInfo_Map_clientstuff);
718 MapInfo_ClearTemps();
720 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
722 cache_mutatormsg = strzone("");
723 cache_lastmutatormsg = strzone("");
725 InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
728 bool world_already_spawned;
729 spawnfunc(worldspawn)
731 cvar_set("_endmatch", "0");
732 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
734 if (autocvar_sv_termsofservice_url && autocvar_sv_termsofservice_url != "")
736 strcpy(sv_termsofservice_url_escaped, strreplace(":", "|", autocvar_sv_termsofservice_url));
740 strcpy(sv_termsofservice_url_escaped, "INVALID");
743 bool wantrestart = false;
745 if (!server_is_dedicated)
747 // DP unloads dlcache pk3s before starting a listen server since https://gitlab.com/xonotic/darkplaces/-/merge_requests/134
748 // restore csqc_progname too
749 string expect = "csprogs.dat";
750 wantrestart = cvar_string("csqc_progname") != expect;
751 cvar_set("csqc_progname", expect);
755 // Try to use versioned csprogs from pk3
756 // Only ever use versioned csprogs.dat files on dedicated servers;
757 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
758 string pk3csprogs = "csprogs-" WATERMARK ".dat";
759 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
760 string select = "csprogs.dat";
761 if (fexists(pk3csprogs)) select = pk3csprogs;
762 if (cvar_string("csqc_progname") != select)
764 cvar_set("csqc_progname", select);
767 // Check for updates on startup
768 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
769 int sentinel = fopen("progs.txt", FILE_READ);
772 string switchversion = fgets(sentinel);
774 if (switchversion != "" && switchversion != WATERMARK)
776 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
777 // if it doesn't exist, assume either:
778 // a) the current program was overwritten
779 // b) this is a client only update
780 string newprogs = sprintf("progs-%s.dat", switchversion);
781 if (fexists(newprogs))
783 cvar_set("sv_progs", newprogs);
786 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
787 if (fexists(newcsprogs))
789 cvar_set("csqc_progname", newcsprogs);
797 LOG_INFO("Restart requested");
798 changelevel(mapname);
799 // let initialization continue, shutdown depends on it
803 if(world_already_spawned)
804 error("world already spawned - you may have EXACTLY ONE worldspawn!");
805 world_already_spawned = true;
807 delete_fn = remove_safely; // during spawning, watch what you remove!
809 cvar_changes_init(); // do this very early now so it REALLY matches the server config
811 // default to RACE_RECORD, can be overwritten by gamemodes
812 record_type = RACE_RECORD;
814 // needs to be done so early because of the constants they create
817 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
819 TemporaryDB = db_create();
824 // 1 FLICKER (first variety)
825 lightstyle(1, "mmnmmommommnonmmonqnmmo");
827 // 2 SLOW STRONG PULSE
828 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
830 // 3 CANDLE (first variety)
831 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
834 lightstyle(4, "mamamamamama");
837 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
839 // 6 FLICKER (second variety)
840 lightstyle(6, "nmonqnmomnmomomno");
842 // 7 CANDLE (second variety)
843 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
845 // 8 CANDLE (third variety)
846 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
848 // 9 SLOW STROBE (fourth variety)
849 lightstyle(9, "aaaaaaaazzzzzzzz");
851 // 10 FLUORESCENT FLICKER
852 lightstyle(10, "mmamammmmammamamaaamammma");
854 // 11 SLOW PULSE NOT FADE TO BLACK
855 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
857 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
862 if(autocvar_g_campaign)
865 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
867 Map_MarkAsRecent(mapname);
871 static_init_precache();
874 GameRules_limit_fallbacks();
877 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
878 if(bot_waypoints_for_items == 1)
879 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
880 bot_waypoints_for_items = 0;
882 WaypointSprite_Init();
885 // changing the logic generating it is okay. But:
886 // it HAS to stay <= 64 chars
887 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
888 // strftime(false, "%s") isn't reliable, see strftime_s description
889 matchid = strzone(sprintf("%d.%s.%06d", autocvar_sv_eventlog_files_counter, strftime_s(), random() * 1000000));
891 if(autocvar_sv_eventlog)
892 GameLogInit(); // requires matchid to be set
894 cvar_set("nextmap", "");
898 if(autocvar_g_campaign)
904 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
906 q3compat = BITSET(q3compat, Q3COMPAT_ARENA, _MapInfo_FindArenaFile(mapname, ".arena") != "");
907 q3compat = BITSET(q3compat, Q3COMPAT_DEFI, _MapInfo_FindArenaFile(mapname, ".defi") != "");
909 // quake 3 music support
910 if(world.music || world.noise)
912 // prefer .music over .noise
915 chosen_music = world.music;
917 chosen_music = world.noise;
919 string newstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
920 strcpy(clientstuff, newstuff);
923 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
925 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
929 while((s = fgets(fd)))
931 int l = tokenize_console(s);
936 string trackname = argv(2);
937 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
938 LOG_INFO(" cdtrack ", trackname);
939 if (cvar_value_issafe(trackname))
941 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
942 strcpy(clientstuff, newstuff);
945 else if(argv(0) == "fog")
947 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
948 LOG_INFO(" \"fog\" \"", s, "\"");
950 else if(argv(0) == "set")
952 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
953 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
955 else if(argv(0) != "//")
957 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
958 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
969 // set up information replies for clients and server to use
970 maplist_reply = strzone(getmaplist());
971 lsmaps_reply = strzone(getlsmaps());
972 monsterlist_reply = strzone(getmonsterlist());
973 bool records_available = false;
974 for(int i = 0; i < 10; ++i)
976 string s = getrecords(i);
979 records_reply[i] = strzone(s);
980 records_available = true;
983 if (!records_available)
984 records_reply[0] = "No records available for the current game mode.\n";
985 ladder_reply = strzone(getladder());
986 rankings_reply = strzone(getrankings());
991 PingPLReport_Spawn();
995 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
997 // fill sv_curl_serverpackages from .serverpackage files
998 if (autocvar_sv_curl_serverpackages_auto)
1000 string s = "csprogs-" WATERMARK ".dat";
1001 // remove automatically managed files from the list to prevent duplicates
1002 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
1004 string pkg = argv(i);
1005 if (startsWith(pkg, "csprogs-")) continue;
1006 if (endsWith(pkg, "-serverpackage.txt")) continue;
1007 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
1010 // add automatically managed files to the list
1011 #define X(match) MACRO_BEGIN \
1012 int fd = search_begin(match, true, false); \
1015 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1017 s = cons(s, search_getfilename(fd, i)); \
1022 X("*-serverpackage.txt");
1023 X("*.serverpackage");
1025 cvar_set("sv_curl_serverpackages", s);
1028 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1029 modname = "Xonotic";
1030 // physics/balance/config changes that count as mod
1031 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1032 modname = cvar_string("g_mod_physics");
1033 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1034 modname = cvar_string("g_mod_balance");
1035 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1036 modname = cvar_string("g_mod_config");
1037 // extra mutators that deserve to count as mod
1038 MUTATOR_CALLHOOK(SetModname, modname);
1039 modname = M_ARGV(0, string);
1041 // save it for later
1042 modname = strzone(modname);
1044 WinningConditionHelper(this); // set worldstatus
1046 world_initialized = 1;
1047 __spawnfunc_spawn_all();
1052 //makestatic (this); // Who the f___ did that?
1056 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance, bool frompos)
1058 float m = e.dphitcontentsmask;
1059 e.dphitcontentsmask = goodcontents | badcontents;
1061 vector org = boundmin;
1062 vector delta = boundmax - boundmin;
1066 int j; // used after the loop
1067 for(j = 0; j < attempts; ++j)
1069 start.x = org.x + random() * delta.x;
1070 start.y = org.y + random() * delta.y;
1071 start.z = org.z + random() * delta.z;
1073 // rule 1: start inside world bounds, and outside
1074 // solid, and don't start from somewhere where you can
1075 // fall down to evil
1076 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1077 if (trace_fraction >= 1)
1079 if (trace_startsolid)
1081 if (trace_dphitcontents & badcontents)
1083 if (trace_dphitq3surfaceflags & badsurfaceflags)
1086 // rule 2: if we are too high, lower the point
1087 if (trace_fraction * delta.z > maxaboveground)
1088 start = trace_endpos + '0 0 1' * maxaboveground;
1089 vector enddown = trace_endpos;
1091 // rule 3: make sure we aren't outside the map. This only works
1092 // for somewhat well formed maps. A good rule of thumb is that
1093 // the map should have a convex outside hull.
1094 // these can be traceLINES as we already verified the starting box
1095 vector mstart = start + 0.5 * (e.mins + e.maxs);
1096 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1097 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1099 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1100 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1102 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1103 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1105 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1106 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1108 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1109 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1112 // rule 4: we must "see" some spawnpoint or item
1116 if((traceline(mstart, e.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1121 IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1123 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1132 int items_checked = 0;
1133 IL_EACH(g_items, checkpvs(mstart, it),
1135 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1142 if(items_checked >= attempts)
1150 // find a random vector to "look at"
1151 end.x = org.x + random() * delta.x;
1152 end.y = org.y + random() * delta.y;
1153 end.z = org.z + random() * delta.z;
1154 end = start + normalize(end - start) * vlen(delta);
1156 // rule 4: start TO end must not be too short
1157 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1158 if(trace_startsolid)
1160 if(trace_fraction < minviewdistance / vlen(delta))
1163 // rule 5: don't want to look at sky
1164 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1167 // rule 6: we must not end up in trigger_hurt
1168 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1174 e.dphitcontentsmask = m;
1178 setorigin(e, start);
1179 e.angles = vectoangles(end - start);
1180 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1186 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1188 return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance, false);
1192 ===============================================================================
1196 ===============================================================================
1199 void DumpStats(float final)
1208 to_console = autocvar_sv_logscores_console;
1209 to_eventlog = autocvar_sv_eventlog;
1210 to_file = autocvar_sv_logscores_file;
1214 to_console = true; // always print printstats replies
1215 to_eventlog = false; // but never print them to the event log
1219 if(autocvar_sv_eventlog_console)
1220 to_console = false; // otherwise we get the output twice
1226 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1236 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1240 fputs(file, strcat(s, "\n"));
1243 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1249 fputs(file, strcat(s, "\n"));
1251 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1252 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1253 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1254 if(IS_PLAYER(it) || INGAME_JOINED(it))
1255 s = strcat(s, ftos(it.team), ":");
1257 s = strcat(s, "spectator:");
1260 LOG_HELP(s, playername(it.netname, it.team, false));
1262 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1264 fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1269 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1275 fputs(file, strcat(s, "\n"));
1277 for(i = 1; i < 16; ++i)
1279 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1280 s = strcat(s, ":", ftos(i));
1286 fputs(file, strcat(s, "\n"));
1293 GameLogEcho(":end");
1296 fputs(file, ":end\n");
1302 go to the next level for deathmatch
1303 only called if a time or frag limit has expired
1307 cvar_set("_endmatch", "0");
1308 game_stopped = true;
1309 intermission_running = true; // game over
1311 // enforce a wait time before allowing changelevel
1312 if(player_count > 0)
1313 intermission_exittime = time + autocvar_sv_mapchange_delay;
1315 intermission_exittime = -1;
1318 WriteByte (MSG_ALL, SVC_CDTRACK);
1319 WriteByte (MSG_ALL, 3);
1320 WriteByte (MSG_ALL, 3);
1321 // done in FixIntermission
1324 //pos = FindIntermission ();
1331 PlayerStats_GameReport(true);
1332 WeaponStats_Shutdown();
1334 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1336 if(autocvar_sv_eventlog)
1337 GameLogEcho(":gameover");
1341 int winner_team = 0;
1342 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1343 FixIntermissionClient(it);
1346 if (teamplay && !winner_team)
1348 winner_team = it.team;
1349 bprint(Team_ColorCode(winner_team), Team_ColorName_Upper(winner_team), "^7 team wins the match\n");
1351 bprint(playername(it.netname, it.team, false), " ^7wins\n");
1355 target_music_kill();
1357 if(autocvar_g_campaign)
1358 CampaignPreIntermission();
1360 MUTATOR_CALLHOOK(MatchEnd);
1362 localcmd("\nsv_hook_gameend\n");
1366 int InitiateSuddenDeath()
1368 // Check first whether normal overtimes could be added before initiating suddendeath mode
1369 // - for this timelimit_overtime needs to be >0 of course
1370 // - also check the winning condition calculated in the previous frame and only add normal overtime
1371 // again, if at the point at which timelimit would be extended again, still no winner was found
1372 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1373 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1374 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1376 return 1; // need to call InitiateOvertime later
1380 if(!checkrules_suddendeathend)
1382 if(autocvar_g_campaign)
1384 checkrules_suddendeathend = time; // no suddendeath in campaign
1388 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1391 if(g_race && !g_race_qualifying)
1392 race_StartCompleting();
1398 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1400 ++checkrules_overtimesadded;
1401 overtimes = checkrules_overtimesadded;
1402 //add one more overtime by simply extending the timelimit
1403 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1404 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1407 float GetWinningCode(float fraglimitreached, float equality)
1409 if(autocvar_g_campaign == 1)
1411 if(fraglimitreached)
1420 if(fraglimitreached)
1421 return WINNING_STARTSUDDENDEATHOVERTIME;
1423 return WINNING_NEVER;
1427 if(fraglimitreached)
1435 // set the .winning flag for exactly those players with a given field value
1436 void SetWinners(.float field, float value)
1438 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = (it.(field) == value); });
1441 // set the .winning flag for those players with a given field value
1442 void AddWinners(.float field, float value)
1444 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1445 if(it.(field) == value)
1450 // clear the .winning flags
1453 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = 0; });
1457 float WinningCondition_Scores(float limit, float leadlimit)
1459 // TODO make everything use THIS winning condition (except LMS)
1460 WinningConditionHelper(NULL);
1464 for (int i = 1; i < 5; ++i)
1466 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1467 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1472 if(WinningConditionHelper_winner)
1473 WinningConditionHelper_winner.winning = 1;
1474 if(WinningConditionHelper_winnerteam >= 0)
1475 SetWinners(team, WinningConditionHelper_winnerteam);
1477 if(WinningConditionHelper_lowerisbetter)
1479 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1480 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1484 if(WinningConditionHelper_zeroisworst)
1485 leadlimit = 0; // not supported in this mode
1487 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1490 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1496 fragsleft = FLOAT_MAX;
1497 float leadingfragsleft = FLOAT_MAX;
1499 fragsleft = limit - WinningConditionHelper_topscore;
1501 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1503 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1504 fragsleft = max(fragsleft, leadingfragsleft);
1506 fragsleft = min(fragsleft, leadingfragsleft);
1509 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1512 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1513 else if (fragsleft == 2)
1514 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1515 else if (fragsleft == 3)
1516 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1518 fragsleft_last = fragsleft;
1522 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1523 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1526 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1527 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1528 limit_reached = (fraglimit_reached && leadlimit_reached);
1530 limit_reached = (fraglimit_reached || leadlimit_reached);
1532 return GetWinningCode(
1533 WinningConditionHelper_topscore && limit_reached,
1534 WinningConditionHelper_equality
1538 float WinningCondition_RanOutOfSpawns()
1540 if(have_team_spawns <= 0)
1543 if(!autocvar_g_spawn_useallspawns)
1546 if(!some_spawn_has_been_used)
1549 for (int i = 1; i < 5; ++i)
1551 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1554 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1556 if (Team_IsValidTeam(it.team))
1558 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1562 IL_EACH(g_spawnpoints, true,
1564 if (Team_IsValidTeam(it.team))
1566 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1571 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1572 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1573 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1574 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1575 if(team1_score + team2_score + team3_score + team4_score == 0)
1577 checkrules_equality = true;
1580 else if(team1_score + team2_score + team3_score + team4_score == 1)
1585 else if(team2_score)
1587 else if(team3_score)
1589 else // if(team4_score)
1591 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1592 for(i = 0; i < MAX_TEAMSCORE; ++i)
1594 for (int j = 1; j <= NUM_TEAMS; ++j)
1600 if (!TeamBalance_IsTeamAllowed(balance, j))
1604 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1608 AddWinners(team, t);
1619 Exit deathmatch games upon conditions
1622 void CheckRules_World()
1629 if (intermission_running) // someone else quit the game already
1631 if(player_count == 0) // Nobody there? Then let's go to the next map
1633 // this will actually check the player count in the next frame
1634 // again, but this shouldn't hurt
1638 float timelimit = autocvar_timelimit * 60;
1639 float fraglimit = autocvar_fraglimit;
1640 float leadlimit = autocvar_leadlimit;
1641 if (leadlimit < 0) leadlimit = 0;
1643 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1646 timelimit = 0; // timelimit is not made for warmup
1648 fraglimit = 0; // no fraglimit for now
1649 leadlimit = 0; // no leadlimit for now
1652 if (autocvar__endmatch || timelimit < 0)
1660 timelimit += game_starttime;
1662 int overtimes_prev = overtimes;
1663 int wantovertime = 0;
1665 if(checkrules_suddendeathend)
1667 if(!checkrules_suddendeathwarning)
1669 checkrules_suddendeathwarning = true;
1670 if(g_race && !g_race_qualifying)
1671 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1673 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1678 if (timelimit && time >= timelimit)
1680 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1683 float playerswithlaps;
1685 totalplayers = playerswithlaps = readyplayers = 0;
1686 FOREACH_CLIENT(IS_PLAYER(it), {
1688 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1694 // at least 2 of the players have completed a lap: start the RACE
1695 // otherwise, the players should end the qualifying on their own
1696 if(readyplayers || playerswithlaps >= 2)
1698 checkrules_suddendeathend = 0;
1699 ReadyRestart(true); // go to race
1703 wantovertime |= InitiateSuddenDeath();
1706 wantovertime |= InitiateSuddenDeath();
1710 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1716 int checkrules_status = WinningCondition_RanOutOfSpawns();
1717 if(checkrules_status == WINNING_YES)
1718 bprint("Hey! Someone ran out of spawns!\n");
1719 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1720 checkrules_status = M_ARGV(0, float);
1722 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1724 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1726 checkrules_status = WINNING_NEVER;
1727 checkrules_overtimesadded = -1;
1728 wantovertime |= InitiateSuddenDeath();
1731 if(checkrules_status == WINNING_NEVER)
1732 // equality cases! Nobody wins if the overtime ends in a draw.
1737 if(checkrules_status == WINNING_NEVER)
1740 checkrules_status = WINNING_YES;
1743 if(checkrules_suddendeathend)
1744 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1745 checkrules_status = WINNING_YES;
1747 if(checkrules_status == WINNING_YES)
1749 if (overtimes == -1 && overtimes != overtimes_prev)
1751 // if suddendeathend overtime has just begun, revert it
1752 checkrules_suddendeathend = 0;
1753 overtimes = overtimes_prev;
1755 //print("WINNING\n");
1760 float want_weapon(entity weaponinfo, float allguns)
1763 bool allow_mutatorblocked = false;
1765 if(!weaponinfo.m_id)
1768 bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1769 d = M_ARGV(1, float);
1770 allguns = M_ARGV(2, bool);
1771 allow_mutatorblocked = M_ARGV(3, bool);
1774 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1775 else if(!mutator_returnvalue)
1776 d = !(!weaponinfo.weaponstart);
1778 if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1781 float t = weaponinfo.weaponstartoverride;
1783 //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1788 // 4: is set by default?
1797 /// Weapons the player normally starts with outside weapon arena.
1798 WepSet weapons_start()
1800 WepSet ret = '0 0 0';
1801 FOREACH(Weapons, it != WEP_Null, {
1802 int w = want_weapon(it, false);
1809 WepSet weapons_all()
1811 WepSet ret = '0 0 0';
1812 FOREACH(Weapons, it != WEP_Null, {
1813 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1819 WepSet weapons_devall()
1821 WepSet ret = '0 0 0';
1822 FOREACH(Weapons, it != WEP_Null,
1829 WepSet weapons_most()
1831 WepSet ret = '0 0 0';
1832 FOREACH(Weapons, it != WEP_Null, {
1833 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
1839 void weaponarena_available_all_update(entity this)
1841 if (weaponsInMapAll)
1843 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
1847 // if no weapons are available on the map, just fall back to all weapons arena
1848 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
1852 void weaponarena_available_devall_update(entity this)
1854 if (weaponsInMapAll)
1856 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
1860 // if no weapons are available on the map, just fall back to devall weapons arena
1861 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
1865 void weaponarena_available_most_update(entity this)
1867 if (weaponsInMapAll)
1869 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
1873 // if no weapons are available on the map, just fall back to most weapons arena
1874 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
1878 void readplayerstartcvars()
1880 // initialize starting values for players
1881 start_weapons = '0 0 0';
1882 start_weapons_default = '0 0 0';
1883 start_weapons_defaultmask = '0 0 0';
1885 start_ammo_shells = 0;
1886 start_ammo_nails = 0;
1887 start_ammo_rockets = 0;
1888 start_ammo_cells = 0;
1889 start_ammo_plasma = 0;
1890 if (random_start_ammo == NULL)
1892 random_start_ammo = new_pure(random_start_ammo);
1894 start_health = cvar("g_balance_health_start");
1895 start_armorvalue = cvar("g_balance_armor_start");
1898 g_weaponarena_weapons = '0 0 0';
1900 string s = cvar_string("g_weaponarena");
1902 MUTATOR_CALLHOOK(SetWeaponArena, s);
1903 s = M_ARGV(0, string);
1905 if (s == "0" || s == "")
1909 else if (s == "off")
1911 // forcibly turn off weaponarena
1913 else if (s == "all" || s == "1")
1916 g_weaponarena_list = "All Weapons Arena";
1917 g_weaponarena_weapons = weapons_all();
1919 else if (s == "devall")
1922 g_weaponarena_list = "Dev All Weapons Arena";
1923 g_weaponarena_weapons = weapons_devall();
1925 else if (s == "most")
1928 g_weaponarena_list = "Most Weapons Arena";
1929 g_weaponarena_weapons = weapons_most();
1931 else if (s == "all_available")
1934 g_weaponarena_list = "All Available Weapons Arena";
1936 // this needs to run after weaponsInMapAll is initialized
1937 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
1939 else if (s == "devall_available")
1942 g_weaponarena_list = "Dev All Available Weapons Arena";
1944 // this needs to run after weaponsInMapAll is initialized
1945 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
1947 else if (s == "most_available")
1950 g_weaponarena_list = "Most Available Weapons Arena";
1952 // this needs to run after weaponsInMapAll is initialized
1953 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
1955 else if (s == "none")
1958 g_weaponarena_list = "No Weapons Arena";
1963 float t = tokenize_console(s);
1964 g_weaponarena_list = "";
1965 for (int j = 0; j < t; ++j)
1968 Weapon wep = Weapon_from_name(s);
1971 g_weaponarena_weapons |= (wep.m_wepset);
1972 g_weaponarena_list = strcat(g_weaponarena_list, wep.netname, " & ");
1975 if (g_weaponarena_list != "") // remove trailing " & "
1976 g_weaponarena_list = substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3);
1977 else // no valid weapon found
1978 g_weaponarena_list = "No Weapons Arena";
1983 g_weapon_stay = 0; // incompatible
1984 start_weapons = g_weaponarena_weapons;
1985 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
1986 g_weaponarena_list = strzone(g_weaponarena_list);
1990 FOREACH(Weapons, it != WEP_Null, {
1991 int w = want_weapon(it, false);
1992 WepSet s = it.m_wepset;
1996 start_weapons_default |= s;
1998 start_weapons_defaultmask |= s;
2002 if(cvar("g_balance_superweapons_time") < 0)
2003 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2005 if(!cvar("g_use_ammunition"))
2006 start_items |= IT_UNLIMITED_AMMO;
2008 if(start_items & IT_UNLIMITED_AMMO)
2010 start_ammo_shells = 999;
2011 start_ammo_nails = 999;
2012 start_ammo_rockets = 999;
2013 start_ammo_cells = 999;
2014 start_ammo_plasma = 999;
2015 start_ammo_fuel = 999;
2019 start_ammo_shells = cvar("g_start_ammo_shells");
2020 start_ammo_nails = cvar("g_start_ammo_nails");
2021 start_ammo_rockets = cvar("g_start_ammo_rockets");
2022 start_ammo_cells = cvar("g_start_ammo_cells");
2023 start_ammo_plasma = cvar("g_start_ammo_plasma");
2024 start_ammo_fuel = cvar("g_start_ammo_fuel");
2025 random_start_weapons_count = cvar("g_random_start_weapons_count");
2026 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2027 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2028 SetResource(random_start_ammo, RES_ROCKETS, cvar("g_random_start_rockets"));
2029 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2030 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2033 warmup_start_ammo_shells = start_ammo_shells;
2034 warmup_start_ammo_nails = start_ammo_nails;
2035 warmup_start_ammo_rockets = start_ammo_rockets;
2036 warmup_start_ammo_cells = start_ammo_cells;
2037 warmup_start_ammo_plasma = start_ammo_plasma;
2038 warmup_start_ammo_fuel = start_ammo_fuel;
2039 warmup_start_health = start_health;
2040 warmup_start_armorvalue = start_armorvalue;
2041 warmup_start_weapons = start_weapons;
2042 warmup_start_weapons_default = start_weapons_default;
2043 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2047 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2048 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2049 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2050 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2051 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2052 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2053 warmup_start_health = cvar("g_warmup_start_health");
2054 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2055 warmup_start_weapons = '0 0 0';
2056 warmup_start_weapons_default = '0 0 0';
2057 warmup_start_weapons_defaultmask = '0 0 0';
2058 FOREACH(Weapons, it != WEP_Null, {
2059 int w = want_weapon(it, autocvar_g_warmup_allguns);
2060 WepSet s = it.m_wepset;
2062 warmup_start_weapons |= s;
2064 warmup_start_weapons_default |= s;
2066 warmup_start_weapons_defaultmask |= s;
2070 if (autocvar_g_jetpack)
2071 start_items |= ITEM_Jetpack.m_itemid;
2073 MUTATOR_CALLHOOK(SetStartItems);
2075 if (start_items & ITEM_Jetpack.m_itemid)
2077 start_items |= ITEM_JetpackRegen.m_itemid;
2078 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2079 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2082 start_ammo_shells = max(0, start_ammo_shells);
2083 start_ammo_nails = max(0, start_ammo_nails);
2084 start_ammo_rockets = max(0, start_ammo_rockets);
2085 start_ammo_cells = max(0, start_ammo_cells);
2086 start_ammo_plasma = max(0, start_ammo_plasma);
2087 start_ammo_fuel = max(0, start_ammo_fuel);
2088 SetResource(random_start_ammo, RES_SHELLS, max(0, GetResource(random_start_ammo, RES_SHELLS)));
2089 SetResource(random_start_ammo, RES_BULLETS, max(0, GetResource(random_start_ammo, RES_BULLETS)));
2090 SetResource(random_start_ammo, RES_ROCKETS, max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2091 SetResource(random_start_ammo, RES_CELLS, max(0, GetResource(random_start_ammo, RES_CELLS)));
2092 SetResource(random_start_ammo, RES_PLASMA, max(0, GetResource(random_start_ammo, RES_PLASMA)));
2094 warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2095 warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2096 warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2097 warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2098 warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2099 warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2102 void readlevelcvars()
2104 serverflags &= ~SERVERFLAG_ALLOW_FULLBRIGHT;
2105 if(cvar("sv_allow_fullbright"))
2106 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2108 serverflags &= ~SERVERFLAG_FORBID_PICKUPTIMER;
2109 if(cvar("sv_forbid_pickuptimer"))
2110 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2112 sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2114 if(cvar("g_campaign"))
2115 warmup_stage = 0; // no warmup during campaign
2118 warmup_stage = autocvar_g_warmup;
2119 if (warmup_stage < 0 || warmup_stage > 1)
2120 warmup_limit = -1; // don't start until there's enough players
2121 else if (warmup_stage == 1)
2123 // this code is duplicated in ReadyCount()
2124 warmup_limit = cvar("g_warmup_limit");
2125 if(warmup_limit == 0)
2126 warmup_limit = autocvar_timelimit * 60;
2130 g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2131 g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2132 g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2133 g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
2134 g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
2135 g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
2136 g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2137 g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2138 g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2139 g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2140 g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
2141 g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
2142 g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
2143 g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2145 g_pickup_shells = cvar("g_pickup_shells");
2146 g_pickup_shells_max = cvar("g_pickup_shells_max");
2147 g_pickup_nails = cvar("g_pickup_nails");
2148 g_pickup_nails_max = cvar("g_pickup_nails_max");
2149 g_pickup_rockets = cvar("g_pickup_rockets");
2150 g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2151 g_pickup_cells = cvar("g_pickup_cells");
2152 g_pickup_cells_max = cvar("g_pickup_cells_max");
2153 g_pickup_plasma = cvar("g_pickup_plasma");
2154 g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2155 g_pickup_fuel = cvar("g_pickup_fuel");
2156 g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2157 g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2158 g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2159 g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2160 g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2161 g_pickup_armormedium = cvar("g_pickup_armormedium");
2162 g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2163 g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2164 g_pickup_armorbig = cvar("g_pickup_armorbig");
2165 g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2166 g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2167 g_pickup_armormega = cvar("g_pickup_armormega");
2168 g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2169 g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2170 g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2171 g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2172 g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2173 g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2174 g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2175 g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2176 g_pickup_healthbig = cvar("g_pickup_healthbig");
2177 g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2178 g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2179 g_pickup_healthmega = cvar("g_pickup_healthmega");
2180 g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2181 g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2183 g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2184 g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2186 g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2188 g_weapon_stay = cvar("g_weapon_stay");
2190 MUTATOR_CALLHOOK(ReadLevelCvars);
2192 if (!warmup_stage && !autocvar_g_campaign)
2193 game_starttime = time + cvar("g_start_delay");
2195 FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2197 readplayerstartcvars();
2200 void InitializeEntity(entity e, void(entity this) func, int order)
2204 if (!e || e.initialize_entity)
2206 // make a proxy initializer entity
2208 e = new(initialize_entity);
2212 e.initialize_entity = func;
2213 e.initialize_entity_order = order;
2215 cur = initialize_entity_first;
2219 if (!cur || cur.initialize_entity_order > order)
2221 // insert between prev and cur
2223 prev.initialize_entity_next = e;
2225 initialize_entity_first = e;
2226 e.initialize_entity_next = cur;
2230 cur = cur.initialize_entity_next;
2233 void InitializeEntitiesRun()
2235 entity startoflist = initialize_entity_first;
2236 initialize_entity_first = NULL;
2237 delete_fn = remove_except_protected;
2238 for (entity e = startoflist; e; e = e.initialize_entity_next)
2240 e.remove_except_protected_forbidden = 1;
2242 for (entity e = startoflist; e; )
2244 e.remove_except_protected_forbidden = 0;
2245 e.initialize_entity_order = 0;
2246 entity next = e.initialize_entity_next;
2247 e.initialize_entity_next = NULL;
2248 var void(entity this) func = e.initialize_entity;
2249 e.initialize_entity = func_null;
2250 if (e.classname == "initialize_entity")
2252 entity wrappee = e.enemy;
2256 //dprint("Delayed initialization: ", e.classname, "\n");
2264 backtrace(strcat("Null function in: ", e.classname, "\n"));
2268 delete_fn = remove_unsafely;
2271 // deferred dropping
2272 // ported from VM_SV_droptofloor TODO: make a common function for the client-side?
2273 void DropToFloor_Handler(entity this)
2275 if(!this || wasfreed(this))
2277 // no modifying free entities
2281 vector end = this.origin;
2282 if (autocvar_sv_mapformat_is_quake3)
2284 else if (autocvar_sv_mapformat_is_quake2)
2287 end.z -= 256; // Quake, QuakeWorld
2289 // NOTE: SV_NudgeOutOfSolid is used in the engine here
2290 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2292 _Movetype_UnstickEntity(this);
2293 move_out_of_solid(this);
2296 tracebox(this.origin, this.mins, this.maxs, end, MOVE_NORMAL, this);
2298 if(trace_startsolid && autocvar_sv_gameplayfix_droptofloorstartsolid)
2301 offset = 0.5 * (this.mins + this.maxs);
2302 offset.z = this.mins.z;
2303 org = this.origin + offset;
2304 traceline(org, end, MOVE_NORMAL, this);
2305 trace_endpos = trace_endpos - offset;
2306 if(trace_startsolid)
2308 LOG_DEBUGF("DropToFloor_Handler: %v could not fix badly placed entity", this.origin);
2309 _Movetype_LinkEdict(this, false);
2311 this.groundentity = NULL;
2313 else if(trace_fraction < 1)
2315 LOG_DEBUGF("DropToFloor_Handler: %v fixed badly placed entity", this.origin);
2316 setorigin(this, trace_endpos);
2317 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2319 _Movetype_UnstickEntity(this);
2320 move_out_of_solid(this);
2323 this.groundentity = trace_ent;
2324 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2325 this.move_suspendedinair = true;
2330 if(!trace_allsolid && trace_fraction < 1)
2332 setorigin(this, trace_endpos);
2334 this.groundentity = trace_ent;
2335 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2336 this.move_suspendedinair = true;
2340 // if we can't get the entity out of solid, mark it as on ground so physics doesn't attempt to drop it
2341 // hacky workaround for #2774
2345 this.dropped_origin = this.origin;
2348 void droptofloor(entity this)
2350 InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2353 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2354 void RunThink(entity this, float dt)
2356 // don't let things stay in the past.
2357 // it is possible to start that way by a trigger with a local time.
2358 if(this.nextthink <= 0 || this.nextthink > time + dt)
2361 float oldtime = time; // do we need to save this?
2363 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2365 time = max(oldtime, this.nextthink);
2369 getthink(this)(this);
2370 // mods often set nextthink to time to cause a think every frame,
2371 // we don't want to loop in that case, so exit if the new nextthink is
2372 // <= the time the qc was told, also exit if it is past the end of the
2374 if(this.nextthink <= time || this.nextthink > oldtime + dt || !autocvar_sv_gameplayfix_multiplethinksperframe)
2381 bool autocvar_sv_freezenonclients;
2382 void Physics_Frame()
2384 if(autocvar_sv_freezenonclients)
2387 IL_EACH(g_moveables, true,
2389 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2392 //set_movetype(it, it.move_movetype);
2393 // inline the set_movetype function, since this is called a lot
2394 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2396 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2397 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2399 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2401 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2402 continue; // these movetypes have no regular think function
2403 // handle thinking here
2404 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + PHYS_INPUT_TIMELENGTH)
2405 RunThink(it, PHYS_INPUT_TIMELENGTH);
2409 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2412 // make a second pass to see if any ents spawned this frame and make
2413 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2414 // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2415 IL_EACH(g_moveables, it.move_qcphysics,
2417 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2419 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2423 void systems_update();
2426 anticheat_endframe();
2430 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2431 entity e = IS_SPEC(it) ? it.enemy : it;
2432 if (e.typehitsound) {
2433 STAT(TYPEHIT_TIME, it) = time;
2434 } else if (e.killsound) {
2435 STAT(KILL_TIME, it) = time;
2436 } else if (e.hitsound_damage_dealt) {
2437 STAT(HIT_TIME, it) = time;
2438 // NOTE: this is not accurate as client code doesn't need so much accuracy for its purposes
2439 STAT(HITSOUND_DAMAGE_DEALT_TOTAL, it) += ceil(e.hitsound_damage_dealt);
2442 // add 1 frametime because after this, engine SV_Physics
2443 // increases time by a frametime and then networks the frame
2444 // add another frametime because client shows everything with
2445 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2447 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2448 FOREACH_CLIENT(true, {
2449 it.typehitsound = false;
2450 it.hitsound_damage_dealt = 0;
2451 it.killsound = false;
2452 antilag_record(it, CS(it), altime);
2454 IL_EACH(g_monsters, true,
2456 antilag_record(it, it, altime);
2458 IL_EACH(g_projectiles, it.classname == "nade",
2460 antilag_record(it, it, altime);
2469 * returns true if redirecting
2471 float redirection_timeout;
2472 float redirection_nextthink;
2473 float RedirectionThink()
2475 float clients_found;
2477 if(redirection_target == "")
2480 if(!redirection_timeout)
2482 cvar_set("sv_public", "-2");
2483 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2484 if(redirection_target == "self")
2485 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2487 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2490 if(time < redirection_nextthink)
2493 redirection_nextthink = time + 1;
2496 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2498 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2499 if(redirection_target == "self")
2500 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2502 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2506 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2508 if(time > redirection_timeout || clients_found == 0)
2509 localcmd("\nwait; wait; wait; quit\n");
2516 // Loaded from a save game
2517 // some things then break, so let's work around them...
2519 // Progs DB (capture records)
2520 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2524 MapInfo_Enumerate();
2525 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2528 TargetMusic_RestoreGame();
2535 if(world_initialized > 0)
2537 world_initialized = 0;
2539 // if a timeout is active, reset the slowmo value to normal
2540 if(timeout_status == TIMEOUT_ACTIVE)
2541 cvar_set("slowmo", ftos(orig_slowmo));
2543 LOG_TRACE("Saving persistent data...");
2546 // playerstats with unfinished match
2547 PlayerStats_GameReport(false);
2549 if(!cheatcount_total)
2551 if(autocvar_sv_db_saveasdump)
2552 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2554 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2556 if(autocvar_developer > 0)
2558 if(autocvar_sv_db_saveasdump)
2559 db_dump(TemporaryDB, "server-temp.db");
2561 db_save(TemporaryDB, "server-temp.db");
2563 CheatShutdown(); // must be after cheatcount check
2564 db_close(ServerProgsDB);
2565 db_close(TemporaryDB);
2566 LOG_TRACE("Saving persistent data... done!");
2567 // tell the bot system the game is ending now
2570 WeaponStats_Shutdown();
2573 strfree(sv_termsofservice_url_escaped);
2575 else if(world_initialized == 0)
2577 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2581 __init_dedicated_server_shutdown();