]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - protocol.c
Update build system, fix and enable ODE by default
[xonotic/darkplaces.git] / protocol.c
1 #include "quakedef.h"
2
3 #define ENTITYSIZEPROFILING_START(msg, num) \
4         int entityprofiling_startsize = msg->cursize
5
6 #define ENTITYSIZEPROFILING_END(msg, num) \
7         if(developer_networkentities.integer >= 2) \
8         { \
9                 prvm_edict_t *ed = prog->edicts + num; \
10                 Con_Printf("sent entity update of size %d for a %s\n", (msg->cursize - entityprofiling_startsize), PRVM_serveredictstring(ed, classname) ? PRVM_GetString(prog, PRVM_serveredictstring(ed, classname)) : "(no classname)"); \
11         }
12
13 // this is 88 bytes (must match entity_state_t in protocol.h)
14 entity_state_t defaultstate =
15 {
16         // ! means this is not sent to client
17         0,//double time; // ! time this state was built (used on client for interpolation)
18         {0,0,0},//float netcenter[3]; // ! for network prioritization, this is the center of the bounding box (which may differ from the origin)
19         {0,0,0},//float origin[3];
20         {0,0,0},//float angles[3];
21         0,//int effects;
22         0,//unsigned int customizeentityforclient; // !
23         0,//unsigned short number; // entity number this state is for
24         0,//unsigned short modelindex;
25         0,//unsigned short frame;
26         0,//unsigned short tagentity;
27         0,//unsigned short specialvisibilityradius; // ! larger if it has effects/light
28         0,//unsigned short viewmodelforclient; // !
29         0,//unsigned short exteriormodelforclient; // ! not shown if first person viewing from this entity, shown in all other cases
30         0,//unsigned short nodrawtoclient; // !
31         0,//unsigned short drawonlytoclient; // !
32         0,//unsigned short traileffectnum;
33         {0,0,0,0},//unsigned short light[4]; // color*256 (0.00 to 255.996), and radius*1
34         ACTIVE_NOT,//unsigned char active; // true if a valid state
35         0,//unsigned char lightstyle;
36         0,//unsigned char lightpflags;
37         0,//unsigned char colormap;
38         0,//unsigned char skin; // also chooses cubemap for rtlights if lightpflags & LIGHTPFLAGS_FULLDYNAMIC
39         255,//unsigned char alpha;
40         16,//unsigned char scale;
41         0,//unsigned char glowsize;
42         254,//unsigned char glowcolor;
43         0,//unsigned char flags;
44         0,//unsigned char internaleffects; // INTEF_FLAG1QW and so on
45         0,//unsigned char tagindex;
46         {32, 32, 32},//unsigned char colormod[3];
47         {32, 32, 32},//unsigned char glowmod[3];
48 };
49
50 // LordHavoc: I own protocol ranges 96, 97, 3500-3599
51
52 struct protocolversioninfo_s
53 {
54         int number;
55         protocolversion_t version;
56         const char *name;
57 }
58 protocolversioninfo[] =
59 {
60         { 3504, PROTOCOL_DARKPLACES7 , "DP7"},
61         { 3503, PROTOCOL_DARKPLACES6 , "DP6"},
62         { 3502, PROTOCOL_DARKPLACES5 , "DP5"},
63         { 3501, PROTOCOL_DARKPLACES4 , "DP4"},
64         { 3500, PROTOCOL_DARKPLACES3 , "DP3"},
65         {   97, PROTOCOL_DARKPLACES2 , "DP2"},
66         {   96, PROTOCOL_DARKPLACES1 , "DP1"},
67         {   15, PROTOCOL_QUAKEDP     , "QUAKEDP"},
68         {   15, PROTOCOL_QUAKE       , "QUAKE"},
69         {   28, PROTOCOL_QUAKEWORLD  , "QW"},
70         {  250, PROTOCOL_NEHAHRAMOVIE, "NEHAHRAMOVIE"},
71         {10000, PROTOCOL_NEHAHRABJP  , "NEHAHRABJP"},
72         {10001, PROTOCOL_NEHAHRABJP2 , "NEHAHRABJP2"},
73         {10002, PROTOCOL_NEHAHRABJP3 , "NEHAHRABJP3"},
74         {    0, PROTOCOL_UNKNOWN     , NULL}
75 };
76
77 protocolversion_t Protocol_EnumForName(const char *s)
78 {
79         int i;
80         for (i = 0;protocolversioninfo[i].name;i++)
81                 if (!strcasecmp(s, protocolversioninfo[i].name))
82                         return protocolversioninfo[i].version;
83         return PROTOCOL_UNKNOWN;
84 }
85
86 const char *Protocol_NameForEnum(protocolversion_t p)
87 {
88         int i;
89         for (i = 0;protocolversioninfo[i].name;i++)
90                 if (protocolversioninfo[i].version == p)
91                         return protocolversioninfo[i].name;
92         return "UNKNOWN";
93 }
94
95 protocolversion_t Protocol_EnumForNumber(int n)
96 {
97         int i;
98         for (i = 0;protocolversioninfo[i].name;i++)
99                 if (protocolversioninfo[i].number == n)
100                         return protocolversioninfo[i].version;
101         return PROTOCOL_UNKNOWN;
102 }
103
104 int Protocol_NumberForEnum(protocolversion_t p)
105 {
106         int i;
107         for (i = 0;protocolversioninfo[i].name;i++)
108                 if (protocolversioninfo[i].version == p)
109                         return protocolversioninfo[i].number;
110         return 0;
111 }
112
113 void Protocol_Names(char *buffer, size_t buffersize)
114 {
115         int i;
116         if (buffersize < 1)
117                 return;
118         buffer[0] = 0;
119         for (i = 0;protocolversioninfo[i].name;i++)
120         {
121                 if (i > 1)
122                         strlcat(buffer, " ", buffersize);
123                 strlcat(buffer, protocolversioninfo[i].name, buffersize);
124         }
125 }
126
127 void EntityFrameQuake_ReadEntity(int bits)
128 {
129         int num;
130         entity_t *ent;
131         entity_state_t s;
132
133         if (bits & U_MOREBITS)
134                 bits |= (MSG_ReadByte(&cl_message)<<8);
135         if ((bits & U_EXTEND1) && cls.protocol != PROTOCOL_NEHAHRAMOVIE)
136         {
137                 bits |= MSG_ReadByte(&cl_message) << 16;
138                 if (bits & U_EXTEND2)
139                         bits |= MSG_ReadByte(&cl_message) << 24;
140         }
141
142         if (bits & U_LONGENTITY)
143                 num = (unsigned short) MSG_ReadShort(&cl_message);
144         else
145                 num = MSG_ReadByte(&cl_message);
146
147         if (num >= MAX_EDICTS)
148                 Host_Error("EntityFrameQuake_ReadEntity: entity number (%i) >= MAX_EDICTS (%i)", num, MAX_EDICTS);
149         if (num < 1)
150                 Host_Error("EntityFrameQuake_ReadEntity: invalid entity number (%i)", num);
151
152         if (cl.num_entities <= num)
153         {
154                 cl.num_entities = num + 1;
155                 if (num >= cl.max_entities)
156                         CL_ExpandEntities(num);
157         }
158
159         ent = cl.entities + num;
160
161         // note: this inherits the 'active' state of the baseline chosen
162         // (state_baseline is always active, state_current may not be active if
163         // the entity was missing in the last frame)
164         if (bits & U_DELTA)
165                 s = ent->state_current;
166         else
167         {
168                 s = ent->state_baseline;
169                 s.active = ACTIVE_NETWORK;
170         }
171
172         cl.isquakeentity[num] = true;
173         if (cl.lastquakeentity < num)
174                 cl.lastquakeentity = num;
175         s.number = num;
176         s.time = cl.mtime[0];
177         s.flags = 0;
178         if (bits & U_MODEL)
179         {
180                 if (cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
181                                                         s.modelindex = (unsigned short) MSG_ReadShort(&cl_message);
182                 else
183                                                         s.modelindex = (s.modelindex & 0xFF00) | MSG_ReadByte(&cl_message);
184         }
185         if (bits & U_FRAME)             s.frame = (s.frame & 0xFF00) | MSG_ReadByte(&cl_message);
186         if (bits & U_COLORMAP)  s.colormap = MSG_ReadByte(&cl_message);
187         if (bits & U_SKIN)              s.skin = MSG_ReadByte(&cl_message);
188         if (bits & U_EFFECTS)   s.effects = (s.effects & 0xFF00) | MSG_ReadByte(&cl_message);
189         if (bits & U_ORIGIN1)   s.origin[0] = MSG_ReadCoord(&cl_message, cls.protocol);
190         if (bits & U_ANGLE1)    s.angles[0] = MSG_ReadAngle(&cl_message, cls.protocol);
191         if (bits & U_ORIGIN2)   s.origin[1] = MSG_ReadCoord(&cl_message, cls.protocol);
192         if (bits & U_ANGLE2)    s.angles[1] = MSG_ReadAngle(&cl_message, cls.protocol);
193         if (bits & U_ORIGIN3)   s.origin[2] = MSG_ReadCoord(&cl_message, cls.protocol);
194         if (bits & U_ANGLE3)    s.angles[2] = MSG_ReadAngle(&cl_message, cls.protocol);
195         if (bits & U_STEP)              s.flags |= RENDER_STEP;
196         if (bits & U_ALPHA)             s.alpha = MSG_ReadByte(&cl_message);
197         if (bits & U_SCALE)             s.scale = MSG_ReadByte(&cl_message);
198         if (bits & U_EFFECTS2)  s.effects = (s.effects & 0x00FF) | (MSG_ReadByte(&cl_message) << 8);
199         if (bits & U_GLOWSIZE)  s.glowsize = MSG_ReadByte(&cl_message);
200         if (bits & U_GLOWCOLOR) s.glowcolor = MSG_ReadByte(&cl_message);
201         if (bits & U_COLORMOD)  {int c = MSG_ReadByte(&cl_message);s.colormod[0] = (unsigned char)(((c >> 5) & 7) * (32.0f / 7.0f));s.colormod[1] = (unsigned char)(((c >> 2) & 7) * (32.0f / 7.0f));s.colormod[2] = (unsigned char)((c & 3) * (32.0f / 3.0f));}
202         if (bits & U_GLOWTRAIL) s.flags |= RENDER_GLOWTRAIL;
203         if (bits & U_FRAME2)    s.frame = (s.frame & 0x00FF) | (MSG_ReadByte(&cl_message) << 8);
204         if (bits & U_MODEL2)    s.modelindex = (s.modelindex & 0x00FF) | (MSG_ReadByte(&cl_message) << 8);
205         if (bits & U_VIEWMODEL) s.flags |= RENDER_VIEWMODEL;
206         if (bits & U_EXTERIORMODEL)     s.flags |= RENDER_EXTERIORMODEL;
207
208         // LordHavoc: to allow playback of the Nehahra movie
209         if (cls.protocol == PROTOCOL_NEHAHRAMOVIE && (bits & U_EXTEND1))
210         {
211                 // LordHavoc: evil format
212                 int i = (int)MSG_ReadFloat(&cl_message);
213                 int j = (int)(MSG_ReadFloat(&cl_message) * 255.0f);
214                 if (i == 2)
215                 {
216                         i = (int)MSG_ReadFloat(&cl_message);
217                         if (i)
218                                 s.effects |= EF_FULLBRIGHT;
219                 }
220                 if (j < 0)
221                         s.alpha = 0;
222                 else if (j == 0 || j >= 255)
223                         s.alpha = 255;
224                 else
225                         s.alpha = j;
226         }
227
228         ent->state_previous = ent->state_current;
229         ent->state_current = s;
230         if (ent->state_current.active == ACTIVE_NETWORK)
231         {
232                 CL_MoveLerpEntityStates(ent);
233                 cl.entities_active[ent->state_current.number] = true;
234         }
235
236         if (cl_message.badread)
237                 Host_Error("EntityFrameQuake_ReadEntity: read error");
238 }
239
240 void EntityFrameQuake_ISeeDeadEntities(void)
241 {
242         int num, lastentity;
243         if (cl.lastquakeentity == 0)
244                 return;
245         lastentity = cl.lastquakeentity;
246         cl.lastquakeentity = 0;
247         for (num = 0;num <= lastentity;num++)
248         {
249                 if (cl.isquakeentity[num])
250                 {
251                         if (cl.entities_active[num] && cl.entities[num].state_current.time == cl.mtime[0])
252                         {
253                                 cl.isquakeentity[num] = true;
254                                 cl.lastquakeentity = num;
255                         }
256                         else
257                         {
258                                 cl.isquakeentity[num] = false;
259                                 cl.entities_active[num] = ACTIVE_NOT;
260                                 cl.entities[num].state_current = defaultstate;
261                                 cl.entities[num].state_current.number = num;
262                         }
263                 }
264         }
265 }
266
267 // NOTE: this only works with DP5 protocol and upwards. For lower protocols
268 // (including QUAKE), no packet loss handling for CSQC is done, which makes
269 // CSQC basically useless.
270 // Always use the DP5 protocol, or a higher one, when using CSQC entities.
271 static void EntityFrameCSQC_LostAllFrames(client_t *client)
272 {
273         prvm_prog_t *prog = SVVM_prog;
274         // mark ALL csqc entities as requiring a FULL resend!
275         // I know this is a bad workaround, but better than nothing.
276         int i, n;
277         prvm_edict_t *ed;
278
279         n = client->csqcnumedicts;
280         for(i = 0; i < n; ++i)
281         {
282                 if(client->csqcentityglobalhistory[i])
283                 {
284                         ed = prog->edicts + i;
285                         if (PRVM_serveredictfunction(ed, SendEntity))
286                                 client->csqcentitysendflags[i] |= 0xFFFFFF; // FULL RESEND
287                         else // if it was ever sent to that client as a CSQC entity
288                         {
289                                 client->csqcentityscope[i] = 1; // REMOVE
290                                 client->csqcentitysendflags[i] |= 0xFFFFFF;
291                         }
292                 }
293         }
294 }
295 void EntityFrameCSQC_LostFrame(client_t *client, int framenum)
296 {
297         // marks a frame as lost
298         int i, j;
299         qboolean valid;
300         int ringfirst, ringlast;
301         static int recoversendflags[MAX_EDICTS]; // client only
302         csqcentityframedb_t *d;
303
304         if(client->csqcentityframe_lastreset < 0)
305                 return;
306         if(framenum < client->csqcentityframe_lastreset)
307                 return; // no action required, as we resent that data anyway
308
309         // is our frame out of history?
310         ringfirst = client->csqcentityframehistory_next; // oldest entry
311         ringlast = (ringfirst + NUM_CSQCENTITYDB_FRAMES - 1) % NUM_CSQCENTITYDB_FRAMES; // most recently added entry
312
313         valid = false;
314         
315         for(j = 0; j < NUM_CSQCENTITYDB_FRAMES; ++j)
316         {
317                 d = &client->csqcentityframehistory[(ringfirst + j) % NUM_CSQCENTITYDB_FRAMES];
318                 if(d->framenum < 0)
319                         continue;
320                 if(d->framenum == framenum)
321                         break;
322                 else if(d->framenum < framenum)
323                         valid = true;
324         }
325         if(j == NUM_CSQCENTITYDB_FRAMES)
326         {
327                 if(valid) // got beaten, i.e. there is a frame < framenum
328                 {
329                         // a non-csqc frame got lost... great
330                         return;
331                 }
332                 else
333                 {
334                         // a too old frame got lost... sorry, cannot handle this
335                         Con_DPrintf("CSQC entity DB: lost a frame too early to do any handling (resending ALL)...\n");
336                         Con_DPrintf("Lost frame = %d\n", framenum);
337                         Con_DPrintf("Entity DB = %d to %d\n", client->csqcentityframehistory[ringfirst].framenum, client->csqcentityframehistory[ringlast].framenum);
338                         EntityFrameCSQC_LostAllFrames(client);
339                         client->csqcentityframe_lastreset = -1;
340                 }
341                 return;
342         }
343
344         // so j is the frame that got lost
345         // ringlast is the frame that we have to go to
346         ringfirst = (ringfirst + j) % NUM_CSQCENTITYDB_FRAMES;
347         if(ringlast < ringfirst)
348                 ringlast += NUM_CSQCENTITYDB_FRAMES;
349         
350         memset(recoversendflags, 0, sizeof(recoversendflags));
351
352         for(j = ringfirst; j <= ringlast; ++j)
353         {
354                 d = &client->csqcentityframehistory[j % NUM_CSQCENTITYDB_FRAMES];
355                 if(d->framenum < 0)
356                 {
357                         // deleted frame
358                 }
359                 else if(d->framenum < framenum)
360                 {
361                         // a frame in the past... should never happen
362                         Con_Printf("CSQC entity DB encountered a frame from the past when recovering from PL...?\n");
363                 }
364                 else if(d->framenum == framenum)
365                 {
366                         // handling the actually lost frame now
367                         for(i = 0; i < d->num; ++i)
368                         {
369                                 int sf = d->sendflags[i];
370                                 int ent = d->entno[i];
371                                 if(sf < 0) // remove
372                                         recoversendflags[ent] |= -1; // all bits, including sign
373                                 else if(sf > 0)
374                                         recoversendflags[ent] |= sf;
375                         }
376                 }
377                 else
378                 {
379                         // handling the frames that followed it now
380                         for(i = 0; i < d->num; ++i)
381                         {
382                                 int sf = d->sendflags[i];
383                                 int ent = d->entno[i];
384                                 if(sf < 0) // remove
385                                 {
386                                         recoversendflags[ent] = 0; // no need to update, we got a more recent remove (and will fix it THEN)
387                                         break; // no flags left to remove...
388                                 }
389                                 else if(sf > 0)
390                                         recoversendflags[ent] &= ~sf; // no need to update these bits, we already got them later
391                         }
392                 }
393         }
394
395         for(i = 0; i < client->csqcnumedicts; ++i)
396         {
397                 if(recoversendflags[i] < 0)
398                 {
399                         // a remove got lost, then either send a remove or - if it was
400                         // recreated later - a FULL update to make totally sure
401                         client->csqcentityscope[i] = 1;
402                         client->csqcentitysendflags[i] = 0xFFFFFF;
403                 }
404                 else
405                         client->csqcentitysendflags[i] |= recoversendflags[i];
406         }
407 }
408 static int EntityFrameCSQC_AllocFrame(client_t *client, int framenum)
409 {
410         int ringfirst = client->csqcentityframehistory_next; // oldest entry
411         client->csqcentityframehistory_next += 1;
412         client->csqcentityframehistory_next %= NUM_CSQCENTITYDB_FRAMES;
413         client->csqcentityframehistory[ringfirst].framenum = framenum;
414         client->csqcentityframehistory[ringfirst].num = 0;
415         return ringfirst;
416 }
417 static void EntityFrameCSQC_DeallocFrame(client_t *client, int framenum)
418 {
419         int ringfirst = client->csqcentityframehistory_next; // oldest entry
420         int ringlast = (ringfirst + NUM_CSQCENTITYDB_FRAMES - 1) % NUM_CSQCENTITYDB_FRAMES; // most recently added entry
421         if(framenum == client->csqcentityframehistory[ringlast].framenum)
422         {
423                 client->csqcentityframehistory[ringlast].framenum = -1;
424                 client->csqcentityframehistory[ringlast].num = 0;
425                 client->csqcentityframehistory_next = ringlast;
426         }
427         else
428                 Con_Printf("Trying to dealloc the wrong entity frame\n");
429 }
430
431 //[515]: we use only one array per-client for SendEntity feature
432 // TODO: add some handling for entity send priorities, to better deal with huge
433 // amounts of csqc networked entities
434 qboolean EntityFrameCSQC_WriteFrame (sizebuf_t *msg, int maxsize, int numnumbers, const unsigned short *numbers, int framenum)
435 {
436         prvm_prog_t *prog = SVVM_prog;
437         int num, number, end, sendflags;
438         qboolean sectionstarted = false;
439         const unsigned short *n;
440         prvm_edict_t *ed;
441         client_t *client = svs.clients + sv.writeentitiestoclient_clientnumber;
442         int dbframe = EntityFrameCSQC_AllocFrame(client, framenum);
443         csqcentityframedb_t *db = &client->csqcentityframehistory[dbframe];
444
445         if(client->csqcentityframe_lastreset < 0)
446                 client->csqcentityframe_lastreset = framenum;
447
448         maxsize -= 24; // always fit in an empty svc_entities message (for packet loss detection!)
449
450         // make sure there is enough room to store the svc_csqcentities byte,
451         // the terminator (0x0000) and at least one entity update
452         if (msg->cursize + 32 >= maxsize)
453                 return false;
454
455         if (client->csqcnumedicts < prog->num_edicts)
456                 client->csqcnumedicts = prog->num_edicts;
457
458         number = 1;
459         for (num = 0, n = numbers;num < numnumbers;num++, n++)
460         {
461                 end = *n;
462                 for (;number < end;number++)
463                 {
464                         if (client->csqcentityscope[number])
465                         {
466                                 client->csqcentityscope[number] = 1;
467                                 client->csqcentitysendflags[number] = 0xFFFFFF;
468                         }
469                 }
470                 ed = prog->edicts + number;
471                 if (PRVM_serveredictfunction(ed, SendEntity))
472                         client->csqcentityscope[number] = 2;
473                 else if (client->csqcentityscope[number])
474                 {
475                         client->csqcentityscope[number] = 1;
476                         client->csqcentitysendflags[number] = 0xFFFFFF;
477                 }
478                 number++;
479         }
480         end = client->csqcnumedicts;
481         for (;number < end;number++)
482         {
483                 if (client->csqcentityscope[number])
484                 {
485                         client->csqcentityscope[number] = 1;
486                         client->csqcentitysendflags[number] = 0xFFFFFF;
487                 }
488         }
489
490         /*
491         // mark all scope entities as remove
492         for (number = 1;number < client->csqcnumedicts;number++)
493                 if (client->csqcentityscope[number])
494                         client->csqcentityscope[number] = 1;
495         // keep visible entities
496         for (i = 0, n = numbers;i < numnumbers;i++, n++)
497         {
498                 number = *n;
499                 ed = prog->edicts + number;
500                 if (PRVM_serveredictfunction(ed, SendEntity))
501                         client->csqcentityscope[number] = 2;
502         }
503         */
504
505         // now try to emit the entity updates
506         // (FIXME: prioritize by distance?)
507         end = client->csqcnumedicts;
508         for (number = 1;number < end;number++)
509         {
510                 if (!client->csqcentityscope[number])
511                         continue;
512                 sendflags = client->csqcentitysendflags[number];
513                 if (!sendflags)
514                         continue;
515                 if(db->num >= NUM_CSQCENTITIES_PER_FRAME)
516                         break;
517                 ed = prog->edicts + number;
518                 // entity scope is either update (2) or remove (1)
519                 if (client->csqcentityscope[number] == 1)
520                 {
521                         // write a remove message
522                         // first write the message identifier if needed
523                         if(!sectionstarted)
524                         {
525                                 sectionstarted = 1;
526                                 MSG_WriteByte(msg, svc_csqcentities);
527                         }
528                         // write the remove message
529                         {
530                                 ENTITYSIZEPROFILING_START(msg, number);
531                                 MSG_WriteShort(msg, (unsigned short)number | 0x8000);
532                                 client->csqcentityscope[number] = 0;
533                                 client->csqcentitysendflags[number] = 0xFFFFFF; // resend completely if it becomes active again
534                                 db->entno[db->num] = number;
535                                 db->sendflags[db->num] = -1;
536                                 db->num += 1;
537                                 client->csqcentityglobalhistory[number] = 1;
538                                 ENTITYSIZEPROFILING_END(msg, number);
539                         }
540                         if (msg->cursize + 17 >= maxsize)
541                                 break;
542                 }
543                 else
544                 {
545                         // write an update
546                         // save the cursize value in case we overflow and have to rollback
547                         int oldcursize = msg->cursize;
548                         client->csqcentityscope[number] = 1;
549                         if (PRVM_serveredictfunction(ed, SendEntity))
550                         {
551                                 if(!sectionstarted)
552                                         MSG_WriteByte(msg, svc_csqcentities);
553                                 {
554                                         ENTITYSIZEPROFILING_START(msg, number);
555                                         MSG_WriteShort(msg, number);
556                                         msg->allowoverflow = true;
557                                         PRVM_G_INT(OFS_PARM0) = sv.writeentitiestoclient_cliententitynumber;
558                                         PRVM_G_FLOAT(OFS_PARM1) = sendflags;
559                                         PRVM_serverglobaledict(self) = number;
560                                         prog->ExecuteProgram(prog, PRVM_serveredictfunction(ed, SendEntity), "Null SendEntity\n");
561                                         msg->allowoverflow = false;
562                                         if(PRVM_G_FLOAT(OFS_RETURN) && msg->cursize + 2 <= maxsize)
563                                         {
564                                                 // an update has been successfully written
565                                                 client->csqcentitysendflags[number] = 0;
566                                                 db->entno[db->num] = number;
567                                                 db->sendflags[db->num] = sendflags;
568                                                 db->num += 1;
569                                                 client->csqcentityglobalhistory[number] = 1;
570                                                 // and take note that we have begun the svc_csqcentities
571                                                 // section of the packet
572                                                 sectionstarted = 1;
573                                                 ENTITYSIZEPROFILING_END(msg, number);
574                                                 if (msg->cursize + 17 >= maxsize)
575                                                         break;
576                                                 continue;
577                                         }
578                                 }
579                         }
580                         // self.SendEntity returned false (or does not exist) or the
581                         // update was too big for this packet - rollback the buffer to its
582                         // state before the writes occurred, we'll try again next frame
583                         msg->cursize = oldcursize;
584                         msg->overflowed = false;
585                 }
586         }
587         if (sectionstarted)
588         {
589                 // write index 0 to end the update (0 is never used by real entities)
590                 MSG_WriteShort(msg, 0);
591         }
592
593         if(db->num == 0)
594                 // if no single ent got added, remove the frame from the DB again, to allow
595                 // for a larger history
596                 EntityFrameCSQC_DeallocFrame(client, framenum);
597         
598         return sectionstarted;
599 }
600
601 void Protocol_UpdateClientStats(const int *stats)
602 {
603         int i;
604         // update the stats array and set deltabits for any changed stats
605         for (i = 0;i < MAX_CL_STATS;i++)
606         {
607                 if (host_client->stats[i] != stats[i])
608                 {
609                         host_client->statsdeltabits[i >> 3] |= 1 << (i & 7);
610                         host_client->stats[i] = stats[i];
611                 }
612         }
613 }
614
615 // only a few stats are within the 32 stat limit of Quake, and most of them
616 // are sent every frame in svc_clientdata messages, so we only send the
617 // remaining ones here
618 static const int sendquakestats[] =
619 {
620 // quake did not send these secrets/monsters stats in this way, but doing so
621 // allows a mod to increase STAT_TOTALMONSTERS during the game, and ensures
622 // that STAT_SECRETS and STAT_MONSTERS are always correct (even if a client
623 // didn't receive an svc_foundsecret or svc_killedmonster), which may be most
624 // valuable if randomly seeking around in a demo
625 STAT_TOTALSECRETS, // never changes during game
626 STAT_TOTALMONSTERS, // changes in some mods
627 STAT_SECRETS, // this makes svc_foundsecret unnecessary
628 STAT_MONSTERS, // this makes svc_killedmonster unnecessary
629 STAT_VIEWHEIGHT, // sent just for FTEQW clients
630 STAT_VIEWZOOM, // this rarely changes
631 -1,
632 };
633
634 void Protocol_WriteStatsReliable(void)
635 {
636         int i, j;
637         if (!host_client->netconnection)
638                 return;
639         // detect changes in stats and write reliable messages
640         // this only deals with 32 stats because the older protocols which use
641         // this function can only cope with 32 stats,
642         // they also do not support svc_updatestatubyte which was introduced in
643         // DP6 protocol (except for QW)
644         for (j = 0;sendquakestats[j] >= 0;j++)
645         {
646                 i = sendquakestats[j];
647                 // check if this bit is set
648                 if (host_client->statsdeltabits[i >> 3] & (1 << (i & 7)))
649                 {
650                         host_client->statsdeltabits[i >> 3] -= (1 << (i & 7));
651                         // send the stat as a byte if possible
652                         if (sv.protocol == PROTOCOL_QUAKEWORLD)
653                         {
654                                 if (host_client->stats[i] >= 0 && host_client->stats[i] < 256)
655                                 {
656                                         MSG_WriteByte(&host_client->netconnection->message, qw_svc_updatestat);
657                                         MSG_WriteByte(&host_client->netconnection->message, i);
658                                         MSG_WriteByte(&host_client->netconnection->message, host_client->stats[i]);
659                                 }
660                                 else
661                                 {
662                                         MSG_WriteByte(&host_client->netconnection->message, qw_svc_updatestatlong);
663                                         MSG_WriteByte(&host_client->netconnection->message, i);
664                                         MSG_WriteLong(&host_client->netconnection->message, host_client->stats[i]);
665                                 }
666                         }
667                         else
668                         {
669                                 // this could make use of svc_updatestatubyte in DP6 and later
670                                 // protocols but those protocols do not use this function
671                                 MSG_WriteByte(&host_client->netconnection->message, svc_updatestat);
672                                 MSG_WriteByte(&host_client->netconnection->message, i);
673                                 MSG_WriteLong(&host_client->netconnection->message, host_client->stats[i]);
674                         }
675                 }
676         }
677 }
678
679
680 qboolean EntityFrameQuake_WriteFrame(sizebuf_t *msg, int maxsize, int numstates, const entity_state_t **states)
681 {
682         prvm_prog_t *prog = SVVM_prog;
683         const entity_state_t *s;
684         entity_state_t baseline;
685         int i, bits;
686         sizebuf_t buf;
687         unsigned char data[128];
688         qboolean success = false;
689
690         // prepare the buffer
691         memset(&buf, 0, sizeof(buf));
692         buf.data = data;
693         buf.maxsize = sizeof(data);
694
695         for (i = 0;i < numstates;i++)
696         {
697                 ENTITYSIZEPROFILING_START(msg, states[i]->number);
698                 s = states[i];
699                 if(PRVM_serveredictfunction((&prog->edicts[s->number]), SendEntity))
700                         continue;
701
702                 // prepare the buffer
703                 SZ_Clear(&buf);
704
705 // send an update
706                 bits = 0;
707                 if (s->number >= 256)
708                         bits |= U_LONGENTITY;
709                 if (s->flags & RENDER_STEP)
710                         bits |= U_STEP;
711                 if (s->flags & RENDER_VIEWMODEL)
712                         bits |= U_VIEWMODEL;
713                 if (s->flags & RENDER_GLOWTRAIL)
714                         bits |= U_GLOWTRAIL;
715                 if (s->flags & RENDER_EXTERIORMODEL)
716                         bits |= U_EXTERIORMODEL;
717
718                 // LordHavoc: old stuff, but rewritten to have more exact tolerances
719                 baseline = prog->edicts[s->number].priv.server->baseline;
720                 if (baseline.origin[0] != s->origin[0])
721                         bits |= U_ORIGIN1;
722                 if (baseline.origin[1] != s->origin[1])
723                         bits |= U_ORIGIN2;
724                 if (baseline.origin[2] != s->origin[2])
725                         bits |= U_ORIGIN3;
726                 if (baseline.angles[0] != s->angles[0])
727                         bits |= U_ANGLE1;
728                 if (baseline.angles[1] != s->angles[1])
729                         bits |= U_ANGLE2;
730                 if (baseline.angles[2] != s->angles[2])
731                         bits |= U_ANGLE3;
732                 if (baseline.colormap != s->colormap)
733                         bits |= U_COLORMAP;
734                 if (baseline.skin != s->skin)
735                         bits |= U_SKIN;
736                 if (baseline.frame != s->frame)
737                 {
738                         bits |= U_FRAME;
739                         if (s->frame & 0xFF00)
740                                 bits |= U_FRAME2;
741                 }
742                 if (baseline.effects != s->effects)
743                 {
744                         bits |= U_EFFECTS;
745                         if (s->effects & 0xFF00)
746                                 bits |= U_EFFECTS2;
747                 }
748                 if (baseline.modelindex != s->modelindex)
749                 {
750                         bits |= U_MODEL;
751                         if ((s->modelindex & 0xFF00) && sv.protocol != PROTOCOL_NEHAHRABJP && sv.protocol != PROTOCOL_NEHAHRABJP2 && sv.protocol != PROTOCOL_NEHAHRABJP3)
752                                 bits |= U_MODEL2;
753                 }
754                 if (baseline.alpha != s->alpha)
755                         bits |= U_ALPHA;
756                 if (baseline.scale != s->scale)
757                         bits |= U_SCALE;
758                 if (baseline.glowsize != s->glowsize)
759                         bits |= U_GLOWSIZE;
760                 if (baseline.glowcolor != s->glowcolor)
761                         bits |= U_GLOWCOLOR;
762                 if (!VectorCompare(baseline.colormod, s->colormod))
763                         bits |= U_COLORMOD;
764
765                 // if extensions are disabled, clear the relevant update flags
766                 if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_NEHAHRAMOVIE)
767                         bits &= 0x7FFF;
768                 if (sv.protocol == PROTOCOL_NEHAHRAMOVIE)
769                         if (s->alpha != 255 || s->effects & EF_FULLBRIGHT)
770                                 bits |= U_EXTEND1;
771
772                 // write the message
773                 if (bits >= 16777216)
774                         bits |= U_EXTEND2;
775                 if (bits >= 65536)
776                         bits |= U_EXTEND1;
777                 if (bits >= 256)
778                         bits |= U_MOREBITS;
779                 bits |= U_SIGNAL;
780
781                 MSG_WriteByte (&buf, bits);
782                 if (bits & U_MOREBITS)          MSG_WriteByte(&buf, bits>>8);
783                 if (sv.protocol != PROTOCOL_NEHAHRAMOVIE)
784                 {
785                         if (bits & U_EXTEND1)   MSG_WriteByte(&buf, bits>>16);
786                         if (bits & U_EXTEND2)   MSG_WriteByte(&buf, bits>>24);
787                 }
788                 if (bits & U_LONGENTITY)        MSG_WriteShort(&buf, s->number);
789                 else                                            MSG_WriteByte(&buf, s->number);
790
791                 if (bits & U_MODEL)
792                 {
793                         if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
794                                 MSG_WriteShort(&buf, s->modelindex);
795                         else
796                                 MSG_WriteByte(&buf, s->modelindex);
797                 }
798                 if (bits & U_FRAME)                     MSG_WriteByte(&buf, s->frame);
799                 if (bits & U_COLORMAP)          MSG_WriteByte(&buf, s->colormap);
800                 if (bits & U_SKIN)                      MSG_WriteByte(&buf, s->skin);
801                 if (bits & U_EFFECTS)           MSG_WriteByte(&buf, s->effects);
802                 if (bits & U_ORIGIN1)           MSG_WriteCoord(&buf, s->origin[0], sv.protocol);
803                 if (bits & U_ANGLE1)            MSG_WriteAngle(&buf, s->angles[0], sv.protocol);
804                 if (bits & U_ORIGIN2)           MSG_WriteCoord(&buf, s->origin[1], sv.protocol);
805                 if (bits & U_ANGLE2)            MSG_WriteAngle(&buf, s->angles[1], sv.protocol);
806                 if (bits & U_ORIGIN3)           MSG_WriteCoord(&buf, s->origin[2], sv.protocol);
807                 if (bits & U_ANGLE3)            MSG_WriteAngle(&buf, s->angles[2], sv.protocol);
808                 if (bits & U_ALPHA)                     MSG_WriteByte(&buf, s->alpha);
809                 if (bits & U_SCALE)                     MSG_WriteByte(&buf, s->scale);
810                 if (bits & U_EFFECTS2)          MSG_WriteByte(&buf, s->effects >> 8);
811                 if (bits & U_GLOWSIZE)          MSG_WriteByte(&buf, s->glowsize);
812                 if (bits & U_GLOWCOLOR)         MSG_WriteByte(&buf, s->glowcolor);
813                 if (bits & U_COLORMOD)          {int c = ((int)bound(0, s->colormod[0] * (7.0f / 32.0f), 7) << 5) | ((int)bound(0, s->colormod[1] * (7.0f / 32.0f), 7) << 2) | ((int)bound(0, s->colormod[2] * (3.0f / 32.0f), 3) << 0);MSG_WriteByte(&buf, c);}
814                 if (bits & U_FRAME2)            MSG_WriteByte(&buf, s->frame >> 8);
815                 if (bits & U_MODEL2)            MSG_WriteByte(&buf, s->modelindex >> 8);
816
817                 // the nasty protocol
818                 if ((bits & U_EXTEND1) && sv.protocol == PROTOCOL_NEHAHRAMOVIE)
819                 {
820                         if (s->effects & EF_FULLBRIGHT)
821                         {
822                                 MSG_WriteFloat(&buf, 2); // QSG protocol version
823                                 MSG_WriteFloat(&buf, s->alpha <= 0 ? 0 : (s->alpha >= 255 ? 1 : s->alpha * (1.0f / 255.0f))); // alpha
824                                 MSG_WriteFloat(&buf, 1); // fullbright
825                         }
826                         else
827                         {
828                                 MSG_WriteFloat(&buf, 1); // QSG protocol version
829                                 MSG_WriteFloat(&buf, s->alpha <= 0 ? 0 : (s->alpha >= 255 ? 1 : s->alpha * (1.0f / 255.0f))); // alpha
830                         }
831                 }
832
833                 // if the commit is full, we're done this frame
834                 if (msg->cursize + buf.cursize > maxsize)
835                 {
836                         // next frame we will continue where we left off
837                         break;
838                 }
839                 // write the message to the packet
840                 SZ_Write(msg, buf.data, buf.cursize);
841                 success = true;
842                 ENTITYSIZEPROFILING_END(msg, s->number);
843         }
844         return success;
845 }
846
847 int EntityState_DeltaBits(const entity_state_t *o, const entity_state_t *n)
848 {
849         unsigned int bits;
850         // if o is not active, delta from default
851         if (o->active != ACTIVE_NETWORK)
852                 o = &defaultstate;
853         bits = 0;
854         if (fabs(n->origin[0] - o->origin[0]) > (1.0f / 256.0f))
855                 bits |= E_ORIGIN1;
856         if (fabs(n->origin[1] - o->origin[1]) > (1.0f / 256.0f))
857                 bits |= E_ORIGIN2;
858         if (fabs(n->origin[2] - o->origin[2]) > (1.0f / 256.0f))
859                 bits |= E_ORIGIN3;
860         if ((unsigned char) (n->angles[0] * (256.0f / 360.0f)) != (unsigned char) (o->angles[0] * (256.0f / 360.0f)))
861                 bits |= E_ANGLE1;
862         if ((unsigned char) (n->angles[1] * (256.0f / 360.0f)) != (unsigned char) (o->angles[1] * (256.0f / 360.0f)))
863                 bits |= E_ANGLE2;
864         if ((unsigned char) (n->angles[2] * (256.0f / 360.0f)) != (unsigned char) (o->angles[2] * (256.0f / 360.0f)))
865                 bits |= E_ANGLE3;
866         if ((n->modelindex ^ o->modelindex) & 0x00FF)
867                 bits |= E_MODEL1;
868         if ((n->modelindex ^ o->modelindex) & 0xFF00)
869                 bits |= E_MODEL2;
870         if ((n->frame ^ o->frame) & 0x00FF)
871                 bits |= E_FRAME1;
872         if ((n->frame ^ o->frame) & 0xFF00)
873                 bits |= E_FRAME2;
874         if ((n->effects ^ o->effects) & 0x00FF)
875                 bits |= E_EFFECTS1;
876         if ((n->effects ^ o->effects) & 0xFF00)
877                 bits |= E_EFFECTS2;
878         if (n->colormap != o->colormap)
879                 bits |= E_COLORMAP;
880         if (n->skin != o->skin)
881                 bits |= E_SKIN;
882         if (n->alpha != o->alpha)
883                 bits |= E_ALPHA;
884         if (n->scale != o->scale)
885                 bits |= E_SCALE;
886         if (n->glowsize != o->glowsize)
887                 bits |= E_GLOWSIZE;
888         if (n->glowcolor != o->glowcolor)
889                 bits |= E_GLOWCOLOR;
890         if (n->flags != o->flags)
891                 bits |= E_FLAGS;
892         if (n->tagindex != o->tagindex || n->tagentity != o->tagentity)
893                 bits |= E_TAGATTACHMENT;
894         if (n->light[0] != o->light[0] || n->light[1] != o->light[1] || n->light[2] != o->light[2] || n->light[3] != o->light[3])
895                 bits |= E_LIGHT;
896         if (n->lightstyle != o->lightstyle)
897                 bits |= E_LIGHTSTYLE;
898         if (n->lightpflags != o->lightpflags)
899                 bits |= E_LIGHTPFLAGS;
900
901         if (bits)
902         {
903                 if (bits &  0xFF000000)
904                         bits |= 0x00800000;
905                 if (bits &  0x00FF0000)
906                         bits |= 0x00008000;
907                 if (bits &  0x0000FF00)
908                         bits |= 0x00000080;
909         }
910         return bits;
911 }
912
913 void EntityState_WriteExtendBits(sizebuf_t *msg, unsigned int bits)
914 {
915         MSG_WriteByte(msg, bits & 0xFF);
916         if (bits & 0x00000080)
917         {
918                 MSG_WriteByte(msg, (bits >> 8) & 0xFF);
919                 if (bits & 0x00008000)
920                 {
921                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
922                         if (bits & 0x00800000)
923                                 MSG_WriteByte(msg, (bits >> 24) & 0xFF);
924                 }
925         }
926 }
927
928 void EntityState_WriteFields(const entity_state_t *ent, sizebuf_t *msg, unsigned int bits)
929 {
930         if (sv.protocol == PROTOCOL_DARKPLACES2)
931         {
932                 if (bits & E_ORIGIN1)
933                         MSG_WriteCoord16i(msg, ent->origin[0]);
934                 if (bits & E_ORIGIN2)
935                         MSG_WriteCoord16i(msg, ent->origin[1]);
936                 if (bits & E_ORIGIN3)
937                         MSG_WriteCoord16i(msg, ent->origin[2]);
938         }
939         else
940         {
941                 // LordHavoc: have to write flags first, as they can modify protocol
942                 if (bits & E_FLAGS)
943                         MSG_WriteByte(msg, ent->flags);
944                 if (ent->flags & RENDER_LOWPRECISION)
945                 {
946                         if (bits & E_ORIGIN1)
947                                 MSG_WriteCoord16i(msg, ent->origin[0]);
948                         if (bits & E_ORIGIN2)
949                                 MSG_WriteCoord16i(msg, ent->origin[1]);
950                         if (bits & E_ORIGIN3)
951                                 MSG_WriteCoord16i(msg, ent->origin[2]);
952                 }
953                 else
954                 {
955                         if (bits & E_ORIGIN1)
956                                 MSG_WriteCoord32f(msg, ent->origin[0]);
957                         if (bits & E_ORIGIN2)
958                                 MSG_WriteCoord32f(msg, ent->origin[1]);
959                         if (bits & E_ORIGIN3)
960                                 MSG_WriteCoord32f(msg, ent->origin[2]);
961                 }
962         }
963         if ((sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4) && (ent->flags & RENDER_LOWPRECISION))
964         {
965                 if (bits & E_ANGLE1)
966                         MSG_WriteAngle8i(msg, ent->angles[0]);
967                 if (bits & E_ANGLE2)
968                         MSG_WriteAngle8i(msg, ent->angles[1]);
969                 if (bits & E_ANGLE3)
970                         MSG_WriteAngle8i(msg, ent->angles[2]);
971         }
972         else
973         {
974                 if (bits & E_ANGLE1)
975                         MSG_WriteAngle16i(msg, ent->angles[0]);
976                 if (bits & E_ANGLE2)
977                         MSG_WriteAngle16i(msg, ent->angles[1]);
978                 if (bits & E_ANGLE3)
979                         MSG_WriteAngle16i(msg, ent->angles[2]);
980         }
981         if (bits & E_MODEL1)
982                 MSG_WriteByte(msg, ent->modelindex & 0xFF);
983         if (bits & E_MODEL2)
984                 MSG_WriteByte(msg, (ent->modelindex >> 8) & 0xFF);
985         if (bits & E_FRAME1)
986                 MSG_WriteByte(msg, ent->frame & 0xFF);
987         if (bits & E_FRAME2)
988                 MSG_WriteByte(msg, (ent->frame >> 8) & 0xFF);
989         if (bits & E_EFFECTS1)
990                 MSG_WriteByte(msg, ent->effects & 0xFF);
991         if (bits & E_EFFECTS2)
992                 MSG_WriteByte(msg, (ent->effects >> 8) & 0xFF);
993         if (bits & E_COLORMAP)
994                 MSG_WriteByte(msg, ent->colormap);
995         if (bits & E_SKIN)
996                 MSG_WriteByte(msg, ent->skin);
997         if (bits & E_ALPHA)
998                 MSG_WriteByte(msg, ent->alpha);
999         if (bits & E_SCALE)
1000                 MSG_WriteByte(msg, ent->scale);
1001         if (bits & E_GLOWSIZE)
1002                 MSG_WriteByte(msg, ent->glowsize);
1003         if (bits & E_GLOWCOLOR)
1004                 MSG_WriteByte(msg, ent->glowcolor);
1005         if (sv.protocol == PROTOCOL_DARKPLACES2)
1006                 if (bits & E_FLAGS)
1007                         MSG_WriteByte(msg, ent->flags);
1008         if (bits & E_TAGATTACHMENT)
1009         {
1010                 MSG_WriteShort(msg, ent->tagentity);
1011                 MSG_WriteByte(msg, ent->tagindex);
1012         }
1013         if (bits & E_LIGHT)
1014         {
1015                 MSG_WriteShort(msg, ent->light[0]);
1016                 MSG_WriteShort(msg, ent->light[1]);
1017                 MSG_WriteShort(msg, ent->light[2]);
1018                 MSG_WriteShort(msg, ent->light[3]);
1019         }
1020         if (bits & E_LIGHTSTYLE)
1021                 MSG_WriteByte(msg, ent->lightstyle);
1022         if (bits & E_LIGHTPFLAGS)
1023                 MSG_WriteByte(msg, ent->lightpflags);
1024 }
1025
1026 void EntityState_WriteUpdate(const entity_state_t *ent, sizebuf_t *msg, const entity_state_t *delta)
1027 {
1028         prvm_prog_t *prog = SVVM_prog;
1029         unsigned int bits;
1030         ENTITYSIZEPROFILING_START(msg, ent->number);
1031         if (ent->active == ACTIVE_NETWORK)
1032         {
1033                 // entity is active, check for changes from the delta
1034                 if ((bits = EntityState_DeltaBits(delta, ent)))
1035                 {
1036                         // write the update number, bits, and fields
1037                         MSG_WriteShort(msg, ent->number);
1038                         EntityState_WriteExtendBits(msg, bits);
1039                         EntityState_WriteFields(ent, msg, bits);
1040                 }
1041         }
1042         else
1043         {
1044                 // entity is inactive, check if the delta was active
1045                 if (delta->active == ACTIVE_NETWORK)
1046                 {
1047                         // write the remove number
1048                         MSG_WriteShort(msg, ent->number | 0x8000);
1049                 }
1050         }
1051         ENTITYSIZEPROFILING_END(msg, ent->number);
1052 }
1053
1054 int EntityState_ReadExtendBits(void)
1055 {
1056         unsigned int bits;
1057         bits = MSG_ReadByte(&cl_message);
1058         if (bits & 0x00000080)
1059         {
1060                 bits |= MSG_ReadByte(&cl_message) << 8;
1061                 if (bits & 0x00008000)
1062                 {
1063                         bits |= MSG_ReadByte(&cl_message) << 16;
1064                         if (bits & 0x00800000)
1065                                 bits |= MSG_ReadByte(&cl_message) << 24;
1066                 }
1067         }
1068         return bits;
1069 }
1070
1071 void EntityState_ReadFields(entity_state_t *e, unsigned int bits)
1072 {
1073         if (cls.protocol == PROTOCOL_DARKPLACES2)
1074         {
1075                 if (bits & E_ORIGIN1)
1076                         e->origin[0] = MSG_ReadCoord16i(&cl_message);
1077                 if (bits & E_ORIGIN2)
1078                         e->origin[1] = MSG_ReadCoord16i(&cl_message);
1079                 if (bits & E_ORIGIN3)
1080                         e->origin[2] = MSG_ReadCoord16i(&cl_message);
1081         }
1082         else
1083         {
1084                 if (bits & E_FLAGS)
1085                         e->flags = MSG_ReadByte(&cl_message);
1086                 if (e->flags & RENDER_LOWPRECISION)
1087                 {
1088                         if (bits & E_ORIGIN1)
1089                                 e->origin[0] = MSG_ReadCoord16i(&cl_message);
1090                         if (bits & E_ORIGIN2)
1091                                 e->origin[1] = MSG_ReadCoord16i(&cl_message);
1092                         if (bits & E_ORIGIN3)
1093                                 e->origin[2] = MSG_ReadCoord16i(&cl_message);
1094                 }
1095                 else
1096                 {
1097                         if (bits & E_ORIGIN1)
1098                                 e->origin[0] = MSG_ReadCoord32f(&cl_message);
1099                         if (bits & E_ORIGIN2)
1100                                 e->origin[1] = MSG_ReadCoord32f(&cl_message);
1101                         if (bits & E_ORIGIN3)
1102                                 e->origin[2] = MSG_ReadCoord32f(&cl_message);
1103                 }
1104         }
1105         if ((cls.protocol == PROTOCOL_DARKPLACES5 || cls.protocol == PROTOCOL_DARKPLACES6) && !(e->flags & RENDER_LOWPRECISION))
1106         {
1107                 if (bits & E_ANGLE1)
1108                         e->angles[0] = MSG_ReadAngle16i(&cl_message);
1109                 if (bits & E_ANGLE2)
1110                         e->angles[1] = MSG_ReadAngle16i(&cl_message);
1111                 if (bits & E_ANGLE3)
1112                         e->angles[2] = MSG_ReadAngle16i(&cl_message);
1113         }
1114         else
1115         {
1116                 if (bits & E_ANGLE1)
1117                         e->angles[0] = MSG_ReadAngle8i(&cl_message);
1118                 if (bits & E_ANGLE2)
1119                         e->angles[1] = MSG_ReadAngle8i(&cl_message);
1120                 if (bits & E_ANGLE3)
1121                         e->angles[2] = MSG_ReadAngle8i(&cl_message);
1122         }
1123         if (bits & E_MODEL1)
1124                 e->modelindex = (e->modelindex & 0xFF00) | (unsigned int) MSG_ReadByte(&cl_message);
1125         if (bits & E_MODEL2)
1126                 e->modelindex = (e->modelindex & 0x00FF) | ((unsigned int) MSG_ReadByte(&cl_message) << 8);
1127         if (bits & E_FRAME1)
1128                 e->frame = (e->frame & 0xFF00) | (unsigned int) MSG_ReadByte(&cl_message);
1129         if (bits & E_FRAME2)
1130                 e->frame = (e->frame & 0x00FF) | ((unsigned int) MSG_ReadByte(&cl_message) << 8);
1131         if (bits & E_EFFECTS1)
1132                 e->effects = (e->effects & 0xFF00) | (unsigned int) MSG_ReadByte(&cl_message);
1133         if (bits & E_EFFECTS2)
1134                 e->effects = (e->effects & 0x00FF) | ((unsigned int) MSG_ReadByte(&cl_message) << 8);
1135         if (bits & E_COLORMAP)
1136                 e->colormap = MSG_ReadByte(&cl_message);
1137         if (bits & E_SKIN)
1138                 e->skin = MSG_ReadByte(&cl_message);
1139         if (bits & E_ALPHA)
1140                 e->alpha = MSG_ReadByte(&cl_message);
1141         if (bits & E_SCALE)
1142                 e->scale = MSG_ReadByte(&cl_message);
1143         if (bits & E_GLOWSIZE)
1144                 e->glowsize = MSG_ReadByte(&cl_message);
1145         if (bits & E_GLOWCOLOR)
1146                 e->glowcolor = MSG_ReadByte(&cl_message);
1147         if (cls.protocol == PROTOCOL_DARKPLACES2)
1148                 if (bits & E_FLAGS)
1149                         e->flags = MSG_ReadByte(&cl_message);
1150         if (bits & E_TAGATTACHMENT)
1151         {
1152                 e->tagentity = (unsigned short) MSG_ReadShort(&cl_message);
1153                 e->tagindex = MSG_ReadByte(&cl_message);
1154         }
1155         if (bits & E_LIGHT)
1156         {
1157                 e->light[0] = (unsigned short) MSG_ReadShort(&cl_message);
1158                 e->light[1] = (unsigned short) MSG_ReadShort(&cl_message);
1159                 e->light[2] = (unsigned short) MSG_ReadShort(&cl_message);
1160                 e->light[3] = (unsigned short) MSG_ReadShort(&cl_message);
1161         }
1162         if (bits & E_LIGHTSTYLE)
1163                 e->lightstyle = MSG_ReadByte(&cl_message);
1164         if (bits & E_LIGHTPFLAGS)
1165                 e->lightpflags = MSG_ReadByte(&cl_message);
1166
1167         if (developer_networkentities.integer >= 2)
1168         {
1169                 Con_Printf("ReadFields e%i", e->number);
1170
1171                 if (bits & E_ORIGIN1)
1172                         Con_Printf(" E_ORIGIN1 %f", e->origin[0]);
1173                 if (bits & E_ORIGIN2)
1174                         Con_Printf(" E_ORIGIN2 %f", e->origin[1]);
1175                 if (bits & E_ORIGIN3)
1176                         Con_Printf(" E_ORIGIN3 %f", e->origin[2]);
1177                 if (bits & E_ANGLE1)
1178                         Con_Printf(" E_ANGLE1 %f", e->angles[0]);
1179                 if (bits & E_ANGLE2)
1180                         Con_Printf(" E_ANGLE2 %f", e->angles[1]);
1181                 if (bits & E_ANGLE3)
1182                         Con_Printf(" E_ANGLE3 %f", e->angles[2]);
1183                 if (bits & (E_MODEL1 | E_MODEL2))
1184                         Con_Printf(" E_MODEL %i", e->modelindex);
1185
1186                 if (bits & (E_FRAME1 | E_FRAME2))
1187                         Con_Printf(" E_FRAME %i", e->frame);
1188                 if (bits & (E_EFFECTS1 | E_EFFECTS2))
1189                         Con_Printf(" E_EFFECTS %i", e->effects);
1190                 if (bits & E_ALPHA)
1191                         Con_Printf(" E_ALPHA %f", e->alpha / 255.0f);
1192                 if (bits & E_SCALE)
1193                         Con_Printf(" E_SCALE %f", e->scale / 16.0f);
1194                 if (bits & E_COLORMAP)
1195                         Con_Printf(" E_COLORMAP %i", e->colormap);
1196                 if (bits & E_SKIN)
1197                         Con_Printf(" E_SKIN %i", e->skin);
1198
1199                 if (bits & E_GLOWSIZE)
1200                         Con_Printf(" E_GLOWSIZE %i", e->glowsize * 4);
1201                 if (bits & E_GLOWCOLOR)
1202                         Con_Printf(" E_GLOWCOLOR %i", e->glowcolor);
1203
1204                 if (bits & E_LIGHT)
1205                         Con_Printf(" E_LIGHT %i:%i:%i:%i", e->light[0], e->light[1], e->light[2], e->light[3]);
1206                 if (bits & E_LIGHTPFLAGS)
1207                         Con_Printf(" E_LIGHTPFLAGS %i", e->lightpflags);
1208
1209                 if (bits & E_TAGATTACHMENT)
1210                         Con_Printf(" E_TAGATTACHMENT e%i:%i", e->tagentity, e->tagindex);
1211                 if (bits & E_LIGHTSTYLE)
1212                         Con_Printf(" E_LIGHTSTYLE %i", e->lightstyle);
1213                 Con_Print("\n");
1214         }
1215 }
1216
1217 // (client and server) allocates a new empty database
1218 entityframe_database_t *EntityFrame_AllocDatabase(mempool_t *mempool)
1219 {
1220         return (entityframe_database_t *)Mem_Alloc(mempool, sizeof(entityframe_database_t));
1221 }
1222
1223 // (client and server) frees the database
1224 void EntityFrame_FreeDatabase(entityframe_database_t *d)
1225 {
1226         Mem_Free(d);
1227 }
1228
1229 // (server) clears the database to contain no frames (thus delta compression compresses against nothing)
1230 void EntityFrame_ClearDatabase(entityframe_database_t *d)
1231 {
1232         memset(d, 0, sizeof(*d));
1233 }
1234
1235 // (server and client) removes frames older than 'frame' from database
1236 void EntityFrame_AckFrame(entityframe_database_t *d, int frame)
1237 {
1238         int i;
1239         d->ackframenum = frame;
1240         for (i = 0;i < d->numframes && d->frames[i].framenum < frame;i++);
1241         // ignore outdated frame acks (out of order packets)
1242         if (i == 0)
1243                 return;
1244         d->numframes -= i;
1245         // if some queue is left, slide it down to beginning of array
1246         if (d->numframes)
1247                 memmove(&d->frames[0], &d->frames[i], sizeof(d->frames[0]) * d->numframes);
1248 }
1249
1250 // (server) clears frame, to prepare for adding entities
1251 void EntityFrame_Clear(entity_frame_t *f, vec3_t eye, int framenum)
1252 {
1253         f->time = 0;
1254         f->framenum = framenum;
1255         f->numentities = 0;
1256         if (eye == NULL)
1257                 VectorClear(f->eye);
1258         else
1259                 VectorCopy(eye, f->eye);
1260 }
1261
1262 // (server and client) reads a frame from the database
1263 void EntityFrame_FetchFrame(entityframe_database_t *d, int framenum, entity_frame_t *f)
1264 {
1265         int i, n;
1266         EntityFrame_Clear(f, NULL, -1);
1267         for (i = 0;i < d->numframes && d->frames[i].framenum < framenum;i++);
1268         if (i < d->numframes && framenum == d->frames[i].framenum)
1269         {
1270                 f->framenum = framenum;
1271                 f->numentities = d->frames[i].endentity - d->frames[i].firstentity;
1272                 n = MAX_ENTITY_DATABASE - (d->frames[i].firstentity % MAX_ENTITY_DATABASE);
1273                 if (n > f->numentities)
1274                         n = f->numentities;
1275                 memcpy(f->entitydata, d->entitydata + d->frames[i].firstentity % MAX_ENTITY_DATABASE, sizeof(*f->entitydata) * n);
1276                 if (f->numentities > n)
1277                         memcpy(f->entitydata + n, d->entitydata, sizeof(*f->entitydata) * (f->numentities - n));
1278                 VectorCopy(d->eye, f->eye);
1279         }
1280 }
1281
1282 // (client) adds a entity_frame to the database, for future reference
1283 void EntityFrame_AddFrame_Client(entityframe_database_t *d, vec3_t eye, int framenum, int numentities, const entity_state_t *entitydata)
1284 {
1285         int n, e;
1286         entity_frameinfo_t *info;
1287
1288         VectorCopy(eye, d->eye);
1289
1290         // figure out how many entity slots are used already
1291         if (d->numframes)
1292         {
1293                 n = d->frames[d->numframes - 1].endentity - d->frames[0].firstentity;
1294                 if (n + numentities > MAX_ENTITY_DATABASE || d->numframes >= MAX_ENTITY_HISTORY)
1295                 {
1296                         // ran out of room, dump database
1297                         EntityFrame_ClearDatabase(d);
1298                 }
1299         }
1300
1301         info = &d->frames[d->numframes];
1302         info->framenum = framenum;
1303         e = -1000;
1304         // make sure we check the newly added frame as well, but we haven't incremented numframes yet
1305         for (n = 0;n <= d->numframes;n++)
1306         {
1307                 if (e >= d->frames[n].framenum)
1308                 {
1309                         if (e == framenum)
1310                                 Con_Print("EntityFrame_AddFrame: tried to add out of sequence frame to database\n");
1311                         else
1312                                 Con_Print("EntityFrame_AddFrame: out of sequence frames in database\n");
1313                         return;
1314                 }
1315                 e = d->frames[n].framenum;
1316         }
1317         // if database still has frames after that...
1318         if (d->numframes)
1319                 info->firstentity = d->frames[d->numframes - 1].endentity;
1320         else
1321                 info->firstentity = 0;
1322         info->endentity = info->firstentity + numentities;
1323         d->numframes++;
1324
1325         n = info->firstentity % MAX_ENTITY_DATABASE;
1326         e = MAX_ENTITY_DATABASE - n;
1327         if (e > numentities)
1328                 e = numentities;
1329         memcpy(d->entitydata + n, entitydata, sizeof(entity_state_t) * e);
1330         if (numentities > e)
1331                 memcpy(d->entitydata, entitydata + e, sizeof(entity_state_t) * (numentities - e));
1332 }
1333
1334 // (server) adds a entity_frame to the database, for future reference
1335 void EntityFrame_AddFrame_Server(entityframe_database_t *d, vec3_t eye, int framenum, int numentities, const entity_state_t **entitydata)
1336 {
1337         int n, e;
1338         entity_frameinfo_t *info;
1339
1340         VectorCopy(eye, d->eye);
1341
1342         // figure out how many entity slots are used already
1343         if (d->numframes)
1344         {
1345                 n = d->frames[d->numframes - 1].endentity - d->frames[0].firstentity;
1346                 if (n + numentities > MAX_ENTITY_DATABASE || d->numframes >= MAX_ENTITY_HISTORY)
1347                 {
1348                         // ran out of room, dump database
1349                         EntityFrame_ClearDatabase(d);
1350                 }
1351         }
1352
1353         info = &d->frames[d->numframes];
1354         info->framenum = framenum;
1355         e = -1000;
1356         // make sure we check the newly added frame as well, but we haven't incremented numframes yet
1357         for (n = 0;n <= d->numframes;n++)
1358         {
1359                 if (e >= d->frames[n].framenum)
1360                 {
1361                         if (e == framenum)
1362                                 Con_Print("EntityFrame_AddFrame: tried to add out of sequence frame to database\n");
1363                         else
1364                                 Con_Print("EntityFrame_AddFrame: out of sequence frames in database\n");
1365                         return;
1366                 }
1367                 e = d->frames[n].framenum;
1368         }
1369         // if database still has frames after that...
1370         if (d->numframes)
1371                 info->firstentity = d->frames[d->numframes - 1].endentity;
1372         else
1373                 info->firstentity = 0;
1374         info->endentity = info->firstentity + numentities;
1375         d->numframes++;
1376
1377         n = info->firstentity % MAX_ENTITY_DATABASE;
1378         e = MAX_ENTITY_DATABASE - n;
1379         if (e > numentities)
1380                 e = numentities;
1381         memcpy(d->entitydata + n, entitydata, sizeof(entity_state_t) * e);
1382         if (numentities > e)
1383                 memcpy(d->entitydata, entitydata + e, sizeof(entity_state_t) * (numentities - e));
1384 }
1385
1386 // (server) writes a frame to network stream
1387 qboolean EntityFrame_WriteFrame(sizebuf_t *msg, int maxsize, entityframe_database_t *d, int numstates, const entity_state_t **states, int viewentnum)
1388 {
1389         prvm_prog_t *prog = SVVM_prog;
1390         int i, onum, number;
1391         entity_frame_t *o = &d->deltaframe;
1392         const entity_state_t *ent, *delta;
1393         vec3_t eye;
1394
1395         d->latestframenum++;
1396
1397         VectorClear(eye);
1398         for (i = 0;i < numstates;i++)
1399         {
1400                 ent = states[i];
1401                 if (ent->number == viewentnum)
1402                 {
1403                         VectorSet(eye, ent->origin[0], ent->origin[1], ent->origin[2] + 22);
1404                         break;
1405                 }
1406         }
1407
1408         EntityFrame_AddFrame_Server(d, eye, d->latestframenum, numstates, states);
1409
1410         EntityFrame_FetchFrame(d, d->ackframenum, o);
1411
1412         MSG_WriteByte (msg, svc_entities);
1413         MSG_WriteLong (msg, o->framenum);
1414         MSG_WriteLong (msg, d->latestframenum);
1415         MSG_WriteFloat (msg, eye[0]);
1416         MSG_WriteFloat (msg, eye[1]);
1417         MSG_WriteFloat (msg, eye[2]);
1418
1419         onum = 0;
1420         for (i = 0;i < numstates;i++)
1421         {
1422                 ent = states[i];
1423                 number = ent->number;
1424
1425                 if (PRVM_serveredictfunction((&prog->edicts[number]), SendEntity))
1426                         continue;
1427                 for (;onum < o->numentities && o->entitydata[onum].number < number;onum++)
1428                 {
1429                         // write remove message
1430                         MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
1431                 }
1432                 if (onum < o->numentities && (o->entitydata[onum].number == number))
1433                 {
1434                         // delta from previous frame
1435                         delta = o->entitydata + onum;
1436                         // advance to next entity in delta frame
1437                         onum++;
1438                 }
1439                 else
1440                 {
1441                         // delta from defaults
1442                         delta = &defaultstate;
1443                 }
1444                 EntityState_WriteUpdate(ent, msg, delta);
1445         }
1446         for (;onum < o->numentities;onum++)
1447         {
1448                 // write remove message
1449                 MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
1450         }
1451         MSG_WriteShort(msg, 0xFFFF);
1452
1453         return true;
1454 }
1455
1456 // (client) reads a frame from network stream
1457 void EntityFrame_CL_ReadFrame(void)
1458 {
1459         int i, number, removed;
1460         entity_frame_t *f, *delta;
1461         entity_state_t *e, *old, *oldend;
1462         entity_t *ent;
1463         entityframe_database_t *d;
1464         if (!cl.entitydatabase)
1465                 cl.entitydatabase = EntityFrame_AllocDatabase(cls.levelmempool);
1466         d = cl.entitydatabase;
1467         f = &d->framedata;
1468         delta = &d->deltaframe;
1469
1470         EntityFrame_Clear(f, NULL, -1);
1471
1472         // read the frame header info
1473         f->time = cl.mtime[0];
1474         number = MSG_ReadLong(&cl_message);
1475         f->framenum = MSG_ReadLong(&cl_message);
1476         CL_NewFrameReceived(f->framenum);
1477         f->eye[0] = MSG_ReadFloat(&cl_message);
1478         f->eye[1] = MSG_ReadFloat(&cl_message);
1479         f->eye[2] = MSG_ReadFloat(&cl_message);
1480         EntityFrame_AckFrame(d, number);
1481         EntityFrame_FetchFrame(d, number, delta);
1482         old = delta->entitydata;
1483         oldend = old + delta->numentities;
1484         // read entities until we hit the magic 0xFFFF end tag
1485         while ((number = (unsigned short) MSG_ReadShort(&cl_message)) != 0xFFFF && !cl_message.badread)
1486         {
1487                 if (cl_message.badread)
1488                         Host_Error("EntityFrame_Read: read error");
1489                 removed = number & 0x8000;
1490                 number &= 0x7FFF;
1491                 if (number >= MAX_EDICTS)
1492                         Host_Error("EntityFrame_Read: number (%i) >= MAX_EDICTS (%i)", number, MAX_EDICTS);
1493
1494                 // seek to entity, while copying any skipped entities (assume unchanged)
1495                 while (old < oldend && old->number < number)
1496                 {
1497                         if (f->numentities >= MAX_ENTITY_DATABASE)
1498                                 Host_Error("EntityFrame_Read: entity list too big");
1499                         f->entitydata[f->numentities] = *old++;
1500                         f->entitydata[f->numentities++].time = cl.mtime[0];
1501                 }
1502                 if (removed)
1503                 {
1504                         if (old < oldend && old->number == number)
1505                                 old++;
1506                         else
1507                                 Con_Printf("EntityFrame_Read: REMOVE on unused entity %i\n", number);
1508                 }
1509                 else
1510                 {
1511                         if (f->numentities >= MAX_ENTITY_DATABASE)
1512                                 Host_Error("EntityFrame_Read: entity list too big");
1513
1514                         // reserve this slot
1515                         e = f->entitydata + f->numentities++;
1516
1517                         if (old < oldend && old->number == number)
1518                         {
1519                                 // delta from old entity
1520                                 *e = *old++;
1521                         }
1522                         else
1523                         {
1524                                 // delta from defaults
1525                                 *e = defaultstate;
1526                         }
1527
1528                         if (cl.num_entities <= number)
1529                         {
1530                                 cl.num_entities = number + 1;
1531                                 if (number >= cl.max_entities)
1532                                         CL_ExpandEntities(number);
1533                         }
1534                         cl.entities_active[number] = true;
1535                         e->active = ACTIVE_NETWORK;
1536                         e->time = cl.mtime[0];
1537                         e->number = number;
1538                         EntityState_ReadFields(e, EntityState_ReadExtendBits());
1539                 }
1540         }
1541         while (old < oldend)
1542         {
1543                 if (f->numentities >= MAX_ENTITY_DATABASE)
1544                         Host_Error("EntityFrame_Read: entity list too big");
1545                 f->entitydata[f->numentities] = *old++;
1546                 f->entitydata[f->numentities++].time = cl.mtime[0];
1547         }
1548         EntityFrame_AddFrame_Client(d, f->eye, f->framenum, f->numentities, f->entitydata);
1549
1550         memset(cl.entities_active, 0, cl.num_entities * sizeof(unsigned char));
1551         number = 1;
1552         for (i = 0;i < f->numentities;i++)
1553         {
1554                 for (;number < f->entitydata[i].number && number < cl.num_entities;number++)
1555                 {
1556                         if (cl.entities_active[number])
1557                         {
1558                                 cl.entities_active[number] = false;
1559                                 cl.entities[number].state_current.active = ACTIVE_NOT;
1560                         }
1561                 }
1562                 if (number >= cl.num_entities)
1563                         break;
1564                 // update the entity
1565                 ent = &cl.entities[number];
1566                 ent->state_previous = ent->state_current;
1567                 ent->state_current = f->entitydata[i];
1568                 CL_MoveLerpEntityStates(ent);
1569                 // the entity lives again...
1570                 cl.entities_active[number] = true;
1571                 number++;
1572         }
1573         for (;number < cl.num_entities;number++)
1574         {
1575                 if (cl.entities_active[number])
1576                 {
1577                         cl.entities_active[number] = false;
1578                         cl.entities[number].state_current.active = ACTIVE_NOT;
1579                 }
1580         }
1581 }
1582
1583
1584 // (client) returns the frame number of the most recent frame recieved
1585 int EntityFrame_MostRecentlyRecievedFrameNum(entityframe_database_t *d)
1586 {
1587         if (d->numframes)
1588                 return d->frames[d->numframes - 1].framenum;
1589         else
1590                 return -1;
1591 }
1592
1593
1594
1595
1596
1597
1598 entity_state_t *EntityFrame4_GetReferenceEntity(entityframe4_database_t *d, int number)
1599 {
1600         if (d->maxreferenceentities <= number)
1601         {
1602                 int oldmax = d->maxreferenceentities;
1603                 entity_state_t *oldentity = d->referenceentity;
1604                 d->maxreferenceentities = (number + 15) & ~7;
1605                 d->referenceentity = (entity_state_t *)Mem_Alloc(d->mempool, d->maxreferenceentities * sizeof(*d->referenceentity));
1606                 if (oldentity)
1607                 {
1608                         memcpy(d->referenceentity, oldentity, oldmax * sizeof(*d->referenceentity));
1609                         Mem_Free(oldentity);
1610                 }
1611                 // clear the newly created entities
1612                 for (;oldmax < d->maxreferenceentities;oldmax++)
1613                 {
1614                         d->referenceentity[oldmax] = defaultstate;
1615                         d->referenceentity[oldmax].number = oldmax;
1616                 }
1617         }
1618         return d->referenceentity + number;
1619 }
1620
1621 void EntityFrame4_AddCommitEntity(entityframe4_database_t *d, const entity_state_t *s)
1622 {
1623         // resize commit's entity list if full
1624         if (d->currentcommit->maxentities <= d->currentcommit->numentities)
1625         {
1626                 entity_state_t *oldentity = d->currentcommit->entity;
1627                 d->currentcommit->maxentities += 8;
1628                 d->currentcommit->entity = (entity_state_t *)Mem_Alloc(d->mempool, d->currentcommit->maxentities * sizeof(*d->currentcommit->entity));
1629                 if (oldentity)
1630                 {
1631                         memcpy(d->currentcommit->entity, oldentity, d->currentcommit->numentities * sizeof(*d->currentcommit->entity));
1632                         Mem_Free(oldentity);
1633                 }
1634         }
1635         d->currentcommit->entity[d->currentcommit->numentities++] = *s;
1636 }
1637
1638 entityframe4_database_t *EntityFrame4_AllocDatabase(mempool_t *pool)
1639 {
1640         entityframe4_database_t *d;
1641         d = (entityframe4_database_t *)Mem_Alloc(pool, sizeof(*d));
1642         d->mempool = pool;
1643         EntityFrame4_ResetDatabase(d);
1644         return d;
1645 }
1646
1647 void EntityFrame4_FreeDatabase(entityframe4_database_t *d)
1648 {
1649         int i;
1650         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1651                 if (d->commit[i].entity)
1652                         Mem_Free(d->commit[i].entity);
1653         if (d->referenceentity)
1654                 Mem_Free(d->referenceentity);
1655         Mem_Free(d);
1656 }
1657
1658 void EntityFrame4_ResetDatabase(entityframe4_database_t *d)
1659 {
1660         int i;
1661         d->referenceframenum = -1;
1662         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1663                 d->commit[i].numentities = 0;
1664         for (i = 0;i < d->maxreferenceentities;i++)
1665                 d->referenceentity[i] = defaultstate;
1666 }
1667
1668 int EntityFrame4_AckFrame(entityframe4_database_t *d, int framenum, int servermode)
1669 {
1670         int i, j, found;
1671         entity_database4_commit_t *commit;
1672         if (framenum == -1)
1673         {
1674                 // reset reference, but leave commits alone
1675                 d->referenceframenum = -1;
1676                 for (i = 0;i < d->maxreferenceentities;i++)
1677                         d->referenceentity[i] = defaultstate;
1678                 // if this is the server, remove commits
1679                         for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1680                                 commit->numentities = 0;
1681                 found = true;
1682         }
1683         else if (d->referenceframenum == framenum)
1684                 found = true;
1685         else
1686         {
1687                 found = false;
1688                 for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1689                 {
1690                         if (commit->numentities && commit->framenum <= framenum)
1691                         {
1692                                 if (commit->framenum == framenum)
1693                                 {
1694                                         found = true;
1695                                         d->referenceframenum = framenum;
1696                                         if (developer_networkentities.integer >= 3)
1697                                         {
1698                                                 for (j = 0;j < commit->numentities;j++)
1699                                                 {
1700                                                         entity_state_t *s = EntityFrame4_GetReferenceEntity(d, commit->entity[j].number);
1701                                                         if (commit->entity[j].active != s->active)
1702                                                         {
1703                                                                 if (commit->entity[j].active == ACTIVE_NETWORK)
1704                                                                         Con_Printf("commit entity %i has become active (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1705                                                                 else
1706                                                                         Con_Printf("commit entity %i has become inactive (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1707                                                         }
1708                                                         *s = commit->entity[j];
1709                                                 }
1710                                         }
1711                                         else
1712                                                 for (j = 0;j < commit->numentities;j++)
1713                                                         *EntityFrame4_GetReferenceEntity(d, commit->entity[j].number) = commit->entity[j];
1714                                 }
1715                                 commit->numentities = 0;
1716                         }
1717                 }
1718         }
1719         if (developer_networkentities.integer >= 1)
1720         {
1721                 Con_Printf("ack ref:%i database updated to: ref:%i commits:", framenum, d->referenceframenum);
1722                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1723                         if (d->commit[i].numentities)
1724                                 Con_Printf(" %i", d->commit[i].framenum);
1725                 Con_Print("\n");
1726         }
1727         return found;
1728 }
1729
1730 void EntityFrame4_CL_ReadFrame(void)
1731 {
1732         int i, n, cnumber, referenceframenum, framenum, enumber, done, stopnumber, skip = false;
1733         entity_state_t *s;
1734         entityframe4_database_t *d;
1735         if (!cl.entitydatabase4)
1736                 cl.entitydatabase4 = EntityFrame4_AllocDatabase(cls.levelmempool);
1737         d = cl.entitydatabase4;
1738         // read the number of the frame this refers to
1739         referenceframenum = MSG_ReadLong(&cl_message);
1740         // read the number of this frame
1741         framenum = MSG_ReadLong(&cl_message);
1742         CL_NewFrameReceived(framenum);
1743         // read the start number
1744         enumber = (unsigned short) MSG_ReadShort(&cl_message);
1745         if (developer_networkentities.integer >= 10)
1746         {
1747                 Con_Printf("recv svc_entities num:%i ref:%i database: ref:%i commits:", framenum, referenceframenum, d->referenceframenum);
1748                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1749                         if (d->commit[i].numentities)
1750                                 Con_Printf(" %i", d->commit[i].framenum);
1751                 Con_Print("\n");
1752         }
1753         if (!EntityFrame4_AckFrame(d, referenceframenum, false))
1754         {
1755                 Con_Print("EntityFrame4_CL_ReadFrame: reference frame invalid (VERY BAD ERROR), this update will be skipped\n");
1756                 skip = true;
1757         }
1758         d->currentcommit = NULL;
1759         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1760         {
1761                 if (!d->commit[i].numentities)
1762                 {
1763                         d->currentcommit = d->commit + i;
1764                         d->currentcommit->framenum = framenum;
1765                         d->currentcommit->numentities = 0;
1766                 }
1767         }
1768         if (d->currentcommit == NULL)
1769         {
1770                 Con_Printf("EntityFrame4_CL_ReadFrame: error while decoding frame %i: database full, reading but not storing this update\n", framenum);
1771                 skip = true;
1772         }
1773         done = false;
1774         while (!done && !cl_message.badread)
1775         {
1776                 // read the number of the modified entity
1777                 // (gaps will be copied unmodified)
1778                 n = (unsigned short)MSG_ReadShort(&cl_message);
1779                 if (n == 0x8000)
1780                 {
1781                         // no more entities in this update, but we still need to copy the
1782                         // rest of the reference entities (final gap)
1783                         done = true;
1784                         // read end of range number, then process normally
1785                         n = (unsigned short)MSG_ReadShort(&cl_message);
1786                 }
1787                 // high bit means it's a remove message
1788                 cnumber = n & 0x7FFF;
1789                 // if this is a live entity we may need to expand the array
1790                 if (cl.num_entities <= cnumber && !(n & 0x8000))
1791                 {
1792                         cl.num_entities = cnumber + 1;
1793                         if (cnumber >= cl.max_entities)
1794                                 CL_ExpandEntities(cnumber);
1795                 }
1796                 // add one (the changed one) if not done
1797                 stopnumber = cnumber + !done;
1798                 // process entities in range from the last one to the changed one
1799                 for (;enumber < stopnumber;enumber++)
1800                 {
1801                         if (skip || enumber >= cl.num_entities)
1802                         {
1803                                 if (enumber == cnumber && (n & 0x8000) == 0)
1804                                 {
1805                                         entity_state_t tempstate;
1806                                         EntityState_ReadFields(&tempstate, EntityState_ReadExtendBits());
1807                                 }
1808                                 continue;
1809                         }
1810                         // slide the current into the previous slot
1811                         cl.entities[enumber].state_previous = cl.entities[enumber].state_current;
1812                         // copy a new current from reference database
1813                         cl.entities[enumber].state_current = *EntityFrame4_GetReferenceEntity(d, enumber);
1814                         s = &cl.entities[enumber].state_current;
1815                         // if this is the one to modify, read more data...
1816                         if (enumber == cnumber)
1817                         {
1818                                 if (n & 0x8000)
1819                                 {
1820                                         // simply removed
1821                                         if (developer_networkentities.integer >= 2)
1822                                                 Con_Printf("entity %i: remove\n", enumber);
1823                                         *s = defaultstate;
1824                                 }
1825                                 else
1826                                 {
1827                                         // read the changes
1828                                         if (developer_networkentities.integer >= 2)
1829                                                 Con_Printf("entity %i: update\n", enumber);
1830                                         s->active = ACTIVE_NETWORK;
1831                                         EntityState_ReadFields(s, EntityState_ReadExtendBits());
1832                                 }
1833                         }
1834                         else if (developer_networkentities.integer >= 4)
1835                                 Con_Printf("entity %i: copy\n", enumber);
1836                         // set the cl.entities_active flag
1837                         cl.entities_active[enumber] = (s->active == ACTIVE_NETWORK);
1838                         // set the update time
1839                         s->time = cl.mtime[0];
1840                         // fix the number (it gets wiped occasionally by copying from defaultstate)
1841                         s->number = enumber;
1842                         // check if we need to update the lerp stuff
1843                         if (s->active == ACTIVE_NETWORK)
1844                                 CL_MoveLerpEntityStates(&cl.entities[enumber]);
1845                         // add this to the commit entry whether it is modified or not
1846                         if (d->currentcommit)
1847                                 EntityFrame4_AddCommitEntity(d, &cl.entities[enumber].state_current);
1848                         // print extra messages if desired
1849                         if (developer_networkentities.integer >= 2 && cl.entities[enumber].state_current.active != cl.entities[enumber].state_previous.active)
1850                         {
1851                                 if (cl.entities[enumber].state_current.active == ACTIVE_NETWORK)
1852                                         Con_Printf("entity #%i has become active\n", enumber);
1853                                 else if (cl.entities[enumber].state_previous.active)
1854                                         Con_Printf("entity #%i has become inactive\n", enumber);
1855                         }
1856                 }
1857         }
1858         d->currentcommit = NULL;
1859         if (skip)
1860                 EntityFrame4_ResetDatabase(d);
1861 }
1862
1863 qboolean EntityFrame4_WriteFrame(sizebuf_t *msg, int maxsize, entityframe4_database_t *d, int numstates, const entity_state_t **states)
1864 {
1865         prvm_prog_t *prog = SVVM_prog;
1866         const entity_state_t *e, *s;
1867         entity_state_t inactiveentitystate;
1868         int i, n, startnumber;
1869         sizebuf_t buf;
1870         unsigned char data[128];
1871
1872         // if there isn't enough space to accomplish anything, skip it
1873         if (msg->cursize + 24 > maxsize)
1874                 return false;
1875
1876         // prepare the buffer
1877         memset(&buf, 0, sizeof(buf));
1878         buf.data = data;
1879         buf.maxsize = sizeof(data);
1880
1881         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1882                 if (!d->commit[i].numentities)
1883                         break;
1884         // if commit buffer full, just don't bother writing an update this frame
1885         if (i == MAX_ENTITY_HISTORY)
1886                 return false;
1887         d->currentcommit = d->commit + i;
1888
1889         // this state's number gets played around with later
1890         inactiveentitystate = defaultstate;
1891
1892         d->currentcommit->numentities = 0;
1893         d->currentcommit->framenum = ++d->latestframenumber;
1894         MSG_WriteByte(msg, svc_entities);
1895         MSG_WriteLong(msg, d->referenceframenum);
1896         MSG_WriteLong(msg, d->currentcommit->framenum);
1897         if (developer_networkentities.integer >= 10)
1898         {
1899                 Con_Printf("send svc_entities num:%i ref:%i (database: ref:%i commits:", d->currentcommit->framenum, d->referenceframenum, d->referenceframenum);
1900                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1901                         if (d->commit[i].numentities)
1902                                 Con_Printf(" %i", d->commit[i].framenum);
1903                 Con_Print(")\n");
1904         }
1905         if (d->currententitynumber >= prog->max_edicts)
1906                 startnumber = 1;
1907         else
1908                 startnumber = bound(1, d->currententitynumber, prog->max_edicts - 1);
1909         MSG_WriteShort(msg, startnumber);
1910         // reset currententitynumber so if the loop does not break it we will
1911         // start at beginning next frame (if it does break, it will set it)
1912         d->currententitynumber = 1;
1913         for (i = 0, n = startnumber;n < prog->max_edicts;n++)
1914         {
1915                 if (PRVM_serveredictfunction((&prog->edicts[n]), SendEntity))
1916                         continue;
1917                 // find the old state to delta from
1918                 e = EntityFrame4_GetReferenceEntity(d, n);
1919                 // prepare the buffer
1920                 SZ_Clear(&buf);
1921                 // entity exists, build an update (if empty there is no change)
1922                 // find the state in the list
1923                 for (;i < numstates && states[i]->number < n;i++);
1924                 // make the message
1925                 s = states[i];
1926                 if (s->number == n)
1927                 {
1928                         // build the update
1929                         EntityState_WriteUpdate(s, &buf, e);
1930                 }
1931                 else
1932                 {
1933                         inactiveentitystate.number = n;
1934                         s = &inactiveentitystate;
1935                         if (e->active == ACTIVE_NETWORK)
1936                         {
1937                                 // entity used to exist but doesn't anymore, send remove
1938                                 MSG_WriteShort(&buf, n | 0x8000);
1939                         }
1940                 }
1941                 // if the commit is full, we're done this frame
1942                 if (msg->cursize + buf.cursize > maxsize - 4)
1943                 {
1944                         // next frame we will continue where we left off
1945                         break;
1946                 }
1947                 // add the entity to the commit
1948                 EntityFrame4_AddCommitEntity(d, s);
1949                 // if the message is empty, skip out now
1950                 if (buf.cursize)
1951                 {
1952                         // write the message to the packet
1953                         SZ_Write(msg, buf.data, buf.cursize);
1954                 }
1955         }
1956         d->currententitynumber = n;
1957
1958         // remove world message (invalid, and thus a good terminator)
1959         MSG_WriteShort(msg, 0x8000);
1960         // write the number of the end entity
1961         MSG_WriteShort(msg, d->currententitynumber);
1962         // just to be sure
1963         d->currentcommit = NULL;
1964
1965         return true;
1966 }
1967
1968
1969
1970
1971 entityframe5_database_t *EntityFrame5_AllocDatabase(mempool_t *pool)
1972 {
1973         int i;
1974         entityframe5_database_t *d;
1975         d = (entityframe5_database_t *)Mem_Alloc(pool, sizeof(*d));
1976         d->latestframenum = 0;
1977         for (i = 0;i < d->maxedicts;i++)
1978                 d->states[i] = defaultstate;
1979         return d;
1980 }
1981
1982 void EntityFrame5_FreeDatabase(entityframe5_database_t *d)
1983 {
1984         // all the [maxedicts] memory is allocated at once, so there's only one
1985         // thing to free
1986         if (d->maxedicts)
1987                 Mem_Free(d->deltabits);
1988         Mem_Free(d);
1989 }
1990
1991 static void EntityFrame5_ExpandEdicts(entityframe5_database_t *d, int newmax)
1992 {
1993         if (d->maxedicts < newmax)
1994         {
1995                 unsigned char *data;
1996                 int oldmaxedicts = d->maxedicts;
1997                 int *olddeltabits = d->deltabits;
1998                 unsigned char *oldpriorities = d->priorities;
1999                 int *oldupdateframenum = d->updateframenum;
2000                 entity_state_t *oldstates = d->states;
2001                 unsigned char *oldvisiblebits = d->visiblebits;
2002                 d->maxedicts = newmax;
2003                 data = (unsigned char *)Mem_Alloc(sv_mempool, d->maxedicts * sizeof(int) + d->maxedicts * sizeof(unsigned char) + d->maxedicts * sizeof(int) + d->maxedicts * sizeof(entity_state_t) + (d->maxedicts+7)/8 * sizeof(unsigned char));
2004                 d->deltabits = (int *)data;data += d->maxedicts * sizeof(int);
2005                 d->priorities = (unsigned char *)data;data += d->maxedicts * sizeof(unsigned char);
2006                 d->updateframenum = (int *)data;data += d->maxedicts * sizeof(int);
2007                 d->states = (entity_state_t *)data;data += d->maxedicts * sizeof(entity_state_t);
2008                 d->visiblebits = (unsigned char *)data;data += (d->maxedicts+7)/8 * sizeof(unsigned char);
2009                 if (oldmaxedicts)
2010                 {
2011                         memcpy(d->deltabits, olddeltabits, oldmaxedicts * sizeof(int));
2012                         memcpy(d->priorities, oldpriorities, oldmaxedicts * sizeof(unsigned char));
2013                         memcpy(d->updateframenum, oldupdateframenum, oldmaxedicts * sizeof(int));
2014                         memcpy(d->states, oldstates, oldmaxedicts * sizeof(entity_state_t));
2015                         memcpy(d->visiblebits, oldvisiblebits, (oldmaxedicts+7)/8 * sizeof(unsigned char));
2016                         // the previous buffers were a single allocation, so just one free
2017                         Mem_Free(olddeltabits);
2018                 }
2019         }
2020 }
2021
2022 static int EntityState5_Priority(entityframe5_database_t *d, int stateindex)
2023 {
2024         int limit, priority;
2025         entity_state_t *s = NULL; // hush compiler warning by initializing this
2026         // if it is the player, update urgently
2027         if (stateindex == d->viewentnum)
2028                 return ENTITYFRAME5_PRIORITYLEVELS - 1;
2029         // priority increases each frame no matter what happens
2030         priority = d->priorities[stateindex] + 1;
2031         // players get an extra priority boost
2032         if (stateindex <= svs.maxclients)
2033                 priority++;
2034         // remove dead entities very quickly because they are just 2 bytes
2035         if (d->states[stateindex].active != ACTIVE_NETWORK)
2036         {
2037                 priority++;
2038                 return bound(1, priority, ENTITYFRAME5_PRIORITYLEVELS - 1);
2039         }
2040         // certain changes are more noticable than others
2041         if (d->deltabits[stateindex] & (E5_FULLUPDATE | E5_ATTACHMENT | E5_MODEL | E5_FLAGS | E5_COLORMAP))
2042                 priority++;
2043         // find the root entity this one is attached to, and judge relevance by it
2044         for (limit = 0;limit < 256;limit++)
2045         {
2046                 s = d->states + stateindex;
2047                 if (s->flags & RENDER_VIEWMODEL)
2048                         stateindex = d->viewentnum;
2049                 else if (s->tagentity)
2050                         stateindex = s->tagentity;
2051                 else
2052                         break;
2053                 if (d->maxedicts < stateindex)
2054                         EntityFrame5_ExpandEdicts(d, (stateindex+256)&~255);
2055         }
2056         if (limit >= 256)
2057                 Con_DPrintf("Protocol: Runaway loop recursing tagentity links on entity %i\n", stateindex);
2058         // now that we have the parent entity we can make some decisions based on
2059         // distance from the player
2060         if (VectorDistance(d->states[d->viewentnum].netcenter, s->netcenter) < 1024.0f)
2061                 priority++;
2062         return bound(1, priority, ENTITYFRAME5_PRIORITYLEVELS - 1);
2063 }
2064
2065 static double anim_reducetime(double t, double frameduration, double maxtime)
2066 {
2067         if(t < 0) // clamp to non-negative
2068                 return 0;
2069         if(t <= maxtime) // time can be represented normally
2070                 return t;
2071         if(frameduration == 0) // don't like dividing by zero
2072                 return t;
2073         if(maxtime <= 2 * frameduration) // if two frames don't fit, we better not do this
2074                 return t;
2075         t -= frameduration * ceil((t - maxtime) / frameduration);
2076         // now maxtime - frameduration < t <= maxtime
2077         return t;
2078 }
2079
2080 // see VM_SV_frameduration
2081 static double anim_frameduration(dp_model_t *model, int framenum)
2082 {
2083         if (!model || !model->animscenes || framenum < 0 || framenum >= model->numframes)
2084                 return 0;
2085         if(model->animscenes[framenum].framerate)
2086                 return model->animscenes[framenum].framecount / model->animscenes[framenum].framerate;
2087         return 0;
2088 }
2089
2090 void EntityState5_WriteUpdate(int number, const entity_state_t *s, int changedbits, sizebuf_t *msg)
2091 {
2092         prvm_prog_t *prog = SVVM_prog;
2093         unsigned int bits = 0;
2094         //dp_model_t *model;
2095         ENTITYSIZEPROFILING_START(msg, s->number);
2096
2097         if (s->active != ACTIVE_NETWORK)
2098                 MSG_WriteShort(msg, number | 0x8000);
2099         else
2100         {
2101                 if (PRVM_serveredictfunction((&prog->edicts[s->number]), SendEntity))
2102                         return;
2103
2104                 bits = changedbits;
2105                 if ((bits & E5_ORIGIN) && (!(s->flags & RENDER_LOWPRECISION) || s->exteriormodelforclient || s->tagentity || s->viewmodelforclient || (s->number >= 1 && s->number <= svs.maxclients) || s->origin[0] <= -4096.0625 || s->origin[0] >= 4095.9375 || s->origin[1] <= -4096.0625 || s->origin[1] >= 4095.9375 || s->origin[2] <= -4096.0625 || s->origin[2] >= 4095.9375))
2106                 // maybe also add: ((model = SV_GetModelByIndex(s->modelindex)) != NULL && model->name[0] == '*')
2107                         bits |= E5_ORIGIN32;
2108                         // possible values:
2109                         //   negative origin:
2110                         //     (int)(f * 8 - 0.5) >= -32768
2111                         //          (f * 8 - 0.5) >  -32769
2112                         //           f            >  -4096.0625
2113                         //   positive origin:
2114                         //     (int)(f * 8 + 0.5) <=  32767
2115                         //          (f * 8 + 0.5) <   32768
2116                         //           f * 8 + 0.5) <   4095.9375
2117                 if ((bits & E5_ANGLES) && !(s->flags & RENDER_LOWPRECISION))
2118                         bits |= E5_ANGLES16;
2119                 if ((bits & E5_MODEL) && s->modelindex >= 256)
2120                         bits |= E5_MODEL16;
2121                 if ((bits & E5_FRAME) && s->frame >= 256)
2122                         bits |= E5_FRAME16;
2123                 if (bits & E5_EFFECTS)
2124                 {
2125                         if (s->effects & 0xFFFF0000)
2126                                 bits |= E5_EFFECTS32;
2127                         else if (s->effects & 0xFFFFFF00)
2128                                 bits |= E5_EFFECTS16;
2129                 }
2130                 if (bits >= 256)
2131                         bits |= E5_EXTEND1;
2132                 if (bits >= 65536)
2133                         bits |= E5_EXTEND2;
2134                 if (bits >= 16777216)
2135                         bits |= E5_EXTEND3;
2136                 MSG_WriteShort(msg, number);
2137                 MSG_WriteByte(msg, bits & 0xFF);
2138                 if (bits & E5_EXTEND1)
2139                         MSG_WriteByte(msg, (bits >> 8) & 0xFF);
2140                 if (bits & E5_EXTEND2)
2141                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
2142                 if (bits & E5_EXTEND3)
2143                         MSG_WriteByte(msg, (bits >> 24) & 0xFF);
2144                 if (bits & E5_FLAGS)
2145                         MSG_WriteByte(msg, s->flags);
2146                 if (bits & E5_ORIGIN)
2147                 {
2148                         if (bits & E5_ORIGIN32)
2149                         {
2150                                 MSG_WriteCoord32f(msg, s->origin[0]);
2151                                 MSG_WriteCoord32f(msg, s->origin[1]);
2152                                 MSG_WriteCoord32f(msg, s->origin[2]);
2153                         }
2154                         else
2155                         {
2156                                 MSG_WriteCoord13i(msg, s->origin[0]);
2157                                 MSG_WriteCoord13i(msg, s->origin[1]);
2158                                 MSG_WriteCoord13i(msg, s->origin[2]);
2159                         }
2160                 }
2161                 if (bits & E5_ANGLES)
2162                 {
2163                         if (bits & E5_ANGLES16)
2164                         {
2165                                 MSG_WriteAngle16i(msg, s->angles[0]);
2166                                 MSG_WriteAngle16i(msg, s->angles[1]);
2167                                 MSG_WriteAngle16i(msg, s->angles[2]);
2168                         }
2169                         else
2170                         {
2171                                 MSG_WriteAngle8i(msg, s->angles[0]);
2172                                 MSG_WriteAngle8i(msg, s->angles[1]);
2173                                 MSG_WriteAngle8i(msg, s->angles[2]);
2174                         }
2175                 }
2176                 if (bits & E5_MODEL)
2177                 {
2178                         if (bits & E5_MODEL16)
2179                                 MSG_WriteShort(msg, s->modelindex);
2180                         else
2181                                 MSG_WriteByte(msg, s->modelindex);
2182                 }
2183                 if (bits & E5_FRAME)
2184                 {
2185                         if (bits & E5_FRAME16)
2186                                 MSG_WriteShort(msg, s->frame);
2187                         else
2188                                 MSG_WriteByte(msg, s->frame);
2189                 }
2190                 if (bits & E5_SKIN)
2191                         MSG_WriteByte(msg, s->skin);
2192                 if (bits & E5_EFFECTS)
2193                 {
2194                         if (bits & E5_EFFECTS32)
2195                                 MSG_WriteLong(msg, s->effects);
2196                         else if (bits & E5_EFFECTS16)
2197                                 MSG_WriteShort(msg, s->effects);
2198                         else
2199                                 MSG_WriteByte(msg, s->effects);
2200                 }
2201                 if (bits & E5_ALPHA)
2202                         MSG_WriteByte(msg, s->alpha);
2203                 if (bits & E5_SCALE)
2204                         MSG_WriteByte(msg, s->scale);
2205                 if (bits & E5_COLORMAP)
2206                         MSG_WriteByte(msg, s->colormap);
2207                 if (bits & E5_ATTACHMENT)
2208                 {
2209                         MSG_WriteShort(msg, s->tagentity);
2210                         MSG_WriteByte(msg, s->tagindex);
2211                 }
2212                 if (bits & E5_LIGHT)
2213                 {
2214                         MSG_WriteShort(msg, s->light[0]);
2215                         MSG_WriteShort(msg, s->light[1]);
2216                         MSG_WriteShort(msg, s->light[2]);
2217                         MSG_WriteShort(msg, s->light[3]);
2218                         MSG_WriteByte(msg, s->lightstyle);
2219                         MSG_WriteByte(msg, s->lightpflags);
2220                 }
2221                 if (bits & E5_GLOW)
2222                 {
2223                         MSG_WriteByte(msg, s->glowsize);
2224                         MSG_WriteByte(msg, s->glowcolor);
2225                 }
2226                 if (bits & E5_COLORMOD)
2227                 {
2228                         MSG_WriteByte(msg, s->colormod[0]);
2229                         MSG_WriteByte(msg, s->colormod[1]);
2230                         MSG_WriteByte(msg, s->colormod[2]);
2231                 }
2232                 if (bits & E5_GLOWMOD)
2233                 {
2234                         MSG_WriteByte(msg, s->glowmod[0]);
2235                         MSG_WriteByte(msg, s->glowmod[1]);
2236                         MSG_WriteByte(msg, s->glowmod[2]);
2237                 }
2238                 if (bits & E5_COMPLEXANIMATION)
2239                 {
2240                         if (s->skeletonobject.model && s->skeletonobject.relativetransforms)
2241                         {
2242                                 int numbones = s->skeletonobject.model->num_bones;
2243                                 int bonenum;
2244                                 short pose7s[7];
2245                                 MSG_WriteByte(msg, 4);
2246                                 MSG_WriteShort(msg, s->modelindex);
2247                                 MSG_WriteByte(msg, numbones);
2248                                 for (bonenum = 0;bonenum < numbones;bonenum++)
2249                                 {
2250                                         Matrix4x4_ToBonePose7s(s->skeletonobject.relativetransforms + bonenum, 64, pose7s);
2251                                         MSG_WriteShort(msg, pose7s[0]);
2252                                         MSG_WriteShort(msg, pose7s[1]);
2253                                         MSG_WriteShort(msg, pose7s[2]);
2254                                         MSG_WriteShort(msg, pose7s[3]);
2255                                         MSG_WriteShort(msg, pose7s[4]);
2256                                         MSG_WriteShort(msg, pose7s[5]);
2257                                         MSG_WriteShort(msg, pose7s[6]);
2258                                 }
2259                         }
2260                         else
2261                         {
2262                                 dp_model_t *model = SV_GetModelByIndex(s->modelindex);
2263                                 if (s->framegroupblend[3].lerp > 0)
2264                                 {
2265                                         MSG_WriteByte(msg, 3);
2266                                         MSG_WriteShort(msg, s->framegroupblend[0].frame);
2267                                         MSG_WriteShort(msg, s->framegroupblend[1].frame);
2268                                         MSG_WriteShort(msg, s->framegroupblend[2].frame);
2269                                         MSG_WriteShort(msg, s->framegroupblend[3].frame);
2270                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[0].start, anim_frameduration(model, s->framegroupblend[0].frame), 65.535) * 1000.0));
2271                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[1].start, anim_frameduration(model, s->framegroupblend[1].frame), 65.535) * 1000.0));
2272                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[2].start, anim_frameduration(model, s->framegroupblend[2].frame), 65.535) * 1000.0));
2273                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[3].start, anim_frameduration(model, s->framegroupblend[3].frame), 65.535) * 1000.0));
2274                                         MSG_WriteByte(msg, s->framegroupblend[0].lerp * 255.0f);
2275                                         MSG_WriteByte(msg, s->framegroupblend[1].lerp * 255.0f);
2276                                         MSG_WriteByte(msg, s->framegroupblend[2].lerp * 255.0f);
2277                                         MSG_WriteByte(msg, s->framegroupblend[3].lerp * 255.0f);
2278                                 }
2279                                 else if (s->framegroupblend[2].lerp > 0)
2280                                 {
2281                                         MSG_WriteByte(msg, 2);
2282                                         MSG_WriteShort(msg, s->framegroupblend[0].frame);
2283                                         MSG_WriteShort(msg, s->framegroupblend[1].frame);
2284                                         MSG_WriteShort(msg, s->framegroupblend[2].frame);
2285                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[0].start, anim_frameduration(model, s->framegroupblend[0].frame), 65.535) * 1000.0));
2286                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[1].start, anim_frameduration(model, s->framegroupblend[1].frame), 65.535) * 1000.0));
2287                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[2].start, anim_frameduration(model, s->framegroupblend[2].frame), 65.535) * 1000.0));
2288                                         MSG_WriteByte(msg, s->framegroupblend[0].lerp * 255.0f);
2289                                         MSG_WriteByte(msg, s->framegroupblend[1].lerp * 255.0f);
2290                                         MSG_WriteByte(msg, s->framegroupblend[2].lerp * 255.0f);
2291                                 }
2292                                 else if (s->framegroupblend[1].lerp > 0)
2293                                 {
2294                                         MSG_WriteByte(msg, 1);
2295                                         MSG_WriteShort(msg, s->framegroupblend[0].frame);
2296                                         MSG_WriteShort(msg, s->framegroupblend[1].frame);
2297                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[0].start, anim_frameduration(model, s->framegroupblend[0].frame), 65.535) * 1000.0));
2298                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[1].start, anim_frameduration(model, s->framegroupblend[1].frame), 65.535) * 1000.0));
2299                                         MSG_WriteByte(msg, s->framegroupblend[0].lerp * 255.0f);
2300                                         MSG_WriteByte(msg, s->framegroupblend[1].lerp * 255.0f);
2301                                 }
2302                                 else
2303                                 {
2304                                         MSG_WriteByte(msg, 0);
2305                                         MSG_WriteShort(msg, s->framegroupblend[0].frame);
2306                                         MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[0].start, anim_frameduration(model, s->framegroupblend[0].frame), 65.535) * 1000.0));
2307                                 }
2308                         }
2309                 }
2310                 if (bits & E5_TRAILEFFECTNUM)
2311                         MSG_WriteShort(msg, s->traileffectnum);
2312         }
2313
2314         ENTITYSIZEPROFILING_END(msg, s->number);
2315 }
2316
2317 static void EntityState5_ReadUpdate(entity_state_t *s, int number)
2318 {
2319         int bits;
2320         int startoffset = cl_message.readcount;
2321         int bytes = 0;
2322         bits = MSG_ReadByte(&cl_message);
2323         if (bits & E5_EXTEND1)
2324         {
2325                 bits |= MSG_ReadByte(&cl_message) << 8;
2326                 if (bits & E5_EXTEND2)
2327                 {
2328                         bits |= MSG_ReadByte(&cl_message) << 16;
2329                         if (bits & E5_EXTEND3)
2330                                 bits |= MSG_ReadByte(&cl_message) << 24;
2331                 }
2332         }
2333         if (bits & E5_FULLUPDATE)
2334         {
2335                 *s = defaultstate;
2336                 s->active = ACTIVE_NETWORK;
2337         }
2338         if (bits & E5_FLAGS)
2339                 s->flags = MSG_ReadByte(&cl_message);
2340         if (bits & E5_ORIGIN)
2341         {
2342                 if (bits & E5_ORIGIN32)
2343                 {
2344                         s->origin[0] = MSG_ReadCoord32f(&cl_message);
2345                         s->origin[1] = MSG_ReadCoord32f(&cl_message);
2346                         s->origin[2] = MSG_ReadCoord32f(&cl_message);
2347                 }
2348                 else
2349                 {
2350                         s->origin[0] = MSG_ReadCoord13i(&cl_message);
2351                         s->origin[1] = MSG_ReadCoord13i(&cl_message);
2352                         s->origin[2] = MSG_ReadCoord13i(&cl_message);
2353                 }
2354         }
2355         if (bits & E5_ANGLES)
2356         {
2357                 if (bits & E5_ANGLES16)
2358                 {
2359                         s->angles[0] = MSG_ReadAngle16i(&cl_message);
2360                         s->angles[1] = MSG_ReadAngle16i(&cl_message);
2361                         s->angles[2] = MSG_ReadAngle16i(&cl_message);
2362                 }
2363                 else
2364                 {
2365                         s->angles[0] = MSG_ReadAngle8i(&cl_message);
2366                         s->angles[1] = MSG_ReadAngle8i(&cl_message);
2367                         s->angles[2] = MSG_ReadAngle8i(&cl_message);
2368                 }
2369         }
2370         if (bits & E5_MODEL)
2371         {
2372                 if (bits & E5_MODEL16)
2373                         s->modelindex = (unsigned short) MSG_ReadShort(&cl_message);
2374                 else
2375                         s->modelindex = MSG_ReadByte(&cl_message);
2376         }
2377         if (bits & E5_FRAME)
2378         {
2379                 if (bits & E5_FRAME16)
2380                         s->frame = (unsigned short) MSG_ReadShort(&cl_message);
2381                 else
2382                         s->frame = MSG_ReadByte(&cl_message);
2383         }
2384         if (bits & E5_SKIN)
2385                 s->skin = MSG_ReadByte(&cl_message);
2386         if (bits & E5_EFFECTS)
2387         {
2388                 if (bits & E5_EFFECTS32)
2389                         s->effects = (unsigned int) MSG_ReadLong(&cl_message);
2390                 else if (bits & E5_EFFECTS16)
2391                         s->effects = (unsigned short) MSG_ReadShort(&cl_message);
2392                 else
2393                         s->effects = MSG_ReadByte(&cl_message);
2394         }
2395         if (bits & E5_ALPHA)
2396                 s->alpha = MSG_ReadByte(&cl_message);
2397         if (bits & E5_SCALE)
2398                 s->scale = MSG_ReadByte(&cl_message);
2399         if (bits & E5_COLORMAP)
2400                 s->colormap = MSG_ReadByte(&cl_message);
2401         if (bits & E5_ATTACHMENT)
2402         {
2403                 s->tagentity = (unsigned short) MSG_ReadShort(&cl_message);
2404                 s->tagindex = MSG_ReadByte(&cl_message);
2405         }
2406         if (bits & E5_LIGHT)
2407         {
2408                 s->light[0] = (unsigned short) MSG_ReadShort(&cl_message);
2409                 s->light[1] = (unsigned short) MSG_ReadShort(&cl_message);
2410                 s->light[2] = (unsigned short) MSG_ReadShort(&cl_message);
2411                 s->light[3] = (unsigned short) MSG_ReadShort(&cl_message);
2412                 s->lightstyle = MSG_ReadByte(&cl_message);
2413                 s->lightpflags = MSG_ReadByte(&cl_message);
2414         }
2415         if (bits & E5_GLOW)
2416         {
2417                 s->glowsize = MSG_ReadByte(&cl_message);
2418                 s->glowcolor = MSG_ReadByte(&cl_message);
2419         }
2420         if (bits & E5_COLORMOD)
2421         {
2422                 s->colormod[0] = MSG_ReadByte(&cl_message);
2423                 s->colormod[1] = MSG_ReadByte(&cl_message);
2424                 s->colormod[2] = MSG_ReadByte(&cl_message);
2425         }
2426         if (bits & E5_GLOWMOD)
2427         {
2428                 s->glowmod[0] = MSG_ReadByte(&cl_message);
2429                 s->glowmod[1] = MSG_ReadByte(&cl_message);
2430                 s->glowmod[2] = MSG_ReadByte(&cl_message);
2431         }
2432         if (bits & E5_COMPLEXANIMATION)
2433         {
2434                 skeleton_t *skeleton;
2435                 const dp_model_t *model;
2436                 int modelindex;
2437                 int type;
2438                 int bonenum;
2439                 int numbones;
2440                 short pose7s[7];
2441                 type = MSG_ReadByte(&cl_message);
2442                 switch(type)
2443                 {
2444                 case 0:
2445                         s->framegroupblend[0].frame = MSG_ReadShort(&cl_message);
2446                         s->framegroupblend[1].frame = 0;
2447                         s->framegroupblend[2].frame = 0;
2448                         s->framegroupblend[3].frame = 0;
2449                         s->framegroupblend[0].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2450                         s->framegroupblend[1].start = 0;
2451                         s->framegroupblend[2].start = 0;
2452                         s->framegroupblend[3].start = 0;
2453                         s->framegroupblend[0].lerp = 1;
2454                         s->framegroupblend[1].lerp = 0;
2455                         s->framegroupblend[2].lerp = 0;
2456                         s->framegroupblend[3].lerp = 0;
2457                         break;
2458                 case 1:
2459                         s->framegroupblend[0].frame = MSG_ReadShort(&cl_message);
2460                         s->framegroupblend[1].frame = MSG_ReadShort(&cl_message);
2461                         s->framegroupblend[2].frame = 0;
2462                         s->framegroupblend[3].frame = 0;
2463                         s->framegroupblend[0].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2464                         s->framegroupblend[1].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2465                         s->framegroupblend[2].start = 0;
2466                         s->framegroupblend[3].start = 0;
2467                         s->framegroupblend[0].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2468                         s->framegroupblend[1].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2469                         s->framegroupblend[2].lerp = 0;
2470                         s->framegroupblend[3].lerp = 0;
2471                         break;
2472                 case 2:
2473                         s->framegroupblend[0].frame = MSG_ReadShort(&cl_message);
2474                         s->framegroupblend[1].frame = MSG_ReadShort(&cl_message);
2475                         s->framegroupblend[2].frame = MSG_ReadShort(&cl_message);
2476                         s->framegroupblend[3].frame = 0;
2477                         s->framegroupblend[0].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2478                         s->framegroupblend[1].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2479                         s->framegroupblend[2].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2480                         s->framegroupblend[3].start = 0;
2481                         s->framegroupblend[0].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2482                         s->framegroupblend[1].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2483                         s->framegroupblend[2].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2484                         s->framegroupblend[3].lerp = 0;
2485                         break;
2486                 case 3:
2487                         s->framegroupblend[0].frame = MSG_ReadShort(&cl_message);
2488                         s->framegroupblend[1].frame = MSG_ReadShort(&cl_message);
2489                         s->framegroupblend[2].frame = MSG_ReadShort(&cl_message);
2490                         s->framegroupblend[3].frame = MSG_ReadShort(&cl_message);
2491                         s->framegroupblend[0].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2492                         s->framegroupblend[1].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2493                         s->framegroupblend[2].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2494                         s->framegroupblend[3].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2495                         s->framegroupblend[0].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2496                         s->framegroupblend[1].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2497                         s->framegroupblend[2].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2498                         s->framegroupblend[3].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2499                         break;
2500                 case 4:
2501                         if (!cl.engineskeletonobjects)
2502                                 cl.engineskeletonobjects = (skeleton_t *) Mem_Alloc(cls.levelmempool, sizeof(*cl.engineskeletonobjects) * MAX_EDICTS);
2503                         skeleton = &cl.engineskeletonobjects[number];
2504                         modelindex = MSG_ReadShort(&cl_message);
2505                         model = CL_GetModelByIndex(modelindex);
2506                         numbones = MSG_ReadByte(&cl_message);
2507                         if (model && numbones != model->num_bones)
2508                                 Host_Error("E5_COMPLEXANIMATION: model has different number of bones than network packet describes\n");
2509                         if (!skeleton->relativetransforms || skeleton->model != model)
2510                         {
2511                                 skeleton->model = model;
2512                                 skeleton->relativetransforms = (matrix4x4_t *) Mem_Realloc(cls.levelmempool, skeleton->relativetransforms, sizeof(*skeleton->relativetransforms) * skeleton->model->num_bones);
2513                                 for (bonenum = 0;bonenum < model->num_bones;bonenum++)
2514                                         skeleton->relativetransforms[bonenum] = identitymatrix;
2515                         }
2516                         for (bonenum = 0;bonenum < numbones;bonenum++)
2517                         {
2518                                 pose7s[0] = (short)MSG_ReadShort(&cl_message);
2519                                 pose7s[1] = (short)MSG_ReadShort(&cl_message);
2520                                 pose7s[2] = (short)MSG_ReadShort(&cl_message);
2521                                 pose7s[3] = (short)MSG_ReadShort(&cl_message);
2522                                 pose7s[4] = (short)MSG_ReadShort(&cl_message);
2523                                 pose7s[5] = (short)MSG_ReadShort(&cl_message);
2524                                 pose7s[6] = (short)MSG_ReadShort(&cl_message);
2525                                 Matrix4x4_FromBonePose7s(skeleton->relativetransforms + bonenum, 1.0f / 64.0f, pose7s);
2526                         }
2527                         s->skeletonobject = *skeleton;
2528                         break;
2529                 default:
2530                         Host_Error("E5_COMPLEXANIMATION: Parse error - unknown type %i\n", type);
2531                         break;
2532                 }
2533         }
2534         if (bits & E5_TRAILEFFECTNUM)
2535                 s->traileffectnum = (unsigned short) MSG_ReadShort(&cl_message);
2536
2537
2538         bytes = cl_message.readcount - startoffset;
2539         if (developer_networkentities.integer >= 2)
2540         {
2541                 Con_Printf("ReadFields e%i (%i bytes)", number, bytes);
2542
2543                 if (bits & E5_ORIGIN)
2544                         Con_Printf(" E5_ORIGIN %f %f %f", s->origin[0], s->origin[1], s->origin[2]);
2545                 if (bits & E5_ANGLES)
2546                         Con_Printf(" E5_ANGLES %f %f %f", s->angles[0], s->angles[1], s->angles[2]);
2547                 if (bits & E5_MODEL)
2548                         Con_Printf(" E5_MODEL %i", s->modelindex);
2549                 if (bits & E5_FRAME)
2550                         Con_Printf(" E5_FRAME %i", s->frame);
2551                 if (bits & E5_SKIN)
2552                         Con_Printf(" E5_SKIN %i", s->skin);
2553                 if (bits & E5_EFFECTS)
2554                         Con_Printf(" E5_EFFECTS %i", s->effects);
2555                 if (bits & E5_FLAGS)
2556                 {
2557                         Con_Printf(" E5_FLAGS %i (", s->flags);
2558                         if (s->flags & RENDER_STEP)
2559                                 Con_Print(" STEP");
2560                         if (s->flags & RENDER_GLOWTRAIL)
2561                                 Con_Print(" GLOWTRAIL");
2562                         if (s->flags & RENDER_VIEWMODEL)
2563                                 Con_Print(" VIEWMODEL");
2564                         if (s->flags & RENDER_EXTERIORMODEL)
2565                                 Con_Print(" EXTERIORMODEL");
2566                         if (s->flags & RENDER_LOWPRECISION)
2567                                 Con_Print(" LOWPRECISION");
2568                         if (s->flags & RENDER_COLORMAPPED)
2569                                 Con_Print(" COLORMAPPED");
2570                         if (s->flags & RENDER_SHADOW)
2571                                 Con_Print(" SHADOW");
2572                         if (s->flags & RENDER_LIGHT)
2573                                 Con_Print(" LIGHT");
2574                         if (s->flags & RENDER_NOSELFSHADOW)
2575                                 Con_Print(" NOSELFSHADOW");
2576                         Con_Print(")");
2577                 }
2578                 if (bits & E5_ALPHA)
2579                         Con_Printf(" E5_ALPHA %f", s->alpha / 255.0f);
2580                 if (bits & E5_SCALE)
2581                         Con_Printf(" E5_SCALE %f", s->scale / 16.0f);
2582                 if (bits & E5_COLORMAP)
2583                         Con_Printf(" E5_COLORMAP %i", s->colormap);
2584                 if (bits & E5_ATTACHMENT)
2585                         Con_Printf(" E5_ATTACHMENT e%i:%i", s->tagentity, s->tagindex);
2586                 if (bits & E5_LIGHT)
2587                         Con_Printf(" E5_LIGHT %i:%i:%i:%i %i:%i", s->light[0], s->light[1], s->light[2], s->light[3], s->lightstyle, s->lightpflags);
2588                 if (bits & E5_GLOW)
2589                         Con_Printf(" E5_GLOW %i:%i", s->glowsize * 4, s->glowcolor);
2590                 if (bits & E5_COLORMOD)
2591                         Con_Printf(" E5_COLORMOD %f:%f:%f", s->colormod[0] / 32.0f, s->colormod[1] / 32.0f, s->colormod[2] / 32.0f);
2592                 if (bits & E5_GLOWMOD)
2593                         Con_Printf(" E5_GLOWMOD %f:%f:%f", s->glowmod[0] / 32.0f, s->glowmod[1] / 32.0f, s->glowmod[2] / 32.0f);
2594                 if (bits & E5_COMPLEXANIMATION)
2595                         Con_Printf(" E5_COMPLEXANIMATION");
2596                 if (bits & E5_TRAILEFFECTNUM)
2597                         Con_Printf(" E5_TRAILEFFECTNUM %i", s->traileffectnum);
2598                 Con_Print("\n");
2599         }
2600 }
2601
2602 static int EntityState5_DeltaBits(const entity_state_t *o, const entity_state_t *n)
2603 {
2604         unsigned int bits = 0;
2605         if (n->active == ACTIVE_NETWORK)
2606         {
2607                 if (o->active != ACTIVE_NETWORK)
2608                         bits |= E5_FULLUPDATE;
2609                 if (!VectorCompare(o->origin, n->origin))
2610                         bits |= E5_ORIGIN;
2611                 if (!VectorCompare(o->angles, n->angles))
2612                         bits |= E5_ANGLES;
2613                 if (o->modelindex != n->modelindex)
2614                         bits |= E5_MODEL;
2615                 if (o->frame != n->frame)
2616                         bits |= E5_FRAME;
2617                 if (o->skin != n->skin)
2618                         bits |= E5_SKIN;
2619                 if (o->effects != n->effects)
2620                         bits |= E5_EFFECTS;
2621                 if (o->flags != n->flags)
2622                         bits |= E5_FLAGS;
2623                 if (o->alpha != n->alpha)
2624                         bits |= E5_ALPHA;
2625                 if (o->scale != n->scale)
2626                         bits |= E5_SCALE;
2627                 if (o->colormap != n->colormap)
2628                         bits |= E5_COLORMAP;
2629                 if (o->tagentity != n->tagentity || o->tagindex != n->tagindex)
2630                         bits |= E5_ATTACHMENT;
2631                 if (o->light[0] != n->light[0] || o->light[1] != n->light[1] || o->light[2] != n->light[2] || o->light[3] != n->light[3] || o->lightstyle != n->lightstyle || o->lightpflags != n->lightpflags)
2632                         bits |= E5_LIGHT;
2633                 if (o->glowsize != n->glowsize || o->glowcolor != n->glowcolor)
2634                         bits |= E5_GLOW;
2635                 if (o->colormod[0] != n->colormod[0] || o->colormod[1] != n->colormod[1] || o->colormod[2] != n->colormod[2])
2636                         bits |= E5_COLORMOD;
2637                 if (o->glowmod[0] != n->glowmod[0] || o->glowmod[1] != n->glowmod[1] || o->glowmod[2] != n->glowmod[2])
2638                         bits |= E5_GLOWMOD;
2639                 if (n->flags & RENDER_COMPLEXANIMATION)
2640                 {
2641                         if ((o->skeletonobject.model && o->skeletonobject.relativetransforms) != (n->skeletonobject.model && n->skeletonobject.relativetransforms))
2642                         {
2643                                 bits |= E5_COMPLEXANIMATION;
2644                         }
2645                         else if (o->skeletonobject.model && o->skeletonobject.relativetransforms)
2646                         {
2647                                 if(o->modelindex != n->modelindex)
2648                                         bits |= E5_COMPLEXANIMATION;
2649                                 else if(o->skeletonobject.model->num_bones != n->skeletonobject.model->num_bones)
2650                                         bits |= E5_COMPLEXANIMATION;
2651                                 else if(memcmp(o->skeletonobject.relativetransforms, n->skeletonobject.relativetransforms, o->skeletonobject.model->num_bones * sizeof(*o->skeletonobject.relativetransforms)))
2652                                         bits |= E5_COMPLEXANIMATION;
2653                         }
2654                         else if (memcmp(o->framegroupblend, n->framegroupblend, sizeof(o->framegroupblend)))
2655                         {
2656                                 bits |= E5_COMPLEXANIMATION;
2657                         }
2658                 }
2659                 if (o->traileffectnum != n->traileffectnum)
2660                         bits |= E5_TRAILEFFECTNUM;
2661         }
2662         else
2663                 if (o->active == ACTIVE_NETWORK)
2664                         bits |= E5_FULLUPDATE;
2665         return bits;
2666 }
2667
2668 void EntityFrame5_CL_ReadFrame(void)
2669 {
2670         int n, enumber, framenum;
2671         entity_t *ent;
2672         entity_state_t *s;
2673         // read the number of this frame to echo back in next input packet
2674         framenum = MSG_ReadLong(&cl_message);
2675         CL_NewFrameReceived(framenum);
2676         if (cls.protocol != PROTOCOL_QUAKE && cls.protocol != PROTOCOL_QUAKEDP && cls.protocol != PROTOCOL_NEHAHRAMOVIE && cls.protocol != PROTOCOL_DARKPLACES1 && cls.protocol != PROTOCOL_DARKPLACES2 && cls.protocol != PROTOCOL_DARKPLACES3 && cls.protocol != PROTOCOL_DARKPLACES4 && cls.protocol != PROTOCOL_DARKPLACES5 && cls.protocol != PROTOCOL_DARKPLACES6)
2677                 cls.servermovesequence = MSG_ReadLong(&cl_message);
2678         // read entity numbers until we find a 0x8000
2679         // (which would be remove world entity, but is actually a terminator)
2680         while ((n = (unsigned short)MSG_ReadShort(&cl_message)) != 0x8000 && !cl_message.badread)
2681         {
2682                 // get the entity number
2683                 enumber = n & 0x7FFF;
2684                 // we may need to expand the array
2685                 if (cl.num_entities <= enumber)
2686                 {
2687                         cl.num_entities = enumber + 1;
2688                         if (enumber >= cl.max_entities)
2689                                 CL_ExpandEntities(enumber);
2690                 }
2691                 // look up the entity
2692                 ent = cl.entities + enumber;
2693                 // slide the current into the previous slot
2694                 ent->state_previous = ent->state_current;
2695                 // read the update
2696                 s = &ent->state_current;
2697                 if (n & 0x8000)
2698                 {
2699                         // remove entity
2700                         *s = defaultstate;
2701                 }
2702                 else
2703                 {
2704                         // update entity
2705                         EntityState5_ReadUpdate(s, enumber);
2706                 }
2707                 // set the cl.entities_active flag
2708                 cl.entities_active[enumber] = (s->active == ACTIVE_NETWORK);
2709                 // set the update time
2710                 s->time = cl.mtime[0];
2711                 // fix the number (it gets wiped occasionally by copying from defaultstate)
2712                 s->number = enumber;
2713                 // check if we need to update the lerp stuff
2714                 if (s->active == ACTIVE_NETWORK)
2715                         CL_MoveLerpEntityStates(&cl.entities[enumber]);
2716                 // print extra messages if desired
2717                 if (developer_networkentities.integer >= 2 && cl.entities[enumber].state_current.active != cl.entities[enumber].state_previous.active)
2718                 {
2719                         if (cl.entities[enumber].state_current.active == ACTIVE_NETWORK)
2720                                 Con_Printf("entity #%i has become active\n", enumber);
2721                         else if (cl.entities[enumber].state_previous.active)
2722                                 Con_Printf("entity #%i has become inactive\n", enumber);
2723                 }
2724         }
2725 }
2726
2727 static int packetlog5cmp(const void *a_, const void *b_)
2728 {
2729         const entityframe5_packetlog_t *a = (const entityframe5_packetlog_t *) a_;
2730         const entityframe5_packetlog_t *b = (const entityframe5_packetlog_t *) b_;
2731         return a->packetnumber - b->packetnumber;
2732 }
2733
2734 void EntityFrame5_LostFrame(entityframe5_database_t *d, int framenum)
2735 {
2736         int i, j, l, bits;
2737         entityframe5_changestate_t *s;
2738         entityframe5_packetlog_t *p;
2739         static unsigned char statsdeltabits[(MAX_CL_STATS+7)/8];
2740         static int deltabits[MAX_EDICTS];
2741         entityframe5_packetlog_t *packetlogs[ENTITYFRAME5_MAXPACKETLOGS];
2742
2743         for (i = 0, p = d->packetlog;i < ENTITYFRAME5_MAXPACKETLOGS;i++, p++)
2744                 packetlogs[i] = p;
2745         qsort(packetlogs, sizeof(*packetlogs), ENTITYFRAME5_MAXPACKETLOGS, packetlog5cmp);
2746
2747         memset(deltabits, 0, sizeof(deltabits));
2748         memset(statsdeltabits, 0, sizeof(statsdeltabits));
2749         for (i = 0; i < ENTITYFRAME5_MAXPACKETLOGS; i++)
2750         {
2751                 p = packetlogs[i];
2752
2753                 if (!p->packetnumber)
2754                         continue;
2755
2756                 if (p->packetnumber <= framenum)
2757                 {
2758                         for (j = 0, s = p->states;j < p->numstates;j++, s++)
2759                                 deltabits[s->number] |= s->bits;
2760
2761                         for (l = 0;l < (MAX_CL_STATS+7)/8;l++)
2762                                 statsdeltabits[l] |= p->statsdeltabits[l];
2763
2764                         p->packetnumber = 0;
2765                 }
2766                 else
2767                 {
2768                         for (j = 0, s = p->states;j < p->numstates;j++, s++)
2769                                 deltabits[s->number] &= ~s->bits;
2770                         for (l = 0;l < (MAX_CL_STATS+7)/8;l++)
2771                                 statsdeltabits[l] &= ~p->statsdeltabits[l];
2772                 }
2773         }
2774
2775         for(i = 0; i < d->maxedicts; ++i)
2776         {
2777                 bits = deltabits[i] & ~d->deltabits[i];
2778                 if(bits)
2779                 {
2780                         d->deltabits[i] |= bits;
2781                         // if it was a very important update, set priority higher
2782                         if (bits & (E5_FULLUPDATE | E5_ATTACHMENT | E5_MODEL | E5_COLORMAP))
2783                                 d->priorities[i] = max(d->priorities[i], 4);
2784                         else
2785                                 d->priorities[i] = max(d->priorities[i], 1);
2786                 }
2787         }
2788
2789         for (l = 0;l < (MAX_CL_STATS+7)/8;l++)
2790                 host_client->statsdeltabits[l] |= statsdeltabits[l];
2791                 // no need to mask out the already-set bits here, as we do not
2792                 // do that priorities stuff
2793 }
2794
2795 void EntityFrame5_AckFrame(entityframe5_database_t *d, int framenum)
2796 {
2797         int i;
2798         // scan for packets made obsolete by this ack and delete them
2799         for (i = 0;i < ENTITYFRAME5_MAXPACKETLOGS;i++)
2800                 if (d->packetlog[i].packetnumber <= framenum)
2801                         d->packetlog[i].packetnumber = 0;
2802 }
2803
2804 qboolean EntityFrame5_WriteFrame(sizebuf_t *msg, int maxsize, entityframe5_database_t *d, int numstates, const entity_state_t **states, int viewentnum, int movesequence, qboolean need_empty)
2805 {
2806         prvm_prog_t *prog = SVVM_prog;
2807         const entity_state_t *n;
2808         int i, num, l, framenum, packetlognumber, priority;
2809         sizebuf_t buf;
2810         unsigned char data[128];
2811         entityframe5_packetlog_t *packetlog;
2812
2813         if (prog->max_edicts > d->maxedicts)
2814                 EntityFrame5_ExpandEdicts(d, prog->max_edicts);
2815
2816         framenum = d->latestframenum + 1;
2817         d->viewentnum = viewentnum;
2818
2819         // if packet log is full, mark all frames as lost, this will cause
2820         // it to send the lost data again
2821         for (packetlognumber = 0;packetlognumber < ENTITYFRAME5_MAXPACKETLOGS;packetlognumber++)
2822                 if (d->packetlog[packetlognumber].packetnumber == 0)
2823                         break;
2824         if (packetlognumber == ENTITYFRAME5_MAXPACKETLOGS)
2825         {
2826                 Con_DPrintf("EntityFrame5_WriteFrame: packetlog overflow for a client, resetting\n");
2827                 EntityFrame5_LostFrame(d, framenum);
2828                 packetlognumber = 0;
2829         }
2830
2831         // prepare the buffer
2832         memset(&buf, 0, sizeof(buf));
2833         buf.data = data;
2834         buf.maxsize = sizeof(data);
2835
2836         // detect changes in states
2837         num = 1;
2838         for (i = 0;i < numstates;i++)
2839         {
2840                 n = states[i];
2841                 // mark gaps in entity numbering as removed entities
2842                 for (;num < n->number;num++)
2843                 {
2844                         // if the entity used to exist, clear it
2845                         if (CHECKPVSBIT(d->visiblebits, num))
2846                         {
2847                                 CLEARPVSBIT(d->visiblebits, num);
2848                                 d->deltabits[num] = E5_FULLUPDATE;
2849                                 d->priorities[num] = max(d->priorities[num], 8); // removal is cheap
2850                                 d->states[num] = defaultstate;
2851                                 d->states[num].number = num;
2852                         }
2853                 }
2854                 // update the entity state data
2855                 if (!CHECKPVSBIT(d->visiblebits, num))
2856                 {
2857                         // entity just spawned in, don't let it completely hog priority
2858                         // because of being ancient on the first frame
2859                         d->updateframenum[num] = framenum;
2860                         // initial priority is a bit high to make projectiles send on the
2861                         // first frame, among other things
2862                         d->priorities[num] = max(d->priorities[num], 4);
2863                 }
2864                 SETPVSBIT(d->visiblebits, num);
2865                 d->deltabits[num] |= EntityState5_DeltaBits(d->states + num, n);
2866                 d->priorities[num] = max(d->priorities[num], 1);
2867                 d->states[num] = *n;
2868                 d->states[num].number = num;
2869                 // advance to next entity so the next iteration doesn't immediately remove it
2870                 num++;
2871         }
2872         // all remaining entities are dead
2873         for (;num < d->maxedicts;num++)
2874         {
2875                 if (CHECKPVSBIT(d->visiblebits, num))
2876                 {
2877                         CLEARPVSBIT(d->visiblebits, num);
2878                         d->deltabits[num] = E5_FULLUPDATE;
2879                         d->priorities[num] = max(d->priorities[num], 8); // removal is cheap
2880                         d->states[num] = defaultstate;
2881                         d->states[num].number = num;
2882                 }
2883         }
2884
2885         // if there isn't at least enough room for an empty svc_entities,
2886         // don't bother trying...
2887         if (buf.cursize + 11 > buf.maxsize)
2888                 return false;
2889
2890         // build lists of entities by priority level
2891         memset(d->prioritychaincounts, 0, sizeof(d->prioritychaincounts));
2892         l = 0;
2893         for (num = 0;num < d->maxedicts;num++)
2894         {
2895                 if (d->priorities[num])
2896                 {
2897                         if (d->deltabits[num])
2898                         {
2899                                 if (d->priorities[num] < (ENTITYFRAME5_PRIORITYLEVELS - 1))
2900                                         d->priorities[num] = EntityState5_Priority(d, num);
2901                                 l = num;
2902                                 priority = d->priorities[num];
2903                                 if (d->prioritychaincounts[priority] < ENTITYFRAME5_MAXSTATES)
2904                                         d->prioritychains[priority][d->prioritychaincounts[priority]++] = num;
2905                         }
2906                         else
2907                                 d->priorities[num] = 0;
2908                 }
2909         }
2910
2911         packetlog = NULL;
2912         // write stat updates
2913         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)
2914         {
2915                 for (i = 0;i < MAX_CL_STATS && msg->cursize + 6 + 11 <= maxsize;i++)
2916                 {
2917                         if (host_client->statsdeltabits[i>>3] & (1<<(i&7)))
2918                         {
2919                                 host_client->statsdeltabits[i>>3] &= ~(1<<(i&7));
2920                                 // add packetlog entry now that we have something for it
2921                                 if (!packetlog)
2922                                 {
2923                                         packetlog = d->packetlog + packetlognumber;
2924                                         packetlog->packetnumber = framenum;
2925                                         packetlog->numstates = 0;
2926                                         memset(packetlog->statsdeltabits, 0, sizeof(packetlog->statsdeltabits));
2927                                 }
2928                                 packetlog->statsdeltabits[i>>3] |= (1<<(i&7));
2929                                 if (host_client->stats[i] >= 0 && host_client->stats[i] < 256)
2930                                 {
2931                                         MSG_WriteByte(msg, svc_updatestatubyte);
2932                                         MSG_WriteByte(msg, i);
2933                                         MSG_WriteByte(msg, host_client->stats[i]);
2934                                         l = 1;
2935                                 }
2936                                 else
2937                                 {
2938                                         MSG_WriteByte(msg, svc_updatestat);
2939                                         MSG_WriteByte(msg, i);
2940                                         MSG_WriteLong(msg, host_client->stats[i]);
2941                                         l = 1;
2942                                 }
2943                         }
2944                 }
2945         }
2946
2947         // only send empty svc_entities frame if needed
2948         if(!l && !need_empty)
2949                 return false;
2950
2951         // add packetlog entry now that we have something for it
2952         if (!packetlog)
2953         {
2954                 packetlog = d->packetlog + packetlognumber;
2955                 packetlog->packetnumber = framenum;
2956                 packetlog->numstates = 0;
2957                 memset(packetlog->statsdeltabits, 0, sizeof(packetlog->statsdeltabits));
2958         }
2959
2960         // write state updates
2961         if (developer_networkentities.integer >= 10)
2962                 Con_Printf("send: svc_entities %i\n", framenum);
2963         d->latestframenum = framenum;
2964         MSG_WriteByte(msg, svc_entities);
2965         MSG_WriteLong(msg, framenum);
2966         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 && sv.protocol != PROTOCOL_DARKPLACES6)
2967                 MSG_WriteLong(msg, movesequence);
2968         for (priority = ENTITYFRAME5_PRIORITYLEVELS - 1;priority >= 0 && packetlog->numstates < ENTITYFRAME5_MAXSTATES;priority--)
2969         {
2970                 for (i = 0;i < d->prioritychaincounts[priority] && packetlog->numstates < ENTITYFRAME5_MAXSTATES;i++)
2971                 {
2972                         num = d->prioritychains[priority][i];
2973                         n = d->states + num;
2974                         if (d->deltabits[num] & E5_FULLUPDATE)
2975                                 d->deltabits[num] = E5_FULLUPDATE | EntityState5_DeltaBits(&defaultstate, n);
2976                         buf.cursize = 0;
2977                         EntityState5_WriteUpdate(num, n, d->deltabits[num], &buf);
2978                         // if the entity won't fit, try the next one
2979                         if (msg->cursize + buf.cursize + 2 > maxsize)
2980                                 continue;
2981                         // write entity to the packet
2982                         SZ_Write(msg, buf.data, buf.cursize);
2983                         // mark age on entity for prioritization
2984                         d->updateframenum[num] = framenum;
2985                         // log entity so deltabits can be restored later if lost
2986                         packetlog->states[packetlog->numstates].number = num;
2987                         packetlog->states[packetlog->numstates].bits = d->deltabits[num];
2988                         packetlog->numstates++;
2989                         // clear deltabits and priority so it won't be sent again
2990                         d->deltabits[num] = 0;
2991                         d->priorities[num] = 0;
2992                 }
2993         }
2994         MSG_WriteShort(msg, 0x8000);
2995
2996         return true;
2997 }
2998
2999
3000 static void QW_TranslateEffects(entity_state_t *s, int qweffects)
3001 {
3002         s->effects = 0;
3003         s->internaleffects = 0;
3004         if (qweffects & QW_EF_BRIGHTFIELD)
3005                 s->effects |= EF_BRIGHTFIELD;
3006         if (qweffects & QW_EF_MUZZLEFLASH)
3007                 s->effects |= EF_MUZZLEFLASH;
3008         if (qweffects & QW_EF_FLAG1)
3009         {
3010                 // mimic FTEQW's interpretation of EF_FLAG1 as EF_NODRAW on non-player entities
3011                 if (s->number > cl.maxclients)
3012                         s->effects |= EF_NODRAW;
3013                 else
3014                         s->internaleffects |= INTEF_FLAG1QW;
3015         }
3016         if (qweffects & QW_EF_FLAG2)
3017         {
3018                 // mimic FTEQW's interpretation of EF_FLAG2 as EF_ADDITIVE on non-player entities
3019                 if (s->number > cl.maxclients)
3020                         s->effects |= EF_ADDITIVE;
3021                 else
3022                         s->internaleffects |= INTEF_FLAG2QW;
3023         }
3024         if (qweffects & QW_EF_RED)
3025         {
3026                 if (qweffects & QW_EF_BLUE)
3027                         s->effects |= EF_RED | EF_BLUE;
3028                 else
3029                         s->effects |= EF_RED;
3030         }
3031         else if (qweffects & QW_EF_BLUE)
3032                 s->effects |= EF_BLUE;
3033         else if (qweffects & QW_EF_BRIGHTLIGHT)
3034                 s->effects |= EF_BRIGHTLIGHT;
3035         else if (qweffects & QW_EF_DIMLIGHT)
3036                 s->effects |= EF_DIMLIGHT;
3037 }
3038
3039 void EntityStateQW_ReadPlayerUpdate(void)
3040 {
3041         int slot = MSG_ReadByte(&cl_message);
3042         int enumber = slot + 1;
3043         int weaponframe;
3044         int msec;
3045         int playerflags;
3046         int bits;
3047         entity_state_t *s;
3048         // look up the entity
3049         entity_t *ent = cl.entities + enumber;
3050         vec3_t viewangles;
3051         vec3_t velocity;
3052
3053         // slide the current state into the previous
3054         ent->state_previous = ent->state_current;
3055
3056         // read the update
3057         s = &ent->state_current;
3058         *s = defaultstate;
3059         s->active = ACTIVE_NETWORK;
3060         s->number = enumber;
3061         s->colormap = enumber;
3062         playerflags = MSG_ReadShort(&cl_message);
3063         MSG_ReadVector(&cl_message, s->origin, cls.protocol);
3064         s->frame = MSG_ReadByte(&cl_message);
3065
3066         VectorClear(viewangles);
3067         VectorClear(velocity);
3068
3069         if (playerflags & QW_PF_MSEC)
3070         {
3071                 // time difference between last update this player sent to the server,
3072                 // and last input we sent to the server (this packet is in response to
3073                 // our input, so msec is how long ago the last update of this player
3074                 // entity occurred, compared to our input being received)
3075                 msec = MSG_ReadByte(&cl_message);
3076         }
3077         else
3078                 msec = 0;
3079         if (playerflags & QW_PF_COMMAND)
3080         {
3081                 bits = MSG_ReadByte(&cl_message);
3082                 if (bits & QW_CM_ANGLE1)
3083                         viewangles[0] = MSG_ReadAngle16i(&cl_message); // cmd->angles[0]
3084                 if (bits & QW_CM_ANGLE2)
3085                         viewangles[1] = MSG_ReadAngle16i(&cl_message); // cmd->angles[1]
3086                 if (bits & QW_CM_ANGLE3)
3087                         viewangles[2] = MSG_ReadAngle16i(&cl_message); // cmd->angles[2]
3088                 if (bits & QW_CM_FORWARD)
3089                         MSG_ReadShort(&cl_message); // cmd->forwardmove
3090                 if (bits & QW_CM_SIDE)
3091                         MSG_ReadShort(&cl_message); // cmd->sidemove
3092                 if (bits & QW_CM_UP)
3093                         MSG_ReadShort(&cl_message); // cmd->upmove
3094                 if (bits & QW_CM_BUTTONS)
3095                         (void) MSG_ReadByte(&cl_message); // cmd->buttons
3096                 if (bits & QW_CM_IMPULSE)
3097                         (void) MSG_ReadByte(&cl_message); // cmd->impulse
3098                 (void) MSG_ReadByte(&cl_message); // cmd->msec
3099         }
3100         if (playerflags & QW_PF_VELOCITY1)
3101                 velocity[0] = MSG_ReadShort(&cl_message);
3102         if (playerflags & QW_PF_VELOCITY2)
3103                 velocity[1] = MSG_ReadShort(&cl_message);
3104         if (playerflags & QW_PF_VELOCITY3)
3105                 velocity[2] = MSG_ReadShort(&cl_message);
3106         if (playerflags & QW_PF_MODEL)
3107                 s->modelindex = MSG_ReadByte(&cl_message);
3108         else
3109                 s->modelindex = cl.qw_modelindex_player;
3110         if (playerflags & QW_PF_SKINNUM)
3111                 s->skin = MSG_ReadByte(&cl_message);
3112         if (playerflags & QW_PF_EFFECTS)
3113                 QW_TranslateEffects(s, MSG_ReadByte(&cl_message));
3114         if (playerflags & QW_PF_WEAPONFRAME)
3115                 weaponframe = MSG_ReadByte(&cl_message);
3116         else
3117                 weaponframe = 0;
3118
3119         if (enumber == cl.playerentity)
3120         {
3121                 // if this is an update on our player, update the angles
3122                 VectorCopy(cl.viewangles, viewangles);
3123         }
3124
3125         // calculate the entity angles from the viewangles
3126         s->angles[0] = viewangles[0] * -0.0333;
3127         s->angles[1] = viewangles[1];
3128         s->angles[2] = 0;
3129         s->angles[2] = V_CalcRoll(s->angles, velocity)*4;
3130
3131         // if this is an update on our player, update interpolation state
3132         if (enumber == cl.playerentity)
3133         {
3134                 VectorCopy (cl.mpunchangle[0], cl.mpunchangle[1]);
3135                 VectorCopy (cl.mpunchvector[0], cl.mpunchvector[1]);
3136                 VectorCopy (cl.mvelocity[0], cl.mvelocity[1]);
3137                 cl.mviewzoom[1] = cl.mviewzoom[0];
3138
3139                 cl.idealpitch = 0;
3140                 cl.mpunchangle[0][0] = 0;
3141                 cl.mpunchangle[0][1] = 0;
3142                 cl.mpunchangle[0][2] = 0;
3143                 cl.mpunchvector[0][0] = 0;
3144                 cl.mpunchvector[0][1] = 0;
3145                 cl.mpunchvector[0][2] = 0;
3146                 cl.mvelocity[0][0] = 0;
3147                 cl.mvelocity[0][1] = 0;
3148                 cl.mvelocity[0][2] = 0;
3149                 cl.mviewzoom[0] = 1;
3150
3151                 VectorCopy(velocity, cl.mvelocity[0]);
3152                 cl.stats[STAT_WEAPONFRAME] = weaponframe;
3153                 if (playerflags & QW_PF_GIB)
3154                         cl.stats[STAT_VIEWHEIGHT] = 8;
3155                 else if (playerflags & QW_PF_DEAD)
3156                         cl.stats[STAT_VIEWHEIGHT] = -16;
3157                 else
3158                         cl.stats[STAT_VIEWHEIGHT] = 22;
3159         }
3160
3161         // set the cl.entities_active flag
3162         cl.entities_active[enumber] = (s->active == ACTIVE_NETWORK);
3163         // set the update time
3164         s->time = cl.mtime[0] - msec * 0.001; // qw has no clock
3165         // check if we need to update the lerp stuff
3166         if (s->active == ACTIVE_NETWORK)
3167                 CL_MoveLerpEntityStates(&cl.entities[enumber]);
3168 }
3169
3170 static void EntityStateQW_ReadEntityUpdate(entity_state_t *s, int bits)
3171 {
3172         int qweffects = 0;
3173         s->active = ACTIVE_NETWORK;
3174         s->number = bits & 511;
3175         bits &= ~511;
3176         if (bits & QW_U_MOREBITS)
3177                 bits |= MSG_ReadByte(&cl_message);
3178
3179         // store the QW_U_SOLID bit here?
3180
3181         if (bits & QW_U_MODEL)
3182                 s->modelindex = MSG_ReadByte(&cl_message);
3183         if (bits & QW_U_FRAME)
3184                 s->frame = MSG_ReadByte(&cl_message);
3185         if (bits & QW_U_COLORMAP)
3186                 s->colormap = MSG_ReadByte(&cl_message);
3187         if (bits & QW_U_SKIN)
3188                 s->skin = MSG_ReadByte(&cl_message);
3189         if (bits & QW_U_EFFECTS)
3190                 QW_TranslateEffects(s, qweffects = MSG_ReadByte(&cl_message));
3191         if (bits & QW_U_ORIGIN1)
3192                 s->origin[0] = MSG_ReadCoord13i(&cl_message);
3193         if (bits & QW_U_ANGLE1)
3194                 s->angles[0] = MSG_ReadAngle8i(&cl_message);
3195         if (bits & QW_U_ORIGIN2)
3196                 s->origin[1] = MSG_ReadCoord13i(&cl_message);
3197         if (bits & QW_U_ANGLE2)
3198                 s->angles[1] = MSG_ReadAngle8i(&cl_message);
3199         if (bits & QW_U_ORIGIN3)
3200                 s->origin[2] = MSG_ReadCoord13i(&cl_message);
3201         if (bits & QW_U_ANGLE3)
3202                 s->angles[2] = MSG_ReadAngle8i(&cl_message);
3203
3204         if (developer_networkentities.integer >= 2)
3205         {
3206                 Con_Printf("ReadFields e%i", s->number);
3207                 if (bits & QW_U_MODEL)
3208                         Con_Printf(" U_MODEL %i", s->modelindex);
3209                 if (bits & QW_U_FRAME)
3210                         Con_Printf(" U_FRAME %i", s->frame);
3211                 if (bits & QW_U_COLORMAP)
3212                         Con_Printf(" U_COLORMAP %i", s->colormap);
3213                 if (bits & QW_U_SKIN)
3214                         Con_Printf(" U_SKIN %i", s->skin);
3215                 if (bits & QW_U_EFFECTS)
3216                         Con_Printf(" U_EFFECTS %i", qweffects);
3217                 if (bits & QW_U_ORIGIN1)
3218                         Con_Printf(" U_ORIGIN1 %f", s->origin[0]);
3219                 if (bits & QW_U_ANGLE1)
3220                         Con_Printf(" U_ANGLE1 %f", s->angles[0]);
3221                 if (bits & QW_U_ORIGIN2)
3222                         Con_Printf(" U_ORIGIN2 %f", s->origin[1]);
3223                 if (bits & QW_U_ANGLE2)
3224                         Con_Printf(" U_ANGLE2 %f", s->angles[1]);
3225                 if (bits & QW_U_ORIGIN3)
3226                         Con_Printf(" U_ORIGIN3 %f", s->origin[2]);
3227                 if (bits & QW_U_ANGLE3)
3228                         Con_Printf(" U_ANGLE3 %f", s->angles[2]);
3229                 if (bits & QW_U_SOLID)
3230                         Con_Printf(" U_SOLID");
3231                 Con_Print("\n");
3232         }
3233 }
3234
3235 entityframeqw_database_t *EntityFrameQW_AllocDatabase(mempool_t *pool)
3236 {
3237         entityframeqw_database_t *d;
3238         d = (entityframeqw_database_t *)Mem_Alloc(pool, sizeof(*d));
3239         return d;
3240 }
3241
3242 void EntityFrameQW_FreeDatabase(entityframeqw_database_t *d)
3243 {
3244         Mem_Free(d);
3245 }
3246
3247 void EntityFrameQW_CL_ReadFrame(qboolean delta)
3248 {
3249         qboolean invalid = false;
3250         int number, oldsnapindex, newsnapindex, oldindex, newindex, oldnum, newnum;
3251         entity_t *ent;
3252         entityframeqw_database_t *d;
3253         entityframeqw_snapshot_t *oldsnap, *newsnap;
3254
3255         if (!cl.entitydatabaseqw)
3256                 cl.entitydatabaseqw = EntityFrameQW_AllocDatabase(cls.levelmempool);
3257         d = cl.entitydatabaseqw;
3258
3259         // there is no cls.netcon in demos, so this reading code can't access
3260         // cls.netcon-> at all...  so cls.qw_incoming_sequence and
3261         // cls.qw_outgoing_sequence are updated every time the corresponding
3262         // cls.netcon->qw. variables are updated
3263         // read the number of this frame to echo back in next input packet
3264         cl.qw_validsequence = cls.qw_incoming_sequence;
3265         newsnapindex = cl.qw_validsequence & QW_UPDATE_MASK;
3266         newsnap = d->snapshot + newsnapindex;
3267         memset(newsnap, 0, sizeof(*newsnap));
3268         oldsnap = NULL;
3269         if (delta)
3270         {
3271                 number = MSG_ReadByte(&cl_message);
3272                 oldsnapindex = cl.qw_deltasequence[newsnapindex];
3273                 if ((number & QW_UPDATE_MASK) != (oldsnapindex & QW_UPDATE_MASK))
3274                         Con_DPrintf("WARNING: from mismatch\n");
3275                 if (oldsnapindex != -1)
3276                 {
3277                         if (cls.qw_outgoing_sequence - oldsnapindex >= QW_UPDATE_BACKUP-1)
3278                         {
3279                                 Con_DPrintf("delta update too old\n");
3280                                 newsnap->invalid = invalid = true; // too old
3281                                 delta = false;
3282                         }
3283                         oldsnap = d->snapshot + (oldsnapindex & QW_UPDATE_MASK);
3284                 }
3285                 else
3286                         delta = false;
3287         }
3288
3289         // if we can't decode this frame properly, report that to the server
3290         if (invalid)
3291                 cl.qw_validsequence = 0;
3292
3293         // read entity numbers until we find a 0x0000
3294         // (which would be an empty update on world entity, but is actually a terminator)
3295         newsnap->num_entities = 0;
3296         oldindex = 0;
3297         for (;;)
3298         {
3299                 int word = (unsigned short)MSG_ReadShort(&cl_message);
3300                 if (cl_message.badread)
3301                         return; // just return, the main parser will print an error
3302                 newnum = word == 0 ? 512 : (word & 511);
3303                 oldnum = delta ? (oldindex >= oldsnap->num_entities ? 9999 : oldsnap->entities[oldindex].number) : 9999;
3304
3305                 // copy unmodified oldsnap entities
3306                 while (newnum > oldnum) // delta only
3307                 {
3308                         if (developer_networkentities.integer >= 2)
3309                                 Con_Printf("copy %i\n", oldnum);
3310                         // copy one of the old entities
3311                         if (newsnap->num_entities >= QW_MAX_PACKET_ENTITIES)
3312                                 Host_Error("EntityFrameQW_CL_ReadFrame: newsnap->num_entities == MAX_PACKETENTITIES");
3313                         newsnap->entities[newsnap->num_entities] = oldsnap->entities[oldindex++];
3314                         newsnap->num_entities++;
3315                         oldnum = oldindex >= oldsnap->num_entities ? 9999 : oldsnap->entities[oldindex].number;
3316                 }
3317
3318                 if (word == 0)
3319                         break;
3320
3321                 if (developer_networkentities.integer >= 2)
3322                 {
3323                         if (word & QW_U_REMOVE)
3324                                 Con_Printf("remove %i\n", newnum);
3325                         else if (newnum == oldnum)
3326                                 Con_Printf("delta %i\n", newnum);
3327                         else
3328                                 Con_Printf("baseline %i\n", newnum);
3329                 }
3330
3331                 if (word & QW_U_REMOVE)
3332                 {
3333                         if (newnum != oldnum && !delta && !invalid)
3334                         {
3335                                 cl.qw_validsequence = 0;
3336                                 Con_Printf("WARNING: U_REMOVE %i on full update\n", newnum);
3337                         }
3338                 }
3339                 else
3340                 {
3341                         if (newsnap->num_entities >= QW_MAX_PACKET_ENTITIES)
3342                                 Host_Error("EntityFrameQW_CL_ReadFrame: newsnap->num_entities == MAX_PACKETENTITIES");
3343                         newsnap->entities[newsnap->num_entities] = (newnum == oldnum) ? oldsnap->entities[oldindex] : cl.entities[newnum].state_baseline;
3344                         EntityStateQW_ReadEntityUpdate(newsnap->entities + newsnap->num_entities, word);
3345                         newsnap->num_entities++;
3346                 }
3347
3348                 if (newnum == oldnum)
3349                         oldindex++;
3350         }
3351
3352         // expand cl.num_entities to include every entity we've seen this game
3353         newnum = newsnap->num_entities ? newsnap->entities[newsnap->num_entities - 1].number : 1;
3354         if (cl.num_entities <= newnum)
3355         {
3356                 cl.num_entities = newnum + 1;
3357                 if (cl.max_entities < newnum + 1)
3358                         CL_ExpandEntities(newnum);
3359         }
3360
3361         // now update the non-player entities from the snapshot states
3362         number = cl.maxclients + 1;
3363         for (newindex = 0;;newindex++)
3364         {
3365                 newnum = newindex >= newsnap->num_entities ? cl.num_entities : newsnap->entities[newindex].number;
3366                 // kill any missing entities
3367                 for (;number < newnum;number++)
3368                 {
3369                         if (cl.entities_active[number])
3370                         {
3371                                 cl.entities_active[number] = false;
3372                                 cl.entities[number].state_current.active = ACTIVE_NOT;
3373                         }
3374                 }
3375                 if (number >= cl.num_entities)
3376                         break;
3377                 // update the entity
3378                 ent = &cl.entities[number];
3379                 ent->state_previous = ent->state_current;
3380                 ent->state_current = newsnap->entities[newindex];
3381                 ent->state_current.time = cl.mtime[0];
3382                 CL_MoveLerpEntityStates(ent);
3383                 // the entity lives again...
3384                 cl.entities_active[number] = true;
3385                 number++;
3386         }
3387 }