NavigationMesh.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "CollisionShape.h"
  24. #include "Context.h"
  25. #include "DebugRenderer.h"
  26. #include "Drawable.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "MemoryBuffer.h"
  30. #include "Model.h"
  31. #include "Navigable.h"
  32. #include "NavigationMesh.h"
  33. #include "OffMeshConnection.h"
  34. #include "Profiler.h"
  35. #include "Scene.h"
  36. #include "StaticModel.h"
  37. #include "TerrainPatch.h"
  38. #include "VectorBuffer.h"
  39. #include <cfloat>
  40. #include <DetourNavMesh.h>
  41. #include <DetourNavMeshBuilder.h>
  42. #include <DetourNavMeshQuery.h>
  43. #include <Recast.h>
  44. #include "DebugNew.h"
  45. namespace Urho3D
  46. {
  47. extern const char* NAVIGATION_CATEGORY;
  48. static const int DEFAULT_TILE_SIZE = 128;
  49. static const float DEFAULT_CELL_SIZE = 0.3f;
  50. static const float DEFAULT_CELL_HEIGHT = 0.2f;
  51. static const float DEFAULT_AGENT_HEIGHT = 2.0f;
  52. static const float DEFAULT_AGENT_RADIUS = 0.6f;
  53. static const float DEFAULT_AGENT_MAX_CLIMB = 0.9f;
  54. static const float DEFAULT_AGENT_MAX_SLOPE = 45.0f;
  55. static const float DEFAULT_REGION_MIN_SIZE = 8.0f;
  56. static const float DEFAULT_REGION_MERGE_SIZE = 20.0f;
  57. static const float DEFAULT_EDGE_MAX_LENGTH = 12.0f;
  58. static const float DEFAULT_EDGE_MAX_ERROR = 1.3f;
  59. static const float DEFAULT_DETAIL_SAMPLE_DISTANCE = 6.0f;
  60. static const float DEFAULT_DETAIL_SAMPLE_MAX_ERROR = 1.0f;
  61. static const int MAX_POLYS = 2048;
  62. /// Temporary data for building one tile of the navigation mesh.
  63. struct NavigationBuildData
  64. {
  65. /// Construct.
  66. NavigationBuildData() :
  67. ctx_(new rcContext(false)),
  68. heightField_(0),
  69. compactHeightField_(0),
  70. contourSet_(0),
  71. polyMesh_(0),
  72. polyMeshDetail_(0)
  73. {
  74. }
  75. /// Destruct.
  76. ~NavigationBuildData()
  77. {
  78. delete(ctx_);
  79. rcFreeHeightField(heightField_);
  80. rcFreeCompactHeightfield(compactHeightField_);
  81. rcFreeContourSet(contourSet_);
  82. rcFreePolyMesh(polyMesh_);
  83. rcFreePolyMeshDetail(polyMeshDetail_);
  84. ctx_ = 0;
  85. heightField_ = 0;
  86. compactHeightField_ = 0;
  87. contourSet_ = 0;
  88. polyMesh_ = 0;
  89. polyMeshDetail_ = 0;
  90. }
  91. /// World-space bounding box of the navigation mesh tile.
  92. BoundingBox worldBoundingBox_;
  93. /// Vertices from geometries.
  94. PODVector<Vector3> vertices_;
  95. /// Triangle indices from geometries.
  96. PODVector<int> indices_;
  97. /// Offmesh connection vertices.
  98. PODVector<Vector3> offMeshVertices_;
  99. /// Offmesh connection radii.
  100. PODVector<float> offMeshRadii_;
  101. /// Offmesh connection flags.
  102. PODVector<unsigned short> offMeshFlags_;
  103. /// Offmesh connection areas.
  104. PODVector<unsigned char> offMeshAreas_;
  105. /// Offmesh connection direction.
  106. PODVector<unsigned char> offMeshDir_;
  107. /// Recast context.
  108. rcContext* ctx_;
  109. /// Recast heightfield.
  110. rcHeightfield* heightField_;
  111. /// Recast compact heightfield.
  112. rcCompactHeightfield* compactHeightField_;
  113. /// Recast contour set.
  114. rcContourSet* contourSet_;
  115. /// Recast poly mesh.
  116. rcPolyMesh* polyMesh_;
  117. /// Recast detail poly mesh.
  118. rcPolyMeshDetail* polyMeshDetail_;
  119. };
  120. /// Temporary data for finding a path.
  121. struct FindPathData
  122. {
  123. // Polygons.
  124. dtPolyRef polys_[MAX_POLYS];
  125. // Polygons on the path.
  126. dtPolyRef pathPolys_[MAX_POLYS];
  127. // Points on the path.
  128. Vector3 pathPoints_[MAX_POLYS];
  129. // Flags on the path.
  130. unsigned char pathFlags_[MAX_POLYS];
  131. };
  132. NavigationMesh::NavigationMesh(Context* context) :
  133. Component(context),
  134. navMesh_(0),
  135. navMeshQuery_(0),
  136. queryFilter_(new dtQueryFilter()),
  137. pathData_(new FindPathData()),
  138. tileSize_(DEFAULT_TILE_SIZE),
  139. cellSize_(DEFAULT_CELL_SIZE),
  140. cellHeight_(DEFAULT_CELL_HEIGHT),
  141. agentHeight_(DEFAULT_AGENT_HEIGHT),
  142. agentRadius_(DEFAULT_AGENT_RADIUS),
  143. agentMaxClimb_(DEFAULT_AGENT_MAX_CLIMB),
  144. agentMaxSlope_(DEFAULT_AGENT_MAX_SLOPE),
  145. regionMinSize_(DEFAULT_REGION_MIN_SIZE),
  146. regionMergeSize_(DEFAULT_REGION_MERGE_SIZE),
  147. edgeMaxLength_(DEFAULT_EDGE_MAX_LENGTH),
  148. edgeMaxError_(DEFAULT_EDGE_MAX_ERROR),
  149. detailSampleDistance_(DEFAULT_DETAIL_SAMPLE_DISTANCE),
  150. detailSampleMaxError_(DEFAULT_DETAIL_SAMPLE_MAX_ERROR),
  151. padding_(Vector3::ONE),
  152. numTilesX_(0),
  153. numTilesZ_(0)
  154. {
  155. }
  156. NavigationMesh::~NavigationMesh()
  157. {
  158. ReleaseNavigationMesh();
  159. delete queryFilter_;
  160. queryFilter_ = 0;
  161. delete pathData_;
  162. pathData_ = 0;
  163. }
  164. void NavigationMesh::RegisterObject(Context* context)
  165. {
  166. context->RegisterFactory<NavigationMesh>(NAVIGATION_CATEGORY);
  167. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_INT, "Tile Size", GetTileSize, SetTileSize, int, DEFAULT_TILE_SIZE, AM_DEFAULT);
  168. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Cell Size", GetCellSize, SetCellSize, float, DEFAULT_CELL_SIZE, AM_DEFAULT);
  169. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Cell Height", GetCellHeight, SetCellHeight, float, DEFAULT_CELL_HEIGHT, AM_DEFAULT);
  170. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Height", GetAgentHeight, SetAgentHeight, float, DEFAULT_AGENT_HEIGHT, AM_DEFAULT);
  171. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Radius", GetAgentRadius, SetAgentRadius, float, DEFAULT_AGENT_RADIUS, AM_DEFAULT);
  172. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Max Climb", GetAgentMaxClimb, SetAgentMaxClimb, float, DEFAULT_AGENT_MAX_CLIMB, AM_DEFAULT);
  173. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Max Slope", GetAgentMaxSlope, SetAgentMaxSlope, float, DEFAULT_AGENT_MAX_SLOPE, AM_DEFAULT);
  174. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Region Min Size", GetRegionMinSize, SetRegionMinSize, float, DEFAULT_REGION_MIN_SIZE, AM_DEFAULT);
  175. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Region Merge Size", GetRegionMergeSize, SetRegionMergeSize, float, DEFAULT_REGION_MERGE_SIZE, AM_DEFAULT);
  176. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Edge Max Length", GetEdgeMaxLength, SetEdgeMaxLength, float, DEFAULT_EDGE_MAX_LENGTH, AM_DEFAULT);
  177. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Edge Max Error", GetEdgeMaxError, SetEdgeMaxError, float, DEFAULT_EDGE_MAX_ERROR, AM_DEFAULT);
  178. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Detail Sample Distance", GetDetailSampleDistance, SetDetailSampleDistance, float, DEFAULT_DETAIL_SAMPLE_DISTANCE, AM_DEFAULT);
  179. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Detail Sample Max Error", GetDetailSampleMaxError, SetDetailSampleMaxError, float, DEFAULT_DETAIL_SAMPLE_MAX_ERROR, AM_DEFAULT);
  180. REF_ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_VECTOR3, "Bounding Box Padding", GetPadding, SetPadding, Vector3, Vector3::ONE, AM_DEFAULT);
  181. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_BUFFER, "Navigation Data", GetNavigationDataAttr, SetNavigationDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  182. }
  183. void NavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  184. {
  185. if (!navMesh_ || !node_)
  186. return;
  187. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  188. const dtNavMesh* navMesh = navMesh_;
  189. for (int z = 0; z < numTilesZ_; ++z)
  190. {
  191. for (int x = 0; x < numTilesX_; ++x)
  192. {
  193. const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);
  194. if (!tile)
  195. continue;
  196. for (int i = 0; i < tile->header->polyCount; ++i)
  197. {
  198. dtPoly* poly = tile->polys + i;
  199. for (unsigned j = 0; j < poly->vertCount; ++j)
  200. {
  201. debug->AddLine(
  202. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),
  203. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),
  204. Color::YELLOW,
  205. depthTest
  206. );
  207. }
  208. }
  209. }
  210. }
  211. }
  212. void NavigationMesh::SetTileSize(int size)
  213. {
  214. tileSize_ = Max(size, 16);
  215. MarkNetworkUpdate();
  216. }
  217. void NavigationMesh::SetCellSize(float size)
  218. {
  219. cellSize_ = Max(size, M_EPSILON);
  220. MarkNetworkUpdate();
  221. }
  222. void NavigationMesh::SetCellHeight(float height)
  223. {
  224. cellHeight_ = Max(height, M_EPSILON);
  225. MarkNetworkUpdate();
  226. }
  227. void NavigationMesh::SetAgentHeight(float height)
  228. {
  229. agentHeight_ = Max(height, M_EPSILON);
  230. MarkNetworkUpdate();
  231. }
  232. void NavigationMesh::SetAgentRadius(float radius)
  233. {
  234. agentRadius_ = Max(radius, M_EPSILON);
  235. MarkNetworkUpdate();
  236. }
  237. void NavigationMesh::SetAgentMaxClimb(float maxClimb)
  238. {
  239. agentMaxClimb_ = Max(maxClimb, M_EPSILON);
  240. MarkNetworkUpdate();
  241. }
  242. void NavigationMesh::SetAgentMaxSlope(float maxSlope)
  243. {
  244. agentMaxSlope_ = Max(maxSlope, 0.0f);
  245. MarkNetworkUpdate();
  246. }
  247. void NavigationMesh::SetRegionMinSize(float size)
  248. {
  249. regionMinSize_ = Max(size, M_EPSILON);
  250. MarkNetworkUpdate();
  251. }
  252. void NavigationMesh::SetRegionMergeSize(float size)
  253. {
  254. regionMergeSize_ = Max(size, M_EPSILON);
  255. MarkNetworkUpdate();
  256. }
  257. void NavigationMesh::SetEdgeMaxLength(float length)
  258. {
  259. edgeMaxLength_ = Max(length, M_EPSILON);
  260. MarkNetworkUpdate();
  261. }
  262. void NavigationMesh::SetEdgeMaxError(float error)
  263. {
  264. edgeMaxError_ = Max(error, M_EPSILON);
  265. MarkNetworkUpdate();
  266. }
  267. void NavigationMesh::SetDetailSampleDistance(float distance)
  268. {
  269. detailSampleDistance_ = Max(distance, M_EPSILON);
  270. MarkNetworkUpdate();
  271. }
  272. void NavigationMesh::SetDetailSampleMaxError(float error)
  273. {
  274. detailSampleMaxError_ = Max(error, M_EPSILON);
  275. MarkNetworkUpdate();
  276. }
  277. void NavigationMesh::SetPadding(const Vector3& padding)
  278. {
  279. padding_ = padding;
  280. MarkNetworkUpdate();
  281. }
  282. bool NavigationMesh::Build()
  283. {
  284. PROFILE(BuildNavigationMesh);
  285. // Release existing navigation data and zero the bounding box
  286. ReleaseNavigationMesh();
  287. if (!node_)
  288. return false;
  289. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  290. LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  291. Vector<NavigationGeometryInfo> geometryList;
  292. CollectGeometries(geometryList);
  293. if (geometryList.Empty())
  294. return true; // Nothing to do
  295. // Build the combined bounding box
  296. for (unsigned i = 0; i < geometryList.Size(); ++i)
  297. boundingBox_.Merge(geometryList[i].boundingBox_);
  298. // Expand bounding box by padding
  299. boundingBox_.min_ -= padding_;
  300. boundingBox_.max_ += padding_;
  301. {
  302. PROFILE(BuildNavigationMesh);
  303. // Calculate number of tiles
  304. int gridW = 0, gridH = 0;
  305. float tileEdgeLength = (float)tileSize_ * cellSize_;
  306. rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);
  307. numTilesX_ = (gridW + tileSize_ - 1) / tileSize_;
  308. numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_;
  309. // Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile
  310. unsigned maxTiles = NextPowerOfTwo(numTilesX_ * numTilesZ_);
  311. unsigned tileBits = 0;
  312. unsigned temp = maxTiles;
  313. while (temp > 1)
  314. {
  315. temp >>= 1;
  316. ++tileBits;
  317. }
  318. unsigned maxPolys = 1 << (22 - tileBits);
  319. dtNavMeshParams params;
  320. rcVcopy(params.orig, &boundingBox_.min_.x_);
  321. params.tileWidth = tileEdgeLength;
  322. params.tileHeight = tileEdgeLength;
  323. params.maxTiles = maxTiles;
  324. params.maxPolys = maxPolys;
  325. navMesh_ = dtAllocNavMesh();
  326. if (!navMesh_)
  327. {
  328. LOGERROR("Could not allocate navigation mesh");
  329. return false;
  330. }
  331. if (dtStatusFailed(navMesh_->init(&params)))
  332. {
  333. LOGERROR("Could not initialize navigation mesh");
  334. ReleaseNavigationMesh();
  335. return false;
  336. }
  337. // Build each tile
  338. unsigned numTiles = 0;
  339. for (int z = 0; z < numTilesZ_; ++z)
  340. {
  341. for (int x = 0; x < numTilesX_; ++x)
  342. {
  343. if (BuildTile(geometryList, x, z))
  344. ++numTiles;
  345. }
  346. }
  347. LOGDEBUG("Built navigation mesh with " + String(numTiles) + " tiles");
  348. return true;
  349. }
  350. }
  351. bool NavigationMesh::Build(const BoundingBox& boundingBox)
  352. {
  353. PROFILE(BuildPartialNavigationMesh);
  354. if (!node_)
  355. return false;
  356. if (!navMesh_)
  357. {
  358. LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt");
  359. return false;
  360. }
  361. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  362. LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  363. BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse());
  364. float tileEdgeLength = (float)tileSize_ * cellSize_;
  365. Vector<NavigationGeometryInfo> geometryList;
  366. CollectGeometries(geometryList);
  367. int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  368. int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  369. int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  370. int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  371. unsigned numTiles = 0;
  372. for (int z = sz; z <= ez; ++z)
  373. {
  374. for (int x = sx; x <= ex; ++x)
  375. {
  376. if (BuildTile(geometryList, x, z))
  377. ++numTiles;
  378. }
  379. }
  380. LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  381. return true;
  382. }
  383. void NavigationMesh::FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, const Vector3& extents)
  384. {
  385. PROFILE(FindPath);
  386. dest.Clear();
  387. if (!InitializeQuery())
  388. return;
  389. // Navigation data is in local space. Transform path points from world to local
  390. const Matrix3x4& transform = node_->GetWorldTransform();
  391. Matrix3x4 inverse = transform.Inverse();
  392. Vector3 localStart = inverse * start;
  393. Vector3 localEnd = inverse * end;
  394. dtPolyRef startRef;
  395. dtPolyRef endRef;
  396. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  397. navMeshQuery_->findNearestPoly(&localEnd.x_, &extents.x_, queryFilter_, &endRef, 0);
  398. if (!startRef || !endRef)
  399. return;
  400. int numPolys = 0;
  401. int numPathPoints = 0;
  402. navMeshQuery_->findPath(startRef, endRef, &localStart.x_, &localEnd.x_, queryFilter_, pathData_->polys_, &numPolys,
  403. MAX_POLYS);
  404. if (!numPolys)
  405. return;
  406. Vector3 actualLocalEnd = localEnd;
  407. // If full path was not found, clamp end point to the end polygon
  408. if (pathData_->polys_[numPolys - 1] != endRef)
  409. navMeshQuery_->closestPointOnPoly(pathData_->polys_[numPolys - 1], &localEnd.x_, &actualLocalEnd.x_);
  410. navMeshQuery_->findStraightPath(&localStart.x_, &actualLocalEnd.x_, pathData_->polys_, numPolys,
  411. &pathData_->pathPoints_[0].x_, pathData_->pathFlags_, pathData_->pathPolys_, &numPathPoints, MAX_POLYS);
  412. // Transform path result back to world space
  413. for (int i = 0; i < numPathPoints; ++i)
  414. dest.Push(transform * pathData_->pathPoints_[i]);
  415. }
  416. Vector3 NavigationMesh::GetRandomPoint()
  417. {
  418. if (!InitializeQuery())
  419. return Vector3::ZERO;
  420. dtPolyRef polyRef;
  421. Vector3 point(Vector3::ZERO);
  422. navMeshQuery_->findRandomPoint(queryFilter_, Random, &polyRef, &point.x_);
  423. return node_->GetWorldTransform() * point;
  424. }
  425. Vector3 NavigationMesh::GetRandomPointInCircle(const Vector3& center, float radius, const Vector3& extents)
  426. {
  427. if (!InitializeQuery())
  428. return center;
  429. const Matrix3x4& transform = node_->GetWorldTransform();
  430. Matrix3x4 inverse = transform.Inverse();
  431. Vector3 localCenter = inverse * center;
  432. dtPolyRef startRef;
  433. navMeshQuery_->findNearestPoly(&localCenter.x_, &extents.x_, queryFilter_, &startRef, 0);
  434. if (!startRef)
  435. return center;
  436. dtPolyRef polyRef;
  437. Vector3 point(localCenter);
  438. navMeshQuery_->findRandomPointAroundCircle(startRef, &localCenter.x_, radius, queryFilter_, Random, &polyRef, &point.x_);
  439. return transform * point;
  440. }
  441. float NavigationMesh::GetDistanceToWall(const Vector3& point, float radius, const Vector3& extents)
  442. {
  443. if (!InitializeQuery())
  444. return radius;
  445. const Matrix3x4& transform = node_->GetWorldTransform();
  446. Matrix3x4 inverse = transform.Inverse();
  447. Vector3 localPoint = inverse * point;
  448. dtPolyRef startRef;
  449. navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter_, &startRef, 0);
  450. if (!startRef)
  451. return radius;
  452. float hitDist = radius;
  453. Vector3 hitPos;
  454. Vector3 hitNormal;
  455. navMeshQuery_->findDistanceToWall(startRef, &localPoint.x_, radius, queryFilter_, &hitDist, &hitPos.x_, &hitNormal.x_);
  456. return hitDist;
  457. }
  458. Vector3 NavigationMesh::Raycast(const Vector3& start, const Vector3& end, const Vector3& extents)
  459. {
  460. if (!InitializeQuery())
  461. return end;
  462. const Matrix3x4& transform = node_->GetWorldTransform();
  463. Matrix3x4 inverse = transform.Inverse();
  464. Vector3 localStart = inverse * start;
  465. Vector3 localEnd = inverse * end;
  466. dtPolyRef startRef;
  467. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  468. if (!startRef)
  469. return end;
  470. Vector3 localHitNormal;
  471. float t;
  472. int numPolys;
  473. navMeshQuery_->raycast(startRef, &localStart.x_, &localEnd.x_, queryFilter_, &t, &localHitNormal.x_, pathData_->polys_, &numPolys, MAX_POLYS);
  474. if (t == FLT_MAX)
  475. t = 1.0f;
  476. return start.Lerp(end, t);
  477. }
  478. BoundingBox NavigationMesh::GetWorldBoundingBox() const
  479. {
  480. return node_ ? boundingBox_.Transformed(node_->GetWorldTransform()) : boundingBox_;
  481. }
  482. void NavigationMesh::SetNavigationDataAttr(PODVector<unsigned char> value)
  483. {
  484. ReleaseNavigationMesh();
  485. if (value.Empty())
  486. return;
  487. MemoryBuffer buffer(value);
  488. boundingBox_ = buffer.ReadBoundingBox();
  489. numTilesX_ = buffer.ReadInt();
  490. numTilesZ_ = buffer.ReadInt();
  491. dtNavMeshParams params;
  492. rcVcopy(params.orig, &boundingBox_.min_.x_);
  493. params.tileWidth = buffer.ReadFloat();
  494. params.tileHeight = buffer.ReadFloat();
  495. params.maxTiles = buffer.ReadInt();
  496. params.maxPolys = buffer.ReadInt();
  497. navMesh_ = dtAllocNavMesh();
  498. if (!navMesh_)
  499. {
  500. LOGERROR("Could not allocate navigation mesh");
  501. return;
  502. }
  503. if (dtStatusFailed(navMesh_->init(&params)))
  504. {
  505. LOGERROR("Could not initialize navigation mesh");
  506. ReleaseNavigationMesh();
  507. return;
  508. }
  509. unsigned numTiles = 0;
  510. while (!buffer.IsEof())
  511. {
  512. /*int x =*/ buffer.ReadInt();
  513. /*int z =*/ buffer.ReadInt();
  514. /*dtTileRef tileRef =*/ buffer.ReadUInt();
  515. unsigned navDataSize = buffer.ReadUInt();
  516. unsigned char* navData = (unsigned char*)dtAlloc(navDataSize, DT_ALLOC_PERM);
  517. if (!navData)
  518. {
  519. LOGERROR("Could not allocate data for navigation mesh tile");
  520. return;
  521. }
  522. buffer.Read(navData, navDataSize);
  523. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  524. {
  525. LOGERROR("Failed to add navigation mesh tile");
  526. dtFree(navData);
  527. return;
  528. }
  529. else
  530. ++numTiles;
  531. }
  532. LOGDEBUG("Created navigation mesh with " + String(numTiles) + " tiles from serialized data");
  533. }
  534. PODVector<unsigned char> NavigationMesh::GetNavigationDataAttr() const
  535. {
  536. VectorBuffer ret;
  537. if (navMesh_)
  538. {
  539. ret.WriteBoundingBox(boundingBox_);
  540. ret.WriteInt(numTilesX_);
  541. ret.WriteInt(numTilesZ_);
  542. const dtNavMeshParams* params = navMesh_->getParams();
  543. ret.WriteFloat(params->tileWidth);
  544. ret.WriteFloat(params->tileHeight);
  545. ret.WriteInt(params->maxTiles);
  546. ret.WriteInt(params->maxPolys);
  547. const dtNavMesh* navMesh = navMesh_;
  548. for (int z = 0; z < numTilesZ_; ++z)
  549. {
  550. for (int x = 0; x < numTilesX_; ++x)
  551. {
  552. const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);
  553. if (!tile)
  554. continue;
  555. ret.WriteInt(x);
  556. ret.WriteInt(z);
  557. ret.WriteUInt(navMesh->getTileRef(tile));
  558. ret.WriteUInt(tile->dataSize);
  559. ret.Write(tile->data, tile->dataSize);
  560. }
  561. }
  562. }
  563. return ret.GetBuffer();
  564. }
  565. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList)
  566. {
  567. PROFILE(CollectNavigationGeometry);
  568. // Get Navigable components from child nodes, not from whole scene. This makes it possible to partition
  569. // the scene into several navigation meshes
  570. PODVector<Navigable*> navigables;
  571. node_->GetComponents<Navigable>(navigables, true);
  572. HashSet<Node*> processedNodes;
  573. for (unsigned i = 0; i < navigables.Size(); ++i)
  574. {
  575. if (navigables[i]->IsEnabledEffective())
  576. CollectGeometries(geometryList, navigables[i]->GetNode(), processedNodes, navigables[i]->IsRecursive());
  577. }
  578. // Get offmesh connections
  579. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  580. PODVector<OffMeshConnection*> connections;
  581. node_->GetComponents<OffMeshConnection>(connections, true);
  582. for (unsigned i = 0; i < connections.Size(); ++i)
  583. {
  584. OffMeshConnection* connection = connections[i];
  585. if (connection->IsEnabledEffective() && connection->GetEndPoint())
  586. {
  587. const Matrix3x4& transform = connection->GetNode()->GetWorldTransform();
  588. NavigationGeometryInfo info;
  589. info.component_ = connection;
  590. info.boundingBox_ = BoundingBox(Sphere(transform.Translation(), connection->GetRadius())).Transformed(inverse);
  591. geometryList.Push(info);
  592. }
  593. }
  594. }
  595. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes, bool recursive)
  596. {
  597. // Make sure nodes are not included twice
  598. if (processedNodes.Contains(node))
  599. return;
  600. processedNodes.Insert(node);
  601. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  602. // Prefer compatible physics collision shapes (triangle mesh, convex hull, box) if found.
  603. // Then fallback to visible geometry
  604. PODVector<CollisionShape*> collisionShapes;
  605. node->GetComponents<CollisionShape>(collisionShapes);
  606. bool collisionShapeFound = false;
  607. for (unsigned i = 0; i < collisionShapes.Size(); ++i)
  608. {
  609. CollisionShape* shape = collisionShapes[i];
  610. if (!shape->IsEnabledEffective())
  611. continue;
  612. ShapeType type = shape->GetShapeType();
  613. if ((type == SHAPE_BOX || type == SHAPE_TRIANGLEMESH || type == SHAPE_CONVEXHULL) && shape->GetCollisionShape())
  614. {
  615. Matrix3x4 shapeTransform(shape->GetPosition(), shape->GetRotation(), shape->GetSize());
  616. NavigationGeometryInfo info;
  617. info.component_ = shape;
  618. info.transform_ = inverse * node->GetWorldTransform() * shapeTransform;
  619. info.boundingBox_ = shape->GetWorldBoundingBox().Transformed(inverse);
  620. geometryList.Push(info);
  621. collisionShapeFound = true;
  622. }
  623. }
  624. if (!collisionShapeFound)
  625. {
  626. PODVector<Drawable*> drawables;
  627. node->GetDerivedComponents<Drawable>(drawables);
  628. for (unsigned i = 0; i < drawables.Size(); ++i)
  629. {
  630. /// \todo Evaluate whether should handle other types. Now StaticModel & TerrainPatch are supported, others skipped
  631. Drawable* drawable = drawables[i];
  632. if (!drawable->IsEnabledEffective())
  633. continue;
  634. NavigationGeometryInfo info;
  635. if (drawable->GetType() == StaticModel::GetTypeStatic())
  636. info.lodLevel_ = static_cast<StaticModel*>(drawable)->GetOcclusionLodLevel();
  637. else if (drawable->GetType() == TerrainPatch::GetTypeStatic())
  638. info.lodLevel_ = 0;
  639. else
  640. continue;
  641. info.component_ = drawable;
  642. info.transform_ = inverse * node->GetWorldTransform();
  643. info.boundingBox_ = drawable->GetWorldBoundingBox().Transformed(inverse);
  644. geometryList.Push(info);
  645. }
  646. }
  647. if (recursive)
  648. {
  649. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  650. for(unsigned i = 0; i < children.Size(); ++i)
  651. CollectGeometries(geometryList, children[i], processedNodes, recursive);
  652. }
  653. }
  654. void NavigationMesh::GetTileGeometry(NavigationBuildData& build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box)
  655. {
  656. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  657. for (unsigned i = 0; i < geometryList.Size(); ++i)
  658. {
  659. if (box.IsInsideFast(geometryList[i].boundingBox_) != OUTSIDE)
  660. {
  661. const Matrix3x4& transform = geometryList[i].transform_;
  662. if (geometryList[i].component_->GetType() == OffMeshConnection::GetTypeStatic())
  663. {
  664. OffMeshConnection* connection = static_cast<OffMeshConnection*>(geometryList[i].component_);
  665. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  666. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  667. build.offMeshVertices_.Push(start);
  668. build.offMeshVertices_.Push(end);
  669. build.offMeshRadii_.Push(connection->GetRadius());
  670. /// \todo Allow to define custom flags
  671. build.offMeshFlags_.Push(0x1);
  672. build.offMeshAreas_.Push(0);
  673. build.offMeshDir_.Push(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0);
  674. continue;
  675. }
  676. CollisionShape* shape = dynamic_cast<CollisionShape*>(geometryList[i].component_);
  677. if (shape)
  678. {
  679. switch (shape->GetShapeType())
  680. {
  681. case SHAPE_TRIANGLEMESH:
  682. {
  683. Model* model = shape->GetModel();
  684. if (!model)
  685. continue;
  686. unsigned lodLevel = shape->GetLodLevel();
  687. for (unsigned j = 0; j < model->GetNumGeometries(); ++j)
  688. AddTriMeshGeometry(build, model->GetGeometry(j, lodLevel), transform);
  689. }
  690. break;
  691. case SHAPE_CONVEXHULL:
  692. {
  693. ConvexData* data = static_cast<ConvexData*>(shape->GetGeometryData());
  694. if (!data)
  695. continue;
  696. unsigned numVertices = data->vertexCount_;
  697. unsigned numIndices = data->indexCount_;
  698. unsigned destVertexStart = build.vertices_.Size();
  699. for (unsigned j = 0; j < numVertices; ++j)
  700. build.vertices_.Push(transform * data->vertexData_[j]);
  701. for (unsigned j = 0; j < numIndices; ++j)
  702. build.indices_.Push(data->indexData_[j] + destVertexStart);
  703. }
  704. break;
  705. case SHAPE_BOX:
  706. {
  707. unsigned destVertexStart = build.vertices_.Size();
  708. build.vertices_.Push(transform * Vector3(-0.5f, 0.5f, -0.5f));
  709. build.vertices_.Push(transform * Vector3(0.5f, 0.5f, -0.5f));
  710. build.vertices_.Push(transform * Vector3(0.5f, -0.5f, -0.5f));
  711. build.vertices_.Push(transform * Vector3(-0.5f, -0.5f, -0.5f));
  712. build.vertices_.Push(transform * Vector3(-0.5f, 0.5f, 0.5f));
  713. build.vertices_.Push(transform * Vector3(0.5f, 0.5f, 0.5f));
  714. build.vertices_.Push(transform * Vector3(0.5f, -0.5f, 0.5f));
  715. build.vertices_.Push(transform * Vector3(-0.5f, -0.5f, 0.5f));
  716. const unsigned indices[] = {
  717. 0, 1, 2, 0, 2, 3, 1, 5, 6, 1, 6, 2, 4, 5, 1, 4, 1, 0, 5, 4, 7, 5, 7, 6,
  718. 4, 0, 3, 4, 3, 7, 1, 0, 4, 1, 4, 5
  719. };
  720. for (unsigned j = 0; j < 36; ++j)
  721. build.indices_.Push(indices[j] + destVertexStart);
  722. }
  723. break;
  724. default:
  725. break;
  726. }
  727. continue;
  728. }
  729. Drawable* drawable = dynamic_cast<Drawable*>(geometryList[i].component_);
  730. if (drawable)
  731. {
  732. const Vector<SourceBatch>& batches = drawable->GetBatches();
  733. for (unsigned j = 0; j < batches.Size(); ++j)
  734. AddTriMeshGeometry(build, drawable->GetLodGeometry(j, geometryList[i].lodLevel_), transform);
  735. }
  736. }
  737. }
  738. }
  739. void NavigationMesh::AddTriMeshGeometry(NavigationBuildData& build, Geometry* geometry, const Matrix3x4& transform)
  740. {
  741. if (!geometry)
  742. return;
  743. const unsigned char* vertexData;
  744. const unsigned char* indexData;
  745. unsigned vertexSize;
  746. unsigned indexSize;
  747. unsigned elementMask;
  748. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  749. if (!vertexData || !indexData || (elementMask & MASK_POSITION) == 0)
  750. return;
  751. unsigned srcIndexStart = geometry->GetIndexStart();
  752. unsigned srcIndexCount = geometry->GetIndexCount();
  753. unsigned srcVertexStart = geometry->GetVertexStart();
  754. unsigned srcVertexCount = geometry->GetVertexCount();
  755. if (!srcIndexCount)
  756. return;
  757. unsigned destVertexStart = build.vertices_.Size();
  758. for (unsigned k = srcVertexStart; k < srcVertexStart + srcVertexCount; ++k)
  759. {
  760. Vector3 vertex = transform * *((const Vector3*)(&vertexData[k * vertexSize]));
  761. build.vertices_.Push(vertex);
  762. }
  763. // Copy remapped indices
  764. if (indexSize == sizeof(unsigned short))
  765. {
  766. const unsigned short* indices = ((const unsigned short*)indexData) + srcIndexStart;
  767. const unsigned short* indicesEnd = indices + srcIndexCount;
  768. while (indices < indicesEnd)
  769. {
  770. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  771. ++indices;
  772. }
  773. }
  774. else
  775. {
  776. const unsigned* indices = ((const unsigned*)indexData) + srcIndexStart;
  777. const unsigned* indicesEnd = indices + srcIndexCount;
  778. while (indices < indicesEnd)
  779. {
  780. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  781. ++indices;
  782. }
  783. }
  784. }
  785. bool NavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z)
  786. {
  787. PROFILE(BuildNavigationMeshTile);
  788. // Remove previous tile (if any)
  789. navMesh_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  790. float tileEdgeLength = (float)tileSize_ * cellSize_;
  791. BoundingBox tileBoundingBox(Vector3(
  792. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  793. boundingBox_.min_.y_,
  794. boundingBox_.min_.z_ + tileEdgeLength * (float)z
  795. ),
  796. Vector3(
  797. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  798. boundingBox_.max_.y_,
  799. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)
  800. ));
  801. NavigationBuildData build;
  802. rcConfig cfg;
  803. memset(&cfg, 0, sizeof cfg);
  804. cfg.cs = cellSize_;
  805. cfg.ch = cellHeight_;
  806. cfg.walkableSlopeAngle = agentMaxSlope_;
  807. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  808. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  809. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  810. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  811. cfg.maxSimplificationError = edgeMaxError_;
  812. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  813. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  814. cfg.maxVertsPerPoly = 6;
  815. cfg.tileSize = tileSize_;
  816. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  817. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  818. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  819. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  820. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  821. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  822. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  823. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  824. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  825. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  826. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  827. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  828. GetTileGeometry(build, geometryList, expandedBox);
  829. if (build.vertices_.Empty() || build.indices_.Empty())
  830. return true; // Nothing to do
  831. build.heightField_ = rcAllocHeightfield();
  832. if (!build.heightField_)
  833. {
  834. LOGERROR("Could not allocate heightfield");
  835. return false;
  836. }
  837. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  838. cfg.ch))
  839. {
  840. LOGERROR("Could not create heightfield");
  841. return false;
  842. }
  843. unsigned numTriangles = build.indices_.Size() / 3;
  844. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  845. memset(triAreas.Get(), 0, numTriangles);
  846. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  847. &build.indices_[0], numTriangles, triAreas.Get());
  848. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  849. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  850. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  851. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  852. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  853. build.compactHeightField_ = rcAllocCompactHeightfield();
  854. if (!build.compactHeightField_)
  855. {
  856. LOGERROR("Could not allocate create compact heightfield");
  857. return false;
  858. }
  859. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  860. *build.compactHeightField_))
  861. {
  862. LOGERROR("Could not build compact heightfield");
  863. return false;
  864. }
  865. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  866. {
  867. LOGERROR("Could not erode compact heightfield");
  868. return false;
  869. }
  870. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  871. {
  872. LOGERROR("Could not build distance field");
  873. return false;
  874. }
  875. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  876. cfg.mergeRegionArea))
  877. {
  878. LOGERROR("Could not build regions");
  879. return false;
  880. }
  881. build.contourSet_ = rcAllocContourSet();
  882. if (!build.contourSet_)
  883. {
  884. LOGERROR("Could not allocate contour set");
  885. return false;
  886. }
  887. if (!rcBuildContours(build.ctx_, *build.compactHeightField_, cfg.maxSimplificationError, cfg.maxEdgeLen,
  888. *build.contourSet_))
  889. {
  890. LOGERROR("Could not create contours");
  891. return false;
  892. }
  893. build.polyMesh_ = rcAllocPolyMesh();
  894. if (!build.polyMesh_)
  895. {
  896. LOGERROR("Could not allocate poly mesh");
  897. return false;
  898. }
  899. if (!rcBuildPolyMesh(build.ctx_, *build.contourSet_, cfg.maxVertsPerPoly, *build.polyMesh_))
  900. {
  901. LOGERROR("Could not triangulate contours");
  902. return false;
  903. }
  904. build.polyMeshDetail_ = rcAllocPolyMeshDetail();
  905. if (!build.polyMeshDetail_)
  906. {
  907. LOGERROR("Could not allocate detail mesh");
  908. return false;
  909. }
  910. if (!rcBuildPolyMeshDetail(build.ctx_, *build.polyMesh_, *build.compactHeightField_, cfg.detailSampleDist,
  911. cfg.detailSampleMaxError, *build.polyMeshDetail_))
  912. {
  913. LOGERROR("Could not build detail mesh");
  914. return false;
  915. }
  916. // Set polygon flags
  917. /// \todo Allow to define custom flags
  918. for (int i = 0; i < build.polyMesh_->npolys; ++i)
  919. {
  920. if (build.polyMesh_->areas[i] == RC_WALKABLE_AREA)
  921. build.polyMesh_->flags[i] = 0x1;
  922. }
  923. unsigned char* navData = 0;
  924. int navDataSize = 0;
  925. dtNavMeshCreateParams params;
  926. memset(&params, 0, sizeof params);
  927. params.verts = build.polyMesh_->verts;
  928. params.vertCount = build.polyMesh_->nverts;
  929. params.polys = build.polyMesh_->polys;
  930. params.polyAreas = build.polyMesh_->areas;
  931. params.polyFlags = build.polyMesh_->flags;
  932. params.polyCount = build.polyMesh_->npolys;
  933. params.nvp = build.polyMesh_->nvp;
  934. params.detailMeshes = build.polyMeshDetail_->meshes;
  935. params.detailVerts = build.polyMeshDetail_->verts;
  936. params.detailVertsCount = build.polyMeshDetail_->nverts;
  937. params.detailTris = build.polyMeshDetail_->tris;
  938. params.detailTriCount = build.polyMeshDetail_->ntris;
  939. params.walkableHeight = agentHeight_;
  940. params.walkableRadius = agentRadius_;
  941. params.walkableClimb = agentMaxClimb_;
  942. params.tileX = x;
  943. params.tileY = z;
  944. rcVcopy(params.bmin, build.polyMesh_->bmin);
  945. rcVcopy(params.bmax, build.polyMesh_->bmax);
  946. params.cs = cfg.cs;
  947. params.ch = cfg.ch;
  948. params.buildBvTree = true;
  949. // Add off-mesh connections if have them
  950. if (build.offMeshRadii_.Size())
  951. {
  952. params.offMeshConCount = build.offMeshRadii_.Size();
  953. params.offMeshConVerts = &build.offMeshVertices_[0].x_;
  954. params.offMeshConRad = &build.offMeshRadii_[0];
  955. params.offMeshConFlags = &build.offMeshFlags_[0];
  956. params.offMeshConAreas = &build.offMeshAreas_[0];
  957. params.offMeshConDir = &build.offMeshDir_[0];
  958. }
  959. if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
  960. {
  961. LOGERROR("Could not build navigation mesh tile data");
  962. return false;
  963. }
  964. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  965. {
  966. LOGERROR("Failed to add navigation mesh tile");
  967. dtFree(navData);
  968. return false;
  969. }
  970. return true;
  971. }
  972. bool NavigationMesh::InitializeQuery()
  973. {
  974. if (!navMesh_ || !node_)
  975. return false;
  976. if (navMeshQuery_)
  977. return true;
  978. navMeshQuery_ = dtAllocNavMeshQuery();
  979. if (!navMeshQuery_)
  980. {
  981. LOGERROR("Could not create navigation mesh query");
  982. return false;
  983. }
  984. if (dtStatusFailed(navMeshQuery_->init(navMesh_, MAX_POLYS)))
  985. {
  986. LOGERROR("Could not init navigation mesh query");
  987. return false;
  988. }
  989. return true;
  990. }
  991. void NavigationMesh::ReleaseNavigationMesh()
  992. {
  993. dtFreeNavMesh(navMesh_);
  994. navMesh_ = 0;
  995. dtFreeNavMeshQuery(navMeshQuery_);
  996. navMeshQuery_ = 0;
  997. numTilesX_ = 0;
  998. numTilesZ_ = 0;
  999. boundingBox_.min_ = boundingBox_.max_ = Vector3::ZERO;
  1000. boundingBox_.defined_ = false;
  1001. }
  1002. }