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