2
0

NavigationMesh.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. #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 (!debug || !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. Vector3 NavigationMesh::FindNearestPoint(const Vector3& point, const Vector3& extents)
  384. {
  385. if(!InitializeQuery())
  386. return point;
  387. const Matrix3x4& transform = node_->GetWorldTransform();
  388. Matrix3x4 inverse = transform.Inverse();
  389. Vector3 localPoint = inverse * point;
  390. Vector3 nearestPoint;
  391. dtPolyRef pointRef;
  392. navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter_, &pointRef, &nearestPoint.x_);
  393. if (!pointRef)
  394. return point;
  395. return transform*nearestPoint;
  396. }
  397. Vector3 NavigationMesh::MoveAlongSurface(const Vector3& start, const Vector3& end, const Vector3& extents, int maxVisited)
  398. {
  399. if (!InitializeQuery())
  400. return end;
  401. const Matrix3x4& transform = node_->GetWorldTransform();
  402. Matrix3x4 inverse = transform.Inverse();
  403. Vector3 localStart = inverse * start;
  404. Vector3 localEnd = inverse * end;
  405. dtPolyRef startRef;
  406. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  407. if (!startRef)
  408. return end;
  409. Vector3 resultPos;
  410. int visitedCount = 0;
  411. maxVisited = Max(maxVisited, 0);
  412. PODVector<dtPolyRef> visited(maxVisited);
  413. navMeshQuery_->moveAlongSurface(startRef, &localStart.x_, &localEnd.x_, queryFilter_, &resultPos.x_, maxVisited ?
  414. &visited[0] : (dtPolyRef*)0, &visitedCount, maxVisited);
  415. return transform * resultPos;
  416. }
  417. void NavigationMesh::FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, const Vector3& extents)
  418. {
  419. PROFILE(FindPath);
  420. dest.Clear();
  421. if (!InitializeQuery())
  422. return;
  423. // Navigation data is in local space. Transform path points from world to local
  424. const Matrix3x4& transform = node_->GetWorldTransform();
  425. Matrix3x4 inverse = transform.Inverse();
  426. Vector3 localStart = inverse * start;
  427. Vector3 localEnd = inverse * end;
  428. dtPolyRef startRef;
  429. dtPolyRef endRef;
  430. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  431. navMeshQuery_->findNearestPoly(&localEnd.x_, &extents.x_, queryFilter_, &endRef, 0);
  432. if (!startRef || !endRef)
  433. return;
  434. int numPolys = 0;
  435. int numPathPoints = 0;
  436. navMeshQuery_->findPath(startRef, endRef, &localStart.x_, &localEnd.x_, queryFilter_, pathData_->polys_, &numPolys,
  437. MAX_POLYS);
  438. if (!numPolys)
  439. return;
  440. Vector3 actualLocalEnd = localEnd;
  441. // If full path was not found, clamp end point to the end polygon
  442. if (pathData_->polys_[numPolys - 1] != endRef)
  443. navMeshQuery_->closestPointOnPoly(pathData_->polys_[numPolys - 1], &localEnd.x_, &actualLocalEnd.x_);
  444. navMeshQuery_->findStraightPath(&localStart.x_, &actualLocalEnd.x_, pathData_->polys_, numPolys,
  445. &pathData_->pathPoints_[0].x_, pathData_->pathFlags_, pathData_->pathPolys_, &numPathPoints, MAX_POLYS);
  446. // Transform path result back to world space
  447. for (int i = 0; i < numPathPoints; ++i)
  448. dest.Push(transform * pathData_->pathPoints_[i]);
  449. }
  450. Vector3 NavigationMesh::GetRandomPoint()
  451. {
  452. if (!InitializeQuery())
  453. return Vector3::ZERO;
  454. dtPolyRef polyRef;
  455. Vector3 point(Vector3::ZERO);
  456. navMeshQuery_->findRandomPoint(queryFilter_, Random, &polyRef, &point.x_);
  457. return node_->GetWorldTransform() * point;
  458. }
  459. Vector3 NavigationMesh::GetRandomPointInCircle(const Vector3& center, float radius, const Vector3& extents)
  460. {
  461. if (!InitializeQuery())
  462. return center;
  463. const Matrix3x4& transform = node_->GetWorldTransform();
  464. Matrix3x4 inverse = transform.Inverse();
  465. Vector3 localCenter = inverse * center;
  466. dtPolyRef startRef;
  467. navMeshQuery_->findNearestPoly(&localCenter.x_, &extents.x_, queryFilter_, &startRef, 0);
  468. if (!startRef)
  469. return center;
  470. dtPolyRef polyRef;
  471. Vector3 point(localCenter);
  472. navMeshQuery_->findRandomPointAroundCircle(startRef, &localCenter.x_, radius, queryFilter_, Random, &polyRef, &point.x_);
  473. return transform * point;
  474. }
  475. float NavigationMesh::GetDistanceToWall(const Vector3& point, float radius, const Vector3& extents)
  476. {
  477. if (!InitializeQuery())
  478. return radius;
  479. const Matrix3x4& transform = node_->GetWorldTransform();
  480. Matrix3x4 inverse = transform.Inverse();
  481. Vector3 localPoint = inverse * point;
  482. dtPolyRef startRef;
  483. navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter_, &startRef, 0);
  484. if (!startRef)
  485. return radius;
  486. float hitDist = radius;
  487. Vector3 hitPos;
  488. Vector3 hitNormal;
  489. navMeshQuery_->findDistanceToWall(startRef, &localPoint.x_, radius, queryFilter_, &hitDist, &hitPos.x_, &hitNormal.x_);
  490. return hitDist;
  491. }
  492. Vector3 NavigationMesh::Raycast(const Vector3& start, const Vector3& end, const Vector3& extents)
  493. {
  494. if (!InitializeQuery())
  495. return end;
  496. const Matrix3x4& transform = node_->GetWorldTransform();
  497. Matrix3x4 inverse = transform.Inverse();
  498. Vector3 localStart = inverse * start;
  499. Vector3 localEnd = inverse * end;
  500. dtPolyRef startRef;
  501. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  502. if (!startRef)
  503. return end;
  504. Vector3 localHitNormal;
  505. float t;
  506. int numPolys;
  507. navMeshQuery_->raycast(startRef, &localStart.x_, &localEnd.x_, queryFilter_, &t, &localHitNormal.x_, pathData_->polys_, &numPolys, MAX_POLYS);
  508. if (t == FLT_MAX)
  509. t = 1.0f;
  510. return start.Lerp(end, t);
  511. }
  512. void NavigationMesh::DrawDebugGeometry(bool depthTest)
  513. {
  514. Scene* scene = GetScene();
  515. if (scene)
  516. {
  517. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  518. if (debug)
  519. DrawDebugGeometry(debug, depthTest);
  520. }
  521. }
  522. BoundingBox NavigationMesh::GetWorldBoundingBox() const
  523. {
  524. return node_ ? boundingBox_.Transformed(node_->GetWorldTransform()) : boundingBox_;
  525. }
  526. void NavigationMesh::SetNavigationDataAttr(PODVector<unsigned char> value)
  527. {
  528. ReleaseNavigationMesh();
  529. if (value.Empty())
  530. return;
  531. MemoryBuffer buffer(value);
  532. boundingBox_ = buffer.ReadBoundingBox();
  533. numTilesX_ = buffer.ReadInt();
  534. numTilesZ_ = buffer.ReadInt();
  535. dtNavMeshParams params;
  536. rcVcopy(params.orig, &boundingBox_.min_.x_);
  537. params.tileWidth = buffer.ReadFloat();
  538. params.tileHeight = buffer.ReadFloat();
  539. params.maxTiles = buffer.ReadInt();
  540. params.maxPolys = buffer.ReadInt();
  541. navMesh_ = dtAllocNavMesh();
  542. if (!navMesh_)
  543. {
  544. LOGERROR("Could not allocate navigation mesh");
  545. return;
  546. }
  547. if (dtStatusFailed(navMesh_->init(&params)))
  548. {
  549. LOGERROR("Could not initialize navigation mesh");
  550. ReleaseNavigationMesh();
  551. return;
  552. }
  553. unsigned numTiles = 0;
  554. while (!buffer.IsEof())
  555. {
  556. /*int x =*/ buffer.ReadInt();
  557. /*int z =*/ buffer.ReadInt();
  558. /*dtTileRef tileRef =*/ buffer.ReadUInt();
  559. unsigned navDataSize = buffer.ReadUInt();
  560. unsigned char* navData = (unsigned char*)dtAlloc(navDataSize, DT_ALLOC_PERM);
  561. if (!navData)
  562. {
  563. LOGERROR("Could not allocate data for navigation mesh tile");
  564. return;
  565. }
  566. buffer.Read(navData, navDataSize);
  567. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  568. {
  569. LOGERROR("Failed to add navigation mesh tile");
  570. dtFree(navData);
  571. return;
  572. }
  573. else
  574. ++numTiles;
  575. }
  576. LOGDEBUG("Created navigation mesh with " + String(numTiles) + " tiles from serialized data");
  577. }
  578. PODVector<unsigned char> NavigationMesh::GetNavigationDataAttr() const
  579. {
  580. VectorBuffer ret;
  581. if (navMesh_)
  582. {
  583. ret.WriteBoundingBox(boundingBox_);
  584. ret.WriteInt(numTilesX_);
  585. ret.WriteInt(numTilesZ_);
  586. const dtNavMeshParams* params = navMesh_->getParams();
  587. ret.WriteFloat(params->tileWidth);
  588. ret.WriteFloat(params->tileHeight);
  589. ret.WriteInt(params->maxTiles);
  590. ret.WriteInt(params->maxPolys);
  591. const dtNavMesh* navMesh = navMesh_;
  592. for (int z = 0; z < numTilesZ_; ++z)
  593. {
  594. for (int x = 0; x < numTilesX_; ++x)
  595. {
  596. const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);
  597. if (!tile)
  598. continue;
  599. ret.WriteInt(x);
  600. ret.WriteInt(z);
  601. ret.WriteUInt(navMesh->getTileRef(tile));
  602. ret.WriteUInt(tile->dataSize);
  603. ret.Write(tile->data, tile->dataSize);
  604. }
  605. }
  606. }
  607. return ret.GetBuffer();
  608. }
  609. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList)
  610. {
  611. PROFILE(CollectNavigationGeometry);
  612. // Get Navigable components from child nodes, not from whole scene. This makes it possible to partition
  613. // the scene into several navigation meshes
  614. PODVector<Navigable*> navigables;
  615. node_->GetComponents<Navigable>(navigables, true);
  616. HashSet<Node*> processedNodes;
  617. for (unsigned i = 0; i < navigables.Size(); ++i)
  618. {
  619. if (navigables[i]->IsEnabledEffective())
  620. CollectGeometries(geometryList, navigables[i]->GetNode(), processedNodes, navigables[i]->IsRecursive());
  621. }
  622. // Get offmesh connections
  623. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  624. PODVector<OffMeshConnection*> connections;
  625. node_->GetComponents<OffMeshConnection>(connections, true);
  626. for (unsigned i = 0; i < connections.Size(); ++i)
  627. {
  628. OffMeshConnection* connection = connections[i];
  629. if (connection->IsEnabledEffective() && connection->GetEndPoint())
  630. {
  631. const Matrix3x4& transform = connection->GetNode()->GetWorldTransform();
  632. NavigationGeometryInfo info;
  633. info.component_ = connection;
  634. info.boundingBox_ = BoundingBox(Sphere(transform.Translation(), connection->GetRadius())).Transformed(inverse);
  635. geometryList.Push(info);
  636. }
  637. }
  638. }
  639. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes, bool recursive)
  640. {
  641. // Make sure nodes are not included twice
  642. if (processedNodes.Contains(node))
  643. return;
  644. processedNodes.Insert(node);
  645. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  646. // Prefer compatible physics collision shapes (triangle mesh, convex hull, box) if found.
  647. // Then fallback to visible geometry
  648. PODVector<CollisionShape*> collisionShapes;
  649. node->GetComponents<CollisionShape>(collisionShapes);
  650. bool collisionShapeFound = false;
  651. for (unsigned i = 0; i < collisionShapes.Size(); ++i)
  652. {
  653. CollisionShape* shape = collisionShapes[i];
  654. if (!shape->IsEnabledEffective())
  655. continue;
  656. ShapeType type = shape->GetShapeType();
  657. if ((type == SHAPE_BOX || type == SHAPE_TRIANGLEMESH || type == SHAPE_CONVEXHULL) && shape->GetCollisionShape())
  658. {
  659. Matrix3x4 shapeTransform(shape->GetPosition(), shape->GetRotation(), shape->GetSize());
  660. NavigationGeometryInfo info;
  661. info.component_ = shape;
  662. info.transform_ = inverse * node->GetWorldTransform() * shapeTransform;
  663. info.boundingBox_ = shape->GetWorldBoundingBox().Transformed(inverse);
  664. geometryList.Push(info);
  665. collisionShapeFound = true;
  666. }
  667. }
  668. if (!collisionShapeFound)
  669. {
  670. PODVector<Drawable*> drawables;
  671. node->GetDerivedComponents<Drawable>(drawables);
  672. for (unsigned i = 0; i < drawables.Size(); ++i)
  673. {
  674. /// \todo Evaluate whether should handle other types. Now StaticModel & TerrainPatch are supported, others skipped
  675. Drawable* drawable = drawables[i];
  676. if (!drawable->IsEnabledEffective())
  677. continue;
  678. NavigationGeometryInfo info;
  679. if (drawable->GetType() == StaticModel::GetTypeStatic())
  680. info.lodLevel_ = static_cast<StaticModel*>(drawable)->GetOcclusionLodLevel();
  681. else if (drawable->GetType() == TerrainPatch::GetTypeStatic())
  682. info.lodLevel_ = 0;
  683. else
  684. continue;
  685. info.component_ = drawable;
  686. info.transform_ = inverse * node->GetWorldTransform();
  687. info.boundingBox_ = drawable->GetWorldBoundingBox().Transformed(inverse);
  688. geometryList.Push(info);
  689. }
  690. }
  691. if (recursive)
  692. {
  693. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  694. for(unsigned i = 0; i < children.Size(); ++i)
  695. CollectGeometries(geometryList, children[i], processedNodes, recursive);
  696. }
  697. }
  698. void NavigationMesh::GetTileGeometry(NavigationBuildData& build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box)
  699. {
  700. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  701. for (unsigned i = 0; i < geometryList.Size(); ++i)
  702. {
  703. if (box.IsInsideFast(geometryList[i].boundingBox_) != OUTSIDE)
  704. {
  705. const Matrix3x4& transform = geometryList[i].transform_;
  706. if (geometryList[i].component_->GetType() == OffMeshConnection::GetTypeStatic())
  707. {
  708. OffMeshConnection* connection = static_cast<OffMeshConnection*>(geometryList[i].component_);
  709. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  710. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  711. build.offMeshVertices_.Push(start);
  712. build.offMeshVertices_.Push(end);
  713. build.offMeshRadii_.Push(connection->GetRadius());
  714. /// \todo Allow to define custom flags
  715. build.offMeshFlags_.Push(0x1);
  716. build.offMeshAreas_.Push(0);
  717. build.offMeshDir_.Push(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0);
  718. continue;
  719. }
  720. CollisionShape* shape = dynamic_cast<CollisionShape*>(geometryList[i].component_);
  721. if (shape)
  722. {
  723. switch (shape->GetShapeType())
  724. {
  725. case SHAPE_TRIANGLEMESH:
  726. {
  727. Model* model = shape->GetModel();
  728. if (!model)
  729. continue;
  730. unsigned lodLevel = shape->GetLodLevel();
  731. for (unsigned j = 0; j < model->GetNumGeometries(); ++j)
  732. AddTriMeshGeometry(build, model->GetGeometry(j, lodLevel), transform);
  733. }
  734. break;
  735. case SHAPE_CONVEXHULL:
  736. {
  737. ConvexData* data = static_cast<ConvexData*>(shape->GetGeometryData());
  738. if (!data)
  739. continue;
  740. unsigned numVertices = data->vertexCount_;
  741. unsigned numIndices = data->indexCount_;
  742. unsigned destVertexStart = build.vertices_.Size();
  743. for (unsigned j = 0; j < numVertices; ++j)
  744. build.vertices_.Push(transform * data->vertexData_[j]);
  745. for (unsigned j = 0; j < numIndices; ++j)
  746. build.indices_.Push(data->indexData_[j] + destVertexStart);
  747. }
  748. break;
  749. case SHAPE_BOX:
  750. {
  751. unsigned destVertexStart = build.vertices_.Size();
  752. build.vertices_.Push(transform * Vector3(-0.5f, 0.5f, -0.5f));
  753. build.vertices_.Push(transform * Vector3(0.5f, 0.5f, -0.5f));
  754. build.vertices_.Push(transform * Vector3(0.5f, -0.5f, -0.5f));
  755. build.vertices_.Push(transform * Vector3(-0.5f, -0.5f, -0.5f));
  756. build.vertices_.Push(transform * Vector3(-0.5f, 0.5f, 0.5f));
  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. const unsigned indices[] = {
  761. 0, 1, 2, 0, 2, 3, 1, 5, 6, 1, 6, 2, 4, 5, 1, 4, 1, 0, 5, 4, 7, 5, 7, 6,
  762. 4, 0, 3, 4, 3, 7, 1, 0, 4, 1, 4, 5
  763. };
  764. for (unsigned j = 0; j < 36; ++j)
  765. build.indices_.Push(indices[j] + destVertexStart);
  766. }
  767. break;
  768. default:
  769. break;
  770. }
  771. continue;
  772. }
  773. Drawable* drawable = dynamic_cast<Drawable*>(geometryList[i].component_);
  774. if (drawable)
  775. {
  776. const Vector<SourceBatch>& batches = drawable->GetBatches();
  777. for (unsigned j = 0; j < batches.Size(); ++j)
  778. AddTriMeshGeometry(build, drawable->GetLodGeometry(j, geometryList[i].lodLevel_), transform);
  779. }
  780. }
  781. }
  782. }
  783. void NavigationMesh::AddTriMeshGeometry(NavigationBuildData& build, Geometry* geometry, const Matrix3x4& transform)
  784. {
  785. if (!geometry)
  786. return;
  787. const unsigned char* vertexData;
  788. const unsigned char* indexData;
  789. unsigned vertexSize;
  790. unsigned indexSize;
  791. unsigned elementMask;
  792. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  793. if (!vertexData || !indexData || (elementMask & MASK_POSITION) == 0)
  794. return;
  795. unsigned srcIndexStart = geometry->GetIndexStart();
  796. unsigned srcIndexCount = geometry->GetIndexCount();
  797. unsigned srcVertexStart = geometry->GetVertexStart();
  798. unsigned srcVertexCount = geometry->GetVertexCount();
  799. if (!srcIndexCount)
  800. return;
  801. unsigned destVertexStart = build.vertices_.Size();
  802. for (unsigned k = srcVertexStart; k < srcVertexStart + srcVertexCount; ++k)
  803. {
  804. Vector3 vertex = transform * *((const Vector3*)(&vertexData[k * vertexSize]));
  805. build.vertices_.Push(vertex);
  806. }
  807. // Copy remapped indices
  808. if (indexSize == sizeof(unsigned short))
  809. {
  810. const unsigned short* indices = ((const unsigned short*)indexData) + srcIndexStart;
  811. const unsigned short* indicesEnd = indices + srcIndexCount;
  812. while (indices < indicesEnd)
  813. {
  814. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  815. ++indices;
  816. }
  817. }
  818. else
  819. {
  820. const unsigned* indices = ((const unsigned*)indexData) + srcIndexStart;
  821. const unsigned* indicesEnd = indices + srcIndexCount;
  822. while (indices < indicesEnd)
  823. {
  824. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  825. ++indices;
  826. }
  827. }
  828. }
  829. bool NavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z)
  830. {
  831. PROFILE(BuildNavigationMeshTile);
  832. // Remove previous tile (if any)
  833. navMesh_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  834. float tileEdgeLength = (float)tileSize_ * cellSize_;
  835. BoundingBox tileBoundingBox(Vector3(
  836. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  837. boundingBox_.min_.y_,
  838. boundingBox_.min_.z_ + tileEdgeLength * (float)z
  839. ),
  840. Vector3(
  841. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  842. boundingBox_.max_.y_,
  843. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)
  844. ));
  845. NavigationBuildData build;
  846. rcConfig cfg;
  847. memset(&cfg, 0, sizeof cfg);
  848. cfg.cs = cellSize_;
  849. cfg.ch = cellHeight_;
  850. cfg.walkableSlopeAngle = agentMaxSlope_;
  851. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  852. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  853. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  854. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  855. cfg.maxSimplificationError = edgeMaxError_;
  856. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  857. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  858. cfg.maxVertsPerPoly = 6;
  859. cfg.tileSize = tileSize_;
  860. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  861. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  862. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  863. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  864. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  865. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  866. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  867. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  868. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  869. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  870. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  871. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  872. GetTileGeometry(build, geometryList, expandedBox);
  873. if (build.vertices_.Empty() || build.indices_.Empty())
  874. return true; // Nothing to do
  875. build.heightField_ = rcAllocHeightfield();
  876. if (!build.heightField_)
  877. {
  878. LOGERROR("Could not allocate heightfield");
  879. return false;
  880. }
  881. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  882. cfg.ch))
  883. {
  884. LOGERROR("Could not create heightfield");
  885. return false;
  886. }
  887. unsigned numTriangles = build.indices_.Size() / 3;
  888. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  889. memset(triAreas.Get(), 0, numTriangles);
  890. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  891. &build.indices_[0], numTriangles, triAreas.Get());
  892. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  893. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  894. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  895. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  896. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  897. build.compactHeightField_ = rcAllocCompactHeightfield();
  898. if (!build.compactHeightField_)
  899. {
  900. LOGERROR("Could not allocate create compact heightfield");
  901. return false;
  902. }
  903. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  904. *build.compactHeightField_))
  905. {
  906. LOGERROR("Could not build compact heightfield");
  907. return false;
  908. }
  909. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  910. {
  911. LOGERROR("Could not erode compact heightfield");
  912. return false;
  913. }
  914. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  915. {
  916. LOGERROR("Could not build distance field");
  917. return false;
  918. }
  919. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  920. cfg.mergeRegionArea))
  921. {
  922. LOGERROR("Could not build regions");
  923. return false;
  924. }
  925. build.contourSet_ = rcAllocContourSet();
  926. if (!build.contourSet_)
  927. {
  928. LOGERROR("Could not allocate contour set");
  929. return false;
  930. }
  931. if (!rcBuildContours(build.ctx_, *build.compactHeightField_, cfg.maxSimplificationError, cfg.maxEdgeLen,
  932. *build.contourSet_))
  933. {
  934. LOGERROR("Could not create contours");
  935. return false;
  936. }
  937. build.polyMesh_ = rcAllocPolyMesh();
  938. if (!build.polyMesh_)
  939. {
  940. LOGERROR("Could not allocate poly mesh");
  941. return false;
  942. }
  943. if (!rcBuildPolyMesh(build.ctx_, *build.contourSet_, cfg.maxVertsPerPoly, *build.polyMesh_))
  944. {
  945. LOGERROR("Could not triangulate contours");
  946. return false;
  947. }
  948. build.polyMeshDetail_ = rcAllocPolyMeshDetail();
  949. if (!build.polyMeshDetail_)
  950. {
  951. LOGERROR("Could not allocate detail mesh");
  952. return false;
  953. }
  954. if (!rcBuildPolyMeshDetail(build.ctx_, *build.polyMesh_, *build.compactHeightField_, cfg.detailSampleDist,
  955. cfg.detailSampleMaxError, *build.polyMeshDetail_))
  956. {
  957. LOGERROR("Could not build detail mesh");
  958. return false;
  959. }
  960. // Set polygon flags
  961. /// \todo Allow to define custom flags
  962. for (int i = 0; i < build.polyMesh_->npolys; ++i)
  963. {
  964. if (build.polyMesh_->areas[i] == RC_WALKABLE_AREA)
  965. build.polyMesh_->flags[i] = 0x1;
  966. }
  967. unsigned char* navData = 0;
  968. int navDataSize = 0;
  969. dtNavMeshCreateParams params;
  970. memset(&params, 0, sizeof params);
  971. params.verts = build.polyMesh_->verts;
  972. params.vertCount = build.polyMesh_->nverts;
  973. params.polys = build.polyMesh_->polys;
  974. params.polyAreas = build.polyMesh_->areas;
  975. params.polyFlags = build.polyMesh_->flags;
  976. params.polyCount = build.polyMesh_->npolys;
  977. params.nvp = build.polyMesh_->nvp;
  978. params.detailMeshes = build.polyMeshDetail_->meshes;
  979. params.detailVerts = build.polyMeshDetail_->verts;
  980. params.detailVertsCount = build.polyMeshDetail_->nverts;
  981. params.detailTris = build.polyMeshDetail_->tris;
  982. params.detailTriCount = build.polyMeshDetail_->ntris;
  983. params.walkableHeight = agentHeight_;
  984. params.walkableRadius = agentRadius_;
  985. params.walkableClimb = agentMaxClimb_;
  986. params.tileX = x;
  987. params.tileY = z;
  988. rcVcopy(params.bmin, build.polyMesh_->bmin);
  989. rcVcopy(params.bmax, build.polyMesh_->bmax);
  990. params.cs = cfg.cs;
  991. params.ch = cfg.ch;
  992. params.buildBvTree = true;
  993. // Add off-mesh connections if have them
  994. if (build.offMeshRadii_.Size())
  995. {
  996. params.offMeshConCount = build.offMeshRadii_.Size();
  997. params.offMeshConVerts = &build.offMeshVertices_[0].x_;
  998. params.offMeshConRad = &build.offMeshRadii_[0];
  999. params.offMeshConFlags = &build.offMeshFlags_[0];
  1000. params.offMeshConAreas = &build.offMeshAreas_[0];
  1001. params.offMeshConDir = &build.offMeshDir_[0];
  1002. }
  1003. if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
  1004. {
  1005. LOGERROR("Could not build navigation mesh tile data");
  1006. return false;
  1007. }
  1008. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  1009. {
  1010. LOGERROR("Failed to add navigation mesh tile");
  1011. dtFree(navData);
  1012. return false;
  1013. }
  1014. return true;
  1015. }
  1016. bool NavigationMesh::InitializeQuery()
  1017. {
  1018. if (!navMesh_ || !node_)
  1019. return false;
  1020. if (navMeshQuery_)
  1021. return true;
  1022. navMeshQuery_ = dtAllocNavMeshQuery();
  1023. if (!navMeshQuery_)
  1024. {
  1025. LOGERROR("Could not create navigation mesh query");
  1026. return false;
  1027. }
  1028. if (dtStatusFailed(navMeshQuery_->init(navMesh_, MAX_POLYS)))
  1029. {
  1030. LOGERROR("Could not init navigation mesh query");
  1031. return false;
  1032. }
  1033. return true;
  1034. }
  1035. void NavigationMesh::ReleaseNavigationMesh()
  1036. {
  1037. dtFreeNavMesh(navMesh_);
  1038. navMesh_ = 0;
  1039. dtFreeNavMeshQuery(navMeshQuery_);
  1040. navMeshQuery_ = 0;
  1041. numTilesX_ = 0;
  1042. numTilesZ_ = 0;
  1043. boundingBox_.min_ = boundingBox_.max_ = Vector3::ZERO;
  1044. boundingBox_.defined_ = false;
  1045. }
  1046. }