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