QuadTree.cpp 54 KB

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