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.

3886 lines
112 KiB

  1. //========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose: Base combat character with no AI
  4. //
  5. //=============================================================================//
  6. #include "cbase.h"
  7. #include "basecombatcharacter.h"
  8. #include "basecombatweapon.h"
  9. #include "animation.h"
  10. #include "gib.h"
  11. #include "entitylist.h"
  12. #include "gamerules.h"
  13. #include "ai_basenpc.h"
  14. #include "ai_squadslot.h"
  15. #include "ammodef.h"
  16. #include "ndebugoverlay.h"
  17. #include "player.h"
  18. #include "physics.h"
  19. #include "engine/IEngineSound.h"
  20. #include "tier1/strtools.h"
  21. #include "sendproxy.h"
  22. #include "EntityFlame.h"
  23. #include "CRagdollMagnet.h"
  24. #include "IEffects.h"
  25. #include "iservervehicle.h"
  26. #include "igamesystem.h"
  27. #include "globals.h"
  28. #include "physics_prop_ragdoll.h"
  29. #include "physics_impact_damage.h"
  30. #include "saverestore_utlvector.h"
  31. #include "eventqueue.h"
  32. #include "world.h"
  33. #include "globalstate.h"
  34. #include "items.h"
  35. #include "movevars_shared.h"
  36. #include "RagdollBoogie.h"
  37. #include "rumble_shared.h"
  38. #include "saverestoretypes.h"
  39. #include "nav_mesh.h"
  40. #ifdef HL2_DLL
  41. #include "weapon_physcannon.h"
  42. #include "hl2_gamerules.h"
  43. #endif
  44. #ifdef PORTAL
  45. #include "portal_util_shared.h"
  46. #include "portal_base2d_shared.h"
  47. #include "portal_shareddefs.h"
  48. #include "npc_portal_turret_floor.h"
  49. #endif
  50. // memdbgon must be the last include file in a .cpp file!!!
  51. #include "tier0/memdbgon.h"
  52. #if defined( HL2_DLL )
  53. extern int g_interactionBarnacleVictimReleased;
  54. #endif //HL2_DLL
  55. extern ConVar weapon_showproficiency;
  56. ConVar ai_show_hull_attacks( "ai_show_hull_attacks", "0" );
  57. ConVar ai_force_serverside_ragdoll( "ai_force_serverside_ragdoll", "0" );
  58. #ifndef _RETAIL
  59. ConVar ai_use_visibility_cache( "ai_use_visibility_cache", "1" );
  60. #define ShouldUseVisibilityCache() ai_use_visibility_cache.GetBool()
  61. #else
  62. #define ShouldUseVisibilityCache() true
  63. #endif
  64. BEGIN_DATADESC( CBaseCombatCharacter )
  65. DEFINE_UTLVECTOR( m_hTriggerFogList, FIELD_EHANDLE ),
  66. DEFINE_FIELD( m_hLastFogTrigger, FIELD_EHANDLE ),
  67. DEFINE_FIELD( m_flNextAttack, FIELD_TIME ),
  68. DEFINE_KEYFIELD( m_eHull, FIELD_INTEGER, "HullType" ),
  69. DEFINE_KEYFIELD( m_bloodColor, FIELD_INTEGER, "BloodColor" ),
  70. DEFINE_FIELD( m_iDamageCount, FIELD_INTEGER ),
  71. DEFINE_FIELD( m_flFieldOfView, FIELD_FLOAT ),
  72. DEFINE_FIELD( m_HackedGunPos, FIELD_VECTOR ),
  73. DEFINE_KEYFIELD( m_RelationshipString, FIELD_STRING, "Relationship" ),
  74. DEFINE_FIELD( m_LastHitGroup, FIELD_INTEGER ),
  75. DEFINE_FIELD( m_flDamageAccumulator, FIELD_FLOAT ),
  76. DEFINE_INPUT( m_impactEnergyScale, FIELD_FLOAT, "physdamagescale" ),
  77. DEFINE_FIELD( m_CurrentWeaponProficiency, FIELD_INTEGER),
  78. DEFINE_UTLVECTOR( m_Relationship, FIELD_EMBEDDED),
  79. DEFINE_FIELD( m_nFaction, FIELD_INTEGER ),
  80. DEFINE_AUTO_ARRAY( m_iAmmo, FIELD_INTEGER ),
  81. DEFINE_AUTO_ARRAY( m_hMyWeapons, FIELD_EHANDLE ),
  82. DEFINE_FIELD( m_hActiveWeapon, FIELD_EHANDLE ),
  83. DEFINE_FIELD( m_flTimeOfLastInjury, FIELD_FLOAT ),
  84. DEFINE_FIELD( m_nRelativeDirectionOfLastInjury, FIELD_INTEGER ),
  85. // DEFINE_FIELD( m_uiLastDamageTypeFlags, FIELD_INTEGER ),
  86. DEFINE_FIELD( m_bForceServerRagdoll, FIELD_BOOLEAN ),
  87. DEFINE_FIELD( m_bPreventWeaponPickup, FIELD_BOOLEAN ),
  88. DEFINE_INPUTFUNC( FIELD_VOID, "KilledNPC", InputKilledNPC ),
  89. END_DATADESC()
  90. BEGIN_SIMPLE_DATADESC( Relationship_t )
  91. DEFINE_FIELD( entity, FIELD_EHANDLE ),
  92. DEFINE_FIELD( classType, FIELD_INTEGER ),
  93. DEFINE_FIELD( faction, FIELD_INTEGER ),
  94. DEFINE_FIELD( disposition, FIELD_INTEGER ),
  95. DEFINE_FIELD( priority, FIELD_INTEGER ),
  96. END_DATADESC()
  97. //-----------------------------------------------------------------------------
  98. // Init static variables
  99. //-----------------------------------------------------------------------------
  100. int CBaseCombatCharacter::m_lastInteraction = 0;
  101. Relationship_t** CBaseCombatCharacter::m_DefaultRelationship = NULL;
  102. Relationship_t** CBaseCombatCharacter::m_FactionRelationship = NULL;
  103. CUtlVector< CUtlVector< EHANDLE> > CBaseCombatCharacter::m_aFactions;
  104. //-----------------------------------------------------------------------------
  105. // Purpose:
  106. //-----------------------------------------------------------------------------
  107. class CCleanupDefaultRelationShips : public CAutoGameSystem
  108. {
  109. public:
  110. CCleanupDefaultRelationShips( char const *name ) : CAutoGameSystem( name )
  111. {
  112. }
  113. virtual void Shutdown()
  114. {
  115. if ( CBaseCombatCharacter::m_DefaultRelationship != NULL )
  116. {
  117. int iNumClasses = GameRules() ? GameRules()->NumEntityClasses() : LAST_SHARED_ENTITY_CLASS;
  118. for ( int i=0; i<iNumClasses; ++i )
  119. {
  120. delete[] CBaseCombatCharacter::m_DefaultRelationship[ i ];
  121. }
  122. delete[] CBaseCombatCharacter::m_DefaultRelationship;
  123. CBaseCombatCharacter::m_DefaultRelationship = NULL;
  124. }
  125. if ( CBaseCombatCharacter::m_FactionRelationship != NULL )
  126. {
  127. for( int i = 0; i < CBaseCombatCharacter::m_aFactions.Count(); i++ )
  128. {
  129. delete[] CBaseCombatCharacter::m_FactionRelationship[ i ];
  130. CBaseCombatCharacter::m_aFactions[ i ].Purge();
  131. }
  132. CBaseCombatCharacter::m_aFactions.Purge();
  133. delete[] CBaseCombatCharacter::m_FactionRelationship;
  134. CBaseCombatCharacter::m_FactionRelationship = NULL;
  135. }
  136. }
  137. };
  138. static CCleanupDefaultRelationShips g_CleanupDefaultRelationships( "CCleanupDefaultRelationShips" );
  139. void *SendProxy_SendBaseCombatCharacterLocalDataTable( const SendProp *pProp, const void *pStruct, const void *pVarData, CSendProxyRecipients *pRecipients, int objectID )
  140. {
  141. // Only send to local player if this is a player
  142. pRecipients->ClearAllRecipients();
  143. CBaseCombatCharacter *pBCC = ( CBaseCombatCharacter * )pStruct;
  144. if ( pBCC != NULL)
  145. {
  146. if ( pBCC->IsPlayer() )
  147. {
  148. pRecipients->SetOnly( pBCC->entindex() - 1 );
  149. }
  150. else
  151. {
  152. // If it's a vehicle, send to "driver" (e.g., operator of tf2 manned guns)
  153. IServerVehicle *pVehicle = pBCC->GetServerVehicle();
  154. if ( pVehicle != NULL )
  155. {
  156. CBaseCombatCharacter *pDriver = pVehicle->GetPassenger();
  157. if ( pDriver != NULL )
  158. {
  159. pRecipients->SetOnly( pDriver->entindex() - 1 );
  160. }
  161. }
  162. }
  163. }
  164. return ( void * )pVarData;
  165. }
  166. REGISTER_SEND_PROXY_NON_MODIFIED_POINTER( SendProxy_SendBaseCombatCharacterLocalDataTable );
  167. void *SendProxy_SendBaseCombatCharacterNonLocalDataTable( const SendProp *pProp, const void *pStruct, const void *pVarData, CSendProxyRecipients *pRecipients, int objectID )
  168. {
  169. // Send to all players except itself
  170. CBaseCombatCharacter *pBCC = ( CBaseCombatCharacter * )pStruct;
  171. if ( pBCC != NULL)
  172. {
  173. if ( pBCC->IsPlayer() )
  174. {
  175. pRecipients->ExcludeOnly( pBCC->entindex() - 1 );
  176. }
  177. }
  178. return ( void * )pVarData;
  179. }
  180. REGISTER_SEND_PROXY_NON_MODIFIED_POINTER( SendProxy_SendBaseCombatCharacterNonLocalDataTable );
  181. // Only send active weapon index to local player
  182. BEGIN_SEND_TABLE_NOBASE( CBaseCombatCharacter, DT_BCCLocalPlayerExclusive )
  183. SendPropTime( SENDINFO( m_flNextAttack ) ),
  184. END_SEND_TABLE();
  185. BEGIN_SEND_TABLE_NOBASE( CBaseCombatCharacter, DT_BCCNonLocalPlayerExclusive )
  186. END_SEND_TABLE();
  187. //-----------------------------------------------------------------------------
  188. // This table encodes the CBaseCombatCharacter
  189. //-----------------------------------------------------------------------------
  190. IMPLEMENT_SERVERCLASS_ST(CBaseCombatCharacter, DT_BaseCombatCharacter)
  191. // Data that only gets sent to the local player.
  192. SendPropDataTable( "bcc_localdata", 0, &REFERENCE_SEND_TABLE(DT_BCCLocalPlayerExclusive), SendProxy_SendBaseCombatCharacterLocalDataTable ),
  193. SendPropDataTable( "bcc_nonlocaldata", 0, &REFERENCE_SEND_TABLE(DT_BCCNonLocalPlayerExclusive), SendProxy_SendBaseCombatCharacterNonLocalDataTable ),
  194. SendPropInt( SENDINFO( m_LastHitGroup ), 4, SPROP_UNSIGNED ),
  195. SendPropEHandle( SENDINFO( m_hActiveWeapon ) ),
  196. SendPropTime( SENDINFO( m_flTimeOfLastInjury ) ),
  197. SendPropInt( SENDINFO( m_nRelativeDirectionOfLastInjury ), 3, SPROP_UNSIGNED ),
  198. // SendPropInt( SENDINFO( m_uiLastDamageTypeFlags ), 0, SPROP_UNSIGNED ),
  199. SendPropArray3( SENDINFO_ARRAY3(m_hMyWeapons), SendPropEHandle( SENDINFO_ARRAY(m_hMyWeapons) ) ),
  200. END_SEND_TABLE()
  201. //-----------------------------------------------------------------------------
  202. // Interactions
  203. //-----------------------------------------------------------------------------
  204. void CBaseCombatCharacter::InitInteractionSystem()
  205. {
  206. // interaction ids continue to go up with every map load, otherwise you get
  207. // collisions if a future map has a different set of NPCs from a current map
  208. }
  209. //-----------------------------------------------------------------------------
  210. // Purpose: Return an interaction ID (so we have no collisions)
  211. //-----------------------------------------------------------------------------
  212. int CBaseCombatCharacter::GetInteractionID(void)
  213. {
  214. m_lastInteraction++;
  215. return (m_lastInteraction);
  216. }
  217. // ============================================================================
  218. bool CBaseCombatCharacter::HasHumanGibs( void )
  219. {
  220. #if defined( HL2_DLL )
  221. Class_T myClass = Classify();
  222. if ( myClass == CLASS_CITIZEN_PASSIVE ||
  223. myClass == CLASS_CITIZEN_REBEL ||
  224. myClass == CLASS_COMBINE ||
  225. myClass == CLASS_CONSCRIPT ||
  226. myClass == CLASS_METROPOLICE ||
  227. myClass == CLASS_PLAYER )
  228. return true;
  229. #elif defined( CSPORT_DLL )
  230. Class_T myClass = Classify();
  231. if ( myClass == CLASS_PLAYER )
  232. {
  233. return true;
  234. }
  235. #endif
  236. return false;
  237. }
  238. bool CBaseCombatCharacter::HasAlienGibs( void )
  239. {
  240. #if defined( HL2_DLL )
  241. Class_T myClass = Classify();
  242. if ( myClass == CLASS_BARNACLE ||
  243. myClass == CLASS_STALKER ||
  244. myClass == CLASS_ZOMBIE ||
  245. myClass == CLASS_VORTIGAUNT ||
  246. myClass == CLASS_HEADCRAB )
  247. {
  248. return true;
  249. }
  250. #endif
  251. return false;
  252. }
  253. void CBaseCombatCharacter::CorpseFade( void )
  254. {
  255. StopAnimation();
  256. SetAbsVelocity( vec3_origin );
  257. SetMoveType( MOVETYPE_NONE );
  258. SetLocalAngularVelocity( vec3_angle );
  259. m_flAnimTime = gpGlobals->curtime;
  260. AddEffects( EF_NOINTERP );
  261. SUB_StartFadeOut();
  262. }
  263. //-----------------------------------------------------------------------------
  264. // Visibility caching
  265. //-----------------------------------------------------------------------------
  266. struct VisibilityCacheEntry_t
  267. {
  268. CBaseEntity *pEntity1;
  269. CBaseEntity *pEntity2;
  270. EHANDLE pBlocker;
  271. float time;
  272. };
  273. class CVisibilityCacheEntryLess
  274. {
  275. public:
  276. CVisibilityCacheEntryLess( int ) {}
  277. bool operator!() const { return false; }
  278. bool operator()( const VisibilityCacheEntry_t &lhs, const VisibilityCacheEntry_t &rhs ) const
  279. {
  280. return ( memcmp( &lhs, &rhs, offsetof( VisibilityCacheEntry_t, pBlocker ) ) < 0 );
  281. }
  282. };
  283. static CUtlRBTree<VisibilityCacheEntry_t, unsigned short, CVisibilityCacheEntryLess> g_VisibilityCache;
  284. const float VIS_CACHE_ENTRY_LIFE = .090;
  285. bool CBaseCombatCharacter::FVisible( CBaseEntity *pEntity, int traceMask, CBaseEntity **ppBlocker )
  286. {
  287. VPROF( "CBaseCombatCharacter::FVisible" );
  288. if ( traceMask != MASK_BLOCKLOS || !ShouldUseVisibilityCache() || pEntity == this
  289. #if defined(HL2_DLL)
  290. || Classify() == CLASS_BULLSEYE || pEntity->Classify() == CLASS_BULLSEYE
  291. #endif
  292. )
  293. {
  294. return BaseClass::FVisible( pEntity, traceMask, ppBlocker );
  295. }
  296. VisibilityCacheEntry_t cacheEntry;
  297. if ( this < pEntity )
  298. {
  299. cacheEntry.pEntity1 = this;
  300. cacheEntry.pEntity2 = pEntity;
  301. }
  302. else
  303. {
  304. cacheEntry.pEntity1 = pEntity;
  305. cacheEntry.pEntity2 = this;
  306. }
  307. int iCache = g_VisibilityCache.Find( cacheEntry );
  308. if ( iCache != g_VisibilityCache.InvalidIndex() )
  309. {
  310. if ( gpGlobals->curtime - g_VisibilityCache[iCache].time < VIS_CACHE_ENTRY_LIFE )
  311. {
  312. bool bBlockerValid = g_VisibilityCache[iCache].pBlocker.IsValid();
  313. if ( bBlockerValid )
  314. {
  315. if ( ppBlocker )
  316. {
  317. *ppBlocker = g_VisibilityCache[iCache].pBlocker;
  318. if ( !*ppBlocker )
  319. {
  320. *ppBlocker = GetWorldEntity();
  321. }
  322. }
  323. }
  324. else
  325. {
  326. if ( ppBlocker )
  327. {
  328. *ppBlocker = NULL;
  329. }
  330. }
  331. return !bBlockerValid;
  332. }
  333. }
  334. else
  335. {
  336. if ( g_VisibilityCache.Count() != g_VisibilityCache.InvalidIndex() )
  337. {
  338. iCache = g_VisibilityCache.Insert( cacheEntry );
  339. }
  340. else
  341. {
  342. return BaseClass::FVisible( pEntity, traceMask, ppBlocker );
  343. }
  344. }
  345. CBaseEntity *pBlocker = NULL;
  346. if ( ppBlocker == NULL )
  347. {
  348. ppBlocker = &pBlocker;
  349. }
  350. bool bResult = BaseClass::FVisible( pEntity, traceMask, ppBlocker );
  351. if ( !bResult )
  352. {
  353. g_VisibilityCache[iCache].pBlocker = *ppBlocker;
  354. }
  355. else
  356. {
  357. g_VisibilityCache[iCache].pBlocker = NULL;
  358. }
  359. g_VisibilityCache[iCache].time = gpGlobals->curtime;
  360. return bResult;
  361. }
  362. void CBaseCombatCharacter::ResetVisibilityCache( CBaseCombatCharacter *pBCC )
  363. {
  364. VPROF( "CBaseCombatCharacter::ResetVisibilityCache" );
  365. if ( !pBCC )
  366. {
  367. g_VisibilityCache.RemoveAll();
  368. return;
  369. }
  370. int i = g_VisibilityCache.FirstInorder();
  371. CUtlVector<unsigned short> removals;
  372. while ( i != g_VisibilityCache.InvalidIndex() )
  373. {
  374. if ( g_VisibilityCache[i].pEntity1 == pBCC || g_VisibilityCache[i].pEntity2 == pBCC )
  375. {
  376. removals.AddToTail( i );
  377. }
  378. i = g_VisibilityCache.NextInorder( i );
  379. }
  380. for ( i = 0; i < removals.Count(); i++ )
  381. {
  382. g_VisibilityCache.RemoveAt( removals[i] );
  383. }
  384. }
  385. #ifdef PORTAL
  386. bool CBaseCombatCharacter::FVisibleThroughPortal( const CPortal_Base2D *pPortal, CBaseEntity *pEntity, int traceMask, CBaseEntity **ppBlocker )
  387. {
  388. VPROF( "CBaseCombatCharacter::FVisible" );
  389. if ( pPortal && IsPlayerNearTargetPortal( pPortal->m_hLinkedPortal.Get() ) == false )
  390. return false;
  391. if ( pEntity->GetFlags() & FL_NOTARGET )
  392. return false;
  393. Vector vecLookerOrigin = EyePosition();//look through the caller's 'eyes'
  394. Vector vecTargetOrigin = pEntity->EyePosition();
  395. // Use the custom LOS trace filter
  396. CTraceFilterLOS traceFilter( this, COLLISION_GROUP_NONE, pEntity );
  397. Vector vecTranslatedTargetOrigin;
  398. UTIL_Portal_PointTransform( pPortal->m_hLinkedPortal->MatrixThisToLinked(), vecTargetOrigin, vecTranslatedTargetOrigin );
  399. Ray_t ray;
  400. ray.Init( vecLookerOrigin, vecTranslatedTargetOrigin );
  401. trace_t tr;
  402. // If we're doing an opaque search, include NPCs.
  403. if ( traceMask == MASK_BLOCKLOS )
  404. {
  405. traceMask = MASK_BLOCKLOS_AND_NPCS;
  406. }
  407. UTIL_Portal_TraceRay_Bullets( pPortal, ray, traceMask, &traceFilter, &tr );
  408. if (tr.fraction != 1.0 || tr.startsolid )
  409. {
  410. // If we hit the entity we're looking for, it's visible
  411. if ( tr.m_pEnt == pEntity )
  412. return true;
  413. // Got line of sight on the vehicle the player is driving!
  414. if ( pEntity && pEntity->IsPlayer() )
  415. {
  416. CBasePlayer *pPlayer = assert_cast<CBasePlayer*>( pEntity );
  417. if ( tr.m_pEnt == pPlayer->GetVehicleEntity() )
  418. return true;
  419. }
  420. if (ppBlocker)
  421. {
  422. *ppBlocker = tr.m_pEnt;
  423. }
  424. return false;// Line of sight is not established
  425. }
  426. return true;// line of sight is valid.
  427. }
  428. #endif
  429. //-----------------------------------------------------------------------------
  430. //=========================================================
  431. // FInViewCone - returns true is the passed ent is in
  432. // the caller's forward view cone. The dot product is performed
  433. // in 2d, making the view cone infinitely tall.
  434. //=========================================================
  435. bool CBaseCombatCharacter::FInViewCone( CBaseEntity *pEntity )
  436. {
  437. return FInViewCone( pEntity->WorldSpaceCenter() );
  438. }
  439. //=========================================================
  440. // FInViewCone - returns true is the passed Vector is in
  441. // the caller's forward view cone. The dot product is performed
  442. // in 2d, making the view cone infinitely tall.
  443. //=========================================================
  444. bool CBaseCombatCharacter::FInViewCone( const Vector &vecSpot )
  445. {
  446. Vector eyepos = EyePosition();
  447. // do this in 2D
  448. eyepos.z = vecSpot.z;
  449. return PointWithinViewAngle( eyepos, vecSpot, EyeDirection2D(), m_flFieldOfView );
  450. }
  451. #ifdef PORTAL
  452. //=========================================================
  453. // FInViewCone - returns true is the passed ent is in
  454. // the caller's forward view cone. The dot product is performed
  455. // in 2d, making the view cone infinitely tall.
  456. //=========================================================
  457. CPortal_Base2D* CBaseCombatCharacter::FInViewConeThroughPortal( CBaseEntity *pEntity )
  458. {
  459. return FInViewConeThroughPortal( pEntity->WorldSpaceCenter() );
  460. }
  461. //=========================================================
  462. // FInViewCone - returns true is the passed Vector is in
  463. // the caller's forward view cone. The dot product is performed
  464. // in 2d, making the view cone infinitely tall.
  465. //=========================================================
  466. CPortal_Base2D* CBaseCombatCharacter::FInViewConeThroughPortal( const Vector &vecSpot )
  467. {
  468. int iPortalCount = CPortal_Base2D_Shared::AllPortals.Count();
  469. if( iPortalCount == 0 )
  470. return NULL;
  471. const Vector ptEyePosition = EyePosition();
  472. float fDistToBeat = 1e20; //arbitrarily high number
  473. CPortal_Base2D *pBestPortal = NULL;
  474. CPortal_Base2D **pPortals = CPortal_Base2D_Shared::AllPortals.Base();
  475. // Check through both portals
  476. for ( int iPortal = 0; iPortal < iPortalCount; ++iPortal )
  477. {
  478. CPortal_Base2D *pPortal = pPortals[iPortal];
  479. // Check if this portal is active, linked, and in the view cone
  480. if( pPortal->IsActivedAndLinked() && FInViewCone( pPortal ) )
  481. {
  482. // The facing direction is the eye to the portal to set up a proper FOV through the relatively small portal hole
  483. Vector facingDir = pPortal->GetAbsOrigin() - ptEyePosition;
  484. // If the portal isn't facing the eye, bail
  485. if ( facingDir.Dot( pPortal->m_plane_Origin.normal ) > 0.0f )
  486. continue;
  487. // If the point is behind the linked portal, bail
  488. if ( ( vecSpot - pPortal->m_hLinkedPortal->GetAbsOrigin() ).Dot( pPortal->m_hLinkedPortal->m_plane_Origin.normal ) < 0.0f )
  489. continue;
  490. // Remove height from the equation
  491. facingDir.z = 0.0f;
  492. float fPortalDist = VectorNormalize( facingDir );
  493. // Translate the target spot across the portal
  494. Vector vTranslatedVecSpot;
  495. UTIL_Portal_PointTransform( pPortal->m_hLinkedPortal->MatrixThisToLinked(), vecSpot, vTranslatedVecSpot );
  496. // do this in 2D
  497. Vector los = ( vTranslatedVecSpot - ptEyePosition );
  498. los.z = 0.0f;
  499. float fSpotDist = VectorNormalize( los );
  500. if( fSpotDist > fDistToBeat )
  501. continue; //no point in going further, we already have a better portal
  502. // If the target point is closer than the portal (banana juice), bail
  503. // HACK: Extra 32 is a fix for the player who's origin can be on one side of a portal while his center mirrored across is closer than the portal.
  504. if ( fPortalDist > fSpotDist + 32.0f )
  505. continue;
  506. // Get the worst case FOV from the portal's corners
  507. float fFOVThroughPortal = 1.0f;
  508. for ( int i = 0; i < 4; ++i )
  509. {
  510. //Vector vPortalCorner = pPortal->GetAbsOrigin() + vPortalRight * PORTAL_HALF_WIDTH * ( ( i / 2 == 0 ) ? ( 1.0f ) : ( -1.0f ) ) +
  511. // vPortalUp * PORTAL_HALF_HEIGHT * ( ( i % 2 == 0 ) ? ( 1.0f ) : ( -1.0f ) );
  512. Vector vEyeToCorner = pPortal->m_vPortalCorners[i] - ptEyePosition;
  513. vEyeToCorner.z = 0.0f;
  514. VectorNormalize( vEyeToCorner );
  515. float flCornerDot = DotProduct( vEyeToCorner, facingDir );
  516. if ( flCornerDot < fFOVThroughPortal )
  517. fFOVThroughPortal = flCornerDot;
  518. }
  519. float flDot = DotProduct( los, facingDir );
  520. // Use the tougher FOV of either the standard FOV or FOV clipped to the portal hole
  521. if ( flDot > MAX( fFOVThroughPortal, m_flFieldOfView ) )
  522. {
  523. float fActualDist = ptEyePosition.DistToSqr( vTranslatedVecSpot );
  524. if( fActualDist < fDistToBeat )
  525. {
  526. fDistToBeat = fActualDist;
  527. pBestPortal = pPortal;
  528. }
  529. }
  530. }
  531. }
  532. return pBestPortal;
  533. }
  534. #endif
  535. //=========================================================
  536. // FInAimCone - returns true is the passed ent is in
  537. // the caller's forward aim cone. The dot product is performed
  538. // in 2d, making the aim cone infinitely tall.
  539. //=========================================================
  540. bool CBaseCombatCharacter::FInAimCone( CBaseEntity *pEntity )
  541. {
  542. return FInAimCone( pEntity->BodyTarget( EyePosition() ) );
  543. }
  544. //=========================================================
  545. // FInAimCone - returns true is the passed Vector is in
  546. // the caller's forward aim cone. The dot product is performed
  547. // in 2d, making the view cone infinitely tall. By default, the
  548. // callers aim cone is assumed to be very narrow
  549. //=========================================================
  550. bool CBaseCombatCharacter::FInAimCone( const Vector &vecSpot )
  551. {
  552. Vector los = ( vecSpot - GetAbsOrigin() );
  553. // do this in 2D
  554. los.z = 0;
  555. VectorNormalize( los );
  556. Vector facingDir = BodyDirection2D( );
  557. float flDot = DotProduct( los, facingDir );
  558. if ( flDot > 0.994 )//!!!BUGBUG - magic number same as FacingIdeal(), what is this?
  559. return true;
  560. return false;
  561. }
  562. //-----------------------------------------------------------------------------
  563. // Purpose: This is a generic function (to be implemented by sub-classes) to
  564. // handle specific interactions between different types of characters
  565. // (For example the barnacle grabbing an NPC)
  566. // Input : The type of interaction, extra info pointer, and who started it
  567. // Output : true - if sub-class has a response for the interaction
  568. // false - if sub-class has no response
  569. //-----------------------------------------------------------------------------
  570. bool CBaseCombatCharacter::HandleInteraction( int interactionType, void *data, CBaseCombatCharacter* sourceEnt )
  571. {
  572. #if defined( HL2_DLL )
  573. if ( interactionType == g_interactionBarnacleVictimReleased )
  574. {
  575. // For now, throw away the NPC and leave the ragdoll.
  576. UTIL_Remove( this );
  577. return true;
  578. }
  579. #endif // HL2_DLL
  580. return false;
  581. }
  582. //-----------------------------------------------------------------------------
  583. // Purpose: Constructor : Initialize some fields
  584. //-----------------------------------------------------------------------------
  585. CBaseCombatCharacter::CBaseCombatCharacter( void )
  586. {
  587. #ifdef _DEBUG
  588. // necessary since in debug, we initialize vectors to NAN for debugging
  589. m_HackedGunPos.Init();
  590. #endif
  591. // Zero the damage accumulator.
  592. m_flDamageAccumulator = 0.0f;
  593. // Init weapon and Ammo data
  594. m_hActiveWeapon = NULL;
  595. m_uiLastDamageTypeFlags = 0;
  596. // Init faction
  597. m_nFaction = FACTION_NONE;
  598. // reset all ammo values to 0
  599. RemoveAllAmmo();
  600. // not alive yet
  601. m_aliveTimer.Invalidate();
  602. m_hasBeenInjured = 0;
  603. for( int t=0; t<MAX_DAMAGE_TEAMS; ++t )
  604. {
  605. m_damageHistory[t].team = TEAM_INVALID;
  606. }
  607. m_flTimeOfLastInjury = 0.0f;
  608. // not standing on a nav area yet
  609. m_lastNavArea = NULL;
  610. m_registeredNavTeam = TEAM_INVALID;
  611. m_LastHitGroup = HITGROUP_GENERIC;
  612. for (int i = 0; i < MAX_WEAPONS; i++)
  613. {
  614. m_hMyWeapons.Set( i, INVALID_EHANDLE );
  615. }
  616. V_memset( m_weaponIDToIndex, 0, sizeof(m_weaponIDToIndex) );
  617. // Default so that spawned entities have this set
  618. m_impactEnergyScale = 1.0f;
  619. m_bForceServerRagdoll = ai_force_serverside_ragdoll.GetBool();
  620. }
  621. //------------------------------------------------------------------------------
  622. // Purpose : Destructor
  623. // Input :
  624. // Output :
  625. //------------------------------------------------------------------------------
  626. CBaseCombatCharacter::~CBaseCombatCharacter( void )
  627. {
  628. if ( ( m_nFaction != FACTION_NONE ) && ( m_aFactions.Count() != 0 ) )
  629. {
  630. m_aFactions[ m_nFaction ].FindAndFastRemove( this );
  631. }
  632. ResetVisibilityCache( this );
  633. ClearLastKnownArea();
  634. }
  635. //-----------------------------------------------------------------------------
  636. // Purpose: Put the combat character into the environment
  637. //-----------------------------------------------------------------------------
  638. void CBaseCombatCharacter::Spawn( void )
  639. {
  640. BaseClass::Spawn();
  641. SetBlocksLOS( false );
  642. m_aliveTimer.Start();
  643. m_hasBeenInjured = 0;
  644. for( int t=0; t<MAX_DAMAGE_TEAMS; ++t )
  645. {
  646. m_damageHistory[t].team = TEAM_INVALID;
  647. }
  648. m_flTimeOfLastInjury = 0.0f;
  649. m_LastHitGroup = HITGROUP_GENERIC;
  650. // not standing on a nav area yet
  651. ClearLastKnownArea();
  652. }
  653. //-----------------------------------------------------------------------------
  654. // Purpose:
  655. //-----------------------------------------------------------------------------
  656. void CBaseCombatCharacter::Precache()
  657. {
  658. VPROF( "CBaseCombatCharacter::Precache" );
  659. BaseClass::Precache();
  660. PrecacheScriptSound( "BaseCombatCharacter.CorpseGib" );
  661. PrecacheScriptSound( "BaseCombatCharacter.StopWeaponSounds" );
  662. PrecacheScriptSound( "BaseCombatCharacter.AmmoPickup" );
  663. for ( int i = m_Relationship.Count() - 1; i >= 0 ; i--)
  664. {
  665. if ( !m_Relationship[i].entity && m_Relationship[i].classType == CLASS_NONE )
  666. {
  667. DevMsg( 2, "Removing relationship for lost entity\n" );
  668. m_Relationship.FastRemove( i );
  669. }
  670. }
  671. }
  672. //-----------------------------------------------------------------------------
  673. // Purpose:
  674. //-----------------------------------------------------------------------------
  675. int CBaseCombatCharacter::Restore( IRestore &restore )
  676. {
  677. int status = BaseClass::Restore(restore);
  678. if ( !status )
  679. return 0;
  680. // restore faction information
  681. ChangeFaction( m_nFaction );
  682. if ( gpGlobals->eLoadType == MapLoad_Transition )
  683. {
  684. DevMsg( 2, "%s (%s) removing class relationships due to level transition\n", STRING( GetEntityName() ), GetClassname() );
  685. for ( int i = m_Relationship.Count() - 1; i >= 0; --i )
  686. {
  687. if ( !m_Relationship[i].entity && m_Relationship[i].classType != CLASS_NONE )
  688. {
  689. m_Relationship.FastRemove( i );
  690. }
  691. }
  692. }
  693. return status;
  694. }
  695. //-----------------------------------------------------------------------------
  696. // Purpose:
  697. //-----------------------------------------------------------------------------
  698. void CBaseCombatCharacter::UpdateOnRemove( void )
  699. {
  700. int i;
  701. // Make sure any weapons I didn't drop get removed.
  702. for (i=0;i<MAX_WEAPONS;i++)
  703. {
  704. if (m_hMyWeapons[i])
  705. {
  706. UTIL_Remove( m_hMyWeapons[i] );
  707. }
  708. }
  709. V_memset( m_weaponIDToIndex, 0, sizeof(m_weaponIDToIndex) );
  710. // tell owner ( if any ) that we're dead.This is mostly for NPCMaker functionality.
  711. CBaseEntity *pOwner = GetOwnerEntity();
  712. if ( pOwner )
  713. {
  714. pOwner->DeathNotice( this );
  715. SetOwnerEntity( NULL );
  716. }
  717. RemoveAllWearables();
  718. // Chain at end to mimic destructor unwind order
  719. BaseClass::UpdateOnRemove();
  720. }
  721. //=========================================================
  722. // CorpseGib - create some gore and get rid of a character's
  723. // model.
  724. //=========================================================
  725. bool CBaseCombatCharacter::CorpseGib( const CTakeDamageInfo &info )
  726. {
  727. trace_t tr;
  728. bool gibbed = false;
  729. EmitSound( "BaseCombatCharacter.CorpseGib" );
  730. // only humans throw skulls !!!UNDONE - eventually NPCs will have their own sets of gibs
  731. if ( HasHumanGibs() )
  732. {
  733. CGib::SpawnHeadGib( this );
  734. CGib::SpawnRandomGibs( this, 4, GIB_HUMAN ); // throw some human gibs.
  735. gibbed = true;
  736. }
  737. else if ( HasAlienGibs() )
  738. {
  739. CGib::SpawnRandomGibs( this, 4, GIB_ALIEN ); // Throw alien gibs
  740. gibbed = true;
  741. }
  742. return gibbed;
  743. }
  744. //=========================================================
  745. // GetDeathActivity - determines the best type of death
  746. // anim to play.
  747. //=========================================================
  748. Activity CBaseCombatCharacter::GetDeathActivity ( void )
  749. {
  750. Activity deathActivity;
  751. bool fTriedDirection;
  752. float flDot;
  753. trace_t tr;
  754. Vector vecSrc;
  755. if (IsPlayer())
  756. {
  757. // die in an interesting way
  758. switch( random->RandomInt(0,7) )
  759. {
  760. case 0: return ACT_DIESIMPLE;
  761. case 1: return ACT_DIEBACKWARD;
  762. case 2: return ACT_DIEFORWARD;
  763. case 3: return ACT_DIEVIOLENT;
  764. case 4: return ACT_DIE_HEADSHOT;
  765. case 5: return ACT_DIE_CHESTSHOT;
  766. case 6: return ACT_DIE_GUTSHOT;
  767. case 7: return ACT_DIE_BACKSHOT;
  768. }
  769. }
  770. vecSrc = WorldSpaceCenter();
  771. fTriedDirection = false;
  772. deathActivity = ACT_DIESIMPLE;// in case we can't find any special deaths to do.
  773. Vector forward;
  774. AngleVectors( GetLocalAngles(), &forward );
  775. flDot = -DotProduct( forward, g_vecAttackDir );
  776. switch ( m_LastHitGroup )
  777. {
  778. // try to pick a region-specific death.
  779. case HITGROUP_HEAD:
  780. deathActivity = ACT_DIE_HEADSHOT;
  781. break;
  782. case HITGROUP_STOMACH:
  783. deathActivity = ACT_DIE_GUTSHOT;
  784. break;
  785. case HITGROUP_GENERIC:
  786. // try to pick a death based on attack direction
  787. fTriedDirection = true;
  788. if ( flDot > 0.3 )
  789. {
  790. deathActivity = ACT_DIEFORWARD;
  791. }
  792. else if ( flDot <= -0.3 )
  793. {
  794. deathActivity = ACT_DIEBACKWARD;
  795. }
  796. break;
  797. default:
  798. // try to pick a death based on attack direction
  799. fTriedDirection = true;
  800. if ( flDot > 0.3 )
  801. {
  802. deathActivity = ACT_DIEFORWARD;
  803. }
  804. else if ( flDot <= -0.3 )
  805. {
  806. deathActivity = ACT_DIEBACKWARD;
  807. }
  808. break;
  809. }
  810. // can we perform the prescribed death?
  811. if ( SelectWeightedSequence ( deathActivity ) == ACTIVITY_NOT_AVAILABLE )
  812. {
  813. // no! did we fail to perform a directional death?
  814. if ( fTriedDirection )
  815. {
  816. // if yes, we're out of options. Go simple.
  817. deathActivity = ACT_DIESIMPLE;
  818. }
  819. else
  820. {
  821. // cannot perform the ideal region-specific death, so try a direction.
  822. if ( flDot > 0.3 )
  823. {
  824. deathActivity = ACT_DIEFORWARD;
  825. }
  826. else if ( flDot <= -0.3 )
  827. {
  828. deathActivity = ACT_DIEBACKWARD;
  829. }
  830. }
  831. }
  832. if ( SelectWeightedSequence ( deathActivity ) == ACTIVITY_NOT_AVAILABLE )
  833. {
  834. // if we're still invalid, simple is our only option.
  835. deathActivity = ACT_DIESIMPLE;
  836. if ( SelectWeightedSequence ( deathActivity ) == ACTIVITY_NOT_AVAILABLE )
  837. {
  838. Msg( "ERROR! %s missing ACT_DIESIMPLE\n", STRING(GetModelName()) );
  839. }
  840. }
  841. if ( deathActivity == ACT_DIEFORWARD )
  842. {
  843. // make sure there's room to fall forward
  844. UTIL_TraceHull ( vecSrc, vecSrc + forward * 64, Vector(-16,-16,-18),
  845. Vector(16,16,18), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
  846. if ( tr.fraction != 1.0 )
  847. {
  848. deathActivity = ACT_DIESIMPLE;
  849. }
  850. }
  851. if ( deathActivity == ACT_DIEBACKWARD )
  852. {
  853. // make sure there's room to fall backward
  854. UTIL_TraceHull ( vecSrc, vecSrc - forward * 64, Vector(-16,-16,-18),
  855. Vector(16,16,18), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
  856. if ( tr.fraction != 1.0 )
  857. {
  858. deathActivity = ACT_DIESIMPLE;
  859. }
  860. }
  861. return deathActivity;
  862. }
  863. // UNDONE: Should these operate on a list of weapon/items
  864. Activity CBaseCombatCharacter::Weapon_TranslateActivity( Activity baseAct, bool *pRequired )
  865. {
  866. Activity translated = baseAct;
  867. if ( m_hActiveWeapon )
  868. {
  869. translated = m_hActiveWeapon->ActivityOverride( baseAct, pRequired );
  870. }
  871. else if (pRequired)
  872. {
  873. *pRequired = false;
  874. }
  875. return translated;
  876. }
  877. //-----------------------------------------------------------------------------
  878. // Purpose: NPCs should override this function to translate activities
  879. // such as ACT_WALK, etc.
  880. // Input :
  881. // Output :
  882. //-----------------------------------------------------------------------------
  883. Activity CBaseCombatCharacter::NPC_TranslateActivity( Activity baseAct )
  884. {
  885. return baseAct;
  886. }
  887. void CBaseCombatCharacter::Weapon_SetActivity( Activity newActivity, float duration )
  888. {
  889. if ( m_hActiveWeapon )
  890. {
  891. m_hActiveWeapon->SetActivity( newActivity, duration );
  892. }
  893. }
  894. void CBaseCombatCharacter::Weapon_FrameUpdate( void )
  895. {
  896. if ( m_hActiveWeapon )
  897. {
  898. m_hActiveWeapon->Operator_FrameUpdate( this );
  899. }
  900. }
  901. //------------------------------------------------------------------------------
  902. // Purpose : expects a length to trace, amount
  903. // of damage to do, and damage type. Returns a pointer to
  904. // the damaged entity in case the NPC wishes to do
  905. // other stuff to the victim (punchangle, etc)
  906. //
  907. // Used for many contact-range melee attacks. Bites, claws, etc.
  908. // Input :
  909. // Output :
  910. //------------------------------------------------------------------------------
  911. CBaseEntity *CBaseCombatCharacter::CheckTraceHullAttack( float flDist, const Vector &mins, const Vector &maxs, float flDamage, int iDmgType, float forceScale, bool bDamageAnyNPC )
  912. {
  913. // If only a length is given assume we want to trace in our facing direction
  914. Vector forward;
  915. AngleVectors( GetAbsAngles(), &forward );
  916. Vector vStart = GetAbsOrigin();
  917. // The ideal place to start the trace is in the center of the attacker's bounding box.
  918. // however, we need to make sure there's enough clearance. Some of the smaller monsters aren't
  919. // as big as the hull we try to trace with. (SJB)
  920. float flVerticalOffset = WorldAlignSize().z * 0.5;
  921. if( flVerticalOffset < maxs.z )
  922. {
  923. // There isn't enough room to trace this hull, it's going to drag the ground.
  924. // so make the vertical offset just enough to clear the ground.
  925. flVerticalOffset = maxs.z + 1.0;
  926. }
  927. vStart.z += flVerticalOffset;
  928. Vector vEnd = vStart + (forward * flDist );
  929. return CheckTraceHullAttack( vStart, vEnd, mins, maxs, flDamage, iDmgType, forceScale, bDamageAnyNPC );
  930. }
  931. //-----------------------------------------------------------------------------
  932. // Purpose:
  933. // Input : *pHandleEntity -
  934. // contentsMask -
  935. // Output : Returns true on success, false on failure.
  936. //-----------------------------------------------------------------------------
  937. bool CTraceFilterMelee::ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
  938. {
  939. if ( !StandardFilterRules( pHandleEntity, contentsMask ) )
  940. return false;
  941. if ( !PassServerEntityFilter( pHandleEntity, m_pPassEnt ) )
  942. return false;
  943. // Don't test if the game code tells us we should ignore this collision...
  944. CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity );
  945. if ( pEntity )
  946. {
  947. if ( !pEntity->ShouldCollide( m_collisionGroup, contentsMask ) )
  948. return false;
  949. if ( !g_pGameRules->ShouldCollide( m_collisionGroup, pEntity->GetCollisionGroup() ) )
  950. return false;
  951. if ( pEntity->m_takedamage == DAMAGE_NO )
  952. return false;
  953. // FIXME: Do not translate this to the driver because the driver only accepts damage from the vehicle
  954. // Translate the vehicle into its driver for damage
  955. /*
  956. if ( pEntity->GetServerVehicle() != NULL )
  957. {
  958. CBaseEntity *pDriver = pEntity->GetServerVehicle()->GetPassenger();
  959. if ( pDriver != NULL )
  960. {
  961. pEntity = pDriver;
  962. }
  963. }
  964. */
  965. Vector attackDir = pEntity->WorldSpaceCenter() - m_dmgInfo->GetAttacker()->WorldSpaceCenter();
  966. VectorNormalize( attackDir );
  967. CTakeDamageInfo info = (*m_dmgInfo);
  968. CalculateMeleeDamageForce( &info, attackDir, info.GetAttacker()->WorldSpaceCenter(), m_flForceScale );
  969. CBaseCombatCharacter *pBCC = info.GetAttacker()->MyCombatCharacterPointer();
  970. CBaseCombatCharacter *pVictimBCC = pEntity->MyCombatCharacterPointer();
  971. // Only do these comparisons between NPCs
  972. if ( pBCC && pVictimBCC )
  973. {
  974. // Can only damage other NPCs that we hate
  975. if ( m_bDamageAnyNPC || pBCC->IRelationType( pEntity ) == D_HT )
  976. {
  977. if ( info.GetDamage() )
  978. {
  979. pEntity->TakeDamage( info );
  980. }
  981. // Put a combat sound in
  982. CSoundEnt::InsertSound( SOUND_COMBAT, info.GetDamagePosition(), 200, 0.2f, info.GetAttacker() );
  983. m_pHit = pEntity;
  984. return true;
  985. }
  986. }
  987. else
  988. {
  989. m_pHit = pEntity;
  990. // Make sure if the player is holding this, he drops it
  991. Pickup_ForcePlayerToDropThisObject( pEntity );
  992. // Otherwise just damage passive objects in our way
  993. if ( info.GetDamage() )
  994. {
  995. pEntity->TakeDamage( info );
  996. }
  997. }
  998. }
  999. return false;
  1000. }
  1001. //------------------------------------------------------------------------------
  1002. // Purpose : start and end trace position, amount
  1003. // of damage to do, and damage type. Returns a pointer to
  1004. // the damaged entity in case the NPC wishes to do
  1005. // other stuff to the victim (punchangle, etc)
  1006. //
  1007. // Used for many contact-range melee attacks. Bites, claws, etc.
  1008. // Input :
  1009. // Output :
  1010. //------------------------------------------------------------------------------
  1011. CBaseEntity *CBaseCombatCharacter::CheckTraceHullAttack( const Vector &vStart, const Vector &vEnd, const Vector &mins, const Vector &maxs, float flDamage, int iDmgType, float flForceScale, bool bDamageAnyNPC )
  1012. {
  1013. // Handy debuging tool to visualize HullAttack trace
  1014. if ( ai_show_hull_attacks.GetBool() )
  1015. {
  1016. float length = (vEnd - vStart ).Length();
  1017. Vector direction = (vEnd - vStart );
  1018. VectorNormalize( direction );
  1019. Vector hullMaxs = maxs;
  1020. hullMaxs.x = length + hullMaxs.x;
  1021. NDebugOverlay::BoxDirection(vStart, mins, hullMaxs, direction, 100,255,255,20,1.0);
  1022. NDebugOverlay::BoxDirection(vStart, mins, maxs, direction, 255,0,0,20,1.0);
  1023. }
  1024. #if 1
  1025. CTakeDamageInfo dmgInfo( this, this, flDamage, iDmgType );
  1026. // COLLISION_GROUP_PROJECTILE does some handy filtering that's very appropriate for this type of attack, as well. (sjb) 7/25/2007
  1027. CTraceFilterMelee traceFilter( this, COLLISION_GROUP_PROJECTILE, &dmgInfo, flForceScale, bDamageAnyNPC );
  1028. Ray_t ray;
  1029. ray.Init( vStart, vEnd, mins, maxs );
  1030. trace_t tr;
  1031. enginetrace->TraceRay( ray, MASK_SHOT_HULL, &traceFilter, &tr );
  1032. CBaseEntity *pEntity = traceFilter.m_pHit;
  1033. if ( pEntity == NULL )
  1034. {
  1035. // See if perhaps I'm trying to claw/bash someone who is standing on my head.
  1036. Vector vecTopCenter;
  1037. Vector vecEnd;
  1038. Vector vecMins, vecMaxs;
  1039. // Do a tracehull from the top center of my bounding box.
  1040. vecTopCenter = GetAbsOrigin();
  1041. CollisionProp()->WorldSpaceAABB( &vecMins, &vecMaxs );
  1042. vecTopCenter.z = vecMaxs.z + 1.0f;
  1043. vecEnd = vecTopCenter;
  1044. vecEnd.z += 2.0f;
  1045. ray.Init( vecTopCenter, vEnd, mins, maxs );
  1046. enginetrace->TraceRay( ray, MASK_SHOT_HULL, &traceFilter, &tr );
  1047. pEntity = traceFilter.m_pHit;
  1048. }
  1049. if( pEntity && !pEntity->CanBeHitByMeleeAttack(this) )
  1050. {
  1051. // If we touched something, but it shouldn't be hit, return nothing.
  1052. pEntity = NULL;
  1053. }
  1054. return pEntity;
  1055. #else
  1056. trace_t tr;
  1057. UTIL_TraceHull( vStart, vEnd, mins, maxs, MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, &tr );
  1058. CBaseEntity *pEntity = tr.m_pEnt;
  1059. if ( !pEntity )
  1060. {
  1061. // See if perhaps I'm trying to claw/bash someone who is standing on my head.
  1062. Vector vecTopCenter;
  1063. Vector vecEnd;
  1064. Vector vecMins, vecMaxs;
  1065. // Do a tracehull from the top center of my bounding box.
  1066. vecTopCenter = GetAbsOrigin();
  1067. CollisionProp()->WorldSpaceAABB( &vecMins, &vecMaxs );
  1068. vecTopCenter.z = vecMaxs.z + 1.0f;
  1069. vecEnd = vecTopCenter;
  1070. vecEnd.z += 2.0f;
  1071. UTIL_TraceHull( vecTopCenter, vecEnd, mins, maxs, MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, &tr );
  1072. pEntity = tr.m_pEnt;
  1073. }
  1074. if ( !pEntity || !pEntity->m_takedamage || !pEntity->IsAlive() )
  1075. return NULL;
  1076. // Translate the vehicle into its driver for damage
  1077. if ( pEntity->GetServerVehicle() != NULL )
  1078. {
  1079. CBaseEntity *pDriver = pEntity->GetServerVehicle()->GetPassenger();
  1080. if ( pDriver != NULL )
  1081. {
  1082. pEntity = pDriver;
  1083. //FIXME: Hook for damage scale in car here
  1084. }
  1085. }
  1086. // Must hate the hit entity
  1087. if ( IRelationType( pEntity ) == D_HT )
  1088. {
  1089. if ( iDamage > 0 )
  1090. {
  1091. CTakeDamageInfo info( this, this, flDamage, iDmgType );
  1092. CalculateMeleeDamageForce( &info, (vEnd - vStart), vStart, forceScale );
  1093. pEntity->TakeDamage( info );
  1094. }
  1095. }
  1096. return pEntity;
  1097. #endif
  1098. }
  1099. bool CBaseCombatCharacter::Event_Gibbed( const CTakeDamageInfo &info )
  1100. {
  1101. bool fade = false;
  1102. if ( HasHumanGibs() )
  1103. {
  1104. ConVarRef violence_hgibs( "violence_hgibs" );
  1105. if ( violence_hgibs.IsValid() && violence_hgibs.GetInt() == 0 )
  1106. {
  1107. fade = true;
  1108. }
  1109. }
  1110. else if ( HasAlienGibs() )
  1111. {
  1112. ConVarRef violence_agibs( "violence_agibs" );
  1113. if ( violence_agibs.IsValid() && violence_agibs.GetInt() == 0 )
  1114. {
  1115. fade = true;
  1116. }
  1117. }
  1118. m_takedamage = DAMAGE_NO;
  1119. AddSolidFlags( FSOLID_NOT_SOLID );
  1120. m_lifeState = LIFE_DEAD;
  1121. if ( fade )
  1122. {
  1123. CorpseFade();
  1124. return false;
  1125. }
  1126. else
  1127. {
  1128. AddEffects( EF_NODRAW ); // make the model invisible.
  1129. return CorpseGib( info );
  1130. }
  1131. }
  1132. Vector CBaseCombatCharacter::CalcDeathForceVector( const CTakeDamageInfo &info )
  1133. {
  1134. // Already have a damage force in the data, use that.
  1135. bool bNoPhysicsForceDamage = g_pGameRules->Damage_NoPhysicsForce( info.GetDamageType() );
  1136. if ( info.GetDamageForce() != vec3_origin || bNoPhysicsForceDamage )
  1137. {
  1138. if( info.GetDamageType() & DMG_BLAST )
  1139. {
  1140. // Fudge blast forces a little bit, so that each
  1141. // victim gets a slightly different trajectory.
  1142. // This simulates features that usually vary from
  1143. // person-to-person variables such as bodyweight,
  1144. // which are all indentical for characters using the same model.
  1145. float scale = random->RandomFloat( 0.85, 1.15 );
  1146. Vector force = info.GetDamageForce();
  1147. force.x *= scale;
  1148. force.y *= scale;
  1149. // Try to always exaggerate the upward force because we've got pretty harsh gravity
  1150. force.z *= (force.z > 0) ? 1.15 : scale;
  1151. return force;
  1152. }
  1153. return info.GetDamageForce();
  1154. }
  1155. CBaseEntity *pForce = info.GetInflictor();
  1156. if ( !pForce )
  1157. {
  1158. pForce = info.GetAttacker();
  1159. }
  1160. if ( pForce )
  1161. {
  1162. // Calculate an impulse large enough to push a 75kg man 4 in/sec per point of damage
  1163. float forceScale = info.GetDamage() * 75 * 4;
  1164. Vector forceVector;
  1165. // If the damage is a blast, point the force vector higher than usual, this gives
  1166. // the ragdolls a bodacious "really got blowed up" look.
  1167. if( info.GetDamageType() & DMG_BLAST )
  1168. {
  1169. // exaggerate the force from explosions a little (37.5%)
  1170. forceVector = (GetLocalOrigin() + Vector(0, 0, WorldAlignSize().z) ) - pForce->GetLocalOrigin();
  1171. VectorNormalize(forceVector);
  1172. forceVector *= 1.375f;
  1173. }
  1174. else
  1175. {
  1176. // taking damage from self? Take a little random force, but still try to collapse on the spot.
  1177. if ( this == pForce )
  1178. {
  1179. forceVector.x = random->RandomFloat( -1.0f, 1.0f );
  1180. forceVector.y = random->RandomFloat( -1.0f, 1.0f );
  1181. forceVector.z = 0.0;
  1182. forceScale = random->RandomFloat( 1000.0f, 2000.0f );
  1183. }
  1184. else
  1185. {
  1186. // UNDONE: Collision forces are baked in to CTakeDamageInfo now
  1187. // UNDONE: Is this MOVETYPE_VPHYSICS code still necessary?
  1188. if ( pForce->GetMoveType() == MOVETYPE_VPHYSICS )
  1189. {
  1190. // killed by a physics object
  1191. IPhysicsObject *pPhysics = VPhysicsGetObject();
  1192. if ( !pPhysics )
  1193. {
  1194. pPhysics = pForce->VPhysicsGetObject();
  1195. }
  1196. pPhysics->GetVelocity( &forceVector, NULL );
  1197. forceScale = pPhysics->GetMass();
  1198. }
  1199. else
  1200. {
  1201. forceVector = GetLocalOrigin() - pForce->GetLocalOrigin();
  1202. VectorNormalize(forceVector);
  1203. }
  1204. }
  1205. }
  1206. return forceVector * forceScale;
  1207. }
  1208. return vec3_origin;
  1209. }
  1210. //-----------------------------------------------------------------------------
  1211. // Purpose:
  1212. // Output : Returns true on success, false on failure.
  1213. //-----------------------------------------------------------------------------
  1214. void CBaseCombatCharacter::FixupBurningServerRagdoll( CBaseEntity *pRagdoll )
  1215. {
  1216. if ( !IsOnFire() )
  1217. return;
  1218. // Move the fire effects entity to the ragdoll
  1219. CEntityFlame *pFireChild = dynamic_cast<CEntityFlame *>( GetEffectEntity() );
  1220. if ( pFireChild )
  1221. {
  1222. SetEffectEntity( NULL );
  1223. pRagdoll->AddFlag( FL_ONFIRE );
  1224. pFireChild->SetAbsOrigin( pRagdoll->GetAbsOrigin() );
  1225. pFireChild->AttachToEntity( pRagdoll );
  1226. pFireChild->AddEFlags( EFL_FORCE_CHECK_TRANSMIT );
  1227. pRagdoll->SetEffectEntity( pFireChild );
  1228. color24 color = GetRenderColor();
  1229. pRagdoll->SetRenderColor( color.r, color.g, color.b );
  1230. }
  1231. }
  1232. bool CBaseCombatCharacter::BecomeRagdollBoogie( CBaseEntity *pKiller, const Vector &forceVector, float duration, int flags )
  1233. {
  1234. Assert( CanBecomeRagdoll() );
  1235. CTakeDamageInfo info( pKiller, pKiller, 1.0f, DMG_GENERIC );
  1236. info.SetDamageForce( forceVector );
  1237. CBaseEntity *pRagdoll = CreateServerRagdoll( this, 0, info, COLLISION_GROUP_INTERACTIVE_DEBRIS, true );
  1238. pRagdoll->SetCollisionBounds( CollisionProp()->OBBMins(), CollisionProp()->OBBMaxs() );
  1239. CRagdollBoogie::Create( pRagdoll, 200, gpGlobals->curtime, duration, flags );
  1240. CTakeDamageInfo ragdollInfo( pKiller, pKiller, 10000.0, DMG_GENERIC | DMG_REMOVENORAGDOLL );
  1241. ragdollInfo.SetDamagePosition(WorldSpaceCenter());
  1242. ragdollInfo.SetDamageForce( Vector( 0, 0, 1) );
  1243. TakeDamage( ragdollInfo );
  1244. return true;
  1245. }
  1246. //-----------------------------------------------------------------------------
  1247. // Purpose:
  1248. //-----------------------------------------------------------------------------
  1249. bool CBaseCombatCharacter::BecomeRagdoll( const CTakeDamageInfo &info, const Vector &forceVector )
  1250. {
  1251. if ( (info.GetDamageType() & DMG_VEHICLE) && !g_pGameRules->IsMultiplayer() )
  1252. {
  1253. CTakeDamageInfo info2 = info;
  1254. info2.SetDamageForce( forceVector );
  1255. Vector pos = info2.GetDamagePosition();
  1256. float flAbsMinsZ = GetAbsOrigin().z + WorldAlignMins().z;
  1257. if ( (pos.z - flAbsMinsZ) < 24 )
  1258. {
  1259. // HACKHACK: Make sure the vehicle impact is at least 2ft off the ground
  1260. pos.z = flAbsMinsZ + 24;
  1261. info2.SetDamagePosition( pos );
  1262. }
  1263. // in single player create ragdolls on the server when the player hits someone
  1264. // with their vehicle - for more dramatic death/collisions
  1265. CBaseEntity *pRagdoll = CreateServerRagdoll( this, m_nForceBone, info2, COLLISION_GROUP_INTERACTIVE_DEBRIS, true );
  1266. FixupBurningServerRagdoll( pRagdoll );
  1267. RemoveDeferred();
  1268. return true;
  1269. }
  1270. //Fix up the force applied to server side ragdolls. This fixes magnets not affecting them.
  1271. CTakeDamageInfo newinfo = info;
  1272. newinfo.SetDamageForce( forceVector );
  1273. #ifdef HL2_EPISODIC
  1274. // Burning corpses are server-side in episodic, if we're in darkness mode
  1275. if ( IsOnFire() && HL2GameRules()->IsAlyxInDarknessMode() )
  1276. {
  1277. CBaseEntity *pRagdoll = CreateServerRagdoll( this, m_nForceBone, newinfo, COLLISION_GROUP_DEBRIS );
  1278. FixupBurningServerRagdoll( pRagdoll );
  1279. RemoveDeferred();
  1280. return true;
  1281. }
  1282. #endif
  1283. #if defined( HL2_DLL )
  1284. // Mega physgun requires everything to be a server-side ragdoll
  1285. if ( m_bForceServerRagdoll == true || ( HL2GameRules()->MegaPhyscannonActive() == true ) && !IsPlayer() && Classify() != CLASS_PLAYER_ALLY_VITAL && Classify() != CLASS_PLAYER_ALLY )
  1286. {
  1287. if ( CanBecomeServerRagdoll() == false )
  1288. return false;
  1289. //FIXME: This is fairly leafy to be here, but time is short!
  1290. CBaseEntity *pRagdoll = CreateServerRagdoll( this, m_nForceBone, newinfo, COLLISION_GROUP_INTERACTIVE_DEBRIS, true );
  1291. FixupBurningServerRagdoll( pRagdoll );
  1292. PhysSetEntityGameFlags( pRagdoll, FVPHYSICS_NO_SELF_COLLISIONS );
  1293. RemoveDeferred();
  1294. return true;
  1295. }
  1296. if( hl2_episodic.GetBool() && Classify() == CLASS_PLAYER_ALLY_VITAL )
  1297. {
  1298. CreateServerRagdoll( this, m_nForceBone, newinfo, COLLISION_GROUP_INTERACTIVE_DEBRIS, true );
  1299. RemoveDeferred();
  1300. return true;
  1301. }
  1302. #endif //HL2_DLL
  1303. return BecomeRagdollOnClient( forceVector );
  1304. }
  1305. /*
  1306. ============
  1307. Killed
  1308. ============
  1309. */
  1310. void CBaseCombatCharacter::Event_Killed( const CTakeDamageInfo &info )
  1311. {
  1312. extern ConVar npc_vphysics;
  1313. // Advance life state to dying
  1314. m_lifeState = LIFE_DYING;
  1315. // Calculate death force
  1316. Vector forceVector = CalcDeathForceVector( info );
  1317. // See if there's a ragdoll magnet that should influence our force.
  1318. CRagdollMagnet *pMagnet = CRagdollMagnet::FindBestMagnet( this );
  1319. if( pMagnet )
  1320. {
  1321. forceVector += pMagnet->GetForceVector( this );
  1322. }
  1323. CBaseCombatWeapon *pDroppedWeapon = NULL;
  1324. if ( ShouldDropActiveWeaponWhenKilled() )
  1325. {
  1326. pDroppedWeapon = m_hActiveWeapon.Get();
  1327. // Drop any weapon that I own
  1328. if ( VPhysicsGetObject() )
  1329. {
  1330. Vector weaponForce = forceVector * VPhysicsGetObject()->GetInvMass();
  1331. Weapon_Drop( m_hActiveWeapon, NULL, &weaponForce );
  1332. }
  1333. else
  1334. {
  1335. Weapon_Drop( m_hActiveWeapon );
  1336. }
  1337. }
  1338. // if flagged to drop a health kit
  1339. if (HasSpawnFlags(SF_NPC_DROP_HEALTHKIT))
  1340. {
  1341. CBaseEntity::Create( "item_healthvial", GetAbsOrigin(), GetAbsAngles() );
  1342. }
  1343. // clear the deceased's sound channels.(may have been firing or reloading when killed)
  1344. EmitSound( "BaseCombatCharacter.StopWeaponSounds" );
  1345. // Tell my killer that he got me!
  1346. if( info.GetAttacker() )
  1347. {
  1348. info.GetAttacker()->Event_KilledOther(this, info);
  1349. g_EventQueue.AddEvent( info.GetAttacker(), "KilledNPC", 0.3, this, this );
  1350. }
  1351. SendOnKilledGameEvent( info );
  1352. // Ragdoll unless we've gibbed
  1353. if ( ShouldGib( info ) == false )
  1354. {
  1355. bool bRagdollCreated = false;
  1356. if ( (info.GetDamageType() & DMG_DISSOLVE) && CanBecomeRagdoll() )
  1357. {
  1358. int nDissolveType = ENTITY_DISSOLVE_NORMAL;
  1359. if ( info.GetDamageType() & DMG_SHOCK )
  1360. {
  1361. nDissolveType = ENTITY_DISSOLVE_ELECTRICAL;
  1362. }
  1363. bRagdollCreated = Dissolve( NULL, gpGlobals->curtime, false, nDissolveType );
  1364. // Also dissolve any weapons we dropped
  1365. if ( pDroppedWeapon )
  1366. {
  1367. pDroppedWeapon->Dissolve( NULL, gpGlobals->curtime, false, nDissolveType );
  1368. }
  1369. }
  1370. #ifdef HL2_DLL
  1371. else if ( PlayerHasMegaPhysCannon() )
  1372. {
  1373. if ( pDroppedWeapon )
  1374. {
  1375. pDroppedWeapon->Dissolve( NULL, gpGlobals->curtime, false, ENTITY_DISSOLVE_NORMAL );
  1376. }
  1377. }
  1378. #endif
  1379. if ( !bRagdollCreated && ( info.GetDamageType() & DMG_REMOVENORAGDOLL ) == 0 )
  1380. {
  1381. BecomeRagdoll( info, forceVector );
  1382. }
  1383. }
  1384. // no longer standing on a nav area
  1385. ClearLastKnownArea();
  1386. }
  1387. void CBaseCombatCharacter::Event_Dying( void )
  1388. {
  1389. }
  1390. // ===========================================================================
  1391. // > Weapons
  1392. // ===========================================================================
  1393. bool CBaseCombatCharacter::Weapon_Detach( CBaseCombatWeapon *pWeapon )
  1394. {
  1395. for ( int i = 0; i < MAX_WEAPONS; i++ )
  1396. {
  1397. if ( pWeapon == m_hMyWeapons[i] )
  1398. {
  1399. m_hMyWeapons.Set( i, INVALID_EHANDLE );
  1400. int slotID = (i+1);
  1401. for (int j = 0; j < ARRAYSIZE(m_weaponIDToIndex); j++ )
  1402. {
  1403. if ( m_weaponIDToIndex[j] == slotID )
  1404. {
  1405. m_weaponIDToIndex[j] = 0;
  1406. break;
  1407. }
  1408. }
  1409. pWeapon->SetOwner( NULL );
  1410. if ( pWeapon == m_hActiveWeapon )
  1411. ClearActiveWeapon();
  1412. return true;
  1413. }
  1414. }
  1415. return false;
  1416. }
  1417. //-----------------------------------------------------------------------------
  1418. // For weapon strip
  1419. //-----------------------------------------------------------------------------
  1420. void CBaseCombatCharacter::ThrowDirForWeaponStrip( CBaseCombatWeapon *pWeapon, const Vector &vecForward, Vector *pVecThrowDir )
  1421. {
  1422. // HACK! Always throw the physcannon directly in front of the player
  1423. // This is necessary for the physgun upgrade scene.
  1424. if ( FClassnameIs( pWeapon, "weapon_physcannon" ) )
  1425. {
  1426. if( hl2_episodic.GetBool() )
  1427. {
  1428. // It has been discovered that it's possible to throw the physcannon out of the world this way.
  1429. // So try to find a direction to throw the physcannon that's legal.
  1430. Vector vecOrigin = EyePosition();
  1431. Vector vecRight;
  1432. CrossProduct( vecForward, Vector( 0, 0, 1), vecRight );
  1433. Vector vecTest[ 4 ];
  1434. vecTest[0] = vecForward;
  1435. vecTest[1] = -vecForward;
  1436. vecTest[2] = vecRight;
  1437. vecTest[3] = -vecRight;
  1438. trace_t tr;
  1439. int i;
  1440. for( i = 0 ; i < 4 ; i++ )
  1441. {
  1442. UTIL_TraceLine( vecOrigin, vecOrigin + vecTest[ i ] * 48.0f, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr );
  1443. if ( !tr.startsolid && tr.fraction == 1.0f )
  1444. {
  1445. *pVecThrowDir = vecTest[ i ];
  1446. return;
  1447. }
  1448. }
  1449. }
  1450. // Well, fall through to what we did before we tried to make this a bit more robust.
  1451. *pVecThrowDir = vecForward;
  1452. }
  1453. else
  1454. {
  1455. // Nowhere in particular; just drop it.
  1456. VMatrix zRot;
  1457. MatrixBuildRotateZ( zRot, random->RandomFloat( -60.0f, 60.0f ) );
  1458. Vector vecThrow;
  1459. Vector3DMultiply( zRot, vecForward, *pVecThrowDir );
  1460. pVecThrowDir->z = random->RandomFloat( -0.5f, 0.5f );
  1461. VectorNormalize( *pVecThrowDir );
  1462. }
  1463. }
  1464. //-----------------------------------------------------------------------------
  1465. // For weapon strip
  1466. //-----------------------------------------------------------------------------
  1467. void CBaseCombatCharacter::DropWeaponForWeaponStrip( CBaseCombatWeapon *pWeapon,
  1468. const Vector &vecForward, const QAngle &vecAngles, float flDiameter )
  1469. {
  1470. Vector vecOrigin;
  1471. CollisionProp()->RandomPointInBounds( Vector( 0.5f, 0.5f, 0.5f ), Vector( 0.5f, 0.5f, 1.0f ), &vecOrigin );
  1472. // Nowhere in particular; just drop it.
  1473. Vector vecThrow;
  1474. ThrowDirForWeaponStrip( pWeapon, vecForward, &vecThrow );
  1475. Vector vecOffsetOrigin;
  1476. VectorMA( vecOrigin, flDiameter, vecThrow, vecOffsetOrigin );
  1477. trace_t tr;
  1478. UTIL_TraceLine( vecOrigin, vecOffsetOrigin, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr );
  1479. if ( tr.startsolid || tr.allsolid || ( tr.fraction < 1.0f && tr.m_pEnt != pWeapon ) )
  1480. {
  1481. //FIXME: Throw towards a known safe spot?
  1482. vecThrow.Negate();
  1483. VectorMA( vecOrigin, flDiameter, vecThrow, vecOffsetOrigin );
  1484. }
  1485. vecThrow *= random->RandomFloat( 400.0f, 600.0f );
  1486. pWeapon->SetAbsOrigin( vecOrigin );
  1487. pWeapon->SetAbsAngles( vecAngles );
  1488. pWeapon->Drop( vecThrow );
  1489. pWeapon->SetRemoveable( false );
  1490. Weapon_Detach( pWeapon );
  1491. }
  1492. //-----------------------------------------------------------------------------
  1493. // For weapon strip
  1494. //-----------------------------------------------------------------------------
  1495. void CBaseCombatCharacter::Weapon_DropAll( bool bDisallowWeaponPickup )
  1496. {
  1497. if ( GetFlags() & FL_NPC )
  1498. {
  1499. for (int i=0; i<MAX_WEAPONS; ++i)
  1500. {
  1501. CBaseCombatWeapon *pWeapon = m_hMyWeapons[i];
  1502. if (!pWeapon)
  1503. continue;
  1504. Weapon_Drop( pWeapon );
  1505. }
  1506. return;
  1507. }
  1508. QAngle gunAngles;
  1509. VectorAngles( BodyDirection2D(), gunAngles );
  1510. Vector vecForward;
  1511. AngleVectors( gunAngles, &vecForward, NULL, NULL );
  1512. float flDiameter = sqrt( CollisionProp()->OBBSize().x * CollisionProp()->OBBSize().x +
  1513. CollisionProp()->OBBSize().y * CollisionProp()->OBBSize().y );
  1514. CBaseCombatWeapon *pActiveWeapon = GetActiveWeapon();
  1515. for (int i=0; i<MAX_WEAPONS; ++i)
  1516. {
  1517. CBaseCombatWeapon *pWeapon = m_hMyWeapons[i];
  1518. if (!pWeapon)
  1519. continue;
  1520. // Have to drop this after we've dropped everything else, so autoswitch doesn't happen
  1521. if ( pWeapon == pActiveWeapon )
  1522. continue;
  1523. DropWeaponForWeaponStrip( pWeapon, vecForward, gunAngles, flDiameter );
  1524. // HACK: This hack is required to allow weapons to be disintegrated
  1525. // in the citadel weapon-strip scene
  1526. // Make them not pick-uppable again. This also has the effect of allowing weapons
  1527. // to collide with triggers.
  1528. if ( bDisallowWeaponPickup )
  1529. {
  1530. pWeapon->RemoveSolidFlags( FSOLID_TRIGGER );
  1531. IPhysicsObject *pObj = pWeapon->VPhysicsGetObject();
  1532. if ( pObj != NULL )
  1533. {
  1534. pObj->SetGameFlags( FVPHYSICS_NO_PLAYER_PICKUP );
  1535. }
  1536. }
  1537. }
  1538. // Drop the active weapon normally...
  1539. if ( pActiveWeapon )
  1540. {
  1541. // Nowhere in particular; just drop it.
  1542. Vector vecThrow;
  1543. ThrowDirForWeaponStrip( pActiveWeapon, vecForward, &vecThrow );
  1544. // Throw a little more vigorously; it starts closer to the player
  1545. vecThrow *= random->RandomFloat( 800.0f, 1000.0f );
  1546. Weapon_Drop( pActiveWeapon, NULL, &vecThrow );
  1547. pActiveWeapon->SetRemoveable( false );
  1548. // HACK: This hack is required to allow weapons to be disintegrated
  1549. // in the citadel weapon-strip scene
  1550. // Make them not pick-uppable again. This also has the effect of allowing weapons
  1551. // to collide with triggers.
  1552. if ( bDisallowWeaponPickup )
  1553. {
  1554. pActiveWeapon->RemoveSolidFlags( FSOLID_TRIGGER );
  1555. }
  1556. }
  1557. }
  1558. //-----------------------------------------------------------------------------
  1559. // Purpose: Drop the active weapon, optionally throwing it at the given target position.
  1560. // Input : pWeapon - Weapon to drop/throw.
  1561. // pvecTarget - Position to throw it at, NULL for none.
  1562. //-----------------------------------------------------------------------------
  1563. void CBaseCombatCharacter::Weapon_Drop( CBaseCombatWeapon *pWeapon, const Vector *pvecTarget /* = NULL */, const Vector *pVelocity /* = NULL */ )
  1564. {
  1565. if ( !pWeapon )
  1566. return;
  1567. // If I'm an NPC, fill the weapon with ammo before I drop it.
  1568. if ( GetFlags() & FL_NPC )
  1569. {
  1570. if ( pWeapon->UsesClipsForAmmo1() )
  1571. {
  1572. pWeapon->m_iClip1 = pWeapon->GetDefaultClip1();
  1573. if( FClassnameIs( pWeapon, "weapon_smg1" ) )
  1574. {
  1575. if ( CBasePlayer *pPlayer = UTIL_PlayerByIndex( 1 ) )
  1576. {
  1577. // Drop enough ammo to kill 2 of me.
  1578. // Figure out how much damage one piece of this type of ammo does to this type of enemy.
  1579. float flAmmoDamage = g_pGameRules->GetAmmoDamage( UTIL_PlayerByIndex(1), this, pWeapon->GetPrimaryAmmoType() );
  1580. pWeapon->m_iClip1 = (GetMaxHealth() / flAmmoDamage) * 2;
  1581. }
  1582. else
  1583. {
  1584. pWeapon->m_iClip1 = pWeapon->GetMaxClip1();
  1585. }
  1586. }
  1587. }
  1588. if ( pWeapon->UsesClipsForAmmo2() )
  1589. {
  1590. pWeapon->m_iClip2 = pWeapon->GetDefaultClip2();
  1591. }
  1592. }
  1593. if ( IsPlayer() )
  1594. {
  1595. Vector vThrowPos = Weapon_ShootPosition() - Vector(0,0,12);
  1596. if( UTIL_PointContents(vThrowPos, CONTENTS_SOLID) & CONTENTS_SOLID )
  1597. {
  1598. Msg("Weapon spawning in solid!\n");
  1599. }
  1600. pWeapon->SetAbsOrigin( vThrowPos );
  1601. QAngle gunAngles;
  1602. VectorAngles( BodyDirection2D(), gunAngles );
  1603. pWeapon->SetAbsAngles( gunAngles );
  1604. }
  1605. else
  1606. {
  1607. int iBIndex = -1;
  1608. int iWeaponBoneIndex = -1;
  1609. CStudioHdr *hdr = pWeapon->GetModelPtr();
  1610. // If I have a hand, set the weapon position to my hand bone position.
  1611. if ( hdr && hdr->numbones() > 0 )
  1612. {
  1613. // Assume bone zero is the root
  1614. for ( iWeaponBoneIndex = 0; iWeaponBoneIndex < hdr->numbones(); ++iWeaponBoneIndex )
  1615. {
  1616. iBIndex = LookupBone( hdr->pBone( iWeaponBoneIndex )->pszName() );
  1617. // Found one!
  1618. if ( iBIndex != -1 )
  1619. {
  1620. break;
  1621. }
  1622. }
  1623. if ( iBIndex == -1 )
  1624. {
  1625. iBIndex = LookupBone( "ValveBiped.weapon_bone" );
  1626. }
  1627. }
  1628. else
  1629. {
  1630. iBIndex = LookupBone( "ValveBiped.weapon_bone" );
  1631. }
  1632. if ( iBIndex != -1)
  1633. {
  1634. Vector origin;
  1635. QAngle angles;
  1636. matrix3x4_t transform;
  1637. // Get the transform for the weapon bonetoworldspace in the NPC
  1638. GetBoneTransform( iBIndex, transform );
  1639. // find offset of root bone from origin in local space
  1640. // Make sure we're detached from hierarchy before doing this!!!
  1641. pWeapon->StopFollowingEntity();
  1642. pWeapon->SetAbsOrigin( Vector( 0, 0, 0 ) );
  1643. pWeapon->SetAbsAngles( QAngle( 0, 0, 0 ) );
  1644. pWeapon->InvalidateBoneCache();
  1645. matrix3x4_t rootLocal;
  1646. pWeapon->GetBoneTransform( iWeaponBoneIndex, rootLocal );
  1647. // invert it
  1648. matrix3x4_t rootInvLocal;
  1649. MatrixInvert( rootLocal, rootInvLocal );
  1650. matrix3x4_t weaponMatrix;
  1651. ConcatTransforms( transform, rootInvLocal, weaponMatrix );
  1652. MatrixAngles( weaponMatrix, angles, origin );
  1653. pWeapon->Teleport( &origin, &angles, NULL );
  1654. }
  1655. // Otherwise just set in front of me.
  1656. else
  1657. {
  1658. Vector vFacingDir = BodyDirection2D();
  1659. vFacingDir = vFacingDir * 10.0;
  1660. pWeapon->SetAbsOrigin( Weapon_ShootPosition() + vFacingDir );
  1661. }
  1662. }
  1663. Vector vecThrow;
  1664. if (pvecTarget)
  1665. {
  1666. // I've been told to throw it somewhere specific.
  1667. vecThrow = VecCheckToss( this, pWeapon->GetAbsOrigin(), *pvecTarget, 0.2, 1.0, false );
  1668. }
  1669. else
  1670. {
  1671. if ( pVelocity )
  1672. {
  1673. vecThrow = *pVelocity;
  1674. float flLen = vecThrow.Length();
  1675. if (flLen > 400)
  1676. {
  1677. VectorNormalize(vecThrow);
  1678. vecThrow *= 400;
  1679. }
  1680. }
  1681. else
  1682. {
  1683. // Nowhere in particular; just drop it.
  1684. float throwForce = ( IsPlayer() ) ? 400.0f : random->RandomInt( 64, 128 );
  1685. vecThrow = BodyDirection3D() * throwForce;
  1686. }
  1687. }
  1688. pWeapon->Drop( vecThrow );
  1689. Weapon_Detach( pWeapon );
  1690. if ( HasSpawnFlags( SF_NPC_NO_WEAPON_DROP ) )
  1691. {
  1692. // Don't drop weapons when the super physgun is happening.
  1693. UTIL_Remove( pWeapon );
  1694. }
  1695. }
  1696. //-----------------------------------------------------------------------------
  1697. // Lighting origin
  1698. //-----------------------------------------------------------------------------
  1699. void CBaseCombatCharacter::SetLightingOriginRelative( CBaseEntity *pLightingOrigin )
  1700. {
  1701. BaseClass::SetLightingOriginRelative( pLightingOrigin );
  1702. if ( GetActiveWeapon() )
  1703. {
  1704. GetActiveWeapon()->SetLightingOriginRelative( pLightingOrigin );
  1705. }
  1706. }
  1707. //-----------------------------------------------------------------------------
  1708. // Purpose: Add new weapon to the character
  1709. // Input : New weapon
  1710. //-----------------------------------------------------------------------------
  1711. void CBaseCombatCharacter::Weapon_Equip( CBaseCombatWeapon *pWeapon )
  1712. {
  1713. // Add the weapon to my weapon inventory
  1714. for (int i=0;i<MAX_WEAPONS;i++)
  1715. {
  1716. if (!m_hMyWeapons[i])
  1717. {
  1718. m_hMyWeapons.Set( i, pWeapon );
  1719. m_weaponIDToIndex[pWeapon->GetWeaponID()] = (i+1);
  1720. break;
  1721. }
  1722. }
  1723. // Weapon is now on my team
  1724. pWeapon->ChangeTeam( GetTeamNumber() );
  1725. // ----------------------
  1726. // Give Primary Ammo
  1727. // ----------------------
  1728. // If gun doesn't use clips, just give ammo
  1729. if ( !pWeapon->UsesClipsForAmmo1() )
  1730. {
  1731. #ifdef HL2_DLL
  1732. if( FStrEq(STRING(gpGlobals->mapname), "d3_c17_09") && FClassnameIs(pWeapon, "weapon_rpg") && pWeapon->NameMatches("player_spawn_items") )
  1733. {
  1734. // !!!HACK - Don't give any ammo with the spawn equipment RPG in d3_c17_09. This is a chapter
  1735. // start and the map is way to easy if you start with 3 RPG rounds. It's fine if a player conserves
  1736. // them and uses them here, but it's not OK to start with enough ammo to bypass the snipers completely.
  1737. GiveAmmo( 0, pWeapon->m_iPrimaryAmmoType);
  1738. }
  1739. else
  1740. #endif // HL2_DLL
  1741. {
  1742. // non-clip, exhaustible ammo ( such as grenades ) is still held on player.
  1743. CBaseCombatCharacter * pOwner = NULL;
  1744. if ( pWeapon->GetWpnData().iFlags & ITEM_FLAG_EXHAUSTIBLE )
  1745. {
  1746. pOwner = this;
  1747. pWeapon->SetReserveAmmoCount( AMMO_POSITION_PRIMARY, pWeapon->GetDefaultClip1(), ShouldPickupItemSilently( this ), pOwner );
  1748. }
  1749. }
  1750. }
  1751. // If default ammo given is greater than clip
  1752. // size, fill clips and give extra ammo
  1753. // else if (pWeapon->GetDefaultClip1() > pWeapon->GetMaxClip1() )
  1754. // {
  1755. // pWeapon->m_iClip1 = pWeapon->GetMaxClip1();
  1756. // pWeapon->SetReserveAmmoCount( AMMO_POSITION_PRIMARY, (pWeapon->GetDefaultClip1() - pWeapon->GetMaxClip1()));
  1757. // }
  1758. // ----------------------
  1759. // Give Secondary Ammo
  1760. // ----------------------
  1761. // If gun doesn't use clips, just give ammo
  1762. if ( !pWeapon->UsesClipsForAmmo2() )
  1763. {
  1764. // non-clip, exhaustible ammo ( such as grenades ) is still held on player.
  1765. CBaseCombatCharacter * pOwner = NULL;
  1766. if ( pWeapon->GetWpnData().iFlags & ITEM_FLAG_EXHAUSTIBLE )
  1767. {
  1768. pOwner = this;
  1769. pWeapon->SetReserveAmmoCount( AMMO_POSITION_SECONDARY, pWeapon->GetDefaultClip2(), ShouldPickupItemSilently( this ), pOwner );
  1770. }
  1771. }
  1772. // If default ammo given is greater than clip
  1773. // size, fill clips and give extra ammo
  1774. // else if ( pWeapon->GetDefaultClip2() > pWeapon->GetMaxClip2() )
  1775. // {
  1776. // pWeapon->m_iClip2 = pWeapon->GetMaxClip2();
  1777. // pWeapon->SetReserveAmmoCount( AMMO_POSITION_SECONDARY, ( pWeapon->GetDefaultClip2() - pWeapon->GetMaxClip2() ) );
  1778. // }
  1779. pWeapon->Equip( this );
  1780. // Players don't automatically holster their current weapon
  1781. if ( IsPlayer() == false )
  1782. {
  1783. if ( m_hActiveWeapon )
  1784. {
  1785. m_hActiveWeapon->Holster();
  1786. // FIXME: isn't this handeled by the weapon?
  1787. m_hActiveWeapon->AddEffects( EF_NODRAW );
  1788. }
  1789. SetActiveWeapon( pWeapon );
  1790. m_hActiveWeapon->RemoveEffects( EF_NODRAW );
  1791. }
  1792. // Gotta do this *after* Equip because it may whack maxRange
  1793. if ( IsPlayer() == false )
  1794. {
  1795. // If SF_NPC_LONG_RANGE spawn flags is set let weapon work from any distance
  1796. if ( HasSpawnFlags(SF_NPC_LONG_RANGE) )
  1797. {
  1798. m_hActiveWeapon->m_fMaxRange1 = 999999999;
  1799. m_hActiveWeapon->m_fMaxRange2 = 999999999;
  1800. }
  1801. }
  1802. WeaponProficiency_t proficiency;
  1803. proficiency = CalcWeaponProficiency( pWeapon );
  1804. if( weapon_showproficiency.GetBool() != 0 )
  1805. {
  1806. Msg("%s equipped with %s, proficiency is %s\n", GetClassname(), pWeapon->GetClassname(), GetWeaponProficiencyName( proficiency ) );
  1807. }
  1808. SetCurrentWeaponProficiency( proficiency );
  1809. // Pass the lighting origin over to the weapon if we have one
  1810. pWeapon->SetLightingOriginRelative( GetLightingOriginRelative() );
  1811. }
  1812. //-----------------------------------------------------------------------------
  1813. // Purpose: Leaves weapon, giving only ammo to the character
  1814. // Input : Weapon
  1815. //-----------------------------------------------------------------------------
  1816. bool CBaseCombatCharacter::Weapon_EquipAmmoOnly( CBaseCombatWeapon *pWeapon )
  1817. {
  1818. // Check for duplicates
  1819. for (int i=0;i<MAX_WEAPONS;i++)
  1820. {
  1821. if ( m_hMyWeapons[i].Get() && FClassnameIs(m_hMyWeapons[i], pWeapon->GetClassname()) )
  1822. {
  1823. // Just give the ammo from the clip
  1824. int primaryGiven = (pWeapon->UsesClipsForAmmo1()) ? pWeapon->m_iClip1 : pWeapon->GetPrimaryAmmoCount();
  1825. int secondaryGiven = (pWeapon->UsesClipsForAmmo2()) ? pWeapon->m_iClip2 : pWeapon->GetSecondaryAmmoCount();
  1826. bool bSuppressSound = false;
  1827. #if defined (CSTRIKE15)
  1828. bSuppressSound = ShouldPickupItemSilently( this );
  1829. #endif
  1830. CBaseCombatCharacter * pOwner = NULL;
  1831. if ( pWeapon->GetWpnData().iFlags & ITEM_FLAG_EXHAUSTIBLE )
  1832. pOwner = this;
  1833. int takenPrimary = pWeapon->GiveReserveAmmo( AMMO_POSITION_PRIMARY, primaryGiven, bSuppressSound, pOwner );
  1834. int takenSecondary = pWeapon->GiveReserveAmmo( AMMO_POSITION_SECONDARY, secondaryGiven, bSuppressSound, pOwner );
  1835. if( pWeapon->UsesClipsForAmmo1() )
  1836. {
  1837. pWeapon->m_iClip1 -= takenPrimary;
  1838. }
  1839. else
  1840. {
  1841. pWeapon->SetPrimaryAmmoCount( pWeapon->GetPrimaryAmmoCount() - takenPrimary );
  1842. }
  1843. if( pWeapon->UsesClipsForAmmo2() )
  1844. {
  1845. pWeapon->m_iClip2 -= takenSecondary;
  1846. }
  1847. else
  1848. {
  1849. pWeapon->SetSecondaryAmmoCount( pWeapon->GetSecondaryAmmoCount() - takenSecondary );
  1850. }
  1851. //Only succeed if we've taken ammo from the weapon
  1852. if ( takenPrimary > 0 || takenSecondary > 0 )
  1853. {
  1854. #if defined (CSTRIKE15)
  1855. IGameEvent * event = gameeventmanager->CreateEvent( "ammo_pickup" );
  1856. if( event )
  1857. {
  1858. const char *weaponName = pWeapon->GetClassname();
  1859. if ( IsWeaponClassname( weaponName ) )
  1860. {
  1861. weaponName += WEAPON_CLASSNAME_PREFIX_LENGTH;
  1862. }
  1863. event->SetInt( "userid", engine->GetPlayerUserId( edict() ) );
  1864. event->SetString( "item", weaponName );
  1865. event->SetInt( "index", m_hMyWeapons[i].Get()->entindex() );
  1866. gameeventmanager->FireEvent( event );
  1867. }
  1868. #endif
  1869. return true;
  1870. }
  1871. return false;
  1872. }
  1873. }
  1874. return false;
  1875. }
  1876. //-----------------------------------------------------------------------------
  1877. // Purpose: Returns whether the weapon passed in would occupy a slot already occupied by the carrier
  1878. // Input : *pWeapon - weapon to test for
  1879. // Output : Returns true on success, false on failure.
  1880. //-----------------------------------------------------------------------------
  1881. bool CBaseCombatCharacter::Weapon_SlotOccupied( CBaseCombatWeapon *pWeapon )
  1882. {
  1883. if ( pWeapon == NULL )
  1884. return false;
  1885. //Check to see if there's a resident weapon already in this slot
  1886. if ( Weapon_GetSlot( pWeapon->GetSlot() ) == NULL )
  1887. return false;
  1888. return true;
  1889. }
  1890. //-----------------------------------------------------------------------------
  1891. // Purpose: Get a pointer to a weapon this character has that uses the specified ammo
  1892. //-----------------------------------------------------------------------------
  1893. CBaseCombatWeapon *CBaseCombatCharacter::Weapon_GetWpnForAmmo( int iAmmoIndex )
  1894. {
  1895. for ( int i = 0; i < MAX_WEAPONS; i++ )
  1896. {
  1897. CBaseCombatWeapon *weapon = GetWeapon( i );
  1898. if ( !weapon )
  1899. continue;
  1900. if ( weapon->GetPrimaryAmmoType() == iAmmoIndex )
  1901. return weapon;
  1902. if ( weapon->GetSecondaryAmmoType() == iAmmoIndex )
  1903. return weapon;
  1904. }
  1905. return NULL;
  1906. }
  1907. //-----------------------------------------------------------------------------
  1908. // Purpose: Can this character operate this weapon?
  1909. // Input : A weapon
  1910. // Output : true or false
  1911. //-----------------------------------------------------------------------------
  1912. bool CBaseCombatCharacter::Weapon_CanUse( CBaseCombatWeapon *pWeapon )
  1913. {
  1914. acttable_t *pTable = pWeapon->ActivityList();
  1915. int actCount = pWeapon->ActivityListCount();
  1916. if( actCount < 1 )
  1917. {
  1918. // If the weapon has no activity table, it definitely cannot be used.
  1919. return false;
  1920. }
  1921. for ( int i = 0; i < actCount; i++, pTable++ )
  1922. {
  1923. if ( pTable->required )
  1924. {
  1925. // The NPC might translate the weapon activity into another activity
  1926. Activity translatedActivity = NPC_TranslateActivity( (Activity)(pTable->weaponAct) );
  1927. if ( SelectWeightedSequence(translatedActivity) == ACTIVITY_NOT_AVAILABLE )
  1928. {
  1929. return false;
  1930. }
  1931. }
  1932. }
  1933. return true;
  1934. }
  1935. //-----------------------------------------------------------------------------
  1936. // Purpose:
  1937. // Input :
  1938. // Output :
  1939. //-----------------------------------------------------------------------------
  1940. CBaseCombatWeapon *CBaseCombatCharacter::Weapon_Create( const char *pWeaponName )
  1941. {
  1942. CBaseCombatWeapon *pWeapon = static_cast<CBaseCombatWeapon *>( Create( pWeaponName, GetLocalOrigin(), GetLocalAngles(), this ) );
  1943. return pWeapon;
  1944. }
  1945. //-----------------------------------------------------------------------------
  1946. // Purpose:
  1947. // Input :
  1948. // Output :
  1949. //-----------------------------------------------------------------------------
  1950. void CBaseCombatCharacter::Weapon_HandleAnimEvent( animevent_t *pEvent )
  1951. {
  1952. // UNDONE: Some check to make sure that pEvent->pSource is a weapon I'm holding?
  1953. if ( m_hActiveWeapon )
  1954. {
  1955. // UNDONE: Pass to pEvent->pSource instead?
  1956. m_hActiveWeapon->Operator_HandleAnimEvent( pEvent, this );
  1957. }
  1958. }
  1959. void CBaseCombatCharacter::RemoveAllWeapons()
  1960. {
  1961. ClearActiveWeapon();
  1962. for (int i = 0; i < MAX_WEAPONS; i++)
  1963. {
  1964. if ( m_hMyWeapons[i] )
  1965. {
  1966. m_hMyWeapons[i]->Delete( );
  1967. m_hMyWeapons.Set( i, INVALID_EHANDLE );
  1968. }
  1969. }
  1970. V_memset( m_weaponIDToIndex, 0, sizeof(m_weaponIDToIndex) );
  1971. }
  1972. void CBaseCombatCharacter::RemoveAllWearables( void )
  1973. {
  1974. }
  1975. void CBaseCombatCharacter::RemoveWeaponOnPlayer( CBaseCombatWeapon *pWeapon )
  1976. {
  1977. ClearActiveWeapon();
  1978. for (int i = 0; i < MAX_WEAPONS; i++)
  1979. {
  1980. if ( m_hMyWeapons[i].Get() == pWeapon )
  1981. {
  1982. m_hMyWeapons[i]->Delete( );
  1983. m_hMyWeapons.Set( i, INVALID_EHANDLE );
  1984. }
  1985. }
  1986. V_memset( m_weaponIDToIndex, 0, sizeof(m_weaponIDToIndex) );
  1987. }
  1988. // take health
  1989. int CBaseCombatCharacter::TakeHealth (float flHealth, int bitsDamageType)
  1990. {
  1991. if (!m_takedamage)
  1992. return 0;
  1993. return BaseClass::TakeHealth(flHealth, bitsDamageType);
  1994. }
  1995. /*
  1996. ============
  1997. OnTakeDamage
  1998. The damage is coming from inflictor, but get mad at attacker
  1999. This should be the only function that ever reduces health.
  2000. bitsDamageType indicates the type of damage sustained, ie: DMG_SHOCK
  2001. Time-based damage: only occurs while the NPC is within the trigger_hurt.
  2002. When a NPC is poisoned via an arrow etc it takes all the poison damage at once.
  2003. GLOBALS ASSUMED SET: g_iSkillLevel
  2004. ============
  2005. */
  2006. int CBaseCombatCharacter::OnTakeDamage( const CTakeDamageInfo &info )
  2007. {
  2008. int retVal = 0;
  2009. if (!m_takedamage)
  2010. return 0;
  2011. if( IsPlayer() )
  2012. {
  2013. CBasePlayer *pPlayer = assert_cast<CBasePlayer *>(this);
  2014. pPlayer->RumbleEffect( RUMBLE_DMG_LOW, 0, RUMBLE_FLAG_RESTART );
  2015. }
  2016. m_iDamageCount++;
  2017. m_uiLastDamageTypeFlags = info.GetDamageType();
  2018. if ( info.GetDamageType() & DMG_SHOCK )
  2019. {
  2020. g_pEffects->Sparks( info.GetDamagePosition(), 2, 2 );
  2021. UTIL_Smoke( info.GetDamagePosition(), random->RandomInt( 10, 15 ), 10 );
  2022. }
  2023. // track damage history
  2024. if ( info.GetAttacker() )
  2025. {
  2026. int attackerTeam = info.GetAttacker()->GetTeamNumber();
  2027. m_hasBeenInjured |= ( 1 << attackerTeam );
  2028. for( int i=0; i<MAX_DAMAGE_TEAMS; ++i )
  2029. {
  2030. if ( m_damageHistory[i].team == attackerTeam )
  2031. {
  2032. // restart the injury timer
  2033. m_damageHistory[i].interval.Start();
  2034. break;
  2035. }
  2036. if ( m_damageHistory[i].team == TEAM_INVALID )
  2037. {
  2038. // team not registered yet
  2039. m_damageHistory[i].team = attackerTeam;
  2040. m_damageHistory[i].interval.Start();
  2041. break;
  2042. }
  2043. }
  2044. m_flTimeOfLastInjury = gpGlobals->curtime;
  2045. // Figure out what relative direction it hit from
  2046. Vector vDamageDirection = info.GetDamageForce();
  2047. VectorNormalize( vDamageDirection );
  2048. Vector vForward, vRight;
  2049. if( IsPlayer() )
  2050. {
  2051. AngleVectors( EyeAngles(), &vForward, &vRight, NULL );
  2052. }
  2053. else
  2054. {
  2055. GetVectors( &vForward, &vRight, NULL );
  2056. }
  2057. // Try front and back
  2058. float flDamageDirectionDot = vForward.Dot( vDamageDirection );
  2059. if ( flDamageDirectionDot <= -0.5f )
  2060. {
  2061. m_nRelativeDirectionOfLastInjury = DAMAGED_DIR_FRONT;
  2062. }
  2063. else if ( flDamageDirectionDot >= 0.5f )
  2064. {
  2065. m_nRelativeDirectionOfLastInjury = DAMAGED_DIR_BACK;
  2066. }
  2067. else
  2068. {
  2069. // Try left and right sides
  2070. float flDamageDirectionDot = vRight.Dot( vDamageDirection );
  2071. if ( flDamageDirectionDot <= -0.5f )
  2072. {
  2073. m_nRelativeDirectionOfLastInjury = DAMAGED_DIR_RIGHT;
  2074. }
  2075. else if ( flDamageDirectionDot >= 0.5f )
  2076. {
  2077. m_nRelativeDirectionOfLastInjury = DAMAGED_DIR_LEFT;
  2078. }
  2079. else
  2080. {
  2081. m_nRelativeDirectionOfLastInjury = DAMAGED_DIR_NONE;
  2082. }
  2083. }
  2084. }
  2085. switch( m_lifeState )
  2086. {
  2087. case LIFE_ALIVE:
  2088. retVal = OnTakeDamage_Alive( info );
  2089. if ( m_iHealth <= 0 )
  2090. {
  2091. IPhysicsObject *pPhysics = VPhysicsGetObject();
  2092. if ( pPhysics )
  2093. {
  2094. pPhysics->EnableCollisions( false );
  2095. }
  2096. bool bGibbed = false;
  2097. Event_Killed( info );
  2098. // Only classes that specifically request it are gibbed
  2099. if ( ShouldGib( info ) )
  2100. {
  2101. bGibbed = Event_Gibbed( info );
  2102. }
  2103. if ( bGibbed == false )
  2104. {
  2105. Event_Dying();
  2106. }
  2107. }
  2108. return retVal;
  2109. break;
  2110. case LIFE_DYING:
  2111. return OnTakeDamage_Dying( info );
  2112. default:
  2113. case LIFE_DEAD:
  2114. retVal = OnTakeDamage_Dead( info );
  2115. if ( m_iHealth <= 0 && g_pGameRules->Damage_ShouldGibCorpse( info.GetDamageType() ) && ShouldGib( info ) )
  2116. {
  2117. Event_Gibbed( info );
  2118. retVal = 0;
  2119. }
  2120. return retVal;
  2121. }
  2122. }
  2123. int CBaseCombatCharacter::OnTakeDamage_Alive( const CTakeDamageInfo &info )
  2124. {
  2125. if ( GetFlags() & FL_GODMODE )
  2126. return 0;
  2127. // grab the vector of the incoming attack. ( pretend that the inflictor is a little lower than it really is, so the body will tend to fly upward a bit).
  2128. Vector vecDir = vec3_origin;
  2129. if (info.GetInflictor())
  2130. {
  2131. vecDir = info.GetInflictor()->WorldSpaceCenter() - Vector ( 0, 0, 10 ) - WorldSpaceCenter();
  2132. VectorNormalize(vecDir);
  2133. }
  2134. g_vecAttackDir = vecDir;
  2135. //!!!LATER - make armor consideration here!
  2136. // do the damage
  2137. if ( m_takedamage != DAMAGE_EVENTS_ONLY )
  2138. {
  2139. // Separate the fractional amount of damage from the whole
  2140. float flFractionalDamage = info.GetDamage() - floor( info.GetDamage() );
  2141. float flIntegerDamage = info.GetDamage() - flFractionalDamage;
  2142. // Add fractional damage to the accumulator
  2143. m_flDamageAccumulator += flFractionalDamage;
  2144. // If the accumulator is holding a full point of damage, move that point
  2145. // of damage into the damage we're about to inflict.
  2146. if( m_flDamageAccumulator >= 1.0 )
  2147. {
  2148. flIntegerDamage += 1.0;
  2149. m_flDamageAccumulator -= 1.0;
  2150. }
  2151. if ( flIntegerDamage <= 0 )
  2152. return 0;
  2153. SetHealth( m_iHealth - flIntegerDamage );
  2154. }
  2155. return 1;
  2156. }
  2157. int CBaseCombatCharacter::OnTakeDamage_Dying( const CTakeDamageInfo &info )
  2158. {
  2159. return 1;
  2160. }
  2161. int CBaseCombatCharacter::OnTakeDamage_Dead( const CTakeDamageInfo &info )
  2162. {
  2163. // do the damage
  2164. if ( m_takedamage != DAMAGE_EVENTS_ONLY )
  2165. {
  2166. m_iHealth -= info.GetDamage();
  2167. }
  2168. if( IsPlayer() )
  2169. {
  2170. CBasePlayer *pPlayer = assert_cast<CBasePlayer *>(this);
  2171. pPlayer->RumbleEffect( RUMBLE_DMG_HIGH, 0, RUMBLE_FLAG_RESTART );
  2172. }
  2173. return 1;
  2174. }
  2175. //-----------------------------------------------------------------------------
  2176. // Purpose: Sets vBodyDir to the body direction (2D) of the combat character.
  2177. // Used as NPC's and players extract facing direction differently
  2178. // Input :
  2179. // Output :
  2180. //-----------------------------------------------------------------------------
  2181. QAngle CBaseCombatCharacter::BodyAngles()
  2182. {
  2183. return GetAbsAngles();
  2184. }
  2185. Vector CBaseCombatCharacter::BodyDirection2D( void )
  2186. {
  2187. Vector vBodyDir = BodyDirection3D( );
  2188. vBodyDir.z = 0;
  2189. vBodyDir.AsVector2D().NormalizeInPlace();
  2190. return vBodyDir;
  2191. }
  2192. Vector CBaseCombatCharacter::BodyDirection3D( void )
  2193. {
  2194. QAngle angles = BodyAngles();
  2195. // FIXME: cache this
  2196. Vector vBodyDir;
  2197. AngleVectors( angles, &vBodyDir );
  2198. return vBodyDir;
  2199. }
  2200. void CBaseCombatCharacter::SetTransmit( CCheckTransmitInfo *pInfo, bool bAlways )
  2201. {
  2202. // Skip this work if we're already marked for transmission.
  2203. if ( pInfo->m_pTransmitEdict->Get( entindex() ) )
  2204. return;
  2205. BaseClass::SetTransmit( pInfo, bAlways );
  2206. bool bLocalPlayer = ( pInfo->m_pClientEnt == edict() );
  2207. if ( IsPlayer() && !bLocalPlayer )
  2208. {
  2209. if ( ToBasePlayer( this )->IsSplitScreenUserOnEdict( pInfo->m_pClientEnt ) )
  2210. bLocalPlayer = true;
  2211. }
  2212. if ( bLocalPlayer )
  2213. {
  2214. for ( int i=0; i < MAX_WEAPONS; i++ )
  2215. {
  2216. CBaseCombatWeapon *pWeapon = m_hMyWeapons[i];
  2217. if ( !pWeapon )
  2218. continue;
  2219. // The local player is sent all of his weapons.
  2220. pWeapon->SetTransmit( pInfo, bAlways );
  2221. }
  2222. }
  2223. else
  2224. {
  2225. // The check for EF_NODRAW is useless because the weapon will be networked anyway. In CBaseCombatWeapon::
  2226. // UpdateTransmitState all weapons with owners will transmit to clients in the PVS.
  2227. if ( m_hActiveWeapon && !m_hActiveWeapon->IsEffectActive( EF_NODRAW ) )
  2228. m_hActiveWeapon->SetTransmit( pInfo, bAlways );
  2229. }
  2230. }
  2231. //-----------------------------------------------------------------------------
  2232. // Purpose: Fetch the default team relationship
  2233. // Input :
  2234. // Output :
  2235. //-----------------------------------------------------------------------------
  2236. Disposition_t CBaseCombatCharacter::GetFactionRelationshipDisposition( int nFaction )
  2237. {
  2238. Assert( m_FactionRelationship != NULL );
  2239. return m_FactionRelationship[ GetFaction() ][ nFaction ].disposition;
  2240. }
  2241. //-----------------------------------------------------------------------------
  2242. // Purpose: Add or Change a class relationship for this entity
  2243. // Input :
  2244. // Output :
  2245. //-----------------------------------------------------------------------------
  2246. void CBaseCombatCharacter::AddClassRelationship ( Class_T class_type, Disposition_t disposition, int priority )
  2247. {
  2248. // First check to see if a relationship has already been declared for this class
  2249. // If so, update it with the new relationship
  2250. for (int i=m_Relationship.Count()-1;i >= 0;i--)
  2251. {
  2252. if (m_Relationship[i].classType == class_type)
  2253. {
  2254. m_Relationship[i].disposition = disposition;
  2255. if ( priority != DEF_RELATIONSHIP_PRIORITY )
  2256. m_Relationship[i].priority = priority;
  2257. return;
  2258. }
  2259. }
  2260. int index = m_Relationship.AddToTail();
  2261. // Add the new class relationship to our relationship table
  2262. m_Relationship[index].classType = class_type;
  2263. m_Relationship[index].entity = NULL;
  2264. m_Relationship[index].faction = FACTION_NONE;
  2265. m_Relationship[index].disposition = disposition;
  2266. m_Relationship[index].priority = ( priority != DEF_RELATIONSHIP_PRIORITY ) ? priority : 0;
  2267. }
  2268. //-----------------------------------------------------------------------------
  2269. // Purpose: Add or Change a entity relationship for this entity
  2270. // Input :
  2271. // Output :
  2272. //-----------------------------------------------------------------------------
  2273. void CBaseCombatCharacter::AddEntityRelationship ( CBaseEntity* pEntity, Disposition_t disposition, int priority )
  2274. {
  2275. // First check to see if a relationship has already been declared for this entity
  2276. // If so, update it with the new relationship
  2277. for (int i=m_Relationship.Count()-1;i >= 0;i--)
  2278. {
  2279. if (m_Relationship[i].entity == pEntity)
  2280. {
  2281. m_Relationship[i].disposition = disposition;
  2282. if ( priority != DEF_RELATIONSHIP_PRIORITY )
  2283. m_Relationship[i].priority = priority;
  2284. return;
  2285. }
  2286. }
  2287. int index = m_Relationship.AddToTail();
  2288. // Add the new class relationship to our relationship table
  2289. m_Relationship[index].classType = CLASS_NONE;
  2290. m_Relationship[index].entity = pEntity;
  2291. m_Relationship[index].faction = FACTION_NONE;
  2292. m_Relationship[index].disposition = disposition;
  2293. m_Relationship[index].priority = ( priority != DEF_RELATIONSHIP_PRIORITY ) ? priority : 0;
  2294. }
  2295. //-----------------------------------------------------------------------------
  2296. // Purpose: Removes an entity relationship from our list
  2297. // Input : *pEntity - Entity with whom the relationship should be ended
  2298. // Output : True is entity was removed, false if it was not found
  2299. //-----------------------------------------------------------------------------
  2300. bool CBaseCombatCharacter::RemoveEntityRelationship( CBaseEntity *pEntity )
  2301. {
  2302. // Find the entity in our list, if it exists
  2303. for ( int i = m_Relationship.Count()-1; i >= 0; i-- )
  2304. {
  2305. if ( m_Relationship[i].entity == pEntity )
  2306. {
  2307. // Done, remove it
  2308. m_Relationship.Remove( i );
  2309. return true;
  2310. }
  2311. }
  2312. return false;
  2313. }
  2314. //-----------------------------------------------------------------------------
  2315. // Purpose:
  2316. // Input :
  2317. // Output :
  2318. //-----------------------------------------------------------------------------
  2319. void CBaseCombatCharacter::AddFactionRelationship(int nFaction, Disposition_t disposition, int priority )
  2320. {
  2321. // First check to see if a relationship has already been declared for this faction
  2322. // If so, update it with the new relationship
  2323. for (int i=m_Relationship.Count()-1;i >= 0;i--)
  2324. {
  2325. if (m_Relationship[i].faction == nFaction)
  2326. {
  2327. m_Relationship[i].disposition = disposition;
  2328. if ( priority != DEF_RELATIONSHIP_PRIORITY )
  2329. m_Relationship[i].priority = priority;
  2330. return;
  2331. }
  2332. }
  2333. int index = m_Relationship.AddToTail();
  2334. // Add the new class relationship to our relationship table
  2335. m_Relationship[index].classType = CLASS_NONE;
  2336. m_Relationship[index].entity = NULL;
  2337. m_Relationship[index].faction = nFaction;
  2338. m_Relationship[index].disposition = disposition;
  2339. m_Relationship[index].priority = ( priority != DEF_RELATIONSHIP_PRIORITY ) ? priority : 0;
  2340. }
  2341. //-----------------------------------------------------------------------------
  2342. // Purpose:
  2343. // Input :
  2344. // Output :
  2345. //-----------------------------------------------------------------------------
  2346. void CBaseCombatCharacter::ChangeFaction( int nNewFaction ) {
  2347. int nOldFaction = m_nFaction;
  2348. if ( ( m_nFaction != FACTION_NONE ) && ( m_aFactions.Count() != 0 ) )
  2349. {
  2350. m_aFactions[ m_nFaction ].FindAndFastRemove( this );
  2351. }
  2352. m_nFaction = nNewFaction;
  2353. if ( m_nFaction != FACTION_NONE )
  2354. {
  2355. if ( !m_aFactions.Count() )
  2356. {
  2357. AllocateDefaultFactionRelationships();
  2358. }
  2359. m_aFactions[ m_nFaction ].AddToTail( this );
  2360. }
  2361. // remove any relationship to entities where the relationship may change due to the faction change
  2362. if ( ( m_FactionRelationship ) && ( m_nFaction != FACTION_NONE ) )
  2363. {
  2364. for(int i = 0; i < m_Relationship.Count(); i++ )
  2365. {
  2366. if ( (CBaseEntity *)m_Relationship[ i ].entity && ( (CBaseEntity *)m_Relationship[ i ].entity )->IsNPC() )
  2367. {
  2368. int nFaction = ( (CBaseEntity *)m_Relationship[ i ].entity )->MyNPCPointer()->GetFaction();
  2369. if ( m_FactionRelationship[ m_nFaction ][ nFaction ].disposition != m_FactionRelationship[ nOldFaction ][ nFaction ].disposition )
  2370. {
  2371. m_Relationship.FastRemove( i );
  2372. i--;
  2373. continue;
  2374. }
  2375. }
  2376. }
  2377. }
  2378. }
  2379. //-----------------------------------------------------------------------------
  2380. // Purpose:
  2381. // Input :
  2382. // Output :
  2383. //-----------------------------------------------------------------------------
  2384. int CBaseCombatCharacter::GetNumFactions( void ) {
  2385. if ( !m_aFactions.Count() )
  2386. {
  2387. AllocateDefaultFactionRelationships();
  2388. }
  2389. return m_aFactions.Count();
  2390. }
  2391. //-----------------------------------------------------------------------------
  2392. // Purpose:
  2393. // Input :
  2394. // Output :
  2395. //-----------------------------------------------------------------------------
  2396. CUtlVector<EHANDLE> *CBaseCombatCharacter::GetEntitiesInFaction( int nFaction ) {
  2397. if ( !m_aFactions.Count() )
  2398. {
  2399. return NULL;
  2400. }
  2401. return &m_aFactions[ nFaction ];
  2402. }
  2403. //-----------------------------------------------------------------------------
  2404. // Allocates default relationships
  2405. //-----------------------------------------------------------------------------
  2406. void CBaseCombatCharacter::AllocateDefaultRelationships( )
  2407. {
  2408. if (!m_DefaultRelationship)
  2409. {
  2410. int iNumClasses = GameRules() ? GameRules()->NumEntityClasses() : LAST_SHARED_ENTITY_CLASS;
  2411. m_DefaultRelationship = new Relationship_t*[iNumClasses];
  2412. for (int i=0; i<iNumClasses; ++i)
  2413. {
  2414. // Be default all relationships are neutral of priority zero
  2415. m_DefaultRelationship[i] = new Relationship_t[iNumClasses];
  2416. }
  2417. }
  2418. }
  2419. //-----------------------------------------------------------------------------
  2420. // Allocates default faction relationships
  2421. //-----------------------------------------------------------------------------
  2422. void CBaseCombatCharacter::AllocateDefaultFactionRelationships( )
  2423. {
  2424. if (!m_FactionRelationship)
  2425. {
  2426. int nNumFactions = GameRules() ? GameRules()->NumFactions() : NUM_SHARED_FACTIONS;
  2427. m_aFactions.SetCount( nNumFactions );
  2428. m_FactionRelationship = new Relationship_t*[nNumFactions];
  2429. for (int i=0; i<nNumFactions; ++i)
  2430. {
  2431. // Be default all relationships are neutral of priority zero
  2432. m_FactionRelationship[i] = new Relationship_t[nNumFactions];
  2433. }
  2434. }
  2435. }
  2436. //-----------------------------------------------------------------------------
  2437. // Purpose:
  2438. // Input :
  2439. // Output :
  2440. //-----------------------------------------------------------------------------
  2441. void CBaseCombatCharacter::SetDefaultRelationship(Class_T nClass, Class_T nClassTarget, Disposition_t nDisposition, int nPriority)
  2442. {
  2443. if (m_DefaultRelationship)
  2444. {
  2445. m_DefaultRelationship[nClass][nClassTarget].disposition = nDisposition;
  2446. m_DefaultRelationship[nClass][nClassTarget].priority = nPriority;
  2447. }
  2448. }
  2449. //-----------------------------------------------------------------------------
  2450. // Purpose:
  2451. // Input :
  2452. // Output :
  2453. //-----------------------------------------------------------------------------
  2454. void CBaseCombatCharacter::SetDefaultFactionRelationship(int nFaction, int nFactionTarget, Disposition_t nDisposition, int nPriority)
  2455. {
  2456. if (!m_FactionRelationship)
  2457. {
  2458. AllocateDefaultFactionRelationships();
  2459. }
  2460. m_FactionRelationship[nFaction][nFactionTarget].disposition = nDisposition;
  2461. m_FactionRelationship[nFaction][nFactionTarget].priority = nPriority;
  2462. }
  2463. //-----------------------------------------------------------------------------
  2464. // Purpose: Fetch the default (ignore ai_relationship changes) relationship
  2465. // Input :
  2466. // Output :
  2467. //-----------------------------------------------------------------------------
  2468. Disposition_t CBaseCombatCharacter::GetDefaultRelationshipDisposition( Class_T nClassTarget )
  2469. {
  2470. Assert( m_DefaultRelationship != NULL );
  2471. return m_DefaultRelationship[Classify()][nClassTarget].disposition;
  2472. }
  2473. //-----------------------------------------------------------------------------
  2474. // Purpose: describes the relationship between two types of NPC.
  2475. // Input :
  2476. // Output :
  2477. //-----------------------------------------------------------------------------
  2478. Relationship_t *CBaseCombatCharacter::FindEntityRelationship( CBaseEntity *pTarget )
  2479. {
  2480. if ( !pTarget )
  2481. {
  2482. static Relationship_t dummy;
  2483. return &dummy;
  2484. }
  2485. // First check for specific relationship with this edict
  2486. int i;
  2487. for (i=0;i<m_Relationship.Count();i++)
  2488. {
  2489. if (pTarget == (CBaseEntity *)m_Relationship[i].entity)
  2490. {
  2491. return &m_Relationship[i];
  2492. }
  2493. }
  2494. if (pTarget->Classify() != CLASS_NONE)
  2495. {
  2496. // Then check for relationship with this edict's class
  2497. for (i=0;i<m_Relationship.Count();i++)
  2498. {
  2499. if (pTarget->Classify() == m_Relationship[i].classType)
  2500. {
  2501. return &m_Relationship[i];
  2502. }
  2503. }
  2504. }
  2505. CBaseCombatCharacter *pBaseCombatCharacter = ToBaseCombatCharacter( pTarget );
  2506. if (pBaseCombatCharacter)
  2507. {
  2508. int nFaction = pBaseCombatCharacter->GetFaction();
  2509. if ( nFaction != FACTION_NONE )
  2510. {
  2511. // Then check for relationship with this edict's faction
  2512. for (i=0;i<m_Relationship.Count();i++)
  2513. {
  2514. if (nFaction == m_Relationship[i].faction)
  2515. {
  2516. return &m_Relationship[i];
  2517. }
  2518. }
  2519. if ( ( m_FactionRelationship ) && ( GetFaction() != FACTION_NONE ) )
  2520. {
  2521. return &m_FactionRelationship[ GetFaction() ][ nFaction ];
  2522. }
  2523. }
  2524. }
  2525. AllocateDefaultRelationships();
  2526. // If none found return the default
  2527. return &m_DefaultRelationship[ Classify() ][ pTarget->Classify() ];
  2528. }
  2529. Disposition_t CBaseCombatCharacter::IRelationType ( CBaseEntity *pTarget )
  2530. {
  2531. if ( pTarget )
  2532. return FindEntityRelationship( pTarget )->disposition;
  2533. return D_NU;
  2534. }
  2535. //-----------------------------------------------------------------------------
  2536. // Purpose: describes the relationship between two types of NPC.
  2537. // Input :
  2538. // Output :
  2539. //-----------------------------------------------------------------------------
  2540. int CBaseCombatCharacter::IRelationPriority( CBaseEntity *pTarget )
  2541. {
  2542. if ( pTarget )
  2543. return FindEntityRelationship( pTarget )->priority;
  2544. return 0;
  2545. }
  2546. //-----------------------------------------------------------------------------
  2547. // Purpose: Get shoot position of BCC at current position/orientation
  2548. // Input :
  2549. // Output :
  2550. //-----------------------------------------------------------------------------
  2551. Vector CBaseCombatCharacter::Weapon_ShootPosition( )
  2552. {
  2553. Vector forward, right, up;
  2554. AngleVectors( GetAbsAngles(), &forward, &right, &up );
  2555. Vector vecSrc = GetAbsOrigin()
  2556. + forward * m_HackedGunPos.y
  2557. + right * m_HackedGunPos.x
  2558. + up * m_HackedGunPos.z;
  2559. return vecSrc;
  2560. }
  2561. //-----------------------------------------------------------------------------
  2562. //-----------------------------------------------------------------------------
  2563. CBaseEntity *CBaseCombatCharacter::FindHealthItem( const Vector &vecPosition, const Vector &range )
  2564. {
  2565. CBaseEntity *list[1024];
  2566. int count = UTIL_EntitiesInBox( list, 1024, vecPosition - range, vecPosition + range, 0 );
  2567. for ( int i = 0; i < count; i++ )
  2568. {
  2569. CItem *pItem = dynamic_cast<CItem *>(list[ i ]);
  2570. if( pItem )
  2571. {
  2572. // Healthkits and healthvials
  2573. if( pItem->ClassMatches( "item_health*" ) && FVisible( pItem ) )
  2574. {
  2575. return pItem;
  2576. }
  2577. }
  2578. }
  2579. return NULL;
  2580. }
  2581. //-----------------------------------------------------------------------------
  2582. // Compares the weapon's center with this character's current origin, so it
  2583. // will not give reliable results for weapons that are visible to the NPC
  2584. // but are upstairs/downstairs, etc.
  2585. //
  2586. // A weapon is said to be on the ground if it is no more than 12 inches above
  2587. // or below the caller's feet.
  2588. //-----------------------------------------------------------------------------
  2589. bool CBaseCombatCharacter::Weapon_IsOnGround( CBaseCombatWeapon *pWeapon )
  2590. {
  2591. if( pWeapon->IsConstrained() )
  2592. {
  2593. // Constrained to a rack.
  2594. return false;
  2595. }
  2596. if( fabs(pWeapon->WorldSpaceCenter().z - GetAbsOrigin().z) >= 12.0f )
  2597. {
  2598. return false;
  2599. }
  2600. return true;
  2601. }
  2602. //-----------------------------------------------------------------------------
  2603. // Purpose:
  2604. // Input : &range -
  2605. // Output : CBaseEntity
  2606. //-----------------------------------------------------------------------------
  2607. CBaseEntity *CBaseCombatCharacter::Weapon_FindUsable( const Vector &range )
  2608. {
  2609. bool bConservative = false;
  2610. #ifdef HL2_DLL
  2611. if( hl2_episodic.GetBool() && !GetActiveWeapon() )
  2612. {
  2613. // Unarmed citizens are conservative in their weapon finding
  2614. if ( Classify() != CLASS_PLAYER_ALLY_VITAL )
  2615. {
  2616. bConservative = true;
  2617. }
  2618. }
  2619. #endif
  2620. CBaseCombatWeapon *weaponList[64];
  2621. CBaseCombatWeapon *pBestWeapon = NULL;
  2622. Vector mins = GetAbsOrigin() - range;
  2623. Vector maxs = GetAbsOrigin() + range;
  2624. int listCount = CBaseCombatWeapon::GetAvailableWeaponsInBox( weaponList, ARRAYSIZE(weaponList), mins, maxs );
  2625. float fBestDist = 1e6;
  2626. for ( int i = 0; i < listCount; i++ )
  2627. {
  2628. // Make sure not moving (ie flying through the air)
  2629. Vector velocity;
  2630. CBaseCombatWeapon *pWeapon = weaponList[i];
  2631. Assert(pWeapon);
  2632. pWeapon->GetVelocity( &velocity, NULL );
  2633. if ( pWeapon->CanBePickedUpByNPCs() == false )
  2634. continue;
  2635. if ( velocity.LengthSqr() > 1 || !Weapon_CanUse(pWeapon) )
  2636. continue;
  2637. if ( pWeapon->IsLocked(this) )
  2638. continue;
  2639. if ( GetActiveWeapon() )
  2640. {
  2641. // Already armed. Would picking up this weapon improve my situation?
  2642. if( GetActiveWeapon()->m_iClassname == pWeapon->m_iClassname )
  2643. {
  2644. // No, I'm already using this type of weapon.
  2645. continue;
  2646. }
  2647. if( FClassnameIs( pWeapon, "weapon_pistol" ) )
  2648. {
  2649. // No, it's a pistol.
  2650. continue;
  2651. }
  2652. }
  2653. float fCurDist = (pWeapon->GetLocalOrigin() - GetLocalOrigin()).Length();
  2654. // Give any reserved weapon a bonus
  2655. if( pWeapon->HasSpawnFlags( SF_WEAPON_NO_PLAYER_PICKUP ) )
  2656. {
  2657. fCurDist *= 0.5f;
  2658. }
  2659. if ( pBestWeapon )
  2660. {
  2661. // UNDONE: Better heuristic needed here
  2662. // Need to pick by power of weapons
  2663. // Don't want to pick a weapon right next to a NPC!
  2664. // Give the AR2 a bonus to be selected by making it seem closer.
  2665. if( FClassnameIs( pWeapon, "weapon_ar2" ) )
  2666. {
  2667. fCurDist *= 0.5;
  2668. }
  2669. // choose the last range attack weapon you find or the first available other weapon
  2670. if ( ! (pWeapon->CapabilitiesGet() & bits_CAP_RANGE_ATTACK_GROUP) )
  2671. {
  2672. continue;
  2673. }
  2674. else if (fCurDist > fBestDist )
  2675. {
  2676. continue;
  2677. }
  2678. }
  2679. if( Weapon_IsOnGround(pWeapon) )
  2680. {
  2681. // Weapon appears to be lying on the ground. Make sure this weapon is reachable
  2682. // by tracing out a human sized hull just above the weapon. If not, reject
  2683. trace_t tr;
  2684. Vector vAboveWeapon = pWeapon->GetAbsOrigin();
  2685. UTIL_TraceEntity( this, vAboveWeapon, vAboveWeapon + Vector( 0, 0, 1 ), MASK_SOLID, pWeapon, COLLISION_GROUP_NONE, &tr );
  2686. if ( tr.startsolid || (tr.fraction < 1.0) )
  2687. continue;
  2688. }
  2689. else if( bConservative )
  2690. {
  2691. // Skip it.
  2692. continue;
  2693. }
  2694. if( FVisible(pWeapon) )
  2695. {
  2696. fBestDist = fCurDist;
  2697. pBestWeapon = pWeapon;
  2698. }
  2699. }
  2700. if( pBestWeapon )
  2701. {
  2702. // Lock this weapon for my exclusive use. Lock it for just a couple of seconds because my AI
  2703. // might not actually be able to go pick it up right now.
  2704. pBestWeapon->Lock( 2.0, this );
  2705. }
  2706. return pBestWeapon;
  2707. }
  2708. //-----------------------------------------------------------------------------
  2709. // Purpose: Give the player some ammo.
  2710. // Input : iCount - Amount of ammo to give.
  2711. // iAmmoIndex - Index of the ammo into the AmmoInfoArray
  2712. // iMax - Max carrying capability of the player
  2713. // Output : Amount of ammo actually given
  2714. //-----------------------------------------------------------------------------
  2715. int CBaseCombatCharacter::GiveAmmo( int iCount, int iAmmoIndex, bool bSuppressSound)
  2716. {
  2717. if (iCount <= 0)
  2718. return 0;
  2719. if ( !g_pGameRules->CanHaveAmmo( this, iAmmoIndex ) )
  2720. {
  2721. // game rules say I can't have any more of this ammo type.
  2722. return 0;
  2723. }
  2724. if ( iAmmoIndex < 0 || iAmmoIndex >= MAX_AMMO_SLOTS )
  2725. return 0;
  2726. int iMax = GetAmmoDef()->MaxCarry(iAmmoIndex, this);
  2727. int iAdd = MIN( iCount, iMax - m_iAmmo[iAmmoIndex] );
  2728. if ( iAdd < 1 )
  2729. return 0;
  2730. // Ammo pickup sound
  2731. if ( !bSuppressSound )
  2732. {
  2733. EmitSound( "BaseCombatCharacter.AmmoPickup" );
  2734. }
  2735. m_iAmmo.Set( iAmmoIndex, m_iAmmo[iAmmoIndex] + iAdd );
  2736. return iAdd;
  2737. }
  2738. //-----------------------------------------------------------------------------
  2739. // Purpose: Give the player some ammo.
  2740. //-----------------------------------------------------------------------------
  2741. int CBaseCombatCharacter::GiveAmmo( int iCount, const char *szName, bool bSuppressSound )
  2742. {
  2743. int iAmmoType = GetAmmoDef()->Index(szName);
  2744. if (iAmmoType == -1)
  2745. {
  2746. Msg("ERROR: Attempting to give unknown ammo type (%s)\n",szName);
  2747. return 0;
  2748. }
  2749. return GiveAmmo( iCount, iAmmoType, bSuppressSound );
  2750. }
  2751. ConVar phys_stressbodyweights( "phys_stressbodyweights", "5.0" );
  2752. // disabled stress damage to save CPU, none of the NPCs really use it and the player has a different codepath
  2753. #if !defined( PORTAL2 )
  2754. void CBaseCombatCharacter::VPhysicsUpdate( IPhysicsObject *pPhysics )
  2755. {
  2756. ApplyStressDamage( pPhysics, false );
  2757. BaseClass::VPhysicsUpdate( pPhysics );
  2758. }
  2759. #endif
  2760. float CBaseCombatCharacter::CalculatePhysicsStressDamage( vphysics_objectstress_t *pStressOut, IPhysicsObject *pPhysics )
  2761. {
  2762. // stress damage hack.
  2763. float mass = pPhysics->GetMass();
  2764. CalculateObjectStress( pPhysics, this, pStressOut );
  2765. float stress = (pStressOut->receivedStress * m_impactEnergyScale) / mass;
  2766. // Make sure the stress isn't from being stuck inside some static object.
  2767. // how many times your own weight can you hold up?
  2768. if ( pStressOut->hasNonStaticStress && stress > phys_stressbodyweights.GetFloat() )
  2769. {
  2770. // if stuck, don't do this!
  2771. if ( !(pPhysics->GetGameFlags() & FVPHYSICS_PENETRATING) )
  2772. return 200;
  2773. }
  2774. return 0;
  2775. }
  2776. void CBaseCombatCharacter::ApplyStressDamage( IPhysicsObject *pPhysics, bool bRequireLargeObject )
  2777. {
  2778. #ifdef HL2_DLL
  2779. if( Classify() == CLASS_PLAYER_ALLY || Classify() == CLASS_PLAYER_ALLY_VITAL )
  2780. {
  2781. // Bypass stress completely for allies and vitals.
  2782. if( hl2_episodic.GetBool() )
  2783. return;
  2784. }
  2785. #endif//HL2_DLL
  2786. vphysics_objectstress_t stressOut;
  2787. float damage = CalculatePhysicsStressDamage( &stressOut, pPhysics );
  2788. if ( damage > 0 )
  2789. {
  2790. if ( bRequireLargeObject && !stressOut.hasLargeObjectContact )
  2791. return;
  2792. //Msg("Stress! %.2f / %.2f\n", stressOut.exertedStress, stressOut.receivedStress );
  2793. CTakeDamageInfo dmgInfo( GetWorldEntity(), GetWorldEntity(), vec3_origin, vec3_origin, damage, DMG_CRUSH );
  2794. dmgInfo.SetDamageForce( Vector( 0, 0, -stressOut.receivedStress * sv_gravity.GetFloat() * gpGlobals->frametime ) );
  2795. dmgInfo.SetDamagePosition( GetAbsOrigin() );
  2796. TakeDamage( dmgInfo );
  2797. }
  2798. }
  2799. //-----------------------------------------------------------------------------
  2800. // Purpose:
  2801. // Output : const impactdamagetable_t
  2802. //-----------------------------------------------------------------------------
  2803. const impactdamagetable_t &CBaseCombatCharacter::GetPhysicsImpactDamageTable( void )
  2804. {
  2805. return gDefaultNPCImpactDamageTable;
  2806. }
  2807. // how much to amplify impact forces
  2808. // This is to account for the ragdolls responding differently than
  2809. // the shadow objects. Also this makes the impacts more dramatic.
  2810. ConVar phys_impactforcescale( "phys_impactforcescale", "1.0" );
  2811. ConVar phys_upimpactforcescale( "phys_upimpactforcescale", "0.375" );
  2812. void CBaseCombatCharacter::VPhysicsShadowCollision( int index, gamevcollisionevent_t *pEvent )
  2813. {
  2814. int otherIndex = !index;
  2815. CBaseEntity *pOther = pEvent->pEntities[otherIndex];
  2816. IPhysicsObject *pOtherPhysics = pEvent->pObjects[otherIndex];
  2817. if ( !pOther )
  2818. return;
  2819. // Ragdolls are marked as dying.
  2820. if ( pOther->m_lifeState == LIFE_DYING )
  2821. return;
  2822. if ( pOther->GetMoveType() != MOVETYPE_VPHYSICS )
  2823. return;
  2824. if ( !pOtherPhysics->IsMoveable() )
  2825. return;
  2826. if ( pOther == GetGroundEntity() )
  2827. return;
  2828. // Player can't damage himself if he's was physics attacker *on this frame*
  2829. // which can occur owing to ordering issues it appears.
  2830. float flOtherAttackerTime = 0.0f;
  2831. #if defined( HL2_DLL )
  2832. if ( HL2GameRules()->MegaPhyscannonActive() == true )
  2833. {
  2834. flOtherAttackerTime = 1.0f;
  2835. }
  2836. #endif
  2837. if ( this == pOther->HasPhysicsAttacker( flOtherAttackerTime ) )
  2838. return;
  2839. int damageType = 0;
  2840. float damage = 0;
  2841. damage = CalculatePhysicsImpactDamage( index, pEvent, GetPhysicsImpactDamageTable(), m_impactEnergyScale, false, damageType );
  2842. if ( damage <= 0 )
  2843. return;
  2844. // NOTE: We really need some rotational motion for some of these collisions.
  2845. // REVISIT: Maybe resolve this collision on death with a different (not approximately infinite like AABB tensor)
  2846. // inertia tensor to get torque?
  2847. Vector damageForce = pEvent->postVelocity[index] * pEvent->pObjects[index]->GetMass() * phys_impactforcescale.GetFloat();
  2848. IServerVehicle *vehicleOther = pOther->GetServerVehicle();
  2849. if ( vehicleOther )
  2850. {
  2851. CBaseCombatCharacter *pPassenger = vehicleOther->GetPassenger();
  2852. if ( pPassenger != NULL )
  2853. {
  2854. // flag as vehicle damage
  2855. damageType |= DMG_VEHICLE;
  2856. // if hit by vehicle driven by player, add some upward velocity to force
  2857. float len = damageForce.Length();
  2858. damageForce.z += len*phys_upimpactforcescale.GetFloat();
  2859. //Msg("Force %.1f / %.1f\n", damageForce.Length(), damageForce.z );
  2860. if ( pPassenger->IsPlayer() )
  2861. {
  2862. CBasePlayer *pPlayer = assert_cast<CBasePlayer *>(pPassenger);
  2863. if( damage >= GetMaxHealth() )
  2864. {
  2865. pPlayer->RumbleEffect( RUMBLE_357, 0, RUMBLE_FLAG_RESTART );
  2866. }
  2867. else
  2868. {
  2869. pPlayer->RumbleEffect( RUMBLE_PISTOL, 0, RUMBLE_FLAG_RESTART );
  2870. }
  2871. }
  2872. }
  2873. }
  2874. Vector damagePos;
  2875. pEvent->pInternalData->GetContactPoint( damagePos );
  2876. CTakeDamageInfo dmgInfo( pOther, pOther, damageForce, damagePos, damage, damageType );
  2877. // FIXME: is there a better way for physics objects to keep track of what root entity responsible for them moving?
  2878. CBasePlayer *pPlayer = pOther->HasPhysicsAttacker( 1.0 );
  2879. if (pPlayer)
  2880. {
  2881. dmgInfo.SetAttacker( pPlayer );
  2882. }
  2883. // UNDONE: Find one near damagePos?
  2884. m_nForceBone = 0;
  2885. PhysCallbackDamage( this, dmgInfo, *pEvent, index );
  2886. }
  2887. //-----------------------------------------------------------------------------
  2888. // Purpose: this entity is exploding, or otherwise needs to inflict damage upon
  2889. // entities within a certain range. only damage ents that can clearly
  2890. // be seen by the explosion!
  2891. // Input :
  2892. // Output :
  2893. //-----------------------------------------------------------------------------
  2894. void RadiusDamage( const CTakeDamageInfo &info, const Vector &vecSrc, float flRadius, int iClassIgnore, CBaseEntity *pEntityIgnore )
  2895. {
  2896. // NOTE: I did this this way so I wouldn't have to change a whole bunch of
  2897. // code unnecessarily. We need TF2 specific rules for RadiusDamage, so I moved
  2898. // the implementation of radius damage into gamerules. All existing code calls
  2899. // this method, which calls the game rules method
  2900. g_pGameRules->RadiusDamage( info, vecSrc, flRadius, iClassIgnore, pEntityIgnore );
  2901. // Let the world know if this was an explosion.
  2902. if( info.GetDamageType() & DMG_BLAST )
  2903. {
  2904. // Even the tiniest explosion gets attention. Don't let the radius
  2905. // be less than 128 units.
  2906. float soundRadius = MAX( 128.0f, flRadius * 1.5 );
  2907. CSoundEnt::InsertSound( SOUND_COMBAT | SOUND_CONTEXT_EXPLOSION, vecSrc, soundRadius, 0.25, info.GetInflictor() );
  2908. }
  2909. }
  2910. //-----------------------------------------------------------------------------
  2911. // Purpose: Change active weapon and notify derived classes
  2912. //
  2913. //-----------------------------------------------------------------------------
  2914. void CBaseCombatCharacter::SetActiveWeapon( CBaseCombatWeapon *pNewWeapon )
  2915. {
  2916. CBaseCombatWeapon *pOldWeapon = m_hActiveWeapon;
  2917. if ( pNewWeapon != pOldWeapon )
  2918. {
  2919. m_hActiveWeapon = pNewWeapon;
  2920. OnChangeActiveWeapon( pOldWeapon, pNewWeapon );
  2921. }
  2922. }
  2923. //-----------------------------------------------------------------------------
  2924. // Consider the weapon's built-in accuracy, this character's proficiency with
  2925. // the weapon, and the status of the target. Use this information to determine
  2926. // how accurately to shoot at the target.
  2927. //-----------------------------------------------------------------------------
  2928. Vector CBaseCombatCharacter::GetAttackSpread( CBaseCombatWeapon *pWeapon, CBaseEntity *pTarget )
  2929. {
  2930. if ( pWeapon )
  2931. return pWeapon->GetBulletSpread(GetCurrentWeaponProficiency());
  2932. return VECTOR_CONE_15DEGREES;
  2933. }
  2934. //-----------------------------------------------------------------------------
  2935. float CBaseCombatCharacter::GetSpreadBias( CBaseCombatWeapon *pWeapon, CBaseEntity *pTarget )
  2936. {
  2937. if ( pWeapon )
  2938. return pWeapon->GetSpreadBias(GetCurrentWeaponProficiency());
  2939. return 1.0;
  2940. }
  2941. //-----------------------------------------------------------------------------
  2942. // Assume everyone is average with every weapon. Override this to make exceptions.
  2943. //-----------------------------------------------------------------------------
  2944. WeaponProficiency_t CBaseCombatCharacter::CalcWeaponProficiency( CBaseCombatWeapon *pWeapon )
  2945. {
  2946. return WEAPON_PROFICIENCY_AVERAGE;
  2947. }
  2948. //-----------------------------------------------------------------------------
  2949. // Purpose:
  2950. //-----------------------------------------------------------------------------
  2951. #define MAX_MISS_CANDIDATES 16
  2952. CBaseEntity *CBaseCombatCharacter::FindMissTarget( void )
  2953. {
  2954. CBaseEntity *pMissCandidates[ MAX_MISS_CANDIDATES ];
  2955. int numMissCandidates = 0;
  2956. CBasePlayer *pPlayer = UTIL_GetLocalPlayer();
  2957. CBaseEntity *pEnts[256];
  2958. Vector radius( 100, 100, 100);
  2959. Vector vecSource = GetAbsOrigin();
  2960. int numEnts = UTIL_EntitiesInBox( pEnts, 256, vecSource-radius, vecSource+radius, 0 );
  2961. for ( int i = 0; i < numEnts; i++ )
  2962. {
  2963. if ( pEnts[i] == NULL )
  2964. continue;
  2965. // New rule for this system. Don't shoot what the player won't see.
  2966. if ( pPlayer && !pPlayer->FInViewCone( pEnts[ i ] ) )
  2967. continue;
  2968. if ( numMissCandidates >= MAX_MISS_CANDIDATES )
  2969. break;
  2970. //See if it's a good target candidate
  2971. if ( FClassnameIs( pEnts[i], "prop_dynamic" ) ||
  2972. FClassnameIs( pEnts[i], "prop_physics" ) ||
  2973. FClassnameIs( pEnts[i], "physics_prop" ) )
  2974. {
  2975. pMissCandidates[numMissCandidates++] = pEnts[i];
  2976. continue;
  2977. }
  2978. }
  2979. if( numMissCandidates == 0 )
  2980. return NULL;
  2981. return pMissCandidates[ random->RandomInt( 0, numMissCandidates - 1 ) ];
  2982. }
  2983. //-----------------------------------------------------------------------------
  2984. //-----------------------------------------------------------------------------
  2985. bool CBaseCombatCharacter::ShouldShootMissTarget( CBaseCombatCharacter *pAttacker )
  2986. {
  2987. // Don't shoot at NPC's right now.
  2988. return false;
  2989. }
  2990. //-----------------------------------------------------------------------------
  2991. //-----------------------------------------------------------------------------
  2992. void CBaseCombatCharacter::InputKilledNPC( inputdata_t &inputdata )
  2993. {
  2994. OnKilledNPC( inputdata.pActivator ? inputdata.pActivator->MyCombatCharacterPointer() : NULL );
  2995. }
  2996. //-----------------------------------------------------------------------------
  2997. // Purpose: Overload our muzzle flash and send it to any actively held weapon
  2998. //-----------------------------------------------------------------------------
  2999. void CBaseCombatCharacter::DoMuzzleFlash()
  3000. {
  3001. // Our weapon takes our muzzle flash command
  3002. CBaseCombatWeapon *pWeapon = GetActiveWeapon();
  3003. if ( pWeapon )
  3004. {
  3005. pWeapon->DoMuzzleFlash();
  3006. //NOTENOTE: We do not chain to the base here
  3007. }
  3008. else
  3009. {
  3010. BaseClass::DoMuzzleFlash();
  3011. }
  3012. }
  3013. //-----------------------------------------------------------------------------
  3014. // Purpose: track the last trigger_fog touched by this character
  3015. //-----------------------------------------------------------------------------
  3016. void CBaseCombatCharacter::OnFogTriggerStartTouch( CBaseEntity *fogTrigger )
  3017. {
  3018. m_hTriggerFogList.AddToHead( fogTrigger );
  3019. }
  3020. //-----------------------------------------------------------------------------
  3021. // Purpose: track the last trigger_fog touched by this character
  3022. //-----------------------------------------------------------------------------
  3023. void CBaseCombatCharacter::OnFogTriggerEndTouch( CBaseEntity *fogTrigger )
  3024. {
  3025. m_hTriggerFogList.FindAndRemove( fogTrigger );
  3026. }
  3027. //-----------------------------------------------------------------------------
  3028. // Purpose: track the last trigger_fog touched by this character
  3029. //-----------------------------------------------------------------------------
  3030. CBaseEntity *CBaseCombatCharacter::GetFogTrigger( void )
  3031. {
  3032. float bestDist = 999999.0f;
  3033. CBaseEntity *bestTrigger = NULL;
  3034. for ( int i=0; i<m_hTriggerFogList.Count(); ++i )
  3035. {
  3036. CBaseEntity *fogTrigger = m_hTriggerFogList[i];
  3037. if ( fogTrigger != NULL )
  3038. {
  3039. float dist = WorldSpaceCenter().DistTo( fogTrigger->WorldSpaceCenter() );
  3040. if ( dist < bestDist )
  3041. {
  3042. bestDist = dist;
  3043. bestTrigger = fogTrigger;
  3044. }
  3045. }
  3046. }
  3047. if ( bestTrigger )
  3048. {
  3049. m_hLastFogTrigger = bestTrigger;
  3050. }
  3051. return m_hLastFogTrigger;
  3052. }
  3053. //-----------------------------------------------------------------------------
  3054. // Purpose: return true if given target cant be seen because of fog
  3055. //-----------------------------------------------------------------------------
  3056. bool CBaseCombatCharacter::IsHiddenByFog( const Vector &target ) const
  3057. {
  3058. float range = EyePosition().DistTo( target );
  3059. return IsHiddenByFog( range );
  3060. }
  3061. //-----------------------------------------------------------------------------
  3062. // Purpose: return true if given target cant be seen because of fog
  3063. //-----------------------------------------------------------------------------
  3064. bool CBaseCombatCharacter::IsHiddenByFog( CBaseEntity *target ) const
  3065. {
  3066. if ( !target )
  3067. return false;
  3068. float range = EyePosition().DistTo( target->WorldSpaceCenter() );
  3069. return IsHiddenByFog( range );
  3070. }
  3071. //-----------------------------------------------------------------------------
  3072. // Purpose: return true if given target cant be seen because of fog
  3073. //-----------------------------------------------------------------------------
  3074. bool CBaseCombatCharacter::IsHiddenByFog( float range ) const
  3075. {
  3076. if ( GetFogObscuredRatio( range ) >= 1.0f )
  3077. return true;
  3078. return false;
  3079. }
  3080. //-----------------------------------------------------------------------------
  3081. // Purpose: return 0-1 ratio where zero is not obscured, and 1 is completely obscured
  3082. //-----------------------------------------------------------------------------
  3083. float CBaseCombatCharacter::GetFogObscuredRatio( const Vector &target ) const
  3084. {
  3085. float range = EyePosition().DistTo( target );
  3086. return GetFogObscuredRatio( range );
  3087. }
  3088. //-----------------------------------------------------------------------------
  3089. // Purpose: return 0-1 ratio where zero is not obscured, and 1 is completely obscured
  3090. //-----------------------------------------------------------------------------
  3091. float CBaseCombatCharacter::GetFogObscuredRatio( CBaseEntity *target ) const
  3092. {
  3093. if ( !target )
  3094. return false;
  3095. float range = EyePosition().DistTo( target->WorldSpaceCenter() );
  3096. return GetFogObscuredRatio( range );
  3097. }
  3098. //-----------------------------------------------------------------------------
  3099. // Purpose: return 0-1 ratio where zero is not obscured, and 1 is completely obscured
  3100. //-----------------------------------------------------------------------------
  3101. float CBaseCombatCharacter::GetFogObscuredRatio( float range ) const
  3102. {
  3103. fogparams_t fog;
  3104. GetFogParams( &fog );
  3105. if ( !fog.enable )
  3106. return 0.0f;
  3107. if ( range <= fog.start )
  3108. return 0.0f;
  3109. if ( range >= fog.end )
  3110. return 1.0f;
  3111. float ratio = (range - fog.start) / (fog.end - fog.start);
  3112. ratio = Min( ratio, fog.maxdensity.Get() );
  3113. return ratio;
  3114. }
  3115. //-----------------------------------------------------------------------------
  3116. // Purpose: return the current fog parameters
  3117. //-----------------------------------------------------------------------------
  3118. bool CBaseCombatCharacter::GetFogParams( fogparams_t *fog ) const
  3119. {
  3120. if ( !fog )
  3121. return false;
  3122. return GetWorldFogParams( const_cast< CBaseCombatCharacter * >( this ), *fog );
  3123. }
  3124. //-----------------------------------------------------------------------------
  3125. // Purpose: Invoke this to update our last known nav area
  3126. // (since there is no think method chained to CBaseCombatCharacter)
  3127. //-----------------------------------------------------------------------------
  3128. void CBaseCombatCharacter::UpdateLastKnownArea( void )
  3129. {
  3130. #if !defined(CSTRIKE_DLL)
  3131. VPROF_BUDGET( "CBaseCombatCharacter::UpdateLastKnownArea", "NextBot" );
  3132. if ( TheNavMesh->IsGenerating() )
  3133. {
  3134. ClearLastKnownArea();
  3135. return;
  3136. }
  3137. /*
  3138. if ( z_last_area_update_tolerance.GetFloat() > 0.0f )
  3139. {
  3140. // skip this test if we're not standing on the world (ie: elevators that move us)
  3141. if ( GetGroundEntity() == NULL || GetGroundEntity()->IsWorld() )
  3142. {
  3143. if ( m_lastNavArea && m_NavAreaUpdateMonitor.IsMarkSet() && !m_NavAreaUpdateMonitor.TargetMoved( this ) )
  3144. return;
  3145. m_NavAreaUpdateMonitor.SetMark( this, z_last_area_update_tolerance.GetFloat() );
  3146. }
  3147. }
  3148. */
  3149. // find the area we are directly standing in
  3150. CNavArea *area = TheNavMesh->GetNearestNavArea( this, GETNAVAREA_CHECK_GROUND | GETNAVAREA_CHECK_LOS, 50.0f );
  3151. if ( !area )
  3152. return;
  3153. // make sure we can actually use this area - if not, consider ourselves off the mesh
  3154. if ( !IsAreaTraversable( area ) )
  3155. return;
  3156. if ( area != m_lastNavArea )
  3157. {
  3158. // player entered a new nav area
  3159. if ( m_lastNavArea && m_registeredNavTeam != TEAM_INVALID )
  3160. {
  3161. m_lastNavArea->DecrementPlayerCount( m_registeredNavTeam, entindex() );
  3162. m_lastNavArea->OnExit( this, area );
  3163. }
  3164. m_registeredNavTeam = GetTeamNumber();
  3165. if ( m_registeredNavTeam != TEAM_INVALID )
  3166. {
  3167. area->IncrementPlayerCount( m_registeredNavTeam, entindex() );
  3168. area->OnEnter( this, m_lastNavArea );
  3169. }
  3170. OnNavAreaChanged( area, m_lastNavArea );
  3171. m_lastNavArea = area;
  3172. }
  3173. #endif
  3174. }
  3175. //-----------------------------------------------------------------------------
  3176. // Purpose: Return true if we can use (walk through) the given area
  3177. //-----------------------------------------------------------------------------
  3178. bool CBaseCombatCharacter::IsAreaTraversable( const CNavArea *area ) const
  3179. {
  3180. return area ? !area->IsBlocked( GetTeamNumber() ) : false;
  3181. }
  3182. //-----------------------------------------------------------------------------
  3183. // Purpose: Leaving the nav mesh
  3184. //-----------------------------------------------------------------------------
  3185. void CBaseCombatCharacter::ClearLastKnownArea( void )
  3186. {
  3187. OnNavAreaChanged( NULL, m_lastNavArea );
  3188. if ( m_lastNavArea )
  3189. {
  3190. if ( m_registeredNavTeam != TEAM_INVALID )
  3191. {
  3192. m_lastNavArea->DecrementPlayerCount( m_registeredNavTeam, entindex() );
  3193. m_lastNavArea->OnExit( this, NULL );
  3194. m_registeredNavTeam = TEAM_INVALID;
  3195. }
  3196. m_lastNavArea = NULL;
  3197. }
  3198. }
  3199. //-----------------------------------------------------------------------------
  3200. // Purpose: Handling editor removing the area we're standing upon
  3201. //-----------------------------------------------------------------------------
  3202. void CBaseCombatCharacter::OnNavAreaRemoved( CNavArea *removedArea )
  3203. {
  3204. if ( m_lastNavArea == removedArea )
  3205. {
  3206. ClearLastKnownArea();
  3207. }
  3208. }
  3209. //-----------------------------------------------------------------------------
  3210. // Purpose: Changing team, maintain associated data
  3211. //-----------------------------------------------------------------------------
  3212. void CBaseCombatCharacter::ChangeTeam( int iTeamNum )
  3213. {
  3214. // old team member no longer in the nav mesh
  3215. ClearLastKnownArea();
  3216. BaseClass::ChangeTeam( iTeamNum );
  3217. }
  3218. //-----------------------------------------------------------------------------
  3219. // Return true if we have ever been injured by a member of the given team
  3220. //-----------------------------------------------------------------------------
  3221. bool CBaseCombatCharacter::HasEverBeenInjured( int team /*= TEAM_ANY */ ) const
  3222. {
  3223. if ( team == TEAM_ANY )
  3224. {
  3225. return ( m_hasBeenInjured == 0 ) ? false : true;
  3226. }
  3227. int teamMask = 1 << team;
  3228. if ( m_hasBeenInjured & teamMask )
  3229. {
  3230. return true;
  3231. }
  3232. return false;
  3233. }
  3234. //-----------------------------------------------------------------------------
  3235. // Return time since we were hurt by a member of the given team
  3236. //-----------------------------------------------------------------------------
  3237. float CBaseCombatCharacter::GetTimeSinceLastInjury( int team /*= TEAM_ANY */ ) const
  3238. {
  3239. const float never = 999999999999.9f;
  3240. if ( team == TEAM_ANY )
  3241. {
  3242. float time = never;
  3243. // find most recent injury time
  3244. for( int i=0; i<MAX_DAMAGE_TEAMS; ++i )
  3245. {
  3246. if ( m_damageHistory[i].team != TEAM_INVALID )
  3247. {
  3248. if ( m_damageHistory[i].interval.GetElapsedTime() < time )
  3249. {
  3250. time = m_damageHistory[i].interval.GetElapsedTime();
  3251. }
  3252. }
  3253. }
  3254. return time;
  3255. }
  3256. else
  3257. {
  3258. for( int i=0; i<MAX_DAMAGE_TEAMS; ++i )
  3259. {
  3260. if ( m_damageHistory[i].team == team )
  3261. {
  3262. return m_damageHistory[i].interval.GetElapsedTime();
  3263. }
  3264. }
  3265. }
  3266. return never;
  3267. }