NavigationMesh.cpp 49 KB

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