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