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