]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - sv_main.c
added MAX_PACKETFRAGMENT to limit size of reliable packets, and also try to keep...
[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         eval_t *val;
811         // send all entities that touch the pvs
812         numsendentities = 0;
813         sendentitiesindex[0] = NULL;
814         for (e = 1, ent = NEXT_EDICT(sv.edicts);e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
815         {
816                 sendentitiesindex[e] = NULL;
817                 if (ent->e->free)
818                         continue;
819
820                 ClearStateToDefault(&cs);
821                 cs.active = true;
822                 cs.number = e;
823                 VectorCopy(ent->v->origin, cs.origin);
824                 VectorCopy(ent->v->angles, cs.angles);
825                 cs.flags = 0;
826                 cs.effects = (int)ent->v->effects;
827                 cs.colormap = (qbyte)ent->v->colormap;
828                 cs.skin = (qbyte)ent->v->skin;
829                 cs.frame = (qbyte)ent->v->frame;
830                 cs.viewmodelforclient = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)->edict;
831                 cs.exteriormodelforclient = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)->edict;
832                 cs.nodrawtoclient = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)->edict;
833                 cs.drawonlytoclient = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)->edict;
834                 cs.tagentity = GETEDICTFIELDVALUE(ent, eval_tag_entity)->edict;
835                 cs.tagindex = (qbyte)GETEDICTFIELDVALUE(ent, eval_tag_index)->_float;
836                 i = (int)(GETEDICTFIELDVALUE(ent, eval_glow_size)->_float * 0.25f);
837                 cs.glowsize = (qbyte)bound(0, i, 255);
838                 if (GETEDICTFIELDVALUE(ent, eval_glow_trail)->_float)
839                         cs.flags |= RENDER_GLOWTRAIL;
840
841                 cs.modelindex = 0;
842                 i = (int)ent->v->modelindex;
843                 if (i >= 1 && i < MAX_MODELS && *PR_GetString(ent->v->model))
844                         cs.modelindex = i;
845
846
847                 cs.alpha = 255;
848                 i = (int)(GETEDICTFIELDVALUE(ent, eval_alpha)->_float * 255.0f);
849                 if (i)
850                         cs.alpha = (qbyte)bound(0, i, 255);
851                 // halflife
852                 i = (int)(GETEDICTFIELDVALUE(ent, eval_renderamt)->_float);
853                 if (i)
854                         cs.alpha = (qbyte)bound(0, i, 255);
855
856                 cs.scale = 16;
857                 i = (int)(GETEDICTFIELDVALUE(ent, eval_scale)->_float * 16.0f);
858                 if (i)
859                         cs.scale = (qbyte)bound(0, i, 255);
860
861                 cs.glowcolor = 254;
862                 i = (int)(GETEDICTFIELDVALUE(ent, eval_glow_color)->_float);
863                 if (i)
864                         cs.glowcolor = (int) val->_float;
865
866                 if (GETEDICTFIELDVALUE(ent, eval_fullbright)->_float)
867                         cs.effects |= EF_FULLBRIGHT;
868
869                 if (ent->v->movetype == MOVETYPE_STEP)
870                         cs.flags |= RENDER_STEP;
871                 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)
872                         cs.flags |= RENDER_LOWPRECISION;
873                 if (ent->v->colormap >= 1024)
874                         cs.flags |= RENDER_COLORMAPPED;
875                 if (cs.viewmodelforclient)
876                         cs.flags |= RENDER_VIEWMODEL; // show relative to the view
877
878                 cs.specialvisibilityradius = 0;
879                 if (cs.glowsize)
880                         cs.specialvisibilityradius = max(cs.specialvisibilityradius, cs.glowsize * 4);
881                 if (cs.flags & RENDER_GLOWTRAIL)
882                         cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
883                 if (cs.effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
884                 {
885                         if (cs.effects & EF_BRIGHTFIELD)
886                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 80);
887                         if (cs.effects & EF_MUZZLEFLASH)
888                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
889                         if (cs.effects & EF_BRIGHTLIGHT)
890                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 400);
891                         if (cs.effects & EF_DIMLIGHT)
892                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
893                         if (cs.effects & EF_RED)
894                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
895                         if (cs.effects & EF_BLUE)
896                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
897                         if (cs.effects & EF_FLAME)
898                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 250);
899                         if (cs.effects & EF_STARDUST)
900                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
901                 }
902
903                 if (numsendentities >= MAX_EDICTS)
904                         continue;
905                 // we can omit invisible entities with no effects that are not clients
906                 // LordHavoc: this could kill tags attached to an invisible entity, I
907                 // just hope we never have to support that case
908                 if (cs.number > svs.maxclients && ((cs.effects & EF_NODRAW) || (!cs.modelindex && !cs.specialvisibilityradius)))
909                         continue;
910                 sendentitiesindex[e] = sendentities + numsendentities;
911                 sendentities[numsendentities++] = cs;
912         }
913 }
914
915 static int sententitiesmark = 0;
916 static int sententities[MAX_EDICTS];
917 static int sententitiesconsideration[MAX_EDICTS];
918 static int sv_writeentitiestoclient_culled_pvs;
919 static int sv_writeentitiestoclient_culled_portal;
920 static int sv_writeentitiestoclient_culled_trace;
921 static int sv_writeentitiestoclient_visibleentities;
922 static int sv_writeentitiestoclient_totalentities;
923 static entity_frame_t sv_writeentitiestoclient_entityframe;
924 static int sv_writeentitiestoclient_clentnum;
925 static qbyte *sv_writeentitiestoclient_pvs;
926 static vec3_t sv_writeentitiestoclient_testeye;
927 static client_t *sv_writeentitiestoclient_client;
928
929 void SV_MarkWriteEntityStateToClient(entity_state_t *s)
930 {
931         vec3_t entmins, entmaxs, lightmins, lightmaxs, testorigin;
932         model_t *model;
933         trace_t trace;
934         if (sententitiesconsideration[s->number] == sententitiesmark)
935                 return;
936         sententitiesconsideration[s->number] = sententitiesmark;
937         // viewmodels don't have visibility checking
938         if (s->viewmodelforclient)
939         {
940                 if (s->viewmodelforclient != sv_writeentitiestoclient_clentnum)
941                         return;
942         }
943         // never reject player
944         else if (s->number != sv_writeentitiestoclient_clentnum)
945         {
946                 // check various rejection conditions
947                 if (s->nodrawtoclient == sv_writeentitiestoclient_clentnum)
948                         return;
949                 if (s->drawonlytoclient && s->drawonlytoclient != sv_writeentitiestoclient_clentnum)
950                         return;
951                 if (s->effects & EF_NODRAW)
952                         return;
953                 // LordHavoc: only send entities with a model or important effects
954                 if (!s->modelindex && s->specialvisibilityradius == 0)
955                         return;
956                 if (s->tagentity)
957                 {
958                         // tag attached entities simply check their parent
959                         if (!sendentitiesindex[s->tagentity])
960                                 return;
961                         SV_MarkWriteEntityStateToClient(sendentitiesindex[s->tagentity]);
962                         if (sententities[s->tagentity] != sententitiesmark)
963                                 return;
964                 }
965                 // always send world submodels, they don't generate much traffic
966                 else if ((model = sv.models[s->modelindex]) == NULL || model->name[0] != '*')
967                 {
968                         Mod_CheckLoaded(model);
969                         // entity has survived every check so far, check if visible
970                         // enlarged box to account for prediction (not that there is
971                         // any currently, but still helps the 'run into a room and
972                         // watch items pop up' problem)
973                         entmins[0] = s->origin[0] - 32.0f;
974                         entmins[1] = s->origin[1] - 32.0f;
975                         entmins[2] = s->origin[2] - 32.0f;
976                         entmaxs[0] = s->origin[0] + 32.0f;
977                         entmaxs[1] = s->origin[1] + 32.0f;
978                         entmaxs[2] = s->origin[2] + 32.0f;
979                         // using the model's bounding box to ensure things are visible regardless of their physics box
980                         if (model)
981                         {
982                                 if (s->angles[0] || s->angles[2]) // pitch and roll
983                                 {
984                                         VectorAdd(entmins, model->rotatedmins, entmins);
985                                         VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
986                                 }
987                                 else if (s->angles[1])
988                                 {
989                                         VectorAdd(entmins, model->yawmins, entmins);
990                                         VectorAdd(entmaxs, model->yawmaxs, entmaxs);
991                                 }
992                                 else
993                                 {
994                                         VectorAdd(entmins, model->normalmins, entmins);
995                                         VectorAdd(entmaxs, model->normalmaxs, entmaxs);
996                                 }
997                         }
998                         lightmins[0] = min(entmins[0], s->origin[0] - s->specialvisibilityradius);
999                         lightmins[1] = min(entmins[1], s->origin[1] - s->specialvisibilityradius);
1000                         lightmins[2] = min(entmins[2], s->origin[2] - s->specialvisibilityradius);
1001                         lightmaxs[0] = min(entmaxs[0], s->origin[0] + s->specialvisibilityradius);
1002                         lightmaxs[1] = min(entmaxs[1], s->origin[1] + s->specialvisibilityradius);
1003                         lightmaxs[2] = min(entmaxs[2], s->origin[2] + s->specialvisibilityradius);
1004                         sv_writeentitiestoclient_totalentities++;
1005                         // if not touching a visible leaf
1006                         if (sv_cullentities_pvs.integer && !SV_BoxTouchingPVS(sv_writeentitiestoclient_pvs, lightmins, lightmaxs, sv.worldmodel->brushq1.nodes))
1007                         {
1008                                 sv_writeentitiestoclient_culled_pvs++;
1009                                 return;
1010                         }
1011                         // or not visible through the portals
1012                         if (sv_cullentities_portal.integer && !Portal_CheckBox(sv.worldmodel, sv_writeentitiestoclient_testeye, lightmins, lightmaxs))
1013                         {
1014                                 sv_writeentitiestoclient_culled_portal++;
1015                                 return;
1016                         }
1017                         // or not seen by random tracelines
1018                         if (sv_cullentities_trace.integer)
1019                         {
1020                                 // LordHavoc: test center first
1021                                 testorigin[0] = (entmins[0] + entmaxs[0]) * 0.5f;
1022                                 testorigin[1] = (entmins[1] + entmaxs[1]) * 0.5f;
1023                                 testorigin[2] = (entmins[2] + entmaxs[2]) * 0.5f;
1024                                 trace = SV_Move(sv_writeentitiestoclient_testeye, vec3_origin, vec3_origin, testorigin, MOVE_NOMONSTERS, NULL);
1025                                 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
1026                                         sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
1027                                 else
1028                                 {
1029                                         // LordHavoc: test random offsets, to maximize chance of detection
1030                                         testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
1031                                         testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
1032                                         testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
1033                                         trace = SV_Move(sv_writeentitiestoclient_testeye, vec3_origin, vec3_origin, testorigin, MOVE_NOMONSTERS, NULL);
1034                                         if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
1035                                                 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
1036                                         else
1037                                         {
1038                                                 if (s->specialvisibilityradius)
1039                                                 {
1040                                                         // LordHavoc: test random offsets, to maximize chance of detection
1041                                                         testorigin[0] = lhrandom(lightmins[0], lightmaxs[0]);
1042                                                         testorigin[1] = lhrandom(lightmins[1], lightmaxs[1]);
1043                                                         testorigin[2] = lhrandom(lightmins[2], lightmaxs[2]);
1044                                                         trace = SV_Move(sv_writeentitiestoclient_testeye, vec3_origin, vec3_origin, testorigin, MOVE_NOMONSTERS, NULL);
1045                                                         if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
1046                                                                 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
1047                                                 }
1048                                         }
1049                                 }
1050                                 if (realtime > sv_writeentitiestoclient_client->visibletime[s->number])
1051                                 {
1052                                         sv_writeentitiestoclient_culled_trace++;
1053                                         return;
1054                                 }
1055                         }
1056                         sv_writeentitiestoclient_visibleentities++;
1057                 }
1058         }
1059         // this just marks it for sending
1060         // FIXME: it would be more efficient to send here, but the entity
1061         // compressor isn't that flexible
1062         sententities[s->number] = sententitiesmark;
1063 }
1064
1065 void SV_WriteEntitiesToClient(client_t *client, edict_t *clent, sizebuf_t *msg)
1066 {
1067         int i;
1068         vec3_t testorigin;
1069         entity_state_t *s;
1070
1071         sv_writeentitiestoclient_client = client;
1072
1073         sv_writeentitiestoclient_culled_pvs = 0;
1074         sv_writeentitiestoclient_culled_portal = 0;
1075         sv_writeentitiestoclient_culled_trace = 0;
1076         sv_writeentitiestoclient_visibleentities = 0;
1077         sv_writeentitiestoclient_totalentities = 0;
1078
1079         Mod_CheckLoaded(sv.worldmodel);
1080
1081 // find the client's PVS
1082         // the real place being tested from
1083         VectorAdd(clent->v->origin, clent->v->view_ofs, sv_writeentitiestoclient_testeye);
1084         sv_writeentitiestoclient_pvs = SV_FatPVS(sv_writeentitiestoclient_testeye);
1085
1086         sv_writeentitiestoclient_clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
1087
1088         sententitiesmark++;
1089
1090         // the place being reported (to consider the fact the client still
1091         // applies the view_ofs[2], so we have to only send the fractional part
1092         // of view_ofs[2], undoing what the client will redo)
1093         VectorCopy(sv_writeentitiestoclient_testeye, testorigin);
1094         i = (int) clent->v->view_ofs[2] & 255;
1095         if (i >= 128)
1096                 i -= 256;
1097         testorigin[2] -= (float) i;
1098
1099         for (i = 0;i < numsendentities;i++)
1100                 SV_MarkWriteEntityStateToClient(sendentities + i);
1101
1102         EntityFrame_Clear(&sv_writeentitiestoclient_entityframe, testorigin, ++client->entityframenumber);
1103         for (i = 0;i < numsendentities;i++)
1104         {
1105                 s = sendentities + i;
1106                 if (sententities[s->number] == sententitiesmark)
1107                 {
1108                         if (s->exteriormodelforclient && s->exteriormodelforclient == sv_writeentitiestoclient_clentnum)
1109                         {
1110                                 s->flags |= RENDER_EXTERIORMODEL;
1111                                 EntityFrame_AddEntity(&sv_writeentitiestoclient_entityframe, s);
1112                                 s->flags &= ~RENDER_EXTERIORMODEL;
1113                         }
1114                         else
1115                                 EntityFrame_AddEntity(&sv_writeentitiestoclient_entityframe, s);
1116                 }
1117         }
1118         EntityFrame_Write(&client->entitydatabase, &sv_writeentitiestoclient_entityframe, msg);
1119
1120         if (sv_cullentities_stats.integer)
1121                 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);
1122 }
1123 #endif
1124
1125 /*
1126 =============
1127 SV_CleanupEnts
1128
1129 =============
1130 */
1131 void SV_CleanupEnts (void)
1132 {
1133         int             e;
1134         edict_t *ent;
1135
1136         ent = NEXT_EDICT(sv.edicts);
1137         for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
1138                 ent->v->effects = (int)ent->v->effects & ~EF_MUZZLEFLASH;
1139 }
1140
1141 /*
1142 ==================
1143 SV_WriteClientdataToMessage
1144
1145 ==================
1146 */
1147 void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
1148 {
1149         int             bits;
1150         int             i;
1151         edict_t *other;
1152         int             items;
1153         eval_t  *val;
1154         vec3_t  punchvector;
1155         qbyte   viewzoom;
1156
1157 //
1158 // send a damage message
1159 //
1160         if (ent->v->dmg_take || ent->v->dmg_save)
1161         {
1162                 other = PROG_TO_EDICT(ent->v->dmg_inflictor);
1163                 MSG_WriteByte (msg, svc_damage);
1164                 MSG_WriteByte (msg, ent->v->dmg_save);
1165                 MSG_WriteByte (msg, ent->v->dmg_take);
1166                 for (i=0 ; i<3 ; i++)
1167                         MSG_WriteDPCoord (msg, other->v->origin[i] + 0.5*(other->v->mins[i] + other->v->maxs[i]));
1168
1169                 ent->v->dmg_take = 0;
1170                 ent->v->dmg_save = 0;
1171         }
1172
1173 //
1174 // send the current viewpos offset from the view entity
1175 //
1176         SV_SetIdealPitch ();            // how much to look up / down ideally
1177
1178 // a fixangle might get lost in a dropped packet.  Oh well.
1179         if ( ent->v->fixangle )
1180         {
1181                 MSG_WriteByte (msg, svc_setangle);
1182                 for (i=0 ; i < 3 ; i++)
1183                         MSG_WriteAngle (msg, ent->v->angles[i] );
1184                 ent->v->fixangle = 0;
1185         }
1186
1187         bits = 0;
1188
1189         if (ent->v->view_ofs[2] != DEFAULT_VIEWHEIGHT)
1190                 bits |= SU_VIEWHEIGHT;
1191
1192         if (ent->v->idealpitch)
1193                 bits |= SU_IDEALPITCH;
1194
1195 // stuff the sigil bits into the high bits of items for sbar, or else
1196 // mix in items2
1197         val = GETEDICTFIELDVALUE(ent, eval_items2);
1198
1199         if (val)
1200                 items = (int)ent->v->items | ((int)val->_float << 23);
1201         else
1202                 items = (int)ent->v->items | ((int)pr_global_struct->serverflags << 28);
1203
1204         bits |= SU_ITEMS;
1205
1206         if ( (int)ent->v->flags & FL_ONGROUND)
1207                 bits |= SU_ONGROUND;
1208
1209         if ( ent->v->waterlevel >= 2)
1210                 bits |= SU_INWATER;
1211
1212         // dpprotocol
1213         VectorClear(punchvector);
1214         if ((val = GETEDICTFIELDVALUE(ent, eval_punchvector)))
1215                 VectorCopy(val->vector, punchvector);
1216
1217         i = 255;
1218         if ((val = GETEDICTFIELDVALUE(ent, eval_viewzoom)))
1219         {
1220                 i = val->_float * 255.0f;
1221                 if (i == 0)
1222                         i = 255;
1223                 else
1224                         i = bound(0, i, 255);
1225         }
1226         viewzoom = i;
1227
1228         if (viewzoom != 255)
1229                 bits |= SU_VIEWZOOM;
1230
1231         for (i=0 ; i<3 ; i++)
1232         {
1233                 if (ent->v->punchangle[i])
1234                         bits |= (SU_PUNCH1<<i);
1235                 if (punchvector[i]) // dpprotocol
1236                         bits |= (SU_PUNCHVEC1<<i); // dpprotocol
1237                 if (ent->v->velocity[i])
1238                         bits |= (SU_VELOCITY1<<i);
1239         }
1240
1241         if (ent->v->weaponframe)
1242                 bits |= SU_WEAPONFRAME;
1243
1244         if (ent->v->armorvalue)
1245                 bits |= SU_ARMOR;
1246
1247         bits |= SU_WEAPON;
1248
1249         if (bits >= 65536)
1250                 bits |= SU_EXTEND1;
1251         if (bits >= 16777216)
1252                 bits |= SU_EXTEND2;
1253
1254 // send the data
1255
1256         MSG_WriteByte (msg, svc_clientdata);
1257         MSG_WriteShort (msg, bits);
1258         if (bits & SU_EXTEND1)
1259                 MSG_WriteByte(msg, bits >> 16);
1260         if (bits & SU_EXTEND2)
1261                 MSG_WriteByte(msg, bits >> 24);
1262
1263         if (bits & SU_VIEWHEIGHT)
1264                 MSG_WriteChar (msg, ent->v->view_ofs[2]);
1265
1266         if (bits & SU_IDEALPITCH)
1267                 MSG_WriteChar (msg, ent->v->idealpitch);
1268
1269         for (i=0 ; i<3 ; i++)
1270         {
1271                 if (bits & (SU_PUNCH1<<i))
1272                         MSG_WritePreciseAngle(msg, ent->v->punchangle[i]); // dpprotocol
1273                 if (bits & (SU_PUNCHVEC1<<i)) // dpprotocol
1274                         MSG_WriteDPCoord(msg, punchvector[i]); // dpprotocol
1275                 if (bits & (SU_VELOCITY1<<i))
1276                         MSG_WriteChar (msg, ent->v->velocity[i]/16);
1277         }
1278
1279 // [always sent]        if (bits & SU_ITEMS)
1280         MSG_WriteLong (msg, items);
1281
1282         if (bits & SU_WEAPONFRAME)
1283                 MSG_WriteByte (msg, ent->v->weaponframe);
1284         if (bits & SU_ARMOR)
1285                 MSG_WriteByte (msg, ent->v->armorvalue);
1286         if (bits & SU_WEAPON)
1287                 MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v->weaponmodel)));
1288
1289         MSG_WriteShort (msg, ent->v->health);
1290         MSG_WriteByte (msg, ent->v->currentammo);
1291         MSG_WriteByte (msg, ent->v->ammo_shells);
1292         MSG_WriteByte (msg, ent->v->ammo_nails);
1293         MSG_WriteByte (msg, ent->v->ammo_rockets);
1294         MSG_WriteByte (msg, ent->v->ammo_cells);
1295
1296         if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE)
1297         {
1298                 for(i=0;i<32;i++)
1299                 {
1300                         if ( ((int)ent->v->weapon) & (1<<i) )
1301                         {
1302                                 MSG_WriteByte (msg, i);
1303                                 break;
1304                         }
1305                 }
1306         }
1307         else
1308         {
1309                 MSG_WriteByte (msg, ent->v->weapon);
1310         }
1311
1312         if (bits & SU_VIEWZOOM)
1313                 MSG_WriteByte (msg, viewzoom);
1314 }
1315
1316 /*
1317 =======================
1318 SV_SendClientDatagram
1319 =======================
1320 */
1321 static qbyte sv_sendclientdatagram_buf[MAX_DATAGRAM]; // FIXME?
1322 qboolean SV_SendClientDatagram (client_t *client)
1323 {
1324         sizebuf_t       msg;
1325
1326         msg.data = sv_sendclientdatagram_buf;
1327         msg.maxsize = sizeof(sv_sendclientdatagram_buf);
1328         msg.cursize = 0;
1329
1330         MSG_WriteByte (&msg, svc_time);
1331         MSG_WriteFloat (&msg, sv.time);
1332
1333         // add the client specific data to the datagram
1334         SV_WriteClientdataToMessage (client->edict, &msg);
1335
1336         SV_WriteEntitiesToClient (client, client->edict, &msg);
1337
1338         // copy the server datagram if there is space
1339         if (msg.cursize + sv.datagram.cursize < msg.maxsize)
1340                 SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
1341
1342 // send the datagram
1343         if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1344         {
1345                 SV_DropClient (true);// if the message couldn't send, kick off
1346                 return false;
1347         }
1348
1349         return true;
1350 }
1351
1352 /*
1353 =======================
1354 SV_UpdateToReliableMessages
1355 =======================
1356 */
1357 void SV_UpdateToReliableMessages (void)
1358 {
1359         int i, j;
1360         client_t *client;
1361         eval_t *val;
1362         char *s;
1363
1364 // check for changes to be sent over the reliable streams
1365         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1366         {
1367                 // only update the client fields if they've spawned in
1368                 if (host_client->spawned)
1369                 {
1370                         // update the host_client fields we care about according to the entity fields
1371                         sv_player = host_client->edict;
1372                         s = PR_GetString(sv_player->v->netname);
1373                         if (s != host_client->name)
1374                         {
1375                                 if (s == NULL)
1376                                         s = "";
1377                                 // point the string back at host_client->name to keep it safe
1378                                 strncpy(host_client->name, s, sizeof(host_client->name) - 1);
1379                                 sv_player->v->netname = PR_SetString(host_client->name);
1380                         }
1381                         if ((val = GETEDICTFIELDVALUE(sv_player, eval_clientcolors)) && host_client->colors != val->_float)
1382                                 host_client->colors = val->_float;
1383                         host_client->frags = sv_player->v->frags;
1384                         if (gamemode == GAME_NEHAHRA)
1385                                 if ((val = GETEDICTFIELDVALUE(sv_player, eval_pmodel)) && host_client->pmodel != val->_float)
1386                                         host_client->pmodel = val->_float;
1387
1388                         // if the fields changed, send messages about the changes
1389                         if (strcmp(host_client->old_name, host_client->name))
1390                         {
1391                                 strcpy(host_client->old_name, host_client->name);
1392                                 for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
1393                                 {
1394                                         if (!client->active || !client->spawned)
1395                                                 continue;
1396                                         MSG_WriteByte (&client->message, svc_updatename);
1397                                         MSG_WriteByte (&client->message, i);
1398                                         MSG_WriteString (&client->message, host_client->name);
1399                                 }
1400                         }
1401                         if (host_client->old_colors != host_client->colors)
1402                         {
1403                                 host_client->old_colors = host_client->colors;
1404                                 for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
1405                                 {
1406                                         if (!client->active || !client->spawned)
1407                                                 continue;
1408                                         MSG_WriteByte (&client->message, svc_updatecolors);
1409                                         MSG_WriteByte (&client->message, i);
1410                                         MSG_WriteByte (&client->message, host_client->colors);
1411                                 }
1412                         }
1413                         if (host_client->old_frags != host_client->frags)
1414                         {
1415                                 host_client->old_frags = host_client->frags;
1416                                 for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
1417                                 {
1418                                         if (!client->active || !client->spawned)
1419                                                 continue;
1420                                         MSG_WriteByte (&client->message, svc_updatefrags);
1421                                         MSG_WriteByte (&client->message, i);
1422                                         MSG_WriteShort (&client->message, host_client->frags);
1423                                 }
1424                         }
1425                 }
1426         }
1427
1428         for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
1429         {
1430                 if (!client->active)
1431                         continue;
1432                 SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1433         }
1434
1435         SZ_Clear (&sv.reliable_datagram);
1436 }
1437
1438
1439 /*
1440 =======================
1441 SV_SendNop
1442
1443 Send a nop message without trashing or sending the accumulated client
1444 message buffer
1445 =======================
1446 */
1447 void SV_SendNop (client_t *client)
1448 {
1449         sizebuf_t       msg;
1450         qbyte           buf[4];
1451
1452         msg.data = buf;
1453         msg.maxsize = sizeof(buf);
1454         msg.cursize = 0;
1455
1456         MSG_WriteChar (&msg, svc_nop);
1457
1458         if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1459                 SV_DropClient (true);   // if the message couldn't send, kick off
1460         client->last_message = realtime;
1461 }
1462
1463 /*
1464 =======================
1465 SV_SendClientMessages
1466 =======================
1467 */
1468 void SV_SendClientMessages (void)
1469 {
1470         int i, prepared = false;
1471
1472 // update frags, names, etc
1473         SV_UpdateToReliableMessages();
1474
1475 // build individual updates
1476         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1477         {
1478                 if (!host_client->active)
1479                         continue;
1480
1481                 if (host_client->deadsocket)
1482                 {
1483                         SV_DropClient (true);   // if the message couldn't send, kick off
1484                         continue;
1485                 }
1486
1487                 if (host_client->spawned)
1488                 {
1489                         if (!prepared)
1490                         {
1491                                 prepared = true;
1492                                 // only prepare entities once per frame
1493                                 SV_PrepareEntitiesForSending();
1494                         }
1495                         if (!SV_SendClientDatagram (host_client))
1496                                 continue;
1497                 }
1498                 else
1499                 {
1500                 // the player isn't totally in the game yet
1501                 // send small keepalive messages if too much time has passed
1502                 // send a full message when the next signon stage has been requested
1503                 // some other message data (name changes, etc) may accumulate
1504                 // between signon stages
1505                         if (!host_client->sendsignon)
1506                         {
1507                                 if (realtime - host_client->last_message > 5)
1508                                         SV_SendNop (host_client);
1509                                 continue;       // don't send out non-signon messages
1510                         }
1511                 }
1512
1513                 // check for an overflowed message.  Should only happen
1514                 // on a very fucked up connection that backs up a lot, then
1515                 // changes level
1516                 if (host_client->message.overflowed)
1517                 {
1518                         SV_DropClient (true); // overflowed
1519                         host_client->message.overflowed = false;
1520                         continue;
1521                 }
1522
1523                 if (host_client->message.cursize || host_client->dropasap)
1524                 {
1525                         if (!NetConn_CanSendMessage (host_client->netconnection))
1526                                 continue;
1527
1528                         if (host_client->dropasap)
1529                                 SV_DropClient (false);  // went to another level
1530                         else
1531                         {
1532                                 if (NetConn_SendReliableMessage (host_client->netconnection, &host_client->message) == -1)
1533                                         SV_DropClient (true);   // if the message couldn't send, kick off
1534                                 SZ_Clear (&host_client->message);
1535                                 host_client->last_message = realtime;
1536                                 host_client->sendsignon = false;
1537                         }
1538                 }
1539         }
1540
1541 // clear muzzle flashes
1542         SV_CleanupEnts();
1543 }
1544
1545
1546 /*
1547 ==============================================================================
1548
1549 SERVER SPAWNING
1550
1551 ==============================================================================
1552 */
1553
1554 /*
1555 ================
1556 SV_ModelIndex
1557
1558 ================
1559 */
1560 int SV_ModelIndex (const char *name)
1561 {
1562         int i;
1563
1564         if (!name || !name[0])
1565                 return 0;
1566
1567         for (i=0 ; i<MAX_MODELS && sv.model_precache[i] ; i++)
1568                 if (!strcmp(sv.model_precache[i], name))
1569                         return i;
1570         if (i==MAX_MODELS || !sv.model_precache[i])
1571                 Host_Error ("SV_ModelIndex: model %s not precached", name);
1572         return i;
1573 }
1574
1575 #ifdef SV_QUAKEENTITIES
1576 /*
1577 ================
1578 SV_CreateBaseline
1579
1580 ================
1581 */
1582 void SV_CreateBaseline (void)
1583 {
1584         int i, entnum, large;
1585         edict_t *svent;
1586
1587         // LordHavoc: clear *all* states (note just active ones)
1588         for (entnum = 0;entnum < sv.max_edicts;entnum++)
1589         {
1590                 // get the current server version
1591                 svent = EDICT_NUM(entnum);
1592
1593                 // LordHavoc: always clear state values, whether the entity is in use or not
1594                 ClearStateToDefault(&svent->e->baseline);
1595
1596                 if (svent->e->free)
1597                         continue;
1598                 if (entnum > svs.maxclients && !svent->v->modelindex)
1599                         continue;
1600
1601                 // create entity baseline
1602                 VectorCopy (svent->v->origin, svent->e->baseline.origin);
1603                 VectorCopy (svent->v->angles, svent->e->baseline.angles);
1604                 svent->e->baseline.frame = svent->v->frame;
1605                 svent->e->baseline.skin = svent->v->skin;
1606                 if (entnum > 0 && entnum <= svs.maxclients)
1607                 {
1608                         svent->e->baseline.colormap = entnum;
1609                         svent->e->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
1610                 }
1611                 else
1612                 {
1613                         svent->e->baseline.colormap = 0;
1614                         svent->e->baseline.modelindex = svent->v->modelindex;
1615                 }
1616
1617                 large = false;
1618                 if (svent->e->baseline.modelindex & 0xFF00 || svent->e->baseline.frame & 0xFF00)
1619                         large = true;
1620
1621                 // add to the message
1622                 if (large)
1623                         MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1624                 else
1625                         MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1626                 MSG_WriteShort (&sv.signon, entnum);
1627
1628                 if (large)
1629                 {
1630                         MSG_WriteShort (&sv.signon, svent->e->baseline.modelindex);
1631                         MSG_WriteShort (&sv.signon, svent->e->baseline.frame);
1632                 }
1633                 else
1634                 {
1635                         MSG_WriteByte (&sv.signon, svent->e->baseline.modelindex);
1636                         MSG_WriteByte (&sv.signon, svent->e->baseline.frame);
1637                 }
1638                 MSG_WriteByte (&sv.signon, svent->e->baseline.colormap);
1639                 MSG_WriteByte (&sv.signon, svent->e->baseline.skin);
1640                 for (i=0 ; i<3 ; i++)
1641                 {
1642                         MSG_WriteDPCoord(&sv.signon, svent->e->baseline.origin[i]);
1643                         MSG_WriteAngle(&sv.signon, svent->e->baseline.angles[i]);
1644                 }
1645         }
1646 }
1647 #endif
1648
1649
1650 /*
1651 ================
1652 SV_SendReconnect
1653
1654 Tell all the clients that the server is changing levels
1655 ================
1656 */
1657 void SV_SendReconnect (void)
1658 {
1659         char    data[128];
1660         sizebuf_t       msg;
1661
1662         msg.data = data;
1663         msg.cursize = 0;
1664         msg.maxsize = sizeof(data);
1665
1666         MSG_WriteChar (&msg, svc_stufftext);
1667         MSG_WriteString (&msg, "reconnect\n");
1668         NetConn_SendToAll (&msg, 5);
1669
1670         if (cls.state != ca_dedicated)
1671                 Cmd_ExecuteString ("reconnect\n", src_command);
1672 }
1673
1674
1675 /*
1676 ================
1677 SV_SaveSpawnparms
1678
1679 Grabs the current state of each client for saving across the
1680 transition to another level
1681 ================
1682 */
1683 void SV_SaveSpawnparms (void)
1684 {
1685         int             i, j;
1686
1687         svs.serverflags = pr_global_struct->serverflags;
1688
1689         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1690         {
1691                 if (!host_client->active)
1692                         continue;
1693
1694         // call the progs to get default spawn parms for the new client
1695                 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
1696                 PR_ExecuteProgram (pr_global_struct->SetChangeParms, "QC function SetChangeParms is missing");
1697                 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1698                         host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
1699         }
1700 }
1701
1702 void SV_IncreaseEdicts(void)
1703 {
1704         int i;
1705         edict_t *ent;
1706         int oldmax_edicts = sv.max_edicts;
1707         void *oldedictsengineprivate = sv.edictsengineprivate;
1708         void *oldedictsfields = sv.edictsfields;
1709         void *oldmoved_edicts = sv.moved_edicts;
1710
1711         if (sv.max_edicts >= MAX_EDICTS)
1712                 return;
1713
1714         // links don't survive the transition, so unlink everything
1715         for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1716         {
1717                 if (!ent->e->free)
1718                         SV_UnlinkEdict(sv.edicts + i);
1719                 memset(&ent->e->areagrid, 0, sizeof(ent->e->areagrid));
1720         }
1721         SV_ClearWorld();
1722
1723         sv.max_edicts   = min(sv.max_edicts + 32, MAX_EDICTS);
1724         sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1725         sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1726         sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1727
1728         memcpy(sv.edictsengineprivate, oldedictsengineprivate, oldmax_edicts * sizeof(edict_engineprivate_t));
1729         memcpy(sv.edictsfields, oldedictsfields, oldmax_edicts * pr_edict_size);
1730
1731         for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1732         {
1733                 ent->e = sv.edictsengineprivate + i;
1734                 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1735                 // link every entity except world
1736                 if (!ent->e->free)
1737                         SV_LinkEdict(ent, false);
1738         }
1739
1740         Mem_Free(oldedictsengineprivate);
1741         Mem_Free(oldedictsfields);
1742         Mem_Free(oldmoved_edicts);
1743 }
1744
1745 /*
1746 ================
1747 SV_SpawnServer
1748
1749 This is called at the start of each level
1750 ================
1751 */
1752 extern float            scr_centertime_off;
1753
1754 void SV_SpawnServer (const char *server)
1755 {
1756         edict_t *ent;
1757         int i;
1758         qbyte *entities;
1759
1760         // let's not have any servers with no name
1761         if (hostname.string[0] == 0)
1762                 Cvar_Set ("hostname", "UNNAMED");
1763         scr_centertime_off = 0;
1764
1765         Con_DPrintf ("SpawnServer: %s\n",server);
1766         svs.changelevel_issued = false;         // now safe to issue another
1767
1768 //
1769 // tell all connected clients that we are going to a new level
1770 //
1771         if (sv.active)
1772                 SV_SendReconnect ();
1773         else
1774                 NetConn_OpenServerPorts(svs.maxclients > 1);
1775
1776 //
1777 // make cvars consistant
1778 //
1779         if (coop.integer)
1780                 Cvar_SetValue ("deathmatch", 0);
1781         current_skill = bound(0, (int)(skill.value + 0.5), 3);
1782
1783         Cvar_SetValue ("skill", (float)current_skill);
1784
1785 //
1786 // set up the new server
1787 //
1788         Host_ClearMemory ();
1789
1790         memset (&sv, 0, sizeof(sv));
1791
1792         strcpy (sv.name, server);
1793
1794 // load progs to get entity field count
1795         PR_LoadProgs ();
1796
1797 // allocate server memory
1798         // start out with just enough room for clients and a reasonable estimate of entities
1799         sv.max_edicts = ((svs.maxclients + 128) + 31) & ~31;
1800         sv.max_edicts = min(sv.max_edicts, MAX_EDICTS);
1801
1802         // clear the edict memory pool
1803         Mem_EmptyPool(sv_edicts_mempool);
1804         // edict_t structures (hidden from progs)
1805         sv.edicts = Mem_Alloc(sv_edicts_mempool, MAX_EDICTS * sizeof(edict_t));
1806         // engine private structures (hidden from progs)
1807         sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1808         // progs fields, often accessed by server
1809         sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1810         // used by PushMove to move back pushed entities
1811         sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1812         for (i = 0;i < sv.max_edicts;i++)
1813         {
1814                 ent = sv.edicts + i;
1815                 ent->e = sv.edictsengineprivate + i;
1816                 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1817         }
1818
1819         sv.datagram.maxsize = sizeof(sv.datagram_buf);
1820         sv.datagram.cursize = 0;
1821         sv.datagram.data = sv.datagram_buf;
1822
1823         sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1824         sv.reliable_datagram.cursize = 0;
1825         sv.reliable_datagram.data = sv.reliable_datagram_buf;
1826
1827         sv.signon.maxsize = sizeof(sv.signon_buf);
1828         sv.signon.cursize = 0;
1829         sv.signon.data = sv.signon_buf;
1830
1831 // leave slots at start for clients only
1832         sv.num_edicts = svs.maxclients+1;
1833
1834         sv.state = ss_loading;
1835         sv.paused = false;
1836
1837         sv.time = 1.0;
1838
1839         Mod_ClearUsed();
1840
1841         strcpy (sv.name, server);
1842         sprintf (sv.modelname,"maps/%s.bsp", server);
1843         sv.worldmodel = Mod_ForName(sv.modelname, false, true, true);
1844         if (!sv.worldmodel)
1845         {
1846                 Con_Printf ("Couldn't spawn server %s\n", sv.modelname);
1847                 sv.active = false;
1848                 return;
1849         }
1850         sv.models[1] = sv.worldmodel;
1851
1852 //
1853 // clear world interaction links
1854 //
1855         SV_ClearWorld ();
1856
1857         sv.sound_precache[0] = "";
1858
1859         sv.model_precache[0] = "";
1860         sv.model_precache[1] = sv.modelname;
1861         for (i = 1;i < sv.worldmodel->brushq1.numsubmodels;i++)
1862         {
1863                 sv.model_precache[i+1] = localmodels[i];
1864                 sv.models[i+1] = Mod_ForName (localmodels[i], false, false, false);
1865         }
1866
1867 //
1868 // load the rest of the entities
1869 //
1870         ent = EDICT_NUM(0);
1871         memset (ent->v, 0, progs->entityfields * 4);
1872         ent->e->free = false;
1873         ent->v->model = PR_SetString(sv.modelname);
1874         ent->v->modelindex = 1;         // world model
1875         ent->v->solid = SOLID_BSP;
1876         ent->v->movetype = MOVETYPE_PUSH;
1877
1878         if (coop.value)
1879                 pr_global_struct->coop = coop.integer;
1880         else
1881                 pr_global_struct->deathmatch = deathmatch.integer;
1882
1883         pr_global_struct->mapname = PR_SetString(sv.name);
1884
1885 // serverflags are for cross level information (sigils)
1886         pr_global_struct->serverflags = svs.serverflags;
1887
1888         // load replacement entity file if found
1889         entities = NULL;
1890         if (sv_entpatch.integer)
1891                 entities = FS_LoadFile(va("maps/%s.ent", sv.name), true);
1892         if (entities)
1893         {
1894                 Con_Printf("Loaded maps/%s.ent\n", sv.name);
1895                 ED_LoadFromFile (entities);
1896                 Mem_Free(entities);
1897         }
1898         else
1899                 ED_LoadFromFile (sv.worldmodel->brush.entities);
1900
1901
1902         // LordHavoc: clear world angles (to fix e3m3.bsp)
1903         VectorClear(sv.edicts->v->angles);
1904
1905         sv.active = true;
1906
1907 // all setup is completed, any further precache statements are errors
1908         sv.state = ss_active;
1909
1910 // run two frames to allow everything to settle
1911         for (i = 0;i < 2;i++)
1912         {
1913                 sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1914                 SV_Physics ();
1915         }
1916
1917         Mod_PurgeUnused();
1918
1919 #ifdef QUAKEENTITIES
1920 // create a baseline for more efficient communications
1921         SV_CreateBaseline ();
1922 #endif
1923
1924 // send serverinfo to all connected clients
1925         for (i=0,host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1926                 if (host_client->active)
1927                         SV_SendServerinfo (host_client);
1928
1929         Con_DPrintf ("Server spawned.\n");
1930         NetConn_Heartbeat (2);
1931 }
1932