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