3 #include "anticheat.qh"
9 #include "command/common.qh"
10 #include "command/getreplies.qh"
11 #include "command/sv_cmd.qh"
12 #include "command/vote.qh"
14 #include <server/gamelog.qh>
15 #include <server/damage.qh>
17 #include "mapvoting.qh"
18 #include <server/mutators/_mod.qh>
21 #include "scores_rules.qh"
22 #include "spawnpoints.qh"
23 #include "teamplay.qh"
24 #include "weapons/weaponstats.qh"
25 #include <server/weapons/common.qh>
26 #include "../common/constants.qh"
27 #include <common/net_linked.qh>
28 #include "../common/deathtypes/all.qh"
29 #include <common/gamemodes/_mod.qh>
30 #include "../common/gamemodes/sv_rules.qh"
31 #include "../common/mapinfo.qh"
32 #include "../common/monsters/_mod.qh"
33 #include "../common/monsters/sv_monsters.qh"
34 #include "../common/vehicles/all.qh"
35 #include "../common/notifications/all.qh"
36 #include "../common/physics/player.qh"
37 #include "../common/playerstats.qh"
38 #include "../common/stats.qh"
39 #include "../common/teams.qh"
40 #include <common/mapobjects/triggers.qh>
41 #include "../common/mapobjects/trigger/secret.qh"
42 #include "../common/mapobjects/target/music.qh"
43 #include "../common/util.qh"
44 #include "../common/items/_mod.qh"
45 #include <common/weapons/_all.qh>
46 #include "../common/state.qh"
48 const float LATENCY_THINKRATE = 10;
53 void PingPLReport_Think(entity this)
58 delta = 3 / maxclients;
59 if(delta < sys_frametime)
61 this.nextthink = time + delta;
63 e = edict_num(this.cnt + 1);
64 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
66 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
67 WriteByte(MSG_BROADCAST, this.cnt);
68 WriteShort(MSG_BROADCAST, bound(1, CS(e).ping, 65535));
69 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
70 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
72 // record latency times for clients throughout the match so we can report it to playerstats
73 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
75 CS(e).latency_sum += CS(e).ping;
76 CS(e).latency_cnt += 1;
77 CS(e).latency_time = time;
78 //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
83 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
84 WriteByte(MSG_BROADCAST, this.cnt);
85 WriteShort(MSG_BROADCAST, 0);
86 WriteByte(MSG_BROADCAST, 0);
87 WriteByte(MSG_BROADCAST, 0);
89 this.cnt = (this.cnt + 1) % maxclients;
91 void PingPLReport_Spawn()
93 pingplreport = new_pure(pingplreport);
94 setthink(pingplreport, PingPLReport_Think);
95 pingplreport.nextthink = time;
98 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
99 string redirection_target;
100 float world_initialized;
102 void SetDefaultAlpha()
104 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
106 default_player_alpha = autocvar_g_player_alpha;
107 if(default_player_alpha == 0)
108 default_player_alpha = 1;
109 default_weapon_alpha = default_player_alpha;
113 void GotoFirstMap(entity this)
116 if(autocvar__sv_init)
118 // cvar_set("_sv_init", "0");
119 // we do NOT set this to 0 any more, so someone "accidentally" changing
120 // to this "init" map on a dedicated server will cause no permanent
122 if(autocvar_g_maplist_shuffle)
124 n = tokenizebyseparator(autocvar_g_maplist, " ");
125 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
128 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
130 if(!DoNextMapOverride(1))
138 this.nextthink = time;
142 this.nextthink = time + 1;
143 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
147 void cvar_changes_init()
151 float n, i, adding, pureadding;
153 strfree(cvar_changes);
154 strfree(cvar_purechanges);
155 cvar_purechanges_count = 0;
158 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
164 for(i = 0; i < n; ++i)
166 k = bufstr_get(h, i);
168 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
169 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
170 #define BADCVAR(p) if(k == p) continue
172 // general excludes and namespaces for server admin used cvars
173 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
177 BADPREFIX("cvar_check_");
179 BADCVAR("g_configversion");
180 BADCVAR("halflifebsp");
181 BADCVAR("sv_mapformat_is_quake2");
182 BADCVAR("sv_mapformat_is_quake3");
183 BADPREFIX("sv_world");
189 BADPREFIX("scoreboard_");
190 BADPREFIX("g_campaign");
191 BADPREFIX("g_waypointsprite_");
197 BADPREFIX("net_slist_");
203 BADPREFIX("sensitivity");
204 BADPREFIX("userbind");
207 BADPREFIX("crosshair");
208 BADCVAR("mod_q3bsp_lightmapmergepower");
209 BADCVAR("mod_q3bsp_nolightmaps");
211 BADCVAR("mastervolume");
213 BADCVAR("bgmvolume");
214 BADCVAR("in_pitch_min");
215 BADCVAR("in_pitch_max");
218 BADCVAR("developer");
219 BADCVAR("log_dest_udp");
220 BADCVAR("net_address");
221 BADCVAR("net_address_ipv6");
223 BADCVAR("savedgamecfg");
224 BADCVAR("serverconfig");
225 BADCVAR("sv_autoscreenshot");
226 BADCVAR("sv_heartbeatperiod");
227 BADCVAR("sv_vote_master_password");
228 BADCVAR("sys_colortranslation");
229 BADCVAR("sys_specialcharactertranslation");
230 BADCVAR("timeformat");
231 BADCVAR("timestamps");
232 BADCVAR("g_require_stats");
233 BADPREFIX("developer_");
235 BADPREFIX("g_banned_list");
236 BADPREFIX("g_require_stats_");
237 BADPREFIX("g_chat_flood_");
238 BADPREFIX("g_ghost_items");
239 BADPREFIX("g_playerstats_");
240 BADPREFIX("g_voice_flood_");
241 BADPREFIX("log_file");
244 BADPREFIX("sv_allowdownloads");
245 BADPREFIX("sv_autodemo");
246 BADPREFIX("sv_curl_");
247 BADPREFIX("sv_eventlog");
248 BADPREFIX("sv_logscores_");
249 BADPREFIX("sv_master");
250 BADPREFIX("sv_weaponstats_");
251 BADPREFIX("sv_waypointsprite_");
252 BADCVAR("rescan_pending");
254 // these can contain player IDs, so better hide
255 BADPREFIX("g_forced_team_");
256 BADCVAR("sv_muteban_list");
257 BADCVAR("sv_voteban_list");
258 BADCVAR("sv_allow_customplayermodels_idlist");
259 BADCVAR("sv_allow_customplayermodels_speciallist");
262 BADCVAR("fraglimit");
264 BADCVAR("g_assault");
266 BADCVAR("g_ca_teams");
267 BADCVAR("g_conquest");
268 BADCVAR("g_conquest_teams");
273 BADCVAR("g_domination");
274 BADCVAR("g_domination_default_teams");
276 BADCVAR("g_duel_not_dm_maps");
277 BADCVAR("g_freezetag");
278 BADCVAR("g_freezetag_teams");
279 BADCVAR("g_invasion_teams");
280 BADCVAR("g_invasion_type");
281 BADCVAR("g_jailbreak");
282 BADCVAR("g_jailbreak_teams");
283 BADCVAR("g_keepaway");
284 BADCVAR("g_keyhunt");
285 BADCVAR("g_keyhunt_teams");
287 BADCVAR("g_nexball");
288 BADCVAR("g_onslaught");
290 BADCVAR("g_race_laps_limit");
291 BADCVAR("g_race_qualifying_timelimit");
292 BADCVAR("g_race_qualifying_timelimit_override");
293 BADCVAR("g_runematch");
294 BADCVAR("g_shootfromeye");
296 BADCVAR("g_survival");
297 BADCVAR("g_survival_not_dm_maps");
299 BADCVAR("g_tdm_on_dm_maps");
300 BADCVAR("g_tdm_teams");
302 BADCVAR("leadlimit");
305 BADCVAR("timelimit");
306 BADCVAR("g_mapinfo_settemp_acl");
307 BADCVAR("g_mapinfo_ignore_warnings");
308 BADCVAR("g_maplist_ignore_sizes");
309 BADCVAR("g_maplist_sizes_count_bots");
313 BADCVAR("g_maplist");
314 BADCVAR("g_maplist_mostrecent");
318 d = cvar_defstring(k);
324 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
325 if(strlen(cvar_changes) > 16384)
327 cvar_changes = "// too many settings have been changed to show them here\n";
332 // now check if the changes are actually gameplay relevant
334 // does nothing gameplay relevant
335 BADCVAR("captureleadlimit_override");
336 BADCVAR("condump_stripcolors");
337 BADCVAR("gameversion");
338 BADCVAR("fs_gamedir");
339 BADCVAR("g_allow_oldvortexbeam");
340 BADCVAR("g_balance_kill_delay");
341 BADCVAR("g_buffs_pickup_anyway");
342 BADCVAR("g_buffs_randomize");
343 BADCVAR("g_buffs_randomize_teamplay");
344 BADCVAR("g_campcheck_distance");
345 BADCVAR("g_chatsounds");
346 BADCVAR("g_ca_point_leadlimit");
347 BADCVAR("g_ca_point_limit");
348 BADCVAR("g_ctf_captimerecord_always");
349 BADCVAR("g_ctf_flag_glowtrails");
350 BADCVAR("g_ctf_dynamiclights");
351 BADCVAR("g_ctf_flag_pickup_verbosename");
352 BADPRESUFFIX("g_ctf_flag_", "_model");
353 BADPRESUFFIX("g_ctf_flag_", "_skin");
354 BADCVAR("g_domination_point_leadlimit");
355 BADCVAR("g_forced_respawn");
356 BADCVAR("g_freezetag_point_leadlimit");
357 BADCVAR("g_freezetag_point_limit");
358 BADCVAR("g_glowtrails");
360 BADCVAR("g_casings");
361 BADCVAR("g_invasion_point_limit");
362 BADCVAR("g_jump_grunt");
363 BADCVAR("g_keepaway_ballcarrier_effects");
364 BADCVAR("g_keepawayball_effects");
365 BADCVAR("g_keyhunt_point_leadlimit");
366 BADCVAR("g_nexball_goalleadlimit");
367 BADCVAR("g_new_toys_autoreplace");
368 BADCVAR("g_new_toys_use_pickupsound");
369 BADCVAR("g_physics_predictall");
370 BADCVAR("g_piggyback");
371 BADCVAR("g_playerclip_collisions");
372 BADCVAR("g_spawn_alloweffects");
373 BADCVAR("g_tdm_point_leadlimit");
374 BADCVAR("g_tdm_point_limit");
375 BADCVAR("leadlimit_and_fraglimit");
376 BADCVAR("leadlimit_override");
378 BADCVAR("sv_announcer");
379 BADCVAR("sv_checkforpacketsduringsleep");
380 BADCVAR("sv_damagetext");
381 BADCVAR("sv_db_saveasdump");
382 BADCVAR("sv_intermission_cdtrack");
383 BADCVAR("sv_mapchange_delay");
384 BADCVAR("sv_minigames");
385 BADCVAR("sv_namechangetimer");
386 BADCVAR("sv_precacheplayermodels");
388 BADCVAR("sv_stepheight");
389 BADCVAR("sv_timeout");
390 BADCVAR("sv_weapons_modeloverride");
391 BADCVAR("w_prop_interval");
393 BADPREFIX("crypto_");
394 BADPREFIX("gameversion_");
395 BADPREFIX("g_chat_");
396 BADPREFIX("g_ctf_captimerecord_");
397 BADPREFIX("g_hats_");
398 BADPREFIX("g_maplist_");
400 BADPREFIX("g_respawn_");
402 BADPREFIX("notification_");
405 BADPREFIX("sv_allow_");
406 BADPREFIX("sv_cullentities_");
407 BADPREFIX("sv_maxidle_");
408 BADPREFIX("sv_minigames_");
409 BADPREFIX("sv_radio_");
410 BADPREFIX("sv_timeout_");
411 BADPREFIX("sv_vote_");
412 BADPREFIX("timelimit_");
414 // allowed changes to server admins (please sync this to server.cfg)
418 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
420 // yes, this does contain some redundant stuff, don't really care
421 BADPREFIX("bot_ai_");
422 BADCVAR("bot_config_file");
423 BADCVAR("bot_number");
424 BADCVAR("bot_prefix");
425 BADCVAR("bot_suffix");
426 BADCVAR("capturelimit_override");
427 BADCVAR("fraglimit_override");
429 BADCVAR("g_antilag");
430 BADCVAR("g_balance_teams");
431 BADCVAR("g_balance_teams_prevent_imbalance");
432 BADCVAR("g_balance_teams_scorefactor");
433 BADCVAR("g_ban_sync_trusted_servers");
434 BADCVAR("g_ban_sync_uri");
436 BADCVAR("g_ca_teams_override");
437 BADCVAR("g_ctf_fullbrightflags");
438 BADCVAR("g_ctf_ignore_frags");
439 BADCVAR("g_ctf_leaderboard");
440 BADCVAR("g_domination_point_limit");
441 BADCVAR("g_domination_teams_override");
442 BADCVAR("g_freezetag_teams_override");
443 BADCVAR("g_friendlyfire");
444 BADCVAR("g_fullbrightitems");
445 BADCVAR("g_fullbrightplayers");
446 BADCVAR("g_keyhunt_point_limit");
447 BADCVAR("g_keyhunt_teams_override");
448 BADCVAR("g_lms_lives_override");
449 BADCVAR("g_maplist");
450 BADCVAR("g_maxplayers");
451 BADCVAR("g_mirrordamage");
452 BADCVAR("g_nexball_goallimit");
453 BADCVAR("g_norecoil");
454 BADCVAR("g_physics_clientselect");
456 BADCVAR("g_powerups");
457 BADCVAR("g_player_brightness");
458 BADCVAR("g_rocket_flying");
459 BADCVAR("g_rocket_flying_disabledelays");
460 BADCVAR("g_spawnshieldtime");
461 BADCVAR("g_start_delay");
462 BADCVAR("g_superspectate");
463 BADCVAR("g_tdm_teams_override");
465 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
468 BADCVAR("maxplayers");
469 BADCVAR("minplayers");
470 BADCVAR("minplayers_per_team");
471 BADCVAR("net_address");
473 BADCVAR("rcon_password");
474 BADCVAR("rcon_restricted_commands");
475 BADCVAR("rcon_restricted_password");
477 BADCVAR("sv_adminnick");
478 BADCVAR("sv_autoscreenshot");
479 BADCVAR("sv_autotaunt");
480 BADCVAR("sv_curl_defaulturl");
481 BADCVAR("sv_defaultcharacter");
482 BADCVAR("sv_defaultcharacterskin");
483 BADCVAR("sv_defaultplayercolors");
484 BADCVAR("sv_defaultplayermodel");
485 BADCVAR("sv_defaultplayerskin");
486 BADCVAR("sv_maxidle");
487 BADCVAR("sv_maxrate");
489 BADCVAR("sv_public");
490 BADCVAR("sv_ready_restart");
491 BADCVAR("sv_status_privacy");
493 BADCVAR("sv_vote_call");
494 BADCVAR("sv_vote_commands");
495 BADCVAR("sv_vote_majority_factor");
496 BADCVAR("sv_vote_master");
497 BADCVAR("sv_vote_master_commands");
498 BADCVAR("sv_vote_master_password");
499 BADCVAR("sv_vote_simple_majority_factor");
500 BADCVAR("teamplay_mode");
501 BADCVAR("timelimit_override");
502 BADPREFIX("g_warmup_");
503 BADPREFIX("sv_info_");
504 BADPREFIX("sv_ready_restart_");
506 // mutators that announce themselves properly to the server browser
507 BADCVAR("g_instagib");
508 BADCVAR("g_new_toys");
510 BADCVAR("g_grappling_hook");
511 BADCVAR("g_jetpack");
513 // temporary for testing
514 // TODO remove before 0.8.3 release
515 BADCVAR("g_ca_weaponarena");
516 BADCVAR("g_freezetag_weaponarena");
517 BADCVAR("g_lms_weaponarena");
518 BADCVAR("g_ctf_stalemate_time");
520 if(cvar_string("g_mod_balance") == "Testing")
522 // (temporary) while using the Testing balance, any weapon balance cvars are allowed to be changed
523 BADPREFIX("g_balance_");
532 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
533 if(strlen(cvar_purechanges) > 16384)
535 cvar_purechanges = "// too many settings have been changed to show them here\n";
539 ++cvar_purechanges_count;
540 // WARNING: this variable is used for the server list
541 // NEVER dare to skip this code!
542 // Hacks to intentionally appearing as "pure server" even though you DO have
543 // modified settings may be punished by removal from the server list.
544 // You can do to the variables cvar_changes and cvar_purechanges all you want,
548 if(cvar_changes == "")
549 cvar_changes = "// this server runs at default server settings\n";
551 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
552 cvar_changes = strzone(cvar_changes);
553 if(cvar_purechanges == "")
554 cvar_purechanges = "// this server runs at default gameplay settings\n";
556 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
557 cvar_purechanges = strzone(cvar_purechanges);
561 bool RandomSeed_Send(entity this, entity to, int sf)
563 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
564 WriteShort(MSG_ENTITY, this.cnt);
567 void RandomSeed_Think(entity this)
569 this.cnt = bound(0, floor(random() * 65536), 65535);
570 this.nextthink = time + 5;
574 void RandomSeed_Spawn()
576 randomseed = new_pure(randomseed);
577 setthink(randomseed, RandomSeed_Think);
578 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
580 getthink(randomseed)(randomseed); // sets random seed and nextthink
583 spawnfunc(__init_dedicated_server)
585 // handler for _init/_init map (only for dedicated server initialization)
587 world_initialized = -1; // don't complain
589 delete_fn = remove_unsafely;
592 setthink(e, GotoFirstMap);
593 e.nextthink = time; // this is usually 1 at this point
595 e = new(info_player_deathmatch); // safeguard against player joining
597 // assign reflectively to avoid "assignment to world" warning
598 for (int i = 0, n = numentityfields(); i < n; ++i) {
599 string k = entityfieldname(i);
600 if (k == "classname") {
601 // safeguard against various stuff ;)
602 putentityfieldstring(i, this, "worldspawn");
607 // needs to be done so early because of the constants they create
610 static_init_precache();
612 IL_PUSH(g_spawnpoints, e); // just incase
615 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
618 void __init_dedicated_server_shutdown() {
622 STATIC_INIT_EARLY(maxclients)
625 for (entity head = nextent(NULL); head; head = nextent(head)) {
630 void default_delayedinit(entity this)
632 if(!scores_initialized)
633 ScoreRules_generic();
636 void InitGameplayMode()
640 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
642 // assign reflectively to avoid "assignment to world" warning
643 int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
644 string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
646 putentityfieldstring(i, world, sprintf("%v", v));
647 if (++done == 2) break;
650 // currently, NetRadiant's limit is 131072 qu for each side
651 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
652 // set the distance according to map size but don't go over the limit to avoid issues with float precision
653 // in case somebody makes extremely large maps
654 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
656 MapInfo_LoadMapSettings(mapname);
657 GameRules_teams(false);
659 if (!cvar_value_issafe(world.fog))
661 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
662 world.fog = string_null;
664 if(MapInfo_Map_fog != "")
666 if(MapInfo_Map_fog == "none")
667 world.fog = string_null;
669 world.fog = strzone(MapInfo_Map_fog);
671 clientstuff = strzone(MapInfo_Map_clientstuff);
673 MapInfo_ClearTemps();
675 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
677 cache_mutatormsg = strzone("");
678 cache_lastmutatormsg = strzone("");
680 InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
683 void Map_MarkAsRecent(string m);
684 float world_already_spawned;
685 spawnfunc(worldspawn)
687 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
689 bool wantrestart = false;
691 if (!server_is_dedicated)
693 // force unloading of server pk3 files when starting a listen server
694 // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
695 // restore csqc_progname too
696 string expect = "csprogs.dat";
697 wantrestart = cvar_string("csqc_progname") != expect;
698 cvar_set("csqc_progname", expect);
702 // Try to use versioned csprogs from pk3
703 // Only ever use versioned csprogs.dat files on dedicated servers;
704 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
705 string pk3csprogs = "csprogs-" WATERMARK ".dat";
706 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
707 string select = "csprogs.dat";
708 if (fexists(pk3csprogs)) select = pk3csprogs;
709 if (cvar_string("csqc_progname") != select)
711 cvar_set("csqc_progname", select);
714 // Check for updates on startup
715 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
716 int sentinel = fopen("progs.txt", FILE_READ);
719 string switchversion = fgets(sentinel);
721 if (switchversion != "" && switchversion != WATERMARK)
723 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
724 // if it doesn't exist, assume either:
725 // a) the current program was overwritten
726 // b) this is a client only update
727 string newprogs = sprintf("progs-%s.dat", switchversion);
728 if (fexists(newprogs))
730 cvar_set("sv_progs", newprogs);
733 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
734 if (fexists(newcsprogs))
736 cvar_set("csqc_progname", newcsprogs);
744 LOG_INFO("Restart requested");
745 changelevel(mapname);
746 // let initialization continue, shutdown depends on it
750 if(world_already_spawned)
751 error("world already spawned - you may have EXACTLY ONE worldspawn!");
752 world_already_spawned = true;
754 delete_fn = remove_safely; // during spawning, watch what you remove!
756 cvar_changes_init(); // do this very early now so it REALLY matches the server config
758 // needs to be done so early because of the constants they create
761 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
763 TemporaryDB = db_create();
768 // 1 FLICKER (first variety)
769 lightstyle(1, "mmnmmommommnonmmonqnmmo");
771 // 2 SLOW STRONG PULSE
772 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
774 // 3 CANDLE (first variety)
775 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
778 lightstyle(4, "mamamamamama");
781 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
783 // 6 FLICKER (second variety)
784 lightstyle(6, "nmonqnmomnmomomno");
786 // 7 CANDLE (second variety)
787 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
789 // 8 CANDLE (third variety)
790 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
792 // 9 SLOW STROBE (fourth variety)
793 lightstyle(9, "aaaaaaaazzzzzzzz");
795 // 10 FLUORESCENT FLICKER
796 lightstyle(10, "mmamammmmammamamaaamammma");
798 // 11 SLOW PULSE NOT FADE TO BLACK
799 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
801 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
806 if(autocvar_g_campaign)
809 Map_MarkAsRecent(mapname);
811 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
815 static_init_precache();
819 GameRules_limit_fallbacks();
821 if(warmup_limit == 0)
822 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
825 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
826 if(bot_waypoints_for_items == 1)
827 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
828 bot_waypoints_for_items = 0;
830 WaypointSprite_Init();
832 GameLogInit(); // prepare everything
834 // changing the logic generating it is okay. But:
835 // it HAS to stay <= 64 chars
836 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
837 if(autocvar_sv_eventlog)
839 string s = sprintf("%s.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
840 matchid = strzone(s);
842 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
843 s = ":gameinfo:mutators:LIST";
845 MUTATOR_CALLHOOK(BuildMutatorsString, s);
846 s = M_ARGV(0, string);
848 // initialiation stuff, not good in the mutator system
849 if(!autocvar_g_use_ammunition)
850 s = strcat(s, ":no_use_ammunition");
852 // initialiation stuff, not good in the mutator system
853 if(autocvar_g_pickup_items == 0)
854 s = strcat(s, ":no_pickup_items");
855 if(autocvar_g_pickup_items > 0)
856 s = strcat(s, ":pickup_items");
858 // initialiation stuff, not good in the mutator system
859 if(autocvar_g_weaponarena != "0")
860 s = strcat(s, ":", autocvar_g_weaponarena, " arena");
862 // TODO to mutator system
863 if(autocvar_g_norecoil)
864 s = strcat(s, ":norecoil");
866 // TODO to mutator system
867 if(autocvar_g_powerups == 0)
868 s = strcat(s, ":no_powerups");
869 if(autocvar_g_powerups > 0)
870 s = strcat(s, ":powerups");
873 GameLogEcho(":gameinfo:end");
876 matchid = strzone(ftos(random()));
878 cvar_set("nextmap", "");
882 if(autocvar_g_campaign)
888 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
890 if(fexists(_MapInfo_FindArenaFile(mapname, ".arena")))
891 cvar_settemp("sv_q3acompat_machineshotgunswap", "1");
893 if(fexists(_MapInfo_FindArenaFile(mapname, ".defi")))
894 cvar_settemp("sv_q3defragcompat", "1");
896 // quake 3 music support
897 if(world.music || world.noise)
899 // prefer .music over .noise
903 chosen_music = world.music;
905 chosen_music = world.noise;
907 substring(chosen_music, strlen(chosen_music) - 4, 4) == ".wav"
909 substring(chosen_music, strlen(chosen_music) - 4, 4) == ".ogg"
911 oldstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
913 oldstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
915 strcpy(clientstuff, oldstuff);
918 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
920 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
924 while((s = fgets(fd)))
926 int l = tokenize_console(s);
931 string trackname = argv(2);
932 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
933 LOG_INFO(" cdtrack ", trackname);
934 if (cvar_value_issafe(trackname))
936 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
937 strcpy(clientstuff, newstuff);
940 else if(argv(0) == "fog")
942 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
943 LOG_INFO(" \"fog\" \"", s, "\"");
945 else if(argv(0) == "set")
947 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
948 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
950 else if(argv(0) != "//")
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(0), " ", argv(1));
964 // set up information replies for clients and server to use
965 maplist_reply = strzone(getmaplist());
966 lsmaps_reply = strzone(getlsmaps());
967 monsterlist_reply = strzone(getmonsterlist());
968 for(int i = 0; i < 10; ++i)
970 string s = getrecords(i);
972 records_reply[i] = strzone(s);
974 ladder_reply = strzone(getladder());
975 rankings_reply = strzone(getrankings());
980 PingPLReport_Spawn();
984 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
986 // fill sv_curl_serverpackages from .serverpackage files
987 if (autocvar_sv_curl_serverpackages_auto)
989 string s = "csprogs-" WATERMARK ".txt";
990 // remove automatically managed files from the list to prevent duplicates
991 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
993 string pkg = argv(i);
994 if (startsWith(pkg, "csprogs-")) continue;
995 if (endsWith(pkg, "-serverpackage.txt")) continue;
996 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
999 // add automatically managed files to the list
1000 #define X(match) MACRO_BEGIN \
1001 int fd = search_begin(match, true, false); \
1004 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1006 s = cons(s, search_getfilename(fd, i)); \
1011 X("*-serverpackage.txt");
1012 X("*.serverpackage");
1014 cvar_set("sv_curl_serverpackages", s);
1017 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1018 modname = "Xonotic";
1019 // physics/balance/config changes that count as mod
1020 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1021 modname = cvar_string("g_mod_physics");
1022 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1023 modname = cvar_string("g_mod_balance");
1024 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1025 modname = cvar_string("g_mod_config");
1026 // extra mutators that deserve to count as mod
1027 MUTATOR_CALLHOOK(SetModname, modname);
1028 modname = M_ARGV(0, string);
1030 // save it for later
1031 modname = strzone(modname);
1033 WinningConditionHelper(this); // set worldstatus
1035 world_initialized = 1;
1036 __spawnfunc_spawn_all();
1041 //makestatic (this); // Who the f___ did that?
1045 string GetGametype()
1047 return MapInfo_Type_ToString(MapInfo_LoadedGametype);
1055 float Map_Count, Map_Current;
1056 string Map_Current_Name;
1058 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
1059 int GetMaplistPosition()
1061 string map = GetMapname();
1062 int idx = autocvar_g_maplist_index;
1068 if(map == argv(idx))
1075 for(int pos = 0; pos < Map_Count; ++pos)
1077 if(map == argv(pos))
1081 // resume normal maplist rotation if current map is not in g_maplist
1085 bool MapHasRightSize(string map)
1087 int minplayers = max(0, floor(autocvar_minplayers));
1089 minplayers = max(0, floor(autocvar_minplayers_per_team) * AvailableTeams());
1090 if (autocvar_g_maplist_check_waypoints
1091 && (currentbots || autocvar_bot_number || player_count < minplayers))
1093 string checkwp_msg = strcat("checkwp ", map);
1094 if(!fexists(strcat("maps/", map, ".waypoints")))
1096 LOG_TRACE(checkwp_msg, ": no waypoints");
1099 LOG_TRACE(checkwp_msg, ": has waypoints");
1102 if(autocvar_g_maplist_ignore_sizes)
1105 // open map size restriction file
1106 string opensize_msg = strcat("opensize ", map);
1107 float fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1108 int player_limit = ((autocvar_g_maplist_sizes_count_maxplayers) ? GetPlayerLimit() : 0);
1109 int pcount = ((player_limit > 0) ? min(player_count, player_limit) : player_count); // bind it to the player limit so that forced spectators don't influence the limits
1110 if(!autocvar_g_maplist_sizes_count_bots)
1111 pcount -= currentbots;
1114 opensize_msg = strcat(opensize_msg, ": ok, ");
1115 int mapmin = stoi(fgets(fh));
1116 int mapmax = stoi(fgets(fh));
1120 LOG_TRACE(opensize_msg, "not enough");
1123 if(mapmax && pcount > mapmax)
1125 LOG_TRACE(opensize_msg, "too many");
1128 LOG_TRACE(opensize_msg, "right size");
1131 LOG_TRACE(opensize_msg, ": not found");
1135 string Map_Filename(float position)
1137 return strcat("maps/", argv(position), ".bsp");
1140 void Map_MarkAsRecent(string m)
1142 cvar_set("g_maplist_mostrecent", strwords(cons(m, autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1145 float Map_IsRecent(string m)
1147 return strhasword(autocvar_g_maplist_mostrecent, m);
1150 float Map_Check(float position, float pass)
1154 map_next = argv(position);
1157 if(Map_IsRecent(map_next))
1160 filename = Map_Filename(position);
1161 if(MapInfo_CheckMap(map_next))
1165 if(MapHasRightSize(map_next))
1170 LOG_DEBUG( "Couldn't select '", filename, "'..." );
1175 void Map_Goto_SetStr(string nextmapname)
1177 if(getmapname_stored != "")
1178 strunzone(getmapname_stored);
1179 if(nextmapname == "")
1180 getmapname_stored = "";
1182 getmapname_stored = strzone(nextmapname);
1185 void Map_Goto_SetFloat(float position)
1187 cvar_set("g_maplist_index", ftos(position));
1188 Map_Goto_SetStr(argv(position));
1191 void Map_Goto(float reinit)
1193 MapInfo_LoadMap(getmapname_stored, reinit);
1196 // return codes of map selectors:
1197 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1198 // -2 = permanent failure
1199 float MaplistMethod_Iterate() // usual method
1203 LOG_TRACE("Trying MaplistMethod_Iterate");
1205 for(pass = 1; pass <= 2; ++pass)
1207 for(i = 1; i < Map_Count; ++i)
1210 mapindex = (i + Map_Current) % Map_Count;
1211 if(Map_Check(mapindex, pass))
1218 float MaplistMethod_Repeat() // fallback method
1220 LOG_TRACE("Trying MaplistMethod_Repeat");
1222 if(Map_Check(Map_Current, 2))
1227 float MaplistMethod_Random() // random map selection
1231 LOG_TRACE("Trying MaplistMethod_Random");
1235 for(i = 0; i <= imax; ++i)
1238 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1239 if(Map_Check(mapindex, 1))
1245 float MaplistMethod_Shuffle(float exponent) // more clever shuffling
1246 // the exponent sets a bias on the map selection:
1247 // the higher the exponent, the less likely "shortly repeated" same maps are
1249 float i, j, imax, insertpos;
1251 LOG_TRACE("Trying MaplistMethod_Shuffle");
1255 for(i = 0; i <= imax; ++i)
1259 // now reinsert this at another position
1260 insertpos = (random() ** (1 / exponent)); // ]0, 1]
1261 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
1262 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
1263 LOG_TRACE("SHUFFLE: insert pos = ", ftos(insertpos));
1265 // insert the current map there
1267 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1268 newlist = strcat(newlist, " ", argv(j));
1269 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
1270 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
1271 newlist = strcat(newlist, " ", argv(j));
1272 newlist = substring(newlist, 1, strlen(newlist) - 1);
1273 cvar_set("g_maplist", newlist);
1274 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1276 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1277 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1278 if(Map_Check(Map_Current, 1))
1286 float i = Map_Count = 0;
1287 if(autocvar_g_maplist != "")
1289 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1290 for (i = 0; i < Map_Count; ++i)
1292 if (Map_Check(i, 2))
1299 bprint( "Maplist contains no usable maps! Resetting it to default map list.\n" );
1300 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1301 if(autocvar_g_maplist_shuffle)
1303 if(!server_is_dedicated)
1304 localcmd("\nmenu_cmd sync\n");
1305 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1308 error("empty maplist, cannot select a new map");
1309 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1311 strcpy(Map_Current_Name, argv(Map_Current)); // will be automatically freed on exit thanks to DP
1312 // this may or may not be correct, but who cares, in the worst case a map
1313 // isn't chosen in the first pass that should have been
1322 if(autocvar_g_maplist_shuffle > 0)
1323 nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1326 if(autocvar_g_maplist_selectrandom)
1327 nextMap = MaplistMethod_Random();
1330 nextMap = MaplistMethod_Iterate();
1333 nextMap = MaplistMethod_Repeat();
1337 Map_Goto_SetFloat(nextMap);
1338 return getmapname_stored;
1344 float DoNextMapOverride(float reinit)
1346 if(autocvar_g_campaign)
1348 CampaignPostIntermission();
1349 alreadychangedlevel = true;
1352 if(autocvar_quit_when_empty)
1354 if(player_count <= currentbots)
1357 alreadychangedlevel = true;
1361 if(autocvar_quit_and_redirect != "")
1363 redirection_target = strzone(autocvar_quit_and_redirect);
1364 alreadychangedlevel = true;
1367 if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1369 localcmd("restart\n");
1370 alreadychangedlevel = true;
1373 if(autocvar_nextmap != "")
1376 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1377 cvar_set("nextmap",m);
1379 if(!m || gametypevote)
1381 if(autocvar_sv_vote_gametype)
1387 if(MapInfo_CheckMap(m))
1391 alreadychangedlevel = true;
1395 if(!reinit && autocvar_lastlevel)
1397 cvar_settemp_restore();
1398 localcmd("set lastlevel 0\ntogglemenu 1\n");
1399 alreadychangedlevel = true;
1405 void GotoNextMap(float reinit)
1410 if (alreadychangedlevel)
1412 alreadychangedlevel = true;
1414 string nextMap = GetNextMap();
1416 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1425 When the player presses attack or jump, change to the next level
1428 .float autoscreenshot;
1429 void IntermissionThink(entity this)
1431 FixIntermissionClient(this);
1433 float server_screenshot = (autocvar_sv_autoscreenshot && CS(this).cvar_cl_autoscreenshot);
1434 float client_screenshot = (CS(this).cvar_cl_autoscreenshot == 2);
1436 if( (server_screenshot || client_screenshot)
1437 && ((this.autoscreenshot > 0) && (time > this.autoscreenshot)) )
1439 this.autoscreenshot = -1;
1440 if(IS_REAL_CLIENT(this)) { stuffcmd(this, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(false, "%s"))); }
1444 if (time < intermission_exittime)
1447 if(!mapvote_initialized)
1448 if (time < intermission_exittime + 10 && !(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_JUMP(this) || PHYS_INPUT_BUTTON_ATCK2(this) || PHYS_INPUT_BUTTON_HOOK(this) || PHYS_INPUT_BUTTON_USE(this)))
1455 ===============================================================================
1459 ===============================================================================
1462 void DumpStats(float final)
1471 to_console = autocvar_sv_logscores_console;
1472 to_eventlog = autocvar_sv_eventlog;
1473 to_file = autocvar_sv_logscores_file;
1477 to_console = true; // always print printstats replies
1478 to_eventlog = false; // but never print them to the event log
1482 if(autocvar_sv_eventlog_console)
1483 to_console = false; // otherwise we get the output twice
1489 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1499 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1503 fputs(file, strcat(s, "\n"));
1506 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1512 fputs(file, strcat(s, "\n"));
1514 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1515 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1516 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1517 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1518 s = strcat(s, ftos(it.team), ":");
1520 s = strcat(s, "spectator:");
1523 LOG_INFO(s, playername(it, false));
1525 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it, false)));
1527 fputs(file, strcat(s, playername(it, false), "\n"));
1532 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1538 fputs(file, strcat(s, "\n"));
1540 for(i = 1; i < 16; ++i)
1542 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1543 s = strcat(s, ":", ftos(i));
1549 fputs(file, strcat(s, "\n"));
1556 GameLogEcho(":end");
1559 fputs(file, ":end\n");
1564 void FixIntermissionClient(entity e)
1566 if(!e.autoscreenshot) // initial call
1568 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1569 SetResourceExplicit(e, RES_HEALTH, -2342);
1570 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1571 for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1573 .entity weaponentity = weaponentities[slot];
1574 if(e.(weaponentity))
1576 e.(weaponentity).effects = EF_NODRAW;
1577 if (e.(weaponentity).weaponchild)
1578 e.(weaponentity).weaponchild.effects = EF_NODRAW;
1581 if(IS_REAL_CLIENT(e))
1583 stuffcmd(e, "\nscr_printspeed 1000000\n");
1584 RandomSelection_Init();
1585 FOREACH_WORD(autocvar_sv_intermission_cdtrack, true, {
1586 RandomSelection_AddString(it, 1, 1);
1588 if (RandomSelection_chosen_string != "")
1590 stuffcmd(e, sprintf("\ncd loop %s\n", RandomSelection_chosen_string));
1593 WriteByte(MSG_ONE, SVC_INTERMISSION);
1599 go to the next level for deathmatch
1600 only called if a time or frag limit has expired
1604 game_stopped = true;
1605 intermission_running = 1; // game over
1607 // enforce a wait time before allowing changelevel
1608 if(player_count > 0)
1609 intermission_exittime = time + autocvar_sv_mapchange_delay;
1611 intermission_exittime = -1;
1614 WriteByte (MSG_ALL, SVC_CDTRACK);
1615 WriteByte (MSG_ALL, 3);
1616 WriteByte (MSG_ALL, 3);
1617 // done in FixIntermission
1620 //pos = FindIntermission ();
1627 PlayerStats_GameReport(true);
1628 WeaponStats_Shutdown();
1630 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1632 if(autocvar_sv_eventlog)
1633 GameLogEcho(":gameover");
1637 FOREACH_CLIENT(IS_PLAYER(it), {
1638 FixIntermissionClient(it);
1640 bprint(playername(it, false), " ^7wins.\n");
1643 target_music_kill();
1645 if(autocvar_g_campaign)
1646 CampaignPreIntermission();
1648 MUTATOR_CALLHOOK(MatchEnd);
1650 localcmd("\nsv_hook_gameend\n");
1654 float InitiateSuddenDeath()
1656 // Check first whether normal overtimes could be added before initiating suddendeath mode
1657 // - for this timelimit_overtime needs to be >0 of course
1658 // - also check the winning condition calculated in the previous frame and only add normal overtime
1659 // again, if at the point at which timelimit would be extended again, still no winner was found
1660 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1661 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1662 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1664 return 1; // need to call InitiateOvertime later
1668 if(!checkrules_suddendeathend)
1670 if(autocvar_g_campaign)
1671 checkrules_suddendeathend = time; // no suddendeath in campaign
1673 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1674 if(g_race && !g_race_qualifying)
1675 race_StartCompleting();
1681 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1683 ++checkrules_overtimesadded;
1684 //add one more overtime by simply extending the timelimit
1685 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1686 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1689 float GetWinningCode(float fraglimitreached, float equality)
1691 if(autocvar_g_campaign == 1)
1693 if(fraglimitreached)
1702 if(fraglimitreached)
1703 return WINNING_STARTSUDDENDEATHOVERTIME;
1705 return WINNING_NEVER;
1709 if(fraglimitreached)
1717 // set the .winning flag for exactly those players with a given field value
1718 void SetWinners(.float field, float value)
1720 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = (it.(field) == value); });
1723 // set the .winning flag for those players with a given field value
1724 void AddWinners(.float field, float value)
1726 FOREACH_CLIENT(IS_PLAYER(it), {
1727 if(it.(field) == value)
1732 // clear the .winning flags
1735 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = 0; });
1738 void ShuffleMaplist()
1740 cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1744 float WinningCondition_Scores(float limit, float leadlimit)
1746 // TODO make everything use THIS winning condition (except LMS)
1747 WinningConditionHelper(NULL);
1751 for (int i = 1; i < 5; ++i)
1753 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1754 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1759 if(WinningConditionHelper_winner)
1760 WinningConditionHelper_winner.winning = 1;
1761 if(WinningConditionHelper_winnerteam >= 0)
1762 SetWinners(team, WinningConditionHelper_winnerteam);
1764 if(WinningConditionHelper_lowerisbetter)
1766 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1767 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1771 if(WinningConditionHelper_zeroisworst)
1772 leadlimit = 0; // not supported in this mode
1774 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1777 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1783 fragsleft = FLOAT_MAX;
1784 float leadingfragsleft = FLOAT_MAX;
1786 fragsleft = limit - WinningConditionHelper_topscore;
1788 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1790 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1791 fragsleft = max(fragsleft, leadingfragsleft);
1793 fragsleft = min(fragsleft, leadingfragsleft);
1796 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1799 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1800 else if (fragsleft == 2)
1801 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1802 else if (fragsleft == 3)
1803 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1805 fragsleft_last = fragsleft;
1809 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1810 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1813 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1814 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1815 limit_reached = (fraglimit_reached && leadlimit_reached);
1817 limit_reached = (fraglimit_reached || leadlimit_reached);
1819 return GetWinningCode(
1820 WinningConditionHelper_topscore && limit_reached,
1821 WinningConditionHelper_equality
1825 float WinningCondition_RanOutOfSpawns()
1827 if(have_team_spawns <= 0)
1830 if(!autocvar_g_spawn_useallspawns)
1833 if(!some_spawn_has_been_used)
1836 for (int i = 1; i < 5; ++i)
1838 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1841 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1843 if (Team_IsValidTeam(it.team))
1845 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1849 IL_EACH(g_spawnpoints, true,
1851 if (Team_IsValidTeam(it.team))
1853 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1858 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1859 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1860 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1861 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1862 if(team1_score + team2_score + team3_score + team4_score == 0)
1864 checkrules_equality = true;
1867 else if(team1_score + team2_score + team3_score + team4_score == 1)
1872 else if(team2_score)
1874 else if(team3_score)
1876 else // if(team4_score)
1878 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1879 for(i = 0; i < MAX_TEAMSCORE; ++i)
1881 for (int j = 1; j <= NUM_TEAMS; ++j)
1887 if (!TeamBalance_IsTeamAllowed(balance, j))
1891 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1895 AddWinners(team, t);
1906 Exit deathmatch games upon conditions
1909 void CheckRules_World()
1916 if (intermission_running) // someone else quit the game already
1918 if(player_count == 0) // Nobody there? Then let's go to the next map
1920 // this will actually check the player count in the next frame
1921 // again, but this shouldn't hurt
1925 float timelimit = autocvar_timelimit * 60;
1926 float fraglimit = autocvar_fraglimit;
1927 float leadlimit = autocvar_leadlimit;
1928 if (leadlimit < 0) leadlimit = 0;
1930 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1933 timelimit = 0; // timelimit is not made for warmup
1935 fraglimit = 0; // no fraglimit for now
1936 leadlimit = 0; // no leadlimit for now
1941 timelimit += game_starttime;
1943 else if (timelimit < 0)
1953 if(checkrules_suddendeathend)
1955 if(!checkrules_suddendeathwarning)
1957 checkrules_suddendeathwarning = true;
1958 if(g_race && !g_race_qualifying)
1959 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1961 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1966 if (timelimit && time >= timelimit)
1968 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1971 float playerswithlaps;
1973 totalplayers = playerswithlaps = readyplayers = 0;
1974 FOREACH_CLIENT(IS_PLAYER(it), {
1976 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1982 // at least 2 of the players have completed a lap: start the RACE
1983 // otherwise, the players should end the qualifying on their own
1984 if(readyplayers || playerswithlaps >= 2)
1986 checkrules_suddendeathend = 0;
1987 ReadyRestart(); // go to race
1991 wantovertime |= InitiateSuddenDeath();
1994 wantovertime |= InitiateSuddenDeath();
1998 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2004 int checkrules_status = WinningCondition_RanOutOfSpawns();
2005 if(checkrules_status == WINNING_YES)
2006 bprint("Hey! Someone ran out of spawns!\n");
2007 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
2008 checkrules_status = M_ARGV(0, float);
2010 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2012 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2014 checkrules_status = WINNING_NEVER;
2015 checkrules_overtimesadded = -1;
2016 wantovertime |= InitiateSuddenDeath();
2019 if(checkrules_status == WINNING_NEVER)
2020 // equality cases! Nobody wins if the overtime ends in a draw.
2025 if(checkrules_status == WINNING_NEVER)
2028 checkrules_status = WINNING_YES;
2031 if(checkrules_suddendeathend)
2032 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2033 checkrules_status = WINNING_YES;
2035 if(checkrules_status == WINNING_YES)
2037 //print("WINNING\n");
2042 string GotoMap(string m)
2044 m = GameTypeVote_MapInfo_FixName(m);
2046 return "The map you suggested is not available on this server.";
2047 if (!autocvar_sv_vote_gametype)
2048 if(!MapInfo_CheckMap(m))
2049 return "The map you suggested does not support the current game mode.";
2050 cvar_set("nextmap", m);
2051 cvar_set("timelimit", "-1");
2052 if(mapvote_initialized || alreadychangedlevel)
2054 if(DoNextMapOverride(0))
2055 return "Map switch initiated.";
2057 return "Hm... no. For some reason I like THIS map more.";
2060 return "Map switch will happen after scoreboard.";
2063 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2064 void RunThink(entity this)
2066 // don't let things stay in the past.
2067 // it is possible to start that way by a trigger with a local time.
2068 if(this.nextthink <= 0 || this.nextthink > time + frametime)
2071 float oldtime = time; // do we need to save this?
2073 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2075 time = max(oldtime, this.nextthink);
2079 getthink(this)(this);
2080 // mods often set nextthink to time to cause a think every frame,
2081 // we don't want to loop in that case, so exit if the new nextthink is
2082 // <= the time the qc was told, also exit if it is past the end of the
2084 if(this.nextthink <= time || this.nextthink > oldtime + frametime || !autocvar_sv_gameplayfix_multiplethinksperframe)
2091 bool autocvar_sv_freezenonclients;
2092 void Physics_Frame()
2094 if(autocvar_sv_freezenonclients)
2097 IL_EACH(g_moveables, true,
2099 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2102 //set_movetype(it, it.move_movetype);
2103 // inline the set_movetype function, since this is called a lot
2104 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2106 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2107 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2109 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2111 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2112 continue; // these movetypes have no regular think function
2113 // handle thinking here
2114 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + frametime)
2119 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2122 // make a second pass to see if any ents spawned this frame and make
2123 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2124 IL_EACH(g_moveables, it.move_qcphysics,
2126 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2128 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2132 void systems_update();
2135 anticheat_endframe();
2139 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2140 entity e = IS_SPEC(it) ? it.enemy : it;
2141 if (e.typehitsound) {
2142 STAT(TYPEHIT_TIME, it) = time;
2143 } else if (e.killsound) {
2144 STAT(KILL_TIME, it) = time;
2145 } else if (e.damage_dealt) {
2146 STAT(HIT_TIME, it) = time;
2147 STAT(DAMAGE_DEALT_TOTAL, it) += ceil(e.damage_dealt);
2150 // add 1 frametime because after this, engine SV_Physics
2151 // increases time by a frametime and then networks the frame
2152 // add another frametime because client shows everything with
2153 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2155 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2156 FOREACH_CLIENT(true, {
2157 it.typehitsound = false;
2158 it.damage_dealt = 0;
2159 it.killsound = false;
2160 antilag_record(it, CS(it), altime);
2162 IL_EACH(g_monsters, true,
2164 antilag_record(it, it, altime);
2166 IL_EACH(g_projectiles, it.classname == "nade",
2168 antilag_record(it, it, altime);
2177 * returns true if redirecting
2179 float redirection_timeout;
2180 float redirection_nextthink;
2181 float RedirectionThink()
2183 float clients_found;
2185 if(redirection_target == "")
2188 if(!redirection_timeout)
2190 cvar_set("sv_public", "-2");
2191 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2192 if(redirection_target == "self")
2193 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2195 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2198 if(time < redirection_nextthink)
2201 redirection_nextthink = time + 1;
2204 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2206 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2207 if(redirection_target == "self")
2208 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2210 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2214 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2216 if(time > redirection_timeout || clients_found == 0)
2217 localcmd("\nwait; wait; wait; quit\n");
2224 // Loaded from a save game
2225 // some things then break, so let's work around them...
2227 // Progs DB (capture records)
2228 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2232 MapInfo_Enumerate();
2233 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2236 TargetMusic_RestoreGame();
2243 if(world_initialized > 0)
2245 world_initialized = 0;
2247 // if a timeout is active, reset the slowmo value to normal
2248 if(timeout_status == TIMEOUT_ACTIVE)
2249 cvar_set("slowmo", ftos(orig_slowmo));
2251 LOG_TRACE("Saving persistent data...");
2254 // playerstats with unfinished match
2255 PlayerStats_GameReport(false);
2257 if(!cheatcount_total)
2259 if(autocvar_sv_db_saveasdump)
2260 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2262 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2264 if(autocvar_developer > 0)
2266 if(autocvar_sv_db_saveasdump)
2267 db_dump(TemporaryDB, "server-temp.db");
2269 db_save(TemporaryDB, "server-temp.db");
2271 CheatShutdown(); // must be after cheatcount check
2272 db_close(ServerProgsDB);
2273 db_close(TemporaryDB);
2274 LOG_TRACE("Saving persistent data... done!");
2275 // tell the bot system the game is ending now
2278 WeaponStats_Shutdown();
2281 else if(world_initialized == 0)
2283 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2287 __init_dedicated_server_shutdown();