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.

2004 lines
75 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //=============================================================================//
  7. //
  8. // Author: Michael S. Booth ([email protected]), 2003
  9. //
  10. // NOTE: The CS Bot code uses Doxygen-style comments. If you run Doxygen over this code, it will
  11. // auto-generate documentation. Visit www.doxygen.org to download the system for free.
  12. //
  13. #ifndef _CS_BOT_H_
  14. #define _CS_BOT_H_
  15. #include "bot/bot.h"
  16. #include "bot/cs_bot_manager.h"
  17. #include "bot/cs_bot_chatter.h"
  18. #include "cs_gamestate.h"
  19. #include "cs_player.h"
  20. #include "weapon_csbase.h"
  21. #include "cs_nav_pathfind.h"
  22. #include "cs_nav_area.h"
  23. class CBaseDoor;
  24. class CBasePropDoor;
  25. class CCSBot;
  26. class CPushAwayEnumerator;
  27. //--------------------------------------------------------------------------------------------------------------
  28. /**
  29. * For use with player->m_rgpPlayerItems[]
  30. */
  31. enum InventorySlotType
  32. {
  33. PRIMARY_WEAPON_SLOT = 1,
  34. PISTOL_SLOT,
  35. KNIFE_SLOT,
  36. GRENADE_SLOT,
  37. C4_SLOT
  38. };
  39. //--------------------------------------------------------------------------------------------------------------
  40. /**
  41. * The definition of a bot's behavior state. One or more finite state machines
  42. * using these states implement a bot's behaviors.
  43. */
  44. class BotState
  45. {
  46. public:
  47. virtual void OnEnter( CCSBot *bot ) { } ///< when state is entered
  48. virtual void OnUpdate( CCSBot *bot ) { } ///< state behavior
  49. virtual void OnExit( CCSBot *bot ) { } ///< when state exited
  50. virtual const char *GetName( void ) const = 0; ///< return state name
  51. };
  52. //--------------------------------------------------------------------------------------------------------------
  53. /**
  54. * The state is invoked when a bot has nothing to do, or has finished what it was doing.
  55. * A bot never stays in this state - it is the main action selection mechanism.
  56. */
  57. class IdleState : public BotState
  58. {
  59. public:
  60. virtual void OnEnter( CCSBot *bot );
  61. virtual void OnUpdate( CCSBot *bot );
  62. virtual const char *GetName( void ) const { return "Idle"; }
  63. };
  64. //--------------------------------------------------------------------------------------------------------------
  65. /**
  66. * When a bot is actively searching for an enemy.
  67. */
  68. class HuntState : public BotState
  69. {
  70. public:
  71. virtual void OnEnter( CCSBot *bot );
  72. virtual void OnUpdate( CCSBot *bot );
  73. virtual void OnExit( CCSBot *bot );
  74. virtual const char *GetName( void ) const { return "Hunt"; }
  75. void ClearHuntArea( void ) { m_huntArea = NULL; }
  76. private:
  77. CNavArea *m_huntArea; ///< "far away" area we are moving to
  78. };
  79. //--------------------------------------------------------------------------------------------------------------
  80. /**
  81. * When a bot has an enemy and is attempting to kill it
  82. */
  83. class AttackState : public BotState
  84. {
  85. public:
  86. virtual void OnEnter( CCSBot *bot );
  87. virtual void OnUpdate( CCSBot *bot );
  88. virtual void OnExit( CCSBot *bot );
  89. virtual const char *GetName( void ) const { return "Attack"; }
  90. void SetCrouchAndHold( bool crouch ) { m_crouchAndHold = crouch; }
  91. protected:
  92. enum DodgeStateType
  93. {
  94. STEADY_ON,
  95. SLIDE_LEFT,
  96. SLIDE_RIGHT,
  97. JUMP,
  98. NUM_ATTACK_STATES
  99. };
  100. DodgeStateType m_dodgeState;
  101. float m_nextDodgeStateTimestamp;
  102. CountdownTimer m_repathTimer;
  103. float m_scopeTimestamp;
  104. bool m_haveSeenEnemy; ///< false if we haven't yet seen the enemy since we started this attack (told by a friend, etc)
  105. bool m_isEnemyHidden; ///< true we if we have lost line-of-sight to our enemy
  106. float m_reacquireTimestamp; ///< time when we can fire again, after losing enemy behind cover
  107. float m_shieldToggleTimestamp; ///< time to toggle shield deploy state
  108. bool m_shieldForceOpen; ///< if true, open up and shoot even if in danger
  109. float m_pinnedDownTimestamp; ///< time when we'll consider ourselves "pinned down" by the enemy
  110. bool m_crouchAndHold;
  111. bool m_didAmbushCheck;
  112. bool m_shouldDodge;
  113. bool m_firstDodge;
  114. bool m_isCoward; ///< if true, we'll retreat if outnumbered during this fight
  115. CountdownTimer m_retreatTimer;
  116. void StopAttacking( CCSBot *bot );
  117. void Dodge( CCSBot *bot ); ///< do dodge behavior
  118. };
  119. //--------------------------------------------------------------------------------------------------------------
  120. /**
  121. * When a bot has heard an enemy noise and is moving to find out what it was.
  122. */
  123. class InvestigateNoiseState : public BotState
  124. {
  125. public:
  126. virtual void OnEnter( CCSBot *bot );
  127. virtual void OnUpdate( CCSBot *bot );
  128. virtual void OnExit( CCSBot *bot );
  129. virtual const char *GetName( void ) const { return "InvestigateNoise"; }
  130. private:
  131. void AttendCurrentNoise( CCSBot *bot ); ///< move towards currently heard noise
  132. Vector m_checkNoisePosition; ///< the position of the noise we're investigating
  133. CountdownTimer m_minTimer; ///< minimum time we will investigate our current noise
  134. };
  135. //--------------------------------------------------------------------------------------------------------------
  136. /**
  137. * When a bot is buying equipment at the start of a round.
  138. */
  139. class BuyState : public BotState
  140. {
  141. public:
  142. virtual void OnEnter( CCSBot *bot );
  143. virtual void OnUpdate( CCSBot *bot );
  144. virtual void OnExit( CCSBot *bot );
  145. virtual const char *GetName( void ) const { return "Buy"; }
  146. private:
  147. bool m_isInitialDelay;
  148. int m_prefRetries; ///< for retrying buying preferred weapon at current index
  149. int m_prefIndex; ///< where are we in our list of preferred weapons
  150. int m_retries;
  151. bool m_doneBuying;
  152. bool m_buyDefuseKit;
  153. bool m_buyGrenade;
  154. bool m_buyShield;
  155. bool m_buyPistol;
  156. };
  157. //--------------------------------------------------------------------------------------------------------------
  158. /**
  159. * When a bot is moving to a potentially far away position in the world.
  160. */
  161. class MoveToState : public BotState
  162. {
  163. public:
  164. virtual void OnEnter( CCSBot *bot );
  165. virtual void OnUpdate( CCSBot *bot );
  166. virtual void OnExit( CCSBot *bot );
  167. virtual const char *GetName( void ) const { return "MoveTo"; }
  168. void SetGoalPosition( const Vector &pos ) { m_goalPosition = pos; }
  169. void SetRouteType( RouteType route ) { m_routeType = route; }
  170. private:
  171. Vector m_goalPosition; ///< goal position of move
  172. RouteType m_routeType; ///< the kind of route to build
  173. bool m_radioedPlan;
  174. bool m_askedForCover;
  175. };
  176. //--------------------------------------------------------------------------------------------------------------
  177. /**
  178. * When a Terrorist bot is moving to pick up a dropped bomb.
  179. */
  180. class FetchBombState : public BotState
  181. {
  182. public:
  183. virtual void OnEnter( CCSBot *bot );
  184. virtual void OnUpdate( CCSBot *bot );
  185. virtual const char *GetName( void ) const { return "FetchBomb"; }
  186. };
  187. //--------------------------------------------------------------------------------------------------------------
  188. /**
  189. * When a Terrorist bot is actually planting the bomb.
  190. */
  191. class PlantBombState : public BotState
  192. {
  193. public:
  194. virtual void OnEnter( CCSBot *bot );
  195. virtual void OnUpdate( CCSBot *bot );
  196. virtual void OnExit( CCSBot *bot );
  197. virtual const char *GetName( void ) const { return "PlantBomb"; }
  198. };
  199. //--------------------------------------------------------------------------------------------------------------
  200. /**
  201. * When a CT bot is actually defusing a live bomb.
  202. */
  203. class DefuseBombState : public BotState
  204. {
  205. public:
  206. virtual void OnEnter( CCSBot *bot );
  207. virtual void OnUpdate( CCSBot *bot );
  208. virtual void OnExit( CCSBot *bot );
  209. virtual const char *GetName( void ) const { return "DefuseBomb"; }
  210. };
  211. //--------------------------------------------------------------------------------------------------------------
  212. /**
  213. * When a bot is hiding in a corner.
  214. * NOTE: This state also includes MOVING TO that hiding spot, which may be all the way
  215. * across the map!
  216. */
  217. class HideState : public BotState
  218. {
  219. public:
  220. virtual void OnEnter( CCSBot *bot );
  221. virtual void OnUpdate( CCSBot *bot );
  222. virtual void OnExit( CCSBot *bot );
  223. virtual const char *GetName( void ) const { return "Hide"; }
  224. void SetHidingSpot( const Vector &pos ) { m_hidingSpot = pos; }
  225. const Vector &GetHidingSpot( void ) const { return m_hidingSpot; }
  226. void SetSearchArea( CNavArea *area ) { m_searchFromArea = area; }
  227. void SetSearchRange( float range ) { m_range = range; }
  228. void SetDuration( float time ) { m_duration = time; }
  229. void SetHoldPosition( bool hold ) { m_isHoldingPosition = hold; }
  230. bool IsAtSpot( void ) const { return m_isAtSpot; }
  231. float GetHideTime( void ) const
  232. {
  233. if (IsAtSpot())
  234. {
  235. return m_duration - m_hideTimer.GetRemainingTime();
  236. }
  237. return 0.0f;
  238. }
  239. private:
  240. CNavArea *m_searchFromArea;
  241. float m_range;
  242. Vector m_hidingSpot;
  243. bool m_isLookingOutward;
  244. bool m_isAtSpot;
  245. float m_duration;
  246. CountdownTimer m_hideTimer; ///< how long to hide
  247. bool m_isHoldingPosition;
  248. float m_holdPositionTime; ///< how long to hold our position after we hear nearby enemy noise
  249. bool m_heardEnemy; ///< set to true when we first hear an enemy
  250. float m_firstHeardEnemyTime; ///< when we first heard the enemy
  251. int m_retry; ///< counter for retrying hiding spot
  252. Vector m_leaderAnchorPos; ///< the position of our follow leader when we decided to hide
  253. bool m_isPaused; ///< if true, we have paused in our retreat for a moment
  254. CountdownTimer m_pauseTimer; ///< for stoppping and starting our pauses while we retreat
  255. };
  256. //--------------------------------------------------------------------------------------------------------------
  257. /**
  258. * When a bot is attempting to flee from a bomb that is about to explode.
  259. */
  260. class EscapeFromBombState : public BotState
  261. {
  262. public:
  263. virtual void OnEnter( CCSBot *bot );
  264. virtual void OnUpdate( CCSBot *bot );
  265. virtual void OnExit( CCSBot *bot );
  266. virtual const char *GetName( void ) const { return "EscapeFromBomb"; }
  267. };
  268. //--------------------------------------------------------------------------------------------------------------
  269. /**
  270. * When a bot is following another player.
  271. */
  272. class FollowState : public BotState
  273. {
  274. public:
  275. virtual void OnEnter( CCSBot *bot );
  276. virtual void OnUpdate( CCSBot *bot );
  277. virtual void OnExit( CCSBot *bot );
  278. virtual const char *GetName( void ) const { return "Follow"; }
  279. void SetLeader( CCSPlayer *player ) { m_leader = player; }
  280. private:
  281. CHandle< CCSPlayer > m_leader; ///< the player we are following
  282. Vector m_lastLeaderPos; ///< where the leader was when we computed our follow path
  283. bool m_isStopped;
  284. float m_stoppedTimestamp;
  285. enum LeaderMotionStateType
  286. {
  287. INVALID,
  288. STOPPED,
  289. WALKING,
  290. RUNNING
  291. };
  292. LeaderMotionStateType m_leaderMotionState;
  293. IntervalTimer m_leaderMotionStateTime;
  294. bool m_isSneaking;
  295. float m_lastSawLeaderTime;
  296. CountdownTimer m_repathInterval;
  297. IntervalTimer m_walkTime;
  298. bool m_isAtWalkSpeed;
  299. float m_waitTime;
  300. CountdownTimer m_idleTimer;
  301. void ComputeLeaderMotionState( float leaderSpeed );
  302. };
  303. //--------------------------------------------------------------------------------------------------------------
  304. /**
  305. * When a bot is actually using another entity (ie: facing towards it and pressing the use key)
  306. */
  307. class UseEntityState : public BotState
  308. {
  309. public:
  310. virtual void OnEnter( CCSBot *bot );
  311. virtual void OnUpdate( CCSBot *bot );
  312. virtual void OnExit( CCSBot *bot );
  313. virtual const char *GetName( void ) const { return "UseEntity"; }
  314. void SetEntity( CBaseEntity *entity ) { m_entity = entity; }
  315. private:
  316. EHANDLE m_entity; ///< the entity we will use
  317. };
  318. //--------------------------------------------------------------------------------------------------------------
  319. /**
  320. * When a bot is opening a door
  321. */
  322. class OpenDoorState : public BotState
  323. {
  324. public:
  325. virtual void OnEnter( CCSBot *bot );
  326. virtual void OnUpdate( CCSBot *bot );
  327. virtual void OnExit( CCSBot *bot );
  328. virtual const char *GetName( void ) const { return "OpenDoor"; }
  329. void SetDoor( CBaseEntity *door );
  330. bool IsDone( void ) const { return m_isDone; } ///< return true if behavior is done
  331. private:
  332. CHandle< CBaseDoor > m_funcDoor; ///< the func_door we are opening
  333. CHandle< CBasePropDoor > m_propDoor; ///< the prop_door we are opening
  334. bool m_isDone;
  335. CountdownTimer m_timeout;
  336. };
  337. //--------------------------------------------------------------------------------------------------------------
  338. //--------------------------------------------------------------------------------------------------------------
  339. /**
  340. * The Counter-strike Bot
  341. */
  342. class CCSBot : public CBot< CCSPlayer >
  343. {
  344. public:
  345. DECLARE_CLASS( CCSBot, CBot< CCSPlayer > );
  346. DECLARE_DATADESC();
  347. CCSBot( void ); ///< constructor initializes all values to zero
  348. virtual ~CCSBot();
  349. virtual bool Initialize( const BotProfile *profile, int team ); ///< (EXTEND) prepare bot for action
  350. virtual void Spawn( void ); ///< (EXTEND) spawn the bot into the game
  351. virtual void Touch( CBaseEntity *other ); ///< (EXTEND) when touched by another entity
  352. virtual void Upkeep( void ); ///< lightweight maintenance, invoked frequently
  353. virtual void Update( void ); ///< heavyweight algorithms, invoked less often
  354. virtual void BuildUserCmd( CUserCmd& cmd, const QAngle& viewangles, float forwardmove, float sidemove, float upmove, int buttons, byte impulse );
  355. virtual float GetMoveSpeed( void ); ///< returns current movement speed (for walk/run)
  356. virtual void Walk( void );
  357. virtual bool Jump( bool mustJump = false ); ///< returns true if jump was started
  358. //- behavior properties ------------------------------------------------------------------------------------------
  359. float GetCombatRange( void ) const;
  360. bool IsRogue( void ) const; ///< return true if we dont listen to teammates or pursue scenario goals
  361. void SetRogue( bool rogue );
  362. bool IsHurrying( void ) const; ///< return true if we are in a hurry
  363. void Hurry( float duration ); ///< force bot to hurry
  364. bool IsSafe( void ) const; ///< return true if we are in a safe region
  365. bool IsWellPastSafe( void ) const; ///< return true if it is well past the early, "safe", part of the round
  366. bool IsEndOfSafeTime( void ) const; ///< return true if we were in the safe time last update, but not now
  367. float GetSafeTimeRemaining( void ) const; ///< return the amount of "safe time" we have left
  368. float GetSafeTime( void ) const; ///< return what we think the total "safe time" for this map is
  369. virtual void Blind( float holdTime, float fadeTime, float startingAlpha = 255 ); // player blinded by a flashbang
  370. bool IsUnhealthy( void ) const; ///< returns true if bot is low on health
  371. bool IsAlert( void ) const; ///< return true if bot is in heightened "alert" mode
  372. void BecomeAlert( void ); ///< bot becomes "alert" for immediately nearby enemies
  373. bool IsSneaking( void ) const; ///< return true if bot is sneaking
  374. void Sneak( float duration ); ///< sneak for given duration
  375. //- behaviors ---------------------------------------------------------------------------------------------------
  376. void Idle( void );
  377. void Hide( CNavArea *searchFromArea = NULL, float duration = -1.0f, float hideRange = 750.0f, bool holdPosition = false ); ///< DEPRECATED: Use TryToHide() instead
  378. #define USE_NEAREST true
  379. bool TryToHide( CNavArea *searchFromArea = NULL, float duration = -1.0f, float hideRange = 750.0f, bool holdPosition = false, bool useNearest = false ); ///< try to hide nearby, return false if cannot
  380. void Hide( const Vector &hidingSpot, float duration = -1.0f, bool holdPosition = false ); ///< move to the given hiding place
  381. bool IsHiding( void ) const; ///< returns true if bot is currently hiding
  382. bool IsAtHidingSpot( void ) const; ///< return true if we are hiding and at our hiding spot
  383. float GetHidingTime( void ) const; ///< return number of seconds we have been at our current hiding spot
  384. bool MoveToInitialEncounter( void ); ///< move to a hiding spot and wait for initial encounter with enemy team (return false if no spots are available)
  385. bool TryToRetreat( float maxRange = 1000.0f, float duration = -1.0f ); ///< retreat to a nearby hiding spot, away from enemies
  386. void Hunt( void );
  387. bool IsHunting( void ) const; ///< returns true if bot is currently hunting
  388. void Attack( CCSPlayer *victim );
  389. void FireWeaponAtEnemy( void ); ///< fire our active weapon towards our current enemy
  390. void StopAttacking( void );
  391. bool IsAttacking( void ) const; ///< returns true if bot is currently engaging a target
  392. void MoveTo( const Vector &pos, RouteType route = SAFEST_ROUTE ); ///< move to potentially distant position
  393. bool IsMovingTo( void ) const; ///< return true if we are in the MoveTo state
  394. void PlantBomb( void );
  395. void FetchBomb( void ); ///< bomb has been dropped - go get it
  396. bool NoticeLooseBomb( void ) const; ///< return true if we noticed the bomb on the ground or on radar
  397. bool CanSeeLooseBomb( void ) const; ///< return true if we directly see the loose bomb
  398. void DefuseBomb( void );
  399. bool IsDefusingBomb( void ) const; ///< returns true if bot is currently defusing the bomb
  400. bool CanSeePlantedBomb( void ) const; ///< return true if we directly see the planted bomb
  401. void EscapeFromBomb( void );
  402. bool IsEscapingFromBomb( void ) const; ///< return true if we are escaping from the bomb
  403. void RescueHostages( void ); ///< begin process of rescuing hostages
  404. void UseEntity( CBaseEntity *entity ); ///< use the entity
  405. void OpenDoor( CBaseEntity *door ); ///< open the door (assumes we are right in front of it)
  406. bool IsOpeningDoor( void ) const; ///< return true if we are in the process of opening a door
  407. void Buy( void ); ///< enter the buy state
  408. bool IsBuying( void ) const;
  409. void Panic( void ); ///< look around in panic
  410. bool IsPanicking( void ) const; ///< return true if bot is panicked
  411. void StopPanicking( void ); ///< end our panic
  412. void UpdatePanicLookAround( void ); ///< do panic behavior
  413. void TryToJoinTeam( int team ); ///< try to join the given team
  414. void Follow( CCSPlayer *player ); ///< begin following given Player
  415. void ContinueFollowing( void ); ///< continue following our leader after finishing what we were doing
  416. void StopFollowing( void ); ///< stop following
  417. bool IsFollowing( void ) const; ///< return true if we are following someone (not necessarily in the follow state)
  418. CCSPlayer *GetFollowLeader( void ) const; ///< return the leader we are following
  419. float GetFollowDuration( void ) const; ///< return how long we've been following our leader
  420. bool CanAutoFollow( void ) const; ///< return true if we can auto-follow
  421. bool IsNotMoving( float minDuration = 0.0f ) const; ///< return true if we are currently standing still and have been for minDuration
  422. void AimAtEnemy( void ); ///< point our weapon towards our enemy
  423. void StopAiming( void ); ///< stop aiming at enemy
  424. bool IsAimingAtEnemy( void ) const; ///< returns true if we are trying to aim at an enemy
  425. float GetStateTimestamp( void ) const; ///< get time current state was entered
  426. bool IsDoingScenario( void ) const; ///< return true if we will do scenario-related tasks
  427. //- scenario / gamestate -----------------------------------------------------------------------------------------
  428. CSGameState *GetGameState( void ); ///< return an interface to this bot's gamestate
  429. const CSGameState *GetGameState( void ) const; ///< return an interface to this bot's gamestate
  430. bool IsAtBombsite( void ); ///< return true if we are in a bomb planting zone
  431. bool GuardRandomZone( float range = 500.0f ); ///< pick a random zone and hide near it
  432. bool IsBusy( void ) const; ///< return true if we are busy doing something important
  433. //- high-level tasks ---------------------------------------------------------------------------------------------
  434. enum TaskType
  435. {
  436. SEEK_AND_DESTROY,
  437. PLANT_BOMB,
  438. FIND_TICKING_BOMB,
  439. DEFUSE_BOMB,
  440. GUARD_TICKING_BOMB,
  441. GUARD_BOMB_DEFUSER,
  442. GUARD_LOOSE_BOMB,
  443. GUARD_BOMB_ZONE,
  444. GUARD_INITIAL_ENCOUNTER,
  445. ESCAPE_FROM_BOMB,
  446. HOLD_POSITION,
  447. FOLLOW,
  448. VIP_ESCAPE,
  449. GUARD_VIP_ESCAPE_ZONE,
  450. COLLECT_HOSTAGES,
  451. RESCUE_HOSTAGES,
  452. GUARD_HOSTAGES,
  453. GUARD_HOSTAGE_RESCUE_ZONE,
  454. MOVE_TO_LAST_KNOWN_ENEMY_POSITION,
  455. MOVE_TO_SNIPER_SPOT,
  456. SNIPING,
  457. NUM_TASKS
  458. };
  459. void SetTask( TaskType task, CBaseEntity *entity = NULL ); ///< set our current "task"
  460. TaskType GetTask( void ) const;
  461. CBaseEntity *GetTaskEntity( void );
  462. const char *GetTaskName( void ) const; ///< return string describing current task
  463. //- behavior modifiers ------------------------------------------------------------------------------------------
  464. enum DispositionType
  465. {
  466. ENGAGE_AND_INVESTIGATE, ///< engage enemies on sight and investigate enemy noises
  467. OPPORTUNITY_FIRE, ///< engage enemies on sight, but only look towards enemy noises, dont investigate
  468. SELF_DEFENSE, ///< only engage if fired on, or very close to enemy
  469. IGNORE_ENEMIES, ///< ignore all enemies - useful for ducking around corners, running away, etc
  470. NUM_DISPOSITIONS
  471. };
  472. void SetDisposition( DispositionType disposition ); ///< define how we react to enemies
  473. DispositionType GetDisposition( void ) const;
  474. const char *GetDispositionName( void ) const; ///< return string describing current disposition
  475. void IgnoreEnemies( float duration ); ///< ignore enemies for a short duration
  476. enum MoraleType
  477. {
  478. TERRIBLE = -3,
  479. BAD = -2,
  480. NEGATIVE = -1,
  481. NEUTRAL = 0,
  482. POSITIVE = 1,
  483. GOOD = 2,
  484. EXCELLENT = 3,
  485. };
  486. MoraleType GetMorale( void ) const;
  487. const char *GetMoraleName( void ) const; ///< return string describing current morale
  488. void IncreaseMorale( void );
  489. void DecreaseMorale( void );
  490. void Surprise( float duration ); ///< become "surprised" - can't attack
  491. bool IsSurprised( void ) const; ///< return true if we are "surprised"
  492. //- listening for noises ----------------------------------------------------------------------------------------
  493. bool IsNoiseHeard( void ) const; ///< return true if we have heard a noise
  494. bool HeardInterestingNoise( void ); ///< return true if we heard an enemy noise worth checking in to
  495. void InvestigateNoise( void ); ///< investigate recent enemy noise
  496. bool IsInvestigatingNoise( void ) const; ///< return true if we are investigating a noise
  497. const Vector *GetNoisePosition( void ) const; ///< return position of last heard noise, or NULL if none heard
  498. CNavArea *GetNoiseArea( void ) const; ///< return area where noise was heard
  499. void ForgetNoise( void ); ///< clear the last heard noise
  500. bool CanSeeNoisePosition( void ) const; ///< return true if we directly see where we think the noise came from
  501. float GetNoiseRange( void ) const; ///< return approximate distance to last noise heard
  502. bool CanHearNearbyEnemyGunfire( float range = -1.0f ) const;///< return true if we hear nearby threatening enemy gunfire within given range (-1 == infinite)
  503. PriorityType GetNoisePriority( void ) const; ///< return priority of last heard noise
  504. //- radio and chatter--------------------------------------------------------------------------------------------
  505. void SendRadioMessage( RadioType event ); ///< send a radio message
  506. void SpeakAudio( const char *voiceFilename, float duration, int pitch ); ///< send voice chatter
  507. BotChatterInterface *GetChatter( void ); ///< return an interface to this bot's chatter system
  508. bool RespondToHelpRequest( CCSPlayer *player, Place place, float maxRange = -1.0f ); ///< decide if we should move to help the player, return true if we will
  509. bool IsUsingVoice() const; ///< new-style "voice" chatter gets voice feedback
  510. //- enemies ------------------------------------------------------------------------------------------------------
  511. // BOTPORT: GetEnemy() collides with GetEnemy() in CBaseEntity - need to use different nomenclature
  512. void SetBotEnemy( CCSPlayer *enemy ); ///< set given player as our current enemy
  513. CCSPlayer *GetBotEnemy( void ) const;
  514. int GetNearbyEnemyCount( void ) const; ///< return max number of nearby enemies we've seen recently
  515. unsigned int GetEnemyPlace( void ) const; ///< return location where we see the majority of our enemies
  516. bool CanSeeBomber( void ) const; ///< return true if we can see the bomb carrier
  517. CCSPlayer *GetBomber( void ) const;
  518. int GetNearbyFriendCount( void ) const; ///< return number of nearby teammates
  519. CCSPlayer *GetClosestVisibleFriend( void ) const; ///< return the closest friend that we can see
  520. CCSPlayer *GetClosestVisibleHumanFriend( void ) const; ///< return the closest human friend that we can see
  521. bool IsOutnumbered( void ) const; ///< return true if we are outnumbered by enemies
  522. int OutnumberedCount( void ) const; ///< return number of enemies we are outnumbered by
  523. #define ONLY_VISIBLE_ENEMIES true
  524. CCSPlayer *GetImportantEnemy( bool checkVisibility = false ) const; ///< return the closest "important" enemy for the given scenario (bomb carrier, VIP, hostage escorter)
  525. void UpdateReactionQueue( void ); ///< update our reaction time queue
  526. CCSPlayer *GetRecognizedEnemy( void ); ///< return the most dangerous threat we are "conscious" of
  527. bool IsRecognizedEnemyReloading( void ); ///< return true if the enemy we are "conscious" of is reloading
  528. bool IsRecognizedEnemyProtectedByShield( void ); ///< return true if the enemy we are "conscious" of is hiding behind a shield
  529. float GetRangeToNearestRecognizedEnemy( void ); ///< return distance to closest enemy we are "conscious" of
  530. CCSPlayer *GetAttacker( void ) const; ///< return last enemy that hurt us
  531. float GetTimeSinceAttacked( void ) const; ///< return duration since we were last injured by an attacker
  532. float GetFirstSawEnemyTimestamp( void ) const; ///< time since we saw any enemies
  533. float GetLastSawEnemyTimestamp( void ) const;
  534. float GetTimeSinceLastSawEnemy( void ) const;
  535. float GetTimeSinceAcquiredCurrentEnemy( void ) const;
  536. bool HasNotSeenEnemyForLongTime( void ) const; ///< return true if we haven't seen an enemy for "a long time"
  537. const Vector &GetLastKnownEnemyPosition( void ) const;
  538. bool IsEnemyVisible( void ) const; ///< is our current enemy visible
  539. float GetEnemyDeathTimestamp( void ) const;
  540. bool IsFriendInLineOfFire( void ); ///< return true if a friend is in our weapon's way
  541. bool IsAwareOfEnemyDeath( void ) const; ///< return true if we *noticed* that our enemy died
  542. int GetLastVictimID( void ) const; ///< return the ID (entindex) of the last victim we killed, or zero
  543. bool CanSeeSniper( void ) const; ///< return true if we can see an enemy sniper
  544. bool HasSeenSniperRecently( void ) const; ///< return true if we have seen a sniper recently
  545. float GetTravelDistanceToPlayer( CCSPlayer *player ) const; ///< return shortest path travel distance to this player
  546. bool DidPlayerJustFireWeapon( const CCSPlayer *player ) const; ///< return true if the given player just fired their weapon
  547. //- navigation --------------------------------------------------------------------------------------------------
  548. bool HasPath( void ) const;
  549. void DestroyPath( void );
  550. float GetFeetZ( void ) const; ///< return Z of bottom of feet
  551. enum PathResult
  552. {
  553. PROGRESSING, ///< we are moving along the path
  554. END_OF_PATH, ///< we reached the end of the path
  555. PATH_FAILURE ///< we failed to reach the end of the path
  556. };
  557. #define NO_SPEED_CHANGE false
  558. PathResult UpdatePathMovement( bool allowSpeedChange = true ); ///< move along our computed path - if allowSpeedChange is true, bot will walk when near goal to ensure accuracy
  559. //bool AStarSearch( CNavArea *startArea, CNavArea *goalArea ); ///< find shortest path from startArea to goalArea - don't actually buid the path
  560. bool ComputePath( const Vector &goal, RouteType route = SAFEST_ROUTE ); ///< compute path to goal position
  561. bool StayOnNavMesh( void );
  562. CNavArea *GetLastKnownArea( void ) const; ///< return the last area we know we were inside of
  563. const Vector &GetPathEndpoint( void ) const; ///< return final position of our current path
  564. float GetPathDistanceRemaining( void ) const; ///< return estimated distance left to travel along path
  565. void ResetStuckMonitor( void );
  566. bool IsAreaVisible( const CNavArea *area ) const; ///< is any portion of the area visible to this bot
  567. const Vector &GetPathPosition( int index ) const;
  568. bool GetSimpleGroundHeightWithFloor( const Vector &pos, float *height, Vector *normal = NULL ); ///< find "simple" ground height, treating current nav area as part of the floor
  569. void BreakablesCheck( void );
  570. void DoorCheck( void ); ///< Check for any doors along our path that need opening
  571. virtual void PushawayTouch( CBaseEntity *pOther );
  572. Place GetPlace( void ) const; ///< get our current radio chatter place
  573. bool IsUsingLadder( void ) const; ///< returns true if we are in the process of negotiating a ladder
  574. void GetOffLadder( void ); ///< immediately jump off of our ladder, if we're on one
  575. void SetGoalEntity( CBaseEntity *entity );
  576. CBaseEntity *GetGoalEntity( void );
  577. bool IsNearJump( void ) const; ///< return true if nearing a jump in the path
  578. float GetApproximateFallDamage( float height ) const; ///< return how much damage will will take from the given fall height
  579. void ForceRun( float duration ); ///< force the bot to run if it moves for the given duration
  580. virtual bool IsRunning( void ) const;
  581. void Wait( float duration ); ///< wait where we are for the given duration
  582. bool IsWaiting( void ) const; ///< return true if we are waiting
  583. void StopWaiting( void ); ///< stop waiting
  584. void Wiggle( void ); ///< random movement, for getting un-stuck
  585. bool IsFriendInTheWay( const Vector &goalPos ); ///< return true if a friend is between us and the given position
  586. void FeelerReflexAdjustment( Vector *goalPosition ); ///< do reflex avoidance movements if our "feelers" are touched
  587. bool HasVisitedEnemySpawn( void ) const; ///< return true if we have visited enemy spawn at least once
  588. bool IsAtEnemySpawn( void ) const; ///< return true if we are at the/an enemy spawn right now
  589. //- looking around ----------------------------------------------------------------------------------------------
  590. // BOTPORT: EVIL VILE HACK - why is EyePosition() not const?!?!?
  591. const Vector &EyePositionConst( void ) const;
  592. void SetLookAngles( float yaw, float pitch ); ///< set our desired look angles
  593. void UpdateLookAngles( void ); ///< move actual view angles towards desired ones
  594. void UpdateLookAround( bool updateNow = false ); ///< update "looking around" mechanism
  595. void InhibitLookAround( float duration ); ///< block all "look at" and "looking around" behavior for given duration - just look ahead
  596. /// @todo Clean up notion of "forward angle" and "look ahead angle"
  597. void SetForwardAngle( float angle ); ///< define our forward facing
  598. void SetLookAheadAngle( float angle ); ///< define default look ahead angle
  599. /// look at the given point in space for the given duration (-1 means forever)
  600. void SetLookAt( const char *desc, const Vector &pos, PriorityType pri, float duration = -1.0f, bool clearIfClose = false, float angleTolerance = 5.0f, bool attack = false );
  601. void ClearLookAt( void ); ///< stop looking at a point in space and just look ahead
  602. bool IsLookingAtSpot( PriorityType pri = PRIORITY_LOW ) const; ///< return true if we are looking at spot with equal or higher priority
  603. bool IsViewMoving( float angleVelThreshold = 1.0f ) const; ///< returns true if bot's view angles are rotating (not still)
  604. bool HasViewBeenSteady( float duration ) const; ///< how long has our view been "steady" (ie: not moving) for given duration
  605. bool HasLookAtTarget( void ) const; ///< return true if we are in the process of looking at a target
  606. enum VisiblePartType
  607. {
  608. NONE = 0x00,
  609. GUT = 0x01,
  610. HEAD = 0x02,
  611. LEFT_SIDE = 0x04, ///< the left side of the object from our point of view (not their left side)
  612. RIGHT_SIDE = 0x08, ///< the right side of the object from our point of view (not their right side)
  613. FEET = 0x10
  614. };
  615. #define CHECK_FOV true
  616. bool IsVisible( const Vector &pos, bool testFOV = false, const CBaseEntity *ignore = NULL ) const; ///< return true if we can see the point
  617. bool IsVisible( CCSPlayer *player, bool testFOV = false, unsigned char *visParts = NULL ) const; ///< return true if we can see any part of the player
  618. bool IsNoticable( const CCSPlayer *player, unsigned char visibleParts ) const; ///< return true if we "notice" given player
  619. bool IsEnemyPartVisible( VisiblePartType part ) const; ///< if enemy is visible, return the part we see for our current enemy
  620. const Vector &GetPartPosition( CCSPlayer *player, VisiblePartType part ) const; ///< return world space position of given part on player
  621. float ComputeWeaponSightRange( void ); ///< return line-of-sight distance to obstacle along weapon fire ray
  622. bool IsAnyVisibleEnemyLookingAtMe( bool testFOV = false ) const;///< return true if any enemy I have LOS to is looking directly at me
  623. bool IsSignificantlyCloser( const CCSPlayer *testPlayer, const CCSPlayer *referencePlayer ) const; ///< return true if testPlayer is significantly closer than referencePlayer
  624. //- approach points ---------------------------------------------------------------------------------------------
  625. void ComputeApproachPoints( void ); ///< determine the set of "approach points" representing where the enemy can enter this region
  626. void UpdateApproachPoints( void ); ///< recompute the approach point set if we have moved far enough to invalidate the current ones
  627. void ClearApproachPoints( void );
  628. void DrawApproachPoints( void ) const; ///< for debugging
  629. float GetHidingSpotCheckTimestamp( HidingSpot *spot ) const; ///< return time when given spot was last checked
  630. void SetHidingSpotCheckTimestamp( HidingSpot *spot ); ///< set the timestamp of the given spot to now
  631. const CNavArea *GetInitialEncounterArea( void ) const; ///< return area where we think we will first meet the enemy
  632. void SetInitialEncounterArea( const CNavArea *area );
  633. //- weapon query and equip --------------------------------------------------------------------------------------
  634. #define MUST_EQUIP true
  635. void EquipBestWeapon( bool mustEquip = false ); ///< equip the best weapon we are carrying that has ammo
  636. void EquipPistol( void ); ///< equip our pistol
  637. void EquipKnife( void ); ///< equip the knife
  638. #define DONT_USE_SMOKE_GRENADE true
  639. bool EquipGrenade( bool noSmoke = false ); ///< equip a grenade, return false if we cant
  640. bool IsUsingKnife( void ) const; ///< returns true if we have knife equipped
  641. bool IsUsingPistol( void ) const; ///< returns true if we have pistol equipped
  642. bool IsUsingGrenade( void ) const; ///< returns true if we have grenade equipped
  643. bool IsUsingSniperRifle( void ) const; ///< returns true if using a "sniper" rifle
  644. bool IsUsing( CSWeaponID weapon ) const; ///< returns true if using the specific weapon
  645. bool IsSniper( void ) const; ///< return true if we have a sniper rifle in our inventory
  646. bool IsSniping( void ) const; ///< return true if we are actively sniping (moving to sniper spot or settled in)
  647. bool IsUsingShotgun( void ) const; ///< returns true if using a shotgun
  648. bool IsUsingMachinegun( void ) const; ///< returns true if using the big 'ol machinegun
  649. void ThrowGrenade( const Vector &target ); ///< begin the process of throwing the grenade
  650. bool IsThrowingGrenade( void ) const; ///< return true if we are in the process of throwing a grenade
  651. bool HasGrenade( void ) const; ///< return true if we have a grenade in our inventory
  652. void AvoidEnemyGrenades( void ); ///< react to enemy grenades we see
  653. bool IsAvoidingGrenade( void ) const; ///< return true if we are in the act of avoiding a grenade
  654. bool DoesActiveWeaponHaveSilencer( void ) const; ///< returns true if we are using a weapon with a removable silencer
  655. bool CanActiveWeaponFire( void ) const; ///< returns true if our current weapon can attack
  656. CWeaponCSBase *GetActiveCSWeapon( void ) const; ///< get our current Counter-Strike weapon
  657. void GiveWeapon( const char *weaponAlias ); ///< Debug command to give a named weapon
  658. virtual void PrimaryAttack( void ); ///< presses the fire button, unless we're holding a pistol that can't fire yet (so we can just always call PrimaryAttack())
  659. enum ZoomType { NO_ZOOM, LOW_ZOOM, HIGH_ZOOM };
  660. ZoomType GetZoomLevel( void ); ///< return the current zoom level of our weapon
  661. bool AdjustZoom( float range ); ///< change our zoom level to be appropriate for the given range
  662. bool IsWaitingForZoom( void ) const; ///< return true if we are reacquiring after our zoom
  663. bool IsPrimaryWeaponEmpty( void ) const; ///< return true if primary weapon doesn't exist or is totally out of ammo
  664. bool IsPistolEmpty( void ) const; ///< return true if pistol doesn't exist or is totally out of ammo
  665. int GetHostageEscortCount( void ) const; ///< return the number of hostages following me
  666. void IncreaseHostageEscortCount( void );
  667. float GetRangeToFarthestEscortedHostage( void ) const; ///< return euclidean distance to farthest escorted hostage
  668. void ResetWaitForHostagePatience( void );
  669. //------------------------------------------------------------------------------------
  670. // Event hooks
  671. //
  672. /// invoked when injured by something (EXTEND) - returns the amount of damage inflicted
  673. virtual int OnTakeDamage( const CTakeDamageInfo &info );
  674. /// invoked when killed (EXTEND)
  675. virtual void Event_Killed( const CTakeDamageInfo &info );
  676. virtual bool BumpWeapon( CBaseCombatWeapon *pWeapon ); ///< invoked when in contact with a CWeaponBox
  677. /// invoked when event occurs in the game (some events have NULL entity)
  678. void OnPlayerFootstep( IGameEvent *event );
  679. void OnPlayerRadio( IGameEvent *event );
  680. void OnPlayerDeath( IGameEvent *event );
  681. void OnPlayerFallDamage( IGameEvent *event );
  682. void OnBombPickedUp( IGameEvent *event );
  683. void OnBombPlanted( IGameEvent *event );
  684. void OnBombBeep( IGameEvent *event );
  685. void OnBombDefuseBegin( IGameEvent *event );
  686. void OnBombDefused( IGameEvent *event );
  687. void OnBombDefuseAbort( IGameEvent *event );
  688. void OnBombExploded( IGameEvent *event );
  689. void OnRoundEnd( IGameEvent *event );
  690. void OnRoundStart( IGameEvent *event );
  691. void OnDoorMoving( IGameEvent *event );
  692. void OnBreakProp( IGameEvent *event );
  693. void OnBreakBreakable( IGameEvent *event );
  694. void OnHostageFollows( IGameEvent *event );
  695. void OnHostageRescuedAll( IGameEvent *event );
  696. void OnWeaponFire( IGameEvent *event );
  697. void OnWeaponFireOnEmpty( IGameEvent *event );
  698. void OnWeaponReload( IGameEvent *event );
  699. void OnWeaponZoom( IGameEvent *event );
  700. void OnBulletImpact( IGameEvent *event );
  701. void OnHEGrenadeDetonate( IGameEvent *event );
  702. void OnFlashbangDetonate( IGameEvent *event );
  703. void OnSmokeGrenadeDetonate( IGameEvent *event );
  704. void OnGrenadeBounce( IGameEvent *event );
  705. void OnNavBlocked( IGameEvent *event );
  706. void OnEnteredNavArea( CNavArea *newArea ); ///< invoked when bot enters a nav area
  707. private:
  708. #define IS_FOOTSTEP true
  709. void OnAudibleEvent( IGameEvent *event, CBasePlayer *player, float range, PriorityType priority, bool isHostile, bool isFootstep = false, const Vector *actualOrigin = NULL ); ///< Checks if the bot can hear the event
  710. private:
  711. friend class CCSBotManager;
  712. /// @todo Get rid of these
  713. friend class AttackState;
  714. friend class BuyState;
  715. // BOTPORT: Remove this vile hack
  716. Vector m_eyePosition;
  717. void ResetValues( void ); ///< reset internal data to initial state
  718. void BotDeathThink( void );
  719. char m_name[64]; ///< copied from STRING(pev->netname) for debugging
  720. void DebugDisplay( void ) const; ///< render bot debug info
  721. //- behavior properties ------------------------------------------------------------------------------------------
  722. float m_combatRange; ///< desired distance between us and them during gunplay
  723. mutable bool m_isRogue; ///< if true, the bot is a "rogue" and listens to no-one
  724. mutable CountdownTimer m_rogueTimer;
  725. MoraleType m_morale; ///< our current morale, based on our win/loss history
  726. bool m_diedLastRound; ///< true if we died last round
  727. float m_safeTime; ///< duration at the beginning of the round where we feel "safe"
  728. bool m_wasSafe; ///< true if we were in the safe time last update
  729. void AdjustSafeTime( void ); ///< called when enemy seen to adjust safe time for this round
  730. NavRelativeDirType m_blindMoveDir; ///< which way to move when we're blind
  731. bool m_blindFire; ///< if true, fire weapon while blinded
  732. CountdownTimer m_surpriseTimer; ///< when we were surprised
  733. bool m_isFollowing; ///< true if we are following someone
  734. CHandle< CCSPlayer > m_leader; ///< the ID of who we are following
  735. float m_followTimestamp; ///< when we started following
  736. float m_allowAutoFollowTime; ///< time when we can auto follow
  737. CountdownTimer m_hurryTimer; ///< if valid, bot is in a hurry
  738. CountdownTimer m_alertTimer; ///< if valid, bot is alert
  739. CountdownTimer m_sneakTimer; ///< if valid, bot is sneaking
  740. CountdownTimer m_panicTimer; ///< if valid, bot is panicking
  741. // instances of each possible behavior state, to avoid dynamic memory allocation during runtime
  742. IdleState m_idleState;
  743. HuntState m_huntState;
  744. AttackState m_attackState;
  745. InvestigateNoiseState m_investigateNoiseState;
  746. BuyState m_buyState;
  747. MoveToState m_moveToState;
  748. FetchBombState m_fetchBombState;
  749. PlantBombState m_plantBombState;
  750. DefuseBombState m_defuseBombState;
  751. HideState m_hideState;
  752. EscapeFromBombState m_escapeFromBombState;
  753. FollowState m_followState;
  754. UseEntityState m_useEntityState;
  755. OpenDoorState m_openDoorState;
  756. /// @todo Allow multiple simultaneous state machines (look around, etc)
  757. void SetState( BotState *state ); ///< set the current behavior state
  758. BotState *m_state; ///< current behavior state
  759. float m_stateTimestamp; ///< time state was entered
  760. bool m_isAttacking; ///< if true, special Attack state is overriding the state machine
  761. bool m_isOpeningDoor; ///< if true, special OpenDoor state is overriding the state machine
  762. TaskType m_task; ///< our current task
  763. EHANDLE m_taskEntity; ///< an entity used for our task
  764. //- navigation ---------------------------------------------------------------------------------------------------
  765. Vector m_goalPosition;
  766. EHANDLE m_goalEntity;
  767. void MoveTowardsPosition( const Vector &pos ); ///< move towards position, independant of view angle
  768. void MoveAwayFromPosition( const Vector &pos ); ///< move away from position, independant of view angle
  769. void StrafeAwayFromPosition( const Vector &pos ); ///< strafe (sidestep) away from position, independant of view angle
  770. void StuckCheck( void ); ///< check if we have become stuck
  771. CCSNavArea *m_currentArea; ///< the nav area we are standing on
  772. CCSNavArea *m_lastKnownArea; ///< the last area we were in
  773. EHANDLE m_avoid; ///< higher priority player we need to make way for
  774. float m_avoidTimestamp;
  775. bool m_isStopping; ///< true if we're trying to stop because we entered a 'stop' nav area
  776. bool m_hasVisitedEnemySpawn; ///< true if we have been at the enemy spawn
  777. IntervalTimer m_stillTimer; ///< how long we have been not moving
  778. //- path navigation data ----------------------------------------------------------------------------------------
  779. enum { MAX_PATH_LENGTH = 256 };
  780. struct ConnectInfo
  781. {
  782. CNavArea *area; ///< the area along the path
  783. NavTraverseType how; ///< how to enter this area from the previous one
  784. Vector pos; ///< our movement goal position at this point in the path
  785. const CNavLadder *ladder; ///< if "how" refers to a ladder, this is it
  786. }
  787. m_path[ MAX_PATH_LENGTH ];
  788. int m_pathLength;
  789. int m_pathIndex; ///< index of next area on path
  790. float m_areaEnteredTimestamp;
  791. void BuildTrivialPath( const Vector &goal ); ///< build trivial path to goal, assuming we are already in the same area
  792. CountdownTimer m_repathTimer; ///< must have elapsed before bot can pathfind again
  793. bool ComputePathPositions( void ); ///< determine actual path positions bot will move between along the path
  794. void SetupLadderMovement( void );
  795. void SetPathIndex( int index ); ///< set the current index along the path
  796. void DrawPath( void );
  797. int FindOurPositionOnPath( Vector *close, bool local = false ) const; ///< compute the closest point to our current position on our path
  798. int FindPathPoint( float aheadRange, Vector *point, int *prevIndex = NULL ); ///< compute a point a fixed distance ahead along our path.
  799. bool FindClosestPointOnPath( const Vector &pos, int startIndex, int endIndex, Vector *close ) const; ///< compute closest point on path to given point
  800. bool IsStraightLinePathWalkable( const Vector &goal ) const; ///< test for un-jumpable height change, or unrecoverable fall
  801. void ComputeLadderAngles( float *yaw, float *pitch ); ///< computes ideal yaw/pitch for traversing the current ladder on our path
  802. mutable CountdownTimer m_avoidFriendTimer; ///< used to throttle how often we check for friends in our path
  803. mutable bool m_isFriendInTheWay; ///< true if a friend is blocking our path
  804. CountdownTimer m_politeTimer; ///< we'll wait for friend to move until this runs out
  805. bool m_isWaitingBehindFriend; ///< true if we are waiting for a friend to move
  806. #define ONLY_JUMP_DOWN true
  807. bool DiscontinuityJump( float ground, bool onlyJumpDown = false, bool mustJump = false ); ///< check if we need to jump due to height change
  808. enum LadderNavState
  809. {
  810. APPROACH_ASCENDING_LADDER, ///< prepare to scale a ladder
  811. APPROACH_DESCENDING_LADDER, ///< prepare to go down ladder
  812. FACE_ASCENDING_LADDER,
  813. FACE_DESCENDING_LADDER,
  814. MOUNT_ASCENDING_LADDER, ///< move toward ladder until "on" it
  815. MOUNT_DESCENDING_LADDER, ///< move toward ladder until "on" it
  816. ASCEND_LADDER, ///< go up the ladder
  817. DESCEND_LADDER, ///< go down the ladder
  818. DISMOUNT_ASCENDING_LADDER, ///< get off of the ladder
  819. DISMOUNT_DESCENDING_LADDER, ///< get off of the ladder
  820. MOVE_TO_DESTINATION, ///< dismount ladder and move to destination area
  821. }
  822. m_pathLadderState;
  823. bool m_pathLadderFaceIn; ///< if true, face towards ladder, otherwise face away
  824. const CNavLadder *m_pathLadder; ///< the ladder we need to use to reach the next area
  825. bool UpdateLadderMovement( void ); ///< called by UpdatePathMovement()
  826. NavRelativeDirType m_pathLadderDismountDir; ///< which way to dismount
  827. float m_pathLadderDismountTimestamp; ///< time when dismount started
  828. float m_pathLadderEnd; ///< if ascending, z of top, if descending z of bottom
  829. void ComputeLadderEndpoint( bool ascending );
  830. float m_pathLadderTimestamp; ///< time when we started using ladder - for timeout check
  831. CountdownTimer m_mustRunTimer; ///< if nonzero, bot cannot walk
  832. CountdownTimer m_waitTimer; ///< if nonzero, we are waiting where we are
  833. void UpdateTravelDistanceToAllPlayers( void ); ///< periodically compute shortest path distance to each player
  834. CountdownTimer m_updateTravelDistanceTimer; ///< for throttling travel distance computations
  835. float m_playerTravelDistance[ MAX_PLAYERS ]; ///< current distance from this bot to each player
  836. unsigned char m_travelDistancePhase; ///< a counter for optimizing when to compute travel distance
  837. //- game scenario mechanisms -------------------------------------------------------------------------------------
  838. CSGameState m_gameState; ///< our current knowledge about the state of the scenario
  839. byte m_hostageEscortCount; ///< the number of hostages we're currently escorting
  840. void UpdateHostageEscortCount( void ); ///< periodic check of hostage count in case we lost some
  841. float m_hostageEscortCountTimestamp;
  842. int m_desiredTeam; ///< the team we want to be on
  843. bool m_hasJoined; ///< true if bot has actually joined the game
  844. bool m_isWaitingForHostage;
  845. CountdownTimer m_inhibitWaitingForHostageTimer; ///< if active, inhibits us waiting for lagging hostages
  846. CountdownTimer m_waitForHostageTimer; ///< stops us waiting too long
  847. //- listening mechanism ------------------------------------------------------------------------------------------
  848. Vector m_noisePosition; ///< position we last heard non-friendly noise
  849. float m_noiseTravelDistance; ///< the travel distance to the noise
  850. float m_noiseTimestamp; ///< when we heard it (can get zeroed)
  851. CNavArea *m_noiseArea; ///< the nav area containing the noise
  852. PriorityType m_noisePriority; ///< priority of currently heard noise
  853. bool UpdateLookAtNoise( void ); ///< return true if we decided to look towards the most recent noise source
  854. CountdownTimer m_noiseBendTimer; ///< for throttling how often we bend our line of sight to the noise location
  855. Vector m_bentNoisePosition; ///< the last computed bent line of sight
  856. bool m_bendNoisePositionValid;
  857. //- "looking around" mechanism -----------------------------------------------------------------------------------
  858. float m_lookAroundStateTimestamp; ///< time of next state change
  859. float m_lookAheadAngle; ///< our desired forward look angle
  860. float m_forwardAngle; ///< our current forward facing direction
  861. float m_inhibitLookAroundTimestamp; ///< time when we can look around again
  862. enum LookAtSpotState
  863. {
  864. NOT_LOOKING_AT_SPOT, ///< not currently looking at a point in space
  865. LOOK_TOWARDS_SPOT, ///< in the process of aiming at m_lookAtSpot
  866. LOOK_AT_SPOT, ///< looking at m_lookAtSpot
  867. NUM_LOOK_AT_SPOT_STATES
  868. }
  869. m_lookAtSpotState;
  870. Vector m_lookAtSpot; ///< the spot we're currently looking at
  871. PriorityType m_lookAtSpotPriority;
  872. float m_lookAtSpotDuration; ///< how long we need to look at the spot
  873. float m_lookAtSpotTimestamp; ///< when we actually began looking at the spot
  874. float m_lookAtSpotAngleTolerance; ///< how exactly we must look at the spot
  875. bool m_lookAtSpotClearIfClose; ///< if true, the look at spot is cleared if it gets close to us
  876. bool m_lookAtSpotAttack; ///< if true, the look at spot should be attacked
  877. const char *m_lookAtDesc; ///< for debugging
  878. void UpdateLookAt( void );
  879. void UpdatePeripheralVision(); ///< update enounter spot timestamps, etc
  880. float m_peripheralTimestamp;
  881. enum { MAX_APPROACH_POINTS = 16 };
  882. struct ApproachPoint
  883. {
  884. Vector m_pos;
  885. CNavArea *m_area;
  886. };
  887. ApproachPoint m_approachPoint[ MAX_APPROACH_POINTS ];
  888. unsigned char m_approachPointCount;
  889. Vector m_approachPointViewPosition; ///< the position used when computing current approachPoint set
  890. CBaseEntity * FindEntitiesOnPath( float distance, CPushAwayEnumerator *enumerator, bool checkStuck );
  891. IntervalTimer m_viewSteadyTimer; ///< how long has our view been "steady" (ie: not moving)
  892. bool BendLineOfSight( const Vector &eye, const Vector &target, Vector *bend, float angleLimit = 135.0f ) const; ///< "bend" our line of sight until we can see the target point. Return bend point, false if cant bend.
  893. bool FindApproachPointNearestPath( Vector *pos ); ///< find the approach point that is nearest to our current path, ahead of us
  894. bool FindGrenadeTossPathTarget( Vector *pos ); ///< find spot to throw grenade ahead of us and "around the corner" along our path
  895. enum GrenadeTossState
  896. {
  897. NOT_THROWING, ///< not yet throwing
  898. START_THROW, ///< lining up throw
  899. THROW_LINED_UP, ///< pause for a moment when on-line
  900. FINISH_THROW, ///< throwing
  901. };
  902. GrenadeTossState m_grenadeTossState;
  903. CountdownTimer m_tossGrenadeTimer; ///< timeout timer for grenade tossing
  904. const CNavArea *m_initialEncounterArea; ///< area where we think we will initially encounter the enemy
  905. void LookForGrenadeTargets( void ); ///< look for grenade throw targets and throw our grenade at them
  906. void UpdateGrenadeThrow( void ); ///< process grenade throwing
  907. CountdownTimer m_isAvoidingGrenade; ///< if nonzero we are in the act of avoiding a grenade
  908. SpotEncounter *m_spotEncounter; ///< the spots we will encounter as we move thru our current area
  909. float m_spotCheckTimestamp; ///< when to check next encounter spot
  910. /// @todo Add timestamp for each possible client to hiding spots
  911. enum { MAX_CHECKED_SPOTS = 64 };
  912. struct HidingSpotCheckInfo
  913. {
  914. HidingSpot *spot;
  915. float timestamp;
  916. }
  917. m_checkedHidingSpot[ MAX_CHECKED_SPOTS ];
  918. int m_checkedHidingSpotCount;
  919. //- view angle mechanism -----------------------------------------------------------------------------------------
  920. float m_lookPitch; ///< our desired look pitch angle
  921. float m_lookPitchVel;
  922. float m_lookYaw; ///< our desired look yaw angle
  923. float m_lookYawVel;
  924. //- aim angle mechanism -----------------------------------------------------------------------------------------
  925. Vector m_aimOffset; ///< current error added to victim's position to get actual aim spot
  926. Vector m_aimOffsetGoal; ///< desired aim offset
  927. float m_aimOffsetTimestamp; ///< time of next offset adjustment
  928. float m_aimSpreadTimestamp; ///< time used to determine max spread as it begins to tighten up
  929. void SetAimOffset( float accuracy ); ///< set the current aim offset
  930. void UpdateAimOffset( void ); ///< wiggle aim error based on m_accuracy
  931. Vector m_aimSpot; ///< the spot we are currently aiming to fire at
  932. struct PartInfo
  933. {
  934. Vector m_headPos; ///< current head position
  935. Vector m_gutPos; ///< current gut position
  936. Vector m_feetPos; ///< current feet position
  937. Vector m_leftSidePos; ///< current left side position
  938. Vector m_rightSidePos; ///< current right side position
  939. int m_validFrame; ///< frame of last computation (for lazy evaluation)
  940. };
  941. static PartInfo m_partInfo[ MAX_PLAYERS ]; ///< part positions for each player
  942. void ComputePartPositions( CCSPlayer *player ); ///< compute part positions from bone location
  943. //- attack state data --------------------------------------------------------------------------------------------
  944. DispositionType m_disposition; ///< how we will react to enemies
  945. CountdownTimer m_ignoreEnemiesTimer; ///< how long will we ignore enemies
  946. mutable CHandle< CCSPlayer > m_enemy; ///< our current enemy
  947. bool m_isEnemyVisible; ///< result of last visibility test on enemy
  948. unsigned char m_visibleEnemyParts; ///< which parts of the visible enemy do we see
  949. Vector m_lastEnemyPosition; ///< last place we saw the enemy
  950. float m_lastSawEnemyTimestamp;
  951. float m_firstSawEnemyTimestamp;
  952. float m_currentEnemyAcquireTimestamp;
  953. float m_enemyDeathTimestamp; ///< if m_enemy is dead, this is when he died
  954. float m_friendDeathTimestamp; ///< time since we saw a friend die
  955. bool m_isLastEnemyDead; ///< true if we killed or saw our last enemy die
  956. int m_nearbyEnemyCount; ///< max number of enemies we've seen recently
  957. unsigned int m_enemyPlace; ///< the location where we saw most of our enemies
  958. struct WatchInfo
  959. {
  960. float timestamp; ///< time we last saw this player, zero if never seen
  961. bool isEnemy;
  962. }
  963. m_watchInfo[ MAX_PLAYERS ];
  964. mutable CHandle< CCSPlayer > m_bomber; ///< points to bomber if we can see him
  965. int m_nearbyFriendCount; ///< number of nearby teammates
  966. mutable CHandle< CCSPlayer > m_closestVisibleFriend; ///< the closest friend we can see
  967. mutable CHandle< CCSPlayer > m_closestVisibleHumanFriend; ///< the closest human friend we can see
  968. IntervalTimer m_attentionInterval; ///< time between attention checks
  969. mutable CHandle< CCSPlayer > m_attacker; ///< last enemy that hurt us (may not be same as m_enemy)
  970. float m_attackedTimestamp; ///< when we were hurt by the m_attacker
  971. int m_lastVictimID; ///< the entindex of the last victim we killed, or zero
  972. bool m_isAimingAtEnemy; ///< if true, we are trying to aim at our enemy
  973. bool m_isRapidFiring; ///< if true, RunUpkeep() will toggle our primary attack as fast as it can
  974. IntervalTimer m_equipTimer; ///< how long have we had our current weapon equipped
  975. CountdownTimer m_zoomTimer; ///< for delaying firing immediately after zoom
  976. bool DoEquip( CWeaponCSBase *gun ); ///< equip the given item
  977. void ReloadCheck( void ); ///< reload our weapon if we must
  978. void SilencerCheck( void ); ///< use silencer
  979. float m_fireWeaponTimestamp;
  980. bool m_isEnemySniperVisible; ///< do we see an enemy sniper right now
  981. CountdownTimer m_sawEnemySniperTimer; ///< tracking time since saw enemy sniper
  982. //- reaction time system -----------------------------------------------------------------------------------------
  983. enum { MAX_ENEMY_QUEUE = 20 };
  984. struct ReactionState
  985. {
  986. // NOTE: player position & orientation is not currently stored separately
  987. CHandle<CCSPlayer> player;
  988. bool isReloading;
  989. bool isProtectedByShield;
  990. }
  991. m_enemyQueue[ MAX_ENEMY_QUEUE ]; ///< round-robin queue for simulating reaction times
  992. byte m_enemyQueueIndex;
  993. byte m_enemyQueueCount;
  994. byte m_enemyQueueAttendIndex; ///< index of the timeframe we are "conscious" of
  995. CCSPlayer *FindMostDangerousThreat( void ); ///< return most dangerous threat in my field of view (feeds into reaction time queue)
  996. //- stuck detection ---------------------------------------------------------------------------------------------
  997. bool m_isStuck;
  998. float m_stuckTimestamp; ///< time when we got stuck
  999. Vector m_stuckSpot; ///< the location where we became stuck
  1000. NavRelativeDirType m_wiggleDirection;
  1001. CountdownTimer m_wiggleTimer;
  1002. CountdownTimer m_stuckJumpTimer; ///< time for next jump when stuck
  1003. enum { MAX_VEL_SAMPLES = 10 };
  1004. float m_avgVel[ MAX_VEL_SAMPLES ];
  1005. int m_avgVelIndex;
  1006. int m_avgVelCount;
  1007. Vector m_lastOrigin;
  1008. //- radio --------------------------------------------------------------------------------------------------------
  1009. RadioType m_lastRadioCommand; ///< last radio command we recieved
  1010. float m_lastRadioRecievedTimestamp; ///< time we recieved a radio message
  1011. float m_lastRadioSentTimestamp; ///< time when we send a radio message
  1012. CHandle< CCSPlayer > m_radioSubject; ///< who issued the radio message
  1013. Vector m_radioPosition; ///< position referred to in radio message
  1014. void RespondToRadioCommands( void );
  1015. bool IsRadioCommand( RadioType event ) const; ///< returns true if the radio message is an order to do something
  1016. /// new-style "voice" chatter gets voice feedback
  1017. float m_voiceEndTimestamp;
  1018. BotChatterInterface m_chatter; ///< chatter mechanism
  1019. };
  1020. //
  1021. // Inlines
  1022. //
  1023. inline float CCSBot::GetFeetZ( void ) const
  1024. {
  1025. return GetAbsOrigin().z;
  1026. }
  1027. inline const Vector *CCSBot::GetNoisePosition( void ) const
  1028. {
  1029. if (m_noiseTimestamp > 0.0f)
  1030. return &m_noisePosition;
  1031. return NULL;
  1032. }
  1033. inline bool CCSBot::IsAwareOfEnemyDeath( void ) const
  1034. {
  1035. if (GetEnemyDeathTimestamp() == 0.0f)
  1036. return false;
  1037. if (m_enemy == NULL)
  1038. return true;
  1039. if (!m_enemy->IsAlive() && gpGlobals->curtime - GetEnemyDeathTimestamp() > (1.0f - 0.8f * GetProfile()->GetSkill()))
  1040. return true;
  1041. return false;
  1042. }
  1043. inline void CCSBot::Panic( void )
  1044. {
  1045. // we are stunned for a moment
  1046. Surprise( RandomFloat( 0.2f, 0.3f ) );
  1047. const float panicTime = 3.0f;
  1048. m_panicTimer.Start( panicTime );
  1049. const float panicRetreatRange = 300.0f;
  1050. TryToRetreat( panicRetreatRange, 0.0f );
  1051. PrintIfWatched( "*** PANIC ***\n" );
  1052. }
  1053. inline bool CCSBot::IsPanicking( void ) const
  1054. {
  1055. return !m_panicTimer.IsElapsed();
  1056. }
  1057. inline void CCSBot::StopPanicking( void )
  1058. {
  1059. m_panicTimer.Invalidate();
  1060. }
  1061. inline bool CCSBot::IsNotMoving( float minDuration ) const
  1062. {
  1063. return (m_stillTimer.HasStarted() && m_stillTimer.GetElapsedTime() >= minDuration);
  1064. }
  1065. inline CWeaponCSBase *CCSBot::GetActiveCSWeapon( void ) const
  1066. {
  1067. return reinterpret_cast<CWeaponCSBase *>( GetActiveWeapon() );
  1068. }
  1069. inline float CCSBot::GetCombatRange( void ) const
  1070. {
  1071. return m_combatRange;
  1072. }
  1073. inline void CCSBot::SetRogue( bool rogue )
  1074. {
  1075. m_isRogue = rogue;
  1076. }
  1077. inline void CCSBot::Hurry( float duration )
  1078. {
  1079. m_hurryTimer.Start( duration );
  1080. }
  1081. inline float CCSBot::GetSafeTime( void ) const
  1082. {
  1083. return m_safeTime;
  1084. }
  1085. inline bool CCSBot::IsUnhealthy( void ) const
  1086. {
  1087. return (GetHealth() <= 40);
  1088. }
  1089. inline bool CCSBot::IsAlert( void ) const
  1090. {
  1091. return !m_alertTimer.IsElapsed();
  1092. }
  1093. inline void CCSBot::BecomeAlert( void )
  1094. {
  1095. const float alertCooldownTime = 10.0f;
  1096. m_alertTimer.Start( alertCooldownTime );
  1097. }
  1098. inline bool CCSBot::IsSneaking( void ) const
  1099. {
  1100. return !m_sneakTimer.IsElapsed();
  1101. }
  1102. inline void CCSBot::Sneak( float duration )
  1103. {
  1104. m_sneakTimer.Start( duration );
  1105. }
  1106. inline bool CCSBot::IsFollowing( void ) const
  1107. {
  1108. return m_isFollowing;
  1109. }
  1110. inline CCSPlayer *CCSBot::GetFollowLeader( void ) const
  1111. {
  1112. return m_leader;
  1113. }
  1114. inline float CCSBot::GetFollowDuration( void ) const
  1115. {
  1116. return gpGlobals->curtime - m_followTimestamp;
  1117. }
  1118. inline bool CCSBot::CanAutoFollow( void ) const
  1119. {
  1120. return (gpGlobals->curtime > m_allowAutoFollowTime);
  1121. }
  1122. inline void CCSBot::AimAtEnemy( void )
  1123. {
  1124. m_isAimingAtEnemy = true;
  1125. }
  1126. inline void CCSBot::StopAiming( void )
  1127. {
  1128. m_isAimingAtEnemy = false;
  1129. }
  1130. inline bool CCSBot::IsAimingAtEnemy( void ) const
  1131. {
  1132. return m_isAimingAtEnemy;
  1133. }
  1134. inline float CCSBot::GetStateTimestamp( void ) const
  1135. {
  1136. return m_stateTimestamp;
  1137. }
  1138. inline CSGameState *CCSBot::GetGameState( void )
  1139. {
  1140. return &m_gameState;
  1141. }
  1142. inline const CSGameState *CCSBot::GetGameState( void ) const
  1143. {
  1144. return &m_gameState;
  1145. }
  1146. inline bool CCSBot::IsAtBombsite( void )
  1147. {
  1148. return m_bInBombZone;
  1149. }
  1150. inline void CCSBot::SetTask( TaskType task, CBaseEntity *entity )
  1151. {
  1152. m_task = task;
  1153. m_taskEntity = entity;
  1154. }
  1155. inline CCSBot::TaskType CCSBot::GetTask( void ) const
  1156. {
  1157. return m_task;
  1158. }
  1159. inline CBaseEntity *CCSBot::GetTaskEntity( void )
  1160. {
  1161. return static_cast<CBaseEntity *>( m_taskEntity );
  1162. }
  1163. inline CCSBot::MoraleType CCSBot::GetMorale( void ) const
  1164. {
  1165. return m_morale;
  1166. }
  1167. inline void CCSBot::Surprise( float duration )
  1168. {
  1169. m_surpriseTimer.Start( duration );
  1170. }
  1171. inline bool CCSBot::IsSurprised( void ) const
  1172. {
  1173. return !m_surpriseTimer.IsElapsed();
  1174. }
  1175. inline CNavArea *CCSBot::GetNoiseArea( void ) const
  1176. {
  1177. return m_noiseArea;
  1178. }
  1179. inline void CCSBot::ForgetNoise( void )
  1180. {
  1181. m_noiseTimestamp = 0.0f;
  1182. }
  1183. inline float CCSBot::GetNoiseRange( void ) const
  1184. {
  1185. if (IsNoiseHeard())
  1186. return m_noiseTravelDistance;
  1187. return 999999999.9f;
  1188. }
  1189. inline PriorityType CCSBot::GetNoisePriority( void ) const
  1190. {
  1191. return m_noisePriority;
  1192. }
  1193. inline BotChatterInterface *CCSBot::GetChatter( void )
  1194. {
  1195. return &m_chatter;
  1196. }
  1197. inline CCSPlayer *CCSBot::GetBotEnemy( void ) const
  1198. {
  1199. return m_enemy;
  1200. }
  1201. inline int CCSBot::GetNearbyEnemyCount( void ) const
  1202. {
  1203. return MIN( GetEnemiesRemaining(), m_nearbyEnemyCount );
  1204. }
  1205. inline unsigned int CCSBot::GetEnemyPlace( void ) const
  1206. {
  1207. return m_enemyPlace;
  1208. }
  1209. inline bool CCSBot::CanSeeBomber( void ) const
  1210. {
  1211. return (m_bomber == NULL) ? false : true;
  1212. }
  1213. inline CCSPlayer *CCSBot::GetBomber( void ) const
  1214. {
  1215. return m_bomber;
  1216. }
  1217. inline int CCSBot::GetNearbyFriendCount( void ) const
  1218. {
  1219. return MIN( GetFriendsRemaining(), m_nearbyFriendCount );
  1220. }
  1221. inline CCSPlayer *CCSBot::GetClosestVisibleFriend( void ) const
  1222. {
  1223. return m_closestVisibleFriend;
  1224. }
  1225. inline CCSPlayer *CCSBot::GetClosestVisibleHumanFriend( void ) const
  1226. {
  1227. return m_closestVisibleHumanFriend;
  1228. }
  1229. inline float CCSBot::GetTimeSinceAttacked( void ) const
  1230. {
  1231. return gpGlobals->curtime - m_attackedTimestamp;
  1232. }
  1233. inline float CCSBot::GetFirstSawEnemyTimestamp( void ) const
  1234. {
  1235. return m_firstSawEnemyTimestamp;
  1236. }
  1237. inline float CCSBot::GetLastSawEnemyTimestamp( void ) const
  1238. {
  1239. return m_lastSawEnemyTimestamp;
  1240. }
  1241. inline float CCSBot::GetTimeSinceLastSawEnemy( void ) const
  1242. {
  1243. return gpGlobals->curtime - m_lastSawEnemyTimestamp;
  1244. }
  1245. inline float CCSBot::GetTimeSinceAcquiredCurrentEnemy( void ) const
  1246. {
  1247. return gpGlobals->curtime - m_currentEnemyAcquireTimestamp;
  1248. }
  1249. inline const Vector &CCSBot::GetLastKnownEnemyPosition( void ) const
  1250. {
  1251. return m_lastEnemyPosition;
  1252. }
  1253. inline bool CCSBot::IsEnemyVisible( void ) const
  1254. {
  1255. return m_isEnemyVisible;
  1256. }
  1257. inline float CCSBot::GetEnemyDeathTimestamp( void ) const
  1258. {
  1259. return m_enemyDeathTimestamp;
  1260. }
  1261. inline int CCSBot::GetLastVictimID( void ) const
  1262. {
  1263. return m_lastVictimID;
  1264. }
  1265. inline bool CCSBot::CanSeeSniper( void ) const
  1266. {
  1267. return m_isEnemySniperVisible;
  1268. }
  1269. inline bool CCSBot::HasSeenSniperRecently( void ) const
  1270. {
  1271. return !m_sawEnemySniperTimer.IsElapsed();
  1272. }
  1273. inline float CCSBot::GetTravelDistanceToPlayer( CCSPlayer *player ) const
  1274. {
  1275. if (player == NULL)
  1276. return -1.0f;
  1277. if (!player->IsAlive())
  1278. return -1.0f;
  1279. return m_playerTravelDistance[ player->entindex() % MAX_PLAYERS ];
  1280. }
  1281. inline bool CCSBot::HasPath( void ) const
  1282. {
  1283. return (m_pathLength) ? true : false;
  1284. }
  1285. inline void CCSBot::DestroyPath( void )
  1286. {
  1287. m_isStopping = false;
  1288. m_pathLength = 0;
  1289. m_pathLadder = NULL;
  1290. }
  1291. inline CNavArea *CCSBot::GetLastKnownArea( void ) const
  1292. {
  1293. return m_lastKnownArea;
  1294. }
  1295. inline const Vector &CCSBot::GetPathEndpoint( void ) const
  1296. {
  1297. return m_path[ m_pathLength-1 ].pos;
  1298. }
  1299. inline const Vector &CCSBot::GetPathPosition( int index ) const
  1300. {
  1301. return m_path[ index ].pos;
  1302. }
  1303. inline bool CCSBot::IsUsingLadder( void ) const
  1304. {
  1305. return (m_pathLadder) ? true : false;
  1306. }
  1307. inline void CCSBot::SetGoalEntity( CBaseEntity *entity )
  1308. {
  1309. m_goalEntity = entity;
  1310. }
  1311. inline CBaseEntity *CCSBot::GetGoalEntity( void )
  1312. {
  1313. return m_goalEntity;
  1314. }
  1315. inline void CCSBot::ForceRun( float duration )
  1316. {
  1317. Run();
  1318. m_mustRunTimer.Start( duration );
  1319. }
  1320. inline void CCSBot::Wait( float duration )
  1321. {
  1322. m_waitTimer.Start( duration );
  1323. }
  1324. inline bool CCSBot::IsWaiting( void ) const
  1325. {
  1326. return !m_waitTimer.IsElapsed();
  1327. }
  1328. inline void CCSBot::StopWaiting( void )
  1329. {
  1330. m_waitTimer.Invalidate();
  1331. }
  1332. inline bool CCSBot::HasVisitedEnemySpawn( void ) const
  1333. {
  1334. return m_hasVisitedEnemySpawn;
  1335. }
  1336. inline const Vector &CCSBot::EyePositionConst( void ) const
  1337. {
  1338. return m_eyePosition;
  1339. }
  1340. inline void CCSBot::SetLookAngles( float yaw, float pitch )
  1341. {
  1342. m_lookYaw = yaw;
  1343. m_lookPitch = pitch;
  1344. }
  1345. inline void CCSBot::SetForwardAngle( float angle )
  1346. {
  1347. m_forwardAngle = angle;
  1348. }
  1349. inline void CCSBot::SetLookAheadAngle( float angle )
  1350. {
  1351. m_lookAheadAngle = angle;
  1352. }
  1353. inline void CCSBot::ClearLookAt( void )
  1354. {
  1355. //PrintIfWatched( "ClearLookAt()\n" );
  1356. m_lookAtSpotState = NOT_LOOKING_AT_SPOT;
  1357. m_lookAtDesc = NULL;
  1358. }
  1359. inline bool CCSBot::IsLookingAtSpot( PriorityType pri ) const
  1360. {
  1361. if (m_lookAtSpotState != NOT_LOOKING_AT_SPOT && m_lookAtSpotPriority >= pri)
  1362. return true;
  1363. return false;
  1364. }
  1365. inline bool CCSBot::IsViewMoving( float angleVelThreshold ) const
  1366. {
  1367. if (m_lookYawVel < angleVelThreshold && m_lookYawVel > -angleVelThreshold &&
  1368. m_lookPitchVel < angleVelThreshold && m_lookPitchVel > -angleVelThreshold)
  1369. {
  1370. return false;
  1371. }
  1372. return true;
  1373. }
  1374. inline bool CCSBot::HasViewBeenSteady( float duration ) const
  1375. {
  1376. return (m_viewSteadyTimer.GetElapsedTime() > duration);
  1377. }
  1378. inline bool CCSBot::HasLookAtTarget( void ) const
  1379. {
  1380. return (m_lookAtSpotState != NOT_LOOKING_AT_SPOT);
  1381. }
  1382. inline bool CCSBot::IsEnemyPartVisible( VisiblePartType part ) const
  1383. {
  1384. VPROF_BUDGET( "CCSBot::IsEnemyPartVisible", VPROF_BUDGETGROUP_NPCS );
  1385. if (!IsEnemyVisible())
  1386. return false;
  1387. return (m_visibleEnemyParts & part) ? true : false;
  1388. }
  1389. inline bool CCSBot::IsSignificantlyCloser( const CCSPlayer *testPlayer, const CCSPlayer *referencePlayer ) const
  1390. {
  1391. if ( !referencePlayer )
  1392. return true;
  1393. if ( !testPlayer )
  1394. return false;
  1395. float testDist = ( GetAbsOrigin() - testPlayer->GetAbsOrigin() ).Length();
  1396. float referenceDist = ( GetAbsOrigin() - referencePlayer->GetAbsOrigin() ).Length();
  1397. const float significantRangeFraction = 0.7f;
  1398. if ( testDist < referenceDist * significantRangeFraction )
  1399. return true;
  1400. return false;
  1401. }
  1402. inline void CCSBot::ClearApproachPoints( void )
  1403. {
  1404. m_approachPointCount = 0;
  1405. }
  1406. inline const CNavArea *CCSBot::GetInitialEncounterArea( void ) const
  1407. {
  1408. return m_initialEncounterArea;
  1409. }
  1410. inline void CCSBot::SetInitialEncounterArea( const CNavArea *area )
  1411. {
  1412. m_initialEncounterArea = area;
  1413. }
  1414. inline bool CCSBot::IsThrowingGrenade( void ) const
  1415. {
  1416. return m_grenadeTossState != NOT_THROWING;
  1417. }
  1418. inline bool CCSBot::IsAvoidingGrenade( void ) const
  1419. {
  1420. return !m_isAvoidingGrenade.IsElapsed();
  1421. }
  1422. inline void CCSBot::PrimaryAttack( void )
  1423. {
  1424. if ( IsUsingPistol() && !CanActiveWeaponFire() )
  1425. return;
  1426. BaseClass::PrimaryAttack();
  1427. }
  1428. inline CCSBot::ZoomType CCSBot::GetZoomLevel( void )
  1429. {
  1430. if (GetFOV() > 60.0f)
  1431. return NO_ZOOM;
  1432. if (GetFOV() > 25.0f)
  1433. return LOW_ZOOM;
  1434. return HIGH_ZOOM;
  1435. }
  1436. inline bool CCSBot::IsWaitingForZoom( void ) const
  1437. {
  1438. return !m_zoomTimer.IsElapsed();
  1439. }
  1440. inline int CCSBot::GetHostageEscortCount( void ) const
  1441. {
  1442. return m_hostageEscortCount;
  1443. }
  1444. inline void CCSBot::IncreaseHostageEscortCount( void )
  1445. {
  1446. ++m_hostageEscortCount;
  1447. }
  1448. inline void CCSBot::ResetWaitForHostagePatience( void )
  1449. {
  1450. m_isWaitingForHostage = false;
  1451. m_inhibitWaitingForHostageTimer.Invalidate();
  1452. }
  1453. inline bool CCSBot::IsUsingVoice() const
  1454. {
  1455. return m_voiceEndTimestamp > gpGlobals->curtime;
  1456. }
  1457. inline bool CCSBot::IsOpeningDoor( void ) const
  1458. {
  1459. return m_isOpeningDoor;
  1460. }
  1461. //--------------------------------------------------------------------------------------------------------------
  1462. /**
  1463. * Return true if the given weapon is a sniper rifle
  1464. */
  1465. inline bool IsSniperRifle( CWeaponCSBase *weapon )
  1466. {
  1467. if (weapon == NULL)
  1468. return false;
  1469. return weapon->IsKindOf(WEAPONTYPE_SNIPER_RIFLE);
  1470. }
  1471. //--------------------------------------------------------------------------------------------------------------
  1472. /**
  1473. * Functor used with NavAreaBuildPath()
  1474. */
  1475. class PathCost
  1476. {
  1477. public:
  1478. PathCost( CCSBot *bot, RouteType route = SAFEST_ROUTE )
  1479. {
  1480. m_bot = bot;
  1481. m_route = route;
  1482. }
  1483. // HPE_TODO[pmf]: check that these new parameters are okay to be ignored
  1484. float operator() ( CNavArea *area, CNavArea *fromArea, const CNavLadder *ladder, const CFuncElevator *elevator, float length )
  1485. {
  1486. float baseDangerFactor = 100.0f; // 100
  1487. // respond to the danger modulated by our aggression (even super-aggressives pay SOME attention to danger)
  1488. float dangerFactor = (1.0f - (0.95f * m_bot->GetProfile()->GetAggression())) * baseDangerFactor;
  1489. if (fromArea == NULL)
  1490. {
  1491. if (m_route == FASTEST_ROUTE)
  1492. return 0.0f;
  1493. // first area in path, cost is just danger
  1494. return dangerFactor * area->GetDanger( m_bot->GetTeamNumber() );
  1495. }
  1496. else if ((fromArea->GetAttributes() & NAV_MESH_JUMP) && (area->GetAttributes() & NAV_MESH_JUMP))
  1497. {
  1498. // cannot actually walk in jump areas - disallow moving from jump area to jump area
  1499. return -1.0f;
  1500. }
  1501. if ( area->GetAttributes() & NAV_MESH_NO_HOSTAGES && m_bot->GetHostageEscortCount() )
  1502. {
  1503. // if we're leading hostages, don't try to go where they can't
  1504. return -1.0f;
  1505. }
  1506. else
  1507. {
  1508. // compute distance from previous area to this area
  1509. float dist;
  1510. if (ladder)
  1511. {
  1512. // ladders are slow to use
  1513. const float ladderPenalty = 1.0f; // 3.0f;
  1514. dist = ladderPenalty * ladder->m_length;
  1515. // if we are currently escorting hostages, avoid ladders (hostages are confused by them)
  1516. //if (m_bot->GetHostageEscortCount())
  1517. // dist *= 100.0f;
  1518. }
  1519. else
  1520. {
  1521. dist = (area->GetCenter() - fromArea->GetCenter()).Length();
  1522. }
  1523. // compute distance travelled along path so far
  1524. float cost = dist + fromArea->GetCostSoFar();
  1525. // zombies ignore all path penalties
  1526. if (cv_bot_zombie.GetBool())
  1527. return cost;
  1528. // add cost of "jump down" pain unless we're jumping into water
  1529. if (!area->IsUnderwater() && area->IsConnected( fromArea, NUM_DIRECTIONS ) == false)
  1530. {
  1531. // this is a "jump down" (one way drop) transition - estimate damage we will take to traverse it
  1532. float fallDistance = -fromArea->ComputeGroundHeightChange( area );
  1533. // if it's a drop-down ladder, estimate height from the bottom of the ladder to the lower area
  1534. if ( ladder && ladder->m_bottom.z < fromArea->GetCenter().z && ladder->m_bottom.z > area->GetCenter().z )
  1535. {
  1536. fallDistance = ladder->m_bottom.z - area->GetCenter().z;
  1537. }
  1538. float fallDamage = m_bot->GetApproximateFallDamage( fallDistance );
  1539. if (fallDamage > 0.0f)
  1540. {
  1541. // if the fall would kill us, don't use it
  1542. const float deathFallMargin = 10.0f;
  1543. if (fallDamage + deathFallMargin >= m_bot->GetHealth())
  1544. return -1.0f;
  1545. // if we need to get there in a hurry, ignore minor pain
  1546. const float painTolerance = 15.0f * m_bot->GetProfile()->GetAggression() + 10.0f;
  1547. if (m_route != FASTEST_ROUTE || fallDamage > painTolerance)
  1548. {
  1549. // cost is proportional to how much it hurts when we fall
  1550. // 10 points - not a big deal, 50 points - ouch!
  1551. cost += 100.0f * fallDamage * fallDamage;
  1552. }
  1553. }
  1554. }
  1555. // if this is a "crouch" or "walk" area, add penalty
  1556. if (area->GetAttributes() & (NAV_MESH_CROUCH | NAV_MESH_WALK))
  1557. {
  1558. // these areas are very slow to move through
  1559. float penalty = (m_route == FASTEST_ROUTE) ? 20.0f : 5.0f;
  1560. // avoid crouch areas if we are rescuing hostages
  1561. if ((area->GetAttributes() & NAV_MESH_CROUCH) && m_bot->GetHostageEscortCount())
  1562. {
  1563. penalty *= 3.0f;
  1564. }
  1565. cost += penalty * dist;
  1566. }
  1567. // if this is a "jump" area, add penalty
  1568. if (area->GetAttributes() & NAV_MESH_JUMP)
  1569. {
  1570. // jumping can slow you down
  1571. //const float jumpPenalty = (m_route == FASTEST_ROUTE) ? 100.0f : 0.5f;
  1572. const float jumpPenalty = 1.0f;
  1573. cost += jumpPenalty * dist;
  1574. }
  1575. // if this is an area to avoid, add penalty
  1576. if (area->GetAttributes() & NAV_MESH_AVOID)
  1577. {
  1578. const float avoidPenalty = 20.0f;
  1579. cost += avoidPenalty * dist;
  1580. }
  1581. if (m_route == SAFEST_ROUTE)
  1582. {
  1583. // add in the danger of this path - danger is per unit length travelled
  1584. cost += dist * dangerFactor * area->GetDanger( m_bot->GetTeamNumber() );
  1585. }
  1586. if (!m_bot->IsAttacking())
  1587. {
  1588. // add in cost of teammates in the way
  1589. // approximate density of teammates based on area
  1590. float size = (area->GetSizeX() + area->GetSizeY())/2.0f;
  1591. // degenerate check
  1592. if (size >= 1.0f)
  1593. {
  1594. // cost is proportional to the density of teammates in this area
  1595. const float costPerFriendPerUnit = 50000.0f;
  1596. cost += costPerFriendPerUnit * (float)area->GetPlayerCount( m_bot->GetTeamNumber() ) / size;
  1597. }
  1598. }
  1599. return cost;
  1600. }
  1601. }
  1602. private:
  1603. CCSBot *m_bot;
  1604. RouteType m_route;
  1605. };
  1606. //--------------------------------------------------------------------------------------------------------------
  1607. //
  1608. // Prototypes
  1609. //
  1610. extern int GetBotFollowCount( CCSPlayer *leader );
  1611. extern const Vector *FindNearbyRetreatSpot( CCSBot *me, float maxRange = 250.0f );
  1612. extern const HidingSpot *FindInitialEncounterSpot( CBaseEntity *me, const Vector &searchOrigin, float enemyArriveTime, float maxRange, bool isSniper );
  1613. #endif // _CS_BOT_H_