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