Octree.cpp 13 KB

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