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