NavigationMesh.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "CollisionShape.h"
  24. #include "Context.h"
  25. #include "DebugRenderer.h"
  26. #include "Drawable.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "MemoryBuffer.h"
  30. #include "Model.h"
  31. #include "Navigable.h"
  32. #include "NavigationMesh.h"
  33. #include "OffMeshConnection.h"
  34. #include "Profiler.h"
  35. #include "Scene.h"
  36. #include "StaticModel.h"
  37. #include "TerrainPatch.h"
  38. #include "VectorBuffer.h"
  39. #include <cfloat>
  40. #include <DetourNavMesh.h>
  41. #include <DetourNavMeshBuilder.h>
  42. #include <DetourNavMeshQuery.h>
  43. #include <Recast.h>
  44. #include "DebugNew.h"
  45. namespace Urho3D
  46. {
  47. extern const char* NAVIGATION_CATEGORY;
  48. static const int DEFAULT_TILE_SIZE = 128;
  49. static const float DEFAULT_CELL_SIZE = 0.3f;
  50. static const float DEFAULT_CELL_HEIGHT = 0.2f;
  51. static const float DEFAULT_AGENT_HEIGHT = 2.0f;
  52. static const float DEFAULT_AGENT_RADIUS = 0.6f;
  53. static const float DEFAULT_AGENT_MAX_CLIMB = 0.9f;
  54. static const float DEFAULT_AGENT_MAX_SLOPE = 45.0f;
  55. static const float DEFAULT_REGION_MIN_SIZE = 8.0f;
  56. static const float DEFAULT_REGION_MERGE_SIZE = 20.0f;
  57. static const float DEFAULT_EDGE_MAX_LENGTH = 12.0f;
  58. static const float DEFAULT_EDGE_MAX_ERROR = 1.3f;
  59. static const float DEFAULT_DETAIL_SAMPLE_DISTANCE = 6.0f;
  60. static const float DEFAULT_DETAIL_SAMPLE_MAX_ERROR = 1.0f;
  61. static const int MAX_POLYS = 2048;
  62. /// Temporary data for building one tile of the navigation mesh.
  63. struct NavigationBuildData
  64. {
  65. /// Construct.
  66. NavigationBuildData() :
  67. ctx_(new rcContext(false)),
  68. heightField_(0),
  69. compactHeightField_(0),
  70. contourSet_(0),
  71. polyMesh_(0),
  72. polyMeshDetail_(0)
  73. {
  74. }
  75. /// Destruct.
  76. ~NavigationBuildData()
  77. {
  78. delete(ctx_);
  79. rcFreeHeightField(heightField_);
  80. rcFreeCompactHeightfield(compactHeightField_);
  81. rcFreeContourSet(contourSet_);
  82. rcFreePolyMesh(polyMesh_);
  83. rcFreePolyMeshDetail(polyMeshDetail_);
  84. ctx_ = 0;
  85. heightField_ = 0;
  86. compactHeightField_ = 0;
  87. contourSet_ = 0;
  88. polyMesh_ = 0;
  89. polyMeshDetail_ = 0;
  90. }
  91. /// World-space bounding box of the navigation mesh tile.
  92. BoundingBox worldBoundingBox_;
  93. /// Vertices from geometries.
  94. PODVector<Vector3> vertices_;
  95. /// Triangle indices from geometries.
  96. PODVector<int> indices_;
  97. /// Offmesh connection vertices.
  98. PODVector<Vector3> offMeshVertices_;
  99. /// Offmesh connection radii.
  100. PODVector<float> offMeshRadii_;
  101. /// Offmesh connection flags.
  102. PODVector<unsigned short> offMeshFlags_;
  103. /// Offmesh connection areas.
  104. PODVector<unsigned char> offMeshAreas_;
  105. /// Offmesh connection direction.
  106. PODVector<unsigned char> offMeshDir_;
  107. /// Recast context.
  108. rcContext* ctx_;
  109. /// Recast heightfield.
  110. rcHeightfield* heightField_;
  111. /// Recast compact heightfield.
  112. rcCompactHeightfield* compactHeightField_;
  113. /// Recast contour set.
  114. rcContourSet* contourSet_;
  115. /// Recast poly mesh.
  116. rcPolyMesh* polyMesh_;
  117. /// Recast detail poly mesh.
  118. rcPolyMeshDetail* polyMeshDetail_;
  119. };
  120. /// Temporary data for finding a path.
  121. struct FindPathData
  122. {
  123. // Polygons.
  124. dtPolyRef polys_[MAX_POLYS];
  125. // Polygons on the path.
  126. dtPolyRef pathPolys_[MAX_POLYS];
  127. // Points on the path.
  128. Vector3 pathPoints_[MAX_POLYS];
  129. // Flags on the path.
  130. unsigned char pathFlags_[MAX_POLYS];
  131. };
  132. NavigationMesh::NavigationMesh(Context* context) :
  133. Component(context),
  134. navMesh_(0),
  135. navMeshQuery_(0),
  136. queryFilter_(new dtQueryFilter()),
  137. pathData_(new FindPathData()),
  138. tileSize_(DEFAULT_TILE_SIZE),
  139. cellSize_(DEFAULT_CELL_SIZE),
  140. cellHeight_(DEFAULT_CELL_HEIGHT),
  141. agentHeight_(DEFAULT_AGENT_HEIGHT),
  142. agentRadius_(DEFAULT_AGENT_RADIUS),
  143. agentMaxClimb_(DEFAULT_AGENT_MAX_CLIMB),
  144. agentMaxSlope_(DEFAULT_AGENT_MAX_SLOPE),
  145. regionMinSize_(DEFAULT_REGION_MIN_SIZE),
  146. regionMergeSize_(DEFAULT_REGION_MERGE_SIZE),
  147. edgeMaxLength_(DEFAULT_EDGE_MAX_LENGTH),
  148. edgeMaxError_(DEFAULT_EDGE_MAX_ERROR),
  149. detailSampleDistance_(DEFAULT_DETAIL_SAMPLE_DISTANCE),
  150. detailSampleMaxError_(DEFAULT_DETAIL_SAMPLE_MAX_ERROR),
  151. padding_(Vector3::ONE),
  152. numTilesX_(0),
  153. numTilesZ_(0)
  154. {
  155. }
  156. NavigationMesh::~NavigationMesh()
  157. {
  158. ReleaseNavigationMesh();
  159. delete queryFilter_;
  160. queryFilter_ = 0;
  161. delete pathData_;
  162. pathData_ = 0;
  163. }
  164. void NavigationMesh::RegisterObject(Context* context)
  165. {
  166. context->RegisterFactory<NavigationMesh>(NAVIGATION_CATEGORY);
  167. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_INT, "Tile Size", GetTileSize, SetTileSize, int, DEFAULT_TILE_SIZE, AM_DEFAULT);
  168. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Cell Size", GetCellSize, SetCellSize, float, DEFAULT_CELL_SIZE, AM_DEFAULT);
  169. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Cell Height", GetCellHeight, SetCellHeight, float, DEFAULT_CELL_HEIGHT, AM_DEFAULT);
  170. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Height", GetAgentHeight, SetAgentHeight, float, DEFAULT_AGENT_HEIGHT, AM_DEFAULT);
  171. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Radius", GetAgentRadius, SetAgentRadius, float, DEFAULT_AGENT_RADIUS, AM_DEFAULT);
  172. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Max Climb", GetAgentMaxClimb, SetAgentMaxClimb, float, DEFAULT_AGENT_MAX_CLIMB, AM_DEFAULT);
  173. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Max Slope", GetAgentMaxSlope, SetAgentMaxSlope, float, DEFAULT_AGENT_MAX_SLOPE, AM_DEFAULT);
  174. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Region Min Size", GetRegionMinSize, SetRegionMinSize, float, DEFAULT_REGION_MIN_SIZE, AM_DEFAULT);
  175. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Region Merge Size", GetRegionMergeSize, SetRegionMergeSize, float, DEFAULT_REGION_MERGE_SIZE, AM_DEFAULT);
  176. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Edge Max Length", GetEdgeMaxLength, SetEdgeMaxLength, float, DEFAULT_EDGE_MAX_LENGTH, AM_DEFAULT);
  177. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Edge Max Error", GetEdgeMaxError, SetEdgeMaxError, float, DEFAULT_EDGE_MAX_ERROR, AM_DEFAULT);
  178. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Detail Sample Distance", GetDetailSampleDistance, SetDetailSampleDistance, float, DEFAULT_DETAIL_SAMPLE_DISTANCE, AM_DEFAULT);
  179. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Detail Sample Max Error", GetDetailSampleMaxError, SetDetailSampleMaxError, float, DEFAULT_DETAIL_SAMPLE_MAX_ERROR, AM_DEFAULT);
  180. REF_ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_VECTOR3, "Bounding Box Padding", GetPadding, SetPadding, Vector3, Vector3::ONE, AM_DEFAULT);
  181. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_BUFFER, "Navigation Data", GetNavigationDataAttr, SetNavigationDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  182. }
  183. void NavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  184. {
  185. if (!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. dtPolyRef visited[maxVisited];
  412. navMeshQuery_->moveAlongSurface(startRef, &localStart.x_, &localEnd.x_, queryFilter_, &resultPos.x_, visited, &visitedCount, maxVisited);
  413. return transform*resultPos;
  414. }
  415. void NavigationMesh::FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, const Vector3& extents)
  416. {
  417. PROFILE(FindPath);
  418. dest.Clear();
  419. if (!InitializeQuery())
  420. return;
  421. // Navigation data is in local space. Transform path points from world to local
  422. const Matrix3x4& transform = node_->GetWorldTransform();
  423. Matrix3x4 inverse = transform.Inverse();
  424. Vector3 localStart = inverse * start;
  425. Vector3 localEnd = inverse * end;
  426. dtPolyRef startRef;
  427. dtPolyRef endRef;
  428. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  429. navMeshQuery_->findNearestPoly(&localEnd.x_, &extents.x_, queryFilter_, &endRef, 0);
  430. if (!startRef || !endRef)
  431. return;
  432. int numPolys = 0;
  433. int numPathPoints = 0;
  434. navMeshQuery_->findPath(startRef, endRef, &localStart.x_, &localEnd.x_, queryFilter_, pathData_->polys_, &numPolys,
  435. MAX_POLYS);
  436. if (!numPolys)
  437. return;
  438. Vector3 actualLocalEnd = localEnd;
  439. // If full path was not found, clamp end point to the end polygon
  440. if (pathData_->polys_[numPolys - 1] != endRef)
  441. navMeshQuery_->closestPointOnPoly(pathData_->polys_[numPolys - 1], &localEnd.x_, &actualLocalEnd.x_);
  442. navMeshQuery_->findStraightPath(&localStart.x_, &actualLocalEnd.x_, pathData_->polys_, numPolys,
  443. &pathData_->pathPoints_[0].x_, pathData_->pathFlags_, pathData_->pathPolys_, &numPathPoints, MAX_POLYS);
  444. // Transform path result back to world space
  445. for (int i = 0; i < numPathPoints; ++i)
  446. dest.Push(transform * pathData_->pathPoints_[i]);
  447. }
  448. Vector3 NavigationMesh::GetRandomPoint()
  449. {
  450. if (!InitializeQuery())
  451. return Vector3::ZERO;
  452. dtPolyRef polyRef;
  453. Vector3 point(Vector3::ZERO);
  454. navMeshQuery_->findRandomPoint(queryFilter_, Random, &polyRef, &point.x_);
  455. return node_->GetWorldTransform() * point;
  456. }
  457. Vector3 NavigationMesh::GetRandomPointInCircle(const Vector3& center, float radius, const Vector3& extents)
  458. {
  459. if (!InitializeQuery())
  460. return center;
  461. const Matrix3x4& transform = node_->GetWorldTransform();
  462. Matrix3x4 inverse = transform.Inverse();
  463. Vector3 localCenter = inverse * center;
  464. dtPolyRef startRef;
  465. navMeshQuery_->findNearestPoly(&localCenter.x_, &extents.x_, queryFilter_, &startRef, 0);
  466. if (!startRef)
  467. return center;
  468. dtPolyRef polyRef;
  469. Vector3 point(localCenter);
  470. navMeshQuery_->findRandomPointAroundCircle(startRef, &localCenter.x_, radius, queryFilter_, Random, &polyRef, &point.x_);
  471. return transform * point;
  472. }
  473. float NavigationMesh::GetDistanceToWall(const Vector3& point, float radius, const Vector3& extents)
  474. {
  475. if (!InitializeQuery())
  476. return radius;
  477. const Matrix3x4& transform = node_->GetWorldTransform();
  478. Matrix3x4 inverse = transform.Inverse();
  479. Vector3 localPoint = inverse * point;
  480. dtPolyRef startRef;
  481. navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter_, &startRef, 0);
  482. if (!startRef)
  483. return radius;
  484. float hitDist = radius;
  485. Vector3 hitPos;
  486. Vector3 hitNormal;
  487. navMeshQuery_->findDistanceToWall(startRef, &localPoint.x_, radius, queryFilter_, &hitDist, &hitPos.x_, &hitNormal.x_);
  488. return hitDist;
  489. }
  490. Vector3 NavigationMesh::Raycast(const Vector3& start, const Vector3& end, const Vector3& extents)
  491. {
  492. if (!InitializeQuery())
  493. return end;
  494. const Matrix3x4& transform = node_->GetWorldTransform();
  495. Matrix3x4 inverse = transform.Inverse();
  496. Vector3 localStart = inverse * start;
  497. Vector3 localEnd = inverse * end;
  498. dtPolyRef startRef;
  499. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  500. if (!startRef)
  501. return end;
  502. Vector3 localHitNormal;
  503. float t;
  504. int numPolys;
  505. navMeshQuery_->raycast(startRef, &localStart.x_, &localEnd.x_, queryFilter_, &t, &localHitNormal.x_, pathData_->polys_, &numPolys, MAX_POLYS);
  506. if (t == FLT_MAX)
  507. t = 1.0f;
  508. return start.Lerp(end, t);
  509. }
  510. void NavigationMesh::DrawDebugGeometry(bool depthTest)
  511. {
  512. Scene* scene = GetScene();
  513. if (scene)
  514. {
  515. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  516. if (debug)
  517. DrawDebugGeometry(debug, depthTest);
  518. }
  519. }
  520. BoundingBox NavigationMesh::GetWorldBoundingBox() const
  521. {
  522. return node_ ? boundingBox_.Transformed(node_->GetWorldTransform()) : boundingBox_;
  523. }
  524. void NavigationMesh::SetNavigationDataAttr(PODVector<unsigned char> value)
  525. {
  526. ReleaseNavigationMesh();
  527. if (value.Empty())
  528. return;
  529. MemoryBuffer buffer(value);
  530. boundingBox_ = buffer.ReadBoundingBox();
  531. numTilesX_ = buffer.ReadInt();
  532. numTilesZ_ = buffer.ReadInt();
  533. dtNavMeshParams params;
  534. rcVcopy(params.orig, &boundingBox_.min_.x_);
  535. params.tileWidth = buffer.ReadFloat();
  536. params.tileHeight = buffer.ReadFloat();
  537. params.maxTiles = buffer.ReadInt();
  538. params.maxPolys = buffer.ReadInt();
  539. navMesh_ = dtAllocNavMesh();
  540. if (!navMesh_)
  541. {
  542. LOGERROR("Could not allocate navigation mesh");
  543. return;
  544. }
  545. if (dtStatusFailed(navMesh_->init(&params)))
  546. {
  547. LOGERROR("Could not initialize navigation mesh");
  548. ReleaseNavigationMesh();
  549. return;
  550. }
  551. unsigned numTiles = 0;
  552. while (!buffer.IsEof())
  553. {
  554. /*int x =*/ buffer.ReadInt();
  555. /*int z =*/ buffer.ReadInt();
  556. /*dtTileRef tileRef =*/ buffer.ReadUInt();
  557. unsigned navDataSize = buffer.ReadUInt();
  558. unsigned char* navData = (unsigned char*)dtAlloc(navDataSize, DT_ALLOC_PERM);
  559. if (!navData)
  560. {
  561. LOGERROR("Could not allocate data for navigation mesh tile");
  562. return;
  563. }
  564. buffer.Read(navData, navDataSize);
  565. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  566. {
  567. LOGERROR("Failed to add navigation mesh tile");
  568. dtFree(navData);
  569. return;
  570. }
  571. else
  572. ++numTiles;
  573. }
  574. LOGDEBUG("Created navigation mesh with " + String(numTiles) + " tiles from serialized data");
  575. }
  576. PODVector<unsigned char> NavigationMesh::GetNavigationDataAttr() const
  577. {
  578. VectorBuffer ret;
  579. if (navMesh_)
  580. {
  581. ret.WriteBoundingBox(boundingBox_);
  582. ret.WriteInt(numTilesX_);
  583. ret.WriteInt(numTilesZ_);
  584. const dtNavMeshParams* params = navMesh_->getParams();
  585. ret.WriteFloat(params->tileWidth);
  586. ret.WriteFloat(params->tileHeight);
  587. ret.WriteInt(params->maxTiles);
  588. ret.WriteInt(params->maxPolys);
  589. const dtNavMesh* navMesh = navMesh_;
  590. for (int z = 0; z < numTilesZ_; ++z)
  591. {
  592. for (int x = 0; x < numTilesX_; ++x)
  593. {
  594. const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);
  595. if (!tile)
  596. continue;
  597. ret.WriteInt(x);
  598. ret.WriteInt(z);
  599. ret.WriteUInt(navMesh->getTileRef(tile));
  600. ret.WriteUInt(tile->dataSize);
  601. ret.Write(tile->data, tile->dataSize);
  602. }
  603. }
  604. }
  605. return ret.GetBuffer();
  606. }
  607. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList)
  608. {
  609. PROFILE(CollectNavigationGeometry);
  610. // Get Navigable components from child nodes, not from whole scene. This makes it possible to partition
  611. // the scene into several navigation meshes
  612. PODVector<Navigable*> navigables;
  613. node_->GetComponents<Navigable>(navigables, true);
  614. HashSet<Node*> processedNodes;
  615. for (unsigned i = 0; i < navigables.Size(); ++i)
  616. {
  617. if (navigables[i]->IsEnabledEffective())
  618. CollectGeometries(geometryList, navigables[i]->GetNode(), processedNodes, navigables[i]->IsRecursive());
  619. }
  620. // Get offmesh connections
  621. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  622. PODVector<OffMeshConnection*> connections;
  623. node_->GetComponents<OffMeshConnection>(connections, true);
  624. for (unsigned i = 0; i < connections.Size(); ++i)
  625. {
  626. OffMeshConnection* connection = connections[i];
  627. if (connection->IsEnabledEffective() && connection->GetEndPoint())
  628. {
  629. const Matrix3x4& transform = connection->GetNode()->GetWorldTransform();
  630. NavigationGeometryInfo info;
  631. info.component_ = connection;
  632. info.boundingBox_ = BoundingBox(Sphere(transform.Translation(), connection->GetRadius())).Transformed(inverse);
  633. geometryList.Push(info);
  634. }
  635. }
  636. }
  637. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes, bool recursive)
  638. {
  639. // Make sure nodes are not included twice
  640. if (processedNodes.Contains(node))
  641. return;
  642. processedNodes.Insert(node);
  643. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  644. // Prefer compatible physics collision shapes (triangle mesh, convex hull, box) if found.
  645. // Then fallback to visible geometry
  646. PODVector<CollisionShape*> collisionShapes;
  647. node->GetComponents<CollisionShape>(collisionShapes);
  648. bool collisionShapeFound = false;
  649. for (unsigned i = 0; i < collisionShapes.Size(); ++i)
  650. {
  651. CollisionShape* shape = collisionShapes[i];
  652. if (!shape->IsEnabledEffective())
  653. continue;
  654. ShapeType type = shape->GetShapeType();
  655. if ((type == SHAPE_BOX || type == SHAPE_TRIANGLEMESH || type == SHAPE_CONVEXHULL) && shape->GetCollisionShape())
  656. {
  657. Matrix3x4 shapeTransform(shape->GetPosition(), shape->GetRotation(), shape->GetSize());
  658. NavigationGeometryInfo info;
  659. info.component_ = shape;
  660. info.transform_ = inverse * node->GetWorldTransform() * shapeTransform;
  661. info.boundingBox_ = shape->GetWorldBoundingBox().Transformed(inverse);
  662. geometryList.Push(info);
  663. collisionShapeFound = true;
  664. }
  665. }
  666. if (!collisionShapeFound)
  667. {
  668. PODVector<Drawable*> drawables;
  669. node->GetDerivedComponents<Drawable>(drawables);
  670. for (unsigned i = 0; i < drawables.Size(); ++i)
  671. {
  672. /// \todo Evaluate whether should handle other types. Now StaticModel & TerrainPatch are supported, others skipped
  673. Drawable* drawable = drawables[i];
  674. if (!drawable->IsEnabledEffective())
  675. continue;
  676. NavigationGeometryInfo info;
  677. if (drawable->GetType() == StaticModel::GetTypeStatic())
  678. info.lodLevel_ = static_cast<StaticModel*>(drawable)->GetOcclusionLodLevel();
  679. else if (drawable->GetType() == TerrainPatch::GetTypeStatic())
  680. info.lodLevel_ = 0;
  681. else
  682. continue;
  683. info.component_ = drawable;
  684. info.transform_ = inverse * node->GetWorldTransform();
  685. info.boundingBox_ = drawable->GetWorldBoundingBox().Transformed(inverse);
  686. geometryList.Push(info);
  687. }
  688. }
  689. if (recursive)
  690. {
  691. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  692. for(unsigned i = 0; i < children.Size(); ++i)
  693. CollectGeometries(geometryList, children[i], processedNodes, recursive);
  694. }
  695. }
  696. void NavigationMesh::GetTileGeometry(NavigationBuildData& build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box)
  697. {
  698. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  699. for (unsigned i = 0; i < geometryList.Size(); ++i)
  700. {
  701. if (box.IsInsideFast(geometryList[i].boundingBox_) != OUTSIDE)
  702. {
  703. const Matrix3x4& transform = geometryList[i].transform_;
  704. if (geometryList[i].component_->GetType() == OffMeshConnection::GetTypeStatic())
  705. {
  706. OffMeshConnection* connection = static_cast<OffMeshConnection*>(geometryList[i].component_);
  707. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  708. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  709. build.offMeshVertices_.Push(start);
  710. build.offMeshVertices_.Push(end);
  711. build.offMeshRadii_.Push(connection->GetRadius());
  712. /// \todo Allow to define custom flags
  713. build.offMeshFlags_.Push(0x1);
  714. build.offMeshAreas_.Push(0);
  715. build.offMeshDir_.Push(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0);
  716. continue;
  717. }
  718. CollisionShape* shape = dynamic_cast<CollisionShape*>(geometryList[i].component_);
  719. if (shape)
  720. {
  721. switch (shape->GetShapeType())
  722. {
  723. case SHAPE_TRIANGLEMESH:
  724. {
  725. Model* model = shape->GetModel();
  726. if (!model)
  727. continue;
  728. unsigned lodLevel = shape->GetLodLevel();
  729. for (unsigned j = 0; j < model->GetNumGeometries(); ++j)
  730. AddTriMeshGeometry(build, model->GetGeometry(j, lodLevel), transform);
  731. }
  732. break;
  733. case SHAPE_CONVEXHULL:
  734. {
  735. ConvexData* data = static_cast<ConvexData*>(shape->GetGeometryData());
  736. if (!data)
  737. continue;
  738. unsigned numVertices = data->vertexCount_;
  739. unsigned numIndices = data->indexCount_;
  740. unsigned destVertexStart = build.vertices_.Size();
  741. for (unsigned j = 0; j < numVertices; ++j)
  742. build.vertices_.Push(transform * data->vertexData_[j]);
  743. for (unsigned j = 0; j < numIndices; ++j)
  744. build.indices_.Push(data->indexData_[j] + destVertexStart);
  745. }
  746. break;
  747. case SHAPE_BOX:
  748. {
  749. unsigned destVertexStart = build.vertices_.Size();
  750. build.vertices_.Push(transform * Vector3(-0.5f, 0.5f, -0.5f));
  751. build.vertices_.Push(transform * Vector3(0.5f, 0.5f, -0.5f));
  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. const unsigned indices[] = {
  759. 0, 1, 2, 0, 2, 3, 1, 5, 6, 1, 6, 2, 4, 5, 1, 4, 1, 0, 5, 4, 7, 5, 7, 6,
  760. 4, 0, 3, 4, 3, 7, 1, 0, 4, 1, 4, 5
  761. };
  762. for (unsigned j = 0; j < 36; ++j)
  763. build.indices_.Push(indices[j] + destVertexStart);
  764. }
  765. break;
  766. default:
  767. break;
  768. }
  769. continue;
  770. }
  771. Drawable* drawable = dynamic_cast<Drawable*>(geometryList[i].component_);
  772. if (drawable)
  773. {
  774. const Vector<SourceBatch>& batches = drawable->GetBatches();
  775. for (unsigned j = 0; j < batches.Size(); ++j)
  776. AddTriMeshGeometry(build, drawable->GetLodGeometry(j, geometryList[i].lodLevel_), transform);
  777. }
  778. }
  779. }
  780. }
  781. void NavigationMesh::AddTriMeshGeometry(NavigationBuildData& build, Geometry* geometry, const Matrix3x4& transform)
  782. {
  783. if (!geometry)
  784. return;
  785. const unsigned char* vertexData;
  786. const unsigned char* indexData;
  787. unsigned vertexSize;
  788. unsigned indexSize;
  789. unsigned elementMask;
  790. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  791. if (!vertexData || !indexData || (elementMask & MASK_POSITION) == 0)
  792. return;
  793. unsigned srcIndexStart = geometry->GetIndexStart();
  794. unsigned srcIndexCount = geometry->GetIndexCount();
  795. unsigned srcVertexStart = geometry->GetVertexStart();
  796. unsigned srcVertexCount = geometry->GetVertexCount();
  797. if (!srcIndexCount)
  798. return;
  799. unsigned destVertexStart = build.vertices_.Size();
  800. for (unsigned k = srcVertexStart; k < srcVertexStart + srcVertexCount; ++k)
  801. {
  802. Vector3 vertex = transform * *((const Vector3*)(&vertexData[k * vertexSize]));
  803. build.vertices_.Push(vertex);
  804. }
  805. // Copy remapped indices
  806. if (indexSize == sizeof(unsigned short))
  807. {
  808. const unsigned short* indices = ((const unsigned short*)indexData) + srcIndexStart;
  809. const unsigned short* indicesEnd = indices + srcIndexCount;
  810. while (indices < indicesEnd)
  811. {
  812. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  813. ++indices;
  814. }
  815. }
  816. else
  817. {
  818. const unsigned* indices = ((const unsigned*)indexData) + srcIndexStart;
  819. const unsigned* indicesEnd = indices + srcIndexCount;
  820. while (indices < indicesEnd)
  821. {
  822. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  823. ++indices;
  824. }
  825. }
  826. }
  827. bool NavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z)
  828. {
  829. PROFILE(BuildNavigationMeshTile);
  830. // Remove previous tile (if any)
  831. navMesh_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  832. float tileEdgeLength = (float)tileSize_ * cellSize_;
  833. BoundingBox tileBoundingBox(Vector3(
  834. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  835. boundingBox_.min_.y_,
  836. boundingBox_.min_.z_ + tileEdgeLength * (float)z
  837. ),
  838. Vector3(
  839. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  840. boundingBox_.max_.y_,
  841. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)
  842. ));
  843. NavigationBuildData build;
  844. rcConfig cfg;
  845. memset(&cfg, 0, sizeof cfg);
  846. cfg.cs = cellSize_;
  847. cfg.ch = cellHeight_;
  848. cfg.walkableSlopeAngle = agentMaxSlope_;
  849. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  850. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  851. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  852. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  853. cfg.maxSimplificationError = edgeMaxError_;
  854. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  855. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  856. cfg.maxVertsPerPoly = 6;
  857. cfg.tileSize = tileSize_;
  858. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  859. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  860. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  861. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  862. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  863. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  864. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  865. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  866. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  867. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  868. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  869. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  870. GetTileGeometry(build, geometryList, expandedBox);
  871. if (build.vertices_.Empty() || build.indices_.Empty())
  872. return true; // Nothing to do
  873. build.heightField_ = rcAllocHeightfield();
  874. if (!build.heightField_)
  875. {
  876. LOGERROR("Could not allocate heightfield");
  877. return false;
  878. }
  879. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  880. cfg.ch))
  881. {
  882. LOGERROR("Could not create heightfield");
  883. return false;
  884. }
  885. unsigned numTriangles = build.indices_.Size() / 3;
  886. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  887. memset(triAreas.Get(), 0, numTriangles);
  888. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  889. &build.indices_[0], numTriangles, triAreas.Get());
  890. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  891. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  892. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  893. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  894. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  895. build.compactHeightField_ = rcAllocCompactHeightfield();
  896. if (!build.compactHeightField_)
  897. {
  898. LOGERROR("Could not allocate create compact heightfield");
  899. return false;
  900. }
  901. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  902. *build.compactHeightField_))
  903. {
  904. LOGERROR("Could not build compact heightfield");
  905. return false;
  906. }
  907. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  908. {
  909. LOGERROR("Could not erode compact heightfield");
  910. return false;
  911. }
  912. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  913. {
  914. LOGERROR("Could not build distance field");
  915. return false;
  916. }
  917. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  918. cfg.mergeRegionArea))
  919. {
  920. LOGERROR("Could not build regions");
  921. return false;
  922. }
  923. build.contourSet_ = rcAllocContourSet();
  924. if (!build.contourSet_)
  925. {
  926. LOGERROR("Could not allocate contour set");
  927. return false;
  928. }
  929. if (!rcBuildContours(build.ctx_, *build.compactHeightField_, cfg.maxSimplificationError, cfg.maxEdgeLen,
  930. *build.contourSet_))
  931. {
  932. LOGERROR("Could not create contours");
  933. return false;
  934. }
  935. build.polyMesh_ = rcAllocPolyMesh();
  936. if (!build.polyMesh_)
  937. {
  938. LOGERROR("Could not allocate poly mesh");
  939. return false;
  940. }
  941. if (!rcBuildPolyMesh(build.ctx_, *build.contourSet_, cfg.maxVertsPerPoly, *build.polyMesh_))
  942. {
  943. LOGERROR("Could not triangulate contours");
  944. return false;
  945. }
  946. build.polyMeshDetail_ = rcAllocPolyMeshDetail();
  947. if (!build.polyMeshDetail_)
  948. {
  949. LOGERROR("Could not allocate detail mesh");
  950. return false;
  951. }
  952. if (!rcBuildPolyMeshDetail(build.ctx_, *build.polyMesh_, *build.compactHeightField_, cfg.detailSampleDist,
  953. cfg.detailSampleMaxError, *build.polyMeshDetail_))
  954. {
  955. LOGERROR("Could not build detail mesh");
  956. return false;
  957. }
  958. // Set polygon flags
  959. /// \todo Allow to define custom flags
  960. for (int i = 0; i < build.polyMesh_->npolys; ++i)
  961. {
  962. if (build.polyMesh_->areas[i] == RC_WALKABLE_AREA)
  963. build.polyMesh_->flags[i] = 0x1;
  964. }
  965. unsigned char* navData = 0;
  966. int navDataSize = 0;
  967. dtNavMeshCreateParams params;
  968. memset(&params, 0, sizeof params);
  969. params.verts = build.polyMesh_->verts;
  970. params.vertCount = build.polyMesh_->nverts;
  971. params.polys = build.polyMesh_->polys;
  972. params.polyAreas = build.polyMesh_->areas;
  973. params.polyFlags = build.polyMesh_->flags;
  974. params.polyCount = build.polyMesh_->npolys;
  975. params.nvp = build.polyMesh_->nvp;
  976. params.detailMeshes = build.polyMeshDetail_->meshes;
  977. params.detailVerts = build.polyMeshDetail_->verts;
  978. params.detailVertsCount = build.polyMeshDetail_->nverts;
  979. params.detailTris = build.polyMeshDetail_->tris;
  980. params.detailTriCount = build.polyMeshDetail_->ntris;
  981. params.walkableHeight = agentHeight_;
  982. params.walkableRadius = agentRadius_;
  983. params.walkableClimb = agentMaxClimb_;
  984. params.tileX = x;
  985. params.tileY = z;
  986. rcVcopy(params.bmin, build.polyMesh_->bmin);
  987. rcVcopy(params.bmax, build.polyMesh_->bmax);
  988. params.cs = cfg.cs;
  989. params.ch = cfg.ch;
  990. params.buildBvTree = true;
  991. // Add off-mesh connections if have them
  992. if (build.offMeshRadii_.Size())
  993. {
  994. params.offMeshConCount = build.offMeshRadii_.Size();
  995. params.offMeshConVerts = &build.offMeshVertices_[0].x_;
  996. params.offMeshConRad = &build.offMeshRadii_[0];
  997. params.offMeshConFlags = &build.offMeshFlags_[0];
  998. params.offMeshConAreas = &build.offMeshAreas_[0];
  999. params.offMeshConDir = &build.offMeshDir_[0];
  1000. }
  1001. if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
  1002. {
  1003. LOGERROR("Could not build navigation mesh tile data");
  1004. return false;
  1005. }
  1006. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  1007. {
  1008. LOGERROR("Failed to add navigation mesh tile");
  1009. dtFree(navData);
  1010. return false;
  1011. }
  1012. return true;
  1013. }
  1014. bool NavigationMesh::InitializeQuery()
  1015. {
  1016. if (!navMesh_ || !node_)
  1017. return false;
  1018. if (navMeshQuery_)
  1019. return true;
  1020. navMeshQuery_ = dtAllocNavMeshQuery();
  1021. if (!navMeshQuery_)
  1022. {
  1023. LOGERROR("Could not create navigation mesh query");
  1024. return false;
  1025. }
  1026. if (dtStatusFailed(navMeshQuery_->init(navMesh_, MAX_POLYS)))
  1027. {
  1028. LOGERROR("Could not init navigation mesh query");
  1029. return false;
  1030. }
  1031. return true;
  1032. }
  1033. void NavigationMesh::ReleaseNavigationMesh()
  1034. {
  1035. dtFreeNavMesh(navMesh_);
  1036. navMesh_ = 0;
  1037. dtFreeNavMeshQuery(navMeshQuery_);
  1038. navMeshQuery_ = 0;
  1039. numTilesX_ = 0;
  1040. numTilesZ_ = 0;
  1041. boundingBox_.min_ = boundingBox_.max_ = Vector3::ZERO;
  1042. boundingBox_.defined_ = false;
  1043. }
  1044. }