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