fixed another stack overflow on win32, apparently a 64k packet buffer on the stack...
[divverent/darkplaces.git] / sv_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sv_main.c -- server main program
21
22 #include "quakedef.h"
23
24 static cvar_t sv_cullentities_pvs = {0, "sv_cullentities_pvs", "0"}; // fast but loose
25 static cvar_t sv_cullentities_portal = {0, "sv_cullentities_portal", "0"}; // extremely accurate visibility checking, but too slow
26 static cvar_t sv_cullentities_trace = {0, "sv_cullentities_trace", "1"}; // tends to get false negatives, uses a timeout to keep entities visible a short time after becoming hidden
27 static cvar_t sv_cullentities_stats = {0, "sv_cullentities_stats", "0"};
28
29 server_t                sv;
30 server_static_t svs;
31
32 static char localmodels[MAX_MODELS][5];                 // inline model names for precache
33
34 static mempool_t *sv_edicts_mempool = NULL;
35
36 //============================================================================
37
38 extern void SV_Phys_Init (void);
39 extern void SV_World_Init (void);
40
41 /*
42 ===============
43 SV_Init
44 ===============
45 */
46 void SV_Init (void)
47 {
48         int i;
49
50         Cvar_RegisterVariable (&sv_maxvelocity);
51         Cvar_RegisterVariable (&sv_gravity);
52         Cvar_RegisterVariable (&sv_friction);
53         Cvar_RegisterVariable (&sv_edgefriction);
54         Cvar_RegisterVariable (&sv_stopspeed);
55         Cvar_RegisterVariable (&sv_maxspeed);
56         Cvar_RegisterVariable (&sv_accelerate);
57         Cvar_RegisterVariable (&sv_idealpitchscale);
58         Cvar_RegisterVariable (&sv_aim);
59         Cvar_RegisterVariable (&sv_nostep);
60         Cvar_RegisterVariable (&sv_predict);
61         Cvar_RegisterVariable (&sv_deltacompress);
62         Cvar_RegisterVariable (&sv_cullentities_pvs);
63         Cvar_RegisterVariable (&sv_cullentities_portal);
64         Cvar_RegisterVariable (&sv_cullentities_trace);
65         Cvar_RegisterVariable (&sv_cullentities_stats);
66
67         SV_Phys_Init();
68         SV_World_Init();
69
70         for (i = 0;i < MAX_MODELS;i++)
71                 sprintf (localmodels[i], "*%i", i);
72
73         sv_edicts_mempool = Mem_AllocPool("edicts");
74 }
75
76 /*
77 =============================================================================
78
79 EVENT MESSAGES
80
81 =============================================================================
82 */
83
84 /*
85 ==================
86 SV_StartParticle
87
88 Make sure the event gets sent to all clients
89 ==================
90 */
91 void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
92 {
93         int             i, v;
94
95         if (sv.datagram.cursize > MAX_DATAGRAM-16)
96                 return;
97         MSG_WriteByte (&sv.datagram, svc_particle);
98         MSG_WriteDPCoord (&sv.datagram, org[0]);
99         MSG_WriteDPCoord (&sv.datagram, org[1]);
100         MSG_WriteDPCoord (&sv.datagram, org[2]);
101         for (i=0 ; i<3 ; i++)
102         {
103                 v = dir[i]*16;
104                 if (v > 127)
105                         v = 127;
106                 else if (v < -128)
107                         v = -128;
108                 MSG_WriteChar (&sv.datagram, v);
109         }
110         MSG_WriteByte (&sv.datagram, count);
111         MSG_WriteByte (&sv.datagram, color);
112 }
113
114 /*
115 ==================
116 SV_StartEffect
117
118 Make sure the event gets sent to all clients
119 ==================
120 */
121 void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
122 {
123         if (sv.datagram.cursize > MAX_DATAGRAM-18)
124                 return;
125         if (modelindex >= 256 || startframe >= 256)
126         {
127                 MSG_WriteByte (&sv.datagram, svc_effect2);
128                 MSG_WriteDPCoord (&sv.datagram, org[0]);
129                 MSG_WriteDPCoord (&sv.datagram, org[1]);
130                 MSG_WriteDPCoord (&sv.datagram, org[2]);
131                 MSG_WriteShort (&sv.datagram, modelindex);
132                 MSG_WriteShort (&sv.datagram, startframe);
133                 MSG_WriteByte (&sv.datagram, framecount);
134                 MSG_WriteByte (&sv.datagram, framerate);
135         }
136         else
137         {
138                 MSG_WriteByte (&sv.datagram, svc_effect);
139                 MSG_WriteDPCoord (&sv.datagram, org[0]);
140                 MSG_WriteDPCoord (&sv.datagram, org[1]);
141                 MSG_WriteDPCoord (&sv.datagram, org[2]);
142                 MSG_WriteByte (&sv.datagram, modelindex);
143                 MSG_WriteByte (&sv.datagram, startframe);
144                 MSG_WriteByte (&sv.datagram, framecount);
145                 MSG_WriteByte (&sv.datagram, framerate);
146         }
147 }
148
149 /*
150 ==================
151 SV_StartSound
152
153 Each entity can have eight independant sound sources, like voice,
154 weapon, feet, etc.
155
156 Channel 0 is an auto-allocate channel, the others override anything
157 already running on that entity/channel pair.
158
159 An attenuation of 0 will play full volume everywhere in the level.
160 Larger attenuations will drop off.  (max 4 attenuation)
161
162 ==================
163 */
164 void SV_StartSound (edict_t *entity, int channel, char *sample, int volume,
165     float attenuation)
166 {
167     int         sound_num;
168     int field_mask;
169     int                 i;
170         int                     ent;
171
172         if (volume < 0 || volume > 255)
173                 Host_Error ("SV_StartSound: volume = %i", volume);
174
175         if (attenuation < 0 || attenuation > 4)
176                 Host_Error ("SV_StartSound: attenuation = %f", attenuation);
177
178         if (channel < 0 || channel > 7)
179                 Host_Error ("SV_StartSound: channel = %i", channel);
180
181         if (sv.datagram.cursize > MAX_DATAGRAM-16)
182                 return;
183
184 // find precache number for sound
185     for (sound_num=1 ; sound_num<MAX_SOUNDS
186         && sv.sound_precache[sound_num] ; sound_num++)
187         if (!strcmp(sample, sv.sound_precache[sound_num]))
188             break;
189
190     if ( sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num] )
191     {
192         Con_Printf ("SV_StartSound: %s not precached\n", sample);
193         return;
194     }
195
196         ent = NUM_FOR_EDICT(entity);
197
198         field_mask = 0;
199         if (volume != DEFAULT_SOUND_PACKET_VOLUME)
200                 field_mask |= SND_VOLUME;
201         if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
202                 field_mask |= SND_ATTENUATION;
203         if (ent >= 8192)
204                 field_mask |= SND_LARGEENTITY;
205         if (sound_num >= 256 || channel >= 8)
206                 field_mask |= SND_LARGESOUND;
207
208 // directed messages go only to the entity they are targeted on
209         MSG_WriteByte (&sv.datagram, svc_sound);
210         MSG_WriteByte (&sv.datagram, field_mask);
211         if (field_mask & SND_VOLUME)
212                 MSG_WriteByte (&sv.datagram, volume);
213         if (field_mask & SND_ATTENUATION)
214                 MSG_WriteByte (&sv.datagram, attenuation*64);
215         if (field_mask & SND_LARGEENTITY)
216         {
217                 MSG_WriteShort (&sv.datagram, ent);
218                 MSG_WriteByte (&sv.datagram, channel);
219         }
220         else
221                 MSG_WriteShort (&sv.datagram, (ent<<3) | channel);
222         if (field_mask & SND_LARGESOUND)
223                 MSG_WriteShort (&sv.datagram, sound_num);
224         else
225                 MSG_WriteByte (&sv.datagram, sound_num);
226         for (i = 0;i < 3;i++)
227                 MSG_WriteDPCoord (&sv.datagram, entity->v->origin[i]+0.5*(entity->v->mins[i]+entity->v->maxs[i]));
228 }
229
230 /*
231 ==============================================================================
232
233 CLIENT SPAWNING
234
235 ==============================================================================
236 */
237
238 /*
239 ================
240 SV_SendServerinfo
241
242 Sends the first message from the server to a connected client.
243 This will be sent on the initial connection and upon each server load.
244 ================
245 */
246 void SV_SendServerinfo (client_t *client)
247 {
248         char                    **s;
249         char                    message[2048];
250
251         // LordHavoc: clear entityframe tracking
252         client->entityframenumber = 0;
253         EntityFrame_ClearDatabase(&client->entitydatabase);
254
255         MSG_WriteByte (&client->message, svc_print);
256         sprintf (message, "\002\nServer: %s build %s (progs %i crc)", gamename, buildstring, pr_crc);
257         MSG_WriteString (&client->message,message);
258
259         MSG_WriteByte (&client->message, svc_serverinfo);
260         MSG_WriteLong (&client->message, DPPROTOCOL_VERSION3);
261         MSG_WriteByte (&client->message, svs.maxclients);
262
263         if (!coop.integer && deathmatch.integer)
264                 MSG_WriteByte (&client->message, GAME_DEATHMATCH);
265         else
266                 MSG_WriteByte (&client->message, GAME_COOP);
267
268         sprintf (message, PR_GetString(sv.edicts->v->message));
269
270         MSG_WriteString (&client->message,message);
271
272         for (s = sv.model_precache+1 ; *s ; s++)
273                 MSG_WriteString (&client->message, *s);
274         MSG_WriteByte (&client->message, 0);
275
276         for (s = sv.sound_precache+1 ; *s ; s++)
277                 MSG_WriteString (&client->message, *s);
278         MSG_WriteByte (&client->message, 0);
279
280 // send music
281         MSG_WriteByte (&client->message, svc_cdtrack);
282         MSG_WriteByte (&client->message, sv.edicts->v->sounds);
283         MSG_WriteByte (&client->message, sv.edicts->v->sounds);
284
285 // set view
286         MSG_WriteByte (&client->message, svc_setview);
287         MSG_WriteShort (&client->message, NUM_FOR_EDICT(client->edict));
288
289         MSG_WriteByte (&client->message, svc_signonnum);
290         MSG_WriteByte (&client->message, 1);
291
292         client->sendsignon = true;
293         client->spawned = false;                // need prespawn, spawn, etc
294 }
295
296 /*
297 ================
298 SV_ConnectClient
299
300 Initializes a client_t for a new net connection.  This will only be called
301 once for a player each game, not once for each level change.
302 ================
303 */
304 void SV_ConnectClient (int clientnum)
305 {
306         edict_t                 *ent;
307         client_t                *client;
308         int                             edictnum;
309         struct qsocket_s *netconnection;
310         int                             i;
311         float                   spawn_parms[NUM_SPAWN_PARMS];
312
313         client = svs.clients + clientnum;
314
315         Con_DPrintf ("Client %s connected\n", client->netconnection->address);
316
317         edictnum = clientnum+1;
318
319         ent = EDICT_NUM(edictnum);
320
321 // set up the client_t
322         netconnection = client->netconnection;
323
324         if (sv.loadgame)
325                 memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms));
326         memset (client, 0, sizeof(*client));
327         client->netconnection = netconnection;
328
329         strcpy (client->name, "unconnected");
330         client->active = true;
331         client->spawned = false;
332         client->edict = ent;
333         client->message.data = client->msgbuf;
334         client->message.maxsize = sizeof(client->msgbuf);
335         client->message.allowoverflow = true;           // we can catch it
336
337         if (sv.loadgame)
338                 memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms));
339         else
340         {
341         // call the progs to get default spawn parms for the new client
342                 PR_ExecuteProgram (pr_global_struct->SetNewParms, "QC function SetNewParms is missing");
343                 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
344                         client->spawn_parms[i] = (&pr_global_struct->parm1)[i];
345         }
346
347 #if NOROUTINGFIX
348         SV_SendServerinfo (client);
349 #else
350         // send serverinfo on first nop
351         client->waitingforconnect = true;
352         client->sendsignon = true;
353         client->spawned = false;                // need prespawn, spawn, etc
354 #endif
355 }
356
357
358 /*
359 ===================
360 SV_CheckForNewClients
361
362 ===================
363 */
364 void SV_CheckForNewClients (void)
365 {
366         struct qsocket_s        *ret;
367         int                             i;
368
369 //
370 // check for new connections
371 //
372         while (1)
373         {
374                 ret = NET_CheckNewConnections ();
375                 if (!ret)
376                         break;
377
378         //
379         // init a new client structure
380         //
381                 for (i=0 ; i<svs.maxclients ; i++)
382                         if (!svs.clients[i].active)
383                                 break;
384                 if (i == svs.maxclients)
385                         Sys_Error ("Host_CheckForNewClients: no free clients");
386
387                 svs.clients[i].netconnection = ret;
388                 SV_ConnectClient (i);
389
390                 net_activeconnections++;
391                 NET_Heartbeat (1);
392         }
393 }
394
395
396
397 /*
398 ===============================================================================
399
400 FRAME UPDATES
401
402 ===============================================================================
403 */
404
405 /*
406 ==================
407 SV_ClearDatagram
408
409 ==================
410 */
411 void SV_ClearDatagram (void)
412 {
413         SZ_Clear (&sv.datagram);
414 }
415
416 /*
417 =============================================================================
418
419 The PVS must include a small area around the client to allow head bobbing
420 or other small motion on the client side.  Otherwise, a bob might cause an
421 entity that should be visible to not show up, especially when the bob
422 crosses a waterline.
423
424 =============================================================================
425 */
426
427 int             fatbytes;
428 qbyte   fatpvs[MAX_MAP_LEAFS/8];
429
430 void SV_AddToFatPVS (vec3_t org, mnode_t *node)
431 {
432         int             i;
433         qbyte   *pvs;
434         mplane_t        *plane;
435         float   d;
436
437         while (1)
438         {
439         // if this is a leaf, accumulate the pvs bits
440                 if (node->contents < 0)
441                 {
442                         if (node->contents != CONTENTS_SOLID)
443                         {
444                                 pvs = Mod_LeafPVS ( (mleaf_t *)node, sv.worldmodel);
445                                 for (i=0 ; i<fatbytes ; i++)
446                                         fatpvs[i] |= pvs[i];
447                         }
448                         return;
449                 }
450
451                 plane = node->plane;
452                 d = DotProduct (org, plane->normal) - plane->dist;
453                 if (d > 8)
454                         node = node->children[0];
455                 else if (d < -8)
456                         node = node->children[1];
457                 else
458                 {       // go down both
459                         SV_AddToFatPVS (org, node->children[0]);
460                         node = node->children[1];
461                 }
462         }
463 }
464
465 /*
466 =============
467 SV_FatPVS
468
469 Calculates a PVS that is the inclusive or of all leafs within 8 pixels of the
470 given point.
471 =============
472 */
473 qbyte *SV_FatPVS (vec3_t org)
474 {
475         fatbytes = (sv.worldmodel->numleafs+31)>>3;
476         memset (fatpvs, 0, fatbytes);
477         SV_AddToFatPVS (org, sv.worldmodel->nodes);
478         return fatpvs;
479 }
480
481 //=============================================================================
482
483
484 int SV_BoxTouchingPVS (qbyte *pvs, vec3_t mins, vec3_t maxs, mnode_t *node)
485 {
486         int leafnum;
487 loc0:
488         if (node->contents < 0)
489         {
490                 // leaf
491                 if (node->contents == CONTENTS_SOLID)
492                         return false;
493                 leafnum = (mleaf_t *)node - sv.worldmodel->leafs - 1;
494                 return pvs[leafnum >> 3] & (1 << (leafnum & 7));
495         }
496
497         // node - recurse down the BSP tree
498         switch (BoxOnPlaneSide(mins, maxs, node->plane))
499         {
500         case 1: // front
501                 node = node->children[0];
502                 goto loc0;
503         case 2: // back
504                 node = node->children[1];
505                 goto loc0;
506         default: // crossing
507                 if (node->children[0]->contents != CONTENTS_SOLID)
508                         if (SV_BoxTouchingPVS (pvs, mins, maxs, node->children[0]))
509                                 return true;
510                 node = node->children[1];
511                 goto loc0;
512         }
513         // never reached
514         return false;
515 }
516
517
518 /*
519 =============
520 SV_WriteEntitiesToClient
521
522 =============
523 */
524 #ifdef QUAKEENTITIES
525 void SV_WriteEntitiesToClient (client_t *client, edict_t *clent, sizebuf_t *msg)
526 {
527         int e, clentnum, bits, alpha, glowcolor, glowsize, scale, effects, lightsize;
528         int culled_pvs, culled_portal, culled_trace, visibleentities, totalentities;
529         qbyte *pvs;
530         vec3_t origin, angles, entmins, entmaxs, testorigin, testeye;
531         float nextfullupdate, alphaf;
532         edict_t *ent;
533         eval_t *val;
534         entity_state_t *baseline; // LordHavoc: delta or startup baseline
535         trace_t trace;
536         model_t *model;
537
538         Mod_CheckLoaded(sv.worldmodel);
539
540 // find the client's PVS
541         VectorAdd (clent->v->origin, clent->v->view_ofs, testeye);
542         pvs = SV_FatPVS (testeye);
543
544         culled_pvs = 0;
545         culled_portal = 0;
546         culled_trace = 0;
547         visibleentities = 0;
548         totalentities = 0;
549
550         clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
551         // send all entities that touch the pvs
552         ent = NEXT_EDICT(sv.edicts);
553         for (e = 1;e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
554         {
555                 bits = 0;
556
557                 // prevent delta compression against this frame (unless actually sent, which will restore this later)
558                 nextfullupdate = client->nextfullupdate[e];
559                 client->nextfullupdate[e] = -1;
560
561                 if (ent != clent) // LordHavoc: always send player
562                 {
563                         if ((val = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)) && val->edict)
564                         {
565                                 if (val->edict != clentnum)
566                                 {
567                                         // don't show to anyone else
568                                         continue;
569                                 }
570                                 else
571                                         bits |= U_VIEWMODEL; // show relative to the view
572                         }
573                         else
574                         {
575                                 // LordHavoc: never draw something told not to display to this client
576                                 if ((val = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)) && val->edict == clentnum)
577                                         continue;
578                                 if ((val = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)) && val->edict && val->edict != clentnum)
579                                         continue;
580                         }
581                 }
582
583                 glowsize = 0;
584
585                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_size)))
586                         glowsize = (int) val->_float >> 2;
587                 if (glowsize > 255) glowsize = 255;
588                 if (glowsize < 0) glowsize = 0;
589
590                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_trail)))
591                 if (val->_float != 0)
592                         bits |= U_GLOWTRAIL;
593
594                 if (ent->v->modelindex >= 0 && ent->v->modelindex < MAX_MODELS && *PR_GetString(ent->v->model))
595                 {
596                         model = sv.models[(int)ent->v->modelindex];
597                         Mod_CheckLoaded(model);
598                 }
599                 else
600                 {
601                         model = NULL;
602                         if (ent != clent) // LordHavoc: always send player
603                                 if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
604                                         continue;
605                 }
606
607                 VectorCopy(ent->v->angles, angles);
608                 if (DotProduct(ent->v->velocity, ent->v->velocity) >= 1.0f)
609                 {
610                         VectorMA(ent->v->origin, host_client->latency, ent->v->velocity, origin);
611                         // LordHavoc: trace predicted movement to avoid putting things in walls
612                         trace = SV_Move (ent->v->origin, ent->v->mins, ent->v->maxs, origin, MOVE_NORMAL, ent);
613                         VectorCopy(trace.endpos, origin);
614                 }
615                 else
616                 {
617                         VectorCopy(ent->v->origin, origin);
618                 }
619
620                 // ent has survived every check so far, check if it is visible
621                 if (ent != clent && ((bits & U_VIEWMODEL) == 0))
622                 {
623                         // use the predicted origin
624                         entmins[0] = origin[0] - 1.0f;
625                         entmins[1] = origin[1] - 1.0f;
626                         entmins[2] = origin[2] - 1.0f;
627                         entmaxs[0] = origin[0] + 1.0f;
628                         entmaxs[1] = origin[1] + 1.0f;
629                         entmaxs[2] = origin[2] + 1.0f;
630                         // using the model's bounding box to ensure things are visible regardless of their physics box
631                         if (model)
632                         {
633                                 if (ent->v->angles[0] || ent->v->angles[2]) // pitch and roll
634                                 {
635                                         VectorAdd(entmins, model->rotatedmins, entmins);
636                                         VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
637                                 }
638                                 else if (ent->v->angles[1])
639                                 {
640                                         VectorAdd(entmins, model->yawmins, entmins);
641                                         VectorAdd(entmaxs, model->yawmaxs, entmaxs);
642                                 }
643                                 else
644                                 {
645                                         VectorAdd(entmins, model->normalmins, entmins);
646                                         VectorAdd(entmaxs, model->normalmaxs, entmaxs);
647                                 }
648                         }
649
650                         totalentities++;
651
652                         // if not touching a visible leaf
653                         if (sv_cullentities_pvs.integer && !SV_BoxTouchingPVS(pvs, entmins, entmaxs, sv.worldmodel->nodes))
654                         {
655                                 culled_pvs++;
656                                 continue;
657                         }
658
659                         // or not visible through the portals
660                         if (sv_cullentities_portal.integer && !Portal_CheckBox(sv.worldmodel, testeye, entmins, entmaxs))
661                         {
662                                 culled_portal++;
663                                 continue;
664                         }
665
666                         // don't try to cull embedded brush models with this, they're sometimes huge (spanning several rooms)
667                         if (sv_cullentities_trace.integer && (model == NULL || model->type != mod_brush || model->name[0] != '*'))
668                         {
669                                 // LordHavoc: test random offsets, to maximize chance of detection
670                                 testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
671                                 testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
672                                 testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
673
674                                 Collision_ClipTrace(&trace, NULL, sv.worldmodel, vec3_origin, vec3_origin, vec3_origin, testeye, vec3_origin, vec3_origin, testorigin);
675
676                                 if (trace.fraction == 1)
677                                         client->visibletime[e] = realtime + 1;
678                                 else
679                                 {
680                                         //test nearest point on bbox
681                                         testorigin[0] = bound(entmins[0], testeye[0], entmaxs[0]);
682                                         testorigin[1] = bound(entmins[1], testeye[1], entmaxs[1]);
683                                         testorigin[2] = bound(entmins[2], testeye[2], entmaxs[2]);
684
685                                         Collision_ClipTrace(&trace, NULL, sv.worldmodel, vec3_origin, vec3_origin, vec3_origin, testeye, vec3_origin, vec3_origin, testorigin);
686
687                                         if (trace.fraction == 1)
688                                                 client->visibletime[e] = realtime + 1;
689                                         else if (realtime > client->visibletime[e])
690                                         {
691                                                 culled_trace++;
692                                                 continue;
693                                         }
694                                 }
695                         }
696                         visibleentities++;
697                 }
698
699                 alphaf = 255.0f;
700                 scale = 16;
701                 glowcolor = 254;
702                 effects = ent->v->effects;
703
704                 if ((val = GETEDICTFIELDVALUE(ent, eval_alpha)))
705                 if (val->_float != 0)
706                         alphaf = val->_float * 255.0f;
707
708                 // HalfLife support
709                 if ((val = GETEDICTFIELDVALUE(ent, eval_renderamt)))
710                 if (val->_float != 0)
711                         alphaf = val->_float;
712
713                 if (alphaf == 0.0f)
714                         alphaf = 255.0f;
715                 alpha = bound(0, alphaf, 255);
716
717                 if ((val = GETEDICTFIELDVALUE(ent, eval_scale)))
718                 if ((scale = (int) (val->_float * 16.0)) == 0) scale = 16;
719                 if (scale < 0) scale = 0;
720                 if (scale > 255) scale = 255;
721
722                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_color)))
723                 if (val->_float != 0)
724                         glowcolor = (int) val->_float;
725
726                 if ((val = GETEDICTFIELDVALUE(ent, eval_fullbright)))
727                 if (val->_float != 0)
728                         effects |= EF_FULLBRIGHT;
729
730                 if (ent != clent)
731                 {
732                         if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
733                         {
734                                 if (model) // model
735                                 {
736                                         // don't send if flagged for NODRAW and there are no effects
737                                         if (model->flags == 0 && ((effects & EF_NODRAW) || scale <= 0 || alpha <= 0))
738                                                 continue;
739                                 }
740                                 else // no model and no effects
741                                         continue;
742                         }
743                 }
744
745                 if (msg->maxsize - msg->cursize < 32) // LordHavoc: increased check from 16 to 32
746                 {
747                         Con_Printf ("packet overflow\n");
748                         // mark the rest of the entities so they can't be delta compressed against this frame
749                         for (;e < sv.num_edicts;e++)
750                         {
751                                 client->nextfullupdate[e] = -1;
752                                 client->visibletime[e] = -1;
753                         }
754                         return;
755                 }
756
757                 if ((val = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)) && val->edict == clentnum)
758                         bits = bits | U_EXTERIORMODEL;
759
760 // send an update
761                 baseline = &ent->baseline;
762
763                 if (((int)ent->v->effects & EF_DELTA) && sv_deltacompress.integer)
764                 {
765                         // every half second a full update is forced
766                         if (realtime < client->nextfullupdate[e])
767                         {
768                                 bits |= U_DELTA;
769                                 baseline = &ent->deltabaseline;
770                         }
771                         else
772                                 nextfullupdate = realtime + 0.5f;
773                 }
774                 else
775                         nextfullupdate = realtime + 0.5f;
776
777                 // restore nextfullupdate since this is being sent for real
778                 client->nextfullupdate[e] = nextfullupdate;
779
780                 if (e >= 256)
781                         bits |= U_LONGENTITY;
782
783                 if (ent->v->movetype == MOVETYPE_STEP)
784                         bits |= U_STEP;
785
786                 // LordHavoc: old stuff, but rewritten to have more exact tolerances
787                 if (origin[0] != baseline->origin[0])                                                                                   bits |= U_ORIGIN1;
788                 if (origin[1] != baseline->origin[1])                                                                                   bits |= U_ORIGIN2;
789                 if (origin[2] != baseline->origin[2])                                                                                   bits |= U_ORIGIN3;
790                 if (((int)(angles[0]*(256.0/360.0)) & 255) != ((int)(baseline->angles[0]*(256.0/360.0)) & 255)) bits |= U_ANGLE1;
791                 if (((int)(angles[1]*(256.0/360.0)) & 255) != ((int)(baseline->angles[1]*(256.0/360.0)) & 255)) bits |= U_ANGLE2;
792                 if (((int)(angles[2]*(256.0/360.0)) & 255) != ((int)(baseline->angles[2]*(256.0/360.0)) & 255)) bits |= U_ANGLE3;
793                 if (baseline->colormap != (qbyte) ent->v->colormap)                                                             bits |= U_COLORMAP;
794                 if (baseline->skin != (qbyte) ent->v->skin)                                                                             bits |= U_SKIN;
795                 if ((baseline->frame & 0x00FF) != ((int) ent->v->frame & 0x00FF))                               bits |= U_FRAME;
796                 if ((baseline->effects & 0x00FF) != ((int) ent->v->effects & 0x00FF))                   bits |= U_EFFECTS;
797                 if ((baseline->modelindex & 0x00FF) != ((int) ent->v->modelindex & 0x00FF))             bits |= U_MODEL;
798
799                 // LordHavoc: new stuff
800                 if (baseline->alpha != alpha)                                                                                                   bits |= U_ALPHA;
801                 if (baseline->scale != scale)                                                                                                   bits |= U_SCALE;
802                 if (((int) baseline->effects & 0xFF00) != ((int) ent->v->effects & 0xFF00))             bits |= U_EFFECTS2;
803                 if (baseline->glowsize != glowsize)                                                                                             bits |= U_GLOWSIZE;
804                 if (baseline->glowcolor != glowcolor)                                                                                   bits |= U_GLOWCOLOR;
805                 if (((int) baseline->frame & 0xFF00) != ((int) ent->v->frame & 0xFF00))                 bits |= U_FRAME2;
806                 if (((int) baseline->frame & 0xFF00) != ((int) ent->v->modelindex & 0xFF00))            bits |= U_MODEL2;
807
808                 // update delta baseline
809                 VectorCopy(ent->v->origin, ent->deltabaseline.origin);
810                 VectorCopy(ent->v->angles, ent->deltabaseline.angles);
811                 ent->deltabaseline.colormap = ent->v->colormap;
812                 ent->deltabaseline.skin = ent->v->skin;
813                 ent->deltabaseline.frame = ent->v->frame;
814                 ent->deltabaseline.effects = ent->v->effects;
815                 ent->deltabaseline.modelindex = ent->v->modelindex;
816                 ent->deltabaseline.alpha = alpha;
817                 ent->deltabaseline.scale = scale;
818                 ent->deltabaseline.glowsize = glowsize;
819                 ent->deltabaseline.glowcolor = glowcolor;
820
821                 // write the message
822                 if (bits >= 16777216)
823                         bits |= U_EXTEND2;
824                 if (bits >= 65536)
825                         bits |= U_EXTEND1;
826                 if (bits >= 256)
827                         bits |= U_MOREBITS;
828                 bits |= U_SIGNAL;
829
830                 MSG_WriteByte (msg, bits);
831                 if (bits & U_MOREBITS)
832                         MSG_WriteByte (msg, bits>>8);
833                 // LordHavoc: extend bytes have to be written here due to delta compression
834                 if (bits & U_EXTEND1)
835                         MSG_WriteByte (msg, bits>>16);
836                 if (bits & U_EXTEND2)
837                         MSG_WriteByte (msg, bits>>24);
838
839                 // LordHavoc: old stuff
840                 if (bits & U_LONGENTITY)
841                         MSG_WriteShort (msg,e);
842                 else
843                         MSG_WriteByte (msg,e);
844                 if (bits & U_MODEL)             MSG_WriteByte (msg,     ent->v->modelindex);
845                 if (bits & U_FRAME)             MSG_WriteByte (msg, ent->v->frame);
846                 if (bits & U_COLORMAP)  MSG_WriteByte (msg, ent->v->colormap);
847                 if (bits & U_SKIN)              MSG_WriteByte (msg, ent->v->skin);
848                 if (bits & U_EFFECTS)   MSG_WriteByte (msg, ent->v->effects);
849                 if (bits & U_ORIGIN1)   MSG_WriteDPCoord (msg, origin[0]);
850                 if (bits & U_ANGLE1)    MSG_WriteAngle(msg, angles[0]);
851                 if (bits & U_ORIGIN2)   MSG_WriteDPCoord (msg, origin[1]);
852                 if (bits & U_ANGLE2)    MSG_WriteAngle(msg, angles[1]);
853                 if (bits & U_ORIGIN3)   MSG_WriteDPCoord (msg, origin[2]);
854                 if (bits & U_ANGLE3)    MSG_WriteAngle(msg, angles[2]);
855
856                 // LordHavoc: new stuff
857                 if (bits & U_ALPHA)             MSG_WriteByte(msg, alpha);
858                 if (bits & U_SCALE)             MSG_WriteByte(msg, scale);
859                 if (bits & U_EFFECTS2)  MSG_WriteByte(msg, (int)ent->v->effects >> 8);
860                 if (bits & U_GLOWSIZE)  MSG_WriteByte(msg, glowsize);
861                 if (bits & U_GLOWCOLOR) MSG_WriteByte(msg, glowcolor);
862                 if (bits & U_FRAME2)    MSG_WriteByte(msg, (int)ent->v->frame >> 8);
863                 if (bits & U_MODEL2)    MSG_WriteByte(msg, (int)ent->v->modelindex >> 8);
864         }
865
866         if (sv_cullentities_stats.integer)
867                 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d portal %d trace\n", client->name, totalentities, visibleentities, culled_pvs + culled_portal + culled_trace, culled_pvs, culled_portal, culled_trace);
868 }
869 #else
870 void SV_WriteEntitiesToClient (client_t *client, edict_t *clent, sizebuf_t *msg)
871 {
872         int e, clentnum, flags, alpha, glowcolor, glowsize, scale, effects, modelindex;
873         int culled_pvs, culled_portal, culled_trace, visibleentities, totalentities;
874         float alphaf, lightsize;
875         qbyte *pvs;
876         vec3_t origin, angles, entmins, entmaxs, lightmins, lightmaxs, testorigin, testeye;
877         edict_t *ent;
878         eval_t *val;
879         trace_t trace;
880         model_t *model;
881         entity_frame_t entityframe;
882         entity_state_t *s;
883
884         if (client->sendsignon)
885                 return;
886
887         Mod_CheckLoaded(sv.worldmodel);
888
889 // find the client's PVS
890         // the real place being tested from
891         VectorAdd (clent->v->origin, clent->v->view_ofs, testeye);
892         pvs = SV_FatPVS (testeye);
893
894         // the place being reported (to consider the fact the client still
895         // applies the view_ofs[2], so we have to only send the fractional part
896         // of view_ofs[2], undoing what the client will redo)
897         VectorCopy (testeye, testorigin);
898         e = (int) clent->v->view_ofs[2] & 255;
899         if (e >= 128)
900                 e -= 256;
901         testorigin[2] -= (float) e;
902         EntityFrame_Clear(&entityframe, testorigin);
903
904         culled_pvs = 0;
905         culled_portal = 0;
906         culled_trace = 0;
907         visibleentities = 0;
908         totalentities = 0;
909
910         clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
911         // send all entities that touch the pvs
912         ent = NEXT_EDICT(sv.edicts);
913         for (e = 1;e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
914         {
915                 if (ent->free)
916                         continue;
917                 flags = 0;
918
919                 if (ent != clent) // LordHavoc: always send player
920                 {
921                         if ((val = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)) && val->edict)
922                         {
923                                 if (val->edict == clentnum)
924                                         flags |= RENDER_VIEWMODEL; // show relative to the view
925                                 else
926                                 {
927                                         // don't show to anyone else
928                                         continue;
929                                 }
930                         }
931                         else
932                         {
933                                 // LordHavoc: never draw something told not to display to this client
934                                 if ((val = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)) && val->edict == clentnum)
935                                         continue;
936                                 if ((val = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)) && val->edict && val->edict != clentnum)
937                                         continue;
938                         }
939                 }
940
941                 glowsize = 0;
942                 effects = ent->v->effects;
943                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_size)))
944                         glowsize = (int) val->_float >> 2;
945                 glowsize = bound(0, glowsize, 255);
946
947                 lightsize = 0;
948                 if (effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
949                 {
950                         if (effects & EF_BRIGHTFIELD)
951                                 lightsize = max(lightsize, 80);
952                         if (effects & EF_MUZZLEFLASH)
953                                 lightsize = max(lightsize, 100);
954                         if (effects & EF_BRIGHTLIGHT)
955                                 lightsize = max(lightsize, 400);
956                         if (effects & EF_DIMLIGHT)
957                                 lightsize = max(lightsize, 200);
958                         if (effects & EF_RED)
959                                 lightsize = max(lightsize, 200);
960                         if (effects & EF_BLUE)
961                                 lightsize = max(lightsize, 200);
962                         if (effects & EF_FLAME)
963                                 lightsize = max(lightsize, 250);
964                         if (effects & EF_STARDUST)
965                                 lightsize = max(lightsize, 100);
966                 }
967                 if (glowsize)
968                         lightsize = max(lightsize, glowsize << 2);
969
970                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_trail)))
971                 if (val->_float != 0)
972                 {
973                         flags |= RENDER_GLOWTRAIL;
974                         lightsize = max(lightsize, 100);
975                 }
976
977                 modelindex = 0;
978                 if (ent->v->modelindex >= 0 && ent->v->modelindex < MAX_MODELS && *PR_GetString(ent->v->model))
979                 {
980                         modelindex = ent->v->modelindex;
981                         model = sv.models[(int)ent->v->modelindex];
982                         Mod_CheckLoaded(model);
983                 }
984                 else
985                 {
986                         model = NULL;
987                         if (ent != clent) // LordHavoc: always send player
988                                 if (lightsize == 0) // no effects
989                                         continue;
990                 }
991
992                 VectorCopy(ent->v->angles, angles);
993                 if (DotProduct(ent->v->velocity, ent->v->velocity) >= 1.0f && host_client->latency >= 0.01f)
994                 {
995                         VectorMA(ent->v->origin, host_client->latency, ent->v->velocity, origin);
996                         // LordHavoc: trace predicted movement to avoid putting things in walls
997                         trace = SV_Move (ent->v->origin, ent->v->mins, ent->v->maxs, origin, MOVE_NORMAL, ent);
998                         VectorCopy(trace.endpos, origin);
999                 }
1000                 else
1001                 {
1002                         VectorCopy(ent->v->origin, origin);
1003                 }
1004
1005                 // ent has survived every check so far, check if it is visible
1006                 // always send embedded brush models, they don't generate much traffic
1007                 if (ent != clent && ((flags & RENDER_VIEWMODEL) == 0) && (model == NULL || model->type != mod_brush || model->name[0] != '*'))
1008                 {
1009                         // use the predicted origin
1010                         entmins[0] = origin[0] - 1.0f;
1011                         entmins[1] = origin[1] - 1.0f;
1012                         entmins[2] = origin[2] - 1.0f;
1013                         entmaxs[0] = origin[0] + 1.0f;
1014                         entmaxs[1] = origin[1] + 1.0f;
1015                         entmaxs[2] = origin[2] + 1.0f;
1016                         // using the model's bounding box to ensure things are visible regardless of their physics box
1017                         if (model)
1018                         {
1019                                 if (ent->v->angles[0] || ent->v->angles[2]) // pitch and roll
1020                                 {
1021                                         VectorAdd(entmins, model->rotatedmins, entmins);
1022                                         VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
1023                                 }
1024                                 else if (ent->v->angles[1])
1025                                 {
1026                                         VectorAdd(entmins, model->yawmins, entmins);
1027                                         VectorAdd(entmaxs, model->yawmaxs, entmaxs);
1028                                 }
1029                                 else
1030                                 {
1031                                         VectorAdd(entmins, model->normalmins, entmins);
1032                                         VectorAdd(entmaxs, model->normalmaxs, entmaxs);
1033                                 }
1034                         }
1035                         lightmins[0] = min(entmins[0], origin[0] - lightsize);
1036                         lightmins[1] = min(entmins[1], origin[1] - lightsize);
1037                         lightmins[2] = min(entmins[2], origin[2] - lightsize);
1038                         lightmaxs[0] = min(entmaxs[0], origin[0] + lightsize);
1039                         lightmaxs[1] = min(entmaxs[1], origin[1] + lightsize);
1040                         lightmaxs[2] = min(entmaxs[2], origin[2] + lightsize);
1041
1042                         totalentities++;
1043
1044                         // if not touching a visible leaf
1045                         if (sv_cullentities_pvs.integer && !SV_BoxTouchingPVS(pvs, lightmins, lightmaxs, sv.worldmodel->nodes))
1046                         {
1047                                 culled_pvs++;
1048                                 continue;
1049                         }
1050
1051                         // or not visible through the portals
1052                         if (sv_cullentities_portal.integer && !Portal_CheckBox(sv.worldmodel, testeye, lightmins, lightmaxs))
1053                         {
1054                                 culled_portal++;
1055                                 continue;
1056                         }
1057
1058                         if (sv_cullentities_trace.integer)
1059                         {
1060                                 // LordHavoc: test center first
1061                                 testorigin[0] = (entmins[0] + entmaxs[0]) * 0.5f;
1062                                 testorigin[1] = (entmins[1] + entmaxs[1]) * 0.5f;
1063                                 testorigin[2] = (entmins[2] + entmaxs[2]) * 0.5f;
1064                                 Collision_ClipTrace(&trace, NULL, sv.worldmodel, vec3_origin, vec3_origin, vec3_origin, vec3_origin, testeye, vec3_origin, vec3_origin, testorigin);
1065                                 if (trace.fraction == 1)
1066                                         client->visibletime[e] = realtime + 1;
1067                                 else
1068                                 {
1069                                         // LordHavoc: test random offsets, to maximize chance of detection
1070                                         testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
1071                                         testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
1072                                         testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
1073                                         Collision_ClipTrace(&trace, NULL, sv.worldmodel, vec3_origin, vec3_origin, vec3_origin, vec3_origin, testeye, vec3_origin, vec3_origin, testorigin);
1074                                         if (trace.fraction == 1)
1075                                                 client->visibletime[e] = realtime + 1;
1076                                         else
1077                                         {
1078                                                 if (lightsize)
1079                                                 {
1080                                                         // LordHavoc: test random offsets, to maximize chance of detection
1081                                                         testorigin[0] = lhrandom(lightmins[0], lightmaxs[0]);
1082                                                         testorigin[1] = lhrandom(lightmins[1], lightmaxs[1]);
1083                                                         testorigin[2] = lhrandom(lightmins[2], lightmaxs[2]);
1084                                                         Collision_ClipTrace(&trace, NULL, sv.worldmodel, vec3_origin, vec3_origin, vec3_origin, vec3_origin, testeye, vec3_origin, vec3_origin, testorigin);
1085                                                         if (trace.fraction == 1)
1086                                                                 client->visibletime[e] = realtime + 1;
1087                                                         else
1088                                                         {
1089                                                                 if (realtime > client->visibletime[e])
1090                                                                 {
1091                                                                         culled_trace++;
1092                                                                         continue;
1093                                                                 }
1094                                                         }
1095                                                 }
1096                                                 else
1097                                                 {
1098                                                         if (realtime > client->visibletime[e])
1099                                                         {
1100                                                                 culled_trace++;
1101                                                                 continue;
1102                                                         }
1103                                                 }
1104                                         }
1105                                 }
1106                         }
1107                         visibleentities++;
1108                 }
1109
1110                 alphaf = 255.0f;
1111                 scale = 16;
1112                 glowcolor = 254;
1113                 effects = ent->v->effects;
1114
1115                 if ((val = GETEDICTFIELDVALUE(ent, eval_alpha)))
1116                 if (val->_float != 0)
1117                         alphaf = val->_float * 255.0;
1118
1119                 // HalfLife support
1120                 if ((val = GETEDICTFIELDVALUE(ent, eval_renderamt)))
1121                 if (val->_float != 0)
1122                         alphaf = val->_float;
1123
1124                 if (alphaf == 0.0f)
1125                         alphaf = 255.0f;
1126                 alpha = bound(0, alphaf, 255);
1127
1128                 if ((val = GETEDICTFIELDVALUE(ent, eval_scale)))
1129                 if ((scale = (int) (val->_float * 16.0)) == 0) scale = 16;
1130                 if (scale < 0) scale = 0;
1131                 if (scale > 255) scale = 255;
1132
1133                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_color)))
1134                 if (val->_float != 0)
1135                         glowcolor = (int) val->_float;
1136
1137                 if ((val = GETEDICTFIELDVALUE(ent, eval_fullbright)))
1138                 if (val->_float != 0)
1139                         effects |= EF_FULLBRIGHT;
1140
1141                 if (ent != clent)
1142                 {
1143                         if (lightsize == 0) // no effects
1144                         {
1145                                 if (model) // model
1146                                 {
1147                                         // don't send if flagged for NODRAW and there are no effects
1148                                         if (model->flags == 0 && ((effects & EF_NODRAW) || scale <= 0 || alpha <= 0))
1149                                                 continue;
1150                                 }
1151                                 else // no model and no effects
1152                                         continue;
1153                         }
1154                 }
1155
1156                 if ((val = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)) && val->edict == clentnum)
1157                         flags |= RENDER_EXTERIORMODEL;
1158
1159                 if (ent->v->movetype == MOVETYPE_STEP)
1160                         flags |= RENDER_STEP;
1161                 // don't send an entity if it's coordinates would wrap around
1162                 if ((effects & EF_LOWPRECISION) && origin[0] >= -32768 && origin[1] >= -32768 && origin[2] >= -32768 && origin[0] <= 32767 && origin[1] <= 32767 && origin[2] <= 32767)
1163                         flags |= RENDER_LOWPRECISION;
1164
1165                 s = EntityFrame_NewEntity(&entityframe, e);
1166                 // if we run out of space, abort
1167                 if (!s)
1168                         break;
1169                 VectorCopy(origin, s->origin);
1170                 VectorCopy(angles, s->angles);
1171                 if (ent->v->colormap >= 1024)
1172                         flags |= RENDER_COLORMAPPED;
1173                 s->colormap = ent->v->colormap;
1174                 s->skin = ent->v->skin;
1175                 s->frame = ent->v->frame;
1176                 s->modelindex = modelindex;
1177                 s->effects = effects;
1178                 s->alpha = alpha;
1179                 s->scale = scale;
1180                 s->glowsize = glowsize;
1181                 s->glowcolor = glowcolor;
1182                 s->flags = flags;
1183         }
1184         entityframe.framenum = ++client->entityframenumber;
1185         EntityFrame_Write(&client->entitydatabase, &entityframe, msg);
1186
1187         if (sv_cullentities_stats.integer)
1188                 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d portal %d trace\n", client->name, totalentities, visibleentities, culled_pvs + culled_portal + culled_trace, culled_pvs, culled_portal, culled_trace);
1189 }
1190 #endif
1191
1192 /*
1193 =============
1194 SV_CleanupEnts
1195
1196 =============
1197 */
1198 void SV_CleanupEnts (void)
1199 {
1200         int             e;
1201         edict_t *ent;
1202
1203         ent = NEXT_EDICT(sv.edicts);
1204         for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
1205                 ent->v->effects = (int)ent->v->effects & ~EF_MUZZLEFLASH;
1206 }
1207
1208 /*
1209 ==================
1210 SV_WriteClientdataToMessage
1211
1212 ==================
1213 */
1214 void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
1215 {
1216         int             bits;
1217         int             i;
1218         edict_t *other;
1219         int             items;
1220         eval_t  *val;
1221         vec3_t  punchvector;
1222         qbyte   viewzoom;
1223
1224 //
1225 // send a damage message
1226 //
1227         if (ent->v->dmg_take || ent->v->dmg_save)
1228         {
1229                 other = PROG_TO_EDICT(ent->v->dmg_inflictor);
1230                 MSG_WriteByte (msg, svc_damage);
1231                 MSG_WriteByte (msg, ent->v->dmg_save);
1232                 MSG_WriteByte (msg, ent->v->dmg_take);
1233                 for (i=0 ; i<3 ; i++)
1234                         MSG_WriteDPCoord (msg, other->v->origin[i] + 0.5*(other->v->mins[i] + other->v->maxs[i]));
1235
1236                 ent->v->dmg_take = 0;
1237                 ent->v->dmg_save = 0;
1238         }
1239
1240 //
1241 // send the current viewpos offset from the view entity
1242 //
1243         SV_SetIdealPitch ();            // how much to look up / down ideally
1244
1245 // a fixangle might get lost in a dropped packet.  Oh well.
1246         if ( ent->v->fixangle )
1247         {
1248                 MSG_WriteByte (msg, svc_setangle);
1249                 for (i=0 ; i < 3 ; i++)
1250                         MSG_WriteAngle (msg, ent->v->angles[i] );
1251                 ent->v->fixangle = 0;
1252         }
1253
1254         bits = 0;
1255
1256         if (ent->v->view_ofs[2] != DEFAULT_VIEWHEIGHT)
1257                 bits |= SU_VIEWHEIGHT;
1258
1259         if (ent->v->idealpitch)
1260                 bits |= SU_IDEALPITCH;
1261
1262 // stuff the sigil bits into the high bits of items for sbar, or else
1263 // mix in items2
1264         val = GETEDICTFIELDVALUE(ent, eval_items2);
1265
1266         if (val)
1267                 items = (int)ent->v->items | ((int)val->_float << 23);
1268         else
1269                 items = (int)ent->v->items | ((int)pr_global_struct->serverflags << 28);
1270
1271         bits |= SU_ITEMS;
1272
1273         if ( (int)ent->v->flags & FL_ONGROUND)
1274                 bits |= SU_ONGROUND;
1275
1276         if ( ent->v->waterlevel >= 2)
1277                 bits |= SU_INWATER;
1278
1279         // dpprotocol
1280         VectorClear(punchvector);
1281         if ((val = GETEDICTFIELDVALUE(ent, eval_punchvector)))
1282                 VectorCopy(val->vector, punchvector);
1283
1284         i = 255;
1285         if ((val = GETEDICTFIELDVALUE(ent, eval_viewzoom)))
1286         {
1287                 i = val->_float * 255.0f;
1288                 if (i == 0)
1289                         i = 255;
1290                 else
1291                         i = bound(0, i, 255);
1292         }
1293         viewzoom = i;
1294
1295         if (viewzoom != 255)
1296                 bits |= SU_VIEWZOOM;
1297
1298         for (i=0 ; i<3 ; i++)
1299         {
1300                 if (ent->v->punchangle[i])
1301                         bits |= (SU_PUNCH1<<i);
1302                 if (punchvector[i]) // dpprotocol
1303                         bits |= (SU_PUNCHVEC1<<i); // dpprotocol
1304                 if (ent->v->velocity[i])
1305                         bits |= (SU_VELOCITY1<<i);
1306         }
1307
1308         if (ent->v->weaponframe)
1309                 bits |= SU_WEAPONFRAME;
1310
1311         if (ent->v->armorvalue)
1312                 bits |= SU_ARMOR;
1313
1314         bits |= SU_WEAPON;
1315
1316         if (bits >= 65536)
1317                 bits |= SU_EXTEND1;
1318         if (bits >= 16777216)
1319                 bits |= SU_EXTEND2;
1320
1321 // send the data
1322
1323         MSG_WriteByte (msg, svc_clientdata);
1324         MSG_WriteShort (msg, bits);
1325         if (bits & SU_EXTEND1)
1326                 MSG_WriteByte(msg, bits >> 16);
1327         if (bits & SU_EXTEND2)
1328                 MSG_WriteByte(msg, bits >> 24);
1329
1330         if (bits & SU_VIEWHEIGHT)
1331                 MSG_WriteChar (msg, ent->v->view_ofs[2]);
1332
1333         if (bits & SU_IDEALPITCH)
1334                 MSG_WriteChar (msg, ent->v->idealpitch);
1335
1336         for (i=0 ; i<3 ; i++)
1337         {
1338                 if (bits & (SU_PUNCH1<<i))
1339                         MSG_WritePreciseAngle(msg, ent->v->punchangle[i]); // dpprotocol
1340                 if (bits & (SU_PUNCHVEC1<<i)) // dpprotocol
1341                         MSG_WriteDPCoord(msg, punchvector[i]); // dpprotocol
1342                 if (bits & (SU_VELOCITY1<<i))
1343                         MSG_WriteChar (msg, ent->v->velocity[i]/16);
1344         }
1345
1346 // [always sent]        if (bits & SU_ITEMS)
1347         MSG_WriteLong (msg, items);
1348
1349         if (bits & SU_WEAPONFRAME)
1350                 MSG_WriteByte (msg, ent->v->weaponframe);
1351         if (bits & SU_ARMOR)
1352                 MSG_WriteByte (msg, ent->v->armorvalue);
1353         if (bits & SU_WEAPON)
1354                 MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v->weaponmodel)));
1355
1356         MSG_WriteShort (msg, ent->v->health);
1357         MSG_WriteByte (msg, ent->v->currentammo);
1358         MSG_WriteByte (msg, ent->v->ammo_shells);
1359         MSG_WriteByte (msg, ent->v->ammo_nails);
1360         MSG_WriteByte (msg, ent->v->ammo_rockets);
1361         MSG_WriteByte (msg, ent->v->ammo_cells);
1362
1363         if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE)
1364         {
1365                 for(i=0;i<32;i++)
1366                 {
1367                         if ( ((int)ent->v->weapon) & (1<<i) )
1368                         {
1369                                 MSG_WriteByte (msg, i);
1370                                 break;
1371                         }
1372                 }
1373         }
1374         else
1375         {
1376                 MSG_WriteByte (msg, ent->v->weapon);
1377         }
1378
1379         if (bits & SU_VIEWZOOM)
1380                 MSG_WriteByte (msg, viewzoom);
1381 }
1382
1383 /*
1384 =======================
1385 SV_SendClientDatagram
1386 =======================
1387 */
1388 static qbyte sv_sendclientdatagram_buf[MAX_DATAGRAM]; // FIXME?
1389 qboolean SV_SendClientDatagram (client_t *client)
1390 {
1391         sizebuf_t       msg;
1392
1393         msg.data = sv_sendclientdatagram_buf;
1394         msg.maxsize = sizeof(sv_sendclientdatagram_buf);
1395         msg.cursize = 0;
1396
1397         MSG_WriteByte (&msg, svc_time);
1398         MSG_WriteFloat (&msg, sv.time);
1399
1400         if (client->spawned)
1401         {
1402                 // add the client specific data to the datagram
1403                 SV_WriteClientdataToMessage (client->edict, &msg);
1404
1405                 SV_WriteEntitiesToClient (client, client->edict, &msg);
1406
1407                 // copy the server datagram if there is space
1408                 if (msg.cursize + sv.datagram.cursize < msg.maxsize)
1409                         SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
1410         }
1411
1412 // send the datagram
1413         if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1)
1414         {
1415                 SV_DropClient (true);// if the message couldn't send, kick off
1416                 return false;
1417         }
1418
1419         return true;
1420 }
1421
1422 /*
1423 =======================
1424 SV_UpdateToReliableMessages
1425 =======================
1426 */
1427 void SV_UpdateToReliableMessages (void)
1428 {
1429         int                     i, j;
1430         client_t *client;
1431
1432 // check for changes to be sent over the reliable streams
1433         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1434         {
1435                 if (host_client->old_frags != host_client->edict->v->frags)
1436                 {
1437                         for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
1438                         {
1439                                 if (!client->active || !client->spawned)
1440                                         continue;
1441                                 MSG_WriteByte (&client->message, svc_updatefrags);
1442                                 MSG_WriteByte (&client->message, i);
1443                                 MSG_WriteShort (&client->message, host_client->edict->v->frags);
1444                         }
1445
1446                         host_client->old_frags = host_client->edict->v->frags;
1447                 }
1448         }
1449
1450         for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
1451         {
1452                 if (!client->active)
1453                         continue;
1454                 SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1455         }
1456
1457         SZ_Clear (&sv.reliable_datagram);
1458 }
1459
1460
1461 /*
1462 =======================
1463 SV_SendNop
1464
1465 Send a nop message without trashing or sending the accumulated client
1466 message buffer
1467 =======================
1468 */
1469 void SV_SendNop (client_t *client)
1470 {
1471         sizebuf_t       msg;
1472         qbyte           buf[4];
1473
1474         msg.data = buf;
1475         msg.maxsize = sizeof(buf);
1476         msg.cursize = 0;
1477
1478         MSG_WriteChar (&msg, svc_nop);
1479
1480         if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1)
1481                 SV_DropClient (true);   // if the message couldn't send, kick off
1482         client->last_message = realtime;
1483 }
1484
1485 /*
1486 =======================
1487 SV_SendClientMessages
1488 =======================
1489 */
1490 void SV_SendClientMessages (void)
1491 {
1492         int                     i;
1493
1494 // update frags, names, etc
1495         SV_UpdateToReliableMessages ();
1496
1497 // build individual updates
1498         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1499         {
1500                 if (!host_client->active)
1501                         continue;
1502
1503 #ifndef NOROUTINGFIX
1504                 if (host_client->sendserverinfo)
1505                 {
1506                         host_client->sendserverinfo = false;
1507                         SV_SendServerinfo (host_client);
1508                 }
1509 #endif
1510
1511                 if (host_client->spawned)
1512                 {
1513                         if (!SV_SendClientDatagram (host_client))
1514                                 continue;
1515                 }
1516                 else
1517                 {
1518                 // the player isn't totally in the game yet
1519                 // send small keepalive messages if too much time has passed
1520                 // send a full message when the next signon stage has been requested
1521                 // some other message data (name changes, etc) may accumulate
1522                 // between signon stages
1523                         if (!host_client->sendsignon)
1524                         {
1525                                 if (realtime - host_client->last_message > 5)
1526                                         SV_SendNop (host_client);
1527                                 continue;       // don't send out non-signon messages
1528                         }
1529                 }
1530
1531                 // check for an overflowed message.  Should only happen
1532                 // on a very fucked up connection that backs up a lot, then
1533                 // changes level
1534                 if (host_client->message.overflowed)
1535                 {
1536                         SV_DropClient (true);
1537                         host_client->message.overflowed = false;
1538                         continue;
1539                 }
1540
1541                 if (host_client->message.cursize || host_client->dropasap)
1542                 {
1543                         if (!NET_CanSendMessage (host_client->netconnection))
1544                                 continue;
1545
1546                         if (host_client->dropasap)
1547                                 SV_DropClient (false);  // went to another level
1548                         else
1549                         {
1550                                 if (NET_SendMessage (host_client->netconnection, &host_client->message) == -1)
1551                                         SV_DropClient (true);   // if the message couldn't send, kick off
1552                                 SZ_Clear (&host_client->message);
1553                                 host_client->last_message = realtime;
1554                                 host_client->sendsignon = false;
1555                         }
1556                 }
1557         }
1558
1559
1560 // clear muzzle flashes
1561         SV_CleanupEnts ();
1562 }
1563
1564
1565 /*
1566 ==============================================================================
1567
1568 SERVER SPAWNING
1569
1570 ==============================================================================
1571 */
1572
1573 /*
1574 ================
1575 SV_ModelIndex
1576
1577 ================
1578 */
1579 int SV_ModelIndex (const char *name)
1580 {
1581         int i;
1582
1583         if (!name || !name[0])
1584                 return 0;
1585
1586         for (i=0 ; i<MAX_MODELS && sv.model_precache[i] ; i++)
1587                 if (!strcmp(sv.model_precache[i], name))
1588                         return i;
1589         if (i==MAX_MODELS || !sv.model_precache[i])
1590                 Host_Error ("SV_ModelIndex: model %s not precached", name);
1591         return i;
1592 }
1593
1594 #ifdef SV_QUAKEENTITIES
1595 /*
1596 ================
1597 SV_CreateBaseline
1598
1599 ================
1600 */
1601 void SV_CreateBaseline (void)
1602 {
1603         int i, entnum, large;
1604         edict_t *svent;
1605
1606         // LordHavoc: clear *all* states (note just active ones)
1607         for (entnum = 0;entnum < sv.max_edicts;entnum++)
1608         {
1609                 // get the current server version
1610                 svent = EDICT_NUM(entnum);
1611
1612                 // LordHavoc: always clear state values, whether the entity is in use or not
1613                 ClearStateToDefault(&svent->baseline);
1614
1615                 if (svent->free)
1616                         continue;
1617                 if (entnum > svs.maxclients && !svent->v->modelindex)
1618                         continue;
1619
1620                 // create entity baseline
1621                 VectorCopy (svent->v->origin, svent->baseline.origin);
1622                 VectorCopy (svent->v->angles, svent->baseline.angles);
1623                 svent->baseline.frame = svent->v->frame;
1624                 svent->baseline.skin = svent->v->skin;
1625                 if (entnum > 0 && entnum <= svs.maxclients)
1626                 {
1627                         svent->baseline.colormap = entnum;
1628                         svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
1629                 }
1630                 else
1631                 {
1632                         svent->baseline.colormap = 0;
1633                         svent->baseline.modelindex = svent->v->modelindex;
1634                 }
1635
1636                 large = false;
1637                 if (svent->baseline.modelindex & 0xFF00 || svent->baseline.frame & 0xFF00)
1638                         large = true;
1639
1640                 // add to the message
1641                 if (large)
1642                         MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1643                 else
1644                         MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1645                 MSG_WriteShort (&sv.signon, entnum);
1646
1647                 if (large)
1648                 {
1649                         MSG_WriteShort (&sv.signon, svent->baseline.modelindex);
1650                         MSG_WriteShort (&sv.signon, svent->baseline.frame);
1651                 }
1652                 else
1653                 {
1654                         MSG_WriteByte (&sv.signon, svent->baseline.modelindex);
1655                         MSG_WriteByte (&sv.signon, svent->baseline.frame);
1656                 }
1657                 MSG_WriteByte (&sv.signon, svent->baseline.colormap);
1658                 MSG_WriteByte (&sv.signon, svent->baseline.skin);
1659                 for (i=0 ; i<3 ; i++)
1660                 {
1661                         MSG_WriteDPCoord(&sv.signon, svent->baseline.origin[i]);
1662                         MSG_WriteAngle(&sv.signon, svent->baseline.angles[i]);
1663                 }
1664         }
1665 }
1666 #endif
1667
1668
1669 /*
1670 ================
1671 SV_SendReconnect
1672
1673 Tell all the clients that the server is changing levels
1674 ================
1675 */
1676 void SV_SendReconnect (void)
1677 {
1678         char    data[128];
1679         sizebuf_t       msg;
1680
1681         msg.data = data;
1682         msg.cursize = 0;
1683         msg.maxsize = sizeof(data);
1684
1685         MSG_WriteChar (&msg, svc_stufftext);
1686         MSG_WriteString (&msg, "reconnect\n");
1687         NET_SendToAll (&msg, 5);
1688
1689         if (cls.state != ca_dedicated)
1690                 Cmd_ExecuteString ("reconnect\n", src_command);
1691 }
1692
1693
1694 /*
1695 ================
1696 SV_SaveSpawnparms
1697
1698 Grabs the current state of each client for saving across the
1699 transition to another level
1700 ================
1701 */
1702 void SV_SaveSpawnparms (void)
1703 {
1704         int             i, j;
1705
1706         svs.serverflags = pr_global_struct->serverflags;
1707
1708         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1709         {
1710                 if (!host_client->active)
1711                         continue;
1712
1713         // call the progs to get default spawn parms for the new client
1714                 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
1715                 PR_ExecuteProgram (pr_global_struct->SetChangeParms, "QC function SetChangeParms is missing");
1716                 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1717                         host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
1718         }
1719 }
1720
1721 /*
1722 ================
1723 SV_SpawnServer
1724
1725 This is called at the start of each level
1726 ================
1727 */
1728 extern float            scr_centertime_off;
1729
1730 void SV_SpawnServer (const char *server)
1731 {
1732         edict_t         *ent;
1733         int                     i;
1734
1735         // let's not have any servers with no name
1736         if (hostname.string[0] == 0)
1737                 Cvar_Set ("hostname", "UNNAMED");
1738         scr_centertime_off = 0;
1739
1740         Con_DPrintf ("SpawnServer: %s\n",server);
1741         svs.changelevel_issued = false;         // now safe to issue another
1742
1743 //
1744 // tell all connected clients that we are going to a new level
1745 //
1746         if (sv.active)
1747                 SV_SendReconnect ();
1748
1749 //
1750 // make cvars consistant
1751 //
1752         if (coop.integer)
1753                 Cvar_SetValue ("deathmatch", 0);
1754         current_skill = bound(0, (int)(skill.value + 0.5), 3);
1755
1756         Cvar_SetValue ("skill", (float)current_skill);
1757
1758 //
1759 // set up the new server
1760 //
1761         Host_ClearMemory ();
1762
1763         memset (&sv, 0, sizeof(sv));
1764
1765         strcpy (sv.name, server);
1766
1767 // load progs to get entity field count
1768         PR_LoadProgs ();
1769
1770 // allocate server memory
1771         sv.max_edicts = MAX_EDICTS;
1772
1773         // clear the edict memory pool
1774         Mem_EmptyPool(sv_edicts_mempool);
1775         // edict_t structures (hidden from progs)
1776         sv.edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t));
1777         // progs fields, often accessed by server
1778         sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1779         // table of edict pointers, for quicker lookup of edicts
1780         sv.edictstable = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1781         // used by PushMove to move back pushed entities
1782         sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1783         for (i = 0;i < sv.max_edicts;i++)
1784         {
1785                 ent = sv.edicts + i;
1786                 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1787                 sv.edictstable[i] = ent;
1788         }
1789
1790         sv.datagram.maxsize = sizeof(sv.datagram_buf);
1791         sv.datagram.cursize = 0;
1792         sv.datagram.data = sv.datagram_buf;
1793
1794         sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1795         sv.reliable_datagram.cursize = 0;
1796         sv.reliable_datagram.data = sv.reliable_datagram_buf;
1797
1798         sv.signon.maxsize = sizeof(sv.signon_buf);
1799         sv.signon.cursize = 0;
1800         sv.signon.data = sv.signon_buf;
1801
1802 // leave slots at start for clients only
1803         sv.num_edicts = svs.maxclients+1;
1804         for (i=0 ; i<svs.maxclients ; i++)
1805         {
1806                 ent = EDICT_NUM(i+1);
1807                 svs.clients[i].edict = ent;
1808         }
1809
1810         sv.state = ss_loading;
1811         sv.paused = false;
1812
1813         sv.time = 1.0;
1814
1815         Mod_ClearUsed();
1816
1817         strcpy (sv.name, server);
1818         sprintf (sv.modelname,"maps/%s.bsp", server);
1819         sv.worldmodel = Mod_ForName(sv.modelname, false, true, true);
1820         if (!sv.worldmodel)
1821         {
1822                 Con_Printf ("Couldn't spawn server %s\n", sv.modelname);
1823                 sv.active = false;
1824                 return;
1825         }
1826         sv.models[1] = sv.worldmodel;
1827
1828 //
1829 // clear world interaction links
1830 //
1831         SV_ClearWorld ();
1832
1833         sv.sound_precache[0] = "";
1834
1835         sv.model_precache[0] = "";
1836         sv.model_precache[1] = sv.modelname;
1837         for (i = 1;i < sv.worldmodel->numsubmodels;i++)
1838         {
1839                 sv.model_precache[i+1] = localmodels[i];
1840                 sv.models[i+1] = Mod_ForName (localmodels[i], false, false, false);
1841         }
1842
1843 //
1844 // load the rest of the entities
1845 //
1846         ent = EDICT_NUM(0);
1847         memset (ent->v, 0, progs->entityfields * 4);
1848         ent->free = false;
1849         ent->v->model = PR_SetString(sv.modelname);
1850         ent->v->modelindex = 1;         // world model
1851         ent->v->solid = SOLID_BSP;
1852         ent->v->movetype = MOVETYPE_PUSH;
1853
1854         if (coop.integer)
1855                 pr_global_struct->coop = coop.integer;
1856         else
1857                 pr_global_struct->deathmatch = deathmatch.integer;
1858
1859         pr_global_struct->mapname = PR_SetString(sv.name);
1860
1861 // serverflags are for cross level information (sigils)
1862         pr_global_struct->serverflags = svs.serverflags;
1863
1864         ED_LoadFromFile (sv.worldmodel->entities);
1865         // LordHavoc: clear world angles (to fix e3m3.bsp)
1866         VectorClear(sv.edicts->v->angles);
1867
1868         sv.active = true;
1869
1870 // all setup is completed, any further precache statements are errors
1871         sv.state = ss_active;
1872
1873 // run two frames to allow everything to settle
1874         sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1875         SV_Physics ();
1876         sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1877         SV_Physics ();
1878
1879         Mod_PurgeUnused();
1880
1881 #ifdef QUAKEENTITIES
1882 // create a baseline for more efficient communications
1883         SV_CreateBaseline ();
1884 #endif
1885
1886 // send serverinfo to all connected clients
1887         for (i=0,host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1888                 if (host_client->active)
1889                         SV_SendServerinfo (host_client);
1890
1891         Con_DPrintf ("Server spawned.\n");
1892         NET_Heartbeat (2);
1893 }
1894