DynamicNavigationMesh.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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 "../Navigation/DynamicNavigationMesh.h"
  23. #include "../Math/BoundingBox.h"
  24. #include "../Core/Context.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../Navigation/NavBuildData.h"
  29. #include "../Navigation/NavigationEvents.h"
  30. #include "../Scene/Node.h"
  31. #include "../Navigation/OffMeshConnection.h"
  32. #include "../Core/Profiler.h"
  33. #include "../Navigation/Obstacle.h"
  34. #include "../Scene/Scene.h"
  35. #include "../Scene/SceneEvents.h"
  36. #include <LZ4/lz4.h>
  37. #include <cfloat>
  38. #include <Detour/DetourNavMesh.h>
  39. #include <Detour/DetourNavMeshBuilder.h>
  40. #include <Detour/DetourNavMeshQuery.h>
  41. #include <DetourTileCache/DetourTileCache.h>
  42. #include <DetourTileCache/DetourTileCacheBuilder.h>
  43. #include <Recast/Recast.h>
  44. #include <Recast/RecastAlloc.h>
  45. //DebugNew is deliberately not used because the macro 'free' conflicts DetourTileCache's LinearAllocator interface
  46. //#include "../DebugNew.h"
  47. #define TILECACHE_MAXLAYERS 128
  48. namespace Urho3D
  49. {
  50. extern const char* NAVIGATION_CATEGORY;
  51. static const int DEFAULT_MAX_OBSTACLES = 1024;
  52. struct DynamicNavigationMesh::TileCacheData
  53. {
  54. unsigned char* data;
  55. int dataSize;
  56. };
  57. struct TileCompressor : public dtTileCacheCompressor
  58. {
  59. virtual int maxCompressedSize(const int bufferSize)
  60. {
  61. return (int)(bufferSize* 1.05f);
  62. }
  63. virtual dtStatus compress(const unsigned char* buffer, const int bufferSize,
  64. unsigned char* compressed, const int /*maxCompressedSize*/, int* compressedSize)
  65. {
  66. *compressedSize = LZ4_compress((const char*)buffer, (char*)compressed, bufferSize);
  67. return DT_SUCCESS;
  68. }
  69. virtual dtStatus decompress(const unsigned char* compressed, const int compressedSize,
  70. unsigned char* buffer, const int maxBufferSize, int* bufferSize)
  71. {
  72. *bufferSize = LZ4_decompress_safe((const char*)compressed, (char*)buffer, compressedSize, maxBufferSize);
  73. return *bufferSize < 0 ? DT_FAILURE : DT_SUCCESS;
  74. }
  75. };
  76. struct MeshProcess : public dtTileCacheMeshProcess
  77. {
  78. DynamicNavigationMesh* owner_;
  79. PODVector<Vector3> offMeshVertices_;
  80. PODVector<float> offMeshRadii_;
  81. PODVector<unsigned short> offMeshFlags_;
  82. PODVector<unsigned char> offMeshAreas_;
  83. PODVector<unsigned char> offMeshDir_;
  84. inline MeshProcess(DynamicNavigationMesh* owner) :
  85. owner_(owner)
  86. {
  87. }
  88. virtual void process(struct dtNavMeshCreateParams* params, unsigned char* polyAreas, unsigned short* polyFlags)
  89. {
  90. // Update poly flags from areas.
  91. // \todo Assignment of flags from areas?
  92. for (int i = 0; i < params->polyCount; ++i)
  93. {
  94. if (polyAreas[i] != RC_NULL_AREA)
  95. polyFlags[i] = RC_WALKABLE_AREA;
  96. }
  97. BoundingBox bounds;
  98. rcVcopy(&bounds.min_.x_, params->bmin);
  99. rcVcopy(&bounds.max_.x_, params->bmin);
  100. // collect off-mesh connections
  101. PODVector<OffMeshConnection*> offMeshConnections = owner_->CollectOffMeshConnections(bounds);
  102. if (offMeshConnections.Size() > 0)
  103. {
  104. if (offMeshConnections.Size() != offMeshRadii_.Size())
  105. {
  106. Matrix3x4 inverse = owner_->GetNode()->GetWorldTransform().Inverse();
  107. ClearConnectionData();
  108. for (unsigned i = 0; i < offMeshConnections.Size(); ++i)
  109. {
  110. OffMeshConnection* connection = offMeshConnections[i];
  111. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  112. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  113. offMeshVertices_.Push(start);
  114. offMeshVertices_.Push(end);
  115. offMeshRadii_.Push(connection->GetRadius());
  116. offMeshFlags_.Push(connection->GetMask());
  117. offMeshAreas_.Push((unsigned char)connection->GetAreaID());
  118. offMeshDir_.Push(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0);
  119. }
  120. }
  121. params->offMeshConCount = offMeshRadii_.Size();
  122. params->offMeshConVerts = &offMeshVertices_[0].x_;
  123. params->offMeshConRad = &offMeshRadii_[0];
  124. params->offMeshConFlags = &offMeshFlags_[0];
  125. params->offMeshConAreas = &offMeshAreas_[0];
  126. params->offMeshConDir = &offMeshDir_[0];
  127. }
  128. }
  129. void ClearConnectionData()
  130. {
  131. offMeshVertices_.Clear();
  132. offMeshRadii_.Clear();
  133. offMeshFlags_.Clear();
  134. offMeshAreas_.Clear();
  135. offMeshDir_.Clear();
  136. }
  137. };
  138. // From the Detour/Recast Sample_TempObstacles.cpp
  139. struct LinearAllocator : public dtTileCacheAlloc
  140. {
  141. unsigned char* buffer;
  142. int capacity;
  143. int top;
  144. int high;
  145. LinearAllocator(const int cap) : buffer(0), capacity(0), top(0), high(0)
  146. {
  147. resize(cap);
  148. }
  149. ~LinearAllocator()
  150. {
  151. dtFree(buffer);
  152. }
  153. void resize(const int cap)
  154. {
  155. if (buffer)
  156. dtFree(buffer);
  157. buffer = (unsigned char*)dtAlloc(cap, DT_ALLOC_PERM);
  158. capacity = cap;
  159. }
  160. virtual void reset()
  161. {
  162. high = Max(high, top);
  163. top = 0;
  164. }
  165. virtual void* alloc(const int size)
  166. {
  167. if (!buffer)
  168. return 0;
  169. if (top + size > capacity)
  170. return 0;
  171. unsigned char* mem = &buffer[top];
  172. top += size;
  173. return mem;
  174. }
  175. virtual void free(void*)
  176. {
  177. }
  178. };
  179. DynamicNavigationMesh::DynamicNavigationMesh(Context* context) :
  180. NavigationMesh(context),
  181. tileCache_(0),
  182. maxObstacles_(1024)
  183. {
  184. //64 is the largest tile-size that DetourTileCache will tolerate without silently failing
  185. tileSize_ = 64;
  186. partitionType_ = NAVMESH_PARTITION_MONOTONE;
  187. allocator_ = new LinearAllocator(32000); //32kb to start
  188. compressor_ = new TileCompressor();
  189. meshProcessor_ = new MeshProcess(this);
  190. }
  191. DynamicNavigationMesh::~DynamicNavigationMesh()
  192. {
  193. ReleaseNavigationMesh();
  194. delete allocator_;
  195. allocator_ = 0;
  196. delete compressor_;
  197. compressor_ = 0;
  198. delete meshProcessor_;
  199. meshProcessor_ = 0;
  200. }
  201. void DynamicNavigationMesh::RegisterObject(Context* context)
  202. {
  203. context->RegisterFactory<DynamicNavigationMesh>(NAVIGATION_CATEGORY);
  204. COPY_BASE_ATTRIBUTES(NavigationMesh);
  205. ATTRIBUTE("Max Obstacles", unsigned, maxObstacles_, DEFAULT_MAX_OBSTACLES, AM_DEFAULT);
  206. }
  207. bool DynamicNavigationMesh::Build()
  208. {
  209. PROFILE(BuildNavigationMesh);
  210. // Release existing navigation data and zero the bounding box
  211. ReleaseNavigationMesh();
  212. if (!node_)
  213. return false;
  214. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  215. LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  216. Vector<NavigationGeometryInfo> geometryList;
  217. CollectGeometries(geometryList);
  218. if (geometryList.Empty())
  219. return true; // Nothing to do
  220. // Build the combined bounding box
  221. for (unsigned i = 0; i < geometryList.Size(); ++i)
  222. boundingBox_.Merge(geometryList[i].boundingBox_);
  223. // Expand bounding box by padding
  224. boundingBox_.min_ -= padding_;
  225. boundingBox_.max_ += padding_;
  226. {
  227. PROFILE(BuildNavigationMesh);
  228. // Calculate number of tiles
  229. int gridW = 0, gridH = 0;
  230. float tileEdgeLength = (float)tileSize_ * cellSize_;
  231. rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);
  232. numTilesX_ = (gridW + tileSize_ - 1) / tileSize_;
  233. numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_;
  234. // Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile
  235. unsigned maxTiles = NextPowerOfTwo(numTilesX_ * numTilesZ_) * TILECACHE_MAXLAYERS;
  236. unsigned tileBits = 0;
  237. unsigned temp = maxTiles;
  238. while (temp > 1)
  239. {
  240. temp >>= 1;
  241. ++tileBits;
  242. }
  243. unsigned maxPolys = 1 << (22 - tileBits);
  244. dtNavMeshParams params;
  245. rcVcopy(params.orig, &boundingBox_.min_.x_);
  246. params.tileWidth = tileEdgeLength;
  247. params.tileHeight = tileEdgeLength;
  248. params.maxTiles = maxTiles;
  249. params.maxPolys = maxPolys;
  250. navMesh_ = dtAllocNavMesh();
  251. if (!navMesh_)
  252. {
  253. LOGERROR("Could not allocate navigation mesh");
  254. return false;
  255. }
  256. if (dtStatusFailed(navMesh_->init(&params)))
  257. {
  258. LOGERROR("Could not initialize navigation mesh");
  259. ReleaseNavigationMesh();
  260. return false;
  261. }
  262. dtTileCacheParams tileCacheParams;
  263. memset(&tileCacheParams, 0, sizeof(tileCacheParams));
  264. rcVcopy(tileCacheParams.orig, &boundingBox_.min_.x_);
  265. tileCacheParams.ch = cellHeight_;
  266. tileCacheParams.cs = cellSize_;
  267. tileCacheParams.width = tileSize_;
  268. tileCacheParams.height = tileSize_;
  269. tileCacheParams.maxSimplificationError = edgeMaxError_;
  270. tileCacheParams.maxTiles = numTilesX_ * numTilesZ_ * TILECACHE_MAXLAYERS;
  271. tileCacheParams.maxObstacles = maxObstacles_;
  272. // Settings from NavigationMesh
  273. tileCacheParams.walkableClimb = agentMaxClimb_;
  274. tileCacheParams.walkableHeight = agentHeight_;
  275. tileCacheParams.walkableRadius = agentRadius_;
  276. tileCache_ = dtAllocTileCache();
  277. if (!tileCache_)
  278. {
  279. LOGERROR("Could not allocate tile cache");
  280. ReleaseNavigationMesh();
  281. return false;
  282. }
  283. if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_, compressor_, meshProcessor_)))
  284. {
  285. LOGERROR("Could not initialize tile cache");
  286. ReleaseNavigationMesh();
  287. return false;
  288. }
  289. // Build each tile
  290. unsigned numTiles = 0;
  291. for (int z = 0; z < numTilesZ_; ++z)
  292. {
  293. for (int x = 0; x < numTilesX_; ++x)
  294. {
  295. TileCacheData tiles[TILECACHE_MAXLAYERS];
  296. int layerCt = BuildTile(geometryList, x, z, tiles);
  297. for (int i = 0; i < layerCt; ++i)
  298. {
  299. dtCompressedTileRef tileRef;
  300. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  301. if (dtStatusFailed(status))
  302. {
  303. dtFree(tiles[i].data);
  304. tiles[i].data = 0x0;
  305. }
  306. }
  307. ++numTiles;
  308. }
  309. for (int x = 0; x < numTilesX_; ++x)
  310. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  311. }
  312. // For a full build it's necessary to update the nav mesh
  313. // not doing so will cause dependent components to crash, like DetourCrowdManager
  314. tileCache_->update(0, navMesh_);
  315. LOGDEBUG("Built navigation mesh with " + String(numTiles) + " tiles");
  316. // Send a notification event to concerned parties that we've been fully rebuilt
  317. {
  318. using namespace NavigationMeshRebuilt;
  319. VariantMap& buildEventParams = GetContext()->GetEventDataMap();
  320. buildEventParams[P_NODE] = node_;
  321. buildEventParams[P_MESH] = this;
  322. SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams);
  323. }
  324. // Scan for obstacles to insert into us
  325. PODVector<Node*> obstacles;
  326. GetScene()->GetChildrenWithComponent<Obstacle>(obstacles, true);
  327. for (unsigned i = 0; i < obstacles.Size(); ++i)
  328. {
  329. Obstacle* obs = obstacles[i]->GetComponent<Obstacle>();
  330. if (obs && obs->IsEnabledEffective())
  331. AddObstacle(obs);
  332. }
  333. return true;
  334. }
  335. }
  336. bool DynamicNavigationMesh::Build(const BoundingBox& boundingBox)
  337. {
  338. PROFILE(BuildPartialNavigationMesh);
  339. if (!node_)
  340. return false;
  341. if (!navMesh_)
  342. {
  343. LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt");
  344. return false;
  345. }
  346. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  347. LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  348. BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse());
  349. float tileEdgeLength = (float)tileSize_ * cellSize_;
  350. Vector<NavigationGeometryInfo> geometryList;
  351. CollectGeometries(geometryList);
  352. int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  353. int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  354. int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  355. int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  356. unsigned numTiles = 0;
  357. for (int z = sz; z <= ez; ++z)
  358. {
  359. for (int x = sx; x <= ex; ++x)
  360. {
  361. dtCompressedTileRef existing[TILECACHE_MAXLAYERS];
  362. const int existingCt = tileCache_->getTilesAt(x, z, existing, TILECACHE_MAXLAYERS);
  363. for (int i = 0; i < existingCt; ++i)
  364. {
  365. unsigned char* data = 0x0;
  366. if (!dtStatusFailed(tileCache_->removeTile(existing[i], &data, 0)) && data != 0x0)
  367. dtFree(data);
  368. }
  369. TileCacheData tiles[TILECACHE_MAXLAYERS];
  370. int layerCt = BuildTile(geometryList, x, z, tiles);
  371. for (int i = 0; i < layerCt; ++i)
  372. {
  373. dtCompressedTileRef tileRef;
  374. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  375. if (dtStatusFailed(status))
  376. {
  377. dtFree(tiles[i].data);
  378. tiles[i].data = 0x0;
  379. }
  380. else
  381. {
  382. tileCache_->buildNavMeshTile(tileRef, navMesh_);
  383. ++numTiles;
  384. }
  385. }
  386. }
  387. }
  388. LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  389. return true;
  390. }
  391. void DynamicNavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  392. {
  393. if (!debug || !navMesh_ || !node_)
  394. return;
  395. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  396. const dtNavMesh* navMesh = navMesh_;
  397. for (int z = 0; z < numTilesZ_; ++z)
  398. {
  399. for (int x = 0; x < numTilesX_; ++x)
  400. {
  401. // Get the layers from the tile-cache
  402. const dtMeshTile* tiles[TILECACHE_MAXLAYERS];
  403. int tileCount = navMesh->getTilesAt(x, z, tiles, TILECACHE_MAXLAYERS);
  404. for (int i = 0; i < tileCount; ++i)
  405. {
  406. const dtMeshTile* tile = tiles[i];
  407. if (!tile)
  408. continue;
  409. for (int i = 0; i < tile->header->polyCount; ++i)
  410. {
  411. dtPoly* poly = tile->polys + i;
  412. for (unsigned j = 0; j < poly->vertCount; ++j)
  413. {
  414. debug->AddLine(
  415. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),
  416. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),
  417. Color::YELLOW,
  418. depthTest
  419. );
  420. }
  421. }
  422. }
  423. }
  424. }
  425. }
  426. void DynamicNavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value)
  427. {
  428. ReleaseNavigationMesh();
  429. if (value.Empty())
  430. return;
  431. MemoryBuffer buffer(value);
  432. boundingBox_ = buffer.ReadBoundingBox();
  433. numTilesX_ = buffer.ReadInt();
  434. numTilesZ_ = buffer.ReadInt();
  435. dtNavMeshParams params;
  436. buffer.Read(&params, sizeof(dtNavMeshParams));
  437. navMesh_ = dtAllocNavMesh();
  438. if (!navMesh_)
  439. {
  440. LOGERROR("Could not allocate navigation mesh");
  441. return;
  442. }
  443. if (dtStatusFailed(navMesh_->init(&params)))
  444. {
  445. LOGERROR("Could not initialize navigation mesh");
  446. ReleaseNavigationMesh();
  447. return;
  448. }
  449. dtTileCacheParams tcParams;
  450. buffer.Read(&tcParams, sizeof(tcParams));
  451. tileCache_ = dtAllocTileCache();
  452. if (!tileCache_)
  453. {
  454. LOGERROR("Could not allocate tile cache");
  455. ReleaseNavigationMesh();
  456. return;
  457. }
  458. if (dtStatusFailed(tileCache_->init(&tcParams, allocator_, compressor_, meshProcessor_)))
  459. {
  460. LOGERROR("Could not initialize tile cache");
  461. ReleaseNavigationMesh();
  462. return;
  463. }
  464. while (!buffer.IsEof())
  465. {
  466. dtTileCacheLayerHeader header;
  467. buffer.Read(&header, sizeof(dtTileCacheLayerHeader));
  468. const int dataSize = buffer.ReadInt();
  469. unsigned char* data = (unsigned char*)dtAlloc(dataSize, DT_ALLOC_PERM);
  470. buffer.Read(data, dataSize);
  471. if (dtStatusFailed(tileCache_->addTile(data, dataSize, DT_TILE_FREE_DATA, 0)))
  472. {
  473. LOGERROR("Failed to add tile");
  474. dtFree(data);
  475. return;
  476. }
  477. }
  478. for (int x = 0; x < numTilesX_; ++x)
  479. {
  480. for (int z = 0; z < numTilesZ_; ++z)
  481. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  482. }
  483. tileCache_->update(0, navMesh_);
  484. }
  485. PODVector<unsigned char> DynamicNavigationMesh::GetNavigationDataAttr() const
  486. {
  487. VectorBuffer ret;
  488. if (navMesh_ && tileCache_)
  489. {
  490. ret.WriteBoundingBox(boundingBox_);
  491. ret.WriteInt(numTilesX_);
  492. ret.WriteInt(numTilesZ_);
  493. const dtNavMeshParams* params = navMesh_->getParams();
  494. ret.Write(params, sizeof(dtNavMeshParams));
  495. const dtTileCacheParams* tcParams = tileCache_->getParams();
  496. ret.Write(tcParams, sizeof(dtTileCacheParams));
  497. for (int z = 0; z < numTilesZ_; ++z)
  498. {
  499. for (int x = 0; x < numTilesX_; ++x)
  500. {
  501. dtCompressedTileRef tiles[TILECACHE_MAXLAYERS];
  502. const int ct = tileCache_->getTilesAt(x, z, tiles, TILECACHE_MAXLAYERS);
  503. for (int i = 0; i < ct; ++i)
  504. {
  505. const dtCompressedTile* tile = tileCache_->getTileByRef(tiles[i]);
  506. if (!tile || !tile->header || !tile->dataSize)
  507. continue; // Don't write "void-space" tiles
  508. // The header conveniently has the majority of the information required
  509. ret.Write(tile->header, sizeof(dtTileCacheLayerHeader));
  510. ret.WriteInt(tile->dataSize);
  511. ret.Write(tile->data, tile->dataSize);
  512. }
  513. }
  514. }
  515. }
  516. return ret.GetBuffer();
  517. }
  518. int DynamicNavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z, TileCacheData* tiles)
  519. {
  520. PROFILE(BuildNavigationMeshTile);
  521. tileCache_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  522. float tileEdgeLength = (float)tileSize_ * cellSize_;
  523. BoundingBox tileBoundingBox(Vector3(
  524. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  525. boundingBox_.min_.y_,
  526. boundingBox_.min_.z_ + tileEdgeLength * (float)z
  527. ),
  528. Vector3(
  529. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  530. boundingBox_.max_.y_,
  531. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)
  532. ));
  533. DynamicNavBuildData build(allocator_);
  534. rcConfig cfg;
  535. memset(&cfg, 0, sizeof cfg);
  536. cfg.cs = cellSize_;
  537. cfg.ch = cellHeight_;
  538. cfg.walkableSlopeAngle = agentMaxSlope_;
  539. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  540. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  541. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  542. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  543. cfg.maxSimplificationError = edgeMaxError_;
  544. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  545. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  546. cfg.maxVertsPerPoly = 6;
  547. cfg.tileSize = tileSize_;
  548. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  549. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  550. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  551. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  552. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  553. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  554. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  555. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  556. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  557. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  558. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  559. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  560. GetTileGeometry(&build, geometryList, expandedBox);
  561. if (build.vertices_.Empty() || build.indices_.Empty())
  562. return 0; // Nothing to do
  563. build.heightField_ = rcAllocHeightfield();
  564. if (!build.heightField_)
  565. {
  566. LOGERROR("Could not allocate heightfield");
  567. return 0;
  568. }
  569. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  570. cfg.ch))
  571. {
  572. LOGERROR("Could not create heightfield");
  573. return 0;
  574. }
  575. unsigned numTriangles = build.indices_.Size() / 3;
  576. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  577. memset(triAreas.Get(), 0, numTriangles);
  578. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  579. &build.indices_[0], numTriangles, triAreas.Get());
  580. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  581. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  582. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  583. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  584. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  585. build.compactHeightField_ = rcAllocCompactHeightfield();
  586. if (!build.compactHeightField_)
  587. {
  588. LOGERROR("Could not allocate create compact heightfield");
  589. return 0;
  590. }
  591. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  592. *build.compactHeightField_))
  593. {
  594. LOGERROR("Could not build compact heightfield");
  595. return 0;
  596. }
  597. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  598. {
  599. LOGERROR("Could not erode compact heightfield");
  600. return 0;
  601. }
  602. // area volumes
  603. for (unsigned i = 0; i < build.navAreas_.Size(); ++i)
  604. rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_, build.navAreas_[i].areaID_, *build.compactHeightField_);
  605. if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED)
  606. {
  607. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  608. {
  609. LOGERROR("Could not build distance field");
  610. return 0;
  611. }
  612. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  613. cfg.mergeRegionArea))
  614. {
  615. LOGERROR("Could not build regions");
  616. return 0;
  617. }
  618. }
  619. else
  620. {
  621. if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  622. {
  623. LOGERROR("Could not build monotone regions");
  624. return 0;
  625. }
  626. }
  627. build.heightFieldLayers_ = rcAllocHeightfieldLayerSet();
  628. if (!build.heightFieldLayers_)
  629. {
  630. LOGERROR("Could not allocate height field layer set");
  631. return 0;
  632. }
  633. if (!rcBuildHeightfieldLayers(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.walkableHeight, *build.heightFieldLayers_))
  634. {
  635. LOGERROR("Could not build height field layers");
  636. return 0;
  637. }
  638. int retCt = 0;
  639. for (int i = 0; i < build.heightFieldLayers_->nlayers; ++i)
  640. {
  641. dtTileCacheLayerHeader header;
  642. header.magic = DT_TILECACHE_MAGIC;
  643. header.version = DT_TILECACHE_VERSION;
  644. header.tx = x;
  645. header.ty = z;
  646. header.tlayer = i;
  647. rcHeightfieldLayer* layer = &build.heightFieldLayers_->layers[i];
  648. // Tile info.
  649. rcVcopy(header.bmin, layer->bmin);
  650. rcVcopy(header.bmax, layer->bmax);
  651. header.width = (unsigned char)layer->width;
  652. header.height = (unsigned char)layer->height;
  653. header.minx = (unsigned char)layer->minx;
  654. header.maxx = (unsigned char)layer->maxx;
  655. header.miny = (unsigned char)layer->miny;
  656. header.maxy = (unsigned char)layer->maxy;
  657. header.hmin = (unsigned short)layer->hmin;
  658. header.hmax = (unsigned short)layer->hmax;
  659. if (dtStatusFailed(dtBuildTileCacheLayer(compressor_/*compressor*/, &header, layer->heights, layer->areas/*areas*/, layer->cons, &(tiles[retCt].data), &tiles[retCt].dataSize)))
  660. {
  661. LOGERROR("Failed to build tile cache layers");
  662. return 0;
  663. }
  664. else
  665. ++retCt;
  666. }
  667. // Send a notification of the rebuild of this tile to anyone interested
  668. {
  669. using namespace NavigationAreaRebuilt;
  670. VariantMap& eventData = GetContext()->GetEventDataMap();
  671. eventData[P_NODE] = GetNode();
  672. eventData[P_MESH] = this;
  673. eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_);
  674. eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_);
  675. SendEvent(E_NAVIGATION_AREA_REBUILT, eventData);
  676. }
  677. return retCt;
  678. }
  679. PODVector<OffMeshConnection*> DynamicNavigationMesh::CollectOffMeshConnections(const BoundingBox& bounds)
  680. {
  681. PODVector<OffMeshConnection*> connections;
  682. node_->GetComponents<OffMeshConnection>(connections, true);
  683. for (unsigned i = 0; i < connections.Size(); ++i)
  684. {
  685. OffMeshConnection* connection = connections[i];
  686. if (!(connection->IsEnabledEffective() && connection->GetEndPoint()))
  687. {
  688. // discard this connection
  689. connections.Erase(i);
  690. --i;
  691. }
  692. }
  693. return connections;
  694. }
  695. void DynamicNavigationMesh::ReleaseNavigationMesh()
  696. {
  697. NavigationMesh::ReleaseNavigationMesh();
  698. ReleaseTileCache();
  699. }
  700. void DynamicNavigationMesh::ReleaseTileCache()
  701. {
  702. dtFreeTileCache(tileCache_);
  703. tileCache_ = 0;
  704. }
  705. void DynamicNavigationMesh::OnNodeSet(Node* node)
  706. {
  707. // Subscribe to the scene subsystem update, which will trigger the tile cache to update the nav mesh
  708. if (node)
  709. SubscribeToEvent(node, E_SCENESUBSYSTEMUPDATE, HANDLER(DynamicNavigationMesh, HandleSceneSubsystemUpdate));
  710. }
  711. void DynamicNavigationMesh::AddObstacle(Obstacle* obstacle, bool silent)
  712. {
  713. if (tileCache_)
  714. {
  715. float pos[3];
  716. Vector3 obsPos = obstacle->GetNode()->GetWorldPosition();
  717. rcVcopy(pos, &obsPos.x_);
  718. dtObstacleRef refHolder;
  719. if (dtStatusFailed(tileCache_->addObstacle(pos, obstacle->GetRadius(), obstacle->GetHeight(), &refHolder)))
  720. {
  721. LOGERROR("Failed to add obstacle");
  722. return;
  723. }
  724. obstacle->obstacleId_ = refHolder;
  725. assert(refHolder > 0);
  726. tileCache_->update(1, navMesh_);
  727. if (!silent)
  728. {
  729. using namespace NavigationObstacleAdded;
  730. VariantMap& eventData = GetContext()->GetEventDataMap();
  731. eventData[P_NODE] = obstacle->GetNode();
  732. eventData[P_OBSTACLE] = obstacle;
  733. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  734. eventData[P_RADIUS] = obstacle->GetRadius();
  735. eventData[P_HEIGHT] = obstacle->GetHeight();
  736. SendEvent(E_NAVIGATION_OBSTACLE_ADDED, eventData);
  737. }
  738. }
  739. }
  740. void DynamicNavigationMesh::ObstacleChanged(Obstacle* obstacle)
  741. {
  742. if (tileCache_)
  743. {
  744. RemoveObstacle(obstacle, true);
  745. AddObstacle(obstacle, true);
  746. }
  747. }
  748. void DynamicNavigationMesh::RemoveObstacle(Obstacle* obstacle, bool silent)
  749. {
  750. if (tileCache_ && obstacle->obstacleId_ > 0)
  751. {
  752. if (dtStatusFailed(tileCache_->removeObstacle(obstacle->obstacleId_)))
  753. {
  754. LOGERROR("Failed to remove obstacle");
  755. return;
  756. }
  757. // Require a node in order to send an event
  758. if (!silent && obstacle->GetNode())
  759. {
  760. obstacle->obstacleId_ = 0;
  761. using namespace NavigationObstacleRemoved;
  762. VariantMap& eventData = GetContext()->GetEventDataMap();
  763. eventData[P_NODE] = obstacle->GetNode();
  764. eventData[P_OBSTACLE] = obstacle;
  765. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  766. eventData[P_RADIUS] = obstacle->GetRadius();
  767. eventData[P_HEIGHT] = obstacle->GetHeight();
  768. SendEvent(E_NAVIGATION_OBSTACLE_ADDED, eventData);
  769. }
  770. }
  771. }
  772. void DynamicNavigationMesh::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  773. {
  774. using namespace SceneSubsystemUpdate;
  775. if (tileCache_ && navMesh_ && IsEnabledEffective())
  776. tileCache_->update(eventData[P_TIMESTEP].GetFloat(), navMesh_);
  777. }
  778. }