QuadTree.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Collision/BroadPhase/QuadTree.h>
  6. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseQuadTree.h>
  7. #include <Jolt/Physics/Collision/RayCast.h>
  8. #include <Jolt/Physics/Collision/AABoxCast.h>
  9. #include <Jolt/Physics/Collision/CastResult.h>
  10. #include <Jolt/Physics/Collision/SortReverseAndStore.h>
  11. #include <Jolt/Physics/Body/BodyPair.h>
  12. #include <Jolt/Physics/PhysicsLock.h>
  13. #include <Jolt/Geometry/AABox4.h>
  14. #include <Jolt/Geometry/RayAABox.h>
  15. #include <Jolt/Geometry/OrientedBox.h>
  16. #include <Jolt/Core/STLLocalAllocator.h>
  17. #ifdef JPH_DUMP_BROADPHASE_TREE
  18. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  19. #include <fstream>
  20. JPH_SUPPRESS_WARNINGS_STD_END
  21. #endif // JPH_DUMP_BROADPHASE_TREE
  22. JPH_NAMESPACE_BEGIN
  23. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  24. // QuadTree::Node
  25. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  26. QuadTree::Node::Node(bool inIsChanged) :
  27. mIsChanged(inIsChanged)
  28. {
  29. // First reset bounds
  30. Vec4 val = Vec4::sReplicate(cLargeFloat);
  31. val.StoreFloat4((Float4 *)&mBoundsMinX);
  32. val.StoreFloat4((Float4 *)&mBoundsMinY);
  33. val.StoreFloat4((Float4 *)&mBoundsMinZ);
  34. val = Vec4::sReplicate(-cLargeFloat);
  35. val.StoreFloat4((Float4 *)&mBoundsMaxX);
  36. val.StoreFloat4((Float4 *)&mBoundsMaxY);
  37. val.StoreFloat4((Float4 *)&mBoundsMaxZ);
  38. // Reset child node ids
  39. mChildNodeID[0] = NodeID::sInvalid();
  40. mChildNodeID[1] = NodeID::sInvalid();
  41. mChildNodeID[2] = NodeID::sInvalid();
  42. mChildNodeID[3] = NodeID::sInvalid();
  43. }
  44. void QuadTree::Node::GetChildBounds(int inChildIndex, AABox &outBounds) const
  45. {
  46. // Read bounding box in order min -> max
  47. outBounds.mMin = Vec3(mBoundsMinX[inChildIndex], mBoundsMinY[inChildIndex], mBoundsMinZ[inChildIndex]);
  48. outBounds.mMax = Vec3(mBoundsMaxX[inChildIndex], mBoundsMaxY[inChildIndex], mBoundsMaxZ[inChildIndex]);
  49. }
  50. void QuadTree::Node::SetChildBounds(int inChildIndex, const AABox &inBounds)
  51. {
  52. // Bounding boxes provided to the quad tree should never be larger than cLargeFloat because this may trigger overflow exceptions
  53. // e.g. when squaring the value while testing sphere overlaps
  54. JPH_ASSERT(inBounds.mMin.GetX() >= -cLargeFloat && inBounds.mMin.GetX() <= cLargeFloat
  55. && inBounds.mMin.GetY() >= -cLargeFloat && inBounds.mMin.GetY() <= cLargeFloat
  56. && inBounds.mMin.GetZ() >= -cLargeFloat && inBounds.mMin.GetZ() <= cLargeFloat
  57. && inBounds.mMax.GetX() >= -cLargeFloat && inBounds.mMax.GetX() <= cLargeFloat
  58. && inBounds.mMax.GetY() >= -cLargeFloat && inBounds.mMax.GetY() <= cLargeFloat
  59. && inBounds.mMax.GetZ() >= -cLargeFloat && inBounds.mMax.GetZ() <= cLargeFloat);
  60. // Set max first (this keeps the bounding box invalid for reading threads)
  61. mBoundsMaxZ[inChildIndex] = inBounds.mMax.GetZ();
  62. mBoundsMaxY[inChildIndex] = inBounds.mMax.GetY();
  63. mBoundsMaxX[inChildIndex] = inBounds.mMax.GetX();
  64. // Then set min (and make box valid)
  65. mBoundsMinZ[inChildIndex] = inBounds.mMin.GetZ();
  66. mBoundsMinY[inChildIndex] = inBounds.mMin.GetY();
  67. mBoundsMinX[inChildIndex] = inBounds.mMin.GetX(); // Min X becomes valid last
  68. }
  69. void QuadTree::Node::InvalidateChildBounds(int inChildIndex)
  70. {
  71. // First we make the box invalid by setting the min to cLargeFloat
  72. mBoundsMinX[inChildIndex] = cLargeFloat; // Min X becomes invalid first
  73. mBoundsMinY[inChildIndex] = cLargeFloat;
  74. mBoundsMinZ[inChildIndex] = cLargeFloat;
  75. // Then we reset the max values too
  76. mBoundsMaxX[inChildIndex] = -cLargeFloat;
  77. mBoundsMaxY[inChildIndex] = -cLargeFloat;
  78. mBoundsMaxZ[inChildIndex] = -cLargeFloat;
  79. }
  80. void QuadTree::Node::GetNodeBounds(AABox &outBounds) const
  81. {
  82. // Get first child bounds
  83. GetChildBounds(0, outBounds);
  84. // Encapsulate other child bounds
  85. for (int child_idx = 1; child_idx < 4; ++child_idx)
  86. {
  87. AABox tmp;
  88. GetChildBounds(child_idx, tmp);
  89. outBounds.Encapsulate(tmp);
  90. }
  91. }
  92. bool QuadTree::Node::EncapsulateChildBounds(int inChildIndex, const AABox &inBounds)
  93. {
  94. bool changed = AtomicMin(mBoundsMinX[inChildIndex], inBounds.mMin.GetX());
  95. changed |= AtomicMin(mBoundsMinY[inChildIndex], inBounds.mMin.GetY());
  96. changed |= AtomicMin(mBoundsMinZ[inChildIndex], inBounds.mMin.GetZ());
  97. changed |= AtomicMax(mBoundsMaxX[inChildIndex], inBounds.mMax.GetX());
  98. changed |= AtomicMax(mBoundsMaxY[inChildIndex], inBounds.mMax.GetY());
  99. changed |= AtomicMax(mBoundsMaxZ[inChildIndex], inBounds.mMax.GetZ());
  100. return changed;
  101. }
  102. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  103. // QuadTree
  104. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  105. const AABox QuadTree::cInvalidBounds(Vec3::sReplicate(cLargeFloat), Vec3::sReplicate(-cLargeFloat));
  106. void QuadTree::GetBodyLocation(const TrackingVector &inTracking, BodyID inBodyID, uint32 &outNodeIdx, uint32 &outChildIdx) const
  107. {
  108. uint32 body_location = inTracking[inBodyID.GetIndex()].mBodyLocation;
  109. JPH_ASSERT(body_location != Tracking::cInvalidBodyLocation);
  110. outNodeIdx = body_location & 0x3fffffff;
  111. outChildIdx = body_location >> 30;
  112. JPH_ASSERT(mAllocator->Get(outNodeIdx).mChildNodeID[outChildIdx] == inBodyID, "Make sure that the body is in the node where it should be");
  113. }
  114. void QuadTree::SetBodyLocation(TrackingVector &ioTracking, BodyID inBodyID, uint32 inNodeIdx, uint32 inChildIdx) const
  115. {
  116. JPH_ASSERT(inNodeIdx <= 0x3fffffff);
  117. JPH_ASSERT(inChildIdx < 4);
  118. JPH_ASSERT(mAllocator->Get(inNodeIdx).mChildNodeID[inChildIdx] == inBodyID, "Make sure that the body is in the node where it should be");
  119. ioTracking[inBodyID.GetIndex()].mBodyLocation = inNodeIdx + (inChildIdx << 30);
  120. #ifdef JPH_ENABLE_ASSERTS
  121. uint32 v1, v2;
  122. GetBodyLocation(ioTracking, inBodyID, v1, v2);
  123. JPH_ASSERT(v1 == inNodeIdx);
  124. JPH_ASSERT(v2 == inChildIdx);
  125. #endif
  126. }
  127. void QuadTree::sInvalidateBodyLocation(TrackingVector &ioTracking, BodyID inBodyID)
  128. {
  129. ioTracking[inBodyID.GetIndex()].mBodyLocation = Tracking::cInvalidBodyLocation;
  130. }
  131. QuadTree::~QuadTree()
  132. {
  133. // Get rid of any nodes that are still to be freed
  134. DiscardOldTree();
  135. // Get the current root node
  136. const RootNode &root_node = GetCurrentRoot();
  137. // Collect all bodies
  138. Allocator::Batch free_batch;
  139. Array<NodeID, STLLocalAllocator<NodeID, cStackSize>> node_stack;
  140. node_stack.reserve(cStackSize);
  141. node_stack.push_back(root_node.GetNodeID());
  142. JPH_ASSERT(node_stack.front().IsValid());
  143. if (node_stack.front().IsNode())
  144. {
  145. do
  146. {
  147. // Process node
  148. NodeID node_id = node_stack.back();
  149. node_stack.pop_back();
  150. JPH_ASSERT(!node_id.IsBody());
  151. uint32 node_idx = node_id.GetNodeIndex();
  152. const Node &node = mAllocator->Get(node_idx);
  153. // Recurse and get all child nodes
  154. for (NodeID child_node_id : node.mChildNodeID)
  155. if (child_node_id.IsValid() && child_node_id.IsNode())
  156. node_stack.push_back(child_node_id);
  157. // Mark node to be freed
  158. mAllocator->AddObjectToBatch(free_batch, node_idx);
  159. }
  160. while (!node_stack.empty());
  161. }
  162. // Now free all nodes
  163. mAllocator->DestructObjectBatch(free_batch);
  164. }
  165. uint32 QuadTree::AllocateNode(bool inIsChanged)
  166. {
  167. uint32 index = mAllocator->ConstructObject(inIsChanged);
  168. if (index == Allocator::cInvalidObjectIndex)
  169. {
  170. Trace("QuadTree: Out of nodes!");
  171. std::abort();
  172. }
  173. return index;
  174. }
  175. void QuadTree::Init(Allocator &inAllocator)
  176. {
  177. // Store allocator
  178. mAllocator = &inAllocator;
  179. // Allocate root node
  180. mRootNode[mRootNodeIndex].mIndex = AllocateNode(false);
  181. }
  182. void QuadTree::DiscardOldTree()
  183. {
  184. // Check if there is an old tree
  185. RootNode &old_root_node = mRootNode[mRootNodeIndex ^ 1];
  186. if (old_root_node.mIndex != cInvalidNodeIndex)
  187. {
  188. // Clear the root
  189. old_root_node.mIndex = cInvalidNodeIndex;
  190. // Now free all old nodes
  191. mAllocator->DestructObjectBatch(mFreeNodeBatch);
  192. // Clear the batch
  193. mFreeNodeBatch = Allocator::Batch();
  194. }
  195. }
  196. AABox QuadTree::GetBounds() const
  197. {
  198. uint32 node_idx = GetCurrentRoot().mIndex;
  199. JPH_ASSERT(node_idx != cInvalidNodeIndex);
  200. const Node &node = mAllocator->Get(node_idx);
  201. AABox bounds;
  202. node.GetNodeBounds(bounds);
  203. return bounds;
  204. }
  205. void QuadTree::UpdatePrepare(const BodyVector &inBodies, TrackingVector &ioTracking, UpdateState &outUpdateState, bool inFullRebuild)
  206. {
  207. #ifdef JPH_ENABLE_ASSERTS
  208. // We only read positions
  209. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  210. #endif
  211. // Assert we have no nodes pending deletion, this means DiscardOldTree wasn't called yet
  212. JPH_ASSERT(mFreeNodeBatch.mNumObjects == 0);
  213. // Mark tree non-dirty
  214. mIsDirty = false;
  215. // Get the current root node
  216. const RootNode &root_node = GetCurrentRoot();
  217. #ifdef JPH_DUMP_BROADPHASE_TREE
  218. DumpTree(root_node.GetNodeID(), StringFormat("%s_PRE", mName).c_str());
  219. #endif
  220. // Assert sane data
  221. #ifdef JPH_DEBUG
  222. ValidateTree(inBodies, ioTracking, root_node.mIndex, mNumBodies);
  223. #endif
  224. // Create space for all body ID's
  225. NodeID *node_ids = new NodeID [mNumBodies];
  226. NodeID *cur_node_id = node_ids;
  227. // Collect all bodies
  228. NodeID node_stack[cStackSize];
  229. node_stack[0] = root_node.GetNodeID();
  230. JPH_ASSERT(node_stack[0].IsValid());
  231. int top = 0;
  232. do
  233. {
  234. // Check if node is a body
  235. NodeID node_id = node_stack[top];
  236. if (node_id.IsBody())
  237. {
  238. // Validate that we're still in the right layer
  239. #ifdef JPH_ENABLE_ASSERTS
  240. uint32 body_index = node_id.GetBodyID().GetIndex();
  241. JPH_ASSERT(ioTracking[body_index].mObjectLayer == inBodies[body_index]->GetObjectLayer());
  242. #endif
  243. // Store body
  244. *cur_node_id = node_id;
  245. ++cur_node_id;
  246. }
  247. else
  248. {
  249. // Process normal node
  250. uint32 node_idx = node_id.GetNodeIndex();
  251. const Node &node = mAllocator->Get(node_idx);
  252. if (!node.mIsChanged && !inFullRebuild)
  253. {
  254. // Node is unchanged, treat it as a whole
  255. *cur_node_id = node_id;
  256. ++cur_node_id;
  257. }
  258. else
  259. {
  260. // Node is changed, recurse and get all children
  261. for (NodeID child_node_id : node.mChildNodeID)
  262. if (child_node_id.IsValid())
  263. {
  264. if (top < cStackSize)
  265. {
  266. node_stack[top] = child_node_id;
  267. top++;
  268. }
  269. else
  270. {
  271. JPH_ASSERT(false, "Stack full!\n"
  272. "This must be a very deep tree. Are you batch adding bodies through BodyInterface::AddBodiesPrepare/AddBodiesFinalize?\n"
  273. "If you add lots of bodies through BodyInterface::AddBody you may need to call PhysicsSystem::OptimizeBroadPhase to rebuild the tree.");
  274. // Falling back to adding the node as a whole
  275. *cur_node_id = child_node_id;
  276. ++cur_node_id;
  277. }
  278. }
  279. // Mark node to be freed
  280. mAllocator->AddObjectToBatch(mFreeNodeBatch, node_idx);
  281. }
  282. }
  283. --top;
  284. }
  285. while (top >= 0);
  286. // Check that our book keeping matches
  287. uint32 num_node_ids = uint32(cur_node_id - node_ids);
  288. JPH_ASSERT(inFullRebuild? num_node_ids == mNumBodies : num_node_ids <= mNumBodies);
  289. // This will be the new root node id
  290. NodeID root_node_id;
  291. if (num_node_ids > 0)
  292. {
  293. // We mark the first 5 levels (max 1024 nodes) of the newly built tree as 'changed' so that
  294. // those nodes get recreated every time when we rebuild the tree. This balances the amount of
  295. // time we spend on rebuilding the tree ('unchanged' nodes will be put in the new tree as a whole)
  296. // vs the quality of the built tree.
  297. constexpr uint cMaxDepthMarkChanged = 5;
  298. // Build new tree
  299. AABox root_bounds;
  300. root_node_id = BuildTree(inBodies, ioTracking, node_ids, num_node_ids, cMaxDepthMarkChanged, root_bounds);
  301. if (root_node_id.IsBody())
  302. {
  303. // For a single body we need to allocate a new root node
  304. uint32 root_idx = AllocateNode(false);
  305. Node &root = mAllocator->Get(root_idx);
  306. root.SetChildBounds(0, root_bounds);
  307. root.mChildNodeID[0] = root_node_id;
  308. SetBodyLocation(ioTracking, root_node_id.GetBodyID(), root_idx, 0);
  309. root_node_id = NodeID::sFromNodeIndex(root_idx);
  310. }
  311. }
  312. else
  313. {
  314. // Empty tree, create root node
  315. uint32 root_idx = AllocateNode(false);
  316. root_node_id = NodeID::sFromNodeIndex(root_idx);
  317. }
  318. // Delete temporary data
  319. delete [] node_ids;
  320. outUpdateState.mRootNodeID = root_node_id;
  321. }
  322. void QuadTree::UpdateFinalize([[maybe_unused]] const BodyVector &inBodies, [[maybe_unused]] const TrackingVector &inTracking, const UpdateState &inUpdateState)
  323. {
  324. // Tree building is complete, now we switch the old with the new tree
  325. uint32 new_root_idx = mRootNodeIndex ^ 1;
  326. RootNode &new_root_node = mRootNode[new_root_idx];
  327. {
  328. // Note: We don't need to lock here as the old tree stays available so any queries
  329. // that use it can continue using it until DiscardOldTree is called. This slot
  330. // should be empty and unused at this moment.
  331. JPH_ASSERT(new_root_node.mIndex == cInvalidNodeIndex);
  332. new_root_node.mIndex = inUpdateState.mRootNodeID.GetNodeIndex();
  333. }
  334. // All queries that start from now on will use this new tree
  335. mRootNodeIndex = new_root_idx;
  336. #ifdef JPH_DUMP_BROADPHASE_TREE
  337. DumpTree(new_root_node.GetNodeID(), StringFormat("%s_POST", mName).c_str());
  338. #endif
  339. #ifdef JPH_DEBUG
  340. ValidateTree(inBodies, inTracking, new_root_node.mIndex, mNumBodies);
  341. #endif
  342. }
  343. void QuadTree::sPartition(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inNumber, int &outMidPoint)
  344. {
  345. // Handle trivial case
  346. if (inNumber <= 4)
  347. {
  348. outMidPoint = inNumber / 2;
  349. return;
  350. }
  351. // Calculate bounding box of box centers
  352. Vec3 center_min = Vec3::sReplicate(cLargeFloat);
  353. Vec3 center_max = Vec3::sReplicate(-cLargeFloat);
  354. for (const Vec3 *c = ioNodeCenters, *c_end = ioNodeCenters + inNumber; c < c_end; ++c)
  355. {
  356. Vec3 center = *c;
  357. center_min = Vec3::sMin(center_min, center);
  358. center_max = Vec3::sMax(center_max, center);
  359. }
  360. // Calculate split plane
  361. int dimension = (center_max - center_min).GetHighestComponentIndex();
  362. float split = 0.5f * (center_min + center_max)[dimension];
  363. // Divide bodies
  364. int start = 0, end = inNumber;
  365. while (start < end)
  366. {
  367. // Search for first element that is on the right hand side of the split plane
  368. while (start < end && ioNodeCenters[start][dimension] < split)
  369. ++start;
  370. // Search for the first element that is on the left hand side of the split plane
  371. while (start < end && ioNodeCenters[end - 1][dimension] >= split)
  372. --end;
  373. if (start < end)
  374. {
  375. // Swap the two elements
  376. std::swap(ioNodeIDs[start], ioNodeIDs[end - 1]);
  377. std::swap(ioNodeCenters[start], ioNodeCenters[end - 1]);
  378. ++start;
  379. --end;
  380. }
  381. }
  382. JPH_ASSERT(start == end);
  383. if (start > 0 && start < inNumber)
  384. {
  385. // Success!
  386. outMidPoint = start;
  387. }
  388. else
  389. {
  390. // Failed to divide bodies
  391. outMidPoint = inNumber / 2;
  392. }
  393. }
  394. void QuadTree::sPartition4(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inBegin, int inEnd, int *outSplit)
  395. {
  396. NodeID *node_ids = ioNodeIDs + inBegin;
  397. Vec3 *node_centers = ioNodeCenters + inBegin;
  398. int number = inEnd - inBegin;
  399. // Partition entire range
  400. sPartition(node_ids, node_centers, number, outSplit[2]);
  401. // Partition lower half
  402. sPartition(node_ids, node_centers, outSplit[2], outSplit[1]);
  403. // Partition upper half
  404. sPartition(node_ids + outSplit[2], node_centers + outSplit[2], number - outSplit[2], outSplit[3]);
  405. // Convert to proper range
  406. outSplit[0] = inBegin;
  407. outSplit[1] += inBegin;
  408. outSplit[2] += inBegin;
  409. outSplit[3] += outSplit[2];
  410. outSplit[4] = inEnd;
  411. }
  412. AABox QuadTree::GetNodeOrBodyBounds(const BodyVector &inBodies, NodeID inNodeID) const
  413. {
  414. if (inNodeID.IsNode())
  415. {
  416. // It is a node
  417. uint32 node_idx = inNodeID.GetNodeIndex();
  418. const Node &node = mAllocator->Get(node_idx);
  419. AABox bounds;
  420. node.GetNodeBounds(bounds);
  421. return bounds;
  422. }
  423. else
  424. {
  425. // It is a body
  426. return inBodies[inNodeID.GetBodyID().GetIndex()]->GetWorldSpaceBounds();
  427. }
  428. }
  429. QuadTree::NodeID QuadTree::BuildTree(const BodyVector &inBodies, TrackingVector &ioTracking, NodeID *ioNodeIDs, int inNumber, uint inMaxDepthMarkChanged, AABox &outBounds)
  430. {
  431. // Trivial case: No bodies in tree
  432. if (inNumber == 0)
  433. {
  434. outBounds = cInvalidBounds;
  435. return NodeID::sInvalid();
  436. }
  437. // Trivial case: When we have 1 body or node, return it
  438. if (inNumber == 1)
  439. {
  440. if (ioNodeIDs->IsNode())
  441. {
  442. // When returning an existing node as root, ensure that no parent has been set
  443. Node &node = mAllocator->Get(ioNodeIDs->GetNodeIndex());
  444. node.mParentNodeIndex = cInvalidNodeIndex;
  445. }
  446. outBounds = GetNodeOrBodyBounds(inBodies, *ioNodeIDs);
  447. return *ioNodeIDs;
  448. }
  449. // Calculate centers of all bodies that are to be inserted
  450. Vec3 *centers = new Vec3 [inNumber];
  451. JPH_ASSERT(IsAligned(centers, JPH_VECTOR_ALIGNMENT));
  452. Vec3 *c = centers;
  453. for (const NodeID *n = ioNodeIDs, *n_end = ioNodeIDs + inNumber; n < n_end; ++n, ++c)
  454. *c = GetNodeOrBodyBounds(inBodies, *n).GetCenter();
  455. // The algorithm is a recursive tree build, but to avoid the call overhead we keep track of a stack here
  456. struct StackEntry
  457. {
  458. uint32 mNodeIdx; // Node index of node that is generated
  459. int mChildIdx; // Index of child that we're currently processing
  460. int mSplit[5]; // Indices where the node ID's have been split to form 4 partitions
  461. uint32 mDepth; // Depth of this node in the tree
  462. Vec3 mNodeBoundsMin; // Bounding box of this node, accumulated while iterating over children
  463. Vec3 mNodeBoundsMax;
  464. };
  465. static_assert(sizeof(StackEntry) == 64);
  466. StackEntry stack[cStackSize / 4]; // We don't process 4 at a time in this loop but 1, so the stack can be 4x as small
  467. int top = 0;
  468. // Create root node
  469. stack[0].mNodeIdx = AllocateNode(inMaxDepthMarkChanged > 0);
  470. stack[0].mChildIdx = -1;
  471. stack[0].mDepth = 0;
  472. stack[0].mNodeBoundsMin = Vec3::sReplicate(cLargeFloat);
  473. stack[0].mNodeBoundsMax = Vec3::sReplicate(-cLargeFloat);
  474. sPartition4(ioNodeIDs, centers, 0, inNumber, stack[0].mSplit);
  475. for (;;)
  476. {
  477. StackEntry &cur_stack = stack[top];
  478. // Next child
  479. cur_stack.mChildIdx++;
  480. // Check if all children processed
  481. if (cur_stack.mChildIdx >= 4)
  482. {
  483. // Terminate if there's nothing left to pop
  484. if (top <= 0)
  485. break;
  486. // Add our bounds to our parents bounds
  487. StackEntry &prev_stack = stack[top - 1];
  488. prev_stack.mNodeBoundsMin = Vec3::sMin(prev_stack.mNodeBoundsMin, cur_stack.mNodeBoundsMin);
  489. prev_stack.mNodeBoundsMax = Vec3::sMax(prev_stack.mNodeBoundsMax, cur_stack.mNodeBoundsMax);
  490. // Store parent node
  491. Node &node = mAllocator->Get(cur_stack.mNodeIdx);
  492. node.mParentNodeIndex = prev_stack.mNodeIdx;
  493. // Store this node's properties in the parent node
  494. Node &parent_node = mAllocator->Get(prev_stack.mNodeIdx);
  495. parent_node.mChildNodeID[prev_stack.mChildIdx] = NodeID::sFromNodeIndex(cur_stack.mNodeIdx);
  496. parent_node.SetChildBounds(prev_stack.mChildIdx, AABox(cur_stack.mNodeBoundsMin, cur_stack.mNodeBoundsMax));
  497. // Pop entry from stack
  498. --top;
  499. }
  500. else
  501. {
  502. // Get low and high index to bodies to process
  503. int low = cur_stack.mSplit[cur_stack.mChildIdx];
  504. int high = cur_stack.mSplit[cur_stack.mChildIdx + 1];
  505. int num_bodies = high - low;
  506. if (num_bodies == 1)
  507. {
  508. // Get body info
  509. NodeID child_node_id = ioNodeIDs[low];
  510. AABox bounds = GetNodeOrBodyBounds(inBodies, child_node_id);
  511. // Update node
  512. Node &node = mAllocator->Get(cur_stack.mNodeIdx);
  513. node.mChildNodeID[cur_stack.mChildIdx] = child_node_id;
  514. node.SetChildBounds(cur_stack.mChildIdx, bounds);
  515. if (child_node_id.IsNode())
  516. {
  517. // Update parent for this node
  518. Node &child_node = mAllocator->Get(child_node_id.GetNodeIndex());
  519. child_node.mParentNodeIndex = cur_stack.mNodeIdx;
  520. }
  521. else
  522. {
  523. // Set location in tracking
  524. SetBodyLocation(ioTracking, child_node_id.GetBodyID(), cur_stack.mNodeIdx, cur_stack.mChildIdx);
  525. }
  526. // Encapsulate bounding box in parent
  527. cur_stack.mNodeBoundsMin = Vec3::sMin(cur_stack.mNodeBoundsMin, bounds.mMin);
  528. cur_stack.mNodeBoundsMax = Vec3::sMax(cur_stack.mNodeBoundsMax, bounds.mMax);
  529. }
  530. else if (num_bodies > 1)
  531. {
  532. // Allocate new node
  533. StackEntry &new_stack = stack[++top];
  534. JPH_ASSERT(top < cStackSize / 4);
  535. uint32 next_depth = cur_stack.mDepth + 1;
  536. new_stack.mNodeIdx = AllocateNode(inMaxDepthMarkChanged > next_depth);
  537. new_stack.mChildIdx = -1;
  538. new_stack.mDepth = next_depth;
  539. new_stack.mNodeBoundsMin = Vec3::sReplicate(cLargeFloat);
  540. new_stack.mNodeBoundsMax = Vec3::sReplicate(-cLargeFloat);
  541. sPartition4(ioNodeIDs, centers, low, high, new_stack.mSplit);
  542. }
  543. }
  544. }
  545. // Delete temporary data
  546. delete [] centers;
  547. // Store bounding box of root
  548. outBounds.mMin = stack[0].mNodeBoundsMin;
  549. outBounds.mMax = stack[0].mNodeBoundsMax;
  550. // Return root
  551. return NodeID::sFromNodeIndex(stack[0].mNodeIdx);
  552. }
  553. void QuadTree::MarkNodeAndParentsChanged(uint32 inNodeIndex)
  554. {
  555. uint32 node_idx = inNodeIndex;
  556. do
  557. {
  558. // If node has changed, parent will be too
  559. Node &node = mAllocator->Get(node_idx);
  560. if (node.mIsChanged)
  561. break;
  562. // Mark node as changed
  563. node.mIsChanged = true;
  564. // Get our parent
  565. node_idx = node.mParentNodeIndex;
  566. }
  567. while (node_idx != cInvalidNodeIndex);
  568. }
  569. void QuadTree::WidenAndMarkNodeAndParentsChanged(uint32 inNodeIndex, const AABox &inNewBounds)
  570. {
  571. uint32 node_idx = inNodeIndex;
  572. for (;;)
  573. {
  574. // Mark node as changed
  575. Node &node = mAllocator->Get(node_idx);
  576. node.mIsChanged = true;
  577. // Get our parent
  578. uint32 parent_idx = node.mParentNodeIndex;
  579. if (parent_idx == cInvalidNodeIndex)
  580. break;
  581. // Find which child of the parent we're in
  582. Node &parent_node = mAllocator->Get(parent_idx);
  583. NodeID node_id = NodeID::sFromNodeIndex(node_idx);
  584. int child_idx = -1;
  585. for (int i = 0; i < 4; ++i)
  586. if (parent_node.mChildNodeID[i] == node_id)
  587. {
  588. // Found one, set the node index and child index and update the bounding box too
  589. child_idx = i;
  590. break;
  591. }
  592. JPH_ASSERT(child_idx != -1, "Nodes don't get removed from the tree, we must have found it");
  593. // To avoid any race conditions with other threads we only enlarge bounding boxes
  594. if (!parent_node.EncapsulateChildBounds(child_idx, inNewBounds))
  595. {
  596. // No changes to bounding box, only marking as changed remains to be done
  597. if (!parent_node.mIsChanged)
  598. MarkNodeAndParentsChanged(parent_idx);
  599. break;
  600. }
  601. // Update node index
  602. node_idx = parent_idx;
  603. }
  604. }
  605. bool QuadTree::TryInsertLeaf(TrackingVector &ioTracking, int inNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies)
  606. {
  607. // Tentatively assign the node as parent
  608. bool leaf_is_node = inLeafID.IsNode();
  609. if (leaf_is_node)
  610. {
  611. uint32 leaf_idx = inLeafID.GetNodeIndex();
  612. mAllocator->Get(leaf_idx).mParentNodeIndex = inNodeIndex;
  613. }
  614. // Fetch node that we're adding to
  615. Node &node = mAllocator->Get(inNodeIndex);
  616. // Find an empty child
  617. for (uint32 child_idx = 0; child_idx < 4; ++child_idx)
  618. if (node.mChildNodeID[child_idx].CompareExchange(NodeID::sInvalid(), inLeafID)) // Check if we can claim it
  619. {
  620. // We managed to add it to the node
  621. // If leaf was a body, we need to update its bookkeeping
  622. if (!leaf_is_node)
  623. SetBodyLocation(ioTracking, inLeafID.GetBodyID(), inNodeIndex, child_idx);
  624. // Now set the bounding box making the child valid for queries
  625. node.SetChildBounds(child_idx, inLeafBounds);
  626. // Widen the bounds for our parents too
  627. WidenAndMarkNodeAndParentsChanged(inNodeIndex, inLeafBounds);
  628. // Update body counter
  629. mNumBodies += inLeafNumBodies;
  630. // And we're done
  631. return true;
  632. }
  633. return false;
  634. }
  635. bool QuadTree::TryCreateNewRoot(TrackingVector &ioTracking, atomic<uint32> &ioRootNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies)
  636. {
  637. // Fetch old root
  638. uint32 root_idx = ioRootNodeIndex;
  639. Node &root = mAllocator->Get(root_idx);
  640. // Create new root, mark this new root as changed as we're not creating a very efficient tree at this point
  641. uint32 new_root_idx = AllocateNode(true);
  642. Node &new_root = mAllocator->Get(new_root_idx);
  643. // First child is current root, note that since the tree may be modified concurrently we cannot assume that the bounds of our child will be correct so we set a very large bounding box
  644. new_root.mChildNodeID[0] = NodeID::sFromNodeIndex(root_idx);
  645. new_root.SetChildBounds(0, AABox(Vec3::sReplicate(-cLargeFloat), Vec3::sReplicate(cLargeFloat)));
  646. // Second child is new leaf
  647. new_root.mChildNodeID[1] = inLeafID;
  648. new_root.SetChildBounds(1, inLeafBounds);
  649. // Tentatively assign new root as parent
  650. bool leaf_is_node = inLeafID.IsNode();
  651. if (leaf_is_node)
  652. {
  653. uint32 leaf_idx = inLeafID.GetNodeIndex();
  654. mAllocator->Get(leaf_idx).mParentNodeIndex = new_root_idx;
  655. }
  656. // Try to swap it
  657. if (ioRootNodeIndex.compare_exchange_strong(root_idx, new_root_idx))
  658. {
  659. // We managed to set the new root
  660. // If leaf was a body, we need to update its bookkeeping
  661. if (!leaf_is_node)
  662. SetBodyLocation(ioTracking, inLeafID.GetBodyID(), new_root_idx, 1);
  663. // Store parent node for old root
  664. root.mParentNodeIndex = new_root_idx;
  665. // Update body counter
  666. mNumBodies += inLeafNumBodies;
  667. // And we're done
  668. return true;
  669. }
  670. // Failed to swap, someone else must have created a new root, try again
  671. mAllocator->DestructObject(new_root_idx);
  672. return false;
  673. }
  674. void QuadTree::AddBodiesPrepare(const BodyVector &inBodies, TrackingVector &ioTracking, BodyID *ioBodyIDs, int inNumber, AddState &outState)
  675. {
  676. // Assert sane input
  677. JPH_ASSERT(ioBodyIDs != nullptr);
  678. JPH_ASSERT(inNumber > 0);
  679. #ifdef JPH_ENABLE_ASSERTS
  680. // Below we just cast the body ID's to node ID's, check here that that is valid
  681. for (const BodyID *b = ioBodyIDs, *b_end = ioBodyIDs + inNumber; b < b_end; ++b)
  682. NodeID::sFromBodyID(*b);
  683. #endif
  684. // Build subtree for the new bodies, note that we mark all nodes as 'not changed'
  685. // so they will stay together as a batch and will make the tree rebuild cheaper
  686. outState.mLeafID = BuildTree(inBodies, ioTracking, (NodeID *)ioBodyIDs, inNumber, 0, outState.mLeafBounds);
  687. #ifdef JPH_DEBUG
  688. if (outState.mLeafID.IsNode())
  689. ValidateTree(inBodies, ioTracking, outState.mLeafID.GetNodeIndex(), inNumber);
  690. #endif
  691. }
  692. void QuadTree::AddBodiesFinalize(TrackingVector &ioTracking, int inNumberBodies, const AddState &inState)
  693. {
  694. // Assert sane input
  695. JPH_ASSERT(inNumberBodies > 0);
  696. // Mark tree dirty
  697. mIsDirty = true;
  698. // Get the current root node
  699. RootNode &root_node = GetCurrentRoot();
  700. for (;;)
  701. {
  702. // Check if we can insert the body in the root
  703. if (TryInsertLeaf(ioTracking, root_node.mIndex, inState.mLeafID, inState.mLeafBounds, inNumberBodies))
  704. return;
  705. // Check if we can create a new root
  706. if (TryCreateNewRoot(ioTracking, root_node.mIndex, inState.mLeafID, inState.mLeafBounds, inNumberBodies))
  707. return;
  708. }
  709. }
  710. void QuadTree::AddBodiesAbort(TrackingVector &ioTracking, const AddState &inState)
  711. {
  712. // Collect all bodies
  713. Allocator::Batch free_batch;
  714. NodeID node_stack[cStackSize];
  715. node_stack[0] = inState.mLeafID;
  716. JPH_ASSERT(node_stack[0].IsValid());
  717. int top = 0;
  718. do
  719. {
  720. // Check if node is a body
  721. NodeID child_node_id = node_stack[top];
  722. if (child_node_id.IsBody())
  723. {
  724. // Reset location of body
  725. sInvalidateBodyLocation(ioTracking, child_node_id.GetBodyID());
  726. }
  727. else
  728. {
  729. // Process normal node
  730. uint32 node_idx = child_node_id.GetNodeIndex();
  731. const Node &node = mAllocator->Get(node_idx);
  732. for (NodeID sub_child_node_id : node.mChildNodeID)
  733. if (sub_child_node_id.IsValid())
  734. {
  735. JPH_ASSERT(top < cStackSize);
  736. node_stack[top] = sub_child_node_id;
  737. top++;
  738. }
  739. // Mark it to be freed
  740. mAllocator->AddObjectToBatch(free_batch, node_idx);
  741. }
  742. --top;
  743. }
  744. while (top >= 0);
  745. // Now free all nodes as a single batch
  746. mAllocator->DestructObjectBatch(free_batch);
  747. }
  748. void QuadTree::RemoveBodies([[maybe_unused]] const BodyVector &inBodies, TrackingVector &ioTracking, const BodyID *ioBodyIDs, int inNumber)
  749. {
  750. // Assert sane input
  751. JPH_ASSERT(ioBodyIDs != nullptr);
  752. JPH_ASSERT(inNumber > 0);
  753. // Mark tree dirty
  754. mIsDirty = true;
  755. for (const BodyID *cur = ioBodyIDs, *end = ioBodyIDs + inNumber; cur < end; ++cur)
  756. {
  757. // Check if BodyID is correct
  758. JPH_ASSERT(inBodies[cur->GetIndex()]->GetID() == *cur, "Provided BodyID doesn't match BodyID in body manager");
  759. // Get location of body
  760. uint32 node_idx, child_idx;
  761. GetBodyLocation(ioTracking, *cur, node_idx, child_idx);
  762. // First we reset our internal bookkeeping
  763. sInvalidateBodyLocation(ioTracking, *cur);
  764. // Then we make the bounding box invalid, no queries can find this node anymore
  765. Node &node = mAllocator->Get(node_idx);
  766. node.InvalidateChildBounds(child_idx);
  767. // Finally we reset the child id, this makes the node available for adds again
  768. node.mChildNodeID[child_idx] = NodeID::sInvalid();
  769. // We don't need to bubble up our bounding box changes to our parents since we never make volumes smaller, only bigger
  770. // But we do need to mark the nodes as changed so that the tree can be rebuilt
  771. MarkNodeAndParentsChanged(node_idx);
  772. }
  773. mNumBodies -= inNumber;
  774. }
  775. void QuadTree::NotifyBodiesAABBChanged(const BodyVector &inBodies, const TrackingVector &inTracking, const BodyID *ioBodyIDs, int inNumber)
  776. {
  777. // Assert sane input
  778. JPH_ASSERT(ioBodyIDs != nullptr);
  779. JPH_ASSERT(inNumber > 0);
  780. for (const BodyID *cur = ioBodyIDs, *end = ioBodyIDs + inNumber; cur < end; ++cur)
  781. {
  782. // Check if BodyID is correct
  783. const Body *body = inBodies[cur->GetIndex()];
  784. JPH_ASSERT(body->GetID() == *cur, "Provided BodyID doesn't match BodyID in body manager");
  785. // Get the new bounding box
  786. const AABox &new_bounds = body->GetWorldSpaceBounds();
  787. // Get location of body
  788. uint32 node_idx, child_idx;
  789. GetBodyLocation(inTracking, *cur, node_idx, child_idx);
  790. // Widen bounds for node
  791. Node &node = mAllocator->Get(node_idx);
  792. if (node.EncapsulateChildBounds(child_idx, new_bounds))
  793. {
  794. // Mark tree dirty
  795. mIsDirty = true;
  796. // If bounds changed, widen the bounds for our parents too
  797. WidenAndMarkNodeAndParentsChanged(node_idx, new_bounds);
  798. }
  799. }
  800. }
  801. template <class Visitor>
  802. JPH_INLINE void QuadTree::WalkTree(const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking, Visitor &ioVisitor JPH_IF_TRACK_BROADPHASE_STATS(, LayerToStats &ioStats)) const
  803. {
  804. // Get the root
  805. const RootNode &root_node = GetCurrentRoot();
  806. #ifdef JPH_TRACK_BROADPHASE_STATS
  807. // Start tracking stats
  808. int bodies_visited = 0;
  809. int hits_collected = 0;
  810. int nodes_visited = 0;
  811. uint64 collector_ticks = 0;
  812. uint64 start = GetProcessorTickCount();
  813. #endif // JPH_TRACK_BROADPHASE_STATS
  814. NodeID node_stack[cStackSize];
  815. node_stack[0] = root_node.GetNodeID();
  816. int top = 0;
  817. do
  818. {
  819. // Check if node is a body
  820. NodeID child_node_id = node_stack[top];
  821. if (child_node_id.IsBody())
  822. {
  823. // Track amount of bodies visited
  824. JPH_IF_TRACK_BROADPHASE_STATS(++bodies_visited;)
  825. BodyID body_id = child_node_id.GetBodyID();
  826. ObjectLayer object_layer = inTracking[body_id.GetIndex()].mObjectLayer; // We're not taking a lock on the body, so it may be in the process of being removed so check if the object layer is invalid
  827. if (object_layer != cObjectLayerInvalid && inObjectLayerFilter.ShouldCollide(object_layer))
  828. {
  829. JPH_PROFILE("VisitBody");
  830. // Track amount of hits
  831. JPH_IF_TRACK_BROADPHASE_STATS(++hits_collected;)
  832. // Start track time the collector takes
  833. JPH_IF_TRACK_BROADPHASE_STATS(uint64 collector_start = GetProcessorTickCount();)
  834. // We found a body we collide with, call our visitor
  835. ioVisitor.VisitBody(body_id, top);
  836. // End track time the collector takes
  837. JPH_IF_TRACK_BROADPHASE_STATS(collector_ticks += GetProcessorTickCount() - collector_start;)
  838. // Check if we're done
  839. if (ioVisitor.ShouldAbort())
  840. break;
  841. }
  842. }
  843. else if (child_node_id.IsValid())
  844. {
  845. JPH_IF_TRACK_BROADPHASE_STATS(++nodes_visited;)
  846. // Check if stack can hold more nodes
  847. if (top + 4 < cStackSize)
  848. {
  849. // Process normal node
  850. const Node &node = mAllocator->Get(child_node_id.GetNodeIndex());
  851. JPH_ASSERT(IsAligned(&node, JPH_CACHE_LINE_SIZE));
  852. // Load bounds of 4 children
  853. Vec4 bounds_minx = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinX);
  854. Vec4 bounds_miny = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinY);
  855. Vec4 bounds_minz = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinZ);
  856. Vec4 bounds_maxx = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxX);
  857. Vec4 bounds_maxy = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxY);
  858. Vec4 bounds_maxz = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxZ);
  859. // Load ids for 4 children
  860. UVec4 child_ids = UVec4::sLoadInt4Aligned((const uint32 *)&node.mChildNodeID[0]);
  861. // Check which sub nodes to visit
  862. int num_results = ioVisitor.VisitNodes(bounds_minx, bounds_miny, bounds_minz, bounds_maxx, bounds_maxy, bounds_maxz, child_ids, top);
  863. child_ids.StoreInt4((uint32 *)&node_stack[top]);
  864. top += num_results;
  865. }
  866. else
  867. JPH_ASSERT(false, "Stack full!\n"
  868. "This must be a very deep tree. Are you batch adding bodies through BodyInterface::AddBodiesPrepare/AddBodiesFinalize?\n"
  869. "If you add lots of bodies through BodyInterface::AddBody you may need to call PhysicsSystem::OptimizeBroadPhase to rebuild the tree.");
  870. }
  871. // Fetch next node until we find one that the visitor wants to see
  872. do
  873. --top;
  874. while (top >= 0 && !ioVisitor.ShouldVisitNode(top));
  875. }
  876. while (top >= 0);
  877. #ifdef JPH_TRACK_BROADPHASE_STATS
  878. // Calculate total time the broadphase walk took
  879. uint64 total_ticks = GetProcessorTickCount() - start;
  880. // Update stats under lock protection (slow!)
  881. {
  882. unique_lock lock(mStatsMutex);
  883. Stat &s = ioStats[inObjectLayerFilter.GetDescription()];
  884. s.mNumQueries++;
  885. s.mNodesVisited += nodes_visited;
  886. s.mBodiesVisited += bodies_visited;
  887. s.mHitsReported += hits_collected;
  888. s.mTotalTicks += total_ticks;
  889. s.mCollectorTicks += collector_ticks;
  890. }
  891. #endif // JPH_TRACK_BROADPHASE_STATS
  892. }
  893. void QuadTree::CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  894. {
  895. class Visitor
  896. {
  897. public:
  898. /// Constructor
  899. JPH_INLINE Visitor(const RayCast &inRay, RayCastBodyCollector &ioCollector) :
  900. mOrigin(inRay.mOrigin),
  901. mInvDirection(inRay.mDirection),
  902. mCollector(ioCollector)
  903. {
  904. mFractionStack[0] = -1;
  905. }
  906. /// Returns true if further processing of the tree should be aborted
  907. JPH_INLINE bool ShouldAbort() const
  908. {
  909. return mCollector.ShouldEarlyOut();
  910. }
  911. /// Returns true if this node / body should be visited, false if no hit can be generated
  912. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  913. {
  914. return mFractionStack[inStackTop] < mCollector.GetEarlyOutFraction();
  915. }
  916. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  917. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop)
  918. {
  919. // Test the ray against 4 bounding boxes
  920. Vec4 fraction = RayAABox4(mOrigin, mInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  921. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  922. return SortReverseAndStore(fraction, mCollector.GetEarlyOutFraction(), ioChildNodeIDs, &mFractionStack[inStackTop]);
  923. }
  924. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  925. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  926. {
  927. // Store potential hit with body
  928. BroadPhaseCastResult result { inBodyID, mFractionStack[inStackTop] };
  929. mCollector.AddHit(result);
  930. }
  931. private:
  932. Vec3 mOrigin;
  933. RayInvDirection mInvDirection;
  934. RayCastBodyCollector & mCollector;
  935. float mFractionStack[cStackSize];
  936. };
  937. Visitor visitor(inRay, ioCollector);
  938. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCastRayStats));
  939. }
  940. void QuadTree::CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  941. {
  942. class Visitor
  943. {
  944. public:
  945. /// Constructor
  946. JPH_INLINE Visitor(const AABox &inBox, CollideShapeBodyCollector &ioCollector) :
  947. mBox(inBox),
  948. mCollector(ioCollector)
  949. {
  950. }
  951. /// Returns true if further processing of the tree should be aborted
  952. JPH_INLINE bool ShouldAbort() const
  953. {
  954. return mCollector.ShouldEarlyOut();
  955. }
  956. /// Returns true if this node / body should be visited, false if no hit can be generated
  957. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  958. {
  959. return true;
  960. }
  961. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  962. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop) const
  963. {
  964. // Test the box vs 4 boxes
  965. UVec4 hitting = AABox4VsBox(mBox, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  966. return CountAndSortTrues(hitting, ioChildNodeIDs);
  967. }
  968. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  969. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  970. {
  971. // Store potential hit with body
  972. mCollector.AddHit(inBodyID);
  973. }
  974. private:
  975. const AABox & mBox;
  976. CollideShapeBodyCollector & mCollector;
  977. };
  978. Visitor visitor(inBox, ioCollector);
  979. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCollideAABoxStats));
  980. }
  981. void QuadTree::CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  982. {
  983. class Visitor
  984. {
  985. public:
  986. /// Constructor
  987. JPH_INLINE Visitor(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector) :
  988. mCenterX(inCenter.SplatX()),
  989. mCenterY(inCenter.SplatY()),
  990. mCenterZ(inCenter.SplatZ()),
  991. mRadiusSq(Vec4::sReplicate(Square(inRadius))),
  992. mCollector(ioCollector)
  993. {
  994. }
  995. /// Returns true if further processing of the tree should be aborted
  996. JPH_INLINE bool ShouldAbort() const
  997. {
  998. return mCollector.ShouldEarlyOut();
  999. }
  1000. /// Returns true if this node / body should be visited, false if no hit can be generated
  1001. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  1002. {
  1003. return true;
  1004. }
  1005. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  1006. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop) const
  1007. {
  1008. // Test 4 boxes vs sphere
  1009. UVec4 hitting = AABox4VsSphere(mCenterX, mCenterY, mCenterZ, mRadiusSq, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1010. return CountAndSortTrues(hitting, ioChildNodeIDs);
  1011. }
  1012. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  1013. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  1014. {
  1015. // Store potential hit with body
  1016. mCollector.AddHit(inBodyID);
  1017. }
  1018. private:
  1019. Vec4 mCenterX;
  1020. Vec4 mCenterY;
  1021. Vec4 mCenterZ;
  1022. Vec4 mRadiusSq;
  1023. CollideShapeBodyCollector & mCollector;
  1024. };
  1025. Visitor visitor(inCenter, inRadius, ioCollector);
  1026. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCollideSphereStats));
  1027. }
  1028. void QuadTree::CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  1029. {
  1030. class Visitor
  1031. {
  1032. public:
  1033. /// Constructor
  1034. JPH_INLINE Visitor(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector) :
  1035. mPoint(inPoint),
  1036. mCollector(ioCollector)
  1037. {
  1038. }
  1039. /// Returns true if further processing of the tree should be aborted
  1040. JPH_INLINE bool ShouldAbort() const
  1041. {
  1042. return mCollector.ShouldEarlyOut();
  1043. }
  1044. /// Returns true if this node / body should be visited, false if no hit can be generated
  1045. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  1046. {
  1047. return true;
  1048. }
  1049. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  1050. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop) const
  1051. {
  1052. // Test if point overlaps with box
  1053. UVec4 hitting = AABox4VsPoint(mPoint, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1054. return CountAndSortTrues(hitting, ioChildNodeIDs);
  1055. }
  1056. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  1057. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  1058. {
  1059. // Store potential hit with body
  1060. mCollector.AddHit(inBodyID);
  1061. }
  1062. private:
  1063. Vec3 mPoint;
  1064. CollideShapeBodyCollector & mCollector;
  1065. };
  1066. Visitor visitor(inPoint, ioCollector);
  1067. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCollidePointStats));
  1068. }
  1069. void QuadTree::CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  1070. {
  1071. class Visitor
  1072. {
  1073. public:
  1074. /// Constructor
  1075. JPH_INLINE Visitor(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector) :
  1076. mBox(inBox),
  1077. mCollector(ioCollector)
  1078. {
  1079. }
  1080. /// Returns true if further processing of the tree should be aborted
  1081. JPH_INLINE bool ShouldAbort() const
  1082. {
  1083. return mCollector.ShouldEarlyOut();
  1084. }
  1085. /// Returns true if this node / body should be visited, false if no hit can be generated
  1086. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  1087. {
  1088. return true;
  1089. }
  1090. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  1091. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop) const
  1092. {
  1093. // Test if point overlaps with box
  1094. UVec4 hitting = AABox4VsBox(mBox, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1095. return CountAndSortTrues(hitting, ioChildNodeIDs);
  1096. }
  1097. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  1098. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  1099. {
  1100. // Store potential hit with body
  1101. mCollector.AddHit(inBodyID);
  1102. }
  1103. private:
  1104. OrientedBox mBox;
  1105. CollideShapeBodyCollector & mCollector;
  1106. };
  1107. Visitor visitor(inBox, ioCollector);
  1108. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCollideOrientedBoxStats));
  1109. }
  1110. void QuadTree::CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const
  1111. {
  1112. class Visitor
  1113. {
  1114. public:
  1115. /// Constructor
  1116. JPH_INLINE Visitor(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector) :
  1117. mOrigin(inBox.mBox.GetCenter()),
  1118. mExtent(inBox.mBox.GetExtent()),
  1119. mInvDirection(inBox.mDirection),
  1120. mCollector(ioCollector)
  1121. {
  1122. mFractionStack[0] = -1;
  1123. }
  1124. /// Returns true if further processing of the tree should be aborted
  1125. JPH_INLINE bool ShouldAbort() const
  1126. {
  1127. return mCollector.ShouldEarlyOut();
  1128. }
  1129. /// Returns true if this node / body should be visited, false if no hit can be generated
  1130. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  1131. {
  1132. return mFractionStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  1133. }
  1134. /// Visit nodes, returns number of hits found and sorts ioChildNodeIDs so that they are at the beginning of the vector.
  1135. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioChildNodeIDs, int inStackTop)
  1136. {
  1137. // Enlarge them by the casted aabox extents
  1138. Vec4 bounds_min_x = inBoundsMinX, bounds_min_y = inBoundsMinY, bounds_min_z = inBoundsMinZ, bounds_max_x = inBoundsMaxX, bounds_max_y = inBoundsMaxY, bounds_max_z = inBoundsMaxZ;
  1139. AABox4EnlargeWithExtent(mExtent, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1140. // Test 4 children
  1141. Vec4 fraction = RayAABox4(mOrigin, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1142. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1143. return SortReverseAndStore(fraction, mCollector.GetPositiveEarlyOutFraction(), ioChildNodeIDs, &mFractionStack[inStackTop]);
  1144. }
  1145. /// Visit a body, returns false if the algorithm should terminate because no hits can be generated anymore
  1146. JPH_INLINE void VisitBody(const BodyID &inBodyID, int inStackTop)
  1147. {
  1148. // Store potential hit with body
  1149. BroadPhaseCastResult result { inBodyID, mFractionStack[inStackTop] };
  1150. mCollector.AddHit(result);
  1151. }
  1152. private:
  1153. Vec3 mOrigin;
  1154. Vec3 mExtent;
  1155. RayInvDirection mInvDirection;
  1156. CastShapeBodyCollector & mCollector;
  1157. float mFractionStack[cStackSize];
  1158. };
  1159. Visitor visitor(inBox, ioCollector);
  1160. WalkTree(inObjectLayerFilter, inTracking, visitor JPH_IF_TRACK_BROADPHASE_STATS(, mCastAABoxStats));
  1161. }
  1162. void QuadTree::FindCollidingPairs(const BodyVector &inBodies, const BodyID *inActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, BodyPairCollector &ioPairCollector, const ObjectLayerPairFilter &inObjectLayerPairFilter) const
  1163. {
  1164. // Note that we don't lock the tree at this point. We know that the tree is not going to be swapped or deleted while finding collision pairs due to the way the jobs are scheduled in the PhysicsSystem::Update.
  1165. // We double check this at the end of the function.
  1166. const RootNode &root_node = GetCurrentRoot();
  1167. JPH_ASSERT(root_node.mIndex != cInvalidNodeIndex);
  1168. // Assert sane input
  1169. JPH_ASSERT(inActiveBodies != nullptr);
  1170. JPH_ASSERT(inNumActiveBodies > 0);
  1171. NodeID node_stack[cStackSize];
  1172. // Loop over all active bodies
  1173. for (int b1 = 0; b1 < inNumActiveBodies; ++b1)
  1174. {
  1175. BodyID b1_id = inActiveBodies[b1];
  1176. const Body &body1 = *inBodies[b1_id.GetIndex()];
  1177. JPH_ASSERT(!body1.IsStatic());
  1178. // Expand the bounding box by the speculative contact distance
  1179. AABox bounds1 = body1.GetWorldSpaceBounds();
  1180. bounds1.ExpandBy(Vec3::sReplicate(inSpeculativeContactDistance));
  1181. // Test each body with the tree
  1182. node_stack[0] = root_node.GetNodeID();
  1183. int top = 0;
  1184. do
  1185. {
  1186. // Check if node is a body
  1187. NodeID child_node_id = node_stack[top];
  1188. if (child_node_id.IsBody())
  1189. {
  1190. // Don't collide with self
  1191. BodyID b2_id = child_node_id.GetBodyID();
  1192. if (b1_id != b2_id)
  1193. {
  1194. // Collision between dynamic pairs need to be picked up only once
  1195. const Body &body2 = *inBodies[b2_id.GetIndex()];
  1196. if (inObjectLayerPairFilter.ShouldCollide(body1.GetObjectLayer(), body2.GetObjectLayer())
  1197. && Body::sFindCollidingPairsCanCollide(body1, body2)
  1198. && bounds1.Overlaps(body2.GetWorldSpaceBounds())) // In the broadphase we widen the bounding box when a body moves, do a final check to see if the bounding boxes actually overlap
  1199. {
  1200. // Store potential hit between bodies
  1201. ioPairCollector.AddHit({ b1_id, b2_id });
  1202. }
  1203. }
  1204. }
  1205. else if (child_node_id.IsValid())
  1206. {
  1207. // Process normal node
  1208. const Node &node = mAllocator->Get(child_node_id.GetNodeIndex());
  1209. JPH_ASSERT(IsAligned(&node, JPH_CACHE_LINE_SIZE));
  1210. // Get bounds of 4 children
  1211. Vec4 bounds_minx = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinX);
  1212. Vec4 bounds_miny = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinY);
  1213. Vec4 bounds_minz = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMinZ);
  1214. Vec4 bounds_maxx = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxX);
  1215. Vec4 bounds_maxy = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxY);
  1216. Vec4 bounds_maxz = Vec4::sLoadFloat4Aligned((const Float4 *)&node.mBoundsMaxZ);
  1217. // Test overlap
  1218. UVec4 overlap = AABox4VsBox(bounds1, bounds_minx, bounds_miny, bounds_minz, bounds_maxx, bounds_maxy, bounds_maxz);
  1219. int num_results = overlap.CountTrues();
  1220. if (num_results > 0)
  1221. {
  1222. // Load ids for 4 children
  1223. UVec4 child_ids = UVec4::sLoadInt4Aligned((const uint32 *)&node.mChildNodeID[0]);
  1224. // Sort so that overlaps are first
  1225. child_ids = UVec4::sSort4True(overlap, child_ids);
  1226. // Push them onto the stack
  1227. if (top + 4 < cStackSize)
  1228. {
  1229. child_ids.StoreInt4((uint32 *)&node_stack[top]);
  1230. top += num_results;
  1231. }
  1232. else
  1233. JPH_ASSERT(false, "Stack full!\n"
  1234. "This must be a very deep tree. Are you batch adding bodies through BodyInterface::AddBodiesPrepare/AddBodiesFinalize?\n"
  1235. "If you add lots of bodies through BodyInterface::AddBody you may need to call PhysicsSystem::OptimizeBroadPhase to rebuild the tree.");
  1236. }
  1237. }
  1238. --top;
  1239. }
  1240. while (top >= 0);
  1241. }
  1242. // Test that the root node was not swapped while finding collision pairs.
  1243. // This would mean that UpdateFinalize/DiscardOldTree ran during collision detection which should not be possible due to the way the jobs are scheduled.
  1244. JPH_ASSERT(root_node.mIndex != cInvalidNodeIndex);
  1245. JPH_ASSERT(&root_node == &GetCurrentRoot());
  1246. }
  1247. #ifdef JPH_DEBUG
  1248. void QuadTree::ValidateTree(const BodyVector &inBodies, const TrackingVector &inTracking, uint32 inNodeIndex, uint32 inNumExpectedBodies) const
  1249. {
  1250. JPH_PROFILE_FUNCTION();
  1251. // Root should be valid
  1252. JPH_ASSERT(inNodeIndex != cInvalidNodeIndex);
  1253. // To avoid call overhead, create a stack in place
  1254. JPH_SUPPRESS_WARNING_PUSH
  1255. JPH_CLANG_SUPPRESS_WARNING("-Wunused-member-function") // The default constructor of StackEntry is unused when using Jolt's Array class but not when using std::vector
  1256. struct StackEntry
  1257. {
  1258. StackEntry() = default;
  1259. inline StackEntry(uint32 inNodeIndex, uint32 inParentNodeIndex) : mNodeIndex(inNodeIndex), mParentNodeIndex(inParentNodeIndex) { }
  1260. uint32 mNodeIndex;
  1261. uint32 mParentNodeIndex;
  1262. };
  1263. JPH_SUPPRESS_WARNING_POP
  1264. Array<StackEntry, STLLocalAllocator<StackEntry, cStackSize>> stack;
  1265. stack.reserve(cStackSize);
  1266. stack.emplace_back(inNodeIndex, cInvalidNodeIndex);
  1267. uint32 num_bodies = 0;
  1268. do
  1269. {
  1270. // Copy entry from the stack
  1271. StackEntry cur_stack = stack.back();
  1272. stack.pop_back();
  1273. // Validate parent
  1274. const Node &node = mAllocator->Get(cur_stack.mNodeIndex);
  1275. JPH_ASSERT(node.mParentNodeIndex == cur_stack.mParentNodeIndex);
  1276. // Validate that when a parent is not-changed that all of its children are also
  1277. JPH_ASSERT(cur_stack.mParentNodeIndex == cInvalidNodeIndex || mAllocator->Get(cur_stack.mParentNodeIndex).mIsChanged || !node.mIsChanged);
  1278. // Loop children
  1279. for (uint32 i = 0; i < 4; ++i)
  1280. {
  1281. NodeID child_node_id = node.mChildNodeID[i];
  1282. if (child_node_id.IsValid())
  1283. {
  1284. if (child_node_id.IsNode())
  1285. {
  1286. // Child is a node, recurse
  1287. uint32 child_idx = child_node_id.GetNodeIndex();
  1288. stack.emplace_back(child_idx, cur_stack.mNodeIndex);
  1289. // Validate that the bounding box is bigger or equal to the bounds in the tree
  1290. // Bounding box could also be invalid if all children of our child were removed
  1291. AABox child_bounds;
  1292. node.GetChildBounds(i, child_bounds);
  1293. AABox real_child_bounds;
  1294. mAllocator->Get(child_idx).GetNodeBounds(real_child_bounds);
  1295. JPH_ASSERT(child_bounds.Contains(real_child_bounds) || !real_child_bounds.IsValid());
  1296. }
  1297. else
  1298. {
  1299. // Increment number of bodies found
  1300. ++num_bodies;
  1301. // Check if tracker matches position of body
  1302. uint32 node_idx, child_idx;
  1303. GetBodyLocation(inTracking, child_node_id.GetBodyID(), node_idx, child_idx);
  1304. JPH_ASSERT(node_idx == cur_stack.mNodeIndex);
  1305. JPH_ASSERT(child_idx == i);
  1306. // Validate that the body bounds are bigger or equal to the bounds in the tree
  1307. AABox body_bounds;
  1308. node.GetChildBounds(i, body_bounds);
  1309. const Body *body = inBodies[child_node_id.GetBodyID().GetIndex()];
  1310. AABox cached_body_bounds = body->GetWorldSpaceBounds();
  1311. AABox real_body_bounds = body->GetShape()->GetWorldSpaceBounds(body->GetCenterOfMassTransform(), Vec3::sOne());
  1312. JPH_ASSERT(cached_body_bounds == real_body_bounds); // Check that cached body bounds are up to date
  1313. JPH_ASSERT(body_bounds.Contains(real_body_bounds));
  1314. }
  1315. }
  1316. }
  1317. }
  1318. while (!stack.empty());
  1319. // Check that the amount of bodies in the tree matches our counter
  1320. JPH_ASSERT(num_bodies == inNumExpectedBodies);
  1321. }
  1322. #endif
  1323. #ifdef JPH_DUMP_BROADPHASE_TREE
  1324. void QuadTree::DumpTree(const NodeID &inRoot, const char *inFileNamePrefix) const
  1325. {
  1326. // Open DOT file
  1327. std::ofstream f;
  1328. f.open(StringFormat("%s.dot", inFileNamePrefix).c_str(), std::ofstream::out | std::ofstream::trunc);
  1329. if (!f.is_open())
  1330. return;
  1331. // Write header
  1332. f << "digraph {\n";
  1333. // Iterate the entire tree
  1334. Array<NodeID, STLLocalAllocator<NodeID, cStackSize>> node_stack;
  1335. node_stack.push_back(inRoot);
  1336. JPH_ASSERT(inRoot.IsValid());
  1337. do
  1338. {
  1339. // Check if node is a body
  1340. NodeID node_id = node_stack.back();
  1341. node_stack.pop_back();
  1342. if (node_id.IsBody())
  1343. {
  1344. // Output body
  1345. String body_id = ConvertToString(node_id.GetBodyID().GetIndex());
  1346. f << "body" << body_id << "[label = \"Body " << body_id << "\"]\n";
  1347. }
  1348. else
  1349. {
  1350. // Process normal node
  1351. uint32 node_idx = node_id.GetNodeIndex();
  1352. const Node &node = mAllocator->Get(node_idx);
  1353. // Get bounding box
  1354. AABox bounds;
  1355. node.GetNodeBounds(bounds);
  1356. // Output node
  1357. String node_str = ConvertToString(node_idx);
  1358. f << "node" << node_str << "[label = \"Node " << node_str << "\nVolume: " << ConvertToString(bounds.GetVolume()) << "\" color=" << (node.mIsChanged? "red" : "black") << "]\n";
  1359. // Recurse and get all children
  1360. for (NodeID child_node_id : node.mChildNodeID)
  1361. if (child_node_id.IsValid())
  1362. {
  1363. node_stack.push_back(child_node_id);
  1364. // Output link
  1365. f << "node" << node_str << " -> ";
  1366. if (child_node_id.IsBody())
  1367. f << "body" << ConvertToString(child_node_id.GetBodyID().GetIndex());
  1368. else
  1369. f << "node" << ConvertToString(child_node_id.GetNodeIndex());
  1370. f << "\n";
  1371. }
  1372. }
  1373. }
  1374. while (!node_stack.empty());
  1375. // Finish DOT file
  1376. f << "}\n";
  1377. f.close();
  1378. // Convert to svg file
  1379. String cmd = StringFormat("dot %s.dot -Tsvg -o %s.svg", inFileNamePrefix, inFileNamePrefix);
  1380. system(cmd.c_str());
  1381. }
  1382. #endif // JPH_DUMP_BROADPHASE_TREE
  1383. #ifdef JPH_TRACK_BROADPHASE_STATS
  1384. uint64 QuadTree::GetTicks100Pct(const LayerToStats &inLayer) const
  1385. {
  1386. uint64 total_ticks = 0;
  1387. for (const LayerToStats::value_type &kv : inLayer)
  1388. total_ticks += kv.second.mTotalTicks;
  1389. return total_ticks;
  1390. }
  1391. void QuadTree::ReportStats(const char *inName, const LayerToStats &inLayer, uint64 inTicks100Pct) const
  1392. {
  1393. for (const LayerToStats::value_type &kv : inLayer)
  1394. {
  1395. double total_pct = 100.0 * double(kv.second.mTotalTicks) / double(inTicks100Pct);
  1396. double total_pct_excl_collector = 100.0 * double(kv.second.mTotalTicks - kv.second.mCollectorTicks) / double(inTicks100Pct);
  1397. double hits_reported_vs_bodies_visited = kv.second.mBodiesVisited > 0? 100.0 * double(kv.second.mHitsReported) / double(kv.second.mBodiesVisited) : 100.0;
  1398. double hits_reported_vs_nodes_visited = kv.second.mNodesVisited > 0? double(kv.second.mHitsReported) / double(kv.second.mNodesVisited) : -1.0;
  1399. std::stringstream str;
  1400. str << inName << ", " << kv.first << ", " << mName << ", " << kv.second.mNumQueries << ", " << total_pct << ", " << total_pct_excl_collector << ", " << kv.second.mNodesVisited << ", " << kv.second.mBodiesVisited << ", " << kv.second.mHitsReported << ", " << hits_reported_vs_bodies_visited << ", " << hits_reported_vs_nodes_visited;
  1401. Trace(str.str().c_str());
  1402. }
  1403. }
  1404. uint64 QuadTree::GetTicks100Pct() const
  1405. {
  1406. uint64 total_ticks = 0;
  1407. total_ticks += GetTicks100Pct(mCastRayStats);
  1408. total_ticks += GetTicks100Pct(mCollideAABoxStats);
  1409. total_ticks += GetTicks100Pct(mCollideSphereStats);
  1410. total_ticks += GetTicks100Pct(mCollidePointStats);
  1411. total_ticks += GetTicks100Pct(mCollideOrientedBoxStats);
  1412. total_ticks += GetTicks100Pct(mCastAABoxStats);
  1413. return total_ticks;
  1414. }
  1415. void QuadTree::ReportStats(uint64 inTicks100Pct) const
  1416. {
  1417. unique_lock lock(mStatsMutex);
  1418. ReportStats("RayCast", mCastRayStats, inTicks100Pct);
  1419. ReportStats("CollideAABox", mCollideAABoxStats, inTicks100Pct);
  1420. ReportStats("CollideSphere", mCollideSphereStats, inTicks100Pct);
  1421. ReportStats("CollidePoint", mCollidePointStats, inTicks100Pct);
  1422. ReportStats("CollideOrientedBox", mCollideOrientedBoxStats, inTicks100Pct);
  1423. ReportStats("CastAABox", mCastAABoxStats, inTicks100Pct);
  1424. }
  1425. #endif // JPH_TRACK_BROADPHASE_STATS
  1426. uint QuadTree::GetMaxTreeDepth(const NodeID &inNodeID) const
  1427. {
  1428. // Reached a leaf?
  1429. if (!inNodeID.IsValid() || inNodeID.IsBody())
  1430. return 0;
  1431. // Recurse to children
  1432. uint max_depth = 0;
  1433. const Node &node = mAllocator->Get(inNodeID.GetNodeIndex());
  1434. for (NodeID child_node_id : node.mChildNodeID)
  1435. max_depth = max(max_depth, GetMaxTreeDepth(child_node_id));
  1436. return max_depth + 1;
  1437. }
  1438. JPH_NAMESPACE_END