2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // sv_main.c -- server main program
24 static cvar_t sv_cullentities_pvs = {0, "sv_cullentities_pvs", "1"}; // fast but loose
25 static cvar_t sv_cullentities_trace = {0, "sv_cullentities_trace", "0"}; // tends to get false negatives, uses a timeout to keep entities visible a short time after becoming hidden
26 static cvar_t sv_cullentities_stats = {0, "sv_cullentities_stats", "0"};
27 static cvar_t sv_entpatch = {0, "sv_entpatch", "1"};
29 cvar_t sv_gameplayfix_grenadebouncedownslopes = {0, "sv_gameplayfix_grenadebouncedownslopes", "1"};
30 cvar_t sv_gameplayfix_noairborncorpse = {0, "sv_gameplayfix_noairborncorpse", "1"};
31 cvar_t sv_gameplayfix_stepdown = {0, "sv_gameplayfix_stepdown", "1"};
32 cvar_t sv_gameplayfix_stepwhilejumping = {0, "sv_gameplayfix_stepwhilejumping", "1"};
33 cvar_t sv_gameplayfix_swiminbmodels = {0, "sv_gameplayfix_swiminbmodels", "1"};
38 static char localmodels[MAX_MODELS][5]; // inline model names for precache
40 mempool_t *sv_edicts_mempool = NULL;
42 //============================================================================
44 extern void SV_Phys_Init (void);
45 extern void SV_World_Init (void);
46 static void SV_SaveEntFile_f(void);
57 Cmd_AddCommand("sv_saveentfile", SV_SaveEntFile_f);
58 Cvar_RegisterVariable (&sv_maxvelocity);
59 Cvar_RegisterVariable (&sv_gravity);
60 Cvar_RegisterVariable (&sv_friction);
61 Cvar_RegisterVariable (&sv_edgefriction);
62 Cvar_RegisterVariable (&sv_stopspeed);
63 Cvar_RegisterVariable (&sv_maxspeed);
64 Cvar_RegisterVariable (&sv_accelerate);
65 Cvar_RegisterVariable (&sv_idealpitchscale);
66 Cvar_RegisterVariable (&sv_aim);
67 Cvar_RegisterVariable (&sv_nostep);
68 Cvar_RegisterVariable (&sv_deltacompress);
69 Cvar_RegisterVariable (&sv_cullentities_pvs);
70 Cvar_RegisterVariable (&sv_cullentities_trace);
71 Cvar_RegisterVariable (&sv_cullentities_stats);
72 Cvar_RegisterVariable (&sv_entpatch);
73 Cvar_RegisterVariable (&sv_gameplayfix_grenadebouncedownslopes);
74 Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse);
75 Cvar_RegisterVariable (&sv_gameplayfix_stepdown);
76 Cvar_RegisterVariable (&sv_gameplayfix_stepwhilejumping);
77 Cvar_RegisterVariable (&sv_gameplayfix_swiminbmodels);
82 for (i = 0;i < MAX_MODELS;i++)
83 sprintf (localmodels[i], "*%i", i);
85 sv_edicts_mempool = Mem_AllocPool("server edicts", 0, NULL);
88 static void SV_SaveEntFile_f(void)
90 char basename[MAX_QPATH];
91 if (!sv.active || !sv.worldmodel)
93 Con_Print("Not running a server\n");
96 FS_StripExtension(sv.worldmodel->name, basename, sizeof(basename));
97 FS_WriteFile(va("%s.ent", basename), sv.worldmodel->brush.entities, strlen(sv.worldmodel->brush.entities));
101 =============================================================================
105 =============================================================================
112 Make sure the event gets sent to all clients
115 void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
119 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-18)
121 MSG_WriteByte (&sv.datagram, svc_particle);
122 MSG_WriteDPCoord (&sv.datagram, org[0]);
123 MSG_WriteDPCoord (&sv.datagram, org[1]);
124 MSG_WriteDPCoord (&sv.datagram, org[2]);
125 for (i=0 ; i<3 ; i++)
132 MSG_WriteChar (&sv.datagram, v);
134 MSG_WriteByte (&sv.datagram, count);
135 MSG_WriteByte (&sv.datagram, color);
142 Make sure the event gets sent to all clients
145 void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
147 if (modelindex >= 256 || startframe >= 256)
149 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-19)
151 MSG_WriteByte (&sv.datagram, svc_effect2);
152 MSG_WriteDPCoord (&sv.datagram, org[0]);
153 MSG_WriteDPCoord (&sv.datagram, org[1]);
154 MSG_WriteDPCoord (&sv.datagram, org[2]);
155 MSG_WriteShort (&sv.datagram, modelindex);
156 MSG_WriteShort (&sv.datagram, startframe);
157 MSG_WriteByte (&sv.datagram, framecount);
158 MSG_WriteByte (&sv.datagram, framerate);
162 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-17)
164 MSG_WriteByte (&sv.datagram, svc_effect);
165 MSG_WriteDPCoord (&sv.datagram, org[0]);
166 MSG_WriteDPCoord (&sv.datagram, org[1]);
167 MSG_WriteDPCoord (&sv.datagram, org[2]);
168 MSG_WriteByte (&sv.datagram, modelindex);
169 MSG_WriteByte (&sv.datagram, startframe);
170 MSG_WriteByte (&sv.datagram, framecount);
171 MSG_WriteByte (&sv.datagram, framerate);
179 Each entity can have eight independant sound sources, like voice,
182 Channel 0 is an auto-allocate channel, the others override anything
183 already running on that entity/channel pair.
185 An attenuation of 0 will play full volume everywhere in the level.
186 Larger attenuations will drop off. (max 4 attenuation)
190 void SV_StartSound (edict_t *entity, int channel, char *sample, int volume, float attenuation)
192 int sound_num, field_mask, i, ent;
194 if (volume < 0 || volume > 255)
195 Host_Error ("SV_StartSound: volume = %i", volume);
197 if (attenuation < 0 || attenuation > 4)
198 Host_Error ("SV_StartSound: attenuation = %f", attenuation);
200 if (channel < 0 || channel > 7)
201 Host_Error ("SV_StartSound: channel = %i", channel);
203 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
206 // find precache number for sound
207 for (sound_num=1 ; sound_num<MAX_SOUNDS && sv.sound_precache[sound_num] ; sound_num++)
208 if (!strcmp(sample, sv.sound_precache[sound_num]))
211 if ( sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num] )
213 Con_Printf("SV_StartSound: %s not precached\n", sample);
217 ent = NUM_FOR_EDICT(entity);
220 if (volume != DEFAULT_SOUND_PACKET_VOLUME)
221 field_mask |= SND_VOLUME;
222 if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
223 field_mask |= SND_ATTENUATION;
225 field_mask |= SND_LARGEENTITY;
226 if (sound_num >= 256 || channel >= 8)
227 field_mask |= SND_LARGESOUND;
229 // directed messages go only to the entity they are targeted on
230 MSG_WriteByte (&sv.datagram, svc_sound);
231 MSG_WriteByte (&sv.datagram, field_mask);
232 if (field_mask & SND_VOLUME)
233 MSG_WriteByte (&sv.datagram, volume);
234 if (field_mask & SND_ATTENUATION)
235 MSG_WriteByte (&sv.datagram, attenuation*64);
236 if (field_mask & SND_LARGEENTITY)
238 MSG_WriteShort (&sv.datagram, ent);
239 MSG_WriteByte (&sv.datagram, channel);
242 MSG_WriteShort (&sv.datagram, (ent<<3) | channel);
243 if (field_mask & SND_LARGESOUND)
244 MSG_WriteShort (&sv.datagram, sound_num);
246 MSG_WriteByte (&sv.datagram, sound_num);
247 for (i = 0;i < 3;i++)
248 MSG_WriteDPCoord (&sv.datagram, entity->v->origin[i]+0.5*(entity->v->mins[i]+entity->v->maxs[i]));
252 ==============================================================================
256 ==============================================================================
263 Sends the first message from the server to a connected client.
264 This will be sent on the initial connection and upon each server load.
267 void SV_SendServerinfo (client_t *client)
272 // edicts get reallocated on level changes, so we need to update it here
273 client->edict = EDICT_NUM(client->number + 1);
275 // LordHavoc: clear entityframe tracking
276 client->entityframenumber = 0;
277 if (client->entitydatabase4)
278 EntityFrame4_FreeDatabase(client->entitydatabase4);
279 client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool);
281 MSG_WriteByte (&client->message, svc_print);
282 snprintf (message, sizeof (message), "\002\nServer: %s build %s (progs %i crc)", gamename, buildstring, pr_crc);
283 MSG_WriteString (&client->message,message);
285 MSG_WriteByte (&client->message, svc_serverinfo);
286 MSG_WriteLong (&client->message, PROTOCOL_DARKPLACES5);
287 MSG_WriteByte (&client->message, svs.maxclients);
289 if (!coop.integer && deathmatch.integer)
290 MSG_WriteByte (&client->message, GAME_DEATHMATCH);
292 MSG_WriteByte (&client->message, GAME_COOP);
294 MSG_WriteString (&client->message,PR_GetString(sv.edicts->v->message));
296 for (s = sv.model_precache+1 ; *s ; s++)
297 MSG_WriteString (&client->message, *s);
298 MSG_WriteByte (&client->message, 0);
300 for (s = sv.sound_precache+1 ; *s ; s++)
301 MSG_WriteString (&client->message, *s);
302 MSG_WriteByte (&client->message, 0);
305 MSG_WriteByte (&client->message, svc_cdtrack);
306 MSG_WriteByte (&client->message, sv.edicts->v->sounds);
307 MSG_WriteByte (&client->message, sv.edicts->v->sounds);
310 MSG_WriteByte (&client->message, svc_setview);
311 MSG_WriteShort (&client->message, NUM_FOR_EDICT(client->edict));
313 MSG_WriteByte (&client->message, svc_signonnum);
314 MSG_WriteByte (&client->message, 1);
316 client->sendsignon = true;
317 client->spawned = false; // need prespawn, spawn, etc
324 Initializes a client_t for a new net connection. This will only be called
325 once for a player each game, not once for each level change.
328 void SV_ConnectClient (int clientnum, netconn_t *netconnection)
332 float spawn_parms[NUM_SPAWN_PARMS];
334 client = svs.clients + clientnum;
336 // set up the client_t
338 memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms));
339 memset (client, 0, sizeof(*client));
340 client->active = true;
341 client->netconnection = netconnection;
343 Con_DPrintf("Client %s connected\n", client->netconnection->address);
345 strcpy(client->name, "unconnected");
346 strcpy(client->old_name, "unconnected");
347 client->number = clientnum;
348 client->spawned = false;
349 client->edict = EDICT_NUM(clientnum+1);
350 client->message.data = client->msgbuf;
351 client->message.maxsize = sizeof(client->msgbuf);
352 client->message.allowoverflow = true; // we can catch it
355 memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms));
358 // call the progs to get default spawn parms for the new client
359 PR_ExecuteProgram (pr_global_struct->SetNewParms, "QC function SetNewParms is missing");
360 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
361 client->spawn_parms[i] = (&pr_global_struct->parm1)[i];
364 SV_SendServerinfo (client);
369 ===============================================================================
373 ===============================================================================
382 void SV_ClearDatagram (void)
384 SZ_Clear (&sv.datagram);
388 =============================================================================
390 The PVS must include a small area around the client to allow head bobbing
391 or other small motion on the client side. Otherwise, a bob might cause an
392 entity that should be visible to not show up, especially when the bob
395 =============================================================================
398 int sv_writeentitiestoclient_pvsbytes;
399 qbyte sv_writeentitiestoclient_pvs[MAX_MAP_LEAFS/8];
403 SV_WriteEntitiesToClient
408 void SV_WriteEntitiesToClient (client_t *client, edict_t *clent, sizebuf_t *msg)
410 int e, clentnum, bits, alpha, glowcolor, glowsize, scale, effects, lightsize;
411 int culled_pvs, culled_trace, visibleentities, totalentities;
413 vec3_t origin, angles, entmins, entmaxs, testorigin, testeye;
414 float nextfullupdate, alphaf;
417 entity_state_t *baseline; // LordHavoc: delta or startup baseline
420 Mod_CheckLoaded(sv.worldmodel);
422 // find the client's PVS
423 VectorAdd (clent->v->origin, clent->v->view_ofs, testeye);
425 if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
426 fatbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, testeye, 8, sv_writeentitiestoclient_pvs, sizeof(sv_writeentitiestoclient_pvs));
433 clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
434 // send all entities that touch the pvs
435 ent = NEXT_EDICT(sv.edicts);
436 for (e = 1;e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
440 // prevent delta compression against this frame (unless actually sent, which will restore this later)
441 nextfullupdate = client->nextfullupdate[e];
442 client->nextfullupdate[e] = -1;
444 if (ent != clent) // LordHavoc: always send player
446 if ((val = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)) && val->edict)
448 if (val->edict != clentnum)
450 // don't show to anyone else
454 bits |= U_VIEWMODEL; // show relative to the view
458 // LordHavoc: never draw something told not to display to this client
459 if ((val = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)) && val->edict == clentnum)
461 if ((val = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)) && val->edict && val->edict != clentnum)
468 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_size)))
469 glowsize = (int) val->_float >> 2;
470 if (glowsize > 255) glowsize = 255;
471 if (glowsize < 0) glowsize = 0;
473 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_trail)))
474 if (val->_float != 0)
477 if (ent->v->modelindex >= 0 && ent->v->modelindex < MAX_MODELS && *PR_GetString(ent->v->model))
479 model = sv.models[(int)ent->v->modelindex];
480 Mod_CheckLoaded(model);
485 if (ent != clent) // LordHavoc: always send player
486 if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
490 VectorCopy(ent->v->angles, angles);
491 VectorCopy(ent->v->origin, origin);
493 // ent has survived every check so far, check if it is visible
494 if (ent != clent && ((bits & U_VIEWMODEL) == 0))
496 // use the predicted origin
497 entmins[0] = origin[0] - 1.0f;
498 entmins[1] = origin[1] - 1.0f;
499 entmins[2] = origin[2] - 1.0f;
500 entmaxs[0] = origin[0] + 1.0f;
501 entmaxs[1] = origin[1] + 1.0f;
502 entmaxs[2] = origin[2] + 1.0f;
503 // using the model's bounding box to ensure things are visible regardless of their physics box
506 if (ent->v->angles[0] || ent->v->angles[2]) // pitch and roll
508 VectorAdd(entmins, model->rotatedmins, entmins);
509 VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
511 else if (ent->v->angles[1])
513 VectorAdd(entmins, model->yawmins, entmins);
514 VectorAdd(entmaxs, model->yawmaxs, entmaxs);
518 VectorAdd(entmins, model->normalmins, entmins);
519 VectorAdd(entmaxs, model->normalmaxs, entmaxs);
525 // if not touching a visible leaf
526 if (sv_cullentities_pvs.integer && fatbytes && sv.worldmodel && sv.worldmodel->brush.BoxTouchingPVS && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, sv_writeentitiestoclient_pvs, entmins, entmaxs))
532 // don't try to cull embedded brush models with this, they're sometimes huge (spanning several rooms)
533 if (sv_cullentities_trace.integer && (model == NULL || model->name[0] != '*'))
535 // LordHavoc: test random offsets, to maximize chance of detection
536 testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
537 testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
538 testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
540 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, testeye, testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
541 if (trace.fraction == 1)
542 client->visibletime[e] = realtime + 1;
545 //test nearest point on bbox
546 testorigin[0] = bound(entmins[0], testeye[0], entmaxs[0]);
547 testorigin[1] = bound(entmins[1], testeye[1], entmaxs[1]);
548 testorigin[2] = bound(entmins[2], testeye[2], entmaxs[2]);
550 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, testeye, testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
551 if (trace.fraction == 1)
552 client->visibletime[e] = realtime + 1;
553 else if (realtime > client->visibletime[e])
566 effects = ent->v->effects;
568 if ((val = GETEDICTFIELDVALUE(ent, eval_alpha)))
569 if (val->_float != 0)
570 alphaf = val->_float * 255.0f;
573 if ((val = GETEDICTFIELDVALUE(ent, eval_renderamt)))
574 if (val->_float != 0)
575 alphaf = val->_float;
579 alpha = bound(0, alphaf, 255);
581 if ((val = GETEDICTFIELDVALUE(ent, eval_scale)))
582 if ((scale = (int) (val->_float * 16.0)) == 0) scale = 16;
583 if (scale < 0) scale = 0;
584 if (scale > 255) scale = 255;
586 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_color)))
587 if (val->_float != 0)
588 glowcolor = (int) val->_float;
590 if ((val = GETEDICTFIELDVALUE(ent, eval_fullbright)))
591 if (val->_float != 0)
592 effects |= EF_FULLBRIGHT;
596 if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
600 // don't send if flagged for NODRAW and there are no effects
601 if (model->flags == 0 && ((effects & EF_NODRAW) || scale <= 0 || alpha <= 0))
604 else // no model and no effects
609 if (msg->maxsize - msg->cursize < 32) // LordHavoc: increased check from 16 to 32
611 Con_Print("packet overflow\n");
612 // mark the rest of the entities so they can't be delta compressed against this frame
613 for (;e < sv.num_edicts;e++)
615 client->nextfullupdate[e] = -1;
616 client->visibletime[e] = -1;
621 if ((val = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)) && val->edict == clentnum)
622 bits = bits | U_EXTERIORMODEL;
625 baseline = &ent->e->baseline;
627 if (((int)ent->v->effects & EF_DELTA) && sv_deltacompress.integer)
629 // every half second a full update is forced
630 if (realtime < client->nextfullupdate[e])
633 baseline = &ent->e->deltabaseline;
636 nextfullupdate = realtime + 0.5f;
639 nextfullupdate = realtime + 0.5f;
641 // restore nextfullupdate since this is being sent for real
642 client->nextfullupdate[e] = nextfullupdate;
645 bits |= U_LONGENTITY;
647 if (ent->v->movetype == MOVETYPE_STEP)
650 // LordHavoc: old stuff, but rewritten to have more exact tolerances
651 if (origin[0] != baseline->origin[0]) bits |= U_ORIGIN1;
652 if (origin[1] != baseline->origin[1]) bits |= U_ORIGIN2;
653 if (origin[2] != baseline->origin[2]) bits |= U_ORIGIN3;
654 if (((int)(angles[0]*(256.0/360.0)) & 255) != ((int)(baseline->angles[0]*(256.0/360.0)) & 255)) bits |= U_ANGLE1;
655 if (((int)(angles[1]*(256.0/360.0)) & 255) != ((int)(baseline->angles[1]*(256.0/360.0)) & 255)) bits |= U_ANGLE2;
656 if (((int)(angles[2]*(256.0/360.0)) & 255) != ((int)(baseline->angles[2]*(256.0/360.0)) & 255)) bits |= U_ANGLE3;
657 if (baseline->colormap != (qbyte) ent->v->colormap) bits |= U_COLORMAP;
658 if (baseline->skin != (qbyte) ent->v->skin) bits |= U_SKIN;
659 if ((baseline->frame & 0x00FF) != ((int) ent->v->frame & 0x00FF)) bits |= U_FRAME;
660 if ((baseline->effects & 0x00FF) != ((int) ent->v->effects & 0x00FF)) bits |= U_EFFECTS;
661 if ((baseline->modelindex & 0x00FF) != ((int) ent->v->modelindex & 0x00FF)) bits |= U_MODEL;
663 // LordHavoc: new stuff
664 if (baseline->alpha != alpha) bits |= U_ALPHA;
665 if (baseline->scale != scale) bits |= U_SCALE;
666 if (((int) baseline->effects & 0xFF00) != ((int) ent->v->effects & 0xFF00)) bits |= U_EFFECTS2;
667 if (baseline->glowsize != glowsize) bits |= U_GLOWSIZE;
668 if (baseline->glowcolor != glowcolor) bits |= U_GLOWCOLOR;
669 if (((int) baseline->frame & 0xFF00) != ((int) ent->v->frame & 0xFF00)) bits |= U_FRAME2;
670 if (((int) baseline->frame & 0xFF00) != ((int) ent->v->modelindex & 0xFF00)) bits |= U_MODEL2;
672 // update delta baseline
673 VectorCopy(ent->v->origin, ent->e->deltabaseline.origin);
674 VectorCopy(ent->v->angles, ent->e->deltabaseline.angles);
675 ent->e->deltabaseline.colormap = ent->v->colormap;
676 ent->e->deltabaseline.skin = ent->v->skin;
677 ent->e->deltabaseline.frame = ent->v->frame;
678 ent->e->deltabaseline.effects = ent->v->effects;
679 ent->e->deltabaseline.modelindex = ent->v->modelindex;
680 ent->e->deltabaseline.alpha = alpha;
681 ent->e->deltabaseline.scale = scale;
682 ent->e->deltabaseline.glowsize = glowsize;
683 ent->e->deltabaseline.glowcolor = glowcolor;
686 if (bits >= 16777216)
694 MSG_WriteByte (msg, bits);
695 if (bits & U_MOREBITS)
696 MSG_WriteByte (msg, bits>>8);
697 // LordHavoc: extend bytes have to be written here due to delta compression
698 if (bits & U_EXTEND1)
699 MSG_WriteByte (msg, bits>>16);
700 if (bits & U_EXTEND2)
701 MSG_WriteByte (msg, bits>>24);
703 // LordHavoc: old stuff
704 if (bits & U_LONGENTITY)
705 MSG_WriteShort (msg,e);
707 MSG_WriteByte (msg,e);
708 if (bits & U_MODEL) MSG_WriteByte(msg, ent->v->modelindex);
709 if (bits & U_FRAME) MSG_WriteByte(msg, ent->v->frame);
710 if (bits & U_COLORMAP) MSG_WriteByte(msg, ent->v->colormap);
711 if (bits & U_SKIN) MSG_WriteByte(msg, ent->v->skin);
712 if (bits & U_EFFECTS) MSG_WriteByte(msg, ent->v->effects);
713 if (bits & U_ORIGIN1) MSG_WriteDPCoord(msg, origin[0]);
714 if (bits & U_ANGLE1) MSG_WriteAngle(msg, angles[0]);
715 if (bits & U_ORIGIN2) MSG_WriteDPCoord(msg, origin[1]);
716 if (bits & U_ANGLE2) MSG_WriteAngle(msg, angles[1]);
717 if (bits & U_ORIGIN3) MSG_WriteDPCoord(msg, origin[2]);
718 if (bits & U_ANGLE3) MSG_WriteAngle(msg, angles[2]);
720 // LordHavoc: new stuff
721 if (bits & U_ALPHA) MSG_WriteByte(msg, alpha);
722 if (bits & U_SCALE) MSG_WriteByte(msg, scale);
723 if (bits & U_EFFECTS2) MSG_WriteByte(msg, (int)ent->v->effects >> 8);
724 if (bits & U_GLOWSIZE) MSG_WriteByte(msg, glowsize);
725 if (bits & U_GLOWCOLOR) MSG_WriteByte(msg, glowcolor);
726 if (bits & U_FRAME2) MSG_WriteByte(msg, (int)ent->v->frame >> 8);
727 if (bits & U_MODEL2) MSG_WriteByte(msg, (int)ent->v->modelindex >> 8);
730 if (sv_cullentities_stats.integer)
731 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d trace\n", client->name, totalentities, visibleentities, culled_pvs + culled_trace, culled_pvs, culled_trace);
734 static int numsendentities;
735 static entity_state_t sendentities[MAX_EDICTS];
736 static entity_state_t *sendentitiesindex[MAX_EDICTS];
738 void SV_PrepareEntitiesForSending(void)
744 // send all entities that touch the pvs
746 sendentitiesindex[0] = NULL;
747 for (e = 1, ent = NEXT_EDICT(sv.edicts);e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
749 sendentitiesindex[e] = NULL;
753 ClearStateToDefault(&cs);
756 VectorCopy(ent->v->origin, cs.origin);
757 VectorCopy(ent->v->angles, cs.angles);
759 cs.effects = (int)ent->v->effects;
760 cs.colormap = (qbyte)ent->v->colormap;
761 cs.skin = (qbyte)ent->v->skin;
762 cs.frame = (qbyte)ent->v->frame;
763 cs.viewmodelforclient = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)->edict;
764 cs.exteriormodelforclient = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)->edict;
765 cs.nodrawtoclient = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)->edict;
766 cs.drawonlytoclient = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)->edict;
767 cs.tagentity = GETEDICTFIELDVALUE(ent, eval_tag_entity)->edict;
768 cs.tagindex = (qbyte)GETEDICTFIELDVALUE(ent, eval_tag_index)->_float;
769 i = (int)(GETEDICTFIELDVALUE(ent, eval_glow_size)->_float * 0.25f);
770 cs.glowsize = (qbyte)bound(0, i, 255);
771 if (GETEDICTFIELDVALUE(ent, eval_glow_trail)->_float)
772 cs.flags |= RENDER_GLOWTRAIL;
775 i = (int)ent->v->modelindex;
776 if (i >= 1 && i < MAX_MODELS && *PR_GetString(ent->v->model))
780 f = (GETEDICTFIELDVALUE(ent, eval_alpha)->_float * 255.0f);
784 cs.alpha = (qbyte)bound(0, i, 255);
787 f = (GETEDICTFIELDVALUE(ent, eval_renderamt)->_float);
791 cs.alpha = (qbyte)bound(0, i, 255);
795 f = (GETEDICTFIELDVALUE(ent, eval_scale)->_float * 16.0f);
799 cs.scale = (qbyte)bound(0, i, 255);
803 f = (GETEDICTFIELDVALUE(ent, eval_glow_color)->_float);
805 cs.glowcolor = (int)f;
807 if (GETEDICTFIELDVALUE(ent, eval_fullbright)->_float)
808 cs.effects |= EF_FULLBRIGHT;
810 if (ent->v->movetype == MOVETYPE_STEP)
811 cs.flags |= RENDER_STEP;
812 if ((cs.effects & EF_LOWPRECISION) && cs.origin[0] >= -32768 && cs.origin[1] >= -32768 && cs.origin[2] >= -32768 && cs.origin[0] <= 32767 && cs.origin[1] <= 32767 && cs.origin[2] <= 32767)
813 cs.flags |= RENDER_LOWPRECISION;
814 if (ent->v->colormap >= 1024)
815 cs.flags |= RENDER_COLORMAPPED;
816 if (cs.viewmodelforclient)
817 cs.flags |= RENDER_VIEWMODEL; // show relative to the view
819 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[0]*256;
820 cs.light[0] = (unsigned short)bound(0, f, 65535);
821 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[1]*256;
822 cs.light[1] = (unsigned short)bound(0, f, 65535);
823 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[2]*256;
824 cs.light[2] = (unsigned short)bound(0, f, 65535);
825 f = GETEDICTFIELDVALUE(ent, eval_light_lev)->_float;
826 cs.light[3] = (unsigned short)bound(0, f, 65535);
827 cs.lightstyle = (qbyte)GETEDICTFIELDVALUE(ent, eval_style)->_float;
828 cs.lightpflags = (qbyte)GETEDICTFIELDVALUE(ent, eval_pflags)->_float;
830 if (gamemode == GAME_TENEBRAE)
832 // tenebrae's EF_FULLDYNAMIC conflicts with Q2's EF_NODRAW
836 cs.lightpflags |= PFLAGS_FULLDYNAMIC;
838 // tenebrae's EF_GREEN conflicts with DP's EF_ADDITIVE
846 cs.lightpflags |= PFLAGS_FULLDYNAMIC;
850 cs.specialvisibilityradius = 0;
851 if (cs.lightpflags & PFLAGS_FULLDYNAMIC)
852 cs.specialvisibilityradius = max(cs.specialvisibilityradius, cs.light[3]);
854 cs.specialvisibilityradius = max(cs.specialvisibilityradius, cs.glowsize * 4);
855 if (cs.flags & RENDER_GLOWTRAIL)
856 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
857 if (cs.effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
859 if (cs.effects & EF_BRIGHTFIELD)
860 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 80);
861 if (cs.effects & EF_MUZZLEFLASH)
862 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
863 if (cs.effects & EF_BRIGHTLIGHT)
864 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 400);
865 if (cs.effects & EF_DIMLIGHT)
866 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
867 if (cs.effects & EF_RED)
868 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
869 if (cs.effects & EF_BLUE)
870 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
871 if (cs.effects & EF_FLAME)
872 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 250);
873 if (cs.effects & EF_STARDUST)
874 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
877 if (numsendentities >= MAX_EDICTS)
879 // we can omit invisible entities with no effects that are not clients
880 // LordHavoc: this could kill tags attached to an invisible entity, I
881 // just hope we never have to support that case
882 if (cs.number > svs.maxclients && ((cs.effects & EF_NODRAW) || (!cs.modelindex && !cs.specialvisibilityradius)))
884 sendentitiesindex[e] = sendentities + numsendentities;
885 sendentities[numsendentities++] = cs;
889 static int sententitiesmark = 0;
890 static int sententities[MAX_EDICTS];
891 static int sententitiesconsideration[MAX_EDICTS];
892 static int sv_writeentitiestoclient_culled_pvs;
893 static int sv_writeentitiestoclient_culled_trace;
894 static int sv_writeentitiestoclient_visibleentities;
895 static int sv_writeentitiestoclient_totalentities;
896 //static entity_frame_t sv_writeentitiestoclient_entityframe;
897 static int sv_writeentitiestoclient_clentnum;
898 static vec3_t sv_writeentitiestoclient_testeye;
899 static client_t *sv_writeentitiestoclient_client;
901 void SV_MarkWriteEntityStateToClient(entity_state_t *s)
903 vec3_t entmins, entmaxs, lightmins, lightmaxs, testorigin;
906 if (sententitiesconsideration[s->number] == sententitiesmark)
908 sententitiesconsideration[s->number] = sententitiesmark;
909 // viewmodels don't have visibility checking
910 if (s->viewmodelforclient)
912 if (s->viewmodelforclient != sv_writeentitiestoclient_clentnum)
915 // never reject player
916 else if (s->number != sv_writeentitiestoclient_clentnum)
918 // check various rejection conditions
919 if (s->nodrawtoclient == sv_writeentitiestoclient_clentnum)
921 if (s->drawonlytoclient && s->drawonlytoclient != sv_writeentitiestoclient_clentnum)
923 if (s->effects & EF_NODRAW)
925 // LordHavoc: only send entities with a model or important effects
926 if (!s->modelindex && s->specialvisibilityradius == 0)
930 // tag attached entities simply check their parent
931 if (!sendentitiesindex[s->tagentity])
933 SV_MarkWriteEntityStateToClient(sendentitiesindex[s->tagentity]);
934 if (sententities[s->tagentity] != sententitiesmark)
937 // always send world submodels, they don't generate much traffic
938 else if ((model = sv.models[s->modelindex]) == NULL || model->name[0] != '*')
940 Mod_CheckLoaded(model);
941 // entity has survived every check so far, check if visible
942 // enlarged box to account for prediction (not that there is
943 // any currently, but still helps the 'run into a room and
944 // watch items pop up' problem)
945 entmins[0] = s->origin[0] - 32.0f;
946 entmins[1] = s->origin[1] - 32.0f;
947 entmins[2] = s->origin[2] - 32.0f;
948 entmaxs[0] = s->origin[0] + 32.0f;
949 entmaxs[1] = s->origin[1] + 32.0f;
950 entmaxs[2] = s->origin[2] + 32.0f;
951 // using the model's bounding box to ensure things are visible regardless of their physics box
954 if (s->angles[0] || s->angles[2]) // pitch and roll
956 VectorAdd(entmins, model->rotatedmins, entmins);
957 VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
959 else if (s->angles[1])
961 VectorAdd(entmins, model->yawmins, entmins);
962 VectorAdd(entmaxs, model->yawmaxs, entmaxs);
966 VectorAdd(entmins, model->normalmins, entmins);
967 VectorAdd(entmaxs, model->normalmaxs, entmaxs);
970 lightmins[0] = min(entmins[0], s->origin[0] - s->specialvisibilityradius);
971 lightmins[1] = min(entmins[1], s->origin[1] - s->specialvisibilityradius);
972 lightmins[2] = min(entmins[2], s->origin[2] - s->specialvisibilityradius);
973 lightmaxs[0] = max(entmaxs[0], s->origin[0] + s->specialvisibilityradius);
974 lightmaxs[1] = max(entmaxs[1], s->origin[1] + s->specialvisibilityradius);
975 lightmaxs[2] = max(entmaxs[2], s->origin[2] + s->specialvisibilityradius);
976 sv_writeentitiestoclient_totalentities++;
977 // if not touching a visible leaf
978 if (sv_cullentities_pvs.integer && sv_writeentitiestoclient_pvsbytes && sv.worldmodel && sv.worldmodel->brush.BoxTouchingPVS && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, sv_writeentitiestoclient_pvs, lightmins, lightmaxs))
980 sv_writeentitiestoclient_culled_pvs++;
983 // or not seen by random tracelines
984 if (sv_cullentities_trace.integer)
986 // LordHavoc: test center first
987 testorigin[0] = (entmins[0] + entmaxs[0]) * 0.5f;
988 testorigin[1] = (entmins[1] + entmaxs[1]) * 0.5f;
989 testorigin[2] = (entmins[2] + entmaxs[2]) * 0.5f;
990 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
991 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
992 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
995 // LordHavoc: test random offsets, to maximize chance of detection
996 testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
997 testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
998 testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
999 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
1000 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
1001 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
1004 if (s->specialvisibilityradius)
1006 // LordHavoc: test random offsets, to maximize chance of detection
1007 testorigin[0] = lhrandom(lightmins[0], lightmaxs[0]);
1008 testorigin[1] = lhrandom(lightmins[1], lightmaxs[1]);
1009 testorigin[2] = lhrandom(lightmins[2], lightmaxs[2]);
1010 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
1011 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
1012 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
1016 if (realtime > sv_writeentitiestoclient_client->visibletime[s->number])
1018 sv_writeentitiestoclient_culled_trace++;
1022 sv_writeentitiestoclient_visibleentities++;
1025 // this just marks it for sending
1026 // FIXME: it would be more efficient to send here, but the entity
1027 // compressor isn't that flexible
1028 sententities[s->number] = sententitiesmark;
1031 void SV_WriteEntitiesToClient(client_t *client, edict_t *clent, sizebuf_t *msg)
1036 entity_database4_t *d;
1038 entity_state_t *e, inactiveentitystate;
1042 // if there isn't enough space to accomplish anything, skip it
1043 if (msg->cursize + 24 > msg->maxsize)
1046 // prepare the buffer
1047 memset(&buf, 0, sizeof(buf));
1049 buf.maxsize = sizeof(data);
1051 d = client->entitydatabase4;
1053 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1054 if (!d->commit[i].numentities)
1056 // if commit buffer full, just don't bother writing an update this frame
1057 if (i == MAX_ENTITY_HISTORY)
1059 d->currentcommit = d->commit + i;
1061 // this state's number gets played around with later
1062 ClearStateToDefault(&inactiveentitystate);
1063 //inactiveentitystate = defaultstate;
1065 sv_writeentitiestoclient_client = client;
1067 sv_writeentitiestoclient_culled_pvs = 0;
1068 sv_writeentitiestoclient_culled_trace = 0;
1069 sv_writeentitiestoclient_visibleentities = 0;
1070 sv_writeentitiestoclient_totalentities = 0;
1072 Mod_CheckLoaded(sv.worldmodel);
1074 // find the client's PVS
1075 // the real place being tested from
1076 VectorAdd(clent->v->origin, clent->v->view_ofs, sv_writeentitiestoclient_testeye);
1077 sv_writeentitiestoclient_pvsbytes = 0;
1078 if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
1079 sv_writeentitiestoclient_pvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, sv_writeentitiestoclient_testeye, 8, sv_writeentitiestoclient_pvs, sizeof(sv_writeentitiestoclient_pvs));
1081 sv_writeentitiestoclient_clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
1085 // the place being reported (to consider the fact the client still
1086 // applies the view_ofs[2], so we have to only send the fractional part
1087 // of view_ofs[2], undoing what the client will redo)
1088 VectorCopy(sv_writeentitiestoclient_testeye, testorigin);
1089 i = (int) clent->v->view_ofs[2] & 255;
1092 testorigin[2] -= (float) i;
1094 for (i = 0;i < numsendentities;i++)
1095 SV_MarkWriteEntityStateToClient(sendentities + i);
1097 d->currentcommit->numentities = 0;
1098 d->currentcommit->framenum = ++client->entityframenumber;
1099 MSG_WriteByte(msg, svc_entities);
1100 MSG_WriteLong(msg, d->referenceframenum);
1101 MSG_WriteLong(msg, d->currentcommit->framenum);
1102 if (developer_networkentities.integer >= 1)
1104 Con_Printf("send svc_entities num:%i ref:%i (database: ref:%i commits:", d->currentcommit->framenum, d->referenceframenum, d->referenceframenum);
1105 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1106 if (d->commit[i].numentities)
1107 Con_Printf(" %i", d->commit[i].framenum);
1110 if (d->currententitynumber >= sv.max_edicts)
1113 startnumber = bound(1, d->currententitynumber, sv.max_edicts - 1);
1114 MSG_WriteShort(msg, startnumber);
1115 // reset currententitynumber so if the loop does not break it we will
1116 // start at beginning next frame (if it does break, it will set it)
1117 d->currententitynumber = 1;
1118 for (i = 0, n = startnumber;n < sv.max_edicts;n++)
1120 // find the old state to delta from
1121 e = EntityFrame4_GetReferenceEntity(d, n);
1122 // prepare the buffer
1125 if (sententities[n] == sententitiesmark)
1127 // entity exists, build an update (if empty there is no change)
1128 // find the state in the list
1129 for (;i < numsendentities && sendentities[i].number < n;i++);
1130 s = sendentities + i;
1132 Sys_Error("SV_WriteEntitiesToClient: s->number != n\n");
1134 if (s->exteriormodelforclient && s->exteriormodelforclient == sv_writeentitiestoclient_clentnum)
1136 s->flags |= RENDER_EXTERIORMODEL;
1137 EntityState_WriteUpdate(s, &buf, e);
1138 s->flags &= ~RENDER_EXTERIORMODEL;
1141 EntityState_WriteUpdate(s, &buf, e);
1145 s = &inactiveentitystate;
1149 // entity used to exist but doesn't anymore, send remove
1150 MSG_WriteShort(&buf, n | 0x8000);
1153 // if the commit is full, we're done this frame
1154 if (msg->cursize + buf.cursize > msg->maxsize - 4)
1156 // next frame we will continue where we left off
1159 // add the entity to the commit
1160 EntityFrame4_AddCommitEntity(d, s);
1161 // if the message is empty, skip out now
1164 // write the message to the packet
1165 SZ_Write(msg, buf.data, buf.cursize);
1168 d->currententitynumber = n;
1170 // remove world message (invalid, and thus a good terminator)
1171 MSG_WriteShort(msg, 0x8000);
1172 // write the number of the end entity
1173 MSG_WriteShort(msg, d->currententitynumber);
1175 d->currentcommit = NULL;
1177 if (sv_cullentities_stats.integer)
1178 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d trace\n", client->name, sv_writeentitiestoclient_totalentities, sv_writeentitiestoclient_visibleentities, sv_writeentitiestoclient_culled_pvs + sv_writeentitiestoclient_culled_trace, sv_writeentitiestoclient_culled_pvs, sv_writeentitiestoclient_culled_trace);
1188 void SV_CleanupEnts (void)
1193 ent = NEXT_EDICT(sv.edicts);
1194 for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
1195 ent->v->effects = (int)ent->v->effects & ~EF_MUZZLEFLASH;
1200 SV_WriteClientdataToMessage
1204 void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
1215 // send a damage message
1217 if (ent->v->dmg_take || ent->v->dmg_save)
1219 other = PROG_TO_EDICT(ent->v->dmg_inflictor);
1220 MSG_WriteByte (msg, svc_damage);
1221 MSG_WriteByte (msg, ent->v->dmg_save);
1222 MSG_WriteByte (msg, ent->v->dmg_take);
1223 for (i=0 ; i<3 ; i++)
1224 MSG_WriteDPCoord (msg, other->v->origin[i] + 0.5*(other->v->mins[i] + other->v->maxs[i]));
1226 ent->v->dmg_take = 0;
1227 ent->v->dmg_save = 0;
1231 // send the current viewpos offset from the view entity
1233 SV_SetIdealPitch (); // how much to look up / down ideally
1235 // a fixangle might get lost in a dropped packet. Oh well.
1236 if ( ent->v->fixangle )
1238 MSG_WriteByte (msg, svc_setangle);
1239 for (i=0 ; i < 3 ; i++)
1240 MSG_WriteAngle (msg, ent->v->angles[i] );
1241 ent->v->fixangle = 0;
1246 if (ent->v->view_ofs[2] != DEFAULT_VIEWHEIGHT)
1247 bits |= SU_VIEWHEIGHT;
1249 if (ent->v->idealpitch)
1250 bits |= SU_IDEALPITCH;
1252 // stuff the sigil bits into the high bits of items for sbar, or else
1254 val = GETEDICTFIELDVALUE(ent, eval_items2);
1257 items = (int)ent->v->items | ((int)val->_float << 23);
1259 items = (int)ent->v->items | ((int)pr_global_struct->serverflags << 28);
1263 if ( (int)ent->v->flags & FL_ONGROUND)
1264 bits |= SU_ONGROUND;
1266 if ( ent->v->waterlevel >= 2)
1269 // PROTOCOL_DARKPLACES
1270 VectorClear(punchvector);
1271 if ((val = GETEDICTFIELDVALUE(ent, eval_punchvector)))
1272 VectorCopy(val->vector, punchvector);
1275 if ((val = GETEDICTFIELDVALUE(ent, eval_viewzoom)))
1277 i = val->_float * 255.0f;
1281 i = bound(0, i, 255);
1285 if (viewzoom != 255)
1286 bits |= SU_VIEWZOOM;
1288 for (i=0 ; i<3 ; i++)
1290 if (ent->v->punchangle[i])
1291 bits |= (SU_PUNCH1<<i);
1292 if (punchvector[i]) // PROTOCOL_DARKPLACES
1293 bits |= (SU_PUNCHVEC1<<i); // PROTOCOL_DARKPLACES
1294 if (ent->v->velocity[i])
1295 bits |= (SU_VELOCITY1<<i);
1298 if (ent->v->weaponframe)
1299 bits |= SU_WEAPONFRAME;
1301 if (ent->v->armorvalue)
1308 if (bits >= 16777216)
1313 MSG_WriteByte (msg, svc_clientdata);
1314 MSG_WriteShort (msg, bits);
1315 if (bits & SU_EXTEND1)
1316 MSG_WriteByte(msg, bits >> 16);
1317 if (bits & SU_EXTEND2)
1318 MSG_WriteByte(msg, bits >> 24);
1320 if (bits & SU_VIEWHEIGHT)
1321 MSG_WriteChar (msg, ent->v->view_ofs[2]);
1323 if (bits & SU_IDEALPITCH)
1324 MSG_WriteChar (msg, ent->v->idealpitch);
1326 for (i=0 ; i<3 ; i++)
1328 if (bits & (SU_PUNCH1<<i))
1329 MSG_WritePreciseAngle(msg, ent->v->punchangle[i]); // PROTOCOL_DARKPLACES
1330 if (bits & (SU_PUNCHVEC1<<i)) // PROTOCOL_DARKPLACES
1331 MSG_WriteFloat(msg, punchvector[i]); // PROTOCOL_DARKPLACES
1332 if (bits & (SU_VELOCITY1<<i))
1333 MSG_WriteFloat(msg, ent->v->velocity[i]);
1336 // [always sent] if (bits & SU_ITEMS)
1337 MSG_WriteLong (msg, items);
1339 if (bits & SU_WEAPONFRAME)
1340 MSG_WriteByte (msg, ent->v->weaponframe);
1341 if (bits & SU_ARMOR)
1342 MSG_WriteByte (msg, ent->v->armorvalue);
1343 if (bits & SU_WEAPON)
1344 MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v->weaponmodel)));
1346 MSG_WriteShort (msg, ent->v->health);
1347 MSG_WriteByte (msg, ent->v->currentammo);
1348 MSG_WriteByte (msg, ent->v->ammo_shells);
1349 MSG_WriteByte (msg, ent->v->ammo_nails);
1350 MSG_WriteByte (msg, ent->v->ammo_rockets);
1351 MSG_WriteByte (msg, ent->v->ammo_cells);
1353 if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_NEXUIZ)
1357 if ( ((int)ent->v->weapon) & (1<<i) )
1359 MSG_WriteByte (msg, i);
1366 MSG_WriteByte (msg, ent->v->weapon);
1369 if (bits & SU_VIEWZOOM)
1370 MSG_WriteByte (msg, viewzoom);
1374 =======================
1375 SV_SendClientDatagram
1376 =======================
1378 static qbyte sv_sendclientdatagram_buf[NET_MAXMESSAGE]; // FIXME?
1379 qboolean SV_SendClientDatagram (client_t *client)
1383 msg.data = sv_sendclientdatagram_buf;
1384 msg.maxsize = (int)bound(50.0, client->netconnection->rate * host_realframetime, (double)sizeof(sv_sendclientdatagram_buf));
1387 MSG_WriteByte (&msg, svc_time);
1388 MSG_WriteFloat (&msg, sv.time);
1390 // add the client specific data to the datagram
1391 SV_WriteClientdataToMessage (client->edict, &msg);
1393 SV_WriteEntitiesToClient (client, client->edict, &msg);
1395 // copy the server datagram if there is space
1396 // FIXME: put in delayed queue of effects to send
1397 if (msg.cursize + sv.datagram.cursize <= msg.maxsize)
1398 SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
1400 // send the datagram
1401 if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1403 SV_DropClient (true);// if the message couldn't send, kick off
1411 =======================
1412 SV_UpdateToReliableMessages
1413 =======================
1415 void SV_UpdateToReliableMessages (void)
1422 // check for changes to be sent over the reliable streams
1423 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1425 // update the host_client fields we care about according to the entity fields
1426 sv_player = EDICT_NUM(i+1);
1427 s = PR_GetString(sv_player->v->netname);
1428 if (s != host_client->name)
1432 // point the string back at host_client->name to keep it safe
1433 strlcpy (host_client->name, s, sizeof (host_client->name));
1434 sv_player->v->netname = PR_SetString(host_client->name);
1436 if ((val = GETEDICTFIELDVALUE(sv_player, eval_clientcolors)) && host_client->colors != val->_float)
1437 host_client->colors = val->_float;
1438 host_client->frags = sv_player->v->frags;
1439 if (gamemode == GAME_NEHAHRA)
1440 if ((val = GETEDICTFIELDVALUE(sv_player, eval_pmodel)) && host_client->pmodel != val->_float)
1441 host_client->pmodel = val->_float;
1443 // if the fields changed, send messages about the changes
1444 if (strcmp(host_client->old_name, host_client->name))
1446 strcpy(host_client->old_name, host_client->name);
1447 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1449 if (!client->spawned || !client->netconnection)
1451 MSG_WriteByte (&client->message, svc_updatename);
1452 MSG_WriteByte (&client->message, i);
1453 MSG_WriteString (&client->message, host_client->name);
1456 if (host_client->old_colors != host_client->colors)
1458 host_client->old_colors = host_client->colors;
1459 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1461 if (!client->spawned || !client->netconnection)
1463 MSG_WriteByte (&client->message, svc_updatecolors);
1464 MSG_WriteByte (&client->message, i);
1465 MSG_WriteByte (&client->message, host_client->colors);
1468 if (host_client->old_frags != host_client->frags)
1470 host_client->old_frags = host_client->frags;
1471 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1473 if (!client->spawned || !client->netconnection)
1475 MSG_WriteByte (&client->message, svc_updatefrags);
1476 MSG_WriteByte (&client->message, i);
1477 MSG_WriteShort (&client->message, host_client->frags);
1482 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1483 if (client->netconnection)
1484 SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1486 SZ_Clear (&sv.reliable_datagram);
1491 =======================
1494 Send a nop message without trashing or sending the accumulated client
1496 =======================
1498 void SV_SendNop (client_t *client)
1504 msg.maxsize = sizeof(buf);
1507 MSG_WriteChar (&msg, svc_nop);
1509 if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1510 SV_DropClient (true); // if the message couldn't send, kick off
1511 client->last_message = realtime;
1515 =======================
1516 SV_SendClientMessages
1517 =======================
1519 void SV_SendClientMessages (void)
1521 int i, prepared = false;
1523 // update frags, names, etc
1524 SV_UpdateToReliableMessages();
1526 // build individual updates
1527 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1529 if (!host_client->active)
1531 if (!host_client->netconnection)
1533 SZ_Clear(&host_client->message);
1537 if (host_client->deadsocket || host_client->message.overflowed)
1539 SV_DropClient (true); // if the message couldn't send, kick off
1543 if (host_client->spawned)
1548 // only prepare entities once per frame
1549 SV_PrepareEntitiesForSending();
1551 if (!SV_SendClientDatagram (host_client))
1556 // the player isn't totally in the game yet
1557 // send small keepalive messages if too much time has passed
1558 // send a full message when the next signon stage has been requested
1559 // some other message data (name changes, etc) may accumulate
1560 // between signon stages
1561 if (!host_client->sendsignon)
1563 if (realtime - host_client->last_message > 5)
1564 SV_SendNop (host_client);
1565 continue; // don't send out non-signon messages
1569 if (host_client->message.cursize || host_client->dropasap)
1571 if (!NetConn_CanSendMessage (host_client->netconnection))
1574 if (host_client->dropasap)
1575 SV_DropClient (false); // went to another level
1578 if (NetConn_SendReliableMessage (host_client->netconnection, &host_client->message) == -1)
1579 SV_DropClient (true); // if the message couldn't send, kick off
1580 SZ_Clear (&host_client->message);
1581 host_client->last_message = realtime;
1582 host_client->sendsignon = false;
1587 // clear muzzle flashes
1593 ==============================================================================
1597 ==============================================================================
1606 int SV_ModelIndex (const char *name)
1610 if (!name || !name[0])
1613 for (i=0 ; i<MAX_MODELS && sv.model_precache[i] ; i++)
1614 if (!strcmp(sv.model_precache[i], name))
1616 if (i==MAX_MODELS || !sv.model_precache[i])
1617 Host_Error ("SV_ModelIndex: model %s not precached", name);
1621 #ifdef SV_QUAKEENTITIES
1628 void SV_CreateBaseline (void)
1630 int i, entnum, large;
1633 // LordHavoc: clear *all* states (note just active ones)
1634 for (entnum = 0;entnum < sv.max_edicts;entnum++)
1636 // get the current server version
1637 svent = EDICT_NUM(entnum);
1639 // LordHavoc: always clear state values, whether the entity is in use or not
1640 ClearStateToDefault(&svent->e->baseline);
1644 if (entnum > svs.maxclients && !svent->v->modelindex)
1647 // create entity baseline
1648 VectorCopy (svent->v->origin, svent->e->baseline.origin);
1649 VectorCopy (svent->v->angles, svent->e->baseline.angles);
1650 svent->e->baseline.frame = svent->v->frame;
1651 svent->e->baseline.skin = svent->v->skin;
1652 if (entnum > 0 && entnum <= svs.maxclients)
1654 svent->e->baseline.colormap = entnum;
1655 svent->e->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
1659 svent->e->baseline.colormap = 0;
1660 svent->e->baseline.modelindex = svent->v->modelindex;
1664 if (svent->e->baseline.modelindex & 0xFF00 || svent->e->baseline.frame & 0xFF00)
1667 // add to the message
1669 MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1671 MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1672 MSG_WriteShort (&sv.signon, entnum);
1676 MSG_WriteShort (&sv.signon, svent->e->baseline.modelindex);
1677 MSG_WriteShort (&sv.signon, svent->e->baseline.frame);
1681 MSG_WriteByte (&sv.signon, svent->e->baseline.modelindex);
1682 MSG_WriteByte (&sv.signon, svent->e->baseline.frame);
1684 MSG_WriteByte (&sv.signon, svent->e->baseline.colormap);
1685 MSG_WriteByte (&sv.signon, svent->e->baseline.skin);
1686 for (i=0 ; i<3 ; i++)
1688 MSG_WriteDPCoord(&sv.signon, svent->e->baseline.origin[i]);
1689 MSG_WriteAngle(&sv.signon, svent->e->baseline.angles[i]);
1700 Tell all the clients that the server is changing levels
1703 void SV_SendReconnect (void)
1710 msg.maxsize = sizeof(data);
1712 MSG_WriteChar (&msg, svc_stufftext);
1713 MSG_WriteString (&msg, "reconnect\n");
1714 NetConn_SendToAll (&msg, 5);
1716 if (cls.state != ca_dedicated)
1717 Cmd_ExecuteString ("reconnect\n", src_command);
1725 Grabs the current state of each client for saving across the
1726 transition to another level
1729 void SV_SaveSpawnparms (void)
1733 svs.serverflags = pr_global_struct->serverflags;
1735 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1737 if (!host_client->active)
1740 // call the progs to get default spawn parms for the new client
1741 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
1742 PR_ExecuteProgram (pr_global_struct->SetChangeParms, "QC function SetChangeParms is missing");
1743 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1744 host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
1748 void SV_IncreaseEdicts(void)
1752 int oldmax_edicts = sv.max_edicts;
1753 void *oldedictsengineprivate = sv.edictsengineprivate;
1754 void *oldedictsfields = sv.edictsfields;
1755 void *oldmoved_edicts = sv.moved_edicts;
1757 if (sv.max_edicts >= MAX_EDICTS)
1760 // links don't survive the transition, so unlink everything
1761 for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1764 SV_UnlinkEdict(sv.edicts + i);
1765 memset(&ent->e->areagrid, 0, sizeof(ent->e->areagrid));
1769 sv.max_edicts = min(sv.max_edicts + 256, MAX_EDICTS);
1770 sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1771 sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1772 sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1774 memcpy(sv.edictsengineprivate, oldedictsengineprivate, oldmax_edicts * sizeof(edict_engineprivate_t));
1775 memcpy(sv.edictsfields, oldedictsfields, oldmax_edicts * pr_edict_size);
1777 for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1779 ent->e = sv.edictsengineprivate + i;
1780 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1781 // link every entity except world
1783 SV_LinkEdict(ent, false);
1786 Mem_Free(oldedictsengineprivate);
1787 Mem_Free(oldedictsfields);
1788 Mem_Free(oldmoved_edicts);
1795 This is called at the start of each level
1798 extern float scr_centertime_off;
1800 void SV_SpawnServer (const char *server)
1805 model_t *worldmodel;
1806 char modelname[sizeof(sv.modelname)];
1808 Con_DPrintf("SpawnServer: %s\n", server);
1810 snprintf (modelname, sizeof(modelname), "maps/%s.bsp", server);
1811 worldmodel = Mod_ForName(modelname, false, true, true);
1812 if (!worldmodel || !worldmodel->TraceBox)
1814 Con_Printf("Couldn't load map %s\n", modelname);
1818 // let's not have any servers with no name
1819 if (hostname.string[0] == 0)
1820 Cvar_Set ("hostname", "UNNAMED");
1821 scr_centertime_off = 0;
1823 svs.changelevel_issued = false; // now safe to issue another
1826 // tell all connected clients that we are going to a new level
1832 // make sure cvars have been checked before opening the ports
1833 NetConn_ServerFrame();
1834 NetConn_OpenServerPorts(true);
1838 // make cvars consistant
1841 Cvar_SetValue ("deathmatch", 0);
1842 current_skill = bound(0, (int)(skill.value + 0.5), 3);
1844 Cvar_SetValue ("skill", (float)current_skill);
1847 // set up the new server
1849 Host_ClearMemory ();
1851 memset (&sv, 0, sizeof(sv));
1853 strlcpy (sv.name, server, sizeof (sv.name));
1855 // load progs to get entity field count
1858 // allocate server memory
1859 // start out with just enough room for clients and a reasonable estimate of entities
1860 sv.max_edicts = max(svs.maxclients + 1, 512);
1861 sv.max_edicts = min(sv.max_edicts, MAX_EDICTS);
1863 // clear the edict memory pool
1864 Mem_EmptyPool(sv_edicts_mempool);
1865 // edict_t structures (hidden from progs)
1866 sv.edicts = Mem_Alloc(sv_edicts_mempool, MAX_EDICTS * sizeof(edict_t));
1867 // engine private structures (hidden from progs)
1868 sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1869 // progs fields, often accessed by server
1870 sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1871 // used by PushMove to move back pushed entities
1872 sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1873 for (i = 0;i < sv.max_edicts;i++)
1875 ent = sv.edicts + i;
1876 ent->e = sv.edictsengineprivate + i;
1877 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1880 sv.datagram.maxsize = sizeof(sv.datagram_buf);
1881 sv.datagram.cursize = 0;
1882 sv.datagram.data = sv.datagram_buf;
1884 sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1885 sv.reliable_datagram.cursize = 0;
1886 sv.reliable_datagram.data = sv.reliable_datagram_buf;
1888 sv.signon.maxsize = sizeof(sv.signon_buf);
1889 sv.signon.cursize = 0;
1890 sv.signon.data = sv.signon_buf;
1892 // leave slots at start for clients only
1893 sv.num_edicts = svs.maxclients+1;
1895 sv.state = ss_loading;
1901 worldmodel->used = true;
1903 strlcpy (sv.name, server, sizeof (sv.name));
1904 strcpy(sv.modelname, modelname);
1905 sv.worldmodel = worldmodel;
1906 sv.models[1] = sv.worldmodel;
1909 // clear world interaction links
1913 sv.sound_precache[0] = "";
1915 sv.model_precache[0] = "";
1916 sv.model_precache[1] = sv.modelname;
1917 for (i = 1;i < sv.worldmodel->brush.numsubmodels;i++)
1919 sv.model_precache[i+1] = localmodels[i];
1920 sv.models[i+1] = Mod_ForName (localmodels[i], false, false, false);
1924 // load the rest of the entities
1927 memset (ent->v, 0, progs->entityfields * 4);
1928 ent->e->free = false;
1929 ent->v->model = PR_SetString(sv.modelname);
1930 ent->v->modelindex = 1; // world model
1931 ent->v->solid = SOLID_BSP;
1932 ent->v->movetype = MOVETYPE_PUSH;
1935 pr_global_struct->coop = coop.integer;
1937 pr_global_struct->deathmatch = deathmatch.integer;
1939 pr_global_struct->mapname = PR_SetString(sv.name);
1941 // serverflags are for cross level information (sigils)
1942 pr_global_struct->serverflags = svs.serverflags;
1944 // load replacement entity file if found
1946 if (sv_entpatch.integer)
1947 entities = FS_LoadFile(va("maps/%s.ent", sv.name), tempmempool, true);
1950 Con_Printf("Loaded maps/%s.ent\n", sv.name);
1951 ED_LoadFromFile (entities);
1955 ED_LoadFromFile (sv.worldmodel->brush.entities);
1958 // LordHavoc: clear world angles (to fix e3m3.bsp)
1959 VectorClear(sv.edicts->v->angles);
1963 // all setup is completed, any further precache statements are errors
1964 sv.state = ss_active;
1966 // run two frames to allow everything to settle
1967 for (i = 0;i < 2;i++)
1969 sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1975 #ifdef QUAKEENTITIES
1976 // create a baseline for more efficient communications
1977 SV_CreateBaseline ();
1980 // send serverinfo to all connected clients
1981 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1982 if (host_client->netconnection)
1983 SV_SendServerinfo(host_client);
1985 Con_DPrint("Server spawned.\n");
1986 NetConn_Heartbeat (2);