2
0

AINavigation.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 "AINavigation.h"
  23. #include "AIController.h"
  24. #include "T3D/shapeBase.h"
  25. static U32 sAILoSMask = TerrainObjectType | StaticShapeObjectType | StaticObjectType | AIObjectType;
  26. AINavigation::AINavigation(AIController* controller)
  27. {
  28. mControllerRef = controller;
  29. mJump = None;
  30. mNavSize = Regular;
  31. }
  32. AINavigation::~AINavigation()
  33. {
  34. #ifdef TORQUE_NAVIGATION_ENABLED
  35. clearPath();
  36. clearFollow();
  37. #endif
  38. }
  39. NavMesh* AINavigation::findNavMesh() const
  40. {
  41. GameBase* gbo = dynamic_cast<GameBase*>(mControllerRef->getAIInfo()->mObj.getPointer());
  42. // Search for NavMeshes that contain us entirely with the smallest possible
  43. // volume.
  44. NavMesh* mesh = NULL;
  45. SimSet* set = NavMesh::getServerSet();
  46. for (U32 i = 0; i < set->size(); i++)
  47. {
  48. NavMesh* m = static_cast<NavMesh*>(set->at(i));
  49. if (m->getWorldBox().isContained(gbo->getWorldBox()))
  50. {
  51. // Check that mesh size is appropriate.
  52. if (gbo->isMounted())
  53. {
  54. if (!m->mVehicles)
  55. continue;
  56. }
  57. else
  58. {
  59. if ((getNavSize() == Small && !m->mSmallCharacters) ||
  60. (getNavSize() == Regular && !m->mRegularCharacters) ||
  61. (getNavSize() == Large && !m->mLargeCharacters))
  62. continue;
  63. }
  64. if (!mesh || m->getWorldBox().getVolume() < mesh->getWorldBox().getVolume())
  65. mesh = m;
  66. }
  67. }
  68. return mesh;
  69. }
  70. void AINavigation::updateNavMesh()
  71. {
  72. GameBase* gbo = dynamic_cast<GameBase*>(mControllerRef->getAIInfo()->mObj.getPointer());
  73. NavMesh* old = mNavMesh;
  74. if (mNavMesh.isNull())
  75. mNavMesh = findNavMesh();
  76. else
  77. {
  78. if (!mNavMesh->getWorldBox().isContained(gbo->getWorldBox()))
  79. mNavMesh = findNavMesh();
  80. }
  81. // See if we need to update our path.
  82. if (mNavMesh != old && !mPathData.path.isNull())
  83. {
  84. setPathDestination(mPathData.path->mTo);
  85. }
  86. }
  87. void AINavigation::moveToNode(S32 node)
  88. {
  89. if (mPathData.path.isNull())
  90. return;
  91. // -1 is shorthand for 'last path node'.
  92. if (node == -1)
  93. node = mPathData.path->size() - 1;
  94. // Consider slowing down on the last path node.
  95. setMoveDestination(mPathData.path->getNode(node), false);
  96. // Check flags for this segment.
  97. if (mPathData.index)
  98. {
  99. U16 flags = mPathData.path->getFlags(node - 1);
  100. // Jump if we must.
  101. if (flags & LedgeFlag)
  102. mJump = Ledge;
  103. else if (flags & JumpFlag)
  104. mJump = Now;
  105. else
  106. // Catch pathing errors.
  107. mJump = None;
  108. }
  109. // Store current index.
  110. mPathData.index = node;
  111. }
  112. void AINavigation::repath()
  113. {
  114. // Ineffectual if we don't have a path, or are using someone else's.
  115. if (mPathData.path.isNull() || !mPathData.owned)
  116. return;
  117. if (mRandI(0, 100) < getCtrl()->mControllerData->mFlocking.mChance && flock())
  118. {
  119. mPathData.path->mTo = mMoveDestination;
  120. }
  121. else
  122. {
  123. // If we're following, get their position.
  124. mPathData.path->mTo = getCtrl()->getGoal()->getPosition(true);
  125. }
  126. // Update from position and replan.
  127. mPathData.path->mFrom = getCtrl()->getAIInfo()->getPosition(true);
  128. mPathData.path->plan();
  129. // Move to first node (skip start pos).
  130. moveToNode(1);
  131. }
  132. Point3F AINavigation::getPathDestination() const
  133. {
  134. if (!mPathData.path.isNull())
  135. return mPathData.path->mTo;
  136. return Point3F(0, 0, 0);
  137. }
  138. void AINavigation::setMoveDestination(const Point3F& location, bool slowdown)
  139. {
  140. mMoveDestination = location;
  141. getCtrl()->mMovement.mMoveState = AIController::ModeMove;
  142. getCtrl()->mMovement.mMoveSlowdown = slowdown;
  143. getCtrl()->mMovement.mMoveStuckTestCountdown = getCtrl()->mControllerData->mMoveStuckTestDelay;
  144. }
  145. void AINavigation::onReachDestination()
  146. {
  147. #ifdef TORQUE_NAVIGATION_ENABLED
  148. if (!getPath().isNull())
  149. {
  150. if (mPathData.index == getPath()->size() - 1)
  151. {
  152. // Handle looping paths.
  153. if (getPath()->mIsLooping)
  154. moveToNode(0);
  155. // Otherwise end path.
  156. else
  157. {
  158. clearPath();
  159. getCtrl()->throwCallback("onReachDestination");
  160. }
  161. }
  162. else
  163. {
  164. moveToNode(mPathData.index + 1);
  165. // Throw callback every time if we're on a looping path.
  166. //if(mPathData.path->mIsLooping)
  167. //throwCallback("onReachDestination");
  168. }
  169. }
  170. else
  171. #endif
  172. {
  173. getCtrl()->throwCallback("onReachDestination");
  174. getCtrl()->mMovement.mMoveState = AIController::ModeStop;
  175. }
  176. }
  177. bool AINavigation::setPathDestination(const Point3F& pos, bool replace)
  178. {
  179. if (replace)
  180. getCtrl()->setGoal(pos, getCtrl()->mControllerData->mMoveTolerance);
  181. if (!mNavMesh)
  182. updateNavMesh();
  183. // If we can't find a mesh, just move regularly.
  184. if (!mNavMesh)
  185. {
  186. //setMoveDestination(pos);
  187. getCtrl()->throwCallback("onPathFailed");
  188. return false;
  189. }
  190. // Create a new path.
  191. NavPath* path = new NavPath();
  192. path->mMesh = mNavMesh;
  193. path->mFrom = getCtrl()->getAIInfo()->getPosition(true);
  194. path->mTo = getCtrl()->getGoal()->getPosition(true);
  195. path->mFromSet = path->mToSet = true;
  196. path->mAlwaysRender = true;
  197. path->mLinkTypes = getCtrl()->mControllerData->mLinkTypes;
  198. path->mXray = true;
  199. // Paths plan automatically upon being registered.
  200. if (!path->registerObject())
  201. {
  202. delete path;
  203. return false;
  204. }
  205. if (path->success())
  206. {
  207. // Clear any current path we might have.
  208. clearPath();
  209. getCtrl()->clearCover();
  210. // Store new path.
  211. mPathData.path = path;
  212. mPathData.owned = true;
  213. // Skip node 0, which we are currently standing on.
  214. moveToNode(1);
  215. getCtrl()->throwCallback("onPathSuccess");
  216. return true;
  217. }
  218. else
  219. {
  220. // Just move normally if we can't path.
  221. //setMoveDestination(pos, true);
  222. //return;
  223. getCtrl()->throwCallback("onPathFailed");
  224. path->deleteObject();
  225. return false;
  226. }
  227. }
  228. void AINavigation::followObject()
  229. {
  230. if (getCtrl()->getGoal()->getDist() < getCtrl()->mControllerData->mMoveTolerance)
  231. return;
  232. if (setPathDestination(getCtrl()->getGoal()->getPosition(true)))
  233. {
  234. getCtrl()->clearCover();
  235. }
  236. }
  237. void AINavigation::followObject(SceneObject* obj, F32 radius)
  238. {
  239. getCtrl()->setGoal(obj, radius);
  240. followObject();
  241. }
  242. void AINavigation::clearFollow()
  243. {
  244. getCtrl()->clearGoal();
  245. }
  246. void AINavigation::followNavPath(NavPath* path)
  247. {
  248. // Get rid of our current path.
  249. clearPath();
  250. getCtrl()->clearCover();
  251. // Follow new path.
  252. mPathData.path = path;
  253. mPathData.owned = false;
  254. // Start from 0 since we might not already be there.
  255. moveToNode(0);
  256. }
  257. void AINavigation::clearPath()
  258. {
  259. // Only delete if we own the path.
  260. if (!mPathData.path.isNull() && mPathData.owned)
  261. mPathData.path->deleteObject();
  262. // Reset path data.
  263. mPathData = PathData();
  264. }
  265. bool AINavigation::flock()
  266. {
  267. AIControllerData::Flocking flockingData = getCtrl()->mControllerData->mFlocking;
  268. SimObjectPtr<SceneObject> obj = getCtrl()->getAIInfo()->mObj;
  269. obj->disableCollision();
  270. Point3F pos = obj->getBoxCenter();
  271. Point3F searchArea = Point3F(flockingData.mMin / 2, flockingData.mMax / 2, getCtrl()->getAIInfo()->mObj->getObjBox().maxExtents.z / 2);
  272. F32 maxFlocksq = flockingData.mMax * flockingData.mMax;
  273. bool flocking = false;
  274. if (getCtrl()->getGoal())
  275. {
  276. Point3F dest = mMoveDestination;
  277. if (getCtrl()->mMovement.mMoveState == AIController::ModeStuck)
  278. {
  279. Point3F shuffle = Point3F(mRandF() - 0.5, mRandF() - 0.5, 0);
  280. shuffle.normalize();
  281. dest += shuffle * flockingData.mMin;
  282. }
  283. dest.z = pos.z;
  284. if ((pos - dest).len() > flockingData.mSideStep)
  285. {
  286. //find closest object
  287. SimpleQueryList sql;
  288. Box3F queryBox = Box3F(pos - searchArea, pos + searchArea);
  289. obj->getContainer()->findObjects(queryBox, AIObjectType, SimpleQueryList::insertionCallback, &sql);
  290. sql.mList.remove(obj);
  291. Point3F avoidanceOffset = Point3F::Zero;
  292. U32 found = 0;
  293. //avoid objects in the way
  294. RayInfo info;
  295. if (obj->getContainer()->castRay(pos, dest + Point3F(0, 0, obj->getObjBox().len_z() / 2), sAILoSMask, &info))
  296. {
  297. Point3F blockerOffset = (info.point - dest);
  298. blockerOffset.z = 0;
  299. avoidanceOffset += blockerOffset;
  300. }
  301. //avoid bots that are too close
  302. for (U32 i = 0; i < sql.mList.size(); i++)
  303. {
  304. ShapeBase* other = dynamic_cast<ShapeBase*>(sql.mList[i]);
  305. Point3F objectCenter = other->getBoxCenter();
  306. F32 sumRad = flockingData.mMin + other->getAIController()->mControllerData->mFlocking.mMin;
  307. F32 separation = getCtrl()->getAIInfo()->mRadius + other->getAIController()->getAIInfo()->mRadius;
  308. sumRad += separation;
  309. Point3F offset = (pos - objectCenter);
  310. F32 offsetLensq = offset.lenSquared(); //square roots are expensive, so use squared val compares
  311. if ((flockingData.mMin > 0) && (offsetLensq < (sumRad * sumRad)))
  312. {
  313. other->disableCollision();
  314. if (!obj->getContainer()->castRay(pos, other->getBoxCenter(), sAILoSMask, &info))
  315. {
  316. found++;
  317. offset.normalizeSafe();
  318. offset *= sumRad + separation;
  319. avoidanceOffset += offset; //accumulate total group, move away from that
  320. }
  321. other->enableCollision();
  322. }
  323. }
  324. //if we don't have to worry about bumping into one another (nothing found lower than minFLock), see about grouping up
  325. if (found == 0)
  326. {
  327. for (U32 i = 0; i < sql.mList.size(); i++)
  328. {
  329. ShapeBase* other = static_cast<ShapeBase*>(sql.mList[i]);
  330. Point3F objectCenter = other->getBoxCenter();
  331. F32 sumRad = flockingData.mMin + other->getAIController()->mControllerData->mFlocking.mMin;
  332. F32 separation = getCtrl()->getAIInfo()->mRadius + other->getAIController()->getAIInfo()->mRadius;
  333. sumRad += separation;
  334. Point3F offset = (pos - objectCenter);
  335. if ((flockingData.mMin > 0) && ((sumRad * sumRad) < (maxFlocksq)))
  336. {
  337. other->disableCollision();
  338. if (!obj->getContainer()->castRay(pos, other->getBoxCenter(), sAILoSMask, &info))
  339. {
  340. found++;
  341. offset.normalizeSafe();
  342. offset *= sumRad + separation;
  343. avoidanceOffset -= offset; // subtract total group, move toward it
  344. }
  345. other->enableCollision();
  346. }
  347. }
  348. }
  349. avoidanceOffset.z = 0;
  350. avoidanceOffset.x = (mRandF() * avoidanceOffset.x) * 0.5 + avoidanceOffset.x * 0.75;
  351. avoidanceOffset.y = (mRandF() * avoidanceOffset.y) * 0.5 + avoidanceOffset.y * 0.75;
  352. if (avoidanceOffset.lenSquared() < (maxFlocksq))
  353. {
  354. dest += avoidanceOffset;
  355. }
  356. //if we're not jumping...
  357. if (mJump == None)
  358. {
  359. dest.z = obj->getPosition().z;
  360. //make sure we don't run off a cliff
  361. Point3F zlen(0, 0, getCtrl()->mControllerData->mHeightTolerance);
  362. if (obj->getContainer()->castRay(dest + zlen, dest - zlen, TerrainObjectType | StaticShapeObjectType | StaticObjectType, &info))
  363. {
  364. if ((mMoveDestination - dest).len() > getCtrl()->mControllerData->mMoveTolerance)
  365. {
  366. mMoveDestination = dest;
  367. flocking = true;
  368. }
  369. }
  370. }
  371. }
  372. }
  373. obj->enableCollision();
  374. return flocking;
  375. }
  376. DefineEngineMethod(AIController, setMoveDestination, void, (Point3F goal, bool slowDown), (true),
  377. "@brief Tells the AI to move to the location provided\n\n"
  378. "@param goal Coordinates in world space representing location to move to.\n"
  379. "@param slowDown A boolean value. If set to true, the bot will slow down "
  380. "when it gets within 5-meters of its move destination. If false, the bot "
  381. "will stop abruptly when it reaches the move destination. By default, this is true.\n\n"
  382. "@note Upon reaching a move destination, the bot will clear its move destination and "
  383. "calls to getMoveDestination will return \"0 0 0\"."
  384. "@see getMoveDestination()\n")
  385. {
  386. object->getNav()->setMoveDestination(goal, slowDown);
  387. }
  388. DefineEngineMethod(AIController, getMoveDestination, Point3F, (), ,
  389. "@brief Get the AIPlayer's current destination.\n\n"
  390. "@return Returns a point containing the \"x y z\" position "
  391. "of the AIPlayer's current move destination. If no move destination "
  392. "has yet been set, this returns \"0 0 0\"."
  393. "@see setMoveDestination()\n")
  394. {
  395. return object->getNav()->getMoveDestination();
  396. }
  397. DefineEngineMethod(AIController, setPathDestination, bool, (Point3F goal), ,
  398. "@brief Tells the AI to find a path to the location provided\n\n"
  399. "@param goal Coordinates in world space representing location to move to.\n"
  400. "@return True if a path was found.\n\n"
  401. "@see getPathDestination()\n"
  402. "@see setMoveDestination()\n")
  403. {
  404. return object->getNav()->setPathDestination(goal,true);
  405. }
  406. DefineEngineMethod(AIController, getPathDestination, Point3F, (), ,
  407. "@brief Get the AIPlayer's current pathfinding destination.\n\n"
  408. "@return Returns a point containing the \"x y z\" position "
  409. "of the AIPlayer's current path destination. If no path destination "
  410. "has yet been set, this returns \"0 0 0\"."
  411. "@see setPathDestination()\n")
  412. {
  413. return object->getNav()->getPathDestination();
  414. }
  415. DefineEngineMethod(AIController, followNavPath, void, (SimObjectId obj), ,
  416. "@brief Tell the AIPlayer to follow a path.\n\n"
  417. "@param obj ID of a NavPath object for the character to follow.")
  418. {
  419. NavPath* path;
  420. if (Sim::findObject(obj, path))
  421. object->getNav()->followNavPath(path);
  422. }
  423. DefineEngineMethod(AIController, followObject, void, (SimObjectId obj, F32 radius), ,
  424. "@brief Tell the AIPlayer to follow another object.\n\n"
  425. "@param obj ID of the object to follow.\n"
  426. "@param radius Maximum distance we let the target escape to.")
  427. {
  428. SceneObject* follow;
  429. object->getNav()->clearPath();
  430. object->clearCover();
  431. object->getNav()->clearFollow();
  432. if (Sim::findObject(obj, follow))
  433. object->getNav()->followObject(follow, radius);
  434. }
  435. DefineEngineMethod(AIController, repath, void, (), ,
  436. "@brief Tells the AI to re-plan its path. Does nothing if the character "
  437. "has no path, or if it is following a mission path.\n\n")
  438. {
  439. object->getNav()->repath();
  440. }
  441. DefineEngineMethod(AIController, findNavMesh, S32, (), ,
  442. "@brief Get the NavMesh object this AIPlayer is currently using.\n\n"
  443. "@return The ID of the NavPath object this character is using for "
  444. "pathfinding. This is determined by the character's location, "
  445. "navigation type and other factors. Returns -1 if no NavMesh is "
  446. "found.")
  447. {
  448. NavMesh* mesh = object->getNav()->getNavMesh();
  449. return mesh ? mesh->getId() : -1;
  450. }
  451. DefineEngineMethod(AIController, getNavMesh, S32, (), ,
  452. "@brief Return the NavMesh this AIPlayer is using to navigate.\n\n")
  453. {
  454. NavMesh* m = object->getNav()->getNavMesh();
  455. return m ? m->getId() : 0;
  456. }
  457. DefineEngineMethod(AIController, setNavSize, void, (const char* size), ,
  458. "@brief Set the size of NavMesh this character uses. One of \"Small\", \"Regular\" or \"Large\".")
  459. {
  460. if (!String::compare(size, "Small"))
  461. object->getNav()->setNavSize(AINavigation::Small);
  462. else if (!String::compare(size, "Regular"))
  463. object->getNav()->setNavSize(AINavigation::Regular);
  464. else if (!String::compare(size, "Large"))
  465. object->getNav()->setNavSize(AINavigation::Large);
  466. else
  467. Con::errorf("AIPlayer::setNavSize: no such size '%s'.", size);
  468. }
  469. DefineEngineMethod(AIController, getNavSize, const char*, (), ,
  470. "@brief Return the size of NavMesh this character uses for pathfinding.")
  471. {
  472. switch (object->getNav()->getNavSize())
  473. {
  474. case AINavigation::Small:
  475. return "Small";
  476. case AINavigation::Regular:
  477. return "Regular";
  478. case AINavigation::Large:
  479. return "Large";
  480. }
  481. return "";
  482. }