AIController.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  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. #include "T3D/rigidShape.h"
  25. #include "T3D/vehicles/wheeledVehicle.h"
  26. #include "T3D/vehicles/flyingVehicle.h"
  27. IMPLEMENT_CONOBJECT(AIController);
  28. //-----------------------------------------------------------------------------
  29. void AIController::throwCallback(const char* name)
  30. {
  31. //Con::warnf("throwCallback: %s", name);
  32. Con::executef(mControllerData, name, getIdString()); //controller data callbacks
  33. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  34. if (!gbo) return;
  35. Con::executef(gbo->getDataBlock(), name, getAIInfo()->mObj->getIdString()); //legacy support for object db callbacks
  36. }
  37. void AIController::initPersistFields()
  38. {
  39. addProtectedField("ControllerData", TYPEID< AIControllerData >(), Offset(mControllerData, AIController),
  40. &setControllerDataProperty, &defaultProtectedGetFn,
  41. "Script datablock used for game objects.");
  42. addFieldV("MoveSpeed", TypeRangedF32, Offset(mMovement.mMoveSpeed, AIController), &CommonValidators::PositiveFloat,
  43. "@brief default move sepeed.");
  44. }
  45. bool AIController::setControllerDataProperty(void* obj, const char* index, const char* db)
  46. {
  47. if (db == NULL || !db[0])
  48. {
  49. Con::errorf("AIController::setControllerDataProperty - Can't unset ControllerData on AIController objects");
  50. return false;
  51. }
  52. AIController* object = static_cast<AIController*>(obj);
  53. AIControllerData* data;
  54. if (Sim::findObject(db, data))
  55. {
  56. object->mControllerData = data;
  57. return true;
  58. }
  59. Con::errorf("AIController::setControllerDataProperty - Could not find ControllerData \"%s\"", db);
  60. return false;
  61. }
  62. void AIController::setGoal(AIInfo* targ)
  63. {
  64. if (mGoal) { delete(mGoal); mGoal = NULL; }
  65. if (targ->mObj.isValid())
  66. {
  67. delete(mGoal);
  68. mGoal = new AIGoal(this, targ->mObj, targ->mRadius);
  69. }
  70. else if (targ->mPosSet)
  71. {
  72. delete(mGoal);
  73. mGoal = new AIGoal(this, targ->mPosition, targ->mRadius);
  74. }
  75. }
  76. void AIController::setGoal(Point3F loc, F32 rad)
  77. {
  78. if (mGoal) delete(mGoal);
  79. mGoal = new AIGoal(this, loc, rad);
  80. }
  81. void AIController::setGoal(SimObjectPtr<SceneObject> objIn, F32 rad)
  82. {
  83. if (mGoal) delete(mGoal);
  84. mGoal = new AIGoal(this, objIn, rad);
  85. }
  86. void AIController::setAim(Point3F loc, F32 rad, Point3F offset)
  87. {
  88. if (mAimTarget) delete(mAimTarget);
  89. mAimTarget = new AIAimTarget(this, loc, rad);
  90. mAimTarget->mAimOffset = offset;
  91. }
  92. void AIController::setAim(SimObjectPtr<SceneObject> objIn, F32 rad, Point3F offset)
  93. {
  94. if (mAimTarget) delete(mAimTarget);
  95. mAimTarget = new AIAimTarget(this, objIn, rad);
  96. mAimTarget->mAimOffset = offset;
  97. }
  98. bool AIController::getAIMove(Move* movePtr)
  99. {
  100. *movePtr = NullMove;
  101. ShapeBase* sbo = dynamic_cast<ShapeBase*>(getAIInfo()->mObj.getPointer());
  102. if (!sbo) return false;
  103. // Use the eye as the current position.
  104. MatrixF eye;
  105. sbo->getEyeTransform(&eye);
  106. Point3F location = eye.getPosition();
  107. Point3F rotation = sbo->getTransform().toEuler();
  108. // Test for target location in sight if it's an object. The LOS is
  109. // run from the eye position to the center of the object's bounding,
  110. // which is not very accurate.
  111. if (getAim() && getAim()->mObj)
  112. {
  113. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  114. if (getAim()->checkInLos(gbo))
  115. {
  116. if (!getAim()->mTargetInLOS)
  117. {
  118. throwCallback("onTargetEnterLOS");
  119. getAim()->mTargetInLOS = true;
  120. }
  121. }
  122. else if (getAim()->mTargetInLOS)
  123. {
  124. throwCallback("onTargetExitLOS");
  125. getAim()->mTargetInLOS = false;
  126. }
  127. }
  128. if (sbo->getDamageState() == ShapeBase::Enabled && getGoal())
  129. {
  130. #ifdef TORQUE_NAVIGATION_ENABLED
  131. if (mMovement.mMoveState != ModeStop)
  132. getNav()->updateNavMesh();
  133. if (getNav()->mPathData.path.isNull())
  134. {
  135. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  136. {
  137. if (getGoal()->mObj.isValid())
  138. getNav()->followObject(getGoal()->mObj, mControllerData->mFollowTolerance);
  139. else if (getGoal()->mPosSet)
  140. getNav()->setPathDestination(getGoal()->getPosition(true));
  141. }
  142. }
  143. else
  144. {
  145. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  146. {
  147. SceneObject* obj = getAIInfo()->mObj->getObjectMount();
  148. if (!obj)
  149. {
  150. obj = getAIInfo()->mObj;
  151. }
  152. RayInfo info;
  153. if (obj->getContainer()->castRay(obj->getPosition(), obj->getPosition() - Point3F(0, 0, mControllerData->mHeightTolerance), StaticShapeObjectType, &info))
  154. {
  155. getNav()->repath();
  156. }
  157. getGoal()->mInRange = false;
  158. }
  159. if (getGoal()->getDist() < mControllerData->mFollowTolerance )
  160. {
  161. getNav()->clearPath();
  162. mMovement.mMoveState = ModeStop;
  163. if (!getGoal()->mInRange)
  164. {
  165. getGoal()->mInRange = true;
  166. throwCallback("onTargetInRange");
  167. }
  168. else getGoal()->mInRange = false;
  169. }
  170. else
  171. {
  172. if (getGoal()->getDist() < mControllerData->mAttackRadius )
  173. {
  174. if (!getGoal()->mInFiringRange)
  175. {
  176. getGoal()->mInFiringRange = true;
  177. throwCallback("onTargetInFiringRange");
  178. }
  179. }
  180. else getGoal()->mInFiringRange = false;
  181. }
  182. }
  183. #else
  184. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  185. {
  186. if (getGoal()->mObj.isValid())
  187. getNav()->followObject(getGoal()->mObj, mControllerData->mFollowTolerance);
  188. else if (getGoal()->mPosSet)
  189. getNav()->setPathDestination(getGoal()->getPosition(true));
  190. getGoal()->mInRange = false;
  191. }
  192. if (getGoal()->getDist() < mControllerData->mFollowTolerance)
  193. {
  194. mMovement.mMoveState = ModeStop;
  195. if (!getGoal()->mInRange)
  196. {
  197. getGoal()->mInRange = true;
  198. throwCallback("onTargetInRange");
  199. }
  200. else getGoal()->mInRange = false;
  201. }
  202. else
  203. {
  204. if (getGoal()->getDist() < mControllerData->mAttackRadius)
  205. {
  206. if (!getGoal()->mInFiringRange)
  207. {
  208. getGoal()->mInFiringRange = true;
  209. throwCallback("onTargetInFiringRange");
  210. }
  211. }
  212. else getGoal()->mInFiringRange = false;
  213. }
  214. #endif // TORQUE_NAVIGATION_ENABLED
  215. }
  216. // Orient towards the aim point, aim object, or towards
  217. // our destination.
  218. if (getAim() || mMovement.mMoveState != ModeStop)
  219. {
  220. // Update the aim position if we're aiming for an object or explicit position
  221. if (getAim())
  222. mMovement.mAimLocation = getAim()->getPosition();
  223. else
  224. mMovement.mAimLocation = getNav()->getMoveDestination();
  225. mControllerData->resolveYawPtr(this, location, movePtr);
  226. mControllerData->resolvePitchPtr(this, location, movePtr);
  227. mControllerData->resolveRollPtr(this, location, movePtr);
  228. if (mMovement.mMoveState != AIController::ModeStop)
  229. {
  230. F32 xDiff = getNav()->getMoveDestination().x - location.x;
  231. F32 yDiff = getNav()->getMoveDestination().y - location.y;
  232. if (mFabs(xDiff) < mControllerData->mMoveTolerance && mFabs(yDiff) < mControllerData->mMoveTolerance)
  233. {
  234. getNav()->onReachDestination();
  235. }
  236. else
  237. {
  238. mControllerData->resolveSpeedPtr(this, location, movePtr);
  239. mControllerData->resolveStuckPtr(this);
  240. }
  241. }
  242. }
  243. mControllerData->resolveTriggerStatePtr(this, movePtr);
  244. getAIInfo()->mLastPos = getAIInfo()->getPosition();
  245. return true;
  246. }
  247. void AIController::clearCover()
  248. {
  249. // Notify cover that we are no longer on our way.
  250. if (getCover() && !getCover()->mCoverPoint.isNull())
  251. getCover()->mCoverPoint->setOccupied(false);
  252. SAFE_DELETE(mCover);
  253. }
  254. void AIController::Movement::stopMove()
  255. {
  256. mMoveState = ModeStop;
  257. #ifdef TORQUE_NAVIGATION_ENABLED
  258. getCtrl()->getNav()->clearPath();
  259. getCtrl()->clearCover();
  260. getCtrl()->getNav()->clearFollow();
  261. #endif
  262. }
  263. void AIController::Movement::onStuck()
  264. {
  265. mMoveState = AIController::ModeStuck;
  266. getCtrl()->throwCallback("onMoveStuck");
  267. #ifdef TORQUE_NAVIGATION_ENABLED
  268. if (!getCtrl()->getNav()->getPath().isNull())
  269. getCtrl()->getNav()->repath();
  270. #endif
  271. }
  272. DefineEngineMethod(AIController, setMoveSpeed, void, (F32 speed), ,
  273. "@brief Sets the move speed for an AI object.\n\n"
  274. "@param speed A speed multiplier between 0.0 and 1.0. "
  275. "This is multiplied by the AIController controlled object's base movement rates (as defined in "
  276. "its PlayerData datablock)\n\n"
  277. "@see getMoveDestination()\n")
  278. {
  279. object->mMovement.setMoveSpeed(speed);
  280. }
  281. DefineEngineMethod(AIController, getMoveSpeed, F32, (), ,
  282. "@brief Gets the move speed of an AI object.\n\n"
  283. "@return A speed multiplier between 0.0 and 1.0.\n\n"
  284. "@see setMoveSpeed()\n")
  285. {
  286. return object->mMovement.getMoveSpeed();
  287. }
  288. DefineEngineMethod(AIController, stop, void, (), ,
  289. "@brief Tells the AIController controlled object to stop moving.\n\n")
  290. {
  291. object->mMovement.stopMove();
  292. }
  293. /**
  294. * Set the state of a movement trigger.
  295. *
  296. * @param slot The trigger slot to set
  297. * @param isSet set/unset the trigger
  298. */
  299. void AIController::TriggerState::setMoveTrigger(U32 slot, const bool isSet)
  300. {
  301. if (slot >= MaxTriggerKeys)
  302. {
  303. Con::errorf("Attempting to set an invalid trigger slot (%i)", slot);
  304. }
  305. else
  306. {
  307. mMoveTriggers[slot] = isSet; // set the trigger
  308. mControllerRef->getAIInfo()->mObj->setMaskBits(ShapeBase::NoWarpMask); // force the client to updateMove
  309. }
  310. }
  311. /**
  312. * Get the state of a movement trigger.
  313. *
  314. * @param slot The trigger slot to query
  315. * @return True if the trigger is set, false if it is not set
  316. */
  317. bool AIController::TriggerState::getMoveTrigger(U32 slot) const
  318. {
  319. if (slot >= MaxTriggerKeys)
  320. {
  321. Con::errorf("Attempting to get an invalid trigger slot (%i)", slot);
  322. return false;
  323. }
  324. else
  325. {
  326. return mMoveTriggers[slot];
  327. }
  328. }
  329. /**
  330. * Clear the trigger state for all movement triggers.
  331. */
  332. void AIController::TriggerState::clearMoveTriggers()
  333. {
  334. for (U32 i = 0; i < MaxTriggerKeys; i++)
  335. setMoveTrigger(i, false);
  336. }
  337. //-----------------------------------------------------------------------------
  338. IMPLEMENT_CO_DATABLOCK_V1(AIControllerData);
  339. void AIControllerData::resolveYaw(AIController* obj, Point3F location, Move* move)
  340. {
  341. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  342. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  343. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  344. if (!mIsZero(xDiff) || !mIsZero(yDiff))
  345. {
  346. // First do Yaw
  347. // use the cur yaw between -Pi and Pi
  348. F32 curYaw = rotation.z;
  349. while (curYaw > M_2PI_F)
  350. curYaw -= M_2PI_F;
  351. while (curYaw < -M_2PI_F)
  352. curYaw += M_2PI_F;
  353. // find the yaw offset
  354. F32 newYaw = mAtan2(xDiff, yDiff);
  355. F32 yawDiff = newYaw - curYaw;
  356. // make it between 0 and 2PI
  357. if (yawDiff < 0.0f)
  358. yawDiff += M_2PI_F;
  359. else if (yawDiff >= M_2PI_F)
  360. yawDiff -= M_2PI_F;
  361. // now make sure we take the short way around the circle
  362. if (yawDiff > M_PI_F)
  363. yawDiff -= M_2PI_F;
  364. else if (yawDiff < -M_PI_F)
  365. yawDiff += M_2PI_F;
  366. move->yaw = yawDiff;
  367. }
  368. }
  369. void AIControllerData::resolveRoll(AIController* obj, Point3F location, Move* movePtr)
  370. {
  371. }
  372. void AIControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  373. {
  374. F32 xDiff = obj->getNav()->getMoveDestination().x - location.x;
  375. F32 yDiff = obj->getNav()->getMoveDestination().y - location.y;
  376. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  377. // Build move direction in world space
  378. if (mIsZero(xDiff))
  379. movePtr->y = (location.y > obj->getNav()->getMoveDestination().y) ? -1.0f : 1.0f;
  380. else
  381. {
  382. if (mIsZero(yDiff))
  383. movePtr->x = (location.x > obj->getNav()->getMoveDestination().x) ? -1.0f : 1.0f;
  384. else
  385. {
  386. if (mFabs(xDiff) > mFabs(yDiff))
  387. {
  388. F32 value = mFabs(yDiff / xDiff);
  389. movePtr->y = (location.y > obj->getNav()->getMoveDestination().y) ? -value : value;
  390. movePtr->x = (location.x > obj->getNav()->getMoveDestination().x) ? -1.0f : 1.0f;
  391. }
  392. else
  393. {
  394. F32 value = mFabs(xDiff / yDiff);
  395. movePtr->x = (location.x > obj->getNav()->getMoveDestination().x) ? -value : value;
  396. movePtr->y = (location.y > obj->getNav()->getMoveDestination().y) ? -1.0f : 1.0f;
  397. }
  398. }
  399. }
  400. // Rotate the move into object space (this really only needs
  401. // a 2D matrix)
  402. Point3F newMove;
  403. MatrixF moveMatrix;
  404. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  405. moveMatrix.mulV(Point3F(movePtr->x, movePtr->y, 0.0f), &newMove);
  406. movePtr->x = newMove.x;
  407. movePtr->y = newMove.y;
  408. // Set movement speed. We'll slow down once we get close
  409. // to try and stop on the spot...
  410. if (obj->mMovement.mMoveSlowdown)
  411. {
  412. F32 speed = obj->mMovement.mMoveSpeed;
  413. F32 dist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  414. F32 maxDist = mMoveTolerance * 2;
  415. if (dist < maxDist)
  416. speed *= dist / maxDist;
  417. movePtr->x *= speed;
  418. movePtr->y *= speed;
  419. }
  420. else
  421. {
  422. movePtr->x *= obj->mMovement.mMoveSpeed;
  423. movePtr->y *= obj->mMovement.mMoveSpeed;
  424. }
  425. }
  426. void AIControllerData::resolveTriggerState(AIController* obj, Move* movePtr)
  427. {
  428. //check for scripted overides
  429. for (U32 slot = 0; slot < MaxTriggerKeys; slot++)
  430. {
  431. movePtr->trigger[slot] = obj->mTriggerState.mMoveTriggers[slot];
  432. }
  433. }
  434. void AIControllerData::resolveStuck(AIController* obj)
  435. {
  436. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  437. if (!obj->getGoal()) return;
  438. ShapeBase* sbo = dynamic_cast<ShapeBase*>(obj->getAIInfo()->mObj.getPointer());
  439. // Don't check for ai stuckness if animation during
  440. // an anim-clip effect override.
  441. if (sbo->getDamageState() == ShapeBase::Enabled && !(sbo->anim_clip_flags & ShapeBase::ANIM_OVERRIDDEN) && !sbo->isAnimationLocked())
  442. {
  443. // We should check to see if we are stuck...
  444. F32 locationDelta = (obj->getAIInfo()->getPosition() - obj->getAIInfo()->mLastPos).len();
  445. if (locationDelta < mMoveStuckTolerance)
  446. {
  447. if (obj->mMovement.mMoveStuckTestCountdown > 0)
  448. --obj->mMovement.mMoveStuckTestCountdown;
  449. else
  450. {
  451. // If we are slowing down, then it's likely that our location delta will be less than
  452. // our move stuck tolerance. Because we can be both slowing and stuck
  453. // we should TRY to check if we've moved. This could use better detection.
  454. if (obj->mMovement.mMoveState != AIController::ModeSlowing || locationDelta == 0)
  455. {
  456. obj->mMovement.onStuck();
  457. obj->mMovement.mMoveStuckTestCountdown = obj->mControllerData->mMoveStuckTestDelay;
  458. }
  459. }
  460. }
  461. }
  462. }
  463. AIControllerData::AIControllerData()
  464. {
  465. mMoveTolerance = 0.25f;
  466. mAttackRadius = 2.0f;
  467. mMoveStuckTolerance = 0.01f;
  468. mMoveStuckTestDelay = 30;
  469. mHeightTolerance = 0.001f;
  470. mFollowTolerance = 1.0f;
  471. #ifdef TORQUE_NAVIGATION_ENABLED
  472. mLinkTypes = LinkData(AllFlags);
  473. mNavSize = AINavigation::Regular;
  474. mFlocking.mChance = 90;
  475. mFlocking.mMin = 1.0f;
  476. mFlocking.mMax = 3.0f;
  477. mFlocking.mSideStep = 0.01f;
  478. #endif
  479. resolveYawPtr.bind(this, &AIControllerData::resolveYaw);
  480. resolvePitchPtr.bind(this, &AIControllerData::resolvePitch);
  481. resolveRollPtr.bind(this, &AIControllerData::resolveRoll);
  482. resolveSpeedPtr.bind(this, &AIControllerData::resolveSpeed);
  483. resolveTriggerStatePtr.bind(this, &AIControllerData::resolveTriggerState);
  484. resolveStuckPtr.bind(this, &AIControllerData::resolveStuck);
  485. }
  486. AIControllerData::AIControllerData(const AIControllerData& other, bool temp_clone) : SimDataBlock(other, temp_clone)
  487. {
  488. mMoveTolerance = other.mMoveTolerance;
  489. mAttackRadius = other.mAttackRadius;
  490. mMoveStuckTolerance = other.mMoveStuckTolerance;
  491. mMoveStuckTestDelay = other.mMoveStuckTestDelay;
  492. mHeightTolerance = other.mHeightTolerance;
  493. mFollowTolerance = other.mFollowTolerance;
  494. #ifdef TORQUE_NAVIGATION_ENABLED
  495. mLinkTypes = other.mLinkTypes;
  496. mNavSize = other.mNavSize;
  497. mFlocking.mChance = other.mFlocking.mChance;
  498. mFlocking.mMin = other.mFlocking.mMin;
  499. mFlocking.mMax = other.mFlocking.mMax;
  500. mFlocking.mSideStep = other.mFlocking.mSideStep;
  501. #endif
  502. resolveYawPtr.bind(this, &AIControllerData::resolveYaw);
  503. resolvePitchPtr.bind(this, &AIControllerData::resolvePitch);
  504. resolveRollPtr.bind(this, &AIControllerData::resolveRoll);
  505. resolveSpeedPtr.bind(this, &AIControllerData::resolveSpeed);
  506. resolveTriggerStatePtr.bind(this, &AIControllerData::resolveTriggerState);
  507. resolveStuckPtr.bind(this, &AIControllerData::resolveStuck);
  508. }
  509. void AIControllerData::initPersistFields()
  510. {
  511. docsURL;
  512. addGroup("AI");
  513. addFieldV("moveTolerance", TypeRangedF32, Offset(mMoveTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  514. "@brief Distance from destination before stopping.\n\n"
  515. "When the AIController controlled object is moving to a given destination it will move to within "
  516. "this distance of the destination and then stop. By providing this tolerance "
  517. "it helps the AIController controlled object from never reaching its destination due to minor obstacles, "
  518. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  519. addFieldV("followTolerance", TypeRangedF32, Offset(mFollowTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  520. "@brief Distance from destination before stopping.\n\n"
  521. "When the AIController controlled object is moving to a given destination it will move to within "
  522. "this distance of the destination and then stop. By providing this tolerance "
  523. "it helps the AIController controlled object from never reaching its destination due to minor obstacles, "
  524. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  525. addFieldV("AttackRadius", TypeRangedF32, Offset(mAttackRadius, AIControllerData), &CommonValidators::PositiveFloat,
  526. "@brief Distance considered in firing range for callback purposes.");
  527. addFieldV("moveStuckTolerance", TypeRangedF32, Offset(mMoveStuckTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  528. "@brief Distance tolerance on stuck check.\n\n"
  529. "When the AIController controlled object controlled object is moving to a given destination, if it ever moves less than "
  530. "this tolerance during a single tick, the AIController controlled object is considered stuck. At this point "
  531. "the onMoveStuck() callback is called on the datablock.\n");
  532. addFieldV("HeightTolerance", TypeRangedF32, Offset(mHeightTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  533. "@brief Distance from destination before stopping.\n\n"
  534. "When the AIController controlled object is moving to a given destination it will move to within "
  535. "this distance of the destination and then stop. By providing this tolerance "
  536. "it helps the AIController controlled object from never reaching its destination due to minor obstacles, "
  537. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  538. addFieldV("moveStuckTestDelay", TypeRangedS32, Offset(mMoveStuckTestDelay, AIControllerData), &CommonValidators::PositiveInt,
  539. "@brief The number of ticks to wait before testing if the AIController controlled object is stuck.\n\n"
  540. "When the AIController controlled object is asked to move, this property is the number of ticks to wait "
  541. "before the AIController controlled object starts to check if it is stuck. This delay allows the AIController controlled object "
  542. "to accelerate to full speed without its initial slow start being considered as stuck.\n"
  543. "@note Set to zero to have the stuck test start immediately.\n");
  544. endGroup("AI");
  545. #ifdef TORQUE_NAVIGATION_ENABLED
  546. addGroup("Pathfinding");
  547. addFieldV("FlockChance", TypeRangedS32, Offset(mFlocking.mChance, AIControllerData), &CommonValidators::S32Percent,
  548. "@brief chance of flocking.");
  549. addFieldV("FlockMin", TypeRangedF32, Offset(mFlocking.mMin, AIControllerData), &CommonValidators::PositiveFloat,
  550. "@brief min flocking separation distance.");
  551. addFieldV("FlockMax", TypeRangedF32, Offset(mFlocking.mMax, AIControllerData), &CommonValidators::PositiveFloat,
  552. "@brief max flocking clustering distance.");
  553. addFieldV("FlockSideStep", TypeRangedF32, Offset(mFlocking.mSideStep, AIControllerData), &CommonValidators::PositiveFloat,
  554. "@brief Distance from destination before we stop moving out of the way.");
  555. addField("allowWalk", TypeBool, Offset(mLinkTypes.walk, AIControllerData),
  556. "Allow the character to walk on dry land.");
  557. addField("allowJump", TypeBool, Offset(mLinkTypes.jump, AIControllerData),
  558. "Allow the character to use jump links.");
  559. addField("allowDrop", TypeBool, Offset(mLinkTypes.drop, AIControllerData),
  560. "Allow the character to use drop links.");
  561. addField("allowSwim", TypeBool, Offset(mLinkTypes.swim, AIControllerData),
  562. "Allow the character to move in water.");
  563. addField("allowLedge", TypeBool, Offset(mLinkTypes.ledge, AIControllerData),
  564. "Allow the character to jump ledges.");
  565. addField("allowClimb", TypeBool, Offset(mLinkTypes.climb, AIControllerData),
  566. "Allow the character to use climb links.");
  567. addField("allowTeleport", TypeBool, Offset(mLinkTypes.teleport, AIControllerData),
  568. "Allow the character to use teleporters.");
  569. endGroup("Pathfinding");
  570. #endif // TORQUE_NAVIGATION_ENABLED
  571. Parent::initPersistFields();
  572. }
  573. void AIControllerData::packData(BitStream* stream)
  574. {
  575. Parent::packData(stream);
  576. stream->write(mMoveTolerance);
  577. stream->write(mAttackRadius);
  578. stream->write(mMoveStuckTolerance);
  579. stream->write(mMoveStuckTestDelay);
  580. stream->write(mHeightTolerance);
  581. stream->write(mFollowTolerance);
  582. #ifdef TORQUE_NAVIGATION_ENABLED
  583. //enums
  584. stream->write(mLinkTypes.getFlags());
  585. stream->write((U32)mNavSize);
  586. // end enums
  587. stream->write(mFlocking.mChance);
  588. stream->write(mFlocking.mMin);
  589. stream->write(mFlocking.mMax);
  590. stream->write(mFlocking.mSideStep);
  591. #endif // TORQUE_NAVIGATION_ENABLED
  592. };
  593. void AIControllerData::unpackData(BitStream* stream)
  594. {
  595. Parent::unpackData(stream);
  596. stream->read(&mMoveTolerance);
  597. stream->read(&mAttackRadius);
  598. stream->read(&mMoveStuckTolerance);
  599. stream->read(&mMoveStuckTestDelay);
  600. stream->read(&mHeightTolerance);
  601. stream->read(&mFollowTolerance);
  602. #ifdef TORQUE_NAVIGATION_ENABLED
  603. //enums
  604. U16 linkFlags;
  605. stream->read(&linkFlags);
  606. mLinkTypes = LinkData(linkFlags);
  607. U32 navSize;
  608. stream->read(&navSize);
  609. mNavSize = (AINavigation::NavSize)(navSize);
  610. // end enums
  611. stream->read(&(mFlocking.mChance));
  612. stream->read(&(mFlocking.mMin));
  613. stream->read(&(mFlocking.mMax));
  614. stream->read(&(mFlocking.mSideStep));
  615. #endif // TORQUE_NAVIGATION_ENABLED
  616. };
  617. //-----------------------------------------------------------------------------
  618. //-----------------------------------------------------------------------------
  619. IMPLEMENT_CO_DATABLOCK_V1(AIPlayerControllerData);
  620. void AIPlayerControllerData::resolvePitch(AIController* obj, Point3F location, Move* movePtr)
  621. {
  622. Player* po = dynamic_cast<Player*>(obj->getAIInfo()->mObj.getPointer());
  623. if (!po) return;//not a player
  624. if (obj->getAim() || obj->mMovement.mMoveState != AIController::ModeStop)
  625. {
  626. // Next do pitch.
  627. if (!obj->getAim())
  628. {
  629. // Level out if were just looking at our next way point.
  630. Point3F headRotation = po->getHeadRotation();
  631. movePtr->pitch = -headRotation.x;
  632. }
  633. else
  634. {
  635. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  636. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  637. // This should be adjusted to run from the
  638. // eye point to the object's center position. Though this
  639. // works well enough for now.
  640. F32 vertDist = obj->mMovement.mAimLocation.z - location.z;
  641. F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  642. F32 newPitch = mAtan2(horzDist, vertDist) - (M_PI_F / 2.0f);
  643. if (mFabs(newPitch) > 0.01f)
  644. {
  645. Point3F headRotation = po->getHeadRotation();
  646. movePtr->pitch = newPitch - headRotation.x;
  647. }
  648. }
  649. }
  650. else
  651. {
  652. // Level out if we're not doing anything else
  653. Point3F headRotation = po->getHeadRotation();
  654. movePtr->pitch = -headRotation.x;
  655. }
  656. }
  657. void AIPlayerControllerData::resolveTriggerState(AIController* obj, Move* movePtr)
  658. {
  659. Parent::resolveTriggerState(obj, movePtr);
  660. #ifdef TORQUE_NAVIGATION_ENABLED
  661. if (obj->getNav()->mJump == AINavigation::Now)
  662. {
  663. movePtr->trigger[2] = true;
  664. obj->getNav()->mJump = AINavigation::None;
  665. }
  666. else if (obj->getNav()->mJump == AINavigation::Ledge)
  667. {
  668. // If we're not touching the ground, jump!
  669. RayInfo info;
  670. if (!obj->getAIInfo()->mObj->getContainer()->castRay(obj->getAIInfo()->getPosition(), obj->getAIInfo()->getPosition() - Point3F(0, 0, 0.4f), StaticShapeObjectType, &info))
  671. {
  672. movePtr->trigger[2] = true;
  673. obj->getNav()->mJump = AINavigation::None;
  674. }
  675. }
  676. #endif // TORQUE_NAVIGATION_ENABLED
  677. }
  678. //-----------------------------------------------------------------------------
  679. //-----------------------------------------------------------------------------
  680. IMPLEMENT_CO_DATABLOCK_V1(AIWheeledVehicleControllerData);
  681. void AIWheeledVehicleControllerData::resolveYaw(AIController* obj, Point3F location, Move* movePtr)
  682. {
  683. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  684. WheeledVehicle* wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj.getPointer());
  685. if (!wvo)
  686. {
  687. //cover the case of a connection controling an object in turn controlling another
  688. if (obj->getAIInfo()->mObj->getObjectMount())
  689. wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  690. }
  691. if (!wvo) return;//not a WheeledVehicle
  692. F32 lastYaw = wvo->getSteering().x;
  693. Point3F right = wvo->getTransform().getRightVector();
  694. right.normalize();
  695. Point3F aimLoc = obj->mMovement.mAimLocation;
  696. // Get the AI to Target vector and normalize it.
  697. Point3F toTarg = (location + wvo->getVelocity() * TickSec) - aimLoc;
  698. toTarg.normalize();
  699. F32 dotYaw = -mDot(right, toTarg);
  700. movePtr->yaw = -lastYaw;
  701. VehicleData* vd = (VehicleData*)(wvo->getDataBlock());
  702. F32 maxSteeringAngle = vd->maxSteeringAngle;
  703. if (mFabs(dotYaw) > maxSteeringAngle*1.5f)
  704. dotYaw *= -1.0f;
  705. if (dotYaw > maxSteeringAngle) dotYaw = maxSteeringAngle;
  706. if (dotYaw < -maxSteeringAngle) dotYaw = -maxSteeringAngle;
  707. if (mFabs(dotYaw) > 0.05f)
  708. movePtr->yaw = dotYaw - lastYaw;
  709. };
  710. void AIWheeledVehicleControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  711. {
  712. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  713. WheeledVehicle* wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj.getPointer());
  714. if (!wvo)
  715. {
  716. //cover the case of a connection controling an object in turn controlling another
  717. if (obj->getAIInfo()->mObj->getObjectMount())
  718. wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  719. }
  720. if (!wvo) return;//not a WheeledVehicle
  721. Parent::resolveSpeed(obj, location, movePtr);
  722. VehicleData* db = static_cast<VehicleData *>(wvo->getDataBlock());
  723. movePtr->x = 0;
  724. movePtr->y *= mMax((db->maxSteeringAngle-mFabs(movePtr->yaw) / db->maxSteeringAngle),0.75f);
  725. }
  726. //-----------------------------------------------------------------------------
  727. //-----------------------------------------------------------------------------
  728. IMPLEMENT_CO_DATABLOCK_V1(AIFlyingVehicleControllerData);
  729. void AIFlyingVehicleControllerData::initPersistFields()
  730. {
  731. docsURL;
  732. addGroup("AI");
  733. addFieldV("FlightFloor", TypeRangedF32, Offset(mFlightFloor, AIFlyingVehicleControllerData), &CommonValidators::F32Range,
  734. "@brief Min height we can target.");
  735. addFieldV("FlightCeiling", TypeRangedF32, Offset(mFlightCeiling, AIFlyingVehicleControllerData), &CommonValidators::F32Range,
  736. "@brief Max height we can target.");
  737. endGroup("AI");
  738. Parent::initPersistFields();
  739. }
  740. AIFlyingVehicleControllerData::AIFlyingVehicleControllerData(const AIFlyingVehicleControllerData& other, bool temp_clone) : AIControllerData(other, temp_clone)
  741. {
  742. mFlightCeiling = other.mFlightCeiling;
  743. mFlightFloor = other.mFlightFloor;
  744. resolveYawPtr.bind(this, &AIFlyingVehicleControllerData::resolveYaw);
  745. resolvePitchPtr.bind(this, &AIFlyingVehicleControllerData::resolvePitch);
  746. resolveSpeedPtr.bind(this, &AIFlyingVehicleControllerData::resolveSpeed);
  747. }
  748. void AIFlyingVehicleControllerData::resolveYaw(AIController* obj, Point3F location, Move* movePtr)
  749. {
  750. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  751. FlyingVehicle* fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj.getPointer());
  752. if (!fvo)
  753. {
  754. //cover the case of a connection controling an object in turn controlling another
  755. if (obj->getAIInfo()->mObj->getObjectMount())
  756. fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  757. }
  758. if (!fvo) return;//not a FlyingVehicle
  759. Point3F right = fvo->getTransform().getRightVector();
  760. right.normalize();
  761. // Get the Target to AI vector and normalize it.
  762. Point3F aimLoc = obj->mMovement.mAimLocation;
  763. aimLoc.z = mClampF(aimLoc.z, mFlightFloor, mFlightCeiling);
  764. Point3F toTarg = (location + fvo->getVelocity() * TickSec) - aimLoc;
  765. toTarg.normalize();
  766. movePtr->yaw = 0;
  767. F32 dotYaw = -mDot(right, toTarg);
  768. if (mFabs(dotYaw) > 0.05f)
  769. movePtr->yaw = dotYaw;
  770. };
  771. void AIFlyingVehicleControllerData::resolvePitch(AIController* obj, Point3F location, Move* movePtr)
  772. {
  773. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  774. FlyingVehicle* fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj.getPointer());
  775. if (!fvo)
  776. {
  777. //cover the case of a connection controling an object in turn controlling another
  778. if (obj->getAIInfo()->mObj->getObjectMount())
  779. fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  780. }
  781. if (!fvo) return;//not a FlyingVehicle
  782. Point3F up = fvo->getTransform().getUpVector();
  783. up.normalize();
  784. // Get the Target to AI vector and normalize it.
  785. Point3F aimLoc = obj->mMovement.mAimLocation;
  786. aimLoc.z = mClampF(aimLoc.z, mFlightFloor, mFlightCeiling);
  787. Point3F toTarg = (location + fvo->getVelocity() * TickSec) - aimLoc;
  788. toTarg.normalize();
  789. movePtr->pitch = 0.0f;
  790. F32 dotPitch = mDot(up, toTarg);
  791. if (mFabs(dotPitch) > 0.05f)
  792. movePtr->pitch = dotPitch * M_2PI_F;
  793. }
  794. void AIFlyingVehicleControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  795. {
  796. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  797. FlyingVehicle* fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj.getPointer());
  798. if (!fvo)
  799. {
  800. //cover the case of a connection controling an object in turn controlling another
  801. if (obj->getAIInfo()->mObj->getObjectMount())
  802. fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  803. }
  804. if (!fvo) return;//not a FlyingVehicle
  805. movePtr->x = 0;
  806. movePtr->y = obj->mMovement.mMoveSpeed;
  807. }