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/g_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 "../common/constants.qh"
26 #include <common/net_linked.qh>
27 #include "../common/deathtypes/all.qh"
28 #include <common/gamemodes/_mod.qh>
29 #include "../common/gamemodes/sv_rules.qh"
30 #include "../common/mapinfo.qh"
31 #include "../common/monsters/_mod.qh"
32 #include "../common/monsters/sv_monsters.qh"
33 #include "../common/vehicles/all.qh"
34 #include "../common/notifications/all.qh"
35 #include "../common/physics/player.qh"
36 #include "../common/playerstats.qh"
37 #include "../common/stats.qh"
38 #include "../common/teams.qh"
39 #include "../common/mapobjects/trigger/secret.qh"
40 #include "../common/mapobjects/target/music.qh"
41 #include "../common/util.qh"
42 #include "../common/items/_mod.qh"
43 #include <common/weapons/_all.qh>
44 #include "../common/state.qh"
46 const float LATENCY_THINKRATE = 10;
51 void PingPLReport_Think(entity this)
56 delta = 3 / maxclients;
57 if(delta < sys_frametime)
59 this.nextthink = time + delta;
61 e = edict_num(this.cnt + 1);
62 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
64 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
65 WriteByte(MSG_BROADCAST, this.cnt);
66 WriteShort(MSG_BROADCAST, bound(1, CS(e).ping, 65535));
67 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
68 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
70 // record latency times for clients throughout the match so we can report it to playerstats
71 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
73 CS(e).latency_sum += CS(e).ping;
74 CS(e).latency_cnt += 1;
75 CS(e).latency_time = time;
76 //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
81 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
82 WriteByte(MSG_BROADCAST, this.cnt);
83 WriteShort(MSG_BROADCAST, 0);
84 WriteByte(MSG_BROADCAST, 0);
85 WriteByte(MSG_BROADCAST, 0);
87 this.cnt = (this.cnt + 1) % maxclients;
89 void PingPLReport_Spawn()
91 pingplreport = new_pure(pingplreport);
92 setthink(pingplreport, PingPLReport_Think);
93 pingplreport.nextthink = time;
96 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
97 string redirection_target;
98 float world_initialized;
100 void SetDefaultAlpha()
102 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
104 default_player_alpha = autocvar_g_player_alpha;
105 if(default_player_alpha == 0)
106 default_player_alpha = 1;
107 default_weapon_alpha = default_player_alpha;
111 void GotoFirstMap(entity this)
114 if(autocvar__sv_init)
116 // cvar_set("_sv_init", "0");
117 // we do NOT set this to 0 any more, so someone "accidentally" changing
118 // to this "init" map on a dedicated server will cause no permanent
120 if(autocvar_g_maplist_shuffle)
122 n = tokenizebyseparator(autocvar_g_maplist, " ");
123 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
126 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
128 if(!DoNextMapOverride(1))
136 this.nextthink = time;
140 this.nextthink = time + 1;
141 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
145 void cvar_changes_init()
149 float n, i, adding, pureadding;
151 strfree(cvar_changes);
152 strfree(cvar_purechanges);
153 cvar_purechanges_count = 0;
156 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
162 for(i = 0; i < n; ++i)
164 k = bufstr_get(h, i);
166 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
167 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
168 #define BADCVAR(p) if(k == p) continue
170 // general excludes and namespaces for server admin used cvars
171 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
175 BADPREFIX("cvar_check_");
177 BADCVAR("g_configversion");
178 BADCVAR("halflifebsp");
179 BADCVAR("sv_mapformat_is_quake2");
180 BADCVAR("sv_mapformat_is_quake3");
181 BADPREFIX("sv_world");
187 BADPREFIX("scoreboard_");
188 BADPREFIX("g_campaign");
189 BADPREFIX("g_waypointsprite_");
195 BADPREFIX("net_slist_");
201 BADPREFIX("sensitivity");
202 BADPREFIX("userbind");
205 BADPREFIX("crosshair");
206 BADCVAR("mod_q3bsp_lightmapmergepower");
207 BADCVAR("mod_q3bsp_nolightmaps");
209 BADCVAR("mastervolume");
211 BADCVAR("bgmvolume");
212 BADCVAR("in_pitch_min");
213 BADCVAR("in_pitch_max");
216 BADCVAR("developer");
217 BADCVAR("log_dest_udp");
218 BADCVAR("net_address");
219 BADCVAR("net_address_ipv6");
221 BADCVAR("savedgamecfg");
222 BADCVAR("serverconfig");
223 BADCVAR("sv_autoscreenshot");
224 BADCVAR("sv_heartbeatperiod");
225 BADCVAR("sv_vote_master_password");
226 BADCVAR("sys_colortranslation");
227 BADCVAR("sys_specialcharactertranslation");
228 BADCVAR("timeformat");
229 BADCVAR("timestamps");
230 BADCVAR("g_require_stats");
231 BADPREFIX("developer_");
233 BADPREFIX("g_banned_list");
234 BADPREFIX("g_require_stats_");
235 BADPREFIX("g_chat_flood_");
236 BADPREFIX("g_ghost_items");
237 BADPREFIX("g_playerstats_");
238 BADPREFIX("g_voice_flood_");
239 BADPREFIX("log_file");
242 BADPREFIX("sv_allowdownloads");
243 BADPREFIX("sv_autodemo");
244 BADPREFIX("sv_curl_");
245 BADPREFIX("sv_eventlog");
246 BADPREFIX("sv_logscores_");
247 BADPREFIX("sv_master");
248 BADPREFIX("sv_weaponstats_");
249 BADPREFIX("sv_waypointsprite_");
250 BADCVAR("rescan_pending");
252 // these can contain player IDs, so better hide
253 BADPREFIX("g_forced_team_");
254 BADCVAR("sv_muteban_list");
255 BADCVAR("sv_voteban_list");
256 BADCVAR("sv_allow_customplayermodels_idlist");
257 BADCVAR("sv_allow_customplayermodels_speciallist");
260 BADCVAR("fraglimit");
262 BADCVAR("g_assault");
264 BADCVAR("g_ca_teams");
265 BADCVAR("g_conquest");
266 BADCVAR("g_conquest_teams");
271 BADCVAR("g_domination");
272 BADCVAR("g_domination_default_teams");
274 BADCVAR("g_duel_not_dm_maps");
275 BADCVAR("g_freezetag");
276 BADCVAR("g_freezetag_teams");
277 BADCVAR("g_invasion_teams");
278 BADCVAR("g_invasion_type");
279 BADCVAR("g_jailbreak");
280 BADCVAR("g_jailbreak_teams");
281 BADCVAR("g_keepaway");
282 BADCVAR("g_keyhunt");
283 BADCVAR("g_keyhunt_teams");
285 BADCVAR("g_nexball");
286 BADCVAR("g_onslaught");
288 BADCVAR("g_race_laps_limit");
289 BADCVAR("g_race_qualifying_timelimit");
290 BADCVAR("g_race_qualifying_timelimit_override");
291 BADCVAR("g_runematch");
292 BADCVAR("g_shootfromeye");
294 BADCVAR("g_survival");
295 BADCVAR("g_survival_not_dm_maps");
297 BADCVAR("g_tdm_on_dm_maps");
298 BADCVAR("g_tdm_teams");
300 BADCVAR("leadlimit");
303 BADCVAR("timelimit");
304 BADCVAR("g_mapinfo_settemp_acl");
305 BADCVAR("g_mapinfo_ignore_warnings");
306 BADCVAR("g_maplist_ignore_sizes");
307 BADCVAR("g_maplist_sizes_count_bots");
311 BADCVAR("g_maplist");
312 BADCVAR("g_maplist_mostrecent");
316 d = cvar_defstring(k);
322 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
323 if(strlen(cvar_changes) > 16384)
325 cvar_changes = "// too many settings have been changed to show them here\n";
330 // now check if the changes are actually gameplay relevant
332 // does nothing gameplay relevant
333 BADCVAR("captureleadlimit_override");
334 BADCVAR("condump_stripcolors");
335 BADCVAR("gameversion");
336 BADCVAR("fs_gamedir");
337 BADCVAR("g_allow_oldvortexbeam");
338 BADCVAR("g_balance_kill_delay");
339 BADCVAR("g_buffs_pickup_anyway");
340 BADCVAR("g_buffs_randomize");
341 BADCVAR("g_buffs_randomize_teamplay");
342 BADCVAR("g_campcheck_distance");
343 BADCVAR("g_chatsounds");
344 BADCVAR("g_ca_point_leadlimit");
345 BADCVAR("g_ca_point_limit");
346 BADCVAR("g_ctf_captimerecord_always");
347 BADCVAR("g_ctf_flag_glowtrails");
348 BADCVAR("g_ctf_dynamiclights");
349 BADCVAR("g_ctf_flag_pickup_verbosename");
350 BADPRESUFFIX("g_ctf_flag_", "_model");
351 BADPRESUFFIX("g_ctf_flag_", "_skin");
352 BADCVAR("g_domination_point_leadlimit");
353 BADCVAR("g_forced_respawn");
354 BADCVAR("g_freezetag_point_leadlimit");
355 BADCVAR("g_freezetag_point_limit");
356 BADCVAR("g_glowtrails");
358 BADCVAR("g_casings");
359 BADCVAR("g_invasion_point_limit");
360 BADCVAR("g_jump_grunt");
361 BADCVAR("g_keepaway_ballcarrier_effects");
362 BADCVAR("g_keepawayball_effects");
363 BADCVAR("g_keyhunt_point_leadlimit");
364 BADCVAR("g_nexball_goalleadlimit");
365 BADCVAR("g_new_toys_autoreplace");
366 BADCVAR("g_new_toys_use_pickupsound");
367 BADCVAR("g_physics_predictall");
368 BADCVAR("g_piggyback");
369 BADCVAR("g_playerclip_collisions");
370 BADCVAR("g_spawn_alloweffects");
371 BADCVAR("g_tdm_point_leadlimit");
372 BADCVAR("g_tdm_point_limit");
373 BADCVAR("leadlimit_and_fraglimit");
374 BADCVAR("leadlimit_override");
376 BADCVAR("sv_announcer");
377 BADCVAR("sv_checkforpacketsduringsleep");
378 BADCVAR("sv_damagetext");
379 BADCVAR("sv_db_saveasdump");
380 BADCVAR("sv_intermission_cdtrack");
381 BADCVAR("sv_mapchange_delay");
382 BADCVAR("sv_minigames");
383 BADCVAR("sv_namechangetimer");
384 BADCVAR("sv_precacheplayermodels");
386 BADCVAR("sv_stepheight");
387 BADCVAR("sv_timeout");
388 BADCVAR("sv_weapons_modeloverride");
389 BADCVAR("w_prop_interval");
391 BADPREFIX("crypto_");
392 BADPREFIX("gameversion_");
393 BADPREFIX("g_chat_");
394 BADPREFIX("g_ctf_captimerecord_");
395 BADPREFIX("g_hats_");
396 BADPREFIX("g_maplist_");
398 BADPREFIX("g_respawn_");
400 BADPREFIX("notification_");
403 BADPREFIX("sv_allow_");
404 BADPREFIX("sv_cullentities_");
405 BADPREFIX("sv_maxidle_");
406 BADPREFIX("sv_minigames_");
407 BADPREFIX("sv_radio_");
408 BADPREFIX("sv_timeout_");
409 BADPREFIX("sv_vote_");
410 BADPREFIX("timelimit_");
412 // allowed changes to server admins (please sync this to server.cfg)
416 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
418 // yes, this does contain some redundant stuff, don't really care
419 BADPREFIX("bot_ai_");
420 BADCVAR("bot_config_file");
421 BADCVAR("bot_number");
422 BADCVAR("bot_prefix");
423 BADCVAR("bot_suffix");
424 BADCVAR("capturelimit_override");
425 BADCVAR("fraglimit_override");
427 BADCVAR("g_antilag");
428 BADCVAR("g_balance_teams");
429 BADCVAR("g_balance_teams_prevent_imbalance");
430 BADCVAR("g_balance_teams_scorefactor");
431 BADCVAR("g_ban_sync_trusted_servers");
432 BADCVAR("g_ban_sync_uri");
434 BADCVAR("g_ca_teams_override");
435 BADCVAR("g_ctf_fullbrightflags");
436 BADCVAR("g_ctf_ignore_frags");
437 BADCVAR("g_ctf_leaderboard");
438 BADCVAR("g_domination_point_limit");
439 BADCVAR("g_domination_teams_override");
440 BADCVAR("g_freezetag_teams_override");
441 BADCVAR("g_friendlyfire");
442 BADCVAR("g_fullbrightitems");
443 BADCVAR("g_fullbrightplayers");
444 BADCVAR("g_keyhunt_point_limit");
445 BADCVAR("g_keyhunt_teams_override");
446 BADCVAR("g_lms_lives_override");
447 BADCVAR("g_maplist");
448 BADCVAR("g_maxplayers");
449 BADCVAR("g_mirrordamage");
450 BADCVAR("g_nexball_goallimit");
451 BADCVAR("g_norecoil");
452 BADCVAR("g_physics_clientselect");
454 BADCVAR("g_powerups");
455 BADCVAR("g_player_brightness");
456 BADCVAR("g_rocket_flying");
457 BADCVAR("g_rocket_flying_disabledelays");
458 BADCVAR("g_spawnshieldtime");
459 BADCVAR("g_start_delay");
460 BADCVAR("g_superspectate");
461 BADCVAR("g_tdm_teams_override");
463 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
466 BADCVAR("maxplayers");
467 BADCVAR("minplayers");
468 BADCVAR("minplayers_per_team");
469 BADCVAR("net_address");
471 BADCVAR("rcon_password");
472 BADCVAR("rcon_restricted_commands");
473 BADCVAR("rcon_restricted_password");
475 BADCVAR("sv_adminnick");
476 BADCVAR("sv_autoscreenshot");
477 BADCVAR("sv_autotaunt");
478 BADCVAR("sv_curl_defaulturl");
479 BADCVAR("sv_defaultcharacter");
480 BADCVAR("sv_defaultcharacterskin");
481 BADCVAR("sv_defaultplayercolors");
482 BADCVAR("sv_defaultplayermodel");
483 BADCVAR("sv_defaultplayerskin");
484 BADCVAR("sv_maxidle");
485 BADCVAR("sv_maxrate");
487 BADCVAR("sv_public");
488 BADCVAR("sv_ready_restart");
489 BADCVAR("sv_status_privacy");
491 BADCVAR("sv_vote_call");
492 BADCVAR("sv_vote_commands");
493 BADCVAR("sv_vote_majority_factor");
494 BADCVAR("sv_vote_master");
495 BADCVAR("sv_vote_master_commands");
496 BADCVAR("sv_vote_master_password");
497 BADCVAR("sv_vote_simple_majority_factor");
498 BADCVAR("teamplay_mode");
499 BADCVAR("timelimit_override");
500 BADPREFIX("g_warmup_");
501 BADPREFIX("sv_info_");
502 BADPREFIX("sv_ready_restart_");
504 // mutators that announce themselves properly to the server browser
505 BADCVAR("g_instagib");
506 BADCVAR("g_new_toys");
508 BADCVAR("g_grappling_hook");
509 BADCVAR("g_jetpack");
511 // temporary for testing
512 // TODO remove before 0.8.3 release
513 BADCVAR("g_ca_weaponarena");
514 BADCVAR("g_freezetag_weaponarena");
515 BADCVAR("g_lms_weaponarena");
516 BADCVAR("g_ctf_stalemate_time");
518 if(cvar_string("g_mod_balance") == "Testing")
520 // (temporary) while using the Testing balance, any weapon balance cvars are allowed to be changed
521 BADPREFIX("g_balance_");
530 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
531 if(strlen(cvar_purechanges) > 16384)
533 cvar_purechanges = "// too many settings have been changed to show them here\n";
537 ++cvar_purechanges_count;
538 // WARNING: this variable is used for the server list
539 // NEVER dare to skip this code!
540 // Hacks to intentionally appearing as "pure server" even though you DO have
541 // modified settings may be punished by removal from the server list.
542 // You can do to the variables cvar_changes and cvar_purechanges all you want,
546 if(cvar_changes == "")
547 cvar_changes = "// this server runs at default server settings\n";
549 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
550 cvar_changes = strzone(cvar_changes);
551 if(cvar_purechanges == "")
552 cvar_purechanges = "// this server runs at default gameplay settings\n";
554 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
555 cvar_purechanges = strzone(cvar_purechanges);
559 bool RandomSeed_Send(entity this, entity to, int sf)
561 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
562 WriteShort(MSG_ENTITY, this.cnt);
565 void RandomSeed_Think(entity this)
567 this.cnt = bound(0, floor(random() * 65536), 65535);
568 this.nextthink = time + 5;
572 void RandomSeed_Spawn()
574 randomseed = new_pure(randomseed);
575 setthink(randomseed, RandomSeed_Think);
576 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
578 getthink(randomseed)(randomseed); // sets random seed and nextthink
581 spawnfunc(__init_dedicated_server)
583 // handler for _init/_init map (only for dedicated server initialization)
585 world_initialized = -1; // don't complain
587 delete_fn = remove_unsafely;
590 setthink(e, GotoFirstMap);
591 e.nextthink = time; // this is usually 1 at this point
593 e = new(info_player_deathmatch); // safeguard against player joining
595 // assign reflectively to avoid "assignment to world" warning
596 for (int i = 0, n = numentityfields(); i < n; ++i) {
597 string k = entityfieldname(i);
598 if (k == "classname") {
599 // safeguard against various stuff ;)
600 putentityfieldstring(i, this, "worldspawn");
605 // needs to be done so early because of the constants they create
608 static_init_precache();
610 IL_PUSH(g_spawnpoints, e); // just incase
613 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
616 void __init_dedicated_server_shutdown() {
620 STATIC_INIT_EARLY(maxclients)
623 for (entity head = nextent(NULL); head; head = nextent(head)) {
628 void default_delayedinit(entity this)
630 if(!scores_initialized)
631 ScoreRules_generic();
634 void InitGameplayMode()
638 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
640 // assign reflectively to avoid "assignment to world" warning
641 int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
642 string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
644 putentityfieldstring(i, world, sprintf("%v", v));
645 if (++done == 2) break;
648 // currently, NetRadiant's limit is 131072 qu for each side
649 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
650 // set the distance according to map size but don't go over the limit to avoid issues with float precision
651 // in case somebody makes extremely large maps
652 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
654 MapInfo_LoadMapSettings(mapname);
655 GameRules_teams(false);
657 if (!cvar_value_issafe(world.fog))
659 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
660 world.fog = string_null;
662 if(MapInfo_Map_fog != "")
664 if(MapInfo_Map_fog == "none")
665 world.fog = string_null;
667 world.fog = strzone(MapInfo_Map_fog);
669 clientstuff = strzone(MapInfo_Map_clientstuff);
671 MapInfo_ClearTemps();
673 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
675 cache_mutatormsg = strzone("");
676 cache_lastmutatormsg = strzone("");
678 InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
681 void Map_MarkAsRecent(string m);
682 float world_already_spawned;
683 spawnfunc(worldspawn)
685 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
687 bool wantrestart = false;
689 if (!server_is_dedicated)
691 // force unloading of server pk3 files when starting a listen server
692 // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
693 // restore csqc_progname too
694 string expect = "csprogs.dat";
695 wantrestart = cvar_string("csqc_progname") != expect;
696 cvar_set("csqc_progname", expect);
700 // Try to use versioned csprogs from pk3
701 // Only ever use versioned csprogs.dat files on dedicated servers;
702 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
703 string pk3csprogs = "csprogs-" WATERMARK ".dat";
704 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
705 string select = "csprogs.dat";
706 if (fexists(pk3csprogs)) select = pk3csprogs;
707 if (cvar_string("csqc_progname") != select)
709 cvar_set("csqc_progname", select);
712 // Check for updates on startup
713 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
714 int sentinel = fopen("progs.txt", FILE_READ);
717 string switchversion = fgets(sentinel);
719 if (switchversion != "" && switchversion != WATERMARK)
721 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
722 // if it doesn't exist, assume either:
723 // a) the current program was overwritten
724 // b) this is a client only update
725 string newprogs = sprintf("progs-%s.dat", switchversion);
726 if (fexists(newprogs))
728 cvar_set("sv_progs", newprogs);
731 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
732 if (fexists(newcsprogs))
734 cvar_set("csqc_progname", newcsprogs);
742 LOG_INFO("Restart requested");
743 changelevel(mapname);
744 // let initialization continue, shutdown depends on it
748 if(world_already_spawned)
749 error("world already spawned - you may have EXACTLY ONE worldspawn!");
750 world_already_spawned = true;
752 delete_fn = remove_safely; // during spawning, watch what you remove!
754 cvar_changes_init(); // do this very early now so it REALLY matches the server config
756 // needs to be done so early because of the constants they create
759 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
761 TemporaryDB = db_create();
766 // 1 FLICKER (first variety)
767 lightstyle(1, "mmnmmommommnonmmonqnmmo");
769 // 2 SLOW STRONG PULSE
770 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
772 // 3 CANDLE (first variety)
773 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
776 lightstyle(4, "mamamamamama");
779 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
781 // 6 FLICKER (second variety)
782 lightstyle(6, "nmonqnmomnmomomno");
784 // 7 CANDLE (second variety)
785 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
787 // 8 CANDLE (third variety)
788 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
790 // 9 SLOW STROBE (fourth variety)
791 lightstyle(9, "aaaaaaaazzzzzzzz");
793 // 10 FLUORESCENT FLICKER
794 lightstyle(10, "mmamammmmammamamaaamammma");
796 // 11 SLOW PULSE NOT FADE TO BLACK
797 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
799 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
804 if(autocvar_g_campaign)
807 Map_MarkAsRecent(mapname);
809 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
813 static_init_precache();
817 GameRules_limit_fallbacks();
819 if(warmup_limit == 0)
820 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
823 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
824 if(bot_waypoints_for_items == 1)
825 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
826 bot_waypoints_for_items = 0;
828 WaypointSprite_Init();
830 GameLogInit(); // prepare everything
832 // changing the logic generating it is okay. But:
833 // it HAS to stay <= 64 chars
834 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
835 if(autocvar_sv_eventlog)
837 string s = sprintf("%s.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
838 matchid = strzone(s);
840 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
841 s = ":gameinfo:mutators:LIST";
843 MUTATOR_CALLHOOK(BuildMutatorsString, s);
844 s = M_ARGV(0, string);
846 // initialiation stuff, not good in the mutator system
847 if(!autocvar_g_use_ammunition)
848 s = strcat(s, ":no_use_ammunition");
850 // initialiation stuff, not good in the mutator system
851 if(autocvar_g_pickup_items == 0)
852 s = strcat(s, ":no_pickup_items");
853 if(autocvar_g_pickup_items > 0)
854 s = strcat(s, ":pickup_items");
856 // initialiation stuff, not good in the mutator system
857 if(autocvar_g_weaponarena != "0")
858 s = strcat(s, ":", autocvar_g_weaponarena, " arena");
860 // TODO to mutator system
861 if(autocvar_g_norecoil)
862 s = strcat(s, ":norecoil");
864 // TODO to mutator system
865 if(autocvar_g_powerups == 0)
866 s = strcat(s, ":no_powerups");
867 if(autocvar_g_powerups > 0)
868 s = strcat(s, ":powerups");
871 GameLogEcho(":gameinfo:end");
874 matchid = strzone(ftos(random()));
876 cvar_set("nextmap", "");
880 if(autocvar_g_campaign)
886 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
888 if(fexists(strcat("scripts/", mapname, ".arena")))
889 cvar_settemp("sv_q3acompat_machineshotgunswap", "1");
891 if(fexists(strcat("scripts/", mapname, ".defi")))
892 cvar_settemp("sv_q3defragcompat", "1");
894 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
896 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
900 while((s = fgets(fd)))
902 int l = tokenize_console(s);
907 string trackname = argv(2);
908 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
909 LOG_INFO(" cdtrack ", trackname);
910 if (cvar_value_issafe(trackname))
912 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
913 strcpy(clientstuff, newstuff);
916 else if(argv(0) == "fog")
918 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
919 LOG_INFO(" \"fog\" \"", s, "\"");
921 else if(argv(0) == "set")
923 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
924 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
926 else if(argv(0) != "//")
928 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
929 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
940 // set up information replies for clients and server to use
941 maplist_reply = strzone(getmaplist());
942 lsmaps_reply = strzone(getlsmaps());
943 monsterlist_reply = strzone(getmonsterlist());
944 for(int i = 0; i < 10; ++i)
946 string s = getrecords(i);
948 records_reply[i] = strzone(s);
950 ladder_reply = strzone(getladder());
951 rankings_reply = strzone(getrankings());
956 PingPLReport_Spawn();
960 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
962 // fill sv_curl_serverpackages from .serverpackage files
963 if (autocvar_sv_curl_serverpackages_auto)
965 string s = "csprogs-" WATERMARK ".txt";
966 // remove automatically managed files from the list to prevent duplicates
967 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
969 string pkg = argv(i);
970 if (startsWith(pkg, "csprogs-")) continue;
971 if (endsWith(pkg, "-serverpackage.txt")) continue;
972 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
975 // add automatically managed files to the list
976 #define X(match) MACRO_BEGIN \
977 int fd = search_begin(match, true, false); \
980 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
982 s = cons(s, search_getfilename(fd, i)); \
987 X("*-serverpackage.txt");
988 X("*.serverpackage");
990 cvar_set("sv_curl_serverpackages", s);
993 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
995 // physics/balance/config changes that count as mod
996 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
997 modname = cvar_string("g_mod_physics");
998 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
999 modname = cvar_string("g_mod_balance");
1000 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1001 modname = cvar_string("g_mod_config");
1002 // extra mutators that deserve to count as mod
1003 MUTATOR_CALLHOOK(SetModname, modname);
1004 modname = M_ARGV(0, string);
1006 // save it for later
1007 modname = strzone(modname);
1009 WinningConditionHelper(this); // set worldstatus
1011 world_initialized = 1;
1012 __spawnfunc_spawn_all();
1017 //makestatic (this); // Who the f___ did that?
1021 string GetGametype()
1023 return MapInfo_Type_ToString(MapInfo_LoadedGametype);
1031 float Map_Count, Map_Current;
1032 string Map_Current_Name;
1034 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
1035 int GetMaplistPosition()
1037 string map = GetMapname();
1038 int idx = autocvar_g_maplist_index;
1044 if(map == argv(idx))
1051 for(int pos = 0; pos < Map_Count; ++pos)
1053 if(map == argv(pos))
1057 // resume normal maplist rotation if current map is not in g_maplist
1061 bool MapHasRightSize(string map)
1063 int minplayers = max(0, floor(autocvar_minplayers));
1065 minplayers = max(0, floor(autocvar_minplayers_per_team) * AvailableTeams());
1066 if (autocvar_g_maplist_check_waypoints
1067 && (currentbots || autocvar_bot_number || player_count < minplayers))
1069 string checkwp_msg = strcat("checkwp ", map);
1070 if(!fexists(strcat("maps/", map, ".waypoints")))
1072 LOG_TRACE(checkwp_msg, ": no waypoints");
1075 LOG_TRACE(checkwp_msg, ": has waypoints");
1078 if(autocvar_g_maplist_ignore_sizes)
1081 // open map size restriction file
1082 string opensize_msg = strcat("opensize ", map);
1083 float fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1084 int player_limit = ((autocvar_g_maplist_sizes_count_maxplayers) ? GetPlayerLimit() : 0);
1085 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
1086 if(!autocvar_g_maplist_sizes_count_bots)
1087 pcount -= currentbots;
1090 opensize_msg = strcat(opensize_msg, ": ok, ");
1091 int mapmin = stoi(fgets(fh));
1092 int mapmax = stoi(fgets(fh));
1096 LOG_TRACE(opensize_msg, "not enough");
1099 if(mapmax && pcount > mapmax)
1101 LOG_TRACE(opensize_msg, "too many");
1104 LOG_TRACE(opensize_msg, "right size");
1107 LOG_TRACE(opensize_msg, ": not found");
1111 string Map_Filename(float position)
1113 return strcat("maps/", argv(position), ".bsp");
1116 void Map_MarkAsRecent(string m)
1118 cvar_set("g_maplist_mostrecent", strwords(cons(m, autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1121 float Map_IsRecent(string m)
1123 return strhasword(autocvar_g_maplist_mostrecent, m);
1126 float Map_Check(float position, float pass)
1130 map_next = argv(position);
1133 if(Map_IsRecent(map_next))
1136 filename = Map_Filename(position);
1137 if(MapInfo_CheckMap(map_next))
1141 if(MapHasRightSize(map_next))
1146 LOG_DEBUG( "Couldn't select '", filename, "'..." );
1151 void Map_Goto_SetStr(string nextmapname)
1153 if(getmapname_stored != "")
1154 strunzone(getmapname_stored);
1155 if(nextmapname == "")
1156 getmapname_stored = "";
1158 getmapname_stored = strzone(nextmapname);
1161 void Map_Goto_SetFloat(float position)
1163 cvar_set("g_maplist_index", ftos(position));
1164 Map_Goto_SetStr(argv(position));
1167 void Map_Goto(float reinit)
1169 MapInfo_LoadMap(getmapname_stored, reinit);
1172 // return codes of map selectors:
1173 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1174 // -2 = permanent failure
1175 float MaplistMethod_Iterate() // usual method
1179 LOG_TRACE("Trying MaplistMethod_Iterate");
1181 for(pass = 1; pass <= 2; ++pass)
1183 for(i = 1; i < Map_Count; ++i)
1186 mapindex = (i + Map_Current) % Map_Count;
1187 if(Map_Check(mapindex, pass))
1194 float MaplistMethod_Repeat() // fallback method
1196 LOG_TRACE("Trying MaplistMethod_Repeat");
1198 if(Map_Check(Map_Current, 2))
1203 float MaplistMethod_Random() // random map selection
1207 LOG_TRACE("Trying MaplistMethod_Random");
1211 for(i = 0; i <= imax; ++i)
1214 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1215 if(Map_Check(mapindex, 1))
1221 float MaplistMethod_Shuffle(float exponent) // more clever shuffling
1222 // the exponent sets a bias on the map selection:
1223 // the higher the exponent, the less likely "shortly repeated" same maps are
1225 float i, j, imax, insertpos;
1227 LOG_TRACE("Trying MaplistMethod_Shuffle");
1231 for(i = 0; i <= imax; ++i)
1235 // now reinsert this at another position
1236 insertpos = (random() ** (1 / exponent)); // ]0, 1]
1237 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
1238 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
1239 LOG_TRACE("SHUFFLE: insert pos = ", ftos(insertpos));
1241 // insert the current map there
1243 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1244 newlist = strcat(newlist, " ", argv(j));
1245 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
1246 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
1247 newlist = strcat(newlist, " ", argv(j));
1248 newlist = substring(newlist, 1, strlen(newlist) - 1);
1249 cvar_set("g_maplist", newlist);
1250 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1252 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1253 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1254 if(Map_Check(Map_Current, 1))
1262 float i = Map_Count = 0;
1263 if(autocvar_g_maplist != "")
1265 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1266 for (i = 0; i < Map_Count; ++i)
1268 if (Map_Check(i, 2))
1275 bprint( "Maplist contains no usable maps! Resetting it to default map list.\n" );
1276 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1277 if(autocvar_g_maplist_shuffle)
1279 if(!server_is_dedicated)
1280 localcmd("\nmenu_cmd sync\n");
1281 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1284 error("empty maplist, cannot select a new map");
1285 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1287 strcpy(Map_Current_Name, argv(Map_Current)); // will be automatically freed on exit thanks to DP
1288 // this may or may not be correct, but who cares, in the worst case a map
1289 // isn't chosen in the first pass that should have been
1298 if(autocvar_g_maplist_shuffle > 0)
1299 nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1302 if(autocvar_g_maplist_selectrandom)
1303 nextMap = MaplistMethod_Random();
1306 nextMap = MaplistMethod_Iterate();
1309 nextMap = MaplistMethod_Repeat();
1313 Map_Goto_SetFloat(nextMap);
1314 return getmapname_stored;
1320 float DoNextMapOverride(float reinit)
1322 if(autocvar_g_campaign)
1324 CampaignPostIntermission();
1325 alreadychangedlevel = true;
1328 if(autocvar_quit_when_empty)
1330 if(player_count <= currentbots)
1333 alreadychangedlevel = true;
1337 if(autocvar_quit_and_redirect != "")
1339 redirection_target = strzone(autocvar_quit_and_redirect);
1340 alreadychangedlevel = true;
1343 if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1345 localcmd("restart\n");
1346 alreadychangedlevel = true;
1349 if(autocvar_nextmap != "")
1352 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1353 cvar_set("nextmap",m);
1355 if(!m || gametypevote)
1357 if(autocvar_sv_vote_gametype)
1363 if(MapInfo_CheckMap(m))
1367 alreadychangedlevel = true;
1371 if(!reinit && autocvar_lastlevel)
1373 cvar_settemp_restore();
1374 localcmd("set lastlevel 0\ntogglemenu 1\n");
1375 alreadychangedlevel = true;
1381 void GotoNextMap(float reinit)
1386 if (alreadychangedlevel)
1388 alreadychangedlevel = true;
1390 string nextMap = GetNextMap();
1392 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1401 When the player presses attack or jump, change to the next level
1404 .float autoscreenshot;
1405 void IntermissionThink(entity this)
1407 FixIntermissionClient(this);
1409 float server_screenshot = (autocvar_sv_autoscreenshot && CS(this).cvar_cl_autoscreenshot);
1410 float client_screenshot = (CS(this).cvar_cl_autoscreenshot == 2);
1412 if( (server_screenshot || client_screenshot)
1413 && ((this.autoscreenshot > 0) && (time > this.autoscreenshot)) )
1415 this.autoscreenshot = -1;
1416 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"))); }
1420 if (time < intermission_exittime)
1423 if(!mapvote_initialized)
1424 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)))
1431 ===============================================================================
1435 ===============================================================================
1438 void DumpStats(float final)
1447 to_console = autocvar_sv_logscores_console;
1448 to_eventlog = autocvar_sv_eventlog;
1449 to_file = autocvar_sv_logscores_file;
1453 to_console = true; // always print printstats replies
1454 to_eventlog = false; // but never print them to the event log
1458 if(autocvar_sv_eventlog_console)
1459 to_console = false; // otherwise we get the output twice
1465 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1475 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1479 fputs(file, strcat(s, "\n"));
1482 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1488 fputs(file, strcat(s, "\n"));
1490 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1491 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1492 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1493 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1494 s = strcat(s, ftos(it.team), ":");
1496 s = strcat(s, "spectator:");
1499 LOG_INFO(s, playername(it, false));
1501 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it, false)));
1503 fputs(file, strcat(s, playername(it, false), "\n"));
1508 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1514 fputs(file, strcat(s, "\n"));
1516 for(i = 1; i < 16; ++i)
1518 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1519 s = strcat(s, ":", ftos(i));
1525 fputs(file, strcat(s, "\n"));
1532 GameLogEcho(":end");
1535 fputs(file, ":end\n");
1540 void FixIntermissionClient(entity e)
1542 if(!e.autoscreenshot) // initial call
1544 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1545 SetResourceExplicit(e, RES_HEALTH, -2342);
1546 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1547 for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1549 .entity weaponentity = weaponentities[slot];
1550 if(e.(weaponentity))
1552 e.(weaponentity).effects = EF_NODRAW;
1553 if (e.(weaponentity).weaponchild)
1554 e.(weaponentity).weaponchild.effects = EF_NODRAW;
1557 if(IS_REAL_CLIENT(e))
1559 stuffcmd(e, "\nscr_printspeed 1000000\n");
1560 RandomSelection_Init();
1561 FOREACH_WORD(autocvar_sv_intermission_cdtrack, true, {
1562 RandomSelection_AddString(it, 1, 1);
1564 if (RandomSelection_chosen_string != "")
1566 stuffcmd(e, sprintf("\ncd loop %s\n", RandomSelection_chosen_string));
1569 WriteByte(MSG_ONE, SVC_INTERMISSION);
1575 go to the next level for deathmatch
1576 only called if a time or frag limit has expired
1580 game_stopped = true;
1581 intermission_running = 1; // game over
1583 // enforce a wait time before allowing changelevel
1584 if(player_count > 0)
1585 intermission_exittime = time + autocvar_sv_mapchange_delay;
1587 intermission_exittime = -1;
1590 WriteByte (MSG_ALL, SVC_CDTRACK);
1591 WriteByte (MSG_ALL, 3);
1592 WriteByte (MSG_ALL, 3);
1593 // done in FixIntermission
1596 //pos = FindIntermission ();
1603 PlayerStats_GameReport(true);
1604 WeaponStats_Shutdown();
1606 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1608 if(autocvar_sv_eventlog)
1609 GameLogEcho(":gameover");
1613 FOREACH_CLIENT(IS_PLAYER(it), {
1614 FixIntermissionClient(it);
1616 bprint(playername(it, false), " ^7wins.\n");
1619 target_music_kill();
1621 if(autocvar_g_campaign)
1622 CampaignPreIntermission();
1624 MUTATOR_CALLHOOK(MatchEnd);
1626 localcmd("\nsv_hook_gameend\n");
1630 float InitiateSuddenDeath()
1632 // Check first whether normal overtimes could be added before initiating suddendeath mode
1633 // - for this timelimit_overtime needs to be >0 of course
1634 // - also check the winning condition calculated in the previous frame and only add normal overtime
1635 // again, if at the point at which timelimit would be extended again, still no winner was found
1636 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1637 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1638 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1640 return 1; // need to call InitiateOvertime later
1644 if(!checkrules_suddendeathend)
1646 if(autocvar_g_campaign)
1647 checkrules_suddendeathend = time; // no suddendeath in campaign
1649 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1650 if(g_race && !g_race_qualifying)
1651 race_StartCompleting();
1657 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1659 ++checkrules_overtimesadded;
1660 //add one more overtime by simply extending the timelimit
1661 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1662 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1665 float GetWinningCode(float fraglimitreached, float equality)
1667 if(autocvar_g_campaign == 1)
1669 if(fraglimitreached)
1678 if(fraglimitreached)
1679 return WINNING_STARTSUDDENDEATHOVERTIME;
1681 return WINNING_NEVER;
1685 if(fraglimitreached)
1693 // set the .winning flag for exactly those players with a given field value
1694 void SetWinners(.float field, float value)
1696 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = (it.(field) == value); });
1699 // set the .winning flag for those players with a given field value
1700 void AddWinners(.float field, float value)
1702 FOREACH_CLIENT(IS_PLAYER(it), {
1703 if(it.(field) == value)
1708 // clear the .winning flags
1711 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = 0; });
1714 void ShuffleMaplist()
1716 cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1720 float WinningCondition_Scores(float limit, float leadlimit)
1722 // TODO make everything use THIS winning condition (except LMS)
1723 WinningConditionHelper(NULL);
1727 for (int i = 1; i < 5; ++i)
1729 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1730 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1735 if(WinningConditionHelper_winner)
1736 WinningConditionHelper_winner.winning = 1;
1737 if(WinningConditionHelper_winnerteam >= 0)
1738 SetWinners(team, WinningConditionHelper_winnerteam);
1740 if(WinningConditionHelper_lowerisbetter)
1742 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1743 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1747 if(WinningConditionHelper_zeroisworst)
1748 leadlimit = 0; // not supported in this mode
1750 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1753 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1759 fragsleft = FLOAT_MAX;
1760 float leadingfragsleft = FLOAT_MAX;
1762 fragsleft = limit - WinningConditionHelper_topscore;
1764 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1766 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1767 fragsleft = max(fragsleft, leadingfragsleft);
1769 fragsleft = min(fragsleft, leadingfragsleft);
1772 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1775 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1776 else if (fragsleft == 2)
1777 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1778 else if (fragsleft == 3)
1779 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1781 fragsleft_last = fragsleft;
1785 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1786 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1789 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1790 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1791 limit_reached = (fraglimit_reached && leadlimit_reached);
1793 limit_reached = (fraglimit_reached || leadlimit_reached);
1795 return GetWinningCode(
1796 WinningConditionHelper_topscore && limit_reached,
1797 WinningConditionHelper_equality
1801 float WinningCondition_RanOutOfSpawns()
1803 if(have_team_spawns <= 0)
1806 if(!autocvar_g_spawn_useallspawns)
1809 if(!some_spawn_has_been_used)
1812 for (int i = 1; i < 5; ++i)
1814 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1817 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1819 if (Team_IsValidTeam(it.team))
1821 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1825 IL_EACH(g_spawnpoints, true,
1827 if (Team_IsValidTeam(it.team))
1829 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1834 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1835 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1836 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1837 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1838 if(team1_score + team2_score + team3_score + team4_score == 0)
1840 checkrules_equality = true;
1843 else if(team1_score + team2_score + team3_score + team4_score == 1)
1848 else if(team2_score)
1850 else if(team3_score)
1852 else // if(team4_score)
1854 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1855 for(i = 0; i < MAX_TEAMSCORE; ++i)
1857 for (int j = 1; j <= NUM_TEAMS; ++j)
1863 if (!TeamBalance_IsTeamAllowed(balance, j))
1867 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1871 AddWinners(team, t);
1882 Exit deathmatch games upon conditions
1885 void CheckRules_World()
1892 if (intermission_running) // someone else quit the game already
1894 if(player_count == 0) // Nobody there? Then let's go to the next map
1896 // this will actually check the player count in the next frame
1897 // again, but this shouldn't hurt
1901 float timelimit = autocvar_timelimit * 60;
1902 float fraglimit = autocvar_fraglimit;
1903 float leadlimit = autocvar_leadlimit;
1904 if (leadlimit < 0) leadlimit = 0;
1906 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1909 timelimit = 0; // timelimit is not made for warmup
1911 fraglimit = 0; // no fraglimit for now
1912 leadlimit = 0; // no leadlimit for now
1917 timelimit += game_starttime;
1919 else if (timelimit < 0)
1929 if(checkrules_suddendeathend)
1931 if(!checkrules_suddendeathwarning)
1933 checkrules_suddendeathwarning = true;
1934 if(g_race && !g_race_qualifying)
1935 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1937 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1942 if (timelimit && time >= timelimit)
1944 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1947 float playerswithlaps;
1949 totalplayers = playerswithlaps = readyplayers = 0;
1950 FOREACH_CLIENT(IS_PLAYER(it), {
1952 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1958 // at least 2 of the players have completed a lap: start the RACE
1959 // otherwise, the players should end the qualifying on their own
1960 if(readyplayers || playerswithlaps >= 2)
1962 checkrules_suddendeathend = 0;
1963 ReadyRestart(); // go to race
1967 wantovertime |= InitiateSuddenDeath();
1970 wantovertime |= InitiateSuddenDeath();
1974 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1980 int checkrules_status = WinningCondition_RanOutOfSpawns();
1981 if(checkrules_status == WINNING_YES)
1982 bprint("Hey! Someone ran out of spawns!\n");
1983 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1984 checkrules_status = M_ARGV(0, float);
1986 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1988 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1990 checkrules_status = WINNING_NEVER;
1991 checkrules_overtimesadded = -1;
1992 wantovertime |= InitiateSuddenDeath();
1995 if(checkrules_status == WINNING_NEVER)
1996 // equality cases! Nobody wins if the overtime ends in a draw.
2001 if(checkrules_status == WINNING_NEVER)
2004 checkrules_status = WINNING_YES;
2007 if(checkrules_suddendeathend)
2008 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2009 checkrules_status = WINNING_YES;
2011 if(checkrules_status == WINNING_YES)
2013 //print("WINNING\n");
2018 string GotoMap(string m)
2020 m = GameTypeVote_MapInfo_FixName(m);
2022 return "The map you suggested is not available on this server.";
2023 if (!autocvar_sv_vote_gametype)
2024 if(!MapInfo_CheckMap(m))
2025 return "The map you suggested does not support the current game mode.";
2026 cvar_set("nextmap", m);
2027 cvar_set("timelimit", "-1");
2028 if(mapvote_initialized || alreadychangedlevel)
2030 if(DoNextMapOverride(0))
2031 return "Map switch initiated.";
2033 return "Hm... no. For some reason I like THIS map more.";
2036 return "Map switch will happen after scoreboard.";
2039 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2040 void RunThink(entity this)
2042 // don't let things stay in the past.
2043 // it is possible to start that way by a trigger with a local time.
2044 if(this.nextthink <= 0 || this.nextthink > time + frametime)
2047 float oldtime = time; // do we need to save this?
2049 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2051 time = max(oldtime, this.nextthink);
2055 getthink(this)(this);
2056 // mods often set nextthink to time to cause a think every frame,
2057 // we don't want to loop in that case, so exit if the new nextthink is
2058 // <= the time the qc was told, also exit if it is past the end of the
2060 if(this.nextthink <= time || this.nextthink > oldtime + frametime || !autocvar_sv_gameplayfix_multiplethinksperframe)
2067 bool autocvar_sv_freezenonclients;
2068 bool autocvar_sv_gameplayfix_delayprojectiles = false;
2069 void Physics_Frame()
2071 if(autocvar_sv_freezenonclients)
2074 IL_EACH(g_moveables, true,
2076 if(IS_CLIENT(it) || it.classname == "" || it.move_movetype == MOVETYPE_PHYSICS)
2079 //set_movetype(it, it.move_movetype);
2080 // inline the set_movetype function, since this is called a lot
2081 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2083 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2084 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2086 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2088 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2089 continue; // these movetypes have no regular think function
2090 // handle thinking here
2091 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + frametime)
2096 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2099 IL_EACH(g_moveables, it.move_qcphysics,
2101 if(IS_CLIENT(it) || it.classname == "" || it.move_movetype == MOVETYPE_NONE)
2103 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2107 void systems_update();
2110 anticheat_endframe();
2114 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2115 entity e = IS_SPEC(it) ? it.enemy : it;
2116 if (e.typehitsound) {
2117 STAT(TYPEHIT_TIME, it) = time;
2118 } else if (e.killsound) {
2119 STAT(KILL_TIME, it) = time;
2120 } else if (e.damage_dealt) {
2121 STAT(HIT_TIME, it) = time;
2122 STAT(DAMAGE_DEALT_TOTAL, it) += ceil(e.damage_dealt);
2125 // add 1 frametime because after this, engine SV_Physics
2126 // increases time by a frametime and then networks the frame
2127 // add another frametime because client shows everything with
2128 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2130 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2131 FOREACH_CLIENT(true, {
2132 it.typehitsound = false;
2133 it.damage_dealt = 0;
2134 it.killsound = false;
2135 antilag_record(it, CS(it), altime);
2137 IL_EACH(g_monsters, true,
2139 antilag_record(it, it, altime);
2141 IL_EACH(g_projectiles, it.classname == "nade",
2143 antilag_record(it, it, altime);
2152 * returns true if redirecting
2154 float redirection_timeout;
2155 float redirection_nextthink;
2156 float RedirectionThink()
2158 float clients_found;
2160 if(redirection_target == "")
2163 if(!redirection_timeout)
2165 cvar_set("sv_public", "-2");
2166 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2167 if(redirection_target == "self")
2168 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2170 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2173 if(time < redirection_nextthink)
2176 redirection_nextthink = time + 1;
2179 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2181 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2182 if(redirection_target == "self")
2183 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2185 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2189 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2191 if(time > redirection_timeout || clients_found == 0)
2192 localcmd("\nwait; wait; wait; quit\n");
2199 // Loaded from a save game
2200 // some things then break, so let's work around them...
2202 // Progs DB (capture records)
2203 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2207 MapInfo_Enumerate();
2208 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2211 TargetMusic_RestoreGame();
2218 if(world_initialized > 0)
2220 world_initialized = 0;
2222 // if a timeout is active, reset the slowmo value to normal
2223 if(timeout_status == TIMEOUT_ACTIVE)
2224 cvar_set("slowmo", ftos(orig_slowmo));
2226 LOG_TRACE("Saving persistent data...");
2229 // playerstats with unfinished match
2230 PlayerStats_GameReport(false);
2232 if(!cheatcount_total)
2234 if(autocvar_sv_db_saveasdump)
2235 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2237 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2239 if(autocvar_developer > 0)
2241 if(autocvar_sv_db_saveasdump)
2242 db_dump(TemporaryDB, "server-temp.db");
2244 db_save(TemporaryDB, "server-temp.db");
2246 CheatShutdown(); // must be after cheatcount check
2247 db_close(ServerProgsDB);
2248 db_close(TemporaryDB);
2249 LOG_TRACE("Saving persistent data... done!");
2250 // tell the bot system the game is ending now
2253 WeaponStats_Shutdown();
2256 else if(world_initialized == 0)
2258 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2262 __init_dedicated_server_shutdown();