DetourPathCorridor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. //
  2. // Copyright (c) 2009-2010 Mikko Mononen [email protected]
  3. //
  4. // This software is provided 'as-is', without any express or implied
  5. // warranty. In no event will the authors be held liable for any damages
  6. // arising from the use of this software.
  7. // Permission is granted to anyone to use this software for any purpose,
  8. // including commercial applications, and to alter it and redistribute it
  9. // freely, subject to the following restrictions:
  10. // 1. The origin of this software must not be misrepresented; you must not
  11. // claim that you wrote the original software. If you use this software
  12. // in a product, an acknowledgment in the product documentation would be
  13. // appreciated but is not required.
  14. // 2. Altered source versions must be plainly marked as such, and must not be
  15. // misrepresented as being the original software.
  16. // 3. This notice may not be removed or altered from any source distribution.
  17. //
  18. // Modified by cosmy1 for Urho3D
  19. #include <string.h>
  20. #include "DetourPathCorridor.h"
  21. #include "DetourNavMeshQuery.h"
  22. #include "DetourCommon.h"
  23. #include "DetourAssert.h"
  24. #include "DetourAlloc.h"
  25. int dtMergeCorridorStartMoved(dtPolyRef* path, const int npath, const int maxPath,
  26. const dtPolyRef* visited, const int nvisited)
  27. {
  28. int furthestPath = -1;
  29. int furthestVisited = -1;
  30. // Find furthest common polygon.
  31. for (int i = npath-1; i >= 0; --i)
  32. {
  33. bool found = false;
  34. for (int j = nvisited-1; j >= 0; --j)
  35. {
  36. if (path[i] == visited[j])
  37. {
  38. furthestPath = i;
  39. furthestVisited = j;
  40. found = true;
  41. }
  42. }
  43. if (found)
  44. break;
  45. }
  46. // If no intersection found just return current path.
  47. if (furthestPath == -1 || furthestVisited == -1)
  48. return npath;
  49. // Concatenate paths.
  50. // Adjust beginning of the buffer to include the visited.
  51. const int req = nvisited - furthestVisited;
  52. const int orig = dtMin(furthestPath+1, npath);
  53. int size = dtMax(0, npath-orig);
  54. if (req+size > maxPath)
  55. size = maxPath-req;
  56. if (size)
  57. memmove(path+req, path+orig, size*sizeof(dtPolyRef));
  58. // Store visited
  59. for (int i = 0; i < req; ++i)
  60. path[i] = visited[(nvisited-1)-i];
  61. return req+size;
  62. }
  63. int dtMergeCorridorEndMoved(dtPolyRef* path, const int npath, const int maxPath,
  64. const dtPolyRef* visited, const int nvisited)
  65. {
  66. int furthestPath = -1;
  67. int furthestVisited = -1;
  68. // Find furthest common polygon.
  69. for (int i = 0; i < npath; ++i)
  70. {
  71. bool found = false;
  72. for (int j = nvisited-1; j >= 0; --j)
  73. {
  74. if (path[i] == visited[j])
  75. {
  76. furthestPath = i;
  77. furthestVisited = j;
  78. found = true;
  79. }
  80. }
  81. if (found)
  82. break;
  83. }
  84. // If no intersection found just return current path.
  85. if (furthestPath == -1 || furthestVisited == -1)
  86. return npath;
  87. // Concatenate paths.
  88. const int ppos = furthestPath+1;
  89. const int vpos = furthestVisited+1;
  90. const int count = dtMin(nvisited-vpos, maxPath-ppos);
  91. dtAssert(ppos+count <= maxPath);
  92. if (count)
  93. memcpy(path+ppos, visited+vpos, sizeof(dtPolyRef)*count);
  94. return ppos+count;
  95. }
  96. int dtMergeCorridorStartShortcut(dtPolyRef* path, const int npath, const int maxPath,
  97. const dtPolyRef* visited, const int nvisited)
  98. {
  99. int furthestPath = -1;
  100. int furthestVisited = -1;
  101. // Find furthest common polygon.
  102. for (int i = npath-1; i >= 0; --i)
  103. {
  104. bool found = false;
  105. for (int j = nvisited-1; j >= 0; --j)
  106. {
  107. if (path[i] == visited[j])
  108. {
  109. furthestPath = i;
  110. furthestVisited = j;
  111. found = true;
  112. }
  113. }
  114. if (found)
  115. break;
  116. }
  117. // If no intersection found just return current path.
  118. if (furthestPath == -1 || furthestVisited == -1)
  119. return npath;
  120. // Concatenate paths.
  121. // Adjust beginning of the buffer to include the visited.
  122. const int req = furthestVisited;
  123. if (req <= 0)
  124. return npath;
  125. const int orig = furthestPath;
  126. int size = dtMax(0, npath-orig);
  127. if (req+size > maxPath)
  128. size = maxPath-req;
  129. if (size)
  130. memmove(path+req, path+orig, size*sizeof(dtPolyRef));
  131. // Store visited
  132. for (int i = 0; i < req; ++i)
  133. path[i] = visited[i];
  134. return req+size;
  135. }
  136. /**
  137. @class dtPathCorridor
  138. @par
  139. The corridor is loaded with a path, usually obtained from a #dtNavMeshQuery::findPath() query. The corridor
  140. is then used to plan local movement, with the corridor automatically updating as needed to deal with inaccurate
  141. agent locomotion.
  142. Example of a common use case:
  143. -# Construct the corridor object and call #init() to allocate its path buffer.
  144. -# Obtain a path from a #dtNavMeshQuery object.
  145. -# Use #reset() to set the agent's current position. (At the beginning of the path.)
  146. -# Use #setCorridor() to load the path and target.
  147. -# Use #findCorners() to plan movement. (This handles dynamic path straightening.)
  148. -# Use #movePosition() to feed agent movement back into the corridor. (The corridor will automatically adjust as needed.)
  149. -# If the target is moving, use #moveTargetPosition() to update the end of the corridor.
  150. (The corridor will automatically adjust as needed.)
  151. -# Repeat the previous 3 steps to continue to move the agent.
  152. The corridor position and target are always constrained to the navigation mesh.
  153. One of the difficulties in maintaining a path is that floating point errors, locomotion inaccuracies, and/or local
  154. steering can result in the agent crossing the boundary of the path corridor, temporarily invalidating the path.
  155. This class uses local mesh queries to detect and update the corridor as needed to handle these types of issues.
  156. The fact that local mesh queries are used to move the position and target locations results in two beahviors that
  157. need to be considered:
  158. Every time a move function is used there is a chance that the path will become non-optimial. Basically, the further
  159. the target is moved from its original location, and the further the position is moved outside the original corridor,
  160. the more likely the path will become non-optimal. This issue can be addressed by periodically running the
  161. #optimizePathTopology() and #optimizePathVisibility() methods.
  162. All local mesh queries have distance limitations. (Review the #dtNavMeshQuery methods for details.) So the most accurate
  163. use case is to move the position and target in small increments. If a large increment is used, then the corridor
  164. may not be able to accurately find the new location. Because of this limiation, if a position is moved in a large
  165. increment, then compare the desired and resulting polygon references. If the two do not match, then path replanning
  166. may be needed. E.g. If you move the target, check #getLastPoly() to see if it is the expected polygon.
  167. */
  168. dtPathCorridor::dtPathCorridor() :
  169. m_path(0),
  170. m_npath(0),
  171. m_maxPath(0)
  172. {
  173. // Urho3D: initialize all class members
  174. memset(&m_pos, 0, sizeof(m_pos));
  175. memset(&m_target, 0, sizeof(m_target));
  176. }
  177. dtPathCorridor::~dtPathCorridor()
  178. {
  179. dtFree(m_path);
  180. }
  181. /// @par
  182. ///
  183. /// @warning Cannot be called more than once.
  184. bool dtPathCorridor::init(const int maxPath)
  185. {
  186. dtAssert(!m_path);
  187. m_path = (dtPolyRef*)dtAlloc(sizeof(dtPolyRef)*maxPath, DT_ALLOC_PERM);
  188. if (!m_path)
  189. return false;
  190. m_npath = 0;
  191. m_maxPath = maxPath;
  192. return true;
  193. }
  194. /// @par
  195. ///
  196. /// Essentially, the corridor is set of one polygon in size with the target
  197. /// equal to the position.
  198. void dtPathCorridor::reset(dtPolyRef ref, const float* pos)
  199. {
  200. dtAssert(m_path);
  201. dtVcopy(m_pos, pos);
  202. dtVcopy(m_target, pos);
  203. m_path[0] = ref;
  204. m_npath = 1;
  205. }
  206. /**
  207. @par
  208. This is the function used to plan local movement within the corridor. One or more corners can be
  209. detected in order to plan movement. It performs essentially the same function as #dtNavMeshQuery::findStraightPath.
  210. Due to internal optimizations, the maximum number of corners returned will be (@p maxCorners - 1)
  211. For example: If the buffers are sized to hold 10 corners, the function will never return more than 9 corners.
  212. So if 10 corners are needed, the buffers should be sized for 11 corners.
  213. If the target is within range, it will be the last corner and have a polygon reference id of zero.
  214. */
  215. int dtPathCorridor::findCorners(float* cornerVerts, unsigned char* cornerFlags,
  216. dtPolyRef* cornerPolys, const int maxCorners,
  217. dtNavMeshQuery* navquery, const dtQueryFilter* /*filter*/)
  218. {
  219. dtAssert(m_path);
  220. dtAssert(m_npath);
  221. static const float MIN_TARGET_DIST = 0.01f;
  222. int ncorners = 0;
  223. navquery->findStraightPath(m_pos, m_target, m_path, m_npath,
  224. cornerVerts, cornerFlags, cornerPolys, &ncorners, maxCorners);
  225. // Prune points in the beginning of the path which are too close.
  226. while (ncorners)
  227. {
  228. if ((cornerFlags[0] & DT_STRAIGHTPATH_OFFMESH_CONNECTION) ||
  229. dtVdist2DSqr(&cornerVerts[0], m_pos) > dtSqr(MIN_TARGET_DIST))
  230. break;
  231. ncorners--;
  232. if (ncorners)
  233. {
  234. memmove(cornerFlags, cornerFlags+1, sizeof(unsigned char)*ncorners);
  235. memmove(cornerPolys, cornerPolys+1, sizeof(dtPolyRef)*ncorners);
  236. memmove(cornerVerts, cornerVerts+3, sizeof(float)*3*ncorners);
  237. }
  238. }
  239. // Prune points after an off-mesh connection.
  240. for (int i = 0; i < ncorners; ++i)
  241. {
  242. if (cornerFlags[i] & DT_STRAIGHTPATH_OFFMESH_CONNECTION)
  243. {
  244. ncorners = i+1;
  245. break;
  246. }
  247. }
  248. return ncorners;
  249. }
  250. /**
  251. @par
  252. Inaccurate locomotion or dynamic obstacle avoidance can force the argent position significantly outside the
  253. original corridor. Over time this can result in the formation of a non-optimal corridor. Non-optimal paths can
  254. also form near the corners of tiles.
  255. This function uses an efficient local visibility search to try to optimize the corridor
  256. between the current position and @p next.
  257. The corridor will change only if @p next is visible from the current position and moving directly toward the point
  258. is better than following the existing path.
  259. The more inaccurate the agent movement, the more beneficial this function becomes. Simply adjust the frequency
  260. of the call to match the needs to the agent.
  261. This function is not suitable for long distance searches.
  262. */
  263. void dtPathCorridor::optimizePathVisibility(const float* next, const float pathOptimizationRange,
  264. dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  265. {
  266. dtAssert(m_path);
  267. // Clamp the ray to max distance.
  268. float goal[3];
  269. dtVcopy(goal, next);
  270. float dist = dtVdist2D(m_pos, goal);
  271. // If too close to the goal, do not try to optimize.
  272. if (dist < 0.01f)
  273. return;
  274. // Overshoot a little. This helps to optimize open fields in tiled meshes.
  275. dist = dtMin(dist+0.01f, pathOptimizationRange);
  276. // Adjust ray length.
  277. float delta[3];
  278. dtVsub(delta, goal, m_pos);
  279. dtVmad(goal, m_pos, delta, pathOptimizationRange/dist);
  280. static const int MAX_RES = 32;
  281. dtPolyRef res[MAX_RES];
  282. float t, norm[3];
  283. int nres = 0;
  284. navquery->raycast(m_path[0], m_pos, goal, filter, &t, norm, res, &nres, MAX_RES);
  285. if (nres > 1 && t > 0.99f)
  286. {
  287. m_npath = dtMergeCorridorStartShortcut(m_path, m_npath, m_maxPath, res, nres);
  288. }
  289. }
  290. /**
  291. @par
  292. Inaccurate locomotion or dynamic obstacle avoidance can force the agent position significantly outside the
  293. original corridor. Over time this can result in the formation of a non-optimal corridor. This function will use a
  294. local area path search to try to re-optimize the corridor.
  295. The more inaccurate the agent movement, the more beneficial this function becomes. Simply adjust the frequency of
  296. the call to match the needs to the agent.
  297. */
  298. bool dtPathCorridor::optimizePathTopology(dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  299. {
  300. dtAssert(navquery);
  301. dtAssert(filter);
  302. dtAssert(m_path);
  303. if (m_npath < 3)
  304. return false;
  305. static const int MAX_ITER = 32;
  306. static const int MAX_RES = 32;
  307. dtPolyRef res[MAX_RES];
  308. int nres = 0;
  309. navquery->initSlicedFindPath(m_path[0], m_path[m_npath-1], m_pos, m_target, filter);
  310. navquery->updateSlicedFindPath(MAX_ITER, 0);
  311. dtStatus status = navquery->finalizeSlicedFindPathPartial(m_path, m_npath, res, &nres, MAX_RES);
  312. if (dtStatusSucceed(status) && nres > 0)
  313. {
  314. m_npath = dtMergeCorridorStartShortcut(m_path, m_npath, m_maxPath, res, nres);
  315. return true;
  316. }
  317. return false;
  318. }
  319. bool dtPathCorridor::moveOverOffmeshConnection(dtPolyRef offMeshConRef, dtPolyRef* refs,
  320. float* startPos, float* endPos,
  321. dtNavMeshQuery* navquery)
  322. {
  323. dtAssert(navquery);
  324. dtAssert(m_path);
  325. dtAssert(m_npath);
  326. // Advance the path up to and over the off-mesh connection.
  327. dtPolyRef prevRef = 0, polyRef = m_path[0];
  328. int npos = 0;
  329. while (npos < m_npath && polyRef != offMeshConRef)
  330. {
  331. prevRef = polyRef;
  332. polyRef = m_path[npos];
  333. npos++;
  334. }
  335. if (npos == m_npath)
  336. {
  337. // Could not find offMeshConRef
  338. return false;
  339. }
  340. // Prune path
  341. for (int i = npos; i < m_npath; ++i)
  342. m_path[i-npos] = m_path[i];
  343. m_npath -= npos;
  344. refs[0] = prevRef;
  345. refs[1] = polyRef;
  346. const dtNavMesh* nav = navquery->getAttachedNavMesh();
  347. dtAssert(nav);
  348. dtStatus status = nav->getOffMeshConnectionPolyEndPoints(refs[0], refs[1], startPos, endPos);
  349. if (dtStatusSucceed(status))
  350. {
  351. dtVcopy(m_pos, endPos);
  352. return true;
  353. }
  354. return false;
  355. }
  356. /**
  357. @par
  358. Behavior:
  359. - The movement is constrained to the surface of the navigation mesh.
  360. - The corridor is automatically adjusted (shorted or lengthened) in order to remain valid.
  361. - The new position will be located in the adjusted corridor's first polygon.
  362. The expected use case is that the desired position will be 'near' the current corridor. What is considered 'near'
  363. depends on local polygon density, query search extents, etc.
  364. The resulting position will differ from the desired position if the desired position is not on the navigation mesh,
  365. or it can't be reached using a local search.
  366. */
  367. bool dtPathCorridor::movePosition(const float* npos, dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  368. {
  369. dtAssert(m_path);
  370. dtAssert(m_npath);
  371. // Move along navmesh and update new position.
  372. float result[3];
  373. static const int MAX_VISITED = 16;
  374. dtPolyRef visited[MAX_VISITED];
  375. int nvisited = 0;
  376. dtStatus status = navquery->moveAlongSurface(m_path[0], m_pos, npos, filter,
  377. result, visited, &nvisited, MAX_VISITED);
  378. if (dtStatusSucceed(status)) {
  379. m_npath = dtMergeCorridorStartMoved(m_path, m_npath, m_maxPath, visited, nvisited);
  380. // Adjust the position to stay on top of the navmesh.
  381. float h = m_pos[1];
  382. navquery->getPolyHeight(m_path[0], result, &h);
  383. result[1] = h;
  384. dtVcopy(m_pos, result);
  385. return true;
  386. }
  387. return false;
  388. }
  389. /**
  390. @par
  391. Behavior:
  392. - The movement is constrained to the surface of the navigation mesh.
  393. - The corridor is automatically adjusted (shorted or lengthened) in order to remain valid.
  394. - The new target will be located in the adjusted corridor's last polygon.
  395. The expected use case is that the desired target will be 'near' the current corridor. What is considered 'near' depends on local polygon density, query search extents, etc.
  396. The resulting target will differ from the desired target if the desired target is not on the navigation mesh, or it can't be reached using a local search.
  397. */
  398. bool dtPathCorridor::moveTargetPosition(const float* npos, dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  399. {
  400. dtAssert(m_path);
  401. dtAssert(m_npath);
  402. // Move along navmesh and update new position.
  403. float result[3];
  404. static const int MAX_VISITED = 16;
  405. dtPolyRef visited[MAX_VISITED];
  406. int nvisited = 0;
  407. dtStatus status = navquery->moveAlongSurface(m_path[m_npath-1], m_target, npos, filter,
  408. result, visited, &nvisited, MAX_VISITED);
  409. if (dtStatusSucceed(status))
  410. {
  411. m_npath = dtMergeCorridorEndMoved(m_path, m_npath, m_maxPath, visited, nvisited);
  412. // TODO: should we do that?
  413. // Adjust the position to stay on top of the navmesh.
  414. /* float h = m_target[1];
  415. navquery->getPolyHeight(m_path[m_npath-1], result, &h);
  416. result[1] = h;*/
  417. dtVcopy(m_target, result);
  418. return true;
  419. }
  420. return false;
  421. }
  422. /// @par
  423. ///
  424. /// The current corridor position is expected to be within the first polygon in the path. The target
  425. /// is expected to be in the last polygon.
  426. ///
  427. /// @warning The size of the path must not exceed the size of corridor's path buffer set during #init().
  428. void dtPathCorridor::setCorridor(const float* target, const dtPolyRef* path, const int npath)
  429. {
  430. dtAssert(m_path);
  431. dtAssert(npath > 0);
  432. dtAssert(npath < m_maxPath);
  433. dtVcopy(m_target, target);
  434. memcpy(m_path, path, sizeof(dtPolyRef)*npath);
  435. m_npath = npath;
  436. }
  437. bool dtPathCorridor::fixPathStart(dtPolyRef safeRef, const float* safePos)
  438. {
  439. dtAssert(m_path);
  440. dtVcopy(m_pos, safePos);
  441. if (m_npath < 3 && m_npath > 0)
  442. {
  443. m_path[2] = m_path[m_npath-1];
  444. m_path[0] = safeRef;
  445. m_path[1] = 0;
  446. m_npath = 3;
  447. }
  448. else
  449. {
  450. m_path[0] = safeRef;
  451. m_path[1] = 0;
  452. }
  453. return true;
  454. }
  455. bool dtPathCorridor::trimInvalidPath(dtPolyRef safeRef, const float* safePos,
  456. dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  457. {
  458. dtAssert(navquery);
  459. dtAssert(filter);
  460. dtAssert(m_path);
  461. // Keep valid path as far as possible.
  462. int n = 0;
  463. while (n < m_npath && navquery->isValidPolyRef(m_path[n], filter)) {
  464. n++;
  465. }
  466. if (n == m_npath)
  467. {
  468. // All valid, no need to fix.
  469. return true;
  470. }
  471. else if (n == 0)
  472. {
  473. // The first polyref is bad, use current safe values.
  474. dtVcopy(m_pos, safePos);
  475. m_path[0] = safeRef;
  476. m_npath = 1;
  477. }
  478. else
  479. {
  480. // The path is partially usable.
  481. m_npath = n;
  482. }
  483. // Clamp target pos to last poly
  484. float tgt[3];
  485. dtVcopy(tgt, m_target);
  486. navquery->closestPointOnPolyBoundary(m_path[m_npath-1], tgt, m_target);
  487. return true;
  488. }
  489. /// @par
  490. ///
  491. /// The path can be invalidated if there are structural changes to the underlying navigation mesh, or the state of
  492. /// a polygon within the path changes resulting in it being filtered out. (E.g. An exclusion or inclusion flag changes.)
  493. bool dtPathCorridor::isValid(const int maxLookAhead, dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  494. {
  495. // Check that all polygons still pass query filter.
  496. const int n = dtMin(m_npath, maxLookAhead);
  497. for (int i = 0; i < n; ++i)
  498. {
  499. if (!navquery->isValidPolyRef(m_path[i], filter))
  500. return false;
  501. }
  502. return true;
  503. }