NavigationMesh.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. //
  2. // Copyright (c) 2008-2013 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 "CollisionShape.h"
  24. #include "Context.h"
  25. #include "Drawable.h"
  26. #include "Geometry.h"
  27. #include "Log.h"
  28. #include "Navigable.h"
  29. #include "NavigationMesh.h"
  30. #include "Profiler.h"
  31. #include "Scene.h"
  32. #include "StaticModel.h"
  33. #include "TerrainPatch.h"
  34. #include <DetourNavMesh.h>
  35. #include <DetourNavMeshBuilder.h>
  36. #include <Recast.h>
  37. #include "DebugNew.h"
  38. namespace Urho3D
  39. {
  40. static const float DEFAULT_CELL_SIZE = 0.3f;
  41. static const float DEFAULT_CELL_HEIGHT = 0.2f;
  42. static const float DEFAULT_AGENT_HEIGHT = 2.0f;
  43. static const float DEFAULT_AGENT_RADIUS = 0.6f;
  44. static const float DEFAULT_AGENT_MAX_CLIMB = 0.9f;
  45. static const float DEFAULT_AGENT_MAX_SLOPE = 45.0f;
  46. static const float DEFAULT_REGION_MIN_SIZE = 8.0f;
  47. static const float DEFAULT_REGION_MERGE_SIZE = 20.0f;
  48. static const float DEFAULT_EDGE_MAX_LENGTH = 12.0f;
  49. static const float DEFAULT_EDGE_MAX_ERROR = 1.3f;
  50. static const float DEFAULT_DETAIL_SAMPLE_DISTANCE = 6.0f;
  51. static const float DEFAULT_DETAIL_SAMPLE_MAX_ERROR = 1.0f;
  52. OBJECTTYPESTATIC(NavigationMesh);
  53. NavigationMesh::NavigationMesh(Context* context) :
  54. Component(context),
  55. cellSize_(DEFAULT_CELL_SIZE),
  56. cellHeight_(DEFAULT_CELL_HEIGHT),
  57. agentHeight_(DEFAULT_AGENT_HEIGHT),
  58. agentRadius_(DEFAULT_AGENT_RADIUS),
  59. agentMaxClimb_(DEFAULT_AGENT_MAX_CLIMB),
  60. agentMaxSlope_(DEFAULT_AGENT_MAX_SLOPE),
  61. regionMinSize_(DEFAULT_REGION_MIN_SIZE),
  62. regionMergeSize_(DEFAULT_REGION_MERGE_SIZE),
  63. edgeMaxLength_(DEFAULT_EDGE_MAX_LENGTH),
  64. edgeMaxError_(DEFAULT_EDGE_MAX_ERROR),
  65. detailSampleDistance_(DEFAULT_DETAIL_SAMPLE_DISTANCE),
  66. detailSampleMaxError_(DEFAULT_DETAIL_SAMPLE_MAX_ERROR),
  67. ctx_(0),
  68. heightField_(0),
  69. compactHeightField_(0),
  70. contourSet_(0),
  71. polyMesh_(0),
  72. polyMeshDetail_(0),
  73. navMesh_(0)
  74. {
  75. }
  76. NavigationMesh::~NavigationMesh()
  77. {
  78. ReleaseBuildData();
  79. ReleaseNavMesh();
  80. }
  81. void NavigationMesh::RegisterObject(Context* context)
  82. {
  83. context->RegisterFactory<NavigationMesh>();
  84. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Cell Size", GetCellSize, SetCellSize, float, DEFAULT_CELL_SIZE, AM_DEFAULT);
  85. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Cell Height", GetCellHeight, SetCellHeight, float, DEFAULT_CELL_HEIGHT, AM_DEFAULT);
  86. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Height", GetAgentHeight, SetAgentHeight, float, DEFAULT_AGENT_HEIGHT, AM_DEFAULT);
  87. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Radius", GetAgentRadius, SetAgentRadius, float, DEFAULT_AGENT_RADIUS, AM_DEFAULT);
  88. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Max Climb", GetAgentMaxClimb, SetAgentMaxClimb, float, DEFAULT_AGENT_MAX_CLIMB, AM_DEFAULT);
  89. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Max Slope", GetAgentMaxSlope, SetAgentMaxSlope, float, DEFAULT_AGENT_MAX_SLOPE, AM_DEFAULT);
  90. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Region Min Size", GetRegionMinSize, SetRegionMinSize, float, DEFAULT_REGION_MIN_SIZE, AM_DEFAULT);
  91. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Region Merge Size", GetRegionMergeSize, SetRegionMergeSize, float, DEFAULT_REGION_MERGE_SIZE, AM_DEFAULT);
  92. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Edge Max Length", GetEdgeMaxLength, SetEdgeMaxLength, float, DEFAULT_EDGE_MAX_LENGTH, AM_DEFAULT);
  93. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Edge Max Error", GetEdgeMaxError, SetEdgeMaxError, float, DEFAULT_EDGE_MAX_ERROR, AM_DEFAULT);
  94. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Detail Sample Distance", GetDetailSampleDistance, SetDetailSampleDistance, float, DEFAULT_DETAIL_SAMPLE_DISTANCE, AM_DEFAULT);
  95. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Detail Sample Max Error", GetDetailSampleMaxError, SetDetailSampleMaxError, float, DEFAULT_DETAIL_SAMPLE_MAX_ERROR, AM_DEFAULT);
  96. }
  97. void NavigationMesh::SetCellSize(float size)
  98. {
  99. cellSize_ = Max(size, M_EPSILON);
  100. }
  101. void NavigationMesh::SetCellHeight(float height)
  102. {
  103. cellHeight_ = Max(height, M_EPSILON);
  104. }
  105. void NavigationMesh::SetAgentHeight(float height)
  106. {
  107. agentHeight_ = Max(height, M_EPSILON);
  108. }
  109. void NavigationMesh::SetAgentRadius(float radius)
  110. {
  111. agentRadius_ = Max(radius, M_EPSILON);
  112. }
  113. void NavigationMesh::SetAgentMaxClimb(float maxClimb)
  114. {
  115. agentMaxClimb_ = Max(maxClimb, M_EPSILON);
  116. }
  117. void NavigationMesh::SetAgentMaxSlope(float maxSlope)
  118. {
  119. agentMaxSlope_ = Max(maxSlope, 0.0f);
  120. }
  121. void NavigationMesh::SetRegionMinSize(float size)
  122. {
  123. regionMinSize_ = Max(size, M_EPSILON);
  124. }
  125. void NavigationMesh::SetRegionMergeSize(float size)
  126. {
  127. regionMergeSize_ = Max(size, M_EPSILON);
  128. }
  129. void NavigationMesh::SetEdgeMaxLength(float length)
  130. {
  131. edgeMaxLength_ = Max(length, M_EPSILON);
  132. }
  133. void NavigationMesh::SetEdgeMaxError(float error)
  134. {
  135. edgeMaxError_ = Max(error, M_EPSILON);
  136. }
  137. void NavigationMesh::SetDetailSampleDistance(float distance)
  138. {
  139. detailSampleDistance_ = Max(distance, M_EPSILON);
  140. }
  141. void NavigationMesh::SetDetailSampleMaxError(float error)
  142. {
  143. detailSampleMaxError_ = Max(error, M_EPSILON);
  144. }
  145. bool NavigationMesh::Build()
  146. {
  147. ReleaseBuildData();
  148. ReleaseNavMesh();
  149. if (!node_)
  150. return false;
  151. PROFILE(BuildNavigationMesh);
  152. {
  153. PROFILE(CollectNavigationGeometry);
  154. // Get Navigable components from child nodes, not from whole scene. This makes it theoretically possible to partition
  155. // the scene into several navigation meshes
  156. PODVector<Navigable*> navigables;
  157. node_->GetComponents<Navigable>(navigables, true);
  158. for (unsigned i = 0; i < navigables.Size(); ++i)
  159. CollectGeometries(navigables[i]->GetNode(), navigables[i]->GetNode());
  160. LOGDEBUG("Navigation mesh has " + String(vertices_.Size()) + " vertices and " + String(indices_.Size()) + " indices");
  161. }
  162. if (!vertices_.Size() || !indices_.Size())
  163. return true; // Nothing to do
  164. {
  165. PROFILE(ProcessNavigationGeometry);
  166. rcConfig cfg;
  167. memset(&cfg, 0, sizeof cfg);
  168. cfg.cs = cellSize_;
  169. cfg.ch = cellHeight_;
  170. cfg.walkableSlopeAngle = agentMaxSlope_;
  171. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  172. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  173. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  174. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  175. cfg.maxSimplificationError = edgeMaxError_;
  176. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  177. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  178. cfg.maxVertsPerPoly = 6;
  179. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  180. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  181. rcVcopy(cfg.bmin, &worldBoundingBox_.min_.x_);
  182. rcVcopy(cfg.bmax, &worldBoundingBox_.max_.x_);
  183. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  184. ctx_ = new rcContext(false);
  185. heightField_ = rcAllocHeightfield();
  186. if (!heightField_)
  187. {
  188. LOGERROR("Could not allocate heightfield");
  189. ReleaseBuildData();
  190. return false;
  191. }
  192. if (!rcCreateHeightfield(ctx_, *heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch))
  193. {
  194. LOGERROR("Could not create heightfield");
  195. ReleaseBuildData();
  196. return false;
  197. }
  198. unsigned numTriangles = indices_.Size() / 3;
  199. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  200. memset(triAreas.Get(), 0, numTriangles);
  201. rcMarkWalkableTriangles(ctx_, cfg.walkableSlopeAngle, &vertices_[0].x_, vertices_.Size(), &indices_[0], numTriangles, triAreas.Get());
  202. rcRasterizeTriangles(ctx_, &vertices_[0].x_, vertices_.Size(), &indices_[0], triAreas.Get(), numTriangles, *heightField_, cfg.walkableClimb);
  203. rcFilterLowHangingWalkableObstacles(ctx_, cfg.walkableClimb, *heightField_);
  204. rcFilterLedgeSpans(ctx_, cfg.walkableHeight, cfg.walkableClimb, *heightField_);
  205. rcFilterWalkableLowHeightSpans(ctx_, cfg.walkableHeight, *heightField_);
  206. compactHeightField_ = rcAllocCompactHeightfield();
  207. if (!compactHeightField_)
  208. {
  209. LOGERROR("Could not allocate create compact heightfield");
  210. ReleaseBuildData();
  211. return false;
  212. }
  213. if (!rcBuildCompactHeightfield(ctx_, cfg.walkableHeight, cfg.walkableClimb, *heightField_, *compactHeightField_))
  214. {
  215. LOGERROR("Could not build compact heightfield");
  216. ReleaseBuildData();
  217. return false;
  218. }
  219. if (!rcErodeWalkableArea(ctx_, cfg.walkableRadius, *compactHeightField_))
  220. {
  221. LOGERROR("Could not erode compact heightfield");
  222. ReleaseBuildData();
  223. return false;
  224. }
  225. if (!rcBuildDistanceField(ctx_, *compactHeightField_))
  226. {
  227. LOGERROR("Could not build distance field");
  228. ReleaseBuildData();
  229. return false;
  230. }
  231. if (!rcBuildRegions(ctx_, *compactHeightField_, 0, cfg.minRegionArea, cfg.mergeRegionArea))
  232. {
  233. LOGERROR("Could not build regions");
  234. ReleaseBuildData();
  235. return false;
  236. }
  237. contourSet_ = rcAllocContourSet();
  238. if (!contourSet_)
  239. {
  240. LOGERROR("Could not allocate contour set");
  241. ReleaseBuildData();
  242. return false;
  243. }
  244. if (!rcBuildContours(ctx_, *compactHeightField_, cfg.maxSimplificationError, cfg.maxEdgeLen, *contourSet_))
  245. {
  246. LOGERROR("Could not create contours");
  247. ReleaseBuildData();
  248. return false;
  249. }
  250. polyMesh_ = rcAllocPolyMesh();
  251. if (!polyMesh_)
  252. {
  253. LOGERROR("Could not allocate poly mesh");
  254. ReleaseBuildData();
  255. return false;
  256. }
  257. if (!rcBuildPolyMesh(ctx_, *contourSet_, cfg.maxVertsPerPoly, *polyMesh_))
  258. {
  259. LOGERROR("Could not triangulate contours");
  260. ReleaseBuildData();
  261. return false;
  262. }
  263. polyMeshDetail_ = rcAllocPolyMeshDetail();
  264. if (!polyMeshDetail_)
  265. {
  266. LOGERROR("Could not allocate detail mesh");
  267. ReleaseBuildData();
  268. return false;
  269. }
  270. if (!rcBuildPolyMeshDetail(ctx_, *polyMesh_, *compactHeightField_, cfg.detailSampleDist, cfg.detailSampleMaxError, *polyMeshDetail_))
  271. {
  272. LOGERROR("Could not build detail mesh");
  273. ReleaseBuildData();
  274. return false;
  275. }
  276. unsigned char* navData = 0;
  277. int navDataSize = 0;
  278. dtNavMeshCreateParams params;
  279. memset(&params, 0, sizeof params);
  280. params.verts = polyMesh_->verts;
  281. params.vertCount = polyMesh_->nverts;
  282. params.polys = polyMesh_->polys;
  283. params.polyAreas = polyMesh_->areas;
  284. params.polyFlags = polyMesh_->flags;
  285. params.polyCount = polyMesh_->npolys;
  286. params.nvp = polyMesh_->nvp;
  287. params.detailMeshes = polyMeshDetail_->meshes;
  288. params.detailVerts = polyMeshDetail_->verts;
  289. params.detailVertsCount = polyMeshDetail_->nverts;
  290. params.detailTris = polyMeshDetail_->tris;
  291. params.detailTriCount = polyMeshDetail_->ntris;
  292. params.walkableHeight = agentHeight_;
  293. params.walkableRadius = agentRadius_;
  294. params.walkableClimb = agentMaxClimb_;
  295. rcVcopy(params.bmin, polyMesh_->bmin);
  296. rcVcopy(params.bmax, polyMesh_->bmax);
  297. params.cs = cfg.cs;
  298. params.ch = cfg.ch;
  299. params.buildBvTree = true;
  300. if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
  301. {
  302. LOGERROR("Could not build Detour navmesh");
  303. ReleaseBuildData();
  304. return false;
  305. }
  306. LOGDEBUG("Navmesh data size " + String(navDataSize) + " bytes");
  307. navMesh_ = dtAllocNavMesh();
  308. if (!navMesh_)
  309. {
  310. LOGERROR("Could not create Detour navmesh");
  311. dtFree(navData);
  312. ReleaseBuildData();
  313. return false;
  314. }
  315. dtStatus status;
  316. status = navMesh_->init(navData, navDataSize, DT_TILE_FREE_DATA);
  317. if (dtStatusFailed(status))
  318. {
  319. LOGERROR("Could not init Detour navmesh");
  320. dtFree(navData);
  321. ReleaseBuildData();
  322. return false;
  323. }
  324. }
  325. ReleaseBuildData();
  326. return true;
  327. }
  328. void NavigationMesh::CollectGeometries(Node* node, Node* baseNode)
  329. {
  330. // If find a navigable from a child node that's not the current base node, abort so we're not going to add the geometry twice
  331. if (node != baseNode && node->HasComponent<Navigable>())
  332. return;
  333. /// \todo Prefer physics geometry if available
  334. PODVector<Drawable*> drawables;
  335. node->GetDerivedComponents<Drawable>(drawables);
  336. for (unsigned i = 0; i < drawables.Size(); ++i)
  337. {
  338. /// \todo Evaluate whether should handle other types. Now StaticModel & TerrainPatch are supported, others skipped
  339. Drawable* drawable = drawables[i];
  340. unsigned numGeometries = drawable->GetBatches().Size();
  341. unsigned lodLevel;
  342. if (drawable->GetType() == StaticModel::GetTypeStatic())
  343. lodLevel = static_cast<StaticModel*>(drawable)->GetOcclusionLodLevel();
  344. else if (drawable->GetType() == TerrainPatch::GetTypeStatic())
  345. lodLevel = 0;
  346. else
  347. continue;
  348. for (unsigned j = 0; j < numGeometries; ++j)
  349. AddGeometry(node, drawable->GetLodGeometry(j, lodLevel));
  350. }
  351. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  352. for(unsigned i = 0; i < children.Size(); ++i)
  353. CollectGeometries(children[i], baseNode);
  354. }
  355. void NavigationMesh::AddGeometry(Node* node, Geometry* geometry)
  356. {
  357. const unsigned char* vertexData;
  358. const unsigned char* indexData;
  359. unsigned vertexSize;
  360. unsigned indexSize;
  361. unsigned elementMask;
  362. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  363. if (!vertexData || !indexData || (elementMask & MASK_POSITION) == 0)
  364. {
  365. LOGERROR("Could not use geometry from node " + node->GetName() + ": vertex or index raw data null or positions missing");
  366. return;
  367. }
  368. unsigned srcIndexStart = geometry->GetIndexStart();
  369. unsigned srcIndexCount = geometry->GetIndexCount();
  370. unsigned srcVertexStart = geometry->GetVertexStart();
  371. unsigned srcVertexCount = geometry->GetVertexCount();
  372. if (!srcIndexCount)
  373. {
  374. LOGERROR("Could not use geometry from node " + node->GetName() + ": no indices");
  375. return;
  376. }
  377. unsigned destVertexStart = vertices_.Size();
  378. // Copy draw range vertices transformed into world space
  379. Matrix3x4 transform = node->GetWorldTransform();
  380. for (unsigned i = srcVertexStart; i < srcVertexStart + srcVertexCount; ++i)
  381. {
  382. Vector3 vertex = transform * *((const Vector3*)(&vertexData[i * vertexSize]));
  383. worldBoundingBox_.Merge(vertex);
  384. vertices_.Push(vertex);
  385. }
  386. // Copy remapped indices
  387. if (indexSize == sizeof(unsigned short))
  388. {
  389. const unsigned short* indices = ((const unsigned short*)indexData) + srcIndexStart;
  390. const unsigned short* indicesEnd = indices + srcIndexCount;
  391. while (indices < indicesEnd)
  392. {
  393. indices_.Push(*indices - srcVertexStart + destVertexStart);
  394. ++indices;
  395. }
  396. }
  397. else
  398. {
  399. const unsigned* indices = ((const unsigned*)indexData) + srcIndexStart;
  400. const unsigned* indicesEnd = indices + srcIndexCount;
  401. while (indices < indicesEnd)
  402. {
  403. indices_.Push(*indices - srcVertexStart + destVertexStart);
  404. ++indices;
  405. }
  406. }
  407. }
  408. void NavigationMesh::ReleaseBuildData()
  409. {
  410. delete(ctx_);
  411. ctx_ = 0;
  412. rcFreeHeightField(heightField_);
  413. heightField_ = 0;
  414. rcFreeCompactHeightfield(compactHeightField_);
  415. compactHeightField_ = 0;
  416. rcFreeContourSet(contourSet_);
  417. contourSet_ = 0;
  418. rcFreePolyMesh(polyMesh_);
  419. polyMesh_ = 0;
  420. rcFreePolyMeshDetail(polyMeshDetail_);
  421. polyMeshDetail_ = 0;
  422. vertices_.Clear();
  423. vertices_.Compact();
  424. indices_.Clear();
  425. indices_.Compact();
  426. worldBoundingBox_.defined_ = false;
  427. }
  428. void NavigationMesh::ReleaseNavMesh()
  429. {
  430. dtFreeNavMesh(navMesh_);
  431. navMesh_ = 0;
  432. }
  433. }