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