protocol/dp8: Implement parting messages
[xonotic/darkplaces.git] / sv_send.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
21 #include "quakedef.h"
22 #include "sv_demo.h"
23
24 extern cvar_t sv_airaccel_qw_stretchfactor;
25 extern cvar_t sv_gameplayfix_customstats;
26 extern cvar_t sv_warsowbunny_airforwardaccel;
27 extern cvar_t sv_warsowbunny_accel;
28 extern cvar_t sv_warsowbunny_topspeed;
29 extern cvar_t sv_warsowbunny_turnaccel;
30 extern cvar_t sv_warsowbunny_backtosideratio;
31 extern cvar_t sv_onlycsqcnetworking;
32 extern cvar_t sv_cullentities_trace_entityocclusion;
33 extern cvar_t sv_cullentities_trace_samples_players;
34 extern cvar_t sv_cullentities_trace_eyejitter;
35 extern cvar_t sv_cullentities_trace_expand;
36 extern cvar_t sv_cullentities_trace_delay_players;
37
38 /*
39 =============================================================================
40
41 EVENT MESSAGES
42
43 =============================================================================
44 */
45
46 /*
47 =================
48 SV_ClientPrint
49
50 Sends text across to be displayed
51 FIXME: make this just a stuffed echo?
52 =================
53 */
54 void SV_ClientPrint(const char *msg)
55 {
56         if (host_client->netconnection)
57         {
58                 MSG_WriteByte(&host_client->netconnection->message, svc_print);
59                 MSG_WriteString(&host_client->netconnection->message, msg);
60         }
61 }
62
63 /*
64 =================
65 SV_ClientPrintf
66
67 Sends text across to be displayed
68 FIXME: make this just a stuffed echo?
69 =================
70 */
71 void SV_ClientPrintf(const char *fmt, ...)
72 {
73         va_list argptr;
74         char msg[MAX_INPUTLINE];
75
76         va_start(argptr,fmt);
77         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
78         va_end(argptr);
79
80         SV_ClientPrint(msg);
81 }
82
83 /*
84 =================
85 SV_BroadcastPrint
86
87 Sends text to all active clients
88 =================
89 */
90 void SV_BroadcastPrint(const char *msg)
91 {
92         int i;
93         client_t *client;
94
95         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
96         {
97                 if (client->active && client->netconnection)
98                 {
99                         MSG_WriteByte(&client->netconnection->message, svc_print);
100                         MSG_WriteString(&client->netconnection->message, msg);
101                 }
102         }
103
104         if (sv_echobprint.integer && !host_isclient.integer)
105                 Con_Print(msg);
106 }
107
108 /*
109 =================
110 SV_BroadcastPrintf
111
112 Sends text to all active clients
113 =================
114 */
115 void SV_BroadcastPrintf(const char *fmt, ...)
116 {
117         va_list argptr;
118         char msg[MAX_INPUTLINE];
119
120         va_start(argptr,fmt);
121         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
122         va_end(argptr);
123
124         SV_BroadcastPrint(msg);
125 }
126
127 /*
128 =================
129 SV_ClientCommands
130
131 Send text over to the client to be executed
132 =================
133 */
134 void SV_ClientCommands(const char *fmt, ...)
135 {
136         va_list argptr;
137         char string[MAX_INPUTLINE];
138
139         if (!host_client->netconnection)
140                 return;
141
142         va_start(argptr,fmt);
143         dpvsnprintf(string, sizeof(string), fmt, argptr);
144         va_end(argptr);
145
146         MSG_WriteByte(&host_client->netconnection->message, svc_stufftext);
147         MSG_WriteString(&host_client->netconnection->message, string);
148 }
149
150 /*
151 ==================
152 SV_StartParticle
153
154 Make sure the event gets sent to all clients
155 ==================
156 */
157 void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
158 {
159         int i;
160
161         if (sv.datagram.cursize > MAX_PACKETFRAGMENT-18)
162                 return;
163         MSG_WriteByte (&sv.datagram, svc_particle);
164         MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
165         MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
166         MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
167         for (i=0 ; i<3 ; i++)
168                 MSG_WriteChar (&sv.datagram, (int)bound(-128, dir[i]*16, 127));
169         MSG_WriteByte (&sv.datagram, count);
170         MSG_WriteByte (&sv.datagram, color);
171         SV_FlushBroadcastMessages();
172 }
173
174 /*
175 ==================
176 SV_StartEffect
177
178 Make sure the event gets sent to all clients
179 ==================
180 */
181 void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
182 {
183         if (modelindex >= 256 || startframe >= 256)
184         {
185                 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-19)
186                         return;
187                 MSG_WriteByte (&sv.datagram, svc_effect2);
188                 MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
189                 MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
190                 MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
191                 MSG_WriteShort (&sv.datagram, modelindex);
192                 MSG_WriteShort (&sv.datagram, startframe);
193                 MSG_WriteByte (&sv.datagram, framecount);
194                 MSG_WriteByte (&sv.datagram, framerate);
195         }
196         else
197         {
198                 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-17)
199                         return;
200                 MSG_WriteByte (&sv.datagram, svc_effect);
201                 MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
202                 MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
203                 MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
204                 MSG_WriteByte (&sv.datagram, modelindex);
205                 MSG_WriteByte (&sv.datagram, startframe);
206                 MSG_WriteByte (&sv.datagram, framecount);
207                 MSG_WriteByte (&sv.datagram, framerate);
208         }
209         SV_FlushBroadcastMessages();
210 }
211
212 /*
213 ==================
214 SV_StartSound
215
216 Each entity can have eight independant sound sources, like voice,
217 weapon, feet, etc.
218
219 Channel 0 is an auto-allocate channel, the others override anything
220 already running on that entity/channel pair.
221
222 An attenuation of 0 will play full volume everywhere in the level.
223 Larger attenuations will drop off.  (max 4 attenuation)
224
225 ==================
226 */
227 void SV_StartSound (prvm_edict_t *entity, int channel, const char *sample, int nvolume, float attenuation, qbool reliable, float speed)
228 {
229         prvm_prog_t *prog = SVVM_prog;
230         sizebuf_t *dest;
231         int sound_num, field_mask, i, ent, speed4000;
232
233         dest = (reliable ? &sv.reliable_datagram : &sv.datagram);
234
235         if (nvolume < 0 || nvolume > 255)
236         {
237                 Con_Printf ("SV_StartSound: volume = %i\n", nvolume);
238                 return;
239         }
240
241         if (attenuation < 0 || attenuation > 4)
242         {
243                 Con_Printf ("SV_StartSound: attenuation = %f\n", attenuation);
244                 return;
245         }
246
247         if (!IS_CHAN(channel))
248         {
249                 Con_Printf ("SV_StartSound: channel = %i\n", channel);
250                 return;
251         }
252
253         channel = CHAN_ENGINE2NET(channel);
254
255         if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
256                 return;
257
258 // find precache number for sound
259         sound_num = SV_SoundIndex(sample, 1);
260         if (!sound_num)
261                 return;
262
263         ent = PRVM_NUM_FOR_EDICT(entity);
264
265         speed4000 = (int)floor(speed * 4000.0f + 0.5f);
266         field_mask = 0;
267         if (nvolume != DEFAULT_SOUND_PACKET_VOLUME)
268                 field_mask |= SND_VOLUME;
269         if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
270                 field_mask |= SND_ATTENUATION;
271         if (speed4000 && speed4000 != 4000)
272                 field_mask |= SND_SPEEDUSHORT4000;
273         if (ent >= 8192 || channel < 0 || channel > 7)
274                 field_mask |= SND_LARGEENTITY;
275         if (sound_num >= 256)
276                 field_mask |= SND_LARGESOUND;
277
278 // directed messages go only to the entity they are targeted on
279         MSG_WriteByte (dest, svc_sound);
280         MSG_WriteByte (dest, field_mask);
281         if (field_mask & SND_VOLUME)
282                 MSG_WriteByte (dest, nvolume);
283         if (field_mask & SND_ATTENUATION)
284                 MSG_WriteByte (dest, (int)(attenuation*64));
285         if (field_mask & SND_SPEEDUSHORT4000)
286                 MSG_WriteShort (dest, speed4000);
287         if (field_mask & SND_LARGEENTITY)
288         {
289                 MSG_WriteShort (dest, ent);
290                 MSG_WriteChar (dest, channel);
291         }
292         else
293                 MSG_WriteShort (dest, (ent<<3) | channel);
294         if ((field_mask & SND_LARGESOUND) || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
295                 MSG_WriteShort (dest, sound_num);
296         else
297                 MSG_WriteByte (dest, sound_num);
298         for (i = 0;i < 3;i++)
299                 MSG_WriteCoord (dest, PRVM_serveredictvector(entity, origin)[i]+0.5*(PRVM_serveredictvector(entity, mins)[i]+PRVM_serveredictvector(entity, maxs)[i]), sv.protocol);
300
301         // TODO do we have to do anything here when dest is &sv.reliable_datagram?
302         if(!reliable)
303                 SV_FlushBroadcastMessages();
304 }
305
306 /*
307 ==================
308 SV_StartPointSound
309
310 Nearly the same logic as SV_StartSound, except an origin
311 instead of an entity is provided and channel is omitted.
312
313 The entity sent to the client is 0 (world) and the channel
314 is 0 (CHAN_AUTO).  SND_LARGEENTITY will never occur in this
315 function, therefore the check for it is omitted.
316
317 ==================
318 */
319 void SV_StartPointSound (vec3_t origin, const char *sample, int nvolume, float attenuation, float speed)
320 {
321         int sound_num, field_mask, i, speed4000;
322
323         if (nvolume < 0 || nvolume > 255)
324         {
325                 Con_Printf ("SV_StartPointSound: volume = %i\n", nvolume);
326                 return;
327         }
328
329         if (attenuation < 0 || attenuation > 4)
330         {
331                 Con_Printf ("SV_StartPointSound: attenuation = %f\n", attenuation);
332                 return;
333         }
334
335         if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
336                 return;
337
338         // find precache number for sound
339         sound_num = SV_SoundIndex(sample, 1);
340         if (!sound_num)
341                 return;
342
343         speed4000 = (int)(speed * 40.0f);
344         field_mask = 0;
345         if (nvolume != DEFAULT_SOUND_PACKET_VOLUME)
346                 field_mask |= SND_VOLUME;
347         if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
348                 field_mask |= SND_ATTENUATION;
349         if (sound_num >= 256)
350                 field_mask |= SND_LARGESOUND;
351         if (speed4000 && speed4000 != 4000)
352                 field_mask |= SND_SPEEDUSHORT4000;
353
354 // directed messages go only to the entity they are targeted on
355         MSG_WriteByte (&sv.datagram, svc_sound);
356         MSG_WriteByte (&sv.datagram, field_mask);
357         if (field_mask & SND_VOLUME)
358                 MSG_WriteByte (&sv.datagram, nvolume);
359         if (field_mask & SND_ATTENUATION)
360                 MSG_WriteByte (&sv.datagram, (int)(attenuation*64));
361         if (field_mask & SND_SPEEDUSHORT4000)
362                 MSG_WriteShort (&sv.datagram, speed4000);
363         // Always write entnum 0 for the world entity
364         MSG_WriteShort (&sv.datagram, (0<<3) | 0);
365         if (field_mask & SND_LARGESOUND)
366                 MSG_WriteShort (&sv.datagram, sound_num);
367         else
368                 MSG_WriteByte (&sv.datagram, sound_num);
369         for (i = 0;i < 3;i++)
370                 MSG_WriteCoord (&sv.datagram, origin[i], sv.protocol);
371         SV_FlushBroadcastMessages();
372 }
373
374 /*
375 ===============================================================================
376
377 FRAME UPDATES
378
379 ===============================================================================
380 */
381
382 /*
383 =============================================================================
384
385 The PVS must include a small area around the client to allow head bobbing
386 or other small motion on the client side.  Otherwise, a bob might cause an
387 entity that should be visible to not show up, especially when the bob
388 crosses a waterline.
389
390 =============================================================================
391 */
392
393 static qbool SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *cs, int enumber)
394 {
395         prvm_prog_t *prog = SVVM_prog;
396         int i;
397         unsigned int sendflags;
398         unsigned int version;
399         unsigned int modelindex, effects, flags, glowsize, lightstyle, lightpflags, light[4], specialvisibilityradius;
400         unsigned int customizeentityforclient;
401         unsigned int sendentity;
402         float f;
403         prvm_vec_t *v;
404         vec3_t cullmins, cullmaxs;
405         model_t *model;
406
407         // fast path for games that do not use legacy entity networking
408         // note: still networks clients even if they are legacy
409         sendentity = PRVM_serveredictfunction(ent, SendEntity);
410         if (sv_onlycsqcnetworking.integer && !sendentity && enumber > svs.maxclients)
411                 return false;
412
413         // this 2 billion unit check is actually to detect NAN origins
414         // (we really don't want to send those)
415         if (!(VectorLength2(PRVM_serveredictvector(ent, origin)) < 2000000000.0*2000000000.0))
416                 return false;
417
418         // EF_NODRAW prevents sending for any reason except for your own
419         // client, so we must keep all clients in this superset
420         effects = (unsigned)PRVM_serveredictfloat(ent, effects);
421
422         // we can omit invisible entities with no effects that are not clients
423         // LadyHavoc: this could kill tags attached to an invisible entity, I
424         // just hope we never have to support that case
425         i = (int)PRVM_serveredictfloat(ent, modelindex);
426         modelindex = (i >= 1 && i < MAX_MODELS && PRVM_serveredictstring(ent, model) && *PRVM_GetString(prog, PRVM_serveredictstring(ent, model)) && sv.models[i]) ? i : 0;
427
428         flags = 0;
429         i = (int)(PRVM_serveredictfloat(ent, glow_size) * 0.25f);
430         glowsize = (unsigned char)bound(0, i, 255);
431         if (PRVM_serveredictfloat(ent, glow_trail))
432                 flags |= RENDER_GLOWTRAIL;
433         if (PRVM_serveredictedict(ent, viewmodelforclient))
434                 flags |= RENDER_VIEWMODEL;
435
436         v = PRVM_serveredictvector(ent, color);
437         f = v[0]*256;
438         light[0] = (unsigned short)bound(0, f, 65535);
439         f = v[1]*256;
440         light[1] = (unsigned short)bound(0, f, 65535);
441         f = v[2]*256;
442         light[2] = (unsigned short)bound(0, f, 65535);
443         f = PRVM_serveredictfloat(ent, light_lev);
444         light[3] = (unsigned short)bound(0, f, 65535);
445         lightstyle = (unsigned char)PRVM_serveredictfloat(ent, style);
446         lightpflags = (unsigned char)PRVM_serveredictfloat(ent, pflags);
447
448         if (gamemode == GAME_TENEBRAE)
449         {
450                 // tenebrae's EF_FULLDYNAMIC conflicts with Q2's EF_NODRAW
451                 if (effects & 16)
452                 {
453                         effects &= ~16;
454                         lightpflags |= PFLAGS_FULLDYNAMIC;
455                 }
456                 // tenebrae's EF_GREEN conflicts with DP's EF_ADDITIVE
457                 if (effects & 32)
458                 {
459                         effects &= ~32;
460                         light[0] = (int)(0.2*256);
461                         light[1] = (int)(1.0*256);
462                         light[2] = (int)(0.2*256);
463                         light[3] = 200;
464                         lightpflags |= PFLAGS_FULLDYNAMIC;
465                 }
466         }
467
468         specialvisibilityradius = 0;
469         if (lightpflags & PFLAGS_FULLDYNAMIC)
470                 specialvisibilityradius = max(specialvisibilityradius, light[3]);
471         if (glowsize)
472                 specialvisibilityradius = max(specialvisibilityradius, glowsize * 4);
473         if (flags & RENDER_GLOWTRAIL)
474                 specialvisibilityradius = max(specialvisibilityradius, 100);
475         if (effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
476         {
477                 if (effects & EF_BRIGHTFIELD)
478                         specialvisibilityradius = max(specialvisibilityradius, 80);
479                 if (effects & EF_MUZZLEFLASH)
480                         specialvisibilityradius = max(specialvisibilityradius, 100);
481                 if (effects & EF_BRIGHTLIGHT)
482                         specialvisibilityradius = max(specialvisibilityradius, 400);
483                 if (effects & EF_DIMLIGHT)
484                         specialvisibilityradius = max(specialvisibilityradius, 200);
485                 if (effects & EF_RED)
486                         specialvisibilityradius = max(specialvisibilityradius, 200);
487                 if (effects & EF_BLUE)
488                         specialvisibilityradius = max(specialvisibilityradius, 200);
489                 if (effects & EF_FLAME)
490                         specialvisibilityradius = max(specialvisibilityradius, 250);
491                 if (effects & EF_STARDUST)
492                         specialvisibilityradius = max(specialvisibilityradius, 100);
493         }
494
495         // early culling checks
496         // (final culling is done by SV_MarkWriteEntityStateToClient)
497         customizeentityforclient = PRVM_serveredictfunction(ent, customizeentityforclient);
498         if (!customizeentityforclient && enumber > svs.maxclients && (!modelindex && !specialvisibilityradius))
499                 return false;
500
501         *cs = defaultstate;
502         cs->active = ACTIVE_NETWORK;
503         cs->number = enumber;
504         VectorCopy(PRVM_serveredictvector(ent, origin), cs->origin);
505         VectorCopy(PRVM_serveredictvector(ent, angles), cs->angles);
506         cs->flags = flags;
507         cs->effects = effects;
508         cs->colormap = (unsigned)PRVM_serveredictfloat(ent, colormap);
509         cs->modelindex = modelindex;
510         cs->skin = (unsigned)PRVM_serveredictfloat(ent, skin);
511         cs->frame = (unsigned)PRVM_serveredictfloat(ent, frame);
512         cs->viewmodelforclient = PRVM_serveredictedict(ent, viewmodelforclient);
513         cs->exteriormodelforclient = PRVM_serveredictedict(ent, exteriormodeltoclient);
514         cs->nodrawtoclient = PRVM_serveredictedict(ent, nodrawtoclient);
515         cs->drawonlytoclient = PRVM_serveredictedict(ent, drawonlytoclient);
516         cs->customizeentityforclient = customizeentityforclient;
517         cs->tagentity = PRVM_serveredictedict(ent, tag_entity);
518         cs->tagindex = (unsigned char)PRVM_serveredictfloat(ent, tag_index);
519         cs->glowsize = glowsize;
520         cs->traileffectnum = PRVM_serveredictfloat(ent, traileffectnum);
521
522         // don't need to init cs->colormod because the defaultstate did that for us
523         //cs->colormod[0] = cs->colormod[1] = cs->colormod[2] = 32;
524         v = PRVM_serveredictvector(ent, colormod);
525         if (VectorLength2(v))
526         {
527                 i = (int)(v[0] * 32.0f);cs->colormod[0] = bound(0, i, 255);
528                 i = (int)(v[1] * 32.0f);cs->colormod[1] = bound(0, i, 255);
529                 i = (int)(v[2] * 32.0f);cs->colormod[2] = bound(0, i, 255);
530         }
531
532         // don't need to init cs->glowmod because the defaultstate did that for us
533         //cs->glowmod[0] = cs->glowmod[1] = cs->glowmod[2] = 32;
534         v = PRVM_serveredictvector(ent, glowmod);
535         if (VectorLength2(v))
536         {
537                 i = (int)(v[0] * 32.0f);cs->glowmod[0] = bound(0, i, 255);
538                 i = (int)(v[1] * 32.0f);cs->glowmod[1] = bound(0, i, 255);
539                 i = (int)(v[2] * 32.0f);cs->glowmod[2] = bound(0, i, 255);
540         }
541
542         cs->modelindex = modelindex;
543
544         cs->alpha = 255;
545         f = (PRVM_serveredictfloat(ent, alpha) * 255.0f);
546         if (f)
547         {
548                 i = (int)f;
549                 cs->alpha = (unsigned char)bound(0, i, 255);
550         }
551         // halflife
552         f = (PRVM_serveredictfloat(ent, renderamt));
553         if (f)
554         {
555                 i = (int)f;
556                 cs->alpha = (unsigned char)bound(0, i, 255);
557         }
558
559         cs->scale = 16;
560         f = (PRVM_serveredictfloat(ent, scale) * 16.0f);
561         if (f)
562         {
563                 i = (int)f;
564                 cs->scale = (unsigned char)bound(0, i, 255);
565         }
566
567         cs->glowcolor = 254;
568         f = PRVM_serveredictfloat(ent, glow_color);
569         if (f)
570                 cs->glowcolor = (int)f;
571
572         if (PRVM_serveredictfloat(ent, fullbright))
573                 cs->effects |= EF_FULLBRIGHT;
574
575         f = PRVM_serveredictfloat(ent, modelflags);
576         if (f)
577                 cs->effects |= ((unsigned int)f & 0xff) << 24;
578
579         if (PRVM_serveredictfloat(ent, movetype) == MOVETYPE_STEP)
580                 cs->flags |= RENDER_STEP;
581         if (cs->number != sv.writeentitiestoclient_cliententitynumber && (cs->effects & EF_LOWPRECISION) && cs->origin[0] >= -32768 && cs->origin[1] >= -32768 && cs->origin[2] >= -32768 && cs->origin[0] <= 32767 && cs->origin[1] <= 32767 && cs->origin[2] <= 32767)
582                 cs->flags |= RENDER_LOWPRECISION;
583         if (PRVM_serveredictfloat(ent, colormap) >= 1024)
584                 cs->flags |= RENDER_COLORMAPPED;
585         if (cs->viewmodelforclient)
586                 cs->flags |= RENDER_VIEWMODEL; // show relative to the view
587
588         if (PRVM_serveredictfloat(ent, sendcomplexanimation))
589         {
590                 cs->flags |= RENDER_COMPLEXANIMATION;
591                 if (PRVM_serveredictfloat(ent, skeletonindex) >= 1)
592                         cs->skeletonobject = ent->priv.server->skeleton;
593                 cs->framegroupblend[0].frame = PRVM_serveredictfloat(ent, frame);
594                 cs->framegroupblend[1].frame = PRVM_serveredictfloat(ent, frame2);
595                 cs->framegroupblend[2].frame = PRVM_serveredictfloat(ent, frame3);
596                 cs->framegroupblend[3].frame = PRVM_serveredictfloat(ent, frame4);
597                 cs->framegroupblend[0].start = PRVM_serveredictfloat(ent, frame1time);
598                 cs->framegroupblend[1].start = PRVM_serveredictfloat(ent, frame2time);
599                 cs->framegroupblend[2].start = PRVM_serveredictfloat(ent, frame3time);
600                 cs->framegroupblend[3].start = PRVM_serveredictfloat(ent, frame4time);
601                 cs->framegroupblend[1].lerp = PRVM_serveredictfloat(ent, lerpfrac);
602                 cs->framegroupblend[2].lerp = PRVM_serveredictfloat(ent, lerpfrac3);
603                 cs->framegroupblend[3].lerp = PRVM_serveredictfloat(ent, lerpfrac4);
604                 cs->framegroupblend[0].lerp = 1.0f - cs->framegroupblend[1].lerp - cs->framegroupblend[2].lerp - cs->framegroupblend[3].lerp;
605                 cs->frame = 0; // don't need the legacy frame
606         }
607
608         cs->light[0] = light[0];
609         cs->light[1] = light[1];
610         cs->light[2] = light[2];
611         cs->light[3] = light[3];
612         cs->lightstyle = lightstyle;
613         cs->lightpflags = lightpflags;
614
615         cs->specialvisibilityradius = specialvisibilityradius;
616
617         // calculate the visible box of this entity (don't use the physics box
618         // as that is often smaller than a model, and would not count
619         // specialvisibilityradius)
620         if ((model = SV_GetModelByIndex(modelindex)) && (model->type != mod_null))
621         {
622                 float scale = cs->scale * (1.0f / 16.0f);
623                 if (cs->angles[0] || cs->angles[2]) // pitch and roll
624                 {
625                         VectorMA(cs->origin, scale, model->rotatedmins, cullmins);
626                         VectorMA(cs->origin, scale, model->rotatedmaxs, cullmaxs);
627                 }
628                 else if (cs->angles[1] || ((effects | model->effects) & EF_ROTATE))
629                 {
630                         VectorMA(cs->origin, scale, model->yawmins, cullmins);
631                         VectorMA(cs->origin, scale, model->yawmaxs, cullmaxs);
632                 }
633                 else
634                 {
635                         VectorMA(cs->origin, scale, model->normalmins, cullmins);
636                         VectorMA(cs->origin, scale, model->normalmaxs, cullmaxs);
637                 }
638         }
639         else
640         {
641                 // if there is no model (or it could not be loaded), use the physics box
642                 VectorAdd(cs->origin, PRVM_serveredictvector(ent, mins), cullmins);
643                 VectorAdd(cs->origin, PRVM_serveredictvector(ent, maxs), cullmaxs);
644         }
645         if (specialvisibilityradius)
646         {
647                 cullmins[0] = min(cullmins[0], cs->origin[0] - specialvisibilityradius);
648                 cullmins[1] = min(cullmins[1], cs->origin[1] - specialvisibilityradius);
649                 cullmins[2] = min(cullmins[2], cs->origin[2] - specialvisibilityradius);
650                 cullmaxs[0] = max(cullmaxs[0], cs->origin[0] + specialvisibilityradius);
651                 cullmaxs[1] = max(cullmaxs[1], cs->origin[1] + specialvisibilityradius);
652                 cullmaxs[2] = max(cullmaxs[2], cs->origin[2] + specialvisibilityradius);
653         }
654
655         // calculate center of bbox for network prioritization purposes
656         VectorMAM(0.5f, cullmins, 0.5f, cullmaxs, cs->netcenter);
657
658         // if culling box has moved, update pvs cluster links
659         if (!VectorCompare(cullmins, ent->priv.server->cullmins) || !VectorCompare(cullmaxs, ent->priv.server->cullmaxs))
660         {
661                 VectorCopy(cullmins, ent->priv.server->cullmins);
662                 VectorCopy(cullmaxs, ent->priv.server->cullmaxs);
663                 // a value of -1 for pvs_numclusters indicates that the links are not
664                 // cached, and should be re-tested each time, this is the case if the
665                 // culling box touches too many pvs clusters to store, or if the world
666                 // model does not support FindBoxClusters
667                 ent->priv.server->pvs_numclusters = -1;
668                 if (sv.worldmodel && sv.worldmodel->brush.FindBoxClusters)
669                 {
670                         i = sv.worldmodel->brush.FindBoxClusters(sv.worldmodel, cullmins, cullmaxs, MAX_ENTITYCLUSTERS, ent->priv.server->pvs_clusterlist);
671                         if (i <= MAX_ENTITYCLUSTERS)
672                                 ent->priv.server->pvs_numclusters = i;
673                 }
674         }
675
676         // we need to do some csqc entity upkeep here
677         // get self.SendFlags and clear them
678         // (to let the QC know that they've been read)
679         if (sendentity)
680         {
681                 sendflags = (unsigned int)PRVM_serveredictfloat(ent, SendFlags);
682                 PRVM_serveredictfloat(ent, SendFlags) = 0;
683                 // legacy self.Version system
684                 if ((version = (unsigned int)PRVM_serveredictfloat(ent, Version)))
685                 {
686                         if (sv.csqcentityversion[enumber] != version)
687                                 sendflags = 0xFFFFFF;
688                         sv.csqcentityversion[enumber] = version;
689                 }
690                 // move sendflags into the per-client sendflags
691                 if (sendflags)
692                         for (i = 0;i < svs.maxclients;i++)
693                                 svs.clients[i].csqcentitysendflags[enumber] |= sendflags;
694                 // mark it as inactive for non-csqc networking
695                 cs->active = ACTIVE_SHARED;
696         }
697
698         return true;
699 }
700
701 static void SV_PrepareEntitiesForSending(void)
702 {
703         prvm_prog_t *prog = SVVM_prog;
704         int e;
705         prvm_edict_t *ent;
706         // send all entities that touch the pvs
707         sv.numsendentities = 0;
708         sv.sendentitiesindex[0] = NULL;
709         memset(sv.sendentitiesindex, 0, prog->num_edicts * sizeof(*sv.sendentitiesindex));
710         for (e = 1, ent = PRVM_NEXT_EDICT(prog->edicts);e < prog->num_edicts;e++, ent = PRVM_NEXT_EDICT(ent))
711         {
712                 if (!ent->free && SV_PrepareEntityForSending(ent, sv.sendentities + sv.numsendentities, e))
713                 {
714                         sv.sendentitiesindex[e] = sv.sendentities + sv.numsendentities;
715                         sv.numsendentities++;
716                 }
717         }
718 }
719
720 #define MAX_LINEOFSIGHTTRACES 64
721
722 qbool SV_CanSeeBox(int numtraces, vec_t eyejitter, vec_t enlarge, vec_t entboxexpand, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
723 {
724         prvm_prog_t *prog = SVVM_prog;
725         float pitchsign;
726         float alpha;
727         float starttransformed[3], endtransformed[3];
728         float boxminstransformed[3], boxmaxstransformed[3];
729         float localboxcenter[3], localboxextents[3], localboxmins[3], localboxmaxs[3];
730         int blocked = 0;
731         int traceindex;
732         int originalnumtouchedicts;
733         int numtouchedicts = 0;
734         int touchindex;
735         matrix4x4_t matrix, imatrix;
736         model_t *model;
737         prvm_edict_t *touch;
738         static prvm_edict_t *touchedicts[MAX_EDICTS];
739         vec3_t eyemins, eyemaxs, start;
740         vec3_t boxmins, boxmaxs;
741         vec3_t clipboxmins, clipboxmaxs;
742         vec3_t endpoints[MAX_LINEOFSIGHTTRACES];
743
744         numtraces = min(numtraces, MAX_LINEOFSIGHTTRACES);
745
746         // jitter the eye location within this box
747         eyemins[0] = eye[0] - eyejitter;
748         eyemaxs[0] = eye[0] + eyejitter;
749         eyemins[1] = eye[1] - eyejitter;
750         eyemaxs[1] = eye[1] + eyejitter;
751         eyemins[2] = eye[2] - eyejitter;
752         eyemaxs[2] = eye[2] + eyejitter;
753         // expand the box a little
754         boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0] - entboxexpand;
755         boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0] + entboxexpand;
756         boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1] - entboxexpand;
757         boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1] + entboxexpand;
758         boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2] - entboxexpand;
759         boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2] + entboxexpand;
760
761         VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, endpoints[0]);
762         for (traceindex = 1;traceindex < numtraces;traceindex++)
763                 VectorSet(endpoints[traceindex], lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
764
765         // calculate sweep box for the entire swarm of traces
766         VectorCopy(eyemins, clipboxmins);
767         VectorCopy(eyemaxs, clipboxmaxs);
768         for (traceindex = 0;traceindex < numtraces;traceindex++)
769         {
770                 clipboxmins[0] = min(clipboxmins[0], endpoints[traceindex][0]);
771                 clipboxmins[1] = min(clipboxmins[1], endpoints[traceindex][1]);
772                 clipboxmins[2] = min(clipboxmins[2], endpoints[traceindex][2]);
773                 clipboxmaxs[0] = max(clipboxmaxs[0], endpoints[traceindex][0]);
774                 clipboxmaxs[1] = max(clipboxmaxs[1], endpoints[traceindex][1]);
775                 clipboxmaxs[2] = max(clipboxmaxs[2], endpoints[traceindex][2]);
776         }
777
778         // get the list of entities in the sweep box
779         if (sv_cullentities_trace_entityocclusion.integer)
780                 numtouchedicts = SV_EntitiesInBox(clipboxmins, clipboxmaxs, MAX_EDICTS, touchedicts);
781         if (numtouchedicts > MAX_EDICTS)
782         {
783                 // this never happens
784                 Con_Printf("SV_EntitiesInBox returned %i edicts, max was %i\n", numtouchedicts, MAX_EDICTS);
785                 numtouchedicts = MAX_EDICTS;
786         }
787         // iterate the entities found in the sweep box and filter them
788         originalnumtouchedicts = numtouchedicts;
789         numtouchedicts = 0;
790         for (touchindex = 0;touchindex < originalnumtouchedicts;touchindex++)
791         {
792                 touch = touchedicts[touchindex];
793                 if (PRVM_serveredictfloat(touch, solid) != SOLID_BSP)
794                         continue;
795                 model = SV_GetModelFromEdict(touch);
796                 if (!model || !model->brush.TraceLineOfSight)
797                         continue;
798                 // skip obviously transparent entities
799                 alpha = PRVM_serveredictfloat(touch, alpha);
800                 if (alpha && alpha < 1)
801                         continue;
802                 if ((int)PRVM_serveredictfloat(touch, effects) & EF_ADDITIVE)
803                         continue;
804                 touchedicts[numtouchedicts++] = touch;
805         }
806
807         // now that we have a filtered list of "interesting" entities, fire each
808         // ray against all of them, this gives us an early-out case when something
809         // is visible (which it often is)
810
811         for (traceindex = 0;traceindex < numtraces;traceindex++)
812         {
813                 VectorSet(start, lhrandom(eyemins[0], eyemaxs[0]), lhrandom(eyemins[1], eyemaxs[1]), lhrandom(eyemins[2], eyemaxs[2]));
814                 // check world occlusion
815                 if (sv.worldmodel && sv.worldmodel->brush.TraceLineOfSight)
816                         if (!sv.worldmodel->brush.TraceLineOfSight(sv.worldmodel, start, endpoints[traceindex], boxmins, boxmaxs))
817                                 continue;
818                 for (touchindex = 0;touchindex < numtouchedicts;touchindex++)
819                 {
820                         touch = touchedicts[touchindex];
821                         model = SV_GetModelFromEdict(touch);
822                         if(model && model->brush.TraceLineOfSight)
823                         {
824                                 // get the entity matrix
825                                 pitchsign = SV_GetPitchSign(prog, touch);
826                                 Matrix4x4_CreateFromQuakeEntity(&matrix, PRVM_serveredictvector(touch, origin)[0], PRVM_serveredictvector(touch, origin)[1], PRVM_serveredictvector(touch, origin)[2], pitchsign * PRVM_serveredictvector(touch, angles)[0], PRVM_serveredictvector(touch, angles)[1], PRVM_serveredictvector(touch, angles)[2], 1);
827                                 Matrix4x4_Invert_Simple(&imatrix, &matrix);
828                                 // see if the ray hits this entity
829                                 Matrix4x4_Transform(&imatrix, start, starttransformed);
830                                 Matrix4x4_Transform(&imatrix, endpoints[traceindex], endtransformed);
831                                 Matrix4x4_Transform(&imatrix, boxmins, boxminstransformed);
832                                 Matrix4x4_Transform(&imatrix, boxmaxs, boxmaxstransformed);
833                                 // transform the AABB to local space
834                                 VectorMAM(0.5f, boxminstransformed, 0.5f, boxmaxstransformed, localboxcenter);
835                                 localboxextents[0] = fabs(boxmaxstransformed[0] - localboxcenter[0]);
836                                 localboxextents[1] = fabs(boxmaxstransformed[1] - localboxcenter[1]);
837                                 localboxextents[2] = fabs(boxmaxstransformed[2] - localboxcenter[2]);
838                                 localboxmins[0] = localboxcenter[0] - localboxextents[0];
839                                 localboxmins[1] = localboxcenter[1] - localboxextents[1];
840                                 localboxmins[2] = localboxcenter[2] - localboxextents[2];
841                                 localboxmaxs[0] = localboxcenter[0] + localboxextents[0];
842                                 localboxmaxs[1] = localboxcenter[1] + localboxextents[1];
843                                 localboxmaxs[2] = localboxcenter[2] + localboxextents[2];
844                                 if (!model->brush.TraceLineOfSight(model, starttransformed, endtransformed, localboxmins, localboxmaxs))
845                                 {
846                                         blocked++;
847                                         break;
848                                 }
849                         }
850                 }
851                 // check if the ray was blocked
852                 if (touchindex < numtouchedicts)
853                         continue;
854                 // return if the ray was not blocked
855                 return true;
856         }
857
858         // no rays survived
859         return false;
860 }
861
862 void SV_MarkWriteEntityStateToClient(entity_state_t *s)
863 {
864         prvm_prog_t *prog = SVVM_prog;
865         int isbmodel;
866         model_t *model;
867         prvm_edict_t *ed;
868         if (sv.sententitiesconsideration[s->number] == sv.sententitiesmark)
869                 return;
870         sv.sententitiesconsideration[s->number] = sv.sententitiesmark;
871         sv.writeentitiestoclient_stats_totalentities++;
872
873         if (s->customizeentityforclient)
874         {
875                 PRVM_serverglobalfloat(time) = sv.time;
876                 PRVM_serverglobaledict(self) = s->number;
877                 PRVM_serverglobaledict(other) = sv.writeentitiestoclient_cliententitynumber;
878                 prog->ExecuteProgram(prog, s->customizeentityforclient, "customizeentityforclient: NULL function");
879                 if(!PRVM_G_FLOAT(OFS_RETURN) || !SV_PrepareEntityForSending(PRVM_EDICT_NUM(s->number), s, s->number))
880                         return;
881         }
882
883         // never reject player
884         if (s->number != sv.writeentitiestoclient_cliententitynumber)
885         {
886                 // check various rejection conditions
887                 if (s->nodrawtoclient == sv.writeentitiestoclient_cliententitynumber)
888                         return;
889                 if (s->drawonlytoclient && s->drawonlytoclient != sv.writeentitiestoclient_cliententitynumber)
890                         return;
891                 if (s->effects & EF_NODRAW)
892                         return;
893                 // LadyHavoc: only send entities with a model or important effects
894                 if (!s->modelindex && s->specialvisibilityradius == 0)
895                         return;
896
897                 isbmodel = (model = SV_GetModelByIndex(s->modelindex)) != NULL && model->name[0] == '*';
898                 // viewmodels don't have visibility checking
899                 if (s->viewmodelforclient)
900                 {
901                         if (s->viewmodelforclient != sv.writeentitiestoclient_cliententitynumber)
902                                 return;
903                 }
904                 else if (s->tagentity)
905                 {
906                         // tag attached entities simply check their parent
907                         if (!sv.sendentitiesindex[s->tagentity])
908                                 return;
909                         SV_MarkWriteEntityStateToClient(sv.sendentitiesindex[s->tagentity]);
910                         if (sv.sententities[s->tagentity] != sv.sententitiesmark)
911                                 return;
912                 }
913                 // always send world submodels in newer protocols because they don't
914                 // generate much traffic (in old protocols they hog bandwidth)
915                 // but only if sv_cullentities_nevercullbmodels is off
916                 else if (!(s->effects & EF_NODEPTHTEST) && (!isbmodel || !sv_cullentities_nevercullbmodels.integer || sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE))
917                 {
918                         // entity has survived every check so far, check if visible
919                         ed = PRVM_EDICT_NUM(s->number);
920
921                         // if not touching a visible leaf
922                         if (sv_cullentities_pvs.integer && !r_novis.integer && !r_trippy.integer && sv.writeentitiestoclient_pvsbytes)
923                         {
924                                 if (ed->priv.server->pvs_numclusters < 0)
925                                 {
926                                         // entity too big for clusters list
927                                         if (sv.worldmodel && sv.worldmodel->brush.BoxTouchingPVS && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, sv.writeentitiestoclient_pvs, ed->priv.server->cullmins, ed->priv.server->cullmaxs))
928                                         {
929                                                 sv.writeentitiestoclient_stats_culled_pvs++;
930                                                 return;
931                                         }
932                                 }
933                                 else
934                                 {
935                                         int i;
936                                         // check cached clusters list
937                                         for (i = 0;i < ed->priv.server->pvs_numclusters;i++)
938                                                 if (CHECKPVSBIT(sv.writeentitiestoclient_pvs, ed->priv.server->pvs_clusterlist[i]))
939                                                         break;
940                                         if (i == ed->priv.server->pvs_numclusters)
941                                         {
942                                                 sv.writeentitiestoclient_stats_culled_pvs++;
943                                                 return;
944                                         }
945                                 }
946                         }
947
948                         // or not seen by random tracelines
949                         if (sv_cullentities_trace.integer && !isbmodel && sv.worldmodel && sv.worldmodel->brush.TraceLineOfSight && !r_trippy.integer)
950                         {
951                                 int samples =
952                                         s->number <= svs.maxclients
953                                                 ? sv_cullentities_trace_samples_players.integer
954                                                 :
955                                         s->specialvisibilityradius
956                                                 ? sv_cullentities_trace_samples_extra.integer
957                                                 : sv_cullentities_trace_samples.integer;
958                                 float enlarge = sv_cullentities_trace_enlarge.value;
959
960                                 if(samples > 0)
961                                 {
962                                         int eyeindex;
963                                         for (eyeindex = 0;eyeindex < sv.writeentitiestoclient_numeyes;eyeindex++)
964                                                 if(SV_CanSeeBox(samples, sv_cullentities_trace_eyejitter.value, enlarge, sv_cullentities_trace_expand.value, sv.writeentitiestoclient_eyes[eyeindex], ed->priv.server->cullmins, ed->priv.server->cullmaxs))
965                                                         break;
966                                         if(eyeindex < sv.writeentitiestoclient_numeyes)
967                                                 svs.clients[sv.writeentitiestoclient_clientnumber].visibletime[s->number] =
968                                                         host.realtime + (
969                                                                 s->number <= svs.maxclients
970                                                                         ? sv_cullentities_trace_delay_players.value
971                                                                         : sv_cullentities_trace_delay.value
972                                                         );
973                                         else if (host.realtime > svs.clients[sv.writeentitiestoclient_clientnumber].visibletime[s->number])
974                                         {
975                                                 sv.writeentitiestoclient_stats_culled_trace++;
976                                                 return;
977                                         }
978                                 }
979                         }
980                 }
981         }
982
983         // this just marks it for sending
984         // FIXME: it would be more efficient to send here, but the entity
985         // compressor isn't that flexible
986         sv.writeentitiestoclient_stats_visibleentities++;
987         sv.sententities[s->number] = sv.sententitiesmark;
988 }
989
990 #if MAX_LEVELNETWORKEYES > 0
991 #define MAX_EYE_RECURSION 1 // increase if recursion gets supported by portals
992 void SV_AddCameraEyes(void)
993 {
994         prvm_prog_t *prog = SVVM_prog;
995         int e, i, j, k;
996         prvm_edict_t *ed;
997         static int cameras[MAX_LEVELNETWORKEYES];
998         static vec3_t camera_origins[MAX_LEVELNETWORKEYES];
999         static int eye_levels[MAX_CLIENTNETWORKEYES];
1000         int n_cameras = 0;
1001         vec3_t mi, ma;
1002
1003         for(i = 0; i < sv.writeentitiestoclient_numeyes; ++i)
1004                 eye_levels[i] = 0;
1005
1006         // check line of sight to portal entities and add them to PVS
1007         for (e = 1, ed = PRVM_NEXT_EDICT(prog->edicts);e < prog->num_edicts;e++, ed = PRVM_NEXT_EDICT(ed))
1008         {
1009                 if (!ed->free)
1010                 {
1011                         if(PRVM_serveredictfunction(ed, camera_transform))
1012                         {
1013                                 PRVM_serverglobalfloat(time) = sv.time;
1014                                 PRVM_serverglobaledict(self) = e;
1015                                 PRVM_serverglobaledict(other) = sv.writeentitiestoclient_cliententitynumber;
1016                                 VectorCopy(sv.writeentitiestoclient_eyes[0], PRVM_serverglobalvector(trace_endpos));
1017                                 VectorCopy(sv.writeentitiestoclient_eyes[0], PRVM_G_VECTOR(OFS_PARM0));
1018                                 VectorClear(PRVM_G_VECTOR(OFS_PARM1));
1019                                 prog->ExecuteProgram(prog, PRVM_serveredictfunction(ed, camera_transform), "QC function e.camera_transform is missing");
1020                                 if(!VectorCompare(PRVM_serverglobalvector(trace_endpos), sv.writeentitiestoclient_eyes[0]))
1021                                 {
1022                                         VectorCopy(PRVM_serverglobalvector(trace_endpos), camera_origins[n_cameras]);
1023                                         cameras[n_cameras] = e;
1024                                         ++n_cameras;
1025                                         if(n_cameras >= MAX_LEVELNETWORKEYES)
1026                                                 break;
1027                                 }
1028                         }
1029                 }
1030         }
1031
1032         if(!n_cameras)
1033                 return;
1034
1035         // i is loop counter, is reset to 0 when an eye got added
1036         // j is camera index to check
1037         for(i = 0, j = 0; sv.writeentitiestoclient_numeyes < MAX_CLIENTNETWORKEYES && i < n_cameras; ++i, ++j, j %= n_cameras)
1038         {
1039                 if(!cameras[j])
1040                         continue;
1041                 ed = PRVM_EDICT_NUM(cameras[j]);
1042                 VectorAdd(PRVM_serveredictvector(ed, origin), PRVM_serveredictvector(ed, mins), mi);
1043                 VectorAdd(PRVM_serveredictvector(ed, origin), PRVM_serveredictvector(ed, maxs), ma);
1044                 for(k = 0; k < sv.writeentitiestoclient_numeyes; ++k)
1045                 if(eye_levels[k] <= MAX_EYE_RECURSION)
1046                 {
1047                         if(SV_CanSeeBox(sv_cullentities_trace_samples.integer, sv_cullentities_trace_eyejitter.value, sv_cullentities_trace_enlarge.value, sv_cullentities_trace_expand.value, sv.writeentitiestoclient_eyes[k], mi, ma))
1048                         {
1049                                 eye_levels[sv.writeentitiestoclient_numeyes] = eye_levels[k] + 1;
1050                                 VectorCopy(camera_origins[j], sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes]);
1051                                 // Con_Printf("added eye %d: %f %f %f because we can see %f %f %f .. %f %f %f from eye %d\n", j, sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes][0], sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes][1], sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes][2], mi[0], mi[1], mi[2], ma[0], ma[1], ma[2], k);
1052                                 sv.writeentitiestoclient_numeyes++;
1053                                 cameras[j] = 0;
1054                                 i = 0;
1055                                 break;
1056                         }
1057                 }
1058         }
1059 }
1060 #else
1061 void SV_AddCameraEyes(void)
1062 {
1063 }
1064 #endif
1065
1066 /*
1067 =============
1068 SV_CleanupEnts
1069
1070 =============
1071 */
1072 static void SV_CleanupEnts (void)
1073 {
1074         prvm_prog_t *prog = SVVM_prog;
1075         int             e;
1076         prvm_edict_t    *ent;
1077
1078         ent = PRVM_NEXT_EDICT(prog->edicts);
1079         for (e=1 ; e<prog->num_edicts ; e++, ent = PRVM_NEXT_EDICT(ent))
1080                 PRVM_serveredictfloat(ent, effects) = (int)PRVM_serveredictfloat(ent, effects) & ~EF_MUZZLEFLASH;
1081 }
1082
1083 /*
1084 ==================
1085 SV_WriteClientdataToMessage
1086
1087 ==================
1088 */
1089 void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t *msg, int *stats)
1090 {
1091         prvm_prog_t *prog = SVVM_prog;
1092         int             bits;
1093         int             i;
1094         prvm_edict_t    *other;
1095         int             items;
1096         vec3_t  punchvector;
1097         int             viewzoom;
1098         const char *s;
1099         float   *statsf = (float *)stats;
1100         float gravity;
1101
1102 //
1103 // send a damage message
1104 //
1105         if (PRVM_serveredictfloat(ent, dmg_take) || PRVM_serveredictfloat(ent, dmg_save))
1106         {
1107                 other = PRVM_PROG_TO_EDICT(PRVM_serveredictedict(ent, dmg_inflictor));
1108                 MSG_WriteByte (msg, svc_damage);
1109                 MSG_WriteByte (msg, (int)PRVM_serveredictfloat(ent, dmg_save));
1110                 MSG_WriteByte (msg, (int)PRVM_serveredictfloat(ent, dmg_take));
1111                 for (i=0 ; i<3 ; i++)
1112                         MSG_WriteCoord (msg, PRVM_serveredictvector(other, origin)[i] + 0.5*(PRVM_serveredictvector(other, mins)[i] + PRVM_serveredictvector(other, maxs)[i]), sv.protocol);
1113
1114                 PRVM_serveredictfloat(ent, dmg_take) = 0;
1115                 PRVM_serveredictfloat(ent, dmg_save) = 0;
1116         }
1117
1118 //
1119 // send the current viewpos offset from the view entity
1120 //
1121         SV_SetIdealPitch ();            // how much to look up / down ideally
1122
1123 // a fixangle might get lost in a dropped packet.  Oh well.
1124         if(PRVM_serveredictfloat(ent, fixangle))
1125         {
1126                 // angle fixing was requested by global thinking code...
1127                 // so store the current angles for later use
1128                 VectorCopy(PRVM_serveredictvector(ent, angles), host_client->fixangle_angles);
1129                 host_client->fixangle_angles_set = true;
1130
1131                 // and clear fixangle for the next frame
1132                 PRVM_serveredictfloat(ent, fixangle) = 0;
1133         }
1134
1135         if (host_client->fixangle_angles_set)
1136         {
1137                 MSG_WriteByte (msg, svc_setangle);
1138                 for (i=0 ; i < 3 ; i++)
1139                         MSG_WriteAngle (msg, host_client->fixangle_angles[i], sv.protocol);
1140                 host_client->fixangle_angles_set = false;
1141         }
1142
1143         // the runes are in serverflags, pack them into the items value, also pack
1144         // in the items2 value for mission pack huds
1145         // (used only in the mission packs, which do not use serverflags)
1146         items = (int)PRVM_serveredictfloat(ent, items) | ((int)PRVM_serveredictfloat(ent, items2) << 23) | ((int)PRVM_serverglobalfloat(serverflags) << 28);
1147
1148         VectorCopy(PRVM_serveredictvector(ent, punchvector), punchvector);
1149
1150         // cache weapon model name and index in client struct to save time
1151         // (this search can be almost 1% of cpu time!)
1152         s = PRVM_GetString(prog, PRVM_serveredictstring(ent, weaponmodel));
1153         if (strcmp(s, client->weaponmodel))
1154         {
1155                 strlcpy(client->weaponmodel, s, sizeof(client->weaponmodel));
1156                 client->weaponmodelindex = SV_ModelIndex(s, 1);
1157         }
1158
1159         viewzoom = (int)(PRVM_serveredictfloat(ent, viewzoom) * 255.0f);
1160         if (viewzoom == 0)
1161                 viewzoom = 255;
1162
1163         bits = 0;
1164
1165         if ((int)PRVM_serveredictfloat(ent, flags) & FL_ONGROUND)
1166                 bits |= SU_ONGROUND;
1167         if (PRVM_serveredictfloat(ent, waterlevel) >= 2)
1168                 bits |= SU_INWATER;
1169         if (PRVM_serveredictfloat(ent, idealpitch))
1170                 bits |= SU_IDEALPITCH;
1171
1172         for (i=0 ; i<3 ; i++)
1173         {
1174                 if (PRVM_serveredictvector(ent, punchangle)[i])
1175                         bits |= (SU_PUNCH1<<i);
1176                 if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_NEHAHRABJP && sv.protocol != PROTOCOL_NEHAHRABJP2 && sv.protocol != PROTOCOL_NEHAHRABJP3)
1177                         if (punchvector[i])
1178                                 bits |= (SU_PUNCHVEC1<<i);
1179                 if (PRVM_serveredictvector(ent, velocity)[i])
1180                         bits |= (SU_VELOCITY1<<i);
1181         }
1182
1183         gravity = PRVM_serveredictfloat(ent, gravity);if (!gravity) gravity = 1.0f;
1184
1185         memset(stats, 0, sizeof(int[MAX_CL_STATS]));
1186         stats[STAT_VIEWHEIGHT] = (int)PRVM_serveredictvector(ent, view_ofs)[2];
1187         stats[STAT_ITEMS] = items;
1188         stats[STAT_WEAPONFRAME] = (int)PRVM_serveredictfloat(ent, weaponframe);
1189         stats[STAT_ARMOR] = (int)PRVM_serveredictfloat(ent, armorvalue);
1190         stats[STAT_WEAPON] = client->weaponmodelindex;
1191         stats[STAT_HEALTH] = (int)PRVM_serveredictfloat(ent, health);
1192         stats[STAT_AMMO] = (int)PRVM_serveredictfloat(ent, currentammo);
1193         stats[STAT_SHELLS] = (int)PRVM_serveredictfloat(ent, ammo_shells);
1194         stats[STAT_NAILS] = (int)PRVM_serveredictfloat(ent, ammo_nails);
1195         stats[STAT_ROCKETS] = (int)PRVM_serveredictfloat(ent, ammo_rockets);
1196         stats[STAT_CELLS] = (int)PRVM_serveredictfloat(ent, ammo_cells);
1197         stats[STAT_ACTIVEWEAPON] = (int)PRVM_serveredictfloat(ent, weapon);
1198         stats[STAT_VIEWZOOM] = viewzoom;
1199         stats[STAT_TOTALSECRETS] = (int)PRVM_serverglobalfloat(total_secrets);
1200         stats[STAT_TOTALMONSTERS] = (int)PRVM_serverglobalfloat(total_monsters);
1201         // the QC bumps these itself by sending svc_'s, so we have to keep them
1202         // zero or they'll be corrected by the engine
1203         //stats[STAT_SECRETS] = PRVM_serverglobalfloat(found_secrets);
1204         //stats[STAT_MONSTERS] = PRVM_serverglobalfloat(killed_monsters);
1205
1206         if(!sv_gameplayfix_customstats.integer)
1207         {
1208                 statsf[STAT_MOVEVARS_AIRACCEL_QW_STRETCHFACTOR] = sv_airaccel_qw_stretchfactor.value;
1209                 statsf[STAT_MOVEVARS_AIRCONTROL_PENALTY] = sv_aircontrol_penalty.value;
1210                 statsf[STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW] = sv_airspeedlimit_nonqw.value;               
1211                 statsf[STAT_MOVEVARS_AIRSTRAFEACCEL_QW] = sv_airstrafeaccel_qw.value;
1212                 statsf[STAT_MOVEVARS_AIRCONTROL_POWER] = sv_aircontrol_power.value;
1213                 // movement settings for prediction
1214                 // note: these are not sent in protocols with lower MAX_CL_STATS limits
1215                 stats[STAT_MOVEFLAGS] = MOVEFLAG_VALID
1216                         | (sv_gameplayfix_q2airaccelerate.integer ? MOVEFLAG_Q2AIRACCELERATE : 0)
1217                         | (sv_gameplayfix_nogravityonground.integer ? MOVEFLAG_NOGRAVITYONGROUND : 0)
1218                         | (sv_gameplayfix_gravityunaffectedbyticrate.integer ? MOVEFLAG_GRAVITYUNAFFECTEDBYTICRATE : 0)
1219                 ;
1220                 statsf[STAT_MOVEVARS_WARSOWBUNNY_AIRFORWARDACCEL] = sv_warsowbunny_airforwardaccel.value;
1221                 statsf[STAT_MOVEVARS_WARSOWBUNNY_ACCEL] = sv_warsowbunny_accel.value;
1222                 statsf[STAT_MOVEVARS_WARSOWBUNNY_TOPSPEED] = sv_warsowbunny_topspeed.value;
1223                 statsf[STAT_MOVEVARS_WARSOWBUNNY_TURNACCEL] = sv_warsowbunny_turnaccel.value;
1224                 statsf[STAT_MOVEVARS_WARSOWBUNNY_BACKTOSIDERATIO] = sv_warsowbunny_backtosideratio.value;
1225                 statsf[STAT_MOVEVARS_AIRSTOPACCELERATE] = sv_airstopaccelerate.value;
1226                 statsf[STAT_MOVEVARS_AIRSTRAFEACCELERATE] = sv_airstrafeaccelerate.value;
1227                 statsf[STAT_MOVEVARS_MAXAIRSTRAFESPEED] = sv_maxairstrafespeed.value;
1228                 statsf[STAT_MOVEVARS_AIRCONTROL] = sv_aircontrol.value;
1229                 statsf[STAT_FRAGLIMIT] = fraglimit.value;
1230                 statsf[STAT_TIMELIMIT] = timelimit.value;
1231                 statsf[STAT_MOVEVARS_FRICTION] = sv_friction.value;     
1232                 statsf[STAT_MOVEVARS_WATERFRICTION] = sv_waterfriction.value >= 0 ? sv_waterfriction.value : sv_friction.value;
1233                 statsf[STAT_MOVEVARS_TICRATE] = sys_ticrate.value;
1234                 statsf[STAT_MOVEVARS_TIMESCALE] = host_timescale.value;
1235                 statsf[STAT_MOVEVARS_GRAVITY] = sv_gravity.value;
1236                 statsf[STAT_MOVEVARS_STOPSPEED] = sv_stopspeed.value;
1237                 statsf[STAT_MOVEVARS_MAXSPEED] = sv_maxspeed.value;
1238                 statsf[STAT_MOVEVARS_SPECTATORMAXSPEED] = sv_maxspeed.value; // FIXME: QW has a separate cvar for this
1239                 statsf[STAT_MOVEVARS_ACCELERATE] = sv_accelerate.value;
1240                 statsf[STAT_MOVEVARS_AIRACCELERATE] = sv_airaccelerate.value >= 0 ? sv_airaccelerate.value : sv_accelerate.value;
1241                 statsf[STAT_MOVEVARS_WATERACCELERATE] = sv_wateraccelerate.value >= 0 ? sv_wateraccelerate.value : sv_accelerate.value;
1242                 statsf[STAT_MOVEVARS_ENTGRAVITY] = gravity;
1243                 statsf[STAT_MOVEVARS_JUMPVELOCITY] = sv_jumpvelocity.value;
1244                 statsf[STAT_MOVEVARS_EDGEFRICTION] = sv_edgefriction.value;
1245                 statsf[STAT_MOVEVARS_MAXAIRSPEED] = sv_maxairspeed.value;
1246                 statsf[STAT_MOVEVARS_STEPHEIGHT] = sv_stepheight.value;
1247                 statsf[STAT_MOVEVARS_AIRACCEL_QW] = sv_airaccel_qw.value;
1248                 statsf[STAT_MOVEVARS_AIRACCEL_SIDEWAYS_FRICTION] = sv_airaccel_sideways_friction.value;
1249         }
1250
1251         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
1252         {
1253                 if (stats[STAT_VIEWHEIGHT] != DEFAULT_VIEWHEIGHT) bits |= SU_VIEWHEIGHT;
1254                 bits |= SU_ITEMS;
1255                 if (stats[STAT_WEAPONFRAME]) bits |= SU_WEAPONFRAME;
1256                 if (stats[STAT_ARMOR]) bits |= SU_ARMOR;
1257                 bits |= SU_WEAPON;
1258                 // FIXME: which protocols support this?  does PROTOCOL_DARKPLACES3 support viewzoom?
1259                 if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
1260                         if (viewzoom != 255)
1261                                 bits |= SU_VIEWZOOM;
1262         }
1263
1264         if (bits >= 65536)
1265                 bits |= SU_EXTEND1;
1266         if (bits >= 16777216)
1267                 bits |= SU_EXTEND2;
1268
1269         // send the data
1270         MSG_WriteByte (msg, svc_clientdata);
1271         MSG_WriteShort (msg, bits);
1272         if (bits & SU_EXTEND1)
1273                 MSG_WriteByte(msg, bits >> 16);
1274         if (bits & SU_EXTEND2)
1275                 MSG_WriteByte(msg, bits >> 24);
1276
1277         if (bits & SU_VIEWHEIGHT)
1278                 MSG_WriteChar (msg, stats[STAT_VIEWHEIGHT]);
1279
1280         if (bits & SU_IDEALPITCH)
1281                 MSG_WriteChar (msg, (int)PRVM_serveredictfloat(ent, idealpitch));
1282
1283         for (i=0 ; i<3 ; i++)
1284         {
1285                 if (bits & (SU_PUNCH1<<i))
1286                 {
1287                         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
1288                                 MSG_WriteChar(msg, (int)PRVM_serveredictvector(ent, punchangle)[i]);
1289                         else
1290                                 MSG_WriteAngle16i(msg, PRVM_serveredictvector(ent, punchangle)[i]);
1291                 }
1292                 if (bits & (SU_PUNCHVEC1<<i))
1293                 {
1294                         if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1295                                 MSG_WriteCoord16i(msg, punchvector[i]);
1296                         else
1297                                 MSG_WriteCoord32f(msg, punchvector[i]);
1298                 }
1299                 if (bits & (SU_VELOCITY1<<i))
1300                 {
1301                         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1302                                 MSG_WriteChar(msg, (int)(PRVM_serveredictvector(ent, velocity)[i] * (1.0f / 16.0f)));
1303                         else
1304                                 MSG_WriteCoord32f(msg, PRVM_serveredictvector(ent, velocity)[i]);
1305                 }
1306         }
1307
1308         if (bits & SU_ITEMS)
1309                 MSG_WriteLong (msg, stats[STAT_ITEMS]);
1310
1311         if (sv.protocol == PROTOCOL_DARKPLACES5)
1312         {
1313                 if (bits & SU_WEAPONFRAME)
1314                         MSG_WriteShort (msg, stats[STAT_WEAPONFRAME]);
1315                 if (bits & SU_ARMOR)
1316                         MSG_WriteShort (msg, stats[STAT_ARMOR]);
1317                 if (bits & SU_WEAPON)
1318                         MSG_WriteShort (msg, stats[STAT_WEAPON]);
1319                 MSG_WriteShort (msg, stats[STAT_HEALTH]);
1320                 MSG_WriteShort (msg, stats[STAT_AMMO]);
1321                 MSG_WriteShort (msg, stats[STAT_SHELLS]);
1322                 MSG_WriteShort (msg, stats[STAT_NAILS]);
1323                 MSG_WriteShort (msg, stats[STAT_ROCKETS]);
1324                 MSG_WriteShort (msg, stats[STAT_CELLS]);
1325                 MSG_WriteShort (msg, stats[STAT_ACTIVEWEAPON]);
1326                 if (bits & SU_VIEWZOOM)
1327                         MSG_WriteShort (msg, bound(0, stats[STAT_VIEWZOOM], 65535));
1328         }
1329         else if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1330         {
1331                 if (bits & SU_WEAPONFRAME)
1332                         MSG_WriteByte (msg, stats[STAT_WEAPONFRAME]);
1333                 if (bits & SU_ARMOR)
1334                         MSG_WriteByte (msg, stats[STAT_ARMOR]);
1335                 if (bits & SU_WEAPON)
1336                 {
1337                         if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
1338                                 MSG_WriteShort (msg, stats[STAT_WEAPON]);
1339                         else
1340                                 MSG_WriteByte (msg, stats[STAT_WEAPON]);
1341                 }
1342                 MSG_WriteShort (msg, stats[STAT_HEALTH]);
1343                 MSG_WriteByte (msg, stats[STAT_AMMO]);
1344                 MSG_WriteByte (msg, stats[STAT_SHELLS]);
1345                 MSG_WriteByte (msg, stats[STAT_NAILS]);
1346                 MSG_WriteByte (msg, stats[STAT_ROCKETS]);
1347                 MSG_WriteByte (msg, stats[STAT_CELLS]);
1348                 if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_QUOTH || IS_OLDNEXUIZ_DERIVED(gamemode))
1349                 {
1350                         for (i = 0;i < 32;i++)
1351                                 if (stats[STAT_ACTIVEWEAPON] & (1<<i))
1352                                         break;
1353                         MSG_WriteByte (msg, i);
1354                 }
1355                 else
1356                         MSG_WriteByte (msg, stats[STAT_ACTIVEWEAPON]);
1357                 if (bits & SU_VIEWZOOM)
1358                 {
1359                         if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
1360                                 MSG_WriteByte (msg, bound(0, stats[STAT_VIEWZOOM], 255));
1361                         else
1362                                 MSG_WriteShort (msg, bound(0, stats[STAT_VIEWZOOM], 65535));
1363                 }
1364         }
1365 }
1366
1367 void SV_FlushBroadcastMessages(void)
1368 {
1369         int i;
1370         client_t *client;
1371         if (sv.datagram.cursize <= 0)
1372                 return;
1373         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
1374         {
1375                 if (!client->begun || !client->netconnection || client->unreliablemsg.cursize + sv.datagram.cursize > client->unreliablemsg.maxsize || client->unreliablemsg_splitpoints >= (int)(sizeof(client->unreliablemsg_splitpoint)/sizeof(client->unreliablemsg_splitpoint[0])))
1376                         continue;
1377                 SZ_Write(&client->unreliablemsg, sv.datagram.data, sv.datagram.cursize);
1378                 client->unreliablemsg_splitpoint[client->unreliablemsg_splitpoints++] = client->unreliablemsg.cursize;
1379         }
1380         SZ_Clear(&sv.datagram);
1381 }
1382
1383 static void SV_WriteUnreliableMessages(client_t *client, sizebuf_t *msg, int maxsize, int maxsize2)
1384 {
1385         // scan the splitpoints to find out how many we can fit in
1386         int numsegments, j, split;
1387         if (!client->unreliablemsg_splitpoints)
1388                 return;
1389         // always accept the first one if it's within 1024 bytes, this ensures
1390         // that very big datagrams which are over the rate limit still get
1391         // through, just to keep it working
1392         for (numsegments = 1;numsegments < client->unreliablemsg_splitpoints;numsegments++)
1393                 if (msg->cursize + client->unreliablemsg_splitpoint[numsegments] > maxsize)
1394                         break;
1395         // the first segment gets an exemption from the rate limiting, otherwise
1396         // it could get dropped consistently due to a low rate limit
1397         if (numsegments == 1)
1398                 maxsize = maxsize2;
1399         // some will fit, so add the ones that will fit
1400         split = client->unreliablemsg_splitpoint[numsegments-1];
1401         // note this discards ones that were accepted by the segments scan but
1402         // can not fit, such as a really huge first one that will never ever
1403         // fit in a packet...
1404         if (msg->cursize + split <= maxsize)
1405                 SZ_Write(msg, client->unreliablemsg.data, split);
1406         // remove the part we sent, keeping any remaining data
1407         client->unreliablemsg.cursize -= split;
1408         if (client->unreliablemsg.cursize > 0)
1409                 memmove(client->unreliablemsg.data, client->unreliablemsg.data + split, client->unreliablemsg.cursize);
1410         // adjust remaining splitpoints
1411         client->unreliablemsg_splitpoints -= numsegments;
1412         for (j = 0;j < client->unreliablemsg_splitpoints;j++)
1413                 client->unreliablemsg_splitpoint[j] = client->unreliablemsg_splitpoint[numsegments + j] - split;
1414 }
1415
1416 /*
1417 =======================
1418 SV_SendClientDatagram
1419 =======================
1420 */
1421 static void SV_SendClientDatagram (client_t *client)
1422 {
1423         int clientrate, maxrate, maxsize, maxsize2, downloadsize;
1424         sizebuf_t msg;
1425         int stats[MAX_CL_STATS];
1426         static unsigned char sv_sendclientdatagram_buf[NET_MAXMESSAGE];
1427         double timedelta;
1428
1429         // obey rate limit by limiting packet frequency if the packet size
1430         // limiting fails
1431         // (usually this is caused by reliable messages)
1432         if (!NetConn_CanSend(client->netconnection))
1433                 return;
1434
1435         // PROTOCOL_DARKPLACES5 and later support packet size limiting of updates
1436         maxrate = max(NET_MINRATE, sv_maxrate.integer);
1437         if (sv_maxrate.integer != maxrate)
1438                 Cvar_SetValueQuick(&sv_maxrate, maxrate);
1439
1440         // clientrate determines the 'cleartime' of a packet
1441         // (how long to wait before sending another, based on this packet's size)
1442         clientrate = bound(NET_MINRATE, client->rate, maxrate);
1443
1444         switch (sv.protocol)
1445         {
1446         case PROTOCOL_QUAKE:
1447         case PROTOCOL_QUAKEDP:
1448         case PROTOCOL_NEHAHRAMOVIE:
1449         case PROTOCOL_NEHAHRABJP:
1450         case PROTOCOL_NEHAHRABJP2:
1451         case PROTOCOL_NEHAHRABJP3:
1452         case PROTOCOL_QUAKEWORLD:
1453                 // no packet size limit support on Quake protocols because it just
1454                 // causes missing entities/effects
1455                 // packets are simply sent less often to obey the rate limit
1456                 maxsize = 1024;
1457                 maxsize2 = 1024;
1458                 break;
1459         case PROTOCOL_DARKPLACES1:
1460         case PROTOCOL_DARKPLACES2:
1461         case PROTOCOL_DARKPLACES3:
1462         case PROTOCOL_DARKPLACES4:
1463                 // no packet size limit support on DP1-4 protocols because they kick
1464                 // the client off if they overflow, and miss effects
1465                 // packets are simply sent less often to obey the rate limit
1466                 maxsize = sizeof(sv_sendclientdatagram_buf);
1467                 maxsize2 = sizeof(sv_sendclientdatagram_buf);
1468                 break;
1469         default:
1470                 // DP5 and later protocols support packet size limiting which is a
1471                 // better method than limiting packet frequency as QW does
1472                 //
1473                 // at very low rates (or very small sys_ticrate) the packet size is
1474                 // not reduced below 128, but packets may be sent less often
1475
1476                 // how long are bursts?
1477                 timedelta = host_client->rate_burstsize / (double)client->rate;
1478
1479                 // how much of the burst do we keep reserved?
1480                 timedelta *= 1 - net_burstreserve.value;
1481
1482                 // only try to use excess time
1483                 timedelta = bound(0, host.realtime - host_client->netconnection->cleartime, timedelta);
1484
1485                 // but we know next packet will be in sys_ticrate, so we can use up THAT bandwidth
1486                 timedelta += sys_ticrate.value;
1487
1488                 // note: packet overhead (not counted in maxsize) is 28 bytes
1489                 maxsize = (int)(clientrate * timedelta) - 28;
1490
1491                 // put it in sound bounds
1492                 maxsize = bound(128, maxsize, 1400);
1493                 maxsize2 = 1400;
1494
1495                 // csqc entities can easily exceed 128 bytes, so disable throttling in
1496                 // mods that use csqc (they are likely to use less bandwidth anyway)
1497                 if((net_usesizelimit.integer == 1) ? (sv.csqc_progsize > 0) : (net_usesizelimit.integer < 1))
1498                         maxsize = maxsize2;
1499
1500                 break;
1501         }
1502
1503         if (LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) == LHNETADDRESSTYPE_LOOP && !host_limitlocal.integer)
1504         {
1505                 // for good singleplayer, send huge packets
1506                 maxsize = sizeof(sv_sendclientdatagram_buf);
1507                 maxsize2 = sizeof(sv_sendclientdatagram_buf);
1508                 // never limit frequency in singleplayer
1509                 clientrate = 1000000000;
1510         }
1511
1512         // while downloading, limit entity updates to half the packet
1513         // (any leftover space will be used for downloading)
1514         if (host_client->download_file)
1515                 maxsize /= 2;
1516
1517         msg.data = sv_sendclientdatagram_buf;
1518         msg.maxsize = sizeof(sv_sendclientdatagram_buf);
1519         msg.cursize = 0;
1520         msg.allowoverflow = false;
1521
1522         if (host_client->begun)
1523         {
1524                 // the player is in the game
1525                 MSG_WriteByte (&msg, svc_time);
1526                 MSG_WriteFloat (&msg, sv.time);
1527
1528                 // add the client specific data to the datagram
1529                 SV_WriteClientdataToMessage (client, client->edict, &msg, stats);
1530                 // now update the stats[] array using any registered custom fields
1531                 VM_SV_UpdateCustomStats(client, client->edict, &msg, stats);
1532                 // set host_client->statsdeltabits
1533                 Protocol_UpdateClientStats (stats);
1534
1535                 // add as many queued unreliable messages (effects) as we can fit
1536                 // limit effects to half of the remaining space
1537                 if (client->unreliablemsg.cursize)
1538                         SV_WriteUnreliableMessages (client, &msg, maxsize/2, maxsize2);
1539
1540                 // now write as many entities as we can fit, and also sends stats
1541                 SV_WriteEntitiesToClient (client, client->edict, &msg, maxsize);
1542         }
1543         else if (host.realtime > client->keepalivetime)
1544         {
1545                 // the player isn't totally in the game yet
1546                 // send small keepalive messages if too much time has passed
1547                 // (may also be sending downloads)
1548                 client->keepalivetime = host.realtime + 5;
1549                 MSG_WriteChar (&msg, svc_nop);
1550         }
1551
1552         // if a download is active, see if there is room to fit some download data
1553         // in this packet
1554         downloadsize = min(maxsize*2,maxsize2) - msg.cursize - 7;
1555         if (host_client->download_file && host_client->download_started && downloadsize > 0)
1556         {
1557                 fs_offset_t downloadstart;
1558                 unsigned char data[1400];
1559                 downloadstart = FS_Tell(host_client->download_file);
1560                 downloadsize = min(downloadsize, (int)sizeof(data));
1561                 downloadsize = FS_Read(host_client->download_file, data, downloadsize);
1562                 // note this sends empty messages if at the end of the file, which is
1563                 // necessary to keep the packet loss logic working
1564                 // (the last blocks may be lost and need to be re-sent, and that will
1565                 //  only occur if the client acks the empty end messages, revealing
1566                 //  a gap in the download progress, causing the last blocks to be
1567                 //  sent again)
1568                 MSG_WriteChar (&msg, svc_downloaddata);
1569                 MSG_WriteLong (&msg, downloadstart);
1570                 MSG_WriteShort (&msg, downloadsize);
1571                 if (downloadsize > 0)
1572                         SZ_Write (&msg, data, downloadsize);
1573         }
1574
1575         // reliable only if none is in progress
1576         if(client->sendsignon != 2 && !client->netconnection->sendMessageLength)
1577                 SV_WriteDemoMessage(client, &(client->netconnection->message), false);
1578         // unreliable
1579         SV_WriteDemoMessage(client, &msg, false);
1580
1581 // send the datagram
1582         NetConn_SendUnreliableMessage (client->netconnection, &msg, sv.protocol, clientrate, client->rate_burstsize, client->sendsignon == 2);
1583         if (client->sendsignon == 1 && !client->netconnection->message.cursize)
1584                 client->sendsignon = 2; // prevent reliable until client sends prespawn (this is the keepalive phase)
1585 }
1586
1587 /*
1588 =======================
1589 SV_UpdateToReliableMessages
1590 =======================
1591 */
1592 static void SV_UpdateToReliableMessages (void)
1593 {
1594         prvm_prog_t *prog = SVVM_prog;
1595         int i, j;
1596         client_t *client;
1597         const char *name;
1598         const char *model;
1599         const char *skin;
1600         int clientcamera;
1601
1602 // check for changes to be sent over the reliable streams
1603         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1604         {
1605                 // update the host_client fields we care about according to the entity fields
1606                 host_client->edict = PRVM_EDICT_NUM(i+1);
1607
1608                 // DP_SV_CLIENTNAME
1609                 name = PRVM_GetString(prog, PRVM_serveredictstring(host_client->edict, netname));
1610                 if (name == NULL)
1611                         name = "";
1612                 // always point the string back at host_client->name to keep it safe
1613                 //strlcpy (host_client->name, name, sizeof (host_client->name));
1614                 if (name != host_client->name) // prevent buffer overlap SIGABRT on Mac OSX
1615                         strlcpy (host_client->name, name, sizeof (host_client->name));
1616                 SV_Name(i);
1617
1618                 // DP_SV_CLIENTCOLORS
1619                 host_client->colors = (int)PRVM_serveredictfloat(host_client->edict, clientcolors);
1620                 if (host_client->old_colors != host_client->colors)
1621                 {
1622                         host_client->old_colors = host_client->colors;
1623                         // send notification to all clients
1624                         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
1625                         MSG_WriteByte (&sv.reliable_datagram, i);
1626                         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
1627                 }
1628
1629                 // NEXUIZ_PLAYERMODEL
1630                 model = PRVM_GetString(prog, PRVM_serveredictstring(host_client->edict, playermodel));
1631                 if (model == NULL)
1632                         model = "";
1633                 // always point the string back at host_client->name to keep it safe
1634                 //strlcpy (host_client->playermodel, model, sizeof (host_client->playermodel));
1635                 if (model != host_client->playermodel) // prevent buffer overlap SIGABRT on Mac OSX
1636                         strlcpy (host_client->playermodel, model, sizeof (host_client->playermodel));
1637                 PRVM_serveredictstring(host_client->edict, playermodel) = PRVM_SetEngineString(prog, host_client->playermodel);
1638
1639                 // NEXUIZ_PLAYERSKIN
1640                 skin = PRVM_GetString(prog, PRVM_serveredictstring(host_client->edict, playerskin));
1641                 if (skin == NULL)
1642                         skin = "";
1643                 // always point the string back at host_client->name to keep it safe
1644                 //strlcpy (host_client->playerskin, skin, sizeof (host_client->playerskin));
1645                 if (skin != host_client->playerskin) // prevent buffer overlap SIGABRT on Mac OSX
1646                         strlcpy (host_client->playerskin, skin, sizeof (host_client->playerskin));
1647                 PRVM_serveredictstring(host_client->edict, playerskin) = PRVM_SetEngineString(prog, host_client->playerskin);
1648
1649                 // TODO: add an extension name for this [1/17/2008 Black]
1650                 clientcamera = PRVM_serveredictedict(host_client->edict, clientcamera);
1651                 if (clientcamera > 0)
1652                 {
1653                         int oldclientcamera = host_client->clientcamera;
1654                         if (clientcamera >= prog->max_edicts || PRVM_EDICT_NUM(clientcamera)->free)
1655                                 clientcamera = PRVM_NUM_FOR_EDICT(host_client->edict);
1656                         host_client->clientcamera = clientcamera;
1657
1658                         if (oldclientcamera != host_client->clientcamera && host_client->netconnection)
1659                         {
1660                                 MSG_WriteByte(&host_client->netconnection->message, svc_setview);
1661                                 MSG_WriteShort(&host_client->netconnection->message, host_client->clientcamera);
1662                         }
1663                 }
1664
1665                 // frags
1666                 host_client->frags = (int)PRVM_serveredictfloat(host_client->edict, frags);
1667                 if(IS_OLDNEXUIZ_DERIVED(gamemode))
1668                         if(!host_client->begun && host_client->netconnection)
1669                                 host_client->frags = -666;
1670                 if (host_client->old_frags != host_client->frags)
1671                 {
1672                         host_client->old_frags = host_client->frags;
1673                         // send notification to all clients
1674                         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
1675                         MSG_WriteByte (&sv.reliable_datagram, i);
1676                         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
1677                 }
1678         }
1679
1680         for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1681                 if (client->netconnection && (client->begun || client->clientconnectcalled)) // also send MSG_ALL to people who are past ClientConnect, but not spawned yet
1682                         SZ_Write (&client->netconnection->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1683
1684         SZ_Clear (&sv.reliable_datagram);
1685 }
1686
1687
1688 /*
1689 =======================
1690 SV_SendClientMessages
1691 =======================
1692 */
1693 void SV_SendClientMessages(void)
1694 {
1695         int i, prepared = false;
1696
1697         if (sv.protocol == PROTOCOL_QUAKEWORLD)
1698                 Sys_Error("SV_SendClientMessages: no quakeworld support\n");
1699
1700         SV_FlushBroadcastMessages();
1701
1702 // update frags, names, etc
1703         SV_UpdateToReliableMessages();
1704
1705 // build individual updates
1706         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1707         {
1708                 if (!host_client->active)
1709                         continue;
1710                 if (!host_client->netconnection)
1711                         continue;
1712
1713                 if (host_client->netconnection->message.overflowed)
1714                 {
1715                         SV_DropClient (true, "Buffer overflow in net message"); // if the message couldn't send, kick off
1716                         continue;
1717                 }
1718
1719                 if (!prepared)
1720                 {
1721                         prepared = true;
1722                         // only prepare entities once per frame
1723                         SV_PrepareEntitiesForSending();
1724                 }
1725                 SV_SendClientDatagram(host_client);
1726         }
1727
1728 // clear muzzle flashes
1729         SV_CleanupEnts();
1730 }