Octree.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Scene/Octree.h>
  6. #include <AnKi/Scene/Components/FrustumComponent.h>
  7. #include <AnKi/Collision/Aabb.h>
  8. #include <AnKi/Collision/Functions.h>
  9. #include <AnKi/Util/ThreadHive.h>
  10. namespace anki {
  11. /// Return a heatmap color.
  12. static Vec3 heatmap(F32 factor)
  13. {
  14. F32 intPart;
  15. const F32 fractional = modf(factor * 4.0f, intPart);
  16. if(intPart < 1.0)
  17. {
  18. return mix(Vec3(0.0, 0.0, 0.0), Vec3(0.0, 0.0, 1.0), fractional);
  19. }
  20. else if(intPart < 2.0)
  21. {
  22. return mix(Vec3(0.0, 0.0, 1.0), Vec3(0.0, 1.0, 0.0), fractional);
  23. }
  24. else if(intPart < 3.0)
  25. {
  26. return mix(Vec3(0.0, 1.0, 0.0), Vec3(1.0, 1.0, 0.0), fractional);
  27. }
  28. else
  29. {
  30. return mix(Vec3(1.0, 1.0, 0.0), Vec3(1.0, 0.0, 0.0), fractional);
  31. }
  32. }
  33. class Octree::GatherParallelCtx
  34. {
  35. public:
  36. Octree* m_octree = nullptr;
  37. SpinLock m_lock;
  38. Array<Plane, 6> m_frustumPlanes;
  39. U32 m_testId = MAX_U32;
  40. OctreeNodeVisibilityTestCallback m_testCallback = nullptr;
  41. void* m_testCallbackUserData = nullptr;
  42. DynamicArrayAuto<void*>* m_out = nullptr;
  43. };
  44. class Octree::GatherParallelTaskCtx
  45. {
  46. public:
  47. GatherParallelCtx* m_ctx = nullptr;
  48. Leaf* m_leaf = nullptr;
  49. };
  50. Octree::~Octree()
  51. {
  52. ANKI_ASSERT(m_placeableCount == 0);
  53. cleanupInternal();
  54. ANKI_ASSERT(m_rootLeaf == nullptr);
  55. }
  56. void Octree::init(const Vec3& sceneAabbMin, const Vec3& sceneAabbMax, U32 maxDepth)
  57. {
  58. ANKI_ASSERT(sceneAabbMin < sceneAabbMax);
  59. ANKI_ASSERT(maxDepth > 0);
  60. m_maxDepth = maxDepth;
  61. m_sceneAabbMin = sceneAabbMin;
  62. m_sceneAabbMax = sceneAabbMax;
  63. }
  64. void Octree::place(const Aabb& volume, OctreePlaceable* placeable, Bool updateActualSceneBounds)
  65. {
  66. ANKI_ASSERT(placeable);
  67. ANKI_ASSERT(testCollision(volume, Aabb(m_sceneAabbMin, m_sceneAabbMax)) && "volume is outside the scene");
  68. LockGuard<Mutex> lock(m_globalMtx);
  69. // Remove the placeable from the Octree
  70. removeInternal(*placeable);
  71. // Create the root leaf
  72. if(!m_rootLeaf)
  73. {
  74. m_rootLeaf = newLeaf();
  75. m_rootLeaf->m_aabbMin = m_sceneAabbMin;
  76. m_rootLeaf->m_aabbMax = m_sceneAabbMax;
  77. }
  78. // And re-place it
  79. placeRecursive(volume, placeable, m_rootLeaf, 0);
  80. ++m_placeableCount;
  81. // Update the actual scene bounds
  82. if(updateActualSceneBounds)
  83. {
  84. m_actualSceneAabbMin = m_actualSceneAabbMin.min(volume.getMin().xyz());
  85. m_actualSceneAabbMax = m_actualSceneAabbMax.max(volume.getMax().xyz());
  86. }
  87. }
  88. void Octree::placeAlwaysVisible(OctreePlaceable* placeable)
  89. {
  90. ANKI_ASSERT(placeable);
  91. LockGuard<Mutex> lock(m_globalMtx);
  92. // Remove the placeable from the Octree
  93. removeInternal(*placeable);
  94. // Create the root leaf
  95. if(!m_rootLeaf)
  96. {
  97. m_rootLeaf = newLeaf();
  98. m_rootLeaf->m_aabbMin = m_sceneAabbMin;
  99. m_rootLeaf->m_aabbMax = m_sceneAabbMax;
  100. }
  101. // Connect placeable and leaf
  102. placeable->m_leafs.pushBack(newLeafNode(m_rootLeaf));
  103. m_rootLeaf->m_placeables.pushBack(newPlaceableNode(placeable));
  104. ++m_placeableCount;
  105. }
  106. void Octree::remove(OctreePlaceable& placeable)
  107. {
  108. LockGuard<Mutex> lock(m_globalMtx);
  109. removeInternal(placeable);
  110. }
  111. Bool Octree::volumeTotallyInsideLeaf(const Aabb& volume, const Leaf& leaf)
  112. {
  113. const Vec4& amin = volume.getMin();
  114. const Vec4& amax = volume.getMax();
  115. const Vec3& bmin = leaf.m_aabbMin;
  116. const Vec3& bmax = leaf.m_aabbMax;
  117. Bool superset = true;
  118. superset = superset && amin.x() <= bmin.x();
  119. superset = superset && amax.x() >= bmax.x();
  120. superset = superset && amin.y() <= bmin.y();
  121. superset = superset && amax.y() >= bmax.y();
  122. superset = superset && amin.z() <= bmin.z();
  123. superset = superset && amax.z() >= bmax.z();
  124. return superset;
  125. }
  126. void Octree::placeRecursive(const Aabb& volume, OctreePlaceable* placeable, Leaf* parent, U32 depth)
  127. {
  128. ANKI_ASSERT(placeable);
  129. ANKI_ASSERT(parent);
  130. ANKI_ASSERT(testCollision(volume, Aabb(parent->m_aabbMin, parent->m_aabbMax)) && "Should be inside");
  131. if(depth == m_maxDepth || volumeTotallyInsideLeaf(volume, *parent))
  132. {
  133. // Need to stop and bin the placeable to the leaf
  134. // Checks
  135. #if ANKI_ENABLE_ASSERTIONS
  136. for(const LeafNode& node : placeable->m_leafs)
  137. {
  138. ANKI_ASSERT(node.m_leaf != parent && "Already binned. That's wrong");
  139. }
  140. for(const PlaceableNode& node : parent->m_placeables)
  141. {
  142. ANKI_ASSERT(node.m_placeable != placeable);
  143. }
  144. #endif
  145. // Connect placeable and leaf
  146. placeable->m_leafs.pushBack(newLeafNode(parent));
  147. parent->m_placeables.pushBack(newPlaceableNode(placeable));
  148. return;
  149. }
  150. const Vec4& vMin = volume.getMin();
  151. const Vec4& vMax = volume.getMax();
  152. const Vec3 center = (parent->m_aabbMax + parent->m_aabbMin) / 2.0f;
  153. LeafMask maskX;
  154. if(vMin.x() > center.x())
  155. {
  156. // Only right
  157. maskX = LeafMask::RIGHT;
  158. }
  159. else if(vMax.x() < center.x())
  160. {
  161. // Only left
  162. maskX = LeafMask::LEFT;
  163. }
  164. else
  165. {
  166. maskX = LeafMask::ALL;
  167. }
  168. LeafMask maskY;
  169. if(vMin.y() > center.y())
  170. {
  171. // Only top
  172. maskY = LeafMask::TOP;
  173. }
  174. else if(vMax.y() < center.y())
  175. {
  176. // Only bottom
  177. maskY = LeafMask::BOTTOM;
  178. }
  179. else
  180. {
  181. maskY = LeafMask::ALL;
  182. }
  183. LeafMask maskZ;
  184. if(vMin.z() > center.z())
  185. {
  186. // Only front
  187. maskZ = LeafMask::FRONT;
  188. }
  189. else if(vMax.z() < center.z())
  190. {
  191. // Only back
  192. maskZ = LeafMask::BACK;
  193. }
  194. else
  195. {
  196. maskZ = LeafMask::ALL;
  197. }
  198. const LeafMask maskUnion = maskX & maskY & maskZ;
  199. ANKI_ASSERT(!!maskUnion && "Should be inside at least one leaf");
  200. for(U i = 0; i < 8; ++i)
  201. {
  202. const LeafMask crntBit = LeafMask(1u << i);
  203. if(!!(maskUnion & crntBit))
  204. {
  205. // Inside the leaf, move deeper
  206. // Create the leaf
  207. if(parent->m_children[i] == nullptr)
  208. {
  209. Leaf* child = newLeaf();
  210. // Compute AABB
  211. Vec3 childAabbMin, childAabbMax;
  212. computeChildAabb(crntBit, parent->m_aabbMin, parent->m_aabbMax, center, child->m_aabbMin,
  213. child->m_aabbMax);
  214. parent->m_children[i] = child;
  215. }
  216. // Move deeper
  217. placeRecursive(volume, placeable, parent->m_children[i], depth + 1);
  218. }
  219. }
  220. }
  221. void Octree::computeChildAabb(LeafMask child, const Vec3& parentAabbMin, const Vec3& parentAabbMax,
  222. const Vec3& parentAabbCenter, Vec3& childAabbMin, Vec3& childAabbMax)
  223. {
  224. ANKI_ASSERT(__builtin_popcount(U32(child)) == 1);
  225. const Vec3& m = parentAabbMin;
  226. const Vec3& M = parentAabbMax;
  227. const Vec3& c = parentAabbCenter;
  228. if(!!(child & LeafMask::RIGHT))
  229. {
  230. // Right
  231. childAabbMin.x() = c.x();
  232. childAabbMax.x() = M.x();
  233. }
  234. else
  235. {
  236. // Left
  237. childAabbMin.x() = m.x();
  238. childAabbMax.x() = c.x();
  239. }
  240. if(!!(child & LeafMask::TOP))
  241. {
  242. // Top
  243. childAabbMin.y() = c.y();
  244. childAabbMax.y() = M.y();
  245. }
  246. else
  247. {
  248. // Bottom
  249. childAabbMin.y() = m.y();
  250. childAabbMax.y() = c.y();
  251. }
  252. if(!!(child & LeafMask::FRONT))
  253. {
  254. // Front
  255. childAabbMin.z() = c.z();
  256. childAabbMax.z() = M.z();
  257. }
  258. else
  259. {
  260. // Back
  261. childAabbMin.z() = m.z();
  262. childAabbMax.z() = c.z();
  263. }
  264. }
  265. void Octree::removeInternal(OctreePlaceable& placeable)
  266. {
  267. const Bool isPlaced = !placeable.m_leafs.isEmpty();
  268. if(isPlaced)
  269. {
  270. while(!placeable.m_leafs.isEmpty())
  271. {
  272. // Pop a leaf node
  273. LeafNode* leafNode = placeable.m_leafs.popFront();
  274. // Iterate the placeables of the leaf
  275. Bool found = false;
  276. (void)found;
  277. for(PlaceableNode& placeableNode : leafNode->m_leaf->m_placeables)
  278. {
  279. if(placeableNode.m_placeable == &placeable)
  280. {
  281. found = true;
  282. leafNode->m_leaf->m_placeables.erase(&placeableNode);
  283. releasePlaceableNode(&placeableNode);
  284. break;
  285. }
  286. }
  287. ANKI_ASSERT(found);
  288. // Delete the leaf node
  289. releaseLeafNode(leafNode);
  290. }
  291. // Cleanup the tree if there are no placeables
  292. ANKI_ASSERT(m_placeableCount > 0);
  293. --m_placeableCount;
  294. if(m_placeableCount == 0)
  295. {
  296. cleanupInternal();
  297. ANKI_ASSERT(m_rootLeaf == nullptr);
  298. }
  299. }
  300. }
  301. void Octree::gatherVisibleRecursive(const Plane frustumPlanes[6], U32 testId,
  302. OctreeNodeVisibilityTestCallback testCallback, void* testCallbackUserData,
  303. Leaf* leaf, DynamicArrayAuto<void*>& out)
  304. {
  305. ANKI_ASSERT(leaf);
  306. // Add the placeables that belong to that leaf
  307. for(PlaceableNode& placeableNode : leaf->m_placeables)
  308. {
  309. if(!placeableNode.m_placeable->alreadyVisited(testId))
  310. {
  311. ANKI_ASSERT(placeableNode.m_placeable->m_userData);
  312. out.emplaceBack(placeableNode.m_placeable->m_userData);
  313. }
  314. }
  315. // Move to children leafs
  316. Aabb aabb;
  317. for(Leaf* child : leaf->m_children)
  318. {
  319. if(child)
  320. {
  321. aabb.setMin(child->m_aabbMin);
  322. aabb.setMax(child->m_aabbMax);
  323. Bool inside = true;
  324. for(U i = 0; i < 6; ++i)
  325. {
  326. if(testPlane(frustumPlanes[i], aabb) < 0.0f)
  327. {
  328. inside = false;
  329. break;
  330. }
  331. }
  332. if(inside && testCallback != nullptr)
  333. {
  334. inside = testCallback(testCallbackUserData, aabb);
  335. }
  336. if(inside)
  337. {
  338. gatherVisibleRecursive(frustumPlanes, testId, testCallback, testCallbackUserData, child, out);
  339. }
  340. }
  341. }
  342. }
  343. void Octree::cleanupRecursive(Leaf* leaf, Bool& canDeleteLeafUponReturn)
  344. {
  345. ANKI_ASSERT(leaf);
  346. canDeleteLeafUponReturn = leaf->m_placeables.getSize() == 0;
  347. // Do the children
  348. for(U i = 0; i < 8; ++i)
  349. {
  350. Leaf* const child = leaf->m_children[i];
  351. if(child)
  352. {
  353. Bool canDeleteChild;
  354. cleanupRecursive(child, canDeleteChild);
  355. if(canDeleteChild)
  356. {
  357. releaseLeaf(child);
  358. leaf->m_children[i] = nullptr;
  359. }
  360. else
  361. {
  362. canDeleteLeafUponReturn = false;
  363. }
  364. }
  365. }
  366. }
  367. void Octree::cleanupInternal()
  368. {
  369. if(m_rootLeaf)
  370. {
  371. Bool canDeleteLeaf;
  372. cleanupRecursive(m_rootLeaf, canDeleteLeaf);
  373. if(canDeleteLeaf)
  374. {
  375. releaseLeaf(m_rootLeaf);
  376. m_rootLeaf = nullptr;
  377. }
  378. }
  379. }
  380. void Octree::debugDrawRecursive(const Leaf& leaf, OctreeDebugDrawer& drawer) const
  381. {
  382. const U32 placeableCount = U32(leaf.m_placeables.getSize());
  383. const Vec3 color = (placeableCount > 0) ? heatmap(10.0f / F32(placeableCount)) : Vec3(0.25f);
  384. const Aabb box(leaf.m_aabbMin, leaf.m_aabbMax);
  385. drawer.drawCube(box, Vec4(color, 1.0f));
  386. for(U i = 0; i < 8; ++i)
  387. {
  388. Leaf* const child = leaf.m_children[i];
  389. if(child)
  390. {
  391. debugDrawRecursive(*child, drawer);
  392. }
  393. }
  394. }
  395. void Octree::gatherVisibleParallel(const Plane frustumPlanes[6], U32 testId,
  396. OctreeNodeVisibilityTestCallback testCallback, void* testCallbackUserData,
  397. DynamicArrayAuto<void*>* out, ThreadHive& hive, ThreadHiveSemaphore* waitSemaphore,
  398. ThreadHiveSemaphore*& signalSemaphore)
  399. {
  400. ANKI_ASSERT(out && frustumPlanes);
  401. // Create the ctx
  402. GatherParallelCtx* ctx = static_cast<GatherParallelCtx*>(
  403. hive.allocateScratchMemory(sizeof(GatherParallelCtx), alignof(GatherParallelCtx)));
  404. ctx->m_octree = this;
  405. memcpy(&ctx->m_frustumPlanes[0], frustumPlanes, sizeof(ctx->m_frustumPlanes));
  406. ctx->m_testId = testId;
  407. ctx->m_testCallback = testCallback;
  408. ctx->m_testCallbackUserData = testCallbackUserData;
  409. ctx->m_out = out;
  410. // Create the first test ctx
  411. GatherParallelTaskCtx* taskCtx = static_cast<GatherParallelTaskCtx*>(
  412. hive.allocateScratchMemory(sizeof(GatherParallelTaskCtx), alignof(GatherParallelTaskCtx)));
  413. taskCtx->m_ctx = ctx;
  414. taskCtx->m_leaf = m_rootLeaf;
  415. // Create signal semaphore
  416. signalSemaphore = hive.newSemaphore(1);
  417. // Fire the first task
  418. ThreadHiveTask task;
  419. task.m_callback = gatherVisibleTaskCallback;
  420. task.m_argument = taskCtx;
  421. task.m_signalSemaphore = signalSemaphore;
  422. task.m_waitSemaphore = waitSemaphore;
  423. hive.submitTasks(&task, 1);
  424. }
  425. void Octree::gatherVisibleTaskCallback(void* ud, U32 threadId, ThreadHive& hive, ThreadHiveSemaphore* sem)
  426. {
  427. ANKI_ASSERT(ud);
  428. GatherParallelTaskCtx* taskCtx = static_cast<GatherParallelTaskCtx*>(ud);
  429. taskCtx->m_ctx->m_octree->gatherVisibleParallelTask(threadId, hive, sem, *taskCtx);
  430. }
  431. void Octree::gatherVisibleParallelTask(U32 threadId, ThreadHive& hive, ThreadHiveSemaphore* sem,
  432. GatherParallelTaskCtx& taskCtx)
  433. {
  434. ANKI_ASSERT(taskCtx.m_ctx && taskCtx.m_leaf);
  435. GatherParallelCtx& ctx = *taskCtx.m_ctx;
  436. Leaf* const leaf = taskCtx.m_leaf;
  437. DynamicArrayAuto<void*>& out = *ctx.m_out;
  438. OctreeNodeVisibilityTestCallback testCallback = ctx.m_testCallback;
  439. void* testCallbackUserData = ctx.m_testCallbackUserData;
  440. const U32 testId = ctx.m_testId;
  441. // Add the placeables that belong to that leaf
  442. if(leaf->m_placeables.getSize() > 0)
  443. {
  444. LockGuard<SpinLock> lock(taskCtx.m_ctx->m_lock);
  445. for(PlaceableNode& placeableNode : leaf->m_placeables)
  446. {
  447. if(!placeableNode.m_placeable->alreadyVisited(testId))
  448. {
  449. ANKI_ASSERT(placeableNode.m_placeable->m_userData);
  450. out.emplaceBack(placeableNode.m_placeable->m_userData);
  451. }
  452. }
  453. }
  454. // Move to children leafs
  455. Array<ThreadHiveTask, 8> tasks;
  456. U32 taskCount = 0;
  457. Aabb aabb;
  458. for(Leaf* child : leaf->m_children)
  459. {
  460. if(child)
  461. {
  462. aabb.setMin(child->m_aabbMin);
  463. aabb.setMax(child->m_aabbMax);
  464. Bool inside = true;
  465. for(U i = 0; i < 6; ++i)
  466. {
  467. if(testPlane(taskCtx.m_ctx->m_frustumPlanes[i], aabb) < 0.0f)
  468. {
  469. inside = false;
  470. break;
  471. }
  472. }
  473. if(inside && testCallback != nullptr)
  474. {
  475. inside = testCallback(testCallbackUserData, aabb);
  476. }
  477. if(inside)
  478. {
  479. // New task ctx
  480. GatherParallelTaskCtx* newTaskCtx = static_cast<GatherParallelTaskCtx*>(
  481. hive.allocateScratchMemory(sizeof(GatherParallelTaskCtx), alignof(GatherParallelTaskCtx)));
  482. newTaskCtx->m_ctx = taskCtx.m_ctx;
  483. newTaskCtx->m_leaf = child;
  484. // Populate the task
  485. ThreadHiveTask& task = tasks[taskCount++];
  486. task.m_callback = gatherVisibleTaskCallback;
  487. task.m_argument = newTaskCtx;
  488. task.m_signalSemaphore = sem;
  489. }
  490. }
  491. }
  492. // Submit all tasks at once
  493. if(taskCount)
  494. {
  495. // At this point do a trick. Increase the semaphore value to keep blocking the tasks that depend on the
  496. // gather
  497. sem->increaseSemaphore(taskCount);
  498. // Submit
  499. hive.submitTasks(&tasks[0], taskCount);
  500. }
  501. }
  502. } // end namespace anki