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