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