NavigationMesh.cpp 52 KB

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