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