BroadPhaseQuadTree.cpp 21 KB

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