QuadTree.cpp 54 KB

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