1 /*
2 ===========================================================================
3 
4 Doom 3 GPL Source Code
5 Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
6 
7 This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
8 
9 Doom 3 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 Doom 3 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 Doom 3 Source Code.  If not, see <http://www.gnu.org/licenses/>.
21 
22 In addition, the Doom 3 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 Doom 3 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 #ifndef __GAME_LOCAL_H__
30 #define	__GAME_LOCAL_H__
31 
32 #include "GameBase.h"
33 
34 #include "idlib/containers/StrList.h"
35 #include "idlib/containers/LinkList.h"
36 #include "idlib/BitMsg.h"
37 #include "framework/Game.h"
38 
39 #include "gamesys/SaveGame.h"
40 #include "physics/Clip.h"
41 #include "physics/Push.h"
42 #include "script/Script_Program.h"
43 #include "ai/AAS.h"
44 #include "anim/Anim.h"
45 #include "Pvs.h"
46 #include "MultiplayerGame.h"
47 
48 #ifdef ID_DEBUG_UNINITIALIZED_MEMORY
49 // This is real evil but allows the code to inspect arbitrary class variables.
50 #define private		public
51 #define protected	public
52 #endif
53 
54 /*
55 ===============================================================================
56 
57 	Local implementation of the public game interface.
58 
59 ===============================================================================
60 */
61 class idDeclEntityDef;
62 class idRenderWorld;
63 class idSoundWorld;
64 class idUserInterface;
65 
66 extern idRenderWorld *				gameRenderWorld;
67 extern idSoundWorld *				gameSoundWorld;
68 
69 // classes used by idGameLocal
70 class idEntity;
71 class idActor;
72 class idPlayer;
73 class idCamera;
74 class idWorldspawn;
75 class idTestModel;
76 class idSmokeParticles;
77 class idEntityFx;
78 class idTypeInfo;
79 class idThread;
80 class idEditEntities;
81 class idLocationEntity;
82 
83 //============================================================================
84 extern const int NUM_RENDER_PORTAL_BITS;
85 
86 void gameError( const char *fmt, ... );
87 
88 extern idRenderWorld *				gameRenderWorld;
89 extern idSoundWorld *				gameSoundWorld;
90 
91 extern const int NUM_RENDER_PORTAL_BITS;
92 /*
93 ===============================================================================
94 
95 	Local implementation of the public game interface.
96 
97 ===============================================================================
98 */
99 typedef struct entityState_s {
100 	int						entityNumber;
101 	idBitMsg				state;
102 	byte					stateBuf[MAX_ENTITY_STATE_SIZE];
103 	struct entityState_s *	next;
104 } entityState_t;
105 
106 typedef struct snapshot_s {
107 	int						sequence;
108 	entityState_t *			firstEntityState;
109 	int						pvs[ENTITY_PVS_SIZE];
110 	struct snapshot_s *		next;
111 } snapshot_t;
112 
113 const int MAX_EVENT_PARAM_SIZE		= 128;
114 
115 typedef struct entityNetEvent_s {
116 	int						spawnId;
117 	int						event;
118 	int						time;
119 	int						paramsSize;
120 	byte					paramsBuf[MAX_EVENT_PARAM_SIZE];
121 	struct entityNetEvent_s	*next;
122 	struct entityNetEvent_s *prev;
123 } entityNetEvent_t;
124 
125 enum {
126 	GAME_RELIABLE_MESSAGE_INIT_DECL_REMAP,
127 	GAME_RELIABLE_MESSAGE_REMAP_DECL,
128 	GAME_RELIABLE_MESSAGE_SPAWN_PLAYER,
129 	GAME_RELIABLE_MESSAGE_DELETE_ENT,
130 	GAME_RELIABLE_MESSAGE_CHAT,
131 	GAME_RELIABLE_MESSAGE_TCHAT,
132 	GAME_RELIABLE_MESSAGE_SOUND_EVENT,
133 	GAME_RELIABLE_MESSAGE_SOUND_INDEX,
134 	GAME_RELIABLE_MESSAGE_DB,
135 	GAME_RELIABLE_MESSAGE_KILL,
136 	GAME_RELIABLE_MESSAGE_DROPWEAPON,
137 	GAME_RELIABLE_MESSAGE_RESTART,
138 	GAME_RELIABLE_MESSAGE_SERVERINFO,
139 	GAME_RELIABLE_MESSAGE_TOURNEYLINE,
140 	GAME_RELIABLE_MESSAGE_CALLVOTE,
141 	GAME_RELIABLE_MESSAGE_CASTVOTE,
142 	GAME_RELIABLE_MESSAGE_STARTVOTE,
143 	GAME_RELIABLE_MESSAGE_UPDATEVOTE,
144 	GAME_RELIABLE_MESSAGE_PORTALSTATES,
145 	GAME_RELIABLE_MESSAGE_PORTAL,
146 	GAME_RELIABLE_MESSAGE_VCHAT,
147 	GAME_RELIABLE_MESSAGE_STARTSTATE,
148 	GAME_RELIABLE_MESSAGE_MENU,
149 	GAME_RELIABLE_MESSAGE_WARMUPTIME,
150 	GAME_RELIABLE_MESSAGE_EVENT
151 };
152 
153 typedef enum {
154 	GAMESTATE_UNINITIALIZED,		// prior to Init being called
155 	GAMESTATE_NOMAP,				// no map loaded
156 	GAMESTATE_STARTUP,				// inside InitFromNewMap().  spawning map entities.
157 	GAMESTATE_ACTIVE,				// normal gameplay
158 	GAMESTATE_SHUTDOWN				// inside MapShutdown().  clearing memory.
159 } gameState_t;
160 
161 typedef struct {
162 	idEntity	*ent;
163 	int			dist;
164 } spawnSpot_t;
165 
166 //============================================================================
167 
168 class idEventQueue {
169 public:
170 	typedef enum {
171 		OUTOFORDER_IGNORE,
172 		OUTOFORDER_DROP,
173 		OUTOFORDER_SORT
174 	} outOfOrderBehaviour_t;
175 
idEventQueue()176 							idEventQueue() : start( NULL ), end( NULL ) {}
177 
178 	entityNetEvent_t *		Alloc();
179 	void					Free( entityNetEvent_t *event );
180 	void					Shutdown();
181 
182 	void					Init();
183 	void					Enqueue( entityNetEvent_t* event, outOfOrderBehaviour_t oooBehaviour );
184 	entityNetEvent_t *		Dequeue( void );
185 	entityNetEvent_t *		RemoveLast( void );
186 
Start(void)187 	entityNetEvent_t *		Start( void ) { return start; }
188 
189 private:
190 	entityNetEvent_t *					start;
191 	entityNetEvent_t *					end;
192 	idBlockAlloc<entityNetEvent_t,32>	eventAllocator;
193 };
194 
195 //============================================================================
196 
197 template< class type >
198 class idEntityPtr {
199 public:
200 							idEntityPtr();
201 
202 	// save games
203 	void					Save( idSaveGame *savefile ) const;					// archives object for save game file
204 	void					Restore( idRestoreGame *savefile );					// unarchives object from save game file
205 
206 	idEntityPtr<type> &		operator=( type *ent );
207 
208 	// synchronize entity pointers over the network
GetSpawnId(void)209 	int						GetSpawnId( void ) const { return spawnId; }
210 	bool					SetSpawnId( int id );
211 	bool					UpdateSpawnId( void );
212 
213 	bool					IsValid( void ) const;
214 	type *					GetEntity( void ) const;
215 	int						GetEntityNum( void ) const;
216 
217 private:
218 	int						spawnId;
219 };
220 
221 //============================================================================
222 
223 class idGameLocal : public idGame {
224 public:
225 	idDict					serverInfo;				// all the tunable parameters, like numclients, etc
226 	int						numClients;				// pulled from serverInfo and verified
227 	idDict					userInfo[MAX_CLIENTS];	// client specific settings
228 	usercmd_t				usercmds[MAX_CLIENTS];	// client input commands
229 	idDict					persistentPlayerInfo[MAX_CLIENTS];
230 	idEntity *				entities[MAX_GENTITIES];// index to entities
231 	int						spawnIds[MAX_GENTITIES];// for use in idEntityPtr
232 	int						firstFreeIndex;			// first free index in the entities array
233 	int						num_entities;			// current number <= MAX_GENTITIES
234 	idHashIndex				entityHash;				// hash table to quickly find entities by name
235 	idWorldspawn *			world;					// world entity
236 	idLinkList<idEntity>	spawnedEntities;		// all spawned entities
237 	idLinkList<idEntity>	activeEntities;			// all thinking entities (idEntity::thinkFlags != 0)
238 	int						numEntitiesToDeactivate;// number of entities that became inactive in current frame
239 	bool					sortPushers;			// true if active lists needs to be reordered to place pushers at the front
240 	bool					sortTeamMasters;		// true if active lists needs to be reordered to place physics team masters before their slaves
241 	idDict					persistentLevelInfo;	// contains args that are kept around between levels
242 
243 	// can be used to automatically effect every material in the world that references globalParms
244 	float					globalShaderParms[ MAX_GLOBAL_SHADER_PARMS ];
245 
246 	idRandom				random;					// random number generator used throughout the game
247 
248 	idProgram				program;				// currently loaded script and data space
249 	idThread *				frameCommandThread;
250 
251 	idClip					clip;					// collision detection
252 	idPush					push;					// geometric pushing
253 	idPVS					pvs;					// potential visible set
254 
255 	idTestModel *			testmodel;				// for development testing of models
256 	idEntityFx *			testFx;					// for development testing of fx
257 
258 	idStr					sessionCommand;			// a target_sessionCommand can set this to return something to the session
259 
260 	idMultiplayerGame		mpGame;					// handles rules for standard dm
261 
262 	idSmokeParticles *		smokeParticles;			// global smoke trails
263 	idEditEntities *		editEntities;			// in game editing
264 
265 	int						cinematicSkipTime;		// don't allow skipping cinemetics until this time has passed so player doesn't skip out accidently from a firefight
266 	int						cinematicStopTime;		// cinematics have several camera changes, so keep track of when we stop them so that we don't reset cinematicSkipTime unnecessarily
267 	int						cinematicMaxSkipTime;	// time to end cinematic when skipping.  there's a possibility of an infinite loop if the map isn't set up right.
268 	bool					inCinematic;			// game is playing cinematic (player controls frozen)
269 	bool					skipCinematic;
270 
271 													// are kept up to date with changes to serverInfo
272 	int						framenum;
273 	int						previousTime;			// time in msec of last frame
274 	int						time;					// in msec
275 	static const int		msec = USERCMD_MSEC;	// time since last update in milliseconds
276 
277 	int						vacuumAreaNum;			// -1 if level doesn't have any outside areas
278 
279 	gameType_t				gameType;
280 	bool					isMultiplayer;			// set if the game is run in multiplayer mode
281 	bool					isServer;				// set if the game is run for a dedicated or listen server
282 	bool					isClient;				// set if the game is run for a client
283 													// discriminates between the RunFrame path and the ClientPrediction path
284 													// NOTE: on a listen server, isClient is false
285 	int						localClientNum;			// number of the local client. MP: -1 on a dedicated
286 	idLinkList<idEntity>	snapshotEntities;		// entities from the last snapshot
287 	int						realClientTime;			// real client time
288 	bool					isNewFrame;				// true if this is a new game frame, not a rerun due to prediction
289 	float					clientSmoothing;		// smoothing of other clients in the view
290 	int						entityDefBits;			// bits required to store an entity def number
291 
292 	static const char *		sufaceTypeNames[ MAX_SURFACE_TYPES ];	// text names for surface types
293 
294 	idEntityPtr<idEntity>	lastGUIEnt;				// last entity with a GUI, used by Cmd_NextGUI_f
295 	int						lastGUI;				// last GUI on the lastGUIEnt
296 
297 	// ---------------------- Public idGame Interface -------------------
298 
299 							idGameLocal();
300 
301 	virtual void			Init( void );
302 	virtual void			Shutdown( void );
303 	virtual void			SetLocalClient( int clientNum );
304 	virtual void			ThrottleUserInfo( void );
305 	virtual const idDict *	SetUserInfo( int clientNum, const idDict &userInfo, bool isClient, bool canModify );
306 	virtual const idDict *	GetUserInfo( int clientNum );
307 	virtual void			SetServerInfo( const idDict &serverInfo );
308 
309 	virtual const idDict &	GetPersistentPlayerInfo( int clientNum );
310 	virtual void			SetPersistentPlayerInfo( int clientNum, const idDict &playerInfo );
311 	virtual void			InitFromNewMap( const char *mapName, idRenderWorld *renderWorld, idSoundWorld *soundWorld, bool isServer, bool isClient, int randSeed );
312 	virtual bool			InitFromSaveGame( const char *mapName, idRenderWorld *renderWorld, idSoundWorld *soundWorld, idFile *saveGameFile );
313 	virtual void			SaveGame( idFile *saveGameFile );
314 	virtual void			MapShutdown( void );
315 	virtual void			CacheDictionaryMedia( const idDict *dict );
316 	virtual void			SpawnPlayer( int clientNum );
317 	virtual gameReturn_t	RunFrame( const usercmd_t *clientCmds );
318 	virtual bool			Draw( int clientNum );
319 	virtual escReply_t		HandleESC( idUserInterface **gui );
320 	virtual idUserInterface	*StartMenu( void );
321 	virtual const char *	HandleGuiCommands( const char *menuCommand );
322 	virtual void			HandleMainMenuCommands( const char *menuCommand, idUserInterface *gui );
323 	virtual allowReply_t	ServerAllowClient( int numClients, const char *IP, const char *guid, const char *password, char reason[MAX_STRING_CHARS] );
324 	virtual void			ServerClientConnect( int clientNum, const char *guid );
325 	virtual void			ServerClientBegin( int clientNum );
326 	virtual void			ServerClientDisconnect( int clientNum );
327 	virtual void			ServerWriteInitialReliableMessages( int clientNum );
328 	virtual void			ServerWriteSnapshot( int clientNum, int sequence, idBitMsg &msg, byte *clientInPVS, int numPVSClients );
329 	virtual bool			ServerApplySnapshot( int clientNum, int sequence );
330 	virtual void			ServerProcessReliableMessage( int clientNum, const idBitMsg &msg );
331 	virtual void			ClientReadSnapshot( int clientNum, int sequence, const int gameFrame, const int gameTime, const int dupeUsercmds, const int aheadOfServer, const idBitMsg &msg );
332 	virtual bool			ClientApplySnapshot( int clientNum, int sequence );
333 	virtual void			ClientProcessReliableMessage( int clientNum, const idBitMsg &msg );
334 	virtual gameReturn_t	ClientPrediction( int clientNum, const usercmd_t *clientCmds, bool lastPredictFrame );
335 
336 	virtual void			GetClientStats( int clientNum, char *data, const int len );
337 	virtual void			SwitchTeam( int clientNum, int team );
338 
339 	virtual bool			DownloadRequest( const char *IP, const char *guid, const char *paks, char urls[ MAX_STRING_CHARS ] );
340 
341 	// ---------------------- Public idGameLocal Interface -------------------
342 
343 	void					Printf( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
344 	void					DPrintf( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
345 	void					Warning( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
346 	void					DWarning( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
347 	void					Error( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
348 
349 							// Initializes all map variables common to both save games and spawned games
350 	void					LoadMap( const char *mapName, int randseed );
351 
352 	void					LocalMapRestart( void );
353 	void					MapRestart( void );
354 	static void				MapRestart_f( const idCmdArgs &args );
355 	bool					NextMap( void );	// returns wether serverinfo settings have been modified
356 	static void				NextMap_f( const idCmdArgs &args );
357 
358 	idMapFile *				GetLevelMap( void );
359 	const char *			GetMapName( void ) const;
360 
361 	int						NumAAS( void ) const;
362 	idAAS *					GetAAS( int num ) const;
363 	idAAS *					GetAAS( const char *name ) const;
364 	void					SetAASAreaState( const idBounds &bounds, const int areaContents, bool closed );
365 	aasHandle_t				AddAASObstacle( const idBounds &bounds );
366 	void					RemoveAASObstacle( const aasHandle_t handle );
367 	void					RemoveAllAASObstacles( void );
368 
369 	bool					CheatsOk( bool requirePlayer = true );
370 	void					SetSkill( int value );
371 	gameState_t				GameState( void ) const;
372 	idEntity *				SpawnEntityType( const idTypeInfo &classdef, const idDict *args = NULL, bool bIsClientReadSnapshot = false );
373 	bool					SpawnEntityDef( const idDict &args, idEntity **ent = NULL, bool setDefaults = true );
374 	int						GetSpawnId( const idEntity *ent ) const;
375 
376 	const idDeclEntityDef *	FindEntityDef( const char *name, bool makeDefault = true ) const;
377 	const idDict *			FindEntityDefDict( const char *name, bool makeDefault = true ) const;
378 
379 	void					RegisterEntity( idEntity *ent );
380 	void					UnregisterEntity( idEntity *ent );
381 
382 	bool					RequirementMet( idEntity *activator, const idStr &requires, int removeItem );
383 
384 	void					AlertAI( idEntity *ent );
385 	idActor *				GetAlertEntity( void );
386 
387 	bool					InPlayerPVS( idEntity *ent ) const;
388 	bool					InPlayerConnectedArea( idEntity *ent ) const;
389 
390 	void					SetCamera( idCamera *cam );
391 	idCamera *				GetCamera( void ) const;
392 	bool					SkipCinematic( void );
393 	void					CalcFov( float base_fov, float &fov_x, float &fov_y ) const;
394 
395 	void					AddEntityToHash( const char *name, idEntity *ent );
396 	bool					RemoveEntityFromHash( const char *name, idEntity *ent );
397 	int						GetTargets( const idDict &args, idList< idEntityPtr<idEntity> > &list, const char *ref ) const;
398 
399 							// returns the master entity of a trace.  for example, if the trace entity is the player's head, it will return the player.
400 	idEntity *				GetTraceEntity( const trace_t &trace ) const;
401 
402 	static void				ArgCompletion_EntityName( const idCmdArgs &args, void(*callback)( const char *s ) );
403 	idEntity *				FindTraceEntity( idVec3 start, idVec3 end, const idTypeInfo &c, const idEntity *skip ) const;
404 	idEntity *				FindEntity( const char *name ) const;
405 	idEntity *				FindEntityUsingDef( idEntity *from, const char *match ) const;
406 	int						EntitiesWithinRadius( const idVec3 org, float radius, idEntity **entityList, int maxCount ) const;
407 
408 	void					KillBox( idEntity *ent, bool catch_teleport = false );
409 	void					RadiusDamage( const idVec3 &origin, idEntity *inflictor, idEntity *attacker, idEntity *ignoreDamage, idEntity *ignorePush, const char *damageDefName, float dmgPower = 1.0f );
410 	void					RadiusPush( const idVec3 &origin, const float radius, const float push, const idEntity *inflictor, const idEntity *ignore, float inflictorScale, const bool quake );
411 	void					RadiusPushClipModel( const idVec3 &origin, const float push, const idClipModel *clipModel );
412 
413 	void					ProjectDecal( const idVec3 &origin, const idVec3 &dir, float depth, bool parallel, float size, const char *material, float angle = 0 );
414 	void					BloodSplat( const idVec3 &origin, const idVec3 &dir, float size, const char *material );
415 
416 	void					CallFrameCommand( idEntity *ent, const function_t *frameCommand );
417 	void					CallObjectFrameCommand( idEntity *ent, const char *frameCommand );
418 
419 	const idVec3 &			GetGravity( void ) const;
420 
421 	// added the following to assist licensees with merge issues
GetFrameNum()422 	int						GetFrameNum() const { return framenum; };
GetTime()423 	int						GetTime() const { return time; };
GetMSec()424 	int						GetMSec() const { return msec; };
425 
426 	int						GetNextClientNum( int current ) const;
427 	idPlayer *				GetClientByNum( int current ) const;
428 	idPlayer *				GetClientByName( const char *name ) const;
429 	idPlayer *				GetClientByCmdArgs( const idCmdArgs &args ) const;
430 
431 	idPlayer *				GetLocalPlayer() const;
432 
433 	void					SpreadLocations();
434 	idLocationEntity *		LocationForPoint( const idVec3 &point );	// May return NULL
435 	idEntity *				SelectInitialSpawnPoint( idPlayer *player );
436 
437 	void					SetPortalState( qhandle_t portal, int blockingBits );
438 	void					SaveEntityNetworkEvent( const idEntity *ent, int event, const idBitMsg *msg );
439 	void					ServerSendChatMessage( int to, const char *name, const char *text );
440 	int						ServerRemapDecl( int clientNum, declType_t type, int index );
441 	int						ClientRemapDecl( declType_t type, int index );
442 
443 	void					SetGlobalMaterial( const idMaterial *mat );
444 	const idMaterial *		GetGlobalMaterial();
445 
SetGibTime(int _time)446 	void					SetGibTime( int _time ) { nextGibTime = _time; };
GetGibTime()447 	int						GetGibTime() { return nextGibTime; };
448 
449 	bool					NeedRestart();
450 
451 private:
452 	const static int		INITIAL_SPAWN_COUNT = 1;
453 	const static int		INTERNAL_SAVEGAME_VERSION = 1; // DG: added this for >= 1305 savegames
454 
455 	idStr					mapFileName;			// name of the map, empty string if no map loaded
456 	idMapFile *				mapFile;				// will be NULL during the game unless in-game editing is used
457 	bool					mapCycleLoaded;
458 
459 	int						spawnCount;
460 	int						mapSpawnCount;			// it's handy to know which entities are part of the map
461 
462 	idLocationEntity **		locationEntities;		// for location names, etc
463 
464 	idCamera *				camera;
465 	const idMaterial *		globalMaterial;			// for overriding everything
466 
467 	idList<idAAS *>			aasList;				// area system
468 	idStrList				aasNames;
469 
470 	idEntityPtr<idActor>	lastAIAlertEntity;
471 	int						lastAIAlertTime;
472 
473 	idDict					spawnArgs;				// spawn args used during entity spawning  FIXME: shouldn't be necessary anymore
474 
475 	pvsHandle_t				playerPVS;				// merged pvs of all players
476 	pvsHandle_t				playerConnectedAreas;	// all areas connected to any player area
477 
478 	idVec3					gravity;				// global gravity vector
479 	gameState_t				gamestate;				// keeps track of whether we're spawning, shutting down, or normal gameplay
480 	bool					influenceActive;		// true when a phantasm is happening
481 	int						nextGibTime;
482 
483 	idList<int>				clientDeclRemap[MAX_CLIENTS][DECL_MAX_TYPES];
484 
485 	entityState_t *			clientEntityStates[MAX_CLIENTS][MAX_GENTITIES];
486 	int						clientPVS[MAX_CLIENTS][ENTITY_PVS_SIZE];
487 	snapshot_t *			clientSnapshots[MAX_CLIENTS];
488 	idBlockAlloc<entityState_t,256>entityStateAllocator;
489 	idBlockAlloc<snapshot_t,64>snapshotAllocator;
490 
491 	idEventQueue			eventQueue;
492 	idEventQueue			savedEventQueue;
493 
494 	idStaticList<spawnSpot_t, MAX_GENTITIES> spawnSpots;
495 	idStaticList<idEntity *, MAX_GENTITIES> initialSpots;
496 	int						currentInitialSpot;
497 
498 	idDict					newInfo;
499 
500 	idStrList				shakeSounds;
501 
502 	byte					lagometer[ LAGO_IMG_HEIGHT ][ LAGO_IMG_WIDTH ][ 4 ];
503 
504 	void					Clear( void );
505 							// returns true if the entity shouldn't be spawned at all in this game type or difficulty level
506 	bool					InhibitEntitySpawn( idDict &spawnArgs );
507 							// spawn entities from the map file
508 	void					SpawnMapEntities( void );
509 							// commons used by init, shutdown, and restart
510 	void					MapPopulate( void );
511 	void					MapClear( bool clearClients );
512 
513 	pvsHandle_t				GetClientPVS( idPlayer *player, pvsType_t type );
514 	void					SetupPlayerPVS( void );
515 	void					FreePlayerPVS( void );
516 	void					UpdateGravity( void );
517 	void					SortActiveEntityList( void );
518 	void					ShowTargets( void );
519 	void					RunDebugInfo( void );
520 
521 	void					InitScriptForMap( void );
522 
523 	void					InitConsoleCommands( void );
524 	void					ShutdownConsoleCommands( void );
525 
526 	void					InitAsyncNetwork( void );
527 	void					ShutdownAsyncNetwork( void );
528 	void					InitLocalClient( int clientNum );
529 	void					InitClientDeclRemap( int clientNum );
530 	void					ServerSendDeclRemapToClient( int clientNum, declType_t type, int index );
531 	void					FreeSnapshotsOlderThanSequence( int clientNum, int sequence );
532 	bool					ApplySnapshot( int clientNum, int sequence );
533 	void					WriteGameStateToSnapshot( idBitMsgDelta &msg ) const;
534 	void					ReadGameStateFromSnapshot( const idBitMsgDelta &msg );
535 	void					NetworkEventWarning( const entityNetEvent_t *event, const char *fmt, ... ) id_attribute((format(printf,3,4)));
536 	void					ServerProcessEntityNetworkEventQueue( void );
537 	void					ClientProcessEntityNetworkEventQueue( void );
538 	void					ClientShowSnapshot( int clientNum ) const;
539 							// call after any change to serverInfo. Will update various quick-access flags
540 	void					UpdateServerInfoFlags( void );
541 	void					RandomizeInitialSpawns( void );
542 	static int				sortSpawnPoints( const void *ptr1, const void *ptr2 );
543 
544 	void					DumpOggSounds( void );
545 	void					GetShakeSounds( const idDict *dict );
546 
547 	virtual void			SelectTimeGroup( int timeGroup );
548 	virtual int				GetTimeGroupTime( int timeGroup );
549 	virtual void			GetBestGameType( const char* map, const char* gametype, char buf[ MAX_STRING_CHARS ] );
550 
551 	void					Tokenize( idStrList &out, const char *in );
552 
553 	void					UpdateLagometer( int aheadOfServer, int dupeUsercmds );
554 
555 	virtual void			GetMapLoadingGUI( char gui[ MAX_STRING_CHARS ] );
556 };
557 
558 //============================================================================
559 
560 extern idGameLocal			gameLocal;
561 extern idAnimManager		animationLib;
562 
563 //============================================================================
564 
565 class idGameError : public idException {
566 public:
idGameError(const char * text)567 	idGameError( const char *text ) : idException( text ) {}
568 };
569 
570 //============================================================================
571 
572 template< class type >
idEntityPtr()573 ID_INLINE idEntityPtr<type>::idEntityPtr() {
574 	spawnId = 0;
575 }
576 
577 template< class type >
Save(idSaveGame * savefile)578 ID_INLINE void idEntityPtr<type>::Save( idSaveGame *savefile ) const {
579 	savefile->WriteInt( spawnId );
580 }
581 
582 template< class type >
Restore(idRestoreGame * savefile)583 ID_INLINE void idEntityPtr<type>::Restore( idRestoreGame *savefile ) {
584 	savefile->ReadInt( spawnId );
585 }
586 
587 template< class type >
588 ID_INLINE idEntityPtr<type> &idEntityPtr<type>::operator=( type *ent ) {
589 	if ( ent == NULL ) {
590 		spawnId = 0;
591 	} else {
592 		spawnId = ( gameLocal.spawnIds[ent->entityNumber] << GENTITYNUM_BITS ) | ent->entityNumber;
593 	}
594 	return *this;
595 }
596 
597 template< class type >
SetSpawnId(int id)598 ID_INLINE bool idEntityPtr<type>::SetSpawnId( int id ) {
599 	// the reason for this first check is unclear:
600 	// the function returning false may mean the spawnId is already set right, or the entity is missing
601 	if ( id == spawnId ) {
602 		return false;
603 	}
604 	if ( ( id >> GENTITYNUM_BITS ) == gameLocal.spawnIds[ id & ( ( 1 << GENTITYNUM_BITS ) - 1 ) ] ) {
605 		spawnId = id;
606 		return true;
607 	}
608 	return false;
609 }
610 
611 template< class type >
IsValid(void)612 ID_INLINE bool idEntityPtr<type>::IsValid( void ) const {
613 	return ( gameLocal.spawnIds[ spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ) ] == ( spawnId >> GENTITYNUM_BITS ) );
614 }
615 
616 template< class type >
GetEntity(void)617 ID_INLINE type *idEntityPtr<type>::GetEntity( void ) const {
618 	int entityNum = spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 );
619 	if ( gameLocal.spawnIds[ entityNum ] == ( spawnId >> GENTITYNUM_BITS ) ) {
620 		return static_cast<type *>( gameLocal.entities[ entityNum ] );
621 	}
622 	return NULL;
623 }
624 
625 template< class type >
GetEntityNum(void)626 ID_INLINE int idEntityPtr<type>::GetEntityNum( void ) const {
627 	return ( spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ) );
628 }
629 
630 //============================================================================
631 
632 //
633 // these defines work for all startsounds from all entity types
634 // make sure to change script/doom_defs.script if you add any channels, or change their order
635 //
636 typedef enum {
637 	SND_CHANNEL_ANY = SCHANNEL_ANY,
638 	SND_CHANNEL_VOICE = SCHANNEL_ONE,
639 	SND_CHANNEL_VOICE2,
640 	SND_CHANNEL_BODY,
641 	SND_CHANNEL_BODY2,
642 	SND_CHANNEL_BODY3,
643 	SND_CHANNEL_WEAPON,
644 	SND_CHANNEL_ITEM,
645 	SND_CHANNEL_HEART,
646 	SND_CHANNEL_PDA,
647 	SND_CHANNEL_DEMONIC,
648 	SND_CHANNEL_RADIO,
649 
650 	// internal use only.  not exposed to script or framecommands.
651 	SND_CHANNEL_AMBIENT,
652 	SND_CHANNEL_DAMAGE
653 } gameSoundChannel_t;
654 
655 extern const float	DEFAULT_GRAVITY;
656 extern const idVec3	DEFAULT_GRAVITY_VEC3;
657 extern const int	CINEMATIC_SKIP_DELAY;
658 
659 #endif	/* !__GAME_LOCAL_H__ */
660