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