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