NavigationMesh.cpp 55 KB

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