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