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