Set groundentity when sv_gameplayfix_downtracesupportsongroundflag detects a floor
[xonotic/darkplaces.git] / sv_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sv_main.c -- server main program
21
22 #include "quakedef.h"
23 #include "sv_demo.h"
24 #include "libcurl.h"
25 #include "csprogs.h"
26 #include "thread.h"
27
28 // current client
29 client_t *host_client;
30
31 static void SV_SaveEntFile_f(cmd_state_t *cmd);
32 static void SV_StartDownload_f(cmd_state_t *cmd);
33 static void SV_Download_f(cmd_state_t *cmd);
34 static void SV_VM_Setup(void);
35 extern cvar_t net_connecttimeout;
36
37 cvar_t sv_worldmessage = {CF_SERVER | CF_READONLY, "sv_worldmessage", "", "title of current level"};
38 cvar_t sv_worldname = {CF_SERVER | CF_READONLY, "sv_worldname", "", "name of current worldmodel"};
39 cvar_t sv_worldnamenoextension = {CF_SERVER | CF_READONLY, "sv_worldnamenoextension", "", "name of current worldmodel without extension"};
40 cvar_t sv_worldbasename = {CF_SERVER | CF_READONLY, "sv_worldbasename", "", "name of current worldmodel without maps/ prefix or extension"};
41
42 cvar_t sv_disablenotify = {CF_SERVER, "sv_disablenotify", "0", "suppress broadcast prints when certain cvars are changed (CF_NOTIFY flag in engine code)"};
43 cvar_t coop = {CF_SERVER, "coop","0", "coop mode, 0 = no coop, 1 = coop mode, multiple players playing through the singleplayer game (coop mode also shuts off deathmatch)"};
44 cvar_t deathmatch = {CF_SERVER, "deathmatch","0", "deathmatch mode, values depend on mod but typically 0 = no deathmatch, 1 = normal deathmatch with respawning weapons, 2 = weapons stay (players can only pick up new weapons)"};
45 cvar_t fraglimit = {CF_SERVER | CF_NOTIFY, "fraglimit","0", "ends level if this many frags is reached by any player"};
46 cvar_t gamecfg = {CF_SERVER, "gamecfg", "0", "unused cvar in quake, can be used by mods"};
47 cvar_t noexit = {CF_SERVER | CF_NOTIFY, "noexit","0", "kills anyone attempting to use an exit"};
48 cvar_t nomonsters = {CF_SERVER, "nomonsters", "0", "unused cvar in quake, can be used by mods"};
49 cvar_t pausable = {CF_SERVER, "pausable","1", "allow players to pause or not (otherwise, only the server admin can)"};
50 cvar_t pr_checkextension = {CF_SERVER | CF_READONLY, "pr_checkextension", "1", "indicates to QuakeC that the standard quakec extensions system is available (if 0, quakec should not attempt to use extensions)"};
51 cvar_t samelevel = {CF_SERVER | CF_NOTIFY, "samelevel","0", "repeats same level if level ends (due to timelimit or someone hitting an exit)"};
52 cvar_t skill = {CF_SERVER, "skill","1", "difficulty level of game, affects monster layouts in levels, 0 = easy, 1 = normal, 2 = hard, 3 = nightmare (same layout as hard but monsters fire twice)"};
53 cvar_t campaign = {CF_SERVER, "campaign", "0", "singleplayer mode"};
54 cvar_t host_timescale = {CF_CLIENT | CF_SERVER, "host_timescale", "1.0", "controls game speed, 0.5 is half speed, 2 is double speed"};
55
56 cvar_t sv_accelerate = {CF_SERVER, "sv_accelerate", "10", "rate at which a player accelerates to sv_maxspeed"};
57 cvar_t sv_aim = {CF_SERVER | CF_ARCHIVE, "sv_aim", "2", "maximum cosine angle for quake's vertical autoaim, a value above 1 completely disables the autoaim, quake used 0.93"};
58 cvar_t sv_airaccel_qw = {CF_SERVER, "sv_airaccel_qw", "1", "ratio of QW-style air control as opposed to simple acceleration; when < 0, the speed is clamped against the maximum allowed forward speed after the move"};
59 cvar_t sv_airaccel_qw_stretchfactor = {CF_SERVER, "sv_airaccel_qw_stretchfactor", "0", "when set, the maximum acceleration increase the player may get compared to forward-acceleration when strafejumping"};
60 cvar_t sv_airaccel_sideways_friction = {CF_SERVER, "sv_airaccel_sideways_friction", "", "anti-sideways movement stabilization (reduces speed gain when zigzagging); when < 0, only so much friction is applied that braking (by accelerating backwards) cannot be stronger"};
61 cvar_t sv_airaccelerate = {CF_SERVER, "sv_airaccelerate", "-1", "rate at which a player accelerates to sv_maxairspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
62 cvar_t sv_airstopaccelerate = {CF_SERVER, "sv_airstopaccelerate", "0", "when set, replacement for sv_airaccelerate when moving backwards"};
63 cvar_t sv_airspeedlimit_nonqw = {CF_SERVER, "sv_airspeedlimit_nonqw", "0", "when set, this is a soft speed limit while in air when using airaccel_qw not equal to 1"};
64 cvar_t sv_airstrafeaccelerate = {CF_SERVER, "sv_airstrafeaccelerate", "0", "when set, replacement for sv_airaccelerate when just strafing"};
65 cvar_t sv_maxairstrafespeed = {CF_SERVER, "sv_maxairstrafespeed", "0", "when set, replacement for sv_maxairspeed when just strafing"};
66 cvar_t sv_airstrafeaccel_qw = {CF_SERVER, "sv_airstrafeaccel_qw", "0", "when set, replacement for sv_airaccel_qw when just strafing"};
67 cvar_t sv_aircontrol = {CF_SERVER, "sv_aircontrol", "0", "CPMA-style air control"};
68 cvar_t sv_aircontrol_power = {CF_SERVER, "sv_aircontrol_power", "2", "CPMA-style air control exponent"};
69 cvar_t sv_aircontrol_penalty = {CF_SERVER, "sv_aircontrol_penalty", "0", "deceleration while using CPMA-style air control"};
70 cvar_t sv_allowdownloads = {CF_SERVER, "sv_allowdownloads", "1", "whether to allow clients to download files from the server (does not affect http downloads)"};
71 cvar_t sv_allowdownloads_archive = {CF_SERVER, "sv_allowdownloads_archive", "0", "whether to allow downloads of archives (pak/pk3)"};
72 cvar_t sv_allowdownloads_config = {CF_SERVER, "sv_allowdownloads_config", "0", "whether to allow downloads of config files (cfg)"};
73 cvar_t sv_allowdownloads_dlcache = {CF_SERVER, "sv_allowdownloads_dlcache", "0", "whether to allow downloads of dlcache files (dlcache/)"};
74 cvar_t sv_allowdownloads_inarchive = {CF_SERVER, "sv_allowdownloads_inarchive", "0", "whether to allow downloads from archives (pak/pk3)"};
75 cvar_t sv_areagrid_mingridsize = {CF_SERVER | CF_NOTIFY, "sv_areagrid_mingridsize", "128", "minimum areagrid cell size, smaller values work better for lots of small objects, higher values for large objects"};
76 cvar_t sv_checkforpacketsduringsleep = {CF_SERVER, "sv_checkforpacketsduringsleep", "0", "uses select() function to wait between frames which can be interrupted by packets being received, instead of Sleep()/usleep()/SDL_Sleep() functions which do not check for packets"};
77 cvar_t sv_clmovement_enable = {CF_SERVER, "sv_clmovement_enable", "1", "whether to allow clients to use cl_movement prediction, which can cause choppy movement on the server which may annoy other players"};
78 cvar_t sv_clmovement_minping = {CF_SERVER, "sv_clmovement_minping", "0", "if client ping is below this time in milliseconds, then their ability to use cl_movement prediction is disabled for a while (as they don't need it)"};
79 cvar_t sv_clmovement_minping_disabletime = {CF_SERVER, "sv_clmovement_minping_disabletime", "1000", "when client falls below minping, disable their prediction for this many milliseconds (should be at least 1000 or else their prediction may turn on/off frequently)"};
80 cvar_t sv_clmovement_inputtimeout = {CF_SERVER, "sv_clmovement_inputtimeout", "0.1", "when a client does not send input for this many seconds (max 0.1), force them to move anyway (unlike QuakeWorld)"};
81 cvar_t sv_cullentities_nevercullbmodels = {CF_SERVER, "sv_cullentities_nevercullbmodels", "0", "if enabled the clients are always notified of moving doors and lifts and other submodels of world (warning: eats a lot of network bandwidth on some levels!)"};
82 cvar_t sv_cullentities_pvs = {CF_SERVER, "sv_cullentities_pvs", "1", "fast but loose culling of hidden entities"};
83 cvar_t sv_cullentities_stats = {CF_SERVER, "sv_cullentities_stats", "0", "displays stats on network entities culled by various methods for each client"};
84 cvar_t sv_cullentities_trace = {CF_SERVER, "sv_cullentities_trace", "0", "somewhat slow but very tight culling of hidden entities, minimizes network traffic and makes wallhack cheats useless"};
85 cvar_t sv_cullentities_trace_delay = {CF_SERVER, "sv_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
86 cvar_t sv_cullentities_trace_delay_players = {CF_SERVER, "sv_cullentities_trace_delay_players", "0.2", "number of seconds until the entity gets actually culled if it is a player entity"};
87 cvar_t sv_cullentities_trace_enlarge = {CF_SERVER, "sv_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
88 cvar_t sv_cullentities_trace_expand = {CF_SERVER, "sv_cullentities_trace_expand", "0", "box is expanded by this many units for entity culling"};
89 cvar_t sv_cullentities_trace_eyejitter = {CF_SERVER, "sv_cullentities_trace_eyejitter", "16", "jitter the eye by this much for each trace"};
90 cvar_t sv_cullentities_trace_prediction = {CF_SERVER, "sv_cullentities_trace_prediction", "1", "also trace from the predicted player position"};
91 cvar_t sv_cullentities_trace_prediction_time = {CF_SERVER, "sv_cullentities_trace_prediction_time", "0.2", "how many seconds of prediction to use"};
92 cvar_t sv_cullentities_trace_entityocclusion = {CF_SERVER, "sv_cullentities_trace_entityocclusion", "0", "also check if doors and other bsp models are in the way"};
93 cvar_t sv_cullentities_trace_samples = {CF_SERVER, "sv_cullentities_trace_samples", "2", "number of samples to test for entity culling"};
94 cvar_t sv_cullentities_trace_samples_extra = {CF_SERVER, "sv_cullentities_trace_samples_extra", "2", "number of samples to test for entity culling when the entity affects its surroundings by e.g. dlight"};
95 cvar_t sv_cullentities_trace_samples_players = {CF_SERVER, "sv_cullentities_trace_samples_players", "8", "number of samples to test for entity culling when the entity is a player entity"};
96 cvar_t sv_debugmove = {CF_SERVER | CF_NOTIFY, "sv_debugmove", "0", "disables collision detection optimizations for debugging purposes"};
97 cvar_t sv_echobprint = {CF_SERVER | CF_ARCHIVE, "sv_echobprint", "1", "prints gamecode bprint() calls to server console"};
98 cvar_t sv_edgefriction = {CF_SERVER, "edgefriction", "1", "how much you slow down when nearing a ledge you might fall off, multiplier of sv_friction (Quake used 2, QuakeWorld used 1 due to a bug in physics code)"};
99 cvar_t sv_entpatch = {CF_SERVER, "sv_entpatch", "1", "enables loading of .ent files to override entities in the bsp (for example Threewave CTF server pack contains .ent patch files enabling play of CTF on id1 maps)"};
100 cvar_t sv_freezenonclients = {CF_SERVER | CF_NOTIFY, "sv_freezenonclients", "0", "freezes time, except for players, allowing you to walk around and take screenshots of explosions"};
101 cvar_t sv_friction = {CF_SERVER | CF_NOTIFY, "sv_friction","4", "how fast you slow down"};
102 cvar_t sv_gameplayfix_blowupfallenzombies = {CF_SERVER, "sv_gameplayfix_blowupfallenzombies", "1", "causes findradius to detect SOLID_NOT entities such as zombies and corpses on the floor, allowing splash damage to apply to them"};
103 cvar_t sv_gameplayfix_consistentplayerprethink = {CF_SERVER, "sv_gameplayfix_consistentplayerprethink", "0", "improves fairness in multiplayer by running all PlayerPreThink functions (which fire weapons) before performing physics, then running all PlayerPostThink functions"};
104 cvar_t sv_gameplayfix_delayprojectiles = {CF_SERVER, "sv_gameplayfix_delayprojectiles", "1", "causes entities to not move on the same frame they are spawned, meaning that projectiles wait until the next frame to perform their first move, giving proper interpolation and rocket trails, but making weapons harder to use at low framerates"};
105 cvar_t sv_gameplayfix_droptofloorstartsolid = {CF_SERVER, "sv_gameplayfix_droptofloorstartsolid", "1", "prevents items and monsters that start in a solid area from falling out of the level (makes droptofloor treat trace_startsolid as an acceptable outcome)"};
106 cvar_t sv_gameplayfix_droptofloorstartsolid_nudgetocorrect = {CF_SERVER, "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect", "1", "tries to nudge stuck items and monsters out of walls before droptofloor is performed"};
107 cvar_t sv_gameplayfix_easierwaterjump = {CF_SERVER, "sv_gameplayfix_easierwaterjump", "1", "changes water jumping to make it easier to get out of water (exactly like in QuakeWorld)"};
108 cvar_t sv_gameplayfix_findradiusdistancetobox = {CF_SERVER, "sv_gameplayfix_findradiusdistancetobox", "1", "causes findradius to check the distance to the corner of a box rather than the center of the box, makes findradius detect bmodels such as very large doors that would otherwise be unaffected by splash damage"};
109 cvar_t sv_gameplayfix_gravityunaffectedbyticrate = {CF_SERVER, "sv_gameplayfix_gravityunaffectedbyticrate", "0", "fix some ticrate issues in physics."};
110 cvar_t sv_gameplayfix_grenadebouncedownslopes = {CF_SERVER, "sv_gameplayfix_grenadebouncedownslopes", "1", "prevents MOVETYPE_BOUNCE (grenades) from getting stuck when fired down a downward sloping surface"};
111 cvar_t sv_gameplayfix_multiplethinksperframe = {CF_SERVER, "sv_gameplayfix_multiplethinksperframe", "1", "allows entities to think more often than the server framerate, primarily useful for very high fire rate weapons"};
112 cvar_t sv_gameplayfix_noairborncorpse = {CF_SERVER, "sv_gameplayfix_noairborncorpse", "1", "causes entities (corpses, items, etc) sitting ontop of moving entities (players) to fall when the moving entity (player) is no longer supporting them"};
113 cvar_t sv_gameplayfix_noairborncorpse_allowsuspendeditems = {CF_SERVER, "sv_gameplayfix_noairborncorpse_allowsuspendeditems", "1", "causes entities sitting ontop of objects that are instantaneously remove to float in midair (special hack to allow a common level design trick for floating items)"};
114 cvar_t sv_gameplayfix_nudgeoutofsolid = {CF_SERVER, "sv_gameplayfix_nudgeoutofsolid", "0", "attempts to fix physics errors (where an object ended up in solid for some reason)"};
115 cvar_t sv_gameplayfix_nudgeoutofsolid_separation = {CF_SERVER, "sv_gameplayfix_nudgeoutofsolid_separation", "0.03125", "keep objects this distance apart to prevent collision issues on seams"};
116 cvar_t sv_gameplayfix_q2airaccelerate = {CF_SERVER, "sv_gameplayfix_q2airaccelerate", "0", "Quake2-style air acceleration"};
117 cvar_t sv_gameplayfix_nogravityonground = {CF_SERVER, "sv_gameplayfix_nogravityonground", "0", "turn off gravity when on ground (to get rid of sliding)"};
118 cvar_t sv_gameplayfix_setmodelrealbox = {CF_SERVER, "sv_gameplayfix_setmodelrealbox", "1", "fixes a bug in Quake that made setmodel always set the entity box to ('-16 -16 -16', '16 16 16') rather than properly checking the model box, breaks some poorly coded mods"};
119 cvar_t sv_gameplayfix_slidemoveprojectiles = {CF_SERVER, "sv_gameplayfix_slidemoveprojectiles", "1", "allows MOVETYPE_FLY/FLYMISSILE/TOSS/BOUNCE/BOUNCEMISSILE entities to finish their move in a frame even if they hit something, fixes 'gravity accumulation' bug for grenades on steep slopes"};
120 cvar_t sv_gameplayfix_stepdown = {CF_SERVER, "sv_gameplayfix_stepdown", "0", "attempts to step down stairs, not just up them (prevents the familiar thud..thud..thud.. when running down stairs and slopes)"};
121 cvar_t sv_gameplayfix_stepmultipletimes = {CF_SERVER, "sv_gameplayfix_stepmultipletimes", "0", "applies step-up onto a ledge more than once in a single frame, when running quickly up stairs"};
122 cvar_t sv_gameplayfix_nostepmoveonsteepslopes = {CF_SERVER, "sv_gameplayfix_nostepmoveonsteepslopes", "0", "crude fix which prevents MOVETYPE_STEP (not swimming or flying) to move on slopes whose angle is bigger than 45 degree"};
123 cvar_t sv_gameplayfix_swiminbmodels = {CF_SERVER, "sv_gameplayfix_swiminbmodels", "1", "causes pointcontents (used to determine if you are in a liquid) to check bmodel entities as well as the world model, so you can swim around in (possibly moving) water bmodel entities"};
124 cvar_t sv_gameplayfix_upwardvelocityclearsongroundflag = {CF_SERVER, "sv_gameplayfix_upwardvelocityclearsongroundflag", "1", "prevents monsters, items, and most other objects from being stuck to the floor when pushed around by damage, and other situations in mods"};
125 cvar_t sv_gameplayfix_downtracesupportsongroundflag = {CF_SERVER, "sv_gameplayfix_downtracesupportsongroundflag", "1", "prevents very short moves from clearing onground (which may make the player stick to the floor at high netfps), fixes groundentity not being set when walking onto a mover with sv_gameplayfix_nogravityonground"};
126 cvar_t sv_gameplayfix_q1bsptracelinereportstexture = {CF_SERVER, "sv_gameplayfix_q1bsptracelinereportstexture", "1", "enables mods to get accurate trace_texture results on q1bsp by using a surface-hitting traceline implementation rather than the standard solidbsp method, q3bsp always reports texture accurately"};
127 cvar_t sv_gameplayfix_unstickplayers = {CF_SERVER, "sv_gameplayfix_unstickplayers", "1", "big hack to try and fix the rare case of MOVETYPE_WALK entities getting stuck in the world clipping hull."};
128 cvar_t sv_gameplayfix_unstickentities = {CF_SERVER, "sv_gameplayfix_unstickentities", "1", "hack to check if entities are crossing world collision hull and try to move them to the right position"};
129 cvar_t sv_gameplayfix_fixedcheckwatertransition = {CF_SERVER, "sv_gameplayfix_fixedcheckwatertransition", "1", "fix two very stupid bugs in SV_CheckWaterTransition when watertype is CONTENTS_EMPTY (the bugs causes waterlevel to be 1 on first frame, -1 on second frame - the fix makes it 0 on both frames)"};
130 cvar_t sv_gameplayfix_customstats = {CF_SERVER, "sv_gameplayfix_customstats", "0", "Disable stats higher than 220, for use by certain games such as Xonotic"};
131 cvar_t sv_gravity = {CF_SERVER | CF_NOTIFY, "sv_gravity","800", "how fast you fall (512 = roughly earth gravity)"};
132 cvar_t sv_init_frame_count = {CF_SERVER, "sv_init_frame_count", "2", "number of frames to run to allow everything to settle before letting clients connect"};
133 cvar_t sv_idealpitchscale = {CF_SERVER, "sv_idealpitchscale","0.8", "how much to look up/down slopes and stairs when not using freelook"};
134 cvar_t sv_jumpstep = {CF_SERVER | CF_NOTIFY, "sv_jumpstep", "0", "whether you can step up while jumping"};
135 cvar_t sv_jumpvelocity = {CF_SERVER, "sv_jumpvelocity", "270", "cvar that can be used by QuakeC code for jump velocity"};
136 cvar_t sv_maxairspeed = {CF_SERVER, "sv_maxairspeed", "30", "maximum speed a player can accelerate to when airborn (note that it is possible to completely stop by moving the opposite direction)"};
137 cvar_t sv_maxrate = {CF_SERVER | CF_ARCHIVE | CF_NOTIFY, "sv_maxrate", "1000000", "upper limit on client rate cvar, should reflect your network connection quality"};
138 cvar_t sv_maxspeed = {CF_SERVER | CF_NOTIFY, "sv_maxspeed", "320", "maximum speed a player can accelerate to when on ground (can be exceeded by tricks)"};
139 cvar_t sv_maxvelocity = {CF_SERVER | CF_NOTIFY, "sv_maxvelocity","2000", "universal speed limit on all entities"};
140 cvar_t sv_nostep = {CF_SERVER | CF_NOTIFY, "sv_nostep","0", "prevents MOVETYPE_STEP entities (monsters) from moving"};
141 cvar_t sv_playerphysicsqc = {CF_SERVER | CF_NOTIFY, "sv_playerphysicsqc", "1", "enables QuakeC function to override player physics"};
142 cvar_t sv_progs = {CF_SERVER, "sv_progs", "progs.dat", "selects which quakec progs.dat file to run" };
143 cvar_t sv_protocolname = {CF_SERVER, "sv_protocolname", "DP7", "selects network protocol to host for (values include QUAKE, QUAKEDP, NEHAHRAMOVIE, DP1 and up)"};
144 cvar_t sv_random_seed = {CF_SERVER, "sv_random_seed", "", "random seed; when set, on every map start this random seed is used to initialize the random number generator. Don't touch it unless for benchmarking or debugging"};
145 cvar_t host_limitlocal = {CF_SERVER, "host_limitlocal", "0", "whether to apply rate limiting to the local player in a listen server (only useful for testing)"};
146 cvar_t sv_sound_land = {CF_SERVER, "sv_sound_land", "demon/dland2.wav", "sound to play when MOVETYPE_STEP entity hits the ground at high speed (empty cvar disables the sound)"};
147 cvar_t sv_sound_watersplash = {CF_SERVER, "sv_sound_watersplash", "misc/h2ohit1.wav", "sound to play when MOVETYPE_FLY/TOSS/BOUNCE/STEP entity enters or leaves water (empty cvar disables the sound)"};
148 cvar_t sv_stepheight = {CF_SERVER | CF_NOTIFY, "sv_stepheight", "18", "how high you can step up (TW_SV_STEPCONTROL extension)"};
149 cvar_t sv_stopspeed = {CF_SERVER | CF_NOTIFY, "sv_stopspeed","100", "how fast you come to a complete stop"};
150 cvar_t sv_wallfriction = {CF_SERVER | CF_NOTIFY, "sv_wallfriction", "1", "how much you slow down when sliding along a wall"};
151 cvar_t sv_wateraccelerate = {CF_SERVER, "sv_wateraccelerate", "-1", "rate at which a player accelerates to sv_maxspeed while in water, if less than 0 the sv_accelerate variable is used instead"};
152 cvar_t sv_waterfriction = {CF_SERVER | CF_NOTIFY, "sv_waterfriction","-1", "how fast you slow down in water, if less than 0 the sv_friction variable is used instead"};
153 cvar_t sv_warsowbunny_airforwardaccel = {CF_SERVER, "sv_warsowbunny_airforwardaccel", "1.00001", "how fast you accelerate until you reach sv_maxspeed"};
154 cvar_t sv_warsowbunny_accel = {CF_SERVER, "sv_warsowbunny_accel", "0.1585", "how fast you accelerate until after reaching sv_maxspeed (it gets harder as you near sv_warsowbunny_topspeed)"};
155 cvar_t sv_warsowbunny_topspeed = {CF_SERVER, "sv_warsowbunny_topspeed", "925", "soft speed limit (can get faster with rjs and on ramps)"};
156 cvar_t sv_warsowbunny_turnaccel = {CF_SERVER, "sv_warsowbunny_turnaccel", "0", "max sharpness of turns (also master switch for the sv_warsowbunny_* mode; set this to 9 to enable)"};
157 cvar_t sv_warsowbunny_backtosideratio = {CF_SERVER, "sv_warsowbunny_backtosideratio", "0.8", "lower values make it easier to change direction without losing speed; the drawback is \"understeering\" in sharp turns"};
158 cvar_t sv_onlycsqcnetworking = {CF_SERVER, "sv_onlycsqcnetworking", "0", "disables legacy entity networking code for higher performance (except on clients, which can still be legacy)"};
159 cvar_t sv_areadebug = {CF_SERVER, "sv_areadebug", "0", "disables physics culling for debugging purposes (only for development)"};
160 cvar_t sys_ticrate = {CF_SERVER | CF_ARCHIVE, "sys_ticrate","0.0138889", "how long a server frame is in seconds, 0.05 is 20fps server rate, 0.1 is 10fps (can not be set higher than 0.1), 0 runs as many server frames as possible (makes games against bots a little smoother, overwhelms network players), 0.0138889 matches QuakeWorld physics"};
161 cvar_t teamplay = {CF_SERVER | CF_NOTIFY, "teamplay","0", "teamplay mode, values depend on mod but typically 0 = no teams, 1 = no team damage no self damage, 2 = team damage and self damage, some mods support 3 = no team damage but can damage self"};
162 cvar_t timelimit = {CF_SERVER | CF_NOTIFY, "timelimit","0", "ends level at this time (in minutes)"};
163 cvar_t sv_threaded = {CF_SERVER, "sv_threaded", "0", "enables a separate thread for server code, improving performance, especially when hosting a game while playing, EXPERIMENTAL, may be crashy"};
164
165 cvar_t sv_rollspeed = {CF_CLIENT, "sv_rollspeed", "200", "how much strafing is necessary to tilt the view"};
166 cvar_t sv_rollangle = {CF_CLIENT, "sv_rollangle", "2.0", "how much to tilt the view when strafing"};
167
168 cvar_t saved1 = {CF_SERVER | CF_ARCHIVE, "saved1", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
169 cvar_t saved2 = {CF_SERVER | CF_ARCHIVE, "saved2", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
170 cvar_t saved3 = {CF_SERVER | CF_ARCHIVE, "saved3", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
171 cvar_t saved4 = {CF_SERVER | CF_ARCHIVE, "saved4", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
172 cvar_t savedgamecfg = {CF_SERVER | CF_ARCHIVE, "savedgamecfg", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
173 cvar_t scratch1 = {CF_SERVER, "scratch1", "0", "unused cvar in quake, can be used by mods"};
174 cvar_t scratch2 = {CF_SERVER,"scratch2", "0", "unused cvar in quake, can be used by mods"};
175 cvar_t scratch3 = {CF_SERVER, "scratch3", "0", "unused cvar in quake, can be used by mods"};
176 cvar_t scratch4 = {CF_SERVER, "scratch4", "0", "unused cvar in quake, can be used by mods"};
177 cvar_t temp1 = {CF_SERVER, "temp1","0", "general cvar for mods to use, in stock id1 this selects which death animation to use on players (0 = random death, other values select specific death scenes)"};
178
179 cvar_t nehx00 = {CF_SERVER, "nehx00", "0", "nehahra data storage cvar (used in singleplayer)"};
180 cvar_t nehx01 = {CF_SERVER, "nehx01", "0", "nehahra data storage cvar (used in singleplayer)"};
181 cvar_t nehx02 = {CF_SERVER, "nehx02", "0", "nehahra data storage cvar (used in singleplayer)"};
182 cvar_t nehx03 = {CF_SERVER, "nehx03", "0", "nehahra data storage cvar (used in singleplayer)"};
183 cvar_t nehx04 = {CF_SERVER, "nehx04", "0", "nehahra data storage cvar (used in singleplayer)"};
184 cvar_t nehx05 = {CF_SERVER, "nehx05", "0", "nehahra data storage cvar (used in singleplayer)"};
185 cvar_t nehx06 = {CF_SERVER, "nehx06", "0", "nehahra data storage cvar (used in singleplayer)"};
186 cvar_t nehx07 = {CF_SERVER, "nehx07", "0", "nehahra data storage cvar (used in singleplayer)"};
187 cvar_t nehx08 = {CF_SERVER, "nehx08", "0", "nehahra data storage cvar (used in singleplayer)"};
188 cvar_t nehx09 = {CF_SERVER, "nehx09", "0", "nehahra data storage cvar (used in singleplayer)"};
189 cvar_t nehx10 = {CF_SERVER, "nehx10", "0", "nehahra data storage cvar (used in singleplayer)"};
190 cvar_t nehx11 = {CF_SERVER, "nehx11", "0", "nehahra data storage cvar (used in singleplayer)"};
191 cvar_t nehx12 = {CF_SERVER, "nehx12", "0", "nehahra data storage cvar (used in singleplayer)"};
192 cvar_t nehx13 = {CF_SERVER, "nehx13", "0", "nehahra data storage cvar (used in singleplayer)"};
193 cvar_t nehx14 = {CF_SERVER, "nehx14", "0", "nehahra data storage cvar (used in singleplayer)"};
194 cvar_t nehx15 = {CF_SERVER, "nehx15", "0", "nehahra data storage cvar (used in singleplayer)"};
195 cvar_t nehx16 = {CF_SERVER, "nehx16", "0", "nehahra data storage cvar (used in singleplayer)"};
196 cvar_t nehx17 = {CF_SERVER, "nehx17", "0", "nehahra data storage cvar (used in singleplayer)"};
197 cvar_t nehx18 = {CF_SERVER, "nehx18", "0", "nehahra data storage cvar (used in singleplayer)"};
198 cvar_t nehx19 = {CF_SERVER, "nehx19", "0", "nehahra data storage cvar (used in singleplayer)"};
199 cvar_t cutscene = {CF_SERVER, "cutscene", "1", "enables cutscenes in nehahra, can be used by other mods"};
200
201 cvar_t sv_autodemo_perclient = {CF_SERVER | CF_ARCHIVE, "sv_autodemo_perclient", "0", "set to 1 to enable autorecorded per-client demos (they'll start to record at the beginning of a match); set it to 2 to also record client->server packets (for debugging)"};
202 cvar_t sv_autodemo_perclient_nameformat = {CF_SERVER | CF_ARCHIVE, "sv_autodemo_perclient_nameformat", "sv_autodemos/%Y-%m-%d_%H-%M", "The format of the sv_autodemo_perclient filename, followed by the map name, the client number and the IP address + port number, separated by underscores (the date is encoded using strftime escapes)" };
203 cvar_t sv_autodemo_perclient_discardable = {CF_SERVER | CF_ARCHIVE, "sv_autodemo_perclient_discardable", "0", "Allow game code to decide whether a demo should be kept or discarded."};
204
205 cvar_t halflifebsp = {CF_SERVER, "halflifebsp", "0", "indicates the current map is hlbsp format (useful to know because of different bounding box sizes)"};
206 cvar_t sv_mapformat_is_quake2 = {CF_SERVER, "sv_mapformat_is_quake2", "0", "indicates the current map is q2bsp format (useful to know because of different entity behaviors, .frame on submodels and other things)"};
207 cvar_t sv_mapformat_is_quake3 = {CF_SERVER, "sv_mapformat_is_quake3", "0", "indicates the current map is q2bsp format (useful to know because of different entity behaviors)"};
208
209 cvar_t sv_writepicture_quality = {CF_SERVER | CF_ARCHIVE, "sv_writepicture_quality", "10", "WritePicture quality offset (higher means better quality, but slower)"};
210
211 server_t sv;
212 server_static_t svs;
213
214 mempool_t *sv_mempool = NULL;
215
216 extern cvar_t host_timescale;
217 extern float            scr_centertime_off;
218
219 // MUST match effectnameindex_t in client.h
220 static const char *standardeffectnames[EFFECT_TOTAL] =
221 {
222         "",
223         "TE_GUNSHOT",
224         "TE_GUNSHOTQUAD",
225         "TE_SPIKE",
226         "TE_SPIKEQUAD",
227         "TE_SUPERSPIKE",
228         "TE_SUPERSPIKEQUAD",
229         "TE_WIZSPIKE",
230         "TE_KNIGHTSPIKE",
231         "TE_EXPLOSION",
232         "TE_EXPLOSIONQUAD",
233         "TE_TAREXPLOSION",
234         "TE_TELEPORT",
235         "TE_LAVASPLASH",
236         "TE_SMALLFLASH",
237         "TE_FLAMEJET",
238         "EF_FLAME",
239         "TE_BLOOD",
240         "TE_SPARK",
241         "TE_PLASMABURN",
242         "TE_TEI_G3",
243         "TE_TEI_SMOKE",
244         "TE_TEI_BIGEXPLOSION",
245         "TE_TEI_PLASMAHIT",
246         "EF_STARDUST",
247         "TR_ROCKET",
248         "TR_GRENADE",
249         "TR_BLOOD",
250         "TR_WIZSPIKE",
251         "TR_SLIGHTBLOOD",
252         "TR_KNIGHTSPIKE",
253         "TR_VORESPIKE",
254         "TR_NEHAHRASMOKE",
255         "TR_NEXUIZPLASMA",
256         "TR_GLOWTRAIL",
257         "SVC_PARTICLE"
258 };
259
260 #define SV_REQFUNCS 0
261 #define sv_reqfuncs NULL
262
263 //#define SV_REQFUNCS (sizeof(sv_reqfuncs) / sizeof(const char *))
264 //static const char *sv_reqfuncs[] = {
265 //};
266
267 #define SV_REQFIELDS (sizeof(sv_reqfields) / sizeof(prvm_required_field_t))
268
269 prvm_required_field_t sv_reqfields[] =
270 {
271 #define PRVM_DECLARE_serverglobalfloat(x)
272 #define PRVM_DECLARE_serverglobalvector(x)
273 #define PRVM_DECLARE_serverglobalstring(x)
274 #define PRVM_DECLARE_serverglobaledict(x)
275 #define PRVM_DECLARE_serverglobalfunction(x)
276 #define PRVM_DECLARE_clientglobalfloat(x)
277 #define PRVM_DECLARE_clientglobalvector(x)
278 #define PRVM_DECLARE_clientglobalstring(x)
279 #define PRVM_DECLARE_clientglobaledict(x)
280 #define PRVM_DECLARE_clientglobalfunction(x)
281 #define PRVM_DECLARE_menuglobalfloat(x)
282 #define PRVM_DECLARE_menuglobalvector(x)
283 #define PRVM_DECLARE_menuglobalstring(x)
284 #define PRVM_DECLARE_menuglobaledict(x)
285 #define PRVM_DECLARE_menuglobalfunction(x)
286 #define PRVM_DECLARE_serverfieldfloat(x) {ev_float, #x},
287 #define PRVM_DECLARE_serverfieldvector(x) {ev_vector, #x},
288 #define PRVM_DECLARE_serverfieldstring(x) {ev_string, #x},
289 #define PRVM_DECLARE_serverfieldedict(x) {ev_entity, #x},
290 #define PRVM_DECLARE_serverfieldfunction(x) {ev_function, #x},
291 #define PRVM_DECLARE_clientfieldfloat(x)
292 #define PRVM_DECLARE_clientfieldvector(x)
293 #define PRVM_DECLARE_clientfieldstring(x)
294 #define PRVM_DECLARE_clientfieldedict(x)
295 #define PRVM_DECLARE_clientfieldfunction(x)
296 #define PRVM_DECLARE_menufieldfloat(x)
297 #define PRVM_DECLARE_menufieldvector(x)
298 #define PRVM_DECLARE_menufieldstring(x)
299 #define PRVM_DECLARE_menufieldedict(x)
300 #define PRVM_DECLARE_menufieldfunction(x)
301 #define PRVM_DECLARE_serverfunction(x)
302 #define PRVM_DECLARE_clientfunction(x)
303 #define PRVM_DECLARE_menufunction(x)
304 #define PRVM_DECLARE_field(x)
305 #define PRVM_DECLARE_global(x)
306 #define PRVM_DECLARE_function(x)
307 #include "prvm_offsets.h"
308 #undef PRVM_DECLARE_serverglobalfloat
309 #undef PRVM_DECLARE_serverglobalvector
310 #undef PRVM_DECLARE_serverglobalstring
311 #undef PRVM_DECLARE_serverglobaledict
312 #undef PRVM_DECLARE_serverglobalfunction
313 #undef PRVM_DECLARE_clientglobalfloat
314 #undef PRVM_DECLARE_clientglobalvector
315 #undef PRVM_DECLARE_clientglobalstring
316 #undef PRVM_DECLARE_clientglobaledict
317 #undef PRVM_DECLARE_clientglobalfunction
318 #undef PRVM_DECLARE_menuglobalfloat
319 #undef PRVM_DECLARE_menuglobalvector
320 #undef PRVM_DECLARE_menuglobalstring
321 #undef PRVM_DECLARE_menuglobaledict
322 #undef PRVM_DECLARE_menuglobalfunction
323 #undef PRVM_DECLARE_serverfieldfloat
324 #undef PRVM_DECLARE_serverfieldvector
325 #undef PRVM_DECLARE_serverfieldstring
326 #undef PRVM_DECLARE_serverfieldedict
327 #undef PRVM_DECLARE_serverfieldfunction
328 #undef PRVM_DECLARE_clientfieldfloat
329 #undef PRVM_DECLARE_clientfieldvector
330 #undef PRVM_DECLARE_clientfieldstring
331 #undef PRVM_DECLARE_clientfieldedict
332 #undef PRVM_DECLARE_clientfieldfunction
333 #undef PRVM_DECLARE_menufieldfloat
334 #undef PRVM_DECLARE_menufieldvector
335 #undef PRVM_DECLARE_menufieldstring
336 #undef PRVM_DECLARE_menufieldedict
337 #undef PRVM_DECLARE_menufieldfunction
338 #undef PRVM_DECLARE_serverfunction
339 #undef PRVM_DECLARE_clientfunction
340 #undef PRVM_DECLARE_menufunction
341 #undef PRVM_DECLARE_field
342 #undef PRVM_DECLARE_global
343 #undef PRVM_DECLARE_function
344 };
345
346 #define SV_REQGLOBALS (sizeof(sv_reqglobals) / sizeof(prvm_required_field_t))
347
348 prvm_required_field_t sv_reqglobals[] =
349 {
350 #define PRVM_DECLARE_serverglobalfloat(x) {ev_float, #x},
351 #define PRVM_DECLARE_serverglobalvector(x) {ev_vector, #x},
352 #define PRVM_DECLARE_serverglobalstring(x) {ev_string, #x},
353 #define PRVM_DECLARE_serverglobaledict(x) {ev_entity, #x},
354 #define PRVM_DECLARE_serverglobalfunction(x) {ev_function, #x},
355 #define PRVM_DECLARE_clientglobalfloat(x)
356 #define PRVM_DECLARE_clientglobalvector(x)
357 #define PRVM_DECLARE_clientglobalstring(x)
358 #define PRVM_DECLARE_clientglobaledict(x)
359 #define PRVM_DECLARE_clientglobalfunction(x)
360 #define PRVM_DECLARE_menuglobalfloat(x)
361 #define PRVM_DECLARE_menuglobalvector(x)
362 #define PRVM_DECLARE_menuglobalstring(x)
363 #define PRVM_DECLARE_menuglobaledict(x)
364 #define PRVM_DECLARE_menuglobalfunction(x)
365 #define PRVM_DECLARE_serverfieldfloat(x)
366 #define PRVM_DECLARE_serverfieldvector(x)
367 #define PRVM_DECLARE_serverfieldstring(x)
368 #define PRVM_DECLARE_serverfieldedict(x)
369 #define PRVM_DECLARE_serverfieldfunction(x)
370 #define PRVM_DECLARE_clientfieldfloat(x)
371 #define PRVM_DECLARE_clientfieldvector(x)
372 #define PRVM_DECLARE_clientfieldstring(x)
373 #define PRVM_DECLARE_clientfieldedict(x)
374 #define PRVM_DECLARE_clientfieldfunction(x)
375 #define PRVM_DECLARE_menufieldfloat(x)
376 #define PRVM_DECLARE_menufieldvector(x)
377 #define PRVM_DECLARE_menufieldstring(x)
378 #define PRVM_DECLARE_menufieldedict(x)
379 #define PRVM_DECLARE_menufieldfunction(x)
380 #define PRVM_DECLARE_serverfunction(x)
381 #define PRVM_DECLARE_clientfunction(x)
382 #define PRVM_DECLARE_menufunction(x)
383 #define PRVM_DECLARE_field(x)
384 #define PRVM_DECLARE_global(x)
385 #define PRVM_DECLARE_function(x)
386 #include "prvm_offsets.h"
387 #undef PRVM_DECLARE_serverglobalfloat
388 #undef PRVM_DECLARE_serverglobalvector
389 #undef PRVM_DECLARE_serverglobalstring
390 #undef PRVM_DECLARE_serverglobaledict
391 #undef PRVM_DECLARE_serverglobalfunction
392 #undef PRVM_DECLARE_clientglobalfloat
393 #undef PRVM_DECLARE_clientglobalvector
394 #undef PRVM_DECLARE_clientglobalstring
395 #undef PRVM_DECLARE_clientglobaledict
396 #undef PRVM_DECLARE_clientglobalfunction
397 #undef PRVM_DECLARE_menuglobalfloat
398 #undef PRVM_DECLARE_menuglobalvector
399 #undef PRVM_DECLARE_menuglobalstring
400 #undef PRVM_DECLARE_menuglobaledict
401 #undef PRVM_DECLARE_menuglobalfunction
402 #undef PRVM_DECLARE_serverfieldfloat
403 #undef PRVM_DECLARE_serverfieldvector
404 #undef PRVM_DECLARE_serverfieldstring
405 #undef PRVM_DECLARE_serverfieldedict
406 #undef PRVM_DECLARE_serverfieldfunction
407 #undef PRVM_DECLARE_clientfieldfloat
408 #undef PRVM_DECLARE_clientfieldvector
409 #undef PRVM_DECLARE_clientfieldstring
410 #undef PRVM_DECLARE_clientfieldedict
411 #undef PRVM_DECLARE_clientfieldfunction
412 #undef PRVM_DECLARE_menufieldfloat
413 #undef PRVM_DECLARE_menufieldvector
414 #undef PRVM_DECLARE_menufieldstring
415 #undef PRVM_DECLARE_menufieldedict
416 #undef PRVM_DECLARE_menufieldfunction
417 #undef PRVM_DECLARE_serverfunction
418 #undef PRVM_DECLARE_clientfunction
419 #undef PRVM_DECLARE_menufunction
420 #undef PRVM_DECLARE_field
421 #undef PRVM_DECLARE_global
422 #undef PRVM_DECLARE_function
423 };
424
425 static void Host_Timescale_c(cvar_t *var)
426 {
427         if(var->value < 0.00001 && var->value != 0)
428                 Cvar_SetValueQuick(var, 0);
429 }
430
431 //============================================================================
432
433 static void SV_AreaStats_f(cmd_state_t *cmd)
434 {
435         World_PrintAreaStats(&sv.world, "server");
436 }
437
438 static void SV_ServerOptions (void)
439 {
440         int i;
441
442         // general default
443         svs.maxclients = 8;
444
445 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
446 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
447         // if no client is in the executable or -dedicated is specified on
448         // commandline, start a dedicated server
449         i = Sys_CheckParm ("-dedicated");
450         if (i || !cl_available)
451         {
452                 cls.state = ca_dedicated;
453                 // check for -dedicated specifying how many players
454                 if (i && i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
455                         svs.maxclients = atoi (sys.argv[i+1]);
456                 if (Sys_CheckParm ("-listen"))
457                         Con_Printf ("Only one of -dedicated or -listen can be specified\n");
458                 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
459                 Cvar_SetValue(&cvars_all, "sv_public", 1);
460         }
461         else if (cl_available)
462         {
463                 // client exists and not dedicated, check if -listen is specified
464                 cls.state = ca_disconnected;
465                 i = Sys_CheckParm ("-listen");
466                 if (i)
467                 {
468                         // default players unless specified
469                         if (i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
470                                 svs.maxclients = atoi (sys.argv[i+1]);
471                 }
472                 else
473                 {
474                         // default players in some games, singleplayer in most
475                         if (gamemode != GAME_GOODVSBAD2 && !IS_NEXUIZ_DERIVED(gamemode) && gamemode != GAME_BATTLEMECH)
476                                 svs.maxclients = 1;
477                 }
478         }
479
480         svs.maxclients = svs.maxclients_next = bound(1, svs.maxclients, MAX_SCOREBOARD);
481
482         svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
483
484         if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
485                 Cvar_SetValueQuick(&deathmatch, 1);
486 }
487
488 /*
489 ===============
490 SV_Init
491 ===============
492 */
493 void SV_Init (void)
494 {
495         // init the csqc progs cvars, since they are updated/used by the server code
496         // TODO: fix this since this is a quick hack to make some of [515]'s broken code run ;) [9/13/2006 Black]
497         extern cvar_t csqc_progname;    //[515]: csqc crc check and right csprogs name according to progs.dat
498         extern cvar_t csqc_progcrc;
499         extern cvar_t csqc_progsize;
500         extern cvar_t csqc_usedemoprogs;
501
502         Cvar_RegisterVariable(&sv_worldmessage);
503         Cvar_RegisterVariable(&sv_worldname);
504         Cvar_RegisterVariable(&sv_worldnamenoextension);
505         Cvar_RegisterVariable(&sv_worldbasename);
506
507         Cvar_RegisterVariable (&csqc_progname);
508         Cvar_RegisterVariable (&csqc_progcrc);
509         Cvar_RegisterVariable (&csqc_progsize);
510         Cvar_RegisterVariable (&csqc_usedemoprogs);
511
512         Cmd_AddCommand(CF_SHARED, "sv_saveentfile", SV_SaveEntFile_f, "save map entities to .ent file (to allow external editing)");
513         Cmd_AddCommand(CF_SHARED, "sv_areastats", SV_AreaStats_f, "prints statistics on entity culling during collision traces");
514         Cmd_AddCommand(CF_CLIENT | CF_SERVER_FROM_CLIENT, "sv_startdownload", SV_StartDownload_f, "begins sending a file to the client (network protocol use only)");
515         Cmd_AddCommand(CF_CLIENT | CF_SERVER_FROM_CLIENT, "download", SV_Download_f, "downloads a specified file from the server");
516
517         Cvar_RegisterVariable (&sv_disablenotify);
518         Cvar_RegisterVariable (&coop);
519         Cvar_RegisterVariable (&deathmatch);
520         Cvar_RegisterVariable (&fraglimit);
521         Cvar_RegisterVariable (&gamecfg);
522         Cvar_RegisterVariable (&noexit);
523         Cvar_RegisterVariable (&nomonsters);
524         Cvar_RegisterVariable (&pausable);
525         Cvar_RegisterVariable (&pr_checkextension);
526         Cvar_RegisterVariable (&samelevel);
527         Cvar_RegisterVariable (&skill);
528         Cvar_RegisterVariable (&campaign);
529         Cvar_RegisterVariable (&host_timescale);
530         Cvar_RegisterCallback (&host_timescale, Host_Timescale_c);
531         Cvar_RegisterVirtual (&host_timescale, "slowmo");
532         Cvar_RegisterVirtual (&host_timescale, "timescale");
533         Cvar_RegisterVariable (&sv_accelerate);
534         Cvar_RegisterVariable (&sv_aim);
535         Cvar_RegisterVariable (&sv_airaccel_qw);
536         Cvar_RegisterVariable (&sv_airaccel_qw_stretchfactor);
537         Cvar_RegisterVariable (&sv_airaccel_sideways_friction);
538         Cvar_RegisterVariable (&sv_airaccelerate);
539         Cvar_RegisterVariable (&sv_airstopaccelerate);
540         Cvar_RegisterVariable (&sv_airstrafeaccelerate);
541         Cvar_RegisterVariable (&sv_maxairstrafespeed);
542         Cvar_RegisterVariable (&sv_airstrafeaccel_qw);
543         Cvar_RegisterVariable (&sv_airspeedlimit_nonqw);
544         Cvar_RegisterVariable (&sv_aircontrol);
545         Cvar_RegisterVariable (&sv_aircontrol_power);
546         Cvar_RegisterVariable (&sv_aircontrol_penalty);
547         Cvar_RegisterVariable (&sv_allowdownloads);
548         Cvar_RegisterVariable (&sv_allowdownloads_archive);
549         Cvar_RegisterVariable (&sv_allowdownloads_config);
550         Cvar_RegisterVariable (&sv_allowdownloads_dlcache);
551         Cvar_RegisterVariable (&sv_allowdownloads_inarchive);
552         Cvar_RegisterVariable (&sv_areagrid_mingridsize);
553         Cvar_RegisterVariable (&sv_checkforpacketsduringsleep);
554         Cvar_RegisterVariable (&sv_clmovement_enable);
555         Cvar_RegisterVariable (&sv_clmovement_minping);
556         Cvar_RegisterVariable (&sv_clmovement_minping_disabletime);
557         Cvar_RegisterVariable (&sv_clmovement_inputtimeout);
558         Cvar_RegisterVariable (&sv_cullentities_nevercullbmodels);
559         Cvar_RegisterVariable (&sv_cullentities_pvs);
560         Cvar_RegisterVariable (&sv_cullentities_stats);
561         Cvar_RegisterVariable (&sv_cullentities_trace);
562         Cvar_RegisterVariable (&sv_cullentities_trace_delay);
563         Cvar_RegisterVariable (&sv_cullentities_trace_delay_players);
564         Cvar_RegisterVariable (&sv_cullentities_trace_enlarge);
565         Cvar_RegisterVariable (&sv_cullentities_trace_expand);
566         Cvar_RegisterVariable (&sv_cullentities_trace_eyejitter);
567         Cvar_RegisterVariable (&sv_cullentities_trace_entityocclusion);
568         Cvar_RegisterVariable (&sv_cullentities_trace_prediction);
569         Cvar_RegisterVariable (&sv_cullentities_trace_prediction_time);
570         Cvar_RegisterVariable (&sv_cullentities_trace_samples);
571         Cvar_RegisterVariable (&sv_cullentities_trace_samples_extra);
572         Cvar_RegisterVariable (&sv_cullentities_trace_samples_players);
573         Cvar_RegisterVariable (&sv_debugmove);
574         Cvar_RegisterVariable (&sv_echobprint);
575         Cvar_RegisterVariable (&sv_edgefriction);
576         Cvar_RegisterVariable (&sv_entpatch);
577         Cvar_RegisterVariable (&sv_freezenonclients);
578         Cvar_RegisterVariable (&sv_friction);
579         Cvar_RegisterVariable (&sv_gameplayfix_blowupfallenzombies);
580         Cvar_RegisterVariable (&sv_gameplayfix_consistentplayerprethink);
581         Cvar_RegisterVariable (&sv_gameplayfix_delayprojectiles);
582         Cvar_RegisterVariable (&sv_gameplayfix_droptofloorstartsolid);
583         Cvar_RegisterVariable (&sv_gameplayfix_droptofloorstartsolid_nudgetocorrect);
584         Cvar_RegisterVariable (&sv_gameplayfix_easierwaterjump);
585         Cvar_RegisterVariable (&sv_gameplayfix_findradiusdistancetobox);
586         Cvar_RegisterVariable (&sv_gameplayfix_gravityunaffectedbyticrate);
587         Cvar_RegisterVariable (&sv_gameplayfix_grenadebouncedownslopes);
588         Cvar_RegisterVariable (&sv_gameplayfix_multiplethinksperframe);
589         Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse);
590         Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse_allowsuspendeditems);
591         Cvar_RegisterVariable (&sv_gameplayfix_nudgeoutofsolid);
592         Cvar_RegisterVariable (&sv_gameplayfix_nudgeoutofsolid_separation);
593         Cvar_RegisterVariable (&sv_gameplayfix_q2airaccelerate);
594         Cvar_RegisterVariable (&sv_gameplayfix_nogravityonground);
595         Cvar_RegisterVariable (&sv_gameplayfix_setmodelrealbox);
596         Cvar_RegisterVariable (&sv_gameplayfix_slidemoveprojectiles);
597         Cvar_RegisterVariable (&sv_gameplayfix_stepdown);
598         Cvar_RegisterVariable (&sv_gameplayfix_stepmultipletimes);
599         Cvar_RegisterVariable (&sv_gameplayfix_nostepmoveonsteepslopes);
600         Cvar_RegisterVariable (&sv_gameplayfix_swiminbmodels);
601         Cvar_RegisterVariable (&sv_gameplayfix_upwardvelocityclearsongroundflag);
602         Cvar_RegisterVariable (&sv_gameplayfix_downtracesupportsongroundflag);
603         Cvar_RegisterVariable (&sv_gameplayfix_q1bsptracelinereportstexture);
604         Cvar_RegisterVariable (&sv_gameplayfix_unstickplayers);
605         Cvar_RegisterVariable (&sv_gameplayfix_unstickentities);
606         Cvar_RegisterVariable (&sv_gameplayfix_fixedcheckwatertransition);
607         Cvar_RegisterVariable (&sv_gameplayfix_customstats);
608         Cvar_RegisterVariable (&sv_gravity);
609         Cvar_RegisterVariable (&sv_init_frame_count);
610         Cvar_RegisterVariable (&sv_idealpitchscale);
611         Cvar_RegisterVariable (&sv_jumpstep);
612         Cvar_RegisterVariable (&sv_jumpvelocity);
613         Cvar_RegisterVariable (&sv_maxairspeed);
614         Cvar_RegisterVariable (&sv_maxrate);
615         Cvar_RegisterVariable (&sv_maxspeed);
616         Cvar_RegisterVariable (&sv_maxvelocity);
617         Cvar_RegisterVariable (&sv_nostep);
618         Cvar_RegisterVariable (&sv_playerphysicsqc);
619         Cvar_RegisterVariable (&sv_progs);
620         Cvar_RegisterVariable (&sv_protocolname);
621         Cvar_RegisterVariable (&sv_random_seed);
622         Cvar_RegisterVariable (&host_limitlocal);
623         Cvar_RegisterVirtual(&host_limitlocal, "sv_ratelimitlocalplayer");
624         Cvar_RegisterVariable (&sv_sound_land);
625         Cvar_RegisterVariable (&sv_sound_watersplash);
626         Cvar_RegisterVariable (&sv_stepheight);
627         Cvar_RegisterVariable (&sv_stopspeed);
628         Cvar_RegisterVariable (&sv_wallfriction);
629         Cvar_RegisterVariable (&sv_wateraccelerate);
630         Cvar_RegisterVariable (&sv_waterfriction);
631         Cvar_RegisterVariable (&sv_warsowbunny_airforwardaccel);
632         Cvar_RegisterVariable (&sv_warsowbunny_accel);
633         Cvar_RegisterVariable (&sv_warsowbunny_topspeed);
634         Cvar_RegisterVariable (&sv_warsowbunny_turnaccel);
635         Cvar_RegisterVariable (&sv_warsowbunny_backtosideratio);
636         Cvar_RegisterVariable (&sv_onlycsqcnetworking);
637         Cvar_RegisterVariable (&sv_areadebug);
638         Cvar_RegisterVariable (&sys_ticrate);
639         Cvar_RegisterVariable (&teamplay);
640         Cvar_RegisterVariable (&timelimit);
641         Cvar_RegisterVariable (&sv_threaded);
642
643         Cvar_RegisterVariable (&sv_rollangle);
644         Cvar_RegisterVariable (&sv_rollspeed);
645
646         Cvar_RegisterVariable (&saved1);
647         Cvar_RegisterVariable (&saved2);
648         Cvar_RegisterVariable (&saved3);
649         Cvar_RegisterVariable (&saved4);
650         Cvar_RegisterVariable (&savedgamecfg);
651         Cvar_RegisterVariable (&scratch1);
652         Cvar_RegisterVariable (&scratch2);
653         Cvar_RegisterVariable (&scratch3);
654         Cvar_RegisterVariable (&scratch4);
655         Cvar_RegisterVariable (&temp1);
656
657         // LadyHavoc: Nehahra uses these to pass data around cutscene demos
658         Cvar_RegisterVariable (&nehx00);
659         Cvar_RegisterVariable (&nehx01);
660         Cvar_RegisterVariable (&nehx02);
661         Cvar_RegisterVariable (&nehx03);
662         Cvar_RegisterVariable (&nehx04);
663         Cvar_RegisterVariable (&nehx05);
664         Cvar_RegisterVariable (&nehx06);
665         Cvar_RegisterVariable (&nehx07);
666         Cvar_RegisterVariable (&nehx08);
667         Cvar_RegisterVariable (&nehx09);
668         Cvar_RegisterVariable (&nehx10);
669         Cvar_RegisterVariable (&nehx11);
670         Cvar_RegisterVariable (&nehx12);
671         Cvar_RegisterVariable (&nehx13);
672         Cvar_RegisterVariable (&nehx14);
673         Cvar_RegisterVariable (&nehx15);
674         Cvar_RegisterVariable (&nehx16);
675         Cvar_RegisterVariable (&nehx17);
676         Cvar_RegisterVariable (&nehx18);
677         Cvar_RegisterVariable (&nehx19);
678         Cvar_RegisterVariable (&cutscene); // for Nehahra but useful to other mods as well
679
680         Cvar_RegisterVariable (&sv_autodemo_perclient);
681         Cvar_RegisterVariable (&sv_autodemo_perclient_nameformat);
682         Cvar_RegisterVariable (&sv_autodemo_perclient_discardable);
683
684         Cvar_RegisterVariable (&halflifebsp);
685         Cvar_RegisterVariable (&sv_mapformat_is_quake2);
686         Cvar_RegisterVariable (&sv_mapformat_is_quake3);
687
688         Cvar_RegisterVariable (&sv_writepicture_quality);
689
690         SV_InitOperatorCommands();
691         host.hook.SV_Shutdown = SV_Shutdown;
692
693         sv_mempool = Mem_AllocPool("server", 0, NULL);
694
695         SV_ServerOptions();
696         Cvar_Callback(&sv_netport);
697 }
698
699 static void SV_SaveEntFile_f(cmd_state_t *cmd)
700 {
701         char vabuf[1024];
702         if (!sv.active || !sv.worldmodel)
703         {
704                 Con_Print("Not running a server\n");
705                 return;
706         }
707         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s.ent", sv.worldnamenoextension), sv.worldmodel->brush.entities, (fs_offset_t)strlen(sv.worldmodel->brush.entities));
708 }
709
710 /*
711 ==============================================================================
712
713 CLIENT SPAWNING
714
715 ==============================================================================
716 */
717
718 /*
719 ================
720 SV_SendServerinfo
721
722 Sends the first message from the server to a connected client.
723 This will be sent on the initial connection and upon each server load.
724 ================
725 */
726 void SV_SendServerinfo (client_t *client)
727 {
728         prvm_prog_t *prog = SVVM_prog;
729         int i;
730         char message[128];
731         char vabuf[1024];
732
733         // we know that this client has a netconnection and thus is not a bot
734
735         // edicts get reallocated on level changes, so we need to update it here
736         client->edict = PRVM_EDICT_NUM((client - svs.clients) + 1);
737
738         // clear cached stuff that depends on the level
739         client->weaponmodel[0] = 0;
740         client->weaponmodelindex = 0;
741
742         // LadyHavoc: clear entityframe tracking
743         client->latestframenum = 0;
744
745         // initialize the movetime, so a speedhack can't make use of the time before this client joined
746         client->cmd.time = sv.time;
747
748         if (client->entitydatabase)
749                 EntityFrame_FreeDatabase(client->entitydatabase);
750         if (client->entitydatabase4)
751                 EntityFrame4_FreeDatabase(client->entitydatabase4);
752         if (client->entitydatabase5)
753                 EntityFrame5_FreeDatabase(client->entitydatabase5);
754
755         memset(client->stats, 0, sizeof(client->stats));
756         memset(client->statsdeltabits, 0, sizeof(client->statsdeltabits));
757
758         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_NEHAHRABJP && sv.protocol != PROTOCOL_NEHAHRABJP2 && sv.protocol != PROTOCOL_NEHAHRABJP3)
759         {
760                 if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3)
761                         client->entitydatabase = EntityFrame_AllocDatabase(sv_mempool);
762                 else if (sv.protocol == PROTOCOL_DARKPLACES4)
763                         client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_mempool);
764                 else
765                         client->entitydatabase5 = EntityFrame5_AllocDatabase(sv_mempool);
766         }
767
768         // reset csqc entity versions
769         for (i = 0;i < prog->max_edicts;i++)
770         {
771                 client->csqcentityscope[i] = 0;
772                 client->csqcentitysendflags[i] = 0xFFFFFF;
773         }
774         for (i = 0;i < NUM_CSQCENTITYDB_FRAMES;i++)
775         {
776                 client->csqcentityframehistory[i].num = 0;
777                 client->csqcentityframehistory[i].framenum = -1;
778         }
779         client->csqcnumedicts = 0;
780         client->csqcentityframehistory_next = 0;
781
782         SZ_Clear (&client->netconnection->message);
783         MSG_WriteByte (&client->netconnection->message, svc_print);
784         dpsnprintf (message, sizeof (message), "\nServer: %s build %s (progs %i crc)\n", gamename, buildstring, prog->filecrc);
785         MSG_WriteString (&client->netconnection->message,message);
786
787         SV_StopDemoRecording(client); // to split up demos into different files
788         if(sv_autodemo_perclient.integer)
789         {
790                 char demofile[MAX_OSPATH];
791                 char ipaddress[MAX_QPATH];
792                 size_t j;
793
794                 // start a new demo file
795                 LHNETADDRESS_ToString(&(client->netconnection->peeraddress), ipaddress, sizeof(ipaddress), true);
796                 for(j = 0; ipaddress[j]; ++j)
797                         if(!isalnum(ipaddress[j]))
798                                 ipaddress[j] = '-';
799                 dpsnprintf (demofile, sizeof(demofile), "%s_%s_%d_%s.dem", Sys_TimeString (sv_autodemo_perclient_nameformat.string), sv.worldbasename, PRVM_NUM_FOR_EDICT(client->edict), ipaddress);
800
801                 SV_StartDemoRecording(client, demofile, -1);
802         }
803
804         //[515]: init csprogs according to version of svprogs, check the crc, etc.
805         if (sv.csqc_progname[0])
806         {
807                 Con_DPrintf("sending csqc info to client (\"%s\" with size %i and crc %i)\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
808                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
809                 MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progname %s\n", sv.csqc_progname));
810                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
811                 MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progsize %i\n", sv.csqc_progsize));
812                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
813                 MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progcrc %i\n", sv.csqc_progcrc));
814
815                 if(client->sv_demo_file != NULL)
816                 {
817                         int k;
818                         static char buf[NET_MAXMESSAGE];
819                         sizebuf_t sb;
820
821                         sb.data = (unsigned char *) buf;
822                         sb.maxsize = sizeof(buf);
823                         k = 0;
824                         while(MakeDownloadPacket(sv.csqc_progname, svs.csqc_progdata, sv.csqc_progsize, sv.csqc_progcrc, k++, &sb, sv.protocol))
825                                 SV_WriteDemoMessage(client, &sb, false);
826                 }
827
828                 //[515]: init stufftext string (it is sent before svc_serverinfo)
829                 if (PRVM_GetString(prog, PRVM_serverglobalstring(SV_InitCmd)))
830                 {
831                         MSG_WriteByte (&client->netconnection->message, svc_stufftext);
832                         MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "%s\n", PRVM_GetString(prog, PRVM_serverglobalstring(SV_InitCmd))));
833                 }
834         }
835
836         //if (sv_allowdownloads.integer)
837         // always send the info that the server supports the protocol, even if downloads are forbidden
838         // only because of that, the CSQC exception can work
839         {
840                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
841                 MSG_WriteString (&client->netconnection->message, "cl_serverextension_download 2\n");
842         }
843
844         // send at this time so it's guaranteed to get executed at the right time
845         {
846                 client_t *save;
847                 save = host_client;
848                 host_client = client;
849                 Curl_SendRequirements();
850                 host_client = save;
851         }
852
853         MSG_WriteByte (&client->netconnection->message, svc_serverinfo);
854         MSG_WriteLong (&client->netconnection->message, Protocol_NumberForEnum(sv.protocol));
855         MSG_WriteByte (&client->netconnection->message, svs.maxclients);
856
857         if (!coop.integer && deathmatch.integer)
858                 MSG_WriteByte (&client->netconnection->message, GAME_DEATHMATCH);
859         else
860                 MSG_WriteByte (&client->netconnection->message, GAME_COOP);
861
862         MSG_WriteString (&client->netconnection->message,PRVM_GetString(prog, PRVM_serveredictstring(prog->edicts, message)));
863
864         for (i = 1;i < MAX_MODELS && sv.model_precache[i][0];i++)
865                 MSG_WriteString (&client->netconnection->message, sv.model_precache[i]);
866         MSG_WriteByte (&client->netconnection->message, 0);
867
868         for (i = 1;i < MAX_SOUNDS && sv.sound_precache[i][0];i++)
869                 MSG_WriteString (&client->netconnection->message, sv.sound_precache[i]);
870         MSG_WriteByte (&client->netconnection->message, 0);
871
872 // send music
873         MSG_WriteByte (&client->netconnection->message, svc_cdtrack);
874         MSG_WriteByte (&client->netconnection->message, (int)PRVM_serveredictfloat(prog->edicts, sounds));
875         MSG_WriteByte (&client->netconnection->message, (int)PRVM_serveredictfloat(prog->edicts, sounds));
876
877 // set view
878 // store this in clientcamera, too
879         client->clientcamera = PRVM_NUM_FOR_EDICT(client->edict);
880         MSG_WriteByte (&client->netconnection->message, svc_setview);
881         MSG_WriteShort (&client->netconnection->message, client->clientcamera);
882
883         MSG_WriteByte (&client->netconnection->message, svc_signonnum);
884         MSG_WriteByte (&client->netconnection->message, 1);
885
886         client->prespawned = false;             // need prespawn, spawn, etc
887         client->spawned = false;                // need prespawn, spawn, etc
888         client->begun = false;                  // need prespawn, spawn, etc
889         client->sendsignon = 1;                 // send this message, and increment to 2, 2 will be set to 0 by the prespawn command
890
891         // clear movement info until client enters the new level properly
892         memset(&client->cmd, 0, sizeof(client->cmd));
893         client->movesequence = 0;
894         client->movement_highestsequence_seen = 0;
895         memset(&client->movement_count, 0, sizeof(client->movement_count));
896         client->ping = 0;
897
898         // allow the client some time to send his keepalives, even if map loading took ages
899         client->netconnection->timeout = host.realtime + net_connecttimeout.value;
900 }
901
902 /*
903 ================
904 SV_ConnectClient
905
906 Initializes a client_t for a new net connection.  This will only be called
907 once for a player each game, not once for each level change.
908 ================
909 */
910 void SV_ConnectClient (int clientnum, netconn_t *netconnection)
911 {
912         prvm_prog_t *prog = SVVM_prog;
913         client_t                *client;
914         int                             i;
915
916         client = svs.clients + clientnum;
917
918 // set up the client_t
919         if (sv.loadgame)
920         {
921                 float backupparms[NUM_SPAWN_PARMS];
922                 memcpy(backupparms, client->spawn_parms, sizeof(backupparms));
923                 memset(client, 0, sizeof(*client));
924                 memcpy(client->spawn_parms, backupparms, sizeof(backupparms));
925         }
926         else
927                 memset(client, 0, sizeof(*client));
928         client->active = true;
929         client->netconnection = netconnection;
930
931         Con_DPrintf("Client %s connected\n", client->netconnection ? client->netconnection->address : "botclient");
932
933         if(client->netconnection && client->netconnection->crypto.authenticated)
934         {
935                 Con_Printf("%s connection to %s has been established: client is %s@%s%.*s, I am %.*s@%s%.*s\n",
936                                 client->netconnection->crypto.use_aes ? "Encrypted" : "Authenticated",
937                                 client->netconnection->address,
938                                 client->netconnection->crypto.client_idfp[0] ? client->netconnection->crypto.client_idfp : "-",
939                                 (client->netconnection->crypto.client_issigned || !client->netconnection->crypto.client_keyfp[0]) ? "" : "~",
940                                 crypto_keyfp_recommended_length, client->netconnection->crypto.client_keyfp[0] ? client->netconnection->crypto.client_keyfp : "-",
941                                 crypto_keyfp_recommended_length, client->netconnection->crypto.server_idfp[0] ? client->netconnection->crypto.server_idfp : "-",
942                                 (client->netconnection->crypto.server_issigned || !client->netconnection->crypto.server_keyfp[0]) ? "" : "~",
943                                 crypto_keyfp_recommended_length, client->netconnection->crypto.server_keyfp[0] ? client->netconnection->crypto.server_keyfp : "-"
944                                 );
945         }
946
947         strlcpy(client->name, "unconnected", sizeof(client->name));
948         strlcpy(client->old_name, "unconnected", sizeof(client->old_name));
949         client->prespawned = false;
950         client->spawned = false;
951         client->begun = false;
952         client->edict = PRVM_EDICT_NUM(clientnum+1);
953         if (client->netconnection)
954                 client->netconnection->message.allowoverflow = true;            // we can catch it
955         // prepare the unreliable message buffer
956         client->unreliablemsg.data = client->unreliablemsg_data;
957         client->unreliablemsg.maxsize = sizeof(client->unreliablemsg_data);
958         // updated by receiving "rate" command from client, this is also the default if not using a DP client
959         client->rate = 1000000000;
960         client->connecttime = host.realtime;
961
962         if (!sv.loadgame)
963         {
964                 // call the progs to get default spawn parms for the new client
965                 // set self to world to intentionally cause errors with broken SetNewParms code in some mods
966                 PRVM_serverglobalfloat(time) = sv.time;
967                 PRVM_serverglobaledict(self) = 0;
968                 prog->ExecuteProgram(prog, PRVM_serverfunction(SetNewParms), "QC function SetNewParms is missing");
969                 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
970                         client->spawn_parms[i] = (&PRVM_serverglobalfloat(parm1))[i];
971
972                 // set up the entity for this client (including .colormap, .team, etc)
973                 PRVM_ED_ClearEdict(prog, client->edict);
974         }
975
976         // don't call SendServerinfo for a fresh botclient because its fields have
977         // not been set up by the qc yet
978         if (client->netconnection)
979                 SV_SendServerinfo (client);
980         else
981                 client->prespawned = client->spawned = client->begun = true;
982 }
983
984 /*
985 =====================
986 SV_DropClient
987
988 Called when the player is getting totally kicked off the host
989 if (leaving = true), don't bother sending signofs
990 =====================
991 */
992 void SV_DropClient(qbool leaving, const char *fmt, ... )
993 {
994         prvm_prog_t *prog = SVVM_prog;
995         int i;
996
997         va_list argptr;
998         char reason[512] = "";
999
1000         Con_Printf("Client \"%s\" dropped", host_client->name);
1001
1002         if(fmt)
1003         {
1004                 va_start(argptr, fmt);
1005                 dpvsnprintf(reason, sizeof(reason), fmt, argptr);
1006                 va_end(argptr);
1007
1008                 Con_Printf(" (%s)\n", reason);
1009         }
1010         else
1011         {
1012                 Con_Printf(" \n");
1013         }
1014
1015         SV_StopDemoRecording(host_client);
1016
1017         // make sure edict is not corrupt (from a level change for example)
1018         host_client->edict = PRVM_EDICT_NUM(host_client - svs.clients + 1);
1019
1020         if (host_client->netconnection)
1021         {
1022                 // tell the client to be gone
1023                 if (!leaving)
1024                 {
1025                         // LadyHavoc: no opportunity for resending, so use unreliable 3 times
1026                         unsigned char bufdata[520]; // Disconnect reason string can be 512 characters
1027                         sizebuf_t buf;
1028                         memset(&buf, 0, sizeof(buf));
1029                         buf.data = bufdata;
1030                         buf.maxsize = sizeof(bufdata);
1031                         MSG_WriteByte(&buf, svc_disconnect);
1032                         if(fmt)
1033                         {
1034                                 if(sv.protocol == PROTOCOL_DARKPLACES8)
1035                                         MSG_WriteString(&buf, reason);
1036                                 else
1037                                         SV_ClientPrintf("%s\n", reason);
1038                         }
1039                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
1040                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
1041                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
1042                 }
1043         }
1044
1045         // call qc ClientDisconnect function
1046         // LadyHavoc: don't call QC if server is dead (avoids recursive
1047         // Host_Error in some mods when they run out of edicts)
1048         if (host_client->clientconnectcalled && sv.active && host_client->edict)
1049         {
1050                 // call the prog function for removing a client
1051                 // this will set the body to a dead frame, among other things
1052                 int saveSelf = PRVM_serverglobaledict(self);
1053                 host_client->clientconnectcalled = false;
1054                 PRVM_serverglobalfloat(time) = sv.time;
1055                 PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
1056                 prog->ExecuteProgram(prog, PRVM_serverfunction(ClientDisconnect), "QC function ClientDisconnect is missing");
1057                 PRVM_serverglobaledict(self) = saveSelf;
1058         }
1059
1060         if (host_client->netconnection)
1061         {
1062                 // break the net connection
1063                 NetConn_Close(host_client->netconnection);
1064                 host_client->netconnection = NULL;
1065         }
1066         if(fmt)
1067                 SV_BroadcastPrintf("\003^3%s left the game (%s)\n", host_client->name, reason);
1068         else
1069                 SV_BroadcastPrintf("\003^3%s left the game\n", host_client->name);
1070
1071         // if a download is active, close it
1072         if (host_client->download_file)
1073         {
1074                 Con_DPrintf("Download of %s aborted when %s dropped\n", host_client->download_name, host_client->name);
1075                 FS_Close(host_client->download_file);
1076                 host_client->download_file = NULL;
1077                 host_client->download_name[0] = 0;
1078                 host_client->download_expectedposition = 0;
1079                 host_client->download_started = false;
1080         }
1081
1082         // remove leaving player from scoreboard
1083         host_client->name[0] = 0;
1084         host_client->colors = 0;
1085         host_client->frags = 0;
1086         // send notification to all clients
1087         // get number of client manually just to make sure we get it right...
1088         i = host_client - svs.clients;
1089         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
1090         MSG_WriteByte (&sv.reliable_datagram, i);
1091         MSG_WriteString (&sv.reliable_datagram, host_client->name);
1092         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
1093         MSG_WriteByte (&sv.reliable_datagram, i);
1094         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
1095         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
1096         MSG_WriteByte (&sv.reliable_datagram, i);
1097         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
1098
1099         // free the client now
1100         if (host_client->entitydatabase)
1101                 EntityFrame_FreeDatabase(host_client->entitydatabase);
1102         if (host_client->entitydatabase4)
1103                 EntityFrame4_FreeDatabase(host_client->entitydatabase4);
1104         if (host_client->entitydatabase5)
1105                 EntityFrame5_FreeDatabase(host_client->entitydatabase5);
1106
1107         if (sv.active)
1108         {
1109                 // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
1110                 PRVM_ED_ClearEdict(prog, host_client->edict);
1111         }
1112
1113         // clear the client struct (this sets active to false)
1114         memset(host_client, 0, sizeof(*host_client));
1115
1116         // update server listing on the master because player count changed
1117         // (which the master uses for filtering empty/full servers)
1118         NetConn_Heartbeat(1);
1119
1120         if (sv.loadgame)
1121         {
1122                 for (i = 0;i < svs.maxclients;i++)
1123                         if (svs.clients[i].active && !svs.clients[i].spawned)
1124                                 break;
1125                 if (i == svs.maxclients)
1126                 {
1127                         Con_Printf("Loaded game, everyone rejoined - unpausing\n");
1128                         sv.paused = sv.loadgame = false; // we're basically done with loading now
1129                 }
1130         }
1131 }
1132
1133 static void SV_StartDownload_f(cmd_state_t *cmd)
1134 {
1135         if (host_client->download_file)
1136                 host_client->download_started = true;
1137 }
1138
1139 /*
1140  * Compression extension negotiation:
1141  *
1142  * Server to client:
1143  *   cl_serverextension_download 2
1144  *
1145  * Client to server:
1146  *   download <filename> <list of zero or more suppported compressions in order of preference>
1147  * e.g.
1148  *   download maps/map1.bsp lzo deflate huffman
1149  *
1150  * Server to client:
1151  *   cl_downloadbegin <compressed size> <filename> <compression method actually used>
1152  * e.g.
1153  *   cl_downloadbegin 123456 maps/map1.bsp deflate
1154  *
1155  * The server may choose not to compress the file by sending no compression name, like:
1156  *   cl_downloadbegin 345678 maps/map1.bsp
1157  *
1158  * NOTE: the "download" command may only specify compression algorithms if
1159  *       cl_serverextension_download is 2!
1160  *       If cl_serverextension_download has a different value, the client must
1161  *       assume this extension is not supported!
1162  */
1163
1164 static void Download_CheckExtensions(cmd_state_t *cmd)
1165 {
1166         int i;
1167         int argc = Cmd_Argc(cmd);
1168
1169         // first reset them all
1170         host_client->download_deflate = false;
1171         
1172         for(i = 2; i < argc; ++i)
1173         {
1174                 if(!strcmp(Cmd_Argv(cmd, i), "deflate"))
1175                 {
1176                         host_client->download_deflate = true;
1177                         break;
1178                 }
1179         }
1180 }
1181
1182 static void SV_Download_f(cmd_state_t *cmd)
1183 {
1184         const char *whichpack, *whichpack2, *extension;
1185         qbool is_csqc; // so we need to check only once
1186
1187         if (Cmd_Argc(cmd) < 2)
1188         {
1189                 SV_ClientPrintf("usage: download <filename> {<extensions>}*\n");
1190                 SV_ClientPrintf("       supported extensions: deflate\n");
1191                 return;
1192         }
1193
1194         if (FS_CheckNastyPath(Cmd_Argv(cmd, 1), false))
1195         {
1196                 SV_ClientPrintf("Download rejected: nasty filename \"%s\"\n", Cmd_Argv(cmd, 1));
1197                 return;
1198         }
1199
1200         if (host_client->download_file)
1201         {
1202                 // at this point we'll assume the previous download should be aborted
1203                 Con_DPrintf("Download of %s aborted by %s starting a new download\n", host_client->download_name, host_client->name);
1204                 SV_ClientCommands("\nstopdownload\n");
1205
1206                 // close the file and reset variables
1207                 FS_Close(host_client->download_file);
1208                 host_client->download_file = NULL;
1209                 host_client->download_name[0] = 0;
1210                 host_client->download_expectedposition = 0;
1211                 host_client->download_started = false;
1212         }
1213
1214         is_csqc = (sv.csqc_progname[0] && strcmp(Cmd_Argv(cmd, 1), sv.csqc_progname) == 0);
1215         
1216         if (!sv_allowdownloads.integer && !is_csqc)
1217         {
1218                 SV_ClientPrintf("Downloads are disabled on this server\n");
1219                 SV_ClientCommands("\nstopdownload\n");
1220                 return;
1221         }
1222
1223         Download_CheckExtensions(cmd);
1224
1225         strlcpy(host_client->download_name, Cmd_Argv(cmd, 1), sizeof(host_client->download_name));
1226         extension = FS_FileExtension(host_client->download_name);
1227
1228         // host_client is asking to download a specified file
1229         if (developer_extra.integer)
1230                 Con_DPrintf("Download request for %s by %s\n", host_client->download_name, host_client->name);
1231
1232         if(is_csqc)
1233         {
1234                 char extensions[MAX_QPATH]; // make sure this can hold all extensions
1235                 extensions[0] = '\0';
1236                 
1237                 if(host_client->download_deflate)
1238                         strlcat(extensions, " deflate", sizeof(extensions));
1239                 
1240                 Con_DPrintf("Downloading %s to %s\n", host_client->download_name, host_client->name);
1241
1242                 if(host_client->download_deflate && svs.csqc_progdata_deflated)
1243                         host_client->download_file = FS_FileFromData(svs.csqc_progdata_deflated, svs.csqc_progsize_deflated, true);
1244                 else
1245                         host_client->download_file = FS_FileFromData(svs.csqc_progdata, sv.csqc_progsize, true);
1246                 
1247                 // no, no space is needed between %s and %s :P
1248                 SV_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
1249
1250                 host_client->download_expectedposition = 0;
1251                 host_client->download_started = false;
1252                 host_client->sendsignon = true; // make sure this message is sent
1253                 return;
1254         }
1255
1256         if (!FS_FileExists(host_client->download_name))
1257         {
1258                 SV_ClientPrintf("Download rejected: server does not have the file \"%s\"\nYou may need to separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
1259                 SV_ClientCommands("\nstopdownload\n");
1260                 return;
1261         }
1262
1263         // check if the user is trying to download part of registered Quake(r)
1264         whichpack = FS_WhichPack(host_client->download_name);
1265         whichpack2 = FS_WhichPack("gfx/pop.lmp");
1266         if ((whichpack && whichpack2 && !strcasecmp(whichpack, whichpack2)) || FS_IsRegisteredQuakePack(host_client->download_name))
1267         {
1268                 SV_ClientPrintf("Download rejected: file \"%s\" is part of registered Quake(r)\nYou must purchase Quake(r) from id Software or a retailer to get this file\nPlease go to http://www.idsoftware.com/games/quake/quake/index.php?game_section=buy\n", host_client->download_name);
1269                 SV_ClientCommands("\nstopdownload\n");
1270                 return;
1271         }
1272
1273         // check if the server has forbidden archive downloads entirely
1274         if (!sv_allowdownloads_inarchive.integer)
1275         {
1276                 whichpack = FS_WhichPack(host_client->download_name);
1277                 if (whichpack)
1278                 {
1279                         SV_ClientPrintf("Download rejected: file \"%s\" is in an archive (\"%s\")\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name, whichpack);
1280                         SV_ClientCommands("\nstopdownload\n");
1281                         return;
1282                 }
1283         }
1284
1285         if (!sv_allowdownloads_config.integer)
1286         {
1287                 if (!strcasecmp(extension, "cfg"))
1288                 {
1289                         SV_ClientPrintf("Download rejected: file \"%s\" is a .cfg file which is forbidden for security reasons\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
1290                         SV_ClientCommands("\nstopdownload\n");
1291                         return;
1292                 }
1293         }
1294
1295         if (!sv_allowdownloads_dlcache.integer)
1296         {
1297                 if (!strncasecmp(host_client->download_name, "dlcache/", 8))
1298                 {
1299                         SV_ClientPrintf("Download rejected: file \"%s\" is in the dlcache/ directory which is forbidden for security reasons\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
1300                         SV_ClientCommands("\nstopdownload\n");
1301                         return;
1302                 }
1303         }
1304
1305         if (!sv_allowdownloads_archive.integer)
1306         {
1307                 if (!strcasecmp(extension, "pak") || !strcasecmp(extension, "pk3") || !strcasecmp(extension, "dpk"))
1308                 {
1309                         SV_ClientPrintf("Download rejected: file \"%s\" is an archive\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
1310                         SV_ClientCommands("\nstopdownload\n");
1311                         return;
1312                 }
1313         }
1314
1315         host_client->download_file = FS_OpenVirtualFile(host_client->download_name, true);
1316         if (!host_client->download_file)
1317         {
1318                 SV_ClientPrintf("Download rejected: server could not open the file \"%s\"\n", host_client->download_name);
1319                 SV_ClientCommands("\nstopdownload\n");
1320                 return;
1321         }
1322
1323         if (FS_FileSize(host_client->download_file) > 1<<30)
1324         {
1325                 SV_ClientPrintf("Download rejected: file \"%s\" is very large\n", host_client->download_name);
1326                 SV_ClientCommands("\nstopdownload\n");
1327                 FS_Close(host_client->download_file);
1328                 host_client->download_file = NULL;
1329                 return;
1330         }
1331
1332         if (FS_FileSize(host_client->download_file) < 0)
1333         {
1334                 SV_ClientPrintf("Download rejected: file \"%s\" is not a regular file\n", host_client->download_name);
1335                 SV_ClientCommands("\nstopdownload\n");
1336                 FS_Close(host_client->download_file);
1337                 host_client->download_file = NULL;
1338                 return;
1339         }
1340
1341         Con_DPrintf("Downloading %s to %s\n", host_client->download_name, host_client->name);
1342
1343         /*
1344          * we can only do this if we would actually deflate on the fly
1345          * which we do not (yet)!
1346         {
1347                 char extensions[MAX_QPATH]; // make sure this can hold all extensions
1348                 extensions[0] = '\0';
1349                 
1350                 if(host_client->download_deflate)
1351                         strlcat(extensions, " deflate", sizeof(extensions));
1352
1353                 // no, no space is needed between %s and %s :P
1354                 SV_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
1355         }
1356         */
1357         SV_ClientCommands("\ncl_downloadbegin %i %s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name);
1358
1359         host_client->download_expectedposition = 0;
1360         host_client->download_started = false;
1361         host_client->sendsignon = true; // make sure this message is sent
1362
1363         // the rest of the download process is handled in SV_SendClientDatagram
1364         // and other code dealing with svc_downloaddata and clc_ackdownloaddata
1365         //
1366         // no svc_downloaddata messages will be sent until sv_startdownload is
1367         // sent by the client
1368 }
1369
1370 /*
1371 ==============================================================================
1372
1373 SERVER SPAWNING
1374
1375 ==============================================================================
1376 */
1377
1378 /*
1379 ================
1380 SV_ModelIndex
1381
1382 ================
1383 */
1384 int SV_ModelIndex(const char *s, int precachemode)
1385 {
1386         int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE) ? 256 : MAX_MODELS);
1387         char filename[MAX_QPATH];
1388         if (!s || !*s)
1389                 return 0;
1390         // testing
1391         //if (precachemode == 2)
1392         //      return 0;
1393         strlcpy(filename, s, sizeof(filename));
1394         for (i = 2;i < limit;i++)
1395         {
1396                 if (!sv.model_precache[i][0])
1397                 {
1398                         if (precachemode)
1399                         {
1400                                 if (sv.state != ss_loading && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5))
1401                                 {
1402                                         Con_Printf("SV_ModelIndex(\"%s\"): precache_model can only be done in spawn functions\n", filename);
1403                                         return 0;
1404                                 }
1405                                 if (precachemode == 1)
1406                                         Con_Printf("SV_ModelIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
1407                                 strlcpy(sv.model_precache[i], filename, sizeof(sv.model_precache[i]));
1408                                 if (sv.state == ss_loading)
1409                                 {
1410                                         // running from SV_SpawnServer which is launched from the client console command interpreter
1411                                         sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.worldname : NULL);
1412                                 }
1413                                 else
1414                                 {
1415                                         if (svs.threaded)
1416                                         {
1417                                                 // this is running on the server thread, we can't load a model here (it would crash on renderer calls), so only look it up, the svc_precache will cause it to be loaded when it reaches the client
1418                                                 sv.models[i] = Mod_FindName (sv.model_precache[i], s[0] == '*' ? sv.worldname : NULL);
1419                                         }
1420                                         else
1421                                         {
1422                                                 // running single threaded, so we can load the model here
1423                                                 sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.worldname : NULL);
1424                                         }
1425                                         MSG_WriteByte(&sv.reliable_datagram, svc_precache);
1426                                         MSG_WriteShort(&sv.reliable_datagram, i);
1427                                         MSG_WriteString(&sv.reliable_datagram, filename);
1428                                 }
1429                                 return i;
1430                         }
1431                         Con_Printf("SV_ModelIndex(\"%s\"): not precached\n", filename);
1432                         return 0;
1433                 }
1434                 if (!strcmp(sv.model_precache[i], filename))
1435                         return i;
1436         }
1437         Con_Printf("SV_ModelIndex(\"%s\"): i (%i) == MAX_MODELS (%i)\n", filename, i, MAX_MODELS);
1438         return 0;
1439 }
1440
1441 /*
1442 ================
1443 SV_SoundIndex
1444
1445 ================
1446 */
1447 int SV_SoundIndex(const char *s, int precachemode)
1448 {
1449         int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP) ? 256 : MAX_SOUNDS);
1450         char filename[MAX_QPATH];
1451         if (!s || !*s)
1452                 return 0;
1453         // testing
1454         //if (precachemode == 2)
1455         //      return 0;
1456         strlcpy(filename, s, sizeof(filename));
1457         for (i = 1;i < limit;i++)
1458         {
1459                 if (!sv.sound_precache[i][0])
1460                 {
1461                         if (precachemode)
1462                         {
1463                                 if (sv.state != ss_loading && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5))
1464                                 {
1465                                         Con_Printf("SV_SoundIndex(\"%s\"): precache_sound can only be done in spawn functions\n", filename);
1466                                         return 0;
1467                                 }
1468                                 if (precachemode == 1)
1469                                         Con_Printf("SV_SoundIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
1470                                 strlcpy(sv.sound_precache[i], filename, sizeof(sv.sound_precache[i]));
1471                                 if (sv.state != ss_loading)
1472                                 {
1473                                         MSG_WriteByte(&sv.reliable_datagram, svc_precache);
1474                                         MSG_WriteShort(&sv.reliable_datagram, i + 32768);
1475                                         MSG_WriteString(&sv.reliable_datagram, filename);
1476                                 }
1477                                 return i;
1478                         }
1479                         Con_Printf("SV_SoundIndex(\"%s\"): not precached\n", filename);
1480                         return 0;
1481                 }
1482                 if (!strcmp(sv.sound_precache[i], filename))
1483                         return i;
1484         }
1485         Con_Printf("SV_SoundIndex(\"%s\"): i (%i) == MAX_SOUNDS (%i)\n", filename, i, MAX_SOUNDS);
1486         return 0;
1487 }
1488
1489 /*
1490 ================
1491 SV_ParticleEffectIndex
1492
1493 ================
1494 */
1495 int SV_ParticleEffectIndex(const char *name)
1496 {
1497         int i, argc, linenumber, effectnameindex;
1498         int filepass;
1499         fs_offset_t filesize;
1500         unsigned char *filedata;
1501         const char *text;
1502         const char *textstart;
1503         //const char *textend;
1504         char argv[16][1024];
1505         char filename[MAX_QPATH];
1506         if (!sv.particleeffectnamesloaded)
1507         {
1508                 sv.particleeffectnamesloaded = true;
1509                 memset(sv.particleeffectname, 0, sizeof(sv.particleeffectname));
1510                 for (i = 0;i < EFFECT_TOTAL;i++)
1511                         strlcpy(sv.particleeffectname[i], standardeffectnames[i], sizeof(sv.particleeffectname[i]));
1512                 for (filepass = 0;;filepass++)
1513                 {
1514                         if (filepass == 0)
1515                                 dpsnprintf(filename, sizeof(filename), "effectinfo.txt");
1516                         else if (filepass == 1)
1517                                 dpsnprintf(filename, sizeof(filename), "%s_effectinfo.txt", sv.worldnamenoextension);
1518                         else
1519                                 break;
1520                         filedata = FS_LoadFile(filename, tempmempool, true, &filesize);
1521                         if (!filedata)
1522                                 continue;
1523                         textstart = (const char *)filedata;
1524                         //textend = (const char *)filedata + filesize;
1525                         text = textstart;
1526                         for (linenumber = 1;;linenumber++)
1527                         {
1528                                 argc = 0;
1529                                 for (;;)
1530                                 {
1531                                         if (!COM_ParseToken_Simple(&text, true, false, true) || !strcmp(com_token, "\n"))
1532                                                 break;
1533                                         if (argc < 16)
1534                                         {
1535                                                 strlcpy(argv[argc], com_token, sizeof(argv[argc]));
1536                                                 argc++;
1537                                         }
1538                                 }
1539                                 if (com_token[0] == 0)
1540                                         break; // if the loop exited and it's not a \n, it's EOF
1541                                 if (argc < 1)
1542                                         continue;
1543                                 if (!strcmp(argv[0], "effect"))
1544                                 {
1545                                         if (argc == 2)
1546                                         {
1547                                                 for (effectnameindex = 1;effectnameindex < MAX_PARTICLEEFFECTNAME;effectnameindex++)
1548                                                 {
1549                                                         if (sv.particleeffectname[effectnameindex][0])
1550                                                         {
1551                                                                 if (!strcmp(sv.particleeffectname[effectnameindex], argv[1]))
1552                                                                         break;
1553                                                         }
1554                                                         else
1555                                                         {
1556                                                                 strlcpy(sv.particleeffectname[effectnameindex], argv[1], sizeof(sv.particleeffectname[effectnameindex]));
1557                                                                 break;
1558                                                         }
1559                                                 }
1560                                                 // if we run out of names, abort
1561                                                 if (effectnameindex == MAX_PARTICLEEFFECTNAME)
1562                                                 {
1563                                                         Con_Printf("%s:%i: too many effects!\n", filename, linenumber);
1564                                                         break;
1565                                                 }
1566                                         }
1567                                 }
1568                         }
1569                         Mem_Free(filedata);
1570                 }
1571         }
1572         // search for the name
1573         for (effectnameindex = 1;effectnameindex < MAX_PARTICLEEFFECTNAME && sv.particleeffectname[effectnameindex][0];effectnameindex++)
1574                 if (!strcmp(sv.particleeffectname[effectnameindex], name))
1575                         return effectnameindex;
1576         // return 0 if we couldn't find it
1577         return 0;
1578 }
1579
1580 model_t *SV_GetModelByIndex(int modelindex)
1581 {
1582         return (modelindex > 0 && modelindex < MAX_MODELS) ? sv.models[modelindex] : NULL;
1583 }
1584
1585 model_t *SV_GetModelFromEdict(prvm_edict_t *ed)
1586 {
1587         prvm_prog_t *prog = SVVM_prog;
1588         int modelindex;
1589         if (!ed || ed->free)
1590                 return NULL;
1591         modelindex = (int)PRVM_serveredictfloat(ed, modelindex);
1592         return (modelindex > 0 && modelindex < MAX_MODELS) ? sv.models[modelindex] : NULL;
1593 }
1594
1595 /*
1596 ================
1597 SV_CreateBaseline
1598
1599 ================
1600 */
1601 static void SV_CreateBaseline (void)
1602 {
1603         prvm_prog_t *prog = SVVM_prog;
1604         int i, entnum, large;
1605         prvm_edict_t *svent;
1606
1607         // LadyHavoc: clear *all* baselines (not just active ones)
1608         for (entnum = 0;entnum < prog->max_edicts;entnum++)
1609         {
1610                 // get the current server version
1611                 svent = PRVM_EDICT_NUM(entnum);
1612
1613                 // LadyHavoc: always clear state values, whether the entity is in use or not
1614                 svent->priv.server->baseline = defaultstate;
1615
1616                 if (svent->free)
1617                         continue;
1618                 if (entnum > svs.maxclients && !PRVM_serveredictfloat(svent, modelindex))
1619                         continue;
1620
1621                 // create entity baseline
1622                 VectorCopy (PRVM_serveredictvector(svent, origin), svent->priv.server->baseline.origin);
1623                 VectorCopy (PRVM_serveredictvector(svent, angles), svent->priv.server->baseline.angles);
1624                 svent->priv.server->baseline.frame = (int)PRVM_serveredictfloat(svent, frame);
1625                 svent->priv.server->baseline.skin = (int)PRVM_serveredictfloat(svent, skin);
1626                 if (entnum > 0 && entnum <= svs.maxclients)
1627                 {
1628                         svent->priv.server->baseline.colormap = entnum;
1629                         svent->priv.server->baseline.modelindex = SV_ModelIndex("progs/player.mdl", 1);
1630                 }
1631                 else
1632                 {
1633                         svent->priv.server->baseline.colormap = 0;
1634                         svent->priv.server->baseline.modelindex = (int)PRVM_serveredictfloat(svent, modelindex);
1635                 }
1636
1637                 large = false;
1638                 if (svent->priv.server->baseline.modelindex & 0xFF00 || svent->priv.server->baseline.frame & 0xFF00)
1639                 {
1640                         large = true;
1641                         if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
1642                                 large = false;
1643                 }
1644
1645                 // add to the message
1646                 if (large)
1647                         MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1648                 else
1649                         MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1650                 MSG_WriteShort (&sv.signon, entnum);
1651
1652                 if (large)
1653                 {
1654                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.modelindex);
1655                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.frame);
1656                 }
1657                 else if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
1658                 {
1659                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.modelindex);
1660                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.frame);
1661                 }
1662                 else
1663                 {
1664                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.modelindex);
1665                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.frame);
1666                 }
1667                 MSG_WriteByte (&sv.signon, svent->priv.server->baseline.colormap);
1668                 MSG_WriteByte (&sv.signon, svent->priv.server->baseline.skin);
1669                 for (i=0 ; i<3 ; i++)
1670                 {
1671                         MSG_WriteCoord(&sv.signon, svent->priv.server->baseline.origin[i], sv.protocol);
1672                         MSG_WriteAngle(&sv.signon, svent->priv.server->baseline.angles[i], sv.protocol);
1673                 }
1674         }
1675 }
1676
1677 /*
1678 ================
1679 SV_Prepare_CSQC
1680
1681 Load csprogs.dat and comperss it so it doesn't need to be
1682 reloaded on request.
1683 ================
1684 */
1685 static void SV_Prepare_CSQC(void)
1686 {
1687         fs_offset_t progsize;
1688
1689         if(svs.csqc_progdata)
1690         {
1691                 Con_DPrintf("Unloading old CSQC data.\n");
1692                 Mem_Free(svs.csqc_progdata);
1693                 if(svs.csqc_progdata_deflated)
1694                         Mem_Free(svs.csqc_progdata_deflated);
1695         }
1696
1697         svs.csqc_progdata = NULL;
1698         svs.csqc_progdata_deflated = NULL;
1699         
1700         sv.csqc_progname[0] = 0;
1701         svs.csqc_progdata = FS_LoadFile(csqc_progname.string, sv_mempool, false, &progsize);
1702
1703         if(progsize > 0)
1704         {
1705                 size_t deflated_size;
1706
1707                 sv.csqc_progsize = (int)progsize;
1708                 sv.csqc_progcrc = CRC_Block(svs.csqc_progdata, progsize);
1709                 strlcpy(sv.csqc_progname, csqc_progname.string, sizeof(sv.csqc_progname));
1710                 Con_DPrintf("server detected csqc progs file \"%s\" with size %i and crc %i\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
1711
1712                 Con_DPrint("Compressing csprogs.dat\n");
1713                 //unsigned char *FS_Deflate(const unsigned char *data, size_t size, size_t *deflated_size, int level, mempool_t *mempool);
1714                 svs.csqc_progdata_deflated = FS_Deflate(svs.csqc_progdata, progsize, &deflated_size, -1, sv_mempool);
1715                 svs.csqc_progsize_deflated = (int)deflated_size;
1716                 if(svs.csqc_progdata_deflated)
1717                 {
1718                         Con_DPrintf("Deflated: %g%%\n", 100.0 - 100.0 * (deflated_size / (float)progsize));
1719                         Con_DPrintf("Uncompressed: %u\nCompressed:   %u\n", (unsigned)sv.csqc_progsize, (unsigned)svs.csqc_progsize_deflated);
1720                 }
1721                 else
1722                         Con_DPrintf("Cannot compress - need zlib for this. Using uncompressed progs only.\n");
1723         }
1724 }
1725
1726 /*
1727 ================
1728 SV_SaveSpawnparms
1729
1730 Grabs the current state of each client for saving across the
1731 transition to another level
1732 ================
1733 */
1734 void SV_SaveSpawnparms (void)
1735 {
1736         prvm_prog_t *prog = SVVM_prog;
1737         int             i, j;
1738
1739         svs.serverflags = (int)PRVM_serverglobalfloat(serverflags);
1740
1741         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1742         {
1743                 if (!host_client->active)
1744                         continue;
1745
1746         // call the progs to get default spawn parms for the new client
1747                 PRVM_serverglobalfloat(time) = sv.time;
1748                 PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
1749                 prog->ExecuteProgram(prog, PRVM_serverfunction(SetChangeParms), "QC function SetChangeParms is missing");
1750                 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1751                         host_client->spawn_parms[j] = (&PRVM_serverglobalfloat(parm1))[j];
1752         }
1753 }
1754
1755 // Returns 1 if we're singleplayer, > 1 if we're a listen server
1756 int SV_IsLocalServer(void)
1757 {
1758         return (host_isclient.integer && sv.active ? svs.maxclients : 0);
1759 }
1760
1761 /*
1762 ================
1763 SV_SpawnServer
1764
1765 This is called at the start of each level
1766 ================
1767 */
1768
1769 void SV_SpawnServer (const char *map)
1770 {
1771         prvm_prog_t *prog = SVVM_prog;
1772         prvm_edict_t *ent;
1773         int i;
1774         char *entities;
1775         model_t *worldmodel;
1776         char modelname[sizeof(sv.worldname)];
1777         char vabuf[1024];
1778
1779         Con_Printf("SpawnServer: %s\n", map);
1780
1781         dpsnprintf (modelname, sizeof(modelname), "maps/%s.bsp", map);
1782
1783         if (!FS_FileExists(modelname))
1784         {
1785                 dpsnprintf (modelname, sizeof(modelname), "maps/%s", map);
1786                 if (!FS_FileExists(modelname))
1787                 {
1788                         Con_Printf("SpawnServer: no map file named %s\n", modelname);
1789                         return;
1790                 }
1791         }
1792
1793 //      SV_LockThreadMutex();
1794
1795         if(!host_isclient.integer)
1796                 Sys_MakeProcessNice();
1797         else
1798         {
1799                 SCR_BeginLoadingPlaque(false);
1800                 S_StopAllSounds();
1801         }
1802
1803         if(sv.active)
1804         {
1805                 World_End(&sv.world);
1806                 if(PRVM_serverfunction(SV_Shutdown))
1807                 {
1808                         func_t s = PRVM_serverfunction(SV_Shutdown);
1809                         PRVM_serverglobalfloat(time) = sv.time;
1810                         PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
1811                         prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
1812                 }
1813         }
1814
1815         // free q3 shaders so that any newly downloaded shaders will be active
1816         Mod_FreeQ3Shaders();
1817
1818         worldmodel = Mod_ForName(modelname, false, developer.integer > 0, NULL);
1819         if (!worldmodel || !worldmodel->TraceBox)
1820         {
1821                 Con_Printf("Couldn't load map %s\n", modelname);
1822
1823                 if(!host_isclient.integer)
1824                         Sys_MakeProcessMean();
1825
1826 //              SV_UnlockThreadMutex();
1827
1828                 return;
1829         }
1830
1831         Collision_Cache_Reset(true);
1832
1833         // let's not have any servers with no name
1834         if (hostname.string[0] == 0)
1835                 Cvar_SetQuick(&hostname, "UNNAMED");
1836         scr_centertime_off = 0;
1837
1838         svs.changelevel_issued = false;         // now safe to issue another
1839
1840         // make the map a required file for clients
1841         Curl_ClearRequirements();
1842         Curl_RequireFile(modelname);
1843
1844 //
1845 // tell all connected clients that we are going to a new level
1846 //
1847         if (sv.active)
1848         {
1849                 client_t *client;
1850                 for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
1851                 {
1852                         if (client->netconnection)
1853                         {
1854                                 MSG_WriteByte(&client->netconnection->message, svc_stufftext);
1855                                 MSG_WriteString(&client->netconnection->message, "reconnect\n");
1856                         }
1857                 }
1858         }
1859         else
1860         {
1861                 // open server port
1862                 NetConn_OpenServerPorts(true);
1863         }
1864
1865 //
1866 // make cvars consistant
1867 //
1868
1869         if (coop.integer)
1870         {
1871                 Cvar_SetValueQuick(&deathmatch, 0);
1872                 Cvar_SetValueQuick(&campaign, 0);
1873         }
1874         else if(!deathmatch.integer)
1875                 Cvar_SetValueQuick(&campaign, 1);
1876         else
1877                 Cvar_SetValueQuick(&campaign, 0);
1878         // LadyHavoc: it can be useful to have skills outside the range 0-3...
1879         //current_skill = bound(0, (int)(skill.value + 0.5), 3);
1880         //Cvar_SetValue ("skill", (float)current_skill);
1881         current_skill = (int)(skill.value + 0.5);
1882
1883 //
1884 // set up the new server
1885 //
1886         memset (&sv, 0, sizeof(sv));
1887         // if running a local client, make sure it doesn't try to access the last
1888         // level's data which is no longer valiud
1889         cls.signon = 0;
1890
1891         Cvar_SetValueQuick(&halflifebsp, worldmodel->brush.ishlbsp);
1892         Cvar_SetValueQuick(&sv_mapformat_is_quake2, worldmodel->brush.isq2bsp);
1893         Cvar_SetValueQuick(&sv_mapformat_is_quake3, worldmodel->brush.isq3bsp);
1894
1895         if(*sv_random_seed.string)
1896         {
1897                 srand(sv_random_seed.integer);
1898                 Con_Printf(CON_WARN "NOTE: random seed is %d; use for debugging/benchmarking only!\nUnset sv_random_seed to get real random numbers again.\n", sv_random_seed.integer);
1899         }
1900
1901         SV_VM_Setup();
1902
1903         sv.active = true;
1904
1905         // set level base name variables for later use
1906         strlcpy (sv.name, map, sizeof (sv.name));
1907         strlcpy(sv.worldname, modelname, sizeof(sv.worldname));
1908         FS_StripExtension(sv.worldname, sv.worldnamenoextension, sizeof(sv.worldnamenoextension));
1909         strlcpy(sv.worldbasename, !strncmp(sv.worldnamenoextension, "maps/", 5) ? sv.worldnamenoextension + 5 : sv.worldnamenoextension, sizeof(sv.worldbasename));
1910         //Cvar_SetQuick(&sv_worldmessage, sv.worldmessage); // set later after QC is spawned
1911         Cvar_SetQuick(&sv_worldname, sv.worldname);
1912         Cvar_SetQuick(&sv_worldnamenoextension, sv.worldnamenoextension);
1913         Cvar_SetQuick(&sv_worldbasename, sv.worldbasename);
1914
1915         sv.protocol = Protocol_EnumForName(sv_protocolname.string);
1916         if (sv.protocol == PROTOCOL_UNKNOWN)
1917         {
1918                 char buffer[1024];
1919                 Protocol_Names(buffer, sizeof(buffer));
1920                 Con_Printf(CON_ERROR "Unknown sv_protocolname \"%s\", valid values are:\n%s\n", sv_protocolname.string, buffer);
1921                 sv.protocol = PROTOCOL_QUAKE;
1922         }
1923
1924 // load progs to get entity field count
1925         //PR_LoadProgs ( sv_progs.string );
1926
1927         sv.datagram.maxsize = sizeof(sv.datagram_buf);
1928         sv.datagram.cursize = 0;
1929         sv.datagram.data = sv.datagram_buf;
1930
1931         sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1932         sv.reliable_datagram.cursize = 0;
1933         sv.reliable_datagram.data = sv.reliable_datagram_buf;
1934
1935         sv.signon.maxsize = sizeof(sv.signon_buf);
1936         sv.signon.cursize = 0;
1937         sv.signon.data = sv.signon_buf;
1938
1939 // leave slots at start for clients only
1940         //prog->num_edicts = svs.maxclients+1;
1941
1942         sv.state = ss_loading;
1943         prog->allowworldwrites = true;
1944         sv.paused = false;
1945
1946         sv.time = 1.0;
1947
1948         Mod_ClearUsed();
1949         worldmodel->used = true;
1950
1951         sv.worldmodel = worldmodel;
1952         sv.models[1] = sv.worldmodel;
1953
1954 //
1955 // clear world interaction links
1956 //
1957         World_SetSize(&sv.world, sv.worldname, sv.worldmodel->normalmins, sv.worldmodel->normalmaxs, prog);
1958         World_Start(&sv.world);
1959
1960         strlcpy(sv.sound_precache[0], "", sizeof(sv.sound_precache[0]));
1961
1962         strlcpy(sv.model_precache[0], "", sizeof(sv.model_precache[0]));
1963         strlcpy(sv.model_precache[1], sv.worldname, sizeof(sv.model_precache[1]));
1964         for (i = 1;i < sv.worldmodel->brush.numsubmodels && i+1 < MAX_MODELS;i++)
1965         {
1966                 dpsnprintf(sv.model_precache[i+1], sizeof(sv.model_precache[i+1]), "*%i", i);
1967                 sv.models[i+1] = Mod_ForName (sv.model_precache[i+1], false, false, sv.worldname);
1968         }
1969         if(i < sv.worldmodel->brush.numsubmodels)
1970                 Con_Printf("Too many submodels (MAX_MODELS is %i)\n", MAX_MODELS);
1971
1972 //
1973 // load the rest of the entities
1974 //
1975         // AK possible hack since num_edicts is still 0
1976         ent = PRVM_EDICT_NUM(0);
1977         memset (ent->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
1978         ent->free = false;
1979         PRVM_serveredictstring(ent, model) = PRVM_SetEngineString(prog, sv.worldname);
1980         PRVM_serveredictfloat(ent, modelindex) = 1;             // world model
1981         PRVM_serveredictfloat(ent, solid) = SOLID_BSP;
1982         PRVM_serveredictfloat(ent, movetype) = MOVETYPE_PUSH;
1983         VectorCopy(sv.world.mins, PRVM_serveredictvector(ent, mins));
1984         VectorCopy(sv.world.maxs, PRVM_serveredictvector(ent, maxs));
1985         VectorCopy(sv.world.mins, PRVM_serveredictvector(ent, absmin));
1986         VectorCopy(sv.world.maxs, PRVM_serveredictvector(ent, absmax));
1987
1988         if (coop.value)
1989                 PRVM_serverglobalfloat(coop) = coop.integer;
1990         else
1991                 PRVM_serverglobalfloat(deathmatch) = deathmatch.integer;
1992
1993         PRVM_serverglobalstring(mapname) = PRVM_SetEngineString(prog, sv.name);
1994
1995 // serverflags are for cross level information (sigils)
1996         PRVM_serverglobalfloat(serverflags) = svs.serverflags;
1997
1998         // we need to reset the spawned flag on all connected clients here so that
1999         // their thinks don't run during startup (before PutClientInServer)
2000         // we also need to set up the client entities now
2001         // and we need to set the ->edict pointers to point into the progs edicts
2002         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2003         {
2004                 host_client->begun = false;
2005                 host_client->edict = PRVM_EDICT_NUM(i + 1);
2006                 PRVM_ED_ClearEdict(prog, host_client->edict);
2007         }
2008
2009         // load replacement entity file if found
2010         if (sv_entpatch.integer && (entities = (char *)FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.ent", sv.worldnamenoextension), tempmempool, true, NULL)))
2011         {
2012                 Con_Printf("Loaded %s.ent\n", sv.worldnamenoextension);
2013                 PRVM_ED_LoadFromFile(prog, entities);
2014                 Mem_Free(entities);
2015         }
2016         else
2017                 PRVM_ED_LoadFromFile(prog, sv.worldmodel->brush.entities);
2018
2019
2020         // LadyHavoc: clear world angles (to fix e3m3.bsp)
2021         VectorClear(PRVM_serveredictvector(prog->edicts, angles));
2022
2023 // all setup is completed, any further precache statements are errors
2024 //      sv.state = ss_active; // LadyHavoc: workaround for svc_precache bug
2025         prog->allowworldwrites = false;
2026
2027 // run two frames to allow everything to settle
2028         sv.time = 1.0001;
2029         for (i = 0;i < sv_init_frame_count.integer;i++)
2030         {
2031                 sv.frametime = 0.1;
2032                 SV_Physics ();
2033         }
2034
2035         // Once all init frames have been run, we consider svqc code fully initialized.
2036         prog->inittime = host.realtime;
2037
2038         if(!host_isclient.integer)
2039                 Mod_PurgeUnused();
2040
2041 // create a baseline for more efficient communications
2042         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
2043                 SV_CreateBaseline ();
2044
2045         sv.state = ss_active; // LadyHavoc: workaround for svc_precache bug
2046
2047 // send serverinfo to all connected clients, and set up botclients coming back from a level change
2048         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2049         {
2050                 host_client->clientconnectcalled = false; // do NOT call ClientDisconnect if he drops before ClientConnect!
2051                 if (!host_client->active)
2052                         continue;
2053                 if (host_client->netconnection)
2054                         SV_SendServerinfo(host_client);
2055                 else
2056                 {
2057                         int j;
2058                         // if client is a botclient coming from a level change, we need to
2059                         // set up client info that normally requires networking
2060
2061                         // copy spawn parms out of the client_t
2062                         for (j=0 ; j< NUM_SPAWN_PARMS ; j++)
2063                                 (&PRVM_serverglobalfloat(parm1))[j] = host_client->spawn_parms[j];
2064
2065                         // call the spawn function
2066                         host_client->clientconnectcalled = true;
2067                         PRVM_serverglobalfloat(time) = sv.time;
2068                         PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
2069                         prog->ExecuteProgram(prog, PRVM_serverfunction(ClientConnect), "QC function ClientConnect is missing");
2070                         prog->ExecuteProgram(prog, PRVM_serverfunction(PutClientInServer), "QC function PutClientInServer is missing");
2071                         host_client->begun = true;
2072                 }
2073         }
2074
2075         // update the map title cvar
2076         strlcpy(sv.worldmessage, PRVM_GetString(prog, PRVM_serveredictstring(prog->edicts, message)), sizeof(sv.worldmessage)); // map title (not related to filename)
2077         Cvar_SetQuick(&sv_worldmessage, sv.worldmessage);
2078
2079         Con_Printf("Server spawned.\n");
2080         NetConn_Heartbeat (2);
2081
2082         if(!host_isclient.integer)
2083                 Sys_MakeProcessMean();
2084
2085 //      SV_UnlockThreadMutex();
2086 }
2087
2088 /*
2089 ==================
2090 SV_Shutdown
2091
2092 This only happens at the end of a game, not between levels
2093 ==================
2094 */
2095 void SV_Shutdown(void)
2096 {
2097         prvm_prog_t *prog = SVVM_prog;
2098         int i;
2099
2100         SV_LockThreadMutex();
2101
2102         if (!sv.active)
2103                 goto end;
2104
2105         Con_DPrintf("SV_Shutdown\n");
2106
2107         NetConn_Heartbeat(2);
2108         NetConn_Heartbeat(2);
2109
2110 // make sure all the clients know we're disconnecting
2111         World_End(&sv.world);
2112         if(prog->loaded)
2113         {
2114                 if(PRVM_serverfunction(SV_Shutdown))
2115                 {
2116                         func_t s = PRVM_serverfunction(SV_Shutdown);
2117                         PRVM_serverglobalfloat(time) = sv.time;
2118                         PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
2119                         prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
2120                 }
2121         }
2122         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2123                 if (host_client->active)
2124                         SV_DropClient(false, "Server shutting down"); // server shutdown
2125
2126         NetConn_CloseServerPorts();
2127
2128         sv.active = false;
2129 //
2130 // clear structures
2131 //
2132         memset(&sv, 0, sizeof(sv));
2133         memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
2134 end:
2135         SV_UnlockThreadMutex();
2136 }
2137
2138 /////////////////////////////////////////////////////
2139 // SV VM stuff
2140
2141 static void SVVM_begin_increase_edicts(prvm_prog_t *prog)
2142 {
2143         // links don't survive the transition, so unlink everything
2144         World_UnlinkAll(&sv.world);
2145 }
2146
2147 static void SVVM_end_increase_edicts(prvm_prog_t *prog)
2148 {
2149         int i;
2150         prvm_edict_t *ent;
2151
2152         // link every entity except world
2153         for (i = 1, ent = prog->edicts;i < prog->num_edicts;i++, ent++)
2154                 if (!ent->free && !VectorCompare(PRVM_serveredictvector(ent, absmin), PRVM_serveredictvector(ent, absmax)))
2155                         SV_LinkEdict(ent);
2156 }
2157
2158 static void SVVM_init_edict(prvm_prog_t *prog, prvm_edict_t *e)
2159 {
2160         // LadyHavoc: for consistency set these here
2161         int num = PRVM_NUM_FOR_EDICT(e) - 1;
2162
2163         e->priv.server->move = false; // don't move on first frame
2164
2165         if (num >= 0 && num < svs.maxclients)
2166         {
2167                 // set colormap and team on newly created player entity
2168                 PRVM_serveredictfloat(e, colormap) = num + 1;
2169                 PRVM_serveredictfloat(e, team) = (svs.clients[num].colors & 15) + 1;
2170                 // set netname/clientcolors back to client values so that
2171                 // DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS will not immediately
2172                 // reset them
2173                 PRVM_serveredictstring(e, netname) = PRVM_SetEngineString(prog, svs.clients[num].name);
2174                 PRVM_serveredictfloat(e, clientcolors) = svs.clients[num].colors;
2175                 // NEXUIZ_PLAYERMODEL and NEXUIZ_PLAYERSKIN
2176                 PRVM_serveredictstring(e, playermodel) = PRVM_SetEngineString(prog, svs.clients[num].playermodel);
2177                 PRVM_serveredictstring(e, playerskin) = PRVM_SetEngineString(prog, svs.clients[num].playerskin);
2178                 // Assign netaddress (IP Address, etc)
2179                 if(svs.clients[num].netconnection != NULL)
2180                 {
2181                         // Acquire Readable Address
2182                         LHNETADDRESS_ToString(&svs.clients[num].netconnection->peeraddress, svs.clients[num].netaddress, sizeof(svs.clients[num].netaddress), false);
2183                         PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString(prog, svs.clients[num].netaddress);
2184                 }
2185                 else
2186                         PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString(prog, "null/botclient");
2187                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_idfp[0])
2188                         PRVM_serveredictstring(e, crypto_idfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.client_idfp);
2189                 else
2190                         PRVM_serveredictstring(e, crypto_idfp) = 0;
2191                 PRVM_serveredictfloat(e, crypto_idfp_signed) = (svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_issigned);
2192                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_keyfp[0])
2193                         PRVM_serveredictstring(e, crypto_keyfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.client_keyfp);
2194                 else
2195                         PRVM_serveredictstring(e, crypto_keyfp) = 0;
2196                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.server_keyfp[0])
2197                         PRVM_serveredictstring(e, crypto_mykeyfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.server_keyfp);
2198                 else
2199                         PRVM_serveredictstring(e, crypto_mykeyfp) = 0;
2200                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.use_aes)
2201                         PRVM_serveredictstring(e, crypto_encryptmethod) = PRVM_SetEngineString(prog, "AES128");
2202                 else
2203                         PRVM_serveredictstring(e, crypto_encryptmethod) = 0;
2204                 if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated)
2205                         PRVM_serveredictstring(e, crypto_signmethod) = PRVM_SetEngineString(prog, "HMAC-SHA256");
2206                 else
2207                         PRVM_serveredictstring(e, crypto_signmethod) = 0;
2208         }
2209 }
2210
2211 static void SVVM_free_edict(prvm_prog_t *prog, prvm_edict_t *ed)
2212 {
2213         int i;
2214         int e;
2215
2216         World_UnlinkEdict(ed);          // unlink from world bsp
2217
2218         PRVM_serveredictstring(ed, model) = 0;
2219         PRVM_serveredictfloat(ed, takedamage) = 0;
2220         PRVM_serveredictfloat(ed, modelindex) = 0;
2221         PRVM_serveredictfloat(ed, colormap) = 0;
2222         PRVM_serveredictfloat(ed, skin) = 0;
2223         PRVM_serveredictfloat(ed, frame) = 0;
2224         VectorClear(PRVM_serveredictvector(ed, origin));
2225         VectorClear(PRVM_serveredictvector(ed, angles));
2226         PRVM_serveredictfloat(ed, nextthink) = -1;
2227         PRVM_serveredictfloat(ed, solid) = 0;
2228
2229         VM_RemoveEdictSkeleton(prog, ed);
2230 #ifdef USEODE
2231         World_Physics_RemoveFromEntity(&sv.world, ed);
2232         World_Physics_RemoveJointFromEntity(&sv.world, ed);
2233 #endif
2234         // make sure csqc networking is aware of the removed entity
2235         e = PRVM_NUM_FOR_EDICT(ed);
2236         sv.csqcentityversion[e] = 0;
2237         for (i = 0;i < svs.maxclients;i++)
2238                 svs.clients[i].csqcentitysendflags[e] = 0xFFFFFF;
2239 }
2240
2241 static void SVVM_count_edicts(prvm_prog_t *prog)
2242 {
2243         int             i;
2244         prvm_edict_t    *ent;
2245         int             active, models, solid, step;
2246
2247         active = models = solid = step = 0;
2248         for (i=0 ; i<prog->num_edicts ; i++)
2249         {
2250                 ent = PRVM_EDICT_NUM(i);
2251                 if (ent->free)
2252                         continue;
2253                 active++;
2254                 if (PRVM_serveredictfloat(ent, solid))
2255                         solid++;
2256                 if (PRVM_serveredictstring(ent, model))
2257                         models++;
2258                 if (PRVM_serveredictfloat(ent, movetype) == MOVETYPE_STEP)
2259                         step++;
2260         }
2261
2262         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
2263         Con_Printf("active    :%3i\n", active);
2264         Con_Printf("view      :%3i\n", models);
2265         Con_Printf("touch     :%3i\n", solid);
2266         Con_Printf("step      :%3i\n", step);
2267 }
2268
2269 static qbool SVVM_load_edict(prvm_prog_t *prog, prvm_edict_t *ent)
2270 {
2271         // remove things from different skill levels or deathmatch
2272         if (gamemode != GAME_TRANSFUSION) //Transfusion does this in QC
2273         {
2274                 if (deathmatch.integer)
2275                 {
2276                         if (((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_DEATHMATCH))
2277                         {
2278                                 return false;
2279                         }
2280                 }
2281                 else if ((current_skill <= 0 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_EASY  ))
2282                         || (current_skill == 1 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_MEDIUM))
2283                         || (current_skill >= 2 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_HARD  )))
2284                 {
2285                         return false;
2286                 }
2287         }
2288         return true;
2289 }
2290
2291 static void SV_VM_Setup(void)
2292 {
2293         prvm_prog_t *prog = SVVM_prog;
2294         PRVM_Prog_Init(prog, cmd_local);
2295
2296         // allocate the mempools
2297         // TODO: move the magic numbers/constants into #defines [9/13/2006 Black]
2298         prog->progs_mempool = Mem_AllocPool("Server Progs", 0, NULL);
2299         prog->builtins = vm_sv_builtins;
2300         prog->numbuiltins = vm_sv_numbuiltins;
2301         prog->max_edicts = 512;
2302         if (sv.protocol == PROTOCOL_QUAKE)
2303                 prog->limit_edicts = 640; // before quake mission pack 1 this was 512
2304         else if (sv.protocol == PROTOCOL_QUAKEDP)
2305                 prog->limit_edicts = 2048; // guessing
2306         else if (sv.protocol == PROTOCOL_NEHAHRAMOVIE)
2307                 prog->limit_edicts = 2048; // guessing!
2308         else if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
2309                 prog->limit_edicts = 4096; // guessing!
2310         else
2311                 prog->limit_edicts = MAX_EDICTS;
2312         prog->reserved_edicts = svs.maxclients;
2313         prog->edictprivate_size = sizeof(edict_engineprivate_t);
2314         prog->name = "server";
2315         prog->extensionstring = vm_sv_extensions;
2316         prog->loadintoworld = true;
2317
2318         // all callbacks must be defined (pointers are not checked before calling)
2319         prog->begin_increase_edicts = SVVM_begin_increase_edicts;
2320         prog->end_increase_edicts   = SVVM_end_increase_edicts;
2321         prog->init_edict            = SVVM_init_edict;
2322         prog->free_edict            = SVVM_free_edict;
2323         prog->count_edicts          = SVVM_count_edicts;
2324         prog->load_edict            = SVVM_load_edict;
2325         prog->init_cmd              = SVVM_init_cmd;
2326         prog->reset_cmd             = SVVM_reset_cmd;
2327         prog->error_cmd             = Host_Error;
2328         prog->ExecuteProgram        = SVVM_ExecuteProgram;
2329
2330         PRVM_Prog_Load(prog, sv_progs.string, NULL, 0, SV_REQFUNCS, sv_reqfuncs, SV_REQFIELDS, sv_reqfields, SV_REQGLOBALS, sv_reqglobals);
2331
2332         // some mods compiled with scrambling compilers lack certain critical
2333         // global names and field names such as "self" and "time" and "nextthink"
2334         // so we have to set these offsets manually, matching the entvars_t
2335         // but we only do this if the prog header crc matches, otherwise it's totally freeform
2336         if (prog->progs_crc == PROGHEADER_CRC || prog->progs_crc == PROGHEADER_CRC_TENEBRAE)
2337         {
2338                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, modelindex);
2339                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, absmin);
2340                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, absmax);
2341                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ltime);
2342                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, movetype);
2343                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, solid);
2344                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, origin);
2345                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, oldorigin);
2346                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, velocity);
2347                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, angles);
2348                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, avelocity);
2349                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, punchangle);
2350                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, classname);
2351                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, model);
2352                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frame);
2353                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, skin);
2354                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, effects);
2355                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, mins);
2356                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, maxs);
2357                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, size);
2358                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, touch);
2359                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, use);
2360                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, think);
2361                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, blocked);
2362                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, nextthink);
2363                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, groundentity);
2364                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, health);
2365                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frags);
2366                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weapon);
2367                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weaponmodel);
2368                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weaponframe);
2369                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, currentammo);
2370                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_shells);
2371                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_nails);
2372                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_rockets);
2373                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_cells);
2374                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, items);
2375                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, takedamage);
2376                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, chain);
2377                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, deadflag);
2378                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, view_ofs);
2379                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button0);
2380                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button1);
2381                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button2);
2382                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, impulse);
2383                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, fixangle);
2384                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, v_angle);
2385                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, idealpitch);
2386                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, netname);
2387                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, enemy);
2388                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, flags);
2389                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, colormap);
2390                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, team);
2391                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, max_health);
2392                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, teleport_time);
2393                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, armortype);
2394                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, armorvalue);
2395                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, waterlevel);
2396                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, watertype);
2397                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ideal_yaw);
2398                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, yaw_speed);
2399                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, aiment);
2400                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, goalentity);
2401                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, spawnflags);
2402                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, target);
2403                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, targetname);
2404                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_take);
2405                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_save);
2406                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_inflictor);
2407                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, owner);
2408                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, movedir);
2409                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, message);
2410                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, sounds);
2411                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise);
2412                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise1);
2413                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise2);
2414                 PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise3);
2415                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, self);
2416                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, other);
2417                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, world);
2418                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, time);
2419                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, frametime);
2420                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, force_retouch);
2421                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, mapname);
2422                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, deathmatch);
2423                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, coop);
2424                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, teamplay);
2425                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, serverflags);
2426                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, total_secrets);
2427                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, total_monsters);
2428                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, found_secrets);
2429                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, killed_monsters);
2430                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm1);
2431                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm2);
2432                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm3);
2433                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm4);
2434                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm5);
2435                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm6);
2436                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm7);
2437                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm8);
2438                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm9);
2439                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm10);
2440                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm11);
2441                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm12);
2442                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm13);
2443                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm14);
2444                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm15);
2445                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm16);
2446                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_forward);
2447                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_up);
2448                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_right);
2449                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_allsolid);
2450                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_startsolid);
2451                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_fraction);
2452                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_endpos);
2453                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_normal);
2454                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_dist);
2455                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_ent);
2456                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inopen);
2457                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inwater);
2458                 PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, msg_entity);
2459 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, main);
2460 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, StartFrame);
2461 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PlayerPreThink);
2462 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PlayerPostThink);
2463 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientKill);
2464 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientConnect);
2465 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PutClientInServer);
2466 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientDisconnect);
2467 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, SetNewParms);
2468 //              PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, SetChangeParms);
2469         }
2470         else
2471                 Con_DPrintf("%s: %s system vars have been modified (CRC %i != engine %i), will not load in other engines\n", prog->name, sv_progs.string, prog->progs_crc, PROGHEADER_CRC);
2472
2473         // OP_STATE is always supported on server because we add fields/globals for it
2474         prog->flag |= PRVM_OP_STATE;
2475
2476         VM_CustomStats_Clear();//[515]: csqc
2477
2478         SV_Prepare_CSQC();
2479 }
2480
2481 static void SV_CheckTimeouts(void)
2482 {
2483         int i;
2484
2485         // never timeout loopback connections
2486         for (i = (host_isclient.integer ? 1 : 0), host_client = &svs.clients[i]; i < svs.maxclients; i++, host_client++)
2487                 if (host_client->netconnection && host.realtime > host_client->netconnection->timeout)
2488                         SV_DropClient(false, "Timed out");
2489 }
2490
2491 /*
2492 ==================
2493 SV_TimeReport
2494
2495 Returns a time report string, for example for
2496 ==================
2497 */
2498 const char *SV_TimingReport(char *buf, size_t buflen)
2499 {
2500         return va(buf, buflen, "%.1f%% CPU, %.2f%% lost, offset avg %.1fms, max %.1fms, sdev %.1fms", svs.perf_cpuload * 100, svs.perf_lost * 100, svs.perf_offset_avg * 1000, svs.perf_offset_max * 1000, svs.perf_offset_sdev * 1000);
2501 }
2502
2503 extern cvar_t host_maxwait;
2504 extern cvar_t host_framerate;
2505 extern cvar_t cl_maxphysicsframesperserverframe;
2506 double SV_Frame(double time)
2507 {
2508         static double sv_timer;
2509         int i;
2510         char vabuf[1024];
2511         qbool playing = false;
2512
2513         if (!svs.threaded)
2514         {
2515                 svs.perf_acc_sleeptime = host.sleeptime;
2516                 svs.perf_acc_realtime += time;
2517
2518                 // Look for clients who have spawned
2519                 for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++)
2520                         if(host_client->begun && host_client->netconnection)
2521                                 playing = true;
2522
2523                 if(svs.perf_acc_realtime > 5)
2524                 {
2525                         svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
2526                         svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
2527
2528                         if(svs.perf_acc_offset_samples > 0)
2529                         {
2530                                 svs.perf_offset_max = svs.perf_acc_offset_max;
2531                                 svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
2532                                 svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
2533                         }
2534
2535                         if(svs.perf_lost > 0 && developer_extra.integer && playing) // only complain if anyone is looking
2536                                 Con_DPrintf("Server can't keep up: %s\n", SV_TimingReport(vabuf, sizeof(vabuf)));
2537                 }
2538
2539                 if(svs.perf_acc_realtime > 5 || sv.time < 10)
2540                 {
2541                         /*
2542                          * Don't accumulate time for the first 10 seconds of a match
2543                          * so things can settle
2544                          */
2545                         svs.perf_acc_realtime = svs.perf_acc_sleeptime =
2546                         svs.perf_acc_lost = svs.perf_acc_offset =
2547                         svs.perf_acc_offset_squared = svs.perf_acc_offset_max =
2548                         svs.perf_acc_offset_samples = host.sleeptime = 0;
2549                 }
2550
2551                 /*
2552                  * Receive packets on each main loop iteration, as the main loop may
2553                  * be undersleeping due to select() detecting a new packet
2554                  */
2555                 if (sv.active)
2556                 {
2557                         NetConn_ServerFrame();
2558                         SV_CheckTimeouts();
2559                 }
2560         }
2561
2562         /*
2563          * If the accumulator hasn't become positive, don't
2564          * run the frame. Everything that happens before this
2565          * point will happen even if we're sleeping this frame.
2566          */
2567         if((sv_timer += time) < 0)
2568                 return sv_timer;
2569
2570         // limit the frametime steps to no more than 100ms each
2571         if (sv_timer > 0.1)
2572         {
2573                 if (!svs.threaded)
2574                         svs.perf_acc_lost += (sv_timer - 0.1);
2575                 sv_timer = 0.1;
2576         }
2577
2578         if (sv.active && sv_timer > 0 && !svs.threaded)
2579         {
2580                 /*
2581                  * Execute one or more server frames, with an upper limit on how much
2582                  * execution time to spend on server frames to avoid freezing the game if
2583                  * the server is overloaded. This execution time limit means the game will
2584                  * slow down if the server is taking too long.
2585                  */
2586                 int framecount, framelimit = 1;
2587                 double advancetime, aborttime = 0;
2588                 float offset;
2589                 prvm_prog_t *prog = SVVM_prog;
2590
2591                 // run the world state
2592                 // don't allow simulation to run too fast or too slow or logic glitches can occur
2593
2594                 // stop running server frames if the wall time reaches this value
2595                 if (sys_ticrate.value <= 0)
2596                         advancetime = sv_timer;
2597                 else
2598                 {
2599                         advancetime = sys_ticrate.value;
2600                         // listen servers can run multiple server frames per client frame
2601                         framelimit = cl_maxphysicsframesperserverframe.integer;
2602                         aborttime = Sys_DirtyTime() + 0.1;
2603                 }
2604
2605                 if(host_timescale.value > 0 && host_timescale.value < 1)
2606                         advancetime = min(advancetime, 0.1 / host_timescale.value);
2607                 else
2608                         advancetime = min(advancetime, 0.1);
2609
2610                 if(advancetime > 0)
2611                 {
2612                         offset = Sys_DirtyTime() - host.dirtytime;
2613                         if (offset < 0 || offset >= 1800)
2614                                 offset = 0;
2615
2616                         offset += sv_timer;
2617                         ++svs.perf_acc_offset_samples;
2618                         svs.perf_acc_offset += offset;
2619                         svs.perf_acc_offset_squared += offset * offset;
2620                         
2621                         if(svs.perf_acc_offset_max < offset)
2622                                 svs.perf_acc_offset_max = offset;
2623                 }
2624
2625                 // only advance time if not paused
2626                 // the game also pauses in singleplayer when menu or console is used
2627                 sv.frametime = advancetime * host_timescale.value;
2628                 if (host_framerate.value)
2629                         sv.frametime = host_framerate.value;
2630                 if (sv.paused || host.paused)
2631                         sv.frametime = 0;
2632
2633                 for (framecount = 0; framecount < framelimit && sv_timer > 0; framecount++)
2634                 {
2635                         sv_timer -= advancetime;
2636
2637                         // move things around and think unless paused
2638                         if (sv.frametime)
2639                                 SV_Physics();
2640
2641                         // if this server frame took too long, break out of the loop
2642                         if (framelimit > 1 && Sys_DirtyTime() >= aborttime)
2643                                 break;
2644                 }
2645
2646                 R_TimeReport("serverphysics");
2647
2648                 // send all messages to the clients
2649                 SV_SendClientMessages();
2650
2651                 if (sv.paused == 1 && host.realtime > sv.pausedstart && sv.pausedstart > 0) {
2652                         prog->globals.fp[OFS_PARM0] = host.realtime - sv.pausedstart;
2653                         PRVM_serverglobalfloat(time) = sv.time;
2654                         prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
2655                 }
2656
2657                 // send an heartbeat if enough time has passed since the last one
2658                 NetConn_Heartbeat(0);
2659                 R_TimeReport("servernetwork");
2660         }
2661         else
2662         {
2663                 // don't let r_speeds display jump around
2664                 R_TimeReport("serverphysics");
2665                 R_TimeReport("servernetwork");
2666         }
2667
2668         // if there is some time remaining from this frame, reset the timer
2669         if (sv_timer >= 0)
2670         {
2671                 if (!svs.threaded)
2672                         svs.perf_acc_lost += sv_timer;
2673                 sv_timer = 0;
2674         }
2675
2676         return sv_timer;
2677 }
2678
2679 static int SV_ThreadFunc(void *voiddata)
2680 {
2681         prvm_prog_t *prog = SVVM_prog;
2682         qbool playing = false;
2683         double sv_timer = 0;
2684         double sv_deltarealtime, sv_oldrealtime, sv_realtime;
2685         double wait;
2686         int i;
2687         char vabuf[1024];
2688         sv_realtime = Sys_DirtyTime();
2689         while (!svs.threadstop)
2690         {
2691                 // FIXME: we need to handle Host_Error in the server thread somehow
2692 //              if (setjmp(sv_abortframe))
2693 //                      continue;                       // something bad happened in the server game
2694
2695                 sv_oldrealtime = sv_realtime;
2696                 sv_realtime = Sys_DirtyTime();
2697                 sv_deltarealtime = sv_realtime - sv_oldrealtime;
2698                 if (sv_deltarealtime < 0 || sv_deltarealtime >= 1800) sv_deltarealtime = 0;
2699
2700                 sv_timer += sv_deltarealtime;
2701
2702                 svs.perf_acc_realtime += sv_deltarealtime;
2703
2704                 // at this point we start doing real server work, and must block on any client activity pertaining to the server (such as executing SV_SpawnServer)
2705                 SV_LockThreadMutex();
2706
2707                 // Look for clients who have spawned
2708                 playing = false;
2709                 if (sv.active)
2710                         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2711                                 if(host_client->begun)
2712                                         if(host_client->netconnection)
2713                                                 playing = true;
2714                 if(sv.time < 10)
2715                 {
2716                         // don't accumulate time for the first 10 seconds of a match
2717                         // so things can settle
2718                         svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
2719                 }
2720                 else if(svs.perf_acc_realtime > 5)
2721                 {
2722                         svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
2723                         svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
2724                         if(svs.perf_acc_offset_samples > 0)
2725                         {
2726                                 svs.perf_offset_max = svs.perf_acc_offset_max;
2727                                 svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
2728                                 svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
2729                         }
2730                         if(svs.perf_lost > 0 && developer_extra.integer)
2731                                 if(playing)
2732                                         Con_DPrintf("Server can't keep up: %s\n", SV_TimingReport(vabuf, sizeof(vabuf)));
2733                         svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
2734                 }
2735
2736                 // get new packets
2737                 if (sv.active)
2738                 {
2739                         NetConn_ServerFrame();
2740                         SV_CheckTimeouts();
2741                 }
2742
2743                 // if the accumulators haven't become positive yet, wait a while
2744                 wait = sv_timer * -1000000.0;
2745                 if (wait >= 1)
2746                 {
2747                         double time0, delta;
2748                         SV_UnlockThreadMutex(); // don't keep mutex locked while sleeping
2749                         if (host_maxwait.value <= 0)
2750                                 wait = min(wait, 1000000.0);
2751                         else
2752                                 wait = min(wait, host_maxwait.value * 1000.0);
2753                         if(wait < 1)
2754                                 wait = 1; // because we cast to int
2755                         time0 = Sys_DirtyTime();
2756                         Sys_Sleep((int)wait);
2757                         delta = Sys_DirtyTime() - time0;if (delta < 0 || delta >= 1800) delta = 0;
2758                         svs.perf_acc_sleeptime += delta;
2759                         continue;
2760                 }
2761
2762                 if (sv.active && sv_timer > 0)
2763                 {
2764                         // execute one server frame
2765                         double advancetime;
2766                         float offset;
2767
2768                         if (sys_ticrate.value <= 0)
2769                                 advancetime = min(sv_timer, 0.1); // don't step more than 100ms
2770                         else
2771                                 advancetime = sys_ticrate.value;
2772
2773                         if(advancetime > 0)
2774                         {
2775                                 offset = sv_timer + (Sys_DirtyTime() - sv_realtime); // LadyHavoc: FIXME: I don't understand this line
2776                                 ++svs.perf_acc_offset_samples;
2777                                 svs.perf_acc_offset += offset;
2778                                 svs.perf_acc_offset_squared += offset * offset;
2779                                 if(svs.perf_acc_offset_max < offset)
2780                                         svs.perf_acc_offset_max = offset;
2781                         }
2782
2783                         // only advance time if not paused
2784                         // the game also pauses in singleplayer when menu or console is used
2785                         sv.frametime = advancetime * host_timescale.value;
2786                         if (host_framerate.value)
2787                                 sv.frametime = host_framerate.value;
2788                         if (sv.paused || host.paused)
2789                                 sv.frametime = 0;
2790
2791                         sv_timer -= advancetime;
2792
2793                         // move things around and think unless paused
2794                         if (sv.frametime)
2795                                 SV_Physics();
2796
2797                         // send all messages to the clients
2798                         SV_SendClientMessages();
2799
2800                         if (sv.paused == 1 && sv_realtime > sv.pausedstart && sv.pausedstart > 0)
2801                         {
2802                                 PRVM_serverglobalfloat(time) = sv.time;
2803                                 prog->globals.fp[OFS_PARM0] = sv_realtime - sv.pausedstart;
2804                                 prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
2805                         }
2806
2807                         // send an heartbeat if enough time has passed since the last one
2808                         NetConn_Heartbeat(0);
2809
2810                 }
2811
2812                 // we're back to safe code now
2813                 SV_UnlockThreadMutex();
2814
2815                 // if there is some time remaining from this frame, reset the timers
2816                 if (sv_timer >= 0)
2817                 {
2818                         svs.perf_acc_lost += sv_timer;
2819                         sv_timer = 0;
2820                 }
2821         }
2822         return 0;
2823 }
2824
2825 void SV_StartThread(void)
2826 {
2827         if (!sv_threaded.integer || !Thread_HasThreads())
2828                 return;
2829         svs.threaded = true;
2830         svs.threadstop = false;
2831         svs.threadmutex = Thread_CreateMutex();
2832         svs.thread = Thread_CreateThread(SV_ThreadFunc, NULL);
2833 }
2834
2835 void SV_StopThread(void)
2836 {
2837         if (!svs.threaded)
2838                 return;
2839         svs.threadstop = true;
2840         Thread_WaitThread(svs.thread, 0);
2841         Thread_DestroyMutex(svs.threadmutex);
2842         svs.threaded = false;
2843 }