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 send_TotalShards(entity to) {
105 // Send total number of picked up shards
106 if(!autocvar_rjz_count_shards) return;
107 if(!IS_REAL_CLIENT(to)) return;
110 WriteHeader(MSG_ONE, TE_CSQC_TOTALSHARDS);
111 WriteInt24_t(MSG_ONE, total_shards);
114 void send_TotalShardsAll() {
116 // Send total number of picked up shards
117 if(!autocvar_rjz_count_shards) return;
119 FOREACH_CLIENT(IS_REAL_CLIENT(it) && (IS_SPEC(it) || IS_OBSERVER(it)), {
120 send_TotalShards(it);
124 void SetDefaultAlpha()
126 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
128 default_player_alpha = autocvar_g_player_alpha;
129 if(default_player_alpha == 0)
130 default_player_alpha = 1;
131 default_weapon_alpha = default_player_alpha;
135 void GotoFirstMap(entity this)
138 if(autocvar__sv_init)
140 // cvar_set("_sv_init", "0");
141 // we do NOT set this to 0 any more, so someone "accidentally" changing
142 // to this "init" map on a dedicated server will cause no permanent
144 if(autocvar_g_maplist_shuffle)
146 n = tokenizebyseparator(autocvar_g_maplist, " ");
147 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
150 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
152 if(!DoNextMapOverride(1))
160 this.nextthink = time;
164 this.nextthink = time + 1;
165 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
169 void cvar_changes_init()
173 float n, i, adding, pureadding;
175 strfree(cvar_changes);
176 strfree(cvar_purechanges);
177 cvar_purechanges_count = 0;
180 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
186 for(i = 0; i < n; ++i)
188 k = bufstr_get(h, i);
190 #define BADPREFIX_COND(p) (substring(k, 0, strlen(p)) == p)
191 #define BADSUFFIX_COND(s) (substring(k, -strlen(s), -1) == s)
193 #define BADPREFIX(p) if(BADPREFIX_COND(p)) continue
194 #define BADPRESUFFIX(p, s) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s)) continue
195 #define BADCVAR(p) if(k == p) continue
196 #define BADVALUE(p, val) if (k == p && v == val) continue
197 #define BADPRESUFFIXVALUE(p, s, val) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s) && v == val) continue
199 // general excludes and namespaces for server admin used cvars
200 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
204 BADPREFIX("cvar_check_");
206 BADCVAR("g_configversion");
207 BADCVAR("halflifebsp");
208 BADCVAR("sv_mapformat_is_quake2");
209 BADCVAR("sv_mapformat_is_quake3");
210 BADPREFIX("sv_world");
216 BADPREFIX("scoreboard_");
217 BADPREFIX("g_campaign");
218 BADPREFIX("g_waypointsprite_");
224 BADPREFIX("net_slist_");
230 BADPREFIX("sensitivity");
231 BADPREFIX("userbind");
234 BADPREFIX("crosshair");
235 BADCVAR("mod_q3bsp_lightmapmergepower");
236 BADCVAR("mod_q3bsp_nolightmaps");
238 BADCVAR("mastervolume");
240 BADCVAR("bgmvolume");
241 BADCVAR("in_pitch_min");
242 BADCVAR("in_pitch_max");
245 BADCVAR("developer");
246 BADCVAR("log_dest_udp");
247 BADCVAR("net_address");
248 BADCVAR("net_address_ipv6");
250 BADCVAR("savedgamecfg");
251 BADCVAR("serverconfig");
252 BADCVAR("sv_autoscreenshot");
253 BADCVAR("sv_heartbeatperiod");
254 BADCVAR("sv_vote_master_password");
255 BADCVAR("sys_colortranslation");
256 BADCVAR("sys_specialcharactertranslation");
257 BADCVAR("timeformat");
258 BADCVAR("timestamps");
259 BADCVAR("g_require_stats");
260 BADCVAR("g_chatban_list");
261 BADCVAR("g_playban_list");
262 BADCVAR("g_playban_minigames");
263 BADCVAR("g_voteban_list");
264 BADPREFIX("developer_");
266 BADPREFIX("g_banned_list");
267 BADPREFIX("g_require_stats_");
268 BADPREFIX("g_chat_flood_");
269 BADPREFIX("g_ghost_items");
270 BADPREFIX("g_playerstats_");
271 BADPREFIX("g_voice_flood_");
272 BADPREFIX("log_file");
275 BADPREFIX("sv_allowdownloads");
276 BADPREFIX("sv_autodemo");
277 BADPREFIX("sv_curl_");
278 BADPREFIX("sv_eventlog");
279 BADPREFIX("sv_logscores_");
280 BADPREFIX("sv_master");
281 BADPREFIX("sv_weaponstats_");
282 BADPREFIX("sv_waypointsprite_");
283 BADCVAR("rescan_pending");
285 // these can contain player IDs, so better hide
286 BADPREFIX("g_forced_team_");
287 BADCVAR("sv_allow_customplayermodels_idlist");
288 BADCVAR("sv_allow_customplayermodels_speciallist");
291 BADCVAR("fraglimit");
293 BADCVAR("g_assault");
295 BADCVAR("g_ca_teams");
296 BADCVAR("g_conquest");
297 BADCVAR("g_conquest_teams");
302 BADCVAR("g_domination");
303 BADCVAR("g_domination_default_teams");
305 BADCVAR("g_duel_not_dm_maps");
306 BADCVAR("g_freezetag");
307 BADCVAR("g_freezetag_teams");
308 BADCVAR("g_invasion_type");
309 BADCVAR("g_jailbreak");
310 BADCVAR("g_jailbreak_teams");
311 BADCVAR("g_keepaway");
312 BADCVAR("g_keyhunt");
313 BADCVAR("g_keyhunt_teams");
316 BADCVAR("g_nexball");
317 BADCVAR("g_onslaught");
319 BADCVAR("g_race_laps_limit");
320 BADCVAR("g_race_qualifying_timelimit");
321 BADCVAR("g_race_qualifying_timelimit_override");
322 BADCVAR("g_runematch");
323 BADCVAR("g_shootfromeye");
325 BADCVAR("g_survival");
326 BADCVAR("g_survival_not_dm_maps");
328 BADCVAR("g_tdm_on_dm_maps");
329 BADCVAR("g_tdm_teams");
331 BADCVAR("g_tka_on_ka_maps");
332 BADCVAR("g_tka_on_tdm_maps");
333 BADCVAR("g_tka_teams");
334 BADCVAR("g_tmayhem");
335 BADCVAR("g_tmayhem_teams");
337 BADCVAR("leadlimit");
340 BADCVAR("timelimit");
341 BADCVAR("g_mapinfo_q3compat");
342 BADCVAR("g_mapinfo_settemp_acl");
343 BADCVAR("g_mapinfo_ignore_warnings");
344 BADCVAR("g_maplist_ignore_sizes");
345 BADCVAR("g_maplist_sizes_count_bots");
348 BADCVAR("hostname_full");
349 BADCVAR("g_maplist");
350 BADCVAR("g_maplist_mostrecent");
352 BADCVAR("sv_motd_permanent");
354 BADPREFIX("g_teamnames_");
355 BADCVAR("sv_termsofservice_url");
358 d = cvar_defstring(k);
364 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
365 if(strlen(cvar_changes) > 16384)
367 cvar_changes = "// too many settings have been changed to show them here\n";
372 // now check if the changes are actually gameplay relevant
374 // does nothing gameplay relevant
375 BADCVAR("captureleadlimit_override");
376 BADCVAR("condump_stripcolors");
377 BADCVAR("fs_gamedir");
378 BADCVAR("g_allow_oldvortexbeam");
379 BADCVAR("g_balance_kill_delay");
380 BADCVAR("g_buffs_pickup_anyway");
381 BADCVAR("g_buffs_randomize");
382 BADCVAR("g_buffs_randomize_teamplay");
383 BADCVAR("g_campcheck_distance");
384 BADCVAR("g_chatsounds");
385 BADCVAR("g_ca_point_leadlimit");
386 BADCVAR("g_ca_point_limit");
387 BADCVAR("g_ca_spectate_enemies");
388 BADCVAR("g_ctf_captimerecord_always");
389 BADCVAR("g_ctf_flag_glowtrails");
390 BADCVAR("g_ctf_dynamiclights");
391 BADCVAR("g_ctf_flag_pickup_verbosename");
392 BADCVAR("g_ctf_flagcarrier_auto_helpme_damage");
393 BADPRESUFFIX("g_ctf_flag_", "_model");
394 BADPRESUFFIX("g_ctf_flag_", "_skin");
395 BADCVAR("g_domination_point_leadlimit");
396 BADCVAR("g_forced_respawn");
397 BADCVAR("g_freezetag_point_leadlimit");
398 BADCVAR("g_freezetag_point_limit");
399 BADCVAR("g_freezetag_revive_respawn");
400 BADCVAR("g_freezetag_round_stop");
401 BADCVAR("g_freezetag_round_respawn");
402 BADCVAR("g_glowtrails");
404 BADCVAR("g_casings");
405 BADCVAR("g_invasion_point_limit");
406 BADCVAR("g_jump_grunt");
407 BADCVAR("g_keepaway_ballcarrier_effects");
408 BADCVAR("g_keepawayball_effects");
409 BADCVAR("g_keyhunt_point_leadlimit");
410 BADCVAR("g_nexball_goalleadlimit");
411 BADCVAR("g_new_toys_autoreplace");
412 BADCVAR("g_new_toys_use_pickupsound");
413 BADCVAR("g_physics_predictall");
414 BADCVAR("g_piggyback");
415 BADCVAR("g_playerclip_collisions");
416 BADCVAR("g_spawn_alloweffects");
417 BADCVAR("g_tdm_point_leadlimit");
418 BADCVAR("g_tdm_point_limit");
419 BADCVAR("g_mayhem_point_limit");
420 BADCVAR("g_mayhem_point_leadlimit");
421 BADCVAR("g_tmayhem_point_limit");
422 BADCVAR("g_tmayhem_point_leadlimit");
423 BADCVAR("leadlimit_and_fraglimit");
424 BADCVAR("leadlimit_override");
425 BADCVAR("g_mayhem_scoringmethod");
426 BADCVAR("g_mayhem_scoringmethod_damage_weight");
427 BADCVAR("g_mayhem_scoringmethod_frag_weight");
428 BADCVAR("g_tmayhem_scoringmethod");
429 BADCVAR("g_tmayhem_scoringmethod_damage_weight");
430 BADCVAR("g_tmayhem_scoringmethod_frag_weight");
432 BADCVAR("sv_announcer");
433 BADCVAR("sv_autopause");
434 BADCVAR("sv_checkforpacketsduringsleep");
435 BADCVAR("sv_damagetext");
436 BADCVAR("sv_db_saveasdump");
437 BADCVAR("sv_intermission_cdtrack");
438 BADCVAR("sv_mapchange_delay");
439 BADCVAR("sv_minigames");
440 BADCVAR("sv_namechangetimer");
441 BADCVAR("sv_precacheplayermodels");
442 BADCVAR("sv_qcphysics");
444 BADCVAR("sv_stepheight");
445 BADCVAR("sv_timeout");
446 BADCVAR("sv_weapons_modeloverride");
447 BADCVAR("w_prop_interval");
449 BADPREFIX("crypto_");
450 BADPREFIX("g_chat_");
451 BADPREFIX("g_ctf_captimerecord_");
452 BADPREFIX("g_hats_");
453 BADPREFIX("g_maplist_");
455 BADPREFIX("g_respawn_");
457 BADPREFIX("notification_");
460 BADPREFIX("sv_allow_");
461 BADPREFIX("sv_cullentities_");
462 BADPREFIX("sv_maxidle");
463 BADPREFIX("sv_minigames_");
464 BADPREFIX("sv_radio_");
465 BADPREFIX("sv_timeout_");
466 BADPREFIX("sv_vote_");
467 BADPREFIX("timelimit_");
468 BADPREFIX("sv_chat_");
469 BADPREFIX("sv_jingle_");
470 BADPRESUFFIX("g_", "_round_timelimit");
472 // allowed changes to server admins (please sync this to server.cfg)
476 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
478 // yes, this does contain some redundant stuff, don't really care
479 BADPREFIX("bot_ai_");
480 BADCVAR("bot_config_file");
481 BADCVAR("bot_number");
482 BADCVAR("bot_prefix");
483 BADCVAR("bot_suffix");
484 BADCVAR("capturelimit_override");
485 BADCVAR("fraglimit_override");
487 BADCVAR("g_antilag");
488 BADCVAR("g_balance_teams");
489 BADCVAR("g_balance_teams_queue");
490 BADCVAR("g_balance_teams_remove");
491 BADCVAR("g_balance_teams_remove_wait");
492 BADCVAR("g_balance_teams_prevent_imbalance");
493 BADCVAR("g_balance_teams_scorefactor");
494 BADCVAR("g_ban_sync_trusted_servers");
495 BADCVAR("g_ban_sync_uri");
497 BADCVAR("g_ca_teams_override");
498 BADCVAR("g_ca_prevent_stalemate");
499 BADCVAR("g_ctf_fullbrightflags");
500 BADCVAR("g_ctf_ignore_frags");
501 BADCVAR("g_ctf_leaderboard");
502 BADCVAR("g_domination_point_limit");
503 BADCVAR("g_domination_teams_override");
504 BADCVAR("g_freezetag_revive_spawnshield");
505 BADCVAR("g_freezetag_teams_override");
506 BADCVAR("g_friendlyfire");
507 BADCVAR("g_fullbrightitems");
508 BADCVAR("g_fullbrightplayers");
509 BADCVAR("g_keyhunt_point_limit");
510 BADCVAR("g_keyhunt_teams_override");
511 BADCVAR("g_lms_lives_override");
512 BADCVAR("g_mayhem_powerups");
513 BADCVAR("g_maplist");
514 BADCVAR("g_maxplayers");
515 BADCVAR("g_mirrordamage");
516 BADCVAR("g_nexball_goallimit");
517 BADCVAR("g_norecoil");
518 BADCVAR("g_physics_clientselect");
520 BADCVAR("g_powerups");
521 BADCVAR("g_powerups_drop_ondeath");
522 BADCVAR("g_player_brightness");
523 BADCVAR("g_rocket_flying");
524 BADCVAR("g_rocket_flying_disabledelays");
525 BADPREFIX("g_spawnshield");
526 BADCVAR("g_start_delay");
527 BADCVAR("g_superspectate");
528 BADCVAR("g_tdm_teams_override");
529 BADCVAR("g_tmayhem_teams_override");
530 BADCVAR("g_tmayhem_powerups");
531 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
534 BADCVAR("maxplayers");
535 BADCVAR("minplayers");
536 BADCVAR("minplayers_per_team");
537 BADCVAR("net_address");
539 BADCVAR("rcon_password");
540 BADCVAR("rcon_restricted_commands");
541 BADCVAR("rcon_restricted_password");
543 BADCVAR("sv_adminnick");
544 BADCVAR("sv_autoscreenshot");
545 BADCVAR("sv_autotaunt");
546 BADCVAR("sv_curl_defaulturl");
547 BADCVAR("sv_defaultcharacter");
548 BADCVAR("sv_defaultcharacterskin");
549 BADCVAR("sv_defaultplayercolors");
550 BADCVAR("sv_defaultplayermodel");
551 BADCVAR("sv_defaultplayerskin");
552 BADCVAR("sv_maxrate");
554 BADCVAR("sv_public");
555 BADCVAR("sv_showfps");
556 BADCVAR("sv_showspectators");
557 BADCVAR("sv_status_privacy");
559 BADCVAR("sv_vote_call");
560 BADCVAR("sv_vote_commands");
561 BADCVAR("sv_vote_majority_factor");
562 BADCVAR("sv_vote_master");
563 BADCVAR("sv_vote_master_commands");
564 BADCVAR("sv_vote_master_password");
565 BADCVAR("sv_vote_simple_majority_factor");
566 BADVALUE("sys_ticrate", "0.0166667");
567 BADVALUE("sys_ticrate", "0.0333333");
568 BADCVAR("teamplay_mode");
569 BADCVAR("timelimit_override");
570 BADPREFIX("g_warmup");
571 BADPREFIX("sv_info_");
572 BADPREFIX("sv_ready_restart_");
574 BADPRESUFFIXVALUE("g_", "_weaponarena", "most");
575 BADPRESUFFIXVALUE("g_", "_weaponarena", "most_available");
577 // mutators that announce themselves properly to the server browser
578 BADCVAR("g_instagib");
579 BADCVAR("g_new_toys");
581 BADCVAR("g_grappling_hook");
582 BADCVAR("g_jetpack");
584 // temporary for testing
585 // TODO remove before 0.8.3 release
586 BADCVAR("g_ca_weaponarena");
587 BADCVAR("g_freezetag_weaponarena");
588 BADCVAR("g_lms_weaponarena");
589 BADCVAR("g_mayhem_weaponarena");
590 BADCVAR("g_tmayhem_weaponarena");
591 BADCVAR("g_ctf_stalemate_time");
597 #undef BADPRESUFFIXVALUE
601 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
602 if(strlen(cvar_purechanges) > 16384)
604 cvar_purechanges = "// too many settings have been changed to show them here\n";
608 ++cvar_purechanges_count;
609 // WARNING: this variable is used for the server list
610 // NEVER dare to skip this code!
611 // Hacks to intentionally appearing as "pure server" even though you DO have
612 // modified settings may be punished by removal from the server list.
613 // You can do to the variables cvar_changes and cvar_purechanges all you want,
617 if(cvar_changes == "")
618 cvar_changes = "// this server runs at default server settings\n";
620 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
621 cvar_changes = strzone(cvar_changes);
622 if(cvar_purechanges == "")
623 cvar_purechanges = "// this server runs at default gameplay settings\n";
625 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
626 cvar_purechanges = strzone(cvar_purechanges);
630 bool RandomSeed_Send(entity this, entity to, int sf)
632 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
633 WriteShort(MSG_ENTITY, this.cnt);
636 void RandomSeed_Think(entity this)
638 this.cnt = bound(0, floor(random() * 65536), 65535);
639 this.nextthink = time + 5;
643 void RandomSeed_Spawn()
645 randomseed = new_pure(randomseed);
646 setthink(randomseed, RandomSeed_Think);
647 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
649 getthink(randomseed)(randomseed); // sets random seed and nextthink
652 spawnfunc(__init_dedicated_server)
654 // handler for _init/_init map (only for dedicated server initialization)
656 world_initialized = -1; // don't complain
658 delete_fn = remove_unsafely;
660 entity e = new(GotoFirstMap);
661 setthink(e, GotoFirstMap);
662 e.nextthink = time; // this is usually 1 at this point
664 e = new(info_player_deathmatch); // safeguard against player joining
666 // assign reflectively to avoid "assignment to world" warning
667 for (int i = 0, n = numentityfields(); i < n; ++i)
669 string k = entityfieldname(i);
670 if (k == "classname")
672 // safeguard against various stuff ;)
673 putentityfieldstring(i, this, "worldspawn");
678 // needs to be done so early because of the constants they create
681 static_init_precache();
683 IL_PUSH(g_spawnpoints, e); // just incase
686 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
689 void __init_dedicated_server_shutdown() {
693 STATIC_INIT_EARLY(maxclients)
696 for (entity head = nextent(NULL); head; head = nextent(head)) {
701 void GameplayMode_DelayedInit(entity this)
703 // at this stage team entities are spawned, teamplay contains the number of them
705 if(!scores_initialized)
706 ScoreRules_generic();
708 if (warmup_stage >= 0 && autocvar_g_maxplayers >= 0)
711 MapReadSizes(mapname);
713 if (autocvar_g_maxplayers < 0 && teamplay)
715 // automatic maxplayers should be a multiple of team count
716 if (map_maxplayers == 0 || map_maxplayers > maxclients)
717 map_maxplayers = maxclients; // unlimited, but may need rounding
718 int d = map_maxplayers % AVAILABLE_TEAMS;
719 int u = AVAILABLE_TEAMS - d;
720 map_maxplayers += (u <= d && u + map_maxplayers <= maxclients) ? u : -d;
723 if (warmup_stage < 0)
725 int m = GetPlayerLimit();
726 if (m <= 0) m = maxclients;
727 map_minplayers = bound(max(2, AVAILABLE_TEAMS * 2), map_minplayers, m);
730 // automatic minplayers should be a multiple of team count
731 int d = map_minplayers % AVAILABLE_TEAMS;
732 int u = AVAILABLE_TEAMS - d;
733 map_minplayers += (u < d && u + map_minplayers <= m) ? u : -d;
737 map_minplayers = 0; // don't display a minimum if it's not used (g_maxplayers < 0 && g_warmup >= 0)
740 void InitGameplayMode()
744 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
746 // assign reflectively to avoid "assignment to world" warning
747 for (int i = 0, done = 0, n = numentityfields(); i < n; ++i)
749 string k = entityfieldname(i);
750 vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
753 putentityfieldstring(i, world, sprintf("%v", v));
754 if (++done == 2) break;
757 // currently, NetRadiant's limit is 131072 qu for each side
758 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
759 // set the distance according to map size but don't go over the limit to avoid issues with float precision
760 // in case somebody makes extremely large maps
761 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
763 MapInfo_LoadMapSettings(mapname);
764 GameRules_teams(false);
766 if (!cvar_value_issafe(world.fog))
768 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
769 world.fog = string_null;
771 if(MapInfo_Map_fog != "")
773 if(MapInfo_Map_fog == "none")
774 world.fog = string_null;
776 world.fog = strzone(MapInfo_Map_fog);
778 clientstuff = strzone(MapInfo_Map_clientstuff);
780 MapInfo_ClearTemps();
782 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
784 cache_mutatormsg = strzone("");
785 cache_lastmutatormsg = strzone("");
787 InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
790 bool world_already_spawned;
791 spawnfunc(worldspawn)
793 cvar_set("_endmatch", "0");
794 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
796 if (autocvar_sv_termsofservice_url && autocvar_sv_termsofservice_url != "")
798 strcpy(sv_termsofservice_url_escaped, strreplace(":", "|", autocvar_sv_termsofservice_url));
802 strcpy(sv_termsofservice_url_escaped, "INVALID");
805 bool wantrestart = false;
807 if (!server_is_dedicated)
809 // DP unloads dlcache pk3s before starting a listen server since https://gitlab.com/xonotic/darkplaces/-/merge_requests/134
810 // restore csqc_progname too
811 string expect = "csprogs.dat";
812 wantrestart = cvar_string("csqc_progname") != expect;
813 cvar_set("csqc_progname", expect);
817 // Try to use versioned csprogs from pk3
818 // Only ever use versioned csprogs.dat files on dedicated servers;
819 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
820 string pk3csprogs = "csprogs-" WATERMARK ".dat";
821 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
822 string select = "csprogs.dat";
823 if (fexists(pk3csprogs)) select = pk3csprogs;
824 if (cvar_string("csqc_progname") != select)
826 cvar_set("csqc_progname", select);
829 // Check for updates on startup
830 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
831 int sentinel = fopen("progs.txt", FILE_READ);
834 string switchversion = fgets(sentinel);
836 if (switchversion != "" && switchversion != WATERMARK)
838 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
839 // if it doesn't exist, assume either:
840 // a) the current program was overwritten
841 // b) this is a client only update
842 string newprogs = sprintf("progs-%s.dat", switchversion);
843 if (fexists(newprogs))
845 cvar_set("sv_progs", newprogs);
848 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
849 if (fexists(newcsprogs))
851 cvar_set("csqc_progname", newcsprogs);
859 LOG_INFO("Restart requested");
860 changelevel(mapname);
861 // let initialization continue, shutdown depends on it
865 if(world_already_spawned)
866 error("world already spawned - you may have EXACTLY ONE worldspawn!");
867 world_already_spawned = true;
869 delete_fn = remove_safely; // during spawning, watch what you remove!
871 cvar_changes_init(); // do this very early now so it REALLY matches the server config
873 // default to RACE_RECORD, can be overwritten by gamemodes
874 record_type = RACE_RECORD;
876 // needs to be done so early because of the constants they create
879 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
881 TemporaryDB = db_create();
886 // 1 FLICKER (first variety)
887 lightstyle(1, "mmnmmommommnonmmonqnmmo");
889 // 2 SLOW STRONG PULSE
890 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
892 // 3 CANDLE (first variety)
893 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
896 lightstyle(4, "mamamamamama");
899 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
901 // 6 FLICKER (second variety)
902 lightstyle(6, "nmonqnmomnmomomno");
904 // 7 CANDLE (second variety)
905 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
907 // 8 CANDLE (third variety)
908 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
910 // 9 SLOW STROBE (fourth variety)
911 lightstyle(9, "aaaaaaaazzzzzzzz");
913 // 10 FLUORESCENT FLICKER
914 lightstyle(10, "mmamammmmammamamaaamammma");
916 // 11 SLOW PULSE NOT FADE TO BLACK
917 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
919 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
924 if(autocvar_g_campaign)
927 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
929 Map_MarkAsRecent(mapname);
933 static_init_precache();
936 GameRules_limit_fallbacks();
939 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
940 if(bot_waypoints_for_items == 1)
941 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
942 bot_waypoints_for_items = 0;
944 WaypointSprite_Init();
947 // changing the logic generating it is okay. But:
948 // it HAS to stay <= 64 chars
949 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
950 // strftime(false, "%s") isn't reliable, see strftime_s description
951 matchid = strzone(sprintf("%d.%s.%06d", autocvar_sv_eventlog_files_counter, strftime_s(), random() * 1000000));
953 if(autocvar_sv_eventlog)
954 GameLogInit(); // requires matchid to be set
956 cvar_set("nextmap", "");
960 if(autocvar_g_campaign)
966 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
968 q3compat = BITSET(q3compat, Q3COMPAT_ARENA, _MapInfo_FindArenaFile(mapname, ".arena") != "");
969 q3compat = BITSET(q3compat, Q3COMPAT_DEFI, _MapInfo_FindArenaFile(mapname, ".defi") != "");
971 // quake 3 music support
972 if(world.music || world.noise)
974 // prefer .music over .noise
977 chosen_music = world.music;
979 chosen_music = world.noise;
981 string newstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
982 strcpy(clientstuff, newstuff);
985 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
987 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
991 while((s = fgets(fd)))
993 int l = tokenize_console(s);
998 string trackname = argv(2);
999 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
1000 LOG_INFO(" cdtrack ", trackname);
1001 if (cvar_value_issafe(trackname))
1003 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
1004 strcpy(clientstuff, newstuff);
1007 else if(argv(0) == "fog")
1009 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
1010 LOG_INFO(" \"fog\" \"", s, "\"");
1012 else if(argv(0) == "set")
1014 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
1015 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
1017 else if(argv(0) != "//")
1019 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
1020 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
1031 // set up information replies for clients and server to use
1032 maplist_reply = strzone(getmaplist());
1033 lsmaps_reply = strzone(getlsmaps());
1034 monsterlist_reply = strzone(getmonsterlist());
1035 bool records_available = false;
1036 for(int i = 0; i < 10; ++i)
1038 string s = getrecords(i);
1041 records_reply[i] = strzone(s);
1042 records_available = true;
1045 if (!records_available)
1046 records_reply[0] = "No records available for the current game mode.\n";
1047 ladder_reply = strzone(getladder());
1048 rankings_reply = strzone(getrankings());
1053 PingPLReport_Spawn();
1057 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
1059 // fill sv_curl_serverpackages from .serverpackage files
1060 if (autocvar_sv_curl_serverpackages_auto)
1062 string s = "csprogs-" WATERMARK ".dat";
1063 // remove automatically managed files from the list to prevent duplicates
1064 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
1066 string pkg = argv(i);
1067 if (startsWith(pkg, "csprogs-")) continue;
1068 if (endsWith(pkg, "-serverpackage.txt")) continue;
1069 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
1072 // add automatically managed files to the list
1073 #define X(match) MACRO_BEGIN \
1074 int fd = search_begin(match, true, false); \
1077 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1079 s = cons(s, search_getfilename(fd, i)); \
1084 X("*-serverpackage.txt");
1085 X("*.serverpackage");
1087 cvar_set("sv_curl_serverpackages", s);
1090 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1091 modname = "Xonotic";
1092 // physics/balance/config changes that count as mod
1093 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1094 modname = cvar_string("g_mod_physics");
1095 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1096 modname = cvar_string("g_mod_balance");
1097 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1098 modname = cvar_string("g_mod_config");
1099 // extra mutators that deserve to count as mod
1100 MUTATOR_CALLHOOK(SetModname, modname);
1101 modname = M_ARGV(0, string);
1103 // save it for later
1104 modname = strzone(modname);
1106 WinningConditionHelper(this); // set worldstatus
1108 round_handler_Activate(!warmup_stage);
1111 if (autocvar_rjz_count_shards && warmup_stage) {
1113 send_TotalShardsAll();
1116 if (autocvar_sv_autopause && server_is_dedicated && !wantrestart)
1117 // INITPRIO_LAST is to soon: bots either didn't join yet or didn't leave yet, see: bot_fixcount()
1118 defer(this, 5, Pause_TryPause_Dedicated);
1120 world_initialized = 1;
1121 __spawnfunc_spawn_all();
1126 //makestatic (this); // Who the f___ did that?
1130 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance, bool frompos)
1132 float m = e.dphitcontentsmask;
1133 e.dphitcontentsmask = goodcontents | badcontents;
1135 vector org = boundmin;
1136 vector delta = boundmax - boundmin;
1140 int j; // used after the loop
1141 for(j = 0; j < attempts; ++j)
1143 start.x = org.x + random() * delta.x;
1144 start.y = org.y + random() * delta.y;
1145 start.z = org.z + random() * delta.z;
1147 // rule 1: start inside world bounds, and outside
1148 // solid, and don't start from somewhere where you can
1149 // fall down to evil
1150 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1151 if (trace_fraction >= 1)
1153 if (trace_startsolid)
1155 if (trace_dphitcontents & badcontents)
1157 if (trace_dphitq3surfaceflags & badsurfaceflags)
1160 // rule 2: if we are too high, lower the point
1161 if (trace_fraction * delta.z > maxaboveground)
1162 start = trace_endpos + '0 0 1' * maxaboveground;
1163 vector enddown = trace_endpos;
1165 // rule 3: make sure we aren't outside the map. This only works
1166 // for somewhat well formed maps. A good rule of thumb is that
1167 // the map should have a convex outside hull.
1168 // these can be traceLINES as we already verified the starting box
1169 vector mstart = start + 0.5 * (e.mins + e.maxs);
1170 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1171 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1173 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1174 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1176 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1177 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1179 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1180 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1182 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1183 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1186 // rule 4: we must "see" some spawnpoint or item
1190 if((traceline(mstart, e.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1195 IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1197 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1206 int items_checked = 0;
1207 IL_EACH(g_items, checkpvs(mstart, it),
1209 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1216 if(items_checked >= attempts)
1224 // find a random vector to "look at"
1225 end.x = org.x + random() * delta.x;
1226 end.y = org.y + random() * delta.y;
1227 end.z = org.z + random() * delta.z;
1228 end = start + normalize(end - start) * vlen(delta);
1230 // rule 4: start TO end must not be too short
1231 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1232 if(trace_startsolid)
1234 if(trace_fraction < minviewdistance / vlen(delta))
1237 // rule 5: don't want to look at sky
1238 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1241 // rule 6: we must not end up in trigger_hurt
1242 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1248 e.dphitcontentsmask = m;
1252 setorigin(e, start);
1253 e.angles = vectoangles(end - start);
1254 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1260 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1262 return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance, false);
1266 ===============================================================================
1270 ===============================================================================
1273 void DumpStats(float final)
1282 to_console = autocvar_sv_logscores_console;
1283 to_eventlog = autocvar_sv_eventlog;
1284 to_file = autocvar_sv_logscores_file;
1288 to_console = true; // always print printstats replies
1289 to_eventlog = false; // but never print them to the event log
1293 if(autocvar_sv_eventlog_console)
1294 to_console = false; // otherwise we get the output twice
1300 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1310 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1314 fputs(file, strcat(s, "\n"));
1317 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1323 fputs(file, strcat(s, "\n"));
1325 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1326 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1327 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1328 if(IS_PLAYER(it) || INGAME_JOINED(it))
1329 s = strcat(s, ftos(it.team), ":");
1331 s = strcat(s, "spectator:");
1334 LOG_HELP(s, playername(it.netname, it.team, false));
1336 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1338 fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1343 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1349 fputs(file, strcat(s, "\n"));
1351 for(i = 1; i < 16; ++i)
1353 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1354 s = strcat(s, ":", ftos(i));
1360 fputs(file, strcat(s, "\n"));
1367 GameLogEcho(":end");
1370 fputs(file, ":end\n");
1376 go to the next level for deathmatch
1377 only called if a time or frag limit has expired
1381 cvar_set("_endmatch", "0");
1382 game_stopped = true;
1383 intermission_running = true; // game over
1385 // enforce a wait time before allowing changelevel
1386 if(player_count > 0)
1387 intermission_exittime = time + autocvar_sv_mapchange_delay;
1389 intermission_exittime = -1;
1392 WriteByte (MSG_ALL, SVC_CDTRACK);
1393 WriteByte (MSG_ALL, 3);
1394 WriteByte (MSG_ALL, 3);
1395 // done in FixIntermission
1398 //pos = FindIntermission ();
1400 sound(NULL, CH_INFO, SND_ENDMATCH, VOL_BASE, ATTN_NONE);
1407 PlayerStats_GameReport(true);
1408 WeaponStats_Shutdown();
1410 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1412 // send winner notification
1414 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, APP_TEAM_NUM(WinningConditionHelper_winnerteam, ANNCE_TEAM_WINS));
1417 if(autocvar_sv_eventlog)
1418 GameLogEcho(":gameover");
1422 int winner_team = 0;
1423 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1424 FixIntermissionClient(it);
1427 if (teamplay && !winner_team)
1429 winner_team = it.team;
1430 bprint(Team_ColorCode(winner_team), Team_ColorName_Upper(winner_team), "^7 team wins the match\n");
1432 bprint(playername(it.netname, it.team, false), " ^7wins\n");
1436 target_music_kill();
1439 if(autocvar_sv_jingle_end) {
1440 int jingles_len = 0;
1444 FOREACH_WORD(autocvar_sv_jingle_end_list, it,
1446 jingles[jingles_len] = it;
1451 int song_to_play = rint(random() * (jingles_len - 1));
1453 FOREACH_CLIENT(IS_REAL_CLIENT(it),
1455 stuffcmd(it, "cd stop\n");
1456 _sound(it, CH_INFO, strcat("jingle/", jingles[song_to_play], ".ogg"), VOL_BASE * autocvar_sv_jingle_end_volume, ATTEN_NORM);
1461 if(autocvar_g_campaign)
1462 CampaignPreIntermission();
1464 MUTATOR_CALLHOOK(MatchEnd);
1466 localcmd("\nsv_hook_gameend\n");
1470 int InitiateSuddenDeath()
1472 // Check first whether normal overtimes could be added before initiating suddendeath mode
1473 // - for this timelimit_overtime needs to be >0 of course
1474 // - also check the winning condition calculated in the previous frame and only add normal overtime
1475 // again, if at the point at which timelimit would be extended again, still no winner was found
1476 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1477 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1478 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1480 return 1; // need to call InitiateOvertime later
1484 if(!checkrules_suddendeathend)
1486 if(autocvar_g_campaign)
1488 checkrules_suddendeathend = time; // no suddendeath in campaign
1492 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1495 if(g_race && !g_race_qualifying)
1496 race_StartCompleting();
1502 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1504 ++checkrules_overtimesadded;
1505 overtimes = checkrules_overtimesadded;
1506 //add one more overtime by simply extending the timelimit
1507 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1508 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1510 sound(NULL, CH_INFO, SND_OVERTIME, VOL_BASE, ATTN_NONE);
1511 if(checkrules_overtimesadded == 1) {
1512 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_OVERTIME);
1513 overtime_starttime = time;
1517 float GetWinningCode(float fraglimitreached, float equality)
1519 if(autocvar_g_campaign == 1)
1521 if(fraglimitreached)
1530 if(fraglimitreached)
1531 return WINNING_STARTSUDDENDEATHOVERTIME;
1533 return WINNING_NEVER;
1537 if(fraglimitreached)
1545 // set the .winning flag for exactly those players with a given field value
1546 void SetWinners(.float field, float value)
1548 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = (it.(field) == value); });
1551 // set the .winning flag for those players with a given field value
1552 void AddWinners(.float field, float value)
1554 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1555 if(it.(field) == value)
1560 // clear the .winning flags
1563 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = 0; });
1566 void AnnounceNewLeader()
1568 // Don't announce if in warmup or just started
1569 if(warmup_stage || time - game_starttime < 1) return;
1572 if (WinningConditionHelper_equality)
1573 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_TEAM_LEADS_TIED);
1575 FOREACH_CLIENT(IS_PLAYER(it), {
1576 if(it.team == WinningConditionHelper_winnerteam)
1577 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_LEADS_TEAM);
1579 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_LEADS_ENEMY);
1581 Send_Notification(NOTIF_ALL_SPEC, NULL, MSG_ANNCE, APP_TEAM_NUM(WinningConditionHelper_winnerteam, ANNCE_TEAM_LEADS));
1583 if (WinningConditionHelper_equality)
1585 Send_Notification(NOTIF_ONE, WinningConditionHelper_equality_one, MSG_ANNCE, ANNCE_LEAD_TIED);
1586 Send_Notification(NOTIF_ONE, WinningConditionHelper_equality_two, MSG_ANNCE, ANNCE_LEAD_TIED);
1590 Send_Notification(NOTIF_ONE, WinningConditionHelper_winner, MSG_ANNCE, ANNCE_LEAD_GAINED);
1591 Send_Notification(NOTIF_ONE, WinningConditionHelper_second, MSG_ANNCE, ANNCE_LEAD_LOST);
1596 void AnnounceScores(float tm)
1598 WinningConditionHelper(NULL);
1599 if (Score_NewLeader()) {
1600 AnnounceNewLeader();
1602 FOREACH_CLIENT(IS_PLAYER(it), {
1604 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_SCORES_TEAM);
1606 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_SCORES_ENEMY);
1608 Send_Notification(NOTIF_ALL_SPEC, NULL, MSG_ANNCE, APP_TEAM_NUM(tm, ANNCE_TEAM_SCORES));
1612 float WinningCondition_Scores(float limit, float leadlimit)
1614 // TODO make everything use THIS winning condition (except LMS)
1615 WinningConditionHelper(NULL);
1619 for (int i = 1; i < 5; ++i)
1621 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1622 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1627 if(WinningConditionHelper_winner)
1628 WinningConditionHelper_winner.winning = 1;
1629 if(WinningConditionHelper_winnerteam >= 0)
1630 SetWinners(team, WinningConditionHelper_winnerteam);
1632 if(WinningConditionHelper_lowerisbetter)
1634 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1635 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1639 if(WinningConditionHelper_zeroisworst)
1640 leadlimit = 0; // not supported in this mode
1642 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1644 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1650 fragsleft = FLOAT_MAX;
1651 float leadingfragsleft = FLOAT_MAX;
1653 fragsleft = limit - WinningConditionHelper_topscore;
1655 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1657 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1658 fragsleft = max(fragsleft, leadingfragsleft);
1660 fragsleft = min(fragsleft, leadingfragsleft);
1663 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1666 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1667 else if (fragsleft == 2)
1668 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1669 else if (fragsleft == 3)
1670 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1672 fragsleft_last = fragsleft;
1676 // z411 - lead announcer
1677 if(MUTATOR_CALLHOOK(Scores_AnnounceLeads)) {
1678 if (Score_NewLeader())
1679 AnnounceNewLeader();
1682 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1683 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1686 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1687 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1688 limit_reached = (fraglimit_reached && leadlimit_reached);
1690 limit_reached = (fraglimit_reached || leadlimit_reached);
1692 return GetWinningCode(
1693 WinningConditionHelper_topscore && limit_reached,
1694 WinningConditionHelper_equality
1698 float WinningCondition_RanOutOfSpawns()
1700 if(have_team_spawns <= 0)
1703 if(!autocvar_g_spawn_useallspawns)
1706 if(!some_spawn_has_been_used)
1709 for (int i = 1; i < 5; ++i)
1711 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1714 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1716 if (Team_IsValidTeam(it.team))
1718 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1722 IL_EACH(g_spawnpoints, true,
1724 if (Team_IsValidTeam(it.team))
1726 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1731 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1732 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1733 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1734 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1735 if(team1_score + team2_score + team3_score + team4_score == 0)
1737 checkrules_equality = true;
1740 else if(team1_score + team2_score + team3_score + team4_score == 1)
1745 else if(team2_score)
1747 else if(team3_score)
1749 else // if(team4_score)
1751 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1752 for(i = 0; i < MAX_TEAMSCORE; ++i)
1754 for (int j = 1; j <= NUM_TEAMS; ++j)
1760 if (!TeamBalance_IsTeamAllowed(balance, j))
1764 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1768 AddWinners(team, t);
1779 Exit deathmatch games upon conditions
1782 void CheckRules_World()
1789 if (intermission_running) // someone else quit the game already
1791 if(player_count == 0) // Nobody there? Then let's go to the next map
1793 // this will actually check the player count in the next frame
1794 // again, but this shouldn't hurt
1798 // z411 don't check rules if we're in a timeout
1799 if (game_timeout) return;
1801 float timelimit = autocvar_timelimit * 60;
1802 float fraglimit = autocvar_fraglimit;
1803 float leadlimit = autocvar_leadlimit;
1804 if (leadlimit < 0) leadlimit = 0;
1806 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1809 timelimit = 0; // timelimit is not made for warmup
1811 fraglimit = 0; // no fraglimit for now
1812 leadlimit = 0; // no leadlimit for now
1815 if (autocvar__endmatch || timelimit < 0)
1823 timelimit += game_starttime;
1825 int overtimes_prev = overtimes;
1826 int wantovertime = 0;
1828 if(checkrules_suddendeathend)
1830 if(!checkrules_suddendeathwarning)
1832 checkrules_suddendeathwarning = true;
1833 if(g_race && !g_race_qualifying)
1834 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1836 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1837 checkrules_overtimesadded = 1;
1838 sound(NULL, CH_INFO, SND_OVERTIME, VOL_BASE, ATTN_NONE);
1839 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_OVERTIME);
1844 if (timelimit && time >= timelimit)
1846 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1849 float playerswithlaps;
1851 totalplayers = playerswithlaps = readyplayers = 0;
1852 FOREACH_CLIENT(IS_PLAYER(it), {
1854 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1860 // at least 2 of the players have completed a lap: start the RACE
1861 // otherwise, the players should end the qualifying on their own
1862 if(readyplayers || playerswithlaps >= 2)
1864 checkrules_suddendeathend = 0;
1865 ReadyRestart(true); // go to race
1869 wantovertime |= InitiateSuddenDeath();
1872 wantovertime |= InitiateSuddenDeath();
1876 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1882 int checkrules_status = WinningCondition_RanOutOfSpawns();
1883 if(checkrules_status == WINNING_YES)
1884 bprint("Hey! Someone ran out of spawns!\n");
1885 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1886 checkrules_status = M_ARGV(0, float);
1888 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1890 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1892 checkrules_status = WINNING_NEVER;
1893 checkrules_overtimesadded = -1;
1894 wantovertime |= InitiateSuddenDeath();
1897 if(checkrules_status == WINNING_NEVER)
1898 // equality cases! Nobody wins if the overtime ends in a draw.
1903 if(checkrules_status == WINNING_NEVER)
1906 checkrules_status = WINNING_YES;
1909 if(checkrules_suddendeathend)
1910 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1911 checkrules_status = WINNING_YES;
1913 if(checkrules_status == WINNING_YES)
1915 if (overtimes == -1 && overtimes != overtimes_prev)
1917 // if suddendeathend overtime has just begun, revert it
1918 checkrules_suddendeathend = 0;
1919 overtimes = overtimes_prev;
1921 //print("WINNING\n");
1926 float want_weapon(entity weaponinfo, float allguns)
1929 bool allow_mutatorblocked = false;
1931 if(!weaponinfo.m_id)
1934 bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1935 d = M_ARGV(1, float);
1936 allguns = M_ARGV(2, bool);
1937 allow_mutatorblocked = M_ARGV(3, bool);
1940 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1941 else if(!mutator_returnvalue)
1942 d = !(!weaponinfo.weaponstart);
1944 if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1947 float t = weaponinfo.weaponstartoverride;
1949 //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1954 // 4: is set by default?
1963 /// Weapons the player normally starts with outside weapon arena.
1964 WepSet weapons_start()
1966 WepSet ret = '0 0 0';
1967 FOREACH(Weapons, it != WEP_Null, {
1968 int w = want_weapon(it, false);
1975 WepSet weapons_all()
1977 WepSet ret = '0 0 0';
1978 FOREACH(Weapons, it != WEP_Null, {
1979 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1985 WepSet weapons_devall()
1987 WepSet ret = '0 0 0';
1988 FOREACH(Weapons, it != WEP_Null,
1995 WepSet weapons_most()
1997 WepSet ret = '0 0 0';
1998 FOREACH(Weapons, it != WEP_Null, {
1999 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
2005 void weaponarena_available_all_update(entity this)
2007 if (weaponsInMapAll)
2009 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
2013 // if no weapons are available on the map, just fall back to all weapons arena
2014 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
2018 void weaponarena_available_devall_update(entity this)
2020 if (weaponsInMapAll)
2022 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
2026 // if no weapons are available on the map, just fall back to devall weapons arena
2027 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
2031 void weaponarena_available_most_update(entity this)
2033 if (weaponsInMapAll)
2035 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
2039 // if no weapons are available on the map, just fall back to most weapons arena
2040 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
2044 void readplayerstartcvars()
2046 // initialize starting values for players
2047 start_weapons = '0 0 0';
2048 start_weapons_default = '0 0 0';
2049 start_weapons_defaultmask = '0 0 0';
2051 start_ammo_shells = 0;
2052 start_ammo_nails = 0;
2053 start_ammo_rockets = 0;
2054 start_ammo_cells = 0;
2055 start_ammo_plasma = 0;
2056 if (random_start_ammo == NULL)
2058 random_start_ammo = new_pure(random_start_ammo);
2060 start_health = cvar("g_balance_health_start");
2061 start_armorvalue = cvar("g_balance_armor_start");
2064 g_weaponarena_weapons = '0 0 0';
2066 string s = cvar_string("g_weaponarena");
2068 MUTATOR_CALLHOOK(SetWeaponArena, s);
2069 s = M_ARGV(0, string);
2071 if (s == "0" || s == "")
2075 else if (s == "off")
2077 // forcibly turn off weaponarena
2079 else if (s == "all" || s == "1")
2082 g_weaponarena_list = "All Weapons Arena";
2083 g_weaponarena_weapons = weapons_all();
2085 else if (s == "devall")
2088 g_weaponarena_list = "Dev All Weapons Arena";
2089 g_weaponarena_weapons = weapons_devall();
2091 else if (s == "most")
2094 g_weaponarena_list = "Most Weapons Arena";
2095 g_weaponarena_weapons = weapons_most();
2097 else if (s == "all_available")
2100 g_weaponarena_list = "All Available Weapons Arena";
2102 // this needs to run after weaponsInMapAll is initialized
2103 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
2105 else if (s == "devall_available")
2108 g_weaponarena_list = "Dev All Available Weapons Arena";
2110 // this needs to run after weaponsInMapAll is initialized
2111 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
2113 else if (s == "most_available")
2116 g_weaponarena_list = "Most Available Weapons Arena";
2118 // this needs to run after weaponsInMapAll is initialized
2119 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
2121 else if (s == "none")
2124 g_weaponarena_list = "No Weapons Arena";
2129 float t = tokenize_console(s);
2130 g_weaponarena_list = "";
2131 for (int j = 0; j < t; ++j)
2134 Weapon wep = Weapon_from_name(s);
2137 g_weaponarena_weapons |= (wep.m_wepset);
2138 g_weaponarena_list = strcat(g_weaponarena_list, wep.netname, " & ");
2141 if (g_weaponarena_list != "") // remove trailing " & "
2142 g_weaponarena_list = substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3);
2143 else // no valid weapon found
2144 g_weaponarena_list = "No Weapons Arena";
2149 g_weapon_stay = 0; // incompatible
2150 start_weapons = g_weaponarena_weapons;
2151 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
2152 g_weaponarena_list = strzone(g_weaponarena_list);
2156 FOREACH(Weapons, it != WEP_Null, {
2157 int w = want_weapon(it, false);
2158 WepSet s = it.m_wepset;
2162 start_weapons_default |= s;
2164 start_weapons_defaultmask |= s;
2168 if(cvar("g_balance_superweapons_time") < 0)
2169 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2171 if(!cvar("g_use_ammunition"))
2172 start_items |= IT_UNLIMITED_AMMO;
2174 if(start_items & IT_UNLIMITED_AMMO)
2176 start_ammo_shells = 999;
2177 start_ammo_nails = 999;
2178 start_ammo_rockets = 999;
2179 start_ammo_cells = 999;
2180 start_ammo_plasma = 999;
2181 start_ammo_fuel = 999;
2185 start_ammo_shells = cvar("g_start_ammo_shells");
2186 start_ammo_nails = cvar("g_start_ammo_nails");
2187 start_ammo_rockets = cvar("g_start_ammo_rockets");
2188 start_ammo_cells = cvar("g_start_ammo_cells");
2189 start_ammo_plasma = cvar("g_start_ammo_plasma");
2190 start_ammo_fuel = cvar("g_start_ammo_fuel");
2191 random_start_weapons_count = cvar("g_random_start_weapons_count");
2192 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2193 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2194 SetResource(random_start_ammo, RES_ROCKETS, cvar("g_random_start_rockets"));
2195 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2196 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2199 warmup_start_ammo_shells = start_ammo_shells;
2200 warmup_start_ammo_nails = start_ammo_nails;
2201 warmup_start_ammo_rockets = start_ammo_rockets;
2202 warmup_start_ammo_cells = start_ammo_cells;
2203 warmup_start_ammo_plasma = start_ammo_plasma;
2204 warmup_start_ammo_fuel = start_ammo_fuel;
2205 warmup_start_health = start_health;
2206 warmup_start_armorvalue = start_armorvalue;
2207 warmup_start_weapons = start_weapons;
2208 warmup_start_weapons_default = start_weapons_default;
2209 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2213 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2214 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2215 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2216 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2217 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2218 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2219 warmup_start_health = cvar("g_warmup_start_health");
2220 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2221 warmup_start_weapons = '0 0 0';
2222 warmup_start_weapons_default = '0 0 0';
2223 warmup_start_weapons_defaultmask = '0 0 0';
2224 FOREACH(Weapons, it != WEP_Null, {
2225 int w = want_weapon(it, autocvar_g_warmup_allguns);
2226 WepSet s = it.m_wepset;
2228 warmup_start_weapons |= s;
2230 warmup_start_weapons_default |= s;
2232 warmup_start_weapons_defaultmask |= s;
2236 if (autocvar_g_jetpack)
2237 start_items |= ITEM_Jetpack.m_itemid;
2239 MUTATOR_CALLHOOK(SetStartItems);
2241 if (start_items & ITEM_Jetpack.m_itemid)
2243 start_items |= ITEM_JetpackRegen.m_itemid;
2244 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2245 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2248 start_ammo_shells = max(0, start_ammo_shells);
2249 start_ammo_nails = max(0, start_ammo_nails);
2250 start_ammo_rockets = max(0, start_ammo_rockets);
2251 start_ammo_cells = max(0, start_ammo_cells);
2252 start_ammo_plasma = max(0, start_ammo_plasma);
2253 start_ammo_fuel = max(0, start_ammo_fuel);
2254 SetResource(random_start_ammo, RES_SHELLS, max(0, GetResource(random_start_ammo, RES_SHELLS)));
2255 SetResource(random_start_ammo, RES_BULLETS, max(0, GetResource(random_start_ammo, RES_BULLETS)));
2256 SetResource(random_start_ammo, RES_ROCKETS, max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2257 SetResource(random_start_ammo, RES_CELLS, max(0, GetResource(random_start_ammo, RES_CELLS)));
2258 SetResource(random_start_ammo, RES_PLASMA, max(0, GetResource(random_start_ammo, RES_PLASMA)));
2260 warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2261 warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2262 warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2263 warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2264 warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2265 warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2268 void readlevelcvars()
2270 serverflags &= ~SERVERFLAG_ALLOW_FULLBRIGHT;
2271 if(cvar("sv_allow_fullbright"))
2272 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2273 if(cvar("sv_forbid_pickuptimer"))
2274 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2276 serverflags &= ~SERVERFLAG_FORBID_PICKUPTIMER;
2277 if(cvar("sv_forbid_pickuptimer"))
2278 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2280 sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2282 if(cvar("g_campaign"))
2283 warmup_stage = 0; // no warmup during campaign
2286 warmup_stage = autocvar_g_warmup;
2287 if (warmup_stage < 0 || warmup_stage > 1)
2288 warmup_limit = -1; // don't start until there's enough players
2289 else if (warmup_stage == 1)
2291 // this code is duplicated in ReadyCount()
2292 warmup_limit = cvar("g_warmup_limit");
2293 if(warmup_limit == 0)
2294 warmup_limit = autocvar_timelimit * 60;
2298 g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2299 g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2300 g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2301 g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
2302 g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
2303 g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
2304 g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2305 g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2306 g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2307 g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2308 g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
2309 g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
2310 g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
2311 g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2313 g_pickup_shells = cvar("g_pickup_shells");
2314 g_pickup_shells_max = cvar("g_pickup_shells_max");
2315 g_pickup_nails = cvar("g_pickup_nails");
2316 g_pickup_nails_max = cvar("g_pickup_nails_max");
2317 g_pickup_rockets = cvar("g_pickup_rockets");
2318 g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2319 g_pickup_cells = cvar("g_pickup_cells");
2320 g_pickup_cells_max = cvar("g_pickup_cells_max");
2321 g_pickup_plasma = cvar("g_pickup_plasma");
2322 g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2323 g_pickup_fuel = cvar("g_pickup_fuel");
2324 g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2325 g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2326 g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2327 g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2328 g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2329 g_pickup_armormedium = cvar("g_pickup_armormedium");
2330 g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2331 g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2332 g_pickup_armorbig = cvar("g_pickup_armorbig");
2333 g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2334 g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2335 g_pickup_armormega = cvar("g_pickup_armormega");
2336 g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2337 g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2338 g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2339 g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2340 g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2341 g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2342 g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2343 g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2344 g_pickup_healthbig = cvar("g_pickup_healthbig");
2345 g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2346 g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2347 g_pickup_healthmega = cvar("g_pickup_healthmega");
2348 g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2349 g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2351 g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2352 g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2354 g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2356 g_weapon_stay = cvar("g_weapon_stay");
2358 MUTATOR_CALLHOOK(ReadLevelCvars);
2360 if (!warmup_stage && !autocvar_g_campaign)
2361 game_starttime = time + cvar("g_start_delay");
2363 FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2365 readplayerstartcvars();
2368 void InitializeEntity(entity e, void(entity this) func, int order)
2372 if (!e || e.initialize_entity)
2374 // make a proxy initializer entity
2376 e = new(initialize_entity);
2380 e.initialize_entity = func;
2381 e.initialize_entity_order = order;
2383 cur = initialize_entity_first;
2387 if (!cur || cur.initialize_entity_order > order)
2389 // insert between prev and cur
2391 prev.initialize_entity_next = e;
2393 initialize_entity_first = e;
2394 e.initialize_entity_next = cur;
2398 cur = cur.initialize_entity_next;
2401 void InitializeEntitiesRun()
2403 entity startoflist = initialize_entity_first;
2404 initialize_entity_first = NULL;
2405 delete_fn = remove_except_protected;
2406 for (entity e = startoflist; e; e = e.initialize_entity_next)
2408 e.remove_except_protected_forbidden = 1;
2410 for (entity e = startoflist; e; )
2412 e.remove_except_protected_forbidden = 0;
2413 e.initialize_entity_order = 0;
2414 entity next = e.initialize_entity_next;
2415 e.initialize_entity_next = NULL;
2416 var void(entity this) func = e.initialize_entity;
2417 e.initialize_entity = func_null;
2418 if (e.classname == "initialize_entity")
2420 entity wrappee = e.enemy;
2424 //dprint("Delayed initialization: ", e.classname, "\n");
2432 backtrace(strcat("Null function in: ", e.classname, "\n"));
2436 delete_fn = remove_unsafely;
2439 // deferred dropping
2440 // ported from VM_SV_droptofloor TODO: make a common function for the client-side?
2441 void DropToFloor_Handler(entity this)
2443 if(!this || wasfreed(this))
2445 // no modifying free entities
2449 vector end = this.origin;
2450 if (autocvar_sv_mapformat_is_quake3)
2452 else if (autocvar_sv_mapformat_is_quake2)
2455 end.z -= 256; // Quake, QuakeWorld
2457 // NOTE: SV_NudgeOutOfSolid is used in the engine here
2458 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2460 _Movetype_UnstickEntity(this);
2461 move_out_of_solid(this);
2464 tracebox(this.origin, this.mins, this.maxs, end, MOVE_NORMAL, this);
2466 if(trace_startsolid && autocvar_sv_gameplayfix_droptofloorstartsolid)
2469 offset = 0.5 * (this.mins + this.maxs);
2470 offset.z = this.mins.z;
2471 org = this.origin + offset;
2472 traceline(org, end, MOVE_NORMAL, this);
2473 trace_endpos = trace_endpos - offset;
2474 if(trace_startsolid)
2476 LOG_DEBUGF("DropToFloor_Handler: %v could not fix badly placed entity", this.origin);
2477 _Movetype_LinkEdict(this, false);
2479 this.groundentity = NULL;
2481 else if(trace_fraction < 1)
2483 LOG_DEBUGF("DropToFloor_Handler: %v fixed badly placed entity", this.origin);
2484 setorigin(this, trace_endpos);
2485 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2487 _Movetype_UnstickEntity(this);
2488 move_out_of_solid(this);
2491 this.groundentity = trace_ent;
2492 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2493 this.move_suspendedinair = true;
2498 if(!trace_allsolid && trace_fraction < 1)
2500 setorigin(this, trace_endpos);
2502 this.groundentity = trace_ent;
2503 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2504 this.move_suspendedinair = true;
2508 // if we can't get the entity out of solid, mark it as on ground so physics doesn't attempt to drop it
2509 // hacky workaround for #2774
2513 this.dropped_origin = this.origin;
2516 void droptofloor(entity this)
2518 InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2521 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2522 void RunThink(entity this, float dt)
2524 // don't let things stay in the past.
2525 // it is possible to start that way by a trigger with a local time.
2526 if(this.nextthink <= 0 || this.nextthink > time + dt)
2529 float oldtime = time; // do we need to save this?
2531 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2533 time = max(oldtime, this.nextthink);
2537 getthink(this)(this);
2538 // mods often set nextthink to time to cause a think every frame,
2539 // we don't want to loop in that case, so exit if the new nextthink is
2540 // <= the time the qc was told, also exit if it is past the end of the
2542 if(this.nextthink <= time || this.nextthink > oldtime + dt || !autocvar_sv_gameplayfix_multiplethinksperframe)
2549 bool autocvar_sv_freezenonclients;
2550 void Physics_Frame()
2552 if(autocvar_sv_freezenonclients || game_timeout)
2555 IL_EACH(g_moveables, true,
2557 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2560 //set_movetype(it, it.move_movetype);
2561 // inline the set_movetype function, since this is called a lot
2562 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2564 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2565 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2567 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2569 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2570 continue; // these movetypes have no regular think function
2571 // handle thinking here
2572 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + PHYS_INPUT_TIMELENGTH)
2573 RunThink(it, PHYS_INPUT_TIMELENGTH);
2577 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2580 // make a second pass to see if any ents spawned this frame and make
2581 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2582 // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2583 IL_EACH(g_moveables, it.move_qcphysics,
2585 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2587 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2591 void systems_update();
2594 anticheat_endframe();
2598 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2599 entity e = IS_SPEC(it) ? it.enemy : it;
2600 if (e.typehitsound) {
2601 STAT(TYPEHIT_TIME, it) = time;
2602 } else if (e.killsound) {
2603 STAT(KILL_TIME, it) = time;
2604 } else if (e.hitsound_damage_dealt) {
2605 STAT(HIT_TIME, it) = time;
2606 // NOTE: this is not accurate as client code doesn't need so much accuracy for its purposes
2607 STAT(HITSOUND_DAMAGE_DEALT_TOTAL, it) += ceil(e.hitsound_damage_dealt);
2610 // add 1 frametime because after this, engine SV_Physics
2611 // increases time by a frametime and then networks the frame
2612 // add another frametime because client shows everything with
2613 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2615 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2616 FOREACH_CLIENT(true, {
2617 it.typehitsound = false;
2618 it.hitsound_damage_dealt = 0;
2619 it.killsound = false;
2620 antilag_record(it, CS(it), altime);
2622 IL_EACH(g_monsters, true,
2624 antilag_record(it, it, altime);
2626 IL_EACH(g_projectiles, it.classname == "nade",
2628 antilag_record(it, it, altime);
2637 * returns true if redirecting
2639 float redirection_timeout;
2640 float redirection_nextthink;
2641 float RedirectionThink()
2643 float clients_found;
2645 if(redirection_target == "")
2648 if(!redirection_timeout)
2650 cvar_set("sv_public", "-2");
2651 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2652 if(redirection_target == "self")
2653 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2655 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2658 if(time < redirection_nextthink)
2661 redirection_nextthink = time + 1;
2664 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2666 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2667 if(redirection_target == "self")
2668 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2670 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2674 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2676 if(time > redirection_timeout || clients_found == 0)
2677 localcmd("\nwait; wait; wait; quit\n");
2684 // Loaded from a save game
2685 // some things then break, so let's work around them...
2687 // Progs DB (capture records)
2688 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2692 MapInfo_Enumerate();
2693 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2696 TargetMusic_RestoreGame();
2703 if(world_initialized > 0)
2705 world_initialized = 0;
2707 // if a timeout is active, reset the slowmo value to normal
2708 if(timeout_status == TIMEOUT_ACTIVE)
2709 cvar_set("slowmo", ftos(orig_slowmo));
2711 LOG_TRACE("Saving persistent data...");
2714 // playerstats with unfinished match
2715 PlayerStats_GameReport(false);
2717 if(!cheatcount_total)
2719 if(autocvar_sv_db_saveasdump)
2720 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2722 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2724 if(autocvar_developer > 0)
2726 if(autocvar_sv_db_saveasdump)
2727 db_dump(TemporaryDB, "server-temp.db");
2729 db_save(TemporaryDB, "server-temp.db");
2731 CheatShutdown(); // must be after cheatcount check
2732 db_close(ServerProgsDB);
2733 db_close(TemporaryDB);
2734 LOG_TRACE("Saving persistent data... done!");
2735 // tell the bot system the game is ending now
2738 WeaponStats_Shutdown();
2741 strfree(sv_termsofservice_url_escaped);
2743 else if(world_initialized == 0)
2745 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2749 __init_dedicated_server_shutdown();