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