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