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