NavigationMesh.cpp 42 KB

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