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