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