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