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