]> icculus.org git repositories - divverent/darkplaces.git/blob - protocol.c
implemented DP_EF_NODEPTHTEST extension
[divverent/darkplaces.git] / protocol.c
1
2 #include "quakedef.h"
3
4 // this is 80 bytes
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 origin[3];
10         {0,0,0},//float angles[3];
11         0,//int number; // entity number this state is for
12         0,//int effects;
13         0,//unsigned short modelindex;
14         0,//unsigned short frame;
15         0,//unsigned short tagentity;
16         0,//unsigned short specialvisibilityradius; // ! larger if it has effects/light
17         0,//unsigned short viewmodelforclient; // !
18         0,//unsigned short exteriormodelforclient; // ! not shown if first person viewing from this entity, shown in all other cases
19         0,//unsigned short nodrawtoclient; // !
20         0,//unsigned short drawonlytoclient; // !
21         {0,0,0,0},//unsigned short light[4]; // color*256 (0.00 to 255.996), and radius*1
22         0,//unsigned char active; // true if a valid state
23         0,//unsigned char lightstyle;
24         0,//unsigned char lightpflags;
25         0,//unsigned char colormap;
26         0,//unsigned char skin; // also chooses cubemap for rtlights if lightpflags & LIGHTPFLAGS_FULLDYNAMIC
27         255,//unsigned char alpha;
28         16,//unsigned char scale;
29         0,//unsigned char glowsize;
30         254,//unsigned char glowcolor;
31         0,//unsigned char flags;
32         0,//unsigned char tagindex;
33         255,//unsigned char colormod;
34         // padding to a multiple of 8 bytes (to align the double time)
35         {0,0,0,0}//unsigned char unused[4]; // !
36 };
37
38 // keep track of quake entities because they need to be killed if they get stale
39 int cl_lastquakeentity = 0;
40 qbyte cl_isquakeentity[MAX_EDICTS];
41
42 void EntityFrameQuake_ReadEntity(int bits)
43 {
44         int num;
45         entity_t *ent;
46         entity_state_t s;
47
48         if (bits & U_MOREBITS)
49                 bits |= (MSG_ReadByte()<<8);
50         if ((bits & U_EXTEND1) && cl.protocol != PROTOCOL_NEHAHRAMOVIE)
51         {
52                 bits |= MSG_ReadByte() << 16;
53                 if (bits & U_EXTEND2)
54                         bits |= MSG_ReadByte() << 24;
55         }
56
57         if (bits & U_LONGENTITY)
58                 num = (unsigned short) MSG_ReadShort ();
59         else
60                 num = MSG_ReadByte ();
61
62         if (num >= MAX_EDICTS)
63                 Host_Error("EntityFrameQuake_ReadEntity: entity number (%i) >= MAX_EDICTS (%i)\n", num, MAX_EDICTS);
64         if (num < 1)
65                 Host_Error("EntityFrameQuake_ReadEntity: invalid entity number (%i)\n", num);
66
67         ent = cl_entities + num;
68
69         // note: this inherits the 'active' state of the baseline chosen
70         // (state_baseline is always active, state_current may not be active if
71         // the entity was missing in the last frame)
72         if (bits & U_DELTA)
73                 s = ent->state_current;
74         else
75         {
76                 s = ent->state_baseline;
77                 s.active = true;
78         }
79
80         cl_isquakeentity[num] = true;
81         if (cl_lastquakeentity < num)
82                 cl_lastquakeentity = num;
83         s.number = num;
84         s.time = cl.mtime[0];
85         s.flags = 0;
86         if (bits & U_MODEL)             s.modelindex = (s.modelindex & 0xFF00) | MSG_ReadByte();
87         if (bits & U_FRAME)             s.frame = (s.frame & 0xFF00) | MSG_ReadByte();
88         if (bits & U_COLORMAP)  s.colormap = MSG_ReadByte();
89         if (bits & U_SKIN)              s.skin = MSG_ReadByte();
90         if (bits & U_EFFECTS)   s.effects = (s.effects & 0xFF00) | MSG_ReadByte();
91         if (bits & U_ORIGIN1)   s.origin[0] = MSG_ReadCoord(cl.protocol);
92         if (bits & U_ANGLE1)    s.angles[0] = MSG_ReadAngle(cl.protocol);
93         if (bits & U_ORIGIN2)   s.origin[1] = MSG_ReadCoord(cl.protocol);
94         if (bits & U_ANGLE2)    s.angles[1] = MSG_ReadAngle(cl.protocol);
95         if (bits & U_ORIGIN3)   s.origin[2] = MSG_ReadCoord(cl.protocol);
96         if (bits & U_ANGLE3)    s.angles[2] = MSG_ReadAngle(cl.protocol);
97         if (bits & U_STEP)              s.flags |= RENDER_STEP;
98         if (bits & U_ALPHA)             s.alpha = MSG_ReadByte();
99         if (bits & U_SCALE)             s.scale = MSG_ReadByte();
100         if (bits & U_EFFECTS2)  s.effects = (s.effects & 0x00FF) | (MSG_ReadByte() << 8);
101         if (bits & U_GLOWSIZE)  s.glowsize = MSG_ReadByte();
102         if (bits & U_GLOWCOLOR) s.glowcolor = MSG_ReadByte();
103         if (bits & U_COLORMOD)  s.colormod = MSG_ReadByte();
104         if (bits & U_GLOWTRAIL) s.flags |= RENDER_GLOWTRAIL;
105         if (bits & U_FRAME2)    s.frame = (s.frame & 0x00FF) | (MSG_ReadByte() << 8);
106         if (bits & U_MODEL2)    s.modelindex = (s.modelindex & 0x00FF) | (MSG_ReadByte() << 8);
107         if (bits & U_VIEWMODEL) s.flags |= RENDER_VIEWMODEL;
108         if (bits & U_EXTERIORMODEL)     s.flags |= RENDER_EXTERIORMODEL;
109
110         // LordHavoc: to allow playback of the Nehahra movie
111         if (cl.protocol == PROTOCOL_NEHAHRAMOVIE && (bits & U_EXTEND1))
112         {
113                 // LordHavoc: evil format
114                 int i = MSG_ReadFloat();
115                 int j = MSG_ReadFloat() * 255.0f;
116                 if (i == 2)
117                 {
118                         i = MSG_ReadFloat();
119                         if (i)
120                                 s.effects |= EF_FULLBRIGHT;
121                 }
122                 if (j < 0)
123                         s.alpha = 0;
124                 else if (j == 0 || j >= 255)
125                         s.alpha = 255;
126                 else
127                         s.alpha = j;
128         }
129
130         ent->state_previous = ent->state_current;
131         ent->state_current = s;
132         if (ent->state_current.active)
133         {
134                 CL_MoveLerpEntityStates(ent);
135                 cl_entities_active[ent->state_current.number] = true;
136         }
137
138         if (msg_badread)
139                 Host_Error("EntityFrameQuake_ReadEntity: read error\n");
140 }
141
142 void EntityFrameQuake_ISeeDeadEntities(void)
143 {
144         int num, lastentity;
145         if (cl_lastquakeentity == 0)
146                 return;
147         lastentity = cl_lastquakeentity;
148         cl_lastquakeentity = 0;
149         for (num = 0;num < lastentity;num++)
150         {
151                 if (cl_isquakeentity[num])
152                 {
153                         cl_isquakeentity[num] = false;
154                         if (cl_entities_active[num])
155                         {
156                                 if (cl_entities[num].state_current.time == cl.mtime[0])
157                                 {
158                                         cl_isquakeentity[num] = true;
159                                         cl_lastquakeentity = num;
160                                 }
161                                 else
162                                 {
163                                         cl_isquakeentity[num] = false;
164                                         cl_entities_active[num] = false;
165                                         cl_entities[num].state_current = defaultstate;
166                                         cl_entities[num].state_current.number = num;
167                                 }
168                         }
169                 }
170         }
171 }
172
173 void EntityFrameQuake_WriteFrame(sizebuf_t *msg, int numstates, const entity_state_t *states)
174 {
175         const entity_state_t *s;
176         entity_state_t baseline;
177         int i, bits;
178         sizebuf_t buf;
179         qbyte data[128];
180
181         // prepare the buffer
182         memset(&buf, 0, sizeof(buf));
183         buf.data = data;
184         buf.maxsize = sizeof(data);
185
186         for (i = 0, s = states;i < numstates;i++, s++)
187         {
188                 // prepare the buffer
189                 SZ_Clear(&buf);
190
191 // send an update
192                 bits = 0;
193                 if (s->number >= 256)
194                         bits |= U_LONGENTITY;
195                 if (s->flags & RENDER_STEP)
196                         bits |= U_STEP;
197                 if (s->flags & RENDER_VIEWMODEL)
198                         bits |= U_VIEWMODEL;
199                 if (s->flags & RENDER_GLOWTRAIL)
200                         bits |= U_GLOWTRAIL;
201                 if (s->flags & RENDER_EXTERIORMODEL)
202                         bits |= U_EXTERIORMODEL;
203
204                 // LordHavoc: old stuff, but rewritten to have more exact tolerances
205                 baseline = sv.edicts[s->number].e->baseline;
206                 if (baseline.origin[0] != s->origin[0])
207                         bits |= U_ORIGIN1;
208                 if (baseline.origin[1] != s->origin[1])
209                         bits |= U_ORIGIN2;
210                 if (baseline.origin[2] != s->origin[2])
211                         bits |= U_ORIGIN3;
212                 if (baseline.angles[0] != s->angles[0])
213                         bits |= U_ANGLE1;
214                 if (baseline.angles[1] != s->angles[1])
215                         bits |= U_ANGLE2;
216                 if (baseline.angles[2] != s->angles[2])
217                         bits |= U_ANGLE3;
218                 if (baseline.colormap != s->colormap)
219                         bits |= U_COLORMAP;
220                 if (baseline.skin != s->skin)
221                         bits |= U_SKIN;
222                 if (baseline.frame != s->frame)
223                 {
224                         bits |= U_FRAME;
225                         if (s->frame & 0xFF00)
226                                 bits |= U_FRAME2;
227                 }
228                 if (baseline.effects != s->effects)
229                 {
230                         bits |= U_EFFECTS;
231                         if (s->effects & 0xFF00)
232                                 bits |= U_EFFECTS2;
233                 }
234                 if (baseline.modelindex != s->modelindex)
235                 {
236                         bits |= U_MODEL;
237                         if (s->modelindex & 0xFF00)
238                                 bits |= U_MODEL2;
239                 }
240                 if (baseline.alpha != s->alpha)
241                         bits |= U_ALPHA;
242                 if (baseline.scale != s->scale)
243                         bits |= U_SCALE;
244                 if (baseline.glowsize != s->glowsize)
245                         bits |= U_GLOWSIZE;
246                 if (baseline.glowcolor != s->glowcolor)
247                         bits |= U_GLOWCOLOR;
248
249                 // if extensions are disabled, clear the relevant update flags
250                 if (sv.netquakecompatible)
251                         bits &= 0x7FFF;
252
253                 // write the message
254                 if (bits >= 16777216)
255                         bits |= U_EXTEND2;
256                 if (bits >= 65536)
257                         bits |= U_EXTEND1;
258                 if (bits >= 256)
259                         bits |= U_MOREBITS;
260                 bits |= U_SIGNAL;
261
262                 MSG_WriteByte (&buf, bits);
263                 if (bits & U_MOREBITS)          MSG_WriteByte(&buf, bits>>8);
264                 if (bits & U_EXTEND1)           MSG_WriteByte(&buf, bits>>16);
265                 if (bits & U_EXTEND2)           MSG_WriteByte(&buf, bits>>24);
266                 if (bits & U_LONGENTITY)        MSG_WriteShort(&buf, s->number);
267                 else                                            MSG_WriteByte(&buf, s->number);
268
269                 if (bits & U_MODEL)                     MSG_WriteByte(&buf, s->modelindex);
270                 if (bits & U_FRAME)                     MSG_WriteByte(&buf, s->frame);
271                 if (bits & U_COLORMAP)          MSG_WriteByte(&buf, s->colormap);
272                 if (bits & U_SKIN)                      MSG_WriteByte(&buf, s->skin);
273                 if (bits & U_EFFECTS)           MSG_WriteByte(&buf, s->effects);
274                 if (bits & U_ORIGIN1)           MSG_WriteCoord(&buf, s->origin[0], sv.protocol);
275                 if (bits & U_ANGLE1)            MSG_WriteAngle(&buf, s->angles[0], sv.protocol);
276                 if (bits & U_ORIGIN2)           MSG_WriteCoord(&buf, s->origin[1], sv.protocol);
277                 if (bits & U_ANGLE2)            MSG_WriteAngle(&buf, s->angles[1], sv.protocol);
278                 if (bits & U_ORIGIN3)           MSG_WriteCoord(&buf, s->origin[2], sv.protocol);
279                 if (bits & U_ANGLE3)            MSG_WriteAngle(&buf, s->angles[2], sv.protocol);
280                 if (bits & U_ALPHA)                     MSG_WriteByte(&buf, s->alpha);
281                 if (bits & U_SCALE)                     MSG_WriteByte(&buf, s->scale);
282                 if (bits & U_EFFECTS2)          MSG_WriteByte(&buf, s->effects >> 8);
283                 if (bits & U_GLOWSIZE)          MSG_WriteByte(&buf, s->glowsize);
284                 if (bits & U_GLOWCOLOR)         MSG_WriteByte(&buf, s->glowcolor);
285                 if (bits & U_COLORMOD)          MSG_WriteByte(&buf, s->colormod);
286                 if (bits & U_FRAME2)            MSG_WriteByte(&buf, s->frame >> 8);
287                 if (bits & U_MODEL2)            MSG_WriteByte(&buf, s->modelindex >> 8);
288
289                 // if the commit is full, we're done this frame
290                 if (msg->cursize + buf.cursize > msg->maxsize)
291                 {
292                         // next frame we will continue where we left off
293                         break;
294                 }
295                 // write the message to the packet
296                 SZ_Write(msg, buf.data, buf.cursize);
297         }
298 }
299
300 int EntityState_DeltaBits(const entity_state_t *o, const entity_state_t *n)
301 {
302         unsigned int bits;
303         // if o is not active, delta from default
304         if (!o->active)
305                 o = &defaultstate;
306         bits = 0;
307         if (fabs(n->origin[0] - o->origin[0]) > (1.0f / 256.0f))
308                 bits |= E_ORIGIN1;
309         if (fabs(n->origin[1] - o->origin[1]) > (1.0f / 256.0f))
310                 bits |= E_ORIGIN2;
311         if (fabs(n->origin[2] - o->origin[2]) > (1.0f / 256.0f))
312                 bits |= E_ORIGIN3;
313         if ((qbyte) (n->angles[0] * (256.0f / 360.0f)) != (qbyte) (o->angles[0] * (256.0f / 360.0f)))
314                 bits |= E_ANGLE1;
315         if ((qbyte) (n->angles[1] * (256.0f / 360.0f)) != (qbyte) (o->angles[1] * (256.0f / 360.0f)))
316                 bits |= E_ANGLE2;
317         if ((qbyte) (n->angles[2] * (256.0f / 360.0f)) != (qbyte) (o->angles[2] * (256.0f / 360.0f)))
318                 bits |= E_ANGLE3;
319         if ((n->modelindex ^ o->modelindex) & 0x00FF)
320                 bits |= E_MODEL1;
321         if ((n->modelindex ^ o->modelindex) & 0xFF00)
322                 bits |= E_MODEL2;
323         if ((n->frame ^ o->frame) & 0x00FF)
324                 bits |= E_FRAME1;
325         if ((n->frame ^ o->frame) & 0xFF00)
326                 bits |= E_FRAME2;
327         if ((n->effects ^ o->effects) & 0x00FF)
328                 bits |= E_EFFECTS1;
329         if ((n->effects ^ o->effects) & 0xFF00)
330                 bits |= E_EFFECTS2;
331         if (n->colormap != o->colormap)
332                 bits |= E_COLORMAP;
333         if (n->skin != o->skin)
334                 bits |= E_SKIN;
335         if (n->alpha != o->alpha)
336                 bits |= E_ALPHA;
337         if (n->scale != o->scale)
338                 bits |= E_SCALE;
339         if (n->glowsize != o->glowsize)
340                 bits |= E_GLOWSIZE;
341         if (n->glowcolor != o->glowcolor)
342                 bits |= E_GLOWCOLOR;
343         if (n->flags != o->flags)
344                 bits |= E_FLAGS;
345         if (n->tagindex != o->tagindex || n->tagentity != o->tagentity)
346                 bits |= E_TAGATTACHMENT;
347         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])
348                 bits |= E_LIGHT;
349         if (n->lightstyle != o->lightstyle)
350                 bits |= E_LIGHTSTYLE;
351         if (n->lightpflags != o->lightpflags)
352                 bits |= E_LIGHTPFLAGS;
353
354         if (bits)
355         {
356                 if (bits &  0xFF000000)
357                         bits |= 0x00800000;
358                 if (bits &  0x00FF0000)
359                         bits |= 0x00008000;
360                 if (bits &  0x0000FF00)
361                         bits |= 0x00000080;
362         }
363         return bits;
364 }
365
366 void EntityState_WriteExtendBits(sizebuf_t *msg, unsigned int bits)
367 {
368         MSG_WriteByte(msg, bits & 0xFF);
369         if (bits & 0x00000080)
370         {
371                 MSG_WriteByte(msg, (bits >> 8) & 0xFF);
372                 if (bits & 0x00008000)
373                 {
374                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
375                         if (bits & 0x00800000)
376                                 MSG_WriteByte(msg, (bits >> 24) & 0xFF);
377                 }
378         }
379 }
380
381 void EntityState_WriteFields(const entity_state_t *ent, sizebuf_t *msg, unsigned int bits)
382 {
383         if (sv.protocol == PROTOCOL_DARKPLACES2)
384         {
385                 if (bits & E_ORIGIN1)
386                         MSG_WriteCoord16i(msg, ent->origin[0]);
387                 if (bits & E_ORIGIN2)
388                         MSG_WriteCoord16i(msg, ent->origin[1]);
389                 if (bits & E_ORIGIN3)
390                         MSG_WriteCoord16i(msg, ent->origin[2]);
391         }
392         else if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
393         {
394                 // LordHavoc: have to write flags first, as they can modify protocol
395                 if (bits & E_FLAGS)
396                         MSG_WriteByte(msg, ent->flags);
397                 if (ent->flags & RENDER_LOWPRECISION)
398                 {
399                         if (bits & E_ORIGIN1)
400                                 MSG_WriteCoord16i(msg, ent->origin[0]);
401                         if (bits & E_ORIGIN2)
402                                 MSG_WriteCoord16i(msg, ent->origin[1]);
403                         if (bits & E_ORIGIN3)
404                                 MSG_WriteCoord16i(msg, ent->origin[2]);
405                 }
406                 else
407                 {
408                         if (bits & E_ORIGIN1)
409                                 MSG_WriteCoord32f(msg, ent->origin[0]);
410                         if (bits & E_ORIGIN2)
411                                 MSG_WriteCoord32f(msg, ent->origin[1]);
412                         if (bits & E_ORIGIN3)
413                                 MSG_WriteCoord32f(msg, ent->origin[2]);
414                 }
415         }
416         if (sv.protocol == PROTOCOL_DARKPLACES5 && !(ent->flags & RENDER_LOWPRECISION))
417         {
418                 if (bits & E_ANGLE1)
419                         MSG_WriteAngle16i(msg, ent->angles[0]);
420                 if (bits & E_ANGLE2)
421                         MSG_WriteAngle16i(msg, ent->angles[1]);
422                 if (bits & E_ANGLE3)
423                         MSG_WriteAngle16i(msg, ent->angles[2]);
424         }
425         else
426         {
427                 if (bits & E_ANGLE1)
428                         MSG_WriteAngle8i(msg, ent->angles[0]);
429                 if (bits & E_ANGLE2)
430                         MSG_WriteAngle8i(msg, ent->angles[1]);
431                 if (bits & E_ANGLE3)
432                         MSG_WriteAngle8i(msg, ent->angles[2]);
433         }
434         if (bits & E_MODEL1)
435                 MSG_WriteByte(msg, ent->modelindex & 0xFF);
436         if (bits & E_MODEL2)
437                 MSG_WriteByte(msg, (ent->modelindex >> 8) & 0xFF);
438         if (bits & E_FRAME1)
439                 MSG_WriteByte(msg, ent->frame & 0xFF);
440         if (bits & E_FRAME2)
441                 MSG_WriteByte(msg, (ent->frame >> 8) & 0xFF);
442         if (bits & E_EFFECTS1)
443                 MSG_WriteByte(msg, ent->effects & 0xFF);
444         if (bits & E_EFFECTS2)
445                 MSG_WriteByte(msg, (ent->effects >> 8) & 0xFF);
446         if (bits & E_COLORMAP)
447                 MSG_WriteByte(msg, ent->colormap);
448         if (bits & E_SKIN)
449                 MSG_WriteByte(msg, ent->skin);
450         if (bits & E_ALPHA)
451                 MSG_WriteByte(msg, ent->alpha);
452         if (bits & E_SCALE)
453                 MSG_WriteByte(msg, ent->scale);
454         if (bits & E_GLOWSIZE)
455                 MSG_WriteByte(msg, ent->glowsize);
456         if (bits & E_GLOWCOLOR)
457                 MSG_WriteByte(msg, ent->glowcolor);
458         if (sv.protocol == PROTOCOL_DARKPLACES2)
459                 if (bits & E_FLAGS)
460                         MSG_WriteByte(msg, ent->flags);
461         if (bits & E_TAGATTACHMENT)
462         {
463                 MSG_WriteShort(msg, ent->tagentity);
464                 MSG_WriteByte(msg, ent->tagindex);
465         }
466         if (bits & E_LIGHT)
467         {
468                 MSG_WriteShort(msg, ent->light[0]);
469                 MSG_WriteShort(msg, ent->light[1]);
470                 MSG_WriteShort(msg, ent->light[2]);
471                 MSG_WriteShort(msg, ent->light[3]);
472         }
473         if (bits & E_LIGHTSTYLE)
474                 MSG_WriteByte(msg, ent->lightstyle);
475         if (bits & E_LIGHTPFLAGS)
476                 MSG_WriteByte(msg, ent->lightpflags);
477 }
478
479 void EntityState_WriteUpdate(const entity_state_t *ent, sizebuf_t *msg, const entity_state_t *delta)
480 {
481         unsigned int bits;
482         if (ent->active)
483         {
484                 // entity is active, check for changes from the delta
485                 if ((bits = EntityState_DeltaBits(delta, ent)))
486                 {
487                         // write the update number, bits, and fields
488                         MSG_WriteShort(msg, ent->number);
489                         EntityState_WriteExtendBits(msg, bits);
490                         EntityState_WriteFields(ent, msg, bits);
491                 }
492         }
493         else
494         {
495                 // entity is inactive, check if the delta was active
496                 if (delta->active)
497                 {
498                         // write the remove number
499                         MSG_WriteShort(msg, ent->number | 0x8000);
500                 }
501         }
502 }
503
504 int EntityState_ReadExtendBits(void)
505 {
506         unsigned int bits;
507         bits = MSG_ReadByte();
508         if (bits & 0x00000080)
509         {
510                 bits |= MSG_ReadByte() << 8;
511                 if (bits & 0x00008000)
512                 {
513                         bits |= MSG_ReadByte() << 16;
514                         if (bits & 0x00800000)
515                                 bits |= MSG_ReadByte() << 24;
516                 }
517         }
518         return bits;
519 }
520
521 void EntityState_ReadFields(entity_state_t *e, unsigned int bits)
522 {
523         if (cl.protocol == PROTOCOL_DARKPLACES2)
524         {
525                 if (bits & E_ORIGIN1)
526                         e->origin[0] = MSG_ReadCoord16i();
527                 if (bits & E_ORIGIN2)
528                         e->origin[1] = MSG_ReadCoord16i();
529                 if (bits & E_ORIGIN3)
530                         e->origin[2] = MSG_ReadCoord16i();
531         }
532         else if (cl.protocol == PROTOCOL_DARKPLACES1 || cl.protocol == PROTOCOL_DARKPLACES3 || cl.protocol == PROTOCOL_DARKPLACES4 || cl.protocol == PROTOCOL_DARKPLACES5)
533         {
534                 if (bits & E_FLAGS)
535                         e->flags = MSG_ReadByte();
536                 if (e->flags & RENDER_LOWPRECISION)
537                 {
538                         if (bits & E_ORIGIN1)
539                                 e->origin[0] = MSG_ReadCoord16i();
540                         if (bits & E_ORIGIN2)
541                                 e->origin[1] = MSG_ReadCoord16i();
542                         if (bits & E_ORIGIN3)
543                                 e->origin[2] = MSG_ReadCoord16i();
544                 }
545                 else
546                 {
547                         if (bits & E_ORIGIN1)
548                                 e->origin[0] = MSG_ReadCoord32f();
549                         if (bits & E_ORIGIN2)
550                                 e->origin[1] = MSG_ReadCoord32f();
551                         if (bits & E_ORIGIN3)
552                                 e->origin[2] = MSG_ReadCoord32f();
553                 }
554         }
555         if (cl.protocol == PROTOCOL_DARKPLACES5 && !(e->flags & RENDER_LOWPRECISION))
556         {
557                 if (bits & E_ANGLE1)
558                         e->angles[0] = MSG_ReadAngle16i();
559                 if (bits & E_ANGLE2)
560                         e->angles[1] = MSG_ReadAngle16i();
561                 if (bits & E_ANGLE3)
562                         e->angles[2] = MSG_ReadAngle16i();
563         }
564         else
565         {
566                 if (bits & E_ANGLE1)
567                         e->angles[0] = MSG_ReadAngle8i();
568                 if (bits & E_ANGLE2)
569                         e->angles[1] = MSG_ReadAngle8i();
570                 if (bits & E_ANGLE3)
571                         e->angles[2] = MSG_ReadAngle8i();
572         }
573         if (bits & E_MODEL1)
574                 e->modelindex = (e->modelindex & 0xFF00) | (unsigned int) MSG_ReadByte();
575         if (bits & E_MODEL2)
576                 e->modelindex = (e->modelindex & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
577         if (bits & E_FRAME1)
578                 e->frame = (e->frame & 0xFF00) | (unsigned int) MSG_ReadByte();
579         if (bits & E_FRAME2)
580                 e->frame = (e->frame & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
581         if (bits & E_EFFECTS1)
582                 e->effects = (e->effects & 0xFF00) | (unsigned int) MSG_ReadByte();
583         if (bits & E_EFFECTS2)
584                 e->effects = (e->effects & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
585         if (bits & E_COLORMAP)
586                 e->colormap = MSG_ReadByte();
587         if (bits & E_SKIN)
588                 e->skin = MSG_ReadByte();
589         if (bits & E_ALPHA)
590                 e->alpha = MSG_ReadByte();
591         if (bits & E_SCALE)
592                 e->scale = MSG_ReadByte();
593         if (bits & E_GLOWSIZE)
594                 e->glowsize = MSG_ReadByte();
595         if (bits & E_GLOWCOLOR)
596                 e->glowcolor = MSG_ReadByte();
597         if (cl.protocol == PROTOCOL_DARKPLACES2)
598                 if (bits & E_FLAGS)
599                         e->flags = MSG_ReadByte();
600         if (bits & E_TAGATTACHMENT)
601         {
602                 e->tagentity = (unsigned short) MSG_ReadShort();
603                 e->tagindex = MSG_ReadByte();
604         }
605         if (bits & E_LIGHT)
606         {
607                 e->light[0] = (unsigned short) MSG_ReadShort();
608                 e->light[1] = (unsigned short) MSG_ReadShort();
609                 e->light[2] = (unsigned short) MSG_ReadShort();
610                 e->light[3] = (unsigned short) MSG_ReadShort();
611         }
612         if (bits & E_LIGHTSTYLE)
613                 e->lightstyle = MSG_ReadByte();
614         if (bits & E_LIGHTPFLAGS)
615                 e->lightpflags = MSG_ReadByte();
616
617         if (developer_networkentities.integer >= 2)
618         {
619                 Con_Printf("ReadFields e%i", e->number);
620
621                 if (bits & E_ORIGIN1)
622                         Con_Printf(" E_ORIGIN1 %f", e->origin[0]);
623                 if (bits & E_ORIGIN2)
624                         Con_Printf(" E_ORIGIN2 %f", e->origin[1]);
625                 if (bits & E_ORIGIN3)
626                         Con_Printf(" E_ORIGIN3 %f", e->origin[2]);
627                 if (bits & E_ANGLE1)
628                         Con_Printf(" E_ANGLE1 %f", e->angles[0]);
629                 if (bits & E_ANGLE2)
630                         Con_Printf(" E_ANGLE2 %f", e->angles[1]);
631                 if (bits & E_ANGLE3)
632                         Con_Printf(" E_ANGLE3 %f", e->angles[2]);
633                 if (bits & (E_MODEL1 | E_MODEL2))
634                         Con_Printf(" E_MODEL %i", e->modelindex);
635
636                 if (bits & (E_FRAME1 | E_FRAME2))
637                         Con_Printf(" E_FRAME %i", e->frame);
638                 if (bits & (E_EFFECTS1 | E_EFFECTS2))
639                         Con_Printf(" E_EFFECTS %i", e->effects);
640                 if (bits & E_ALPHA)
641                         Con_Printf(" E_ALPHA %f", e->alpha / 255.0f);
642                 if (bits & E_SCALE)
643                         Con_Printf(" E_SCALE %f", e->scale / 16.0f);
644                 if (bits & E_COLORMAP)
645                         Con_Printf(" E_COLORMAP %i", e->colormap);
646                 if (bits & E_SKIN)
647                         Con_Printf(" E_SKIN %i", e->skin);
648
649                 if (bits & E_GLOWSIZE)
650                         Con_Printf(" E_GLOWSIZE %i", e->glowsize * 4);
651                 if (bits & E_GLOWCOLOR)
652                         Con_Printf(" E_GLOWCOLOR %i", e->glowcolor);
653                 
654                 if (bits & E_LIGHT)
655                         Con_Printf(" E_LIGHT %i:%i:%i:%i", e->light[0], e->light[1], e->light[2], e->light[3]);
656                 if (bits & E_LIGHTPFLAGS)                       
657                         Con_Printf(" E_LIGHTPFLAGS %i", e->lightpflags);
658
659                 if (bits & E_TAGATTACHMENT)
660                         Con_Printf(" E_TAGATTACHMENT e%i:%i", e->tagentity, e->tagindex);
661                 if (bits & E_LIGHTSTYLE)
662                         Con_Printf(" E_LIGHTSTYLE %i", e->lightstyle);
663                 Con_Print("\n");
664         }
665 }
666
667 // (client and server) allocates a new empty database
668 entityframe_database_t *EntityFrame_AllocDatabase(mempool_t *mempool)
669 {
670         return Mem_Alloc(mempool, sizeof(entityframe_database_t));
671 }
672
673 // (client and server) frees the database
674 void EntityFrame_FreeDatabase(entityframe_database_t *d)
675 {
676         Mem_Free(d);
677 }
678
679 // (server) clears the database to contain no frames (thus delta compression compresses against nothing)
680 void EntityFrame_ClearDatabase(entityframe_database_t *d)
681 {
682         memset(d, 0, sizeof(*d));
683 }
684
685 // (server and client) removes frames older than 'frame' from database
686 void EntityFrame_AckFrame(entityframe_database_t *d, int frame)
687 {
688         int i;
689         if (d->ackframenum < frame)
690                 d->ackframenum = frame;
691         for (i = 0;i < d->numframes && d->frames[i].framenum < frame;i++);
692         // ignore outdated frame acks (out of order packets)
693         if (i == 0)
694                 return;
695         d->numframes -= i;
696         // if some queue is left, slide it down to beginning of array
697         if (d->numframes)
698                 memmove(&d->frames[0], &d->frames[i], sizeof(d->frames[0]) * d->numframes);
699 }
700
701 // (server) clears frame, to prepare for adding entities
702 void EntityFrame_Clear(entity_frame_t *f, vec3_t eye, int framenum)
703 {
704         f->time = 0;
705         f->framenum = framenum;
706         f->numentities = 0;
707         if (eye == NULL)
708                 VectorClear(f->eye);
709         else
710                 VectorCopy(eye, f->eye);
711 }
712
713 // (server and client) reads a frame from the database
714 void EntityFrame_FetchFrame(entityframe_database_t *d, int framenum, entity_frame_t *f)
715 {
716         int i, n;
717         EntityFrame_Clear(f, NULL, -1);
718         for (i = 0;i < d->numframes && d->frames[i].framenum < framenum;i++);
719         if (i < d->numframes && framenum == d->frames[i].framenum)
720         {
721                 f->framenum = framenum;
722                 f->numentities = d->frames[i].endentity - d->frames[i].firstentity;
723                 n = MAX_ENTITY_DATABASE - (d->frames[i].firstentity % MAX_ENTITY_DATABASE);
724                 if (n > f->numentities)
725                         n = f->numentities;
726                 memcpy(f->entitydata, d->entitydata + d->frames[i].firstentity % MAX_ENTITY_DATABASE, sizeof(*f->entitydata) * n);
727                 if (f->numentities > n)
728                         memcpy(f->entitydata + n, d->entitydata, sizeof(*f->entitydata) * (f->numentities - n));
729                 VectorCopy(d->eye, f->eye);
730         }
731 }
732
733 // (server and client) adds a entity_frame to the database, for future reference
734 void EntityFrame_AddFrame(entityframe_database_t *d, vec3_t eye, int framenum, int numentities, const entity_state_t *entitydata)
735 {
736         int n, e;
737         entity_frameinfo_t *info;
738
739         VectorCopy(eye, d->eye);
740
741         // figure out how many entity slots are used already
742         if (d->numframes)
743         {
744                 n = d->frames[d->numframes - 1].endentity - d->frames[0].firstentity;
745                 if (n + numentities > MAX_ENTITY_DATABASE || d->numframes >= MAX_ENTITY_HISTORY)
746                 {
747                         // ran out of room, dump database
748                         EntityFrame_ClearDatabase(d);
749                 }
750         }
751
752         info = &d->frames[d->numframes];
753         info->framenum = framenum;
754         e = -1000;
755         // make sure we check the newly added frame as well, but we haven't incremented numframes yet
756         for (n = 0;n <= d->numframes;n++)
757         {
758                 if (e >= d->frames[n].framenum)
759                 {
760                         if (e == framenum)
761                                 Con_Print("EntityFrame_AddFrame: tried to add out of sequence frame to database\n");
762                         else
763                                 Con_Print("EntityFrame_AddFrame: out of sequence frames in database\n");
764                         return;
765                 }
766                 e = d->frames[n].framenum;
767         }
768         // if database still has frames after that...
769         if (d->numframes)
770                 info->firstentity = d->frames[d->numframes - 1].endentity;
771         else
772                 info->firstentity = 0;
773         info->endentity = info->firstentity + numentities;
774         d->numframes++;
775
776         n = info->firstentity % MAX_ENTITY_DATABASE;
777         e = MAX_ENTITY_DATABASE - n;
778         if (e > numentities)
779                 e = numentities;
780         memcpy(d->entitydata + n, entitydata, sizeof(entity_state_t) * e);
781         if (numentities > e)
782                 memcpy(d->entitydata, entitydata + e, sizeof(entity_state_t) * (numentities - e));
783 }
784
785 // (server) writes a frame to network stream
786 static entity_frame_t deltaframe; // FIXME?
787 void EntityFrame_WriteFrame(sizebuf_t *msg, entityframe_database_t *d, int numstates, const entity_state_t *states, int viewentnum)
788 {
789         int i, onum, number;
790         entity_frame_t *o = &deltaframe;
791         const entity_state_t *ent, *delta;
792         vec3_t eye;
793
794         d->latestframenum++;
795
796         VectorClear(eye);
797         for (i = 0;i < numstates;i++)
798         {
799                 if (states[i].number == viewentnum)
800                 {
801                         VectorSet(eye, states[i].origin[0], states[i].origin[1], states[i].origin[2] + 22);
802                         break;
803                 }
804         }
805
806         EntityFrame_AddFrame(d, eye, d->latestframenum, numstates, states);
807
808         EntityFrame_FetchFrame(d, d->ackframenum > 0 ? d->ackframenum : -1, o);
809
810         MSG_WriteByte (msg, svc_entities);
811         MSG_WriteLong (msg, o->framenum);
812         MSG_WriteLong (msg, d->latestframenum);
813         MSG_WriteFloat (msg, eye[0]);
814         MSG_WriteFloat (msg, eye[1]);
815         MSG_WriteFloat (msg, eye[2]);
816
817         onum = 0;
818         for (i = 0;i < numstates;i++)
819         {
820                 ent = states + i;
821                 number = ent->number;
822                 for (;onum < o->numentities && o->entitydata[onum].number < number;onum++)
823                 {
824                         // write remove message
825                         MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
826                 }
827                 if (onum < o->numentities && (o->entitydata[onum].number == number))
828                 {
829                         // delta from previous frame
830                         delta = o->entitydata + onum;
831                         // advance to next entity in delta frame
832                         onum++;
833                 }
834                 else
835                 {
836                         // delta from defaults
837                         delta = &defaultstate;
838                 }
839                 EntityState_WriteUpdate(ent, msg, delta);
840         }
841         for (;onum < o->numentities;onum++)
842         {
843                 // write remove message
844                 MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
845         }
846         MSG_WriteShort(msg, 0xFFFF);
847 }
848
849 // (client) reads a frame from network stream
850 static entity_frame_t framedata; // FIXME?
851 void EntityFrame_CL_ReadFrame(void)
852 {
853         int i, number, removed;
854         entity_frame_t *f = &framedata, *delta = &deltaframe;
855         entity_state_t *e, *old, *oldend;
856         entity_t *ent;
857         entityframe_database_t *d;
858         if (!cl.entitydatabase)
859                 cl.entitydatabase = EntityFrame_AllocDatabase(cl_entities_mempool);
860         d = cl.entitydatabase;
861
862         EntityFrame_Clear(f, NULL, -1);
863
864         // read the frame header info
865         f->time = cl.mtime[0];
866         number = MSG_ReadLong();
867         cl.latestframenum = f->framenum = MSG_ReadLong();
868         f->eye[0] = MSG_ReadFloat();
869         f->eye[1] = MSG_ReadFloat();
870         f->eye[2] = MSG_ReadFloat();
871         EntityFrame_AckFrame(d, number);
872         EntityFrame_FetchFrame(d, number, delta);
873         old = delta->entitydata;
874         oldend = old + delta->numentities;
875         // read entities until we hit the magic 0xFFFF end tag
876         while ((number = (unsigned short) MSG_ReadShort()) != 0xFFFF && !msg_badread)
877         {
878                 if (msg_badread)
879                         Host_Error("EntityFrame_Read: read error\n");
880                 removed = number & 0x8000;
881                 number &= 0x7FFF;
882                 if (number >= MAX_EDICTS)
883                         Host_Error("EntityFrame_Read: number (%i) >= MAX_EDICTS (%i)\n", number, MAX_EDICTS);
884
885                 // seek to entity, while copying any skipped entities (assume unchanged)
886                 while (old < oldend && old->number < number)
887                 {
888                         if (f->numentities >= MAX_ENTITY_DATABASE)
889                                 Host_Error("EntityFrame_Read: entity list too big\n");
890                         f->entitydata[f->numentities] = *old++;
891                         f->entitydata[f->numentities++].time = cl.mtime[0];
892                 }
893                 if (removed)
894                 {
895                         if (old < oldend && old->number == number)
896                                 old++;
897                         else
898                                 Con_Printf("EntityFrame_Read: REMOVE on unused entity %i\n", number);
899                 }
900                 else
901                 {
902                         if (f->numentities >= MAX_ENTITY_DATABASE)
903                                 Host_Error("EntityFrame_Read: entity list too big\n");
904
905                         // reserve this slot
906                         e = f->entitydata + f->numentities++;
907
908                         if (old < oldend && old->number == number)
909                         {
910                                 // delta from old entity
911                                 *e = *old++;
912                         }
913                         else
914                         {
915                                 // delta from defaults
916                                 *e = defaultstate;
917                         }
918
919                         cl_entities_active[number] = true;
920                         e->active = true;
921                         e->time = cl.mtime[0];
922                         e->number = number;
923                         EntityState_ReadFields(e, EntityState_ReadExtendBits());
924                 }
925         }
926         while (old < oldend)
927         {
928                 if (f->numentities >= MAX_ENTITY_DATABASE)
929                         Host_Error("EntityFrame_Read: entity list too big\n");
930                 f->entitydata[f->numentities] = *old++;
931                 f->entitydata[f->numentities++].time = cl.mtime[0];
932         }
933         EntityFrame_AddFrame(d, f->eye, f->framenum, f->numentities, f->entitydata);
934
935         memset(cl_entities_active, 0, cl_max_entities * sizeof(qbyte));
936         number = 1;
937         for (i = 0;i < f->numentities;i++)
938         {
939                 for (;number < f->entitydata[i].number;number++)
940                 {
941                         if (cl_entities_active[number])
942                         {
943                                 cl_entities_active[number] = false;
944                                 cl_entities[number].state_current.active = false;
945                         }
946                 }
947                 // update the entity
948                 ent = &cl_entities[number];
949                 ent->state_previous = ent->state_current;
950                 ent->state_current = f->entitydata[i];
951                 CL_MoveLerpEntityStates(ent);
952                 // the entity lives again...
953                 cl_entities_active[number] = true;
954                 number++;
955         }
956         for (;number < cl_max_entities;number++)
957         {
958                 if (cl_entities_active[number])
959                 {
960                         cl_entities_active[number] = false;
961                         cl_entities[number].state_current.active = false;
962                 }
963         }
964 }
965
966
967 // (client) returns the frame number of the most recent frame recieved
968 int EntityFrame_MostRecentlyRecievedFrameNum(entityframe_database_t *d)
969 {
970         if (d->numframes)
971                 return d->frames[d->numframes - 1].framenum;
972         else
973                 return -1;
974 }
975
976
977
978
979
980
981 entity_state_t *EntityFrame4_GetReferenceEntity(entityframe4_database_t *d, int number)
982 {
983         if (d->maxreferenceentities <= number)
984         {
985                 int oldmax = d->maxreferenceentities;
986                 entity_state_t *oldentity = d->referenceentity;
987                 d->maxreferenceentities = (number + 15) & ~7;
988                 d->referenceentity = Mem_Alloc(d->mempool, d->maxreferenceentities * sizeof(*d->referenceentity));
989                 if (oldentity)
990                 {
991                         memcpy(d->referenceentity, oldentity, oldmax * sizeof(*d->referenceentity));
992                         Mem_Free(oldentity);
993                 }
994                 // clear the newly created entities
995                 for (;oldmax < d->maxreferenceentities;oldmax++)
996                 {
997                         d->referenceentity[oldmax] = defaultstate;
998                         d->referenceentity[oldmax].number = oldmax;
999                 }
1000         }
1001         return d->referenceentity + number;
1002 }
1003
1004 void EntityFrame4_AddCommitEntity(entityframe4_database_t *d, const entity_state_t *s)
1005 {
1006         // resize commit's entity list if full
1007         if (d->currentcommit->maxentities <= d->currentcommit->numentities)
1008         {
1009                 entity_state_t *oldentity = d->currentcommit->entity;
1010                 d->currentcommit->maxentities += 8;
1011                 d->currentcommit->entity = Mem_Alloc(d->mempool, d->currentcommit->maxentities * sizeof(*d->currentcommit->entity));
1012                 if (oldentity)
1013                 {
1014                         memcpy(d->currentcommit->entity, oldentity, d->currentcommit->numentities * sizeof(*d->currentcommit->entity));
1015                         Mem_Free(oldentity);
1016                 }
1017         }
1018         d->currentcommit->entity[d->currentcommit->numentities++] = *s;
1019 }
1020
1021 entityframe4_database_t *EntityFrame4_AllocDatabase(mempool_t *pool)
1022 {
1023         entityframe4_database_t *d;
1024         d = Mem_Alloc(pool, sizeof(*d));
1025         d->mempool = pool;
1026         EntityFrame4_ResetDatabase(d);
1027         d->ackframenum = -1;
1028         return d;
1029 }
1030
1031 void EntityFrame4_FreeDatabase(entityframe4_database_t *d)
1032 {
1033         int i;
1034         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1035                 if (d->commit[i].entity)
1036                         Mem_Free(d->commit[i].entity);
1037         if (d->referenceentity)
1038                 Mem_Free(d->referenceentity);
1039         Mem_Free(d);
1040 }
1041
1042 void EntityFrame4_ResetDatabase(entityframe4_database_t *d)
1043 {
1044         int i;
1045         d->ackframenum = -1;
1046         d->referenceframenum = -1;
1047         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1048                 d->commit[i].numentities = 0;
1049         for (i = 0;i < d->maxreferenceentities;i++)
1050                 d->referenceentity[i] = defaultstate;
1051 }
1052
1053 int EntityFrame4_AckFrame(entityframe4_database_t *d, int framenum, int servermode)
1054 {
1055         int i, j, found;
1056         entity_database4_commit_t *commit;
1057         if (framenum == -1)
1058         {
1059                 // reset reference, but leave commits alone
1060                 d->referenceframenum = -1;
1061                 for (i = 0;i < d->maxreferenceentities;i++)
1062                         d->referenceentity[i] = defaultstate;
1063                 // if this is the server, remove commits
1064                         for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1065                                 commit->numentities = 0;
1066                 found = true;
1067         }
1068         else if (d->referenceframenum == framenum)
1069                 found = true;
1070         else
1071         {
1072                 found = false;
1073                 for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1074                 {
1075                         if (commit->numentities && commit->framenum <= framenum)
1076                         {
1077                                 if (commit->framenum == framenum)
1078                                 {
1079                                         found = true;
1080                                         d->referenceframenum = framenum;
1081                                         if (developer_networkentities.integer >= 3)
1082                                         {
1083                                                 for (j = 0;j < commit->numentities;j++)
1084                                                 {
1085                                                         entity_state_t *s = EntityFrame4_GetReferenceEntity(d, commit->entity[j].number);
1086                                                         if (commit->entity[j].active != s->active)
1087                                                         {
1088                                                                 if (commit->entity[j].active)
1089                                                                         Con_Printf("commit entity %i has become active (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1090                                                                 else
1091                                                                         Con_Printf("commit entity %i has become inactive (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1092                                                         }
1093                                                         *s = commit->entity[j];
1094                                                 }
1095                                         }
1096                                         else
1097                                                 for (j = 0;j < commit->numentities;j++)
1098                                                         *EntityFrame4_GetReferenceEntity(d, commit->entity[j].number) = commit->entity[j];
1099                                 }
1100                                 commit->numentities = 0;
1101                         }
1102                 }
1103         }
1104         if (developer_networkentities.integer >= 1)
1105         {
1106                 Con_Printf("ack ref:%i database updated to: ref:%i commits:", framenum, d->referenceframenum);
1107                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1108                         if (d->commit[i].numentities)
1109                                 Con_Printf(" %i", d->commit[i].framenum);
1110                 Con_Print("\n");
1111         }
1112         return found;
1113 }
1114
1115 void EntityFrame4_CL_ReadFrame(void)
1116 {
1117         int i, n, cnumber, referenceframenum, framenum, enumber, done, stopnumber, skip = false;
1118         entity_state_t *s;
1119         entityframe4_database_t *d;
1120         if (!cl.entitydatabase4)
1121                 cl.entitydatabase4 = EntityFrame4_AllocDatabase(cl_entities_mempool);
1122         d = cl.entitydatabase4;
1123         // read the number of the frame this refers to
1124         referenceframenum = MSG_ReadLong();
1125         // read the number of this frame
1126         cl.latestframenum = framenum = MSG_ReadLong();
1127         // read the start number
1128         enumber = (unsigned short) MSG_ReadShort();
1129         if (developer_networkentities.integer >= 1)
1130         {
1131                 Con_Printf("recv svc_entities num:%i ref:%i database: ref:%i commits:", framenum, referenceframenum, d->referenceframenum);
1132                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1133                         if (d->commit[i].numentities)
1134                                 Con_Printf(" %i", d->commit[i].framenum);
1135                 Con_Print("\n");
1136         }
1137         if (!EntityFrame4_AckFrame(d, referenceframenum, false))
1138         {
1139                 Con_Print("EntityFrame4_CL_ReadFrame: reference frame invalid (VERY BAD ERROR), this update will be skipped\n");
1140                 skip = true;
1141         }
1142         d->currentcommit = NULL;
1143         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1144         {
1145                 if (!d->commit[i].numentities)
1146                 {
1147                         d->currentcommit = d->commit + i;
1148                         d->currentcommit->framenum = d->ackframenum = framenum;
1149                         d->currentcommit->numentities = 0;
1150                 }
1151         }
1152         if (d->currentcommit == NULL)
1153         {
1154                 Con_Printf("EntityFrame4_CL_ReadFrame: error while decoding frame %i: database full, reading but not storing this update\n", framenum);
1155                 skip = true;
1156         }
1157         done = false;
1158         while (!done && !msg_badread)
1159         {
1160                 // read the number of the modified entity
1161                 // (gaps will be copied unmodified)
1162                 n = (unsigned short)MSG_ReadShort();
1163                 if (n == 0x8000)
1164                 {
1165                         // no more entities in this update, but we still need to copy the
1166                         // rest of the reference entities (final gap)
1167                         done = true;
1168                         // read end of range number, then process normally
1169                         n = (unsigned short)MSG_ReadShort();
1170                 }
1171                 // high bit means it's a remove message
1172                 cnumber = n & 0x7FFF;
1173                 // add one (the changed one) if not done
1174                 stopnumber = cnumber + !done;
1175                 // process entities in range from the last one to the changed one
1176                 for (;enumber < stopnumber;enumber++)
1177                 {
1178                         if (skip)
1179                         {
1180                                 if (enumber == cnumber && (n & 0x8000) == 0)
1181                                 {
1182                                         entity_state_t tempstate;
1183                                         EntityState_ReadFields(&tempstate, EntityState_ReadExtendBits());
1184                                 }
1185                                 continue;
1186                         }
1187                         // slide the current into the previous slot
1188                         cl_entities[enumber].state_previous = cl_entities[enumber].state_current;
1189                         // copy a new current from reference database
1190                         cl_entities[enumber].state_current = *EntityFrame4_GetReferenceEntity(d, enumber);
1191                         s = &cl_entities[enumber].state_current;
1192                         // if this is the one to modify, read more data...
1193                         if (enumber == cnumber)
1194                         {
1195                                 if (n & 0x8000)
1196                                 {
1197                                         // simply removed
1198                                         if (developer_networkentities.integer >= 2)
1199                                                 Con_Printf("entity %i: remove\n", enumber);
1200                                         *s = defaultstate;
1201                                 }
1202                                 else
1203                                 {
1204                                         // read the changes
1205                                         if (developer_networkentities.integer >= 2)
1206                                                 Con_Printf("entity %i: update\n", enumber);
1207                                         s->active = true;
1208                                         EntityState_ReadFields(s, EntityState_ReadExtendBits());
1209                                 }
1210                         }
1211                         else if (developer_networkentities.integer >= 4)
1212                                 Con_Printf("entity %i: copy\n", enumber);
1213                         // set the cl_entities_active flag
1214                         cl_entities_active[enumber] = s->active;
1215                         // set the update time
1216                         s->time = cl.mtime[0];
1217                         // fix the number (it gets wiped occasionally by copying from defaultstate)
1218                         s->number = enumber;
1219                         // check if we need to update the lerp stuff
1220                         if (s->active)
1221                                 CL_MoveLerpEntityStates(&cl_entities[enumber]);
1222                         // add this to the commit entry whether it is modified or not
1223                         if (d->currentcommit)
1224                                 EntityFrame4_AddCommitEntity(d, &cl_entities[enumber].state_current);
1225                         // print extra messages if desired
1226                         if (developer_networkentities.integer >= 2 && cl_entities[enumber].state_current.active != cl_entities[enumber].state_previous.active)
1227                         {
1228                                 if (cl_entities[enumber].state_current.active)
1229                                         Con_Printf("entity #%i has become active\n", enumber);
1230                                 else if (cl_entities[enumber].state_previous.active)
1231                                         Con_Printf("entity #%i has become inactive\n", enumber);
1232                         }
1233                 }
1234         }
1235         d->currentcommit = NULL;
1236         if (skip)
1237                 EntityFrame4_ResetDatabase(d);
1238 }
1239
1240 void EntityFrame4_WriteFrame(sizebuf_t *msg, entityframe4_database_t *d, int numstates, const entity_state_t *states)
1241 {
1242         const entity_state_t *e, *s;
1243         entity_state_t inactiveentitystate;
1244         int i, n, startnumber;
1245         sizebuf_t buf;
1246         qbyte data[128];
1247
1248         // if there isn't enough space to accomplish anything, skip it
1249         if (msg->cursize + 24 > msg->maxsize)
1250                 return;
1251
1252         // prepare the buffer
1253         memset(&buf, 0, sizeof(buf));
1254         buf.data = data;
1255         buf.maxsize = sizeof(data);
1256
1257         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1258                 if (!d->commit[i].numentities)
1259                         break;
1260         // if commit buffer full, just don't bother writing an update this frame
1261         if (i == MAX_ENTITY_HISTORY)
1262                 return;
1263         d->currentcommit = d->commit + i;
1264
1265         // this state's number gets played around with later
1266         inactiveentitystate = defaultstate;
1267
1268         d->currentcommit->numentities = 0;
1269         d->currentcommit->framenum = ++d->latestframenumber;
1270         MSG_WriteByte(msg, svc_entities);
1271         MSG_WriteLong(msg, d->referenceframenum);
1272         MSG_WriteLong(msg, d->currentcommit->framenum);
1273         if (developer_networkentities.integer >= 1)
1274         {
1275                 Con_Printf("send svc_entities num:%i ref:%i (database: ref:%i commits:", d->currentcommit->framenum, d->referenceframenum, d->referenceframenum);
1276                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1277                         if (d->commit[i].numentities)
1278                                 Con_Printf(" %i", d->commit[i].framenum);
1279                 Con_Print(")\n");
1280         }
1281         if (d->currententitynumber >= sv.max_edicts)
1282                 startnumber = 1;
1283         else
1284                 startnumber = bound(1, d->currententitynumber, sv.max_edicts - 1);
1285         MSG_WriteShort(msg, startnumber);
1286         // reset currententitynumber so if the loop does not break it we will
1287         // start at beginning next frame (if it does break, it will set it)
1288         d->currententitynumber = 1;
1289         for (i = 0, n = startnumber;n < sv.max_edicts;n++)
1290         {
1291                 // find the old state to delta from
1292                 e = EntityFrame4_GetReferenceEntity(d, n);
1293                 // prepare the buffer
1294                 SZ_Clear(&buf);
1295                 // entity exists, build an update (if empty there is no change)
1296                 // find the state in the list
1297                 for (;i < numstates && states[i].number < n;i++);
1298                 // make the message
1299                 s = states + i;
1300                 if (s->number == n)
1301                 {
1302                         // build the update
1303                         EntityState_WriteUpdate(s, &buf, e);
1304                 }
1305                 else
1306                 {
1307                         inactiveentitystate.number = n;
1308                         s = &inactiveentitystate;
1309                         if (e->active)
1310                         {
1311                                 // entity used to exist but doesn't anymore, send remove
1312                                 MSG_WriteShort(&buf, n | 0x8000);
1313                         }
1314                 }
1315                 // if the commit is full, we're done this frame
1316                 if (msg->cursize + buf.cursize > msg->maxsize - 4)
1317                 {
1318                         // next frame we will continue where we left off
1319                         break;
1320                 }
1321                 // add the entity to the commit
1322                 EntityFrame4_AddCommitEntity(d, s);
1323                 // if the message is empty, skip out now
1324                 if (buf.cursize)
1325                 {
1326                         // write the message to the packet
1327                         SZ_Write(msg, buf.data, buf.cursize);
1328                 }
1329         }
1330         d->currententitynumber = n;
1331
1332         // remove world message (invalid, and thus a good terminator)
1333         MSG_WriteShort(msg, 0x8000);
1334         // write the number of the end entity
1335         MSG_WriteShort(msg, d->currententitynumber);
1336         // just to be sure
1337         d->currentcommit = NULL;
1338 }
1339
1340
1341
1342
1343 #define E5_PROTOCOL_PRIORITYLEVELS 32
1344
1345 entityframe5_database_t *EntityFrame5_AllocDatabase(mempool_t *pool)
1346 {
1347         entityframe5_database_t *d;
1348         d = Mem_Alloc(pool, sizeof(*d));
1349         EntityFrame5_ResetDatabase(d);
1350         return d;
1351 }
1352
1353 void EntityFrame5_FreeDatabase(entityframe5_database_t *d)
1354 {
1355         Mem_Free(d);
1356 }
1357
1358 void EntityFrame5_ResetDatabase(entityframe5_database_t *d)
1359 {
1360         int i;
1361         memset(d, 0, sizeof(*d));
1362         d->latestframenum = 0;
1363         d->ackframenum = -1;
1364         for (i = 0;i < MAX_EDICTS;i++)
1365                 d->states[i] = defaultstate;
1366 }
1367
1368
1369 int EntityState5_Priority(entityframe5_database_t *d, entity_state_t *view, entity_state_t *s, int changedbits, int age)
1370 {
1371         int lowprecision, limit, priority;
1372         double distance;
1373         if (!changedbits)
1374                 return 0;
1375         if (!s->active/* && changedbits & E5_FULLUPDATE*/)
1376                 return E5_PROTOCOL_PRIORITYLEVELS - 1;
1377         // check whole attachment chain to judge relevance to player
1378         lowprecision = false;
1379         for (limit = 0;limit < 256;limit++)
1380         {
1381                 if (s == view)
1382                         return E5_PROTOCOL_PRIORITYLEVELS - 1;
1383                 if (s->flags & RENDER_VIEWMODEL)
1384                         return E5_PROTOCOL_PRIORITYLEVELS - 1;
1385                 if (s->flags & RENDER_LOWPRECISION)
1386                         lowprecision = true;
1387                 if (!s->tagentity)
1388                 {
1389                         if (VectorCompare(s->origin, view->origin))
1390                                 return E5_PROTOCOL_PRIORITYLEVELS - 1;
1391                         break;
1392                 }
1393                 s = d->states + s->tagentity;
1394         }
1395         if (limit >= 256)
1396                 Con_Printf("Protocol: Runaway loop recursing tagentity links on entity %i\n", s->number);
1397         // it's not a viewmodel for this client
1398         distance = VectorDistance(view->origin, s->origin);
1399         priority = (E5_PROTOCOL_PRIORITYLEVELS / 2) + age - (int)(distance * (E5_PROTOCOL_PRIORITYLEVELS / 16384.0f));
1400         if (lowprecision)
1401                 priority -= (E5_PROTOCOL_PRIORITYLEVELS / 4);
1402         //if (changedbits & E5_FULLUPDATE)
1403         //      priority += 4;
1404         //if (changedbits & (E5_ATTACHMENT | E5_MODEL | E5_FLAGS | E5_COLORMAP))
1405         //      priority += 4;
1406         return (int) bound(1, priority, E5_PROTOCOL_PRIORITYLEVELS - 1);
1407 }
1408
1409 void EntityState5_WriteUpdate(int number, const entity_state_t *s, int changedbits, sizebuf_t *msg)
1410 {
1411         unsigned int bits = 0;
1412         if (!s->active)
1413                 MSG_WriteShort(msg, number | 0x8000);
1414         else
1415         {
1416                 bits = changedbits;
1417                 if ((bits & E5_ORIGIN) && (s->origin[0] < -4096 || s->origin[0] >= 4096 || s->origin[1] < -4096 || s->origin[1] >= 4096 || s->origin[2] < -4096 || s->origin[2] >= 4096))
1418                         bits |= E5_ORIGIN32;
1419                 if ((bits & E5_ANGLES) && !(s->flags & RENDER_LOWPRECISION))
1420                         bits |= E5_ANGLES16;
1421                 if ((bits & E5_MODEL) && s->modelindex >= 256)
1422                         bits |= E5_MODEL16;
1423                 if ((bits & E5_FRAME) && s->frame >= 256)
1424                         bits |= E5_FRAME16;
1425                 if (bits & E5_EFFECTS)
1426                 {
1427                         if (s->effects >= 65536)
1428                                 bits |= E5_EFFECTS32;
1429                         else if (s->effects >= 256)
1430                                 bits |= E5_EFFECTS16;
1431                 }
1432                 if (bits >= 256)
1433                         bits |= E5_EXTEND1;
1434                 if (bits >= 65536)
1435                         bits |= E5_EXTEND2;
1436                 if (bits >= 16777216)
1437                         bits |= E5_EXTEND3;
1438                 MSG_WriteShort(msg, number);
1439                 MSG_WriteByte(msg, bits & 0xFF);
1440                 if (bits & E5_EXTEND1)
1441                         MSG_WriteByte(msg, (bits >> 8) & 0xFF);
1442                 if (bits & E5_EXTEND2)
1443                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
1444                 if (bits & E5_EXTEND3)
1445                         MSG_WriteByte(msg, (bits >> 24) & 0xFF);
1446                 if (bits & E5_FLAGS)
1447                         MSG_WriteByte(msg, s->flags);
1448                 if (bits & E5_ORIGIN)
1449                 {
1450                         if (bits & E5_ORIGIN32)
1451                         {
1452                                 MSG_WriteCoord32f(msg, s->origin[0]);
1453                                 MSG_WriteCoord32f(msg, s->origin[1]);
1454                                 MSG_WriteCoord32f(msg, s->origin[2]);
1455                         }
1456                         else
1457                         {
1458                                 MSG_WriteCoord13i(msg, s->origin[0]);
1459                                 MSG_WriteCoord13i(msg, s->origin[1]);
1460                                 MSG_WriteCoord13i(msg, s->origin[2]);
1461                         }
1462                 }
1463                 if (bits & E5_ANGLES)
1464                 {
1465                         if (bits & E5_ANGLES16)
1466                         {
1467                                 MSG_WriteAngle16i(msg, s->angles[0]);
1468                                 MSG_WriteAngle16i(msg, s->angles[1]);
1469                                 MSG_WriteAngle16i(msg, s->angles[2]);
1470                         }
1471                         else
1472                         {
1473                                 MSG_WriteAngle8i(msg, s->angles[0]);
1474                                 MSG_WriteAngle8i(msg, s->angles[1]);
1475                                 MSG_WriteAngle8i(msg, s->angles[2]);
1476                         }
1477                 }
1478                 if (bits & E5_MODEL)
1479                 {
1480                         if (bits & E5_MODEL16)
1481                                 MSG_WriteShort(msg, s->modelindex);
1482                         else
1483                                 MSG_WriteByte(msg, s->modelindex);
1484                 }
1485                 if (bits & E5_FRAME)
1486                 {
1487                         if (bits & E5_FRAME16)
1488                                 MSG_WriteShort(msg, s->frame);
1489                         else
1490                                 MSG_WriteByte(msg, s->frame);
1491                 }
1492                 if (bits & E5_SKIN)
1493                         MSG_WriteByte(msg, s->skin);
1494                 if (bits & E5_EFFECTS)
1495                 {
1496                         if (bits & E5_EFFECTS32)
1497                                 MSG_WriteLong(msg, s->effects);
1498                         else if (bits & E5_EFFECTS16)
1499                                 MSG_WriteShort(msg, s->effects);
1500                         else
1501                                 MSG_WriteByte(msg, s->effects);
1502                 }
1503                 if (bits & E5_ALPHA)
1504                         MSG_WriteByte(msg, s->alpha);
1505                 if (bits & E5_SCALE)
1506                         MSG_WriteByte(msg, s->scale);
1507                 if (bits & E5_COLORMAP)
1508                         MSG_WriteByte(msg, s->colormap);
1509                 if (bits & E5_ATTACHMENT)
1510                 {
1511                         MSG_WriteShort(msg, s->tagentity);
1512                         MSG_WriteByte(msg, s->tagindex);
1513                 }
1514                 if (bits & E5_LIGHT)
1515                 {
1516                         MSG_WriteShort(msg, s->light[0]);
1517                         MSG_WriteShort(msg, s->light[1]);
1518                         MSG_WriteShort(msg, s->light[2]);
1519                         MSG_WriteShort(msg, s->light[3]);
1520                         MSG_WriteByte(msg, s->lightstyle);
1521                         MSG_WriteByte(msg, s->lightpflags);
1522                 }
1523                 if (bits & E5_GLOW)
1524                 {
1525                         MSG_WriteByte(msg, s->glowsize);
1526                         MSG_WriteByte(msg, s->glowcolor);
1527                 }
1528         }
1529 }
1530
1531 void EntityState5_ReadUpdate(entity_state_t *s)
1532 {
1533         int bits;
1534         bits = MSG_ReadByte();
1535         if (bits & E5_EXTEND1)
1536         {
1537                 bits |= MSG_ReadByte() << 8;
1538                 if (bits & E5_EXTEND2)
1539                 {
1540                         bits |= MSG_ReadByte() << 16;
1541                         if (bits & E5_EXTEND3)
1542                                 bits |= MSG_ReadByte() << 24;
1543                 }
1544         }
1545         if (bits & E5_FULLUPDATE)
1546         {
1547                 *s = defaultstate;
1548                 s->active = true;
1549         }
1550         if (bits & E5_FLAGS)
1551                 s->flags = MSG_ReadByte();
1552         if (bits & E5_ORIGIN)
1553         {
1554                 if (bits & E5_ORIGIN32)
1555                 {
1556                         s->origin[0] = MSG_ReadCoord32f();
1557                         s->origin[1] = MSG_ReadCoord32f();
1558                         s->origin[2] = MSG_ReadCoord32f();
1559                 }
1560                 else
1561                 {
1562                         s->origin[0] = MSG_ReadCoord13i();
1563                         s->origin[1] = MSG_ReadCoord13i();
1564                         s->origin[2] = MSG_ReadCoord13i();
1565                 }
1566         }
1567         if (bits & E5_ANGLES)
1568         {
1569                 if (bits & E5_ANGLES16)
1570                 {
1571                         s->angles[0] = MSG_ReadAngle16i(); 
1572                         s->angles[1] = MSG_ReadAngle16i(); 
1573                         s->angles[2] = MSG_ReadAngle16i(); 
1574                 }
1575                 else
1576                 {
1577                         s->angles[0] = MSG_ReadAngle8i(); 
1578                         s->angles[1] = MSG_ReadAngle8i(); 
1579                         s->angles[2] = MSG_ReadAngle8i(); 
1580                 }
1581         }
1582         if (bits & E5_MODEL)
1583         {
1584                 if (bits & E5_MODEL16)
1585                         s->modelindex = (unsigned short) MSG_ReadShort();
1586                 else
1587                         s->modelindex = MSG_ReadByte();
1588         }
1589         if (bits & E5_FRAME)
1590         {
1591                 if (bits & E5_FRAME16)
1592                         s->frame = (unsigned short) MSG_ReadShort();
1593                 else
1594                         s->frame = MSG_ReadByte();
1595         }
1596         if (bits & E5_SKIN)
1597                 s->skin = MSG_ReadByte();
1598         if (bits & E5_EFFECTS)
1599         {
1600                 if (bits & E5_EFFECTS32)
1601                         s->effects = (unsigned int) MSG_ReadLong();
1602                 else if (bits & E5_EFFECTS16)
1603                         s->effects = (unsigned short) MSG_ReadShort();
1604                 else
1605                         s->effects = MSG_ReadByte();
1606         }
1607         if (bits & E5_ALPHA)
1608                 s->alpha = MSG_ReadByte();
1609         if (bits & E5_SCALE)
1610                 s->scale = MSG_ReadByte();
1611         if (bits & E5_COLORMAP)
1612                 s->colormap = MSG_ReadByte();
1613         if (bits & E5_ATTACHMENT)
1614         {
1615                 s->tagentity = (unsigned short) MSG_ReadShort();
1616                 s->tagindex = MSG_ReadByte();
1617         }
1618         if (bits & E5_LIGHT)
1619         {
1620                 s->light[0] = (unsigned short) MSG_ReadShort();
1621                 s->light[1] = (unsigned short) MSG_ReadShort();
1622                 s->light[2] = (unsigned short) MSG_ReadShort();
1623                 s->light[3] = (unsigned short) MSG_ReadShort();
1624                 s->lightstyle = MSG_ReadByte();
1625                 s->lightpflags = MSG_ReadByte();
1626         }
1627         if (bits & E5_GLOW)
1628         {
1629                 s->glowsize = MSG_ReadByte();
1630                 s->glowcolor = MSG_ReadByte();
1631         }
1632
1633
1634         if (developer_networkentities.integer >= 2)
1635         {
1636                 Con_Printf("ReadFields e%i", s->number);
1637
1638                 if (bits & E5_ORIGIN)
1639                         Con_Printf(" E5_ORIGIN %f %f %f", s->origin[0], s->origin[1], s->origin[2]);
1640                 if (bits & E5_ANGLES)
1641                         Con_Printf(" E5_ANGLES %f %f %f", s->angles[0], s->angles[1], s->angles[2]);
1642                 if (bits & E5_MODEL)
1643                         Con_Printf(" E5_MODEL %i", s->modelindex);
1644                 if (bits & E5_FRAME)
1645                         Con_Printf(" E5_FRAME %i", s->frame);
1646                 if (bits & E5_SKIN)
1647                         Con_Printf(" E5_SKIN %i", s->skin);
1648                 if (bits & E5_EFFECTS)
1649                         Con_Printf(" E5_EFFECTS %i", s->effects);
1650                 if (bits & E5_FLAGS)
1651                 {
1652                         Con_Printf(" E5_FLAGS %i (", s->flags);
1653                         if (s->flags & RENDER_STEP)
1654                                 Con_Print(" STEP");
1655                         if (s->flags & RENDER_GLOWTRAIL)
1656                                 Con_Print(" GLOWTRAIL");
1657                         if (s->flags & RENDER_VIEWMODEL)
1658                                 Con_Print(" VIEWMODEL");
1659                         if (s->flags & RENDER_EXTERIORMODEL)
1660                                 Con_Print(" EXTERIORMODEL");
1661                         if (s->flags & RENDER_LOWPRECISION)
1662                                 Con_Print(" LOWPRECISION");
1663                         if (s->flags & RENDER_COLORMAPPED)
1664                                 Con_Print(" COLORMAPPED");
1665                         if (s->flags & RENDER_SHADOW)
1666                                 Con_Print(" SHADOW");
1667                         if (s->flags & RENDER_LIGHT)
1668                                 Con_Print(" LIGHT");
1669                         Con_Print(")");
1670                 }
1671                 if (bits & E5_ALPHA)
1672                         Con_Printf(" E5_ALPHA %f", s->alpha / 255.0f);
1673                 if (bits & E5_SCALE)
1674                         Con_Printf(" E5_SCALE %f", s->scale / 16.0f);
1675                 if (bits & E5_COLORMAP)
1676                         Con_Printf(" E5_COLORMAP %i", s->colormap);
1677                 if (bits & E5_ATTACHMENT)
1678                         Con_Printf(" E5_ATTACHMENT e%i:%i", s->tagentity, s->tagindex);
1679                 if (bits & E5_LIGHT)
1680                         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);
1681                 if (bits & E5_GLOW)
1682                         Con_Printf(" E5_GLOW %i:%i", s->glowsize * 4, s->glowcolor);
1683                 Con_Print("\n");
1684         }
1685 }
1686
1687 int EntityState5_DeltaBits(const entity_state_t *o, const entity_state_t *n)
1688 {
1689         unsigned int bits = 0;
1690         if (n->active)
1691         {
1692                 if (!o->active)
1693                         bits |= E5_FULLUPDATE;
1694                 if (!VectorCompare(o->origin, n->origin))
1695                         bits |= E5_ORIGIN;
1696                 if (!VectorCompare(o->angles, n->angles))
1697                         bits |= E5_ANGLES;
1698                 if (o->modelindex != n->modelindex)
1699                         bits |= E5_MODEL;
1700                 if (o->frame != n->frame)
1701                         bits |= E5_FRAME;
1702                 if (o->skin != n->skin)
1703                         bits |= E5_SKIN;
1704                 if (o->effects != n->effects)
1705                         bits |= E5_EFFECTS;
1706                 if (o->flags != n->flags)
1707                         bits |= E5_FLAGS;
1708                 if (o->alpha != n->alpha)
1709                         bits |= E5_ALPHA;
1710                 if (o->scale != n->scale)
1711                         bits |= E5_SCALE;
1712                 if (o->colormap != n->colormap)
1713                         bits |= E5_COLORMAP;
1714                 if (o->tagentity != n->tagentity || o->tagindex != n->tagindex)
1715                         bits |= E5_ATTACHMENT;
1716                 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)
1717                         bits |= E5_LIGHT;
1718                 if (o->glowsize != n->glowsize || o->glowcolor != n->glowcolor)
1719                         bits |= E5_GLOW;
1720         }
1721         else
1722                 if (o->active)
1723                         bits |= E5_FULLUPDATE;
1724         return bits;
1725 }
1726
1727 void EntityFrame5_CL_ReadFrame(void)
1728 {
1729         int n, enumber;
1730         entity_t *ent;
1731         entity_state_t *s;
1732         // read the number of this frame to echo back in next input packet
1733         cl.latestframenum = MSG_ReadLong();
1734         // read entity numbers until we find a 0x8000
1735         // (which would be remove world entity, but is actually a terminator)
1736         while ((n = (unsigned short)MSG_ReadShort()) != 0x8000 && !msg_badread)
1737         {
1738                 // get the entity number and look it up
1739                 enumber = n & 0x7FFF;
1740                 ent = cl_entities + enumber;
1741                 // slide the current into the previous slot
1742                 ent->state_previous = ent->state_current;
1743                 // read the update
1744                 s = &ent->state_current;
1745                 if (n & 0x8000)
1746                 {
1747                         // remove entity
1748                         *s = defaultstate;
1749                 }
1750                 else
1751                 {
1752                         // update entity
1753                         EntityState5_ReadUpdate(s);
1754                 }
1755                 // set the cl_entities_active flag
1756                 cl_entities_active[enumber] = s->active;
1757                 // set the update time
1758                 s->time = cl.mtime[0];
1759                 // fix the number (it gets wiped occasionally by copying from defaultstate)
1760                 s->number = enumber;
1761                 // check if we need to update the lerp stuff
1762                 if (s->active)
1763                         CL_MoveLerpEntityStates(&cl_entities[enumber]);
1764                 // print extra messages if desired
1765                 if (developer_networkentities.integer >= 2 && cl_entities[enumber].state_current.active != cl_entities[enumber].state_previous.active)
1766                 {
1767                         if (cl_entities[enumber].state_current.active)
1768                                 Con_Printf("entity #%i has become active\n", enumber);
1769                         else if (cl_entities[enumber].state_previous.active)
1770                                 Con_Printf("entity #%i has become inactive\n", enumber);
1771                 }
1772         }
1773 }
1774
1775 void EntityFrame5_AckFrame(entityframe5_database_t *d, int framenum, int viewentnum)
1776 {
1777         int i, j, k, l, bits;
1778         entityframe5_changestate_t *s, *s2;
1779         entityframe5_packetlog_t *p, *p2;
1780         if (framenum <= d->ackframenum)
1781                 return;
1782         d->ackframenum = framenum;
1783         // scan for packets made obsolete by this ack
1784         for (i = 0, p = d->packetlog;i < ENTITYFRAME5_MAXPACKETLOGS;i++, p++)
1785         {
1786                 // skip packets that are empty or in the future
1787                 if (p->packetnumber == 0 || p->packetnumber > framenum)
1788                         continue;
1789                 // if the packetnumber matches it is deleted without any processing 
1790                 // (since it was received).
1791                 // if the packet number is less than this ack it was lost and its
1792                 // important information will be repeated in this update if it is not
1793                 // already obsolete due to a later update.
1794                 if (p->packetnumber < framenum)
1795                 {
1796                         // packet was lost - merge deltabits into the main array so they
1797                         // will be re-sent, but only if there is no newer update of that
1798                         // bit in the logs (as those will arrive before this update)
1799                         for (j = 0, s = p->states;j < p->numstates;j++, s++)
1800                         {
1801                                 // check for any newer updates to this entity and mask off any
1802                                 // overlapping bits (we don't need to send something again if
1803                                 // it has already been sent more recently)
1804                                 bits = s->bits & ~d->deltabits[s->number];
1805                                 for (k = 0, p2 = d->packetlog;k < ENTITYFRAME5_MAXPACKETLOGS && bits;k++, p2++)
1806                                 {
1807                                         if (p2->packetnumber > framenum)
1808                                         {
1809                                                 for (l = 0, s2 = p2->states;l < p2->numstates;l++, p2++)
1810                                                 {
1811                                                         if (s2->number == s->number)
1812                                                         {
1813                                                                 bits &= ~s2->bits;
1814                                                                 break;
1815                                                         }
1816                                                 }
1817                                         }
1818                                 }
1819                                 // if the bits haven't all been cleared, there were some bits
1820                                 // lost with this packet, so set them again now
1821                                 if (bits)
1822                                 {
1823                                         d->deltabits[s->number] |= bits;
1824                                         d->priorities[s->number] = EntityState5_Priority(d, d->states + viewentnum, d->states + s->number, d->deltabits[s->number], d->latestframenum - d->updateframenum[s->number]);
1825                                 }
1826                         }
1827                 }
1828                 // delete this packet log as it is now obsolete
1829                 p->packetnumber = 0;
1830         }
1831 }
1832
1833 int entityframe5_prioritychaincounts[E5_PROTOCOL_PRIORITYLEVELS];
1834 unsigned short entityframe5_prioritychains[E5_PROTOCOL_PRIORITYLEVELS][ENTITYFRAME5_MAXSTATES];
1835
1836 void EntityFrame5_WriteFrame(sizebuf_t *msg, entityframe5_database_t *d, int numstates, const entity_state_t *states, int viewentnum)
1837 {
1838         const entity_state_t *n;
1839         int i, num, l, framenum, packetlognumber, priority;
1840         sizebuf_t buf;
1841         qbyte data[128];
1842         entityframe5_packetlog_t *packetlog;
1843
1844         framenum = d->latestframenum + 1;
1845
1846         // prepare the buffer
1847         memset(&buf, 0, sizeof(buf));
1848         buf.data = data;
1849         buf.maxsize = sizeof(data);
1850
1851         // detect changes in states
1852         num = 0;
1853         for (i = 0, n = states;i < numstates;i++, n++)
1854         {
1855                 // mark gaps in entity numbering as removed entities
1856                 for (;num < n->number;num++)
1857                 {
1858                         // if the entity used to exist, clear it
1859                         if (CHECKPVSBIT(d->visiblebits, num))
1860                         {
1861                                 CLEARPVSBIT(d->visiblebits, num);
1862                                 d->deltabits[num] = E5_FULLUPDATE;
1863                                 d->priorities[num] = EntityState5_Priority(d, d->states + viewentnum, d->states + num, d->deltabits[num], framenum - d->updateframenum[num]);
1864                                 d->states[num] = defaultstate;
1865                                 d->states[num].number = num;
1866                         }
1867                 }
1868                 // update the entity state data
1869                 if (!CHECKPVSBIT(d->visiblebits, num))
1870                 {
1871                         // entity just spawned in, don't let it completely hog priority
1872                         // because of being ancient on the first frame
1873                         d->updateframenum[num] = framenum;
1874                 }
1875                 SETPVSBIT(d->visiblebits, num);
1876                 d->deltabits[num] |= EntityState5_DeltaBits(d->states + num, n);
1877                 d->priorities[num] = EntityState5_Priority(d, d->states + viewentnum, d->states + num, d->deltabits[num], framenum - d->updateframenum[num]);
1878                 d->states[num] = *n;
1879                 d->states[num].number = num;
1880                 // advance to next entity so the next iteration doesn't immediately remove it
1881                 num++;
1882         }
1883         // all remaining entities are dead
1884         for (;num < MAX_EDICTS;num++)
1885         {
1886                 if (CHECKPVSBIT(d->visiblebits, num))
1887                 {
1888                         CLEARPVSBIT(d->visiblebits, num);
1889                         d->deltabits[num] = E5_FULLUPDATE;
1890                         d->priorities[num] = EntityState5_Priority(d, d->states + viewentnum, d->states + num, d->deltabits[num], framenum - d->updateframenum[num]);
1891                         d->states[num] = defaultstate;
1892                         d->states[num].number = num;
1893                 }
1894         }
1895
1896         // build lists of entities by priority level
1897         memset(entityframe5_prioritychaincounts, 0, sizeof(entityframe5_prioritychaincounts));
1898         l = 0;
1899         for (num = 0;num < MAX_EDICTS;num++)
1900         {
1901                 if (d->priorities[num])
1902                 {
1903                         l = num;
1904                         priority = d->priorities[num];
1905                         if (entityframe5_prioritychaincounts[priority] < ENTITYFRAME5_MAXSTATES)
1906                                 entityframe5_prioritychains[priority][entityframe5_prioritychaincounts[priority]++] = num;
1907                 }
1908         }
1909
1910         // return early if there are no entities to send this time
1911         if (l == 0)
1912                 return;
1913
1914         d->latestframenum = framenum;
1915         MSG_WriteByte(msg, svc_entities);
1916         MSG_WriteLong(msg, framenum);
1917
1918         // if packet log is full, an empty update is still written
1919         // (otherwise the client might have nothing to ack to remove packetlogs)
1920         for (packetlognumber = 0, packetlog = d->packetlog;packetlognumber < ENTITYFRAME5_MAXPACKETLOGS;packetlognumber++, packetlog++)
1921                 if (packetlog->packetnumber == 0)
1922                         break;
1923         if (packetlognumber < ENTITYFRAME5_MAXPACKETLOGS)
1924         {
1925                 // write to packet and log
1926                 packetlog->packetnumber = framenum;
1927                 packetlog->numstates = 0;
1928                 for (priority = E5_PROTOCOL_PRIORITYLEVELS - 1;priority >= 0 && packetlog->numstates < ENTITYFRAME5_MAXSTATES;priority--)
1929                 {
1930                         for (i = 0;i < entityframe5_prioritychaincounts[priority] && packetlog->numstates < ENTITYFRAME5_MAXSTATES;i++)
1931                         {
1932                                 num = entityframe5_prioritychains[priority][i];
1933                                 n = d->states + num;
1934                                 if (d->deltabits[num] & E5_FULLUPDATE)
1935                                         d->deltabits[num] = E5_FULLUPDATE | EntityState5_DeltaBits(&defaultstate, n);
1936                                 buf.cursize = 0;
1937                                 EntityState5_WriteUpdate(num, n, d->deltabits[num], &buf);
1938                                 // if the entity won't fit, try the next one
1939                                 if (msg->cursize + buf.cursize + 2 > msg->maxsize)
1940                                         continue;
1941                                 // write entity to the packet
1942                                 SZ_Write(msg, buf.data, buf.cursize);
1943                                 // mark age on entity for prioritization
1944                                 d->updateframenum[num] = framenum;
1945                                 // log entity so deltabits can be restored later if lost
1946                                 packetlog->states[packetlog->numstates].number = num;
1947                                 packetlog->states[packetlog->numstates].bits = d->deltabits[num];
1948                                 packetlog->numstates++;
1949                                 // clear deltabits and priority so it won't be sent again
1950                                 d->deltabits[num] = 0;
1951                                 d->priorities[num] = 0;
1952                         }
1953                 }
1954         }
1955
1956         MSG_WriteShort(msg, 0x8000);
1957 }
1958