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