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