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