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