NavigationMesh.cpp 45 KB

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