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