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