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_stepwhilejumping = {0, "sv_gameplayfix_stepwhilejumping", "1"};
32 cvar_t sv_gameplayfix_swiminbmodels = {0, "sv_gameplayfix_swiminbmodels", "1"};
37 static char localmodels[MAX_MODELS][5]; // inline model names for precache
39 mempool_t *sv_edicts_mempool = NULL;
41 //============================================================================
43 extern void SV_Phys_Init (void);
44 extern void SV_World_Init (void);
45 static void SV_SaveEntFile_f(void);
56 Cmd_AddCommand("sv_saveentfile", SV_SaveEntFile_f);
57 Cvar_RegisterVariable (&sv_maxvelocity);
58 Cvar_RegisterVariable (&sv_gravity);
59 Cvar_RegisterVariable (&sv_friction);
60 Cvar_RegisterVariable (&sv_edgefriction);
61 Cvar_RegisterVariable (&sv_stopspeed);
62 Cvar_RegisterVariable (&sv_maxspeed);
63 Cvar_RegisterVariable (&sv_accelerate);
64 Cvar_RegisterVariable (&sv_idealpitchscale);
65 Cvar_RegisterVariable (&sv_aim);
66 Cvar_RegisterVariable (&sv_nostep);
67 Cvar_RegisterVariable (&sv_deltacompress);
68 Cvar_RegisterVariable (&sv_cullentities_pvs);
69 Cvar_RegisterVariable (&sv_cullentities_trace);
70 Cvar_RegisterVariable (&sv_cullentities_stats);
71 Cvar_RegisterVariable (&sv_entpatch);
72 Cvar_RegisterVariable (&sv_gameplayfix_grenadebouncedownslopes);
73 Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse);
74 Cvar_RegisterVariable (&sv_gameplayfix_stepwhilejumping);
75 Cvar_RegisterVariable (&sv_gameplayfix_swiminbmodels);
80 for (i = 0;i < MAX_MODELS;i++)
81 sprintf (localmodels[i], "*%i", i);
83 sv_edicts_mempool = Mem_AllocPool("server edicts");
86 static void SV_SaveEntFile_f(void)
88 char basename[MAX_QPATH];
89 if (!sv.active || !sv.worldmodel)
91 Con_Print("Not running a server\n");
94 FS_StripExtension(sv.worldmodel->name, basename, sizeof(basename));
95 FS_WriteFile(va("%s.ent", basename), sv.worldmodel->brush.entities, strlen(sv.worldmodel->brush.entities));
99 =============================================================================
103 =============================================================================
110 Make sure the event gets sent to all clients
113 void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
117 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-18)
119 MSG_WriteByte (&sv.datagram, svc_particle);
120 MSG_WriteDPCoord (&sv.datagram, org[0]);
121 MSG_WriteDPCoord (&sv.datagram, org[1]);
122 MSG_WriteDPCoord (&sv.datagram, org[2]);
123 for (i=0 ; i<3 ; i++)
130 MSG_WriteChar (&sv.datagram, v);
132 MSG_WriteByte (&sv.datagram, count);
133 MSG_WriteByte (&sv.datagram, color);
140 Make sure the event gets sent to all clients
143 void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
145 if (modelindex >= 256 || startframe >= 256)
147 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-19)
149 MSG_WriteByte (&sv.datagram, svc_effect2);
150 MSG_WriteDPCoord (&sv.datagram, org[0]);
151 MSG_WriteDPCoord (&sv.datagram, org[1]);
152 MSG_WriteDPCoord (&sv.datagram, org[2]);
153 MSG_WriteShort (&sv.datagram, modelindex);
154 MSG_WriteShort (&sv.datagram, startframe);
155 MSG_WriteByte (&sv.datagram, framecount);
156 MSG_WriteByte (&sv.datagram, framerate);
160 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-17)
162 MSG_WriteByte (&sv.datagram, svc_effect);
163 MSG_WriteDPCoord (&sv.datagram, org[0]);
164 MSG_WriteDPCoord (&sv.datagram, org[1]);
165 MSG_WriteDPCoord (&sv.datagram, org[2]);
166 MSG_WriteByte (&sv.datagram, modelindex);
167 MSG_WriteByte (&sv.datagram, startframe);
168 MSG_WriteByte (&sv.datagram, framecount);
169 MSG_WriteByte (&sv.datagram, framerate);
177 Each entity can have eight independant sound sources, like voice,
180 Channel 0 is an auto-allocate channel, the others override anything
181 already running on that entity/channel pair.
183 An attenuation of 0 will play full volume everywhere in the level.
184 Larger attenuations will drop off. (max 4 attenuation)
188 void SV_StartSound (edict_t *entity, int channel, char *sample, int volume, float attenuation)
190 int sound_num, field_mask, i, ent;
192 if (volume < 0 || volume > 255)
193 Host_Error ("SV_StartSound: volume = %i", volume);
195 if (attenuation < 0 || attenuation > 4)
196 Host_Error ("SV_StartSound: attenuation = %f", attenuation);
198 if (channel < 0 || channel > 7)
199 Host_Error ("SV_StartSound: channel = %i", channel);
201 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
204 // find precache number for sound
205 for (sound_num=1 ; sound_num<MAX_SOUNDS && sv.sound_precache[sound_num] ; sound_num++)
206 if (!strcmp(sample, sv.sound_precache[sound_num]))
209 if ( sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num] )
211 Con_Printf("SV_StartSound: %s not precached\n", sample);
215 ent = NUM_FOR_EDICT(entity);
218 if (volume != DEFAULT_SOUND_PACKET_VOLUME)
219 field_mask |= SND_VOLUME;
220 if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
221 field_mask |= SND_ATTENUATION;
223 field_mask |= SND_LARGEENTITY;
224 if (sound_num >= 256 || channel >= 8)
225 field_mask |= SND_LARGESOUND;
227 // directed messages go only to the entity they are targeted on
228 MSG_WriteByte (&sv.datagram, svc_sound);
229 MSG_WriteByte (&sv.datagram, field_mask);
230 if (field_mask & SND_VOLUME)
231 MSG_WriteByte (&sv.datagram, volume);
232 if (field_mask & SND_ATTENUATION)
233 MSG_WriteByte (&sv.datagram, attenuation*64);
234 if (field_mask & SND_LARGEENTITY)
236 MSG_WriteShort (&sv.datagram, ent);
237 MSG_WriteByte (&sv.datagram, channel);
240 MSG_WriteShort (&sv.datagram, (ent<<3) | channel);
241 if (field_mask & SND_LARGESOUND)
242 MSG_WriteShort (&sv.datagram, sound_num);
244 MSG_WriteByte (&sv.datagram, sound_num);
245 for (i = 0;i < 3;i++)
246 MSG_WriteDPCoord (&sv.datagram, entity->v->origin[i]+0.5*(entity->v->mins[i]+entity->v->maxs[i]));
250 ==============================================================================
254 ==============================================================================
261 Sends the first message from the server to a connected client.
262 This will be sent on the initial connection and upon each server load.
265 void SV_SendServerinfo (client_t *client)
270 // edicts get reallocated on level changes, so we need to update it here
271 client->edict = EDICT_NUM(client->number + 1);
273 // LordHavoc: clear entityframe tracking
274 client->entityframenumber = 0;
275 if (client->entitydatabase4)
276 EntityFrame4_FreeDatabase(client->entitydatabase4);
277 client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool);
279 MSG_WriteByte (&client->message, svc_print);
280 snprintf (message, sizeof (message), "\002\nServer: %s build %s (progs %i crc)", gamename, buildstring, pr_crc);
281 MSG_WriteString (&client->message,message);
283 MSG_WriteByte (&client->message, svc_serverinfo);
284 MSG_WriteLong (&client->message, PROTOCOL_DARKPLACES5);
285 MSG_WriteByte (&client->message, svs.maxclients);
287 if (!coop.integer && deathmatch.integer)
288 MSG_WriteByte (&client->message, GAME_DEATHMATCH);
290 MSG_WriteByte (&client->message, GAME_COOP);
292 MSG_WriteString (&client->message,PR_GetString(sv.edicts->v->message));
294 for (s = sv.model_precache+1 ; *s ; s++)
295 MSG_WriteString (&client->message, *s);
296 MSG_WriteByte (&client->message, 0);
298 for (s = sv.sound_precache+1 ; *s ; s++)
299 MSG_WriteString (&client->message, *s);
300 MSG_WriteByte (&client->message, 0);
303 MSG_WriteByte (&client->message, svc_cdtrack);
304 MSG_WriteByte (&client->message, sv.edicts->v->sounds);
305 MSG_WriteByte (&client->message, sv.edicts->v->sounds);
308 MSG_WriteByte (&client->message, svc_setview);
309 MSG_WriteShort (&client->message, NUM_FOR_EDICT(client->edict));
311 MSG_WriteByte (&client->message, svc_signonnum);
312 MSG_WriteByte (&client->message, 1);
314 client->sendsignon = true;
315 client->spawned = false; // need prespawn, spawn, etc
322 Initializes a client_t for a new net connection. This will only be called
323 once for a player each game, not once for each level change.
326 void SV_ConnectClient (int clientnum, netconn_t *netconnection)
330 float spawn_parms[NUM_SPAWN_PARMS];
332 client = svs.clients + clientnum;
334 // set up the client_t
336 memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms));
337 memset (client, 0, sizeof(*client));
338 client->active = true;
339 client->netconnection = netconnection;
341 Con_DPrintf("Client %s connected\n", client->netconnection->address);
343 strcpy(client->name, "unconnected");
344 strcpy(client->old_name, "unconnected");
345 client->number = clientnum;
346 client->spawned = false;
347 client->edict = EDICT_NUM(clientnum+1);
348 client->message.data = client->msgbuf;
349 client->message.maxsize = sizeof(client->msgbuf);
350 client->message.allowoverflow = true; // we can catch it
353 memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms));
356 // call the progs to get default spawn parms for the new client
357 PR_ExecuteProgram (pr_global_struct->SetNewParms, "QC function SetNewParms is missing");
358 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
359 client->spawn_parms[i] = (&pr_global_struct->parm1)[i];
362 SV_SendServerinfo (client);
367 ===============================================================================
371 ===============================================================================
380 void SV_ClearDatagram (void)
382 SZ_Clear (&sv.datagram);
386 =============================================================================
388 The PVS must include a small area around the client to allow head bobbing
389 or other small motion on the client side. Otherwise, a bob might cause an
390 entity that should be visible to not show up, especially when the bob
393 =============================================================================
396 int sv_writeentitiestoclient_pvsbytes;
397 qbyte sv_writeentitiestoclient_pvs[MAX_MAP_LEAFS/8];
401 SV_WriteEntitiesToClient
406 void SV_WriteEntitiesToClient (client_t *client, edict_t *clent, sizebuf_t *msg)
408 int e, clentnum, bits, alpha, glowcolor, glowsize, scale, effects, lightsize;
409 int culled_pvs, culled_trace, visibleentities, totalentities;
411 vec3_t origin, angles, entmins, entmaxs, testorigin, testeye;
412 float nextfullupdate, alphaf;
415 entity_state_t *baseline; // LordHavoc: delta or startup baseline
418 Mod_CheckLoaded(sv.worldmodel);
420 // find the client's PVS
421 VectorAdd (clent->v->origin, clent->v->view_ofs, testeye);
423 if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
424 fatbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, testeye, 8, sv_writeentitiestoclient_pvs, sizeof(sv_writeentitiestoclient_pvs));
431 clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
432 // send all entities that touch the pvs
433 ent = NEXT_EDICT(sv.edicts);
434 for (e = 1;e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
438 // prevent delta compression against this frame (unless actually sent, which will restore this later)
439 nextfullupdate = client->nextfullupdate[e];
440 client->nextfullupdate[e] = -1;
442 if (ent != clent) // LordHavoc: always send player
444 if ((val = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)) && val->edict)
446 if (val->edict != clentnum)
448 // don't show to anyone else
452 bits |= U_VIEWMODEL; // show relative to the view
456 // LordHavoc: never draw something told not to display to this client
457 if ((val = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)) && val->edict == clentnum)
459 if ((val = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)) && val->edict && val->edict != clentnum)
466 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_size)))
467 glowsize = (int) val->_float >> 2;
468 if (glowsize > 255) glowsize = 255;
469 if (glowsize < 0) glowsize = 0;
471 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_trail)))
472 if (val->_float != 0)
475 if (ent->v->modelindex >= 0 && ent->v->modelindex < MAX_MODELS && *PR_GetString(ent->v->model))
477 model = sv.models[(int)ent->v->modelindex];
478 Mod_CheckLoaded(model);
483 if (ent != clent) // LordHavoc: always send player
484 if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
488 VectorCopy(ent->v->angles, angles);
489 VectorCopy(ent->v->origin, origin);
491 // ent has survived every check so far, check if it is visible
492 if (ent != clent && ((bits & U_VIEWMODEL) == 0))
494 // use the predicted origin
495 entmins[0] = origin[0] - 1.0f;
496 entmins[1] = origin[1] - 1.0f;
497 entmins[2] = origin[2] - 1.0f;
498 entmaxs[0] = origin[0] + 1.0f;
499 entmaxs[1] = origin[1] + 1.0f;
500 entmaxs[2] = origin[2] + 1.0f;
501 // using the model's bounding box to ensure things are visible regardless of their physics box
504 if (ent->v->angles[0] || ent->v->angles[2]) // pitch and roll
506 VectorAdd(entmins, model->rotatedmins, entmins);
507 VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
509 else if (ent->v->angles[1])
511 VectorAdd(entmins, model->yawmins, entmins);
512 VectorAdd(entmaxs, model->yawmaxs, entmaxs);
516 VectorAdd(entmins, model->normalmins, entmins);
517 VectorAdd(entmaxs, model->normalmaxs, entmaxs);
523 // if not touching a visible leaf
524 if (sv_cullentities_pvs.integer && fatbytes && sv.worldmodel && sv.worldmodel->brush.BoxTouchingPVS && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, sv_writeentitiestoclient_pvs, entmins, entmaxs))
530 // don't try to cull embedded brush models with this, they're sometimes huge (spanning several rooms)
531 if (sv_cullentities_trace.integer && (model == NULL || model->name[0] != '*'))
533 // LordHavoc: test random offsets, to maximize chance of detection
534 testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
535 testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
536 testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
538 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, testeye, testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
539 if (trace.fraction == 1)
540 client->visibletime[e] = realtime + 1;
543 //test nearest point on bbox
544 testorigin[0] = bound(entmins[0], testeye[0], entmaxs[0]);
545 testorigin[1] = bound(entmins[1], testeye[1], entmaxs[1]);
546 testorigin[2] = bound(entmins[2], testeye[2], entmaxs[2]);
548 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, testeye, testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
549 if (trace.fraction == 1)
550 client->visibletime[e] = realtime + 1;
551 else if (realtime > client->visibletime[e])
564 effects = ent->v->effects;
566 if ((val = GETEDICTFIELDVALUE(ent, eval_alpha)))
567 if (val->_float != 0)
568 alphaf = val->_float * 255.0f;
571 if ((val = GETEDICTFIELDVALUE(ent, eval_renderamt)))
572 if (val->_float != 0)
573 alphaf = val->_float;
577 alpha = bound(0, alphaf, 255);
579 if ((val = GETEDICTFIELDVALUE(ent, eval_scale)))
580 if ((scale = (int) (val->_float * 16.0)) == 0) scale = 16;
581 if (scale < 0) scale = 0;
582 if (scale > 255) scale = 255;
584 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_color)))
585 if (val->_float != 0)
586 glowcolor = (int) val->_float;
588 if ((val = GETEDICTFIELDVALUE(ent, eval_fullbright)))
589 if (val->_float != 0)
590 effects |= EF_FULLBRIGHT;
594 if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
598 // don't send if flagged for NODRAW and there are no effects
599 if (model->flags == 0 && ((effects & EF_NODRAW) || scale <= 0 || alpha <= 0))
602 else // no model and no effects
607 if (msg->maxsize - msg->cursize < 32) // LordHavoc: increased check from 16 to 32
609 Con_Print("packet overflow\n");
610 // mark the rest of the entities so they can't be delta compressed against this frame
611 for (;e < sv.num_edicts;e++)
613 client->nextfullupdate[e] = -1;
614 client->visibletime[e] = -1;
619 if ((val = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)) && val->edict == clentnum)
620 bits = bits | U_EXTERIORMODEL;
623 baseline = &ent->e->baseline;
625 if (((int)ent->v->effects & EF_DELTA) && sv_deltacompress.integer)
627 // every half second a full update is forced
628 if (realtime < client->nextfullupdate[e])
631 baseline = &ent->e->deltabaseline;
634 nextfullupdate = realtime + 0.5f;
637 nextfullupdate = realtime + 0.5f;
639 // restore nextfullupdate since this is being sent for real
640 client->nextfullupdate[e] = nextfullupdate;
643 bits |= U_LONGENTITY;
645 if (ent->v->movetype == MOVETYPE_STEP)
648 // LordHavoc: old stuff, but rewritten to have more exact tolerances
649 if (origin[0] != baseline->origin[0]) bits |= U_ORIGIN1;
650 if (origin[1] != baseline->origin[1]) bits |= U_ORIGIN2;
651 if (origin[2] != baseline->origin[2]) bits |= U_ORIGIN3;
652 if (((int)(angles[0]*(256.0/360.0)) & 255) != ((int)(baseline->angles[0]*(256.0/360.0)) & 255)) bits |= U_ANGLE1;
653 if (((int)(angles[1]*(256.0/360.0)) & 255) != ((int)(baseline->angles[1]*(256.0/360.0)) & 255)) bits |= U_ANGLE2;
654 if (((int)(angles[2]*(256.0/360.0)) & 255) != ((int)(baseline->angles[2]*(256.0/360.0)) & 255)) bits |= U_ANGLE3;
655 if (baseline->colormap != (qbyte) ent->v->colormap) bits |= U_COLORMAP;
656 if (baseline->skin != (qbyte) ent->v->skin) bits |= U_SKIN;
657 if ((baseline->frame & 0x00FF) != ((int) ent->v->frame & 0x00FF)) bits |= U_FRAME;
658 if ((baseline->effects & 0x00FF) != ((int) ent->v->effects & 0x00FF)) bits |= U_EFFECTS;
659 if ((baseline->modelindex & 0x00FF) != ((int) ent->v->modelindex & 0x00FF)) bits |= U_MODEL;
661 // LordHavoc: new stuff
662 if (baseline->alpha != alpha) bits |= U_ALPHA;
663 if (baseline->scale != scale) bits |= U_SCALE;
664 if (((int) baseline->effects & 0xFF00) != ((int) ent->v->effects & 0xFF00)) bits |= U_EFFECTS2;
665 if (baseline->glowsize != glowsize) bits |= U_GLOWSIZE;
666 if (baseline->glowcolor != glowcolor) bits |= U_GLOWCOLOR;
667 if (((int) baseline->frame & 0xFF00) != ((int) ent->v->frame & 0xFF00)) bits |= U_FRAME2;
668 if (((int) baseline->frame & 0xFF00) != ((int) ent->v->modelindex & 0xFF00)) bits |= U_MODEL2;
670 // update delta baseline
671 VectorCopy(ent->v->origin, ent->e->deltabaseline.origin);
672 VectorCopy(ent->v->angles, ent->e->deltabaseline.angles);
673 ent->e->deltabaseline.colormap = ent->v->colormap;
674 ent->e->deltabaseline.skin = ent->v->skin;
675 ent->e->deltabaseline.frame = ent->v->frame;
676 ent->e->deltabaseline.effects = ent->v->effects;
677 ent->e->deltabaseline.modelindex = ent->v->modelindex;
678 ent->e->deltabaseline.alpha = alpha;
679 ent->e->deltabaseline.scale = scale;
680 ent->e->deltabaseline.glowsize = glowsize;
681 ent->e->deltabaseline.glowcolor = glowcolor;
684 if (bits >= 16777216)
692 MSG_WriteByte (msg, bits);
693 if (bits & U_MOREBITS)
694 MSG_WriteByte (msg, bits>>8);
695 // LordHavoc: extend bytes have to be written here due to delta compression
696 if (bits & U_EXTEND1)
697 MSG_WriteByte (msg, bits>>16);
698 if (bits & U_EXTEND2)
699 MSG_WriteByte (msg, bits>>24);
701 // LordHavoc: old stuff
702 if (bits & U_LONGENTITY)
703 MSG_WriteShort (msg,e);
705 MSG_WriteByte (msg,e);
706 if (bits & U_MODEL) MSG_WriteByte(msg, ent->v->modelindex);
707 if (bits & U_FRAME) MSG_WriteByte(msg, ent->v->frame);
708 if (bits & U_COLORMAP) MSG_WriteByte(msg, ent->v->colormap);
709 if (bits & U_SKIN) MSG_WriteByte(msg, ent->v->skin);
710 if (bits & U_EFFECTS) MSG_WriteByte(msg, ent->v->effects);
711 if (bits & U_ORIGIN1) MSG_WriteDPCoord(msg, origin[0]);
712 if (bits & U_ANGLE1) MSG_WriteAngle(msg, angles[0]);
713 if (bits & U_ORIGIN2) MSG_WriteDPCoord(msg, origin[1]);
714 if (bits & U_ANGLE2) MSG_WriteAngle(msg, angles[1]);
715 if (bits & U_ORIGIN3) MSG_WriteDPCoord(msg, origin[2]);
716 if (bits & U_ANGLE3) MSG_WriteAngle(msg, angles[2]);
718 // LordHavoc: new stuff
719 if (bits & U_ALPHA) MSG_WriteByte(msg, alpha);
720 if (bits & U_SCALE) MSG_WriteByte(msg, scale);
721 if (bits & U_EFFECTS2) MSG_WriteByte(msg, (int)ent->v->effects >> 8);
722 if (bits & U_GLOWSIZE) MSG_WriteByte(msg, glowsize);
723 if (bits & U_GLOWCOLOR) MSG_WriteByte(msg, glowcolor);
724 if (bits & U_FRAME2) MSG_WriteByte(msg, (int)ent->v->frame >> 8);
725 if (bits & U_MODEL2) MSG_WriteByte(msg, (int)ent->v->modelindex >> 8);
728 if (sv_cullentities_stats.integer)
729 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);
732 static int numsendentities;
733 static entity_state_t sendentities[MAX_EDICTS];
734 static entity_state_t *sendentitiesindex[MAX_EDICTS];
736 void SV_PrepareEntitiesForSending(void)
742 // send all entities that touch the pvs
744 sendentitiesindex[0] = NULL;
745 for (e = 1, ent = NEXT_EDICT(sv.edicts);e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
747 sendentitiesindex[e] = NULL;
751 ClearStateToDefault(&cs);
754 VectorCopy(ent->v->origin, cs.origin);
755 VectorCopy(ent->v->angles, cs.angles);
757 cs.effects = (int)ent->v->effects;
758 cs.colormap = (qbyte)ent->v->colormap;
759 cs.skin = (qbyte)ent->v->skin;
760 cs.frame = (qbyte)ent->v->frame;
761 cs.viewmodelforclient = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)->edict;
762 cs.exteriormodelforclient = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)->edict;
763 cs.nodrawtoclient = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)->edict;
764 cs.drawonlytoclient = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)->edict;
765 cs.tagentity = GETEDICTFIELDVALUE(ent, eval_tag_entity)->edict;
766 cs.tagindex = (qbyte)GETEDICTFIELDVALUE(ent, eval_tag_index)->_float;
767 i = (int)(GETEDICTFIELDVALUE(ent, eval_glow_size)->_float * 0.25f);
768 cs.glowsize = (qbyte)bound(0, i, 255);
769 if (GETEDICTFIELDVALUE(ent, eval_glow_trail)->_float)
770 cs.flags |= RENDER_GLOWTRAIL;
773 i = (int)ent->v->modelindex;
774 if (i >= 1 && i < MAX_MODELS && *PR_GetString(ent->v->model))
778 f = (GETEDICTFIELDVALUE(ent, eval_alpha)->_float * 255.0f);
782 cs.alpha = (qbyte)bound(0, i, 255);
785 f = (GETEDICTFIELDVALUE(ent, eval_renderamt)->_float);
789 cs.alpha = (qbyte)bound(0, i, 255);
793 f = (GETEDICTFIELDVALUE(ent, eval_scale)->_float * 16.0f);
797 cs.scale = (qbyte)bound(0, i, 255);
801 f = (GETEDICTFIELDVALUE(ent, eval_glow_color)->_float);
803 cs.glowcolor = (int)f;
805 if (GETEDICTFIELDVALUE(ent, eval_fullbright)->_float)
806 cs.effects |= EF_FULLBRIGHT;
808 if (ent->v->movetype == MOVETYPE_STEP)
809 cs.flags |= RENDER_STEP;
810 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)
811 cs.flags |= RENDER_LOWPRECISION;
812 if (ent->v->colormap >= 1024)
813 cs.flags |= RENDER_COLORMAPPED;
814 if (cs.viewmodelforclient)
815 cs.flags |= RENDER_VIEWMODEL; // show relative to the view
817 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[0]*256;
818 cs.light[0] = (unsigned short)bound(0, f, 65535);
819 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[1]*256;
820 cs.light[1] = (unsigned short)bound(0, f, 65535);
821 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[2]*256;
822 cs.light[2] = (unsigned short)bound(0, f, 65535);
823 f = GETEDICTFIELDVALUE(ent, eval_light_lev)->_float;
824 cs.light[3] = (unsigned short)bound(0, f, 65535);
825 cs.lightstyle = (qbyte)GETEDICTFIELDVALUE(ent, eval_style)->_float;
826 cs.lightpflags = (qbyte)GETEDICTFIELDVALUE(ent, eval_pflags)->_float;
828 if (gamemode == GAME_TENEBRAE)
830 // tenebrae's EF_FULLDYNAMIC conflicts with Q2's EF_NODRAW
834 cs.lightpflags |= PFLAGS_FULLDYNAMIC;
836 // tenebrae's EF_GREEN conflicts with DP's EF_ADDITIVE
844 cs.lightpflags |= PFLAGS_FULLDYNAMIC;
848 cs.specialvisibilityradius = 0;
849 if (cs.lightpflags & PFLAGS_FULLDYNAMIC)
850 cs.specialvisibilityradius = max(cs.specialvisibilityradius, cs.light[3]);
852 cs.specialvisibilityradius = max(cs.specialvisibilityradius, cs.glowsize * 4);
853 if (cs.flags & RENDER_GLOWTRAIL)
854 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
855 if (cs.effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
857 if (cs.effects & EF_BRIGHTFIELD)
858 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 80);
859 if (cs.effects & EF_MUZZLEFLASH)
860 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
861 if (cs.effects & EF_BRIGHTLIGHT)
862 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 400);
863 if (cs.effects & EF_DIMLIGHT)
864 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
865 if (cs.effects & EF_RED)
866 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
867 if (cs.effects & EF_BLUE)
868 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
869 if (cs.effects & EF_FLAME)
870 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 250);
871 if (cs.effects & EF_STARDUST)
872 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
875 if (numsendentities >= MAX_EDICTS)
877 // we can omit invisible entities with no effects that are not clients
878 // LordHavoc: this could kill tags attached to an invisible entity, I
879 // just hope we never have to support that case
880 if (cs.number > svs.maxclients && ((cs.effects & EF_NODRAW) || (!cs.modelindex && !cs.specialvisibilityradius)))
882 sendentitiesindex[e] = sendentities + numsendentities;
883 sendentities[numsendentities++] = cs;
887 static int sententitiesmark = 0;
888 static int sententities[MAX_EDICTS];
889 static int sententitiesconsideration[MAX_EDICTS];
890 static int sv_writeentitiestoclient_culled_pvs;
891 static int sv_writeentitiestoclient_culled_trace;
892 static int sv_writeentitiestoclient_visibleentities;
893 static int sv_writeentitiestoclient_totalentities;
894 //static entity_frame_t sv_writeentitiestoclient_entityframe;
895 static int sv_writeentitiestoclient_clentnum;
896 static vec3_t sv_writeentitiestoclient_testeye;
897 static client_t *sv_writeentitiestoclient_client;
899 void SV_MarkWriteEntityStateToClient(entity_state_t *s)
901 vec3_t entmins, entmaxs, lightmins, lightmaxs, testorigin;
904 if (sententitiesconsideration[s->number] == sententitiesmark)
906 sententitiesconsideration[s->number] = sententitiesmark;
907 // viewmodels don't have visibility checking
908 if (s->viewmodelforclient)
910 if (s->viewmodelforclient != sv_writeentitiestoclient_clentnum)
913 // never reject player
914 else if (s->number != sv_writeentitiestoclient_clentnum)
916 // check various rejection conditions
917 if (s->nodrawtoclient == sv_writeentitiestoclient_clentnum)
919 if (s->drawonlytoclient && s->drawonlytoclient != sv_writeentitiestoclient_clentnum)
921 if (s->effects & EF_NODRAW)
923 // LordHavoc: only send entities with a model or important effects
924 if (!s->modelindex && s->specialvisibilityradius == 0)
928 // tag attached entities simply check their parent
929 if (!sendentitiesindex[s->tagentity])
931 SV_MarkWriteEntityStateToClient(sendentitiesindex[s->tagentity]);
932 if (sententities[s->tagentity] != sententitiesmark)
935 // always send world submodels, they don't generate much traffic
936 else if ((model = sv.models[s->modelindex]) == NULL || model->name[0] != '*')
938 Mod_CheckLoaded(model);
939 // entity has survived every check so far, check if visible
940 // enlarged box to account for prediction (not that there is
941 // any currently, but still helps the 'run into a room and
942 // watch items pop up' problem)
943 entmins[0] = s->origin[0] - 32.0f;
944 entmins[1] = s->origin[1] - 32.0f;
945 entmins[2] = s->origin[2] - 32.0f;
946 entmaxs[0] = s->origin[0] + 32.0f;
947 entmaxs[1] = s->origin[1] + 32.0f;
948 entmaxs[2] = s->origin[2] + 32.0f;
949 // using the model's bounding box to ensure things are visible regardless of their physics box
952 if (s->angles[0] || s->angles[2]) // pitch and roll
954 VectorAdd(entmins, model->rotatedmins, entmins);
955 VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
957 else if (s->angles[1])
959 VectorAdd(entmins, model->yawmins, entmins);
960 VectorAdd(entmaxs, model->yawmaxs, entmaxs);
964 VectorAdd(entmins, model->normalmins, entmins);
965 VectorAdd(entmaxs, model->normalmaxs, entmaxs);
968 lightmins[0] = min(entmins[0], s->origin[0] - s->specialvisibilityradius);
969 lightmins[1] = min(entmins[1], s->origin[1] - s->specialvisibilityradius);
970 lightmins[2] = min(entmins[2], s->origin[2] - s->specialvisibilityradius);
971 lightmaxs[0] = max(entmaxs[0], s->origin[0] + s->specialvisibilityradius);
972 lightmaxs[1] = max(entmaxs[1], s->origin[1] + s->specialvisibilityradius);
973 lightmaxs[2] = max(entmaxs[2], s->origin[2] + s->specialvisibilityradius);
974 sv_writeentitiestoclient_totalentities++;
975 // if not touching a visible leaf
976 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))
978 sv_writeentitiestoclient_culled_pvs++;
981 // or not seen by random tracelines
982 if (sv_cullentities_trace.integer)
984 // LordHavoc: test center first
985 testorigin[0] = (entmins[0] + entmaxs[0]) * 0.5f;
986 testorigin[1] = (entmins[1] + entmaxs[1]) * 0.5f;
987 testorigin[2] = (entmins[2] + entmaxs[2]) * 0.5f;
988 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
989 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
990 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
993 // LordHavoc: test random offsets, to maximize chance of detection
994 testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
995 testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
996 testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
997 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
998 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
999 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
1002 if (s->specialvisibilityradius)
1004 // LordHavoc: test random offsets, to maximize chance of detection
1005 testorigin[0] = lhrandom(lightmins[0], lightmaxs[0]);
1006 testorigin[1] = lhrandom(lightmins[1], lightmaxs[1]);
1007 testorigin[2] = lhrandom(lightmins[2], lightmaxs[2]);
1008 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
1009 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
1010 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
1014 if (realtime > sv_writeentitiestoclient_client->visibletime[s->number])
1016 sv_writeentitiestoclient_culled_trace++;
1020 sv_writeentitiestoclient_visibleentities++;
1023 // this just marks it for sending
1024 // FIXME: it would be more efficient to send here, but the entity
1025 // compressor isn't that flexible
1026 sententities[s->number] = sententitiesmark;
1029 void SV_WriteEntitiesToClient(client_t *client, edict_t *clent, sizebuf_t *msg)
1034 entity_database4_t *d;
1036 entity_state_t *e, inactiveentitystate;
1040 // if there isn't enough space to accomplish anything, skip it
1041 if (msg->cursize + 24 > msg->maxsize)
1044 // prepare the buffer
1045 memset(&buf, 0, sizeof(buf));
1047 buf.maxsize = sizeof(data);
1049 d = client->entitydatabase4;
1051 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1052 if (!d->commit[i].numentities)
1054 // if commit buffer full, just don't bother writing an update this frame
1055 if (i == MAX_ENTITY_HISTORY)
1057 d->currentcommit = d->commit + i;
1059 // this state's number gets played around with later
1060 ClearStateToDefault(&inactiveentitystate);
1061 //inactiveentitystate = defaultstate;
1063 sv_writeentitiestoclient_client = client;
1065 sv_writeentitiestoclient_culled_pvs = 0;
1066 sv_writeentitiestoclient_culled_trace = 0;
1067 sv_writeentitiestoclient_visibleentities = 0;
1068 sv_writeentitiestoclient_totalentities = 0;
1070 Mod_CheckLoaded(sv.worldmodel);
1072 // find the client's PVS
1073 // the real place being tested from
1074 VectorAdd(clent->v->origin, clent->v->view_ofs, sv_writeentitiestoclient_testeye);
1075 sv_writeentitiestoclient_pvsbytes = 0;
1076 if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
1077 sv_writeentitiestoclient_pvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, sv_writeentitiestoclient_testeye, 8, sv_writeentitiestoclient_pvs, sizeof(sv_writeentitiestoclient_pvs));
1079 sv_writeentitiestoclient_clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
1083 // the place being reported (to consider the fact the client still
1084 // applies the view_ofs[2], so we have to only send the fractional part
1085 // of view_ofs[2], undoing what the client will redo)
1086 VectorCopy(sv_writeentitiestoclient_testeye, testorigin);
1087 i = (int) clent->v->view_ofs[2] & 255;
1090 testorigin[2] -= (float) i;
1092 for (i = 0;i < numsendentities;i++)
1093 SV_MarkWriteEntityStateToClient(sendentities + i);
1095 d->currentcommit->numentities = 0;
1096 d->currentcommit->framenum = ++client->entityframenumber;
1097 MSG_WriteByte(msg, svc_entities);
1098 MSG_WriteLong(msg, d->referenceframenum);
1099 MSG_WriteLong(msg, d->currentcommit->framenum);
1100 if (developer_networkentities.integer >= 1)
1102 Con_Printf("send svc_entities num:%i ref:%i (database: ref:%i commits:", d->currentcommit->framenum, d->referenceframenum, d->referenceframenum);
1103 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1104 if (d->commit[i].numentities)
1105 Con_Printf(" %i", d->commit[i].framenum);
1108 if (d->currententitynumber >= sv.max_edicts)
1111 startnumber = bound(1, d->currententitynumber, sv.max_edicts - 1);
1112 MSG_WriteShort(msg, startnumber);
1113 // reset currententitynumber so if the loop does not break it we will
1114 // start at beginning next frame (if it does break, it will set it)
1115 d->currententitynumber = 1;
1116 for (i = 0, n = startnumber;n < sv.max_edicts;n++)
1118 // find the old state to delta from
1119 e = EntityFrame4_GetReferenceEntity(d, n);
1120 // prepare the buffer
1123 if (sententities[n] == sententitiesmark)
1125 // entity exists, build an update (if empty there is no change)
1126 // find the state in the list
1127 for (;i < numsendentities && sendentities[i].number < n;i++);
1128 s = sendentities + i;
1130 Sys_Error("SV_WriteEntitiesToClient: s->number != n\n");
1132 if (s->exteriormodelforclient && s->exteriormodelforclient == sv_writeentitiestoclient_clentnum)
1134 s->flags |= RENDER_EXTERIORMODEL;
1135 EntityState_Write(s, &buf, e);
1136 s->flags &= ~RENDER_EXTERIORMODEL;
1139 EntityState_Write(s, &buf, e);
1143 s = &inactiveentitystate;
1147 // entity used to exist but doesn't anymore, send remove
1148 MSG_WriteShort(&buf, n | 0x8000);
1151 // if the commit is full, we're done this frame
1152 if (msg->cursize + buf.cursize > msg->maxsize - 4)
1154 // next frame we will continue where we left off
1157 // add the entity to the commit
1158 EntityFrame4_AddCommitEntity(d, s);
1159 // if the message is empty, skip out now
1162 // write the message to the packet
1163 SZ_Write(msg, buf.data, buf.cursize);
1166 d->currententitynumber = n;
1168 // remove world message (invalid, and thus a good terminator)
1169 MSG_WriteShort(msg, 0x8000);
1170 // write the number of the end entity
1171 MSG_WriteShort(msg, d->currententitynumber);
1173 d->currentcommit = NULL;
1175 if (sv_cullentities_stats.integer)
1176 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);
1186 void SV_CleanupEnts (void)
1191 ent = NEXT_EDICT(sv.edicts);
1192 for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
1193 ent->v->effects = (int)ent->v->effects & ~EF_MUZZLEFLASH;
1198 SV_WriteClientdataToMessage
1202 void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
1213 // send a damage message
1215 if (ent->v->dmg_take || ent->v->dmg_save)
1217 other = PROG_TO_EDICT(ent->v->dmg_inflictor);
1218 MSG_WriteByte (msg, svc_damage);
1219 MSG_WriteByte (msg, ent->v->dmg_save);
1220 MSG_WriteByte (msg, ent->v->dmg_take);
1221 for (i=0 ; i<3 ; i++)
1222 MSG_WriteDPCoord (msg, other->v->origin[i] + 0.5*(other->v->mins[i] + other->v->maxs[i]));
1224 ent->v->dmg_take = 0;
1225 ent->v->dmg_save = 0;
1229 // send the current viewpos offset from the view entity
1231 SV_SetIdealPitch (); // how much to look up / down ideally
1233 // a fixangle might get lost in a dropped packet. Oh well.
1234 if ( ent->v->fixangle )
1236 MSG_WriteByte (msg, svc_setangle);
1237 for (i=0 ; i < 3 ; i++)
1238 MSG_WriteAngle (msg, ent->v->angles[i] );
1239 ent->v->fixangle = 0;
1244 if (ent->v->view_ofs[2] != DEFAULT_VIEWHEIGHT)
1245 bits |= SU_VIEWHEIGHT;
1247 if (ent->v->idealpitch)
1248 bits |= SU_IDEALPITCH;
1250 // stuff the sigil bits into the high bits of items for sbar, or else
1252 val = GETEDICTFIELDVALUE(ent, eval_items2);
1255 items = (int)ent->v->items | ((int)val->_float << 23);
1257 items = (int)ent->v->items | ((int)pr_global_struct->serverflags << 28);
1261 if ( (int)ent->v->flags & FL_ONGROUND)
1262 bits |= SU_ONGROUND;
1264 if ( ent->v->waterlevel >= 2)
1267 // PROTOCOL_DARKPLACES
1268 VectorClear(punchvector);
1269 if ((val = GETEDICTFIELDVALUE(ent, eval_punchvector)))
1270 VectorCopy(val->vector, punchvector);
1273 if ((val = GETEDICTFIELDVALUE(ent, eval_viewzoom)))
1275 i = val->_float * 255.0f;
1279 i = bound(0, i, 255);
1283 if (viewzoom != 255)
1284 bits |= SU_VIEWZOOM;
1286 for (i=0 ; i<3 ; i++)
1288 if (ent->v->punchangle[i])
1289 bits |= (SU_PUNCH1<<i);
1290 if (punchvector[i]) // PROTOCOL_DARKPLACES
1291 bits |= (SU_PUNCHVEC1<<i); // PROTOCOL_DARKPLACES
1292 if (ent->v->velocity[i])
1293 bits |= (SU_VELOCITY1<<i);
1296 if (ent->v->weaponframe)
1297 bits |= SU_WEAPONFRAME;
1299 if (ent->v->armorvalue)
1306 if (bits >= 16777216)
1311 MSG_WriteByte (msg, svc_clientdata);
1312 MSG_WriteShort (msg, bits);
1313 if (bits & SU_EXTEND1)
1314 MSG_WriteByte(msg, bits >> 16);
1315 if (bits & SU_EXTEND2)
1316 MSG_WriteByte(msg, bits >> 24);
1318 if (bits & SU_VIEWHEIGHT)
1319 MSG_WriteChar (msg, ent->v->view_ofs[2]);
1321 if (bits & SU_IDEALPITCH)
1322 MSG_WriteChar (msg, ent->v->idealpitch);
1324 for (i=0 ; i<3 ; i++)
1326 if (bits & (SU_PUNCH1<<i))
1327 MSG_WritePreciseAngle(msg, ent->v->punchangle[i]); // PROTOCOL_DARKPLACES
1328 if (bits & (SU_PUNCHVEC1<<i)) // PROTOCOL_DARKPLACES
1329 MSG_WriteFloat(msg, punchvector[i]); // PROTOCOL_DARKPLACES
1330 if (bits & (SU_VELOCITY1<<i))
1331 MSG_WriteFloat(msg, ent->v->velocity[i]);
1334 // [always sent] if (bits & SU_ITEMS)
1335 MSG_WriteLong (msg, items);
1337 if (bits & SU_WEAPONFRAME)
1338 MSG_WriteByte (msg, ent->v->weaponframe);
1339 if (bits & SU_ARMOR)
1340 MSG_WriteByte (msg, ent->v->armorvalue);
1341 if (bits & SU_WEAPON)
1342 MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v->weaponmodel)));
1344 MSG_WriteShort (msg, ent->v->health);
1345 MSG_WriteByte (msg, ent->v->currentammo);
1346 MSG_WriteByte (msg, ent->v->ammo_shells);
1347 MSG_WriteByte (msg, ent->v->ammo_nails);
1348 MSG_WriteByte (msg, ent->v->ammo_rockets);
1349 MSG_WriteByte (msg, ent->v->ammo_cells);
1351 if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_NEXUIZ)
1355 if ( ((int)ent->v->weapon) & (1<<i) )
1357 MSG_WriteByte (msg, i);
1364 MSG_WriteByte (msg, ent->v->weapon);
1367 if (bits & SU_VIEWZOOM)
1368 MSG_WriteByte (msg, viewzoom);
1372 =======================
1373 SV_SendClientDatagram
1374 =======================
1376 static qbyte sv_sendclientdatagram_buf[NET_MAXMESSAGE]; // FIXME?
1377 qboolean SV_SendClientDatagram (client_t *client)
1381 msg.data = sv_sendclientdatagram_buf;
1382 msg.maxsize = (int)bound(50.0, client->netconnection->rate * host_realframetime, (double)sizeof(sv_sendclientdatagram_buf));
1385 MSG_WriteByte (&msg, svc_time);
1386 MSG_WriteFloat (&msg, sv.time);
1388 // add the client specific data to the datagram
1389 SV_WriteClientdataToMessage (client->edict, &msg);
1391 SV_WriteEntitiesToClient (client, client->edict, &msg);
1393 // copy the server datagram if there is space
1394 // FIXME: put in delayed queue of effects to send
1395 if (msg.cursize + sv.datagram.cursize <= msg.maxsize)
1396 SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
1398 // send the datagram
1399 if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1401 SV_DropClient (true);// if the message couldn't send, kick off
1409 =======================
1410 SV_UpdateToReliableMessages
1411 =======================
1413 void SV_UpdateToReliableMessages (void)
1420 // check for changes to be sent over the reliable streams
1421 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1423 // update the host_client fields we care about according to the entity fields
1424 sv_player = EDICT_NUM(i+1);
1425 s = PR_GetString(sv_player->v->netname);
1426 if (s != host_client->name)
1430 // point the string back at host_client->name to keep it safe
1431 strlcpy (host_client->name, s, sizeof (host_client->name));
1432 sv_player->v->netname = PR_SetString(host_client->name);
1434 if ((val = GETEDICTFIELDVALUE(sv_player, eval_clientcolors)) && host_client->colors != val->_float)
1435 host_client->colors = val->_float;
1436 host_client->frags = sv_player->v->frags;
1437 if (gamemode == GAME_NEHAHRA)
1438 if ((val = GETEDICTFIELDVALUE(sv_player, eval_pmodel)) && host_client->pmodel != val->_float)
1439 host_client->pmodel = val->_float;
1441 // if the fields changed, send messages about the changes
1442 if (strcmp(host_client->old_name, host_client->name))
1444 strcpy(host_client->old_name, host_client->name);
1445 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1447 if (!client->spawned || !client->netconnection)
1449 MSG_WriteByte (&client->message, svc_updatename);
1450 MSG_WriteByte (&client->message, i);
1451 MSG_WriteString (&client->message, host_client->name);
1454 if (host_client->old_colors != host_client->colors)
1456 host_client->old_colors = host_client->colors;
1457 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1459 if (!client->spawned || !client->netconnection)
1461 MSG_WriteByte (&client->message, svc_updatecolors);
1462 MSG_WriteByte (&client->message, i);
1463 MSG_WriteByte (&client->message, host_client->colors);
1466 if (host_client->old_frags != host_client->frags)
1468 host_client->old_frags = host_client->frags;
1469 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1471 if (!client->spawned || !client->netconnection)
1473 MSG_WriteByte (&client->message, svc_updatefrags);
1474 MSG_WriteByte (&client->message, i);
1475 MSG_WriteShort (&client->message, host_client->frags);
1480 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1481 if (client->netconnection)
1482 SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1484 SZ_Clear (&sv.reliable_datagram);
1489 =======================
1492 Send a nop message without trashing or sending the accumulated client
1494 =======================
1496 void SV_SendNop (client_t *client)
1502 msg.maxsize = sizeof(buf);
1505 MSG_WriteChar (&msg, svc_nop);
1507 if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1508 SV_DropClient (true); // if the message couldn't send, kick off
1509 client->last_message = realtime;
1513 =======================
1514 SV_SendClientMessages
1515 =======================
1517 void SV_SendClientMessages (void)
1519 int i, prepared = false;
1521 // update frags, names, etc
1522 SV_UpdateToReliableMessages();
1524 // build individual updates
1525 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1527 if (!host_client->active)
1529 if (!host_client->netconnection)
1531 SZ_Clear(&host_client->message);
1535 if (host_client->deadsocket || host_client->message.overflowed)
1537 SV_DropClient (true); // if the message couldn't send, kick off
1541 if (host_client->spawned)
1546 // only prepare entities once per frame
1547 SV_PrepareEntitiesForSending();
1549 if (!SV_SendClientDatagram (host_client))
1554 // the player isn't totally in the game yet
1555 // send small keepalive messages if too much time has passed
1556 // send a full message when the next signon stage has been requested
1557 // some other message data (name changes, etc) may accumulate
1558 // between signon stages
1559 if (!host_client->sendsignon)
1561 if (realtime - host_client->last_message > 5)
1562 SV_SendNop (host_client);
1563 continue; // don't send out non-signon messages
1567 if (host_client->message.cursize || host_client->dropasap)
1569 if (!NetConn_CanSendMessage (host_client->netconnection))
1572 if (host_client->dropasap)
1573 SV_DropClient (false); // went to another level
1576 if (NetConn_SendReliableMessage (host_client->netconnection, &host_client->message) == -1)
1577 SV_DropClient (true); // if the message couldn't send, kick off
1578 SZ_Clear (&host_client->message);
1579 host_client->last_message = realtime;
1580 host_client->sendsignon = false;
1585 // clear muzzle flashes
1591 ==============================================================================
1595 ==============================================================================
1604 int SV_ModelIndex (const char *name)
1608 if (!name || !name[0])
1611 for (i=0 ; i<MAX_MODELS && sv.model_precache[i] ; i++)
1612 if (!strcmp(sv.model_precache[i], name))
1614 if (i==MAX_MODELS || !sv.model_precache[i])
1615 Host_Error ("SV_ModelIndex: model %s not precached", name);
1619 #ifdef SV_QUAKEENTITIES
1626 void SV_CreateBaseline (void)
1628 int i, entnum, large;
1631 // LordHavoc: clear *all* states (note just active ones)
1632 for (entnum = 0;entnum < sv.max_edicts;entnum++)
1634 // get the current server version
1635 svent = EDICT_NUM(entnum);
1637 // LordHavoc: always clear state values, whether the entity is in use or not
1638 ClearStateToDefault(&svent->e->baseline);
1642 if (entnum > svs.maxclients && !svent->v->modelindex)
1645 // create entity baseline
1646 VectorCopy (svent->v->origin, svent->e->baseline.origin);
1647 VectorCopy (svent->v->angles, svent->e->baseline.angles);
1648 svent->e->baseline.frame = svent->v->frame;
1649 svent->e->baseline.skin = svent->v->skin;
1650 if (entnum > 0 && entnum <= svs.maxclients)
1652 svent->e->baseline.colormap = entnum;
1653 svent->e->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
1657 svent->e->baseline.colormap = 0;
1658 svent->e->baseline.modelindex = svent->v->modelindex;
1662 if (svent->e->baseline.modelindex & 0xFF00 || svent->e->baseline.frame & 0xFF00)
1665 // add to the message
1667 MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1669 MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1670 MSG_WriteShort (&sv.signon, entnum);
1674 MSG_WriteShort (&sv.signon, svent->e->baseline.modelindex);
1675 MSG_WriteShort (&sv.signon, svent->e->baseline.frame);
1679 MSG_WriteByte (&sv.signon, svent->e->baseline.modelindex);
1680 MSG_WriteByte (&sv.signon, svent->e->baseline.frame);
1682 MSG_WriteByte (&sv.signon, svent->e->baseline.colormap);
1683 MSG_WriteByte (&sv.signon, svent->e->baseline.skin);
1684 for (i=0 ; i<3 ; i++)
1686 MSG_WriteDPCoord(&sv.signon, svent->e->baseline.origin[i]);
1687 MSG_WriteAngle(&sv.signon, svent->e->baseline.angles[i]);
1698 Tell all the clients that the server is changing levels
1701 void SV_SendReconnect (void)
1708 msg.maxsize = sizeof(data);
1710 MSG_WriteChar (&msg, svc_stufftext);
1711 MSG_WriteString (&msg, "reconnect\n");
1712 NetConn_SendToAll (&msg, 5);
1714 if (cls.state != ca_dedicated)
1715 Cmd_ExecuteString ("reconnect\n", src_command);
1723 Grabs the current state of each client for saving across the
1724 transition to another level
1727 void SV_SaveSpawnparms (void)
1731 svs.serverflags = pr_global_struct->serverflags;
1733 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1735 if (!host_client->active)
1738 // call the progs to get default spawn parms for the new client
1739 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
1740 PR_ExecuteProgram (pr_global_struct->SetChangeParms, "QC function SetChangeParms is missing");
1741 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1742 host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
1746 void SV_IncreaseEdicts(void)
1750 int oldmax_edicts = sv.max_edicts;
1751 void *oldedictsengineprivate = sv.edictsengineprivate;
1752 void *oldedictsfields = sv.edictsfields;
1753 void *oldmoved_edicts = sv.moved_edicts;
1755 if (sv.max_edicts >= MAX_EDICTS)
1758 // links don't survive the transition, so unlink everything
1759 for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1762 SV_UnlinkEdict(sv.edicts + i);
1763 memset(&ent->e->areagrid, 0, sizeof(ent->e->areagrid));
1767 sv.max_edicts = min(sv.max_edicts + 256, MAX_EDICTS);
1768 sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1769 sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1770 sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1772 memcpy(sv.edictsengineprivate, oldedictsengineprivate, oldmax_edicts * sizeof(edict_engineprivate_t));
1773 memcpy(sv.edictsfields, oldedictsfields, oldmax_edicts * pr_edict_size);
1775 for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1777 ent->e = sv.edictsengineprivate + i;
1778 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1779 // link every entity except world
1781 SV_LinkEdict(ent, false);
1784 Mem_Free(oldedictsengineprivate);
1785 Mem_Free(oldedictsfields);
1786 Mem_Free(oldmoved_edicts);
1793 This is called at the start of each level
1796 extern float scr_centertime_off;
1798 void SV_SpawnServer (const char *server)
1803 model_t *worldmodel;
1804 char modelname[sizeof(sv.modelname)];
1806 Con_DPrintf("SpawnServer: %s\n", server);
1808 snprintf (modelname, sizeof(modelname), "maps/%s.bsp", server);
1809 worldmodel = Mod_ForName(modelname, false, true, true);
1810 if (!worldmodel || !worldmodel->TraceBox)
1812 Con_Printf("Couldn't load map %s\n", modelname);
1816 // let's not have any servers with no name
1817 if (hostname.string[0] == 0)
1818 Cvar_Set ("hostname", "UNNAMED");
1819 scr_centertime_off = 0;
1821 svs.changelevel_issued = false; // now safe to issue another
1824 // tell all connected clients that we are going to a new level
1830 // make sure cvars have been checked before opening the ports
1831 NetConn_ServerFrame();
1832 NetConn_OpenServerPorts(true);
1836 // make cvars consistant
1839 Cvar_SetValue ("deathmatch", 0);
1840 current_skill = bound(0, (int)(skill.value + 0.5), 3);
1842 Cvar_SetValue ("skill", (float)current_skill);
1845 // set up the new server
1847 Host_ClearMemory ();
1849 memset (&sv, 0, sizeof(sv));
1851 strlcpy (sv.name, server, sizeof (sv.name));
1853 // load progs to get entity field count
1856 // allocate server memory
1857 // start out with just enough room for clients and a reasonable estimate of entities
1858 sv.max_edicts = max(svs.maxclients + 1, 512);
1859 sv.max_edicts = min(sv.max_edicts, MAX_EDICTS);
1861 // clear the edict memory pool
1862 Mem_EmptyPool(sv_edicts_mempool);
1863 // edict_t structures (hidden from progs)
1864 sv.edicts = Mem_Alloc(sv_edicts_mempool, MAX_EDICTS * sizeof(edict_t));
1865 // engine private structures (hidden from progs)
1866 sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1867 // progs fields, often accessed by server
1868 sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1869 // used by PushMove to move back pushed entities
1870 sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1871 for (i = 0;i < sv.max_edicts;i++)
1873 ent = sv.edicts + i;
1874 ent->e = sv.edictsengineprivate + i;
1875 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1878 sv.datagram.maxsize = sizeof(sv.datagram_buf);
1879 sv.datagram.cursize = 0;
1880 sv.datagram.data = sv.datagram_buf;
1882 sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1883 sv.reliable_datagram.cursize = 0;
1884 sv.reliable_datagram.data = sv.reliable_datagram_buf;
1886 sv.signon.maxsize = sizeof(sv.signon_buf);
1887 sv.signon.cursize = 0;
1888 sv.signon.data = sv.signon_buf;
1890 // leave slots at start for clients only
1891 sv.num_edicts = svs.maxclients+1;
1893 sv.state = ss_loading;
1899 worldmodel->used = true;
1901 strlcpy (sv.name, server, sizeof (sv.name));
1902 strcpy(sv.modelname, modelname);
1903 sv.worldmodel = worldmodel;
1904 sv.models[1] = sv.worldmodel;
1907 // clear world interaction links
1911 sv.sound_precache[0] = "";
1913 sv.model_precache[0] = "";
1914 sv.model_precache[1] = sv.modelname;
1915 for (i = 1;i < sv.worldmodel->brush.numsubmodels;i++)
1917 sv.model_precache[i+1] = localmodels[i];
1918 sv.models[i+1] = Mod_ForName (localmodels[i], false, false, false);
1922 // load the rest of the entities
1925 memset (ent->v, 0, progs->entityfields * 4);
1926 ent->e->free = false;
1927 ent->v->model = PR_SetString(sv.modelname);
1928 ent->v->modelindex = 1; // world model
1929 ent->v->solid = SOLID_BSP;
1930 ent->v->movetype = MOVETYPE_PUSH;
1933 pr_global_struct->coop = coop.integer;
1935 pr_global_struct->deathmatch = deathmatch.integer;
1937 pr_global_struct->mapname = PR_SetString(sv.name);
1939 // serverflags are for cross level information (sigils)
1940 pr_global_struct->serverflags = svs.serverflags;
1942 // load replacement entity file if found
1944 if (sv_entpatch.integer)
1945 entities = FS_LoadFile(va("maps/%s.ent", sv.name), tempmempool, true);
1948 Con_Printf("Loaded maps/%s.ent\n", sv.name);
1949 ED_LoadFromFile (entities);
1953 ED_LoadFromFile (sv.worldmodel->brush.entities);
1956 // LordHavoc: clear world angles (to fix e3m3.bsp)
1957 VectorClear(sv.edicts->v->angles);
1961 // all setup is completed, any further precache statements are errors
1962 sv.state = ss_active;
1964 // run two frames to allow everything to settle
1965 for (i = 0;i < 2;i++)
1967 sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1973 #ifdef QUAKEENTITIES
1974 // create a baseline for more efficient communications
1975 SV_CreateBaseline ();
1978 // send serverinfo to all connected clients
1979 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1980 if (host_client->netconnection)
1981 SV_SendServerinfo(host_client);
1983 Con_DPrint("Server spawned.\n");
1984 NetConn_Heartbeat (2);