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