Team Fortress 2 Source Code as on 22/4/2020
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.

3124 lines
107 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose: Base NPC character with AI
  4. //
  5. //=============================================================================//
  6. #ifndef AI_BASENPC_H
  7. #define AI_BASENPC_H
  8. #ifdef _WIN32
  9. #pragma once
  10. #endif
  11. #include "simtimer.h"
  12. #include "basecombatcharacter.h"
  13. #include "ai_debug.h"
  14. #include "ai_default.h"
  15. #include "ai_schedule.h"
  16. #include "ai_condition.h"
  17. #include "ai_component.h"
  18. #include "ai_task.h"
  19. #include "ai_movetypes.h"
  20. #include "ai_navtype.h"
  21. #include "ai_namespaces.h"
  22. #include "ai_npcstate.h"
  23. #include "ai_hull.h"
  24. #include "ai_utils.h"
  25. #include "ai_moveshoot.h"
  26. #include "entityoutput.h"
  27. #include "utlvector.h"
  28. #include "activitylist.h"
  29. #include "bitstring.h"
  30. #include "ai_basenpc.h"
  31. #include "ai_navgoaltype.h" //GoalType_t enum
  32. #include "eventlist.h"
  33. #include "soundent.h"
  34. #include "ai_navigator.h"
  35. #include "tier1/functors.h"
  36. #define PLAYER_SQUADNAME "player_squad"
  37. class CAI_Schedule;
  38. class CAI_Network;
  39. class CAI_Route;
  40. class CAI_Hint;
  41. class CAI_Node;
  42. class CAI_Navigator;
  43. class CAI_Pathfinder;
  44. class CAI_Senses;
  45. class CAI_Enemies;
  46. class CAI_Squad;
  47. class CAI_Expresser;
  48. class CAI_BehaviorBase;
  49. class CAI_GoalEntity;
  50. class CAI_Motor;
  51. class CAI_MoveProbe;
  52. class CAI_LocalNavigator;
  53. class CAI_TacticalServices;
  54. class CVarBitVec;
  55. class CAI_ScriptedSequence;
  56. class CSceneEntity;
  57. class CBaseGrenade;
  58. class CBaseDoor;
  59. class CBasePropDoor;
  60. struct AI_Waypoint_t;
  61. class AI_Response;
  62. class CBaseFilter;
  63. typedef CBitVec<MAX_CONDITIONS> CAI_ScheduleBits;
  64. // Used to control optimizations mostly dealing with pathfinding for NPCs
  65. extern ConVar ai_strong_optimizations;
  66. extern bool AIStrongOpt( void );
  67. // AI_MONITOR_FOR_OSCILLATION defaults to OFF. If you build with this ON, you can flag
  68. // NPC's and monitor them to detect oscillations in their schedule (circular logic and conditions bugs)
  69. // DO NOT SHIP WITH THIS ON!
  70. #undef AI_MONITOR_FOR_OSCILLATION
  71. //=============================================================================
  72. //
  73. // Constants & enumerations
  74. //
  75. //=============================================================================
  76. #define TURRET_CLOSE_RANGE 200
  77. #define TURRET_MEDIUM_RANGE 500
  78. #define COMMAND_GOAL_TOLERANCE 48 // 48 inches.
  79. #define TIME_CARE_ABOUT_DAMAGE 3.0
  80. #define ITEM_PICKUP_TOLERANCE 48.0f
  81. // Max's of the box used to search for a weapon to pick up. 45x45x~8 ft.
  82. #define WEAPON_SEARCH_DELTA Vector( 540, 540, 100 )
  83. enum Interruptability_t
  84. {
  85. GENERAL_INTERRUPTABILITY,
  86. DAMAGEORDEATH_INTERRUPTABILITY,
  87. DEATH_INTERRUPTABILITY
  88. };
  89. //-------------------------------------
  90. // Memory
  91. //-------------------------------------
  92. #define MEMORY_CLEAR 0
  93. #define bits_MEMORY_PROVOKED ( 1 << 0 )// right now only used for houndeyes.
  94. #define bits_MEMORY_INCOVER ( 1 << 1 )// npc knows it is in a covered position.
  95. #define bits_MEMORY_SUSPICIOUS ( 1 << 2 )// Ally is suspicious of the player, and will move to provoked more easily
  96. #define bits_MEMORY_TASK_EXPENSIVE ( 1 << 3 )// NPC has completed a task which is considered costly, so don't do another task this frame
  97. //#define bits_MEMORY_ ( 1 << 4 )
  98. #define bits_MEMORY_PATH_FAILED ( 1 << 5 )// Failed to find a path
  99. #define bits_MEMORY_FLINCHED ( 1 << 6 )// Has already flinched
  100. //#define bits_MEMORY_ ( 1 << 7 )
  101. #define bits_MEMORY_TOURGUIDE ( 1 << 8 )// I have been acting as a tourguide.
  102. //#define bits_MEMORY_ ( 1 << 9 )//
  103. #define bits_MEMORY_LOCKED_HINT ( 1 << 10 )//
  104. //#define bits_MEMORY_ ( 1 << 12 )
  105. #define bits_MEMORY_TURNING ( 1 << 13 )// Turning, don't interrupt me.
  106. #define bits_MEMORY_TURNHACK ( 1 << 14 )
  107. #define bits_MEMORY_HAD_ENEMY ( 1 << 15 )// Had an enemy
  108. #define bits_MEMORY_HAD_PLAYER ( 1 << 16 )// Had player
  109. #define bits_MEMORY_HAD_LOS ( 1 << 17 )// Had LOS to enemy
  110. #define bits_MEMORY_MOVED_FROM_SPAWN ( 1 << 18 )// Has moved since spawning.
  111. #define bits_MEMORY_CUSTOM4 ( 1 << 28 ) // NPC-specific memory
  112. #define bits_MEMORY_CUSTOM3 ( 1 << 29 ) // NPC-specific memory
  113. #define bits_MEMORY_CUSTOM2 ( 1 << 30 ) // NPC-specific memory
  114. #define bits_MEMORY_CUSTOM1 ( 1 << 31 ) // NPC-specific memory
  115. //-------------------------------------
  116. // Spawn flags
  117. //-------------------------------------
  118. #define SF_NPC_WAIT_TILL_SEEN ( 1 << 0 ) // spawnflag that makes npcs wait until player can see them before attacking.
  119. #define SF_NPC_GAG ( 1 << 1 ) // no idle noises from this npc
  120. #define SF_NPC_FALL_TO_GROUND ( 1 << 2 ) // used my NPC_Maker
  121. #define SF_NPC_DROP_HEALTHKIT ( 1 << 3 ) // Drop a healthkit upon death
  122. #define SF_NPC_START_EFFICIENT ( 1 << 4 ) // Set into efficiency mode from spawn
  123. // ( 1 << 5 )
  124. // ( 1 << 6 )
  125. #define SF_NPC_WAIT_FOR_SCRIPT ( 1 << 7 ) // spawnflag that makes npcs wait to check for attacking until the script is done or they've been attacked
  126. #define SF_NPC_LONG_RANGE ( 1 << 8 ) // makes npcs look far and relaxes weapon range limit
  127. #define SF_NPC_FADE_CORPSE ( 1 << 9 ) // Fade out corpse after death
  128. #define SF_NPC_ALWAYSTHINK ( 1 << 10 ) // Simulate even when player isn't in PVS.
  129. #define SF_NPC_TEMPLATE ( 1 << 11 ) // This NPC will be used as a template by an npc_maker -- do not spawn.
  130. #define SF_NPC_ALTCOLLISION ( 1 << 12 )
  131. #define SF_NPC_NO_WEAPON_DROP ( 1 << 13 ) // This NPC will not actually drop a weapon that can be picked up
  132. #define SF_NPC_NO_PLAYER_PUSHAWAY ( 1 << 14 )
  133. // ( 1 << 15 )
  134. // !! Flags above ( 1 << 15 ) are reserved for NPC sub-classes
  135. //-------------------------------------
  136. //
  137. // Return codes from CanPlaySequence.
  138. //
  139. //-------------------------------------
  140. enum CanPlaySequence_t
  141. {
  142. CANNOT_PLAY = 0, // Can't play for any number of reasons.
  143. CAN_PLAY_NOW, // Can play the script immediately.
  144. CAN_PLAY_ENQUEUED, // Can play the script after I finish playing my current script.
  145. };
  146. //-------------------------------------
  147. // Weapon holstering
  148. //-------------------------------------
  149. enum DesiredWeaponState_t
  150. {
  151. DESIREDWEAPONSTATE_IGNORE = 0,
  152. DESIREDWEAPONSTATE_HOLSTERED,
  153. DESIREDWEAPONSTATE_HOLSTERED_DESTROYED, // Put the weapon away, then destroy it.
  154. DESIREDWEAPONSTATE_UNHOLSTERED,
  155. DESIREDWEAPONSTATE_CHANGING,
  156. DESIREDWEAPONSTATE_CHANGING_DESTROY, // Destroy the weapon when this change is complete.
  157. };
  158. //-------------------------------------
  159. //
  160. // Efficiency modes
  161. //
  162. //-------------------------------------
  163. enum AI_Efficiency_t
  164. {
  165. // Run at full tilt
  166. AIE_NORMAL,
  167. // Run decision process less often
  168. AIE_EFFICIENT,
  169. // Run decision process even less often, ignore other NPCs
  170. AIE_VERY_EFFICIENT,
  171. // Run decision process even less often, ignore other NPCs
  172. AIE_SUPER_EFFICIENT,
  173. // Don't run at all
  174. AIE_DORMANT,
  175. };
  176. enum AI_MoveEfficiency_t
  177. {
  178. AIME_NORMAL,
  179. AIME_EFFICIENT,
  180. };
  181. //-------------------------------------
  182. //
  183. // Sleep state
  184. //
  185. //-------------------------------------
  186. enum AI_SleepState_t
  187. {
  188. AISS_AWAKE,
  189. AISS_WAITING_FOR_THREAT,
  190. AISS_WAITING_FOR_PVS,
  191. AISS_WAITING_FOR_INPUT,
  192. AISS_AUTO_PVS,
  193. AISS_AUTO_PVS_AFTER_PVS, // Same as AUTO_PVS, except doesn't activate until/unless the NPC is IN the player's PVS.
  194. };
  195. #define AI_SLEEP_FLAGS_NONE 0x00000000
  196. #define AI_SLEEP_FLAG_AUTO_PVS 0x00000001
  197. #define AI_SLEEP_FLAG_AUTO_PVS_AFTER_PVS 0x00000002
  198. //-------------------------------------
  199. //
  200. // Debug bits
  201. //
  202. //-------------------------------------
  203. enum DebugBaseNPCBits_e
  204. {
  205. bits_debugDisableAI = 0x00000001, // disable AI
  206. bits_debugStepAI = 0x00000002, // step AI
  207. };
  208. //-------------------------------------
  209. //
  210. // Base Sentence index for behaviors
  211. //
  212. //-------------------------------------
  213. enum SentenceIndex_t
  214. {
  215. SENTENCE_BASE_BEHAVIOR_INDEX = 1000,
  216. };
  217. #ifdef AI_MONITOR_FOR_OSCILLATION
  218. struct AIScheduleChoice_t
  219. {
  220. float m_flTimeSelected;
  221. CAI_Schedule *m_pScheduleSelected;
  222. };
  223. #endif//AI_MONITOR_FOR_OSCILLATION
  224. #define MARK_TASK_EXPENSIVE() \
  225. if ( GetOuter() ) \
  226. { \
  227. GetOuter()->Remember( bits_MEMORY_TASK_EXPENSIVE ); \
  228. }
  229. //=============================================================================
  230. //
  231. // Types used by CAI_BaseNPC
  232. //
  233. //=============================================================================
  234. struct AIScheduleState_t
  235. {
  236. int iCurTask;
  237. TaskStatus_e fTaskStatus;
  238. float timeStarted;
  239. float timeCurTaskStarted;
  240. AI_TaskFailureCode_t taskFailureCode;
  241. int iTaskInterrupt;
  242. bool bTaskRanAutomovement;
  243. bool bTaskUpdatedYaw;
  244. bool bScheduleWasInterrupted;
  245. DECLARE_SIMPLE_DATADESC();
  246. };
  247. // -----------------------------------------
  248. // An entity that this NPC can't reach
  249. // -----------------------------------------
  250. struct UnreachableEnt_t
  251. {
  252. EHANDLE hUnreachableEnt; // Entity that's unreachable
  253. float fExpireTime; // Time to forget this information
  254. Vector vLocationWhenUnreachable;
  255. DECLARE_SIMPLE_DATADESC();
  256. };
  257. //=============================================================================
  258. // SCRIPTED NPC INTERACTIONS
  259. //=============================================================================
  260. // -----------------------------------------
  261. // Scripted NPC interaction flags
  262. // -----------------------------------------
  263. #define SCNPC_FLAG_TEST_OTHER_ANGLES ( 1 << 1 )
  264. #define SCNPC_FLAG_TEST_OTHER_VELOCITY ( 1 << 2 )
  265. #define SCNPC_FLAG_LOOP_IN_ACTION ( 1 << 3 )
  266. #define SCNPC_FLAG_NEEDS_WEAPON_ME ( 1 << 4 )
  267. #define SCNPC_FLAG_NEEDS_WEAPON_THEM ( 1 << 5 )
  268. #define SCNPC_FLAG_DONT_TELEPORT_AT_END_ME ( 1 << 6 )
  269. #define SCNPC_FLAG_DONT_TELEPORT_AT_END_THEM ( 1 << 7 )
  270. // -----------------------------------------
  271. // Scripted NPC interaction trigger methods
  272. // -----------------------------------------
  273. enum
  274. {
  275. SNPCINT_CODE = 0,
  276. SNPCINT_AUTOMATIC_IN_COMBAT = 1,
  277. };
  278. // -----------------------------------------
  279. // Scripted NPC interaction loop breaking trigger methods
  280. // -----------------------------------------
  281. #define SNPCINT_LOOPBREAK_ON_DAMAGE ( 1 << 1 )
  282. #define SNPCINT_LOOPBREAK_ON_FLASHLIGHT_ILLUM ( 1 << 2 )
  283. // -----------------------------------------
  284. // Scripted NPC interaction anim phases
  285. // -----------------------------------------
  286. enum
  287. {
  288. SNPCINT_ENTRY = 0,
  289. SNPCINT_SEQUENCE,
  290. SNPCINT_EXIT,
  291. SNPCINT_NUM_PHASES
  292. };
  293. struct ScriptedNPCInteraction_Phases_t
  294. {
  295. string_t iszSequence;
  296. int iActivity;
  297. DECLARE_SIMPLE_DATADESC();
  298. };
  299. // Allowable delta from the desired dynamic scripted sequence point
  300. #define DSS_MAX_DIST 6
  301. #define DSS_MAX_ANGLE_DIFF 4
  302. // Interaction Logic States
  303. enum
  304. {
  305. NPCINT_NOT_RUNNING = 0,
  306. NPCINT_RUNNING_ACTIVE, // I'm in an interaction that I initiated
  307. NPCINT_RUNNING_PARTNER, // I'm in an interaction that was initiated by the other NPC
  308. NPCINT_MOVING_TO_MARK, // I'm moving to a position to do an interaction
  309. };
  310. #define NPCINT_NONE -1
  311. #define MAXTACLAT_IGNORE -1
  312. // -----------------------------------------
  313. // A scripted interaction between NPCs
  314. // -----------------------------------------
  315. struct ScriptedNPCInteraction_t
  316. {
  317. ScriptedNPCInteraction_t()
  318. {
  319. iszInteractionName = NULL_STRING;
  320. iFlags = 0;
  321. iTriggerMethod = SNPCINT_CODE;
  322. iLoopBreakTriggerMethod = 0;
  323. vecRelativeOrigin = vec3_origin;
  324. bValidOnCurrentEnemy = false;
  325. flDelay = 5.0;
  326. flDistSqr = (DSS_MAX_DIST * DSS_MAX_DIST);
  327. flNextAttemptTime = 0;
  328. iszMyWeapon = NULL_STRING;
  329. iszTheirWeapon = NULL_STRING;
  330. for ( int i = 0; i < SNPCINT_NUM_PHASES; i++)
  331. {
  332. sPhases[i].iszSequence = NULL_STRING;
  333. sPhases[i].iActivity = ACT_INVALID;
  334. }
  335. }
  336. // Fill out these when passing to AddScriptedNPCInteraction
  337. string_t iszInteractionName;
  338. int iFlags;
  339. int iTriggerMethod;
  340. int iLoopBreakTriggerMethod;
  341. Vector vecRelativeOrigin; // (forward, right, up)
  342. QAngle angRelativeAngles;
  343. Vector vecRelativeVelocity; // Desired relative velocity of the other NPC
  344. float flDelay; // Delay before interaction can be used again
  345. float flDistSqr; // Max distance sqr from the relative origin the NPC is allowed to be to trigger
  346. string_t iszMyWeapon; // Classname of the weapon I'm holding, if any
  347. string_t iszTheirWeapon; // Classname of the weapon my interaction partner is holding, if any
  348. ScriptedNPCInteraction_Phases_t sPhases[SNPCINT_NUM_PHASES];
  349. // These will be filled out for you in AddScriptedNPCInteraction
  350. VMatrix matDesiredLocalToWorld; // Desired relative position / angles of the other NPC
  351. bool bValidOnCurrentEnemy;
  352. float flNextAttemptTime;
  353. DECLARE_SIMPLE_DATADESC();
  354. };
  355. //=============================================================================
  356. //
  357. // Utility functions
  358. //
  359. //=============================================================================
  360. Vector VecCheckToss ( CBaseEntity *pEdict, Vector vecSpot1, Vector vecSpot2, float flHeightMaxRatio, float flGravityAdj, bool bRandomize, Vector *vecMins = NULL, Vector *vecMaxs = NULL );
  361. Vector VecCheckToss ( CBaseEntity *pEntity, ITraceFilter *pFilter, Vector vecSpot1, Vector vecSpot2, float flHeightMaxRatio, float flGravityAdj, bool bRandomize, Vector *vecMins = NULL, Vector *vecMaxs = NULL );
  362. Vector VecCheckThrow( CBaseEntity *pEdict, const Vector &vecSpot1, Vector vecSpot2, float flSpeed, float flGravityAdj = 1.0f, Vector *vecMins = NULL, Vector *vecMaxs = NULL );
  363. extern Vector g_vecAttackDir;
  364. bool FBoxVisible ( CBaseEntity *pLooker, CBaseEntity *pTarget );
  365. bool FBoxVisible ( CBaseEntity *pLooker, CBaseEntity *pTarget, Vector &vecTargetOrigin, float flSize = 0.0 );
  366. // FIXME: move to utils?
  367. float DeltaV( float v0, float v1, float d );
  368. float ChangeDistance( float flInterval, float flGoalDistance, float flGoalVelocity, float flCurVelocity, float flIdealVelocity, float flAccelRate, float &flNewDistance, float &flNewVelocity );
  369. //=============================================================================
  370. //
  371. // class CAI_Manager
  372. //
  373. // Central location for components of the AI to operate across all AIs without
  374. // iterating over the global list of entities.
  375. //
  376. //=============================================================================
  377. class CAI_Manager
  378. {
  379. public:
  380. CAI_Manager();
  381. CAI_BaseNPC ** AccessAIs();
  382. int NumAIs();
  383. void AddAI( CAI_BaseNPC *pAI );
  384. void RemoveAI( CAI_BaseNPC *pAI );
  385. bool FindAI( CAI_BaseNPC *pAI ) { return ( m_AIs.Find( pAI ) != m_AIs.InvalidIndex() ); }
  386. private:
  387. enum
  388. {
  389. MAX_AIS = 256
  390. };
  391. typedef CUtlVector<CAI_BaseNPC *> CAIArray;
  392. CAIArray m_AIs;
  393. };
  394. //-------------------------------------
  395. extern CAI_Manager g_AI_Manager;
  396. //=============================================================================
  397. //
  398. // class CAI_BaseNPC
  399. //
  400. //=============================================================================
  401. class CAI_BaseNPC : public CBaseCombatCharacter,
  402. public CAI_DefMovementSink
  403. {
  404. DECLARE_CLASS( CAI_BaseNPC, CBaseCombatCharacter );
  405. public:
  406. //-----------------------------------------------------
  407. //
  408. // Initialization, cleanup, serialization, identity
  409. //
  410. CAI_BaseNPC();
  411. ~CAI_BaseNPC();
  412. //---------------------------------
  413. DECLARE_DATADESC();
  414. DECLARE_SERVERCLASS();
  415. virtual int Save( ISave &save );
  416. virtual int Restore( IRestore &restore );
  417. virtual void OnRestore();
  418. void SaveConditions( ISave &save, const CAI_ScheduleBits &conditions );
  419. void RestoreConditions( IRestore &restore, CAI_ScheduleBits *pConditions );
  420. bool ShouldSavePhysics() { return false; }
  421. virtual unsigned int PhysicsSolidMaskForEntity( void ) const;
  422. virtual bool KeyValue( const char *szKeyName, const char *szValue );
  423. //---------------------------------
  424. virtual void PostConstructor( const char *szClassname );
  425. virtual void Activate( void );
  426. virtual void Precache( void ); // derived calls at start of Spawn()
  427. virtual bool CreateVPhysics();
  428. virtual void NPCInit( void ); // derived calls after Spawn()
  429. void NPCInitThink( void );
  430. virtual void PostNPCInit() {};// called after NPC_InitThink
  431. virtual void StartNPC( void );
  432. virtual bool IsTemplate( void );
  433. virtual void CleanupOnDeath( CBaseEntity *pCulprit = NULL, bool bFireDeathOutput = true );
  434. virtual void UpdateOnRemove( void );
  435. virtual int UpdateTransmitState();
  436. //---------------------------------
  437. // Component creation factories
  438. //
  439. // The master call, override if you introduce new component types. Call base first
  440. virtual bool CreateComponents();
  441. // Components defined by the base AI class
  442. virtual CAI_Senses * CreateSenses();
  443. virtual CAI_MoveProbe * CreateMoveProbe();
  444. virtual CAI_Motor * CreateMotor();
  445. virtual CAI_LocalNavigator *CreateLocalNavigator();
  446. virtual CAI_Navigator * CreateNavigator();
  447. virtual CAI_Pathfinder *CreatePathfinder();
  448. virtual CAI_TacticalServices *CreateTacticalServices();
  449. //---------------------------------
  450. virtual bool IsNPC( void ) const { return true; }
  451. //---------------------------------
  452. void TestPlayerPushing( CBaseEntity *pPlayer );
  453. void CascadePlayerPush( const Vector &push, const Vector &pushOrigin );
  454. void NotifyPushMove();
  455. public:
  456. //-----------------------------------------------------
  457. //
  458. // AI processing - thinking, schedule selection and task running
  459. //
  460. //-----------------------------------------------------
  461. void CallNPCThink( void );
  462. // Thinking, including core thinking, movement, animation
  463. virtual void NPCThink( void );
  464. // Core thinking (schedules & tasks)
  465. virtual void RunAI( void );// core ai function!
  466. // Called to gather up all relevant conditons
  467. virtual void GatherConditions( void );
  468. // Called immediately prior to schedule processing
  469. virtual void PrescheduleThink( void );
  470. // Called immediately after schedule processing
  471. virtual void PostscheduleThink( void ) { return; };
  472. // Notification that the current schedule, if any, is ending and a new one is being selected
  473. virtual void OnScheduleChange( void );
  474. // Notification that a new schedule is about to run its first task
  475. virtual void OnStartSchedule( int scheduleType ) {};
  476. // This function implements a decision tree for the NPC. It is responsible for choosing the next behavior (schedule)
  477. // based on the current conditions and state.
  478. virtual int SelectSchedule( void );
  479. virtual int SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode );
  480. // After the schedule has been selected, it will be processed by this function so child NPC classes can
  481. // remap base schedules into child-specific behaviors
  482. virtual int TranslateSchedule( int scheduleType );
  483. virtual void StartTask( const Task_t *pTask );
  484. virtual void RunTask( const Task_t *pTask );
  485. void ClearTransientConditions();
  486. virtual void HandleAnimEvent( animevent_t *pEvent );
  487. virtual bool IsInterruptable();
  488. virtual void OnStartScene( void ) {} // Called when an NPC begins a cine scene (useful for clean-up)
  489. virtual bool ShouldPlayerAvoid( void );
  490. virtual void SetPlayerAvoidState( void );
  491. virtual void PlayerPenetratingVPhysics( void );
  492. virtual bool ShouldAlwaysThink();
  493. void ForceGatherConditions() { m_bForceConditionsGather = true; SetEfficiency( AIE_NORMAL ); } // Force an NPC out of PVS to call GatherConditions on next think
  494. virtual float LineOfSightDist( const Vector &vecDir = vec3_invalid, float zEye = FLT_MAX );
  495. virtual void MakeTracer( const Vector &vecTracerSrc, const trace_t &tr, int iTracerType );
  496. virtual const char *GetTracerType( void );
  497. virtual void DoImpactEffect( trace_t &tr, int nDamageType );
  498. enum
  499. {
  500. NEXT_SCHEDULE = LAST_SHARED_SCHEDULE,
  501. NEXT_TASK = LAST_SHARED_TASK,
  502. NEXT_CONDITION = LAST_SHARED_CONDITION,
  503. };
  504. protected:
  505. // Used by derived classes to chain a task to a task that might not be the
  506. // one they are currently handling:
  507. void ChainStartTask( int task, float taskData = 0 ) { Task_t tempTask = { task, taskData }; StartTask( (const Task_t *)&tempTask ); }
  508. void ChainRunTask( int task, float taskData = 0 ) { Task_t tempTask = { task, taskData }; RunTask( (const Task_t *) &tempTask ); }
  509. void StartTaskOverlay();
  510. void RunTaskOverlay();
  511. void EndTaskOverlay();
  512. virtual void PostRunStopMoving();
  513. bool CheckPVSCondition();
  514. private:
  515. bool CanThinkRebalance();
  516. void RebalanceThinks();
  517. bool PreNPCThink();
  518. void PostNPCThink();
  519. bool PreThink( void );
  520. void PerformSensing();
  521. void CheckOnGround( void );
  522. void MaintainSchedule( void );
  523. void RunAnimation( void );
  524. void PostRun( void );
  525. void PerformMovement();
  526. void PostMovement();
  527. virtual int StartTask ( Task_t *pTask ) { DevMsg( "Called wrong StartTask()\n" ); StartTask( (const Task_t *)pTask ); return 0; } // to ensure correct signature in derived classes
  528. virtual int RunTask ( Task_t *pTask ) { DevMsg( "Called wrong RunTask()\n" ); RunTask( (const Task_t *)pTask ); return 0; } // to ensure correct signature in derived classes
  529. public:
  530. //-----------------------------------------------------
  531. //
  532. // Schedules & tasks
  533. //
  534. //-----------------------------------------------------
  535. void SetSchedule( CAI_Schedule *pNewSchedule );
  536. bool SetSchedule( int localScheduleID );
  537. void SetDefaultFailSchedule( int failSchedule ) { m_failSchedule = failSchedule; }
  538. void ClearSchedule( const char *szReason );
  539. CAI_Schedule * GetCurSchedule() { return m_pSchedule; }
  540. bool IsCurSchedule( int schedId, bool fIdeal = true );
  541. virtual CAI_Schedule *GetSchedule(int localScheduleID);
  542. virtual int GetLocalScheduleId( int globalScheduleID ) { return AI_IdIsLocal( globalScheduleID ) ? globalScheduleID : GetClassScheduleIdSpace()->ScheduleGlobalToLocal( globalScheduleID ); }
  543. virtual int GetGlobalScheduleId( int localScheduleID ) { return AI_IdIsGlobal( localScheduleID ) ? localScheduleID : GetClassScheduleIdSpace()->ScheduleLocalToGlobal( localScheduleID ); }
  544. float GetTimeScheduleStarted() const { return m_ScheduleState.timeStarted; }
  545. //---------------------------------
  546. const Task_t* GetTask( void );
  547. int TaskIsRunning( void );
  548. virtual void TaskFail( AI_TaskFailureCode_t );
  549. void TaskFail( const char *pszGeneralFailText ) { TaskFail( MakeFailCode( pszGeneralFailText ) ); }
  550. void TaskComplete( bool fIgnoreSetFailedCondition = false );
  551. void TaskInterrupt() { m_ScheduleState.iTaskInterrupt++; }
  552. void ClearTaskInterrupt() { m_ScheduleState.iTaskInterrupt = 0; }
  553. int GetTaskInterrupt() const { return m_ScheduleState.iTaskInterrupt; }
  554. void TaskMovementComplete( void );
  555. inline int TaskIsComplete( void ) { return (GetTaskStatus() == TASKSTATUS_COMPLETE); }
  556. virtual const char *TaskName(int taskID);
  557. float GetTimeTaskStarted() const { return m_ScheduleState.timeCurTaskStarted; }
  558. virtual int GetLocalTaskId( int globalTaskId) { return GetClassScheduleIdSpace()->TaskGlobalToLocal( globalTaskId ); }
  559. virtual const char *GetSchedulingErrorName() { return "CAI_BaseNPC"; }
  560. protected:
  561. static bool LoadSchedules(void);
  562. virtual bool LoadedSchedules(void);
  563. virtual void BuildScheduleTestBits( void );
  564. //---------------------------------
  565. // This is the main call to select/translate a schedule
  566. virtual CAI_Schedule *GetNewSchedule( void );
  567. virtual CAI_Schedule *GetFailSchedule( void );
  568. //---------------------------------
  569. virtual bool CanFlinch( void );
  570. virtual void CheckFlinches( void );
  571. virtual void PlayFlinchGesture( void );
  572. int SelectFlinchSchedule( void );
  573. virtual bool IsAllowedToDodge( void );
  574. bool IsInChoreo() const;
  575. private:
  576. // This function maps the type through TranslateSchedule() and then retrieves the pointer
  577. // to the actual CAI_Schedule from the database of schedules available to this class.
  578. CAI_Schedule * GetScheduleOfType( int scheduleType );
  579. bool FHaveSchedule( void );
  580. bool FScheduleDone ( void );
  581. CAI_Schedule * ScheduleInList( const char *pName, CAI_Schedule **pList, int listCount );
  582. int GetScheduleCurTaskIndex() const { return m_ScheduleState.iCurTask; }
  583. inline int IncScheduleCurTaskIndex();
  584. inline void ResetScheduleCurTaskIndex();
  585. void NextScheduledTask ( void );
  586. bool IsScheduleValid ( void );
  587. bool ShouldSelectIdealState( void );
  588. // Selecting the ideal state
  589. NPC_STATE SelectIdleIdealState();
  590. NPC_STATE SelectAlertIdealState();
  591. NPC_STATE SelectScriptIdealState();
  592. // Various schedule selections based on NPC_STATE
  593. int SelectIdleSchedule();
  594. int SelectAlertSchedule();
  595. int SelectCombatSchedule();
  596. virtual int SelectDeadSchedule();
  597. int SelectScriptSchedule();
  598. int SelectInteractionSchedule();
  599. void OnStartTask( void ) { SetTaskStatus( TASKSTATUS_RUN_MOVE_AND_TASK ); }
  600. void SetTaskStatus( TaskStatus_e status ) { m_ScheduleState.fTaskStatus = status; }
  601. TaskStatus_e GetTaskStatus() const { return m_ScheduleState.fTaskStatus; }
  602. void DiscardScheduleState();
  603. //---------------------------------
  604. CAI_Schedule * m_pSchedule;
  605. int m_IdealSchedule;
  606. AIScheduleState_t m_ScheduleState;
  607. int m_failSchedule; // Schedule type to choose if current schedule fails
  608. bool m_bDoPostRestoreRefindPath;
  609. bool m_bUsingStandardThinkTime;
  610. float m_flLastRealThinkTime;
  611. int m_iFrameBlocked;
  612. bool m_bInChoreo;
  613. static int gm_iNextThinkRebalanceTick;
  614. static float gm_flTimeLastSpawn;
  615. static int gm_nSpawnedThisFrame;
  616. protected: // pose parameters
  617. int m_poseAim_Pitch;
  618. int m_poseAim_Yaw;
  619. int m_poseMove_Yaw;
  620. virtual void PopulatePoseParameters( void );
  621. public:
  622. inline bool HasPoseMoveYaw() { return ( m_poseMove_Yaw >= 0 ); }
  623. // Return the stored pose parameter for "move_yaw"
  624. inline int LookupPoseMoveYaw() { return m_poseMove_Yaw; }
  625. //-----------------------------------------------------
  626. //
  627. // Hooks for CAI_Behaviors, *if* derived class supports them
  628. //
  629. //-----------------------------------------------------
  630. template <class BEHAVIOR_TYPE>
  631. bool GetBehavior( BEHAVIOR_TYPE **ppBehavior )
  632. {
  633. CAI_BehaviorBase **ppBehaviors = AccessBehaviors();
  634. *ppBehavior = NULL;
  635. for ( int i = 0; i < NumBehaviors(); i++ )
  636. {
  637. *ppBehavior = dynamic_cast<BEHAVIOR_TYPE *>(ppBehaviors[i]);
  638. if ( *ppBehavior )
  639. return true;
  640. }
  641. return false;
  642. }
  643. virtual CAI_BehaviorBase *GetRunningBehavior() { return NULL; }
  644. virtual bool ShouldAcceptGoal( CAI_BehaviorBase *pBehavior, CAI_GoalEntity *pGoal ) { return true; }
  645. virtual void OnClearGoal( CAI_BehaviorBase *pBehavior, CAI_GoalEntity *pGoal ) {}
  646. // Notification that the status behavior ability to select schedules has changed.
  647. // Return "true" to signal a schedule interrupt is desired
  648. virtual bool OnBehaviorChangeStatus( CAI_BehaviorBase *pBehavior, bool fCanFinishSchedule ) { return false; }
  649. private:
  650. virtual CAI_BehaviorBase ** AccessBehaviors() { return NULL; }
  651. virtual int NumBehaviors() { return 0; }
  652. public:
  653. //-----------------------------------------------------
  654. //
  655. // Conditions
  656. //
  657. //-----------------------------------------------------
  658. virtual const char* ConditionName(int conditionID);
  659. virtual void RemoveIgnoredConditions ( void );
  660. void SetCondition( int iCondition /*, bool state = true*/ );
  661. bool HasCondition( int iCondition );
  662. bool HasCondition( int iCondition, bool bUseIgnoreConditions );
  663. bool HasInterruptCondition( int iCondition );
  664. bool HasConditionsToInterruptSchedule( int nLocalScheduleID );
  665. void ClearCondition( int iCondition );
  666. void ClearConditions( int *pConditions, int nConditions );
  667. void SetIgnoreConditions( int *pConditions, int nConditions );
  668. void ClearIgnoreConditions( int *pConditions, int nConditions );
  669. bool ConditionInterruptsCurSchedule( int iCondition );
  670. bool ConditionInterruptsSchedule( int schedule, int iCondition );
  671. void SetCustomInterruptCondition( int nCondition );
  672. bool IsCustomInterruptConditionSet( int nCondition );
  673. void ClearCustomInterruptCondition( int nCondition );
  674. void ClearCustomInterruptConditions( void );
  675. bool ConditionsGathered() const { return m_bConditionsGathered; }
  676. const CAI_ScheduleBits &AccessConditionBits() const { return m_Conditions; }
  677. CAI_ScheduleBits & AccessConditionBits() { return m_Conditions; }
  678. bool DidChooseEnemy() const { return !m_bSkippedChooseEnemy; }
  679. private:
  680. CAI_ScheduleBits m_Conditions;
  681. CAI_ScheduleBits m_CustomInterruptConditions; //Bit string assembled by the schedule running, then
  682. //modified by leaf classes to suit their needs
  683. CAI_ScheduleBits m_ConditionsPreIgnore;
  684. CAI_ScheduleBits m_InverseIgnoreConditions;
  685. bool m_bForceConditionsGather;
  686. bool m_bConditionsGathered;
  687. bool m_bSkippedChooseEnemy;
  688. public:
  689. //-----------------------------------------------------
  690. //
  691. // NPC State
  692. //
  693. //-----------------------------------------------------
  694. inline void SetIdealState( NPC_STATE eIdealState );
  695. inline NPC_STATE GetIdealState();
  696. virtual NPC_STATE SelectIdealState( void );
  697. void SetState( NPC_STATE State );
  698. virtual bool ShouldGoToIdleState( void ) { return ( false ); }
  699. virtual void OnStateChange( NPC_STATE OldState, NPC_STATE NewState ) {/*Base class doesn't care*/};
  700. NPC_STATE GetState( void ) { return m_NPCState; }
  701. AI_Efficiency_t GetEfficiency() const { return m_Efficiency; }
  702. void SetEfficiency( AI_Efficiency_t efficiency ) { m_Efficiency = efficiency; }
  703. AI_MoveEfficiency_t GetMoveEfficiency() const { return m_MoveEfficiency; }
  704. void SetMoveEfficiency( AI_MoveEfficiency_t efficiency ) { m_MoveEfficiency = efficiency; }
  705. virtual void UpdateEfficiency( bool bInPVS );
  706. void ForceDecisionThink() { m_flNextDecisionTime = 0; SetEfficiency( AIE_NORMAL ); }
  707. bool IsFlaggedEfficient() const { return HasSpawnFlags( SF_NPC_START_EFFICIENT ); }
  708. AI_SleepState_t GetSleepState() const { return m_SleepState; }
  709. void SetSleepState( AI_SleepState_t sleepState ) { m_SleepState = sleepState; }
  710. void AddSleepFlags( int flags ) { m_SleepFlags |= flags; }
  711. void RemoveSleepFlags( int flags ) { m_SleepFlags &= ~flags; }
  712. bool HasSleepFlags( int flags ) { return (m_SleepFlags & flags) == flags; }
  713. void UpdateSleepState( bool bInPVS );
  714. virtual void Wake( bool bFireOutput = true );
  715. void Sleep();
  716. bool WokeThisTick() const;
  717. //---------------------------------
  718. NPC_STATE m_NPCState; // npc's current state
  719. float m_flLastStateChangeTime;
  720. private:
  721. NPC_STATE m_IdealNPCState; // npc should change to this state
  722. AI_Efficiency_t m_Efficiency;
  723. AI_MoveEfficiency_t m_MoveEfficiency;
  724. float m_flNextDecisionTime;
  725. AI_SleepState_t m_SleepState;
  726. int m_SleepFlags;
  727. float m_flWakeRadius;
  728. bool m_bWakeSquad;
  729. int m_nWakeTick;
  730. public:
  731. //-----------------------------------------------------
  732. //
  733. // Activities
  734. //
  735. //-----------------------------------------------------
  736. Activity TranslateActivity( Activity idealActivity, Activity *pIdealWeaponActivity = NULL );
  737. Activity NPC_TranslateActivity( Activity eNewActivity );
  738. Activity GetActivity( void ) { return m_Activity; }
  739. virtual void SetActivity( Activity NewActivity );
  740. Activity GetIdealActivity( void ) { return m_IdealActivity; }
  741. void SetIdealActivity( Activity NewActivity );
  742. void ResetIdealActivity( Activity newIdealActivity );
  743. void SetSequenceByName( const char *szSequence );
  744. void SetSequenceById( int iSequence );
  745. Activity GetScriptCustomMoveActivity( void );
  746. int GetScriptCustomMoveSequence( void );
  747. Activity GetStoppedActivity( void );
  748. inline bool HaveSequenceForActivity( Activity activity );
  749. inline bool IsActivityStarted(void);
  750. virtual bool IsActivityFinished( void );
  751. virtual bool IsActivityMovementPhased( Activity activity );
  752. virtual void OnChangeActivity( Activity eNewActivity );
  753. void MaintainActivity(void);
  754. void ResetActivity(void) { m_Activity = ACT_RESET; }
  755. void SetActivityAndSequence(Activity NewActivity, int iSequence, Activity translatedActivity, Activity weaponActivity);
  756. private:
  757. void AdvanceToIdealActivity(void);
  758. void ResolveActivityToSequence(Activity NewActivity, int &iSequence, Activity &translatedActivity, Activity &weaponActivity);
  759. Activity m_Activity; // Current animation state
  760. Activity m_translatedActivity; // Current actual translated animation
  761. Activity m_IdealActivity; // Desired animation state
  762. int m_nIdealSequence; // Desired animation sequence
  763. Activity m_IdealTranslatedActivity; // Desired actual translated animation state
  764. Activity m_IdealWeaponActivity; // Desired weapon animation state
  765. CNetworkVar(int, m_iDeathPose );
  766. CNetworkVar(int, m_iDeathFrame );
  767. public:
  768. //-----------------------------------------------------
  769. //
  770. // Senses
  771. //
  772. //-----------------------------------------------------
  773. CAI_Senses * GetSenses() { return m_pSenses; }
  774. const CAI_Senses * GetSenses() const { return m_pSenses; }
  775. void SetDistLook( float flDistLook );
  776. virtual bool QueryHearSound( CSound *pSound );
  777. virtual bool QuerySeeEntity( CBaseEntity *pEntity, bool bOnlyHateOrFearIfNPC = false );
  778. virtual void OnLooked( int iDistance );
  779. virtual void OnListened();
  780. virtual void OnSeeEntity( CBaseEntity *pEntity ) {}
  781. // If true, AI will try to see this entity regardless of distance.
  782. virtual bool ShouldNotDistanceCull() { return false; }
  783. virtual int GetSoundInterests( void );
  784. virtual int GetSoundPriority( CSound *pSound );
  785. CSound * GetLoudestSoundOfType( int iType );
  786. virtual CSound * GetBestSound( int validTypes = ALL_SOUNDS );
  787. virtual CSound * GetBestScent( void );
  788. virtual float HearingSensitivity( void ) { return 1.0; }
  789. virtual bool ShouldIgnoreSound( CSound * ) { return false; }
  790. bool SoundIsVisible( CSound *pSound );
  791. protected:
  792. virtual void ClearSenseConditions( void );
  793. private:
  794. void LockBestSound();
  795. void UnlockBestSound();
  796. CAI_Senses * m_pSenses;
  797. CSound * m_pLockedBestSound;
  798. public:
  799. //-----------------------------------------------------
  800. //
  801. // Enemy and target
  802. //
  803. //-----------------------------------------------------
  804. Vector GetSmoothedVelocity( void );
  805. CBaseEntity* GetEnemy() { return m_hEnemy.Get(); }
  806. CBaseEntity* GetEnemy() const { return m_hEnemy.Get(); }
  807. float GetTimeEnemyAcquired() { return m_flTimeEnemyAcquired; }
  808. void SetEnemy( CBaseEntity *pEnemy, bool bSetCondNewEnemy = true );
  809. const Vector & GetEnemyLKP() const;
  810. float GetEnemyLastTimeSeen() const;
  811. void MarkEnemyAsEluded();
  812. void ClearEnemyMemory();
  813. bool EnemyHasEludedMe() const;
  814. virtual CBaseEntity *BestEnemy(); // returns best enemy in memory list
  815. virtual bool IsValidEnemy( CBaseEntity *pEnemy );
  816. virtual bool CanBeAnEnemyOf( CBaseEntity *pEnemy );
  817. void ForceChooseNewEnemy() { m_EnemiesSerialNumber = -1; }
  818. bool ChooseEnemy();
  819. virtual bool ShouldChooseNewEnemy();
  820. virtual void GatherEnemyConditions( CBaseEntity *pEnemy );
  821. virtual float EnemyDistTolerance() { return 0; } // Enemy distances within this tolerance of each other are considered equivalent.
  822. float EnemyDistance( CBaseEntity *pEnemy );
  823. CBaseCombatCharacter *GetEnemyCombatCharacterPointer();
  824. void SetEnemyOccluder(CBaseEntity *pBlocker);
  825. CBaseEntity *GetEnemyOccluder(void);
  826. virtual void StartTargetHandling( CBaseEntity *pTargetEnt );
  827. //---------------------------------
  828. CBaseEntity* GetTarget() { return m_hTargetEnt.Get(); }
  829. void SetTarget( CBaseEntity *pTarget );
  830. void CheckTarget( CBaseEntity *pTarget );
  831. float GetAcceptableTimeSeenEnemy( void ) { return m_flAcceptableTimeSeenEnemy; }
  832. virtual CAI_BaseNPC *CreateCustomTarget( const Vector &vecOrigin, float duration = -1 );
  833. void SetDeathPose( const int &iDeathPose ) { m_iDeathPose = iDeathPose; }
  834. void SetDeathPoseFrame( const int &iDeathPoseFrame ) { m_iDeathFrame = iDeathPoseFrame; }
  835. void SelectDeathPose( const CTakeDamageInfo &info );
  836. virtual bool ShouldPickADeathPose( void ) { return true; }
  837. virtual bool AllowedToIgnite( void ) { return false; }
  838. protected:
  839. virtual float GetGoalRepathTolerance( CBaseEntity *pGoalEnt, GoalType_t type, const Vector &curGoal, const Vector &curTargetPos );
  840. private:
  841. void * CheckEnemy( CBaseEntity *pEnemy ) { return NULL; } // OBSOLETE, replaced by GatherEnemyConditions(), left here to make derived code not compile
  842. // Updates the goal position in case of GOALTYPE_ENEMY
  843. void UpdateEnemyPos();
  844. // Updates the goal position in case of GOALTYPE_TARGETENT
  845. void UpdateTargetPos();
  846. //---------------------------------
  847. EHANDLE m_hEnemy; // the entity that the npc is fighting.
  848. float m_flTimeEnemyAcquired; // The time at which the entity the NPC is fighting became the NPC's enemy.
  849. EHANDLE m_hTargetEnt; // the entity that the npc is trying to reach
  850. CRandStopwatch m_GiveUpOnDeadEnemyTimer;
  851. CSimpleSimTimer m_FailChooseEnemyTimer;
  852. int m_EnemiesSerialNumber;
  853. float m_flAcceptableTimeSeenEnemy;
  854. CSimpleSimTimer m_UpdateEnemyPosTimer;
  855. static CSimpleSimTimer m_AnyUpdateEnemyPosTimer;
  856. public:
  857. //-----------------------------------------------------
  858. //
  859. // Commander mode stuff.
  860. //
  861. //-----------------------------------------------------
  862. virtual bool IsCommandable() { return false; }
  863. virtual bool IsPlayerAlly( CBasePlayer *pPlayer = NULL );
  864. virtual bool IsMedic() { return false; }
  865. virtual bool IsCommandMoving() { return false; }
  866. virtual bool ShouldAutoSummon() { return false; }
  867. virtual void SetCommandGoal( const Vector &vecGoal );
  868. virtual void ClearCommandGoal();
  869. virtual void OnTargetOrder() {}
  870. virtual void OnMoveOrder() {}
  871. virtual bool IsValidCommandTarget( CBaseEntity *pTarget ) { return false; }
  872. const Vector &GetCommandGoal() const { return m_vecCommandGoal; }
  873. virtual void OnMoveToCommandGoalFailed() {}
  874. string_t GetPlayerSquadName() const { Assert( gm_iszPlayerSquad != NULL_STRING ); return gm_iszPlayerSquad; }
  875. bool IsInPlayerSquad() const;
  876. virtual CAI_BaseNPC *GetSquadCommandRepresentative() { return NULL; }
  877. virtual bool TargetOrder( CBaseEntity *pTarget, CAI_BaseNPC **Allies, int numAllies ) { OnTargetOrder(); return true; }
  878. virtual void MoveOrder( const Vector &vecDest, CAI_BaseNPC **Allies, int numAllies ) { SetCommandGoal( vecDest ); SetCondition( COND_RECEIVED_ORDERS ); OnMoveOrder(); }
  879. // Return true if you're willing to be idly talked to by other friends.
  880. virtual bool CanBeUsedAsAFriend( void );
  881. private:
  882. Vector m_vecCommandGoal;
  883. static string_t gm_iszPlayerSquad;
  884. public:
  885. CAI_MoveMonitor m_CommandMoveMonitor;
  886. //-----------------------------------------------------
  887. // Dynamic scripted NPC interactions
  888. //-----------------------------------------------------
  889. public:
  890. float GetInteractionYaw( void ) const { return m_flInteractionYaw; }
  891. protected:
  892. void ParseScriptedNPCInteractions( void );
  893. void AddScriptedNPCInteraction( ScriptedNPCInteraction_t *pInteraction );
  894. const char *GetScriptedNPCInteractionSequence( ScriptedNPCInteraction_t *pInteraction, int iPhase );
  895. void StartRunningInteraction( CAI_BaseNPC *pOtherNPC, bool bActive );
  896. void StartScriptedNPCInteraction( CAI_BaseNPC *pOtherNPC, ScriptedNPCInteraction_t *pInteraction, Vector vecOtherOrigin, QAngle angOtherAngles );
  897. void CheckForScriptedNPCInteractions( void );
  898. void CalculateValidEnemyInteractions( void );
  899. void CheckForcedNPCInteractions( void );
  900. bool InteractionCouldStart( CAI_BaseNPC *pOtherNPC, ScriptedNPCInteraction_t *pInteraction, Vector &vecOrigin, QAngle &angAngles );
  901. virtual bool CanRunAScriptedNPCInteraction( bool bForced = false );
  902. bool IsRunningDynamicInteraction( void ) { return (m_iInteractionState != NPCINT_NOT_RUNNING && (m_hCine != NULL)); }
  903. bool IsActiveDynamicInteraction( void ) { return (m_iInteractionState == NPCINT_RUNNING_ACTIVE && (m_hCine != NULL)); }
  904. ScriptedNPCInteraction_t *GetRunningDynamicInteraction( void ) { return &(m_ScriptedInteractions[m_iInteractionPlaying]); }
  905. void SetInteractionCantDie( bool bCantDie ) { m_bCannotDieDuringInteraction = bCantDie; }
  906. bool HasInteractionCantDie( void );
  907. void InputForceInteractionWithNPC( inputdata_t &inputdata );
  908. void StartForcedInteraction( CAI_BaseNPC *pNPC, int iInteraction );
  909. void CleanupForcedInteraction( void );
  910. void CalculateForcedInteractionPosition( void );
  911. CAI_BaseNPC *GetInteractionPartner( void );
  912. private:
  913. // Forced interactions
  914. CHandle<CAI_BaseNPC> m_hForcedInteractionPartner;
  915. Vector m_vecForcedWorldPosition;
  916. float m_flForcedInteractionTimeout; // Abort the interaction if it hasn't started by this time.
  917. CHandle<CAI_BaseNPC> m_hInteractionPartner;
  918. EHANDLE m_hLastInteractionTestTarget;
  919. bool m_bCannotDieDuringInteraction;
  920. int m_iInteractionState;
  921. int m_iInteractionPlaying;
  922. CUtlVector<ScriptedNPCInteraction_t> m_ScriptedInteractions;
  923. float m_flInteractionYaw;
  924. public:
  925. //-----------------------------------------------------
  926. //
  927. // Sounds
  928. //
  929. //-----------------------------------------------------
  930. virtual CanPlaySequence_t CanPlaySequence( bool fDisregardState, int interruptLevel );
  931. virtual bool CanPlaySentence( bool fDisregardState ) { return IsAlive(); }
  932. virtual int PlaySentence( const char *pszSentence, float delay, float volume, soundlevel_t soundlevel, CBaseEntity *pListener = NULL );
  933. virtual int PlayScriptedSentence( const char *pszSentence, float delay, float volume, soundlevel_t soundlevel, bool bConcurrent, CBaseEntity *pListener );
  934. virtual bool FOkToMakeSound( int soundPriority = 0 );
  935. virtual void JustMadeSound( int soundPriority = 0, float flSoundLength = 0.0f );
  936. virtual void DeathSound( const CTakeDamageInfo &info ) { return; };
  937. virtual void AlertSound( void ) { return; };
  938. virtual void IdleSound( void ) { return; };
  939. virtual void PainSound( const CTakeDamageInfo &info ) { return; };
  940. virtual void FearSound( void ) { return; };
  941. virtual void LostEnemySound( void ) { return; };
  942. virtual void FoundEnemySound( void ) { return; };
  943. virtual void BarnacleDeathSound( void ) { CTakeDamageInfo info; PainSound( info ); }
  944. virtual void SpeakSentence( int sentenceType ) { return; };
  945. virtual bool ShouldPlayIdleSound( void );
  946. virtual void MakeAIFootstepSound( float volume, float duration = 0.5f );
  947. //---------------------------------
  948. virtual CAI_Expresser *GetExpresser() { return NULL; }
  949. const CAI_Expresser *GetExpresser() const { return const_cast<CAI_BaseNPC *>(this)->GetExpresser(); }
  950. //---------------------------------
  951. // NPC Event Response System
  952. virtual bool CanRespondToEvent( const char *ResponseConcept ) { return false; }
  953. virtual bool RespondedTo( const char *ResponseConcept, bool bForce, bool bCancelScene ) { return false; }
  954. virtual void PlayerHasIlluminatedNPC( CBasePlayer *pPlayer, float flDot );
  955. virtual void ModifyOrAppendCriteria( AI_CriteriaSet& set );
  956. protected:
  957. float SoundWaitTime() const { return m_flSoundWaitTime; }
  958. public:
  959. //-----------------------------------------------------
  960. //
  961. // Capabilities report (from CBaseCombatCharacter)
  962. //
  963. //-----------------------------------------------------
  964. virtual int CapabilitiesGet( void ) const;
  965. // local capabilities access
  966. int CapabilitiesAdd( int capabilities );
  967. int CapabilitiesRemove( int capabilities );
  968. void CapabilitiesClear( void );
  969. private:
  970. int m_afCapability; // tells us what a npc can/can't do.
  971. public:
  972. //-----------------------------------------------------
  973. //
  974. // Pathfinding, navigation & movement
  975. //
  976. //-----------------------------------------------------
  977. CAI_Navigator * GetNavigator() { return m_pNavigator; }
  978. const CAI_Navigator *GetNavigator() const { return m_pNavigator; }
  979. CAI_LocalNavigator *GetLocalNavigator() { return m_pLocalNavigator; }
  980. const CAI_LocalNavigator *GetLocalNavigator() const { return m_pLocalNavigator; }
  981. CAI_Pathfinder * GetPathfinder() { return m_pPathfinder; }
  982. const CAI_Pathfinder *GetPathfinder() const { return m_pPathfinder; }
  983. CAI_MoveProbe * GetMoveProbe() { return m_pMoveProbe; }
  984. const CAI_MoveProbe *GetMoveProbe() const { return m_pMoveProbe; }
  985. CAI_Motor * GetMotor() { return m_pMotor; }
  986. const CAI_Motor * GetMotor() const { return m_pMotor; }
  987. //---------------------------------
  988. static bool FindSpotForNPCInRadius( Vector *pResult, const Vector &vStartPos, CAI_BaseNPC *pNPC, float radius, bool bOutOfPlayerViewcone = false );
  989. //---------------------------------
  990. virtual bool IsNavigationUrgent();
  991. virtual bool ShouldFailNav( bool bMovementFailed );
  992. virtual bool ShouldBruteForceFailedNav() { return false; }
  993. // The current navigation (movement) mode (e.g. fly, swim, locomote, etc)
  994. Navigation_t GetNavType() const;
  995. void SetNavType( Navigation_t navType );
  996. CBaseEntity * GetNavTargetEntity(void);
  997. bool IsMoving( void );
  998. virtual float GetTimeToNavGoal();
  999. // NPCs can override this to tweak with how costly particular movements are
  1000. virtual bool MovementCost( int moveType, const Vector &vecStart, const Vector &vecEnd, float *pCost );
  1001. // Turns a directional vector into a yaw value that points down that vector.
  1002. float VecToYaw( const Vector &vecDir );
  1003. // Turning
  1004. virtual float CalcIdealYaw( const Vector &vecTarget );
  1005. virtual float MaxYawSpeed( void ); // Get max yaw speed
  1006. bool FacingIdeal( void );
  1007. void SetUpdatedYaw() { m_ScheduleState.bTaskUpdatedYaw = true; }
  1008. // Add multiple facing goals while moving/standing still.
  1009. virtual void AddFacingTarget( CBaseEntity *pTarget, float flImportance, float flDuration, float flRamp = 0.0 );
  1010. virtual void AddFacingTarget( const Vector &vecPosition, float flImportance, float flDuration, float flRamp = 0.0 );
  1011. virtual void AddFacingTarget( CBaseEntity *pTarget, const Vector &vecPosition, float flImportance, float flDuration, float flRamp = 0.0 );
  1012. virtual float GetFacingDirection( Vector &vecDir );
  1013. // ------------
  1014. // Methods used by motor to query properties/preferences/move-related state
  1015. // ------------
  1016. virtual bool CanStandOn( CBaseEntity *pSurface ) const;
  1017. virtual bool IsJumpLegal( const Vector &startPos, const Vector &apex, const Vector &endPos ) const; // Override for specific creature types
  1018. bool IsJumpLegal( const Vector &startPos, const Vector &apex, const Vector &endPos, float maxUp, float maxDown, float maxDist ) const;
  1019. bool ShouldMoveWait();
  1020. virtual float StepHeight() const { return 18.0f; }
  1021. float GetStepDownMultiplier() const;
  1022. virtual float GetMaxJumpSpeed() const { return 350.0f; }
  1023. virtual float GetJumpGravity() const { return 1.0f; }
  1024. //---------------------------------
  1025. virtual bool OverrideMove( float flInterval ); // Override to take total control of movement (return true if done so)
  1026. virtual bool OverrideMoveFacing( const AILocalMoveGoal_t &move, float flInterval );
  1027. //---------------------------------
  1028. virtual bool IsUnusableNode(int iNodeID, CAI_Hint *pHint); // Override for special NPC behavior
  1029. virtual bool ValidateNavGoal();
  1030. virtual bool IsCurTaskContinuousMove();
  1031. virtual bool IsValidMoveAwayDest( const Vector &vecDest ) { return true; }
  1032. //---------------------------------
  1033. //
  1034. // Notifications from navigator
  1035. //
  1036. virtual void OnMovementFailed() {};
  1037. virtual void OnMovementComplete() {};
  1038. //---------------------------------
  1039. bool FindNearestValidGoalPos( const Vector &vTestPoint, Vector *pResult );
  1040. void RememberUnreachable( CBaseEntity* pEntity, float duration = -1 ); // Remember that entity is unreachable
  1041. virtual bool IsUnreachable( CBaseEntity* pEntity ); // Is entity is unreachable?
  1042. //---------------------------------
  1043. // Inherited from IAI_MotorMovementServices
  1044. virtual float CalcYawSpeed( void );
  1045. virtual bool OnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal,
  1046. float distClear,
  1047. AIMoveResult_t *pResult );
  1048. virtual bool OnObstructionPreSteer( AILocalMoveGoal_t *pMoveGoal,
  1049. float distClear,
  1050. AIMoveResult_t *pResult );
  1051. // Translations of the above into some useful game terms
  1052. virtual bool OnObstructingDoor( AILocalMoveGoal_t *pMoveGoal,
  1053. CBaseDoor *pDoor,
  1054. float distClear,
  1055. AIMoveResult_t *pResult );
  1056. virtual bool OnUpcomingPropDoor( AILocalMoveGoal_t *pMoveGoal,
  1057. CBasePropDoor *pDoor,
  1058. float distClear,
  1059. AIMoveResult_t *pResult );
  1060. void OpenPropDoorBegin( CBasePropDoor *pDoor );
  1061. void OpenPropDoorNow( CBasePropDoor *pDoor );
  1062. //---------------------------------
  1063. void DelayMoveStart( float delay ) { m_flMoveWaitFinished = gpGlobals->curtime + delay; }
  1064. float m_flMoveWaitFinished;
  1065. //
  1066. // Stuff for opening doors.
  1067. //
  1068. void OnDoorFullyOpen(CBasePropDoor *pDoor);
  1069. void OnDoorBlocked(CBasePropDoor *pDoor);
  1070. CHandle<CBasePropDoor> m_hOpeningDoor; // The CBasePropDoor that we are in the midst of opening for navigation.
  1071. protected:
  1072. // BRJ 4/11
  1073. // Semi-obsolete-looking Lars code I moved out of the engine and into here
  1074. int FlyMove( const Vector& vecPosition, unsigned int mask );
  1075. int WalkMove( const Vector& vecPosition, unsigned int mask );
  1076. // Unreachable Entities
  1077. CUtlVector<UnreachableEnt_t> m_UnreachableEnts; // Array of unreachable entities
  1078. private:
  1079. CAI_Navigator * m_pNavigator;
  1080. CAI_LocalNavigator *m_pLocalNavigator;
  1081. CAI_Pathfinder * m_pPathfinder;
  1082. CAI_MoveProbe * m_pMoveProbe;
  1083. CAI_Motor * m_pMotor;
  1084. EHANDLE m_hGoalEnt; // path corner we are heading towards
  1085. float m_flTimeLastMovement;
  1086. CSimpleSimTimer m_CheckOnGroundTimer;
  1087. public:
  1088. //-----------------------------------------------------
  1089. //
  1090. // Eye position, view offset, head direction, eye direction
  1091. //
  1092. //-----------------------------------------------------
  1093. void SetDefaultEyeOffset ( void );
  1094. const Vector & GetDefaultEyeOffset( void ) { return m_vDefaultEyeOffset; }
  1095. virtual Vector GetNodeViewOffset() { return GetViewOffset(); }
  1096. virtual Vector EyeOffset( Activity nActivity );
  1097. virtual Vector EyePosition( void );
  1098. //---------------------------------
  1099. virtual Vector HeadDirection2D( void );
  1100. virtual Vector HeadDirection3D( void );
  1101. virtual Vector EyeDirection2D( void );
  1102. virtual Vector EyeDirection3D( void );
  1103. virtual CBaseEntity *EyeLookTarget( void ); // Overridden by subclass to force look at an entity
  1104. virtual void AddLookTarget( CBaseEntity *pTarget, float flImportance, float flDuration, float flRamp = 0.0 ) { };
  1105. virtual void AddLookTarget( const Vector &vecPosition, float flImportance, float flDuration, float flRamp = 0.0 ) { };
  1106. virtual void SetHeadDirection( const Vector &vTargetPos, float flInterval );
  1107. virtual void MaintainLookTargets( float flInterval );
  1108. virtual bool ValidEyeTarget(const Vector &lookTargetPos);
  1109. virtual Vector FacingPosition( void ) { return EyePosition(); }; // position that other npc's use when facing you
  1110. virtual void MaintainTurnActivity( void );
  1111. virtual bool FInAimCone( const Vector &vecSpot );
  1112. virtual void AimGun();
  1113. virtual void SetAim( const Vector &aimDir );
  1114. virtual void RelaxAim( void );
  1115. virtual CBaseEntity *GetAlternateMoveShootTarget() { return NULL; }
  1116. protected:
  1117. Vector m_vDefaultEyeOffset;
  1118. float m_flNextEyeLookTime; // Next time a pick a new place to look
  1119. float m_flEyeIntegRate; // How fast does eye move to target
  1120. private:
  1121. Vector m_vEyeLookTarget; // Where I want to be looking
  1122. Vector m_vCurEyeTarget; // Direction I'm looking at
  1123. EHANDLE m_hEyeLookTarget; // What I want to be looking at
  1124. float m_flHeadYaw; // Current head yaw
  1125. float m_flHeadPitch; // Current head pitch
  1126. protected:
  1127. float m_flOriginalYaw; // This is the direction facing when the level designer placed the NPC in the level.
  1128. public:
  1129. //-----------------------------------------------------
  1130. // Mapmaker Scripting
  1131. //
  1132. // Set when the NPC is being scripted by a mapmaker, and
  1133. // shouldn't be responding to external stimuli that would
  1134. // break him out of his "script". NOT a scripted sequence.
  1135. //-----------------------------------------------------
  1136. inline bool IsInAScript( void ) { return m_bInAScript; }
  1137. inline void SetInAScript( bool bScript ) { m_bInAScript = bScript; }
  1138. void InputStartScripting( inputdata_t &inputdata ) { m_bInAScript = true; }
  1139. void InputStopScripting( inputdata_t &inputdata ) { m_bInAScript = false; }
  1140. void InputGagEnable( inputdata_t &inputdata ) { AddSpawnFlags(SF_NPC_GAG); }
  1141. void InputGagDisable( inputdata_t &inputdata ) { RemoveSpawnFlags(SF_NPC_GAG); }
  1142. bool HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt);
  1143. virtual void InputOutsideTransition( inputdata_t &inputdata );
  1144. virtual void InputInsideTransition( inputdata_t &inputdata );
  1145. void CleanupScriptsOnTeleport( bool bEnrouteAsWell );
  1146. virtual void SetScriptedScheduleIgnoreConditions( Interruptability_t interrupt );
  1147. private:
  1148. bool m_bInAScript;
  1149. public:
  1150. //-----------------------------------------------------
  1151. //
  1152. // Scripting
  1153. //
  1154. //-----------------------------------------------------
  1155. // Scripted sequence Info
  1156. enum SCRIPTSTATE
  1157. {
  1158. SCRIPT_PLAYING = 0, // Playing the action animation.
  1159. SCRIPT_WAIT, // Waiting on everyone in the script to be ready. Plays the pre idle animation if there is one.
  1160. SCRIPT_POST_IDLE, // Playing the post idle animation after playing the action animation.
  1161. SCRIPT_CLEANUP, // Cancelling the script / cleaning up.
  1162. SCRIPT_WALK_TO_MARK, // Walking to the scripted sequence position.
  1163. SCRIPT_RUN_TO_MARK, // Running to the scripted sequence position.
  1164. SCRIPT_CUSTOM_MOVE_TO_MARK, // Moving to the scripted sequence position while playing a custom movement animation.
  1165. };
  1166. bool ExitScriptedSequence();
  1167. bool CineCleanup();
  1168. virtual void Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity );
  1169. // forces movement and sets a new schedule
  1170. virtual bool ScheduledMoveToGoalEntity( int scheduleType, CBaseEntity *pGoalEntity, Activity movementActivity );
  1171. virtual bool ScheduledFollowPath( int scheduleType, CBaseEntity *pPathStart, Activity movementActivity );
  1172. static void ForceSelectedGo(CBaseEntity *pPlayer, const Vector &targetPos, const Vector &traceDir, bool bRun);
  1173. static void ForceSelectedGoRandom(void);
  1174. bool AutoMovement( CBaseEntity *pTarget = NULL, AIMoveTrace_t *pTraceResult = NULL );
  1175. bool AutoMovement( float flInterval, CBaseEntity *pTarget = NULL, AIMoveTrace_t *pTraceResult = NULL );
  1176. bool TaskRanAutomovement( void ) { return m_ScheduleState.bTaskRanAutomovement; }
  1177. SCRIPTSTATE m_scriptState; // internal cinematic state
  1178. CHandle<CAI_ScriptedSequence> m_hCine;
  1179. Activity m_ScriptArrivalActivity;
  1180. string_t m_strScriptArrivalSequence;
  1181. //-----------------------------------------------------
  1182. //
  1183. // Scenes
  1184. //
  1185. //-----------------------------------------------------
  1186. void AddSceneLock( float flDuration = 0.2f ) { m_flSceneTime = MAX( gpGlobals->curtime + flDuration, m_flSceneTime ); };
  1187. void ClearSceneLock( float flDuration = 0.2f ) { m_flSceneTime = gpGlobals->curtime + flDuration; };
  1188. bool IsInLockedScene( void ) { return m_flSceneTime > gpGlobals->curtime; };
  1189. float m_flSceneTime;
  1190. string_t m_iszSceneCustomMoveSeq;
  1191. public:
  1192. //-----------------------------------------------------
  1193. //
  1194. // Memory
  1195. //
  1196. //-----------------------------------------------------
  1197. inline void Remember( int iMemory ) { m_afMemory |= iMemory; }
  1198. inline void Forget( int iMemory ) { m_afMemory &= ~iMemory; }
  1199. inline bool HasMemory( int iMemory ) { if ( m_afMemory & iMemory ) return TRUE; return FALSE; }
  1200. inline bool HasAllMemories( int iMemory ) { if ( (m_afMemory & iMemory) == iMemory ) return TRUE; return FALSE; }
  1201. virtual CAI_Enemies *GetEnemies( void );
  1202. virtual void RemoveMemory( void );
  1203. virtual bool UpdateEnemyMemory( CBaseEntity *pEnemy, const Vector &position, CBaseEntity *pInformer = NULL );
  1204. virtual float GetReactionDelay( CBaseEntity *pEnemy );
  1205. void SetLastAttackTime( float time) { m_flLastAttackTime = time; }
  1206. float GetLastAttackTime() const { return m_flLastAttackTime; }
  1207. float GetLastDamageTime() const { return m_flLastDamageTime; }
  1208. float GetLastPlayerDamageTime() const { return m_flLastPlayerDamageTime; }
  1209. float GetLastEnemyTime() const { return m_flLastEnemyTime; }
  1210. // Set up the shot regulator based on the equipped weapon
  1211. virtual void OnChangeActiveWeapon( CBaseCombatWeapon *pOldWeapon, CBaseCombatWeapon *pNewWeapon );
  1212. // Weapon holstering
  1213. virtual bool CanHolsterWeapon( void );
  1214. virtual int HolsterWeapon( void );
  1215. virtual int UnholsterWeapon( void );
  1216. void InputHolsterWeapon( inputdata_t &inputdata );
  1217. void InputHolsterAndDestroyWeapon( inputdata_t &inputdata );
  1218. void InputUnholsterWeapon( inputdata_t &inputdata );
  1219. bool IsWeaponHolstered( void );
  1220. bool IsWeaponStateChanging( void );
  1221. void SetDesiredWeaponState( DesiredWeaponState_t iState ) { m_iDesiredWeaponState = iState; }
  1222. // NOTE: The Shot Regulator is used to manage the RangeAttack1 weapon.
  1223. inline CAI_ShotRegulator* GetShotRegulator() { return &m_ShotRegulator; }
  1224. virtual void OnRangeAttack1();
  1225. protected:
  1226. // Shot regulator code
  1227. virtual void OnUpdateShotRegulator( );
  1228. protected:
  1229. CAI_Enemies * m_pEnemies; // Holds information about enemies / danger positions / shared between sqaud members
  1230. int m_afMemory;
  1231. EHANDLE m_hEnemyOccluder; // The entity my enemy is hiding behind.
  1232. float m_flSumDamage; // How much consecutive damage I've received
  1233. float m_flLastDamageTime; // Last time I received damage
  1234. float m_flLastPlayerDamageTime; // Last time I received damage from the player
  1235. float m_flLastSawPlayerTime; // Last time I saw the player
  1236. float m_flLastAttackTime; // Last time that I attacked my current enemy
  1237. float m_flLastEnemyTime;
  1238. float m_flNextWeaponSearchTime; // next time to search for a better weapon
  1239. string_t m_iszPendingWeapon; // THe NPC should create and equip this weapon.
  1240. bool m_bIgnoreUnseenEnemies;
  1241. private:
  1242. CAI_ShotRegulator m_ShotRegulator; // When should I shoot next?
  1243. DesiredWeaponState_t m_iDesiredWeaponState;
  1244. public:
  1245. //-----------------------------------------------------
  1246. //
  1247. // Squads & tactics
  1248. //
  1249. //-----------------------------------------------------
  1250. virtual bool InitSquad( void );
  1251. virtual const char* SquadSlotName(int slotID) { return gm_SquadSlotNamespace.IdToSymbol(slotID); }
  1252. bool OccupyStrategySlot( int squadSlotID );
  1253. bool OccupyStrategySlotRange( int slotIDStart, int slotIDEnd );
  1254. bool HasStrategySlot( int squadSlotID );
  1255. bool HasStrategySlotRange( int slotIDStart, int slotIDEnd );
  1256. int GetMyStrategySlot() { return m_iMySquadSlot; }
  1257. void VacateStrategySlot( void );
  1258. bool IsStrategySlotRangeOccupied( int slotIDStart, int slotIDEnd ); // Returns true if all in the range are occupied
  1259. CAI_Squad * GetSquad() { return m_pSquad; }
  1260. virtual void SetSquad( CAI_Squad *pSquad );
  1261. void AddToSquad( string_t name );
  1262. void RemoveFromSquad();
  1263. void CheckSquad();
  1264. void SetSquadName( string_t name ) { m_SquadName = name; }
  1265. bool IsInSquad() const { return m_pSquad != NULL; }
  1266. virtual bool IsSilentSquadMember() const { return false; }
  1267. int NumWeaponsInSquad( const char *pszWeaponClassname );
  1268. string_t GetHintGroup( void ) { return m_strHintGroup; }
  1269. void ClearHintGroup( void ) { SetHintGroup( NULL_STRING ); }
  1270. void SetHintGroup( string_t name, bool bHintGroupNavLimiting = false );
  1271. bool IsLimitingHintGroups( void ) { return m_bHintGroupNavLimiting; }
  1272. //---------------------------------
  1273. CAI_TacticalServices *GetTacticalServices() { return m_pTacticalServices; }
  1274. const CAI_TacticalServices *GetTacticalServices() const { return m_pTacticalServices; }
  1275. //---------------------------------
  1276. // Cover
  1277. virtual bool FindCoverPos( CBaseEntity *pEntity, Vector *pResult );
  1278. virtual bool FindCoverPosInRadius( CBaseEntity *pEntity, const Vector &goalPos, float coverRadius, Vector *pResult );
  1279. virtual bool FindCoverPos( CSound *pSound, Vector *pResult );
  1280. virtual bool IsValidCover ( const Vector &vecCoverLocation, CAI_Hint const *pHint );
  1281. virtual bool IsValidShootPosition ( const Vector &vecCoverLocation, CAI_Node *pNode, CAI_Hint const *pHint );
  1282. virtual bool TestShootPosition(const Vector &vecShootPos, const Vector &targetPos ) { return WeaponLOSCondition( vecShootPos, targetPos, false ); }
  1283. virtual bool IsCoverPosition( const Vector &vecThreat, const Vector &vecPosition );
  1284. virtual float CoverRadius( void ) { return 1024; } // Default cover radius
  1285. virtual float GetMaxTacticalLateralMovement( void ) { return MAXTACLAT_IGNORE; }
  1286. protected:
  1287. virtual void OnChangeHintGroup( string_t oldGroup, string_t newGroup ) {}
  1288. CAI_Squad * m_pSquad; // The squad that I'm on
  1289. string_t m_SquadName;
  1290. int m_iMySquadSlot; // this is the behaviour slot that the npc currently holds in the squad.
  1291. private:
  1292. string_t m_strHintGroup;
  1293. bool m_bHintGroupNavLimiting;
  1294. CAI_TacticalServices *m_pTacticalServices;
  1295. public:
  1296. //-----------------------------------------------------
  1297. //
  1298. // Base schedule & task support; Miscellaneous
  1299. //
  1300. //-----------------------------------------------------
  1301. void InitRelationshipTable( void );
  1302. void AddRelationship( const char *pszRelationship, CBaseEntity *pActivator );
  1303. virtual void AddEntityRelationship( CBaseEntity *pEntity, Disposition_t nDisposition, int nPriority );
  1304. virtual void AddClassRelationship( Class_T nClass, Disposition_t nDisposition, int nPriority );
  1305. void NPCUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
  1306. CBaseGrenade* IncomingGrenade(void);
  1307. virtual bool ShouldFadeOnDeath( void );
  1308. void NPCInitDead( void ); // Call after animation/pose is set up
  1309. void CorpseFallThink( void );
  1310. float ThrowLimit( const Vector &vecStart, const Vector &vecEnd, float fGravity, float fArcSize, const Vector &mins, const Vector &maxs, CBaseEntity *pTarget, Vector *jumpVel, CBaseEntity **pBlocker);
  1311. // these functions will survey conditions and set appropriate conditions bits for attack types.
  1312. virtual int RangeAttack1Conditions( float flDot, float flDist );
  1313. virtual int RangeAttack2Conditions( float flDot, float flDist );
  1314. virtual int MeleeAttack1Conditions( float flDot, float flDist );
  1315. virtual int MeleeAttack2Conditions( float flDot, float flDist );
  1316. virtual float InnateRange1MinRange( void ) { return 0.0f; }
  1317. virtual float InnateRange1MaxRange( void ) { return FLT_MAX; }
  1318. virtual bool OnBeginMoveAndShoot( void ) { return true; }
  1319. virtual void OnEndMoveAndShoot( void ) {}
  1320. virtual bool UseAttackSquadSlots() { return false; }
  1321. //---------------------------------
  1322. virtual CBaseEntity *FindNamedEntity( const char *pszName, IEntityFindFilter *pFilter = NULL );
  1323. //---------------------------------
  1324. // States
  1325. //---------------------------------
  1326. virtual void ClearAttackConditions( void );
  1327. void GatherAttackConditions( CBaseEntity *pTarget, float flDist );
  1328. virtual bool ShouldLookForBetterWeapon();
  1329. bool Weapon_IsBetterAvailable ( void ) ;
  1330. virtual Vector Weapon_ShootPosition( void );
  1331. virtual void GiveWeapon( string_t iszWeaponName );
  1332. virtual void OnGivenWeapon( CBaseCombatWeapon *pNewWeapon ) { }
  1333. bool IsMovingToPickupWeapon();
  1334. virtual bool WeaponLOSCondition(const Vector &ownerPos, const Vector &targetPos, bool bSetConditions);
  1335. virtual bool CurrentWeaponLOSCondition(const Vector &targetPos, bool bSetConditions) { return WeaponLOSCondition( GetAbsOrigin(), targetPos, bSetConditions ); }
  1336. virtual bool IsWaitingToRappel( void ) { return false; }
  1337. virtual void BeginRappel() {}
  1338. // override to change the chase location of an enemy
  1339. // This is where your origin should go when you are chasing pEnemy when his origin is at chasePosition
  1340. // by default, leave this alone to make your origin coincide with his.
  1341. virtual void TranslateNavGoal( CBaseEntity *pEnemy, Vector &chasePosition);
  1342. virtual float GetDefaultNavGoalTolerance() { return (GetHullWidth() * 2.0); }
  1343. virtual bool FCanCheckAttacks ( void );
  1344. virtual void CheckAmmo( void ) {}
  1345. virtual bool FValidateHintType( CAI_Hint *pHint );
  1346. virtual Activity GetHintActivity( short sHintType, Activity HintsActivity );
  1347. virtual float GetHintDelay( short sHintType );
  1348. virtual Activity GetCoverActivity( CAI_Hint* pHint );
  1349. virtual Activity GetReloadActivity( CAI_Hint* pHint );
  1350. virtual void SetTurnActivity( void );
  1351. bool UpdateTurnGesture( void );
  1352. // Returns the time when the door will be open
  1353. float OpenDoorAndWait( CBaseEntity *pDoor );
  1354. bool BBoxFlat( void );
  1355. //---------------------------------
  1356. virtual void Ignite( float flFlameLifetime, bool bNPCOnly = true, float flSize = 0.0f, bool bCalledByLevelDesigner = false );
  1357. virtual bool PassesDamageFilter( const CTakeDamageInfo &info );
  1358. //---------------------------------
  1359. void MakeDamageBloodDecal( int cCount, float flNoise, trace_t *ptr, Vector vecDir );
  1360. virtual float GetHitgroupDamageMultiplier( int iHitGroup, const CTakeDamageInfo &info );
  1361. void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator );
  1362. void DecalTrace( trace_t *pTrace, char const *decalName );
  1363. void ImpactTrace( trace_t *pTrace, int iDamageType, const char *pCustomImpactName );
  1364. virtual bool PlayerInSpread( const Vector &sourcePos, const Vector &targetPos, float flSpread, float maxDistOffCenter, bool ignoreHatedPlayers = true );
  1365. CBaseEntity * PlayerInRange( const Vector &vecLocation, float flDist );
  1366. bool PointInSpread( CBaseCombatCharacter *pCheckEntity, const Vector &sourcePos, const Vector &targetPos, const Vector &testPoint, float flSpread, float maxDistOffCenter );
  1367. bool IsSquadmateInSpread( const Vector &sourcePos, const Vector &targetPos, float flSpread, float maxDistOffCenter );
  1368. //---------------------------------
  1369. // combat functions
  1370. //---------------------------------
  1371. virtual bool InnateWeaponLOSCondition( const Vector &ownerPos, const Vector &targetPos, bool bSetConditions );
  1372. virtual Activity GetFlinchActivity( bool bHeavyDamage, bool bGesture );
  1373. virtual bool Event_Gibbed( const CTakeDamageInfo &info );
  1374. virtual void Event_Killed( const CTakeDamageInfo &info );
  1375. virtual Vector GetShootEnemyDir( const Vector &shootOrigin, bool bNoisy = true );
  1376. #ifdef HL2_DLL
  1377. virtual Vector GetActualShootPosition( const Vector &shootOrigin );
  1378. virtual Vector GetActualShootTrajectory( const Vector &shootOrigin );
  1379. virtual Vector GetAttackSpread( CBaseCombatWeapon *pWeapon, CBaseEntity *pTarget = NULL );
  1380. virtual float GetSpreadBias( CBaseCombatWeapon *pWeapon, CBaseEntity *pTarget );
  1381. #endif //HL2_DLL
  1382. virtual void CollectShotStats( const Vector &vecShootOrigin, const Vector &vecShootDir );
  1383. virtual Vector BodyTarget( const Vector &posSrc, bool bNoisy = true );
  1384. virtual Vector GetAutoAimCenter() { return BodyTarget(vec3_origin, false); }
  1385. virtual void FireBullets( const FireBulletsInfo_t &info );
  1386. // OLD VERSION! Use the struct version
  1387. void FireBullets( int cShots, const Vector &vecSrc, const Vector &vecDirShooting,
  1388. const Vector &vecSpread, float flDistance, int iAmmoType, int iTracerFreq = 4,
  1389. int firingEntID = -1, int attachmentID = -1, int iDamage = 0,
  1390. CBaseEntity *pAttacker = NULL, bool bFirstShotAccurate = false );
  1391. virtual bool ShouldMoveAndShoot( void );
  1392. //---------------------------------
  1393. // Damage
  1394. //---------------------------------
  1395. virtual int OnTakeDamage_Alive( const CTakeDamageInfo &info );
  1396. virtual int OnTakeDamage_Dying( const CTakeDamageInfo &info );
  1397. virtual int OnTakeDamage_Dead( const CTakeDamageInfo &info );
  1398. virtual void NotifyFriendsOfDamage( CBaseEntity *pAttackerEntity );
  1399. virtual void OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker );
  1400. virtual bool IsLightDamage( const CTakeDamageInfo &info );
  1401. virtual bool IsHeavyDamage( const CTakeDamageInfo &info );
  1402. void DoRadiusDamage( const CTakeDamageInfo &info, int iClassIgnore, CBaseEntity *pEntityIgnore );
  1403. void DoRadiusDamage( const CTakeDamageInfo &info, const Vector &vecSrc, int iClassIgnore, CBaseEntity *pEntityIgnore );
  1404. //---------------------------------
  1405. virtual void PickupWeapon( CBaseCombatWeapon *pWeapon );
  1406. virtual void PickupItem( CBaseEntity *pItem ) { };
  1407. CBaseEntity* DropItem( const char *pszItemName, Vector vecPos, QAngle vecAng );// drop an item.
  1408. //---------------------------------
  1409. // Inputs
  1410. //---------------------------------
  1411. void InputSetRelationship( inputdata_t &inputdata );
  1412. void InputSetEnemyFilter( inputdata_t &inputdata );
  1413. void InputSetHealth( inputdata_t &inputdata );
  1414. void InputBeginRappel( inputdata_t &inputdata );
  1415. void InputSetSquad( inputdata_t &inputdata );
  1416. void InputWake( inputdata_t &inputdata );
  1417. void InputForgetEntity( inputdata_t &inputdata );
  1418. void InputIgnoreDangerSounds( inputdata_t &inputdata );
  1419. void InputUpdateEnemyMemory( inputdata_t &inputdata );
  1420. //---------------------------------
  1421. virtual void NotifyDeadFriend( CBaseEntity *pFriend ) { return; }
  1422. //---------------------------------
  1423. // Utility methods
  1424. static Vector CalcThrowVelocity(const Vector &startPos, const Vector &endPos, float fGravity, float fArcSize);
  1425. //---------------------------------
  1426. float SetWait( float minWait, float maxWait = 0.0 );
  1427. void ClearWait();
  1428. float GetWaitFinishTime() { return m_flWaitFinished; }
  1429. bool IsWaitFinished();
  1430. bool IsWaitSet();
  1431. CBaseEntity* GetGoalEnt() { return m_hGoalEnt; }
  1432. void SetGoalEnt( CBaseEntity *pGoalEnt ) { m_hGoalEnt.Set( pGoalEnt ); }
  1433. CAI_Hint *GetHintNode() { return m_pHintNode; }
  1434. const CAI_Hint *GetHintNode() const { return m_pHintNode; }
  1435. void SetHintNode( CAI_Hint *pHintNode );
  1436. void ClearHintNode( float reuseDelay = 0.0 );
  1437. float m_flWaitFinished; // if we're told to wait, this is the time that the wait will be over.
  1438. float m_flNextFlinchTime; // Time at which we'll flinch fully again (as opposed to just doing gesture flinches)
  1439. float m_flNextDodgeTime; // Time at which I can dodge again. Used so that the behavior doesn't happen over and over.
  1440. CAI_MoveAndShootOverlay m_MoveAndShootOverlay;
  1441. Vector m_vecLastPosition; // npc sometimes wants to return to where it started after an operation.
  1442. Vector m_vSavePosition; // position stored by code that called this schedules
  1443. Vector m_vInterruptSavePosition; // position stored by a task that was interrupted
  1444. private:
  1445. CHandle<CAI_Hint> m_pHintNode; // this is the hint that the npc is moving towards or performing active idle on.
  1446. public:
  1447. int m_cAmmoLoaded; // how much ammo is in the weapon (used to trigger reload anim sequences)
  1448. float m_flDistTooFar; // if enemy farther away than this, bits_COND_ENEMY_TOOFAR set in GatherEnemyConditions
  1449. string_t m_spawnEquipment;
  1450. bool m_fNoDamageDecal;
  1451. EHANDLE m_hStoredPathTarget; // For TASK_SET_GOAL
  1452. Vector m_vecStoredPathGoal; //
  1453. GoalType_t m_nStoredPathType; //
  1454. int m_fStoredPathFlags; //
  1455. CHandle<CBaseFilter> m_hEnemyFilter;
  1456. string_t m_iszEnemyFilterName;
  1457. bool m_bDidDeathCleanup;
  1458. IMPLEMENT_NETWORK_VAR_FOR_DERIVED( m_lifeState );
  1459. //---------------------------------
  1460. // Outputs
  1461. //---------------------------------
  1462. COutputEvent m_OnDamaged;
  1463. COutputEvent m_OnDeath;
  1464. COutputEvent m_OnHalfHealth;
  1465. COutputEHANDLE m_OnFoundEnemy;
  1466. COutputEvent m_OnLostEnemyLOS;
  1467. COutputEvent m_OnLostEnemy;
  1468. COutputEHANDLE m_OnFoundPlayer;
  1469. COutputEvent m_OnLostPlayerLOS;
  1470. COutputEvent m_OnLostPlayer;
  1471. COutputEvent m_OnHearWorld;
  1472. COutputEvent m_OnHearPlayer;
  1473. COutputEvent m_OnHearCombat;
  1474. COutputEvent m_OnDamagedByPlayer;
  1475. COutputEvent m_OnDamagedByPlayerSquad;
  1476. COutputEvent m_OnDenyCommanderUse;
  1477. COutputEvent m_OnRappelTouchdown;
  1478. COutputEvent m_OnSleep;
  1479. COutputEvent m_OnWake;
  1480. COutputEvent m_OnForcedInteractionStarted;
  1481. COutputEvent m_OnForcedInteractionAborted;
  1482. COutputEvent m_OnForcedInteractionFinished;
  1483. public:
  1484. // use this to shrink the bbox temporarily
  1485. void SetHullSizeNormal( bool force = false );
  1486. bool SetHullSizeSmall( bool force = false );
  1487. bool IsUsingSmallHull() const { return m_fIsUsingSmallHull; }
  1488. const Vector & GetHullMins() const { return NAI_Hull::Mins(GetHullType()); }
  1489. const Vector & GetHullMaxs() const { return NAI_Hull::Maxs(GetHullType()); }
  1490. float GetHullWidth() const { return NAI_Hull::Width(GetHullType()); }
  1491. float GetHullHeight() const { return NAI_Hull::Height(GetHullType()); }
  1492. void SetupVPhysicsHull();
  1493. virtual void StartTouch( CBaseEntity *pOther );
  1494. void CheckPhysicsContacts();
  1495. private:
  1496. void TryRestoreHull( void );
  1497. bool m_fIsUsingSmallHull;
  1498. bool m_bCheckContacts;
  1499. private:
  1500. // Task implementation helpers
  1501. void StartTurn( float flDeltaYaw );
  1502. bool FindCoverFromEnemy( bool bNodesOnly = false, float flMinDistance = 0, float flMaxDistance = FLT_MAX );
  1503. bool FindCoverFromBestSound( Vector *pCoverPos );
  1504. void StartScriptMoveToTargetTask( int task );
  1505. void RunDieTask();
  1506. void RunAttackTask( int task );
  1507. protected:
  1508. virtual float CalcReasonableFacing( bool bIgnoreOriginalFacing = false );
  1509. virtual bool IsValidReasonableFacing( const Vector &vecSightDir, float sightDist ) { return true; }
  1510. virtual float GetReasonableFacingDist( void );
  1511. public:
  1512. inline int UsableNPCObjectCaps( int baseCaps )
  1513. {
  1514. if ( IsAlive() )
  1515. baseCaps |= FCAP_IMPULSE_USE;
  1516. return baseCaps;
  1517. }
  1518. virtual int ObjectCaps() { return (BaseClass::ObjectCaps() | FCAP_NOTIFY_ON_TRANSITION); }
  1519. //-----------------------------------------------------
  1520. //
  1521. // Core mapped data structures
  1522. //
  1523. // String Registries for default AI Shared by all CBaseNPCs
  1524. // These are used only during initialization and in debug
  1525. //-----------------------------------------------------
  1526. static void InitSchedulingTables();
  1527. static CAI_GlobalScheduleNamespace *GetSchedulingSymbols() { return &gm_SchedulingSymbols; }
  1528. static CAI_ClassScheduleIdSpace &AccessClassScheduleIdSpaceDirect() { return gm_ClassScheduleIdSpace; }
  1529. virtual CAI_ClassScheduleIdSpace * GetClassScheduleIdSpace() { return &gm_ClassScheduleIdSpace; }
  1530. static int GetScheduleID (const char* schedName);
  1531. static int GetActivityID (const char* actName);
  1532. static int GetConditionID (const char* condName);
  1533. static int GetTaskID (const char* taskName);
  1534. static int GetSquadSlotID (const char* slotName);
  1535. virtual const char* GetSquadSlotDebugName( int iSquadSlot );
  1536. static const char* GetActivityName (int actID);
  1537. static void AddActivityToSR(const char *actName, int conID);
  1538. static void AddEventToSR(const char *eventName, int conID);
  1539. static const char* GetEventName (int actID);
  1540. static int GetEventID (const char* actName);
  1541. public:
  1542. //-----------------------------------------------------
  1543. // Crouch handling
  1544. //-----------------------------------------------------
  1545. bool CrouchIsDesired( void ) const;
  1546. virtual bool IsCrouching( void );
  1547. inline void ForceCrouch( void );
  1548. inline void ClearForceCrouch( void );
  1549. protected:
  1550. virtual bool Crouch( void );
  1551. virtual bool Stand( void );
  1552. virtual void DesireCrouch( void );
  1553. inline void DesireStand( void );
  1554. bool CouldShootIfCrouching( CBaseEntity *pTarget );
  1555. virtual bool IsCrouchedActivity( Activity activity );
  1556. protected:
  1557. // Override these in your derived NPC class
  1558. virtual Vector GetCrouchEyeOffset( void ) { return Vector(0,0,40); }
  1559. virtual Vector GetCrouchGunOffset( void ) { return Vector(0,0,36); }
  1560. private:
  1561. bool m_bCrouchDesired;
  1562. bool m_bForceCrouch;
  1563. bool m_bIsCrouching;
  1564. //-----------------------------------------------------
  1565. //-----------------------------------------------------
  1566. // ai_post_frame_navigation
  1567. //-----------------------------------------------------
  1568. private:
  1569. bool m_bDeferredNavigation; // This NPCs has a navigation query that's being deferred until later in the frame
  1570. public:
  1571. void SetNavigationDeferred( bool bState ) { m_bDeferredNavigation = bState; }
  1572. bool IsNavigationDeferred( void ) { return m_bDeferredNavigation; }
  1573. //-----------------------------------------------------
  1574. protected:
  1575. static CAI_GlobalNamespace gm_SquadSlotNamespace;
  1576. static CAI_LocalIdSpace gm_SquadSlotIdSpace;
  1577. private:
  1578. // Checks to see that the nav hull is valid for the NPC
  1579. bool IsNavHullValid() const;
  1580. friend class CAI_SystemHook;
  1581. friend class CAI_SchedulesManager;
  1582. static bool LoadDefaultSchedules(void);
  1583. static void InitDefaultScheduleSR(void);
  1584. static void InitDefaultTaskSR(void);
  1585. static void InitDefaultConditionSR(void);
  1586. static void InitDefaultActivitySR(void);
  1587. static void InitDefaultSquadSlotSR(void);
  1588. static CStringRegistry* m_pActivitySR;
  1589. static int m_iNumActivities;
  1590. static CStringRegistry* m_pEventSR;
  1591. static int m_iNumEvents;
  1592. static CAI_GlobalScheduleNamespace gm_SchedulingSymbols;
  1593. static CAI_ClassScheduleIdSpace gm_ClassScheduleIdSpace;
  1594. public:
  1595. //----------------------------------------------------
  1596. // Debugging tools
  1597. //
  1598. // -----------------------------
  1599. // Debuging Fields and Methods
  1600. // -----------------------------
  1601. const char* m_failText; // Text of why it failed
  1602. const char* m_interruptText; // Text of why schedule interrupted
  1603. CAI_Schedule* m_failedSchedule; // The schedule that failed last
  1604. CAI_Schedule* m_interuptSchedule; // The schedule that was interrupted last
  1605. int m_nDebugCurIndex; // Index used for stepping through AI
  1606. virtual void ReportAIState( void );
  1607. virtual void ReportOverThinkLimit( float time );
  1608. void DumpTaskTimings();
  1609. void DrawDebugGeometryOverlays(void);
  1610. virtual int DrawDebugTextOverlays(void);
  1611. void ToggleFreeze(void);
  1612. static void ClearAllSchedules(void);
  1613. static int m_nDebugBits;
  1614. static CAI_BaseNPC* m_pDebugNPC;
  1615. static int m_nDebugPauseIndex; // Current step
  1616. static inline void SetDebugNPC( CAI_BaseNPC *pNPC ) { m_pDebugNPC = pNPC; }
  1617. static inline bool IsDebugNPC( CAI_BaseNPC *pNPC ) { return( pNPC == m_pDebugNPC ); }
  1618. float m_LastShootAccuracy;
  1619. int m_TotalShots;
  1620. int m_TotalHits;
  1621. #ifdef _DEBUG
  1622. bool m_bSelected;
  1623. #endif
  1624. float m_flSoundWaitTime; // Time when I'm allowed to make another sound
  1625. int m_nSoundPriority;
  1626. float m_flIgnoreDangerSoundsUntil;
  1627. #ifdef AI_MONITOR_FOR_OSCILLATION
  1628. CUtlVector<AIScheduleChoice_t> m_ScheduleHistory;
  1629. #endif//AI_MONITOR_FOR_OSCILLATION
  1630. private:
  1631. // Break into pieces!
  1632. void Break( CBaseEntity *pBreaker );
  1633. void InputBreak( inputdata_t &inputdata );
  1634. friend void CC_NPC_Go();
  1635. friend void CC_NPC_GoRandom();
  1636. friend void CC_NPC_Freeze( const CCommand &args );
  1637. public:
  1638. CNetworkVar( bool, m_bPerformAvoidance );
  1639. CNetworkVar( bool, m_bIsMoving );
  1640. CNetworkVar( bool, m_bFadeCorpse );
  1641. CNetworkVar( bool, m_bImportanRagdoll );
  1642. CNetworkVar( bool, m_bSpeedModActive );
  1643. CNetworkVar( int, m_iSpeedModRadius );
  1644. CNetworkVar( int, m_iSpeedModSpeed );
  1645. CNetworkVar( float, m_flTimePingEffect ); // Display the pinged effect until this time
  1646. void InputActivateSpeedModifier( inputdata_t &inputdata ) { m_bSpeedModActive = true; }
  1647. void InputDisableSpeedModifier( inputdata_t &inputdata ) { m_bSpeedModActive = false; }
  1648. void InputSetSpeedModifierRadius( inputdata_t &inputdata );
  1649. void InputSetSpeedModifierSpeed( inputdata_t &inputdata );
  1650. virtual bool ShouldProbeCollideAgainstEntity( CBaseEntity *pEntity );
  1651. bool m_bPlayerAvoidState;
  1652. void GetPlayerAvoidBounds( Vector *pMins, Vector *pMaxs );
  1653. void StartPingEffect( void ) { m_flTimePingEffect = gpGlobals->curtime + 2.0f; DispatchUpdateTransmitState(); }
  1654. };
  1655. //-----------------------------------------------------------------------------
  1656. // Purpose: Returns whether our ideal activity has started. If not, we are in
  1657. // a transition sequence.
  1658. //-----------------------------------------------------------------------------
  1659. inline bool CAI_BaseNPC::IsActivityStarted(void)
  1660. {
  1661. return (GetSequence() == m_nIdealSequence);
  1662. }
  1663. //-----------------------------------------------------------------------------
  1664. // Bullet firing (legacy)...
  1665. //-----------------------------------------------------------------------------
  1666. inline void CAI_BaseNPC::FireBullets( int cShots, const Vector &vecSrc,
  1667. const Vector &vecDirShooting, const Vector &vecSpread, float flDistance,
  1668. int iAmmoType, int iTracerFreq, int firingEntID, int attachmentID,
  1669. int iDamage, CBaseEntity *pAttacker, bool bFirstShotAccurate )
  1670. {
  1671. FireBulletsInfo_t info;
  1672. info.m_iShots = cShots;
  1673. info.m_vecSrc = vecSrc;
  1674. info.m_vecDirShooting = vecDirShooting;
  1675. info.m_vecSpread = vecSpread;
  1676. info.m_flDistance = flDistance;
  1677. info.m_iAmmoType = iAmmoType;
  1678. info.m_iTracerFreq = iTracerFreq;
  1679. info.m_flDamage = iDamage;
  1680. info.m_pAttacker = pAttacker;
  1681. info.m_nFlags = bFirstShotAccurate ? FIRE_BULLETS_FIRST_SHOT_ACCURATE : 0;
  1682. FireBullets( info );
  1683. }
  1684. //-----------------------------------------------------------------------------
  1685. // Purpose: Sets the ideal state of this NPC.
  1686. //-----------------------------------------------------------------------------
  1687. inline void CAI_BaseNPC::SetIdealState( NPC_STATE eIdealState )
  1688. {
  1689. if (eIdealState != m_IdealNPCState)
  1690. {
  1691. /*switch (eIdealState)
  1692. {
  1693. case NPC_STATE_NONE:
  1694. Msg("%s.SetIdealState: NPC_STATE_NONE\n", GetDebugName());
  1695. break;
  1696. case NPC_STATE_IDLE:
  1697. Msg("%s.SetIdealState: NPC_STATE_IDLE\n", GetDebugName());
  1698. break;
  1699. case NPC_STATE_ALERT:
  1700. Msg("%s.SetIdealState: NPC_STATE_ALERT\n", GetDebugName());
  1701. break;
  1702. case NPC_STATE_COMBAT:
  1703. Msg("%s.SetIdealState: NPC_STATE_COMBAT\n", GetDebugName());
  1704. break;
  1705. case NPC_STATE_SCRIPT:
  1706. Msg("%s.SetIdealState: NPC_STATE_SCRIPT\n", GetDebugName());
  1707. break;
  1708. case NPC_STATE_PLAYDEAD:
  1709. Msg("%s.SetIdealState: NPC_STATE_PLAYDEAD\n", GetDebugName());
  1710. break;
  1711. case NPC_STATE_PRONE:
  1712. Msg("%s.SetIdealState: NPC_STATE_PRONE\n", GetDebugName());
  1713. break;
  1714. case NPC_STATE_DEAD:
  1715. Msg("%s.SetIdealState: NPC_STATE_DEAD\n", GetDebugName());
  1716. break;
  1717. default:
  1718. Msg("%s.SetIdealState: <Unknown>\n", GetDebugName());
  1719. break;
  1720. }*/
  1721. m_IdealNPCState = eIdealState;
  1722. }
  1723. }
  1724. //-----------------------------------------------------------------------------
  1725. // Purpose: Returns the current ideal state the NPC will try to achieve.
  1726. //-----------------------------------------------------------------------------
  1727. inline NPC_STATE CAI_BaseNPC::GetIdealState()
  1728. {
  1729. return m_IdealNPCState;
  1730. }
  1731. //-----------------------------------------------------------------------------
  1732. //-----------------------------------------------------------------------------
  1733. inline int CAI_BaseNPC::IncScheduleCurTaskIndex()
  1734. {
  1735. m_ScheduleState.iTaskInterrupt = 0;
  1736. m_ScheduleState.bTaskRanAutomovement = false;
  1737. m_ScheduleState.bTaskUpdatedYaw = false;
  1738. return ++m_ScheduleState.iCurTask;
  1739. }
  1740. //-----------------------------------------------------------------------------
  1741. //-----------------------------------------------------------------------------
  1742. inline void CAI_BaseNPC::ResetScheduleCurTaskIndex()
  1743. {
  1744. m_ScheduleState.iCurTask = 0;
  1745. m_ScheduleState.iTaskInterrupt = 0;
  1746. m_ScheduleState.bTaskRanAutomovement = false;
  1747. m_ScheduleState.bTaskUpdatedYaw = false;
  1748. }
  1749. //-----------------------------------------------------------------------------
  1750. //-----------------------------------------------------------------------------
  1751. inline bool CAI_BaseNPC::CrouchIsDesired( void ) const
  1752. {
  1753. return ( (CapabilitiesGet() & bits_CAP_DUCK) && (m_bCrouchDesired | m_bForceCrouch) );
  1754. }
  1755. //-----------------------------------------------------------------------------
  1756. // Purpose:
  1757. //-----------------------------------------------------------------------------
  1758. inline void CAI_BaseNPC::DesireStand( void )
  1759. {
  1760. m_bCrouchDesired = false;
  1761. }
  1762. //-----------------------------------------------------------------------------
  1763. // Purpose:
  1764. //-----------------------------------------------------------------------------
  1765. inline void CAI_BaseNPC::ForceCrouch( void )
  1766. {
  1767. m_bForceCrouch = true;
  1768. Crouch();
  1769. }
  1770. //-----------------------------------------------------------------------------
  1771. // Purpose:
  1772. //-----------------------------------------------------------------------------
  1773. inline void CAI_BaseNPC::ClearForceCrouch( void )
  1774. {
  1775. m_bForceCrouch = false;
  1776. if ( IsCrouching() )
  1777. {
  1778. Stand();
  1779. }
  1780. }
  1781. inline bool CAI_BaseNPC::HaveSequenceForActivity( Activity activity )
  1782. {
  1783. #if STUDIO_SEQUENCE_ACTIVITY_LOOKUPS_ARE_SLOW
  1784. return ( (GetModelPtr()) ? (SelectWeightedSequence( activity ) != ACTIVITY_NOT_AVAILABLE) : false );
  1785. #else
  1786. return ( (GetModelPtr()) ? GetModelPtr()->HaveSequenceForActivity(activity) : false );
  1787. #endif
  1788. }
  1789. typedef CHandle<CAI_BaseNPC> AIHANDLE;
  1790. // ============================================================================
  1791. // Macros for introducing new schedules in sub-classes
  1792. //
  1793. // Strings registries and schedules use unique ID's for each item, but
  1794. // sub-class enumerations are non-unique, so we translate between the
  1795. // enumerations and unique ID's
  1796. // ============================================================================
  1797. #define AI_BEGIN_CUSTOM_SCHEDULE_PROVIDER( derivedClass ) \
  1798. IMPLEMENT_CUSTOM_SCHEDULE_PROVIDER(derivedClass ) \
  1799. void derivedClass::InitCustomSchedules( void ) \
  1800. { \
  1801. typedef derivedClass CNpc; \
  1802. const char *pszClassName = #derivedClass; \
  1803. \
  1804. CUtlVector<const char *> schedulesToLoad; \
  1805. CUtlVector<AIScheduleLoadFunc_t> reqiredOthers; \
  1806. CAI_NamespaceInfos scheduleIds; \
  1807. CAI_NamespaceInfos taskIds; \
  1808. CAI_NamespaceInfos conditionIds;
  1809. //-----------------
  1810. #define AI_BEGIN_CUSTOM_NPC( className, derivedClass ) \
  1811. IMPLEMENT_CUSTOM_AI(className, derivedClass ) \
  1812. void derivedClass::InitCustomSchedules( void ) \
  1813. { \
  1814. typedef derivedClass CNpc; \
  1815. const char *pszClassName = #derivedClass; \
  1816. \
  1817. CUtlVector<const char *> schedulesToLoad; \
  1818. CUtlVector<AIScheduleLoadFunc_t> reqiredOthers; \
  1819. CAI_NamespaceInfos scheduleIds; \
  1820. CAI_NamespaceInfos taskIds; \
  1821. CAI_NamespaceInfos conditionIds; \
  1822. CAI_NamespaceInfos squadSlotIds;
  1823. //-----------------
  1824. #define EXTERN_SCHEDULE( id ) \
  1825. scheduleIds.PushBack( #id, id ); \
  1826. extern const char * g_psz##id; \
  1827. schedulesToLoad.AddToTail( g_psz##id );
  1828. //-----------------
  1829. #define DEFINE_SCHEDULE( id, text ) \
  1830. scheduleIds.PushBack( #id, id ); \
  1831. const char * g_psz##id = \
  1832. "\n Schedule" \
  1833. "\n " #id \
  1834. text \
  1835. "\n"; \
  1836. schedulesToLoad.AddToTail( g_psz##id );
  1837. //-----------------
  1838. #define DECLARE_CONDITION( id ) \
  1839. conditionIds.PushBack( #id, id );
  1840. //-----------------
  1841. #define DECLARE_TASK( id ) \
  1842. taskIds.PushBack( #id, id );
  1843. //-----------------
  1844. #define DECLARE_ACTIVITY( id ) \
  1845. ADD_CUSTOM_ACTIVITY( CNpc, id );
  1846. //-----------------
  1847. #define DECLARE_SQUADSLOT( id ) \
  1848. squadSlotIds.PushBack( #id, id );
  1849. //-----------------
  1850. #define DECLARE_INTERACTION( interaction ) \
  1851. ADD_CUSTOM_INTERACTION( interaction );
  1852. //-----------------
  1853. #define DECLARE_ANIMEVENT( id ) \
  1854. ADD_CUSTOM_ANIMEVENT( CNpc, id );
  1855. //-----------------
  1856. #define DECLARE_USES_SCHEDULE_PROVIDER( classname ) reqiredOthers.AddToTail( ScheduleLoadHelper(classname) );
  1857. //-----------------
  1858. // IDs are stored and then added in order due to constraints in the namespace implementation
  1859. #define AI_END_CUSTOM_SCHEDULE_PROVIDER() \
  1860. \
  1861. int i; \
  1862. \
  1863. CNpc::AccessClassScheduleIdSpaceDirect().Init( pszClassName, BaseClass::GetSchedulingSymbols(), &BaseClass::AccessClassScheduleIdSpaceDirect() ); \
  1864. \
  1865. scheduleIds.Sort(); \
  1866. taskIds.Sort(); \
  1867. conditionIds.Sort(); \
  1868. \
  1869. for ( i = 0; i < scheduleIds.Count(); i++ ) \
  1870. { \
  1871. ADD_CUSTOM_SCHEDULE_NAMED( CNpc, scheduleIds[i].pszName, scheduleIds[i].localId ); \
  1872. } \
  1873. \
  1874. for ( i = 0; i < taskIds.Count(); i++ ) \
  1875. { \
  1876. ADD_CUSTOM_TASK_NAMED( CNpc, taskIds[i].pszName, taskIds[i].localId ); \
  1877. } \
  1878. \
  1879. for ( i = 0; i < conditionIds.Count(); i++ ) \
  1880. { \
  1881. if ( ValidateConditionLimits( conditionIds[i].pszName ) ) \
  1882. { \
  1883. ADD_CUSTOM_CONDITION_NAMED( CNpc, conditionIds[i].pszName, conditionIds[i].localId ); \
  1884. } \
  1885. } \
  1886. \
  1887. for ( i = 0; i < reqiredOthers.Count(); i++ ) \
  1888. { \
  1889. (*reqiredOthers[i])(); \
  1890. } \
  1891. \
  1892. for ( i = 0; i < schedulesToLoad.Count(); i++ ) \
  1893. { \
  1894. if ( CNpc::gm_SchedLoadStatus.fValid ) \
  1895. { \
  1896. CNpc::gm_SchedLoadStatus.fValid = g_AI_SchedulesManager.LoadSchedulesFromBuffer( pszClassName, schedulesToLoad[i], &AccessClassScheduleIdSpaceDirect() ); \
  1897. } \
  1898. else \
  1899. break; \
  1900. } \
  1901. }
  1902. inline bool ValidateConditionLimits( const char *pszNewCondition )
  1903. {
  1904. int nGlobalConditions = CAI_BaseNPC::GetSchedulingSymbols()->NumConditions();
  1905. if ( nGlobalConditions >= MAX_CONDITIONS )
  1906. {
  1907. AssertMsg2( 0, "Exceeded max number of conditions (%d), ignoring condition %s\n", MAX_CONDITIONS, pszNewCondition );
  1908. DevWarning( "Exceeded max number of conditions (%d), ignoring condition %s\n", MAX_CONDITIONS, pszNewCondition );
  1909. return false;
  1910. }
  1911. return true;
  1912. }
  1913. //-------------------------------------
  1914. // IDs are stored and then added in order due to constraints in the namespace implementation
  1915. #define AI_END_CUSTOM_NPC() \
  1916. \
  1917. int i; \
  1918. \
  1919. CNpc::AccessClassScheduleIdSpaceDirect().Init( pszClassName, BaseClass::GetSchedulingSymbols(), &BaseClass::AccessClassScheduleIdSpaceDirect() ); \
  1920. CNpc::gm_SquadSlotIdSpace.Init( &BaseClass::gm_SquadSlotNamespace, &BaseClass::gm_SquadSlotIdSpace); \
  1921. \
  1922. scheduleIds.Sort(); \
  1923. taskIds.Sort(); \
  1924. conditionIds.Sort(); \
  1925. squadSlotIds.Sort(); \
  1926. \
  1927. for ( i = 0; i < scheduleIds.Count(); i++ ) \
  1928. { \
  1929. ADD_CUSTOM_SCHEDULE_NAMED( CNpc, scheduleIds[i].pszName, scheduleIds[i].localId ); \
  1930. } \
  1931. \
  1932. for ( i = 0; i < taskIds.Count(); i++ ) \
  1933. { \
  1934. ADD_CUSTOM_TASK_NAMED( CNpc, taskIds[i].pszName, taskIds[i].localId ); \
  1935. } \
  1936. \
  1937. for ( i = 0; i < conditionIds.Count(); i++ ) \
  1938. { \
  1939. if ( ValidateConditionLimits( conditionIds[i].pszName ) ) \
  1940. { \
  1941. ADD_CUSTOM_CONDITION_NAMED( CNpc, conditionIds[i].pszName, conditionIds[i].localId ); \
  1942. } \
  1943. } \
  1944. \
  1945. for ( i = 0; i < squadSlotIds.Count(); i++ ) \
  1946. { \
  1947. ADD_CUSTOM_SQUADSLOT_NAMED( CNpc, squadSlotIds[i].pszName, squadSlotIds[i].localId ); \
  1948. } \
  1949. \
  1950. for ( i = 0; i < reqiredOthers.Count(); i++ ) \
  1951. { \
  1952. (*reqiredOthers[i])(); \
  1953. } \
  1954. \
  1955. for ( i = 0; i < schedulesToLoad.Count(); i++ ) \
  1956. { \
  1957. if ( CNpc::gm_SchedLoadStatus.fValid ) \
  1958. { \
  1959. CNpc::gm_SchedLoadStatus.fValid = g_AI_SchedulesManager.LoadSchedulesFromBuffer( pszClassName, schedulesToLoad[i], &AccessClassScheduleIdSpaceDirect() ); \
  1960. } \
  1961. else \
  1962. break; \
  1963. } \
  1964. }
  1965. //-------------------------------------
  1966. struct AI_NamespaceAddInfo_t
  1967. {
  1968. AI_NamespaceAddInfo_t( const char *pszName, int localId )
  1969. : pszName( pszName ),
  1970. localId( localId )
  1971. {
  1972. }
  1973. const char *pszName;
  1974. int localId;
  1975. };
  1976. class CAI_NamespaceInfos : public CUtlVector<AI_NamespaceAddInfo_t>
  1977. {
  1978. public:
  1979. void PushBack( const char *pszName, int localId )
  1980. {
  1981. AddToTail( AI_NamespaceAddInfo_t( pszName, localId ) );
  1982. }
  1983. void Sort()
  1984. {
  1985. CUtlVector<AI_NamespaceAddInfo_t>::Sort( Compare );
  1986. }
  1987. private:
  1988. static int __cdecl Compare(const AI_NamespaceAddInfo_t *pLeft, const AI_NamespaceAddInfo_t *pRight )
  1989. {
  1990. return pLeft->localId - pRight->localId;
  1991. }
  1992. };
  1993. //-------------------------------------
  1994. // Declares the static variables that hold the string registry offset for the new subclass
  1995. // as well as the initialization in schedule load functions
  1996. struct AI_SchedLoadStatus_t
  1997. {
  1998. bool fValid;
  1999. int signature;
  2000. };
  2001. // Load schedules pulled out to support stepping through with debugger
  2002. inline bool AI_DoLoadSchedules( bool (*pfnBaseLoad)(), void (*pfnInitCustomSchedules)(),
  2003. AI_SchedLoadStatus_t *pLoadStatus )
  2004. {
  2005. (*pfnBaseLoad)();
  2006. if (pLoadStatus->signature != g_AI_SchedulesManager.GetScheduleLoadSignature())
  2007. {
  2008. (*pfnInitCustomSchedules)();
  2009. pLoadStatus->fValid = true;
  2010. pLoadStatus->signature = g_AI_SchedulesManager.GetScheduleLoadSignature();
  2011. }
  2012. return pLoadStatus->fValid;
  2013. }
  2014. //-------------------------------------
  2015. typedef bool (*AIScheduleLoadFunc_t)();
  2016. // @Note (toml 02-16-03): The following class exists to allow us to establish an anonymous friendship
  2017. // in DEFINE_CUSTOM_SCHEDULE_PROVIDER. The particulars of this implementation is almost entirely
  2018. // defined by bugs in MSVC 6.0
  2019. class ScheduleLoadHelperImpl
  2020. {
  2021. public:
  2022. template <typename T>
  2023. static AIScheduleLoadFunc_t AccessScheduleLoadFunc(T *)
  2024. {
  2025. return (&T::LoadSchedules);
  2026. }
  2027. };
  2028. #define ScheduleLoadHelper( type ) (ScheduleLoadHelperImpl::AccessScheduleLoadFunc((type *)0))
  2029. //-------------------------------------
  2030. #define DEFINE_CUSTOM_SCHEDULE_PROVIDER\
  2031. static AI_SchedLoadStatus_t gm_SchedLoadStatus; \
  2032. static CAI_ClassScheduleIdSpace gm_ClassScheduleIdSpace; \
  2033. static const char * gm_pszErrorClassName;\
  2034. \
  2035. static CAI_ClassScheduleIdSpace & AccessClassScheduleIdSpaceDirect() { return gm_ClassScheduleIdSpace; } \
  2036. virtual CAI_ClassScheduleIdSpace * GetClassScheduleIdSpace() { return &gm_ClassScheduleIdSpace; } \
  2037. virtual const char * GetSchedulingErrorName() { return gm_pszErrorClassName; } \
  2038. \
  2039. static void InitCustomSchedules(void);\
  2040. \
  2041. static bool LoadSchedules(void);\
  2042. virtual bool LoadedSchedules(void); \
  2043. \
  2044. friend class ScheduleLoadHelperImpl; \
  2045. \
  2046. class CScheduleLoader \
  2047. { \
  2048. public: \
  2049. CScheduleLoader(); \
  2050. } m_ScheduleLoader; \
  2051. \
  2052. friend class CScheduleLoader;
  2053. //-------------------------------------
  2054. #define DEFINE_CUSTOM_AI\
  2055. DEFINE_CUSTOM_SCHEDULE_PROVIDER \
  2056. \
  2057. static CAI_LocalIdSpace gm_SquadSlotIdSpace; \
  2058. \
  2059. const char* SquadSlotName (int squadSlotID);
  2060. //-------------------------------------
  2061. #define IMPLEMENT_CUSTOM_SCHEDULE_PROVIDER(derivedClass)\
  2062. AI_SchedLoadStatus_t derivedClass::gm_SchedLoadStatus = { true, -1 }; \
  2063. CAI_ClassScheduleIdSpace derivedClass::gm_ClassScheduleIdSpace; \
  2064. const char * derivedClass::gm_pszErrorClassName = #derivedClass; \
  2065. \
  2066. derivedClass::CScheduleLoader::CScheduleLoader()\
  2067. { \
  2068. derivedClass::LoadSchedules(); \
  2069. } \
  2070. \
  2071. /* --------------------------------------------- */ \
  2072. /* Load schedules for this type of NPC */ \
  2073. /* --------------------------------------------- */ \
  2074. bool derivedClass::LoadSchedules(void)\
  2075. {\
  2076. return AI_DoLoadSchedules( derivedClass::BaseClass::LoadSchedules, \
  2077. derivedClass::InitCustomSchedules, \
  2078. &derivedClass::gm_SchedLoadStatus ); \
  2079. }\
  2080. \
  2081. bool derivedClass::LoadedSchedules(void) \
  2082. { \
  2083. return derivedClass::gm_SchedLoadStatus.fValid;\
  2084. }
  2085. //-------------------------------------
  2086. // Initialize offsets and implement methods for loading and getting squad info for the subclass
  2087. #define IMPLEMENT_CUSTOM_AI(className, derivedClass)\
  2088. IMPLEMENT_CUSTOM_SCHEDULE_PROVIDER(derivedClass)\
  2089. \
  2090. CAI_LocalIdSpace derivedClass::gm_SquadSlotIdSpace; \
  2091. \
  2092. /* -------------------------------------------------- */ \
  2093. /* Given squadSlot enumeration return squadSlot name */ \
  2094. /* -------------------------------------------------- */ \
  2095. const char* derivedClass::SquadSlotName(int slotEN)\
  2096. {\
  2097. return gm_SquadSlotNamespace.IdToSymbol( derivedClass::gm_SquadSlotIdSpace.LocalToGlobal(slotEN) );\
  2098. }
  2099. //-------------------------------------
  2100. #define ADD_CUSTOM_SCHEDULE_NAMED(derivedClass,schedName,schedEN)\
  2101. if ( !derivedClass::AccessClassScheduleIdSpaceDirect().AddSchedule( schedName, schedEN, derivedClass::gm_pszErrorClassName ) ) return;
  2102. #define ADD_CUSTOM_SCHEDULE(derivedClass,schedEN) ADD_CUSTOM_SCHEDULE_NAMED(derivedClass,#schedEN,schedEN)
  2103. #define ADD_CUSTOM_TASK_NAMED(derivedClass,taskName,taskEN)\
  2104. if ( !derivedClass::AccessClassScheduleIdSpaceDirect().AddTask( taskName, taskEN, derivedClass::gm_pszErrorClassName ) ) return;
  2105. #define ADD_CUSTOM_TASK(derivedClass,taskEN) ADD_CUSTOM_TASK_NAMED(derivedClass,#taskEN,taskEN)
  2106. #define ADD_CUSTOM_CONDITION_NAMED(derivedClass,condName,condEN)\
  2107. if ( !derivedClass::AccessClassScheduleIdSpaceDirect().AddCondition( condName, condEN, derivedClass::gm_pszErrorClassName ) ) return;
  2108. #define ADD_CUSTOM_CONDITION(derivedClass,condEN) ADD_CUSTOM_CONDITION_NAMED(derivedClass,#condEN,condEN)
  2109. //-------------------------------------
  2110. #define INIT_CUSTOM_AI(derivedClass)\
  2111. derivedClass::AccessClassScheduleIdSpaceDirect().Init( #derivedClass, BaseClass::GetSchedulingSymbols(), &BaseClass::AccessClassScheduleIdSpaceDirect() ); \
  2112. derivedClass::gm_SquadSlotIdSpace.Init( &CAI_BaseNPC::gm_SquadSlotNamespace, &BaseClass::gm_SquadSlotIdSpace);
  2113. #define ADD_CUSTOM_INTERACTION( interaction ) { interaction = CBaseCombatCharacter::GetInteractionID(); }
  2114. #define ADD_CUSTOM_SQUADSLOT_NAMED(derivedClass,squadSlotName,squadSlotEN)\
  2115. if ( !derivedClass::gm_SquadSlotIdSpace.AddSymbol( squadSlotName, squadSlotEN, "squadslot", derivedClass::gm_pszErrorClassName ) ) return;
  2116. #define ADD_CUSTOM_SQUADSLOT(derivedClass,squadSlotEN) ADD_CUSTOM_SQUADSLOT_NAMED(derivedClass,#squadSlotEN,squadSlotEN)
  2117. #define ADD_CUSTOM_ACTIVITY_NAMED(derivedClass,activityName,activityEnum)\
  2118. REGISTER_PRIVATE_ACTIVITY(activityEnum);\
  2119. CAI_BaseNPC::AddActivityToSR(activityName,activityEnum);
  2120. #define ADD_CUSTOM_ACTIVITY(derivedClass,activityEnum) ADD_CUSTOM_ACTIVITY_NAMED(derivedClass,#activityEnum,activityEnum)
  2121. #define ADD_CUSTOM_ANIMEVENT_NAMED(derivedClass,eventName,eventEnum)\
  2122. REGISTER_PRIVATE_ANIMEVENT(eventEnum);\
  2123. CAI_BaseNPC::AddEventToSR(eventName,eventEnum);
  2124. #define ADD_CUSTOM_ANIMEVENT(derivedClass,eventEnum) ADD_CUSTOM_ANIMEVENT_NAMED(derivedClass,#eventEnum,eventEnum)
  2125. //=============================================================================
  2126. // class CAI_Component
  2127. //=============================================================================
  2128. inline const Vector &CAI_Component::GetLocalOrigin() const
  2129. {
  2130. return GetOuter()->GetLocalOrigin();
  2131. }
  2132. //-----------------------------------------------------------------------------
  2133. inline void CAI_Component::SetLocalOrigin(const Vector &origin)
  2134. {
  2135. GetOuter()->SetLocalOrigin(origin);
  2136. }
  2137. //-----------------------------------------------------------------------------
  2138. inline const Vector &CAI_Component::GetAbsOrigin() const
  2139. {
  2140. return GetOuter()->GetAbsOrigin();
  2141. }
  2142. //-----------------------------------------------------------------------------
  2143. inline const QAngle &CAI_Component::GetAbsAngles() const
  2144. {
  2145. return GetOuter()->GetAbsAngles();
  2146. }
  2147. //-----------------------------------------------------------------------------
  2148. inline void CAI_Component::SetSolid( SolidType_t val )
  2149. {
  2150. GetOuter()->SetSolid(val);
  2151. }
  2152. //-----------------------------------------------------------------------------
  2153. inline SolidType_t CAI_Component::GetSolid() const
  2154. {
  2155. return GetOuter()->GetSolid();
  2156. }
  2157. //-----------------------------------------------------------------------------
  2158. inline const Vector &CAI_Component::WorldAlignMins() const
  2159. {
  2160. return GetOuter()->WorldAlignMins();
  2161. }
  2162. //-----------------------------------------------------------------------------
  2163. inline const Vector &CAI_Component::WorldAlignMaxs() const
  2164. {
  2165. return GetOuter()->WorldAlignMaxs();
  2166. }
  2167. //-----------------------------------------------------------------------------
  2168. inline Hull_t CAI_Component::GetHullType() const
  2169. {
  2170. return GetOuter()->GetHullType();
  2171. }
  2172. //-----------------------------------------------------------------------------
  2173. inline Vector CAI_Component::WorldSpaceCenter() const
  2174. {
  2175. return GetOuter()->WorldSpaceCenter();
  2176. }
  2177. //-----------------------------------------------------------------------------
  2178. inline float CAI_Component::GetGravity() const
  2179. {
  2180. return GetOuter()->GetGravity();
  2181. }
  2182. //-----------------------------------------------------------------------------
  2183. inline void CAI_Component::SetGravity( float flGravity )
  2184. {
  2185. GetOuter()->SetGravity( flGravity );
  2186. }
  2187. //-----------------------------------------------------------------------------
  2188. inline float CAI_Component::GetHullWidth() const
  2189. {
  2190. return NAI_Hull::Width(GetOuter()->GetHullType());
  2191. }
  2192. //-----------------------------------------------------------------------------
  2193. inline float CAI_Component::GetHullHeight() const
  2194. {
  2195. return NAI_Hull::Height(GetOuter()->GetHullType());
  2196. }
  2197. //-----------------------------------------------------------------------------
  2198. inline const Vector &CAI_Component::GetHullMins() const
  2199. {
  2200. return NAI_Hull::Mins(GetOuter()->GetHullType());
  2201. }
  2202. //-----------------------------------------------------------------------------
  2203. inline const Vector &CAI_Component::GetHullMaxs() const
  2204. {
  2205. return NAI_Hull::Maxs(GetOuter()->GetHullType());
  2206. }
  2207. //-----------------------------------------------------------------------------
  2208. inline int CAI_Component::GetCollisionGroup() const
  2209. {
  2210. return GetOuter()->GetCollisionGroup();
  2211. }
  2212. //-----------------------------------------------------------------------------
  2213. inline CBaseEntity *CAI_Component::GetEnemy()
  2214. {
  2215. return GetOuter()->GetEnemy();
  2216. }
  2217. //-----------------------------------------------------------------------------
  2218. inline const Vector &CAI_Component::GetEnemyLKP() const
  2219. {
  2220. return GetOuter()->GetEnemyLKP();
  2221. }
  2222. //-----------------------------------------------------------------------------
  2223. inline void CAI_Component::TranslateNavGoal( CBaseEntity *pEnemy, Vector &chasePosition )
  2224. {
  2225. GetOuter()->TranslateNavGoal( pEnemy, chasePosition );
  2226. }
  2227. //-----------------------------------------------------------------------------
  2228. inline CBaseEntity *CAI_Component::GetTarget()
  2229. {
  2230. return GetOuter()->GetTarget();
  2231. }
  2232. //-----------------------------------------------------------------------------
  2233. inline void CAI_Component::SetTarget( CBaseEntity *pTarget )
  2234. {
  2235. GetOuter()->SetTarget( pTarget );
  2236. }
  2237. //-----------------------------------------------------------------------------
  2238. inline const Task_t *CAI_Component::GetCurTask()
  2239. {
  2240. return GetOuter()->GetTask();
  2241. }
  2242. //-----------------------------------------------------------------------------
  2243. inline void CAI_Component::TaskFail( AI_TaskFailureCode_t code )
  2244. {
  2245. GetOuter()->TaskFail( code );
  2246. }
  2247. //-----------------------------------------------------------------------------
  2248. inline void CAI_Component::TaskFail( const char *pszGeneralFailText )
  2249. {
  2250. GetOuter()->TaskFail( pszGeneralFailText );
  2251. }
  2252. //-----------------------------------------------------------------------------
  2253. inline void CAI_Component::TaskComplete( bool fIgnoreSetFailedCondition )
  2254. {
  2255. GetOuter()->TaskComplete( fIgnoreSetFailedCondition );
  2256. }
  2257. //-----------------------------------------------------------------------------
  2258. inline int CAI_Component::TaskIsRunning()
  2259. {
  2260. return GetOuter()->TaskIsRunning();
  2261. }
  2262. //-----------------------------------------------------------------------------
  2263. inline int CAI_Component::TaskIsComplete()
  2264. {
  2265. return GetOuter()->TaskIsComplete();
  2266. }
  2267. //-----------------------------------------------------------------------------
  2268. inline Activity CAI_Component::GetActivity()
  2269. {
  2270. return GetOuter()->GetActivity();
  2271. }
  2272. //-----------------------------------------------------------------------------
  2273. inline void CAI_Component::SetActivity( Activity NewActivity )
  2274. {
  2275. GetOuter()->SetActivity( NewActivity );
  2276. }
  2277. //-----------------------------------------------------------------------------
  2278. inline float CAI_Component::GetIdealSpeed() const
  2279. {
  2280. return GetOuter()->GetIdealSpeed();
  2281. }
  2282. //-----------------------------------------------------------------------------
  2283. inline float CAI_Component::GetIdealAccel() const
  2284. {
  2285. return GetOuter()->GetIdealAccel();
  2286. }
  2287. //-----------------------------------------------------------------------------
  2288. inline int CAI_Component::GetSequence()
  2289. {
  2290. return GetOuter()->GetSequence();
  2291. }
  2292. //-----------------------------------------------------------------------------
  2293. inline int CAI_Component::GetEntFlags() const
  2294. {
  2295. return GetOuter()->GetFlags();
  2296. }
  2297. //-----------------------------------------------------------------------------
  2298. inline void CAI_Component::AddEntFlag( int flags )
  2299. {
  2300. GetOuter()->AddFlag( flags );
  2301. }
  2302. //-----------------------------------------------------------------------------
  2303. inline void CAI_Component::RemoveEntFlag( int flagsToRemove )
  2304. {
  2305. GetOuter()->RemoveFlag( flagsToRemove );
  2306. }
  2307. //-----------------------------------------------------------------------------
  2308. // Purpose: Change the ground entity for the outer
  2309. // Input : *ground -
  2310. // Output : inline void
  2311. //-----------------------------------------------------------------------------
  2312. inline void CAI_Component::SetGroundEntity( CBaseEntity *ground )
  2313. {
  2314. GetOuter()->SetGroundEntity( ground );
  2315. }
  2316. //-----------------------------------------------------------------------------
  2317. inline void CAI_Component::ToggleEntFlag( int flagToToggle )
  2318. {
  2319. GetOuter()->ToggleFlag( flagToToggle );
  2320. }
  2321. //-----------------------------------------------------------------------------
  2322. inline CBaseEntity* CAI_Component::GetGoalEnt()
  2323. {
  2324. return GetOuter()->GetGoalEnt();
  2325. }
  2326. //-----------------------------------------------------------------------------
  2327. inline void CAI_Component::SetGoalEnt( CBaseEntity *pGoalEnt )
  2328. {
  2329. GetOuter()->SetGoalEnt( pGoalEnt );
  2330. }
  2331. //-----------------------------------------------------------------------------
  2332. inline void CAI_Component::Remember( int iMemory )
  2333. {
  2334. GetOuter()->Remember( iMemory );
  2335. }
  2336. //-----------------------------------------------------------------------------
  2337. inline void CAI_Component::Forget( int iMemory )
  2338. {
  2339. GetOuter()->Forget( iMemory );
  2340. }
  2341. //-----------------------------------------------------------------------------
  2342. inline bool CAI_Component::HasMemory( int iMemory )
  2343. {
  2344. return GetOuter()->HasMemory( iMemory );
  2345. }
  2346. //-----------------------------------------------------------------------------
  2347. inline CAI_Enemies *CAI_Component::GetEnemies()
  2348. {
  2349. return GetOuter()->GetEnemies();
  2350. }
  2351. //-----------------------------------------------------------------------------
  2352. inline const char *CAI_Component::GetEntClassname()
  2353. {
  2354. return GetOuter()->GetClassname();
  2355. }
  2356. //-----------------------------------------------------------------------------
  2357. inline int CAI_Component::CapabilitiesGet()
  2358. {
  2359. return GetOuter()->CapabilitiesGet();
  2360. }
  2361. //-----------------------------------------------------------------------------
  2362. inline void CAI_Component::SetLocalAngles( const QAngle& angles )
  2363. {
  2364. GetOuter()->SetLocalAngles( angles );
  2365. }
  2366. //-----------------------------------------------------------------------------
  2367. inline const QAngle &CAI_Component::GetLocalAngles( void ) const
  2368. {
  2369. return GetOuter()->GetLocalAngles();
  2370. }
  2371. //-----------------------------------------------------------------------------
  2372. inline edict_t *CAI_Component::GetEdict()
  2373. {
  2374. return GetOuter()->NetworkProp()->edict();
  2375. }
  2376. //-----------------------------------------------------------------------------
  2377. inline float CAI_Component::GetLastThink( const char *szContext )
  2378. {
  2379. return GetOuter()->GetLastThink( szContext );
  2380. }
  2381. // ============================================================================
  2382. abstract_class INPCInteractive
  2383. {
  2384. public:
  2385. virtual bool CanInteractWith( CAI_BaseNPC *pUser ) = 0;
  2386. virtual bool HasBeenInteractedWith() = 0;
  2387. virtual void NotifyInteraction( CAI_BaseNPC *pUser ) = 0;
  2388. // Alyx specific interactions
  2389. virtual void AlyxStartedInteraction( void ) = 0;
  2390. virtual void AlyxFinishedInteraction( void ) = 0;
  2391. };
  2392. // Base Class for any NPC that wants to be interactable by other NPCS (i.e. Alyx Hackable)
  2393. // NOTE: YOU MUST DEFINE THE OUTPUTS IN YOUR CLASS'S DATADESC!
  2394. // THE DO SO, INSERT THE FOLLOWING MACRO INTO YOUR CLASS'S DATADESC.
  2395. //
  2396. #define DEFINE_BASENPCINTERACTABLE_DATADESC() \
  2397. DEFINE_OUTPUT( m_OnAlyxStartedInteraction, "OnAlyxStartedInteraction" ), \
  2398. DEFINE_OUTPUT( m_OnAlyxFinishedInteraction, "OnAlyxFinishedInteraction" ), \
  2399. DEFINE_INPUTFUNC( FIELD_VOID, "InteractivePowerDown", InputPowerdown )
  2400. template <class NPC_CLASS>
  2401. class CNPCBaseInteractive : public NPC_CLASS, public INPCInteractive
  2402. {
  2403. DECLARE_CLASS( CNPCBaseInteractive, NPC_CLASS );
  2404. public:
  2405. virtual bool CanInteractWith( CAI_BaseNPC *pUser ) { return false; };
  2406. virtual bool HasBeenInteractedWith() { return false; };
  2407. virtual void NotifyInteraction( CAI_BaseNPC *pUser ) { return; };
  2408. virtual void InputPowerdown( inputdata_t &inputdata )
  2409. {
  2410. }
  2411. // Alyx specific interactions
  2412. virtual void AlyxStartedInteraction( void )
  2413. {
  2414. m_OnAlyxStartedInteraction.FireOutput( this, this );
  2415. }
  2416. virtual void AlyxFinishedInteraction( void )
  2417. {
  2418. m_OnAlyxFinishedInteraction.FireOutput( this, this );
  2419. }
  2420. public:
  2421. // Outputs
  2422. // Alyx specific interactions
  2423. COutputEvent m_OnAlyxStartedInteraction;
  2424. COutputEvent m_OnAlyxFinishedInteraction;
  2425. };
  2426. //
  2427. // Deferred Navigation calls go here
  2428. //
  2429. extern ConVar ai_post_frame_navigation;
  2430. class CPostFrameNavigationHook : public CBaseGameSystemPerFrame
  2431. {
  2432. public:
  2433. virtual const char *Name( void ) { return "CPostFrameNavigationHook"; }
  2434. virtual bool Init( void );
  2435. virtual void FrameUpdatePostEntityThink( void );
  2436. virtual void FrameUpdatePreEntityThink( void );
  2437. bool IsGameFrameRunning( void ) { return m_bGameFrameRunning; }
  2438. void SetGrameFrameRunning( bool bState ) { m_bGameFrameRunning = bState; }
  2439. void EnqueueEntityNavigationQuery( CAI_BaseNPC *pNPC, CFunctor *functor );
  2440. private:
  2441. CUtlVector<CFunctor *> m_Functors;
  2442. bool m_bGameFrameRunning;
  2443. };
  2444. extern CPostFrameNavigationHook *PostFrameNavigationSystem( void );
  2445. #endif // AI_BASENPC_H