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