aiPlayer.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "T3D/aiPlayer.h"
  28. #include "console/consoleInternal.h"
  29. #include "math/mMatrix.h"
  30. #include "T3D/gameBase/moveManager.h"
  31. #include "console/engineAPI.h"
  32. #include <cfloat>
  33. static U32 sAIPlayerLoSMask = TerrainObjectType | StaticShapeObjectType | StaticObjectType;
  34. IMPLEMENT_CO_NETOBJECT_V1(AIPlayer);
  35. ConsoleDocClass( AIPlayer,
  36. "@brief A Player object not controlled by conventional input, but by an AI engine.\n\n"
  37. "The AIPlayer provides a Player object that may be controlled from script. You control "
  38. "where the player moves and how fast. You may also set where the AIPlayer is aiming at "
  39. "-- either a location or another game object.\n\n"
  40. "The AIPlayer class does not have a datablock of its own. It makes use of the PlayerData "
  41. "datablock to define how it looks, etc. As the AIPlayer is an extension of the Player class "
  42. "it can mount objects and fire weapons, or mount vehicles and drive them.\n\n"
  43. "While the PlayerData datablock is used, there are a number of additional callbacks that are "
  44. "implemented by AIPlayer on the datablock. These are listed here:\n\n"
  45. "void onReachDestination(AIPlayer obj) \n"
  46. "Called when the player has reached its set destination using the setMoveDestination() method. "
  47. "The actual point at which this callback is called is when the AIPlayer is within the mMoveTolerance "
  48. "of the defined destination.\n\n"
  49. "void onMoveStuck(AIPlayer obj) \n"
  50. "While in motion, if an AIPlayer has moved less than moveStuckTolerance within a single tick, this "
  51. "callback is called. From here you could choose an alternate destination to get the AIPlayer moving "
  52. "again.\n\n"
  53. "void onTargetEnterLOS(AIPlayer obj) \n"
  54. "When an object is being aimed at (following a call to setAimObject()) and the targeted object enters "
  55. "the AIPlayer's line of sight, this callback is called. The LOS test is a ray from the AIPlayer's eye "
  56. "position to the center of the target's bounding box. The LOS ray test only checks against interiors, "
  57. "statis shapes, and terrain.\n\n"
  58. "void onTargetExitLOS(AIPlayer obj) \n"
  59. "When an object is being aimed at (following a call to setAimObject()) and the targeted object leaves "
  60. "the AIPlayer's line of sight, this callback is called. The LOS test is a ray from the AIPlayer's eye "
  61. "position to the center of the target's bounding box. The LOS ray test only checks against interiors, "
  62. "statis shapes, and terrain.\n\n"
  63. "@tsexample\n"
  64. "// Create the demo player object\n"
  65. "%player = new AiPlayer()\n"
  66. "{\n"
  67. " dataBlock = DemoPlayer;\n"
  68. " path = \"\";\n"
  69. "};\n"
  70. "@endtsexample\n\n"
  71. "@see Player for a list of all inherited functions, variables, and base description\n"
  72. "@ingroup AI\n"
  73. "@ingroup gameObjects\n");
  74. /**
  75. * Constructor
  76. */
  77. AIPlayer::AIPlayer()
  78. {
  79. mMoveDestination.set( 0.0f, 0.0f, 0.0f );
  80. mMoveSpeed = 1.0f;
  81. mMoveTolerance = 0.25f;
  82. mMoveStuckTolerance = 0.01f;
  83. mMoveStuckTestDelay = 30;
  84. mMoveStuckTestCountdown = 0;
  85. mMoveSlowdown = true;
  86. mMoveState = ModeStop;
  87. // This new member saves the movement state of the AI so that
  88. // it can be restored after a substituted animation is finished.
  89. mMoveState_saved = -1;
  90. mAimObject = 0;
  91. mAimLocationSet = false;
  92. mTargetInLOS = false;
  93. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  94. #ifdef TORQUE_NAVIGATION_ENABLED
  95. mJump = None;
  96. mNavSize = Regular;
  97. mLinkTypes = LinkData(AllFlags);
  98. #endif
  99. mIsAiControlled = true;
  100. for( S32 i = 0; i < MaxTriggerKeys; i ++ )
  101. mMoveTriggers[ i ] = false;
  102. mAttackRadius = 1;
  103. }
  104. /**
  105. * Destructor
  106. */
  107. AIPlayer::~AIPlayer()
  108. {
  109. }
  110. void AIPlayer::initPersistFields()
  111. {
  112. addGroup( "AI" );
  113. addField( "mMoveTolerance", TypeF32, Offset( mMoveTolerance, AIPlayer ),
  114. "@brief Distance from destination before stopping.\n\n"
  115. "When the AIPlayer is moving to a given destination it will move to within "
  116. "this distance of the destination and then stop. By providing this tolerance "
  117. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  118. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  119. addField( "moveStuckTolerance", TypeF32, Offset( mMoveStuckTolerance, AIPlayer ),
  120. "@brief Distance tolerance on stuck check.\n\n"
  121. "When the AIPlayer is moving to a given destination, if it ever moves less than "
  122. "this tolerance during a single tick, the AIPlayer is considered stuck. At this point "
  123. "the onMoveStuck() callback is called on the datablock.\n");
  124. addField( "moveStuckTestDelay", TypeS32, Offset( mMoveStuckTestDelay, AIPlayer ),
  125. "@brief The number of ticks to wait before testing if the AIPlayer is stuck.\n\n"
  126. "When the AIPlayer is asked to move, this property is the number of ticks to wait "
  127. "before the AIPlayer starts to check if it is stuck. This delay allows the AIPlayer "
  128. "to accelerate to full speed without its initial slow start being considered as stuck.\n"
  129. "@note Set to zero to have the stuck test start immediately.\n");
  130. addField( "AttackRadius", TypeF32, Offset( mAttackRadius, AIPlayer ),
  131. "@brief Distance considered in firing range for callback purposes.");
  132. endGroup( "AI" );
  133. #ifdef TORQUE_NAVIGATION_ENABLED
  134. addGroup("Pathfinding");
  135. addField("allowWalk", TypeBool, Offset(mLinkTypes.walk, AIPlayer),
  136. "Allow the character to walk on dry land.");
  137. addField("allowJump", TypeBool, Offset(mLinkTypes.jump, AIPlayer),
  138. "Allow the character to use jump links.");
  139. addField("allowDrop", TypeBool, Offset(mLinkTypes.drop, AIPlayer),
  140. "Allow the character to use drop links.");
  141. addField("allowSwim", TypeBool, Offset(mLinkTypes.swim, AIPlayer),
  142. "Allow the character to move in water.");
  143. addField("allowLedge", TypeBool, Offset(mLinkTypes.ledge, AIPlayer),
  144. "Allow the character to jump ledges.");
  145. addField("allowClimb", TypeBool, Offset(mLinkTypes.climb, AIPlayer),
  146. "Allow the character to use climb links.");
  147. addField("allowTeleport", TypeBool, Offset(mLinkTypes.teleport, AIPlayer),
  148. "Allow the character to use teleporters.");
  149. endGroup("Pathfinding");
  150. #endif // TORQUE_NAVIGATION_ENABLED
  151. Parent::initPersistFields();
  152. }
  153. bool AIPlayer::onAdd()
  154. {
  155. if (!Parent::onAdd())
  156. return false;
  157. // Use the eye as the current position (see getAIMove)
  158. MatrixF eye;
  159. getEyeTransform(&eye);
  160. mLastLocation = eye.getPosition();
  161. return true;
  162. }
  163. void AIPlayer::onRemove()
  164. {
  165. #ifdef TORQUE_NAVIGATION_ENABLED
  166. clearPath();
  167. clearCover();
  168. clearFollow();
  169. #endif
  170. Parent::onRemove();
  171. }
  172. /**
  173. * Sets the speed at which this AI moves
  174. *
  175. * @param speed Speed to move, default player was 10
  176. */
  177. void AIPlayer::setMoveSpeed( F32 speed )
  178. {
  179. mMoveSpeed = getMax(0.0f, getMin( 1.0f, speed ));
  180. }
  181. /**
  182. * Stops movement for this AI
  183. */
  184. void AIPlayer::stopMove()
  185. {
  186. mMoveState = ModeStop;
  187. #ifdef TORQUE_NAVIGATION_ENABLED
  188. clearPath();
  189. clearCover();
  190. clearFollow();
  191. #endif
  192. }
  193. /**
  194. * Sets how far away from the move location is considered
  195. * "on target"
  196. *
  197. * @param tolerance Movement tolerance for error
  198. */
  199. void AIPlayer::setMoveTolerance( const F32 tolerance )
  200. {
  201. mMoveTolerance = getMax( 0.1f, tolerance );
  202. }
  203. /**
  204. * Sets the location for the bot to run to
  205. *
  206. * @param location Point to run to
  207. */
  208. void AIPlayer::setMoveDestination( const Point3F &location, bool slowdown )
  209. {
  210. mMoveDestination = location;
  211. mMoveState = ModeMove;
  212. mMoveSlowdown = slowdown;
  213. mMoveStuckTestCountdown = mMoveStuckTestDelay;
  214. }
  215. /**
  216. * Sets the object the bot is targeting
  217. *
  218. * @param targetObject The object to target
  219. */
  220. void AIPlayer::setAimObject( GameBase *targetObject )
  221. {
  222. mAimObject = targetObject;
  223. mTargetInLOS = false;
  224. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  225. }
  226. /**
  227. * Sets the object the bot is targeting and an offset to add to target location
  228. *
  229. * @param targetObject The object to target
  230. * @param offset The offest from the target location to aim at
  231. */
  232. void AIPlayer::setAimObject(GameBase *targetObject, const Point3F& offset)
  233. {
  234. mAimObject = targetObject;
  235. mTargetInLOS = false;
  236. mAimOffset = offset;
  237. }
  238. /**
  239. * Sets the location for the bot to aim at
  240. *
  241. * @param location Point to aim at
  242. */
  243. void AIPlayer::setAimLocation( const Point3F &location )
  244. {
  245. mAimObject = 0;
  246. mAimLocationSet = true;
  247. mAimLocation = location;
  248. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  249. }
  250. /**
  251. * Clears the aim location and sets it to the bot's
  252. * current destination so he looks where he's going
  253. */
  254. void AIPlayer::clearAim()
  255. {
  256. mAimObject = 0;
  257. mAimLocationSet = false;
  258. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  259. }
  260. /**
  261. * Sets the correct aim for the bot to the target
  262. */
  263. void AIPlayer::getMuzzleVector(U32 imageSlot,VectorF* vec)
  264. {
  265. MatrixF mat;
  266. getMuzzleTransform(imageSlot,&mat);
  267. MountedImage& image = mMountedImageList[imageSlot];
  268. if (image.dataBlock->correctMuzzleVector)
  269. {
  270. disableHeadZCalc();
  271. if (getCorrectedAim(mat, vec))
  272. {
  273. enableHeadZCalc();
  274. return;
  275. }
  276. enableHeadZCalc();
  277. }
  278. mat.getColumn(1,vec);
  279. }
  280. /**
  281. * Set the state of a movement trigger.
  282. *
  283. * @param slot The trigger slot to set
  284. * @param isSet set/unset the trigger
  285. */
  286. void AIPlayer::setMoveTrigger( U32 slot, const bool isSet )
  287. {
  288. if(slot >= MaxTriggerKeys)
  289. {
  290. Con::errorf("Attempting to set an invalid trigger slot (%i)", slot);
  291. }
  292. else
  293. {
  294. mMoveTriggers[ slot ] = isSet; // set the trigger
  295. setMaskBits(NoWarpMask); // force the client to updateMove
  296. }
  297. }
  298. /**
  299. * Get the state of a movement trigger.
  300. *
  301. * @param slot The trigger slot to query
  302. * @return True if the trigger is set, false if it is not set
  303. */
  304. bool AIPlayer::getMoveTrigger( U32 slot ) const
  305. {
  306. if(slot >= MaxTriggerKeys)
  307. {
  308. Con::errorf("Attempting to get an invalid trigger slot (%i)", slot);
  309. return false;
  310. }
  311. else
  312. {
  313. return mMoveTriggers[ slot ];
  314. }
  315. }
  316. /**
  317. * Clear the trigger state for all movement triggers.
  318. */
  319. void AIPlayer::clearMoveTriggers()
  320. {
  321. for( U32 i = 0; i < MaxTriggerKeys; i ++ )
  322. setMoveTrigger( i, false );
  323. }
  324. /**
  325. * This method calculates the moves for the AI player
  326. *
  327. * @param movePtr Pointer to move the move list into
  328. */
  329. bool AIPlayer::getAIMove(Move *movePtr)
  330. {
  331. *movePtr = NullMove;
  332. // Use the eye as the current position.
  333. MatrixF eye;
  334. getEyeTransform(&eye);
  335. Point3F location = eye.getPosition();
  336. Point3F rotation = getRotation();
  337. #ifdef TORQUE_NAVIGATION_ENABLED
  338. if(mDamageState == Enabled)
  339. {
  340. if(mMoveState != ModeStop)
  341. updateNavMesh();
  342. if(!mFollowData.object.isNull())
  343. {
  344. if(mPathData.path.isNull())
  345. {
  346. if((getPosition() - mFollowData.object->getPosition()).len() > mFollowData.radius)
  347. followObject(mFollowData.object, mFollowData.radius);
  348. }
  349. else
  350. {
  351. if((mPathData.path->mTo - mFollowData.object->getPosition()).len() > mFollowData.radius)
  352. repath();
  353. else if((getPosition() - mFollowData.object->getPosition()).len() < mFollowData.radius)
  354. {
  355. clearPath();
  356. mMoveState = ModeStop;
  357. throwCallback("onTargetInRange");
  358. }
  359. else if((getPosition() - mFollowData.object->getPosition()).len() < mAttackRadius)
  360. {
  361. throwCallback("onTargetInFiringRange");
  362. }
  363. }
  364. }
  365. }
  366. #endif // TORQUE_NAVIGATION_ENABLED
  367. // Orient towards the aim point, aim object, or towards
  368. // our destination.
  369. if (mAimObject || mAimLocationSet || mMoveState != ModeStop)
  370. {
  371. // Update the aim position if we're aiming for an object
  372. if (mAimObject)
  373. mAimLocation = mAimObject->getPosition() + mAimOffset;
  374. else
  375. if (!mAimLocationSet)
  376. mAimLocation = mMoveDestination;
  377. F32 xDiff = mAimLocation.x - location.x;
  378. F32 yDiff = mAimLocation.y - location.y;
  379. if (!mIsZero(xDiff) || !mIsZero(yDiff))
  380. {
  381. // First do Yaw
  382. // use the cur yaw between -Pi and Pi
  383. F32 curYaw = rotation.z;
  384. while (curYaw > M_2PI_F)
  385. curYaw -= M_2PI_F;
  386. while (curYaw < -M_2PI_F)
  387. curYaw += M_2PI_F;
  388. // find the yaw offset
  389. F32 newYaw = mAtan2( xDiff, yDiff );
  390. F32 yawDiff = newYaw - curYaw;
  391. // make it between 0 and 2PI
  392. if( yawDiff < 0.0f )
  393. yawDiff += M_2PI_F;
  394. else if( yawDiff >= M_2PI_F )
  395. yawDiff -= M_2PI_F;
  396. // now make sure we take the short way around the circle
  397. if( yawDiff > M_PI_F )
  398. yawDiff -= M_2PI_F;
  399. else if( yawDiff < -M_PI_F )
  400. yawDiff += M_2PI_F;
  401. movePtr->yaw = yawDiff;
  402. // Next do pitch.
  403. if (!mAimObject && !mAimLocationSet)
  404. {
  405. // Level out if were just looking at our next way point.
  406. Point3F headRotation = getHeadRotation();
  407. movePtr->pitch = -headRotation.x;
  408. }
  409. else
  410. {
  411. // This should be adjusted to run from the
  412. // eye point to the object's center position. Though this
  413. // works well enough for now.
  414. F32 vertDist = mAimLocation.z - location.z;
  415. F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  416. F32 newPitch = mAtan2( horzDist, vertDist ) - ( M_PI_F / 2.0f );
  417. if (mFabs(newPitch) > 0.01f)
  418. {
  419. Point3F headRotation = getHeadRotation();
  420. movePtr->pitch = newPitch - headRotation.x;
  421. }
  422. }
  423. }
  424. }
  425. else
  426. {
  427. // Level out if we're not doing anything else
  428. Point3F headRotation = getHeadRotation();
  429. movePtr->pitch = -headRotation.x;
  430. }
  431. // Move towards the destination
  432. if (mMoveState != ModeStop)
  433. {
  434. F32 xDiff = mMoveDestination.x - location.x;
  435. F32 yDiff = mMoveDestination.y - location.y;
  436. // Check if we should mMove, or if we are 'close enough'
  437. if (mFabs(xDiff) < mMoveTolerance && mFabs(yDiff) < mMoveTolerance)
  438. {
  439. mMoveState = ModeStop;
  440. onReachDestination();
  441. }
  442. else
  443. {
  444. // Build move direction in world space
  445. if (mIsZero(xDiff))
  446. movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f;
  447. else
  448. if (mIsZero(yDiff))
  449. movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f;
  450. else
  451. if (mFabs(xDiff) > mFabs(yDiff))
  452. {
  453. F32 value = mFabs(yDiff / xDiff);
  454. movePtr->y = (location.y > mMoveDestination.y) ? -value : value;
  455. movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f;
  456. }
  457. else
  458. {
  459. F32 value = mFabs(xDiff / yDiff);
  460. movePtr->x = (location.x > mMoveDestination.x) ? -value : value;
  461. movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f;
  462. }
  463. // Rotate the move into object space (this really only needs
  464. // a 2D matrix)
  465. Point3F newMove;
  466. MatrixF moveMatrix;
  467. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  468. moveMatrix.mulV( Point3F( movePtr->x, movePtr->y, 0.0f ), &newMove );
  469. movePtr->x = newMove.x;
  470. movePtr->y = newMove.y;
  471. // Set movement speed. We'll slow down once we get close
  472. // to try and stop on the spot...
  473. if (mMoveSlowdown)
  474. {
  475. F32 speed = mMoveSpeed;
  476. F32 dist = mSqrt(xDiff*xDiff + yDiff*yDiff);
  477. F32 maxDist = mMoveTolerance*2;
  478. if (dist < maxDist)
  479. speed *= dist / maxDist;
  480. movePtr->x *= speed;
  481. movePtr->y *= speed;
  482. mMoveState = ModeSlowing;
  483. }
  484. else
  485. {
  486. movePtr->x *= mMoveSpeed;
  487. movePtr->y *= mMoveSpeed;
  488. mMoveState = ModeMove;
  489. }
  490. // Don't check for ai stuckness if animation during
  491. // an anim-clip effect override.
  492. if (mDamageState == Enabled && !(anim_clip_flags & ANIM_OVERRIDDEN) && !isAnimationLocked()) {
  493. if (mMoveStuckTestCountdown > 0)
  494. --mMoveStuckTestCountdown;
  495. else
  496. {
  497. // We should check to see if we are stuck...
  498. F32 locationDelta = (location - mLastLocation).len();
  499. if (locationDelta < mMoveStuckTolerance && mDamageState == Enabled)
  500. {
  501. // If we are slowing down, then it's likely that our location delta will be less than
  502. // our move stuck tolerance. Because we can be both slowing and stuck
  503. // we should TRY to check if we've moved. This could use better detection.
  504. if ( mMoveState != ModeSlowing || locationDelta == 0 )
  505. {
  506. mMoveState = ModeStuck;
  507. onStuck();
  508. }
  509. }
  510. }
  511. }
  512. }
  513. }
  514. // Test for target location in sight if it's an object. The LOS is
  515. // run from the eye position to the center of the object's bounding,
  516. // which is not very accurate.
  517. if (mAimObject)
  518. {
  519. if (checkInLos(mAimObject.getPointer()))
  520. {
  521. if (!mTargetInLOS)
  522. {
  523. throwCallback( "onTargetEnterLOS" );
  524. mTargetInLOS = true;
  525. }
  526. }
  527. else if (mTargetInLOS)
  528. {
  529. throwCallback( "onTargetExitLOS" );
  530. mTargetInLOS = false;
  531. }
  532. }
  533. Pose desiredPose = mPose;
  534. if ( mSwimming )
  535. desiredPose = SwimPose;
  536. else if ( mAiPose == 1 && canCrouch() )
  537. desiredPose = CrouchPose;
  538. else if ( mAiPose == 2 && canProne() )
  539. desiredPose = PronePose;
  540. else if ( mAiPose == 3 && canSprint() )
  541. desiredPose = SprintPose;
  542. else if ( canStand() )
  543. desiredPose = StandPose;
  544. setPose( desiredPose );
  545. // Replicate the trigger state into the move so that
  546. // triggers can be controlled from scripts.
  547. for( U32 i = 0; i < MaxTriggerKeys; i++ )
  548. movePtr->trigger[ i ] = getImageTriggerState( i );
  549. #ifdef TORQUE_NAVIGATION_ENABLED
  550. if(mJump == Now)
  551. {
  552. movePtr->trigger[2] = true;
  553. mJump = None;
  554. }
  555. else if(mJump == Ledge)
  556. {
  557. // If we're not touching the ground, jump!
  558. RayInfo info;
  559. if(!getContainer()->castRay(getPosition(), getPosition() - Point3F(0, 0, 0.4f), StaticShapeObjectType, &info))
  560. {
  561. movePtr->trigger[2] = true;
  562. mJump = None;
  563. }
  564. }
  565. #endif // TORQUE_NAVIGATION_ENABLED
  566. if (!(anim_clip_flags & ANIM_OVERRIDDEN) && !isAnimationLocked())
  567. mLastLocation = location;
  568. return true;
  569. }
  570. void AIPlayer::updateMove(const Move* move)
  571. {
  572. if (!getControllingClient() && isGhost())
  573. return;
  574. Parent::updateMove(move);
  575. }
  576. void AIPlayer::setAiPose( S32 pose )
  577. {
  578. if (!getControllingClient() && isGhost())
  579. return;
  580. mAiPose = pose;
  581. }
  582. S32 AIPlayer::getAiPose()
  583. {
  584. return mAiPose;
  585. }
  586. /**
  587. * Utility function to throw callbacks. Callbacks always occure
  588. * on the datablock class.
  589. *
  590. * @param name Name of script function to call
  591. */
  592. void AIPlayer::throwCallback( const char *name )
  593. {
  594. Con::executef(getDataBlock(), name, getIdString());
  595. }
  596. /**
  597. * Called when we get within mMoveTolerance of our destination set using
  598. * setMoveDestination(). Only fires the script callback if we are at the end
  599. * of a pathfinding path, or have no pathfinding path.
  600. */
  601. void AIPlayer::onReachDestination()
  602. {
  603. #ifdef TORQUE_NAVIGATION_ENABLED
  604. if(!mPathData.path.isNull())
  605. {
  606. if(mPathData.index == mPathData.path->size() - 1)
  607. {
  608. // Handle looping paths.
  609. if(mPathData.path->mIsLooping)
  610. moveToNode(0);
  611. // Otherwise end path.
  612. else
  613. {
  614. clearPath();
  615. throwCallback("onReachDestination");
  616. }
  617. }
  618. else
  619. {
  620. moveToNode(mPathData.index + 1);
  621. // Throw callback every time if we're on a looping path.
  622. //if(mPathData.path->mIsLooping)
  623. //throwCallback("onReachDestination");
  624. }
  625. }
  626. else
  627. #endif
  628. throwCallback("onReachDestination");
  629. }
  630. /**
  631. * Called when we move less than mMoveStuckTolerance in a tick, signalling
  632. * that some obstacle is preventing us from getting where we need to go.
  633. */
  634. void AIPlayer::onStuck()
  635. {
  636. throwCallback("onMoveStuck");
  637. #ifdef TORQUE_NAVIGATION_ENABLED
  638. if(!mPathData.path.isNull())
  639. repath();
  640. #endif
  641. }
  642. #ifdef TORQUE_NAVIGATION_ENABLED
  643. // --------------------------------------------------------------------------------------------
  644. // Pathfinding
  645. // --------------------------------------------------------------------------------------------
  646. void AIPlayer::clearPath()
  647. {
  648. // Only delete if we own the path.
  649. if(!mPathData.path.isNull() && mPathData.owned)
  650. mPathData.path->deleteObject();
  651. // Reset path data.
  652. mPathData = PathData();
  653. }
  654. void AIPlayer::clearCover()
  655. {
  656. // Notify cover that we are no longer on our way.
  657. if(!mCoverData.cover.isNull())
  658. mCoverData.cover->setOccupied(false);
  659. mCoverData = CoverData();
  660. }
  661. void AIPlayer::clearFollow()
  662. {
  663. mFollowData = FollowData();
  664. }
  665. void AIPlayer::moveToNode(S32 node)
  666. {
  667. if(mPathData.path.isNull())
  668. return;
  669. // -1 is shorthand for 'last path node'.
  670. if(node == -1)
  671. node = mPathData.path->size() - 1;
  672. // Consider slowing down on the last path node.
  673. setMoveDestination(mPathData.path->getNode(node), false);
  674. // Check flags for this segment.
  675. if(mPathData.index)
  676. {
  677. U16 flags = mPathData.path->getFlags(node - 1);
  678. // Jump if we must.
  679. if(flags & LedgeFlag)
  680. mJump = Ledge;
  681. else if(flags & JumpFlag)
  682. mJump = Now;
  683. else
  684. // Catch pathing errors.
  685. mJump = None;
  686. }
  687. // Store current index.
  688. mPathData.index = node;
  689. }
  690. bool AIPlayer::setPathDestination(const Point3F &pos)
  691. {
  692. // Pathfinding only happens on the server.
  693. if(!isServerObject())
  694. return false;
  695. if(!getNavMesh())
  696. updateNavMesh();
  697. // If we can't find a mesh, just move regularly.
  698. if(!getNavMesh())
  699. {
  700. //setMoveDestination(pos);
  701. throwCallback("onPathFailed");
  702. return false;
  703. }
  704. // Create a new path.
  705. NavPath *path = new NavPath();
  706. path->mMesh = getNavMesh();
  707. path->mFrom = getPosition();
  708. path->mTo = pos;
  709. path->mFromSet = path->mToSet = true;
  710. path->mAlwaysRender = true;
  711. path->mLinkTypes = mLinkTypes;
  712. path->mXray = true;
  713. // Paths plan automatically upon being registered.
  714. if(!path->registerObject())
  715. {
  716. delete path;
  717. return false;
  718. }
  719. if(path->success())
  720. {
  721. // Clear any current path we might have.
  722. clearPath();
  723. clearCover();
  724. clearFollow();
  725. // Store new path.
  726. mPathData.path = path;
  727. mPathData.owned = true;
  728. // Skip node 0, which we are currently standing on.
  729. moveToNode(1);
  730. throwCallback("onPathSuccess");
  731. return true;
  732. }
  733. else
  734. {
  735. // Just move normally if we can't path.
  736. //setMoveDestination(pos, true);
  737. //return;
  738. throwCallback("onPathFailed");
  739. path->deleteObject();
  740. return false;
  741. }
  742. }
  743. DefineEngineMethod(AIPlayer, setPathDestination, bool, (Point3F goal),,
  744. "@brief Tells the AI to find a path to the location provided\n\n"
  745. "@param goal Coordinates in world space representing location to move to.\n"
  746. "@return True if a path was found.\n\n"
  747. "@see getPathDestination()\n"
  748. "@see setMoveDestination()\n")
  749. {
  750. return object->setPathDestination(goal);
  751. }
  752. Point3F AIPlayer::getPathDestination() const
  753. {
  754. if(!mPathData.path.isNull())
  755. return mPathData.path->mTo;
  756. return Point3F(0, 0, 0);
  757. }
  758. DefineEngineMethod(AIPlayer, getPathDestination, Point3F, (),,
  759. "@brief Get the AIPlayer's current pathfinding destination.\n\n"
  760. "@return Returns a point containing the \"x y z\" position "
  761. "of the AIPlayer's current path destination. If no path destination "
  762. "has yet been set, this returns \"0 0 0\"."
  763. "@see setPathDestination()\n")
  764. {
  765. return object->getPathDestination();
  766. }
  767. void AIPlayer::followNavPath(NavPath *path)
  768. {
  769. if(!isServerObject())
  770. return;
  771. // Get rid of our current path.
  772. clearPath();
  773. clearCover();
  774. clearFollow();
  775. // Follow new path.
  776. mPathData.path = path;
  777. mPathData.owned = false;
  778. // Start from 0 since we might not already be there.
  779. moveToNode(0);
  780. }
  781. DefineEngineMethod(AIPlayer, followNavPath, void, (SimObjectId obj),,
  782. "@brief Tell the AIPlayer to follow a path.\n\n"
  783. "@param obj ID of a NavPath object for the character to follow.")
  784. {
  785. NavPath *path;
  786. if(Sim::findObject(obj, path))
  787. object->followNavPath(path);
  788. }
  789. void AIPlayer::followObject(SceneObject *obj, F32 radius)
  790. {
  791. if(!isServerObject())
  792. return;
  793. if ((mFollowData.lastPos - obj->getPosition()).len()<mMoveTolerance)
  794. return;
  795. if(setPathDestination(obj->getPosition()))
  796. {
  797. clearCover();
  798. mFollowData.object = obj;
  799. mFollowData.radius = radius;
  800. mFollowData.lastPos = obj->getPosition();
  801. }
  802. }
  803. DefineEngineMethod(AIPlayer, followObject, void, (SimObjectId obj, F32 radius),,
  804. "@brief Tell the AIPlayer to follow another object.\n\n"
  805. "@param obj ID of the object to follow.\n"
  806. "@param radius Maximum distance we let the target escape to.")
  807. {
  808. SceneObject *follow;
  809. object->clearPath();
  810. object->clearCover();
  811. object->clearFollow();
  812. if(Sim::findObject(obj, follow))
  813. object->followObject(follow, radius);
  814. }
  815. void AIPlayer::repath()
  816. {
  817. // Ineffectual if we don't have a path, or are using someone else's.
  818. if(mPathData.path.isNull() || !mPathData.owned)
  819. return;
  820. // If we're following, get their position.
  821. if(!mFollowData.object.isNull())
  822. mPathData.path->mTo = mFollowData.object->getPosition();
  823. // Update from position and replan.
  824. mPathData.path->mFrom = getPosition();
  825. mPathData.path->plan();
  826. // Move to first node (skip start pos).
  827. moveToNode(1);
  828. }
  829. DefineEngineMethod(AIPlayer, repath, void, (),,
  830. "@brief Tells the AI to re-plan its path. Does nothing if the character "
  831. "has no path, or if it is following a mission path.\n\n")
  832. {
  833. object->repath();
  834. }
  835. struct CoverSearch
  836. {
  837. Point3F loc;
  838. Point3F from;
  839. F32 dist;
  840. F32 best;
  841. CoverPoint *point;
  842. CoverSearch() : loc(0, 0, 0), from(0, 0, 0)
  843. {
  844. best = -FLT_MAX;
  845. point = NULL;
  846. dist = FLT_MAX;
  847. }
  848. };
  849. static void findCoverCallback(SceneObject *obj, void *key)
  850. {
  851. CoverPoint *p = dynamic_cast<CoverPoint*>(obj);
  852. if(!p || p->isOccupied())
  853. return;
  854. CoverSearch *s = static_cast<CoverSearch*>(key);
  855. Point3F dir = s->from - p->getPosition();
  856. dir.normalizeSafe();
  857. // Score first based on angle of cover point to enemy.
  858. F32 score = mDot(p->getNormal(), dir);
  859. // Score also based on distance from seeker.
  860. score -= (p->getPosition() - s->loc).len() / s->dist;
  861. // Finally, consider cover size.
  862. score += (p->getSize() + 1) / CoverPoint::NumSizes;
  863. score *= p->getQuality();
  864. if(score > s->best)
  865. {
  866. s->best = score;
  867. s->point = p;
  868. }
  869. }
  870. bool AIPlayer::findCover(const Point3F &from, F32 radius)
  871. {
  872. if(radius <= 0)
  873. return false;
  874. // Create a search state.
  875. CoverSearch s;
  876. s.loc = getPosition();
  877. s.dist = radius;
  878. // Direction we seek cover FROM.
  879. s.from = from;
  880. // Find cover points.
  881. Box3F box(radius * 2.0f);
  882. box.setCenter(getPosition());
  883. getContainer()->findObjects(box, MarkerObjectType, findCoverCallback, &s);
  884. // Go to cover!
  885. if(s.point)
  886. {
  887. // Calling setPathDestination clears cover...
  888. bool foundPath = setPathDestination(s.point->getPosition());
  889. // Now store the cover info.
  890. mCoverData.cover = s.point;
  891. s.point->setOccupied(true);
  892. return foundPath;
  893. }
  894. return false;
  895. }
  896. DefineEngineMethod(AIPlayer, findCover, S32, (Point3F from, F32 radius),,
  897. "@brief Tells the AI to find cover nearby.\n\n"
  898. "@param from Location to find cover from (i.e., enemy position).\n"
  899. "@param radius Distance to search for cover.\n"
  900. "@return Cover point ID if cover was found, -1 otherwise.\n\n")
  901. {
  902. if(object->findCover(from, radius))
  903. {
  904. CoverPoint* cover = object->getCover();
  905. return cover ? cover->getId() : -1;
  906. }
  907. else
  908. {
  909. return -1;
  910. }
  911. }
  912. NavMesh *AIPlayer::findNavMesh() const
  913. {
  914. // Search for NavMeshes that contain us entirely with the smallest possible
  915. // volume.
  916. NavMesh *mesh = NULL;
  917. SimSet *set = NavMesh::getServerSet();
  918. for(U32 i = 0; i < set->size(); i++)
  919. {
  920. NavMesh *m = static_cast<NavMesh*>(set->at(i));
  921. if(m->getWorldBox().isContained(getWorldBox()))
  922. {
  923. // Check that mesh size is appropriate.
  924. if(mMount.object) // Should use isMounted() but it's not const. Grr.
  925. {
  926. if(!m->mVehicles)
  927. continue;
  928. }
  929. else
  930. {
  931. if((getNavSize() == Small && !m->mSmallCharacters) ||
  932. (getNavSize() == Regular && !m->mRegularCharacters) ||
  933. (getNavSize() == Large && !m->mLargeCharacters))
  934. continue;
  935. }
  936. if(!mesh || m->getWorldBox().getVolume() < mesh->getWorldBox().getVolume())
  937. mesh = m;
  938. }
  939. }
  940. return mesh;
  941. }
  942. DefineEngineMethod(AIPlayer, findNavMesh, S32, (),,
  943. "@brief Get the NavMesh object this AIPlayer is currently using.\n\n"
  944. "@return The ID of the NavPath object this character is using for "
  945. "pathfinding. This is determined by the character's location, "
  946. "navigation type and other factors. Returns -1 if no NavMesh is "
  947. "found.")
  948. {
  949. NavMesh *mesh = object->getNavMesh();
  950. return mesh ? mesh->getId() : -1;
  951. }
  952. void AIPlayer::updateNavMesh()
  953. {
  954. NavMesh *old = mNavMesh;
  955. if(mNavMesh.isNull())
  956. mNavMesh = findNavMesh();
  957. else
  958. {
  959. if(!mNavMesh->getWorldBox().isContained(getWorldBox()))
  960. mNavMesh = findNavMesh();
  961. }
  962. // See if we need to update our path.
  963. if(mNavMesh != old && !mPathData.path.isNull())
  964. {
  965. setPathDestination(mPathData.path->mTo);
  966. }
  967. }
  968. DefineEngineMethod(AIPlayer, getNavMesh, S32, (),,
  969. "@brief Return the NavMesh this AIPlayer is using to navigate.\n\n")
  970. {
  971. NavMesh *m = object->getNavMesh();
  972. return m ? m->getId() : 0;
  973. }
  974. DefineEngineMethod(AIPlayer, setNavSize, void, (const char *size),,
  975. "@brief Set the size of NavMesh this character uses. One of \"Small\", \"Regular\" or \"Large\".")
  976. {
  977. if(!String::compare(size, "Small"))
  978. object->setNavSize(AIPlayer::Small);
  979. else if(!String::compare(size, "Regular"))
  980. object->setNavSize(AIPlayer::Regular);
  981. else if(!String::compare(size, "Large"))
  982. object->setNavSize(AIPlayer::Large);
  983. else
  984. Con::errorf("AIPlayer::setNavSize: no such size '%s'.", size);
  985. }
  986. DefineEngineMethod(AIPlayer, getNavSize, const char*, (),,
  987. "@brief Return the size of NavMesh this character uses for pathfinding.")
  988. {
  989. switch(object->getNavSize())
  990. {
  991. case AIPlayer::Small:
  992. return "Small";
  993. case AIPlayer::Regular:
  994. return "Regular";
  995. case AIPlayer::Large:
  996. return "Large";
  997. }
  998. return "";
  999. }
  1000. #endif // TORQUE_NAVIGATION_ENABLED
  1001. // --------------------------------------------------------------------------------------------
  1002. // Console Functions
  1003. // --------------------------------------------------------------------------------------------
  1004. DefineEngineMethod( AIPlayer, stop, void, ( ),,
  1005. "@brief Tells the AIPlayer to stop moving.\n\n")
  1006. {
  1007. object->stopMove();
  1008. }
  1009. DefineEngineMethod( AIPlayer, clearAim, void, ( ),,
  1010. "@brief Use this to stop aiming at an object or a point.\n\n"
  1011. "@see setAimLocation()\n"
  1012. "@see setAimObject()\n")
  1013. {
  1014. object->clearAim();
  1015. }
  1016. DefineEngineMethod( AIPlayer, setMoveSpeed, void, ( F32 speed ),,
  1017. "@brief Sets the move speed for an AI object.\n\n"
  1018. "@param speed A speed multiplier between 0.0 and 1.0. "
  1019. "This is multiplied by the AIPlayer's base movement rates (as defined in "
  1020. "its PlayerData datablock)\n\n"
  1021. "@see getMoveDestination()\n")
  1022. {
  1023. object->setMoveSpeed(speed);
  1024. }
  1025. DefineEngineMethod( AIPlayer, getMoveSpeed, F32, ( ),,
  1026. "@brief Gets the move speed of an AI object.\n\n"
  1027. "@return A speed multiplier between 0.0 and 1.0.\n\n"
  1028. "@see setMoveSpeed()\n")
  1029. {
  1030. return object->getMoveSpeed();
  1031. }
  1032. DefineEngineMethod( AIPlayer, setMoveDestination, void, ( Point3F goal, bool slowDown ), ( true ),
  1033. "@brief Tells the AI to move to the location provided\n\n"
  1034. "@param goal Coordinates in world space representing location to move to.\n"
  1035. "@param slowDown A boolean value. If set to true, the bot will slow down "
  1036. "when it gets within 5-meters of its move destination. If false, the bot "
  1037. "will stop abruptly when it reaches the move destination. By default, this is true.\n\n"
  1038. "@note Upon reaching a move destination, the bot will clear its move destination and "
  1039. "calls to getMoveDestination will return \"0 0 0\"."
  1040. "@see getMoveDestination()\n")
  1041. {
  1042. object->setMoveDestination( goal, slowDown);
  1043. }
  1044. DefineEngineMethod( AIPlayer, getMoveDestination, Point3F, (),,
  1045. "@brief Get the AIPlayer's current destination.\n\n"
  1046. "@return Returns a point containing the \"x y z\" position "
  1047. "of the AIPlayer's current move destination. If no move destination "
  1048. "has yet been set, this returns \"0 0 0\"."
  1049. "@see setMoveDestination()\n")
  1050. {
  1051. return object->getMoveDestination();
  1052. }
  1053. DefineEngineMethod( AIPlayer, setAimLocation, void, ( Point3F target ),,
  1054. "@brief Tells the AIPlayer to aim at the location provided.\n\n"
  1055. "@param target An \"x y z\" position in the game world to target.\n\n"
  1056. "@see getAimLocation()\n")
  1057. {
  1058. object->setAimLocation(target);
  1059. }
  1060. DefineEngineMethod( AIPlayer, getAimLocation, Point3F, (),,
  1061. "@brief Returns the point the AIPlayer is aiming at.\n\n"
  1062. "This will reflect the position set by setAimLocation(), "
  1063. "or the position of the object that the bot is now aiming at. "
  1064. "If the bot is not aiming at anything, this value will "
  1065. "change to whatever point the bot's current line-of-sight intercepts."
  1066. "@return World space coordinates of the object AI is aiming at. Formatted as \"X Y Z\".\n\n"
  1067. "@see setAimLocation()\n"
  1068. "@see setAimObject()\n")
  1069. {
  1070. return object->getAimLocation();
  1071. }
  1072. ConsoleDocFragment _setAimObject(
  1073. "@brief Sets the AIPlayer's target object. May optionally set an offset from target location\n\n"
  1074. "@param targetObject The object to target\n"
  1075. "@param offset Optional three-element offset vector which will be added to the position of the aim object.\n\n"
  1076. "@tsexample\n"
  1077. "// Without an offset\n"
  1078. "%ai.setAimObject(%target);\n\n"
  1079. "// With an offset\n"
  1080. "// Cause our AI object to aim at the target\n"
  1081. "// offset (0, 0, 1) so you don't aim at the target's feet\n"
  1082. "%ai.setAimObject(%target, \"0 0 1\");\n"
  1083. "@endtsexample\n\n"
  1084. "@see getAimLocation()\n"
  1085. "@see getAimObject()\n"
  1086. "@see clearAim()\n",
  1087. "AIPlayer",
  1088. "void setAimObject(GameBase targetObject, Point3F offset);"
  1089. );
  1090. DefineEngineMethod( AIPlayer, setAimObject, void, ( const char * objName, Point3F offset ), (Point3F::Zero), "( GameBase obj, [Point3F offset] )"
  1091. "Sets the bot's target object. Optionally set an offset from target location."
  1092. "@hide")
  1093. {
  1094. // Find the target
  1095. GameBase *targetObject;
  1096. if( Sim::findObject( objName, targetObject ) )
  1097. {
  1098. object->setAimObject( targetObject, offset );
  1099. }
  1100. else
  1101. object->setAimObject( 0, offset );
  1102. }
  1103. DefineEngineMethod( AIPlayer, getAimObject, S32, (),,
  1104. "@brief Gets the object the AIPlayer is targeting.\n\n"
  1105. "@return Returns -1 if no object is being aimed at, "
  1106. "or the SimObjectID of the object the AIPlayer is aiming at.\n\n"
  1107. "@see setAimObject()\n")
  1108. {
  1109. GameBase* obj = object->getAimObject();
  1110. return obj? obj->getId(): -1;
  1111. }
  1112. bool AIPlayer::checkInLos(GameBase* target, bool _useMuzzle, bool _checkEnabled)
  1113. {
  1114. if (!isServerObject()) return false;
  1115. if (!target)
  1116. {
  1117. target = mAimObject.getPointer();
  1118. if (!target)
  1119. return false;
  1120. }
  1121. if (_checkEnabled)
  1122. {
  1123. if (target->getTypeMask() & ShapeBaseObjectType)
  1124. {
  1125. ShapeBase *shapeBaseCheck = static_cast<ShapeBase *>(target);
  1126. if (shapeBaseCheck)
  1127. if (shapeBaseCheck->getDamageState() != Enabled) return false;
  1128. }
  1129. else
  1130. return false;
  1131. }
  1132. RayInfo ri;
  1133. disableCollision();
  1134. S32 mountCount = target->getMountedObjectCount();
  1135. for (S32 i = 0; i < mountCount; i++)
  1136. {
  1137. target->getMountedObject(i)->disableCollision();
  1138. }
  1139. Point3F checkPoint ;
  1140. if (_useMuzzle)
  1141. getMuzzlePointAI(0, &checkPoint );
  1142. else
  1143. {
  1144. MatrixF eyeMat;
  1145. getEyeTransform(&eyeMat);
  1146. eyeMat.getColumn(3, &checkPoint );
  1147. }
  1148. bool hit = !gServerContainer.castRay(checkPoint, target->getBoxCenter(), sAIPlayerLoSMask, &ri);
  1149. enableCollision();
  1150. for (S32 i = 0; i < mountCount; i++)
  1151. {
  1152. target->getMountedObject(i)->enableCollision();
  1153. }
  1154. return hit;
  1155. }
  1156. DefineEngineMethod(AIPlayer, checkInLos, bool, (ShapeBase* obj, bool useMuzzle, bool checkEnabled),(nullAsType<ShapeBase*>(), false, false),
  1157. "@brief Check whether an object is in line of sight.\n"
  1158. "@obj Object to check. (If blank, it will check the current target).\n"
  1159. "@useMuzzle Use muzzle position. Otherwise use eye position. (defaults to false).\n"
  1160. "@checkEnabled check whether the object can take damage and if so is still alive.(Defaults to false)\n")
  1161. {
  1162. return object->checkInLos(obj, useMuzzle, checkEnabled);
  1163. }
  1164. bool AIPlayer::checkInFoV(GameBase* target, F32 camFov, bool _checkEnabled)
  1165. {
  1166. if (!isServerObject()) return false;
  1167. if (!target)
  1168. {
  1169. target = mAimObject.getPointer();
  1170. if (!target)
  1171. return false;
  1172. }
  1173. if (_checkEnabled)
  1174. {
  1175. if (target->getTypeMask() & ShapeBaseObjectType)
  1176. {
  1177. ShapeBase *shapeBaseCheck = static_cast<ShapeBase *>(target);
  1178. if (shapeBaseCheck)
  1179. if (shapeBaseCheck->getDamageState() != Enabled) return false;
  1180. }
  1181. else
  1182. return false;
  1183. }
  1184. MatrixF cam = getTransform();
  1185. Point3F camPos;
  1186. VectorF camDir;
  1187. cam.getColumn(3, &camPos);
  1188. cam.getColumn(1, &camDir);
  1189. camFov = mDegToRad(camFov) / 2;
  1190. Point3F shapePos = target->getBoxCenter();
  1191. VectorF shapeDir = shapePos - camPos;
  1192. // Test to see if it's within our viewcone, this test doesn't
  1193. // actually match the viewport very well, should consider
  1194. // projection and box test.
  1195. shapeDir.normalize();
  1196. F32 dot = mDot(shapeDir, camDir);
  1197. return (dot > mCos(camFov));
  1198. }
  1199. DefineEngineMethod(AIPlayer, checkInFoV, bool, (ShapeBase* obj, F32 fov, bool checkEnabled), (nullAsType<ShapeBase*>(), 45.0f, false),
  1200. "@brief Check whether an object is within a specified veiw cone.\n"
  1201. "@obj Object to check. (If blank, it will check the current target).\n"
  1202. "@fov view angle in degrees.(Defaults to 45)\n"
  1203. "@checkEnabled check whether the object can take damage and if so is still alive.(Defaults to false)\n")
  1204. {
  1205. return object->checkInFoV(obj, fov, checkEnabled);
  1206. }
  1207. DefineEngineMethod( AIPlayer, setMoveTrigger, void, ( U32 slot ),,
  1208. "@brief Sets a movement trigger on an AI object.\n\n"
  1209. "@param slot The trigger slot to set.\n"
  1210. "@see getMoveTrigger()\n"
  1211. "@see clearMoveTrigger()\n"
  1212. "@see clearMoveTriggers()\n")
  1213. {
  1214. object->setMoveTrigger( slot, true );
  1215. }
  1216. DefineEngineMethod( AIPlayer, clearMoveTrigger, void, ( U32 slot ),,
  1217. "@brief Clears a movement trigger on an AI object.\n\n"
  1218. "@param slot The trigger slot to set.\n"
  1219. "@see setMoveTrigger()\n"
  1220. "@see getMoveTrigger()\n"
  1221. "@see clearMoveTriggers()\n")
  1222. {
  1223. object->setMoveTrigger( slot, false );
  1224. }
  1225. DefineEngineMethod( AIPlayer, getMoveTrigger, bool, ( U32 slot ),,
  1226. "@brief Tests if a movement trigger on an AI object is set.\n\n"
  1227. "@param slot The trigger slot to check.\n"
  1228. "@return a boolean indicating if the trigger is set/unset.\n"
  1229. "@see setMoveTrigger()\n"
  1230. "@see clearMoveTrigger()\n"
  1231. "@see clearMoveTriggers()\n")
  1232. {
  1233. return object->getMoveTrigger( slot );
  1234. }
  1235. DefineEngineMethod( AIPlayer, clearMoveTriggers, void, ( ),,
  1236. "@brief Clear ALL movement triggers on an AI object.\n"
  1237. "@see setMoveTrigger()\n"
  1238. "@see getMoveTrigger()\n"
  1239. "@see clearMoveTrigger()\n")
  1240. {
  1241. object->clearMoveTriggers();
  1242. }
  1243. // These changes coordinate with anim-clip mods to parent class, Player.
  1244. // New method, restartMove(), restores the AIPlayer to its normal move-state
  1245. // following animation overrides from AFX. The tag argument is used to match
  1246. // the latest override and prevents interruption of overlapping animation
  1247. // overrides. See related anim-clip changes in Player.[h,cc].
  1248. void AIPlayer::restartMove(U32 tag)
  1249. {
  1250. if (tag != 0 && tag == last_anim_tag)
  1251. {
  1252. if (mMoveState_saved != -1)
  1253. {
  1254. mMoveState = (MoveState) mMoveState_saved;
  1255. mMoveState_saved = -1;
  1256. }
  1257. bool is_death_anim = ((anim_clip_flags & IS_DEATH_ANIM) != 0);
  1258. last_anim_tag = 0;
  1259. anim_clip_flags &= ~(ANIM_OVERRIDDEN | IS_DEATH_ANIM);
  1260. if (mDamageState != Enabled)
  1261. {
  1262. if (!is_death_anim)
  1263. {
  1264. // this is a bit hardwired and desperate,
  1265. // but if he's dead he needs to look like it.
  1266. setActionThread("death10", false, false, false);
  1267. }
  1268. }
  1269. }
  1270. }
  1271. // New method, saveMoveState(), stores the current movement state
  1272. // so that it can be restored when restartMove() is called.
  1273. void AIPlayer::saveMoveState()
  1274. {
  1275. if (mMoveState_saved == -1)
  1276. mMoveState_saved = (S32) mMoveState;
  1277. }
  1278. F32 AIPlayer::getTargetDistance(GameBase* target, bool _checkEnabled)
  1279. {
  1280. if (!isServerObject()) return false;
  1281. if (!target)
  1282. {
  1283. target = mAimObject.getPointer();
  1284. if (!target)
  1285. return F32_MAX;
  1286. }
  1287. if (_checkEnabled)
  1288. {
  1289. if (target->getTypeMask() & ShapeBaseObjectType)
  1290. {
  1291. ShapeBase *shapeBaseCheck = static_cast<ShapeBase *>(target);
  1292. if (shapeBaseCheck)
  1293. if (shapeBaseCheck->getDamageState() != Enabled) return false;
  1294. }
  1295. else
  1296. return F32_MAX;
  1297. }
  1298. return (getPosition() - target->getPosition()).len();
  1299. }
  1300. DefineEngineMethod(AIPlayer, getTargetDistance, F32, (ShapeBase* obj, bool checkEnabled), (nullAsType<ShapeBase*>(), false),
  1301. "@brief The distance to a given object.\n"
  1302. "@obj Object to check. (If blank, it will check the current target).\n"
  1303. "@checkEnabled check whether the object can take damage and if so is still alive.(Defaults to false)\n")
  1304. {
  1305. return object->getTargetDistance(obj, checkEnabled);
  1306. }
  1307. DefineEngineMethod( AIPlayer, setAiPose, void, ( S32 pose ),,
  1308. "@brief Sets the AiPose for an AI object.\n"
  1309. "@param pose StandPose=0, CrouchPose=1, PronePose=2, SprintPose=3.\n"
  1310. "Uses the new AiPose variable from shapebase (as defined in its PlayerData datablock).\n")
  1311. {
  1312. object->setAiPose(pose);
  1313. }
  1314. DefineEngineMethod( AIPlayer, getAiPose, S32, (),,
  1315. "@brief Get the object's current AiPose.\n"
  1316. "@return StandPose=0, CrouchPose=1, PronePose=2, SprintPose=3.\n")
  1317. {
  1318. return object->getAiPose();
  1319. }