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