AIController.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. #include "AIController.h"
  23. #include "T3D/player.h"
  24. IMPLEMENT_CONOBJECT(AIController);
  25. //-----------------------------------------------------------------------------
  26. void AIController::throwCallback(const char* name)
  27. {
  28. Con::executef(mControllerData, name, getIdString()); //controller data callbacks
  29. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  30. if (!gbo) return;
  31. Con::executef(gbo->getDataBlock(), name, getAIInfo()->mObj->getIdString()); //legacy support for object db callbacks
  32. }
  33. void AIController::initPersistFields()
  34. {
  35. addProtectedField("ControllerData", TYPEID< AIControllerData >(), Offset(mControllerData, AIController),
  36. &setControllerDataProperty, &defaultProtectedGetFn,
  37. "Script datablock used for game objects.");
  38. addFieldV("MoveSpeed", TypeRangedF32, Offset(mMovement.mMoveSpeed, AIController), &CommonValidators::PositiveFloat,
  39. "@brief default move sepeed.");
  40. }
  41. bool AIController::setControllerDataProperty(void* obj, const char* index, const char* db)
  42. {
  43. if (db == NULL || !db[0])
  44. {
  45. Con::errorf("AIController::setControllerDataProperty - Can't unset ControllerData on AIController objects");
  46. return false;
  47. }
  48. AIController* object = static_cast<AIController*>(obj);
  49. AIControllerData* data;
  50. if (Sim::findObject(db, data))
  51. {
  52. object->mControllerData = data;
  53. return true;
  54. }
  55. Con::errorf("AIController::setControllerDataProperty - Could not find ControllerData \"%s\"", db);
  56. return false;
  57. }
  58. #ifdef TORQUE_NAVIGATION_ENABLED
  59. bool AIController::getAIMove(Move* movePtr)
  60. {
  61. *movePtr = NullMove;
  62. ShapeBase* sbo = dynamic_cast<ShapeBase*>(getAIInfo()->mObj.getPointer());
  63. if (!sbo) return false;
  64. // Use the eye as the current position.
  65. MatrixF eye;
  66. sbo->getEyeTransform(&eye);
  67. Point3F location = eye.getPosition();
  68. Point3F rotation = sbo->getTransform().toEuler();
  69. #ifdef TORQUE_NAVIGATION_ENABLED
  70. if (sbo->getDamageState() == ShapeBase::Enabled)
  71. {
  72. if (mMovement.mMoveState != ModeStop)
  73. getNav()->updateNavMesh();
  74. if (getGoal() && !getGoal()->mObj.isNull())
  75. {
  76. if (getNav()->mPathData.path.isNull())
  77. {
  78. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  79. getNav()->followObject(getGoal()->mObj, mControllerData->mFollowTolerance);
  80. }
  81. else
  82. {
  83. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  84. getNav()->repath();
  85. if (getGoal()->getDist() < mControllerData->mFollowTolerance)
  86. {
  87. getNav()->clearPath();
  88. mMovement.mMoveState = ModeStop;
  89. throwCallback("onTargetInRange");
  90. }
  91. else if (getGoal()->getDist() < mControllerData->mAttackRadius)
  92. {
  93. throwCallback("onTargetInFiringRange");
  94. }
  95. }
  96. }
  97. }
  98. #endif // TORQUE_NAVIGATION_ENABLED
  99. // Orient towards the aim point, aim object, or towards
  100. // our destination.
  101. if (getAim() || mMovement.mMoveState != ModeStop)
  102. {
  103. // Update the aim position if we're aiming for an object or explicit position
  104. if (getAim())
  105. mMovement.mAimLocation = getAim()->getPosition();
  106. else
  107. mMovement.mAimLocation = getNav()->mMoveDestination;
  108. mControllerData->resolveYaw(this, location, movePtr);
  109. mControllerData->resolvePitch(this, location, movePtr);
  110. mControllerData->resolveRoll(this, location, movePtr);
  111. mControllerData->resolveSpeed(this, location, movePtr);
  112. mControllerData->resolveStuck(this);
  113. }
  114. // Test for target location in sight if it's an object. The LOS is
  115. // run from the eye position to the center of the object's bounding,
  116. // which is not very accurate.
  117. if (getAim() && getAim()->mObj)
  118. {
  119. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  120. if (getAim()->checkInLos(gbo))
  121. {
  122. if (!getAim()->mTargetInLOS)
  123. {
  124. throwCallback("onTargetEnterLOS");
  125. getAim()->mTargetInLOS = true;
  126. }
  127. }
  128. else if (getAim()->mTargetInLOS)
  129. {
  130. throwCallback("onTargetExitLOS");
  131. getAim()->mTargetInLOS = false;
  132. }
  133. }
  134. /*
  135. // Replicate the trigger state into the move so that
  136. // triggers can be controlled from scripts.
  137. for (U32 i = 0; i < MaxTriggerKeys; i++)
  138. movePtr->trigger[i] = getImageTriggerState(i);
  139. */
  140. #ifdef TORQUE_NAVIGATION_ENABLED
  141. if (getNav()->mJump == AINavigation::Now)
  142. {
  143. movePtr->trigger[2] = true;
  144. getNav()->mJump = AINavigation::None;
  145. }
  146. else if (getNav()->mJump == AINavigation::Ledge)
  147. {
  148. // If we're not touching the ground, jump!
  149. RayInfo info;
  150. if (!getAIInfo()->mObj->getContainer()->castRay(getAIInfo()->getPosition(), getAIInfo()->getPosition() - Point3F(0, 0, 0.4f), StaticShapeObjectType, &info))
  151. {
  152. movePtr->trigger[2] = true;
  153. getNav()->mJump = AINavigation::None;
  154. }
  155. }
  156. #endif // TORQUE_NAVIGATION_ENABLED
  157. return true;
  158. }
  159. void AIController::clearCover()
  160. {
  161. // Notify cover that we are no longer on our way.
  162. if (getCover() && !getCover()->mCoverPoint.isNull())
  163. getCover()->mCoverPoint->setOccupied(false);
  164. SAFE_DELETE(mCover);
  165. }
  166. void AIController::Movement::stopMove()
  167. {
  168. mMoveState = ModeStop;
  169. #ifdef TORQUE_NAVIGATION_ENABLED
  170. mControllerRef->getNav()->clearPath();
  171. mControllerRef->clearCover();
  172. mControllerRef->getNav()->clearFollow();
  173. #endif
  174. }
  175. void AIController::Movement::onStuck()
  176. {
  177. mControllerRef->throwCallback("onMoveStuck");
  178. #ifdef TORQUE_NAVIGATION_ENABLED
  179. if (!mControllerRef->getNav()->getPath().isNull())
  180. mControllerRef->getNav()->repath();
  181. #endif
  182. }
  183. DefineEngineMethod(AIController, setMoveSpeed, void, (F32 speed), ,
  184. "@brief Sets the move speed for an AI object.\n\n"
  185. "@param speed A speed multiplier between 0.0 and 1.0. "
  186. "This is multiplied by the AIPlayer's base movement rates (as defined in "
  187. "its PlayerData datablock)\n\n"
  188. "@see getMoveDestination()\n")
  189. {
  190. object->mMovement.setMoveSpeed(speed);
  191. }
  192. DefineEngineMethod(AIController, getMoveSpeed, F32, (), ,
  193. "@brief Gets the move speed of an AI object.\n\n"
  194. "@return A speed multiplier between 0.0 and 1.0.\n\n"
  195. "@see setMoveSpeed()\n")
  196. {
  197. return object->mMovement.getMoveSpeed();
  198. }
  199. DefineEngineMethod(AIController, stop, void, (), ,
  200. "@brief Tells the AIPlayer to stop moving.\n\n")
  201. {
  202. object->mMovement.stopMove();
  203. }
  204. /**
  205. * Set the state of a movement trigger.
  206. *
  207. * @param slot The trigger slot to set
  208. * @param isSet set/unset the trigger
  209. */
  210. void AIController::TriggerState::setMoveTrigger(U32 slot, const bool isSet)
  211. {
  212. if (slot >= MaxTriggerKeys)
  213. {
  214. Con::errorf("Attempting to set an invalid trigger slot (%i)", slot);
  215. }
  216. else
  217. {
  218. mMoveTriggers[slot] = isSet; // set the trigger
  219. mControllerRef->getAIInfo()->mObj->setMaskBits(ShapeBase::NoWarpMask); // force the client to updateMove
  220. }
  221. }
  222. /**
  223. * Get the state of a movement trigger.
  224. *
  225. * @param slot The trigger slot to query
  226. * @return True if the trigger is set, false if it is not set
  227. */
  228. bool AIController::TriggerState::getMoveTrigger(U32 slot) const
  229. {
  230. if (slot >= MaxTriggerKeys)
  231. {
  232. Con::errorf("Attempting to get an invalid trigger slot (%i)", slot);
  233. return false;
  234. }
  235. else
  236. {
  237. return mMoveTriggers[slot];
  238. }
  239. }
  240. /**
  241. * Clear the trigger state for all movement triggers.
  242. */
  243. void AIController::TriggerState::clearMoveTriggers()
  244. {
  245. for (U32 i = 0; i < MaxTriggerKeys; i++)
  246. setMoveTrigger(i, false);
  247. }
  248. //-----------------------------------------------------------------------------
  249. IMPLEMENT_CO_DATABLOCK_V1(AIControllerData);
  250. void AIControllerData::resolveYaw(AIController* obj, Point3F location, Move* move)
  251. {
  252. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  253. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  254. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  255. if (!mIsZero(xDiff) || !mIsZero(yDiff))
  256. {
  257. // First do Yaw
  258. // use the cur yaw between -Pi and Pi
  259. F32 curYaw = rotation.z;
  260. while (curYaw > M_2PI_F)
  261. curYaw -= M_2PI_F;
  262. while (curYaw < -M_2PI_F)
  263. curYaw += M_2PI_F;
  264. // find the yaw offset
  265. F32 newYaw = mAtan2(xDiff, yDiff);
  266. F32 yawDiff = newYaw - curYaw;
  267. // make it between 0 and 2PI
  268. if (yawDiff < 0.0f)
  269. yawDiff += M_2PI_F;
  270. else if (yawDiff >= M_2PI_F)
  271. yawDiff -= M_2PI_F;
  272. // now make sure we take the short way around the circle
  273. if (yawDiff > M_PI_F)
  274. yawDiff -= M_2PI_F;
  275. else if (yawDiff < -M_PI_F)
  276. yawDiff += M_2PI_F;
  277. move->yaw = yawDiff;
  278. }
  279. }
  280. void AIControllerData::resolveRoll(AIController* obj, Point3F location, Move* movePtr)
  281. {
  282. }
  283. void AIControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  284. {
  285. // Move towards the destination
  286. if (obj->mMovement.mMoveState != AIController::ModeStop)
  287. {
  288. F32 xDiff = obj->getNav()->mMoveDestination.x - location.x;
  289. F32 yDiff = obj->getNav()->mMoveDestination.y - location.y;
  290. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  291. // Check if we should mMove, or if we are 'close enough'
  292. if (mFabs(xDiff) < mMoveTolerance && mFabs(yDiff) < mMoveTolerance)
  293. {
  294. obj->mMovement.mMoveState = AIController::ModeStop;
  295. obj->getNav()->onReachDestination();
  296. }
  297. else
  298. {
  299. // Build move direction in world space
  300. if (mIsZero(xDiff))
  301. movePtr->y = (location.y > obj->getNav()->mMoveDestination.y) ? -1.0f : 1.0f;
  302. else
  303. if (mIsZero(yDiff))
  304. movePtr->x = (location.x > obj->getNav()->mMoveDestination.x) ? -1.0f : 1.0f;
  305. else
  306. if (mFabs(xDiff) > mFabs(yDiff))
  307. {
  308. F32 value = mFabs(yDiff / xDiff);
  309. movePtr->y = (location.y > obj->getNav()->mMoveDestination.y) ? -value : value;
  310. movePtr->x = (location.x > obj->getNav()->mMoveDestination.x) ? -1.0f : 1.0f;
  311. }
  312. else
  313. {
  314. F32 value = mFabs(xDiff / yDiff);
  315. movePtr->x = (location.x > obj->getNav()->mMoveDestination.x) ? -value : value;
  316. movePtr->y = (location.y > obj->getNav()->mMoveDestination.y) ? -1.0f : 1.0f;
  317. }
  318. // Rotate the move into object space (this really only needs
  319. // a 2D matrix)
  320. Point3F newMove;
  321. MatrixF moveMatrix;
  322. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  323. moveMatrix.mulV(Point3F(movePtr->x, movePtr->y, 0.0f), &newMove);
  324. movePtr->x = newMove.x;
  325. movePtr->y = newMove.y;
  326. // Set movement speed. We'll slow down once we get close
  327. // to try and stop on the spot...
  328. if (obj->mMovement.mMoveSlowdown)
  329. {
  330. F32 speed = obj->mMovement.mMoveSpeed;
  331. F32 dist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  332. F32 maxDist = mMoveTolerance * 2;
  333. if (dist < maxDist)
  334. speed *= dist / maxDist;
  335. movePtr->x *= speed;
  336. movePtr->y *= speed;
  337. obj->mMovement.mMoveState = AIController::ModeSlowing;
  338. }
  339. else
  340. {
  341. movePtr->x *= obj->mMovement.mMoveSpeed;
  342. movePtr->y *= obj->mMovement.mMoveSpeed;
  343. obj->mMovement.mMoveState = AIController::ModeMove;
  344. }
  345. }
  346. }
  347. }
  348. void AIControllerData::resolveStuck(AIController* obj)
  349. {
  350. if (obj->mMovement.mMoveState == AIController::ModeStop) return;
  351. ShapeBase* sbo = dynamic_cast<ShapeBase*>(obj->getAIInfo()->mObj.getPointer());
  352. // Don't check for ai stuckness if animation during
  353. // an anim-clip effect override.
  354. if (sbo->getDamageState() == ShapeBase::Enabled && !(sbo->anim_clip_flags & ShapeBase::ANIM_OVERRIDDEN) && !sbo->isAnimationLocked()) {
  355. if (obj->mMovement.mMoveStuckTestCountdown > 0)
  356. --obj->mMovement.mMoveStuckTestCountdown;
  357. else
  358. {
  359. // We should check to see if we are stuck...
  360. F32 locationDelta = (obj->getAIInfo()->getPosition() - obj->getAIInfo()->mLastPos).len();
  361. if (locationDelta < mMoveStuckTolerance && (sbo->getDamageState() == ShapeBase::Enabled))
  362. {
  363. // If we are slowing down, then it's likely that our location delta will be less than
  364. // our move stuck tolerance. Because we can be both slowing and stuck
  365. // we should TRY to check if we've moved. This could use better detection.
  366. if (obj->mMovement.mMoveState != AIController::ModeSlowing || locationDelta == 0)
  367. {
  368. obj->mMovement.mMoveState = AIController::ModeStuck;
  369. obj->mMovement.onStuck();
  370. obj->throwCallback("onStuck");
  371. }
  372. }
  373. }
  374. obj->getAIInfo()->mLastPos = obj->getAIInfo()->getPosition();
  375. }
  376. }
  377. void AIControllerData::initPersistFields()
  378. {
  379. docsURL;
  380. addGroup("AI");
  381. addFieldV("moveTolerance", TypeRangedF32, Offset(mMoveTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  382. "@brief Distance from destination before stopping.\n\n"
  383. "When the AIPlayer is moving to a given destination it will move to within "
  384. "this distance of the destination and then stop. By providing this tolerance "
  385. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  386. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  387. addFieldV("followTolerance", TypeRangedF32, Offset(mFollowTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  388. "@brief Distance from destination before stopping.\n\n"
  389. "When the AIPlayer is moving to a given destination it will move to within "
  390. "this distance of the destination and then stop. By providing this tolerance "
  391. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  392. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  393. addFieldV("moveStuckTolerance", TypeRangedF32, Offset(mMoveStuckTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  394. "@brief Distance tolerance on stuck check.\n\n"
  395. "When the AIPlayer is moving to a given destination, if it ever moves less than "
  396. "this tolerance during a single tick, the AIPlayer is considered stuck. At this point "
  397. "the onMoveStuck() callback is called on the datablock.\n");
  398. addFieldV("moveStuckTestDelay", TypeRangedS32, Offset(mMoveStuckTestDelay, AIControllerData), &CommonValidators::PositiveInt,
  399. "@brief The number of ticks to wait before testing if the AIPlayer is stuck.\n\n"
  400. "When the AIPlayer is asked to move, this property is the number of ticks to wait "
  401. "before the AIPlayer starts to check if it is stuck. This delay allows the AIPlayer "
  402. "to accelerate to full speed without its initial slow start being considered as stuck.\n"
  403. "@note Set to zero to have the stuck test start immediately.\n");
  404. addFieldV("AttackRadius", TypeRangedF32, Offset(mAttackRadius, AIControllerData), &CommonValidators::PositiveFloat,
  405. "@brief Distance considered in firing range for callback purposes.");
  406. endGroup("AI");
  407. #ifdef TORQUE_NAVIGATION_ENABLED
  408. addGroup("Pathfinding");
  409. addField("allowWalk", TypeBool, Offset(mLinkTypes.walk, AIControllerData),
  410. "Allow the character to walk on dry land.");
  411. addField("allowJump", TypeBool, Offset(mLinkTypes.jump, AIControllerData),
  412. "Allow the character to use jump links.");
  413. addField("allowDrop", TypeBool, Offset(mLinkTypes.drop, AIControllerData),
  414. "Allow the character to use drop links.");
  415. addField("allowSwim", TypeBool, Offset(mLinkTypes.swim, AIControllerData),
  416. "Allow the character to move in water.");
  417. addField("allowLedge", TypeBool, Offset(mLinkTypes.ledge, AIControllerData),
  418. "Allow the character to jump ledges.");
  419. addField("allowClimb", TypeBool, Offset(mLinkTypes.climb, AIControllerData),
  420. "Allow the character to use climb links.");
  421. addField("allowTeleport", TypeBool, Offset(mLinkTypes.teleport, AIControllerData),
  422. "Allow the character to use teleporters.");
  423. endGroup("Pathfinding");
  424. #endif // TORQUE_NAVIGATION_ENABLED
  425. Parent::initPersistFields();
  426. }
  427. //-----------------------------------------------------------------------------
  428. //-----------------------------------------------------------------------------
  429. IMPLEMENT_CO_DATABLOCK_V1(AIPlayerControllerData);
  430. void AIPlayerControllerData::resolvePitch(AIController* obj, Point3F location, Move* movePtr)
  431. {
  432. Player* po = dynamic_cast<Player*>(obj->getAIInfo()->mObj.getPointer());
  433. if (!po) return;//not a player
  434. if (obj->getAim()->mObj || obj->getAim()->mPosSet || obj->mMovement.mMoveState != AIController::ModeStop)
  435. {
  436. // Next do pitch.
  437. if (!obj->getAim()->mObj && !obj->getAim()->mPosSet)
  438. {
  439. // Level out if were just looking at our next way point.
  440. Point3F headRotation = po->getHeadRotation();
  441. movePtr->pitch = -headRotation.x;
  442. }
  443. else
  444. {
  445. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  446. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  447. // This should be adjusted to run from the
  448. // eye point to the object's center position. Though this
  449. // works well enough for now.
  450. F32 vertDist = obj->mMovement.mAimLocation.z - location.z;
  451. F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  452. F32 newPitch = mAtan2(horzDist, vertDist) - (M_PI_F / 2.0f);
  453. if (mFabs(newPitch) > 0.01f)
  454. {
  455. Point3F headRotation = po->getHeadRotation();
  456. movePtr->pitch = newPitch - headRotation.x;
  457. }
  458. }
  459. }
  460. else
  461. {
  462. // Level out if we're not doing anything else
  463. Point3F headRotation = po->getHeadRotation();
  464. movePtr->pitch = -headRotation.x;
  465. }
  466. }
  467. #endif //_AICONTROLLER_H_