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