Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2795 lines
92 KiB

  1. //===== Copyright (c) Valve Corporation, All rights reserved. ======//
  2. //
  3. // Purpose: A base class for the client-side representation of entities.
  4. //
  5. // This class encompasses both entities that are created on the server
  6. // and networked to the client AND entities that are created on the
  7. // client.
  8. //
  9. // $NoKeywords: $
  10. //==================================================================//
  11. #ifndef C_BASEENTITY_H
  12. #define C_BASEENTITY_H
  13. #ifdef _WIN32
  14. #pragma once
  15. #endif
  16. #include "mathlib/vector.h"
  17. #include "icliententityinternal.h"
  18. #include "engine/ivmodelrender.h"
  19. #include "client_class.h"
  20. #include "iclientshadowmgr.h"
  21. #include "ehandle.h"
  22. #include "iclientunknown.h"
  23. #include "client_thinklist.h"
  24. #if !defined( NO_ENTITY_PREDICTION )
  25. #include "predictableid.h"
  26. #endif
  27. #include "soundflags.h"
  28. #include "shareddefs.h"
  29. #include "networkvar.h"
  30. #include "sharedvar.h"
  31. #include "tier1/interpolatedvar.h"
  32. #include "collisionproperty.h"
  33. #include "particle_property.h"
  34. #include "toolframework/itoolentity.h"
  35. #include "tier0/threadtools.h"
  36. #include "vscript/ivscript.h"
  37. #include "vscript_shared.h"
  38. class C_Team;
  39. class IPhysicsObject;
  40. class IClientVehicle;
  41. class CPredictionCopy;
  42. class C_BasePlayer;
  43. struct studiohdr_t;
  44. class CStudioHdr;
  45. class CDamageModifier;
  46. class IRecipientFilter;
  47. class CUserCmd;
  48. struct solid_t;
  49. class ISave;
  50. class IRestore;
  51. class C_BaseAnimating;
  52. class C_BaseAnimatingOverlay;
  53. class C_AI_BaseNPC;
  54. struct EmitSound_t;
  55. class C_RecipientFilter;
  56. class CTakeDamageInfo;
  57. class C_BaseCombatCharacter;
  58. class CEntityMapData;
  59. class ConVar;
  60. class CClientAlphaProperty;
  61. struct CSoundParameters;
  62. class CCallQueue;
  63. typedef unsigned int AimEntsListHandle_t;
  64. #define INVALID_AIMENTS_LIST_HANDLE (AimEntsListHandle_t)~0
  65. extern void RecvProxy_LocalVelocity( const CRecvProxyData *pData, void *pStruct, void *pOut );
  66. enum CollideType_t
  67. {
  68. ENTITY_SHOULD_NOT_COLLIDE = 0,
  69. ENTITY_SHOULD_COLLIDE,
  70. ENTITY_SHOULD_RESPOND
  71. };
  72. class VarMapEntry_t
  73. {
  74. public:
  75. unsigned short type;
  76. unsigned short m_bNeedsToInterpolate; // Set to false when this var doesn't
  77. // need Interpolate() called on it anymore.
  78. void *data;
  79. IInterpolatedVar *watcher;
  80. };
  81. struct VarMapping_t
  82. {
  83. VarMapping_t()
  84. {
  85. m_nInterpolatedEntries = 0;
  86. }
  87. CUtlVector< VarMapEntry_t > m_Entries;
  88. int m_nInterpolatedEntries;
  89. float m_lastInterpolationTime;
  90. };
  91. #define DECLARE_INTERPOLATION()
  92. // How many data slots to use when in multiplayer.
  93. #define MULTIPLAYER_BACKUP 150
  94. struct serialentity_t;
  95. typedef CHandle<C_BaseEntity> EHANDLE; // The client's version of EHANDLE.
  96. typedef void (C_BaseEntity::*BASEPTR)(void);
  97. typedef void (C_BaseEntity::*ENTITYFUNCPTR)(C_BaseEntity *pOther );
  98. // For entity creation on the client
  99. typedef C_BaseEntity* (*DISPATCHFUNCTION)( void );
  100. #include "touchlink.h"
  101. #include "groundlink.h"
  102. #if !defined( NO_ENTITY_PREDICTION ) && defined( USE_PREDICTABLEID )
  103. //-----------------------------------------------------------------------------
  104. // Purpose: For fully client side entities we use this information to determine
  105. // authoritatively if the server has acknowledged creating this entity, etc.
  106. //-----------------------------------------------------------------------------
  107. struct PredictionContext
  108. {
  109. PredictionContext()
  110. {
  111. m_bActive = false;
  112. m_nCreationCommandNumber = -1;
  113. m_pszCreationModule = NULL;
  114. m_nCreationLineNumber = 0;
  115. m_hServerEntity = NULL;
  116. }
  117. // The command_number of the usercmd which created this entity
  118. bool m_bActive;
  119. int m_nCreationCommandNumber;
  120. char const *m_pszCreationModule;
  121. int m_nCreationLineNumber;
  122. // The entity to whom we are attached
  123. CHandle< C_BaseEntity > m_hServerEntity;
  124. };
  125. #endif
  126. //-----------------------------------------------------------------------------
  127. // Purpose: think contexts
  128. //-----------------------------------------------------------------------------
  129. struct thinkfunc_t
  130. {
  131. BASEPTR m_pfnThink;
  132. string_t m_iszContext;
  133. int m_nNextThinkTick;
  134. int m_nLastThinkTick;
  135. };
  136. #define CREATE_PREDICTED_ENTITY( className ) \
  137. C_BaseEntity::CreatePredictedEntityByName( className, __FILE__, __LINE__ );
  138. // Entity flags that only exist on the client.
  139. #define ENTCLIENTFLAG_GETTINGSHADOWRENDERBOUNDS 0x0001 // Tells us if we're getting the real ent render bounds or the shadow render bounds.
  140. #define ENTCLIENTFLAG_DONTUSEIK 0x0002 // Don't use IK on this entity even if its model has IK.
  141. #define ENTCLIENTFLAG_ALWAYS_INTERPOLATE 0x0004 // Used by view models.
  142. enum entity_list_ids_t
  143. {
  144. ENTITY_LIST_INTERPOLATE = 0,
  145. ENTITY_LIST_TELEPORT,
  146. ENTITY_LIST_PRERENDER,
  147. ENTITY_LIST_SIMULATE,
  148. ENTITY_LIST_DELETE,
  149. NUM_ENTITY_LISTS
  150. };
  151. template< typename Type >
  152. class CDiscontinuousInterpolatedVar : public CInterpolatedVar<Type>
  153. {
  154. public:
  155. explicit CDiscontinuousInterpolatedVar( const char *pDebugName = NULL )
  156. : CInterpolatedVar<Type>(pDebugName)
  157. {
  158. }
  159. // Returns 1 if the value will always be the same if currentTime is always increasing.
  160. virtual int Interpolate( float currentTime )
  161. {
  162. int iRetVal = CInterpolatedVar<Type>::Interpolate(currentTime);
  163. if( m_Discontinuities.Count() == 0 )
  164. {
  165. return iRetVal;
  166. }
  167. ClearOldDiscontinuities();
  168. float fInterpolatedTime = currentTime - this->m_InterpolationAmount;
  169. for( int i = m_Discontinuities.Count(); --i >= 0; )
  170. {
  171. if( m_Discontinuities[i].fBeforeTime < fInterpolatedTime )
  172. {
  173. break;
  174. }
  175. TransformValue( m_Discontinuities[i].matTransform, *(this->m_pValue) );
  176. iRetVal = 0;
  177. }
  178. return iRetVal;
  179. }
  180. virtual void Reset( float flCurrentTime )
  181. {
  182. CInterpolatedVar<Type>::Reset(flCurrentTime);
  183. ClearOldDiscontinuities();
  184. }
  185. //transforms all history prior to fDiscontinuityTime by matTransform (with the assumption that newer entries are in the new space)
  186. //base interpolation is applied in the new space, with the inverse of matTransform applied to values interpolated to a time prior to fDiscontinuityTime
  187. void InsertDiscontinuity( const matrix3x4_t &matTransform, float fDiscontinuityTime )
  188. {
  189. ClearOldDiscontinuities();
  190. TransformBefore( matTransform, fDiscontinuityTime );
  191. int iInsertAfter;
  192. for( iInsertAfter = m_Discontinuities.Count(); --iInsertAfter >= 0; )
  193. {
  194. if( m_Discontinuities[iInsertAfter].fBeforeTime <= fDiscontinuityTime )
  195. break;
  196. }
  197. if( iInsertAfter < 0 )
  198. {
  199. iInsertAfter = m_Discontinuities.AddToTail();
  200. }
  201. else
  202. {
  203. iInsertAfter = m_Discontinuities.InsertAfter( iInsertAfter );
  204. }
  205. MatrixInvert( matTransform, m_Discontinuities[iInsertAfter].matTransform );
  206. m_Discontinuities[iInsertAfter].fBeforeTime = fDiscontinuityTime;
  207. }
  208. bool RemoveDiscontinuity( float fDiscontinuityTime, const matrix3x4_t *pFailureTransform = NULL )
  209. {
  210. //assume the general case for this is rolling back in time for prediction
  211. for( int i = m_Discontinuities.Count(); --i >= 0; )
  212. {
  213. if( m_Discontinuities[i].fBeforeTime == fDiscontinuityTime )
  214. {
  215. TransformBefore( m_Discontinuities[i].matTransform, fDiscontinuityTime );
  216. m_Discontinuities.Remove( i );
  217. return true;
  218. }
  219. }
  220. if( pFailureTransform )
  221. {
  222. TransformBefore( *pFailureTransform, fDiscontinuityTime );
  223. }
  224. return false;
  225. }
  226. float GetInterpolationAmount( void ) { return this->m_InterpolationAmount; }
  227. float GetInterpolatedTime( float fCurTime ) //What's the timestamp on the value we'll use.
  228. {
  229. float fTargetTime = fCurTime - this->m_InterpolationAmount;
  230. float fOldestEntryTime = this->GetOldestEntry();
  231. fOldestEntryTime = MIN( fOldestEntryTime, fCurTime ); //pull entries in the future to now
  232. return MAX( fTargetTime, fOldestEntryTime );
  233. }
  234. bool HasDiscontinuityForTime( float fCurTime )
  235. {
  236. if( m_Discontinuities.Count() == 0 )
  237. return false;
  238. float fTargetTime = GetInterpolatedTime( fCurTime );
  239. return ( fTargetTime < m_Discontinuities[m_Discontinuities.Count()-1].fBeforeTime );
  240. }
  241. bool GetDiscontinuityTransform( float fCurTime, matrix3x4_t &matOut )
  242. {
  243. if( m_Discontinuities.Count() == 0 )
  244. return false;
  245. float fTargetTime = GetInterpolatedTime( fCurTime );
  246. if( fTargetTime >= m_Discontinuities[m_Discontinuities.Count()-1].fBeforeTime )
  247. return false;
  248. //common case is exactly 0 or 1 transforms. 0's handled above. Do a copy of the first transform now and skip it in the iterator below
  249. matOut = m_Discontinuities[m_Discontinuities.Count() - 1].matTransform;
  250. matrix3x4_t matTemp;
  251. matrix3x4_t *pSwapMatrices[2] = { &matOut, &matTemp };
  252. int iSwapRead = 0; //which of the swap indices has the newest value
  253. for( int i = m_Discontinuities.Count() - 1; --i >= 0; )
  254. {
  255. if( m_Discontinuities[i].fBeforeTime < fTargetTime )
  256. {
  257. break;
  258. }
  259. ConcatTransforms( m_Discontinuities[i].matTransform, *pSwapMatrices[iSwapRead], *pSwapMatrices[1 - iSwapRead] );
  260. iSwapRead = 1 - iSwapRead;
  261. }
  262. if( iSwapRead == 1 ) //matTemp has the most recent value one final copy necessary to output matrix
  263. matOut = matTemp;
  264. return true;
  265. }
  266. protected:
  267. struct Discontinuity_t
  268. {
  269. matrix3x4_t matTransform; //from current space to previous space
  270. float fBeforeTime;
  271. };
  272. void ClearOldDiscontinuities( void )
  273. {
  274. if( m_Discontinuities.Count() == 0 )
  275. return;
  276. float fOldestEntry = this->GetOldestEntry();
  277. while( fOldestEntry >= m_Discontinuities[0].fBeforeTime )
  278. {
  279. m_Discontinuities.Remove( 0 );
  280. if( m_Discontinuities.Count() == 0 )
  281. break;
  282. }
  283. }
  284. void TransformBefore( const matrix3x4_t &matTransform, float fDiscontinuityTime )
  285. {
  286. int iHead = this->GetHead();
  287. if( !this->IsValidIndex( iHead ) )
  288. return;
  289. #ifdef _DEBUG
  290. float fHeadTime;
  291. this->GetHistoryValue( iHead, fHeadTime );
  292. #endif
  293. float fTime;
  294. Type *pCurrent;
  295. int iCurrent;
  296. iCurrent = iHead;
  297. while( (pCurrent = this->GetHistoryValue( iCurrent, fTime )) != NULL )
  298. {
  299. Assert( (fTime <= fHeadTime) || (iCurrent == iHead) ); //asserting that head is always newest
  300. if( fTime < fDiscontinuityTime )
  301. TransformValue( matTransform, *pCurrent );
  302. iCurrent = this->GetNext( iCurrent );
  303. if( iCurrent == iHead )
  304. break;
  305. }
  306. }
  307. static void TransformValue( const matrix3x4_t &matTransform, Type &Value );
  308. CUtlVector<Discontinuity_t> m_Discontinuities;
  309. };
  310. template<>
  311. inline void CDiscontinuousInterpolatedVar<Vector>::TransformValue( const matrix3x4_t &matTransform, Vector &Value )
  312. {
  313. Vector vTemp = Value;
  314. VectorTransform( vTemp, matTransform, Value );
  315. }
  316. template<>
  317. inline void CDiscontinuousInterpolatedVar<QAngle>::TransformValue( const matrix3x4_t &matTransform, QAngle &Value )
  318. {
  319. Value = TransformAnglesToWorldSpace( Value, matTransform );
  320. }
  321. //-----------------------------------------------------------------------------
  322. // Purpose: Base client side entity object
  323. //-----------------------------------------------------------------------------
  324. class C_BaseEntity : public IClientEntity, public IClientModelRenderable
  325. {
  326. // Construction
  327. DECLARE_CLASS_NOBASE( C_BaseEntity );
  328. friend class CPrediction;
  329. friend void cc_cl_interp_all_changed( IConVar *pConVar, const char *pOldString, float flOldValue );
  330. public:
  331. DECLARE_DATADESC();
  332. DECLARE_CLIENTCLASS();
  333. DECLARE_PREDICTABLE();
  334. // script description
  335. DECLARE_ENT_SCRIPTDESC();
  336. C_BaseEntity();
  337. protected:
  338. // Use UTIL_Remove to delete!
  339. virtual ~C_BaseEntity();
  340. public:
  341. static C_BaseEntity *CreatePredictedEntityByName( const char *classname, const char *module, int line, bool persist = false );
  342. static void UpdateVisibilityAllEntities();
  343. // FireBullets uses shared code for prediction.
  344. virtual void FireBullets( const FireBulletsInfo_t &info );
  345. virtual bool ShouldDrawUnderwaterBulletBubbles();
  346. virtual bool ShouldDrawWaterImpacts( void ) { return true; }
  347. virtual bool HandleShotImpactingWater( const FireBulletsInfo_t &info,
  348. const Vector &vecEnd, ITraceFilter *pTraceFilter, Vector *pVecTracerDest );
  349. virtual ITraceFilter* GetBeamTraceFilter( void );
  350. virtual void DispatchTraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr );
  351. virtual void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr );
  352. virtual void DoImpactEffect( trace_t &tr, int nDamageType );
  353. virtual void MakeTracer( const Vector &vecTracerSrc, const trace_t &tr, int iTracerType );
  354. virtual int GetTracerAttachment( void );
  355. void ComputeTracerStartPosition( const Vector &vecShotSrc, Vector *pVecTracerStart );
  356. void TraceBleed( float flDamage, const Vector &vecDir, trace_t *ptr, int bitsDamageType );
  357. virtual int BloodColor();
  358. virtual const char* GetTracerType();
  359. // called when entity is damaged by predicted attacks
  360. virtual void TakeDamage( const CTakeDamageInfo &info ) { }
  361. virtual void Spawn( void );
  362. virtual void SpawnClientEntity( void );
  363. virtual void Precache( void );
  364. virtual void Activate();
  365. void ParseMapData( CEntityMapData *mapData );
  366. virtual void OnParseMapDataFinished();
  367. virtual bool KeyValue( const char *szKeyName, const char *szValue );
  368. virtual bool KeyValue( const char *szKeyName, float flValue );
  369. virtual bool KeyValue( const char *szKeyName, int nValue );
  370. virtual bool KeyValue( const char *szKeyName, const Vector &vecValue );
  371. virtual bool GetKeyValue( const char *szKeyName, char *szValue, int iMaxLen );
  372. // Entities block Line-Of-Sight for NPCs by default.
  373. // Set this to false if you want to change this behavior.
  374. void SetBlocksLOS( bool bBlocksLOS );
  375. bool BlocksLOS( void );
  376. void SetAIWalkable( bool bBlocksLOS );
  377. bool IsAIWalkable( void );
  378. virtual void InitSharedVars( void ) {};
  379. void Interp_SetupMappings( VarMapping_t *map );
  380. // Returns 1 if there are no more changes (ie: we could call RemoveFromInterpolationList).
  381. int Interp_Interpolate( VarMapping_t *map, float currentTime );
  382. void Interp_RestoreToLastNetworked( VarMapping_t *map, int flags );
  383. void Interp_UpdateInterpolationAmounts( VarMapping_t *map );
  384. void Interp_HierarchyUpdateInterpolationAmounts();
  385. // Called by the CLIENTCLASS macros.
  386. virtual bool Init( int entnum, int iSerialNum );
  387. // Called in the destructor to shutdown everything.
  388. void Term();
  389. // memory handling, uses calloc so members are zero'd out on instantiation
  390. void *operator new( size_t stAllocateBlock );
  391. void *operator new[]( size_t stAllocateBlock );
  392. void *operator new( size_t stAllocateBlock, int nBlockUse, const char *pFileName, int nLine );
  393. void *operator new[]( size_t stAllocateBlock, int nBlockUse, const char *pFileName, int nLine );
  394. void operator delete( void *pMem );
  395. void operator delete( void *pMem, int nBlockUse, const char *pFileName, int nLine ) { operator delete( pMem ); }
  396. // This just picks one of the routes to IClientUnknown.
  397. IClientUnknown* GetIClientUnknown() { return this; }
  398. virtual C_BaseAnimating* GetBaseAnimating() { return NULL; }
  399. virtual C_BaseAnimatingOverlay *GetBaseAnimatingOverlay() { return NULL; }
  400. virtual void SetClassname( const char *className );
  401. virtual Class_T Classify( void ) { return CLASS_NONE; }
  402. string_t m_iClassname;
  403. HSCRIPT GetScriptInstance();
  404. HSCRIPT m_hScriptInstance;
  405. string_t m_iszScriptId;
  406. float m_flLastMadeNoiseTime;
  407. // IClientUnknown overrides.
  408. public:
  409. virtual void SetRefEHandle( const CBaseHandle &handle );
  410. virtual const CBaseHandle& GetRefEHandle() const;
  411. void SetToolHandle( HTOOLHANDLE handle );
  412. HTOOLHANDLE GetToolHandle() const;
  413. void EnableInToolView( bool bEnable );
  414. bool IsEnabledInToolView() const;
  415. void SetToolRecording( bool recording );
  416. bool IsToolRecording() const;
  417. bool HasRecordedThisFrame() const;
  418. virtual void RecordToolMessage();
  419. virtual void OnToolStartRecording( void ) {};
  420. // used to exclude entities from being recorded in the SFM tools
  421. void DontRecordInTools();
  422. bool ShouldRecordInTools() const;
  423. protected:
  424. virtual void Release();
  425. // IClientEntity
  426. public:
  427. virtual ICollideable* GetCollideable() { return CollisionProp(); }
  428. virtual IClientNetworkable* GetClientNetworkable() { return this; }
  429. virtual IClientRenderable* GetClientRenderable() { return this; }
  430. virtual IClientEntity* GetIClientEntity() { return this; }
  431. virtual C_BaseEntity* GetBaseEntity() { return this; }
  432. virtual IClientThinkable* GetClientThinkable() { return this; }
  433. virtual IClientModelRenderable* GetClientModelRenderable();
  434. virtual IClientAlphaProperty* GetClientAlphaProperty();
  435. // Inherited from IClientModelRenderable
  436. public:
  437. virtual bool GetRenderData( void *pData, ModelDataCategory_t nCategory );
  438. #if 0
  439. virtual string_t GetModelName( void ) const;
  440. #endif
  441. // Methods of IClientRenderable
  442. public:
  443. virtual const Vector& GetRenderOrigin( void );
  444. virtual const QAngle& GetRenderAngles( void );
  445. virtual Vector GetObserverCamOrigin( void ) { return GetRenderOrigin(); } // Return the origin for player observers tracking this target
  446. virtual const matrix3x4_t & RenderableToWorldTransform();
  447. virtual bool IsTransparent( void );
  448. virtual int GetRenderFlags( void );
  449. virtual const model_t *GetModel( void ) const;
  450. virtual int DrawModel( int flags, const RenderableInstance_t &instance );
  451. virtual bool LODTest() { return true; } // NOTE: UNUSED
  452. virtual void GetRenderBounds( Vector& mins, Vector& maxs );
  453. virtual IPVSNotify* GetPVSNotifyInterface();
  454. virtual void GetRenderBoundsWorldspace( Vector& absMins, Vector& absMaxs );
  455. virtual void GetShadowRenderBounds( Vector &mins, Vector &maxs, ShadowType_t shadowType );
  456. // Determine the color modulation amount
  457. virtual void GetColorModulation( float* color );
  458. virtual void OnThreadedDrawSetup() {}
  459. public:
  460. virtual bool TestCollision( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr );
  461. virtual bool TestHitboxes( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr );
  462. // To mimic server call convention
  463. C_BaseEntity *GetOwnerEntity( void ) const;
  464. void SetOwnerEntity( C_BaseEntity *pOwner );
  465. C_BaseEntity *GetEffectEntity( void ) const;
  466. void SetEffectEntity( C_BaseEntity *pEffectEnt );
  467. bool IsAbleToHaveFireEffect( void ) const;
  468. // This function returns a value that scales all damage done by this entity.
  469. // Use CDamageModifier to hook in damage modifiers on a guy.
  470. virtual float GetAttackDamageScale( void );
  471. // IClientNetworkable implementation.
  472. public:
  473. virtual void NotifyShouldTransmit( ShouldTransmitState_t state );
  474. // save out interpolated values
  475. virtual void PreDataUpdate( DataUpdateType_t updateType );
  476. virtual void PostDataUpdate( DataUpdateType_t updateType );
  477. virtual void OnDataUnchangedInPVS();
  478. virtual void ValidateModelIndex( void );
  479. // pvs info. NOTE: Do not override these!!
  480. virtual void SetDormant( bool bDormant );
  481. virtual bool IsDormant( void ) const;
  482. virtual void OnSetDormant( bool bDormant ) {}
  483. // Tells the entity that it's about to be destroyed due to the client receiving
  484. // an uncompressed update that's caused it to destroy all entities & recreate them.
  485. virtual void SetDestroyedOnRecreateEntities( void );
  486. virtual int GetEFlags() const;
  487. virtual void SetEFlags( int iEFlags );
  488. void AddEFlags( int nEFlagMask );
  489. void RemoveEFlags( int nEFlagMask );
  490. bool IsEFlagSet( int nEFlagMask ) const;
  491. // checks to see if the entity is marked for deletion
  492. bool IsMarkedForDeletion( void );
  493. virtual int entindex( void ) const;
  494. // This works for client-only entities and returns the GetEntryIndex() of the entity's handle,
  495. // so the sound system can get an IClientEntity from it.
  496. int GetSoundSourceIndex() const;
  497. // Server to client message received
  498. virtual void ReceiveMessage( int classID, bf_read &msg );
  499. virtual void* GetDataTableBasePtr();
  500. // IClientThinkable.
  501. public:
  502. // Called whenever you registered for a think message (with SetNextClientThink).
  503. virtual void ClientThink();
  504. virtual ClientThinkHandle_t GetThinkHandle();
  505. virtual void SetThinkHandle( ClientThinkHandle_t hThink );
  506. public:
  507. void AddVar( void *data, IInterpolatedVar *watcher, int type, bool bSetup=false );
  508. void RemoveVar( void *data, bool bAssert=true );
  509. VarMapping_t* GetVarMapping();
  510. VarMapping_t m_VarMap;
  511. public:
  512. // An inline version the game code can use
  513. CCollisionProperty *CollisionProp();
  514. const CCollisionProperty*CollisionProp() const;
  515. CParticleProperty *ParticleProp();
  516. const CParticleProperty *ParticleProp() const;
  517. CClientAlphaProperty *AlphaProp();
  518. const CClientAlphaProperty *AlphaProp() const;
  519. // Simply here for game shared
  520. bool IsFloating();
  521. virtual bool ShouldSavePhysics();
  522. // save/restore stuff
  523. virtual void OnSave();
  524. virtual void OnRestore();
  525. // capabilities for save/restore
  526. virtual int ObjectCaps( void );
  527. // only overload these if you have special data to serialize
  528. virtual int Save( ISave &save );
  529. virtual int Restore( IRestore &restore );
  530. bool IsRenderingInFastReflections() const;
  531. private:
  532. int SaveDataDescBlock( ISave &save, datamap_t *dmap );
  533. int RestoreDataDescBlock( IRestore &restore, datamap_t *dmap );
  534. bool ComputeIsRenderingInFastReflections() const;
  535. // Client code should call this under any circumstances where fast reflection rendering type may change
  536. void OnFastReflectionRenderingChanged();
  537. void OnDisableShadowDepthRenderingChanged();
  538. void OnDisableCSMRenderingChanged();
  539. void OnShadowDepthRenderingCacheableStateChanged();
  540. public:
  541. // Called after spawn, and in the case of self-managing objects, after load
  542. virtual bool CreateVPhysics();
  543. // Convenience routines to init the vphysics simulation for this object.
  544. // This creates a static object. Something that behaves like world geometry - solid, but never moves
  545. IPhysicsObject *VPhysicsInitStatic( void );
  546. // This creates a normal vphysics simulated object
  547. IPhysicsObject *VPhysicsInitNormal( SolidType_t solidType, int nSolidFlags, bool createAsleep, solid_t *pSolid = NULL );
  548. // This creates a vphysics object with a shadow controller that follows the AI
  549. // Move the object to where it should be and call UpdatePhysicsShadowToCurrentPosition()
  550. IPhysicsObject *VPhysicsInitShadow( bool allowPhysicsMovement, bool allowPhysicsRotation, solid_t *pSolid = NULL );
  551. private:
  552. // called by all vphysics inits
  553. bool VPhysicsInitSetup();
  554. public:
  555. void VPhysicsSetObject( IPhysicsObject *pPhysics );
  556. void VPhysicsSwapObject( IPhysicsObject *pSwap );
  557. // destroy and remove the physics object for this entity
  558. virtual void VPhysicsDestroyObject( void );
  559. // Purpose: My physics object has been updated, react or extract data
  560. virtual void VPhysicsUpdate( IPhysicsObject *pPhysics );
  561. virtual void VPhysicsShadowUpdate( IPhysicsObject *pPhysics ) {}
  562. inline IPhysicsObject *VPhysicsGetObject( void ) const { return m_pPhysicsObject; }
  563. virtual int VPhysicsGetObjectList( IPhysicsObject **pList, int listMax );
  564. virtual bool VPhysicsIsFlesh( void );
  565. virtual void VPhysicsCompensateForPredictionErrors( const byte *predictedFrame ); //compare your predictive data vs the server data and do something about any discrepancies.
  566. float VPhysicsGetNonShadowMass( void ) const { return m_flNonShadowMass; }
  567. // IClientEntity implementation.
  568. public:
  569. virtual bool SetupBones( matrix3x4a_t *pBoneToWorldOut, int nMaxBones, int boneMask, float currentTime );
  570. virtual void SetupWeights( const matrix3x4_t *pBoneToWorld, int nFlexWeightCount, float *pFlexWeights, float *pFlexDelayedWeights );
  571. virtual bool UsesFlexDelayedWeights() { return false; }
  572. virtual void DoAnimationEvents( void );
  573. virtual const Vector& GetAbsOrigin( void ) const;
  574. virtual const QAngle& GetAbsAngles( void ) const; // see also GetVectors()
  575. inline Vector Forward() const RESTRICT; ///< get my forward (+x) vector
  576. inline Vector Left() const RESTRICT; ///< get my left (+y) vector
  577. inline Vector Up() const RESTRICT; ///< get my up (+z) vector
  578. const Vector& GetNetworkOrigin() const;
  579. const QAngle& GetNetworkAngles() const;
  580. void SetNetworkOrigin( const Vector& org );
  581. void SetNetworkAngles( const QAngle& ang );
  582. const Vector& GetLocalOrigin( void ) const;
  583. void SetLocalOrigin( const Vector& origin );
  584. vec_t GetLocalOriginDim( int iDim ) const; // You can use the X_INDEX, Y_INDEX, and Z_INDEX defines here.
  585. void SetLocalOriginDim( int iDim, vec_t flValue );
  586. const QAngle& GetLocalAngles( void ) const;
  587. void SetLocalAngles( const QAngle& angles );
  588. vec_t GetLocalAnglesDim( int iDim ) const; // You can use the X_INDEX, Y_INDEX, and Z_INDEX defines here.
  589. void SetLocalAnglesDim( int iDim, vec_t flValue );
  590. virtual const Vector& GetPrevLocalOrigin() const;
  591. virtual const QAngle& GetPrevLocalAngles() const;
  592. // change position, velocity, orientation instantly
  593. // passing NULL means no change
  594. virtual void Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity );
  595. void SetLocalTransform( const matrix3x4_t &localTransform );
  596. void SetModelName( string_t name );
  597. string_t GetModelName( void ) const;
  598. int GetModelIndex( void ) const;
  599. virtual void SetModelIndex( int index );
  600. // These methods return a *world-aligned* box relative to the absorigin of the entity.
  601. // This is used for collision purposes and is *not* guaranteed
  602. // to surround the entire entity's visual representation
  603. // NOTE: It is illegal to ask for the world-aligned bounds for
  604. // SOLID_BSP objects
  605. virtual const Vector& WorldAlignMins( ) const;
  606. virtual const Vector& WorldAlignMaxs( ) const;
  607. // This defines collision bounds *in whatever space is currently defined by the solid type*
  608. // SOLID_BBOX: World Align
  609. // SOLID_OBB: Entity space
  610. // SOLID_BSP: Entity space
  611. // SOLID_VPHYSICS Not used
  612. void SetCollisionBounds( const Vector& mins, const Vector &maxs );
  613. // NOTE: These use the collision OBB to compute a reasonable center point for the entity
  614. virtual const Vector& WorldSpaceCenter( ) const;
  615. // FIXME: Do we want this?
  616. const Vector& WorldAlignSize( ) const;
  617. bool IsPointSized() const;
  618. // Returns a radius of a sphere
  619. // *centered at the world space center* bounding the collision representation
  620. // of the entity. NOTE: The world space center *may* move when the entity rotates.
  621. float BoundingRadius() const;
  622. // Used when the collision prop is told to ask game code for the world-space surrounding box
  623. virtual void ComputeWorldSpaceSurroundingBox( Vector *pVecWorldMins, Vector *pVecWorldMaxs );
  624. // Returns the entity-to-world transform
  625. matrix3x4_t &EntityToWorldTransform();
  626. const matrix3x4_t &EntityToWorldTransform() const;
  627. // Some helper methods that transform a point from entity space to world space + back
  628. void EntityToWorldSpace( const Vector &in, Vector *pOut ) const;
  629. void WorldToEntitySpace( const Vector &in, Vector *pOut ) const;
  630. // This function gets your parent's transform. If you're parented to an attachment,
  631. // this calculates the attachment's transform and gives you that.
  632. //
  633. // You must pass in tempMatrix for scratch space - it may need to fill that in and return it instead of
  634. // pointing you right at a variable in your parent.
  635. matrix3x4_t& GetParentToWorldTransform( matrix3x4_t &tempMatrix );
  636. virtual void GetVectors(Vector* forward, Vector* right, Vector* up) const;
  637. // Sets abs angles, but also sets local angles to be appropriate
  638. void SetAbsOrigin( const Vector& origin );
  639. void SetAbsAngles( const QAngle& angles );
  640. void AddFlag( int flags );
  641. void RemoveFlag( int flagsToRemove );
  642. void ToggleFlag( int flagToToggle );
  643. int GetFlags( void ) const;
  644. void ClearFlags();
  645. void SetDistanceFade( float flMinDist, float flMaxDist );
  646. void SetGlobalFadeScale( float flFadeScale );
  647. float GetMinFadeDist( ) const;
  648. float GetMaxFadeDist( ) const;
  649. float GetGlobalFadeScale( ) const;
  650. MoveType_t GetMoveType( void ) const;
  651. MoveCollide_t GetMoveCollide( void ) const;
  652. virtual SolidType_t GetSolid( void ) const;
  653. virtual int GetSolidFlags( void ) const;
  654. bool IsSolidFlagSet( int flagMask ) const;
  655. void SetSolidFlags( int nFlags );
  656. void AddSolidFlags( int nFlags );
  657. void RemoveSolidFlags( int nFlags );
  658. bool IsSolid() const;
  659. virtual class CMouthInfo *GetMouth( void );
  660. // Retrieve sound spatialization info for the specified sound on this entity
  661. // Return false to indicate sound is not audible
  662. virtual bool GetSoundSpatialization( SpatializationInfo_t& info );
  663. // Attachments
  664. virtual int LookupAttachment( const char *pAttachmentName ) { return -1; }
  665. virtual bool GetAttachment( int number, matrix3x4_t &matrix );
  666. virtual bool GetAttachment( int number, Vector &origin );
  667. virtual bool GetAttachment( int number, Vector &origin, QAngle &angles );
  668. virtual bool ComputeLightingOrigin( int nAttachmentIndex, Vector modelLightingCenter, const matrix3x4_t &matrix, Vector &transformedLightingCenter );
  669. virtual bool GetAttachmentVelocity( int number, Vector &originVel, Quaternion &angleVel );
  670. virtual void InvalidateAttachments() {}
  671. // Team handling
  672. virtual C_Team *GetTeam( void );
  673. virtual int GetTeamNumber( void ) const;
  674. virtual int GetPendingTeamNumber( void ) const;
  675. virtual void ChangeTeam( int iTeamNum ); // Assign this entity to a team.
  676. virtual int GetRenderTeamNumber( void );
  677. virtual bool InSameTeam( C_BaseEntity *pEntity ); // Returns true if the specified entity is on the same team as this one
  678. virtual bool InLocalTeam( void );
  679. // ID Target handling
  680. virtual bool IsValidIDTarget( void ) { return false; }
  681. virtual char *GetIDString( void ) { return ""; };
  682. // See CSoundEmitterSystem
  683. // Will return the sound guid. If negative, the guid is unknown (call may be successful or not). 0 if the sound was not emitted. Positive if the guid is valid.
  684. int EmitSound( const char *soundname, float soundtime = 0.0f, float *duration = NULL ); // Override for doing the general case of CPASAttenuationFilter( this ), and EmitSound( filter, entindex(), etc. );
  685. int EmitSound( const char *soundname, HSOUNDSCRIPTHASH& handle, float soundtime = 0.0f, float *duration = NULL ); // Override for doing the general case of CPASAttenuationFilter( this ), and EmitSound( filter, entindex(), etc. );
  686. void StopSound( const char *soundname );
  687. void StopSound( const char *soundname, HSOUNDSCRIPTHASH& handle );
  688. void GenderExpandString( char const *in, char *out, int maxlen );
  689. void UpdateLastMadeNoiseTime( const char* pszSoundName = NULL );
  690. static float GetSoundDuration( const char *soundname, char const *actormodel );
  691. static bool GetParametersForSound( const char *soundname, CSoundParameters &params, const char *actormodel );
  692. static bool GetParametersForSound( const char *soundname, HSOUNDSCRIPTHASH& handle, CSoundParameters &params, const char *actormodel );
  693. static int EmitSound( IRecipientFilter& filter, int iEntIndex, const char *soundname, const Vector *pOrigin = NULL, float soundtime = 0.0f, float *duration = NULL );
  694. static int EmitSound( IRecipientFilter& filter, int iEntIndex, const char *soundname, HSOUNDSCRIPTHASH& handle, const Vector *pOrigin = NULL, float soundtime = 0.0f, float *duration = NULL );
  695. static void StopSound( int iEntIndex, const char *soundname );
  696. static soundlevel_t LookupSoundLevel( const char *soundname );
  697. static soundlevel_t LookupSoundLevel( const char *soundname, HSOUNDSCRIPTHASH& handle );
  698. static int EmitSound( IRecipientFilter& filter, int iEntIndex, const EmitSound_t & params );
  699. static int EmitSound( IRecipientFilter& filter, int iEntIndex, const EmitSound_t & params, HSOUNDSCRIPTHASH& handle );
  700. static void StopSound( int iEntIndex, int iChannel, const char *pSample, bool bIsStoppingSpeakerSound = false );
  701. static void EmitAmbientSound( int entindex, const Vector& origin, const char *soundname, int flags = 0, float soundtime = 0.0f, float *duration = NULL );
  702. // These files need to be listed in scripts/game_sounds_manifest.txt
  703. static HSOUNDSCRIPTHASH PrecacheScriptSound( const char *soundname );
  704. static void PrefetchScriptSound( const char *soundname );
  705. // For each client who appears to be a valid recipient, checks the client has disabled CC and if so, removes them from
  706. // the recipient list.
  707. static void RemoveRecipientsIfNotCloseCaptioning( C_RecipientFilter& filter );
  708. static void EmitCloseCaption( IRecipientFilter& filter, int entindex, char const *token, CUtlVector< Vector >& soundorigins, float duration, bool warnifmissing = false );
  709. // Moves all aiments into their correct position for the frame
  710. static void MarkAimEntsDirty();
  711. static void CalcAimEntPositions();
  712. static bool IsPrecacheAllowed();
  713. static void SetAllowPrecache( bool allow );
  714. static bool m_bAllowPrecache;
  715. static bool IsSimulatingOnAlternateTicks();
  716. public:
  717. static bool sm_bAccurateTriggerBboxChecks; // SOLID_BBOX entities do a fully accurate trigger vs bbox check when this is set
  718. // C_BaseEntity local functions
  719. public:
  720. virtual void UpdatePartitionListEntry();
  721. // This can be used to setup the entity as a client-only entity.
  722. // Override this to perform per-entity clientside setup
  723. virtual bool InitializeAsClientEntity( const char *pszModelName, bool bRenderWithViewModels );
  724. // This function gets called on all client entities once per simulation phase. If the entity
  725. // is in the simulate list. It dispatches events like OnDataChanged()
  726. // return false if this entity no longer needs to simulate, true otherwise
  727. virtual bool Simulate() { return false; }
  728. // This event is triggered during the simulation phase if an entity's data has changed. It is
  729. // better to hook this instead of PostDataUpdate() because in PostDataUpdate(), server entity origins
  730. // are incorrect and attachment points can't be used.
  731. virtual void OnDataChanged( DataUpdateType_t type );
  732. // This is called once per frame before any data is read in from the server.
  733. virtual void OnPreDataChanged( DataUpdateType_t type );
  734. bool IsStandable() const;
  735. bool IsBSPModel() const;
  736. // If this is a vehicle, returns the vehicle interface
  737. virtual IClientVehicle* GetClientVehicle() { return NULL; }
  738. // Returns the aiment render origin + angles
  739. virtual void GetAimEntOrigin( IClientEntity *pAttachedTo, Vector *pAbsOrigin, QAngle *pAbsAngles );
  740. // get network origin from previous update
  741. virtual const Vector& GetOldOrigin();
  742. // Methods relating to traversing hierarchy
  743. C_BaseEntity *GetMoveParent( void ) const;
  744. C_BaseEntity *GetRootMoveParent();
  745. C_BaseEntity *FirstMoveChild( void ) const;
  746. C_BaseEntity *NextMovePeer( void ) const;
  747. inline ClientEntityHandle_t GetClientHandle() const { return ClientEntityHandle_t( m_RefEHandle ); }
  748. inline bool IsServerEntity( void ) const;
  749. void RenderForceOpaquePass( bool bEnable );
  750. bool IsRenderForceOpaquePass() const;
  751. void RenderWithViewModels( bool bEnable );
  752. bool IsRenderingWithViewModels() const;
  753. void DisableCachedRenderBounds( bool bDisabled );
  754. bool IsCachedRenderBoundsDisabled() const;
  755. // NOTE: The goal of this function is different from IsTranslucent().
  756. // Here, we need to determine whether a renderable is inherently translucent
  757. // when run-time alpha modulation or any other game code is not taken into account
  758. virtual RenderableTranslucencyType_t ComputeTranslucencyType( );
  759. virtual uint8 OverrideAlphaModulation( uint8 nAlpha ) { return nAlpha; }
  760. virtual uint8 OverrideShadowAlphaModulation( uint8 nAlpha ) { return nAlpha; }
  761. // Client code should call this under any circumstances where translucency type may change
  762. void OnTranslucencyTypeChanged();
  763. // Client code should call this under any circumstances where splitscreen rendering may change
  764. void OnSplitscreenRenderingChanged();
  765. virtual void GetToolRecordingState( KeyValues *msg );
  766. virtual void CleanupToolRecordingState( KeyValues *msg );
  767. // The value returned by here determines whether or not (and how) the entity
  768. // is put into the spatial partition.
  769. virtual CollideType_t GetCollideType( void );
  770. virtual bool ShouldDraw();
  771. inline bool IsVisible() const;
  772. inline bool IsVisibleToAnyPlayer() const;
  773. void UpdateVisibility();
  774. // Totally sucky, but I can't think of a better way of doing this
  775. // without changing zillions of ShouldDraw calls.
  776. virtual bool ShouldSuppressForSplitScreenPlayer( int nSlot ) { return false; }
  777. // Returns true if the entity changes its position every frame on the server but it doesn't
  778. // set animtime. In that case, the client returns true here so it copies the server time to
  779. // animtime in OnDataChanged and the position history is correct for interpolation.
  780. virtual bool IsSelfAnimating();
  781. // Set appropriate flags and store off data when these fields are about to change
  782. virtual void OnLatchInterpolatedVariables( int flags );
  783. // For predictable entities, stores last networked value
  784. void OnStoreLastNetworkedValue();
  785. // Initialize things given a new model.
  786. virtual CStudioHdr *OnNewModel();
  787. virtual void OnNewParticleEffect( const char *pszParticleName, CNewParticleEffect *pNewParticleEffect );
  788. virtual void OnParticleEffectDeleted( CNewParticleEffect *pParticleEffect );
  789. bool IsSimulatedEveryTick() const;
  790. bool IsAnimatedEveryTick() const;
  791. void SetSimulatedEveryTick( bool sim );
  792. void SetAnimatedEveryTick( bool anim );
  793. void Interp_Reset( VarMapping_t *map );
  794. virtual void ResetLatched();
  795. float GetInterpolationAmount( int flags );
  796. float GetLastChangeTime( int flags );
  797. //Get the time we would pass as an input to our interpolators
  798. float GetEffectiveInterpolationCurTime( float currentTime );
  799. // Interpolate the position for rendering
  800. virtual bool Interpolate( float currentTime );
  801. // Did the object move so far that it shouldn't interpolate?
  802. bool Teleported( void );
  803. // Is this a submodel of the world ( *1 etc. in name ) ( brush models only )
  804. virtual bool IsSubModel( void );
  805. // Deal with EF_* flags
  806. virtual bool CreateLightEffects( void );
  807. void AddToAimEntsList();
  808. void RemoveFromAimEntsList();
  809. // Reset internal fields
  810. virtual void Clear( void );
  811. // Helper to draw raw brush models
  812. virtual int DrawBrushModel( bool bTranslucent, int nFlags, bool bTwoPass );
  813. // returns the material animation start time
  814. virtual float GetTextureAnimationStartTime();
  815. // Indicates that a texture animation has wrapped
  816. virtual void TextureAnimationWrapped();
  817. // Set the next think time. Pass in CLIENT_THINK_ALWAYS to have Think() called each frame.
  818. virtual void SetNextClientThink( float nextThinkTime );
  819. // anything that has health can override this...
  820. virtual void SetHealth(int iHealth) {}
  821. virtual int GetHealth() const { return 0; }
  822. virtual int GetMaxHealth() const { return 1; }
  823. // Returns the health fraction
  824. float HealthFraction() const;
  825. // Should this object cast shadows?
  826. virtual ShadowType_t ShadowCastType();
  827. // Should this object receive shadows?
  828. virtual bool ShouldReceiveProjectedTextures( int flags );
  829. // Shadow-related methods
  830. virtual bool IsShadowDirty( );
  831. virtual void MarkShadowDirty( bool bDirty );
  832. virtual IClientRenderable *GetShadowParent();
  833. virtual IClientRenderable *FirstShadowChild();
  834. virtual IClientRenderable *NextShadowPeer();
  835. // Sets up a render handle so the leaf system will draw this entity.
  836. void AddToLeafSystem();
  837. void AddToLeafSystem( bool bRenderWithViewModels );
  838. // remove entity form leaf system again
  839. void RemoveFromLeafSystem();
  840. // A method to apply a decal to an entity
  841. virtual void AddDecal( const Vector& rayStart, const Vector& rayEnd,
  842. const Vector& decalCenter, int hitbox, int decalIndex, bool doTrace, trace_t& tr, int maxLODToDecal = ADDDECAL_TO_ALL_LODS, const Vector *saxis = NULL, int nAdditionalDecalFlags = 0 );
  843. // A method to remove all decals from an entity
  844. void RemoveAllDecals( void );
  845. // Is this a brush model?
  846. bool IsBrushModel() const;
  847. // A random value 0-1 used by proxies to make sure they're not all in sync
  848. float ProxyRandomValue() const { return m_flProxyRandomValue; }
  849. void SetProxyRandomValue( float flNewValue ) { m_flProxyRandomValue = flNewValue; }
  850. // The spawn time of this entity
  851. float SpawnTime() const { return m_flSpawnTime; }
  852. virtual bool IsClientCreated( void ) const;
  853. virtual void UpdateOnRemove( void );
  854. virtual void SUB_Remove( void );
  855. // Prediction stuff
  856. /////////////////
  857. void CheckInitPredictable( const char *context );
  858. void CheckShutdownPredictable( const char *context );
  859. virtual C_BasePlayer *GetPredictionOwner( void );
  860. void AllocateIntermediateData( void );
  861. void DestroyIntermediateData( void );
  862. void ShiftIntermediateDataForward( int slots_to_remove, int previous_last_slot );
  863. void ShiftFirstPredictedIntermediateDataForward( int slots_to_remove );
  864. void ShiftIntermediateData_TickAdjust( int delta, int last_slot );
  865. void *GetPredictedFrame( int framenumber );
  866. void *GetFirstPredictedFrame( int framenumber ); //similar to GetPredictedFrame() but only stores the results from the first prediction of each command
  867. void GetUnacknowledgedPredictedFrameRange( int &iStart, int &iEnd ); //Get the range of predicted frames we may restore from at any moment.
  868. void *GetOriginalNetworkDataObject( void );
  869. bool IsIntermediateDataAllocated( void ) const;
  870. virtual void InitPredictable( C_BasePlayer *pOwner );
  871. void ShutdownPredictable( void );
  872. int GetSplitUserPlayerPredictionSlot();
  873. virtual void SetPredictable( bool state );
  874. bool GetPredictable( void ) const;
  875. void PreEntityPacketReceived( int commands_acknowledged );
  876. void PostEntityPacketReceived( void );
  877. bool PostNetworkDataReceived( int commands_acknowledged );
  878. virtual void HandlePredictionError( bool bErrorInThisEntity ); //we just processed a network update with errors, bErrorInThisEntity is false if the prediction errors were entirely in other entities and not this one
  879. virtual bool PredictionErrorShouldResetLatchedForAllPredictables( void ) { return true; } //legacy behavior is that any prediction error causes all predictables to reset latched
  880. virtual bool PredictionIsPhysicallySimulated( void ) { return false; } //by default, all prediction is driven by player commands, return true if your prediction is based on server simulation ticks
  881. bool GetPredictionEligible( void ) const;
  882. void SetPredictionEligible( bool canpredict );
  883. enum
  884. {
  885. SLOT_ORIGINALDATA = -1,
  886. };
  887. void SaveData( const char *context, int slot, int type );
  888. void RestoreData( const char *context, int slot, int type );
  889. // Called after restoring data into prediction slots. This function is used in place of proxies
  890. // on the variables, so if some variable like m_nModelIndex needs to update other state (like
  891. // the model pointer), it is done here.
  892. void OnPostRestoreData();
  893. virtual char const * DamageDecal( int bitsDamageType, int gameMaterial );
  894. virtual void DecalTrace( trace_t *pTrace, char const *decalName );
  895. virtual void ImpactTrace( trace_t *pTrace, int iDamageType, char *pCustomImpactName );
  896. virtual bool ShouldPredict( void ) { return false; };
  897. // interface function pointers
  898. union{
  899. // Doing this lame union to force the compiler to properly align the
  900. // member function pointer to at least 16-bytes for warning control.
  901. void (C_BaseEntity::*m_pfnThink)(void);
  902. char __dont_use_me_pad[16];
  903. };
  904. virtual void Think( void )
  905. {
  906. AssertMsg( m_pfnThink != &C_BaseEntity::Think, "Infinite recursion is infinitely bad." );
  907. if ( m_pfnThink )
  908. {
  909. ( this->*m_pfnThink )();
  910. }
  911. }
  912. void PhysicsDispatchThink( BASEPTR thinkFunc );
  913. // Toggle the visualization of the entity's abs/bbox
  914. enum
  915. {
  916. VISUALIZE_COLLISION_BOUNDS = 0x1,
  917. VISUALIZE_SURROUNDING_BOUNDS = 0x2,
  918. VISUALIZE_RENDER_BOUNDS = 0x4,
  919. };
  920. void ClearBBoxVisualization( void );
  921. void ToggleBBoxVisualization( int fVisFlags );
  922. void DrawBBoxVisualizations( void );
  923. virtual bool PreRender( int nSplitScreenPlayerSlot );
  924. bool IsViewEntity() const;
  925. // Methods implemented on both client and server
  926. public:
  927. void SetSize( const Vector &vecMin, const Vector &vecMax ); // UTIL_SetSize( pev, mins, maxs );
  928. virtual char const *GetClassname( void );
  929. char const *GetDebugName( void );
  930. virtual const char *GetPlayerName() const { return NULL; }
  931. static int PrecacheModel( const char *name );
  932. static bool PrecacheSound( const char *name );
  933. static void PrefetchSound( const char *name );
  934. void Remove( ); // UTIL_Remove( this );
  935. #ifdef PORTAL2
  936. const char *GetSignifierName( void );
  937. #endif // PORTAL2
  938. public:
  939. // Returns the attachment point index on our parent that our transform is relative to.
  940. // 0 if we're relative to the parent's absorigin and absangles.
  941. unsigned char GetParentAttachment() const;
  942. // Externalized data objects ( see sharreddefs.h for DataObjectType_t )
  943. bool HasDataObjectType( int type ) const;
  944. void AddDataObjectType( int type );
  945. void RemoveDataObjectType( int type );
  946. void *GetDataObject( int type );
  947. void *CreateDataObject( int type );
  948. void DestroyDataObject( int type );
  949. void DestroyAllDataObjects( void );
  950. // Determine approximate velocity based on updates from server
  951. virtual void EstimateAbsVelocity( Vector& vel );
  952. #if !defined( NO_ENTITY_PREDICTION )
  953. // The player drives simulation of this entity
  954. void SetPlayerSimulated( C_BasePlayer *pOwner );
  955. bool IsPlayerSimulated( void ) const;
  956. CBasePlayer *GetSimulatingPlayer( void );
  957. void UnsetPlayerSimulated( void );
  958. #endif
  959. // Sorry folks, here lies TF2-specific stuff that really has no other place to go
  960. virtual bool CanBePoweredUp( void ) { return false; }
  961. virtual bool AttemptToPowerup( int iPowerup, float flTime, float flAmount = 0, C_BaseEntity *pAttacker = NULL, CDamageModifier *pDamageModifier = NULL ) { return false; }
  962. void SetCheckUntouch( bool check );
  963. bool GetCheckUntouch() const;
  964. virtual bool IsCurrentlyTouching( void ) const;
  965. virtual void StartTouch( C_BaseEntity *pOther );
  966. virtual void Touch( C_BaseEntity *pOther );
  967. virtual void EndTouch( C_BaseEntity *pOther );
  968. void (C_BaseEntity ::*m_pfnTouch)( C_BaseEntity *pOther );
  969. void PhysicsStep( void );
  970. protected:
  971. static bool sm_bDisableTouchFuncs; // Disables PhysicsTouch and PhysicsStartTouch function calls
  972. bool m_bIsAutoaimTarget;
  973. public:
  974. touchlink_t *PhysicsMarkEntityAsTouched( C_BaseEntity *other );
  975. void PhysicsTouch( C_BaseEntity *pentOther );
  976. void PhysicsStartTouch( C_BaseEntity *pentOther );
  977. // HACKHACK:Get the trace_t from the last physics touch call (replaces the even-hackier global trace vars)
  978. static const trace_t &GetTouchTrace( void );
  979. // FIXME: Should be private, but I can't make em private just yet
  980. void PhysicsImpact( C_BaseEntity *other, trace_t &trace );
  981. void PhysicsMarkEntitiesAsTouching( C_BaseEntity *other, trace_t &trace );
  982. void PhysicsMarkEntitiesAsTouchingEventDriven( C_BaseEntity *other, trace_t &trace );
  983. void PhysicsTouchTriggers( const Vector *pPrevAbsOrigin = NULL );
  984. // Physics helper
  985. static void PhysicsRemoveTouchedList( C_BaseEntity *ent );
  986. static void PhysicsNotifyOtherOfUntouch( C_BaseEntity *ent, C_BaseEntity *other );
  987. static void PhysicsRemoveToucher( C_BaseEntity *other, touchlink_t *link );
  988. groundlink_t *AddEntityToGroundList( CBaseEntity *other );
  989. void PhysicsStartGroundContact( CBaseEntity *pentOther );
  990. static void PhysicsNotifyOtherOfGroundRemoval( CBaseEntity *ent, CBaseEntity *other );
  991. static void PhysicsRemoveGround( CBaseEntity *other, groundlink_t *link );
  992. static void PhysicsRemoveGroundList( CBaseEntity *ent );
  993. void StartGroundContact( CBaseEntity *ground );
  994. void EndGroundContact( CBaseEntity *ground );
  995. void SetGroundChangeTime( float flTime );
  996. float GetGroundChangeTime( void );
  997. // Remove this as ground entity for all object resting on this object
  998. void WakeRestingObjects();
  999. bool HasNPCsOnIt();
  1000. bool PhysicsCheckWater( void );
  1001. void PhysicsCheckVelocity( void );
  1002. void PhysicsAddHalfGravity( float timestep );
  1003. void PhysicsAddGravityMove( Vector &move );
  1004. virtual unsigned int PhysicsSolidMaskForEntity( void ) const;
  1005. void SetGroundEntity( C_BaseEntity *ground );
  1006. C_BaseEntity *GetGroundEntity( void );
  1007. C_BaseEntity *GetGroundEntity( void ) const { return const_cast<C_BaseEntity *>(this)->GetGroundEntity(); }
  1008. void PhysicsPushEntity( const Vector& push, trace_t *pTrace );
  1009. void PhysicsCheckWaterTransition( void );
  1010. // Performs the collision resolution for fliers.
  1011. void PerformFlyCollisionResolution( trace_t &trace, Vector &move );
  1012. void ResolveFlyCollisionBounce( trace_t &trace, Vector &vecVelocity, float flMinTotalElasticity = 0.0f );
  1013. void ResolveFlyCollisionSlide( trace_t &trace, Vector &vecVelocity );
  1014. void ResolveFlyCollisionCustom( trace_t &trace, Vector &vecVelocity );
  1015. void PhysicsCheckForEntityUntouch( void );
  1016. // Creates the shadow (if it doesn't already exist) based on shadow cast type
  1017. void CreateShadow();
  1018. // Destroys the shadow; causes its type to be recomputed if the entity doesn't go away immediately.
  1019. void DestroyShadow();
  1020. protected:
  1021. // think function handling
  1022. enum thinkmethods_t
  1023. {
  1024. THINK_FIRE_ALL_FUNCTIONS,
  1025. THINK_FIRE_BASE_ONLY,
  1026. THINK_FIRE_ALL_BUT_BASE,
  1027. };
  1028. public:
  1029. // Unlinks from hierarchy
  1030. // Set the movement parent. Your local origin and angles will become relative to this parent.
  1031. // If iAttachment is a valid attachment on the parent, then your local origin and angles
  1032. // are relative to the attachment on this entity.
  1033. void SetParent( C_BaseEntity *pParentEntity, int iParentAttachment=0 );
  1034. bool PhysicsRunThink( thinkmethods_t thinkMethod = THINK_FIRE_ALL_FUNCTIONS );
  1035. bool PhysicsRunSpecificThink( int nContextIndex, BASEPTR thinkFunc );
  1036. virtual void PhysicsSimulate( void );
  1037. virtual bool IsAlive( void )const;
  1038. bool IsInWorld( void ) { return true; }
  1039. bool IsWorld() const { return entindex() == 0; }
  1040. /////////////////
  1041. virtual bool ShouldRegenerateOriginFromCellBits() const;
  1042. virtual bool IsPlayer( void ) const { return false; };
  1043. virtual bool IsWeaponWorldModel( void ) const { return false; };
  1044. virtual bool IsBaseCombatCharacter( void ) { return false; };
  1045. //virtual bool IsGrenadeProjectile( void ) { return false; };
  1046. virtual C_BaseCombatCharacter *MyCombatCharacterPointer( void ) { return NULL; }
  1047. virtual bool IsNPC( void ) { return false; }
  1048. C_AI_BaseNPC *MyNPCPointer( void );
  1049. virtual bool IsSprite( void ) const { return false; }
  1050. virtual bool IsProp( void ) const { return false; }
  1051. // TF2 specific
  1052. virtual bool IsBaseObject( void ) const { return false; }
  1053. virtual bool IsBaseCombatWeapon( void ) const { return false; }
  1054. virtual class C_BaseCombatWeapon *MyCombatWeaponPointer() { return NULL; }
  1055. // Entities like the player, weapon models, and view models have special logic per-view port related to visibility and the model to be used, etc.
  1056. virtual bool ShouldDrawForSplitScreenUser( int nSlot );
  1057. void SetBlurState( bool bShouldBlur );
  1058. virtual bool IsBlurred( void );
  1059. virtual bool IsBaseTrain( void ) const { return false; }
  1060. // Returns the eye point + angles (used for viewing + shooting)
  1061. virtual Vector EyePosition( void );
  1062. virtual const QAngle& EyeAngles( void ); // Direction of eyes
  1063. virtual const QAngle& LocalEyeAngles( void ); // Direction of eyes in local space (pl.v_angle)
  1064. // position of ears
  1065. virtual Vector EarPosition( void );
  1066. Vector EyePosition( void ) const; // position of eyes
  1067. const QAngle &EyeAngles( void ) const; // Direction of eyes in world space
  1068. const QAngle &LocalEyeAngles( void ) const; // Direction of eyes
  1069. Vector EarPosition( void ) const; // position of ears
  1070. // Called by physics to see if we should avoid a collision test....
  1071. virtual bool ShouldCollide( int collisionGroup, int contentsMask ) const;
  1072. // Sets physics parameters
  1073. void SetFriction( float flFriction );
  1074. void SetGravity( float flGravity );
  1075. float GetGravity( void ) const;
  1076. // Sets the model from a model index
  1077. void SetModelByIndex( int nModelIndex );
  1078. // Set model... (NOTE: Should only be used by client-only entities
  1079. // Returns false if the model name is bogus
  1080. bool SetModel( const char *pModelName );
  1081. virtual void SetModelPointer( const model_t *pModel );
  1082. // Access movetype and solid.
  1083. void SetMoveType( MoveType_t val, MoveCollide_t moveCollide = MOVECOLLIDE_DEFAULT ); // Set to one of the MOVETYPE_ defines.
  1084. void SetMoveCollide( MoveCollide_t val ); // Set to one of the MOVECOLLIDE_ defines.
  1085. void SetSolid( SolidType_t val ); // Set to one of the SOLID_ defines.
  1086. // NOTE: Setting the abs velocity in either space will cause a recomputation
  1087. // in the other space, so setting the abs velocity will also set the local vel
  1088. void SetLocalVelocity( const Vector &vecVelocity );
  1089. void SetAbsVelocity( const Vector &vecVelocity );
  1090. const Vector& GetLocalVelocity() const;
  1091. const Vector& GetAbsVelocity( ) const;
  1092. void ApplyLocalVelocityImpulse( const Vector &vecImpulse );
  1093. void ApplyAbsVelocityImpulse( const Vector &vecImpulse );
  1094. void ApplyLocalAngularVelocityImpulse( const AngularImpulse &angImpulse );
  1095. // NOTE: Setting the abs velocity in either space will cause a recomputation
  1096. // in the other space, so setting the abs velocity will also set the local vel
  1097. void SetLocalAngularVelocity( const QAngle &vecAngVelocity );
  1098. const QAngle& GetLocalAngularVelocity( ) const;
  1099. // void SetAbsAngularVelocity( const QAngle &vecAngAbsVelocity );
  1100. // const QAngle& GetAbsAngularVelocity( ) const;
  1101. const Vector& GetBaseVelocity() const;
  1102. void SetBaseVelocity( const Vector& v );
  1103. virtual const Vector &GetViewOffset() const;
  1104. virtual void SetViewOffset( const Vector& v );
  1105. virtual void GetGroundVelocityToApply( Vector &vecGroundVel ) { vecGroundVel = vec3_origin; }
  1106. // Invalidates the abs state of all children
  1107. void InvalidatePhysicsRecursive( int nChangeFlags );
  1108. ClientRenderHandle_t GetRenderHandle() const;
  1109. void SetRemovalFlag( bool bRemove );
  1110. bool HasSpawnFlags( int nFlags ) const;
  1111. // Effects...
  1112. bool IsEffectActive( int nEffectMask ) const;
  1113. void AddEffects( int nEffects );
  1114. void RemoveEffects( int nEffects );
  1115. int GetEffects( void ) const;
  1116. void ClearEffects( void );
  1117. void SetEffects( int nEffects );
  1118. // Computes the abs position of a point specified in local space
  1119. void ComputeAbsPosition( const Vector &vecLocalPosition, Vector *pAbsPosition );
  1120. // Computes the abs position of a direction specified in local space
  1121. void ComputeAbsDirection( const Vector &vecLocalDirection, Vector *pAbsDirection );
  1122. // These methods encapsulate MOVETYPE_FOLLOW, which became obsolete
  1123. void FollowEntity( CBaseEntity *pBaseEntity, bool bBoneMerge = true );
  1124. void StopFollowingEntity( ); // will also change to MOVETYPE_NONE
  1125. virtual bool IsFollowingEntity();
  1126. CBaseEntity *GetFollowedEntity();
  1127. // For shadows rendering the correct body + sequence...
  1128. virtual int GetBody() { return 0; }
  1129. virtual int GetSkin() { return 0; }
  1130. const Vector &ScriptGetForward( void ) { static Vector vecForward; GetVectors( &vecForward, NULL, NULL ); return vecForward; }
  1131. const Vector &ScriptGetLeft( void ) { static Vector vecLeft; GetVectors( NULL, &vecLeft, NULL ); return vecLeft; }
  1132. const Vector &ScriptGetUp( void ) { static Vector vecUp; GetVectors( NULL, NULL, &vecUp ); return vecUp; }
  1133. // Stubs on client
  1134. void NetworkStateManualMode( bool activate ) { }
  1135. void NetworkStateChanged() { }
  1136. void NetworkStateChanged( void *pVar ) { }
  1137. void NetworkStateSetUpdateInterval( float N ) { }
  1138. void NetworkStateForceUpdate() { }
  1139. // Think functions with contexts
  1140. int RegisterThinkContext( const char *szContext );
  1141. BASEPTR ThinkSet( BASEPTR func, float flNextThinkTime = 0, const char *szContext = NULL );
  1142. void SetNextThink( float nextThinkTime, const char *szContext = NULL );
  1143. float GetNextThink( const char *szContext = NULL );
  1144. float GetLastThink( const char *szContext = NULL );
  1145. int GetNextThinkTick( const char *szContext = NULL );
  1146. int GetLastThinkTick( const char *szContext = NULL );
  1147. // These set entity flags (EFL_*) to help optimize queries
  1148. void CheckHasThinkFunction( bool isThinkingHint = false );
  1149. void CheckHasGamePhysicsSimulation();
  1150. bool WillThink();
  1151. bool WillSimulateGamePhysics();
  1152. int GetFirstThinkTick(); // get first tick thinking on any context
  1153. float GetAnimTime() const;
  1154. void SetAnimTime( float at );
  1155. float GetSimulationTime() const;
  1156. void SetSimulationTime( float st );
  1157. #if defined(ENABLE_CREATE_TIME)
  1158. float GetCreateTime() { return m_flCreateTime; }
  1159. void SetCreateTime( float flCreateTime ) { m_flCreateTime = flCreateTime; }
  1160. #endif
  1161. int GetCreationTick() const;
  1162. #ifdef _DEBUG
  1163. void FunctionCheck( inputfunc_t pFunction, const char *name );
  1164. ENTITYFUNCPTR TouchSet( ENTITYFUNCPTR func, char *name )
  1165. {
  1166. //COMPILE_TIME_ASSERT( sizeof(func) == 4 ? 8 );
  1167. m_pfnTouch = func;
  1168. //FunctionCheck( reinterpret_cast<inputfunc_t>(m_pfnTouch), name );
  1169. return func;
  1170. }
  1171. #endif
  1172. // Gets the model instance + shadow handle
  1173. virtual ModelInstanceHandle_t GetModelInstance() { return m_ModelInstance; }
  1174. void SetModelInstance( ModelInstanceHandle_t hInstance) { m_ModelInstance = hInstance; }
  1175. bool SnatchModelInstance( C_BaseEntity * pToEntity );
  1176. virtual ClientShadowHandle_t GetShadowHandle() const { return m_ShadowHandle; }
  1177. virtual ClientRenderHandle_t& RenderHandle();
  1178. void CreateModelInstance();
  1179. // Sets the origin + angles to match the last position received
  1180. void MoveToLastReceivedPosition( bool force = false );
  1181. bool IsAutoaimTarget( void ) const;
  1182. protected:
  1183. // Only meant to be called from subclasses
  1184. void DestroyModelInstance();
  1185. // Interpolate entity
  1186. static void ProcessTeleportList();
  1187. static void ProcessInterpolatedList();
  1188. static void CheckInterpolatedVarParanoidMeasurement();
  1189. // overrideable rules if an entity should interpolate
  1190. virtual bool ShouldInterpolate();
  1191. // Call this in OnDataChanged if you don't chain it down!
  1192. void MarkMessageReceived();
  1193. // Gets the last message time
  1194. float GetLastMessageTime() const { return m_flLastMessageTime; }
  1195. // For non-players
  1196. int PhysicsClipVelocity (const Vector& in, const Vector& normal, Vector& out, float overbounce );
  1197. protected:
  1198. // Two part guts of Interpolate(). Shared with C_BaseAnimating.
  1199. enum
  1200. {
  1201. INTERPOLATE_STOP=0,
  1202. INTERPOLATE_CONTINUE
  1203. };
  1204. // Returns INTERPOLATE_STOP or INTERPOLATE_CONTINUE.
  1205. // bNoMoreChanges is set to 1 if you can call RemoveFromInterpolationList on the entity.
  1206. int BaseInterpolatePart1( float &currentTime, Vector &oldOrigin, QAngle &oldAngles, int &bNoMoreChanges );
  1207. void BaseInterpolatePart2( Vector &oldOrigin, QAngle &oldAngles, int nChangeFlags );
  1208. public:
  1209. // Accessors for above
  1210. static int GetPredictionRandomSeed( void );
  1211. static void SetPredictionRandomSeed( const CUserCmd *cmd );
  1212. static C_BasePlayer *GetPredictionPlayer( void );
  1213. static void SetPredictionPlayer( C_BasePlayer *player );
  1214. static void CheckCLInterpChanged();
  1215. // Collision group accessors
  1216. int GetCollisionGroup() const;
  1217. void SetCollisionGroup( int collisionGroup );
  1218. void CollisionRulesChanged();
  1219. static C_BaseEntity *Instance( int iEnt );
  1220. // Doesn't do much, but helps with trace results
  1221. static C_BaseEntity *Instance( IClientEntity *ent );
  1222. static C_BaseEntity *Instance( CBaseHandle hEnt );
  1223. // For debugging shared code
  1224. static bool IsServer( void );
  1225. static bool IsClient( void );
  1226. static char const *GetDLLType( void );
  1227. static void SetAbsQueriesValid( bool bValid );
  1228. static bool IsAbsQueriesValid( void );
  1229. // Enable/disable abs recomputations on a stack.
  1230. static void PushEnableAbsRecomputations( bool bEnable );
  1231. static void PopEnableAbsRecomputations();
  1232. // This requires the abs recomputation stack to be empty and just sets the global state.
  1233. // It should only be used at the scope of the frame loop.
  1234. static void EnableAbsRecomputations( bool bEnable );
  1235. static bool IsAbsRecomputationsEnabled( void );
  1236. static void PreRenderEntities( int nSplitScreenPlayerSlot );
  1237. static void PurgeRemovedEntities();
  1238. static void SimulateEntities();
  1239. //A queue that processes after we simulate all client entities. For operations that modify the simulate list (portal ghostrenderables)
  1240. static CCallQueue * GetSimulateCallQueue( void );
  1241. // Bloat the culling bbox past the parent ent's bbox in local space if EF_BONEMERGE_FASTCULL is set.
  1242. virtual void BoneMergeFastCullBloat( Vector &localMins, Vector &localMaxs, const Vector &thisEntityMins, const Vector &thisEntityMaxs ) const;
  1243. // Accessors for color.
  1244. const color24 GetRenderColor() const;
  1245. byte GetRenderColorR() const;
  1246. byte GetRenderColorG() const;
  1247. byte GetRenderColorB() const;
  1248. byte GetRenderAlpha() const;
  1249. void SetRenderColor( byte r, byte g, byte b );
  1250. void SetRenderColorR( byte r );
  1251. void SetRenderColorG( byte g );
  1252. void SetRenderColorB( byte b );
  1253. void SetRenderAlpha( byte a );
  1254. void SetRenderMode( RenderMode_t nRenderMode, bool bForceUpdate = false );
  1255. RenderMode_t GetRenderMode() const;
  1256. void SetRenderFX( RenderFx_t nRenderFX, float flStartTime = FLT_MAX, float flDuration = 0.0f );
  1257. RenderFx_t GetRenderFX() const;
  1258. // Returns true if there was a change.
  1259. bool SetCellBits( int cellbits = CELL_BASEENTITY_ORIGIN_CELL_BITS );
  1260. static void RecvProxy_CellBits( const CRecvProxyData *pData, void *pStruct, void *pOut );
  1261. static void RecvProxy_CellX( const CRecvProxyData *pData, void *pStruct, void *pOut );
  1262. static void RecvProxy_CellY( const CRecvProxyData *pData, void *pStruct, void *pOut );
  1263. static void RecvProxy_CellZ( const CRecvProxyData *pData, void *pStruct, void *pOut );
  1264. static void RecvProxy_CellOrigin( const CRecvProxyData *pData, void *pStruct, void *pOut );
  1265. static void RecvProxy_CellOriginXY( const CRecvProxyData *pData, void *pStruct, void *pOut );
  1266. static void RecvProxy_CellOriginZ( const CRecvProxyData *pData, void *pStruct, void *pOut );
  1267. static void RecvProxyOldSpottedByMask( const CRecvProxyData *pData, void *pStruct, void *pOut );
  1268. const char *GetEntityName();
  1269. public:
  1270. // Determine what entity this corresponds to
  1271. int index;
  1272. // Entity flags that are only for the client (ENTCLIENTFLAG_ defines).
  1273. unsigned short m_EntClientFlags;
  1274. private:
  1275. // Model for rendering
  1276. const model_t *model;
  1277. CNetworkColor32( m_clrRender );
  1278. public:
  1279. protected: // Cell data is available to derived classes for RecvProxy issues
  1280. int m_cellbits;
  1281. int m_cellwidth;
  1282. int m_cellX;
  1283. int m_cellY;
  1284. int m_cellZ;
  1285. Vector m_vecCellOrigin; // cached cell offset position
  1286. // BEGIN PREDICTION DATA COMPACTION (these fields are together to allow for faster copying in prediction system)
  1287. // FTYPEDESC_INSENDTABLE STUFF
  1288. private:
  1289. Vector m_vecAbsVelocity;
  1290. Vector m_vecAbsOrigin;
  1291. Vector m_vecOrigin;
  1292. QAngle m_vecAngVelocity;
  1293. QAngle m_angAbsRotation;
  1294. QAngle m_angRotation;
  1295. float m_flGravity;
  1296. // A random value used by material proxies for each model instance.
  1297. float m_flProxyRandomValue;
  1298. int m_iEFlags; // entity flags EFL_*
  1299. unsigned char m_nWaterType;
  1300. // For client/server entities, true if the entity goes outside the PVS.
  1301. // Unused for client only entities.
  1302. bool m_bDormant;
  1303. bool m_bCanUseBrushModelFastPath;
  1304. // FTYPEDESC_INSENDTABLE STUFF (end)
  1305. private:
  1306. // Effects to apply
  1307. int m_fEffects;
  1308. public:
  1309. // Team Handling
  1310. int m_iTeamNum;
  1311. int m_iPendingTeamNum;
  1312. int m_nNextThinkTick;
  1313. int m_iHealth;
  1314. private:
  1315. int m_fFlags; // Behavior flags
  1316. protected:
  1317. // Object eye position
  1318. Vector m_vecViewOffset;
  1319. private:
  1320. // Object velocity
  1321. Vector m_vecVelocity;
  1322. Vector m_vecBaseVelocity; // Base velocity
  1323. QAngle m_angNetworkAngles;
  1324. // Last values to come over the wire. Used for interpolation.
  1325. Vector m_vecNetworkOrigin;
  1326. // Friction.
  1327. float m_flFriction;
  1328. // The moveparent received from networking data
  1329. CHandle<C_BaseEntity> m_hNetworkMoveParent;
  1330. // The owner!
  1331. EHANDLE m_hOwnerEntity;
  1332. EHANDLE m_hGroundEntity;
  1333. char m_iName[MAX_PATH];
  1334. #ifdef PORTAL2
  1335. char m_iSignifierName[MAX_PATH];
  1336. #endif // PORTAL2
  1337. public:
  1338. // Object model index
  1339. short m_nModelIndex;
  1340. private:
  1341. unsigned char m_nRenderFX;
  1342. unsigned char m_nRenderMode;
  1343. unsigned char m_MoveType;
  1344. unsigned char m_MoveCollide;
  1345. unsigned char m_nWaterLevel;
  1346. public:
  1347. char m_lifeState;
  1348. // END PREDICTION DATA COMPACTION
  1349. public:
  1350. public:
  1351. // Time animation sequence or frame was last changed
  1352. float m_flAnimTime;
  1353. float m_flOldAnimTime;
  1354. float m_flSimulationTime;
  1355. float m_flOldSimulationTime;
  1356. #if defined(ENABLE_CREATE_TIME)
  1357. float m_flCreateTime;
  1358. #endif
  1359. private:
  1360. unsigned char m_nOldRenderMode;
  1361. public:
  1362. // Used to store the state we were added to the BSP as, so it can
  1363. // reinsert the entity if the state changes.
  1364. ClientRenderHandle_t m_hRender; // link into spatial partition
  1365. CBitVec< MAX_SPLITSCREEN_PLAYERS > m_VisibilityBits;
  1366. // Interpolation says don't draw yet
  1367. bool m_bReadyToDraw;
  1368. bool m_bClientSideRagdoll;
  1369. // Should we be interpolating?
  1370. static bool IsInterpolationEnabled();
  1371. //
  1372. int m_nLastThinkTick;
  1373. char m_takedamage;
  1374. // was pev->speed
  1375. float m_flSpeed;
  1376. // Certain entities (projectiles) can be created on the client
  1377. #if !defined( NO_ENTITY_PREDICTION ) && defined( USE_PREDICTABLEID )
  1378. CPredictableId m_PredictableID;
  1379. PredictionContext *m_pPredictionContext;
  1380. #endif
  1381. // used so we know when things are no longer touching
  1382. int touchStamp;
  1383. // Called after predicted entity has been acknowledged so that no longer needed entity can
  1384. // be deleted
  1385. // Return true to force deletion right now, regardless of isbeingremoved
  1386. virtual bool OnPredictedEntityRemove( bool isbeingremoved, C_BaseEntity *predicted );
  1387. bool IsDormantPredictable( void ) const;
  1388. bool BecameDormantThisPacket( void ) const;
  1389. void SetDormantPredictable( bool dormant );
  1390. int GetWaterLevel() const;
  1391. void SetWaterLevel( int nLevel );
  1392. int GetWaterType() const;
  1393. void SetWaterType( int nType );
  1394. float GetElasticity( void ) const;
  1395. int GetTextureFrameIndex( void );
  1396. void SetTextureFrameIndex( int iIndex );
  1397. virtual bool GetShadowCastDistance( float *pDist, ShadowType_t shadowType ) const;
  1398. virtual bool GetShadowCastDirection( Vector *pDirection, ShadowType_t shadowType ) const;
  1399. virtual C_BaseEntity *GetShadowUseOtherEntity( void ) const;
  1400. virtual void SetShadowUseOtherEntity( C_BaseEntity *pEntity );
  1401. CDiscontinuousInterpolatedVar< QAngle >& GetRotationInterpolator();
  1402. CDiscontinuousInterpolatedVar< Vector >& GetOriginInterpolator();
  1403. virtual bool AddRagdollToFadeQueue( void ) { return true; }
  1404. // Dirty bits
  1405. void MarkRenderHandleDirty();
  1406. // used by SourceTV since move-parents may be missing when child spawns.
  1407. void HierarchyUpdateMoveParent();
  1408. void SetCPULevels( int nMinCPULevel, int nMaxCPULevel );
  1409. void SetGPULevels( int nMinGPULevel, int nMaxGPULevel );
  1410. int GetMinCPULevel( ) const;
  1411. int GetMaxCPULevel( ) const;
  1412. int GetMinGPULevel( ) const;
  1413. int GetMaxGPULevel( ) const;
  1414. #if defined ( PORTAL2 )
  1415. int GetServerObjectCaps() { return m_iObjectCapsCache; }
  1416. #endif
  1417. protected:
  1418. // FIXME: Should I move the functions handling these out of C_ClientEntity
  1419. // and into C_BaseEntity? Then we could make these private.
  1420. // Client handle
  1421. CBaseHandle m_RefEHandle; // Reference ehandle. Used to generate ehandles off this entity.
  1422. private:
  1423. // Set by tools if this entity should route "info" to various tools listening to HTOOLENTITIES
  1424. #ifndef NO_TOOLFRAMEWORK
  1425. bool m_bEnabledInToolView;
  1426. bool m_bToolRecording;
  1427. HTOOLHANDLE m_ToolHandle;
  1428. int m_nLastRecordedFrame;
  1429. bool m_bRecordInTools; // should this entity be recorded in the tools (we exclude some things like models for menus)
  1430. #endif
  1431. protected:
  1432. // pointer to the entity's physics object (vphysics.dll)
  1433. IPhysicsObject *m_pPhysicsObject;
  1434. float m_flNonShadowMass; // cached mass (shadow controllers set mass to VPHYSICS_MAX_MASS, or 50000)
  1435. #if !defined( NO_ENTITY_PREDICTION )
  1436. bool m_bPredictionEligible;
  1437. #endif
  1438. int m_nSimulationTick;
  1439. // Think contexts
  1440. int GetIndexForThinkContext( const char *pszContext );
  1441. CUtlVector< thinkfunc_t > m_aThinkFunctions;
  1442. int m_iCurrentThinkContext;
  1443. int m_spawnflags;
  1444. // Allow studio models to tell us what their m_nBody value is
  1445. virtual int GetStudioBody( void ) { return 0; }
  1446. // call this in postdataupdate to detect hierarchy changes
  1447. bool IsParentChanging();
  1448. #if defined ( PORTAL2 )
  1449. // Received caps from server. Using this for +use validity checking.
  1450. int m_iObjectCapsCache;
  1451. #endif
  1452. private:
  1453. friend void OnRenderStart();
  1454. // This can be used to setup the entity as a client-only entity. It gets an entity handle,
  1455. // a render handle, and is put into the spatial partition.
  1456. bool InitializeAsClientEntityByIndex( int iIndex, bool bRenderWithViewModels );
  1457. // Figure out the smoothly interpolated origin for all server entities. Happens right before
  1458. // letting all entities simulate.
  1459. static void InterpolateServerEntities();
  1460. // Check which entities want to be drawn and add them to the leaf system.
  1461. static void AddVisibleEntities();
  1462. // For entities marked for recording, post bone messages to IToolSystems
  1463. static void ToolRecordEntities();
  1464. // Computes the base velocity
  1465. void UpdateBaseVelocity( void );
  1466. // Physics-related private methods
  1467. void PhysicsPusher( void );
  1468. void PhysicsNone( void );
  1469. void PhysicsNoclip( void );
  1470. void PhysicsParent( void );
  1471. void PhysicsStepRunTimestep( float timestep );
  1472. void PhysicsToss( void );
  1473. void PhysicsCustom( void );
  1474. // Simulation in local space of rigid children
  1475. void PhysicsRigidChild( void );
  1476. // Computes absolute position based on hierarchy
  1477. void CalcAbsolutePosition( );
  1478. void CalcAbsoluteVelocity();
  1479. // Computes new angles based on the angular velocity
  1480. void SimulateAngles( float flFrameTime );
  1481. // Implement this if you use MOVETYPE_CUSTOM
  1482. virtual void PerformCustomPhysics( Vector *pNewPosition, Vector *pNewVelocity, QAngle *pNewAngles, QAngle *pNewAngVelocity );
  1483. // methods related to decal adding
  1484. void AddStudioDecal( const Ray_t& ray, int hitbox, int decalIndex, bool doTrace, trace_t& tr, int maxLODToDecal = ADDDECAL_TO_ALL_LODS, int nAdditionalDecalFlags = 0 );
  1485. void AddBrushModelDecal( const Ray_t& ray, const Vector& decalCenter, int decalIndex, bool doTrace, trace_t& tr, const Vector *saxis = NULL, int nAdditionalDecalFlags = 0 );
  1486. public:
  1487. void AddStudioMaterialDecal( const Ray_t& ray, IMaterial *pDecalMaterial, float flInputRadius, Vector vec_up );
  1488. const float GetUseLookAtAngle( void ) { return m_flUseLookAtAngle; }
  1489. private:
  1490. void ComputePackedOffsets( void );
  1491. int GetIntermediateDataSize( void );
  1492. void UnlinkChild( C_BaseEntity *pParent, C_BaseEntity *pChild );
  1493. void LinkChild( C_BaseEntity *pParent, C_BaseEntity *pChild );
  1494. void HierarchySetParent( C_BaseEntity *pNewParent );
  1495. void UnlinkFromHierarchy();
  1496. // Computes the water level + type
  1497. void UpdateWaterState();
  1498. // Checks a sweep without actually performing the move
  1499. void PhysicsCheckSweep( const Vector& vecAbsStart, const Vector &vecAbsDelta, trace_t *pTrace );
  1500. // FIXME: REMOVE!!!
  1501. void MoveToAimEnt( );
  1502. // Sets/Gets the next think based on context index
  1503. void SetNextThink( int nContextIndex, float thinkTime );
  1504. void SetLastThink( int nContextIndex, float thinkTime );
  1505. float GetNextThink( int nContextIndex ) const;
  1506. int GetNextThinkTick( int nContextIndex ) const;
  1507. void CleanUpAlphaProperty();
  1508. float m_flUseLookAtAngle;
  1509. #if !defined( NO_ENTITY_PREDICTION )
  1510. // It's still in the list for "fixup purposes" and simulation, but don't try to render it any more...
  1511. bool m_bDormantPredictable;
  1512. // So we can clean it up
  1513. int m_nIncomingPacketEntityBecameDormant;
  1514. #endif
  1515. // The spawn time of the entity
  1516. float m_flSpawnTime;
  1517. // Timestamp of message arrival
  1518. float m_flLastMessageTime;
  1519. // Model instance data..
  1520. ModelInstanceHandle_t m_ModelInstance;
  1521. // Shadow data
  1522. ClientShadowHandle_t m_ShadowHandle;
  1523. CBitVec< MAX_SPLITSCREEN_PLAYERS > m_ShadowBits; // Per-splitscreen user shadow visibility bits
  1524. ClientThinkHandle_t m_hThink;
  1525. unsigned char m_iParentAttachment; // 0 if we're relative to the parent's absorigin and absangles.
  1526. unsigned char m_iOldParentAttachment;
  1527. // Prediction system
  1528. bool m_bPredictable;
  1529. bool m_bRenderWithViewModels;
  1530. bool m_bDisableCachedRenderBounds;
  1531. protected:
  1532. // NOTE: This is a hack for portal2. There is a piece of networking code in OnDataChangedInPVS() that slams m_flSimulationTime
  1533. // this causes interpolation bugs on remote players in p2
  1534. bool m_bDisableSimulationFix;
  1535. // Fades
  1536. float m_fadeMinDist;
  1537. float m_fadeMaxDist;
  1538. float m_flFadeScale;
  1539. public:
  1540. void OnSimulationTimeChanging( float flPreviousSimulationTime, float flNextSimulationTime );
  1541. private:
  1542. int m_nSplitUserPlayerPredictionSlot;
  1543. // Hierarchy
  1544. CHandle<C_BaseEntity> m_pMoveParent;
  1545. CHandle<C_BaseEntity> m_pMoveChild;
  1546. CHandle<C_BaseEntity> m_pMovePeer;
  1547. CHandle<C_BaseEntity> m_pMovePrevPeer;
  1548. CHandle<C_BaseEntity> m_hOldMoveParent;
  1549. string_t m_ModelName;
  1550. CNetworkVarEmbedded( CCollisionProperty, m_Collision );
  1551. CNetworkVarEmbedded( CParticleProperty, m_Particles );
  1552. CClientAlphaProperty *m_pClientAlphaProperty;
  1553. // Physics state
  1554. float m_flElasticity;
  1555. float m_flShadowCastDistance;
  1556. EHANDLE m_ShadowDirUseOtherEntity;
  1557. float m_flGroundChangeTime;
  1558. Vector m_vecOldOrigin;
  1559. QAngle m_vecOldAngRotation;
  1560. CDiscontinuousInterpolatedVar< Vector > m_iv_vecOrigin;
  1561. CDiscontinuousInterpolatedVar< QAngle > m_iv_angRotation;
  1562. // Specifies the entity-to-world transform
  1563. matrix3x4_t m_rgflCoordinateFrame;
  1564. // used to cull collision tests
  1565. int m_CollisionGroup;
  1566. #if !defined( NO_ENTITY_PREDICTION )
  1567. // For storing prediction results and pristine network state
  1568. byte *m_pIntermediateData[ MULTIPLAYER_BACKUP ];
  1569. byte *m_pIntermediateData_FirstPredicted[ MULTIPLAYER_BACKUP + 1 ]; //we store just as much as m_pIntermediateData, but also hold onto the frame from our last received packet
  1570. byte *m_pOriginalData;
  1571. int m_nIntermediateDataCount;
  1572. static int s_nIncomingPacketCommandsAcknowledged; //only set to a valid value during entity network update processing
  1573. int m_nIntermediateData_FirstPredictedShiftMarker; //can't use predicted commands to optimize first predicted version of ShiftIntermediateDataForward(). Use this instead for its longer lifetime
  1574. bool m_bEverHadPredictionErrorsForThisCommand;
  1575. bool m_bIsPlayerSimulated;
  1576. #endif
  1577. CNetworkVar( bool, m_bSimulatedEveryTick );
  1578. CNetworkVar( bool, m_bAnimatedEveryTick );
  1579. CNetworkVar( bool, m_bAlternateSorting );
  1580. //CNetworkVar( bool, m_bSpotted );
  1581. bool m_bSpotted;
  1582. bool m_bSpottedBy[MAX_PLAYERS + 1]; // OBSELETE USED BY OLD DEMOS
  1583. CNetworkArray( uint32, m_bSpottedByMask, kNumSpottedByMask );
  1584. unsigned char m_nMinCPULevel;
  1585. unsigned char m_nMaxCPULevel;
  1586. unsigned char m_nMinGPULevel;
  1587. unsigned char m_nMaxGPULevel;
  1588. //Adrian
  1589. unsigned char m_iTextureFrameIndex;
  1590. // Bbox visualization
  1591. unsigned char m_fBBoxVisFlags;
  1592. bool m_bIsValidIKAttachment;
  1593. // The list that holds OnDataChanged events uses this to make sure we don't get multiple
  1594. // OnDataChanged calls in the same frame if the client receives multiple packets.
  1595. int m_DataChangeEventRef;
  1596. #if !defined( NO_ENTITY_PREDICTION )
  1597. // Player who is driving my simulation
  1598. CHandle< CBasePlayer > m_hPlayerSimulationOwner;
  1599. #endif
  1600. EHANDLE m_hEffectEntity;
  1601. // This is a random seed used by the networking code to allow client - side prediction code
  1602. // randon number generators to spit out the same random numbers on both sides for a particular
  1603. // usercmd input.
  1604. static int m_nPredictionRandomSeed;
  1605. static C_BasePlayer *m_pPredictionPlayer;
  1606. static bool s_bAbsQueriesValid;
  1607. static bool s_bAbsRecomputationEnabled;
  1608. static bool s_bInterpolate;
  1609. int m_fDataObjectTypes;
  1610. AimEntsListHandle_t m_AimEntsListHandle;
  1611. int m_nCreationTick;
  1612. public:
  1613. float m_fRenderingClipPlane[4]; //world space clip plane when drawing
  1614. bool m_bEnableRenderingClipPlane; //true to use the custom clip plane when drawing
  1615. float * GetRenderClipPlane( void ); // Rendering clip plane, should be 4 floats, return value of NULL indicates a disabled render clip plane
  1616. bool IsSpotted( void ) { return m_bSpotted && !IsDormant(); }
  1617. bool IsSpottedBy( int nPlayerIndex );
  1618. bool IsSpottedByFriends( int nPlayerIndex );
  1619. protected:
  1620. void SetIsSpottedBy( int nPlayerEntIndex );
  1621. void AddToEntityList( entity_list_ids_t listId );
  1622. void RemoveFromEntityList( entity_list_ids_t listId );
  1623. unsigned short m_ListEntry[NUM_ENTITY_LISTS]; // Entry into each g_EntityList (or InvalidIndex() if not in the list).
  1624. CThreadFastMutex m_CalcAbsolutePositionMutex;
  1625. CThreadFastMutex m_CalcAbsoluteVelocityMutex;
  1626. private:
  1627. bool m_bIsBlurred;
  1628. };
  1629. EXTERN_RECV_TABLE(DT_BaseEntity);
  1630. inline bool FClassnameIs( C_BaseEntity *pEntity, const char *szClassname )
  1631. {
  1632. Assert( pEntity );
  1633. return pEntity && !strcmp( pEntity->GetClassname(), szClassname );
  1634. }
  1635. #define SetThink( a ) ThinkSet( static_cast <void (CBaseEntity::*)(void)> (a), 0, NULL )
  1636. #define SetContextThink( a, b, context ) ThinkSet( static_cast <void (CBaseEntity::*)(void)> (a), (b), context )
  1637. #ifdef _DEBUG
  1638. #define SetTouch( a ) TouchSet( static_cast <void (C_BaseEntity::*)(C_BaseEntity *)> (a), #a )
  1639. #else
  1640. #define SetTouch( a ) m_pfnTouch = static_cast <void (C_BaseEntity::*)(C_BaseEntity *)> (a)
  1641. #endif
  1642. //-----------------------------------------------------------------------------
  1643. // An inline version the game code can use
  1644. //-----------------------------------------------------------------------------
  1645. inline CCollisionProperty *C_BaseEntity::CollisionProp()
  1646. {
  1647. return m_Collision.Get();
  1648. }
  1649. inline const CCollisionProperty *C_BaseEntity::CollisionProp() const
  1650. {
  1651. return m_Collision.Get();
  1652. }
  1653. inline CClientAlphaProperty *C_BaseEntity::AlphaProp()
  1654. {
  1655. return m_pClientAlphaProperty;
  1656. }
  1657. inline const CClientAlphaProperty *C_BaseEntity::AlphaProp() const
  1658. {
  1659. return m_pClientAlphaProperty;
  1660. }
  1661. //-----------------------------------------------------------------------------
  1662. // An inline version the game code can use
  1663. //-----------------------------------------------------------------------------
  1664. inline CParticleProperty *C_BaseEntity::ParticleProp()
  1665. {
  1666. return m_Particles.Get();
  1667. }
  1668. inline const CParticleProperty *C_BaseEntity::ParticleProp() const
  1669. {
  1670. return m_Particles.Get();
  1671. }
  1672. //-----------------------------------------------------------------------------
  1673. // Purpose: Returns whether this entity was created on the client.
  1674. //-----------------------------------------------------------------------------
  1675. inline bool C_BaseEntity::IsServerEntity( void ) const
  1676. {
  1677. return index != -1;
  1678. }
  1679. //-----------------------------------------------------------------------------
  1680. // Inline methods
  1681. //-----------------------------------------------------------------------------
  1682. inline matrix3x4_t &C_BaseEntity::EntityToWorldTransform()
  1683. {
  1684. Assert( s_bAbsQueriesValid );
  1685. CalcAbsolutePosition();
  1686. return m_rgflCoordinateFrame;
  1687. }
  1688. inline const matrix3x4_t &C_BaseEntity::EntityToWorldTransform() const
  1689. {
  1690. Assert( s_bAbsQueriesValid );
  1691. const_cast<C_BaseEntity*>(this)->CalcAbsolutePosition();
  1692. return m_rgflCoordinateFrame;
  1693. }
  1694. //-----------------------------------------------------------------------------
  1695. // Some helper methods that transform a point from entity space to world space + back
  1696. //-----------------------------------------------------------------------------
  1697. inline void C_BaseEntity::EntityToWorldSpace( const Vector &in, Vector *pOut ) const
  1698. {
  1699. if ( GetAbsAngles() == vec3_angle )
  1700. {
  1701. VectorAdd( in, GetAbsOrigin(), *pOut );
  1702. }
  1703. else
  1704. {
  1705. VectorTransform( in, EntityToWorldTransform(), *pOut );
  1706. }
  1707. }
  1708. inline void C_BaseEntity::WorldToEntitySpace( const Vector &in, Vector *pOut ) const
  1709. {
  1710. if ( GetAbsAngles() == vec3_angle )
  1711. {
  1712. VectorSubtract( in, GetAbsOrigin(), *pOut );
  1713. }
  1714. else
  1715. {
  1716. VectorITransform( in, EntityToWorldTransform(), *pOut );
  1717. }
  1718. }
  1719. inline const Vector &C_BaseEntity::GetAbsVelocity( ) const
  1720. {
  1721. Assert( s_bAbsQueriesValid );
  1722. const_cast<C_BaseEntity*>(this)->CalcAbsoluteVelocity();
  1723. return m_vecAbsVelocity;
  1724. }
  1725. inline C_BaseEntity *C_BaseEntity::Instance( IClientEntity *ent )
  1726. {
  1727. return ent ? ent->GetBaseEntity() : NULL;
  1728. }
  1729. // For debugging shared code
  1730. inline bool C_BaseEntity::IsServer( void )
  1731. {
  1732. return false;
  1733. }
  1734. inline bool C_BaseEntity::IsClient( void )
  1735. {
  1736. return true;
  1737. }
  1738. inline const char *C_BaseEntity::GetDLLType( void )
  1739. {
  1740. return "client";
  1741. }
  1742. //-----------------------------------------------------------------------------
  1743. // Methods relating to solid type + flags
  1744. //-----------------------------------------------------------------------------
  1745. inline void C_BaseEntity::SetSolidFlags( int nFlags )
  1746. {
  1747. CollisionProp()->SetSolidFlags( nFlags );
  1748. }
  1749. inline bool C_BaseEntity::IsSolidFlagSet( int flagMask ) const
  1750. {
  1751. return CollisionProp()->IsSolidFlagSet( flagMask );
  1752. }
  1753. inline int C_BaseEntity::GetSolidFlags( void ) const
  1754. {
  1755. return CollisionProp()->GetSolidFlags( );
  1756. }
  1757. inline void C_BaseEntity::AddSolidFlags( int nFlags )
  1758. {
  1759. CollisionProp()->AddSolidFlags( nFlags );
  1760. }
  1761. inline void C_BaseEntity::RemoveSolidFlags( int nFlags )
  1762. {
  1763. CollisionProp()->RemoveSolidFlags( nFlags );
  1764. }
  1765. inline bool C_BaseEntity::IsSolid() const
  1766. {
  1767. return CollisionProp()->IsSolid( );
  1768. }
  1769. inline void C_BaseEntity::SetSolid( SolidType_t val )
  1770. {
  1771. CollisionProp()->SetSolid( val );
  1772. }
  1773. inline SolidType_t C_BaseEntity::GetSolid( ) const
  1774. {
  1775. return CollisionProp()->GetSolid( );
  1776. }
  1777. inline void C_BaseEntity::SetCollisionBounds( const Vector& mins, const Vector &maxs )
  1778. {
  1779. CollisionProp()->SetCollisionBounds( mins, maxs );
  1780. }
  1781. //-----------------------------------------------------------------------------
  1782. // Methods relating to bounds
  1783. //-----------------------------------------------------------------------------
  1784. inline const Vector& C_BaseEntity::WorldAlignMins( ) const
  1785. {
  1786. Assert( !CollisionProp()->IsBoundsDefinedInEntitySpace() );
  1787. Assert( CollisionProp()->GetCollisionAngles() == vec3_angle );
  1788. return CollisionProp()->OBBMins();
  1789. }
  1790. inline const Vector& C_BaseEntity::WorldAlignMaxs( ) const
  1791. {
  1792. Assert( !CollisionProp()->IsBoundsDefinedInEntitySpace() );
  1793. Assert( CollisionProp()->GetCollisionAngles() == vec3_angle );
  1794. return CollisionProp()->OBBMaxs();
  1795. }
  1796. inline const Vector& C_BaseEntity::WorldAlignSize( ) const
  1797. {
  1798. Assert( !CollisionProp()->IsBoundsDefinedInEntitySpace() );
  1799. Assert( CollisionProp()->GetCollisionAngles() == vec3_angle );
  1800. return CollisionProp()->OBBSize();
  1801. }
  1802. inline float CBaseEntity::BoundingRadius() const
  1803. {
  1804. return CollisionProp()->BoundingRadius();
  1805. }
  1806. inline bool CBaseEntity::IsPointSized() const
  1807. {
  1808. return CollisionProp()->BoundingRadius() == 0.0f;
  1809. }
  1810. //-----------------------------------------------------------------------------
  1811. // Methods relating to traversing hierarchy
  1812. //-----------------------------------------------------------------------------
  1813. inline C_BaseEntity *C_BaseEntity::GetMoveParent( void ) const
  1814. {
  1815. return m_pMoveParent;
  1816. }
  1817. inline C_BaseEntity *C_BaseEntity::FirstMoveChild( void ) const
  1818. {
  1819. return m_pMoveChild;
  1820. }
  1821. inline C_BaseEntity *C_BaseEntity::NextMovePeer( void ) const
  1822. {
  1823. return m_pMovePeer;
  1824. }
  1825. //-----------------------------------------------------------------------------
  1826. // Velocity
  1827. //-----------------------------------------------------------------------------
  1828. inline const Vector& C_BaseEntity::GetLocalVelocity() const
  1829. {
  1830. return m_vecVelocity;
  1831. }
  1832. inline const QAngle& C_BaseEntity::GetLocalAngularVelocity( ) const
  1833. {
  1834. return m_vecAngVelocity;
  1835. }
  1836. inline const Vector& C_BaseEntity::GetBaseVelocity() const
  1837. {
  1838. return m_vecBaseVelocity;
  1839. }
  1840. inline void C_BaseEntity::SetBaseVelocity( const Vector& v )
  1841. {
  1842. m_vecBaseVelocity = v;
  1843. }
  1844. inline void C_BaseEntity::SetFriction( float flFriction )
  1845. {
  1846. m_flFriction = flFriction;
  1847. }
  1848. inline void C_BaseEntity::SetGravity( float flGravity )
  1849. {
  1850. m_flGravity = flGravity;
  1851. }
  1852. inline float C_BaseEntity::GetGravity( void ) const
  1853. {
  1854. return m_flGravity;
  1855. }
  1856. inline int C_BaseEntity::GetWaterLevel() const
  1857. {
  1858. return m_nWaterLevel;
  1859. }
  1860. inline void C_BaseEntity::SetWaterLevel( int nLevel )
  1861. {
  1862. m_nWaterLevel = nLevel;
  1863. }
  1864. inline float C_BaseEntity::GetElasticity( void ) const
  1865. {
  1866. return m_flElasticity;
  1867. }
  1868. inline const color24 CBaseEntity::GetRenderColor() const
  1869. {
  1870. color24 c = { m_clrRender->r, m_clrRender->g, m_clrRender->b };
  1871. return c;
  1872. }
  1873. inline byte C_BaseEntity::GetRenderColorR() const
  1874. {
  1875. return m_clrRender->r;
  1876. }
  1877. inline byte C_BaseEntity::GetRenderColorG() const
  1878. {
  1879. return m_clrRender->g;
  1880. }
  1881. inline byte C_BaseEntity::GetRenderColorB() const
  1882. {
  1883. return m_clrRender->b;
  1884. }
  1885. inline void C_BaseEntity::SetRenderColor( byte r, byte g, byte b )
  1886. {
  1887. m_clrRender.SetR( r );
  1888. m_clrRender.SetG( g );
  1889. m_clrRender.SetB( b );
  1890. }
  1891. inline void C_BaseEntity::SetRenderColorR( byte r )
  1892. {
  1893. m_clrRender.SetR( r );
  1894. }
  1895. inline void C_BaseEntity::SetRenderColorG( byte g )
  1896. {
  1897. m_clrRender.SetG( g );
  1898. }
  1899. inline void C_BaseEntity::SetRenderColorB( byte b )
  1900. {
  1901. m_clrRender.SetB( b );
  1902. }
  1903. inline RenderMode_t C_BaseEntity::GetRenderMode() const
  1904. {
  1905. return (RenderMode_t)m_nRenderMode;
  1906. }
  1907. inline RenderFx_t C_BaseEntity::GetRenderFX() const
  1908. {
  1909. return (RenderFx_t)m_nRenderFX;
  1910. }
  1911. inline void C_BaseEntity::SetCPULevels( int nMinCPULevel, int nMaxCPULevel )
  1912. {
  1913. m_nMinCPULevel = nMinCPULevel;
  1914. m_nMaxCPULevel = nMaxCPULevel;
  1915. }
  1916. inline void C_BaseEntity::SetGPULevels( int nMinGPULevel, int nMaxGPULevel )
  1917. {
  1918. m_nMinGPULevel = nMinGPULevel;
  1919. m_nMaxGPULevel = nMaxGPULevel;
  1920. }
  1921. inline int C_BaseEntity::GetMinCPULevel( ) const
  1922. {
  1923. return m_nMinCPULevel;
  1924. }
  1925. inline int C_BaseEntity::GetMaxCPULevel( ) const
  1926. {
  1927. return m_nMaxCPULevel;
  1928. }
  1929. inline int C_BaseEntity::GetMinGPULevel( ) const
  1930. {
  1931. return m_nMinGPULevel;
  1932. }
  1933. inline int C_BaseEntity::GetMaxGPULevel( ) const
  1934. {
  1935. return m_nMaxGPULevel;
  1936. }
  1937. //-----------------------------------------------------------------------------
  1938. // checks to see if the entity is marked for deletion
  1939. //-----------------------------------------------------------------------------
  1940. inline bool C_BaseEntity::IsMarkedForDeletion( void )
  1941. {
  1942. return (m_iEFlags & EFL_KILLME);
  1943. }
  1944. inline void C_BaseEntity::AddEFlags( int nEFlagMask )
  1945. {
  1946. m_iEFlags |= nEFlagMask;
  1947. }
  1948. inline void C_BaseEntity::RemoveEFlags( int nEFlagMask )
  1949. {
  1950. m_iEFlags &= ~nEFlagMask;
  1951. }
  1952. inline bool CBaseEntity::IsEFlagSet( int nEFlagMask ) const
  1953. {
  1954. return (m_iEFlags & nEFlagMask) != 0;
  1955. }
  1956. inline unsigned char CBaseEntity::GetParentAttachment() const
  1957. {
  1958. return m_iParentAttachment;
  1959. }
  1960. inline ClientRenderHandle_t CBaseEntity::GetRenderHandle() const
  1961. {
  1962. return m_hRender;
  1963. }
  1964. inline ClientRenderHandle_t& CBaseEntity::RenderHandle()
  1965. {
  1966. return m_hRender;
  1967. }
  1968. //-----------------------------------------------------------------------------
  1969. // Methods to cast away const
  1970. //-----------------------------------------------------------------------------
  1971. inline Vector C_BaseEntity::EyePosition( void ) const
  1972. {
  1973. return const_cast<C_BaseEntity*>(this)->EyePosition();
  1974. }
  1975. inline const QAngle &C_BaseEntity::EyeAngles( void ) const // Direction of eyes in world space
  1976. {
  1977. return const_cast<C_BaseEntity*>(this)->EyeAngles();
  1978. }
  1979. inline const QAngle &C_BaseEntity::LocalEyeAngles( void ) const // Direction of eyes
  1980. {
  1981. return const_cast<C_BaseEntity*>(this)->LocalEyeAngles();
  1982. }
  1983. inline Vector C_BaseEntity::EarPosition( void ) const // position of ears
  1984. {
  1985. return const_cast<C_BaseEntity*>(this)->EarPosition();
  1986. }
  1987. inline VarMapping_t* C_BaseEntity::GetVarMapping()
  1988. {
  1989. return &m_VarMap;
  1990. }
  1991. //-----------------------------------------------------------------------------
  1992. // Should we be interpolating?
  1993. //-----------------------------------------------------------------------------
  1994. inline bool C_BaseEntity::IsInterpolationEnabled()
  1995. {
  1996. return s_bInterpolate;
  1997. }
  1998. //-----------------------------------------------------------------------------
  1999. // Purpose:
  2000. // Input : handle -
  2001. // Output : inline void
  2002. //-----------------------------------------------------------------------------
  2003. inline void C_BaseEntity::SetToolHandle( HTOOLHANDLE handle )
  2004. {
  2005. #ifndef NO_TOOLFRAMEWORK
  2006. m_ToolHandle = handle;
  2007. #endif
  2008. }
  2009. //-----------------------------------------------------------------------------
  2010. // Purpose:
  2011. // Input : -
  2012. // Output : inline HTOOLHANDLE
  2013. //-----------------------------------------------------------------------------
  2014. inline HTOOLHANDLE C_BaseEntity::GetToolHandle() const
  2015. {
  2016. #ifndef NO_TOOLFRAMEWORK
  2017. return m_ToolHandle;
  2018. #else
  2019. return (HTOOLHANDLE)0;
  2020. #endif
  2021. }
  2022. //-----------------------------------------------------------------------------
  2023. //
  2024. //-----------------------------------------------------------------------------
  2025. inline bool C_BaseEntity::IsEnabledInToolView() const
  2026. {
  2027. #ifndef NO_TOOLFRAMEWORK
  2028. return m_bEnabledInToolView;
  2029. #else
  2030. return false;
  2031. #endif
  2032. }
  2033. //-----------------------------------------------------------------------------
  2034. // Client version of UTIL_Remove
  2035. //-----------------------------------------------------------------------------
  2036. inline void UTIL_Remove( C_BaseEntity *pEntity )
  2037. {
  2038. pEntity->Remove();
  2039. }
  2040. //-----------------------------------------------------------------------------
  2041. // Purpose:
  2042. // Input : -
  2043. // Output : inline bool
  2044. //-----------------------------------------------------------------------------
  2045. inline bool C_BaseEntity::ShouldRecordInTools() const
  2046. {
  2047. #ifndef NO_TOOLFRAMEWORK
  2048. return m_bRecordInTools;
  2049. #else
  2050. return true;
  2051. #endif
  2052. }
  2053. inline bool C_BaseEntity::IsVisible() const
  2054. {
  2055. if ( INVALID_CLIENT_RENDER_HANDLE == m_hRender )
  2056. return false;
  2057. ASSERT_LOCAL_PLAYER_RESOLVABLE();
  2058. return m_VisibilityBits.IsBitSet( GET_ACTIVE_SPLITSCREEN_SLOT() );
  2059. }
  2060. inline bool C_BaseEntity::IsVisibleToAnyPlayer() const
  2061. {
  2062. return !m_VisibilityBits.IsAllClear();
  2063. }
  2064. inline bool C_BaseEntity::HasSpawnFlags( int nFlags ) const
  2065. {
  2066. return (m_spawnflags & nFlags) != 0;
  2067. }
  2068. //-----------------------------------------------------------------------------
  2069. // Inline methods
  2070. //-----------------------------------------------------------------------------
  2071. inline const char *C_BaseEntity::GetEntityName()
  2072. {
  2073. return m_iName;
  2074. }
  2075. #ifdef PORTAL2
  2076. inline const char *C_BaseEntity::GetSignifierName()
  2077. {
  2078. return m_iSignifierName;
  2079. }
  2080. #endif // PORTAL2
  2081. class CAbsQueryScopeGuard
  2082. {
  2083. public:
  2084. explicit CAbsQueryScopeGuard( bool state )
  2085. {
  2086. m_bSavedState = C_BaseEntity::IsAbsQueriesValid();
  2087. C_BaseEntity::SetAbsQueriesValid( state );
  2088. }
  2089. ~CAbsQueryScopeGuard()
  2090. {
  2091. C_BaseEntity::SetAbsQueriesValid( m_bSavedState );
  2092. }
  2093. private:
  2094. bool m_bSavedState;
  2095. };
  2096. #define ABS_QUERY_GUARD( state ) CAbsQueryScopeGuard s_AbsQueryGuard( state );
  2097. C_BaseEntity *CreateEntityByName( const char *className );
  2098. #if !defined( NO_ENTITY_PREDICTION )
  2099. class CEntIndexLessFunc
  2100. {
  2101. public:
  2102. bool Less( C_BaseEntity * const & lhs, C_BaseEntity * const & rhs, void *pContext )
  2103. {
  2104. int e1 = lhs->entindex();
  2105. int e2 = rhs->entindex();
  2106. // if an entity has an invalid entity index, then put it at the end of the list
  2107. e1 = ( e1 == -1 ) ? MAX_EDICTS : e1;
  2108. e2 = ( e2 == -1 ) ? MAX_EDICTS : e2;
  2109. return e1 < e2;
  2110. }
  2111. };
  2112. //-----------------------------------------------------------------------------
  2113. // Purpose: Maintains a list of predicted or client created entities
  2114. //-----------------------------------------------------------------------------
  2115. class CPredictableList
  2116. {
  2117. public:
  2118. C_BaseEntity *GetPredictable( int slot );
  2119. int GetPredictableCount( void ) const;
  2120. protected:
  2121. void AddToPredictableList( C_BaseEntity *add );
  2122. void RemoveFromPredictablesList( C_BaseEntity *remove );
  2123. private:
  2124. CUtlSortVector< C_BaseEntity *, CEntIndexLessFunc > m_Predictables;
  2125. friend class C_BaseEntity;
  2126. };
  2127. //-----------------------------------------------------------------------------
  2128. // Purpose:
  2129. // Input : slot -
  2130. // Output : C_BaseEntity
  2131. //-----------------------------------------------------------------------------
  2132. FORCEINLINE C_BaseEntity *CPredictableList::GetPredictable( int slot )
  2133. {
  2134. return m_Predictables[ slot ];
  2135. }
  2136. //-----------------------------------------------------------------------------
  2137. // Purpose:
  2138. // Output : int
  2139. //-----------------------------------------------------------------------------
  2140. FORCEINLINE int CPredictableList::GetPredictableCount( void ) const
  2141. {
  2142. return m_Predictables.Count();
  2143. }
  2144. FORCEINLINE int C_BaseEntity::GetSplitUserPlayerPredictionSlot()
  2145. {
  2146. #if defined( USE_PREDICTABLEID )
  2147. Assert( m_bPredictable || m_pPredictionContext );
  2148. #else
  2149. Assert( m_bPredictable );
  2150. #endif
  2151. return m_nSplitUserPlayerPredictionSlot;
  2152. }
  2153. extern CPredictableList *GetPredictables( int nSlot );
  2154. // To temporarily muck with gpGlobals->curtime
  2155. class CCurTimeScopeGuard
  2156. {
  2157. public:
  2158. CCurTimeScopeGuard( float flNewCurTime, bool bOptionalCondition = true );
  2159. ~CCurTimeScopeGuard();
  2160. private:
  2161. float m_flSavedTime;
  2162. bool m_bActive;
  2163. };
  2164. #endif
  2165. #endif // C_BASEENTITY_H