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