NavigationMesh.cpp 45 KB

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