]> git.xonotic.org Git - xonotic/darkplaces.git/blob - sv_main.c
network CSQC and network entities separately (should prevent bugs when an entity...
[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
27 static void SV_SaveEntFile_f(void);
28 static void SV_StartDownload_f(void);
29 static void SV_Download_f(void);
30 static void SV_VM_Setup(void);
31 extern cvar_t net_connecttimeout;
32
33 void VM_CustomStats_Clear (void);
34 void VM_SV_UpdateCustomStats (client_t *client, prvm_edict_t *ent, sizebuf_t *msg, int *stats);
35
36 cvar_t coop = {0, "coop","0", "coop mode, 0 = no coop, 1 = coop mode, multiple players playing through the singleplayer game (coop mode also shuts off deathmatch)"};
37 cvar_t deathmatch = {0, "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)"};
38 cvar_t fraglimit = {CVAR_NOTIFY, "fraglimit","0", "ends level if this many frags is reached by any player"};
39 cvar_t gamecfg = {0, "gamecfg", "0", "unused cvar in quake, can be used by mods"};
40 cvar_t noexit = {CVAR_NOTIFY, "noexit","0", "kills anyone attempting to use an exit"};
41 cvar_t nomonsters = {0, "nomonsters", "0", "unused cvar in quake, can be used by mods"};
42 cvar_t pausable = {0, "pausable","1", "allow players to pause or not"};
43 cvar_t pr_checkextension = {CVAR_READONLY, "pr_checkextension", "1", "indicates to QuakeC that the standard quakec extensions system is available (if 0, quakec should not attempt to use extensions)"};
44 cvar_t samelevel = {CVAR_NOTIFY, "samelevel","0", "repeats same level if level ends (due to timelimit or someone hitting an exit)"};
45 cvar_t skill = {0, "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)"};
46 cvar_t slowmo = {0, "slowmo", "1.0", "controls game speed, 0.5 is half speed, 2 is double speed"};
47
48 cvar_t sv_accelerate = {0, "sv_accelerate", "10", "rate at which a player accelerates to sv_maxspeed"};
49 cvar_t sv_aim = {CVAR_SAVE, "sv_aim", "2", "maximum cosine angle for quake's vertical autoaim, a value above 1 completely disables the autoaim, quake used 0.93"};
50 cvar_t sv_airaccel_qw = {0, "sv_airaccel_qw", "1", "ratio of QW-style air control as opposed to simple acceleration"};
51 cvar_t sv_airaccel_sideways_friction = {0, "sv_airaccel_sideways_friction", "", "anti-sideways movement stabilization (reduces speed gain when zigzagging)"};
52 cvar_t sv_airaccelerate = {0, "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"};
53 cvar_t sv_airstopaccelerate = {0, "sv_airstopaccelerate", "0", "when set, replacement for sv_airaccelerate when moving backwards"};
54 cvar_t sv_airstrafeaccelerate = {0, "sv_airstrafeaccelerate", "0", "when set, replacement for sv_airaccelerate when just strafing"};
55 cvar_t sv_maxairstrafespeed = {0, "sv_maxairstrafespeed", "0", "when set, replacement for sv_maxairspeed when just strafing"};
56 cvar_t sv_aircontrol = {0, "sv_aircontrol", "0", "CPMA-style air control"};
57 cvar_t sv_allowdownloads = {0, "sv_allowdownloads", "1", "whether to allow clients to download files from the server (does not affect http downloads)"};
58 cvar_t sv_allowdownloads_archive = {0, "sv_allowdownloads_archive", "0", "whether to allow downloads of archives (pak/pk3)"};
59 cvar_t sv_allowdownloads_config = {0, "sv_allowdownloads_config", "0", "whether to allow downloads of config files (cfg)"};
60 cvar_t sv_allowdownloads_dlcache = {0, "sv_allowdownloads_dlcache", "0", "whether to allow downloads of dlcache files (dlcache/)"};
61 cvar_t sv_allowdownloads_inarchive = {0, "sv_allowdownloads_inarchive", "0", "whether to allow downloads from archives (pak/pk3)"};
62 cvar_t sv_areagrid_mingridsize = {CVAR_NOTIFY, "sv_areagrid_mingridsize", "64", "minimum areagrid cell size, smaller values work better for lots of small objects, higher values for large objects"};
63 cvar_t sv_checkforpacketsduringsleep = {0, "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"};
64 cvar_t sv_clmovement_enable = {0, "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"};
65 cvar_t sv_clmovement_minping = {0, "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)"};
66 cvar_t sv_clmovement_minping_disabletime = {0, "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)"};
67 cvar_t sv_clmovement_inputtimeout = {0, "sv_clmovement_inputtimeout", "0.2", "when a client does not send input for this many seconds, force them to move anyway (unlike QuakeWorld)"};
68 cvar_t sv_cullentities_nevercullbmodels = {0, "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!)"};
69 cvar_t sv_cullentities_pvs = {0, "sv_cullentities_pvs", "1", "fast but loose culling of hidden entities"};
70 cvar_t sv_cullentities_stats = {0, "sv_cullentities_stats", "0", "displays stats on network entities culled by various methods for each client"};
71 cvar_t sv_cullentities_trace = {0, "sv_cullentities_trace", "0", "somewhat slow but very tight culling of hidden entities, minimizes network traffic and makes wallhack cheats useless"};
72 cvar_t sv_cullentities_trace_delay = {0, "sv_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
73 cvar_t sv_cullentities_trace_delay_players = {0, "sv_cullentities_trace_delay_players", "0.2", "number of seconds until the entity gets actually culled if it is a player entity"};
74 cvar_t sv_cullentities_trace_enlarge = {0, "sv_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
75 cvar_t sv_cullentities_trace_prediction = {0, "sv_cullentities_trace_prediction", "1", "also trace from the predicted player position"};
76 cvar_t sv_cullentities_trace_samples = {0, "sv_cullentities_trace_samples", "1", "number of samples to test for entity culling"};
77 cvar_t sv_cullentities_trace_samples_extra = {0, "sv_cullentities_trace_samples_extra", "2", "number of samples to test for entity culling when the entity affects its surroundings by e.g. dlight"};
78 cvar_t sv_cullentities_trace_samples_players = {0, "sv_cullentities_trace_samples_players", "8", "number of samples to test for entity culling when the entity is a player entity"};
79 cvar_t sv_debugmove = {CVAR_NOTIFY, "sv_debugmove", "0", "disables collision detection optimizations for debugging purposes"};
80 cvar_t sv_echobprint = {CVAR_SAVE, "sv_echobprint", "1", "prints gamecode bprint() calls to server console"};
81 cvar_t sv_edgefriction = {0, "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)"};
82 cvar_t sv_entpatch = {0, "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)"};
83 cvar_t sv_fixedframeratesingleplayer = {0, "sv_fixedframeratesingleplayer", "1", "allows you to use server-style timing system in singleplayer (don't run faster than sys_ticrate)"};
84 cvar_t sv_freezenonclients = {CVAR_NOTIFY, "sv_freezenonclients", "0", "freezes time, except for players, allowing you to walk around and take screenshots of explosions"};
85 cvar_t sv_friction = {CVAR_NOTIFY, "sv_friction","4", "how fast you slow down"};
86 cvar_t sv_gameplayfix_blowupfallenzombies = {0, "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"};
87 cvar_t sv_gameplayfix_delayprojectiles = {0, "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"};
88 cvar_t sv_gameplayfix_droptofloorstartsolid = {0, "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)"};
89 cvar_t sv_gameplayfix_droptofloorstartsolid_nudgetocorrect = {0, "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect", "1", "tries to nudge stuck items and monsters out of walls before droptofloor is performed"};
90 cvar_t sv_gameplayfix_easierwaterjump = {0, "sv_gameplayfix_easierwaterjump", "1", "changes water jumping to make it easier to get out of water (exactly like in QuakeWorld)"};
91 cvar_t sv_gameplayfix_findradiusdistancetobox = {0, "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"};
92 cvar_t sv_gameplayfix_grenadebouncedownslopes = {0, "sv_gameplayfix_grenadebouncedownslopes", "1", "prevents MOVETYPE_BOUNCE (grenades) from getting stuck when fired down a downward sloping surface"};
93 cvar_t sv_gameplayfix_multiplethinksperframe = {0, "sv_gameplayfix_multiplethinksperframe", "1", "allows entities to think more often than the server framerate, primarily useful for very high fire rate weapons"};
94 cvar_t sv_gameplayfix_slidemoveprojectiles = {0, "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"};
95 cvar_t sv_gameplayfix_noairborncorpse = {0, "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"};
96 cvar_t sv_gameplayfix_noairborncorpse_allowsuspendeditems = {0, "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)"};
97 cvar_t sv_gameplayfix_setmodelrealbox = {0, "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"};
98 cvar_t sv_gameplayfix_stepdown = {0, "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)"};
99 cvar_t sv_gameplayfix_stepwhilejumping = {0, "sv_gameplayfix_stepwhilejumping", "1", "applies step-up onto a ledge even while airborn, useful if you would otherwise just-miss the floor when running across small areas with gaps (for instance running across the moving platforms in dm2, or jumping to the megahealth and red armor in dm2 rather than using the bridge)"};
100 cvar_t sv_gameplayfix_swiminbmodels = {0, "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"};
101 cvar_t sv_gameplayfix_upwardvelocityclearsongroundflag = {0, "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"};
102 cvar_t sv_gameplayfix_gravityunaffectedbyticrate = {0, "sv_gameplayfix_gravityunaffectedbyticrate", "0", "fix some ticrate issues in physics."};
103 cvar_t sv_gameplayfix_q2airaccelerate = {0, "sv_gameplayfix_q2airaccelerate", "0", "Quake2-style air acceleration"};
104 cvar_t sv_gravity = {CVAR_NOTIFY, "sv_gravity","800", "how fast you fall (512 = roughly earth gravity)"};
105 cvar_t sv_idealpitchscale = {0, "sv_idealpitchscale","0.8", "how much to look up/down slopes and stairs when not using freelook"};
106 cvar_t sv_jumpstep = {CVAR_NOTIFY, "sv_jumpstep", "0", "whether you can step up while jumping (sv_gameplayfix_stepwhilejumping must also be 1)"};
107 cvar_t sv_jumpvelocity = {0, "sv_jumpvelocity", "270", "cvar that can be used by QuakeC code for jump velocity"};
108 cvar_t sv_maxairspeed = {0, "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)"};
109 cvar_t sv_maxrate = {CVAR_SAVE | CVAR_NOTIFY, "sv_maxrate", "1000000", "upper limit on client rate cvar, should reflect your network connection quality"};
110 cvar_t sv_maxspeed = {CVAR_NOTIFY, "sv_maxspeed", "320", "maximum speed a player can accelerate to when on ground (can be exceeded by tricks)"};
111 cvar_t sv_maxvelocity = {CVAR_NOTIFY, "sv_maxvelocity","2000", "universal speed limit on all entities"};
112 cvar_t sv_newflymove = {CVAR_NOTIFY, "sv_newflymove", "0", "enables simpler/buggier player physics (not recommended)"};
113 cvar_t sv_nostep = {CVAR_NOTIFY, "sv_nostep","0", "prevents MOVETYPE_STEP entities (monsters) from moving"};
114 cvar_t sv_playerphysicsqc = {CVAR_NOTIFY, "sv_playerphysicsqc", "1", "enables QuakeC function to override player physics"};
115 cvar_t sv_progs = {0, "sv_progs", "progs.dat", "selects which quakec progs.dat file to run" };
116 cvar_t sv_protocolname = {0, "sv_protocolname", "DP7", "selects network protocol to host for (values include QUAKE, QUAKEDP, NEHAHRAMOVIE, DP1 and up)"};
117 cvar_t sv_random_seed = {0, "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"};
118 cvar_t sv_ratelimitlocalplayer = {0, "sv_ratelimitlocalplayer", "0", "whether to apply rate limiting to the local player in a listen server (only useful for testing)"};
119 cvar_t sv_sound_land = {0, "sv_sound_land", "demon/dland2.wav", "sound to play when MOVETYPE_STEP entity hits the ground at high speed (empty cvar disables the sound)"};
120 cvar_t sv_sound_watersplash = {0, "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)"};
121 cvar_t sv_stepheight = {CVAR_NOTIFY, "sv_stepheight", "18", "how high you can step up (TW_SV_STEPCONTROL extension)"};
122 cvar_t sv_stopspeed = {CVAR_NOTIFY, "sv_stopspeed","100", "how fast you come to a complete stop"};
123 cvar_t sv_wallfriction = {CVAR_NOTIFY, "sv_wallfriction", "1", "how much you slow down when sliding along a wall"};
124 cvar_t sv_wateraccelerate = {0, "sv_wateraccelerate", "-1", "rate at which a player accelerates to sv_maxspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
125 cvar_t sv_waterfriction = {CVAR_NOTIFY, "sv_waterfriction","-1", "how fast you slow down, if less than 0 the sv_friction variable is used instead"};
126 cvar_t sv_warsowbunny_airforwardaccel = {0, "sv_warsowbunny_airforwardaccel", "1.00001", "how fast you accelerate until you reach sv_maxspeed"};
127 cvar_t sv_warsowbunny_accel = {0, "sv_warsowbunny_accel", "0.1585", "how fast you accelerate until after reaching sv_maxspeed (it gets harder as you near sv_warsowbunny_topspeed)"};
128 cvar_t sv_warsowbunny_topspeed = {0, "sv_warsowbunny_topspeed", "925", "soft speed limit (can get faster with rjs and on ramps)"};
129 cvar_t sv_warsowbunny_turnaccel = {0, "sv_warsowbunny_turnaccel", "0", "max sharpness of turns (also master switch for the sv_warsowbunny_* mode; set this to 9 to enable)"};
130 cvar_t sv_warsowbunny_backtosideratio = {0, "sv_warsowbunny_backtosideratio", "0.8", "lower values make it easier to change direction without losing speed; the drawback is \"understeering\" in sharp turns"};
131 cvar_t sys_ticrate = {CVAR_SAVE, "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"};
132 cvar_t teamplay = {CVAR_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"};
133 cvar_t timelimit = {CVAR_NOTIFY, "timelimit","0", "ends level at this time (in minutes)"};
134
135 cvar_t saved1 = {CVAR_SAVE, "saved1", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
136 cvar_t saved2 = {CVAR_SAVE, "saved2", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
137 cvar_t saved3 = {CVAR_SAVE, "saved3", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
138 cvar_t saved4 = {CVAR_SAVE, "saved4", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
139 cvar_t savedgamecfg = {CVAR_SAVE, "savedgamecfg", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
140 cvar_t scratch1 = {0, "scratch1", "0", "unused cvar in quake, can be used by mods"};
141 cvar_t scratch2 = {0,"scratch2", "0", "unused cvar in quake, can be used by mods"};
142 cvar_t scratch3 = {0, "scratch3", "0", "unused cvar in quake, can be used by mods"};
143 cvar_t scratch4 = {0, "scratch4", "0", "unused cvar in quake, can be used by mods"};
144 cvar_t temp1 = {0, "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)"};
145
146 cvar_t nehx00 = {0, "nehx00", "0", "nehahra data storage cvar (used in singleplayer)"};
147 cvar_t nehx01 = {0, "nehx01", "0", "nehahra data storage cvar (used in singleplayer)"};
148 cvar_t nehx02 = {0, "nehx02", "0", "nehahra data storage cvar (used in singleplayer)"};
149 cvar_t nehx03 = {0, "nehx03", "0", "nehahra data storage cvar (used in singleplayer)"};
150 cvar_t nehx04 = {0, "nehx04", "0", "nehahra data storage cvar (used in singleplayer)"};
151 cvar_t nehx05 = {0, "nehx05", "0", "nehahra data storage cvar (used in singleplayer)"};
152 cvar_t nehx06 = {0, "nehx06", "0", "nehahra data storage cvar (used in singleplayer)"};
153 cvar_t nehx07 = {0, "nehx07", "0", "nehahra data storage cvar (used in singleplayer)"};
154 cvar_t nehx08 = {0, "nehx08", "0", "nehahra data storage cvar (used in singleplayer)"};
155 cvar_t nehx09 = {0, "nehx09", "0", "nehahra data storage cvar (used in singleplayer)"};
156 cvar_t nehx10 = {0, "nehx10", "0", "nehahra data storage cvar (used in singleplayer)"};
157 cvar_t nehx11 = {0, "nehx11", "0", "nehahra data storage cvar (used in singleplayer)"};
158 cvar_t nehx12 = {0, "nehx12", "0", "nehahra data storage cvar (used in singleplayer)"};
159 cvar_t nehx13 = {0, "nehx13", "0", "nehahra data storage cvar (used in singleplayer)"};
160 cvar_t nehx14 = {0, "nehx14", "0", "nehahra data storage cvar (used in singleplayer)"};
161 cvar_t nehx15 = {0, "nehx15", "0", "nehahra data storage cvar (used in singleplayer)"};
162 cvar_t nehx16 = {0, "nehx16", "0", "nehahra data storage cvar (used in singleplayer)"};
163 cvar_t nehx17 = {0, "nehx17", "0", "nehahra data storage cvar (used in singleplayer)"};
164 cvar_t nehx18 = {0, "nehx18", "0", "nehahra data storage cvar (used in singleplayer)"};
165 cvar_t nehx19 = {0, "nehx19", "0", "nehahra data storage cvar (used in singleplayer)"};
166 cvar_t cutscene = {0, "cutscene", "1", "enables cutscenes in nehahra, can be used by other mods"};
167
168 cvar_t sv_autodemo_perclient = {CVAR_SAVE, "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)"};
169 cvar_t sv_autodemo_perclient_nameformat = {CVAR_SAVE, "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)" };
170
171 cvar_t halflifebsp = {0, "halflifebsp", "0", "indicates the current map is hlbsp format (useful to know because of different bounding box sizes)"};
172
173 server_t sv;
174 server_static_t svs;
175
176 mempool_t *sv_mempool = NULL;
177
178 extern cvar_t slowmo;
179 extern float            scr_centertime_off;
180
181 // MUST match effectnameindex_t in client.h
182 static const char *standardeffectnames[EFFECT_TOTAL] =
183 {
184         "",
185         "TE_GUNSHOT",
186         "TE_GUNSHOTQUAD",
187         "TE_SPIKE",
188         "TE_SPIKEQUAD",
189         "TE_SUPERSPIKE",
190         "TE_SUPERSPIKEQUAD",
191         "TE_WIZSPIKE",
192         "TE_KNIGHTSPIKE",
193         "TE_EXPLOSION",
194         "TE_EXPLOSIONQUAD",
195         "TE_TAREXPLOSION",
196         "TE_TELEPORT",
197         "TE_LAVASPLASH",
198         "TE_SMALLFLASH",
199         "TE_FLAMEJET",
200         "EF_FLAME",
201         "TE_BLOOD",
202         "TE_SPARK",
203         "TE_PLASMABURN",
204         "TE_TEI_G3",
205         "TE_TEI_SMOKE",
206         "TE_TEI_BIGEXPLOSION",
207         "TE_TEI_PLASMAHIT",
208         "EF_STARDUST",
209         "TR_ROCKET",
210         "TR_GRENADE",
211         "TR_BLOOD",
212         "TR_WIZSPIKE",
213         "TR_SLIGHTBLOOD",
214         "TR_KNIGHTSPIKE",
215         "TR_VORESPIKE",
216         "TR_NEHAHRASMOKE",
217         "TR_NEXUIZPLASMA",
218         "TR_GLOWTRAIL",
219         "SVC_PARTICLE"
220 };
221
222 #define REQFIELDS (sizeof(reqfields) / sizeof(prvm_required_field_t))
223
224 prvm_required_field_t reqfields[] =
225 {
226         {ev_entity, "cursor_trace_ent"},
227         {ev_entity, "drawonlytoclient"},
228         {ev_entity, "exteriormodeltoclient"},
229         {ev_entity, "nodrawtoclient"},
230         {ev_entity, "tag_entity"},
231         {ev_entity, "viewmodelforclient"},
232         {ev_float, "SendFlags"},
233         {ev_float, "Version"},
234         {ev_float, "alpha"},
235         {ev_float, "ammo_cells1"},
236         {ev_float, "ammo_lava_nails"},
237         {ev_float, "ammo_multi_rockets"},
238         {ev_float, "ammo_nails1"},
239         {ev_float, "ammo_plasma"},
240         {ev_float, "ammo_rockets1"},
241         {ev_float, "ammo_shells1"},
242         {ev_float, "button3"},
243         {ev_float, "button4"},
244         {ev_float, "button5"},
245         {ev_float, "button6"},
246         {ev_float, "button7"},
247         {ev_float, "button8"},
248         {ev_float, "button9"},
249         {ev_float, "button10"},
250         {ev_float, "button11"},
251         {ev_float, "button12"},
252         {ev_float, "button13"},
253         {ev_float, "button14"},
254         {ev_float, "button15"},
255         {ev_float, "button16"},
256         {ev_float, "buttonchat"},
257         {ev_float, "buttonuse"},
258         {ev_float, "clientcolors"},
259         {ev_float, "cursor_active"},
260         {ev_float, "disableclientprediction"},
261         {ev_float, "fullbright"},
262         {ev_float, "glow_color"},
263         {ev_float, "glow_size"},
264         {ev_float, "glow_trail"},
265         {ev_float, "gravity"},
266         {ev_float, "idealpitch"},
267         {ev_float, "items2"},
268         {ev_float, "light_lev"},
269         {ev_float, "modelflags"},
270         {ev_float, "pflags"},
271         {ev_float, "ping"},
272         {ev_float, "pitch_speed"},
273         {ev_float, "pmodel"},
274         {ev_float, "renderamt"}, // HalfLife support
275         {ev_float, "rendermode"}, // HalfLife support
276         {ev_float, "scale"},
277         {ev_float, "style"},
278         {ev_float, "tag_index"},
279         {ev_float, "viewzoom"},
280         {ev_function, "SendEntity"},
281         {ev_function, "contentstransition"}, // DRESK - Support for Entity Contents Transition Event
282         {ev_function, "customizeentityforclient"},
283         {ev_function, "movetypesteplandevent"}, // DRESK - Support for MOVETYPE_STEP Entity Land Event
284         {ev_string, "netaddress"},
285         {ev_string, "playermodel"},
286         {ev_string, "playerskin"},
287         {ev_vector, "color"},
288         {ev_vector, "colormod"},
289         {ev_vector, "cursor_screen"},
290         {ev_vector, "cursor_trace_endpos"},
291         {ev_vector, "cursor_trace_start"},
292         {ev_vector, "movement"},
293         {ev_vector, "punchvector"},
294 };
295
296
297
298 //============================================================================
299
300 void SV_AreaStats_f(void)
301 {
302         World_PrintAreaStats(&sv.world, "server");
303 }
304
305 /*
306 ===============
307 SV_Init
308 ===============
309 */
310 void SV_Init (void)
311 {
312         // init the csqc progs cvars, since they are updated/used by the server code
313         // TODO: fix this since this is a quick hack to make some of [515]'s broken code run ;) [9/13/2006 Black]
314         extern cvar_t csqc_progname;    //[515]: csqc crc check and right csprogs name according to progs.dat
315         extern cvar_t csqc_progcrc;
316         extern cvar_t csqc_progsize;
317         Cvar_RegisterVariable (&csqc_progname);
318         Cvar_RegisterVariable (&csqc_progcrc);
319         Cvar_RegisterVariable (&csqc_progsize);
320
321         Cmd_AddCommand("sv_saveentfile", SV_SaveEntFile_f, "save map entities to .ent file (to allow external editing)");
322         Cmd_AddCommand("sv_areastats", SV_AreaStats_f, "prints statistics on entity culling during collision traces");
323         Cmd_AddCommand_WithClientCommand("sv_startdownload", NULL, SV_StartDownload_f, "begins sending a file to the client (network protocol use only)");
324         Cmd_AddCommand_WithClientCommand("download", NULL, SV_Download_f, "downloads a specified file from the server");
325
326         Cvar_RegisterVariable (&coop);
327         Cvar_RegisterVariable (&deathmatch);
328         Cvar_RegisterVariable (&fraglimit);
329         Cvar_RegisterVariable (&gamecfg);
330         Cvar_RegisterVariable (&noexit);
331         Cvar_RegisterVariable (&nomonsters);
332         Cvar_RegisterVariable (&pausable);
333         Cvar_RegisterVariable (&pr_checkextension);
334         Cvar_RegisterVariable (&samelevel);
335         Cvar_RegisterVariable (&skill);
336         Cvar_RegisterVariable (&slowmo);
337         Cvar_RegisterVariable (&sv_accelerate);
338         Cvar_RegisterVariable (&sv_aim);
339         Cvar_RegisterVariable (&sv_airaccel_qw);
340         Cvar_RegisterVariable (&sv_airaccel_sideways_friction);
341         Cvar_RegisterVariable (&sv_airaccelerate);
342         Cvar_RegisterVariable (&sv_airstopaccelerate);
343         Cvar_RegisterVariable (&sv_airstrafeaccelerate);
344         Cvar_RegisterVariable (&sv_maxairstrafespeed);
345         Cvar_RegisterVariable (&sv_aircontrol);
346         Cvar_RegisterVariable (&sv_allowdownloads);
347         Cvar_RegisterVariable (&sv_allowdownloads_archive);
348         Cvar_RegisterVariable (&sv_allowdownloads_config);
349         Cvar_RegisterVariable (&sv_allowdownloads_dlcache);
350         Cvar_RegisterVariable (&sv_allowdownloads_inarchive);
351         Cvar_RegisterVariable (&sv_areagrid_mingridsize);
352         Cvar_RegisterVariable (&sv_checkforpacketsduringsleep);
353         Cvar_RegisterVariable (&sv_clmovement_enable);
354         Cvar_RegisterVariable (&sv_clmovement_minping);
355         Cvar_RegisterVariable (&sv_clmovement_minping_disabletime);
356         Cvar_RegisterVariable (&sv_clmovement_inputtimeout);
357         Cvar_RegisterVariable (&sv_cullentities_nevercullbmodels);
358         Cvar_RegisterVariable (&sv_cullentities_pvs);
359         Cvar_RegisterVariable (&sv_cullentities_stats);
360         Cvar_RegisterVariable (&sv_cullentities_trace);
361         Cvar_RegisterVariable (&sv_cullentities_trace_delay);
362         Cvar_RegisterVariable (&sv_cullentities_trace_delay_players);
363         Cvar_RegisterVariable (&sv_cullentities_trace_enlarge);
364         Cvar_RegisterVariable (&sv_cullentities_trace_prediction);
365         Cvar_RegisterVariable (&sv_cullentities_trace_samples);
366         Cvar_RegisterVariable (&sv_cullentities_trace_samples_extra);
367         Cvar_RegisterVariable (&sv_cullentities_trace_samples_players);
368         Cvar_RegisterVariable (&sv_debugmove);
369         Cvar_RegisterVariable (&sv_echobprint);
370         Cvar_RegisterVariable (&sv_edgefriction);
371         Cvar_RegisterVariable (&sv_entpatch);
372         Cvar_RegisterVariable (&sv_fixedframeratesingleplayer);
373         Cvar_RegisterVariable (&sv_freezenonclients);
374         Cvar_RegisterVariable (&sv_friction);
375         Cvar_RegisterVariable (&sv_gameplayfix_blowupfallenzombies);
376         Cvar_RegisterVariable (&sv_gameplayfix_delayprojectiles);
377         Cvar_RegisterVariable (&sv_gameplayfix_droptofloorstartsolid);
378         Cvar_RegisterVariable (&sv_gameplayfix_droptofloorstartsolid_nudgetocorrect);
379         Cvar_RegisterVariable (&sv_gameplayfix_easierwaterjump);
380         Cvar_RegisterVariable (&sv_gameplayfix_findradiusdistancetobox);
381         Cvar_RegisterVariable (&sv_gameplayfix_grenadebouncedownslopes);
382         Cvar_RegisterVariable (&sv_gameplayfix_multiplethinksperframe);
383         Cvar_RegisterVariable (&sv_gameplayfix_slidemoveprojectiles);
384         Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse);
385         Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse_allowsuspendeditems);
386         Cvar_RegisterVariable (&sv_gameplayfix_setmodelrealbox);
387         Cvar_RegisterVariable (&sv_gameplayfix_stepdown);
388         Cvar_RegisterVariable (&sv_gameplayfix_stepwhilejumping);
389         Cvar_RegisterVariable (&sv_gameplayfix_swiminbmodels);
390         Cvar_RegisterVariable (&sv_gameplayfix_upwardvelocityclearsongroundflag);
391         Cvar_RegisterVariable (&sv_gameplayfix_gravityunaffectedbyticrate);
392         Cvar_RegisterVariable (&sv_gameplayfix_q2airaccelerate);
393         Cvar_RegisterVariable (&sv_gravity);
394         Cvar_RegisterVariable (&sv_idealpitchscale);
395         Cvar_RegisterVariable (&sv_jumpstep);
396         Cvar_RegisterVariable (&sv_jumpvelocity);
397         Cvar_RegisterVariable (&sv_maxairspeed);
398         Cvar_RegisterVariable (&sv_maxrate);
399         Cvar_RegisterVariable (&sv_maxspeed);
400         Cvar_RegisterVariable (&sv_maxvelocity);
401         Cvar_RegisterVariable (&sv_newflymove);
402         Cvar_RegisterVariable (&sv_nostep);
403         Cvar_RegisterVariable (&sv_playerphysicsqc);
404         Cvar_RegisterVariable (&sv_progs);
405         Cvar_RegisterVariable (&sv_protocolname);
406         Cvar_RegisterVariable (&sv_random_seed);
407         Cvar_RegisterVariable (&sv_ratelimitlocalplayer);
408         Cvar_RegisterVariable (&sv_sound_land);
409         Cvar_RegisterVariable (&sv_sound_watersplash);
410         Cvar_RegisterVariable (&sv_stepheight);
411         Cvar_RegisterVariable (&sv_stopspeed);
412         Cvar_RegisterVariable (&sv_wallfriction);
413         Cvar_RegisterVariable (&sv_wateraccelerate);
414         Cvar_RegisterVariable (&sv_waterfriction);
415         Cvar_RegisterVariable (&sv_warsowbunny_airforwardaccel);
416         Cvar_RegisterVariable (&sv_warsowbunny_accel);
417         Cvar_RegisterVariable (&sv_warsowbunny_topspeed);
418         Cvar_RegisterVariable (&sv_warsowbunny_turnaccel);
419         Cvar_RegisterVariable (&sv_warsowbunny_backtosideratio);
420         Cvar_RegisterVariable (&sys_ticrate);
421         Cvar_RegisterVariable (&teamplay);
422         Cvar_RegisterVariable (&timelimit);
423
424         Cvar_RegisterVariable (&saved1);
425         Cvar_RegisterVariable (&saved2);
426         Cvar_RegisterVariable (&saved3);
427         Cvar_RegisterVariable (&saved4);
428         Cvar_RegisterVariable (&savedgamecfg);
429         Cvar_RegisterVariable (&scratch1);
430         Cvar_RegisterVariable (&scratch2);
431         Cvar_RegisterVariable (&scratch3);
432         Cvar_RegisterVariable (&scratch4);
433         Cvar_RegisterVariable (&temp1);
434
435         // LordHavoc: Nehahra uses these to pass data around cutscene demos
436         if (gamemode == GAME_NEHAHRA)
437         {
438                 Cvar_RegisterVariable (&nehx00);
439                 Cvar_RegisterVariable (&nehx01);
440                 Cvar_RegisterVariable (&nehx02);
441                 Cvar_RegisterVariable (&nehx03);
442                 Cvar_RegisterVariable (&nehx04);
443                 Cvar_RegisterVariable (&nehx05);
444                 Cvar_RegisterVariable (&nehx06);
445                 Cvar_RegisterVariable (&nehx07);
446                 Cvar_RegisterVariable (&nehx08);
447                 Cvar_RegisterVariable (&nehx09);
448                 Cvar_RegisterVariable (&nehx10);
449                 Cvar_RegisterVariable (&nehx11);
450                 Cvar_RegisterVariable (&nehx12);
451                 Cvar_RegisterVariable (&nehx13);
452                 Cvar_RegisterVariable (&nehx14);
453                 Cvar_RegisterVariable (&nehx15);
454                 Cvar_RegisterVariable (&nehx16);
455                 Cvar_RegisterVariable (&nehx17);
456                 Cvar_RegisterVariable (&nehx18);
457                 Cvar_RegisterVariable (&nehx19);
458         }
459         Cvar_RegisterVariable (&cutscene); // for Nehahra but useful to other mods as well
460
461         Cvar_RegisterVariable (&sv_autodemo_perclient);
462         Cvar_RegisterVariable (&sv_autodemo_perclient_nameformat);
463
464         Cvar_RegisterVariable (&halflifebsp);
465
466         // any special defaults for gamemodes go here
467         if (gamemode == GAME_NEHAHRA)
468         {
469                 // Nehahra pushable crates malfunction in some levels if this is on
470                 Cvar_SetValueQuick (&sv_gameplayfix_upwardvelocityclearsongroundflag, 0);
471                 // Nehahra NPC AI is confused by this feature
472                 Cvar_SetValueQuick (&sv_gameplayfix_blowupfallenzombies, 0);
473         }
474         if (gamemode == GAME_HIPNOTIC)
475         {
476                 // hipnotic mission pack has issues in their 'friendly monster' ai, which seem to attempt to attack themselves for some reason when findradius() returns non-solid entities.
477                 Cvar_SetValueQuick (&sv_gameplayfix_blowupfallenzombies, 0);
478                 // hipnotic mission pack has issues with bobbing water entities 'jittering' between different heights on alternate frames at the default 0.0138889 ticrate, 0.02 avoids this issue
479                 Cvar_SetValueQuick (&sys_ticrate, 0.02);
480                 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.                                                                                     
481                 Cvar_SetValueQuick (&sv_gameplayfix_slidemoveprojectiles, 0);                                                                                                                                   
482         }
483         if (gamemode == GAME_ROGUE)
484         {
485                 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
486                 Cvar_SetValueQuick (&sv_gameplayfix_findradiusdistancetobox, 0);
487         }
488         if (gamemode == GAME_NEXUIZ)
489         {
490                 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
491                 Cvar_SetValueQuick (&sv_gameplayfix_q2airaccelerate, 1);
492         }
493
494         sv_mempool = Mem_AllocPool("server", 0, NULL);
495 }
496
497 static void SV_SaveEntFile_f(void)
498 {
499         char basename[MAX_QPATH];
500         if (!sv.active || !sv.worldmodel)
501         {
502                 Con_Print("Not running a server\n");
503                 return;
504         }
505         FS_StripExtension(sv.worldmodel->name, basename, sizeof(basename));
506         FS_WriteFile(va("%s.ent", basename), sv.worldmodel->brush.entities, (fs_offset_t)strlen(sv.worldmodel->brush.entities));
507 }
508
509
510 /*
511 =============================================================================
512
513 EVENT MESSAGES
514
515 =============================================================================
516 */
517
518 /*
519 ==================
520 SV_StartParticle
521
522 Make sure the event gets sent to all clients
523 ==================
524 */
525 void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
526 {
527         int i;
528
529         if (sv.datagram.cursize > MAX_PACKETFRAGMENT-18)
530                 return;
531         MSG_WriteByte (&sv.datagram, svc_particle);
532         MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
533         MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
534         MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
535         for (i=0 ; i<3 ; i++)
536                 MSG_WriteChar (&sv.datagram, (int)bound(-128, dir[i]*16, 127));
537         MSG_WriteByte (&sv.datagram, count);
538         MSG_WriteByte (&sv.datagram, color);
539         SV_FlushBroadcastMessages();
540 }
541
542 /*
543 ==================
544 SV_StartEffect
545
546 Make sure the event gets sent to all clients
547 ==================
548 */
549 void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
550 {
551         if (modelindex >= 256 || startframe >= 256)
552         {
553                 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-19)
554                         return;
555                 MSG_WriteByte (&sv.datagram, svc_effect2);
556                 MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
557                 MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
558                 MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
559                 MSG_WriteShort (&sv.datagram, modelindex);
560                 MSG_WriteShort (&sv.datagram, startframe);
561                 MSG_WriteByte (&sv.datagram, framecount);
562                 MSG_WriteByte (&sv.datagram, framerate);
563         }
564         else
565         {
566                 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-17)
567                         return;
568                 MSG_WriteByte (&sv.datagram, svc_effect);
569                 MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
570                 MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
571                 MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
572                 MSG_WriteByte (&sv.datagram, modelindex);
573                 MSG_WriteByte (&sv.datagram, startframe);
574                 MSG_WriteByte (&sv.datagram, framecount);
575                 MSG_WriteByte (&sv.datagram, framerate);
576         }
577         SV_FlushBroadcastMessages();
578 }
579
580 /*
581 ==================
582 SV_StartSound
583
584 Each entity can have eight independant sound sources, like voice,
585 weapon, feet, etc.
586
587 Channel 0 is an auto-allocate channel, the others override anything
588 already running on that entity/channel pair.
589
590 An attenuation of 0 will play full volume everywhere in the level.
591 Larger attenuations will drop off.  (max 4 attenuation)
592
593 ==================
594 */
595 void SV_StartSound (prvm_edict_t *entity, int channel, const char *sample, int volume, float attenuation)
596 {
597         int sound_num, field_mask, i, ent;
598
599         if (volume < 0 || volume > 255)
600         {
601                 Con_Printf ("SV_StartSound: volume = %i\n", volume);
602                 return;
603         }
604
605         if (attenuation < 0 || attenuation > 4)
606         {
607                 Con_Printf ("SV_StartSound: attenuation = %f\n", attenuation);
608                 return;
609         }
610
611         if (channel < 0 || channel > 7)
612         {
613                 Con_Printf ("SV_StartSound: channel = %i\n", channel);
614                 return;
615         }
616
617         if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
618                 return;
619
620 // find precache number for sound
621         sound_num = SV_SoundIndex(sample, 1);
622         if (!sound_num)
623                 return;
624
625         ent = PRVM_NUM_FOR_EDICT(entity);
626
627         field_mask = 0;
628         if (volume != DEFAULT_SOUND_PACKET_VOLUME)
629                 field_mask |= SND_VOLUME;
630         if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
631                 field_mask |= SND_ATTENUATION;
632         if (ent >= 8192)
633                 field_mask |= SND_LARGEENTITY;
634         if (sound_num >= 256 || channel >= 8)
635                 field_mask |= SND_LARGESOUND;
636
637 // directed messages go only to the entity they are targeted on
638         MSG_WriteByte (&sv.datagram, svc_sound);
639         MSG_WriteByte (&sv.datagram, field_mask);
640         if (field_mask & SND_VOLUME)
641                 MSG_WriteByte (&sv.datagram, volume);
642         if (field_mask & SND_ATTENUATION)
643                 MSG_WriteByte (&sv.datagram, (int)(attenuation*64));
644         if (field_mask & SND_LARGEENTITY)
645         {
646                 MSG_WriteShort (&sv.datagram, ent);
647                 MSG_WriteByte (&sv.datagram, channel);
648         }
649         else
650                 MSG_WriteShort (&sv.datagram, (ent<<3) | channel);
651         if ((field_mask & SND_LARGESOUND) || sv.protocol == PROTOCOL_NEHAHRABJP2)
652                 MSG_WriteShort (&sv.datagram, sound_num);
653         else
654                 MSG_WriteByte (&sv.datagram, sound_num);
655         for (i = 0;i < 3;i++)
656                 MSG_WriteCoord (&sv.datagram, entity->fields.server->origin[i]+0.5*(entity->fields.server->mins[i]+entity->fields.server->maxs[i]), sv.protocol);
657         SV_FlushBroadcastMessages();
658 }
659
660 /*
661 ==================
662 SV_StartPointSound
663
664 Nearly the same logic as SV_StartSound, except an origin
665 instead of an entity is provided and channel is omitted.
666
667 The entity sent to the client is 0 (world) and the channel
668 is 0 (CHAN_AUTO).  SND_LARGEENTITY will never occur in this
669 function, therefore the check for it is omitted.
670
671 ==================
672 */
673 void SV_StartPointSound (vec3_t origin, const char *sample, int volume, float attenuation)
674 {
675         int sound_num, field_mask, i;
676
677         if (volume < 0 || volume > 255)
678         {
679                 Con_Printf ("SV_StartPointSound: volume = %i\n", volume);
680                 return;
681         }
682
683         if (attenuation < 0 || attenuation > 4)
684         {
685                 Con_Printf ("SV_StartPointSound: attenuation = %f\n", attenuation);
686                 return;
687         }
688
689         if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
690                 return;
691
692         // find precache number for sound
693         sound_num = SV_SoundIndex(sample, 1);
694         if (!sound_num)
695                 return;
696
697         field_mask = 0;
698         if (volume != DEFAULT_SOUND_PACKET_VOLUME)
699                 field_mask |= SND_VOLUME;
700         if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
701                 field_mask |= SND_ATTENUATION;
702         if (sound_num >= 256)
703                 field_mask |= SND_LARGESOUND;
704
705 // directed messages go only to the entity they are targeted on
706         MSG_WriteByte (&sv.datagram, svc_sound);
707         MSG_WriteByte (&sv.datagram, field_mask);
708         if (field_mask & SND_VOLUME)
709                 MSG_WriteByte (&sv.datagram, volume);
710         if (field_mask & SND_ATTENUATION)
711                 MSG_WriteByte (&sv.datagram, (int)(attenuation*64));
712         // Always write entnum 0 for the world entity
713         MSG_WriteShort (&sv.datagram, (0<<3) | 0);
714         if (field_mask & SND_LARGESOUND)
715                 MSG_WriteShort (&sv.datagram, sound_num);
716         else
717                 MSG_WriteByte (&sv.datagram, sound_num);
718         for (i = 0;i < 3;i++)
719                 MSG_WriteCoord (&sv.datagram, origin[i], sv.protocol);
720         SV_FlushBroadcastMessages();
721 }
722
723 /*
724 ==============================================================================
725
726 CLIENT SPAWNING
727
728 ==============================================================================
729 */
730
731 /*
732 ================
733 SV_SendServerinfo
734
735 Sends the first message from the server to a connected client.
736 This will be sent on the initial connection and upon each server load.
737 ================
738 */
739 void SV_SendServerinfo (client_t *client)
740 {
741         int i;
742         char message[128];
743
744         // we know that this client has a netconnection and thus is not a bot
745
746         // edicts get reallocated on level changes, so we need to update it here
747         client->edict = PRVM_EDICT_NUM((client - svs.clients) + 1);
748
749         // clear cached stuff that depends on the level
750         client->weaponmodel[0] = 0;
751         client->weaponmodelindex = 0;
752
753         // LordHavoc: clear entityframe tracking
754         client->latestframenum = 0;
755
756         // initialize the movetime, so a speedhack can't make use of the time before this client joined
757         client->cmd.time = sv.time;
758
759         if (client->entitydatabase)
760                 EntityFrame_FreeDatabase(client->entitydatabase);
761         if (client->entitydatabase4)
762                 EntityFrame4_FreeDatabase(client->entitydatabase4);
763         if (client->entitydatabase5)
764                 EntityFrame5_FreeDatabase(client->entitydatabase5);
765
766         memset(client->stats, 0, sizeof(client->stats));
767         memset(client->statsdeltabits, 0, sizeof(client->statsdeltabits));
768
769         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)
770         {
771                 if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3)
772                         client->entitydatabase = EntityFrame_AllocDatabase(sv_mempool);
773                 else if (sv.protocol == PROTOCOL_DARKPLACES4)
774                         client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_mempool);
775                 else
776                         client->entitydatabase5 = EntityFrame5_AllocDatabase(sv_mempool);
777         }
778
779         // reset csqc entity versions
780         for (i = 0;i < prog->max_edicts;i++)
781         {
782                 client->csqcentityscope[i] = 0;
783                 client->csqcentitysendflags[i] = 0xFFFFFF;
784                 client->csqcentityglobalhistory[i] = 0;
785         }
786         for (i = 0;i < NUM_CSQCENTITYDB_FRAMES;i++)
787         {
788                 client->csqcentityframehistory[i].num = 0;
789                 client->csqcentityframehistory[i].framenum = -1;
790         }
791         client->csqcnumedicts = 0;
792         client->csqcentityframehistory_next = 0;
793
794         SZ_Clear (&client->netconnection->message);
795         MSG_WriteByte (&client->netconnection->message, svc_print);
796         dpsnprintf (message, sizeof (message), "\nServer: %s build %s (progs %i crc)", gamename, buildstring, prog->filecrc);
797         MSG_WriteString (&client->netconnection->message,message);
798
799         SV_StopDemoRecording(client); // to split up demos into different files
800         if(sv_autodemo_perclient.integer && client->netconnection)
801         {
802                 char demofile[MAX_OSPATH];
803                 char levelname[MAX_QPATH];
804                 char ipaddress[MAX_QPATH];
805                 size_t i;
806
807                 // start a new demo file
808                 strlcpy(levelname, FS_FileWithoutPath(sv.worldmodel->name), sizeof(levelname));
809                 if (strrchr(levelname, '.'))
810                         *(strrchr(levelname, '.')) = 0;
811
812                 LHNETADDRESS_ToString(&(client->netconnection->peeraddress), ipaddress, sizeof(ipaddress), true);
813                 for(i = 0; ipaddress[i]; ++i)
814                         if(!isalnum(ipaddress[i]))
815                                 ipaddress[i] = '-';
816                 dpsnprintf (demofile, sizeof(demofile), "%s_%s_%d_%s.dem", Sys_TimeString (sv_autodemo_perclient_nameformat.string), levelname, PRVM_NUM_FOR_EDICT(client->edict), ipaddress);
817
818                 SV_StartDemoRecording(client, demofile, -1);
819         }
820
821         //[515]: init csprogs according to version of svprogs, check the crc, etc.
822         if (sv.csqc_progname[0])
823         {
824                 prvm_eval_t *val;
825                 Con_DPrintf("sending csqc info to client (\"%s\" with size %i and crc %i)\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
826                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
827                 MSG_WriteString (&client->netconnection->message, va("csqc_progname %s\n", sv.csqc_progname));
828                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
829                 MSG_WriteString (&client->netconnection->message, va("csqc_progsize %i\n", sv.csqc_progsize));
830                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
831                 MSG_WriteString (&client->netconnection->message, va("csqc_progcrc %i\n", sv.csqc_progcrc));
832
833                 if(client->sv_demo_file != NULL)
834                 {
835                         int i;
836                         char buf[NET_MAXMESSAGE];
837                         sizebuf_t sb;
838
839                         sb.data = (unsigned char *) buf;
840                         sb.maxsize = sizeof(buf);
841                         i = 0;
842                         while(MakeDownloadPacket(sv.csqc_progname, svs.csqc_progdata, sv.csqc_progsize, sv.csqc_progcrc, i++, &sb, sv.protocol))
843                                 SV_WriteDemoMessage(client, &sb, false);
844                 }
845
846                 //[515]: init stufftext string (it is sent before svc_serverinfo)
847                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.SV_InitCmd);
848                 if (val)
849                 {
850                         MSG_WriteByte (&client->netconnection->message, svc_stufftext);
851                         MSG_WriteString (&client->netconnection->message, va("%s\n", PRVM_GetString(val->string)));
852                 }
853         }
854
855         //if (sv_allowdownloads.integer)
856         // always send the info that the server supports the protocol, even if downloads are forbidden
857         // only because of that, the CSQC exception can work
858         {
859                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
860                 MSG_WriteString (&client->netconnection->message, "cl_serverextension_download 2\n");
861         }
862
863         // send at this time so it's guaranteed to get executed at the right time
864         {
865                 client_t *save;
866                 save = host_client;
867                 host_client = client;
868                 Curl_SendRequirements();
869                 host_client = save;
870         }
871
872         MSG_WriteByte (&client->netconnection->message, svc_serverinfo);
873         MSG_WriteLong (&client->netconnection->message, Protocol_NumberForEnum(sv.protocol));
874         MSG_WriteByte (&client->netconnection->message, svs.maxclients);
875
876         if (!coop.integer && deathmatch.integer)
877                 MSG_WriteByte (&client->netconnection->message, GAME_DEATHMATCH);
878         else
879                 MSG_WriteByte (&client->netconnection->message, GAME_COOP);
880
881         MSG_WriteString (&client->netconnection->message,PRVM_GetString(prog->edicts->fields.server->message));
882
883         for (i = 1;i < MAX_MODELS && sv.model_precache[i][0];i++)
884                 MSG_WriteString (&client->netconnection->message, sv.model_precache[i]);
885         MSG_WriteByte (&client->netconnection->message, 0);
886
887         for (i = 1;i < MAX_SOUNDS && sv.sound_precache[i][0];i++)
888                 MSG_WriteString (&client->netconnection->message, sv.sound_precache[i]);
889         MSG_WriteByte (&client->netconnection->message, 0);
890
891 // send music
892         MSG_WriteByte (&client->netconnection->message, svc_cdtrack);
893         MSG_WriteByte (&client->netconnection->message, (int)prog->edicts->fields.server->sounds);
894         MSG_WriteByte (&client->netconnection->message, (int)prog->edicts->fields.server->sounds);
895
896 // set view
897 // store this in clientcamera, too
898         client->clientcamera = PRVM_NUM_FOR_EDICT(client->edict);
899         MSG_WriteByte (&client->netconnection->message, svc_setview);
900         MSG_WriteShort (&client->netconnection->message, client->clientcamera);
901
902         MSG_WriteByte (&client->netconnection->message, svc_signonnum);
903         MSG_WriteByte (&client->netconnection->message, 1);
904
905         client->spawned = false;                // need prespawn, spawn, etc
906         client->sendsignon = 1;                 // send this message, and increment to 2, 2 will be set to 0 by the prespawn command
907
908         // clear movement info until client enters the new level properly
909         memset(&client->cmd, 0, sizeof(client->cmd));
910         client->movesequence = 0;
911 #ifdef NUM_PING_TIMES
912         for (i = 0;i < NUM_PING_TIMES;i++)
913                 client->ping_times[i] = 0;
914         client->num_pings = 0;
915 #endif
916         client->ping = 0;
917
918         // allow the client some time to send his keepalives, even if map loading took ages
919         client->netconnection->timeout = realtime + net_connecttimeout.value;
920 }
921
922 /*
923 ================
924 SV_ConnectClient
925
926 Initializes a client_t for a new net connection.  This will only be called
927 once for a player each game, not once for each level change.
928 ================
929 */
930 void SV_ConnectClient (int clientnum, netconn_t *netconnection)
931 {
932         client_t                *client;
933         int                             i;
934         float                   spawn_parms[NUM_SPAWN_PARMS];
935
936         client = svs.clients + clientnum;
937
938 // set up the client_t
939         if (sv.loadgame)
940                 memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms));
941         memset (client, 0, sizeof(*client));
942         client->active = true;
943         client->netconnection = netconnection;
944
945         Con_DPrintf("Client %s connected\n", client->netconnection ? client->netconnection->address : "botclient");
946
947         strlcpy(client->name, "unconnected", sizeof(client->name));
948         strlcpy(client->old_name, "unconnected", sizeof(client->old_name));
949         client->spawned = false;
950         client->edict = PRVM_EDICT_NUM(clientnum+1);
951         if (client->netconnection)
952                 client->netconnection->message.allowoverflow = true;            // we can catch it
953         // prepare the unreliable message buffer
954         client->unreliablemsg.data = client->unreliablemsg_data;
955         client->unreliablemsg.maxsize = sizeof(client->unreliablemsg_data);
956         // updated by receiving "rate" command from client, this is also the default if not using a DP client
957         client->rate = 1000000000;
958         // no limits for local player
959         if (client->netconnection && LHNETADDRESS_GetAddressType(&client->netconnection->peeraddress) == LHNETADDRESSTYPE_LOOP)
960                 client->rate = 1000000000;
961         client->connecttime = realtime;
962
963         if (sv.loadgame)
964                 memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms));
965         else
966         {
967                 // call the progs to get default spawn parms for the new client
968                 // set self to world to intentionally cause errors with broken SetNewParms code in some mods
969                 prog->globals.server->self = 0;
970                 PRVM_ExecuteProgram (prog->globals.server->SetNewParms, "QC function SetNewParms is missing");
971                 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
972                         client->spawn_parms[i] = (&prog->globals.server->parm1)[i];
973
974                 // set up the entity for this client (including .colormap, .team, etc)
975                 PRVM_ED_ClearEdict(client->edict);
976         }
977
978         // don't call SendServerinfo for a fresh botclient because its fields have
979         // not been set up by the qc yet
980         if (client->netconnection)
981                 SV_SendServerinfo (client);
982         else
983                 client->spawned = true;
984 }
985
986
987 /*
988 ===============================================================================
989
990 FRAME UPDATES
991
992 ===============================================================================
993 */
994
995 /*
996 =============================================================================
997
998 The PVS must include a small area around the client to allow head bobbing
999 or other small motion on the client side.  Otherwise, a bob might cause an
1000 entity that should be visible to not show up, especially when the bob
1001 crosses a waterline.
1002
1003 =============================================================================
1004 */
1005
1006 static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *cs, int enumber)
1007 {
1008         int i;
1009         unsigned int sendflags;
1010         unsigned int version;
1011         unsigned int modelindex, effects, flags, glowsize, lightstyle, lightpflags, light[4], specialvisibilityradius;
1012         unsigned int customizeentityforclient;
1013         float f;
1014         vec3_t cullmins, cullmaxs;
1015         dp_model_t *model;
1016         prvm_eval_t *val, *val2;
1017
1018         // this 2 billion unit check is actually to detect NAN origins
1019         // (we really don't want to send those)
1020         if (!(VectorLength2(ent->fields.server->origin) < 2000000000.0*2000000000.0))
1021                 return false;
1022
1023         // EF_NODRAW prevents sending for any reason except for your own
1024         // client, so we must keep all clients in this superset
1025         effects = (unsigned)ent->fields.server->effects;
1026
1027         // we can omit invisible entities with no effects that are not clients
1028         // LordHavoc: this could kill tags attached to an invisible entity, I
1029         // just hope we never have to support that case
1030         i = (int)ent->fields.server->modelindex;
1031         modelindex = (i >= 1 && i < MAX_MODELS && ent->fields.server->model && *PRVM_GetString(ent->fields.server->model)) ? i : 0;
1032
1033         flags = 0;
1034         i = (int)(PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.glow_size)->_float * 0.25f);
1035         glowsize = (unsigned char)bound(0, i, 255);
1036         if (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.glow_trail)->_float)
1037                 flags |= RENDER_GLOWTRAIL;
1038         if (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.viewmodelforclient)->edict)
1039                 flags |= RENDER_VIEWMODEL;
1040
1041         f = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.color)->vector[0]*256;
1042         light[0] = (unsigned short)bound(0, f, 65535);
1043         f = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.color)->vector[1]*256;
1044         light[1] = (unsigned short)bound(0, f, 65535);
1045         f = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.color)->vector[2]*256;
1046         light[2] = (unsigned short)bound(0, f, 65535);
1047         f = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.light_lev)->_float;
1048         light[3] = (unsigned short)bound(0, f, 65535);
1049         lightstyle = (unsigned char)PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.style)->_float;
1050         lightpflags = (unsigned char)PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.pflags)->_float;
1051
1052         if (gamemode == GAME_TENEBRAE)
1053         {
1054                 // tenebrae's EF_FULLDYNAMIC conflicts with Q2's EF_NODRAW
1055                 if (effects & 16)
1056                 {
1057                         effects &= ~16;
1058                         lightpflags |= PFLAGS_FULLDYNAMIC;
1059                 }
1060                 // tenebrae's EF_GREEN conflicts with DP's EF_ADDITIVE
1061                 if (effects & 32)
1062                 {
1063                         effects &= ~32;
1064                         light[0] = (int)(0.2*256);
1065                         light[1] = (int)(1.0*256);
1066                         light[2] = (int)(0.2*256);
1067                         light[3] = 200;
1068                         lightpflags |= PFLAGS_FULLDYNAMIC;
1069                 }
1070         }
1071
1072         specialvisibilityradius = 0;
1073         if (lightpflags & PFLAGS_FULLDYNAMIC)
1074                 specialvisibilityradius = max(specialvisibilityradius, light[3]);
1075         if (glowsize)
1076                 specialvisibilityradius = max(specialvisibilityradius, glowsize * 4);
1077         if (flags & RENDER_GLOWTRAIL)
1078                 specialvisibilityradius = max(specialvisibilityradius, 100);
1079         if (effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
1080         {
1081                 if (effects & EF_BRIGHTFIELD)
1082                         specialvisibilityradius = max(specialvisibilityradius, 80);
1083                 if (effects & EF_MUZZLEFLASH)
1084                         specialvisibilityradius = max(specialvisibilityradius, 100);
1085                 if (effects & EF_BRIGHTLIGHT)
1086                         specialvisibilityradius = max(specialvisibilityradius, 400);
1087                 if (effects & EF_DIMLIGHT)
1088                         specialvisibilityradius = max(specialvisibilityradius, 200);
1089                 if (effects & EF_RED)
1090                         specialvisibilityradius = max(specialvisibilityradius, 200);
1091                 if (effects & EF_BLUE)
1092                         specialvisibilityradius = max(specialvisibilityradius, 200);
1093                 if (effects & EF_FLAME)
1094                         specialvisibilityradius = max(specialvisibilityradius, 250);
1095                 if (effects & EF_STARDUST)
1096                         specialvisibilityradius = max(specialvisibilityradius, 100);
1097         }
1098
1099         // early culling checks
1100         // (final culling is done by SV_MarkWriteEntityStateToClient)
1101         customizeentityforclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.customizeentityforclient)->function;
1102         if (!customizeentityforclient && enumber > svs.maxclients && (!modelindex && !specialvisibilityradius))
1103                 return false;
1104
1105         *cs = defaultstate;
1106         cs->active = ACTIVE_NETWORK;
1107         cs->number = enumber;
1108         VectorCopy(ent->fields.server->origin, cs->origin);
1109         VectorCopy(ent->fields.server->angles, cs->angles);
1110         cs->flags = flags;
1111         cs->effects = effects;
1112         cs->colormap = (unsigned)ent->fields.server->colormap;
1113         cs->modelindex = modelindex;
1114         cs->skin = (unsigned)ent->fields.server->skin;
1115         cs->frame = (unsigned)ent->fields.server->frame;
1116         cs->viewmodelforclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.viewmodelforclient)->edict;
1117         cs->exteriormodelforclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.exteriormodeltoclient)->edict;
1118         cs->nodrawtoclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.nodrawtoclient)->edict;
1119         cs->drawonlytoclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.drawonlytoclient)->edict;
1120         cs->customizeentityforclient = customizeentityforclient;
1121         cs->tagentity = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.tag_entity)->edict;
1122         cs->tagindex = (unsigned char)PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.tag_index)->_float;
1123         cs->glowsize = glowsize;
1124
1125         // don't need to init cs->colormod because the defaultstate did that for us
1126         //cs->colormod[0] = cs->colormod[1] = cs->colormod[2] = 32;
1127         val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.colormod);
1128         if (val->vector[0] || val->vector[1] || val->vector[2])
1129         {
1130                 i = (int)(val->vector[0] * 32.0f);cs->colormod[0] = bound(0, i, 255);
1131                 i = (int)(val->vector[1] * 32.0f);cs->colormod[1] = bound(0, i, 255);
1132                 i = (int)(val->vector[2] * 32.0f);cs->colormod[2] = bound(0, i, 255);
1133         }
1134
1135         cs->modelindex = modelindex;
1136
1137         cs->alpha = 255;
1138         f = (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.alpha)->_float * 255.0f);
1139         if (f)
1140         {
1141                 i = (int)f;
1142                 cs->alpha = (unsigned char)bound(0, i, 255);
1143         }
1144         // halflife
1145         f = (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.renderamt)->_float);
1146         if (f)
1147         {
1148                 i = (int)f;
1149                 cs->alpha = (unsigned char)bound(0, i, 255);
1150         }
1151
1152         cs->scale = 16;
1153         f = (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.scale)->_float * 16.0f);
1154         if (f)
1155         {
1156                 i = (int)f;
1157                 cs->scale = (unsigned char)bound(0, i, 255);
1158         }
1159
1160         cs->glowcolor = 254;
1161         f = (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.glow_color)->_float);
1162         if (f)
1163                 cs->glowcolor = (int)f;
1164
1165         if (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.fullbright)->_float)
1166                 cs->effects |= EF_FULLBRIGHT;
1167
1168         val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.modelflags);
1169         if (val && val->_float)
1170                 cs->effects |= ((unsigned int)val->_float & 0xff) << 24;
1171
1172         if (ent->fields.server->movetype == MOVETYPE_STEP)
1173                 cs->flags |= RENDER_STEP;
1174         if (cs->number != sv.writeentitiestoclient_cliententitynumber && (cs->effects & EF_LOWPRECISION) && cs->origin[0] >= -32768 && cs->origin[1] >= -32768 && cs->origin[2] >= -32768 && cs->origin[0] <= 32767 && cs->origin[1] <= 32767 && cs->origin[2] <= 32767)
1175                 cs->flags |= RENDER_LOWPRECISION;
1176         if (ent->fields.server->colormap >= 1024)
1177                 cs->flags |= RENDER_COLORMAPPED;
1178         if (cs->viewmodelforclient)
1179                 cs->flags |= RENDER_VIEWMODEL; // show relative to the view
1180
1181         cs->light[0] = light[0];
1182         cs->light[1] = light[1];
1183         cs->light[2] = light[2];
1184         cs->light[3] = light[3];
1185         cs->lightstyle = lightstyle;
1186         cs->lightpflags = lightpflags;
1187
1188         cs->specialvisibilityradius = specialvisibilityradius;
1189
1190         // calculate the visible box of this entity (don't use the physics box
1191         // as that is often smaller than a model, and would not count
1192         // specialvisibilityradius)
1193         if ((model = sv.models[modelindex]) && (model->type != mod_null))
1194         {
1195                 float scale = cs->scale * (1.0f / 16.0f);
1196                 if (cs->angles[0] || cs->angles[2]) // pitch and roll
1197                 {
1198                         VectorMA(cs->origin, scale, model->rotatedmins, cullmins);
1199                         VectorMA(cs->origin, scale, model->rotatedmaxs, cullmaxs);
1200                 }
1201                 else if (cs->angles[1])
1202                 {
1203                         VectorMA(cs->origin, scale, model->yawmins, cullmins);
1204                         VectorMA(cs->origin, scale, model->yawmaxs, cullmaxs);
1205                 }
1206                 else
1207                 {
1208                         VectorMA(cs->origin, scale, model->normalmins, cullmins);
1209                         VectorMA(cs->origin, scale, model->normalmaxs, cullmaxs);
1210                 }
1211         }
1212         else
1213         {
1214                 // if there is no model (or it could not be loaded), use the physics box
1215                 VectorAdd(cs->origin, ent->fields.server->mins, cullmins);
1216                 VectorAdd(cs->origin, ent->fields.server->maxs, cullmaxs);
1217         }
1218         if (specialvisibilityradius)
1219         {
1220                 cullmins[0] = min(cullmins[0], cs->origin[0] - specialvisibilityradius);
1221                 cullmins[1] = min(cullmins[1], cs->origin[1] - specialvisibilityradius);
1222                 cullmins[2] = min(cullmins[2], cs->origin[2] - specialvisibilityradius);
1223                 cullmaxs[0] = max(cullmaxs[0], cs->origin[0] + specialvisibilityradius);
1224                 cullmaxs[1] = max(cullmaxs[1], cs->origin[1] + specialvisibilityradius);
1225                 cullmaxs[2] = max(cullmaxs[2], cs->origin[2] + specialvisibilityradius);
1226         }
1227
1228         // calculate center of bbox for network prioritization purposes
1229         VectorMAM(0.5f, cullmins, 0.5f, cullmaxs, cs->netcenter);
1230
1231         // if culling box has moved, update pvs cluster links
1232         if (!VectorCompare(cullmins, ent->priv.server->cullmins) || !VectorCompare(cullmaxs, ent->priv.server->cullmaxs))
1233         {
1234                 VectorCopy(cullmins, ent->priv.server->cullmins);
1235                 VectorCopy(cullmaxs, ent->priv.server->cullmaxs);
1236                 // a value of -1 for pvs_numclusters indicates that the links are not
1237                 // cached, and should be re-tested each time, this is the case if the
1238                 // culling box touches too many pvs clusters to store, or if the world
1239                 // model does not support FindBoxClusters
1240                 ent->priv.server->pvs_numclusters = -1;
1241                 if (sv.worldmodel && sv.worldmodel->brush.FindBoxClusters)
1242                 {
1243                         i = sv.worldmodel->brush.FindBoxClusters(sv.worldmodel, cullmins, cullmaxs, MAX_ENTITYCLUSTERS, ent->priv.server->pvs_clusterlist);
1244                         if (i <= MAX_ENTITYCLUSTERS)
1245                                 ent->priv.server->pvs_numclusters = i;
1246                 }
1247         }
1248
1249         // we need to do some csqc entity upkeep here
1250         // get self.SendFlags and clear them
1251         // (to let the QC know that they've been read)
1252         val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.SendEntity);
1253         if (val->function)
1254         {
1255                 val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.SendFlags);
1256                 sendflags = (unsigned int)val->_float;
1257                 val->_float = 0;
1258                 // legacy self.Version system
1259                 val2 = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.Version);
1260                 if (val2->_float)
1261                 {
1262                         version = (unsigned int)val2->_float;
1263                         if (sv.csqcentityversion[enumber] != version)
1264                                 sendflags = 0xFFFFFF;
1265                         sv.csqcentityversion[enumber] = version;
1266                 }
1267                 // move sendflags into the per-client sendflags
1268                 if (sendflags)
1269                         for (i = 0;i < svs.maxclients;i++)
1270                                 svs.clients[i].csqcentitysendflags[enumber] |= sendflags;
1271                 // mark it as inactive for non-csqc networking
1272                 cs->active = ACTIVE_SHARED;
1273         }
1274
1275         return true;
1276 }
1277
1278 void SV_PrepareEntitiesForSending(void)
1279 {
1280         int e;
1281         prvm_edict_t *ent;
1282         // send all entities that touch the pvs
1283         sv.numsendentities = 0;
1284         sv.sendentitiesindex[0] = NULL;
1285         memset(sv.sendentitiesindex, 0, prog->num_edicts * sizeof(*sv.sendentitiesindex));
1286         for (e = 1, ent = PRVM_NEXT_EDICT(prog->edicts);e < prog->num_edicts;e++, ent = PRVM_NEXT_EDICT(ent))
1287         {
1288                 if (!ent->priv.server->free && SV_PrepareEntityForSending(ent, sv.sendentities + sv.numsendentities, e))
1289                 {
1290                         sv.sendentitiesindex[e] = sv.sendentities + sv.numsendentities;
1291                         sv.numsendentities++;
1292                 }
1293         }
1294 }
1295
1296 void SV_MarkWriteEntityStateToClient(entity_state_t *s)
1297 {
1298         int isbmodel;
1299         dp_model_t *model;
1300         prvm_edict_t *ed;
1301         if (sv.sententitiesconsideration[s->number] == sv.sententitiesmark)
1302                 return;
1303         sv.sententitiesconsideration[s->number] = sv.sententitiesmark;
1304         sv.writeentitiestoclient_stats_totalentities++;
1305
1306         if (s->customizeentityforclient)
1307         {
1308                 prog->globals.server->self = s->number;
1309                 prog->globals.server->other = sv.writeentitiestoclient_cliententitynumber;
1310                 PRVM_ExecuteProgram(s->customizeentityforclient, "customizeentityforclient: NULL function");
1311                 if(!PRVM_G_FLOAT(OFS_RETURN) || !SV_PrepareEntityForSending(PRVM_EDICT_NUM(s->number), s, s->number))
1312                         return;
1313         }
1314
1315         // never reject player
1316         if (s->number != sv.writeentitiestoclient_cliententitynumber)
1317         {
1318                 // check various rejection conditions
1319                 if (s->nodrawtoclient == sv.writeentitiestoclient_cliententitynumber)
1320                         return;
1321                 if (s->drawonlytoclient && s->drawonlytoclient != sv.writeentitiestoclient_cliententitynumber)
1322                         return;
1323                 if (s->effects & EF_NODRAW)
1324                         return;
1325                 // LordHavoc: only send entities with a model or important effects
1326                 if (!s->modelindex && s->specialvisibilityradius == 0)
1327                         return;
1328
1329                 isbmodel = (model = sv.models[s->modelindex]) != NULL && model->name[0] == '*';
1330                 // viewmodels don't have visibility checking
1331                 if (s->viewmodelforclient)
1332                 {
1333                         if (s->viewmodelforclient != sv.writeentitiestoclient_cliententitynumber)
1334                                 return;
1335                 }
1336                 else if (s->tagentity)
1337                 {
1338                         // tag attached entities simply check their parent
1339                         if (!sv.sendentitiesindex[s->tagentity])
1340                                 return;
1341                         SV_MarkWriteEntityStateToClient(sv.sendentitiesindex[s->tagentity]);
1342                         if (sv.sententities[s->tagentity] != sv.sententitiesmark)
1343                                 return;
1344                 }
1345                 // always send world submodels in newer protocols because they don't
1346                 // generate much traffic (in old protocols they hog bandwidth)
1347                 // but only if sv_cullentities_nevercullbmodels is off
1348                 else if (!(s->effects & EF_NODEPTHTEST) && (!isbmodel || !sv_cullentities_nevercullbmodels.integer || sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE))
1349                 {
1350                         // entity has survived every check so far, check if visible
1351                         ed = PRVM_EDICT_NUM(s->number);
1352
1353                         // if not touching a visible leaf
1354                         if (sv_cullentities_pvs.integer && !r_novis.integer && sv.writeentitiestoclient_pvsbytes)
1355                         {
1356                                 if (ed->priv.server->pvs_numclusters < 0)
1357                                 {
1358                                         // entity too big for clusters list
1359                                         if (sv.worldmodel && sv.worldmodel->brush.BoxTouchingPVS && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, sv.writeentitiestoclient_pvs, ed->priv.server->cullmins, ed->priv.server->cullmaxs))
1360                                         {
1361                                                 sv.writeentitiestoclient_stats_culled_pvs++;
1362                                                 return;
1363                                         }
1364                                 }
1365                                 else
1366                                 {
1367                                         int i;
1368                                         // check cached clusters list
1369                                         for (i = 0;i < ed->priv.server->pvs_numclusters;i++)
1370                                                 if (CHECKPVSBIT(sv.writeentitiestoclient_pvs, ed->priv.server->pvs_clusterlist[i]))
1371                                                         break;
1372                                         if (i == ed->priv.server->pvs_numclusters)
1373                                         {
1374                                                 sv.writeentitiestoclient_stats_culled_pvs++;
1375                                                 return;
1376                                         }
1377                                 }
1378                         }
1379
1380                         // or not seen by random tracelines
1381                         if (sv_cullentities_trace.integer && !isbmodel && sv.worldmodel->brush.TraceLineOfSight)
1382                         {
1383                                 int samples =
1384                                         s->number <= svs.maxclients
1385                                                 ? sv_cullentities_trace_samples_players.integer
1386                                                 :
1387                                         s->specialvisibilityradius
1388                                                 ? sv_cullentities_trace_samples_extra.integer
1389                                                 : sv_cullentities_trace_samples.integer;
1390                                 float enlarge = sv_cullentities_trace_enlarge.value;
1391
1392                                 qboolean visible = TRUE;
1393
1394                                 if(samples > 0)
1395                                 {
1396                                         do
1397                                         {
1398                                                 if(Mod_CanSeeBox_Trace(samples, enlarge, sv.worldmodel, sv.writeentitiestoclient_testeye, ed->priv.server->cullmins, ed->priv.server->cullmaxs))
1399                                                         break; // directly visible from the server's view
1400
1401                                                 if(sv_cullentities_trace_prediction.integer)
1402                                                 {
1403                                                         vec3_t predeye;
1404
1405                                                         // get player velocity
1406                                                         float predtime = bound(0, host_client->ping, 0.2); // / 2
1407                                                                 // sorry, no wallhacking by high ping please, and at 200ms
1408                                                                 // ping a FPS is annoying to play anyway and a player is
1409                                                                 // likely to have changed his direction
1410                                                         VectorMA(sv.writeentitiestoclient_testeye, predtime, host_client->edict->fields.server->velocity, predeye);
1411                                                         if(sv.worldmodel->brush.TraceLineOfSight(sv.worldmodel, sv.writeentitiestoclient_testeye, predeye)) // must be able to go there...
1412                                                         {
1413                                                                 if(Mod_CanSeeBox_Trace(samples, enlarge, sv.worldmodel, predeye, ed->priv.server->cullmins, ed->priv.server->cullmaxs))
1414                                                                         break; // directly visible from the predicted view
1415                                                         }
1416                                                         else
1417                                                         {
1418                                                                 //Con_DPrintf("Trying to walk into solid in a pingtime... not predicting for culling\n");
1419                                                         }
1420                                                 }
1421
1422                                                 // when we get here, we can't see the entity
1423                                                 visible = false;
1424                                         }
1425                                         while(0);
1426
1427                                         if(visible)
1428                                                 svs.clients[sv.writeentitiestoclient_clientnumber].visibletime[s->number] =
1429                                                         realtime + (
1430                                                                 s->number <= svs.maxclients
1431                                                                         ? sv_cullentities_trace_delay_players.value
1432                                                                         : sv_cullentities_trace_delay.value
1433                                                         );
1434                                         else if (realtime > svs.clients[sv.writeentitiestoclient_clientnumber].visibletime[s->number])
1435                                         {
1436                                                 sv.writeentitiestoclient_stats_culled_trace++;
1437                                                 return;
1438                                         }
1439                                 }
1440                         }
1441                 }
1442         }
1443
1444         // this just marks it for sending
1445         // FIXME: it would be more efficient to send here, but the entity
1446         // compressor isn't that flexible
1447         sv.writeentitiestoclient_stats_visibleentities++;
1448         sv.sententities[s->number] = sv.sententitiesmark;
1449 }
1450
1451 void SV_WriteEntitiesToClient(client_t *client, prvm_edict_t *clent, sizebuf_t *msg, int maxsize)
1452 {
1453         qboolean need_empty = false;
1454         int i, numsendstates, numcsqcsendstates;
1455         entity_state_t *s;
1456         prvm_edict_t *camera;
1457         qboolean success;
1458
1459         // if there isn't enough space to accomplish anything, skip it
1460         if (msg->cursize + 25 > maxsize)
1461                 return;
1462
1463         sv.writeentitiestoclient_msg = msg;
1464         sv.writeentitiestoclient_clientnumber = client - svs.clients;
1465
1466         sv.writeentitiestoclient_stats_culled_pvs = 0;
1467         sv.writeentitiestoclient_stats_culled_trace = 0;
1468         sv.writeentitiestoclient_stats_visibleentities = 0;
1469         sv.writeentitiestoclient_stats_totalentities = 0;
1470
1471 // find the client's PVS
1472         // the real place being tested from
1473         camera = PRVM_EDICT_NUM( client->clientcamera );
1474         VectorAdd(camera->fields.server->origin, clent->fields.server->view_ofs, sv.writeentitiestoclient_testeye);
1475         sv.writeentitiestoclient_pvsbytes = 0;
1476         if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
1477                 sv.writeentitiestoclient_pvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, sv.writeentitiestoclient_testeye, 8, sv.writeentitiestoclient_pvs, sizeof(sv.writeentitiestoclient_pvs), false);
1478
1479         sv.writeentitiestoclient_cliententitynumber = PRVM_EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
1480
1481         sv.sententitiesmark++;
1482
1483         for (i = 0;i < sv.numsendentities;i++)
1484                 SV_MarkWriteEntityStateToClient(sv.sendentities + i);
1485
1486         numsendstates = 0;
1487         numcsqcsendstates = 0;
1488         for (i = 0;i < sv.numsendentities;i++)
1489         {
1490                 if (sv.sententities[sv.sendentities[i].number] == sv.sententitiesmark)
1491                 {
1492                         if(sv.sendentities[i].active == ACTIVE_NETWORK)
1493                         {
1494                                 s = &sv.writeentitiestoclient_sendstates[numsendstates++];
1495                                 *s = sv.sendentities[i];
1496                                 if (s->exteriormodelforclient && s->exteriormodelforclient == sv.writeentitiestoclient_cliententitynumber)
1497                                         s->flags |= RENDER_EXTERIORMODEL;
1498                         }
1499                         else if(sv.sendentities[i].active == ACTIVE_SHARED)
1500                                 sv.writeentitiestoclient_csqcsendstates[numcsqcsendstates++] = sv.sendentities[i].number;
1501                         else
1502                                 Con_Printf("entity %d is in sv.sendentities and marked, but not active, please breakpoint me\n", sv.sendentities[i].number);
1503                 }
1504         }
1505
1506         if (sv_cullentities_stats.integer)
1507                 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d trace\n", client->name, sv.writeentitiestoclient_stats_totalentities, sv.writeentitiestoclient_stats_visibleentities, sv.writeentitiestoclient_stats_culled_pvs + sv.writeentitiestoclient_stats_culled_trace, sv.writeentitiestoclient_stats_culled_pvs, sv.writeentitiestoclient_stats_culled_trace);
1508
1509         if(client->entitydatabase5)
1510                 need_empty = EntityFrameCSQC_WriteFrame(msg, maxsize, numcsqcsendstates, sv.writeentitiestoclient_csqcsendstates, client->entitydatabase5->latestframenum + 1);
1511         else
1512                 EntityFrameCSQC_WriteFrame(msg, maxsize, numcsqcsendstates, sv.writeentitiestoclient_csqcsendstates, 0);
1513
1514         if(client->num_skippedentityframes >= 10)
1515                 need_empty = true; // force every 10th frame to be not empty (or cl_movement replay takes too long)
1516
1517         if (client->entitydatabase5)
1518                 success = EntityFrame5_WriteFrame(msg, maxsize, client->entitydatabase5, numsendstates, sv.writeentitiestoclient_sendstates, client - svs.clients + 1, client->movesequence, need_empty);
1519         else if (client->entitydatabase4)
1520         {
1521                 success = EntityFrame4_WriteFrame(msg, maxsize, client->entitydatabase4, numsendstates, sv.writeentitiestoclient_sendstates);
1522                 Protocol_WriteStatsReliable();
1523         }
1524         else if (client->entitydatabase)
1525         {
1526                 success = EntityFrame_WriteFrame(msg, maxsize, client->entitydatabase, numsendstates, sv.writeentitiestoclient_sendstates, client - svs.clients + 1);
1527                 Protocol_WriteStatsReliable();
1528         }
1529         else
1530         {
1531                 success = EntityFrameQuake_WriteFrame(msg, maxsize, numsendstates, sv.writeentitiestoclient_sendstates);
1532                 Protocol_WriteStatsReliable();
1533         }
1534
1535         if(success)
1536                 client->num_skippedentityframes = 0;
1537         else
1538                 ++client->num_skippedentityframes;
1539 }
1540
1541 /*
1542 =============
1543 SV_CleanupEnts
1544
1545 =============
1546 */
1547 static void SV_CleanupEnts (void)
1548 {
1549         int             e;
1550         prvm_edict_t    *ent;
1551
1552         ent = PRVM_NEXT_EDICT(prog->edicts);
1553         for (e=1 ; e<prog->num_edicts ; e++, ent = PRVM_NEXT_EDICT(ent))
1554                 ent->fields.server->effects = (int)ent->fields.server->effects & ~EF_MUZZLEFLASH;
1555 }
1556
1557 /*
1558 ==================
1559 SV_WriteClientdataToMessage
1560
1561 ==================
1562 */
1563 void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t *msg, int *stats)
1564 {
1565         int             bits;
1566         int             i;
1567         prvm_edict_t    *other;
1568         int             items;
1569         prvm_eval_t     *val;
1570         vec3_t  punchvector;
1571         int             viewzoom;
1572         const char *s;
1573         float   *statsf = (float *)stats;
1574
1575 //
1576 // send a damage message
1577 //
1578         if (ent->fields.server->dmg_take || ent->fields.server->dmg_save)
1579         {
1580                 other = PRVM_PROG_TO_EDICT(ent->fields.server->dmg_inflictor);
1581                 MSG_WriteByte (msg, svc_damage);
1582                 MSG_WriteByte (msg, (int)ent->fields.server->dmg_save);
1583                 MSG_WriteByte (msg, (int)ent->fields.server->dmg_take);
1584                 for (i=0 ; i<3 ; i++)
1585                         MSG_WriteCoord (msg, other->fields.server->origin[i] + 0.5*(other->fields.server->mins[i] + other->fields.server->maxs[i]), sv.protocol);
1586
1587                 ent->fields.server->dmg_take = 0;
1588                 ent->fields.server->dmg_save = 0;
1589         }
1590
1591 //
1592 // send the current viewpos offset from the view entity
1593 //
1594         SV_SetIdealPitch ();            // how much to look up / down ideally
1595
1596 // a fixangle might get lost in a dropped packet.  Oh well.
1597         if(ent->fields.server->fixangle)
1598         {
1599                 // angle fixing was requested by global thinking code...
1600                 // so store the current angles for later use
1601                 memcpy(host_client->fixangle_angles, ent->fields.server->angles, sizeof(host_client->fixangle_angles));
1602                 host_client->fixangle_angles_set = TRUE;
1603
1604                 // and clear fixangle for the next frame
1605                 ent->fields.server->fixangle = 0;
1606         }
1607
1608         if (host_client->fixangle_angles_set)
1609         {
1610                 MSG_WriteByte (msg, svc_setangle);
1611                 for (i=0 ; i < 3 ; i++)
1612                         MSG_WriteAngle (msg, host_client->fixangle_angles[i], sv.protocol);
1613                 host_client->fixangle_angles_set = FALSE;
1614         }
1615
1616         // stuff the sigil bits into the high bits of items for sbar, or else
1617         // mix in items2
1618         val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.items2);
1619         if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE)
1620                 items = (int)ent->fields.server->items | ((int)val->_float << 23);
1621         else
1622                 items = (int)ent->fields.server->items | ((int)prog->globals.server->serverflags << 28);
1623
1624         VectorClear(punchvector);
1625         if ((val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.punchvector)))
1626                 VectorCopy(val->vector, punchvector);
1627
1628         // cache weapon model name and index in client struct to save time
1629         // (this search can be almost 1% of cpu time!)
1630         s = PRVM_GetString(ent->fields.server->weaponmodel);
1631         if (strcmp(s, client->weaponmodel))
1632         {
1633                 strlcpy(client->weaponmodel, s, sizeof(client->weaponmodel));
1634                 client->weaponmodelindex = SV_ModelIndex(s, 1);
1635         }
1636
1637         viewzoom = 255;
1638         if ((val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.viewzoom)))
1639                 viewzoom = (int)(val->_float * 255.0f);
1640         if (viewzoom == 0)
1641                 viewzoom = 255;
1642
1643         bits = 0;
1644
1645         if ((int)ent->fields.server->flags & FL_ONGROUND)
1646                 bits |= SU_ONGROUND;
1647         if (ent->fields.server->waterlevel >= 2)
1648                 bits |= SU_INWATER;
1649         if (ent->fields.server->idealpitch)
1650                 bits |= SU_IDEALPITCH;
1651
1652         for (i=0 ; i<3 ; i++)
1653         {
1654                 if (ent->fields.server->punchangle[i])
1655                         bits |= (SU_PUNCH1<<i);
1656                 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)
1657                         if (punchvector[i])
1658                                 bits |= (SU_PUNCHVEC1<<i);
1659                 if (ent->fields.server->velocity[i])
1660                         bits |= (SU_VELOCITY1<<i);
1661         }
1662
1663         memset(stats, 0, sizeof(int[MAX_CL_STATS]));
1664         stats[STAT_VIEWHEIGHT] = (int)ent->fields.server->view_ofs[2];
1665         stats[STAT_ITEMS] = items;
1666         stats[STAT_WEAPONFRAME] = (int)ent->fields.server->weaponframe;
1667         stats[STAT_ARMOR] = (int)ent->fields.server->armorvalue;
1668         stats[STAT_WEAPON] = client->weaponmodelindex;
1669         stats[STAT_HEALTH] = (int)ent->fields.server->health;
1670         stats[STAT_AMMO] = (int)ent->fields.server->currentammo;
1671         stats[STAT_SHELLS] = (int)ent->fields.server->ammo_shells;
1672         stats[STAT_NAILS] = (int)ent->fields.server->ammo_nails;
1673         stats[STAT_ROCKETS] = (int)ent->fields.server->ammo_rockets;
1674         stats[STAT_CELLS] = (int)ent->fields.server->ammo_cells;
1675         stats[STAT_ACTIVEWEAPON] = (int)ent->fields.server->weapon;
1676         stats[STAT_VIEWZOOM] = viewzoom;
1677         stats[STAT_TOTALSECRETS] = (int)prog->globals.server->total_secrets;
1678         stats[STAT_TOTALMONSTERS] = (int)prog->globals.server->total_monsters;
1679         // the QC bumps these itself by sending svc_'s, so we have to keep them
1680         // zero or they'll be corrected by the engine
1681         //stats[STAT_SECRETS] = prog->globals.server->found_secrets;
1682         //stats[STAT_MONSTERS] = prog->globals.server->killed_monsters;
1683
1684         // movement settings for prediction
1685         // note: these are not sent in protocols with lower MAX_CL_STATS limits
1686         stats[STAT_MOVEFLAGS] = MOVEFLAG_VALID
1687                 | (sv_gameplayfix_q2airaccelerate.integer ? MOVEFLAG_Q2AIRACCELERATE : 0)
1688         ;
1689         statsf[STAT_MOVEVARS_TICRATE] = sys_ticrate.value;
1690         statsf[STAT_MOVEVARS_TIMESCALE] = slowmo.value;
1691         statsf[STAT_MOVEVARS_GRAVITY] = sv_gravity.value;
1692         statsf[STAT_MOVEVARS_STOPSPEED] = sv_stopspeed.value;
1693         statsf[STAT_MOVEVARS_MAXSPEED] = sv_maxspeed.value;
1694         statsf[STAT_MOVEVARS_SPECTATORMAXSPEED] = sv_maxspeed.value; // FIXME: QW has a separate cvar for this
1695         statsf[STAT_MOVEVARS_ACCELERATE] = sv_accelerate.value;
1696         statsf[STAT_MOVEVARS_AIRACCELERATE] = sv_airaccelerate.value >= 0 ? sv_airaccelerate.value : sv_accelerate.value;
1697         statsf[STAT_MOVEVARS_WATERACCELERATE] = sv_wateraccelerate.value >= 0 ? sv_wateraccelerate.value : sv_accelerate.value;
1698         val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.gravity);
1699         statsf[STAT_MOVEVARS_ENTGRAVITY] = (val && val->_float != 0) ? val->_float : 1.0f;
1700         statsf[STAT_MOVEVARS_JUMPVELOCITY] = sv_jumpvelocity.value;
1701         statsf[STAT_MOVEVARS_EDGEFRICTION] = sv_edgefriction.value;
1702         statsf[STAT_MOVEVARS_MAXAIRSPEED] = sv_maxairspeed.value;
1703         statsf[STAT_MOVEVARS_STEPHEIGHT] = sv_stepheight.value;
1704         statsf[STAT_MOVEVARS_AIRACCEL_QW] = sv_airaccel_qw.value;
1705         statsf[STAT_MOVEVARS_AIRACCEL_SIDEWAYS_FRICTION] = sv_airaccel_sideways_friction.value;
1706         statsf[STAT_MOVEVARS_FRICTION] = sv_friction.value;
1707         statsf[STAT_MOVEVARS_WATERFRICTION] = sv_waterfriction.value >= 0 ? sv_waterfriction.value : sv_friction.value;
1708         statsf[STAT_MOVEVARS_AIRSTOPACCELERATE] = sv_airstopaccelerate.value;
1709         statsf[STAT_MOVEVARS_AIRSTRAFEACCELERATE] = sv_airstrafeaccelerate.value;
1710         statsf[STAT_MOVEVARS_MAXAIRSTRAFESPEED] = sv_maxairstrafespeed.value;
1711         statsf[STAT_MOVEVARS_AIRCONTROL] = sv_aircontrol.value;
1712         statsf[STAT_MOVEVARS_WARSOWBUNNY_AIRFORWARDACCEL] = sv_warsowbunny_airforwardaccel.value;
1713         statsf[STAT_MOVEVARS_WARSOWBUNNY_ACCEL] = sv_warsowbunny_accel.value;
1714         statsf[STAT_MOVEVARS_WARSOWBUNNY_TOPSPEED] = sv_warsowbunny_topspeed.value;
1715         statsf[STAT_MOVEVARS_WARSOWBUNNY_TURNACCEL] = sv_warsowbunny_turnaccel.value;
1716         statsf[STAT_MOVEVARS_WARSOWBUNNY_BACKTOSIDERATIO] = sv_warsowbunny_backtosideratio.value;
1717         statsf[STAT_FRAGLIMIT] = fraglimit.value;
1718         statsf[STAT_TIMELIMIT] = timelimit.value;
1719
1720         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 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
1721         {
1722                 if (stats[STAT_VIEWHEIGHT] != DEFAULT_VIEWHEIGHT) bits |= SU_VIEWHEIGHT;
1723                 bits |= SU_ITEMS;
1724                 if (stats[STAT_WEAPONFRAME]) bits |= SU_WEAPONFRAME;
1725                 if (stats[STAT_ARMOR]) bits |= SU_ARMOR;
1726                 bits |= SU_WEAPON;
1727                 // FIXME: which protocols support this?  does PROTOCOL_DARKPLACES3 support viewzoom?
1728                 if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
1729                         if (viewzoom != 255)
1730                                 bits |= SU_VIEWZOOM;
1731         }
1732
1733         if (bits >= 65536)
1734                 bits |= SU_EXTEND1;
1735         if (bits >= 16777216)
1736                 bits |= SU_EXTEND2;
1737
1738         // send the data
1739         MSG_WriteByte (msg, svc_clientdata);
1740         MSG_WriteShort (msg, bits);
1741         if (bits & SU_EXTEND1)
1742                 MSG_WriteByte(msg, bits >> 16);
1743         if (bits & SU_EXTEND2)
1744                 MSG_WriteByte(msg, bits >> 24);
1745
1746         if (bits & SU_VIEWHEIGHT)
1747                 MSG_WriteChar (msg, stats[STAT_VIEWHEIGHT]);
1748
1749         if (bits & SU_IDEALPITCH)
1750                 MSG_WriteChar (msg, (int)ent->fields.server->idealpitch);
1751
1752         for (i=0 ; i<3 ; i++)
1753         {
1754                 if (bits & (SU_PUNCH1<<i))
1755                 {
1756                         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)
1757                                 MSG_WriteChar(msg, (int)ent->fields.server->punchangle[i]);
1758                         else
1759                                 MSG_WriteAngle16i(msg, ent->fields.server->punchangle[i]);
1760                 }
1761                 if (bits & (SU_PUNCHVEC1<<i))
1762                 {
1763                         if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1764                                 MSG_WriteCoord16i(msg, punchvector[i]);
1765                         else
1766                                 MSG_WriteCoord32f(msg, punchvector[i]);
1767                 }
1768                 if (bits & (SU_VELOCITY1<<i))
1769                 {
1770                         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 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1771                                 MSG_WriteChar(msg, (int)(ent->fields.server->velocity[i] * (1.0f / 16.0f)));
1772                         else
1773                                 MSG_WriteCoord32f(msg, ent->fields.server->velocity[i]);
1774                 }
1775         }
1776
1777         if (bits & SU_ITEMS)
1778                 MSG_WriteLong (msg, stats[STAT_ITEMS]);
1779
1780         if (sv.protocol == PROTOCOL_DARKPLACES5)
1781         {
1782                 if (bits & SU_WEAPONFRAME)
1783                         MSG_WriteShort (msg, stats[STAT_WEAPONFRAME]);
1784                 if (bits & SU_ARMOR)
1785                         MSG_WriteShort (msg, stats[STAT_ARMOR]);
1786                 if (bits & SU_WEAPON)
1787                         MSG_WriteShort (msg, stats[STAT_WEAPON]);
1788                 MSG_WriteShort (msg, stats[STAT_HEALTH]);
1789                 MSG_WriteShort (msg, stats[STAT_AMMO]);
1790                 MSG_WriteShort (msg, stats[STAT_SHELLS]);
1791                 MSG_WriteShort (msg, stats[STAT_NAILS]);
1792                 MSG_WriteShort (msg, stats[STAT_ROCKETS]);
1793                 MSG_WriteShort (msg, stats[STAT_CELLS]);
1794                 MSG_WriteShort (msg, stats[STAT_ACTIVEWEAPON]);
1795                 if (bits & SU_VIEWZOOM)
1796                         MSG_WriteShort (msg, bound(0, stats[STAT_VIEWZOOM], 65535));
1797         }
1798         else 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 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1799         {
1800                 if (bits & SU_WEAPONFRAME)
1801                         MSG_WriteByte (msg, stats[STAT_WEAPONFRAME]);
1802                 if (bits & SU_ARMOR)
1803                         MSG_WriteByte (msg, stats[STAT_ARMOR]);
1804                 if (bits & SU_WEAPON)
1805                 {
1806                         if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
1807                                 MSG_WriteShort (msg, stats[STAT_WEAPON]);
1808                         else
1809                                 MSG_WriteByte (msg, stats[STAT_WEAPON]);
1810                 }
1811                 MSG_WriteShort (msg, stats[STAT_HEALTH]);
1812                 MSG_WriteByte (msg, stats[STAT_AMMO]);
1813                 MSG_WriteByte (msg, stats[STAT_SHELLS]);
1814                 MSG_WriteByte (msg, stats[STAT_NAILS]);
1815                 MSG_WriteByte (msg, stats[STAT_ROCKETS]);
1816                 MSG_WriteByte (msg, stats[STAT_CELLS]);
1817                 if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_NEXUIZ)
1818                 {
1819                         for (i = 0;i < 32;i++)
1820                                 if (stats[STAT_ACTIVEWEAPON] & (1<<i))
1821                                         break;
1822                         MSG_WriteByte (msg, i);
1823                 }
1824                 else
1825                         MSG_WriteByte (msg, stats[STAT_ACTIVEWEAPON]);
1826                 if (bits & SU_VIEWZOOM)
1827                 {
1828                         if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1829                                 MSG_WriteByte (msg, bound(0, stats[STAT_VIEWZOOM], 255));
1830                         else
1831                                 MSG_WriteShort (msg, bound(0, stats[STAT_VIEWZOOM], 65535));
1832                 }
1833         }
1834 }
1835
1836 void SV_FlushBroadcastMessages(void)
1837 {
1838         int i;
1839         client_t *client;
1840         if (sv.datagram.cursize <= 0)
1841                 return;
1842         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
1843         {
1844                 if (!client->spawned || !client->netconnection || client->unreliablemsg.cursize + sv.datagram.cursize > client->unreliablemsg.maxsize || client->unreliablemsg_splitpoints >= (int)(sizeof(client->unreliablemsg_splitpoint)/sizeof(client->unreliablemsg_splitpoint[0])))
1845                         continue;
1846                 SZ_Write(&client->unreliablemsg, sv.datagram.data, sv.datagram.cursize);
1847                 client->unreliablemsg_splitpoint[client->unreliablemsg_splitpoints++] = client->unreliablemsg.cursize;
1848         }
1849         SZ_Clear(&sv.datagram);
1850 }
1851
1852 static void SV_WriteUnreliableMessages(client_t *client, sizebuf_t *msg, int maxsize, int maxsize2)
1853 {
1854         // scan the splitpoints to find out how many we can fit in
1855         int numsegments, j, split;
1856         if (!client->unreliablemsg_splitpoints)
1857                 return;
1858         // always accept the first one if it's within 1024 bytes, this ensures
1859         // that very big datagrams which are over the rate limit still get
1860         // through, just to keep it working
1861         for (numsegments = 1;numsegments < client->unreliablemsg_splitpoints;numsegments++)
1862                 if (msg->cursize + client->unreliablemsg_splitpoint[numsegments] > maxsize)
1863                         break;
1864         // the first segment gets an exemption from the rate limiting, otherwise
1865         // it could get dropped consistently due to a low rate limit
1866         if (numsegments == 1)
1867                 maxsize = maxsize2;
1868         // some will fit, so add the ones that will fit
1869         split = client->unreliablemsg_splitpoint[numsegments-1];
1870         // note this discards ones that were accepted by the segments scan but
1871         // can not fit, such as a really huge first one that will never ever
1872         // fit in a packet...
1873         if (msg->cursize + split <= maxsize)
1874                 SZ_Write(msg, client->unreliablemsg.data, split);
1875         // remove the part we sent, keeping any remaining data
1876         client->unreliablemsg.cursize -= split;
1877         if (client->unreliablemsg.cursize > 0)
1878                 memmove(client->unreliablemsg.data, client->unreliablemsg.data + split, client->unreliablemsg.cursize);
1879         // adjust remaining splitpoints
1880         client->unreliablemsg_splitpoints -= numsegments;
1881         for (j = 0;j < client->unreliablemsg_splitpoints;j++)
1882                 client->unreliablemsg_splitpoint[j] = client->unreliablemsg_splitpoint[numsegments + j] - split;
1883 }
1884
1885 /*
1886 =======================
1887 SV_SendClientDatagram
1888 =======================
1889 */
1890 static void SV_SendClientDatagram (client_t *client)
1891 {
1892         int clientrate, maxrate, maxsize, maxsize2, downloadsize;
1893         sizebuf_t msg;
1894         int stats[MAX_CL_STATS];
1895         unsigned char sv_sendclientdatagram_buf[NET_MAXMESSAGE];
1896
1897         // obey rate limit by limiting packet frequency if the packet size
1898         // limiting fails
1899         // (usually this is caused by reliable messages)
1900         if (!NetConn_CanSend(client->netconnection))
1901                 return;
1902
1903         // PROTOCOL_DARKPLACES5 and later support packet size limiting of updates
1904         maxrate = max(NET_MINRATE, sv_maxrate.integer);
1905         if (sv_maxrate.integer != maxrate)
1906                 Cvar_SetValueQuick(&sv_maxrate, maxrate);
1907
1908         // clientrate determines the 'cleartime' of a packet
1909         // (how long to wait before sending another, based on this packet's size)
1910         clientrate = bound(NET_MINRATE, client->rate, maxrate);
1911
1912         switch (sv.protocol)
1913         {
1914         case PROTOCOL_QUAKE:
1915         case PROTOCOL_QUAKEDP:
1916         case PROTOCOL_NEHAHRAMOVIE:
1917         case PROTOCOL_NEHAHRABJP:
1918         case PROTOCOL_NEHAHRABJP2:
1919         case PROTOCOL_NEHAHRABJP3:
1920         case PROTOCOL_QUAKEWORLD:
1921                 // no packet size limit support on Quake protocols because it just
1922                 // causes missing entities/effects
1923                 // packets are simply sent less often to obey the rate limit
1924                 maxsize = 1024;
1925                 maxsize2 = 1024;
1926                 break;
1927         case PROTOCOL_DARKPLACES1:
1928         case PROTOCOL_DARKPLACES2:
1929         case PROTOCOL_DARKPLACES3:
1930         case PROTOCOL_DARKPLACES4:
1931                 // no packet size limit support on DP1-4 protocols because they kick
1932                 // the client off if they overflow, and miss effects
1933                 // packets are simply sent less often to obey the rate limit
1934                 maxsize = sizeof(sv_sendclientdatagram_buf);
1935                 maxsize2 = sizeof(sv_sendclientdatagram_buf);
1936                 break;
1937         default:
1938                 // DP5 and later protocols support packet size limiting which is a
1939                 // better method than limiting packet frequency as QW does
1940                 //
1941                 // at very low rates (or very small sys_ticrate) the packet size is
1942                 // not reduced below 128, but packets may be sent less often
1943                 maxsize = (int)(clientrate * sys_ticrate.value);
1944                 maxsize = bound(128, maxsize, 1400);
1945                 maxsize2 = 1400;
1946                 // csqc entities can easily exceed 128 bytes, so disable throttling in
1947                 // mods that use csqc (they are likely to use less bandwidth anyway)
1948                 if (sv.csqc_progsize > 0)
1949                         maxsize = maxsize2;
1950                 break;
1951         }
1952
1953         if (LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) == LHNETADDRESSTYPE_LOOP && !sv_ratelimitlocalplayer.integer)
1954         {
1955                 // for good singleplayer, send huge packets
1956                 maxsize = sizeof(sv_sendclientdatagram_buf);
1957                 maxsize2 = sizeof(sv_sendclientdatagram_buf);
1958                 // never limit frequency in singleplayer
1959                 clientrate = 1000000000;
1960         }
1961
1962         // while downloading, limit entity updates to half the packet
1963         // (any leftover space will be used for downloading)
1964         if (host_client->download_file)
1965                 maxsize /= 2;
1966
1967         msg.data = sv_sendclientdatagram_buf;
1968         msg.maxsize = sizeof(sv_sendclientdatagram_buf);
1969         msg.cursize = 0;
1970         msg.allowoverflow = false;
1971
1972         if (host_client->spawned)
1973         {
1974                 // the player is in the game
1975                 MSG_WriteByte (&msg, svc_time);
1976                 MSG_WriteFloat (&msg, sv.time);
1977
1978                 // add the client specific data to the datagram
1979                 SV_WriteClientdataToMessage (client, client->edict, &msg, stats);
1980                 // now update the stats[] array using any registered custom fields
1981                 VM_SV_UpdateCustomStats (client, client->edict, &msg, stats);
1982                 // set host_client->statsdeltabits
1983                 Protocol_UpdateClientStats (stats);
1984
1985                 // add as many queued unreliable messages (effects) as we can fit
1986                 // limit effects to half of the remaining space
1987                 if (client->unreliablemsg.cursize)
1988                         SV_WriteUnreliableMessages (client, &msg, maxsize/2, maxsize2);
1989
1990                 // now write as many entities as we can fit, and also sends stats
1991                 SV_WriteEntitiesToClient (client, client->edict, &msg, maxsize);
1992         }
1993         else if (realtime > client->keepalivetime)
1994         {
1995                 // the player isn't totally in the game yet
1996                 // send small keepalive messages if too much time has passed
1997                 // (may also be sending downloads)
1998                 client->keepalivetime = realtime + 5;
1999                 MSG_WriteChar (&msg, svc_nop);
2000         }
2001
2002         // if a download is active, see if there is room to fit some download data
2003         // in this packet
2004         downloadsize = min(maxsize*2,maxsize2) - msg.cursize - 7;
2005         if (host_client->download_file && host_client->download_started && downloadsize > 0)
2006         {
2007                 fs_offset_t downloadstart;
2008                 unsigned char data[1400];
2009                 downloadstart = FS_Tell(host_client->download_file);
2010                 downloadsize = min(downloadsize, (int)sizeof(data));
2011                 downloadsize = FS_Read(host_client->download_file, data, downloadsize);
2012                 // note this sends empty messages if at the end of the file, which is
2013                 // necessary to keep the packet loss logic working
2014                 // (the last blocks may be lost and need to be re-sent, and that will
2015                 //  only occur if the client acks the empty end messages, revealing
2016                 //  a gap in the download progress, causing the last blocks to be
2017                 //  sent again)
2018                 MSG_WriteChar (&msg, svc_downloaddata);
2019                 MSG_WriteLong (&msg, downloadstart);
2020                 MSG_WriteShort (&msg, downloadsize);
2021                 if (downloadsize > 0)
2022                         SZ_Write (&msg, data, downloadsize);
2023         }
2024
2025         // reliable only if none is in progress
2026         if(client->sendsignon != 2 && !client->netconnection->sendMessageLength)
2027                 SV_WriteDemoMessage(client, &(client->netconnection->message), false);
2028         // unreliable
2029         SV_WriteDemoMessage(client, &msg, false);
2030
2031 // send the datagram
2032         NetConn_SendUnreliableMessage (client->netconnection, &msg, sv.protocol, clientrate, client->sendsignon == 2);
2033         if (client->sendsignon == 1 && !client->netconnection->message.cursize)
2034                 client->sendsignon = 2; // prevent reliable until client sends prespawn (this is the keepalive phase)
2035 }
2036
2037 /*
2038 =======================
2039 SV_UpdateToReliableMessages
2040 =======================
2041 */
2042 static void SV_UpdateToReliableMessages (void)
2043 {
2044         int i, j;
2045         client_t *client;
2046         prvm_eval_t *val;
2047         const char *name;
2048         const char *model;
2049         const char *skin;
2050
2051 // check for changes to be sent over the reliable streams
2052         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2053         {
2054                 // update the host_client fields we care about according to the entity fields
2055                 host_client->edict = PRVM_EDICT_NUM(i+1);
2056
2057                 // DP_SV_CLIENTNAME
2058                 name = PRVM_GetString(host_client->edict->fields.server->netname);
2059                 if (name == NULL)
2060                         name = "";
2061                 // always point the string back at host_client->name to keep it safe
2062                 strlcpy (host_client->name, name, sizeof (host_client->name));
2063                 host_client->edict->fields.server->netname = PRVM_SetEngineString(host_client->name);
2064                 if (strcmp(host_client->old_name, host_client->name))
2065                 {
2066                         if (host_client->spawned)
2067                                 SV_BroadcastPrintf("%s ^7changed name to %s\n", host_client->old_name, host_client->name);
2068                         strlcpy(host_client->old_name, host_client->name, sizeof(host_client->old_name));
2069                         // send notification to all clients
2070                         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
2071                         MSG_WriteByte (&sv.reliable_datagram, i);
2072                         MSG_WriteString (&sv.reliable_datagram, host_client->name);
2073                         SV_WriteNetnameIntoDemo(host_client);
2074                 }
2075
2076                 // DP_SV_CLIENTCOLORS
2077                 // this is always found (since it's added by the progs loader)
2078                 if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.clientcolors)))
2079                         host_client->colors = (int)val->_float;
2080                 if (host_client->old_colors != host_client->colors)
2081                 {
2082                         host_client->old_colors = host_client->colors;
2083                         // send notification to all clients
2084                         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
2085                         MSG_WriteByte (&sv.reliable_datagram, i);
2086                         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
2087                 }
2088
2089                 // NEXUIZ_PLAYERMODEL
2090                 if( prog->fieldoffsets.playermodel >= 0 ) {
2091                         model = PRVM_GetString(PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.playermodel)->string);
2092                         if (model == NULL)
2093                                 model = "";
2094                         // always point the string back at host_client->name to keep it safe
2095                         strlcpy (host_client->playermodel, model, sizeof (host_client->playermodel));
2096                         PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.playermodel)->string = PRVM_SetEngineString(host_client->playermodel);
2097                 }
2098
2099                 // NEXUIZ_PLAYERSKIN
2100                 if( prog->fieldoffsets.playerskin >= 0 ) {
2101                         skin = PRVM_GetString(PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.playerskin)->string);
2102                         if (skin == NULL)
2103                                 skin = "";
2104                         // always point the string back at host_client->name to keep it safe
2105                         strlcpy (host_client->playerskin, skin, sizeof (host_client->playerskin));
2106                         PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.playerskin)->string = PRVM_SetEngineString(host_client->playerskin);
2107                 }
2108
2109                 // TODO: add an extension name for this [1/17/2008 Black]
2110                 if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.clientcamera)) && val->edict > 0 ) {
2111                         int oldclientcamera = host_client->clientcamera;
2112                         if( val->edict >= prog->max_edicts || PRVM_EDICT_NUM( val->edict )->priv.required->free ) {
2113                                 val->edict = host_client->clientcamera = PRVM_NUM_FOR_EDICT( host_client->edict );
2114                         } else {
2115                                 host_client->clientcamera = val->edict;
2116                         }
2117
2118                         if( oldclientcamera != host_client->clientcamera ) {
2119                                 MSG_WriteByte (&sv.reliable_datagram, svc_setview );
2120                                 MSG_WriteShort (&host_client->netconnection->message, host_client->clientcamera);
2121                         }
2122                 }
2123
2124                 // frags
2125                 host_client->frags = (int)host_client->edict->fields.server->frags;
2126                 if(gamemode == GAME_NEXUIZ)
2127                         if(!host_client->spawned && host_client->netconnection)
2128                                 host_client->frags = -666;
2129                 if (host_client->old_frags != host_client->frags)
2130                 {
2131                         host_client->old_frags = host_client->frags;
2132                         // send notification to all clients
2133                         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
2134                         MSG_WriteByte (&sv.reliable_datagram, i);
2135                         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
2136                 }
2137         }
2138
2139         for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
2140                 if (client->netconnection && (client->spawned || client->clientconnectcalled)) // also send MSG_ALL to people who are past ClientConnect, but not spawned yet
2141                         SZ_Write (&client->netconnection->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
2142
2143         SZ_Clear (&sv.reliable_datagram);
2144 }
2145
2146
2147 /*
2148 =======================
2149 SV_SendClientMessages
2150 =======================
2151 */
2152 void SV_SendClientMessages (void)
2153 {
2154         int i, prepared = false;
2155
2156         if (sv.protocol == PROTOCOL_QUAKEWORLD)
2157                 Sys_Error("SV_SendClientMessages: no quakeworld support\n");
2158
2159         SV_FlushBroadcastMessages();
2160
2161 // update frags, names, etc
2162         SV_UpdateToReliableMessages();
2163
2164 // build individual updates
2165         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2166         {
2167                 if (!host_client->active)
2168                         continue;
2169                 if (!host_client->netconnection)
2170                         continue;
2171
2172                 if (host_client->netconnection->message.overflowed)
2173                 {
2174                         SV_DropClient (true);   // if the message couldn't send, kick off
2175                         continue;
2176                 }
2177
2178                 if (!prepared)
2179                 {
2180                         prepared = true;
2181                         // only prepare entities once per frame
2182                         SV_PrepareEntitiesForSending();
2183                 }
2184                 SV_SendClientDatagram (host_client);
2185         }
2186
2187 // clear muzzle flashes
2188         SV_CleanupEnts();
2189 }
2190
2191 static void SV_StartDownload_f(void)
2192 {
2193         if (host_client->download_file)
2194                 host_client->download_started = true;
2195 }
2196
2197 /*
2198  * Compression extension negotiation:
2199  *
2200  * Server to client:
2201  *   cl_serverextension_download 2
2202  *
2203  * Client to server:
2204  *   download <filename> <list of zero or more suppported compressions in order of preference>
2205  * e.g.
2206  *   download maps/map1.bsp lzo deflate huffman
2207  *
2208  * Server to client:
2209  *   cl_downloadbegin <compressed size> <filename> <compression method actually used>
2210  * e.g.
2211  *   cl_downloadbegin 123456 maps/map1.bsp deflate
2212  *
2213  * The server may choose not to compress the file by sending no compression name, like:
2214  *   cl_downloadbegin 345678 maps/map1.bsp
2215  *
2216  * NOTE: the "download" command may only specify compression algorithms if
2217  *       cl_serverextension_download is 2!
2218  *       If cl_serverextension_download has a different value, the client must
2219  *       assume this extension is not supported!
2220  */
2221
2222 static void Download_CheckExtensions(void)
2223 {
2224         int i;
2225         int argc = Cmd_Argc();
2226
2227         // first reset them all
2228         host_client->download_deflate = false;
2229         
2230         for(i = 2; i < argc; ++i)
2231         {
2232                 if(!strcmp(Cmd_Argv(i), "deflate"))
2233                 {
2234                         host_client->download_deflate = true;
2235                         break;
2236                 }
2237         }
2238 }
2239
2240 static void SV_Download_f(void)
2241 {
2242         const char *whichpack, *whichpack2, *extension;
2243         qboolean is_csqc; // so we need to check only once
2244
2245         if (Cmd_Argc() < 2)
2246         {
2247                 SV_ClientPrintf("usage: download <filename> {<extensions>}*\n");
2248                 SV_ClientPrintf("       supported extensions: deflate\n");
2249                 return;
2250         }
2251
2252         if (FS_CheckNastyPath(Cmd_Argv(1), false))
2253         {
2254                 SV_ClientPrintf("Download rejected: nasty filename \"%s\"\n", Cmd_Argv(1));
2255                 return;
2256         }
2257
2258         if (host_client->download_file)
2259         {
2260                 // at this point we'll assume the previous download should be aborted
2261                 Con_DPrintf("Download of %s aborted by %s starting a new download\n", host_client->download_name, host_client->name);
2262                 Host_ClientCommands("\nstopdownload\n");
2263
2264                 // close the file and reset variables
2265                 FS_Close(host_client->download_file);
2266                 host_client->download_file = NULL;
2267                 host_client->download_name[0] = 0;
2268                 host_client->download_expectedposition = 0;
2269                 host_client->download_started = false;
2270         }
2271
2272         is_csqc = (sv.csqc_progname[0] && strcmp(Cmd_Argv(1), sv.csqc_progname) == 0);
2273         
2274         if (!sv_allowdownloads.integer && !is_csqc)
2275         {
2276                 SV_ClientPrintf("Downloads are disabled on this server\n");
2277                 Host_ClientCommands("\nstopdownload\n");
2278                 return;
2279         }
2280
2281         Download_CheckExtensions();
2282
2283         strlcpy(host_client->download_name, Cmd_Argv(1), sizeof(host_client->download_name));
2284         extension = FS_FileExtension(host_client->download_name);
2285
2286         // host_client is asking to download a specified file
2287         if (developer.integer >= 100)
2288                 Con_Printf("Download request for %s by %s\n", host_client->download_name, host_client->name);
2289
2290         if(is_csqc)
2291         {
2292                 char extensions[MAX_QPATH]; // make sure this can hold all extensions
2293                 extensions[0] = '\0';
2294                 
2295                 if(host_client->download_deflate)
2296                         strlcat(extensions, " deflate", sizeof(extensions));
2297                 
2298                 Con_DPrintf("Downloading %s to %s\n", host_client->download_name, host_client->name);
2299
2300                 if(host_client->download_deflate && svs.csqc_progdata_deflated)
2301                         host_client->download_file = FS_FileFromData(svs.csqc_progdata_deflated, svs.csqc_progsize_deflated, true);
2302                 else
2303                         host_client->download_file = FS_FileFromData(svs.csqc_progdata, sv.csqc_progsize, true);
2304                 
2305                 // no, no space is needed between %s and %s :P
2306                 Host_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
2307
2308                 host_client->download_expectedposition = 0;
2309                 host_client->download_started = false;
2310                 host_client->sendsignon = true; // make sure this message is sent
2311                 return;
2312         }
2313
2314         if (!FS_FileExists(host_client->download_name))
2315         {
2316                 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);
2317                 Host_ClientCommands("\nstopdownload\n");
2318                 return;
2319         }
2320
2321         // check if the user is trying to download part of registered Quake(r)
2322         whichpack = FS_WhichPack(host_client->download_name);
2323         whichpack2 = FS_WhichPack("gfx/pop.lmp");
2324         if ((whichpack && whichpack2 && !strcasecmp(whichpack, whichpack2)) || FS_IsRegisteredQuakePack(host_client->download_name))
2325         {
2326                 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);
2327                 Host_ClientCommands("\nstopdownload\n");
2328                 return;
2329         }
2330
2331         // check if the server has forbidden archive downloads entirely
2332         if (!sv_allowdownloads_inarchive.integer)
2333         {
2334                 whichpack = FS_WhichPack(host_client->download_name);
2335                 if (whichpack)
2336                 {
2337                         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);
2338                         Host_ClientCommands("\nstopdownload\n");
2339                         return;
2340                 }
2341         }
2342
2343         if (!sv_allowdownloads_config.integer)
2344         {
2345                 if (!strcasecmp(extension, "cfg"))
2346                 {
2347                         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);
2348                         Host_ClientCommands("\nstopdownload\n");
2349                         return;
2350                 }
2351         }
2352
2353         if (!sv_allowdownloads_dlcache.integer)
2354         {
2355                 if (!strncasecmp(host_client->download_name, "dlcache/", 8))
2356                 {
2357                         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);
2358                         Host_ClientCommands("\nstopdownload\n");
2359                         return;
2360                 }
2361         }
2362
2363         if (!sv_allowdownloads_archive.integer)
2364         {
2365                 if (!strcasecmp(extension, "pak") || !strcasecmp(extension, "pk3"))
2366                 {
2367                         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);
2368                         Host_ClientCommands("\nstopdownload\n");
2369                         return;
2370                 }
2371         }
2372
2373         host_client->download_file = FS_OpenVirtualFile(host_client->download_name, true);
2374         if (!host_client->download_file)
2375         {
2376                 SV_ClientPrintf("Download rejected: server could not open the file \"%s\"\n", host_client->download_name);
2377                 Host_ClientCommands("\nstopdownload\n");
2378                 return;
2379         }
2380
2381         if (FS_FileSize(host_client->download_file) > 1<<30)
2382         {
2383                 SV_ClientPrintf("Download rejected: file \"%s\" is very large\n", host_client->download_name);
2384                 Host_ClientCommands("\nstopdownload\n");
2385                 FS_Close(host_client->download_file);
2386                 host_client->download_file = NULL;
2387                 return;
2388         }
2389
2390         if (FS_FileSize(host_client->download_file) < 0)
2391         {
2392                 SV_ClientPrintf("Download rejected: file \"%s\" is not a regular file\n", host_client->download_name);
2393                 Host_ClientCommands("\nstopdownload\n");
2394                 FS_Close(host_client->download_file);
2395                 host_client->download_file = NULL;
2396                 return;
2397         }
2398
2399         Con_DPrintf("Downloading %s to %s\n", host_client->download_name, host_client->name);
2400
2401         /*
2402          * we can only do this if we would actually deflate on the fly
2403          * which we do not (yet)!
2404         {
2405                 char extensions[MAX_QPATH]; // make sure this can hold all extensions
2406                 extensions[0] = '\0';
2407                 
2408                 if(host_client->download_deflate)
2409                         strlcat(extensions, " deflate", sizeof(extensions));
2410
2411                 // no, no space is needed between %s and %s :P
2412                 Host_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
2413         }
2414         */
2415         Host_ClientCommands("\ncl_downloadbegin %i %s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name);
2416
2417         host_client->download_expectedposition = 0;
2418         host_client->download_started = false;
2419         host_client->sendsignon = true; // make sure this message is sent
2420
2421         // the rest of the download process is handled in SV_SendClientDatagram
2422         // and other code dealing with svc_downloaddata and clc_ackdownloaddata
2423         //
2424         // no svc_downloaddata messages will be sent until sv_startdownload is
2425         // sent by the client
2426 }
2427
2428 /*
2429 ==============================================================================
2430
2431 SERVER SPAWNING
2432
2433 ==============================================================================
2434 */
2435
2436 /*
2437 ================
2438 SV_ModelIndex
2439
2440 ================
2441 */
2442 int SV_ModelIndex(const char *s, int precachemode)
2443 {
2444         int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3) ? 256 : MAX_MODELS);
2445         char filename[MAX_QPATH];
2446         if (!s || !*s)
2447                 return 0;
2448         // testing
2449         //if (precachemode == 2)
2450         //      return 0;
2451         strlcpy(filename, s, sizeof(filename));
2452         for (i = 2;i < limit;i++)
2453         {
2454                 if (!sv.model_precache[i][0])
2455                 {
2456                         if (precachemode)
2457                         {
2458                                 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))
2459                                 {
2460                                         Con_Printf("SV_ModelIndex(\"%s\"): precache_model can only be done in spawn functions\n", filename);
2461                                         return 0;
2462                                 }
2463                                 if (precachemode == 1)
2464                                         Con_Printf("SV_ModelIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
2465                                 strlcpy(sv.model_precache[i], filename, sizeof(sv.model_precache[i]));
2466                                 sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.modelname : NULL);
2467                                 if (sv.state != ss_loading)
2468                                 {
2469                                         MSG_WriteByte(&sv.reliable_datagram, svc_precache);
2470                                         MSG_WriteShort(&sv.reliable_datagram, i);
2471                                         MSG_WriteString(&sv.reliable_datagram, filename);
2472                                 }
2473                                 return i;
2474                         }
2475                         Con_Printf("SV_ModelIndex(\"%s\"): not precached\n", filename);
2476                         return 0;
2477                 }
2478                 if (!strcmp(sv.model_precache[i], filename))
2479                         return i;
2480         }
2481         Con_Printf("SV_ModelIndex(\"%s\"): i (%i) == MAX_MODELS (%i)\n", filename, i, MAX_MODELS);
2482         return 0;
2483 }
2484
2485 /*
2486 ================
2487 SV_SoundIndex
2488
2489 ================
2490 */
2491 int SV_SoundIndex(const char *s, int precachemode)
2492 {
2493         int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3) ? 256 : MAX_SOUNDS);
2494         char filename[MAX_QPATH];
2495         if (!s || !*s)
2496                 return 0;
2497         // testing
2498         //if (precachemode == 2)
2499         //      return 0;
2500         strlcpy(filename, s, sizeof(filename));
2501         for (i = 1;i < limit;i++)
2502         {
2503                 if (!sv.sound_precache[i][0])
2504                 {
2505                         if (precachemode)
2506                         {
2507                                 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))
2508                                 {
2509                                         Con_Printf("SV_SoundIndex(\"%s\"): precache_sound can only be done in spawn functions\n", filename);
2510                                         return 0;
2511                                 }
2512                                 if (precachemode == 1)
2513                                         Con_Printf("SV_SoundIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
2514                                 strlcpy(sv.sound_precache[i], filename, sizeof(sv.sound_precache[i]));
2515                                 if (sv.state != ss_loading)
2516                                 {
2517                                         MSG_WriteByte(&sv.reliable_datagram, svc_precache);
2518                                         MSG_WriteShort(&sv.reliable_datagram, i + 32768);
2519                                         MSG_WriteString(&sv.reliable_datagram, filename);
2520                                 }
2521                                 return i;
2522                         }
2523                         Con_Printf("SV_SoundIndex(\"%s\"): not precached\n", filename);
2524                         return 0;
2525                 }
2526                 if (!strcmp(sv.sound_precache[i], filename))
2527                         return i;
2528         }
2529         Con_Printf("SV_SoundIndex(\"%s\"): i (%i) == MAX_SOUNDS (%i)\n", filename, i, MAX_SOUNDS);
2530         return 0;
2531 }
2532
2533 /*
2534 ================
2535 SV_ParticleEffectIndex
2536
2537 ================
2538 */
2539 int SV_ParticleEffectIndex(const char *name)
2540 {
2541         int i, argc, linenumber, effectnameindex;
2542         fs_offset_t filesize;
2543         unsigned char *filedata;
2544         const char *text, *textstart, *textend;
2545         char argv[16][1024];
2546         if (!sv.particleeffectnamesloaded)
2547         {
2548                 sv.particleeffectnamesloaded = true;
2549                 memset(sv.particleeffectname, 0, sizeof(sv.particleeffectname));
2550                 for (i = 0;i < EFFECT_TOTAL;i++)
2551                         strlcpy(sv.particleeffectname[i], standardeffectnames[i], sizeof(sv.particleeffectname[i]));
2552                 filedata = FS_LoadFile("effectinfo.txt", tempmempool, true, &filesize);
2553                 if (filedata)
2554                 {
2555                         textstart = (const char *)filedata;
2556                         textend = (const char *)filedata + filesize;
2557                         text = textstart;
2558                         for (linenumber = 1;;linenumber++)
2559                         {
2560                                 argc = 0;
2561                                 for (;;)
2562                                 {
2563                                         if (!COM_ParseToken_Simple(&text, true, false) || !strcmp(com_token, "\n"))
2564                                                 break;
2565                                         if (argc < 16)
2566                                         {
2567                                                 strlcpy(argv[argc], com_token, sizeof(argv[argc]));
2568                                                 argc++;
2569                                         }
2570                                 }
2571                                 if (com_token[0] == 0)
2572                                         break; // if the loop exited and it's not a \n, it's EOF
2573                                 if (argc < 1)
2574                                         continue;
2575                                 if (!strcmp(argv[0], "effect"))
2576                                 {
2577                                         if (argc == 2)
2578                                         {
2579                                                 for (effectnameindex = 1;effectnameindex < SV_MAX_PARTICLEEFFECTNAME;effectnameindex++)
2580                                                 {
2581                                                         if (sv.particleeffectname[effectnameindex][0])
2582                                                         {
2583                                                                 if (!strcmp(sv.particleeffectname[effectnameindex], argv[1]))
2584                                                                         break;
2585                                                         }
2586                                                         else
2587                                                         {
2588                                                                 strlcpy(sv.particleeffectname[effectnameindex], argv[1], sizeof(sv.particleeffectname[effectnameindex]));
2589                                                                 break;
2590                                                         }
2591                                                 }
2592                                                 // if we run out of names, abort
2593                                                 if (effectnameindex == SV_MAX_PARTICLEEFFECTNAME)
2594                                                 {
2595                                                         Con_Printf("effectinfo.txt:%i: too many effects!\n", linenumber);
2596                                                         break;
2597                                                 }
2598                                         }
2599                                 }
2600                         }
2601                         Mem_Free(filedata);
2602                 }
2603         }
2604         // search for the name
2605         for (effectnameindex = 1;effectnameindex < SV_MAX_PARTICLEEFFECTNAME && sv.particleeffectname[effectnameindex][0];effectnameindex++)
2606                 if (!strcmp(sv.particleeffectname[effectnameindex], name))
2607                         return effectnameindex;
2608         // return 0 if we couldn't find it
2609         return 0;
2610 }
2611
2612 /*
2613 ================
2614 SV_CreateBaseline
2615
2616 ================
2617 */
2618 static void SV_CreateBaseline (void)
2619 {
2620         int i, entnum, large;
2621         prvm_edict_t *svent;
2622
2623         // LordHavoc: clear *all* states (note just active ones)
2624         for (entnum = 0;entnum < prog->max_edicts;entnum++)
2625         {
2626                 // get the current server version
2627                 svent = PRVM_EDICT_NUM(entnum);
2628
2629                 // LordHavoc: always clear state values, whether the entity is in use or not
2630                 svent->priv.server->baseline = defaultstate;
2631
2632                 if (svent->priv.server->free)
2633                         continue;
2634                 if (entnum > svs.maxclients && !svent->fields.server->modelindex)
2635                         continue;
2636
2637                 // create entity baseline
2638                 VectorCopy (svent->fields.server->origin, svent->priv.server->baseline.origin);
2639                 VectorCopy (svent->fields.server->angles, svent->priv.server->baseline.angles);
2640                 svent->priv.server->baseline.frame = (int)svent->fields.server->frame;
2641                 svent->priv.server->baseline.skin = (int)svent->fields.server->skin;
2642                 if (entnum > 0 && entnum <= svs.maxclients)
2643                 {
2644                         svent->priv.server->baseline.colormap = entnum;
2645                         svent->priv.server->baseline.modelindex = SV_ModelIndex("progs/player.mdl", 1);
2646                 }
2647                 else
2648                 {
2649                         svent->priv.server->baseline.colormap = 0;
2650                         svent->priv.server->baseline.modelindex = (int)svent->fields.server->modelindex;
2651                 }
2652
2653                 large = false;
2654                 if (svent->priv.server->baseline.modelindex & 0xFF00 || svent->priv.server->baseline.frame & 0xFF00)
2655                 {
2656                         large = true;
2657                         if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
2658                                 large = false;
2659                 }
2660
2661                 // add to the message
2662                 if (large)
2663                         MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
2664                 else
2665                         MSG_WriteByte (&sv.signon, svc_spawnbaseline);
2666                 MSG_WriteShort (&sv.signon, entnum);
2667
2668                 if (large)
2669                 {
2670                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.modelindex);
2671                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.frame);
2672                 }
2673                 else if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
2674                 {
2675                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.modelindex);
2676                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.frame);
2677                 }
2678                 else
2679                 {
2680                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.modelindex);
2681                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.frame);
2682                 }
2683                 MSG_WriteByte (&sv.signon, svent->priv.server->baseline.colormap);
2684                 MSG_WriteByte (&sv.signon, svent->priv.server->baseline.skin);
2685                 for (i=0 ; i<3 ; i++)
2686                 {
2687                         MSG_WriteCoord(&sv.signon, svent->priv.server->baseline.origin[i], sv.protocol);
2688                         MSG_WriteAngle(&sv.signon, svent->priv.server->baseline.angles[i], sv.protocol);
2689                 }
2690         }
2691 }
2692
2693 /*
2694 ================
2695 SV_Prepare_CSQC
2696
2697 Load csprogs.dat and comperss it so it doesn't need to be
2698 reloaded on request.
2699 ================
2700 */
2701 void SV_Prepare_CSQC(void)
2702 {
2703         fs_offset_t progsize;
2704
2705         if(svs.csqc_progdata)
2706         {
2707                 Con_DPrintf("Unloading old CSQC data.\n");
2708                 Mem_Free(svs.csqc_progdata);
2709                 if(svs.csqc_progdata_deflated)
2710                         Mem_Free(svs.csqc_progdata_deflated);
2711         }
2712
2713         svs.csqc_progdata = NULL;
2714         svs.csqc_progdata_deflated = NULL;
2715         
2716         Con_Print("Loading csprogs.dat\n");
2717
2718         sv.csqc_progname[0] = 0;
2719         svs.csqc_progdata = FS_LoadFile(csqc_progname.string, sv_mempool, false, &progsize);
2720
2721         if(progsize > 0)
2722         {
2723                 size_t deflated_size;
2724                 
2725                 sv.csqc_progsize = (int)progsize;
2726                 sv.csqc_progcrc = CRC_Block(svs.csqc_progdata, progsize);
2727                 strlcpy(sv.csqc_progname, csqc_progname.string, sizeof(sv.csqc_progname));
2728                 Con_Printf("server detected csqc progs file \"%s\" with size %i and crc %i\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
2729
2730                 Con_Print("Compressing csprogs.dat\n");
2731                 //unsigned char *FS_Deflate(const unsigned char *data, size_t size, size_t *deflated_size, int level, mempool_t *mempool);
2732                 svs.csqc_progdata_deflated = FS_Deflate(svs.csqc_progdata, progsize, &deflated_size, -1, sv_mempool);
2733                 svs.csqc_progsize_deflated = (int)deflated_size;
2734                 if(svs.csqc_progdata_deflated)
2735                 {
2736                         Con_Printf("Deflated: %g%%\n", 100.0 - 100.0 * (deflated_size / (float)progsize));
2737                         Con_DPrintf("Uncompressed: %u\nCompressed:   %u\n", (unsigned)sv.csqc_progsize, (unsigned)svs.csqc_progsize_deflated);
2738                 }
2739                 else
2740                         Con_Printf("Cannot compress - need zlib for this. Using uncompressed progs only.\n");
2741         }
2742 }
2743
2744 /*
2745 ================
2746 SV_SaveSpawnparms
2747
2748 Grabs the current state of each client for saving across the
2749 transition to another level
2750 ================
2751 */
2752 void SV_SaveSpawnparms (void)
2753 {
2754         int             i, j;
2755
2756         svs.serverflags = (int)prog->globals.server->serverflags;
2757
2758         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2759         {
2760                 if (!host_client->active)
2761                         continue;
2762
2763         // call the progs to get default spawn parms for the new client
2764                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
2765                 PRVM_ExecuteProgram (prog->globals.server->SetChangeParms, "QC function SetChangeParms is missing");
2766                 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
2767                         host_client->spawn_parms[j] = (&prog->globals.server->parm1)[j];
2768         }
2769 }
2770
2771 /*
2772 ================
2773 SV_SpawnServer
2774
2775 This is called at the start of each level
2776 ================
2777 */
2778
2779 void SV_SpawnServer (const char *server)
2780 {
2781         prvm_edict_t *ent;
2782         int i;
2783         char *entities;
2784         dp_model_t *worldmodel;
2785         char modelname[sizeof(sv.modelname)];
2786
2787         Con_DPrintf("SpawnServer: %s\n", server);
2788
2789         dpsnprintf (modelname, sizeof(modelname), "maps/%s.bsp", server);
2790
2791         if (!FS_FileExists(modelname))
2792         {
2793                 Con_Printf("SpawnServer: no map file named %s\n", modelname);
2794                 return;
2795         }
2796
2797         if (cls.state != ca_dedicated)
2798         {
2799                 SCR_BeginLoadingPlaque();
2800                 S_StopAllSounds();
2801         }
2802
2803         if(sv.active)
2804         {
2805                 SV_VM_Begin();
2806                 if(prog->funcoffsets.SV_Shutdown)
2807                 {
2808                         func_t s = prog->funcoffsets.SV_Shutdown;
2809                         prog->funcoffsets.SV_Shutdown = 0; // prevent it from getting called again
2810                         PRVM_ExecuteProgram(s,"SV_Shutdown() required");
2811                 }
2812                 SV_VM_End();
2813         }
2814
2815         // free q3 shaders so that any newly downloaded shaders will be active
2816         Mod_FreeQ3Shaders();
2817
2818         worldmodel = Mod_ForName(modelname, false, true, NULL);
2819         if (!worldmodel || !worldmodel->TraceBox)
2820         {
2821                 Con_Printf("Couldn't load map %s\n", modelname);
2822                 return;
2823         }
2824
2825         // let's not have any servers with no name
2826         if (hostname.string[0] == 0)
2827                 Cvar_Set ("hostname", "UNNAMED");
2828         scr_centertime_off = 0;
2829
2830         svs.changelevel_issued = false;         // now safe to issue another
2831
2832         // make the map a required file for clients
2833         Curl_ClearRequirements();
2834         Curl_RequireFile(modelname);
2835
2836 //
2837 // tell all connected clients that we are going to a new level
2838 //
2839         if (sv.active)
2840         {
2841                 client_t *client;
2842                 for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
2843                 {
2844                         if (client->netconnection)
2845                         {
2846                                 MSG_WriteByte(&client->netconnection->message, svc_stufftext);
2847                                 MSG_WriteString(&client->netconnection->message, "reconnect\n");
2848                         }
2849                 }
2850         }
2851         else
2852         {
2853                 // open server port
2854                 NetConn_OpenServerPorts(true);
2855         }
2856
2857 //
2858 // make cvars consistant
2859 //
2860         if (coop.integer)
2861                 Cvar_SetValue ("deathmatch", 0);
2862         // LordHavoc: it can be useful to have skills outside the range 0-3...
2863         //current_skill = bound(0, (int)(skill.value + 0.5), 3);
2864         //Cvar_SetValue ("skill", (float)current_skill);
2865         current_skill = (int)(skill.value + 0.5);
2866
2867 //
2868 // set up the new server
2869 //
2870         memset (&sv, 0, sizeof(sv));
2871         // if running a local client, make sure it doesn't try to access the last
2872         // level's data which is no longer valiud
2873         cls.signon = 0;
2874
2875         Cvar_SetValue("halflifebsp", worldmodel->brush.ishlbsp);
2876
2877         if(*sv_random_seed.string)
2878         {
2879                 srand(sv_random_seed.integer);
2880                 Con_Printf("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);
2881         }
2882
2883         SV_VM_Setup();
2884
2885         sv.active = true;
2886
2887         strlcpy (sv.name, server, sizeof (sv.name));
2888
2889         sv.protocol = Protocol_EnumForName(sv_protocolname.string);
2890         if (sv.protocol == PROTOCOL_UNKNOWN)
2891         {
2892                 char buffer[1024];
2893                 Protocol_Names(buffer, sizeof(buffer));
2894                 Con_Printf("Unknown sv_protocolname \"%s\", valid values are:\n%s\n", sv_protocolname.string, buffer);
2895                 sv.protocol = PROTOCOL_QUAKE;
2896         }
2897
2898         SV_VM_Begin();
2899
2900 // load progs to get entity field count
2901         //PR_LoadProgs ( sv_progs.string );
2902
2903         sv.datagram.maxsize = sizeof(sv.datagram_buf);
2904         sv.datagram.cursize = 0;
2905         sv.datagram.data = sv.datagram_buf;
2906
2907         sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
2908         sv.reliable_datagram.cursize = 0;
2909         sv.reliable_datagram.data = sv.reliable_datagram_buf;
2910
2911         sv.signon.maxsize = sizeof(sv.signon_buf);
2912         sv.signon.cursize = 0;
2913         sv.signon.data = sv.signon_buf;
2914
2915 // leave slots at start for clients only
2916         //prog->num_edicts = svs.maxclients+1;
2917
2918         sv.state = ss_loading;
2919         prog->allowworldwrites = true;
2920         sv.paused = false;
2921
2922         prog->globals.server->time = sv.time = 1.0;
2923
2924         Mod_ClearUsed();
2925         worldmodel->used = true;
2926
2927         strlcpy (sv.name, server, sizeof (sv.name));
2928         strlcpy(sv.modelname, modelname, sizeof(sv.modelname));
2929         sv.worldmodel = worldmodel;
2930         sv.models[1] = sv.worldmodel;
2931
2932 //
2933 // clear world interaction links
2934 //
2935         World_SetSize(&sv.world, sv.worldmodel->name, sv.worldmodel->normalmins, sv.worldmodel->normalmaxs);
2936
2937         strlcpy(sv.sound_precache[0], "", sizeof(sv.sound_precache[0]));
2938
2939         strlcpy(sv.model_precache[0], "", sizeof(sv.model_precache[0]));
2940         strlcpy(sv.model_precache[1], sv.modelname, sizeof(sv.model_precache[1]));
2941         for (i = 1;i < sv.worldmodel->brush.numsubmodels && i+1 < MAX_MODELS;i++)
2942         {
2943                 dpsnprintf(sv.model_precache[i+1], sizeof(sv.model_precache[i+1]), "*%i", i);
2944                 sv.models[i+1] = Mod_ForName (sv.model_precache[i+1], false, false, sv.modelname);
2945         }
2946         if(i < sv.worldmodel->brush.numsubmodels)
2947                 Con_Printf("Too many submodels (MAX_MODELS is %i)\n", MAX_MODELS);
2948
2949 //
2950 // load the rest of the entities
2951 //
2952         // AK possible hack since num_edicts is still 0
2953         ent = PRVM_EDICT_NUM(0);
2954         memset (ent->fields.server, 0, prog->progs->entityfields * 4);
2955         ent->priv.server->free = false;
2956         ent->fields.server->model = PRVM_SetEngineString(sv.modelname);
2957         ent->fields.server->modelindex = 1;             // world model
2958         ent->fields.server->solid = SOLID_BSP;
2959         ent->fields.server->movetype = MOVETYPE_PUSH;
2960         VectorCopy(sv.world.mins, ent->fields.server->mins);
2961         VectorCopy(sv.world.maxs, ent->fields.server->maxs);
2962         VectorCopy(sv.world.mins, ent->fields.server->absmin);
2963         VectorCopy(sv.world.maxs, ent->fields.server->absmax);
2964
2965         if (coop.value)
2966                 prog->globals.server->coop = coop.integer;
2967         else
2968                 prog->globals.server->deathmatch = deathmatch.integer;
2969
2970         prog->globals.server->mapname = PRVM_SetEngineString(sv.name);
2971
2972 // serverflags are for cross level information (sigils)
2973         prog->globals.server->serverflags = svs.serverflags;
2974
2975         // we need to reset the spawned flag on all connected clients here so that
2976         // their thinks don't run during startup (before PutClientInServer)
2977         // we also need to set up the client entities now
2978         // and we need to set the ->edict pointers to point into the progs edicts
2979         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2980         {
2981                 host_client->spawned = false;
2982                 host_client->edict = PRVM_EDICT_NUM(i + 1);
2983                 PRVM_ED_ClearEdict(host_client->edict);
2984         }
2985
2986         // load replacement entity file if found
2987         if (sv_entpatch.integer && (entities = (char *)FS_LoadFile(va("maps/%s.ent", sv.name), tempmempool, true, NULL)))
2988         {
2989                 Con_Printf("Loaded maps/%s.ent\n", sv.name);
2990                 PRVM_ED_LoadFromFile (entities);
2991                 Mem_Free(entities);
2992         }
2993         else
2994                 PRVM_ED_LoadFromFile (sv.worldmodel->brush.entities);
2995
2996
2997         // LordHavoc: clear world angles (to fix e3m3.bsp)
2998         VectorClear(prog->edicts->fields.server->angles);
2999
3000 // all setup is completed, any further precache statements are errors
3001 //      sv.state = ss_active; // LordHavoc: workaround for svc_precache bug
3002         prog->allowworldwrites = false;
3003
3004 // run two frames to allow everything to settle
3005         prog->globals.server->time = sv.time = 1.0001;
3006         for (i = 0;i < 2;i++)
3007         {
3008                 sv.frametime = 0.1;
3009                 SV_Physics ();
3010         }
3011
3012         if (cls.state == ca_dedicated)
3013                 Mod_PurgeUnused();
3014
3015 // create a baseline for more efficient communications
3016         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)
3017                 SV_CreateBaseline ();
3018
3019         sv.state = ss_active; // LordHavoc: workaround for svc_precache bug
3020
3021         // to prevent network timeouts
3022         realtime = Sys_DoubleTime();
3023         
3024 // send serverinfo to all connected clients, and set up botclients coming back from a level change
3025         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
3026         {
3027                 host_client->clientconnectcalled = false; // do NOT call ClientDisconnect if he drops before ClientConnect!
3028                 if (!host_client->active)
3029                         continue;
3030                 if (host_client->netconnection)
3031                         SV_SendServerinfo(host_client);
3032                 else
3033                 {
3034                         int j;
3035                         // if client is a botclient coming from a level change, we need to
3036                         // set up client info that normally requires networking
3037
3038                         // copy spawn parms out of the client_t
3039                         for (j=0 ; j< NUM_SPAWN_PARMS ; j++)
3040                                 (&prog->globals.server->parm1)[j] = host_client->spawn_parms[j];
3041
3042                         // call the spawn function
3043                         host_client->clientconnectcalled = true;
3044                         prog->globals.server->time = sv.time;
3045                         prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
3046                         PRVM_ExecuteProgram (prog->globals.server->ClientConnect, "QC function ClientConnect is missing");
3047                         PRVM_ExecuteProgram (prog->globals.server->PutClientInServer, "QC function PutClientInServer is missing");
3048                         host_client->spawned = true;
3049                 }
3050         }
3051
3052         Con_DPrint("Server spawned.\n");
3053         NetConn_Heartbeat (2);
3054
3055         SV_VM_End();
3056 }
3057
3058 /////////////////////////////////////////////////////
3059 // SV VM stuff
3060
3061 static void SV_VM_CB_BeginIncreaseEdicts(void)
3062 {
3063         // links don't survive the transition, so unlink everything
3064         World_UnlinkAll(&sv.world);
3065 }
3066
3067 static void SV_VM_CB_EndIncreaseEdicts(void)
3068 {
3069         int i;
3070         prvm_edict_t *ent;
3071
3072         // link every entity except world
3073         for (i = 1, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
3074                 if (!ent->priv.server->free)
3075                         SV_LinkEdict(ent, false);
3076 }
3077
3078 static void SV_VM_CB_InitEdict(prvm_edict_t *e)
3079 {
3080         // LordHavoc: for consistency set these here
3081         int num = PRVM_NUM_FOR_EDICT(e) - 1;
3082
3083         e->priv.server->move = false; // don't move on first frame
3084
3085         if (num >= 0 && num < svs.maxclients)
3086         {
3087                 prvm_eval_t *val;
3088                 // set colormap and team on newly created player entity
3089                 e->fields.server->colormap = num + 1;
3090                 e->fields.server->team = (svs.clients[num].colors & 15) + 1;
3091                 // set netname/clientcolors back to client values so that
3092                 // DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS will not immediately
3093                 // reset them
3094                 e->fields.server->netname = PRVM_SetEngineString(svs.clients[num].name);
3095                 if ((val = PRVM_EDICTFIELDVALUE(e, prog->fieldoffsets.clientcolors)))
3096                         val->_float = svs.clients[num].colors;
3097                 // NEXUIZ_PLAYERMODEL and NEXUIZ_PLAYERSKIN
3098                 if( prog->fieldoffsets.playermodel >= 0 )
3099                         PRVM_EDICTFIELDVALUE(e, prog->fieldoffsets.playermodel)->string = PRVM_SetEngineString(svs.clients[num].playermodel);
3100                 if( prog->fieldoffsets.playerskin >= 0 )
3101                         PRVM_EDICTFIELDVALUE(e, prog->fieldoffsets.playerskin)->string = PRVM_SetEngineString(svs.clients[num].playerskin);
3102                 // Assign netaddress (IP Address, etc)
3103                 if(prog->fieldoffsets.netaddress >= 0)
3104                 { // Valid Field; Process
3105                         if(svs.clients[num].netconnection != NULL)
3106                         {// Valid Address; Assign
3107                                 // Acquire Readable Address
3108                                 LHNETADDRESS_ToString(&svs.clients[num].netconnection->peeraddress, svs.clients[num].netaddress, sizeof(svs.clients[num].netaddress), false);
3109                                 PRVM_EDICTFIELDVALUE(e, prog->fieldoffsets.netaddress)->string = PRVM_SetEngineString(svs.clients[num].netaddress);
3110                         }
3111                         else
3112                                 // Invalid / Bot
3113                                 PRVM_EDICTFIELDVALUE(e, prog->fieldoffsets.netaddress)->string = PRVM_SetEngineString("null/botclient");
3114                 }
3115         }
3116 }
3117
3118 static void SV_VM_CB_FreeEdict(prvm_edict_t *ed)
3119 {
3120         int i;
3121         int e;
3122
3123         World_UnlinkEdict(ed);          // unlink from world bsp
3124
3125         ed->fields.server->model = 0;
3126         ed->fields.server->takedamage = 0;
3127         ed->fields.server->modelindex = 0;
3128         ed->fields.server->colormap = 0;
3129         ed->fields.server->skin = 0;
3130         ed->fields.server->frame = 0;
3131         VectorClear(ed->fields.server->origin);
3132         VectorClear(ed->fields.server->angles);
3133         ed->fields.server->nextthink = -1;
3134         ed->fields.server->solid = 0;
3135
3136         // make sure csqc networking is aware of the removed entity
3137         e = PRVM_NUM_FOR_EDICT(ed);
3138         sv.csqcentityversion[e] = 0;
3139         for (i = 0;i < svs.maxclients;i++)
3140         {
3141                 if (svs.clients[i].csqcentityscope[e])
3142                         svs.clients[i].csqcentityscope[e] = 1; // removed, awaiting send
3143                 svs.clients[i].csqcentitysendflags[e] = 0xFFFFFF;
3144         }
3145 }
3146
3147 static void SV_VM_CB_CountEdicts(void)
3148 {
3149         int             i;
3150         prvm_edict_t    *ent;
3151         int             active, models, solid, step;
3152
3153         active = models = solid = step = 0;
3154         for (i=0 ; i<prog->num_edicts ; i++)
3155         {
3156                 ent = PRVM_EDICT_NUM(i);
3157                 if (ent->priv.server->free)
3158                         continue;
3159                 active++;
3160                 if (ent->fields.server->solid)
3161                         solid++;
3162                 if (ent->fields.server->model)
3163                         models++;
3164                 if (ent->fields.server->movetype == MOVETYPE_STEP)
3165                         step++;
3166         }
3167
3168         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
3169         Con_Printf("active    :%3i\n", active);
3170         Con_Printf("view      :%3i\n", models);
3171         Con_Printf("touch     :%3i\n", solid);
3172         Con_Printf("step      :%3i\n", step);
3173 }
3174
3175 static qboolean SV_VM_CB_LoadEdict(prvm_edict_t *ent)
3176 {
3177         // remove things from different skill levels or deathmatch
3178         if (gamemode != GAME_TRANSFUSION) //Transfusion does this in QC
3179         {
3180                 if (deathmatch.integer)
3181                 {
3182                         if (((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_DEATHMATCH))
3183                         {
3184                                 return false;
3185                         }
3186                 }
3187                 else if ((current_skill <= 0 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_EASY  ))
3188                         || (current_skill == 1 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_MEDIUM))
3189                         || (current_skill >= 2 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_HARD  )))
3190                 {
3191                         return false;
3192                 }
3193         }
3194         return true;
3195 }
3196
3197 static void SV_VM_Setup(void)
3198 {
3199         PRVM_Begin;
3200         PRVM_InitProg( PRVM_SERVERPROG );
3201
3202         // allocate the mempools
3203         // TODO: move the magic numbers/constants into #defines [9/13/2006 Black]
3204         prog->progs_mempool = Mem_AllocPool("Server Progs", 0, NULL);
3205         prog->builtins = vm_sv_builtins;
3206         prog->numbuiltins = vm_sv_numbuiltins;
3207         prog->headercrc = PROGHEADER_CRC;
3208         prog->headercrc2 = PROGHEADER_CRC_TENEBRAE;
3209         prog->max_edicts = 512;
3210         if (sv.protocol == PROTOCOL_QUAKE)
3211                 prog->limit_edicts = 640; // before quake mission pack 1 this was 512
3212         else if (sv.protocol == PROTOCOL_QUAKEDP)
3213                 prog->limit_edicts = 2048; // guessing
3214         else if (sv.protocol == PROTOCOL_NEHAHRAMOVIE)
3215                 prog->limit_edicts = 2048; // guessing!
3216         else if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
3217                 prog->limit_edicts = 4096; // guessing!
3218         else
3219                 prog->limit_edicts = MAX_EDICTS;
3220         prog->reserved_edicts = svs.maxclients;
3221         prog->edictprivate_size = sizeof(edict_engineprivate_t);
3222         prog->name = "server";
3223         prog->extensionstring = vm_sv_extensions;
3224         prog->loadintoworld = true;
3225
3226         prog->begin_increase_edicts = SV_VM_CB_BeginIncreaseEdicts;
3227         prog->end_increase_edicts = SV_VM_CB_EndIncreaseEdicts;
3228         prog->init_edict = SV_VM_CB_InitEdict;
3229         prog->free_edict = SV_VM_CB_FreeEdict;
3230         prog->count_edicts = SV_VM_CB_CountEdicts;
3231         prog->load_edict = SV_VM_CB_LoadEdict;
3232         prog->init_cmd = VM_SV_Cmd_Init;
3233         prog->reset_cmd = VM_SV_Cmd_Reset;
3234         prog->error_cmd = Host_Error;
3235
3236         // TODO: add a requiredfuncs list (ask LH if this is necessary at all)
3237         PRVM_LoadProgs( sv_progs.string, 0, NULL, REQFIELDS, reqfields, 0, NULL );
3238
3239         // some mods compiled with scrambling compilers lack certain critical
3240         // global names and field names such as "self" and "time" and "nextthink"
3241         // so we have to set these offsets manually, matching the entvars_t
3242         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, angles);
3243         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, chain);
3244         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, classname);
3245         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frame);
3246         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, groundentity);
3247         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ideal_yaw);
3248         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, nextthink);
3249         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, think);
3250         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, yaw_speed);
3251         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, self);
3252         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, time);
3253         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_forward);
3254         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_right);
3255         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_up);
3256         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_allsolid);
3257         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_startsolid);
3258         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_fraction);
3259         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inwater);
3260         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inopen);
3261         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_endpos);
3262         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_normal);
3263         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_dist);
3264         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_ent);
3265         // OP_STATE is always supported on server (due to entvars_t)
3266         prog->flag |= PRVM_OP_STATE;
3267
3268         VM_CustomStats_Clear();//[515]: csqc
3269
3270         PRVM_End;
3271
3272         SV_Prepare_CSQC();
3273 }
3274
3275 void SV_VM_Begin(void)
3276 {
3277         PRVM_Begin;
3278         PRVM_SetProg( PRVM_SERVERPROG );
3279
3280         prog->globals.server->time = (float) sv.time;
3281 }
3282
3283 void SV_VM_End(void)
3284 {
3285         PRVM_End;
3286 }