NavigationMesh.cpp 46 KB

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