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