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