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