BroadPhaseQuadTree.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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/Core/QuickSort.h>
  10. JPH_NAMESPACE_BEGIN
  11. BroadPhaseQuadTree::~BroadPhaseQuadTree()
  12. {
  13. delete [] mLayers;
  14. }
  15. void BroadPhaseQuadTree::Init(BodyManager *inBodyManager, const BroadPhaseLayerInterface &inLayerInterface)
  16. {
  17. BroadPhase::Init(inBodyManager, inLayerInterface);
  18. // Store input parameters
  19. mBroadPhaseLayerInterface = &inLayerInterface;
  20. mNumLayers = inLayerInterface.GetNumBroadPhaseLayers();
  21. JPH_ASSERT(mNumLayers < (BroadPhaseLayer::Type)cBroadPhaseLayerInvalid);
  22. #ifdef JPH_ENABLE_ASSERTS
  23. // Store lock context
  24. mLockContext = inBodyManager;
  25. #endif // JPH_ENABLE_ASSERTS
  26. // Store max bodies
  27. mMaxBodies = inBodyManager->GetMaxBodies();
  28. // Initialize tracking data
  29. mTracking.resize(mMaxBodies);
  30. // Init allocator
  31. // Estimate the amount of nodes we're going to need
  32. uint32 num_leaves = (uint32)(mMaxBodies + 1) / 2; // Assume 50% fill
  33. uint32 num_leaves_plus_internal_nodes = num_leaves + (num_leaves + 2) / 3; // = Sum(num_leaves * 4^-i) with i = [0, Inf].
  34. mAllocator.Init(2 * num_leaves_plus_internal_nodes, 256); // We use double the amount of nodes while rebuilding the tree during Update()
  35. // Init sub trees
  36. mLayers = new QuadTree [mNumLayers];
  37. for (uint l = 0; l < mNumLayers; ++l)
  38. {
  39. mLayers[l].Init(mAllocator);
  40. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  41. // Set the name of the layer
  42. mLayers[l].SetName(inLayerInterface.GetBroadPhaseLayerName(BroadPhaseLayer(BroadPhaseLayer::Type(l))));
  43. #endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
  44. }
  45. }
  46. void BroadPhaseQuadTree::FrameSync()
  47. {
  48. JPH_PROFILE_FUNCTION();
  49. // Take a unique lock on the old query lock so that we know no one is using the old nodes anymore.
  50. // Note that nothing should be locked at this point to avoid risking a lock inversion deadlock.
  51. // Note that in other places where we lock this mutex we don't use SharedLock to detect lock inversions. As long as
  52. // nothing else is locked this is safe. This is why BroadPhaseQuery should be the highest priority lock.
  53. UniqueLock root_lock(mQueryLocks[mQueryLockIdx ^ 1] JPH_IF_ENABLE_ASSERTS(, mLockContext, EPhysicsLockTypes::BroadPhaseQuery));
  54. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  55. mLayers[l].DiscardOldTree();
  56. }
  57. void BroadPhaseQuadTree::Optimize()
  58. {
  59. JPH_PROFILE_FUNCTION();
  60. FrameSync();
  61. LockModifications();
  62. for (uint l = 0; l < mNumLayers; ++l)
  63. {
  64. QuadTree &tree = mLayers[l];
  65. if (tree.HasBodies())
  66. {
  67. QuadTree::UpdateState update_state;
  68. tree.UpdatePrepare(mBodyManager->GetBodies(), mTracking, update_state, true);
  69. tree.UpdateFinalize(mBodyManager->GetBodies(), mTracking, update_state);
  70. }
  71. }
  72. UnlockModifications();
  73. mNextLayerToUpdate = 0;
  74. }
  75. void BroadPhaseQuadTree::LockModifications()
  76. {
  77. // From this point on we prevent modifications to the tree
  78. PhysicsLock::sLock(mUpdateMutex JPH_IF_ENABLE_ASSERTS(, mLockContext, EPhysicsLockTypes::BroadPhaseUpdate));
  79. }
  80. BroadPhase::UpdateState BroadPhaseQuadTree::UpdatePrepare()
  81. {
  82. // LockModifications should have been called
  83. JPH_ASSERT(mUpdateMutex.is_locked());
  84. // Create update state
  85. UpdateState update_state;
  86. UpdateStateImpl *update_state_impl = reinterpret_cast<UpdateStateImpl *>(&update_state);
  87. // Loop until we've seen all layers
  88. for (uint iteration = 0; iteration < mNumLayers; ++iteration)
  89. {
  90. // Get the layer
  91. QuadTree &tree = mLayers[mNextLayerToUpdate];
  92. mNextLayerToUpdate = (mNextLayerToUpdate + 1) % mNumLayers;
  93. // If it is dirty we update this one
  94. if (tree.HasBodies() && tree.IsDirty() && tree.CanBeUpdated())
  95. {
  96. update_state_impl->mTree = &tree;
  97. tree.UpdatePrepare(mBodyManager->GetBodies(), mTracking, update_state_impl->mUpdateState, false);
  98. return update_state;
  99. }
  100. }
  101. // Nothing to update
  102. update_state_impl->mTree = nullptr;
  103. return update_state;
  104. }
  105. void BroadPhaseQuadTree::UpdateFinalize(const UpdateState &inUpdateState)
  106. {
  107. // LockModifications should have been called
  108. JPH_ASSERT(mUpdateMutex.is_locked());
  109. // Test if a tree was updated
  110. const UpdateStateImpl *update_state_impl = reinterpret_cast<const UpdateStateImpl *>(&inUpdateState);
  111. if (update_state_impl->mTree == nullptr)
  112. return;
  113. update_state_impl->mTree->UpdateFinalize(mBodyManager->GetBodies(), mTracking, update_state_impl->mUpdateState);
  114. // Make all queries from now on use the new lock
  115. mQueryLockIdx = mQueryLockIdx ^ 1;
  116. }
  117. void BroadPhaseQuadTree::UnlockModifications()
  118. {
  119. // From this point on we allow modifications to the tree again
  120. PhysicsLock::sUnlock(mUpdateMutex JPH_IF_ENABLE_ASSERTS(, mLockContext, EPhysicsLockTypes::BroadPhaseUpdate));
  121. }
  122. BroadPhase::AddState BroadPhaseQuadTree::AddBodiesPrepare(BodyID *ioBodies, int inNumber)
  123. {
  124. JPH_PROFILE_FUNCTION();
  125. JPH_ASSERT(inNumber > 0);
  126. const BodyVector &bodies = mBodyManager->GetBodies();
  127. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  128. LayerState *state = new LayerState [mNumLayers];
  129. // Sort bodies on layer
  130. Body * const * const bodies_ptr = bodies.data(); // C pointer or else sort is incredibly slow in debug mode
  131. QuickSort(ioBodies, ioBodies + inNumber, [bodies_ptr](BodyID inLHS, BodyID inRHS) { return bodies_ptr[inLHS.GetIndex()]->GetBroadPhaseLayer() < bodies_ptr[inRHS.GetIndex()]->GetBroadPhaseLayer(); });
  132. BodyID *b_start = ioBodies, *b_end = ioBodies + inNumber;
  133. while (b_start < b_end)
  134. {
  135. // Get broadphase layer
  136. BroadPhaseLayer::Type broadphase_layer = (BroadPhaseLayer::Type)bodies[b_start->GetIndex()]->GetBroadPhaseLayer();
  137. JPH_ASSERT(broadphase_layer < mNumLayers);
  138. // Find first body with different layer
  139. BodyID *b_mid = std::upper_bound(b_start, b_end, broadphase_layer, [bodies_ptr](BroadPhaseLayer::Type inLayer, BodyID inBodyID) { return inLayer < (BroadPhaseLayer::Type)bodies_ptr[inBodyID.GetIndex()]->GetBroadPhaseLayer(); });
  140. // Keep track of state for this layer
  141. LayerState &layer_state = state[broadphase_layer];
  142. layer_state.mBodyStart = b_start;
  143. layer_state.mBodyEnd = b_mid;
  144. // Insert all bodies of the same layer
  145. mLayers[broadphase_layer].AddBodiesPrepare(bodies, mTracking, b_start, int(b_mid - b_start), layer_state.mAddState);
  146. // Keep track in which tree we placed the object
  147. for (const BodyID *b = b_start; b < b_mid; ++b)
  148. {
  149. uint32 index = b->GetIndex();
  150. JPH_ASSERT(bodies[index]->GetID() == *b, "Provided BodyID doesn't match BodyID in body manager");
  151. JPH_ASSERT(!bodies[index]->IsInBroadPhase());
  152. Tracking &t = mTracking[index];
  153. JPH_ASSERT(t.mBroadPhaseLayer == (BroadPhaseLayer::Type)cBroadPhaseLayerInvalid);
  154. t.mBroadPhaseLayer = broadphase_layer;
  155. JPH_ASSERT(t.mObjectLayer == cObjectLayerInvalid);
  156. t.mObjectLayer = bodies[index]->GetObjectLayer();
  157. }
  158. // Repeat
  159. b_start = b_mid;
  160. }
  161. return state;
  162. }
  163. void BroadPhaseQuadTree::AddBodiesFinalize(BodyID *ioBodies, int inNumber, AddState inAddState)
  164. {
  165. JPH_PROFILE_FUNCTION();
  166. // This cannot run concurrently with UpdatePrepare()/UpdateFinalize()
  167. SharedLock lock(mUpdateMutex JPH_IF_ENABLE_ASSERTS(, mLockContext, EPhysicsLockTypes::BroadPhaseUpdate));
  168. BodyVector &bodies = mBodyManager->GetBodies();
  169. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  170. LayerState *state = (LayerState *)inAddState;
  171. for (BroadPhaseLayer::Type broadphase_layer = 0; broadphase_layer < mNumLayers; broadphase_layer++)
  172. {
  173. const LayerState &l = state[broadphase_layer];
  174. if (l.mBodyStart != nullptr)
  175. {
  176. // Insert all bodies of the same layer
  177. mLayers[broadphase_layer].AddBodiesFinalize(mTracking, int(l.mBodyEnd - l.mBodyStart), l.mAddState);
  178. // Mark added to broadphase
  179. for (const BodyID *b = l.mBodyStart; b < l.mBodyEnd; ++b)
  180. {
  181. uint32 index = b->GetIndex();
  182. JPH_ASSERT(bodies[index]->GetID() == *b, "Provided BodyID doesn't match BodyID in body manager");
  183. JPH_ASSERT(mTracking[index].mBroadPhaseLayer == broadphase_layer);
  184. JPH_ASSERT(mTracking[index].mObjectLayer == bodies[index]->GetObjectLayer());
  185. JPH_ASSERT(!bodies[index]->IsInBroadPhase());
  186. bodies[index]->SetInBroadPhaseInternal(true);
  187. }
  188. }
  189. }
  190. delete [] state;
  191. }
  192. void BroadPhaseQuadTree::AddBodiesAbort(BodyID *ioBodies, int inNumber, AddState inAddState)
  193. {
  194. JPH_PROFILE_FUNCTION();
  195. JPH_IF_ENABLE_ASSERTS(const BodyVector &bodies = mBodyManager->GetBodies();)
  196. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  197. LayerState *state = (LayerState *)inAddState;
  198. for (BroadPhaseLayer::Type broadphase_layer = 0; broadphase_layer < mNumLayers; broadphase_layer++)
  199. {
  200. const LayerState &l = state[broadphase_layer];
  201. if (l.mBodyStart != nullptr)
  202. {
  203. // Insert all bodies of the same layer
  204. mLayers[broadphase_layer].AddBodiesAbort(mTracking, l.mAddState);
  205. // Reset bookkeeping
  206. for (const BodyID *b = l.mBodyStart; b < l.mBodyEnd; ++b)
  207. {
  208. uint32 index = b->GetIndex();
  209. JPH_ASSERT(bodies[index]->GetID() == *b, "Provided BodyID doesn't match BodyID in body manager");
  210. JPH_ASSERT(!bodies[index]->IsInBroadPhase());
  211. Tracking &t = mTracking[index];
  212. JPH_ASSERT(t.mBroadPhaseLayer == broadphase_layer);
  213. t.mBroadPhaseLayer = (BroadPhaseLayer::Type)cBroadPhaseLayerInvalid;
  214. t.mObjectLayer = cObjectLayerInvalid;
  215. }
  216. }
  217. }
  218. delete [] state;
  219. }
  220. void BroadPhaseQuadTree::RemoveBodies(BodyID *ioBodies, int inNumber)
  221. {
  222. JPH_PROFILE_FUNCTION();
  223. // This cannot run concurrently with UpdatePrepare()/UpdateFinalize()
  224. SharedLock lock(mUpdateMutex JPH_IF_ENABLE_ASSERTS(, mLockContext, EPhysicsLockTypes::BroadPhaseUpdate));
  225. JPH_ASSERT(inNumber > 0);
  226. BodyVector &bodies = mBodyManager->GetBodies();
  227. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  228. // Sort bodies on layer
  229. Tracking *tracking = mTracking.data(); // C pointer or else sort is incredibly slow in debug mode
  230. QuickSort(ioBodies, ioBodies + inNumber, [tracking](BodyID inLHS, BodyID inRHS) { return tracking[inLHS.GetIndex()].mBroadPhaseLayer < tracking[inRHS.GetIndex()].mBroadPhaseLayer; });
  231. BodyID *b_start = ioBodies, *b_end = ioBodies + inNumber;
  232. while (b_start < b_end)
  233. {
  234. // Get broad phase layer
  235. BroadPhaseLayer::Type broadphase_layer = mTracking[b_start->GetIndex()].mBroadPhaseLayer;
  236. JPH_ASSERT(broadphase_layer != (BroadPhaseLayer::Type)cBroadPhaseLayerInvalid);
  237. // Find first body with different layer
  238. BodyID *b_mid = std::upper_bound(b_start, b_end, broadphase_layer, [tracking](BroadPhaseLayer::Type inLayer, BodyID inBodyID) { return inLayer < tracking[inBodyID.GetIndex()].mBroadPhaseLayer; });
  239. // Remove all bodies of the same layer
  240. mLayers[broadphase_layer].RemoveBodies(bodies, mTracking, b_start, int(b_mid - b_start));
  241. for (const BodyID *b = b_start; b < b_mid; ++b)
  242. {
  243. // Reset bookkeeping
  244. uint32 index = b->GetIndex();
  245. Tracking &t = tracking[index];
  246. t.mBroadPhaseLayer = (BroadPhaseLayer::Type)cBroadPhaseLayerInvalid;
  247. t.mObjectLayer = cObjectLayerInvalid;
  248. // Mark removed from broadphase
  249. JPH_ASSERT(bodies[index]->IsInBroadPhase());
  250. bodies[index]->SetInBroadPhaseInternal(false);
  251. }
  252. // Repeat
  253. b_start = b_mid;
  254. }
  255. }
  256. void BroadPhaseQuadTree::NotifyBodiesAABBChanged(BodyID *ioBodies, int inNumber, bool inTakeLock)
  257. {
  258. JPH_PROFILE_FUNCTION();
  259. JPH_ASSERT(inNumber > 0);
  260. // This cannot run concurrently with UpdatePrepare()/UpdateFinalize()
  261. if (inTakeLock)
  262. PhysicsLock::sLockShared(mUpdateMutex JPH_IF_ENABLE_ASSERTS(, mLockContext, EPhysicsLockTypes::BroadPhaseUpdate));
  263. else
  264. JPH_ASSERT(mUpdateMutex.is_locked());
  265. const BodyVector &bodies = mBodyManager->GetBodies();
  266. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  267. // Sort bodies on layer
  268. const Tracking *tracking = mTracking.data(); // C pointer or else sort is incredibly slow in debug mode
  269. QuickSort(ioBodies, ioBodies + inNumber, [tracking](BodyID inLHS, BodyID inRHS) { return tracking[inLHS.GetIndex()].mBroadPhaseLayer < tracking[inRHS.GetIndex()].mBroadPhaseLayer; });
  270. BodyID *b_start = ioBodies, *b_end = ioBodies + inNumber;
  271. while (b_start < b_end)
  272. {
  273. // Get broadphase layer
  274. BroadPhaseLayer::Type broadphase_layer = tracking[b_start->GetIndex()].mBroadPhaseLayer;
  275. JPH_ASSERT(broadphase_layer != (BroadPhaseLayer::Type)cBroadPhaseLayerInvalid);
  276. // Find first body with different layer
  277. BodyID *b_mid = std::upper_bound(b_start, b_end, broadphase_layer, [tracking](BroadPhaseLayer::Type inLayer, BodyID inBodyID) { return inLayer < tracking[inBodyID.GetIndex()].mBroadPhaseLayer; });
  278. // Nodify all bodies of the same layer changed
  279. mLayers[broadphase_layer].NotifyBodiesAABBChanged(bodies, mTracking, b_start, int(b_mid - b_start));
  280. // Repeat
  281. b_start = b_mid;
  282. }
  283. if (inTakeLock)
  284. PhysicsLock::sUnlockShared(mUpdateMutex JPH_IF_ENABLE_ASSERTS(, mLockContext, EPhysicsLockTypes::BroadPhaseUpdate));
  285. }
  286. void BroadPhaseQuadTree::NotifyBodiesLayerChanged(BodyID *ioBodies, int inNumber)
  287. {
  288. JPH_PROFILE_FUNCTION();
  289. JPH_ASSERT(inNumber > 0);
  290. // First sort the bodies that actually changed layer to beginning of the array
  291. const BodyVector &bodies = mBodyManager->GetBodies();
  292. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  293. for (BodyID *body_id = ioBodies + inNumber - 1; body_id >= ioBodies; --body_id)
  294. {
  295. uint32 index = body_id->GetIndex();
  296. JPH_ASSERT(bodies[index]->GetID() == *body_id, "Provided BodyID doesn't match BodyID in body manager");
  297. const Body *body = bodies[index];
  298. BroadPhaseLayer::Type broadphase_layer = (BroadPhaseLayer::Type)body->GetBroadPhaseLayer();
  299. JPH_ASSERT(broadphase_layer < mNumLayers);
  300. if (mTracking[index].mBroadPhaseLayer == broadphase_layer)
  301. {
  302. // Update tracking information
  303. mTracking[index].mObjectLayer = body->GetObjectLayer();
  304. // Move the body to the end, layer didn't change
  305. swap(*body_id, ioBodies[inNumber - 1]);
  306. --inNumber;
  307. }
  308. }
  309. if (inNumber > 0)
  310. {
  311. // Changing layer requires us to remove from one tree and add to another, so this is equivalent to removing all bodies first and then adding them again
  312. RemoveBodies(ioBodies, inNumber);
  313. AddState add_state = AddBodiesPrepare(ioBodies, inNumber);
  314. AddBodiesFinalize(ioBodies, inNumber, add_state);
  315. }
  316. }
  317. void BroadPhaseQuadTree::CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const
  318. {
  319. JPH_PROFILE_FUNCTION();
  320. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  321. // Prevent this from running in parallel with node deletion in FrameSync(), see notes there
  322. shared_lock lock(mQueryLocks[mQueryLockIdx]);
  323. // Loop over all layers and test the ones that could hit
  324. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  325. {
  326. const QuadTree &tree = mLayers[l];
  327. if (tree.HasBodies() && inBroadPhaseLayerFilter.ShouldCollide(BroadPhaseLayer(l)))
  328. {
  329. JPH_PROFILE(tree.GetName());
  330. tree.CastRay(inRay, ioCollector, inObjectLayerFilter, mTracking);
  331. if (ioCollector.ShouldEarlyOut())
  332. break;
  333. }
  334. }
  335. }
  336. void BroadPhaseQuadTree::CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const
  337. {
  338. JPH_PROFILE_FUNCTION();
  339. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  340. // Prevent this from running in parallel with node deletion in FrameSync(), see notes there
  341. shared_lock lock(mQueryLocks[mQueryLockIdx]);
  342. // Loop over all layers and test the ones that could hit
  343. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  344. {
  345. const QuadTree &tree = mLayers[l];
  346. if (tree.HasBodies() && inBroadPhaseLayerFilter.ShouldCollide(BroadPhaseLayer(l)))
  347. {
  348. JPH_PROFILE(tree.GetName());
  349. tree.CollideAABox(inBox, ioCollector, inObjectLayerFilter, mTracking);
  350. if (ioCollector.ShouldEarlyOut())
  351. break;
  352. }
  353. }
  354. }
  355. void BroadPhaseQuadTree::CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const
  356. {
  357. JPH_PROFILE_FUNCTION();
  358. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  359. // Prevent this from running in parallel with node deletion in FrameSync(), see notes there
  360. shared_lock lock(mQueryLocks[mQueryLockIdx]);
  361. // Loop over all layers and test the ones that could hit
  362. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  363. {
  364. const QuadTree &tree = mLayers[l];
  365. if (tree.HasBodies() && inBroadPhaseLayerFilter.ShouldCollide(BroadPhaseLayer(l)))
  366. {
  367. JPH_PROFILE(tree.GetName());
  368. tree.CollideSphere(inCenter, inRadius, ioCollector, inObjectLayerFilter, mTracking);
  369. if (ioCollector.ShouldEarlyOut())
  370. break;
  371. }
  372. }
  373. }
  374. void BroadPhaseQuadTree::CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const
  375. {
  376. JPH_PROFILE_FUNCTION();
  377. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  378. // Prevent this from running in parallel with node deletion in FrameSync(), see notes there
  379. shared_lock lock(mQueryLocks[mQueryLockIdx]);
  380. // Loop over all layers and test the ones that could hit
  381. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  382. {
  383. const QuadTree &tree = mLayers[l];
  384. if (tree.HasBodies() && inBroadPhaseLayerFilter.ShouldCollide(BroadPhaseLayer(l)))
  385. {
  386. JPH_PROFILE(tree.GetName());
  387. tree.CollidePoint(inPoint, ioCollector, inObjectLayerFilter, mTracking);
  388. if (ioCollector.ShouldEarlyOut())
  389. break;
  390. }
  391. }
  392. }
  393. void BroadPhaseQuadTree::CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const
  394. {
  395. JPH_PROFILE_FUNCTION();
  396. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  397. // Prevent this from running in parallel with node deletion in FrameSync(), see notes there
  398. shared_lock lock(mQueryLocks[mQueryLockIdx]);
  399. // Loop over all layers and test the ones that could hit
  400. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  401. {
  402. const QuadTree &tree = mLayers[l];
  403. if (tree.HasBodies() && inBroadPhaseLayerFilter.ShouldCollide(BroadPhaseLayer(l)))
  404. {
  405. JPH_PROFILE(tree.GetName());
  406. tree.CollideOrientedBox(inBox, ioCollector, inObjectLayerFilter, mTracking);
  407. if (ioCollector.ShouldEarlyOut())
  408. break;
  409. }
  410. }
  411. }
  412. void BroadPhaseQuadTree::CastAABoxNoLock(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const
  413. {
  414. JPH_PROFILE_FUNCTION();
  415. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  416. // Loop over all layers and test the ones that could hit
  417. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  418. {
  419. const QuadTree &tree = mLayers[l];
  420. if (tree.HasBodies() && inBroadPhaseLayerFilter.ShouldCollide(BroadPhaseLayer(l)))
  421. {
  422. JPH_PROFILE(tree.GetName());
  423. tree.CastAABox(inBox, ioCollector, inObjectLayerFilter, mTracking);
  424. if (ioCollector.ShouldEarlyOut())
  425. break;
  426. }
  427. }
  428. }
  429. void BroadPhaseQuadTree::CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const
  430. {
  431. // Prevent this from running in parallel with node deletion in FrameSync(), see notes there
  432. shared_lock lock(mQueryLocks[mQueryLockIdx]);
  433. CastAABoxNoLock(inBox, ioCollector, inBroadPhaseLayerFilter, inObjectLayerFilter);
  434. }
  435. void BroadPhaseQuadTree::FindCollidingPairs(BodyID *ioActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter, BodyPairCollector &ioPairCollector) const
  436. {
  437. JPH_PROFILE_FUNCTION();
  438. const BodyVector &bodies = mBodyManager->GetBodies();
  439. JPH_ASSERT(mMaxBodies == mBodyManager->GetMaxBodies());
  440. // Note that we don't take any locks 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.
  441. // Sort bodies on layer
  442. const Tracking *tracking = mTracking.data(); // C pointer or else sort is incredibly slow in debug mode
  443. QuickSort(ioActiveBodies, ioActiveBodies + inNumActiveBodies, [tracking](BodyID inLHS, BodyID inRHS) { return tracking[inLHS.GetIndex()].mObjectLayer < tracking[inRHS.GetIndex()].mObjectLayer; });
  444. BodyID *b_start = ioActiveBodies, *b_end = ioActiveBodies + inNumActiveBodies;
  445. while (b_start < b_end)
  446. {
  447. // Get broadphase layer
  448. ObjectLayer object_layer = tracking[b_start->GetIndex()].mObjectLayer;
  449. JPH_ASSERT(object_layer != cObjectLayerInvalid);
  450. // Find first body with different layer
  451. BodyID *b_mid = std::upper_bound(b_start, b_end, object_layer, [tracking](ObjectLayer inLayer, BodyID inBodyID) { return inLayer < tracking[inBodyID.GetIndex()].mObjectLayer; });
  452. // Loop over all layers and test the ones that could hit
  453. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  454. {
  455. const QuadTree &tree = mLayers[l];
  456. if (tree.HasBodies() && inObjectVsBroadPhaseLayerFilter.ShouldCollide(object_layer, BroadPhaseLayer(l)))
  457. {
  458. JPH_PROFILE(tree.GetName());
  459. tree.FindCollidingPairs(bodies, b_start, int(b_mid - b_start), inSpeculativeContactDistance, ioPairCollector, inObjectLayerPairFilter);
  460. }
  461. }
  462. // Repeat
  463. b_start = b_mid;
  464. }
  465. }
  466. #ifdef JPH_TRACK_BROADPHASE_STATS
  467. void BroadPhaseQuadTree::ReportStats()
  468. {
  469. Trace("Query Type, Filter Description, Tree Name, Num Queries, Total Time (%%), Total Time Excl. Collector (%%), Nodes Visited, Bodies Visited, Hits Reported, Hits Reported vs Bodies Visited (%%), Hits Reported vs Nodes Visited");
  470. uint64 total_ticks = 0;
  471. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  472. total_ticks += mLayers[l].GetTicks100Pct();
  473. for (BroadPhaseLayer::Type l = 0; l < mNumLayers; ++l)
  474. mLayers[l].ReportStats(total_ticks);
  475. }
  476. #endif // JPH_TRACK_BROADPHASE_STATS
  477. JPH_NAMESPACE_END