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