1 /*
2 ===========================================================================
3 
4 Return to Castle Wolfenstein single player GPL Source Code
5 Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
6 
7 This file is part of the Return to Castle Wolfenstein single player GPL Source Code (“RTCW SP Source Code”).
8 
9 RTCW SP Source Code is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13 
14 RTCW SP Source Code is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18 
19 You should have received a copy of the GNU General Public License
20 along with RTCW SP Source Code.  If not, see <http://www.gnu.org/licenses/>.
21 
22 In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code.  If not, please request a copy in writing from id Software at the address below.
23 
24 If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
25 
26 ===========================================================================
27 */
28 
29 
30 #include "server.h"
31 
32 
33 /*
34 =============================================================================
35 
36 Delta encode a client frame onto the network channel
37 
38 A normal server packet will look like:
39 
40 4	sequence number (high bit set if an oversize fragment)
41 <optional reliable commands>
42 1	svc_snapshot
43 4	last client reliable command
44 4	serverTime
45 1	lastframe for delta compression
46 1	snapFlags
47 1	areaBytes
48 <areabytes>
49 <playerstate>
50 <packetentities>
51 
52 =============================================================================
53 */
54 
55 /*
56 =============
57 SV_EmitPacketEntities
58 
59 Writes a delta update of an entityState_t list to the message.
60 =============
61 */
SV_EmitPacketEntities(clientSnapshot_t * from,clientSnapshot_t * to,msg_t * msg)62 static void SV_EmitPacketEntities( clientSnapshot_t *from, clientSnapshot_t *to, msg_t *msg ) {
63 	entityState_t   *oldent, *newent;
64 	int oldindex, newindex;
65 	int oldnum, newnum;
66 	int from_num_entities;
67 
68 	// generate the delta update
69 	if ( !from ) {
70 		from_num_entities = 0;
71 	} else {
72 		from_num_entities = from->num_entities;
73 	}
74 
75 	newent = NULL;
76 	oldent = NULL;
77 	newindex = 0;
78 	oldindex = 0;
79 	while ( newindex < to->num_entities || oldindex < from_num_entities ) {
80 		if ( newindex >= to->num_entities ) {
81 			newnum = 9999;
82 		} else {
83 			newent = &svs.snapshotEntities[( to->first_entity + newindex ) % svs.numSnapshotEntities];
84 			newnum = newent->number;
85 		}
86 
87 		if ( oldindex >= from_num_entities ) {
88 			oldnum = 9999;
89 		} else {
90 			oldent = &svs.snapshotEntities[( from->first_entity + oldindex ) % svs.numSnapshotEntities];
91 			oldnum = oldent->number;
92 		}
93 
94 		if ( newnum == oldnum ) {
95 			// delta update from old position
96 			// because the force parm is qfalse, this will not result
97 			// in any bytes being emited if the entity has not changed at all
98 			MSG_WriteDeltaEntity( msg, oldent, newent, qfalse );
99 			oldindex++;
100 			newindex++;
101 			continue;
102 		}
103 
104 		if ( newnum < oldnum ) {
105 			// this is a new entity, send it from the baseline
106 			MSG_WriteDeltaEntity( msg, &sv.svEntities[newnum].baseline, newent, qtrue );
107 			newindex++;
108 			continue;
109 		}
110 
111 		if ( newnum > oldnum ) {
112 			// the old entity isn't present in the new message
113 			MSG_WriteDeltaEntity( msg, oldent, NULL, qtrue );
114 			oldindex++;
115 			continue;
116 		}
117 	}
118 
119 	MSG_WriteBits( msg, ( MAX_GENTITIES - 1 ), GENTITYNUM_BITS );   // end of packetentities
120 }
121 
122 
123 
124 /*
125 ==================
126 SV_WriteSnapshotToClient
127 ==================
128 */
SV_WriteSnapshotToClient(client_t * client,msg_t * msg)129 static void SV_WriteSnapshotToClient( client_t *client, msg_t *msg ) {
130 	clientSnapshot_t    *frame, *oldframe;
131 	int lastframe;
132 	int i;
133 	int snapFlags;
134 
135 	// this is the snapshot we are creating
136 	frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ];
137 
138 	// try to use a previous frame as the source for delta compressing the snapshot
139 	if ( client->deltaMessage <= 0 || client->state != CS_ACTIVE ) {
140 		// client is asking for a retransmit
141 		oldframe = NULL;
142 		lastframe = 0;
143 	} else if ( client->netchan.outgoingSequence - client->deltaMessage
144 				>= ( PACKET_BACKUP - 3 ) ) {
145 		// client hasn't gotten a good message through in a long time
146 		Com_DPrintf( "%s: Delta request from out of date packet.\n", client->name );
147 		oldframe = NULL;
148 		lastframe = 0;
149 	} else {
150 		// we have a valid snapshot to delta from
151 		oldframe = &client->frames[ client->deltaMessage & PACKET_MASK ];
152 		lastframe = client->netchan.outgoingSequence - client->deltaMessage;
153 
154 		// the snapshot's entities may still have rolled off the buffer, though
155 		if ( oldframe->first_entity <= svs.nextSnapshotEntities - svs.numSnapshotEntities ) {
156 			Com_DPrintf( "%s: Delta request from out of date entities.\n", client->name );
157 			oldframe = NULL;
158 			lastframe = 0;
159 		}
160 	}
161 
162 	MSG_WriteByte( msg, svc_snapshot );
163 
164 	// NOTE, MRE: now sent at the start of every message from server to client
165 	// let the client know which reliable clientCommands we have received
166 	//MSG_WriteLong( msg, client->lastClientCommand );
167 
168 	// send over the current server time so the client can drift
169 	// its view of time to try to match
170 	if( client->oldServerTime ) {
171 		// The server has not yet got an acknowledgement of the
172 		// new gamestate from this client, so continue to send it
173 		// a time as if the server has not restarted. Note from
174 		// the client's perspective this time is strictly speaking
175 		// incorrect, but since it'll be busy loading a map at
176 		// the time it doesn't really matter.
177 		MSG_WriteLong (msg, sv.time + client->oldServerTime);
178 	} else {
179 		MSG_WriteLong (msg, sv.time);
180 	}
181 
182 	// what we are delta'ing from
183 	MSG_WriteByte( msg, lastframe );
184 
185 	snapFlags = svs.snapFlagServerBit;
186 	if ( client->rateDelayed ) {
187 		snapFlags |= SNAPFLAG_RATE_DELAYED;
188 	}
189 	if ( client->state != CS_ACTIVE ) {
190 		snapFlags |= SNAPFLAG_NOT_ACTIVE;
191 	}
192 
193 	MSG_WriteByte( msg, snapFlags );
194 
195 	// send over the areabits
196 	MSG_WriteByte( msg, frame->areabytes );
197 	MSG_WriteData( msg, frame->areabits, frame->areabytes );
198 
199 	// delta encode the playerstate
200 	if ( oldframe ) {
201 		MSG_WriteDeltaPlayerstate( msg, &oldframe->ps, &frame->ps );
202 	} else {
203 		MSG_WriteDeltaPlayerstate( msg, NULL, &frame->ps );
204 	}
205 
206 	// delta encode the entities
207 	SV_EmitPacketEntities( oldframe, frame, msg );
208 
209 	// padding for rate debugging
210 	if ( sv_padPackets->integer ) {
211 		for ( i = 0 ; i < sv_padPackets->integer ; i++ ) {
212 			MSG_WriteByte( msg, svc_nop );
213 		}
214 	}
215 }
216 
217 
218 /*
219 ==================
220 SV_UpdateServerCommandsToClient
221 
222 (re)send all server commands the client hasn't acknowledged yet
223 ==================
224 */
SV_UpdateServerCommandsToClient(client_t * client,msg_t * msg)225 void SV_UpdateServerCommandsToClient( client_t *client, msg_t *msg ) {
226 	int i;
227 
228 	// write any unacknowledged serverCommands
229 	for ( i = client->reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) {
230 		MSG_WriteByte( msg, svc_serverCommand );
231 		MSG_WriteLong( msg, i );
232 		//MSG_WriteString( msg, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] );
233 		MSG_WriteString( msg, SV_GetReliableCommand( client, i & ( MAX_RELIABLE_COMMANDS - 1 ) ) );
234 	}
235 	client->reliableSent = client->reliableSequence;
236 }
237 
238 /*
239 =============================================================================
240 
241 Build a client snapshot structure
242 
243 =============================================================================
244 */
245 
246 typedef struct {
247 	int numSnapshotEntities;
248 	int snapshotEntities[MAX_SNAPSHOT_ENTITIES];
249 } snapshotEntityNumbers_t;
250 
251 /*
252 =======================
253 SV_QsortEntityNumbers
254 =======================
255 */
SV_QsortEntityNumbers(const void * a,const void * b)256 static int QDECL SV_QsortEntityNumbers( const void *a, const void *b ) {
257 	int *ea, *eb;
258 
259 	ea = (int *)a;
260 	eb = (int *)b;
261 
262 	if ( *ea == *eb ) {
263 		Com_Error( ERR_DROP, "SV_QsortEntityStates: duplicated entity" );
264 	}
265 
266 	if ( *ea < *eb ) {
267 		return -1;
268 	}
269 
270 	return 1;
271 }
272 
273 
274 /*
275 ===============
276 SV_AddEntToSnapshot
277 ===============
278 */
SV_AddEntToSnapshot(svEntity_t * svEnt,sharedEntity_t * gEnt,snapshotEntityNumbers_t * eNums)279 static void SV_AddEntToSnapshot( svEntity_t *svEnt, sharedEntity_t *gEnt, snapshotEntityNumbers_t *eNums ) {
280 	// if we have already added this entity to this snapshot, don't add again
281 	if ( svEnt->snapshotCounter == sv.snapshotCounter ) {
282 		return;
283 	}
284 	svEnt->snapshotCounter = sv.snapshotCounter;
285 
286 	// if we are full, silently discard entities
287 	if ( eNums->numSnapshotEntities == MAX_SNAPSHOT_ENTITIES ) {
288 		return;
289 	}
290 
291 	eNums->snapshotEntities[ eNums->numSnapshotEntities ] = gEnt->s.number;
292 	eNums->numSnapshotEntities++;
293 }
294 
295 /*
296 ===============
297 SV_AddEntitiesVisibleFromPoint
298 ===============
299 */
SV_AddEntitiesVisibleFromPoint(vec3_t origin,clientSnapshot_t * frame,snapshotEntityNumbers_t * eNums,qboolean portal,qboolean localClient)300 static void SV_AddEntitiesVisibleFromPoint( vec3_t origin, clientSnapshot_t *frame,
301 //									snapshotEntityNumbers_t *eNums, qboolean portal, clientSnapshot_t *oldframe, qboolean localClient ) {
302 //									snapshotEntityNumbers_t *eNums, qboolean portal ) {
303 											snapshotEntityNumbers_t *eNums, qboolean portal, qboolean localClient  ) {
304 	int e, i;
305 	sharedEntity_t *ent, *playerEnt;
306 	svEntity_t  *svEnt;
307 	int l;
308 	int clientarea, clientcluster;
309 	int leafnum;
310 	byte    *clientpvs;
311 	byte    *bitvector;
312 
313 	// during an error shutdown message we may need to transmit
314 	// the shutdown message after the server has shutdown, so
315 	// specfically check for it
316 	if ( !sv.state ) {
317 		return;
318 	}
319 
320 	leafnum = CM_PointLeafnum( origin );
321 	clientarea = CM_LeafArea( leafnum );
322 	clientcluster = CM_LeafCluster( leafnum );
323 
324 	// calculate the visible areas
325 	frame->areabytes = CM_WriteAreaBits( frame->areabits, clientarea );
326 
327 	clientpvs = CM_ClusterPVS( clientcluster );
328 
329 	playerEnt = SV_GentityNum( frame->ps.clientNum );
330 
331 	for ( e = 0 ; e < sv.num_entities ; e++ ) {
332 		ent = SV_GentityNum( e );
333 
334 		// never send entities that aren't linked in
335 		if ( !ent->r.linked ) {
336 			continue;
337 		}
338 
339 		if ( ent->s.number != e ) {
340 			Com_DPrintf( "FIXING ENT->S.NUMBER!!!\n" );
341 			ent->s.number = e;
342 		}
343 
344 		// entities can be flagged to explicitly not be sent to the client
345 		if ( ent->r.svFlags & SVF_NOCLIENT ) {
346 			continue;
347 		}
348 
349 		// entities can be flagged to be sent to only one client
350 		if ( ent->r.svFlags & SVF_SINGLECLIENT ) {
351 			if ( ent->r.singleClient != frame->ps.clientNum ) {
352 				continue;
353 			}
354 		}
355 		// entities can be flagged to be sent to everyone but one client
356 		if ( ent->r.svFlags & SVF_NOTSINGLECLIENT ) {
357 			if ( ent->r.singleClient == frame->ps.clientNum ) {
358 				continue;
359 			}
360 		}
361 
362 		svEnt = SV_SvEntityForGentity( ent );
363 
364 		// don't double add an entity through portals
365 		if ( svEnt->snapshotCounter == sv.snapshotCounter ) {
366 			continue;
367 		}
368 
369 		// if this client is viewing from a camera, only add ents visible from portal ents
370 		if ( ( playerEnt->s.eFlags & EF_VIEWING_CAMERA ) && !portal ) {
371 			if ( ent->r.svFlags & SVF_PORTAL ) {
372 				SV_AddEntToSnapshot( svEnt, ent, eNums );
373 //				SV_AddEntitiesVisibleFromPoint( ent->s.origin2, frame, eNums, qtrue, oldframe, localClient );
374 				SV_AddEntitiesVisibleFromPoint( ent->s.origin2, frame, eNums, qtrue, localClient );
375 			}
376 			continue;
377 		}
378 
379 		// broadcast entities are always sent
380 		if ( ent->r.svFlags & SVF_BROADCAST ) {
381 			SV_AddEntToSnapshot( svEnt, ent, eNums );
382 			continue;
383 		}
384 
385 		// ignore if not touching a PV leaf
386 		// check area
387 		if ( !CM_AreasConnected( clientarea, svEnt->areanum ) ) {
388 			// doors can legally straddle two areas, so
389 			// we may need to check another one
390 			if ( !CM_AreasConnected( clientarea, svEnt->areanum2 ) ) {
391 				goto notVisible;    // blocked by a door
392 			}
393 		}
394 
395 		bitvector = clientpvs;
396 
397 		// check individual leafs
398 		if ( !svEnt->numClusters ) {
399 			goto notVisible;
400 		}
401 		l = 0;
402 		for ( i = 0 ; i < svEnt->numClusters ; i++ ) {
403 			l = svEnt->clusternums[i];
404 			if ( bitvector[l >> 3] & ( 1 << ( l & 7 ) ) ) {
405 				break;
406 			}
407 		}
408 
409 		// if we haven't found it to be visible,
410 		// check overflow clusters that coudln't be stored
411 		if ( i == svEnt->numClusters ) {
412 			if ( svEnt->lastCluster ) {
413 				for ( ; l <= svEnt->lastCluster ; l++ ) {
414 					if ( bitvector[l >> 3] & ( 1 << ( l & 7 ) ) ) {
415 						break;
416 					}
417 				}
418 				if ( l == svEnt->lastCluster ) {
419 					goto notVisible;    // not visible
420 				}
421 			} else {
422 				goto notVisible;
423 			}
424 		}
425 
426 		//----(SA) added "visibility dummies"
427 		if ( ent->r.svFlags & SVF_VISDUMMY ) {
428 			sharedEntity_t *ment = 0;
429 
430 			//find master;
431 			ment = SV_GentityNum( ent->s.otherEntityNum );
432 
433 			if ( ment ) {
434 				svEntity_t *master = 0;
435 				master = SV_SvEntityForGentity( ment );
436 
437 				if ( master->snapshotCounter == sv.snapshotCounter || !ment->r.linked ) {
438 					goto notVisible;
439 					//continue;
440 				}
441 
442 				SV_AddEntToSnapshot( master, ment, eNums );
443 			}
444 			goto notVisible;
445 			//continue;	// master needs to be added, but not this dummy ent
446 		}
447 		//----(SA) end
448 		else if ( ent->r.svFlags & SVF_VISDUMMY_MULTIPLE ) {
449 			{
450 				int h;
451 				sharedEntity_t *ment = 0;
452 				svEntity_t *master = 0;
453 
454 				for ( h = 0; h < sv.num_entities; h++ )
455 				{
456 					ment = SV_GentityNum( h );
457 
458 					if ( ment == ent ) {
459 						continue;
460 					}
461 
462 					if ( ment ) {
463 						master = SV_SvEntityForGentity( ment );
464 					} else {
465 						continue;
466 					}
467 
468 					if ( !( ment->r.linked ) ) {
469 						continue;
470 					}
471 
472 					if ( ment->s.number != h ) {
473 						Com_DPrintf( "FIXING vis dummy multiple ment->S.NUMBER!!!\n" );
474 						ment->s.number = h;
475 					}
476 
477 					if ( ment->r.svFlags & SVF_NOCLIENT ) {
478 						continue;
479 					}
480 
481 					if ( master->snapshotCounter == sv.snapshotCounter ) {
482 						continue;
483 					}
484 
485 					if ( ment->s.otherEntityNum == ent->s.number ) {
486 						SV_AddEntToSnapshot( master, ment, eNums );
487 					}
488 				}
489 				goto notVisible;
490 			}
491 		}
492 
493 		// add it
494 		SV_AddEntToSnapshot( svEnt, ent, eNums );
495 
496 		// if it's a portal entity, add everything visible from its camera position
497 		if ( ent->r.svFlags & SVF_PORTAL ) {
498 //			SV_AddEntitiesVisibleFromPoint( ent->s.origin2, frame, eNums, qtrue, oldframe, localClient );
499 			SV_AddEntitiesVisibleFromPoint( ent->s.origin2, frame, eNums, qtrue, localClient );
500 		}
501 
502 		continue;
503 
504 notVisible:
505 
506 		// Ridah, if this entity has changed events, then send it regardless of whether we can see it or not
507 		// DHM - Nerve :: not in multiplayer please
508 		if ( sv_gametype->integer == GT_SINGLE_PLAYER && localClient ) {
509 			if ( ent->r.eventTime == svs.time ) {
510 				ent->s.eFlags |= EF_NODRAW;     // don't draw, just process event
511 				SV_AddEntToSnapshot( svEnt, ent, eNums );
512 			} else if ( ent->s.eType == ET_PLAYER ) {
513 				// keep players around if they are alive and active (so sounds dont get messed up)
514 				if ( !( ent->s.eFlags & EF_DEAD ) ) {
515 					ent->s.eFlags |= EF_NODRAW;     // don't draw, just process events and sounds
516 					SV_AddEntToSnapshot( svEnt, ent, eNums );
517 				}
518 			}
519 		}
520 
521 	}
522 }
523 
524 /*
525 =============
526 SV_BuildClientSnapshot
527 
528 Decides which entities are going to be visible to the client, and
529 copies off the playerstate and areabits.
530 
531 This properly handles multiple recursive portals, but the render
532 currently doesn't.
533 
534 For viewing through other player's eyes, clent can be something other than client->gentity
535 =============
536 */
SV_BuildClientSnapshot(client_t * client)537 static void SV_BuildClientSnapshot( client_t *client ) {
538 	vec3_t org;
539 //	clientSnapshot_t			*frame, *oldframe;
540 	clientSnapshot_t            *frame;
541 	snapshotEntityNumbers_t entityNumbers;
542 	int i;
543 	sharedEntity_t              *ent;
544 	entityState_t               *state;
545 	svEntity_t                  *svEnt;
546 	sharedEntity_t              *clent;
547 	int clientNum;
548 	playerState_t               *ps;
549 
550 	// bump the counter used to prevent double adding
551 	sv.snapshotCounter++;
552 
553 	// this is the frame we are creating
554 	frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ];
555 
556 //	// try to use a previous frame as the source for delta compressing the snapshot
557 //	if ( client->deltaMessage <= 0 || client->state != CS_ACTIVE ) {
558 //		// client is asking for a retransmit
559 //		oldframe = NULL;
560 //	} else if ( client->netchan.outgoingSequence - client->deltaMessage
561 //		>= (PACKET_BACKUP - 3) ) {
562 //		// client hasn't gotten a good message through in a long time
563 //		Com_DPrintf ("%s: Delta request from out of date packet.\n", client->name);
564 //		oldframe = NULL;
565 //	} else {
566 //		// we have a valid snapshot to delta from
567 //		oldframe = &client->frames[ client->deltaMessage & PACKET_MASK ];
568 //
569 //		// the snapshot's entities may still have rolled off the buffer, though
570 //		if ( oldframe->first_entity <= svs.nextSnapshotEntities - svs.numSnapshotEntities ) {
571 //			Com_DPrintf ("%s: Delta request from out of date entities.\n", client->name);
572 //			oldframe = NULL;
573 //		}
574 //	}
575 
576 	// clear everything in this snapshot
577 	entityNumbers.numSnapshotEntities = 0;
578 	memset( frame->areabits, 0, sizeof( frame->areabits ) );
579 
580 	clent = client->gentity;
581 	if ( !clent || client->state == CS_ZOMBIE ) {
582 		return;
583 	}
584 
585 	// grab the current playerState_t
586 	ps = SV_GameClientNum( client - svs.clients );
587 	frame->ps = *ps;
588 
589 	// never send client's own entity, because it can
590 	// be regenerated from the playerstate
591 	clientNum = frame->ps.clientNum;
592 	if ( clientNum < 0 || clientNum >= MAX_GENTITIES ) {
593 		Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" );
594 	}
595 	svEnt = &sv.svEntities[ clientNum ];
596 
597 	svEnt->snapshotCounter = sv.snapshotCounter;
598 
599 	// find the client's viewpoint
600 	VectorCopy( ps->origin, org );
601 	org[2] += ps->viewheight;
602 
603 //----(SA)	added for 'lean'
604 	// need to account for lean, so areaportal doors draw properly
605 	if ( frame->ps.leanf != 0 ) {
606 		vec3_t right, v3ViewAngles;
607 		VectorCopy( ps->viewangles, v3ViewAngles );
608 		v3ViewAngles[2] += frame->ps.leanf / 2.0f;
609 		AngleVectors( v3ViewAngles, NULL, right, NULL );
610 		VectorMA( org, frame->ps.leanf, right, org );
611 	}
612 //----(SA)	end
613 
614 	// add all the entities directly visible to the eye, which
615 	// may include portal entities that merge other viewpoints
616 	SV_AddEntitiesVisibleFromPoint( org, frame, &entityNumbers, qfalse, client->netchan.remoteAddress.type == NA_LOOPBACK );
617 //	SV_AddEntitiesVisibleFromPoint( org, frame, &entityNumbers, qfalse, oldframe, client->netchan.remoteAddress.type == NA_LOOPBACK );
618 
619 	// if there were portals visible, there may be out of order entities
620 	// in the list which will need to be resorted for the delta compression
621 	// to work correctly.  This also catches the error condition
622 	// of an entity being included twice.
623 	qsort( entityNumbers.snapshotEntities, entityNumbers.numSnapshotEntities,
624 		   sizeof( entityNumbers.snapshotEntities[0] ), SV_QsortEntityNumbers );
625 
626 	// now that all viewpoint's areabits have been OR'd together, invert
627 	// all of them to make it a mask vector, which is what the renderer wants
628 	for ( i = 0 ; i < MAX_MAP_AREA_BYTES / 4 ; i++ ) {
629 		( (int *)frame->areabits )[i] = ( (int *)frame->areabits )[i] ^ -1;
630 	}
631 
632 	// copy the entity states out
633 	frame->num_entities = 0;
634 	frame->first_entity = svs.nextSnapshotEntities;
635 	for ( i = 0 ; i < entityNumbers.numSnapshotEntities ; i++ ) {
636 		ent = SV_GentityNum( entityNumbers.snapshotEntities[i] );
637 		state = &svs.snapshotEntities[svs.nextSnapshotEntities % svs.numSnapshotEntities];
638 		*state = ent->s;
639 		svs.nextSnapshotEntities++;
640 		// this should never hit, map should always be restarted first in SV_Frame
641 		if ( svs.nextSnapshotEntities >= 0x7FFFFFFE ) {
642 			Com_Error( ERR_FATAL, "svs.nextSnapshotEntities wrapped" );
643 		}
644 		frame->num_entities++;
645 	}
646 }
647 
648 #ifdef USE_VOIP
649 /*
650 ==================
651 SV_WriteVoipToClient
652 
653 Check to see if there is any VoIP queued for a client, and send if there is.
654 ==================
655 */
SV_WriteVoipToClient(client_t * cl,msg_t * msg)656 static void SV_WriteVoipToClient(client_t *cl, msg_t *msg)
657 {
658 	int totalbytes = 0;
659 	int i;
660 	voipServerPacket_t *packet;
661 
662 	if(cl->queuedVoipPackets)
663 	{
664 		// Write as many VoIP packets as we reasonably can...
665 		for(i = 0; i < cl->queuedVoipPackets; i++)
666 		{
667 			packet = cl->voipPacket[(i + cl->queuedVoipIndex) % ARRAY_LEN(cl->voipPacket)];
668 
669 			if(!*cl->downloadName)
670 			{
671         			totalbytes += packet->len;
672 	        		if (totalbytes > (msg->maxsize - msg->cursize) / 2)
673 		        		break;
674 
675 				MSG_WriteByte(msg, svc_voipOpus);
676         			MSG_WriteShort(msg, packet->sender);
677 	        		MSG_WriteByte(msg, (byte) packet->generation);
678 		        	MSG_WriteLong(msg, packet->sequence);
679 		        	MSG_WriteByte(msg, packet->frames);
680         			MSG_WriteShort(msg, packet->len);
681         			MSG_WriteBits(msg, packet->flags, VOIP_FLAGCNT);
682 	        		MSG_WriteData(msg, packet->data, packet->len);
683                         }
684 
685 			Z_Free(packet);
686 		}
687 
688 		cl->queuedVoipPackets -= i;
689 		cl->queuedVoipIndex += i;
690 		cl->queuedVoipIndex %= ARRAY_LEN(cl->voipPacket);
691 	}
692 }
693 #endif
694 
695 /*
696 =======================
697 SV_SendMessageToClient
698 
699 Called by SV_SendClientSnapshot and SV_SendClientGameState
700 =======================
701 */
SV_SendMessageToClient(msg_t * msg,client_t * client)702 void SV_SendMessageToClient(msg_t *msg, client_t *client)
703 {
704 	// record information about the message
705 	client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSize = msg->cursize;
706 	client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSent = svs.time;
707 	client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageAcked = -1;
708 
709 	// send the datagram
710 	SV_Netchan_Transmit(client, msg);
711 }
712 
713 
714 /*
715 =======================
716 SV_SendClientSnapshot
717 
718 Also called by SV_FinalMessage
719 
720 =======================
721 */
SV_SendClientSnapshot(client_t * client)722 void SV_SendClientSnapshot( client_t *client ) {
723 	byte msg_buf[MAX_MSGLEN];
724 	msg_t msg;
725 
726 	//RF, AI don't need snapshots built
727 	if ( client->gentity && client->gentity->r.svFlags & SVF_CASTAI ) {
728 		return;
729 	}
730 
731 	// build the snapshot
732 	SV_BuildClientSnapshot( client );
733 
734 	// bots need to have their snapshots build, but
735 	// the query them directly without needing to be sent
736 	if ( client->gentity && client->gentity->r.svFlags & SVF_BOT ) {
737 		return;
738 	}
739 
740 	MSG_Init( &msg, msg_buf, sizeof( msg_buf ) );
741 	msg.allowoverflow = qtrue;
742 
743 	// NOTE, MRE: all server->client messages now acknowledge
744 	// let the client know which reliable clientCommands we have received
745 	MSG_WriteLong( &msg, client->lastClientCommand );
746 
747 	// (re)send any reliable server commands
748 	SV_UpdateServerCommandsToClient( client, &msg );
749 
750 	// send over all the relevant entityState_t
751 	// and the playerState_t
752 	SV_WriteSnapshotToClient( client, &msg );
753 
754 #ifdef USE_VOIP
755 	SV_WriteVoipToClient( client, &msg );
756 #endif
757 
758 	// check for overflow
759 	if ( msg.overflowed ) {
760 		Com_Printf( "WARNING: msg overflowed for %s\n", client->name );
761 		MSG_Clear( &msg );
762 	}
763 
764 	SV_SendMessageToClient( &msg, client );
765 }
766 
767 
768 /*
769 =======================
770 SV_SendClientMessages
771 =======================
772 */
SV_SendClientMessages(void)773 void SV_SendClientMessages(void)
774 {
775 	int		i;
776 	client_t    *c;
777 
778 	// send a message to each connected client
779 	for(i=0; i < sv_maxclients->integer; i++)
780 	{
781 		c = &svs.clients[i];
782 
783 		if(!c->state)
784 			continue;       // not connected
785 
786 		if(svs.time - c->lastSnapshotTime < c->snapshotMsec * com_timescale->value)
787 			continue;		// It's not time yet
788 
789 		if(*c->downloadName)
790 			continue;		// Client is downloading, don't send snapshots
791 
792 		if(c->netchan.unsentFragments || c->netchan_start_queue)
793 		{
794 			c->rateDelayed = qtrue;
795 			continue;		// Drop this snapshot if the packet queue is still full or delta compression will break
796 		}
797 
798 		if(!(c->netchan.remoteAddress.type == NA_LOOPBACK ||
799 		     (sv_lanForceRate->integer && Sys_IsLANAddress(c->netchan.remoteAddress))))
800 		{
801 			// rate control for clients not on LAN
802 			if(SV_RateMsec(c) > 0)
803 			{
804 				// Not enough time since last packet passed through the line
805 				c->rateDelayed = qtrue;
806 				continue;
807 			}
808 		}
809 
810 		// generate and send a new message
811 		SV_SendClientSnapshot(c);
812 		c->lastSnapshotTime = svs.time;
813 		c->rateDelayed = qfalse;
814 	}
815 }
816 
817