]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - sv_main.c
patch from div0 to fix the fixangle logic (my fix apparently didn't work properly...
[xonotic/darkplaces.git] / sv_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sv_main.c -- server main program
21
22 #include "quakedef.h"
23 #include "libcurl.h"
24
25 void SV_VM_Init();
26 void SV_VM_Setup();
27
28 void VM_AutoSentStats_Clear (void);
29 void EntityFrameCSQC_ClearVersions (void);
30 void EntityFrameCSQC_InitClientVersions (int client, qboolean clear);
31 void VM_SV_WriteAutoSentStats (client_t *client, prvm_edict_t *ent, sizebuf_t *msg, int *stats);
32 void EntityFrameCSQC_WriteFrame (sizebuf_t *msg, int numstates, const entity_state_t *states);
33
34
35 // select which protocol to host, this is fed to Protocol_EnumForName
36 cvar_t sv_protocolname = {0, "sv_protocolname", "DP7", "selects network protocol to host for (values include QUAKE, QUAKEDP, NEHAHRAMOVIE, DP1 and up)"};
37 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)"};
38 cvar_t sv_maxrate = {CVAR_SAVE | CVAR_NOTIFY, "sv_maxrate", "10000", "upper limit on client rate cvar, should reflect your network connection quality"};
39 cvar_t sv_allowdownloads = {0, "sv_allowdownloads", "1", "whether to allow clients to download files from the server (does not affect http downloads)"};
40 cvar_t sv_allowdownloads_inarchive = {0, "sv_allowdownloads_inarchive", "0", "whether to allow downloads from archives (pak/pk3)"};
41 cvar_t sv_allowdownloads_archive = {0, "sv_allowdownloads_archive", "0", "whether to allow downloads of archives (pak/pk3)"};
42 cvar_t sv_allowdownloads_config = {0, "sv_allowdownloads_config", "0", "whether to allow downloads of config files (cfg)"};
43 cvar_t sv_allowdownloads_dlcache = {0, "sv_allowdownloads_dlcache", "0", "whether to allow downloads of dlcache files (dlcache/)"};
44
45 extern cvar_t sv_random_seed;
46
47 static cvar_t sv_cullentities_pvs = {0, "sv_cullentities_pvs", "1", "fast but loose culling of hidden entities"}; // fast but loose
48 static 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"}; // tends to get false negatives, uses a timeout to keep entities visible a short time after becoming hidden
49 static cvar_t sv_cullentities_trace_samples = {0, "sv_cullentities_trace_samples", "1", "number of samples to test for entity culling"};
50 static 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"};
51 static cvar_t sv_cullentities_trace_enlarge = {0, "sv_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
52 static cvar_t sv_cullentities_trace_delay = {0, "sv_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
53 static cvar_t sv_cullentities_trace_prediction = {0, "sv_cullentities_trace_prediction", "1", "also trace from the predicted player position"};
54 static 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!)"};
55 static cvar_t sv_cullentities_stats = {0, "sv_cullentities_stats", "0", "displays stats on network entities culled by various methods for each client"};
56 static 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)"};
57
58 cvar_t sv_gameplayfix_grenadebouncedownslopes = {0, "sv_gameplayfix_grenadebouncedownslopes", "1", "prevents MOVETYPE_BOUNCE (grenades) from getting stuck when fired down a downward sloping surface"};
59 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"};
60 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)"};
61 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)"};
62 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"};
63 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"};
64 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"};
65 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"};
66 cvar_t sv_gameplayfix_qwplayerphysics = {0, "sv_gameplayfix_qwplayerphysics", "1", "changes water jumping to make it easier to get out of water, and prevents friction on landing when bunnyhopping"};
67 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"};
68 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)"};
69
70 cvar_t sv_progs = {0, "sv_progs", "progs.dat", "selects which quakec progs.dat file to run" };
71
72 // TODO: move these cvars here
73 extern cvar_t sv_clmovement_enable;
74 extern cvar_t sv_clmovement_minping;
75 extern cvar_t sv_clmovement_minping_disabletime;
76 extern cvar_t sv_clmovement_waitforinput;
77
78 server_t sv;
79 server_static_t svs;
80
81 mempool_t *sv_mempool = NULL;
82
83 //============================================================================
84
85 extern void SV_Phys_Init (void);
86 static void SV_SaveEntFile_f(void);
87 static void SV_StartDownload_f(void);
88 static void SV_Download_f(void);
89
90 void SV_AreaStats_f(void)
91 {
92         World_PrintAreaStats(&sv.world, "server");
93 }
94
95 /*
96 ===============
97 SV_Init
98 ===============
99 */
100 void SV_Init (void)
101 {
102         // init the csqc progs cvars, since they are updated/used by the server code
103         // TODO: fix this since this is a quick hack to make some of [515]'s broken code run ;) [9/13/2006 Black]
104         extern cvar_t csqc_progname;    //[515]: csqc crc check and right csprogs name according to progs.dat
105         extern cvar_t csqc_progcrc;
106         extern cvar_t csqc_progsize;
107         Cvar_RegisterVariable (&csqc_progname);
108         Cvar_RegisterVariable (&csqc_progcrc);
109         Cvar_RegisterVariable (&csqc_progsize);
110
111         Cmd_AddCommand("sv_saveentfile", SV_SaveEntFile_f, "save map entities to .ent file (to allow external editing)");
112         Cmd_AddCommand("sv_areastats", SV_AreaStats_f, "prints statistics on entity culling during collision traces");
113         Cmd_AddCommand_WithClientCommand("sv_startdownload", NULL, SV_StartDownload_f, "begins sending a file to the client (network protocol use only)");
114         Cmd_AddCommand_WithClientCommand("download", NULL, SV_Download_f, "downloads a specified file from the server");
115         Cvar_RegisterVariable (&sv_maxvelocity);
116         Cvar_RegisterVariable (&sv_gravity);
117         Cvar_RegisterVariable (&sv_friction);
118         Cvar_RegisterVariable (&sv_waterfriction);
119         Cvar_RegisterVariable (&sv_edgefriction);
120         Cvar_RegisterVariable (&sv_stopspeed);
121         Cvar_RegisterVariable (&sv_maxspeed);
122         Cvar_RegisterVariable (&sv_maxairspeed);
123         Cvar_RegisterVariable (&sv_accelerate);
124         Cvar_RegisterVariable (&sv_airaccelerate);
125         Cvar_RegisterVariable (&sv_wateraccelerate);
126         Cvar_RegisterVariable (&sv_clmovement_enable);
127         Cvar_RegisterVariable (&sv_clmovement_minping);
128         Cvar_RegisterVariable (&sv_clmovement_minping_disabletime);
129         Cvar_RegisterVariable (&sv_clmovement_waitforinput);
130         Cvar_RegisterVariable (&sv_idealpitchscale);
131         Cvar_RegisterVariable (&sv_aim);
132         Cvar_RegisterVariable (&sv_nostep);
133         Cvar_RegisterVariable (&sv_cullentities_pvs);
134         Cvar_RegisterVariable (&sv_cullentities_trace);
135         Cvar_RegisterVariable (&sv_cullentities_trace_samples);
136         Cvar_RegisterVariable (&sv_cullentities_trace_samples_extra);
137         Cvar_RegisterVariable (&sv_cullentities_trace_enlarge);
138         Cvar_RegisterVariable (&sv_cullentities_trace_delay);
139         Cvar_RegisterVariable (&sv_cullentities_trace_prediction);
140         Cvar_RegisterVariable (&sv_cullentities_nevercullbmodels);
141         Cvar_RegisterVariable (&sv_cullentities_stats);
142         Cvar_RegisterVariable (&sv_entpatch);
143         Cvar_RegisterVariable (&sv_gameplayfix_grenadebouncedownslopes);
144         Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse);
145         Cvar_RegisterVariable (&sv_gameplayfix_stepdown);
146         Cvar_RegisterVariable (&sv_gameplayfix_stepwhilejumping);
147         Cvar_RegisterVariable (&sv_gameplayfix_swiminbmodels);
148         Cvar_RegisterVariable (&sv_gameplayfix_setmodelrealbox);
149         Cvar_RegisterVariable (&sv_gameplayfix_blowupfallenzombies);
150         Cvar_RegisterVariable (&sv_gameplayfix_findradiusdistancetobox);
151         Cvar_RegisterVariable (&sv_gameplayfix_qwplayerphysics);
152         Cvar_RegisterVariable (&sv_gameplayfix_upwardvelocityclearsongroundflag);
153         Cvar_RegisterVariable (&sv_gameplayfix_droptofloorstartsolid);
154         Cvar_RegisterVariable (&sv_protocolname);
155         Cvar_RegisterVariable (&sv_ratelimitlocalplayer);
156         Cvar_RegisterVariable (&sv_maxrate);
157         Cvar_RegisterVariable (&sv_allowdownloads);
158         Cvar_RegisterVariable (&sv_allowdownloads_inarchive);
159         Cvar_RegisterVariable (&sv_allowdownloads_archive);
160         Cvar_RegisterVariable (&sv_allowdownloads_config);
161         Cvar_RegisterVariable (&sv_allowdownloads_dlcache);
162         Cvar_RegisterVariable (&sv_progs);
163
164         SV_VM_Init();
165         SV_Phys_Init();
166
167         sv_mempool = Mem_AllocPool("server", 0, NULL);
168 }
169
170 static void SV_SaveEntFile_f(void)
171 {
172         char basename[MAX_QPATH];
173         if (!sv.active || !sv.worldmodel)
174         {
175                 Con_Print("Not running a server\n");
176                 return;
177         }
178         FS_StripExtension(sv.worldmodel->name, basename, sizeof(basename));
179         FS_WriteFile(va("%s.ent", basename), sv.worldmodel->brush.entities, (fs_offset_t)strlen(sv.worldmodel->brush.entities));
180 }
181
182
183 /*
184 =============================================================================
185
186 EVENT MESSAGES
187
188 =============================================================================
189 */
190
191 /*
192 ==================
193 SV_StartParticle
194
195 Make sure the event gets sent to all clients
196 ==================
197 */
198 void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
199 {
200         int i;
201
202         if (sv.datagram.cursize > MAX_PACKETFRAGMENT-18)
203                 return;
204         MSG_WriteByte (&sv.datagram, svc_particle);
205         MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
206         MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
207         MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
208         for (i=0 ; i<3 ; i++)
209                 MSG_WriteChar (&sv.datagram, (int)bound(-128, dir[i]*16, 127));
210         MSG_WriteByte (&sv.datagram, count);
211         MSG_WriteByte (&sv.datagram, color);
212 }
213
214 /*
215 ==================
216 SV_StartEffect
217
218 Make sure the event gets sent to all clients
219 ==================
220 */
221 void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
222 {
223         if (modelindex >= 256 || startframe >= 256)
224         {
225                 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-19)
226                         return;
227                 MSG_WriteByte (&sv.datagram, svc_effect2);
228                 MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
229                 MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
230                 MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
231                 MSG_WriteShort (&sv.datagram, modelindex);
232                 MSG_WriteShort (&sv.datagram, startframe);
233                 MSG_WriteByte (&sv.datagram, framecount);
234                 MSG_WriteByte (&sv.datagram, framerate);
235         }
236         else
237         {
238                 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-17)
239                         return;
240                 MSG_WriteByte (&sv.datagram, svc_effect);
241                 MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
242                 MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
243                 MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
244                 MSG_WriteByte (&sv.datagram, modelindex);
245                 MSG_WriteByte (&sv.datagram, startframe);
246                 MSG_WriteByte (&sv.datagram, framecount);
247                 MSG_WriteByte (&sv.datagram, framerate);
248         }
249 }
250
251 /*
252 ==================
253 SV_StartSound
254
255 Each entity can have eight independant sound sources, like voice,
256 weapon, feet, etc.
257
258 Channel 0 is an auto-allocate channel, the others override anything
259 already running on that entity/channel pair.
260
261 An attenuation of 0 will play full volume everywhere in the level.
262 Larger attenuations will drop off.  (max 4 attenuation)
263
264 ==================
265 */
266 void SV_StartSound (prvm_edict_t *entity, int channel, const char *sample, int volume, float attenuation)
267 {
268         int sound_num, field_mask, i, ent;
269
270         if (volume < 0 || volume > 255)
271         {
272                 Con_Printf ("SV_StartSound: volume = %i\n", volume);
273                 return;
274         }
275
276         if (attenuation < 0 || attenuation > 4)
277         {
278                 Con_Printf ("SV_StartSound: attenuation = %f\n", attenuation);
279                 return;
280         }
281
282         if (channel < 0 || channel > 7)
283         {
284                 Con_Printf ("SV_StartSound: channel = %i\n", channel);
285                 return;
286         }
287
288         if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
289                 return;
290
291 // find precache number for sound
292         sound_num = SV_SoundIndex(sample, 1);
293         if (!sound_num)
294                 return;
295
296         ent = PRVM_NUM_FOR_EDICT(entity);
297
298         field_mask = 0;
299         if (volume != DEFAULT_SOUND_PACKET_VOLUME)
300                 field_mask |= SND_VOLUME;
301         if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
302                 field_mask |= SND_ATTENUATION;
303         if (ent >= 8192)
304                 field_mask |= SND_LARGEENTITY;
305         if (sound_num >= 256 || channel >= 8)
306                 field_mask |= SND_LARGESOUND;
307
308 // directed messages go only to the entity they are targeted on
309         MSG_WriteByte (&sv.datagram, svc_sound);
310         MSG_WriteByte (&sv.datagram, field_mask);
311         if (field_mask & SND_VOLUME)
312                 MSG_WriteByte (&sv.datagram, volume);
313         if (field_mask & SND_ATTENUATION)
314                 MSG_WriteByte (&sv.datagram, (int)(attenuation*64));
315         if (field_mask & SND_LARGEENTITY)
316         {
317                 MSG_WriteShort (&sv.datagram, ent);
318                 MSG_WriteByte (&sv.datagram, channel);
319         }
320         else
321                 MSG_WriteShort (&sv.datagram, (ent<<3) | channel);
322         if (field_mask & SND_LARGESOUND)
323                 MSG_WriteShort (&sv.datagram, sound_num);
324         else
325                 MSG_WriteByte (&sv.datagram, sound_num);
326         for (i = 0;i < 3;i++)
327                 MSG_WriteCoord (&sv.datagram, entity->fields.server->origin[i]+0.5*(entity->fields.server->mins[i]+entity->fields.server->maxs[i]), sv.protocol);
328 }
329
330 /*
331 ==============================================================================
332
333 CLIENT SPAWNING
334
335 ==============================================================================
336 */
337
338 /*
339 ================
340 SV_SendServerinfo
341
342 Sends the first message from the server to a connected client.
343 This will be sent on the initial connection and upon each server load.
344 ================
345 */
346 void SV_SendServerinfo (client_t *client)
347 {
348         int i;
349         char message[128];
350
351         // we know that this client has a netconnection and thus is not a bot
352
353         // edicts get reallocated on level changes, so we need to update it here
354         client->edict = PRVM_EDICT_NUM((client - svs.clients) + 1);
355
356         // clear cached stuff that depends on the level
357         client->weaponmodel[0] = 0;
358         client->weaponmodelindex = 0;
359
360         // LordHavoc: clear entityframe tracking
361         client->latestframenum = 0;
362
363         if (client->entitydatabase)
364                 EntityFrame_FreeDatabase(client->entitydatabase);
365         if (client->entitydatabase4)
366                 EntityFrame4_FreeDatabase(client->entitydatabase4);
367         if (client->entitydatabase5)
368                 EntityFrame5_FreeDatabase(client->entitydatabase5);
369
370         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE)
371         {
372                 if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3)
373                         client->entitydatabase = EntityFrame_AllocDatabase(sv_mempool);
374                 else if (sv.protocol == PROTOCOL_DARKPLACES4)
375                         client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_mempool);
376                 else
377                         client->entitydatabase5 = EntityFrame5_AllocDatabase(sv_mempool);
378         }
379
380         SZ_Clear (&client->netconnection->message);
381         MSG_WriteByte (&client->netconnection->message, svc_print);
382         dpsnprintf (message, sizeof (message), "\nServer: %s build %s (progs %i crc)", gamename, buildstring, prog->filecrc);
383         MSG_WriteString (&client->netconnection->message,message);
384
385         //[515]: init csprogs according to version of svprogs, check the crc, etc.
386         if (sv.csqc_progname[0])
387         {
388                 prvm_eval_t *val;
389                 Con_DPrintf("sending csqc info to client (\"%s\" with size %i and crc %i)\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
390                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
391                 MSG_WriteString (&client->netconnection->message, va("csqc_progname %s\n", sv.csqc_progname));
392                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
393                 MSG_WriteString (&client->netconnection->message, va("csqc_progsize %i\n", sv.csqc_progsize));
394                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
395                 MSG_WriteString (&client->netconnection->message, va("csqc_progcrc %i\n", sv.csqc_progcrc));
396                 //[515]: init stufftext string (it is sent before svc_serverinfo)
397                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.SV_InitCmd);
398                 if (val)
399                 {
400                         MSG_WriteByte (&client->netconnection->message, svc_stufftext);
401                         MSG_WriteString (&client->netconnection->message, va("%s\n", PRVM_GetString(val->string)));
402                 }
403         }
404
405         if (sv_allowdownloads.integer)
406         {
407                 MSG_WriteByte (&client->netconnection->message, svc_stufftext);
408                 MSG_WriteString (&client->netconnection->message, "cl_serverextension_download 1");
409         }
410
411         // send at this time so it's guaranteed to get executed at the right time
412         {
413                 client_t *save;
414                 save = host_client;
415                 host_client = client;
416                 Curl_SendRequirements();
417                 host_client = save;
418         }
419
420         MSG_WriteByte (&client->netconnection->message, svc_serverinfo);
421         MSG_WriteLong (&client->netconnection->message, Protocol_NumberForEnum(sv.protocol));
422         MSG_WriteByte (&client->netconnection->message, svs.maxclients);
423
424         if (!coop.integer && deathmatch.integer)
425                 MSG_WriteByte (&client->netconnection->message, GAME_DEATHMATCH);
426         else
427                 MSG_WriteByte (&client->netconnection->message, GAME_COOP);
428
429         MSG_WriteString (&client->netconnection->message,PRVM_GetString(prog->edicts->fields.server->message));
430
431         for (i = 1;i < MAX_MODELS && sv.model_precache[i][0];i++)
432                 MSG_WriteString (&client->netconnection->message, sv.model_precache[i]);
433         MSG_WriteByte (&client->netconnection->message, 0);
434
435         for (i = 1;i < MAX_SOUNDS && sv.sound_precache[i][0];i++)
436                 MSG_WriteString (&client->netconnection->message, sv.sound_precache[i]);
437         MSG_WriteByte (&client->netconnection->message, 0);
438
439 // send music
440         MSG_WriteByte (&client->netconnection->message, svc_cdtrack);
441         MSG_WriteByte (&client->netconnection->message, (int)prog->edicts->fields.server->sounds);
442         MSG_WriteByte (&client->netconnection->message, (int)prog->edicts->fields.server->sounds);
443
444 // set view
445         MSG_WriteByte (&client->netconnection->message, svc_setview);
446         MSG_WriteShort (&client->netconnection->message, PRVM_NUM_FOR_EDICT(client->edict));
447
448         MSG_WriteByte (&client->netconnection->message, svc_signonnum);
449         MSG_WriteByte (&client->netconnection->message, 1);
450
451         client->spawned = false;                // need prespawn, spawn, etc
452
453         // clear movement info until client enters the new level properly
454         memset(&client->cmd, 0, sizeof(client->cmd));
455         client->movesequence = 0;
456 #ifdef NUM_PING_TIMES
457         for (i = 0;i < NUM_PING_TIMES;i++)
458                 client->ping_times[i] = 0;
459         client->num_pings = 0;
460 #endif
461         client->ping = 0;
462 }
463
464 /*
465 ================
466 SV_ConnectClient
467
468 Initializes a client_t for a new net connection.  This will only be called
469 once for a player each game, not once for each level change.
470 ================
471 */
472 void SV_ConnectClient (int clientnum, netconn_t *netconnection)
473 {
474         client_t                *client;
475         int                             i;
476         float                   spawn_parms[NUM_SPAWN_PARMS];
477
478         client = svs.clients + clientnum;
479
480         if(netconnection)//[515]: bots don't play with csqc =)
481                 EntityFrameCSQC_InitClientVersions(clientnum, false);
482
483 // set up the client_t
484         if (sv.loadgame)
485                 memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms));
486         memset (client, 0, sizeof(*client));
487         client->active = true;
488         client->netconnection = netconnection;
489
490         Con_DPrintf("Client %s connected\n", client->netconnection ? client->netconnection->address : "botclient");
491
492         strlcpy(client->name, "unconnected", sizeof(client->name));
493         strlcpy(client->old_name, "unconnected", sizeof(client->old_name));
494         client->spawned = false;
495         client->edict = PRVM_EDICT_NUM(clientnum+1);
496         if (client->netconnection)
497                 client->netconnection->message.allowoverflow = true;            // we can catch it
498         // updated by receiving "rate" command from client
499         client->rate = NET_MINRATE;
500         // no limits for local player
501         if (client->netconnection && LHNETADDRESS_GetAddressType(&client->netconnection->peeraddress) == LHNETADDRESSTYPE_LOOP)
502                 client->rate = 1000000000;
503         client->connecttime = realtime;
504
505         if (sv.loadgame)
506                 memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms));
507         else
508         {
509                 // call the progs to get default spawn parms for the new client
510                 // set self to world to intentionally cause errors with broken SetNewParms code in some mods
511                 prog->globals.server->self = 0;
512                 PRVM_ExecuteProgram (prog->globals.server->SetNewParms, "QC function SetNewParms is missing");
513                 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
514                         client->spawn_parms[i] = (&prog->globals.server->parm1)[i];
515
516                 // set up the entity for this client (including .colormap, .team, etc)
517                 PRVM_ED_ClearEdict(client->edict);
518         }
519
520         // don't call SendServerinfo for a fresh botclient because its fields have
521         // not been set up by the qc yet
522         if (client->netconnection)
523                 SV_SendServerinfo (client);
524         else
525                 client->spawned = true;
526 }
527
528
529 /*
530 ===============================================================================
531
532 FRAME UPDATES
533
534 ===============================================================================
535 */
536
537 /*
538 ==================
539 SV_ClearDatagram
540
541 ==================
542 */
543 void SV_ClearDatagram (void)
544 {
545         SZ_Clear (&sv.datagram);
546 }
547
548 /*
549 =============================================================================
550
551 The PVS must include a small area around the client to allow head bobbing
552 or other small motion on the client side.  Otherwise, a bob might cause an
553 entity that should be visible to not show up, especially when the bob
554 crosses a waterline.
555
556 =============================================================================
557 */
558
559 int sv_writeentitiestoclient_pvsbytes;
560 unsigned char sv_writeentitiestoclient_pvs[MAX_MAP_LEAFS/8];
561
562 static int numsendentities;
563 static entity_state_t sendentities[MAX_EDICTS];
564 static entity_state_t *sendentitiesindex[MAX_EDICTS];
565
566 qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *cs, int e)
567 {
568         int i;
569         unsigned int modelindex, effects, flags, glowsize, lightstyle, lightpflags, light[4], specialvisibilityradius;
570         unsigned int customizeentityforclient;
571         float f;
572         vec3_t cullmins, cullmaxs;
573         model_t *model;
574         prvm_eval_t *val;
575
576         // EF_NODRAW prevents sending for any reason except for your own
577         // client, so we must keep all clients in this superset
578         effects = (unsigned)ent->fields.server->effects;
579
580         // we can omit invisible entities with no effects that are not clients
581         // LordHavoc: this could kill tags attached to an invisible entity, I
582         // just hope we never have to support that case
583         i = (int)ent->fields.server->modelindex;
584         modelindex = (i >= 1 && i < MAX_MODELS && *PRVM_GetString(ent->fields.server->model)) ? i : 0;
585
586         flags = 0;
587         i = (int)(PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.glow_size)->_float * 0.25f);
588         glowsize = (unsigned char)bound(0, i, 255);
589         if (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.glow_trail)->_float)
590                 flags |= RENDER_GLOWTRAIL;
591
592         f = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.color)->vector[0]*256;
593         light[0] = (unsigned short)bound(0, f, 65535);
594         f = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.color)->vector[1]*256;
595         light[1] = (unsigned short)bound(0, f, 65535);
596         f = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.color)->vector[2]*256;
597         light[2] = (unsigned short)bound(0, f, 65535);
598         f = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.light_lev)->_float;
599         light[3] = (unsigned short)bound(0, f, 65535);
600         lightstyle = (unsigned char)PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.style)->_float;
601         lightpflags = (unsigned char)PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.pflags)->_float;
602
603         if (gamemode == GAME_TENEBRAE)
604         {
605                 // tenebrae's EF_FULLDYNAMIC conflicts with Q2's EF_NODRAW
606                 if (effects & 16)
607                 {
608                         effects &= ~16;
609                         lightpflags |= PFLAGS_FULLDYNAMIC;
610                 }
611                 // tenebrae's EF_GREEN conflicts with DP's EF_ADDITIVE
612                 if (effects & 32)
613                 {
614                         effects &= ~32;
615                         light[0] = (int)(0.2*256);
616                         light[1] = (int)(1.0*256);
617                         light[2] = (int)(0.2*256);
618                         light[3] = 200;
619                         lightpflags |= PFLAGS_FULLDYNAMIC;
620                 }
621         }
622
623         specialvisibilityradius = 0;
624         if (lightpflags & PFLAGS_FULLDYNAMIC)
625                 specialvisibilityradius = max(specialvisibilityradius, light[3]);
626         if (glowsize)
627                 specialvisibilityradius = max(specialvisibilityradius, glowsize * 4);
628         if (flags & RENDER_GLOWTRAIL)
629                 specialvisibilityradius = max(specialvisibilityradius, 100);
630         if (effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
631         {
632                 if (effects & EF_BRIGHTFIELD)
633                         specialvisibilityradius = max(specialvisibilityradius, 80);
634                 if (effects & EF_MUZZLEFLASH)
635                         specialvisibilityradius = max(specialvisibilityradius, 100);
636                 if (effects & EF_BRIGHTLIGHT)
637                         specialvisibilityradius = max(specialvisibilityradius, 400);
638                 if (effects & EF_DIMLIGHT)
639                         specialvisibilityradius = max(specialvisibilityradius, 200);
640                 if (effects & EF_RED)
641                         specialvisibilityradius = max(specialvisibilityradius, 200);
642                 if (effects & EF_BLUE)
643                         specialvisibilityradius = max(specialvisibilityradius, 200);
644                 if (effects & EF_FLAME)
645                         specialvisibilityradius = max(specialvisibilityradius, 250);
646                 if (effects & EF_STARDUST)
647                         specialvisibilityradius = max(specialvisibilityradius, 100);
648         }
649
650         // early culling checks
651         // (final culling is done by SV_MarkWriteEntityStateToClient)
652         customizeentityforclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.customizeentityforclient)->function;
653         if (!customizeentityforclient)
654         {
655                 if (e > svs.maxclients && (!modelindex && !specialvisibilityradius))
656                         return false;
657                 // this 2 billion unit check is actually to detect NAN origins
658                 // (we really don't want to send those)
659                 if (VectorLength2(ent->fields.server->origin) > 2000000000.0*2000000000.0)
660                         return false;
661         }
662
663
664         *cs = defaultstate;
665         cs->active = true;
666         cs->number = e;
667         VectorCopy(ent->fields.server->origin, cs->origin);
668         VectorCopy(ent->fields.server->angles, cs->angles);
669         cs->flags = flags;
670         cs->effects = effects;
671         cs->colormap = (unsigned)ent->fields.server->colormap;
672         cs->modelindex = modelindex;
673         cs->skin = (unsigned)ent->fields.server->skin;
674         cs->frame = (unsigned)ent->fields.server->frame;
675         cs->viewmodelforclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.viewmodelforclient)->edict;
676         cs->exteriormodelforclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.exteriormodeltoclient)->edict;
677         cs->nodrawtoclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.nodrawtoclient)->edict;
678         cs->drawonlytoclient = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.drawonlytoclient)->edict;
679         cs->customizeentityforclient = customizeentityforclient;
680         cs->tagentity = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.tag_entity)->edict;
681         cs->tagindex = (unsigned char)PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.tag_index)->_float;
682         cs->glowsize = glowsize;
683
684         // don't need to init cs->colormod because the defaultstate did that for us
685         //cs->colormod[0] = cs->colormod[1] = cs->colormod[2] = 32;
686         val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.colormod);
687         if (val->vector[0] || val->vector[1] || val->vector[2])
688         {
689                 i = (int)(val->vector[0] * 32.0f);cs->colormod[0] = bound(0, i, 255);
690                 i = (int)(val->vector[1] * 32.0f);cs->colormod[1] = bound(0, i, 255);
691                 i = (int)(val->vector[2] * 32.0f);cs->colormod[2] = bound(0, i, 255);
692         }
693
694         cs->modelindex = modelindex;
695
696         cs->alpha = 255;
697         f = (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.alpha)->_float * 255.0f);
698         if (f)
699         {
700                 i = (int)f;
701                 cs->alpha = (unsigned char)bound(0, i, 255);
702         }
703         // halflife
704         f = (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.renderamt)->_float);
705         if (f)
706         {
707                 i = (int)f;
708                 cs->alpha = (unsigned char)bound(0, i, 255);
709         }
710
711         cs->scale = 16;
712         f = (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.scale)->_float * 16.0f);
713         if (f)
714         {
715                 i = (int)f;
716                 cs->scale = (unsigned char)bound(0, i, 255);
717         }
718
719         cs->glowcolor = 254;
720         f = (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.glow_color)->_float);
721         if (f)
722                 cs->glowcolor = (int)f;
723
724         if (PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.fullbright)->_float)
725                 cs->effects |= EF_FULLBRIGHT;
726
727         if (ent->fields.server->movetype == MOVETYPE_STEP)
728                 cs->flags |= RENDER_STEP;
729         if ((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)
730                 cs->flags |= RENDER_LOWPRECISION;
731         if (ent->fields.server->colormap >= 1024)
732                 cs->flags |= RENDER_COLORMAPPED;
733         if (cs->viewmodelforclient)
734                 cs->flags |= RENDER_VIEWMODEL; // show relative to the view
735
736         cs->light[0] = light[0];
737         cs->light[1] = light[1];
738         cs->light[2] = light[2];
739         cs->light[3] = light[3];
740         cs->lightstyle = lightstyle;
741         cs->lightpflags = lightpflags;
742
743         cs->specialvisibilityradius = specialvisibilityradius;
744
745         // calculate the visible box of this entity (don't use the physics box
746         // as that is often smaller than a model, and would not count
747         // specialvisibilityradius)
748         if ((model = sv.models[modelindex]))
749         {
750                 float scale = cs->scale * (1.0f / 16.0f);
751                 if (cs->angles[0] || cs->angles[2]) // pitch and roll
752                 {
753                         VectorMA(cs->origin, scale, model->rotatedmins, cullmins);
754                         VectorMA(cs->origin, scale, model->rotatedmaxs, cullmaxs);
755                 }
756                 else if (cs->angles[1])
757                 {
758                         VectorMA(cs->origin, scale, model->yawmins, cullmins);
759                         VectorMA(cs->origin, scale, model->yawmaxs, cullmaxs);
760                 }
761                 else
762                 {
763                         VectorMA(cs->origin, scale, model->normalmins, cullmins);
764                         VectorMA(cs->origin, scale, model->normalmaxs, cullmaxs);
765                 }
766         }
767         else
768         {
769                 // if there is no model (or it could not be loaded), use the physics box
770                 VectorAdd(cs->origin, ent->fields.server->mins, cullmins);
771                 VectorAdd(cs->origin, ent->fields.server->maxs, cullmaxs);
772         }
773         if (specialvisibilityradius)
774         {
775                 cullmins[0] = min(cullmins[0], cs->origin[0] - specialvisibilityradius);
776                 cullmins[1] = min(cullmins[1], cs->origin[1] - specialvisibilityradius);
777                 cullmins[2] = min(cullmins[2], cs->origin[2] - specialvisibilityradius);
778                 cullmaxs[0] = max(cullmaxs[0], cs->origin[0] + specialvisibilityradius);
779                 cullmaxs[1] = max(cullmaxs[1], cs->origin[1] + specialvisibilityradius);
780                 cullmaxs[2] = max(cullmaxs[2], cs->origin[2] + specialvisibilityradius);
781         }
782         // calculate center of bbox for network prioritization purposes
783         VectorMAM(0.5f, cullmins, 0.5f, cullmaxs, cs->netcenter);
784         // if culling box has moved, update pvs cluster links
785         if (!VectorCompare(cullmins, ent->priv.server->cullmins) || !VectorCompare(cullmaxs, ent->priv.server->cullmaxs))
786         {
787                 VectorCopy(cullmins, ent->priv.server->cullmins);
788                 VectorCopy(cullmaxs, ent->priv.server->cullmaxs);
789                 // a value of -1 for pvs_numclusters indicates that the links are not
790                 // cached, and should be re-tested each time, this is the case if the
791                 // culling box touches too many pvs clusters to store, or if the world
792                 // model does not support FindBoxClusters
793                 ent->priv.server->pvs_numclusters = -1;
794                 if (sv.worldmodel && sv.worldmodel->brush.FindBoxClusters)
795                 {
796                         i = sv.worldmodel->brush.FindBoxClusters(sv.worldmodel, cullmins, cullmaxs, MAX_ENTITYCLUSTERS, ent->priv.server->pvs_clusterlist);
797                         if (i <= MAX_ENTITYCLUSTERS)
798                                 ent->priv.server->pvs_numclusters = i;
799                 }
800         }
801
802         return true;
803 }
804
805 void SV_PrepareEntitiesForSending(void)
806 {
807         int e;
808         prvm_edict_t *ent;
809         // send all entities that touch the pvs
810         numsendentities = 0;
811         sendentitiesindex[0] = NULL;
812         memset(sendentitiesindex, 0, prog->num_edicts * sizeof(entity_state_t *));
813         for (e = 1, ent = PRVM_NEXT_EDICT(prog->edicts);e < prog->num_edicts;e++, ent = PRVM_NEXT_EDICT(ent))
814         {
815                 if (!ent->priv.server->free && SV_PrepareEntityForSending(ent, sendentities + numsendentities, e))
816                 {
817                         sendentitiesindex[e] = sendentities + numsendentities;
818                         numsendentities++;
819                 }
820         }
821 }
822
823 static int sententitiesmark = 0;
824 static int sententities[MAX_EDICTS];
825 static int sententitiesconsideration[MAX_EDICTS];
826 static int sv_writeentitiestoclient_culled_pvs;
827 static int sv_writeentitiestoclient_culled_trace;
828 static int sv_writeentitiestoclient_visibleentities;
829 static int sv_writeentitiestoclient_totalentities;
830 //static entity_frame_t sv_writeentitiestoclient_entityframe;
831 static int sv_writeentitiestoclient_clentnum;
832 static vec3_t sv_writeentitiestoclient_testeye;
833 static client_t *sv_writeentitiestoclient_client;
834
835 void SV_MarkWriteEntityStateToClient(entity_state_t *s)
836 {
837         int isbmodel;
838         model_t *model;
839         prvm_edict_t *ed;
840         if (sententitiesconsideration[s->number] == sententitiesmark)
841                 return;
842         sententitiesconsideration[s->number] = sententitiesmark;
843         sv_writeentitiestoclient_totalentities++;
844
845         if (s->customizeentityforclient)
846         {
847                 prog->globals.server->self = s->number;
848                 prog->globals.server->other = sv_writeentitiestoclient_clentnum;
849                 PRVM_ExecuteProgram(s->customizeentityforclient, "customizeentityforclient: NULL function");
850                 if(!PRVM_G_FLOAT(OFS_RETURN) || !SV_PrepareEntityForSending(PRVM_EDICT_NUM(s->number), s, s->number))
851                         return;
852         }
853
854         // never reject player
855         if (s->number != sv_writeentitiestoclient_clentnum)
856         {
857                 // check various rejection conditions
858                 if (s->nodrawtoclient == sv_writeentitiestoclient_clentnum)
859                         return;
860                 if (s->drawonlytoclient && s->drawonlytoclient != sv_writeentitiestoclient_clentnum)
861                         return;
862                 if (s->effects & EF_NODRAW)
863                         return;
864                 // LordHavoc: only send entities with a model or important effects
865                 if (!s->modelindex && s->specialvisibilityradius == 0)
866                         return;
867
868                 isbmodel = (model = sv.models[s->modelindex]) != NULL && model->name[0] == '*';
869                 // viewmodels don't have visibility checking
870                 if (s->viewmodelforclient)
871                 {
872                         if (s->viewmodelforclient != sv_writeentitiestoclient_clentnum)
873                                 return;
874                 }
875                 else if (s->tagentity)
876                 {
877                         // tag attached entities simply check their parent
878                         if (!sendentitiesindex[s->tagentity])
879                                 return;
880                         SV_MarkWriteEntityStateToClient(sendentitiesindex[s->tagentity]);
881                         if (sententities[s->tagentity] != sententitiesmark)
882                                 return;
883                 }
884                 // always send world submodels in newer protocols because they don't
885                 // generate much traffic (in old protocols they hog bandwidth)
886                 // but only if sv_cullentities_alwayssendbmodels is on
887                 else if (!(s->effects & EF_NODEPTHTEST) && (!isbmodel || !sv_cullentities_nevercullbmodels.integer || sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE))
888                 {
889                         // entity has survived every check so far, check if visible
890                         ed = PRVM_EDICT_NUM(s->number);
891
892                         // if not touching a visible leaf
893                         if (sv_cullentities_pvs.integer && sv_writeentitiestoclient_pvsbytes)
894                         {
895                                 if (ed->priv.server->pvs_numclusters < 0)
896                                 {
897                                         // entity too big for clusters list
898                                         if (sv.worldmodel && sv.worldmodel->brush.BoxTouchingPVS && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, sv_writeentitiestoclient_pvs, ed->priv.server->cullmins, ed->priv.server->cullmaxs))
899                                         {
900                                                 sv_writeentitiestoclient_culled_pvs++;
901                                                 return;
902                                         }
903                                 }
904                                 else
905                                 {
906                                         int i;
907                                         // check cached clusters list
908                                         for (i = 0;i < ed->priv.server->pvs_numclusters;i++)
909                                                 if (CHECKPVSBIT(sv_writeentitiestoclient_pvs, ed->priv.server->pvs_clusterlist[i]))
910                                                         break;
911                                         if (i == ed->priv.server->pvs_numclusters)
912                                         {
913                                                 sv_writeentitiestoclient_culled_pvs++;
914                                                 return;
915                                         }
916                                 }
917                         }
918
919                         // or not seen by random tracelines
920                         if (sv_cullentities_trace.integer && !isbmodel)
921                         {
922                                 int samples = s->specialvisibilityradius ? sv_cullentities_trace_samples_extra.integer : sv_cullentities_trace_samples.integer;
923                                 float enlarge = sv_cullentities_trace_enlarge.value;
924
925                                 qboolean visible = TRUE;
926
927                                 do
928                                 {
929                                         if(Mod_CanSeeBox_Trace(samples, enlarge, sv.worldmodel, sv_writeentitiestoclient_testeye, ed->priv.server->cullmins, ed->priv.server->cullmaxs))
930                                                 break; // directly visible from the server's view
931
932                                         if(sv_cullentities_trace_prediction.integer)
933                                         {
934                                                 vec3_t predeye;
935
936                                                 // get player velocity
937                                                 float predtime = bound(0, host_client->ping, 0.2); // / 2
938                                                         // sorry, no wallhacking by high ping please, and at 200ms
939                                                         // ping a FPS is annoying to play anyway and a player is
940                                                         // likely to have changed his direction
941                                                 VectorMA(sv_writeentitiestoclient_testeye, predtime, host_client->edict->fields.server->velocity, predeye);
942                                                 if(sv.worldmodel->brush.TraceLineOfSight(sv.worldmodel, sv_writeentitiestoclient_testeye, predeye)) // must be able to go there...
943                                                 {
944                                                         if(Mod_CanSeeBox_Trace(samples, enlarge, sv.worldmodel, predeye, ed->priv.server->cullmins, ed->priv.server->cullmaxs))
945                                                                 break; // directly visible from the predicted view
946                                                 }
947                                                 else
948                                                 {
949                                                         //Con_DPrintf("Trying to walk into solid in a pingtime... not predicting for culling\n");
950                                                 }
951                                         }
952
953                                         // when we get here, we can't see the entity
954                                         visible = FALSE;
955                                 }
956                                 while(0);
957
958                                 if(visible)
959                                         sv_writeentitiestoclient_client->visibletime[s->number] = realtime + sv_cullentities_trace_delay.value;
960
961                                 if (realtime > sv_writeentitiestoclient_client->visibletime[s->number])
962                                 {
963                                         sv_writeentitiestoclient_culled_trace++;
964                                         return;
965                                 }
966                         }
967                 }
968         }
969
970         // this just marks it for sending
971         // FIXME: it would be more efficient to send here, but the entity
972         // compressor isn't that flexible
973         sv_writeentitiestoclient_visibleentities++;
974         sententities[s->number] = sententitiesmark;
975 }
976
977 entity_state_t sendstates[MAX_EDICTS];
978 extern int csqc_clientnum;
979
980 void SV_WriteEntitiesToClient(client_t *client, prvm_edict_t *clent, sizebuf_t *msg, int *stats)
981 {
982         int i, numsendstates;
983         entity_state_t *s;
984
985         // if there isn't enough space to accomplish anything, skip it
986         if (msg->cursize + 25 > msg->maxsize)
987                 return;
988
989         sv_writeentitiestoclient_client = client;
990
991         sv_writeentitiestoclient_culled_pvs = 0;
992         sv_writeentitiestoclient_culled_trace = 0;
993         sv_writeentitiestoclient_visibleentities = 0;
994         sv_writeentitiestoclient_totalentities = 0;
995
996 // find the client's PVS
997         // the real place being tested from
998         VectorAdd(clent->fields.server->origin, clent->fields.server->view_ofs, sv_writeentitiestoclient_testeye);
999         sv_writeentitiestoclient_pvsbytes = 0;
1000         if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
1001                 sv_writeentitiestoclient_pvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, sv_writeentitiestoclient_testeye, 8, sv_writeentitiestoclient_pvs, sizeof(sv_writeentitiestoclient_pvs));
1002
1003         sv_writeentitiestoclient_clentnum = PRVM_EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
1004         csqc_clientnum = sv_writeentitiestoclient_clentnum - 1;
1005
1006         sententitiesmark++;
1007
1008         for (i = 0;i < numsendentities;i++)
1009                 SV_MarkWriteEntityStateToClient(sendentities + i);
1010
1011         numsendstates = 0;
1012         for (i = 0;i < numsendentities;i++)
1013         {
1014                 if (sententities[sendentities[i].number] == sententitiesmark)
1015                 {
1016                         s = &sendstates[numsendstates++];
1017                         *s = sendentities[i];
1018                         if (s->exteriormodelforclient && s->exteriormodelforclient == sv_writeentitiestoclient_clentnum)
1019                                 s->flags |= RENDER_EXTERIORMODEL;
1020                 }
1021         }
1022
1023         if (sv_cullentities_stats.integer)
1024                 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d trace\n", client->name, sv_writeentitiestoclient_totalentities, sv_writeentitiestoclient_visibleentities, sv_writeentitiestoclient_culled_pvs + sv_writeentitiestoclient_culled_trace, sv_writeentitiestoclient_culled_pvs, sv_writeentitiestoclient_culled_trace);
1025
1026         EntityFrameCSQC_WriteFrame(msg, numsendstates, sendstates);
1027
1028         if (client->entitydatabase5)
1029                 EntityFrame5_WriteFrame(msg, client->entitydatabase5, numsendstates, sendstates, client - svs.clients + 1, stats, client->movesequence);
1030         else if (client->entitydatabase4)
1031                 EntityFrame4_WriteFrame(msg, client->entitydatabase4, numsendstates, sendstates);
1032         else if (client->entitydatabase)
1033                 EntityFrame_WriteFrame(msg, client->entitydatabase, numsendstates, sendstates, client - svs.clients + 1);
1034         else
1035                 EntityFrameQuake_WriteFrame(msg, numsendstates, sendstates);
1036 }
1037
1038 /*
1039 =============
1040 SV_CleanupEnts
1041
1042 =============
1043 */
1044 void SV_CleanupEnts (void)
1045 {
1046         int             e;
1047         prvm_edict_t    *ent;
1048
1049         ent = PRVM_NEXT_EDICT(prog->edicts);
1050         for (e=1 ; e<prog->num_edicts ; e++, ent = PRVM_NEXT_EDICT(ent))
1051                 ent->fields.server->effects = (int)ent->fields.server->effects & ~EF_MUZZLEFLASH;
1052 }
1053
1054 /*
1055 ==================
1056 SV_WriteClientdataToMessage
1057
1058 ==================
1059 */
1060 void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t *msg, int *stats)
1061 {
1062         int             bits;
1063         int             i;
1064         prvm_edict_t    *other;
1065         int             items;
1066         prvm_eval_t     *val;
1067         vec3_t  punchvector;
1068         int             viewzoom;
1069         const char *s;
1070
1071 //
1072 // send a damage message
1073 //
1074         if (ent->fields.server->dmg_take || ent->fields.server->dmg_save)
1075         {
1076                 other = PRVM_PROG_TO_EDICT(ent->fields.server->dmg_inflictor);
1077                 MSG_WriteByte (msg, svc_damage);
1078                 MSG_WriteByte (msg, (int)ent->fields.server->dmg_save);
1079                 MSG_WriteByte (msg, (int)ent->fields.server->dmg_take);
1080                 for (i=0 ; i<3 ; i++)
1081                         MSG_WriteCoord (msg, other->fields.server->origin[i] + 0.5*(other->fields.server->mins[i] + other->fields.server->maxs[i]), sv.protocol);
1082
1083                 ent->fields.server->dmg_take = 0;
1084                 ent->fields.server->dmg_save = 0;
1085         }
1086
1087 //
1088 // send the current viewpos offset from the view entity
1089 //
1090         SV_SetIdealPitch ();            // how much to look up / down ideally
1091
1092 // a fixangle might get lost in a dropped packet.  Oh well.
1093         if(ent->fields.server->fixangle)
1094         {
1095                 // angle fixing was requested by global thinking code...
1096                 // so store the current angles for later use
1097                 memcpy(host_client->fixangle_angles, ent->fields.server->angles, sizeof(host_client->fixangle_angles));
1098                 host_client->fixangle_angles_set = TRUE;
1099
1100                 // and clear fixangle for the next frame
1101                 ent->fields.server->fixangle = 0;
1102         }
1103
1104         if (host_client->fixangle_angles_set)
1105         {
1106                 MSG_WriteByte (msg, svc_setangle);
1107                 for (i=0 ; i < 3 ; i++)
1108                         MSG_WriteAngle (msg, host_client->fixangle_angles[i], sv.protocol);
1109                 host_client->fixangle_angles_set = FALSE;
1110         }
1111
1112         // stuff the sigil bits into the high bits of items for sbar, or else
1113         // mix in items2
1114         val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.items2);
1115         if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE)
1116                 items = (int)ent->fields.server->items | ((int)val->_float << 23);
1117         else
1118                 items = (int)ent->fields.server->items | ((int)prog->globals.server->serverflags << 28);
1119
1120         VectorClear(punchvector);
1121         if ((val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.punchvector)))
1122                 VectorCopy(val->vector, punchvector);
1123
1124         // cache weapon model name and index in client struct to save time
1125         // (this search can be almost 1% of cpu time!)
1126         s = PRVM_GetString(ent->fields.server->weaponmodel);
1127         if (strcmp(s, client->weaponmodel))
1128         {
1129                 strlcpy(client->weaponmodel, s, sizeof(client->weaponmodel));
1130                 client->weaponmodelindex = SV_ModelIndex(s, 1);
1131         }
1132
1133         viewzoom = 255;
1134         if ((val = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.viewzoom)))
1135                 viewzoom = (int)(val->_float * 255.0f);
1136         if (viewzoom == 0)
1137                 viewzoom = 255;
1138
1139         bits = 0;
1140
1141         if ((int)ent->fields.server->flags & FL_ONGROUND)
1142                 bits |= SU_ONGROUND;
1143         if (ent->fields.server->waterlevel >= 2)
1144                 bits |= SU_INWATER;
1145         if (ent->fields.server->idealpitch)
1146                 bits |= SU_IDEALPITCH;
1147
1148         for (i=0 ; i<3 ; i++)
1149         {
1150                 if (ent->fields.server->punchangle[i])
1151                         bits |= (SU_PUNCH1<<i);
1152                 if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE)
1153                         if (punchvector[i])
1154                                 bits |= (SU_PUNCHVEC1<<i);
1155                 if (ent->fields.server->velocity[i])
1156                         bits |= (SU_VELOCITY1<<i);
1157         }
1158
1159         memset(stats, 0, sizeof(int[MAX_CL_STATS]));
1160         stats[STAT_VIEWHEIGHT] = (int)ent->fields.server->view_ofs[2];
1161         stats[STAT_ITEMS] = items;
1162         stats[STAT_WEAPONFRAME] = (int)ent->fields.server->weaponframe;
1163         stats[STAT_ARMOR] = (int)ent->fields.server->armorvalue;
1164         stats[STAT_WEAPON] = client->weaponmodelindex;
1165         stats[STAT_HEALTH] = (int)ent->fields.server->health;
1166         stats[STAT_AMMO] = (int)ent->fields.server->currentammo;
1167         stats[STAT_SHELLS] = (int)ent->fields.server->ammo_shells;
1168         stats[STAT_NAILS] = (int)ent->fields.server->ammo_nails;
1169         stats[STAT_ROCKETS] = (int)ent->fields.server->ammo_rockets;
1170         stats[STAT_CELLS] = (int)ent->fields.server->ammo_cells;
1171         stats[STAT_ACTIVEWEAPON] = (int)ent->fields.server->weapon;
1172         stats[STAT_VIEWZOOM] = viewzoom;
1173         stats[STAT_TOTALSECRETS] = prog->globals.server->total_secrets;
1174         stats[STAT_TOTALMONSTERS] = prog->globals.server->total_monsters;
1175         // the QC bumps these itself by sending svc_'s, so we have to keep them
1176         // zero or they'll be corrected by the engine
1177         //stats[STAT_SECRETS] = prog->globals.server->found_secrets;
1178         //stats[STAT_MONSTERS] = prog->globals.server->killed_monsters;
1179
1180         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
1181         {
1182                 if (stats[STAT_VIEWHEIGHT] != DEFAULT_VIEWHEIGHT) bits |= SU_VIEWHEIGHT;
1183                 bits |= SU_ITEMS;
1184                 if (stats[STAT_WEAPONFRAME]) bits |= SU_WEAPONFRAME;
1185                 if (stats[STAT_ARMOR]) bits |= SU_ARMOR;
1186                 bits |= SU_WEAPON;
1187                 // FIXME: which protocols support this?  does PROTOCOL_DARKPLACES3 support viewzoom?
1188                 if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
1189                         if (viewzoom != 255)
1190                                 bits |= SU_VIEWZOOM;
1191         }
1192
1193         if (bits >= 65536)
1194                 bits |= SU_EXTEND1;
1195         if (bits >= 16777216)
1196                 bits |= SU_EXTEND2;
1197
1198         // send the data
1199         MSG_WriteByte (msg, svc_clientdata);
1200         MSG_WriteShort (msg, bits);
1201         if (bits & SU_EXTEND1)
1202                 MSG_WriteByte(msg, bits >> 16);
1203         if (bits & SU_EXTEND2)
1204                 MSG_WriteByte(msg, bits >> 24);
1205
1206         if (bits & SU_VIEWHEIGHT)
1207                 MSG_WriteChar (msg, stats[STAT_VIEWHEIGHT]);
1208
1209         if (bits & SU_IDEALPITCH)
1210                 MSG_WriteChar (msg, (int)ent->fields.server->idealpitch);
1211
1212         for (i=0 ; i<3 ; i++)
1213         {
1214                 if (bits & (SU_PUNCH1<<i))
1215                 {
1216                         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE)
1217                                 MSG_WriteChar(msg, (int)ent->fields.server->punchangle[i]);
1218                         else
1219                                 MSG_WriteAngle16i(msg, ent->fields.server->punchangle[i]);
1220                 }
1221                 if (bits & (SU_PUNCHVEC1<<i))
1222                 {
1223                         if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1224                                 MSG_WriteCoord16i(msg, punchvector[i]);
1225                         else
1226                                 MSG_WriteCoord32f(msg, punchvector[i]);
1227                 }
1228                 if (bits & (SU_VELOCITY1<<i))
1229                 {
1230                         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1231                                 MSG_WriteChar(msg, (int)(ent->fields.server->velocity[i] * (1.0f / 16.0f)));
1232                         else
1233                                 MSG_WriteCoord32f(msg, ent->fields.server->velocity[i]);
1234                 }
1235         }
1236
1237         if (bits & SU_ITEMS)
1238                 MSG_WriteLong (msg, stats[STAT_ITEMS]);
1239
1240         if (sv.protocol == PROTOCOL_DARKPLACES5)
1241         {
1242                 if (bits & SU_WEAPONFRAME)
1243                         MSG_WriteShort (msg, stats[STAT_WEAPONFRAME]);
1244                 if (bits & SU_ARMOR)
1245                         MSG_WriteShort (msg, stats[STAT_ARMOR]);
1246                 if (bits & SU_WEAPON)
1247                         MSG_WriteShort (msg, stats[STAT_WEAPON]);
1248                 MSG_WriteShort (msg, stats[STAT_HEALTH]);
1249                 MSG_WriteShort (msg, stats[STAT_AMMO]);
1250                 MSG_WriteShort (msg, stats[STAT_SHELLS]);
1251                 MSG_WriteShort (msg, stats[STAT_NAILS]);
1252                 MSG_WriteShort (msg, stats[STAT_ROCKETS]);
1253                 MSG_WriteShort (msg, stats[STAT_CELLS]);
1254                 MSG_WriteShort (msg, stats[STAT_ACTIVEWEAPON]);
1255                 if (bits & SU_VIEWZOOM)
1256                         MSG_WriteShort (msg, bound(0, stats[STAT_VIEWZOOM], 65535));
1257         }
1258         else if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1259         {
1260                 if (bits & SU_WEAPONFRAME)
1261                         MSG_WriteByte (msg, stats[STAT_WEAPONFRAME]);
1262                 if (bits & SU_ARMOR)
1263                         MSG_WriteByte (msg, stats[STAT_ARMOR]);
1264                 if (bits & SU_WEAPON)
1265                         MSG_WriteByte (msg, stats[STAT_WEAPON]);
1266                 MSG_WriteShort (msg, stats[STAT_HEALTH]);
1267                 MSG_WriteByte (msg, stats[STAT_AMMO]);
1268                 MSG_WriteByte (msg, stats[STAT_SHELLS]);
1269                 MSG_WriteByte (msg, stats[STAT_NAILS]);
1270                 MSG_WriteByte (msg, stats[STAT_ROCKETS]);
1271                 MSG_WriteByte (msg, stats[STAT_CELLS]);
1272                 if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_NEXUIZ)
1273                 {
1274                         for (i = 0;i < 32;i++)
1275                                 if (stats[STAT_WEAPON] & (1<<i))
1276                                         break;
1277                         MSG_WriteByte (msg, i);
1278                 }
1279                 else
1280                         MSG_WriteByte (msg, stats[STAT_WEAPON]);
1281                 if (bits & SU_VIEWZOOM)
1282                 {
1283                         if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1284                                 MSG_WriteByte (msg, bound(0, stats[STAT_VIEWZOOM], 255));
1285                         else
1286                                 MSG_WriteShort (msg, bound(0, stats[STAT_VIEWZOOM], 65535));
1287                 }
1288         }
1289 }
1290
1291 /*
1292 =======================
1293 SV_SendClientDatagram
1294 =======================
1295 */
1296 static unsigned char sv_sendclientdatagram_buf[NET_MAXMESSAGE]; // FIXME?
1297 void SV_SendClientDatagram (client_t *client)
1298 {
1299         int rate, maxrate, maxsize, maxsize2, downloadsize;
1300         sizebuf_t msg;
1301         int stats[MAX_CL_STATS];
1302
1303         if (LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) == LHNETADDRESSTYPE_LOOP && !sv_ratelimitlocalplayer.integer)
1304         {
1305                 // for good singleplayer, send huge packets
1306                 maxsize = sizeof(sv_sendclientdatagram_buf);
1307                 maxsize2 = sizeof(sv_sendclientdatagram_buf);
1308         }
1309         else if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1310         {
1311                 // no rate limiting support on older protocols because dp protocols
1312                 // 1-4 kick the client off if they overflow, and quake protocol shows
1313                 // less than the full entity set if rate limited
1314                 maxsize = 1400;
1315                 maxsize2 = 1400;
1316         }
1317         else
1318         {
1319                 // PROTOCOL_DARKPLACES5 and later support packet size limiting of updates
1320                 maxrate = max(NET_MINRATE, sv_maxrate.integer);
1321                 if (sv_maxrate.integer != maxrate)
1322                         Cvar_SetValueQuick(&sv_maxrate, maxrate);
1323
1324                 // this rate limiting does not understand sys_ticrate 0
1325                 // (but no one should be running that on a server!)
1326                 rate = bound(NET_MINRATE, client->rate, maxrate);
1327                 rate = (int)(rate * sys_ticrate.value);
1328                 maxsize = bound(50, rate, 1400);
1329                 maxsize2 = 1400;
1330         }
1331
1332         // while downloading, limit entity updates to half the packet
1333         // (any leftover space will be used for downloading)
1334         if (host_client->download_file)
1335                 maxsize /= 2;
1336
1337         msg.data = sv_sendclientdatagram_buf;
1338         msg.maxsize = maxsize;
1339         msg.cursize = 0;
1340
1341         if (host_client->spawned)
1342         {
1343                 MSG_WriteByte (&msg, svc_time);
1344                 MSG_WriteFloat (&msg, sv.time);
1345
1346                 // add the client specific data to the datagram
1347                 SV_WriteClientdataToMessage (client, client->edict, &msg, stats);
1348                 VM_SV_WriteAutoSentStats (client, client->edict, &msg, stats);
1349                 SV_WriteEntitiesToClient (client, client->edict, &msg, stats);
1350
1351                 // expand packet size to allow effects to go over the rate limit
1352                 // (dropping them is FAR too ugly)
1353                 msg.maxsize = maxsize2;
1354
1355                 // copy the server datagram if there is space
1356                 // FIXME: put in delayed queue of effects to send
1357                 if (sv.datagram.cursize > 0 && msg.cursize + sv.datagram.cursize <= msg.maxsize)
1358                         SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
1359         }
1360         else if (realtime > client->keepalivetime)
1361         {
1362                 // the player isn't totally in the game yet
1363                 // send small keepalive messages if too much time has passed
1364                 msg.maxsize = maxsize2;
1365                 client->keepalivetime = realtime + 5;
1366                 MSG_WriteChar (&msg, svc_nop);
1367         }
1368
1369         msg.maxsize = maxsize2;
1370
1371         // if a download is active, see if there is room to fit some download data
1372         // in this packet
1373         downloadsize = maxsize * 2 - msg.cursize - 7;
1374         if (host_client->download_file && host_client->download_started && downloadsize > 0)
1375         {
1376                 fs_offset_t downloadstart;
1377                 unsigned char data[1400];
1378                 downloadstart = FS_Tell(host_client->download_file);
1379                 downloadsize = min(downloadsize, (int)sizeof(data));
1380                 downloadsize = FS_Read(host_client->download_file, data, downloadsize);
1381                 // note this sends empty messages if at the end of the file, which is
1382                 // necessary to keep the packet loss logic working
1383                 // (the last blocks may be lost and need to be re-sent, and that will
1384                 //  only occur if the client acks the empty end messages, revealing
1385                 //  a gap in the download progress, causing the last blocks to be
1386                 //  sent again)
1387                 MSG_WriteChar (&msg, svc_downloaddata);
1388                 MSG_WriteLong (&msg, downloadstart);
1389                 MSG_WriteShort (&msg, downloadsize);
1390                 if (downloadsize > 0)
1391                         SZ_Write (&msg, data, downloadsize);
1392         }
1393
1394 // send the datagram
1395         NetConn_SendUnreliableMessage (client->netconnection, &msg, sv.protocol);
1396 }
1397
1398 /*
1399 =======================
1400 SV_UpdateToReliableMessages
1401 =======================
1402 */
1403 void SV_UpdateToReliableMessages (void)
1404 {
1405         int i, j;
1406         client_t *client;
1407         prvm_eval_t *val;
1408         const char *name;
1409         const char *model;
1410         const char *skin;
1411
1412 // check for changes to be sent over the reliable streams
1413         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1414         {
1415                 // update the host_client fields we care about according to the entity fields
1416                 host_client->edict = PRVM_EDICT_NUM(i+1);
1417
1418                 // DP_SV_CLIENTNAME
1419                 name = PRVM_GetString(host_client->edict->fields.server->netname);
1420                 if (name == NULL)
1421                         name = "";
1422                 // always point the string back at host_client->name to keep it safe
1423                 strlcpy (host_client->name, name, sizeof (host_client->name));
1424                 host_client->edict->fields.server->netname = PRVM_SetEngineString(host_client->name);
1425                 if (strcmp(host_client->old_name, host_client->name))
1426                 {
1427                         if (host_client->spawned)
1428                                 SV_BroadcastPrintf("%s changed name to %s\n", host_client->old_name, host_client->name);
1429                         strlcpy(host_client->old_name, host_client->name, sizeof(host_client->old_name));
1430                         // send notification to all clients
1431                         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
1432                         MSG_WriteByte (&sv.reliable_datagram, i);
1433                         MSG_WriteString (&sv.reliable_datagram, host_client->name);
1434                 }
1435
1436                 // DP_SV_CLIENTCOLORS
1437                 // this is always found (since it's added by the progs loader)
1438                 if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.clientcolors)))
1439                         host_client->colors = (int)val->_float;
1440                 if (host_client->old_colors != host_client->colors)
1441                 {
1442                         host_client->old_colors = host_client->colors;
1443                         // send notification to all clients
1444                         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
1445                         MSG_WriteByte (&sv.reliable_datagram, i);
1446                         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
1447                 }
1448
1449                 // NEXUIZ_PLAYERMODEL
1450                 if( prog->fieldoffsets.playermodel >= 0 ) {
1451                         model = PRVM_GetString(PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.playermodel)->string);
1452                         if (model == NULL)
1453                                 model = "";
1454                         // always point the string back at host_client->name to keep it safe
1455                         strlcpy (host_client->playermodel, model, sizeof (host_client->playermodel));
1456                         PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.playermodel)->string = PRVM_SetEngineString(host_client->playermodel);
1457                 }
1458
1459                 // NEXUIZ_PLAYERSKIN
1460                 if( prog->fieldoffsets.playerskin >= 0 ) {
1461                         skin = PRVM_GetString(PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.playerskin)->string);
1462                         if (skin == NULL)
1463                                 skin = "";
1464                         // always point the string back at host_client->name to keep it safe
1465                         strlcpy (host_client->playerskin, skin, sizeof (host_client->playerskin));
1466                         PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.playerskin)->string = PRVM_SetEngineString(host_client->playerskin);
1467                 }
1468
1469                 // frags
1470                 host_client->frags = (int)host_client->edict->fields.server->frags;
1471                 if (host_client->old_frags != host_client->frags)
1472                 {
1473                         host_client->old_frags = host_client->frags;
1474                         // send notification to all clients
1475                         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
1476                         MSG_WriteByte (&sv.reliable_datagram, i);
1477                         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
1478                 }
1479         }
1480
1481         for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1482                 if (client->netconnection)
1483                         SZ_Write (&client->netconnection->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1484
1485         SZ_Clear (&sv.reliable_datagram);
1486 }
1487
1488
1489 /*
1490 =======================
1491 SV_SendClientMessages
1492 =======================
1493 */
1494 void SV_SendClientMessages (void)
1495 {
1496         int i, prepared = false;
1497
1498         if (sv.protocol == PROTOCOL_QUAKEWORLD)
1499                 Sys_Error("SV_SendClientMessages: no quakeworld support\n");
1500
1501 // update frags, names, etc
1502         SV_UpdateToReliableMessages();
1503
1504 // build individual updates
1505         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1506         {
1507                 if (!host_client->active)
1508                         continue;
1509                 if (!host_client->netconnection)
1510                         continue;
1511
1512                 if (host_client->netconnection->message.overflowed)
1513                 {
1514                         SV_DropClient (true);   // if the message couldn't send, kick off
1515                         continue;
1516                 }
1517
1518                 if (!prepared)
1519                 {
1520                         prepared = true;
1521                         // only prepare entities once per frame
1522                         SV_PrepareEntitiesForSending();
1523                 }
1524                 SV_SendClientDatagram (host_client);
1525         }
1526
1527 // clear muzzle flashes
1528         SV_CleanupEnts();
1529 }
1530
1531 void SV_StartDownload_f(void)
1532 {
1533         if (host_client->download_file)
1534                 host_client->download_started = true;
1535 }
1536
1537 void SV_Download_f(void)
1538 {
1539         const char *whichpack, *whichpack2, *extension;
1540
1541         if (Cmd_Argc() != 2)
1542         {
1543                 SV_ClientPrintf("usage: download <filename>\n");
1544                 return;
1545         }
1546
1547         if (FS_CheckNastyPath(Cmd_Argv(1), false))
1548         {
1549                 SV_ClientPrintf("Download rejected: nasty filename \"%s\"\n", Cmd_Argv(1));
1550                 return;
1551         }
1552
1553         if (host_client->download_file)
1554         {
1555                 // at this point we'll assume the previous download should be aborted
1556                 Con_DPrintf("Download of %s aborted by %s starting a new download\n", host_client->download_name, host_client->name);
1557                 Host_ClientCommands("\nstopdownload\n");
1558
1559                 // close the file and reset variables
1560                 FS_Close(host_client->download_file);
1561                 host_client->download_file = NULL;
1562                 host_client->download_name[0] = 0;
1563                 host_client->download_expectedposition = 0;
1564                 host_client->download_started = false;
1565         }
1566
1567         if (!sv_allowdownloads.integer)
1568         {
1569                 SV_ClientPrintf("Downloads are disabled on this server\n");
1570                 Host_ClientCommands("\nstopdownload\n");
1571                 return;
1572         }
1573
1574         strlcpy(host_client->download_name, Cmd_Argv(1), sizeof(host_client->download_name));
1575         extension = FS_FileExtension(host_client->download_name);
1576
1577         // host_client is asking to download a specified file
1578         if (developer.integer >= 100)
1579                 Con_Printf("Download request for %s by %s\n", host_client->download_name, host_client->name);
1580
1581         if (!FS_FileExists(host_client->download_name))
1582         {
1583                 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);
1584                 Host_ClientCommands("\nstopdownload\n");
1585                 return;
1586         }
1587
1588         // check if the user is trying to download part of registered Quake(r)
1589         whichpack = FS_WhichPack(host_client->download_name);
1590         whichpack2 = FS_WhichPack("gfx/pop.lmp");
1591         if ((whichpack && whichpack2 && !strcasecmp(whichpack, whichpack2)) || FS_IsRegisteredQuakePack(host_client->download_name))
1592         {
1593                 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);
1594                 Host_ClientCommands("\nstopdownload\n");
1595                 return;
1596         }
1597
1598         // check if the server has forbidden archive downloads entirely
1599         if (!sv_allowdownloads_inarchive.integer)
1600         {
1601                 whichpack = FS_WhichPack(host_client->download_name);
1602                 if (whichpack)
1603                 {
1604                         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);
1605                         Host_ClientCommands("\nstopdownload\n");
1606                         return;
1607                 }
1608         }
1609
1610         if (!sv_allowdownloads_config.integer)
1611         {
1612                 if (!strcasecmp(extension, "cfg"))
1613                 {
1614                         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);
1615                         Host_ClientCommands("\nstopdownload\n");
1616                         return;
1617                 }
1618         }
1619
1620         if (!sv_allowdownloads_dlcache.integer)
1621         {
1622                 if (!strncasecmp(host_client->download_name, "dlcache/", 8))
1623                 {
1624                         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);
1625                         Host_ClientCommands("\nstopdownload\n");
1626                         return;
1627                 }
1628         }
1629
1630         if (!sv_allowdownloads_archive.integer)
1631         {
1632                 if (!strcasecmp(extension, "pak") || !strcasecmp(extension, "pk3"))
1633                 {
1634                         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);
1635                         Host_ClientCommands("\nstopdownload\n");
1636                         return;
1637                 }
1638         }
1639
1640         host_client->download_file = FS_Open(host_client->download_name, "rb", true, false);
1641         if (!host_client->download_file)
1642         {
1643                 SV_ClientPrintf("Download rejected: server could not open the file \"%s\"\n", host_client->download_name);
1644                 Host_ClientCommands("\nstopdownload\n");
1645                 return;
1646         }
1647
1648         if (FS_FileSize(host_client->download_file) > 1<<30)
1649         {
1650                 SV_ClientPrintf("Download rejected: file \"%s\" is very large\n", host_client->download_name);
1651                 Host_ClientCommands("\nstopdownload\n");
1652                 FS_Close(host_client->download_file);
1653                 host_client->download_file = NULL;
1654                 return;
1655         }
1656
1657         Con_DPrintf("Downloading %s to %s\n", host_client->download_name, host_client->name);
1658
1659         Host_ClientCommands("\ncl_downloadbegin %i %s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name);
1660
1661         host_client->download_expectedposition = 0;
1662         host_client->download_started = false;
1663
1664         // the rest of the download process is handled in SV_SendClientDatagram
1665         // and other code dealing with svc_downloaddata and clc_ackdownloaddata
1666         //
1667         // no svc_downloaddata messages will be sent until sv_startdownload is
1668         // sent by the client
1669 }
1670
1671 /*
1672 ==============================================================================
1673
1674 SERVER SPAWNING
1675
1676 ==============================================================================
1677 */
1678
1679 /*
1680 ================
1681 SV_ModelIndex
1682
1683 ================
1684 */
1685 int SV_ModelIndex(const char *s, int precachemode)
1686 {
1687         int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE) ? 256 : MAX_MODELS);
1688         char filename[MAX_QPATH];
1689         if (!s || !*s)
1690                 return 0;
1691         // testing
1692         //if (precachemode == 2)
1693         //      return 0;
1694         strlcpy(filename, s, sizeof(filename));
1695         for (i = 2;i < limit;i++)
1696         {
1697                 if (!sv.model_precache[i][0])
1698                 {
1699                         if (precachemode)
1700                         {
1701                                 if (sv.state != ss_loading && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5))
1702                                 {
1703                                         Con_Printf("SV_ModelIndex(\"%s\"): precache_model can only be done in spawn functions\n", filename);
1704                                         return 0;
1705                                 }
1706                                 if (precachemode == 1)
1707                                         Con_Printf("SV_ModelIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
1708                                 strlcpy(sv.model_precache[i], filename, sizeof(sv.model_precache[i]));
1709                                 sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, false);
1710                                 if (sv.state != ss_loading)
1711                                 {
1712                                         MSG_WriteByte(&sv.reliable_datagram, svc_precache);
1713                                         MSG_WriteShort(&sv.reliable_datagram, i);
1714                                         MSG_WriteString(&sv.reliable_datagram, filename);
1715                                 }
1716                                 return i;
1717                         }
1718                         Con_Printf("SV_ModelIndex(\"%s\"): not precached\n", filename);
1719                         return 0;
1720                 }
1721                 if (!strcmp(sv.model_precache[i], filename))
1722                         return i;
1723         }
1724         Con_Printf("SV_ModelIndex(\"%s\"): i (%i) == MAX_MODELS (%i)\n", filename, i, MAX_MODELS);
1725         return 0;
1726 }
1727
1728 /*
1729 ================
1730 SV_SoundIndex
1731
1732 ================
1733 */
1734 int SV_SoundIndex(const char *s, int precachemode)
1735 {
1736         int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE) ? 256 : MAX_SOUNDS);
1737         char filename[MAX_QPATH];
1738         if (!s || !*s)
1739                 return 0;
1740         // testing
1741         //if (precachemode == 2)
1742         //      return 0;
1743         strlcpy(filename, s, sizeof(filename));
1744         for (i = 1;i < limit;i++)
1745         {
1746                 if (!sv.sound_precache[i][0])
1747                 {
1748                         if (precachemode)
1749                         {
1750                                 if (sv.state != ss_loading && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5))
1751                                 {
1752                                         Con_Printf("SV_SoundIndex(\"%s\"): precache_sound can only be done in spawn functions\n", filename);
1753                                         return 0;
1754                                 }
1755                                 if (precachemode == 1)
1756                                         Con_Printf("SV_SoundIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
1757                                 strlcpy(sv.sound_precache[i], filename, sizeof(sv.sound_precache[i]));
1758                                 if (sv.state != ss_loading)
1759                                 {
1760                                         MSG_WriteByte(&sv.reliable_datagram, svc_precache);
1761                                         MSG_WriteShort(&sv.reliable_datagram, i + 32768);
1762                                         MSG_WriteString(&sv.reliable_datagram, filename);
1763                                 }
1764                                 return i;
1765                         }
1766                         Con_Printf("SV_SoundIndex(\"%s\"): not precached\n", filename);
1767                         return 0;
1768                 }
1769                 if (!strcmp(sv.sound_precache[i], filename))
1770                         return i;
1771         }
1772         Con_Printf("SV_SoundIndex(\"%s\"): i (%i) == MAX_SOUNDS (%i)\n", filename, i, MAX_SOUNDS);
1773         return 0;
1774 }
1775
1776 // MUST match effectnameindex_t in client.h
1777 static const char *standardeffectnames[EFFECT_TOTAL] =
1778 {
1779         "",
1780         "TE_GUNSHOT",
1781         "TE_GUNSHOTQUAD",
1782         "TE_SPIKE",
1783         "TE_SPIKEQUAD",
1784         "TE_SUPERSPIKE",
1785         "TE_SUPERSPIKEQUAD",
1786         "TE_WIZSPIKE",
1787         "TE_KNIGHTSPIKE",
1788         "TE_EXPLOSION",
1789         "TE_EXPLOSIONQUAD",
1790         "TE_TAREXPLOSION",
1791         "TE_TELEPORT",
1792         "TE_LAVASPLASH",
1793         "TE_SMALLFLASH",
1794         "TE_FLAMEJET",
1795         "EF_FLAME",
1796         "TE_BLOOD",
1797         "TE_SPARK",
1798         "TE_PLASMABURN",
1799         "TE_TEI_G3",
1800         "TE_TEI_SMOKE",
1801         "TE_TEI_BIGEXPLOSION",
1802         "TE_TEI_PLASMAHIT",
1803         "EF_STARDUST",
1804         "TR_ROCKET",
1805         "TR_GRENADE",
1806         "TR_BLOOD",
1807         "TR_WIZSPIKE",
1808         "TR_SLIGHTBLOOD",
1809         "TR_KNIGHTSPIKE",
1810         "TR_VORESPIKE",
1811         "TR_NEHAHRASMOKE",
1812         "TR_NEXUIZPLASMA",
1813         "TR_GLOWTRAIL",
1814         "SVC_PARTICLE"
1815 };
1816
1817 /*
1818 ================
1819 SV_ParticleEffectIndex
1820
1821 ================
1822 */
1823 int SV_ParticleEffectIndex(const char *name)
1824 {
1825         int i, argc, linenumber, effectnameindex;
1826         fs_offset_t filesize;
1827         unsigned char *filedata;
1828         const char *text, *textstart, *textend;
1829         char argv[16][1024];
1830         if (!sv.particleeffectnamesloaded)
1831         {
1832                 sv.particleeffectnamesloaded = true;
1833                 memset(sv.particleeffectname, 0, sizeof(sv.particleeffectname));
1834                 for (i = 0;i < EFFECT_TOTAL;i++)
1835                         strlcpy(sv.particleeffectname[i], standardeffectnames[i], sizeof(sv.particleeffectname[i]));
1836                 filedata = FS_LoadFile("effectinfo.txt", tempmempool, true, &filesize);
1837                 if (filedata)
1838                 {
1839                         textstart = (const char *)filedata;
1840                         textend = (const char *)filedata + filesize;
1841                         text = textstart;
1842                         for (linenumber = 1;;linenumber++)
1843                         {
1844                                 argc = 0;
1845                                 for (;;)
1846                                 {
1847                                         if (!COM_ParseToken(&text, true) || !strcmp(com_token, "\n"))
1848                                                 break;
1849                                         if (argc < 16)
1850                                         {
1851                                                 strlcpy(argv[argc], com_token, sizeof(argv[argc]));
1852                                                 argc++;
1853                                         }
1854                                 }
1855                                 if (com_token[0] == 0)
1856                                         break; // if the loop exited and it's not a \n, it's EOF
1857                                 if (argc < 1)
1858                                         continue;
1859                                 if (!strcmp(argv[0], "effect"))
1860                                 {
1861                                         if (argc == 2)
1862                                         {
1863                                                 for (effectnameindex = 1;effectnameindex < SV_MAX_PARTICLEEFFECTNAME;effectnameindex++)
1864                                                 {
1865                                                         if (sv.particleeffectname[effectnameindex][0])
1866                                                         {
1867                                                                 if (!strcmp(sv.particleeffectname[effectnameindex], argv[1]))
1868                                                                         break;
1869                                                         }
1870                                                         else
1871                                                         {
1872                                                                 strlcpy(sv.particleeffectname[effectnameindex], argv[1], sizeof(sv.particleeffectname[effectnameindex]));
1873                                                                 break;
1874                                                         }
1875                                                 }
1876                                                 // if we run out of names, abort
1877                                                 if (effectnameindex == SV_MAX_PARTICLEEFFECTNAME)
1878                                                 {
1879                                                         Con_Printf("effectinfo.txt:%i: too many effects!\n", linenumber);
1880                                                         break;
1881                                                 }
1882                                         }
1883                                 }
1884                         }
1885                         Mem_Free(filedata);
1886                 }
1887         }
1888         // search for the name
1889         for (effectnameindex = 1;effectnameindex < SV_MAX_PARTICLEEFFECTNAME && sv.particleeffectname[effectnameindex][0];effectnameindex++)
1890                 if (!strcmp(sv.particleeffectname[effectnameindex], name))
1891                         return effectnameindex;
1892         // return 0 if we couldn't find it
1893         return 0;
1894 }
1895
1896 /*
1897 ================
1898 SV_CreateBaseline
1899
1900 ================
1901 */
1902 void SV_CreateBaseline (void)
1903 {
1904         int i, entnum, large;
1905         prvm_edict_t *svent;
1906
1907         // LordHavoc: clear *all* states (note just active ones)
1908         for (entnum = 0;entnum < prog->max_edicts;entnum++)
1909         {
1910                 // get the current server version
1911                 svent = PRVM_EDICT_NUM(entnum);
1912
1913                 // LordHavoc: always clear state values, whether the entity is in use or not
1914                 svent->priv.server->baseline = defaultstate;
1915
1916                 if (svent->priv.server->free)
1917                         continue;
1918                 if (entnum > svs.maxclients && !svent->fields.server->modelindex)
1919                         continue;
1920
1921                 // create entity baseline
1922                 VectorCopy (svent->fields.server->origin, svent->priv.server->baseline.origin);
1923                 VectorCopy (svent->fields.server->angles, svent->priv.server->baseline.angles);
1924                 svent->priv.server->baseline.frame = (int)svent->fields.server->frame;
1925                 svent->priv.server->baseline.skin = (int)svent->fields.server->skin;
1926                 if (entnum > 0 && entnum <= svs.maxclients)
1927                 {
1928                         svent->priv.server->baseline.colormap = entnum;
1929                         svent->priv.server->baseline.modelindex = SV_ModelIndex("progs/player.mdl", 1);
1930                 }
1931                 else
1932                 {
1933                         svent->priv.server->baseline.colormap = 0;
1934                         svent->priv.server->baseline.modelindex = (int)svent->fields.server->modelindex;
1935                 }
1936
1937                 large = false;
1938                 if (svent->priv.server->baseline.modelindex & 0xFF00 || svent->priv.server->baseline.frame & 0xFF00)
1939                         large = true;
1940
1941                 // add to the message
1942                 if (large)
1943                         MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1944                 else
1945                         MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1946                 MSG_WriteShort (&sv.signon, entnum);
1947
1948                 if (large)
1949                 {
1950                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.modelindex);
1951                         MSG_WriteShort (&sv.signon, svent->priv.server->baseline.frame);
1952                 }
1953                 else
1954                 {
1955                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.modelindex);
1956                         MSG_WriteByte (&sv.signon, svent->priv.server->baseline.frame);
1957                 }
1958                 MSG_WriteByte (&sv.signon, svent->priv.server->baseline.colormap);
1959                 MSG_WriteByte (&sv.signon, svent->priv.server->baseline.skin);
1960                 for (i=0 ; i<3 ; i++)
1961                 {
1962                         MSG_WriteCoord(&sv.signon, svent->priv.server->baseline.origin[i], sv.protocol);
1963                         MSG_WriteAngle(&sv.signon, svent->priv.server->baseline.angles[i], sv.protocol);
1964                 }
1965         }
1966 }
1967
1968
1969 /*
1970 ================
1971 SV_SaveSpawnparms
1972
1973 Grabs the current state of each client for saving across the
1974 transition to another level
1975 ================
1976 */
1977 void SV_SaveSpawnparms (void)
1978 {
1979         int             i, j;
1980
1981         svs.serverflags = (int)prog->globals.server->serverflags;
1982
1983         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1984         {
1985                 if (!host_client->active)
1986                         continue;
1987
1988         // call the progs to get default spawn parms for the new client
1989                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
1990                 PRVM_ExecuteProgram (prog->globals.server->SetChangeParms, "QC function SetChangeParms is missing");
1991                 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1992                         host_client->spawn_parms[j] = (&prog->globals.server->parm1)[j];
1993         }
1994 }
1995 /*
1996 void SV_IncreaseEdicts(void)
1997 {
1998         int i;
1999         prvm_edict_t *ent;
2000         int oldmax_edicts = prog->max_edicts;
2001         void *oldedictsengineprivate = prog->edictprivate;
2002         void *oldedictsfields = prog->edictsfields;
2003         void *oldmoved_edicts = sv.moved_edicts;
2004
2005         if (prog->max_edicts >= MAX_EDICTS)
2006                 return;
2007
2008         // links don't survive the transition, so unlink everything
2009         for (i = 0, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
2010         {
2011                 if (!ent->priv.server->free)
2012                         SV_UnlinkEdict(prog->edicts + i);
2013                 memset(&ent->priv.server->areagrid, 0, sizeof(ent->priv.server->areagrid));
2014         }
2015         World_Clear(&sv.world);
2016
2017         prog->max_edicts   = min(prog->max_edicts + 256, MAX_EDICTS);
2018         prog->edictprivate = PR_Alloc(prog->max_edicts * sizeof(edict_engineprivate_t));
2019         prog->edictsfields = PR_Alloc(prog->max_edicts * prog->edict_size);
2020         sv.moved_edicts = PR_Alloc(prog->max_edicts * sizeof(prvm_edict_t *));
2021
2022         memcpy(prog->edictprivate, oldedictsengineprivate, oldmax_edicts * sizeof(edict_engineprivate_t));
2023         memcpy(prog->edictsfields, oldedictsfields, oldmax_edicts * prog->edict_size);
2024
2025         for (i = 0, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
2026         {
2027                 ent->priv.vp = (unsigned char*) prog->edictprivate + i * prog->edictprivate_size;
2028                 ent->fields.server = (void *)((unsigned char *)prog->edictsfields + i * prog->edict_size);
2029                 // link every entity except world
2030                 if (!ent->priv.server->free)
2031                         SV_LinkEdict(ent, false);
2032         }
2033
2034         PR_Free(oldedictsengineprivate);
2035         PR_Free(oldedictsfields);
2036         PR_Free(oldmoved_edicts);
2037 }*/
2038
2039 /*
2040 ================
2041 SV_SpawnServer
2042
2043 This is called at the start of each level
2044 ================
2045 */
2046 extern float            scr_centertime_off;
2047
2048 void SV_SpawnServer (const char *server)
2049 {
2050         prvm_edict_t *ent;
2051         int i;
2052         char *entities;
2053         model_t *worldmodel;
2054         char modelname[sizeof(sv.modelname)];
2055
2056         Con_DPrintf("SpawnServer: %s\n", server);
2057
2058         if (cls.state != ca_dedicated)
2059                 SCR_BeginLoadingPlaque();
2060
2061         dpsnprintf (modelname, sizeof(modelname), "maps/%s.bsp", server);
2062         worldmodel = Mod_ForName(modelname, false, true, true);
2063         if (!worldmodel || !worldmodel->TraceBox)
2064         {
2065                 Con_Printf("Couldn't load map %s\n", modelname);
2066                 return;
2067         }
2068
2069         // let's not have any servers with no name
2070         if (hostname.string[0] == 0)
2071                 Cvar_Set ("hostname", "UNNAMED");
2072         scr_centertime_off = 0;
2073
2074         svs.changelevel_issued = false;         // now safe to issue another
2075
2076         // make the map a required file for clients
2077         Curl_ClearRequirements();
2078         Curl_RequireFile(modelname);
2079
2080 //
2081 // tell all connected clients that we are going to a new level
2082 //
2083         if (sv.active)
2084         {
2085                 client_t *client;
2086                 for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
2087                 {
2088                         if (client->netconnection)
2089                         {
2090                                 MSG_WriteByte(&client->netconnection->message, svc_stufftext);
2091                                 MSG_WriteString(&client->netconnection->message, "reconnect\n");
2092                         }
2093                 }
2094         }
2095         else
2096         {
2097                 // open server port
2098                 NetConn_OpenServerPorts(true);
2099         }
2100
2101 //
2102 // make cvars consistant
2103 //
2104         if (coop.integer)
2105                 Cvar_SetValue ("deathmatch", 0);
2106         // LordHavoc: it can be useful to have skills outside the range 0-3...
2107         //current_skill = bound(0, (int)(skill.value + 0.5), 3);
2108         //Cvar_SetValue ("skill", (float)current_skill);
2109         current_skill = (int)(skill.value + 0.5);
2110
2111 //
2112 // set up the new server
2113 //
2114         memset (&sv, 0, sizeof(sv));
2115         // if running a local client, make sure it doesn't try to access the last
2116         // level's data which is no longer valiud
2117         cls.signon = 0;
2118
2119         if(*sv_random_seed.string)
2120         {
2121                 srand(sv_random_seed.integer);
2122                 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);
2123         }
2124
2125         SV_VM_Setup();
2126
2127         sv.active = true;
2128
2129         strlcpy (sv.name, server, sizeof (sv.name));
2130
2131         sv.protocol = Protocol_EnumForName(sv_protocolname.string);
2132         if (sv.protocol == PROTOCOL_UNKNOWN)
2133         {
2134                 char buffer[1024];
2135                 Protocol_Names(buffer, sizeof(buffer));
2136                 Con_Printf("Unknown sv_protocolname \"%s\", valid values are:\n%s\n", sv_protocolname.string, buffer);
2137                 sv.protocol = PROTOCOL_QUAKE;
2138         }
2139
2140         SV_VM_Begin();
2141
2142 // load progs to get entity field count
2143         //PR_LoadProgs ( sv_progs.string );
2144
2145         // allocate server memory
2146         /*// start out with just enough room for clients and a reasonable estimate of entities
2147         prog->max_edicts = max(svs.maxclients + 1, 512);
2148         prog->max_edicts = min(prog->max_edicts, MAX_EDICTS);
2149
2150         // prvm_edict_t structures (hidden from progs)
2151         prog->edicts = PR_Alloc(MAX_EDICTS * sizeof(prvm_edict_t));
2152         // engine private structures (hidden from progs)
2153         prog->edictprivate = PR_Alloc(prog->max_edicts * sizeof(edict_engineprivate_t));
2154         // progs fields, often accessed by server
2155         prog->edictsfields = PR_Alloc(prog->max_edicts * prog->edict_size);*/
2156         // used by PushMove to move back pushed entities
2157         sv.moved_edicts = (prvm_edict_t **)PRVM_Alloc(prog->max_edicts * sizeof(prvm_edict_t *));
2158         /*for (i = 0;i < prog->max_edicts;i++)
2159         {
2160                 ent = prog->edicts + i;
2161                 ent->priv.vp = (unsigned char*) prog->edictprivate + i * prog->edictprivate_size;
2162                 ent->fields.server = (void *)((unsigned char *)prog->edictsfields + i * prog->edict_size);
2163         }*/
2164
2165         // reset client csqc entity versions right away.
2166         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2167                 EntityFrameCSQC_InitClientVersions(i, true);
2168
2169         sv.datagram.maxsize = sizeof(sv.datagram_buf);
2170         sv.datagram.cursize = 0;
2171         sv.datagram.data = sv.datagram_buf;
2172
2173         sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
2174         sv.reliable_datagram.cursize = 0;
2175         sv.reliable_datagram.data = sv.reliable_datagram_buf;
2176
2177         sv.signon.maxsize = sizeof(sv.signon_buf);
2178         sv.signon.cursize = 0;
2179         sv.signon.data = sv.signon_buf;
2180
2181 // leave slots at start for clients only
2182         //prog->num_edicts = svs.maxclients+1;
2183
2184         sv.state = ss_loading;
2185         prog->allowworldwrites = true;
2186         sv.paused = false;
2187
2188         prog->globals.server->time = sv.time = 1.0;
2189
2190         Mod_ClearUsed();
2191         worldmodel->used = true;
2192
2193         strlcpy (sv.name, server, sizeof (sv.name));
2194         strlcpy(sv.modelname, modelname, sizeof(sv.modelname));
2195         sv.worldmodel = worldmodel;
2196         sv.models[1] = sv.worldmodel;
2197
2198 //
2199 // clear world interaction links
2200 //
2201         VectorCopy(sv.worldmodel->normalmins, sv.world.areagrid_mins);
2202         VectorCopy(sv.worldmodel->normalmaxs, sv.world.areagrid_maxs);
2203         World_Clear(&sv.world);
2204
2205         strlcpy(sv.sound_precache[0], "", sizeof(sv.sound_precache[0]));
2206
2207         strlcpy(sv.model_precache[0], "", sizeof(sv.model_precache[0]));
2208         strlcpy(sv.model_precache[1], sv.modelname, sizeof(sv.model_precache[1]));
2209         for (i = 1;i < sv.worldmodel->brush.numsubmodels;i++)
2210         {
2211                 dpsnprintf(sv.model_precache[i+1], sizeof(sv.model_precache[i+1]), "*%i", i);
2212                 sv.models[i+1] = Mod_ForName (sv.model_precache[i+1], false, false, false);
2213         }
2214
2215 //
2216 // load the rest of the entities
2217 //
2218         // AK possible hack since num_edicts is still 0
2219         ent = PRVM_EDICT_NUM(0);
2220         memset (ent->fields.server, 0, prog->progs->entityfields * 4);
2221         ent->priv.server->free = false;
2222         ent->fields.server->model = PRVM_SetEngineString(sv.modelname);
2223         ent->fields.server->modelindex = 1;             // world model
2224         ent->fields.server->solid = SOLID_BSP;
2225         ent->fields.server->movetype = MOVETYPE_PUSH;
2226         VectorCopy(sv.worldmodel->normalmins, ent->fields.server->mins);
2227         VectorCopy(sv.worldmodel->normalmaxs, ent->fields.server->maxs);
2228         VectorCopy(sv.worldmodel->normalmins, ent->fields.server->absmin);
2229         VectorCopy(sv.worldmodel->normalmaxs, ent->fields.server->absmax);
2230
2231         if (coop.value)
2232                 prog->globals.server->coop = coop.integer;
2233         else
2234                 prog->globals.server->deathmatch = deathmatch.integer;
2235
2236         prog->globals.server->mapname = PRVM_SetEngineString(sv.name);
2237
2238 // serverflags are for cross level information (sigils)
2239         prog->globals.server->serverflags = svs.serverflags;
2240
2241         // we need to reset the spawned flag on all connected clients here so that
2242         // their thinks don't run during startup (before PutClientInServer)
2243         // we also need to set up the client entities now
2244         // and we need to set the ->edict pointers to point into the progs edicts
2245         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2246         {
2247                 host_client->spawned = false;
2248                 host_client->edict = PRVM_EDICT_NUM(i + 1);
2249                 PRVM_ED_ClearEdict(host_client->edict);
2250         }
2251
2252         // load replacement entity file if found
2253         if (sv_entpatch.integer && (entities = (char *)FS_LoadFile(va("maps/%s.ent", sv.name), tempmempool, true, NULL)))
2254         {
2255                 Con_Printf("Loaded maps/%s.ent\n", sv.name);
2256                 PRVM_ED_LoadFromFile (entities);
2257                 Mem_Free(entities);
2258         }
2259         else
2260                 PRVM_ED_LoadFromFile (sv.worldmodel->brush.entities);
2261
2262
2263         // LordHavoc: clear world angles (to fix e3m3.bsp)
2264         VectorClear(prog->edicts->fields.server->angles);
2265
2266 // all setup is completed, any further precache statements are errors
2267         sv.state = ss_active;
2268         prog->allowworldwrites = false;
2269
2270 // run two frames to allow everything to settle
2271         for (i = 0;i < 2;i++)
2272         {
2273                 sv.frametime = 0.1;
2274                 SV_Physics ();
2275         }
2276
2277         Mod_PurgeUnused();
2278
2279 // create a baseline for more efficient communications
2280         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE)
2281                 SV_CreateBaseline ();
2282
2283 // send serverinfo to all connected clients, and set up botclients coming back from a level change
2284         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2285         {
2286                 if (!host_client->active)
2287                         continue;
2288                 if (host_client->netconnection)
2289                         SV_SendServerinfo(host_client);
2290                 else
2291                 {
2292                         int j;
2293                         // if client is a botclient coming from a level change, we need to
2294                         // set up client info that normally requires networking
2295
2296                         // copy spawn parms out of the client_t
2297                         for (j=0 ; j< NUM_SPAWN_PARMS ; j++)
2298                                 (&prog->globals.server->parm1)[j] = host_client->spawn_parms[j];
2299
2300                         // call the spawn function
2301                         host_client->clientconnectcalled = true;
2302                         prog->globals.server->time = sv.time;
2303                         prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
2304                         PRVM_ExecuteProgram (prog->globals.server->ClientConnect, "QC function ClientConnect is missing");
2305                         PRVM_ExecuteProgram (prog->globals.server->PutClientInServer, "QC function PutClientInServer is missing");
2306                         host_client->spawned = true;
2307                 }
2308         }
2309
2310         Con_DPrint("Server spawned.\n");
2311         NetConn_Heartbeat (2);
2312
2313         SV_VM_End();
2314 }
2315
2316 /////////////////////////////////////////////////////
2317 // SV VM stuff
2318
2319 void SV_VM_CB_BeginIncreaseEdicts(void)
2320 {
2321         int i;
2322         prvm_edict_t *ent;
2323
2324         PRVM_Free( sv.moved_edicts );
2325         sv.moved_edicts = (prvm_edict_t **)PRVM_Alloc(prog->max_edicts * sizeof(prvm_edict_t *));
2326
2327         // links don't survive the transition, so unlink everything
2328         for (i = 0, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
2329         {
2330                 if (!ent->priv.server->free)
2331                         World_UnlinkEdict(prog->edicts + i);
2332                 memset(&ent->priv.server->areagrid, 0, sizeof(ent->priv.server->areagrid));
2333         }
2334         World_Clear(&sv.world);
2335 }
2336
2337 void SV_VM_CB_EndIncreaseEdicts(void)
2338 {
2339         int i;
2340         prvm_edict_t *ent;
2341
2342         // link every entity except world
2343         for (i = 1, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
2344                 if (!ent->priv.server->free)
2345                         SV_LinkEdict(ent, false);
2346 }
2347
2348 void SV_VM_CB_InitEdict(prvm_edict_t *e)
2349 {
2350         // LordHavoc: for consistency set these here
2351         int num = PRVM_NUM_FOR_EDICT(e) - 1;
2352
2353         e->priv.server->move = false; // don't move on first frame
2354
2355         if (num >= 0 && num < svs.maxclients)
2356         {
2357                 prvm_eval_t *val;
2358                 // set colormap and team on newly created player entity
2359                 e->fields.server->colormap = num + 1;
2360                 e->fields.server->team = (svs.clients[num].colors & 15) + 1;
2361                 // set netname/clientcolors back to client values so that
2362                 // DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS will not immediately
2363                 // reset them
2364                 e->fields.server->netname = PRVM_SetEngineString(svs.clients[num].name);
2365                 if ((val = PRVM_EDICTFIELDVALUE(e, prog->fieldoffsets.clientcolors)))
2366                         val->_float = svs.clients[num].colors;
2367                 // NEXUIZ_PLAYERMODEL and NEXUIZ_PLAYERSKIN
2368                 if( prog->fieldoffsets.playermodel >= 0 )
2369                         PRVM_EDICTFIELDVALUE(e, prog->fieldoffsets.playermodel)->string = PRVM_SetEngineString(svs.clients[num].playermodel);
2370                 if( prog->fieldoffsets.playerskin >= 0 )
2371                         PRVM_EDICTFIELDVALUE(e, prog->fieldoffsets.playerskin)->string = PRVM_SetEngineString(svs.clients[num].playerskin);
2372         }
2373 }
2374
2375 void SV_VM_CB_FreeEdict(prvm_edict_t *ed)
2376 {
2377         World_UnlinkEdict(ed);          // unlink from world bsp
2378
2379         ed->fields.server->model = 0;
2380         ed->fields.server->takedamage = 0;
2381         ed->fields.server->modelindex = 0;
2382         ed->fields.server->colormap = 0;
2383         ed->fields.server->skin = 0;
2384         ed->fields.server->frame = 0;
2385         VectorClear(ed->fields.server->origin);
2386         VectorClear(ed->fields.server->angles);
2387         ed->fields.server->nextthink = -1;
2388         ed->fields.server->solid = 0;
2389 }
2390
2391 void SV_VM_CB_CountEdicts(void)
2392 {
2393         int             i;
2394         prvm_edict_t    *ent;
2395         int             active, models, solid, step;
2396
2397         active = models = solid = step = 0;
2398         for (i=0 ; i<prog->num_edicts ; i++)
2399         {
2400                 ent = PRVM_EDICT_NUM(i);
2401                 if (ent->priv.server->free)
2402                         continue;
2403                 active++;
2404                 if (ent->fields.server->solid)
2405                         solid++;
2406                 if (ent->fields.server->model)
2407                         models++;
2408                 if (ent->fields.server->movetype == MOVETYPE_STEP)
2409                         step++;
2410         }
2411
2412         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
2413         Con_Printf("active    :%3i\n", active);
2414         Con_Printf("view      :%3i\n", models);
2415         Con_Printf("touch     :%3i\n", solid);
2416         Con_Printf("step      :%3i\n", step);
2417 }
2418
2419 qboolean SV_VM_CB_LoadEdict(prvm_edict_t *ent)
2420 {
2421         // remove things from different skill levels or deathmatch
2422         if (gamemode != GAME_TRANSFUSION) //Transfusion does this in QC
2423         {
2424                 if (deathmatch.integer)
2425                 {
2426                         if (((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_DEATHMATCH))
2427                         {
2428                                 return false;
2429                         }
2430                 }
2431                 else if ((current_skill <= 0 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_EASY  ))
2432                         || (current_skill == 1 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_MEDIUM))
2433                         || (current_skill >= 2 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_HARD  )))
2434                 {
2435                         return false;
2436                 }
2437         }
2438         return true;
2439 }
2440
2441 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)"};
2442 cvar_t nomonsters = {0, "nomonsters", "0", "unused cvar in quake, can be used by mods"};
2443 cvar_t gamecfg = {0, "gamecfg", "0", "unused cvar in quake, can be used by mods"};
2444 cvar_t scratch1 = {0, "scratch1", "0", "unused cvar in quake, can be used by mods"};
2445 cvar_t scratch2 = {0,"scratch2", "0", "unused cvar in quake, can be used by mods"};
2446 cvar_t scratch3 = {0, "scratch3", "0", "unused cvar in quake, can be used by mods"};
2447 cvar_t scratch4 = {0, "scratch4", "0", "unused cvar in quake, can be used by mods"};
2448 cvar_t savedgamecfg = {CVAR_SAVE, "savedgamecfg", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
2449 cvar_t saved1 = {CVAR_SAVE, "saved1", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
2450 cvar_t saved2 = {CVAR_SAVE, "saved2", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
2451 cvar_t saved3 = {CVAR_SAVE, "saved3", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
2452 cvar_t saved4 = {CVAR_SAVE, "saved4", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
2453 cvar_t nehx00 = {0, "nehx00", "0", "nehahra data storage cvar (used in singleplayer)"};
2454 cvar_t nehx01 = {0, "nehx01", "0", "nehahra data storage cvar (used in singleplayer)"};
2455 cvar_t nehx02 = {0, "nehx02", "0", "nehahra data storage cvar (used in singleplayer)"};
2456 cvar_t nehx03 = {0, "nehx03", "0", "nehahra data storage cvar (used in singleplayer)"};
2457 cvar_t nehx04 = {0, "nehx04", "0", "nehahra data storage cvar (used in singleplayer)"};
2458 cvar_t nehx05 = {0, "nehx05", "0", "nehahra data storage cvar (used in singleplayer)"};
2459 cvar_t nehx06 = {0, "nehx06", "0", "nehahra data storage cvar (used in singleplayer)"};
2460 cvar_t nehx07 = {0, "nehx07", "0", "nehahra data storage cvar (used in singleplayer)"};
2461 cvar_t nehx08 = {0, "nehx08", "0", "nehahra data storage cvar (used in singleplayer)"};
2462 cvar_t nehx09 = {0, "nehx09", "0", "nehahra data storage cvar (used in singleplayer)"};
2463 cvar_t nehx10 = {0, "nehx10", "0", "nehahra data storage cvar (used in singleplayer)"};
2464 cvar_t nehx11 = {0, "nehx11", "0", "nehahra data storage cvar (used in singleplayer)"};
2465 cvar_t nehx12 = {0, "nehx12", "0", "nehahra data storage cvar (used in singleplayer)"};
2466 cvar_t nehx13 = {0, "nehx13", "0", "nehahra data storage cvar (used in singleplayer)"};
2467 cvar_t nehx14 = {0, "nehx14", "0", "nehahra data storage cvar (used in singleplayer)"};
2468 cvar_t nehx15 = {0, "nehx15", "0", "nehahra data storage cvar (used in singleplayer)"};
2469 cvar_t nehx16 = {0, "nehx16", "0", "nehahra data storage cvar (used in singleplayer)"};
2470 cvar_t nehx17 = {0, "nehx17", "0", "nehahra data storage cvar (used in singleplayer)"};
2471 cvar_t nehx18 = {0, "nehx18", "0", "nehahra data storage cvar (used in singleplayer)"};
2472 cvar_t nehx19 = {0, "nehx19", "0", "nehahra data storage cvar (used in singleplayer)"};
2473 cvar_t cutscene = {0, "cutscene", "1", "enables cutscenes in nehahra, can be used by other mods"};
2474
2475 void SV_VM_Init(void)
2476 {
2477         Cvar_RegisterVariable (&pr_checkextension);
2478         Cvar_RegisterVariable (&nomonsters);
2479         Cvar_RegisterVariable (&gamecfg);
2480         Cvar_RegisterVariable (&scratch1);
2481         Cvar_RegisterVariable (&scratch2);
2482         Cvar_RegisterVariable (&scratch3);
2483         Cvar_RegisterVariable (&scratch4);
2484         Cvar_RegisterVariable (&savedgamecfg);
2485         Cvar_RegisterVariable (&saved1);
2486         Cvar_RegisterVariable (&saved2);
2487         Cvar_RegisterVariable (&saved3);
2488         Cvar_RegisterVariable (&saved4);
2489         // LordHavoc: Nehahra uses these to pass data around cutscene demos
2490         if (gamemode == GAME_NEHAHRA)
2491         {
2492                 Cvar_RegisterVariable (&nehx00);
2493                 Cvar_RegisterVariable (&nehx01);
2494                 Cvar_RegisterVariable (&nehx02);
2495                 Cvar_RegisterVariable (&nehx03);
2496                 Cvar_RegisterVariable (&nehx04);
2497                 Cvar_RegisterVariable (&nehx05);
2498                 Cvar_RegisterVariable (&nehx06);
2499                 Cvar_RegisterVariable (&nehx07);
2500                 Cvar_RegisterVariable (&nehx08);
2501                 Cvar_RegisterVariable (&nehx09);
2502                 Cvar_RegisterVariable (&nehx10);
2503                 Cvar_RegisterVariable (&nehx11);
2504                 Cvar_RegisterVariable (&nehx12);
2505                 Cvar_RegisterVariable (&nehx13);
2506                 Cvar_RegisterVariable (&nehx14);
2507                 Cvar_RegisterVariable (&nehx15);
2508                 Cvar_RegisterVariable (&nehx16);
2509                 Cvar_RegisterVariable (&nehx17);
2510                 Cvar_RegisterVariable (&nehx18);
2511                 Cvar_RegisterVariable (&nehx19);
2512         }
2513         Cvar_RegisterVariable (&cutscene); // for Nehahra but useful to other mods as well
2514 }
2515
2516 #define REQFIELDS (sizeof(reqfields) / sizeof(prvm_required_field_t))
2517
2518 prvm_required_field_t reqfields[] =
2519 {
2520         {ev_entity, "cursor_trace_ent"},
2521         {ev_entity, "drawonlytoclient"},
2522         {ev_entity, "exteriormodeltoclient"},
2523         {ev_entity, "nodrawtoclient"},
2524         {ev_entity, "tag_entity"},
2525         {ev_entity, "viewmodelforclient"},
2526         {ev_float, "alpha"},
2527         {ev_float, "ammo_cells1"},
2528         {ev_float, "ammo_lava_nails"},
2529         {ev_float, "ammo_multi_rockets"},
2530         {ev_float, "ammo_nails1"},
2531         {ev_float, "ammo_plasma"},
2532         {ev_float, "ammo_rockets1"},
2533         {ev_float, "ammo_shells1"},
2534         {ev_float, "button3"},
2535         {ev_float, "button4"},
2536         {ev_float, "button5"},
2537         {ev_float, "button6"},
2538         {ev_float, "button7"},
2539         {ev_float, "button8"},
2540         {ev_float, "button9"},
2541         {ev_float, "button10"},
2542         {ev_float, "button11"},
2543         {ev_float, "button12"},
2544         {ev_float, "button13"},
2545         {ev_float, "button14"},
2546         {ev_float, "button15"},
2547         {ev_float, "button16"},
2548         {ev_float, "buttonchat"},
2549         {ev_float, "buttonuse"},
2550         {ev_float, "clientcolors"},
2551         {ev_float, "cursor_active"},
2552         {ev_float, "disableclientprediction"},
2553         {ev_float, "fullbright"},
2554         {ev_float, "glow_color"},
2555         {ev_float, "glow_size"},
2556         {ev_float, "glow_trail"},
2557         {ev_float, "gravity"},
2558         {ev_float, "idealpitch"},
2559         {ev_float, "items2"},
2560         {ev_float, "light_lev"},
2561         {ev_float, "pflags"},
2562         {ev_float, "ping"},
2563         {ev_float, "pitch_speed"},
2564         {ev_float, "pmodel"},
2565         {ev_float, "renderamt"}, // HalfLife support
2566         {ev_float, "rendermode"}, // HalfLife support
2567         {ev_float, "scale"},
2568         {ev_float, "style"},
2569         {ev_float, "tag_index"},
2570         {ev_float, "Version"},
2571         {ev_float, "viewzoom"},
2572         {ev_vector, "color"},
2573         {ev_vector, "colormod"},
2574         {ev_vector, "cursor_screen"},
2575         {ev_vector, "cursor_trace_endpos"},
2576         {ev_vector, "cursor_trace_start"},
2577         {ev_vector, "movement"},
2578         {ev_vector, "punchvector"},
2579         {ev_string, "playermodel"},
2580         {ev_string, "playerskin"},
2581         {ev_function, "SendEntity"},
2582         {ev_function, "customizeentityforclient"},
2583         // DRESK - Support for Entity Contents Transition Event
2584         {ev_function, "contentstransition"},
2585 };
2586
2587 void SV_VM_Setup(void)
2588 {
2589         extern cvar_t csqc_progname;    //[515]: csqc crc check and right csprogs name according to progs.dat
2590         extern cvar_t csqc_progcrc;
2591         extern cvar_t csqc_progsize;
2592         size_t csprogsdatasize;
2593         PRVM_Begin;
2594         PRVM_InitProg( PRVM_SERVERPROG );
2595
2596         // allocate the mempools
2597         // TODO: move the magic numbers/constants into #defines [9/13/2006 Black]
2598         prog->progs_mempool = Mem_AllocPool("Server Progs", 0, NULL);
2599         prog->builtins = vm_sv_builtins;
2600         prog->numbuiltins = vm_sv_numbuiltins;
2601         prog->headercrc = PROGHEADER_CRC;
2602         prog->max_edicts = 512;
2603         prog->limit_edicts = MAX_EDICTS;
2604         prog->reserved_edicts = svs.maxclients;
2605         prog->edictprivate_size = sizeof(edict_engineprivate_t);
2606         prog->name = "server";
2607         prog->extensionstring = vm_sv_extensions;
2608         prog->loadintoworld = true;
2609
2610         prog->begin_increase_edicts = SV_VM_CB_BeginIncreaseEdicts;
2611         prog->end_increase_edicts = SV_VM_CB_EndIncreaseEdicts;
2612         prog->init_edict = SV_VM_CB_InitEdict;
2613         prog->free_edict = SV_VM_CB_FreeEdict;
2614         prog->count_edicts = SV_VM_CB_CountEdicts;
2615         prog->load_edict = SV_VM_CB_LoadEdict;
2616         prog->init_cmd = VM_SV_Cmd_Init;
2617         prog->reset_cmd = VM_SV_Cmd_Reset;
2618         prog->error_cmd = Host_Error;
2619
2620         // TODO: add a requiredfuncs list (ask LH if this is necessary at all)
2621         PRVM_LoadProgs( sv_progs.string, 0, NULL, REQFIELDS, reqfields, 0, NULL );
2622
2623         // some mods compiled with scrambling compilers lack certain critical
2624         // global names and field names such as "self" and "time" and "nextthink"
2625         // so we have to set these offsets manually, matching the entvars_t
2626         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, angles);
2627         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, chain);
2628         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, classname);
2629         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frame);
2630         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, groundentity);
2631         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ideal_yaw);
2632         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, nextthink);
2633         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, think);
2634         PRVM_ED_FindFieldOffset_FromStruct(entvars_t, yaw_speed);
2635         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, self);
2636         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, time);
2637         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_forward);
2638         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_right);
2639         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_up);
2640         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_allsolid);
2641         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_startsolid);
2642         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_fraction);
2643         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inwater);
2644         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inopen);
2645         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_endpos);
2646         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_normal);
2647         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_dist);
2648         PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_ent);
2649         // OP_STATE is always supported on server (due to entvars_t)
2650         prog->flag |= PRVM_OP_STATE;
2651
2652         VM_AutoSentStats_Clear();//[515]: csqc
2653         EntityFrameCSQC_ClearVersions();//[515]: csqc
2654
2655         PRVM_End;
2656
2657         // see if there is a csprogs.dat installed, and if so, set the csqc_progcrc accordingly, this will be sent to connecting clients to tell them to only load a matching csprogs.dat file
2658         sv.csqc_progname[0] = 0;
2659         sv.csqc_progcrc = FS_CRCFile(csqc_progname.string, &csprogsdatasize);
2660         sv.csqc_progsize = csprogsdatasize;
2661         if (sv.csqc_progsize > 0)
2662         {
2663                 strlcpy(sv.csqc_progname, csqc_progname.string, sizeof(sv.csqc_progname));
2664                 Con_DPrintf("server detected csqc progs file \"%s\" with size %i and crc %i\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
2665         }
2666 }
2667
2668 void SV_VM_Begin(void)
2669 {
2670         PRVM_Begin;
2671         PRVM_SetProg( PRVM_SERVERPROG );
2672
2673         prog->globals.server->time = (float) sv.time;
2674 }
2675
2676 void SV_VM_End(void)
2677 {
2678         PRVM_End;
2679 }