]> icculus.org git repositories - divverent/darkplaces.git/blob - sv_main.c
fix for cvar tab completion crash
[divverent/darkplaces.git] / sv_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sv_main.c -- server main program
21
22 #include "quakedef.h"
23
24 server_t                sv;
25 server_static_t svs;
26
27 char    localmodels[MAX_MODELS][5];                     // inline model names for precache
28
29 //============================================================================
30
31 /*
32 ===============
33 SV_Init
34 ===============
35 */
36 void SV_Init (void)
37 {
38         int i;
39
40         Cvar_RegisterVariable (&sv_maxvelocity);
41         Cvar_RegisterVariable (&sv_gravity);
42         Cvar_RegisterVariable (&sv_friction);
43         Cvar_RegisterVariable (&sv_edgefriction);
44         Cvar_RegisterVariable (&sv_stopspeed);
45         Cvar_RegisterVariable (&sv_maxspeed);
46         Cvar_RegisterVariable (&sv_accelerate);
47         Cvar_RegisterVariable (&sv_idealpitchscale);
48         Cvar_RegisterVariable (&sv_aim);
49         Cvar_RegisterVariable (&sv_nostep);
50         Cvar_RegisterVariable (&sv_predict);
51         Cvar_RegisterVariable (&sv_deltacompress);
52
53         for (i = 0;i < MAX_MODELS;i++)
54                 sprintf (localmodels[i], "*%i", i);
55 }
56
57 /*
58 =============================================================================
59
60 EVENT MESSAGES
61
62 =============================================================================
63 */
64
65 /*  
66 ==================
67 SV_StartParticle
68
69 Make sure the event gets sent to all clients
70 ==================
71 */
72 void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
73 {
74         int             i, v;
75
76         if (sv.datagram.cursize > MAX_DATAGRAM-16)
77                 return; 
78         MSG_WriteByte (&sv.datagram, svc_particle);
79         MSG_WriteFloatCoord (&sv.datagram, org[0]);
80         MSG_WriteFloatCoord (&sv.datagram, org[1]);
81         MSG_WriteFloatCoord (&sv.datagram, org[2]);
82         for (i=0 ; i<3 ; i++)
83         {
84                 v = dir[i]*16;
85                 if (v > 127)
86                         v = 127;
87                 else if (v < -128)
88                         v = -128;
89                 MSG_WriteChar (&sv.datagram, v);
90         }
91         MSG_WriteByte (&sv.datagram, count);
92         MSG_WriteByte (&sv.datagram, color);
93 }           
94
95 /*  
96 ==================
97 SV_StartEffect
98
99 Make sure the event gets sent to all clients
100 ==================
101 */
102 void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
103 {
104         if (sv.datagram.cursize > MAX_DATAGRAM-18)
105                 return; 
106         if (modelindex >= 256 || startframe >= 256)
107         {
108                 MSG_WriteByte (&sv.datagram, svc_effect2);
109                 MSG_WriteFloatCoord (&sv.datagram, org[0]);
110                 MSG_WriteFloatCoord (&sv.datagram, org[1]);
111                 MSG_WriteFloatCoord (&sv.datagram, org[2]);
112                 MSG_WriteShort (&sv.datagram, modelindex);
113                 MSG_WriteShort (&sv.datagram, startframe);
114                 MSG_WriteByte (&sv.datagram, framecount);
115                 MSG_WriteByte (&sv.datagram, framerate);
116         }
117         else
118         {
119                 MSG_WriteByte (&sv.datagram, svc_effect);
120                 MSG_WriteFloatCoord (&sv.datagram, org[0]);
121                 MSG_WriteFloatCoord (&sv.datagram, org[1]);
122                 MSG_WriteFloatCoord (&sv.datagram, org[2]);
123                 MSG_WriteByte (&sv.datagram, modelindex);
124                 MSG_WriteByte (&sv.datagram, startframe);
125                 MSG_WriteByte (&sv.datagram, framecount);
126                 MSG_WriteByte (&sv.datagram, framerate);
127         }
128 }           
129
130 /*  
131 ==================
132 SV_StartSound
133
134 Each entity can have eight independant sound sources, like voice,
135 weapon, feet, etc.
136
137 Channel 0 is an auto-allocate channel, the others override anything
138 already running on that entity/channel pair.
139
140 An attenuation of 0 will play full volume everywhere in the level.
141 Larger attenuations will drop off.  (max 4 attenuation)
142
143 ==================
144 */  
145 void SV_StartSound (edict_t *entity, int channel, char *sample, int volume,
146     float attenuation)
147 {       
148     int         sound_num;
149     int field_mask;
150     int                 i;
151         int                     ent;
152         
153         if (volume < 0 || volume > 255)
154                 Host_Error ("SV_StartSound: volume = %i", volume);
155
156         if (attenuation < 0 || attenuation > 4)
157                 Host_Error ("SV_StartSound: attenuation = %f", attenuation);
158
159         if (channel < 0 || channel > 7)
160                 Host_Error ("SV_StartSound: channel = %i", channel);
161
162         if (sv.datagram.cursize > MAX_DATAGRAM-16)
163                 return; 
164
165 // find precache number for sound
166     for (sound_num=1 ; sound_num<MAX_SOUNDS
167         && sv.sound_precache[sound_num] ; sound_num++)
168         if (!strcmp(sample, sv.sound_precache[sound_num]))
169             break;
170     
171     if ( sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num] )
172     {
173         Con_Printf ("SV_StartSound: %s not precached\n", sample);
174         return;
175     }
176     
177         ent = NUM_FOR_EDICT(entity);
178
179         channel = (ent<<3) | channel;
180
181         field_mask = 0;
182         if (volume != DEFAULT_SOUND_PACKET_VOLUME)
183                 field_mask |= SND_VOLUME;
184         if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
185                 field_mask |= SND_ATTENUATION;
186
187 // directed messages go only to the entity they are targeted on
188         if (sound_num >= 256)
189                 MSG_WriteByte (&sv.datagram, svc_sound2);
190         else
191                 MSG_WriteByte (&sv.datagram, svc_sound);
192         MSG_WriteByte (&sv.datagram, field_mask);
193         if (field_mask & SND_VOLUME)
194                 MSG_WriteByte (&sv.datagram, volume);
195         if (field_mask & SND_ATTENUATION)
196                 MSG_WriteByte (&sv.datagram, attenuation*64);
197         MSG_WriteShort (&sv.datagram, channel);
198         if (sound_num >= 256)
199                 MSG_WriteShort (&sv.datagram, sound_num);
200         else
201                 MSG_WriteByte (&sv.datagram, sound_num);
202         for (i=0 ; i<3 ; i++)
203                 MSG_WriteFloatCoord (&sv.datagram, entity->v.origin[i]+0.5*(entity->v.mins[i]+entity->v.maxs[i]));
204 }           
205
206 /*
207 ==============================================================================
208
209 CLIENT SPAWNING
210
211 ==============================================================================
212 */
213
214 /*
215 ================
216 SV_SendServerinfo
217
218 Sends the first message from the server to a connected client.
219 This will be sent on the initial connection and upon each server load.
220 ================
221 */
222 void SV_SendServerinfo (client_t *client)
223 {
224         char                    **s;
225         char                    message[2048];
226
227         MSG_WriteByte (&client->message, svc_print);
228         sprintf (message, "%c\nDARKPLACES VERSION %4.2f BUILD %i SERVER (%i CRC)", 2, VERSION, buildnumber, pr_crc);
229         MSG_WriteString (&client->message,message);
230
231         MSG_WriteByte (&client->message, svc_serverinfo);
232         MSG_WriteLong (&client->message, DPPROTOCOL_VERSION);
233         MSG_WriteByte (&client->message, svs.maxclients);
234
235         if (!coop.value && deathmatch.value)
236                 MSG_WriteByte (&client->message, GAME_DEATHMATCH);
237         else
238                 MSG_WriteByte (&client->message, GAME_COOP);
239
240         sprintf (message, pr_strings+sv.edicts->v.message);
241
242         MSG_WriteString (&client->message,message);
243
244         for (s = sv.model_precache+1 ; *s ; s++)
245                 MSG_WriteString (&client->message, *s);
246         MSG_WriteByte (&client->message, 0);
247
248         for (s = sv.sound_precache+1 ; *s ; s++)
249                 MSG_WriteString (&client->message, *s);
250         MSG_WriteByte (&client->message, 0);
251
252 // send music
253         MSG_WriteByte (&client->message, svc_cdtrack);
254         MSG_WriteByte (&client->message, sv.edicts->v.sounds);
255         MSG_WriteByte (&client->message, sv.edicts->v.sounds);
256
257 // set view     
258         MSG_WriteByte (&client->message, svc_setview);
259         MSG_WriteShort (&client->message, NUM_FOR_EDICT(client->edict));
260
261         MSG_WriteByte (&client->message, svc_signonnum);
262         MSG_WriteByte (&client->message, 1);
263
264         client->sendsignon = true;
265         client->spawned = false;                // need prespawn, spawn, etc
266 }
267
268 /*
269 ================
270 SV_ConnectClient
271
272 Initializes a client_t for a new net connection.  This will only be called
273 once for a player each game, not once for each level change.
274 ================
275 */
276 void SV_ConnectClient (int clientnum)
277 {
278         edict_t                 *ent;
279         client_t                *client;
280         int                             edictnum;
281         struct qsocket_s *netconnection;
282         int                             i;
283         float                   spawn_parms[NUM_SPAWN_PARMS];
284
285         client = svs.clients + clientnum;
286
287         Con_DPrintf ("Client %s connected\n", client->netconnection->address);
288
289         edictnum = clientnum+1;
290
291         ent = EDICT_NUM(edictnum);
292         
293 // set up the client_t
294         netconnection = client->netconnection;
295         
296         if (sv.loadgame)
297                 memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms));
298         memset (client, 0, sizeof(*client));
299         client->netconnection = netconnection;
300
301         strcpy (client->name, "unconnected");
302         client->active = true;
303         client->spawned = false;
304         client->edict = ent;
305         client->message.data = client->msgbuf;
306         client->message.maxsize = sizeof(client->msgbuf);
307         client->message.allowoverflow = true;           // we can catch it
308
309         if (sv.loadgame)
310                 memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms));
311         else
312         {
313         // call the progs to get default spawn parms for the new client
314                 PR_ExecuteProgram (pr_global_struct->SetNewParms, "QC function SetNewParms is missing");
315                 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
316                         client->spawn_parms[i] = (&pr_global_struct->parm1)[i];
317         }
318
319         SV_SendServerinfo (client);
320 }
321
322
323 /*
324 ===================
325 SV_CheckForNewClients
326
327 ===================
328 */
329 void SV_CheckForNewClients (void)
330 {
331         struct qsocket_s        *ret;
332         int                             i;
333                 
334 //
335 // check for new connections
336 //
337         while (1)
338         {
339                 ret = NET_CheckNewConnections ();
340                 if (!ret)
341                         break;
342
343         // 
344         // init a new client structure
345         //      
346                 for (i=0 ; i<svs.maxclients ; i++)
347                         if (!svs.clients[i].active)
348                                 break;
349                 if (i == svs.maxclients)
350                         Sys_Error ("Host_CheckForNewClients: no free clients");
351                 
352                 svs.clients[i].netconnection = ret;
353                 SV_ConnectClient (i);   
354         
355                 net_activeconnections++;
356         }
357 }
358
359
360
361 /*
362 ===============================================================================
363
364 FRAME UPDATES
365
366 ===============================================================================
367 */
368
369 /*
370 ==================
371 SV_ClearDatagram
372
373 ==================
374 */
375 void SV_ClearDatagram (void)
376 {
377         SZ_Clear (&sv.datagram);
378 }
379
380 /*
381 =============================================================================
382
383 The PVS must include a small area around the client to allow head bobbing
384 or other small motion on the client side.  Otherwise, a bob might cause an
385 entity that should be visible to not show up, especially when the bob
386 crosses a waterline.
387
388 =============================================================================
389 */
390
391 int             fatbytes;
392 byte    fatpvs[MAX_MAP_LEAFS/8];
393
394 void SV_AddToFatPVS (vec3_t org, mnode_t *node)
395 {
396         int             i;
397         byte    *pvs;
398         mplane_t        *plane;
399         float   d;
400
401         while (1)
402         {
403         // if this is a leaf, accumulate the pvs bits
404                 if (node->contents < 0)
405                 {
406                         if (node->contents != CONTENTS_SOLID)
407                         {
408                                 pvs = Mod_LeafPVS ( (mleaf_t *)node, sv.worldmodel);
409                                 for (i=0 ; i<fatbytes ; i++)
410                                         fatpvs[i] |= pvs[i];
411                         }
412                         return;
413                 }
414         
415                 plane = node->plane;
416                 d = DotProduct (org, plane->normal) - plane->dist;
417                 if (d > 8)
418                         node = node->children[0];
419                 else if (d < -8)
420                         node = node->children[1];
421                 else
422                 {       // go down both
423                         SV_AddToFatPVS (org, node->children[0]);
424                         node = node->children[1];
425                 }
426         }
427 }
428
429 /*
430 =============
431 SV_FatPVS
432
433 Calculates a PVS that is the inclusive or of all leafs within 8 pixels of the
434 given point.
435 =============
436 */
437 byte *SV_FatPVS (vec3_t org)
438 {
439         fatbytes = (sv.worldmodel->numleafs+31)>>3;
440         memset (fatpvs, 0, fatbytes);
441         SV_AddToFatPVS (org, sv.worldmodel->nodes);
442         return fatpvs;
443 }
444
445 //=============================================================================
446
447
448 /*
449 =============
450 SV_WriteEntitiesToClient
451
452 =============
453 */
454 void SV_WriteEntitiesToClient (client_t *client, edict_t *clent, sizebuf_t *msg)
455 {
456         int             e, i, clentnum, bits, alpha, glowcolor, glowsize, scale, colormod, effects;
457         byte    *pvs;
458         vec3_t  org, origin, angles;
459         float   movelerp, moveilerp, nextfullupdate;
460         edict_t *ent;
461         eval_t  *val;
462         entity_state_t *baseline; // LordHavoc: delta or startup baseline
463
464 // find the client's PVS
465         VectorAdd (clent->v.origin, clent->v.view_ofs, org);
466         pvs = SV_FatPVS (org);
467         /*
468         if (dpprotocol)
469         {
470                 MSG_WriteByte(msg, svc_playerposition);
471                 MSG_WriteFloat(msg, org[0]);
472                 MSG_WriteFloat(msg, org[1]);
473                 MSG_WriteFloat(msg, org[2]);
474         }
475         */
476
477         clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
478 // send over all entities (except the client) that touch the pvs
479         ent = NEXT_EDICT(sv.edicts);
480         for (e = 1;e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
481         {
482                 bits = 0;
483
484                 // prevent delta compression against this frame (unless actually sent, which will restore this later)
485                 nextfullupdate = client->nextfullupdate[e];
486                 client->nextfullupdate[e] = -1;
487
488                 if (ent != clent) // LordHavoc: always send player
489                 {
490                         if ((val = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)) && val->edict)
491                         {
492                                 if (val->edict != clentnum)
493                                 {
494                                         // don't show to anyone else
495                                         continue;
496                                 }
497                                 else
498                                         bits |= U_VIEWMODEL; // show relative to the view
499                         }
500                         else
501                         {
502                                 // LordHavoc: never draw something told not to display to this client
503                                 if ((val = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)) && val->edict == clentnum)
504                                         continue;
505                                 if ((val = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)) && val->edict && val->edict != clentnum)
506                                         continue;
507                                 // ignore if not touching a PV leaf
508                                 for (i = 0;i < ent->num_leafs;i++)
509                                         if (pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i]&7) ))
510                                                 break;
511                                         
512                                 if (i == ent->num_leafs)
513                                 {
514                                         // not visible
515                                         continue;
516                                 }
517                         }
518                 }
519
520                 if ((val = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)) && val->edict == clentnum)
521                         bits = bits | U_EXTERIORMODEL;
522
523                 // don't send if flagged for NODRAW and there are no effects
524                 alpha = 255;
525                 scale = 16;
526                 glowsize = 0;
527                 glowcolor = 254;
528                 colormod = 255;
529                 effects = ent->v.effects;
530
531                 if ((val = GETEDICTFIELDVALUE(ent, eval_alpha)))
532                 if (val->_float != 0)
533                         alpha = (int) (val->_float * 255.0);
534
535                 // HalfLife support
536                 if ((val = GETEDICTFIELDVALUE(ent, eval_renderamt)))
537                 if (val->_float != 0)
538                         alpha = (int) val->_float;
539
540                 if (alpha == 0)
541                         alpha = 255;
542                 alpha = bound(0, alpha, 255);
543
544                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_size)))
545                         glowsize = (int) val->_float >> 2;
546                 if (glowsize > 255) glowsize = 255;
547                 if (glowsize < 0) glowsize = 0;
548
549                 if ((val = GETEDICTFIELDVALUE(ent, eval_scale)))
550                 if ((scale = (int) (val->_float * 16.0)) == 0) scale = 16;
551                 if (scale < 0) scale = 0;
552                 if (scale > 255) scale = 255;
553
554                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_trail)))
555                 if (val->_float != 0)
556                         bits |= U_GLOWTRAIL;
557
558                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_color)))
559                 if (val->_float != 0)
560                         glowcolor = (int) val->_float;
561
562                 if ((val = GETEDICTFIELDVALUE(ent, eval_fullbright)))
563                 if (val->_float != 0)
564                         effects |= EF_FULLBRIGHT;
565
566                 if ((val = GETEDICTFIELDVALUE(ent, eval_colormod)))
567                 if (val->vector[0] != 0 || val->vector[1] != 0 || val->vector[2] != 0)
568                         colormod = (bound(0, (int) (val->vector[0] * 8.0), 7) << 5) | (bound(0, (int) (val->vector[1] * 8.0), 7) << 2) | bound(0, (int) (val->vector[2] * 4.0), 3);
569
570                 if (ent != clent)
571                 {
572                         if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
573                         {
574                                 if (ent->v.modelindex && pr_strings[ent->v.model]) // model
575                                 {
576                                         if (sv.models[ (int)ent->v.modelindex ]->flags == 0 && (ent->v.effects == EF_NODRAW || scale <= 0 || alpha <= 0))
577                                                 continue;
578                                 }
579                                 else // no model and no effects
580                                         continue;
581                         }
582                 }
583
584                 if (msg->maxsize - msg->cursize < 32) // LordHavoc: increased check from 16 to 32
585                 {
586                         Con_Printf ("packet overflow\n");
587                         // mark the rest of the entities so they can't be delta compressed against this frame
588                         for (;e < sv.num_edicts;e++)
589                                 client->nextfullupdate[e] = -1;
590                         return;
591                 }
592
593 // send an update
594                 baseline = &ent->baseline;
595
596                 if (((int)ent->v.effects & EF_DELTA) && sv_deltacompress.value)
597                 {
598                         // every half second a full update is forced
599                         if (realtime < client->nextfullupdate[e])
600                         {
601                                 bits |= U_DELTA;
602                                 baseline = &ent->deltabaseline;
603                         }
604                         else
605                                 nextfullupdate = realtime + 0.5f;
606                 }
607                 else
608                         nextfullupdate = realtime + 0.5f;
609
610                 // restore nextfullupdate since this is being sent
611                 client->nextfullupdate[e] = nextfullupdate;
612
613                 if (e >= 256)
614                         bits |= U_LONGENTITY;
615
616                 if (ent->v.movetype == MOVETYPE_STEP)
617                         bits |= U_STEP;
618                 
619                 if (ent->v.movetype == MOVETYPE_STEP && ((int) ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM))) // monsters have smoothed walking/flying/swimming movement
620                 {
621                         if (!ent->steplerptime || ent->steplerptime > sv.time) // when the level just started...
622                         {
623                                 ent->steplerptime = sv.time;
624                                 VectorCopy(ent->v.origin, ent->stepoldorigin);
625                                 VectorCopy(ent->v.angles, ent->stepoldangles);
626                                 VectorCopy(ent->v.origin, ent->steporigin);
627                                 VectorCopy(ent->v.angles, ent->stepangles);
628                         }
629                         VectorSubtract(ent->v.origin, ent->steporigin, origin);
630                         VectorSubtract(ent->v.angles, ent->stepangles, angles);
631                         if (DotProduct(origin, origin) >= 0.125 || DotProduct(angles, angles) >= 1.4)
632                         {
633                                 // update lerp positions
634                                 ent->steplerptime = sv.time;
635                                 VectorCopy(ent->steporigin, ent->stepoldorigin);
636                                 VectorCopy(ent->stepangles, ent->stepoldangles);
637                                 VectorCopy(ent->v.origin, ent->steporigin);
638                                 VectorCopy(ent->v.angles, ent->stepangles);
639                         }
640                         movelerp = (sv.time - ent->steplerptime) * 10.0;
641                         if (movelerp > 1) movelerp = 1;
642                         moveilerp = 1 - movelerp;
643                         origin[0] = ent->stepoldorigin[0] * moveilerp + ent->steporigin[0] * movelerp;
644                         origin[1] = ent->stepoldorigin[1] * moveilerp + ent->steporigin[1] * movelerp;
645                         origin[2] = ent->stepoldorigin[2] * moveilerp + ent->steporigin[2] * movelerp;
646                         // choose shortest rotate (to avoid 'spin around' situations)
647                         VectorSubtract(ent->stepangles, ent->stepoldangles, angles);
648                         if (angles[0] < -180) angles[0] += 360;if (angles[0] >= 180) angles[0] -= 360;
649                         if (angles[1] < -180) angles[1] += 360;if (angles[1] >= 180) angles[1] -= 360;
650                         if (angles[2] < -180) angles[2] += 360;if (angles[2] >= 180) angles[2] -= 360;
651                         angles[0] = angles[0] * movelerp + ent->stepoldangles[0];
652                         angles[1] = angles[1] * movelerp + ent->stepoldangles[1];
653                         angles[2] = angles[2] * movelerp + ent->stepoldangles[2];
654                         VectorMA(origin, host_client->latency, ent->v.velocity, origin);
655                 }
656                 else // copy as they are
657                 {
658 //                      VectorCopy(ent->v.origin, origin);
659                         VectorCopy(ent->v.angles, angles);
660                         VectorMA(ent->v.origin, host_client->latency, ent->v.velocity, origin);
661                         if (ent->v.movetype == MOVETYPE_STEP) // monster, but airborn, update lerp info
662                         {
663                                 // update lerp positions
664                                 ent->steplerptime = sv.time;
665                                 VectorCopy(ent->v.origin, ent->stepoldorigin);
666                                 VectorCopy(ent->v.angles, ent->stepoldangles);
667                                 VectorCopy(ent->v.origin, ent->steporigin);
668                                 VectorCopy(ent->v.angles, ent->stepangles);
669                         }
670                 }
671
672                 // LordHavoc: old stuff, but rewritten to have more exact tolerances
673 //              if ((int)(origin[0]*8.0) != (int)(baseline->origin[0]*8.0))                                             bits |= U_ORIGIN1;
674 //              if ((int)(origin[1]*8.0) != (int)(baseline->origin[1]*8.0))                                             bits |= U_ORIGIN2;
675 //              if ((int)(origin[2]*8.0) != (int)(baseline->origin[2]*8.0))                                             bits |= U_ORIGIN3;
676                 if (origin[0] != baseline->origin[0])                                                                                   bits |= U_ORIGIN1;
677                 if (origin[1] != baseline->origin[1])                                                                                   bits |= U_ORIGIN2;
678                 if (origin[2] != baseline->origin[2])                                                                                   bits |= U_ORIGIN3;
679                 if ((int)(angles[0]*(256.0/360.0)) != (int)(baseline->angles[0]*(256.0/360.0))) bits |= U_ANGLE1;
680                 if ((int)(angles[1]*(256.0/360.0)) != (int)(baseline->angles[1]*(256.0/360.0))) bits |= U_ANGLE2;
681                 if ((int)(angles[2]*(256.0/360.0)) != (int)(baseline->angles[2]*(256.0/360.0))) bits |= U_ANGLE3;
682                 if (baseline->colormap != (byte) ent->v.colormap)                                                               bits |= U_COLORMAP;
683                 if (baseline->skin != (byte) ent->v.skin)                                                                               bits |= U_SKIN;
684                 if ((baseline->frame & 0x00FF) != ((int) ent->v.frame & 0x00FF))                                bits |= U_FRAME;
685                 if ((baseline->effects & 0x00FF) != ((int) ent->v.effects & 0x00FF))                    bits |= U_EFFECTS;
686                 if ((baseline->modelindex & 0x00FF) != ((int) ent->v.modelindex & 0x00FF))              bits |= U_MODEL;
687
688                 // LordHavoc: new stuff
689                 if (baseline->alpha != alpha)                                                                                                   bits |= U_ALPHA;
690                 if (baseline->scale != scale)                                                                                                   bits |= U_SCALE;
691                 if (((int) baseline->effects & 0xFF00) != ((int) ent->v.effects & 0xFF00))              bits |= U_EFFECTS2;
692                 if (baseline->glowsize != glowsize)                                                                                             bits |= U_GLOWSIZE;
693                 if (baseline->glowcolor != glowcolor)                                                                                   bits |= U_GLOWCOLOR;
694                 if (baseline->colormod != colormod)                                                                                             bits |= U_COLORMOD;
695                 if (((int) baseline->frame & 0xFF00) != ((int) ent->v.frame & 0xFF00))                  bits |= U_FRAME2;
696                 if (((int) baseline->frame & 0xFF00) != ((int) ent->v.modelindex & 0xFF00))             bits |= U_MODEL2;
697
698                 // update delta baseline
699                 VectorCopy(ent->v.origin, ent->deltabaseline.origin);
700                 VectorCopy(ent->v.angles, ent->deltabaseline.angles);
701                 ent->deltabaseline.colormap = ent->v.colormap;
702                 ent->deltabaseline.skin = ent->v.skin;
703                 ent->deltabaseline.frame = ent->v.frame;
704                 ent->deltabaseline.effects = ent->v.effects;
705                 ent->deltabaseline.modelindex = ent->v.modelindex;
706                 ent->deltabaseline.alpha = alpha;
707                 ent->deltabaseline.scale = scale;
708                 ent->deltabaseline.glowsize = glowsize;
709                 ent->deltabaseline.glowcolor = glowcolor;
710                 ent->deltabaseline.colormod = colormod;
711
712                 if (bits & (U_ALPHA | U_SCALE | U_EFFECTS2 | U_GLOWSIZE | U_GLOWCOLOR | U_COLORMOD | U_FRAME2 | U_MODEL2))
713                         i = -1;
714
715                 // write the message
716                 if (bits >= 16777216)
717                         bits |= U_EXTEND2;
718                 if (bits >= 65536)
719                         bits |= U_EXTEND1;
720                 if (bits >= 256)
721                         bits |= U_MOREBITS;
722                 bits |= U_SIGNAL;
723
724                 MSG_WriteByte (msg, bits);
725                 if (bits & U_MOREBITS)
726                         MSG_WriteByte (msg, bits>>8);
727                 // LordHavoc: extend bytes have to be written here due to delta compression
728                 if (bits & U_EXTEND1)
729                         MSG_WriteByte (msg, bits>>16);
730                 if (bits & U_EXTEND2)
731                         MSG_WriteByte (msg, bits>>24);
732
733                 // LordHavoc: old stuff
734                 if (bits & U_LONGENTITY)
735                         MSG_WriteShort (msg,e);
736                 else
737                         MSG_WriteByte (msg,e);
738                 if (bits & U_MODEL)             MSG_WriteByte (msg,     ent->v.modelindex);
739                 if (bits & U_FRAME)             MSG_WriteByte (msg, ent->v.frame);
740                 if (bits & U_COLORMAP)  MSG_WriteByte (msg, ent->v.colormap);
741                 if (bits & U_SKIN)              MSG_WriteByte (msg, ent->v.skin);
742                 if (bits & U_EFFECTS)   MSG_WriteByte (msg, ent->v.effects);
743                 if (bits & U_ORIGIN1)   MSG_WriteFloatCoord (msg, origin[0]);
744                 if (bits & U_ANGLE1)    MSG_WriteAngle(msg, angles[0]);
745                 if (bits & U_ORIGIN2)   MSG_WriteFloatCoord (msg, origin[1]);
746                 if (bits & U_ANGLE2)    MSG_WriteAngle(msg, angles[1]);
747                 if (bits & U_ORIGIN3)   MSG_WriteFloatCoord (msg, origin[2]);
748                 if (bits & U_ANGLE3)    MSG_WriteAngle(msg, angles[2]);
749
750                 // LordHavoc: new stuff
751                 if (bits & U_ALPHA)             MSG_WriteByte(msg, alpha);
752                 if (bits & U_SCALE)             MSG_WriteByte(msg, scale);
753                 if (bits & U_EFFECTS2)  MSG_WriteByte(msg, (int)ent->v.effects >> 8);
754                 if (bits & U_GLOWSIZE)  MSG_WriteByte(msg, glowsize);
755                 if (bits & U_GLOWCOLOR) MSG_WriteByte(msg, glowcolor);
756                 if (bits & U_COLORMOD)  MSG_WriteByte(msg, colormod);
757                 if (bits & U_FRAME2)    MSG_WriteByte(msg, (int)ent->v.frame >> 8);
758                 if (bits & U_MODEL2)    MSG_WriteByte(msg, (int)ent->v.modelindex >> 8);
759         }
760 }
761
762 /*
763 =============
764 SV_CleanupEnts
765
766 =============
767 */
768 void SV_CleanupEnts (void)
769 {
770         int             e;
771         edict_t *ent;
772         
773         ent = NEXT_EDICT(sv.edicts);
774         for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
775         {
776                 ent->v.effects = (int)ent->v.effects & ~EF_MUZZLEFLASH;
777         }
778
779 }
780
781 /*
782 ==================
783 SV_WriteClientdataToMessage
784
785 ==================
786 */
787 void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
788 {
789         int             bits;
790         int             i;
791         edict_t *other;
792         int             items;
793         eval_t  *val;
794         vec3_t  punchvector;
795
796 //
797 // send a damage message
798 //
799         if (ent->v.dmg_take || ent->v.dmg_save)
800         {
801                 other = PROG_TO_EDICT(ent->v.dmg_inflictor);
802                 MSG_WriteByte (msg, svc_damage);
803                 MSG_WriteByte (msg, ent->v.dmg_save);
804                 MSG_WriteByte (msg, ent->v.dmg_take);
805                 for (i=0 ; i<3 ; i++)
806                         MSG_WriteFloatCoord (msg, other->v.origin[i] + 0.5*(other->v.mins[i] + other->v.maxs[i]));
807         
808                 ent->v.dmg_take = 0;
809                 ent->v.dmg_save = 0;
810         }
811
812 //
813 // send the current viewpos offset from the view entity
814 //
815         SV_SetIdealPitch ();            // how much to look up / down ideally
816
817 // a fixangle might get lost in a dropped packet.  Oh well.
818         if ( ent->v.fixangle )
819         {
820                 MSG_WriteByte (msg, svc_setangle);
821                 for (i=0 ; i < 3 ; i++)
822                         MSG_WriteAngle (msg, ent->v.angles[i] );
823                 ent->v.fixangle = 0;
824         }
825
826         bits = 0;
827         
828         if (ent->v.view_ofs[2] != DEFAULT_VIEWHEIGHT)
829                 bits |= SU_VIEWHEIGHT;
830                 
831         if (ent->v.idealpitch)
832                 bits |= SU_IDEALPITCH;
833
834 // stuff the sigil bits into the high bits of items for sbar, or else
835 // mix in items2
836         val = GETEDICTFIELDVALUE(ent, eval_items2);
837
838         if (val)
839                 items = (int)ent->v.items | ((int)val->_float << 23);
840         else
841                 items = (int)ent->v.items | ((int)pr_global_struct->serverflags << 28);
842
843         bits |= SU_ITEMS;
844         
845         if ( (int)ent->v.flags & FL_ONGROUND)
846                 bits |= SU_ONGROUND;
847         
848         if ( ent->v.waterlevel >= 2)
849                 bits |= SU_INWATER;
850         
851         // dpprotocol
852         VectorClear(punchvector);
853         if ((val = GETEDICTFIELDVALUE(ent, eval_punchvector)))
854                 VectorCopy(val->vector, punchvector);
855
856         for (i=0 ; i<3 ; i++)
857         {
858                 if (ent->v.punchangle[i])
859                         bits |= (SU_PUNCH1<<i);
860                 if (punchvector[i]) // dpprotocol
861                         bits |= (SU_PUNCHVEC1<<i); // dpprotocol
862                 if (ent->v.velocity[i])
863                         bits |= (SU_VELOCITY1<<i);
864         }
865         
866         if (ent->v.weaponframe)
867                 bits |= SU_WEAPONFRAME;
868
869         if (ent->v.armorvalue)
870                 bits |= SU_ARMOR;
871
872 //      if (ent->v.weapon)
873                 bits |= SU_WEAPON;
874
875         if (bits >= 65536)
876                 bits |= SU_EXTEND1;
877         if (bits >= 16777216)
878                 bits |= SU_EXTEND2;
879
880 // send the data
881
882         MSG_WriteByte (msg, svc_clientdata);
883         MSG_WriteShort (msg, bits);
884         if (bits & SU_EXTEND1)
885                 MSG_WriteByte(msg, bits >> 16);
886         if (bits & SU_EXTEND2)
887                 MSG_WriteByte(msg, bits >> 24);
888
889         if (bits & SU_VIEWHEIGHT)
890                 MSG_WriteChar (msg, ent->v.view_ofs[2]);
891
892         if (bits & SU_IDEALPITCH)
893                 MSG_WriteChar (msg, ent->v.idealpitch);
894
895         for (i=0 ; i<3 ; i++)
896         {
897                 if (bits & (SU_PUNCH1<<i))
898                         MSG_WritePreciseAngle(msg, ent->v.punchangle[i]); // dpprotocol
899                 if (bits & (SU_PUNCHVEC1<<i)) // dpprotocol
900                         MSG_WriteFloatCoord(msg, punchvector[i]); // dpprotocol
901                 if (bits & (SU_VELOCITY1<<i))
902                         MSG_WriteChar (msg, ent->v.velocity[i]/16);
903         }
904
905 // [always sent]        if (bits & SU_ITEMS)
906         MSG_WriteLong (msg, items);
907
908         if (bits & SU_WEAPONFRAME)
909                 MSG_WriteByte (msg, ent->v.weaponframe);
910         if (bits & SU_ARMOR)
911                 MSG_WriteByte (msg, ent->v.armorvalue);
912         if (bits & SU_WEAPON)
913                 MSG_WriteByte (msg, SV_ModelIndex(pr_strings+ent->v.weaponmodel));
914         
915         MSG_WriteShort (msg, ent->v.health);
916         MSG_WriteByte (msg, ent->v.currentammo);
917         MSG_WriteByte (msg, ent->v.ammo_shells);
918         MSG_WriteByte (msg, ent->v.ammo_nails);
919         MSG_WriteByte (msg, ent->v.ammo_rockets);
920         MSG_WriteByte (msg, ent->v.ammo_cells);
921
922         if (standard_quake)
923         {
924                 MSG_WriteByte (msg, ent->v.weapon);
925         }
926         else
927         {
928                 for(i=0;i<32;i++)
929                 {
930                         if ( ((int)ent->v.weapon) & (1<<i) )
931                         {
932                                 MSG_WriteByte (msg, i);
933                                 break;
934                         }
935                 }
936         }
937 }
938
939 /*
940 =======================
941 SV_SendClientDatagram
942 =======================
943 */
944 qboolean SV_SendClientDatagram (client_t *client)
945 {
946         byte            buf[MAX_DATAGRAM];
947         sizebuf_t       msg;
948         
949         msg.data = buf;
950         msg.maxsize = sizeof(buf);
951         msg.cursize = 0;
952
953         MSG_WriteByte (&msg, svc_time);
954         MSG_WriteFloat (&msg, sv.time);
955
956 // add the client specific data to the datagram
957         SV_WriteClientdataToMessage (client->edict, &msg);
958
959         SV_WriteEntitiesToClient (client, client->edict, &msg);
960
961 // copy the server datagram if there is space
962         if (msg.cursize + sv.datagram.cursize < msg.maxsize)
963                 SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
964
965 // send the datagram
966         if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1)
967         {
968                 SV_DropClient (true);// if the message couldn't send, kick off
969                 return false;
970         }
971         
972         return true;
973 }
974
975 /*
976 =======================
977 SV_UpdateToReliableMessages
978 =======================
979 */
980 void SV_UpdateToReliableMessages (void)
981 {
982         int                     i, j;
983         client_t *client;
984
985 // check for changes to be sent over the reliable streams
986         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
987         {
988                 if (host_client->old_frags != host_client->edict->v.frags)
989                 {
990                         for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
991                         {
992                                 if (!client->active)
993                                         continue;
994                                 MSG_WriteByte (&client->message, svc_updatefrags);
995                                 MSG_WriteByte (&client->message, i);
996                                 MSG_WriteShort (&client->message, host_client->edict->v.frags);
997                         }
998
999                         host_client->old_frags = host_client->edict->v.frags;
1000                 }
1001         }
1002         
1003         for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
1004         {
1005                 if (!client->active)
1006                         continue;
1007                 SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1008         }
1009
1010         SZ_Clear (&sv.reliable_datagram);
1011 }
1012
1013
1014 /*
1015 =======================
1016 SV_SendNop
1017
1018 Send a nop message without trashing or sending the accumulated client
1019 message buffer
1020 =======================
1021 */
1022 void SV_SendNop (client_t *client)
1023 {
1024         sizebuf_t       msg;
1025         byte            buf[4];
1026         
1027         msg.data = buf;
1028         msg.maxsize = sizeof(buf);
1029         msg.cursize = 0;
1030
1031         MSG_WriteChar (&msg, svc_nop);
1032
1033         if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1)
1034                 SV_DropClient (true);   // if the message couldn't send, kick off
1035         client->last_message = realtime;
1036 }
1037
1038 /*
1039 =======================
1040 SV_SendClientMessages
1041 =======================
1042 */
1043 void SV_SendClientMessages (void)
1044 {
1045         int                     i;
1046         
1047 // update frags, names, etc
1048         SV_UpdateToReliableMessages ();
1049
1050 // build individual updates
1051         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1052         {
1053                 if (!host_client->active)
1054                         continue;
1055
1056                 if (host_client->spawned)
1057                 {
1058                         if (!SV_SendClientDatagram (host_client))
1059                                 continue;
1060                 }
1061                 else
1062                 {
1063                 // the player isn't totally in the game yet
1064                 // send small keepalive messages if too much time has passed
1065                 // send a full message when the next signon stage has been requested
1066                 // some other message data (name changes, etc) may accumulate 
1067                 // between signon stages
1068                         if (!host_client->sendsignon)
1069                         {
1070                                 if (realtime - host_client->last_message > 5)
1071                                         SV_SendNop (host_client);
1072                                 continue;       // don't send out non-signon messages
1073                         }
1074                 }
1075
1076                 // check for an overflowed message.  Should only happen
1077                 // on a very fucked up connection that backs up a lot, then
1078                 // changes level
1079                 if (host_client->message.overflowed)
1080                 {
1081                         SV_DropClient (true);
1082                         host_client->message.overflowed = false;
1083                         continue;
1084                 }
1085                         
1086                 if (host_client->message.cursize || host_client->dropasap)
1087                 {
1088                         if (!NET_CanSendMessage (host_client->netconnection))
1089                         {
1090 //                              I_Printf ("can't write\n");
1091                                 continue;
1092                         }
1093
1094                         if (host_client->dropasap)
1095                                 SV_DropClient (false);  // went to another level
1096                         else
1097                         {
1098                                 if (NET_SendMessage (host_client->netconnection, &host_client->message) == -1)
1099                                         SV_DropClient (true);   // if the message couldn't send, kick off
1100                                 SZ_Clear (&host_client->message);
1101                                 host_client->last_message = realtime;
1102                                 host_client->sendsignon = false;
1103                         }
1104                 }
1105         }
1106         
1107         
1108 // clear muzzle flashes
1109         SV_CleanupEnts ();
1110 }
1111
1112
1113 /*
1114 ==============================================================================
1115
1116 SERVER SPAWNING
1117
1118 ==============================================================================
1119 */
1120
1121 /*
1122 ================
1123 SV_ModelIndex
1124
1125 ================
1126 */
1127 int SV_ModelIndex (char *name)
1128 {
1129         int             i;
1130         
1131         if (!name || !name[0])
1132                 return 0;
1133
1134         for (i=0 ; i<MAX_MODELS && sv.model_precache[i] ; i++)
1135                 if (!strcmp(sv.model_precache[i], name))
1136                         return i;
1137         if (i==MAX_MODELS || !sv.model_precache[i])
1138                 Host_Error ("SV_ModelIndex: model %s not precached", name);
1139         return i;
1140 }
1141
1142 /*
1143 ================
1144 SV_CreateBaseline
1145
1146 ================
1147 */
1148 void SV_CreateBaseline (void)
1149 {
1150         int i, entnum, large;
1151         edict_t *svent;
1152
1153         // LordHavoc: clear *all* states (note just active ones)
1154         for (entnum = 0; entnum < MAX_EDICTS ; entnum++)
1155         {
1156                 // get the current server version
1157                 svent = EDICT_NUM(entnum);
1158
1159                 // LordHavoc: always clear state values, whether the entity is in use or not
1160                 ClearStateToDefault(&svent->baseline);
1161
1162                 if (svent->free)
1163                         continue;
1164                 if (entnum > svs.maxclients && !svent->v.modelindex)
1165                         continue;
1166
1167         //
1168                 // create entity baseline
1169         //
1170                 VectorCopy (svent->v.origin, svent->baseline.origin);
1171                 VectorCopy (svent->v.angles, svent->baseline.angles);
1172                 svent->baseline.frame = svent->v.frame;
1173                 svent->baseline.skin = svent->v.skin;
1174                 if (entnum > 0 && entnum <= svs.maxclients)
1175                 {
1176                         svent->baseline.colormap = entnum;
1177                         svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
1178                 }
1179                 else
1180                 {
1181                         svent->baseline.colormap = 0;
1182                         svent->baseline.modelindex = svent->v.modelindex; //SV_ModelIndex(pr_strings + svent->v.model);
1183                 }
1184
1185                 large = false;
1186                 if (svent->baseline.modelindex & 0xFF00 || svent->baseline.frame & 0xFF00)
1187                         large = true;
1188         //
1189                 // add to the message
1190         //
1191                 if (large)
1192                         MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1193                 else
1194                         MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1195                 MSG_WriteShort (&sv.signon, entnum);
1196
1197                 if (large)
1198                 {
1199                         MSG_WriteShort (&sv.signon, svent->baseline.modelindex);
1200                         MSG_WriteShort (&sv.signon, svent->baseline.frame);
1201                 }
1202                 else
1203                 {
1204                         MSG_WriteByte (&sv.signon, svent->baseline.modelindex);
1205                         MSG_WriteByte (&sv.signon, svent->baseline.frame);
1206                 }
1207                 MSG_WriteByte (&sv.signon, svent->baseline.colormap);
1208                 MSG_WriteByte (&sv.signon, svent->baseline.skin);
1209                 for (i=0 ; i<3 ; i++)
1210                 {
1211                         MSG_WriteFloatCoord(&sv.signon, svent->baseline.origin[i]);
1212                         MSG_WriteAngle(&sv.signon, svent->baseline.angles[i]);
1213                 }
1214         }
1215 }
1216
1217
1218 /*
1219 ================
1220 SV_SendReconnect
1221
1222 Tell all the clients that the server is changing levels
1223 ================
1224 */
1225 void SV_SendReconnect (void)
1226 {
1227         char    data[128];
1228         sizebuf_t       msg;
1229
1230         msg.data = data;
1231         msg.cursize = 0;
1232         msg.maxsize = sizeof(data);
1233
1234         MSG_WriteChar (&msg, svc_stufftext);
1235         MSG_WriteString (&msg, "reconnect\n");
1236         NET_SendToAll (&msg, 5);
1237         
1238         if (cls.state != ca_dedicated)
1239                 Cmd_ExecuteString ("reconnect\n", src_command);
1240 }
1241
1242
1243 /*
1244 ================
1245 SV_SaveSpawnparms
1246
1247 Grabs the current state of each client for saving across the
1248 transition to another level
1249 ================
1250 */
1251 void SV_SaveSpawnparms (void)
1252 {
1253         int             i, j;
1254
1255         svs.serverflags = pr_global_struct->serverflags;
1256
1257         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1258         {
1259                 if (!host_client->active)
1260                         continue;
1261
1262         // call the progs to get default spawn parms for the new client
1263                 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
1264                 PR_ExecuteProgram (pr_global_struct->SetChangeParms, "QC function SetChangeParms is missing");
1265                 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1266                         host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
1267         }
1268 }
1269
1270 qboolean isworldmodel;
1271
1272 /*
1273 ================
1274 SV_SpawnServer
1275
1276 This is called at the start of each level
1277 ================
1278 */
1279 extern float            scr_centertime_off;
1280
1281 void SV_SpawnServer (char *server)
1282 {
1283         edict_t         *ent;
1284         int                     i;
1285
1286         // let's not have any servers with no name
1287         if (hostname.string[0] == 0)
1288                 Cvar_Set ("hostname", "UNNAMED");
1289         scr_centertime_off = 0;
1290
1291         Con_DPrintf ("SpawnServer: %s\n",server);
1292         svs.changelevel_issued = false;         // now safe to issue another
1293
1294 //
1295 // tell all connected clients that we are going to a new level
1296 //
1297         if (sv.active)
1298         {
1299                 SV_SendReconnect ();
1300         }
1301
1302 //
1303 // make cvars consistant
1304 //
1305         if (coop.value)
1306                 Cvar_SetValue ("deathmatch", 0);
1307         current_skill = (int)(skill.value + 0.5);
1308         if (current_skill < 0)
1309                 current_skill = 0;
1310         if (current_skill > 3)
1311                 current_skill = 3;
1312
1313         Cvar_SetValue ("skill", (float)current_skill);
1314         
1315 //
1316 // set up the new server
1317 //
1318         Host_ClearMemory ();
1319
1320         memset (&sv, 0, sizeof(sv));
1321
1322         strcpy (sv.name, server);
1323
1324 // load progs to get entity field count
1325         PR_LoadProgs ();
1326
1327 // allocate server memory
1328         sv.max_edicts = MAX_EDICTS;
1329         
1330         sv.edicts = Hunk_AllocName (sv.max_edicts*pr_edict_size, "edicts");
1331
1332         sv.datagram.maxsize = sizeof(sv.datagram_buf);
1333         sv.datagram.cursize = 0;
1334         sv.datagram.data = sv.datagram_buf;
1335         
1336         sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1337         sv.reliable_datagram.cursize = 0;
1338         sv.reliable_datagram.data = sv.reliable_datagram_buf;
1339         
1340         sv.signon.maxsize = sizeof(sv.signon_buf);
1341         sv.signon.cursize = 0;
1342         sv.signon.data = sv.signon_buf;
1343         
1344 // leave slots at start for clients only
1345         sv.num_edicts = svs.maxclients+1;
1346         for (i=0 ; i<svs.maxclients ; i++)
1347         {
1348                 ent = EDICT_NUM(i+1);
1349                 svs.clients[i].edict = ent;
1350         }
1351         
1352         sv.state = ss_loading;
1353         sv.paused = false;
1354
1355         sv.time = 1.0;
1356         
1357         strcpy (sv.name, server);
1358         sprintf (sv.modelname,"maps/%s.bsp", server);
1359         isworldmodel = true; // LordHavoc: only load submodels on the world model
1360         sv.worldmodel = Mod_ForName (sv.modelname, false);
1361         isworldmodel = false;
1362         if (!sv.worldmodel)
1363         {
1364                 Con_Printf ("Couldn't spawn server %s\n", sv.modelname);
1365                 sv.active = false;
1366                 return;
1367         }
1368         sv.models[1] = sv.worldmodel;
1369         
1370 //
1371 // clear world interaction links
1372 //
1373         SV_ClearWorld ();
1374         
1375         sv.sound_precache[0] = pr_strings;
1376
1377         sv.model_precache[0] = pr_strings;
1378         sv.model_precache[1] = sv.modelname;
1379         for (i=1 ; i<sv.worldmodel->numsubmodels ; i++)
1380         {
1381                 sv.model_precache[1+i] = localmodels[i];
1382                 sv.models[i+1] = Mod_ForName (localmodels[i], false);
1383         }
1384
1385 //
1386 // load the rest of the entities
1387 //      
1388         ent = EDICT_NUM(0);
1389         memset (&ent->v, 0, progs->entityfields * 4);
1390         ent->free = false;
1391         ent->v.model = sv.worldmodel->name - pr_strings;
1392         ent->v.modelindex = 1;          // world model
1393         ent->v.solid = SOLID_BSP;
1394         ent->v.movetype = MOVETYPE_PUSH;
1395
1396         if (coop.value)
1397                 pr_global_struct->coop = coop.value;
1398         else
1399                 pr_global_struct->deathmatch = deathmatch.value;
1400
1401         pr_global_struct->mapname = sv.name - pr_strings;
1402
1403 // serverflags are for cross level information (sigils)
1404         pr_global_struct->serverflags = svs.serverflags;
1405         
1406         ED_LoadFromFile (sv.worldmodel->entities);
1407         // LordHavoc: clear world angles (to fix e3m3.bsp)
1408         VectorClear(sv.edicts->v.angles);
1409
1410         sv.active = true;
1411
1412 // all setup is completed, any further precache statements are errors
1413         sv.state = ss_active;
1414         
1415 // run two frames to allow everything to settle
1416         sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1417         SV_Physics ();
1418         SV_Physics ();
1419
1420 // create a baseline for more efficient communications
1421         SV_CreateBaseline ();
1422
1423 // send serverinfo to all connected clients
1424         for (i=0,host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1425                 if (host_client->active)
1426                         SV_SendServerinfo (host_client);
1427         
1428         Con_DPrintf ("Server spawned.\n");
1429 }