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