BodyManager.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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/PhysicsSettings.h>
  6. #include <Jolt/Physics/Body/BodyManager.h>
  7. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  8. #include <Jolt/Physics/Body/BodyLock.h>
  9. #include <Jolt/Physics/Body/BodyActivationListener.h>
  10. #include <Jolt/Physics/SoftBody/SoftBodyMotionProperties.h>
  11. #include <Jolt/Physics/SoftBody/SoftBodyCreationSettings.h>
  12. #include <Jolt/Physics/SoftBody/SoftBodyShape.h>
  13. #include <Jolt/Physics/StateRecorder.h>
  14. #include <Jolt/Core/StringTools.h>
  15. #include <Jolt/Core/QuickSort.h>
  16. #ifdef JPH_DEBUG_RENDERER
  17. #include <Jolt/Renderer/DebugRenderer.h>
  18. #include <Jolt/Physics/Body/BodyFilter.h>
  19. #endif // JPH_DEBUG_RENDERER
  20. JPH_NAMESPACE_BEGIN
  21. #ifdef JPH_ENABLE_ASSERTS
  22. static thread_local bool sOverrideAllowActivation = false;
  23. static thread_local bool sOverrideAllowDeactivation = false;
  24. bool BodyManager::sGetOverrideAllowActivation()
  25. {
  26. return sOverrideAllowActivation;
  27. }
  28. void BodyManager::sSetOverrideAllowActivation(bool inValue)
  29. {
  30. sOverrideAllowActivation = inValue;
  31. }
  32. bool BodyManager::sGetOverrideAllowDeactivation()
  33. {
  34. return sOverrideAllowDeactivation;
  35. }
  36. void BodyManager::sSetOverrideAllowDeactivation(bool inValue)
  37. {
  38. sOverrideAllowDeactivation = inValue;
  39. }
  40. #endif
  41. // Helper class that combines a body and its motion properties
  42. class BodyWithMotionProperties : public Body
  43. {
  44. public:
  45. JPH_OVERRIDE_NEW_DELETE
  46. MotionProperties mMotionProperties;
  47. };
  48. // Helper class that combines a soft body its motion properties and shape
  49. class SoftBodyWithMotionPropertiesAndShape : public Body
  50. {
  51. public:
  52. SoftBodyWithMotionPropertiesAndShape()
  53. {
  54. mShape.SetEmbedded();
  55. }
  56. SoftBodyMotionProperties mMotionProperties;
  57. SoftBodyShape mShape;
  58. };
  59. inline void BodyManager::sDeleteBody(Body *inBody)
  60. {
  61. if (inBody->mMotionProperties != nullptr)
  62. {
  63. JPH_IF_ENABLE_ASSERTS(inBody->mMotionProperties = nullptr;)
  64. if (inBody->IsSoftBody())
  65. {
  66. inBody->mShape = nullptr; // Release the shape to avoid assertion on shape destruction because of embedded object with refcount > 0
  67. delete static_cast<SoftBodyWithMotionPropertiesAndShape *>(inBody);
  68. }
  69. else
  70. delete static_cast<BodyWithMotionProperties *>(inBody);
  71. }
  72. else
  73. delete inBody;
  74. }
  75. BodyManager::~BodyManager()
  76. {
  77. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  78. // Destroy any bodies that are still alive
  79. for (Body *b : mBodies)
  80. if (sIsValidBodyPointer(b))
  81. sDeleteBody(b);
  82. for (BodyID *active_bodies : mActiveBodies)
  83. delete [] active_bodies;
  84. }
  85. void BodyManager::Init(uint inMaxBodies, uint inNumBodyMutexes, const BroadPhaseLayerInterface &inLayerInterface)
  86. {
  87. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  88. // Num body mutexes must be a power of two and not bigger than our MutexMask
  89. uint num_body_mutexes = Clamp<uint>(GetNextPowerOf2(inNumBodyMutexes == 0? 2 * thread::hardware_concurrency() : inNumBodyMutexes), 1, sizeof(MutexMask) * 8);
  90. // Allocate the body mutexes
  91. mBodyMutexes.Init(num_body_mutexes);
  92. // Allocate space for bodies
  93. mBodies.reserve(inMaxBodies);
  94. // Allocate space for active bodies
  95. for (BodyID *&active_bodies : mActiveBodies)
  96. {
  97. JPH_ASSERT(active_bodies == nullptr);
  98. active_bodies = new BodyID [inMaxBodies];
  99. }
  100. // Allocate space for sequence numbers
  101. mBodySequenceNumbers.resize(inMaxBodies);
  102. // Keep layer interface
  103. mBroadPhaseLayerInterface = &inLayerInterface;
  104. }
  105. uint BodyManager::GetNumBodies() const
  106. {
  107. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  108. return mNumBodies;
  109. }
  110. BodyManager::BodyStats BodyManager::GetBodyStats() const
  111. {
  112. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  113. BodyStats stats;
  114. stats.mNumBodies = mNumBodies;
  115. stats.mMaxBodies = uint(mBodies.capacity());
  116. for (const Body *body : mBodies)
  117. if (sIsValidBodyPointer(body))
  118. {
  119. if (body->IsSoftBody())
  120. {
  121. stats.mNumSoftBodies++;
  122. if (body->IsActive())
  123. stats.mNumActiveSoftBodies++;
  124. }
  125. else
  126. {
  127. switch (body->GetMotionType())
  128. {
  129. case EMotionType::Static:
  130. stats.mNumBodiesStatic++;
  131. break;
  132. case EMotionType::Dynamic:
  133. stats.mNumBodiesDynamic++;
  134. if (body->IsActive())
  135. stats.mNumActiveBodiesDynamic++;
  136. break;
  137. case EMotionType::Kinematic:
  138. stats.mNumBodiesKinematic++;
  139. if (body->IsActive())
  140. stats.mNumActiveBodiesKinematic++;
  141. break;
  142. }
  143. }
  144. }
  145. return stats;
  146. }
  147. Body *BodyManager::AllocateBody(const BodyCreationSettings &inBodyCreationSettings) const
  148. {
  149. // Fill in basic properties
  150. Body *body;
  151. if (inBodyCreationSettings.HasMassProperties())
  152. {
  153. BodyWithMotionProperties *bmp = new BodyWithMotionProperties;
  154. body = bmp;
  155. body->mMotionProperties = &bmp->mMotionProperties;
  156. }
  157. else
  158. {
  159. body = new Body;
  160. }
  161. body->mBodyType = EBodyType::RigidBody;
  162. body->mShape = inBodyCreationSettings.GetShape();
  163. body->mUserData = inBodyCreationSettings.mUserData;
  164. body->SetFriction(inBodyCreationSettings.mFriction);
  165. body->SetRestitution(inBodyCreationSettings.mRestitution);
  166. body->mMotionType = inBodyCreationSettings.mMotionType;
  167. if (inBodyCreationSettings.mIsSensor)
  168. body->SetIsSensor(true);
  169. if (inBodyCreationSettings.mCollideKinematicVsNonDynamic)
  170. body->SetCollideKinematicVsNonDynamic(true);
  171. if (inBodyCreationSettings.mUseManifoldReduction)
  172. body->SetUseManifoldReduction(true);
  173. if (inBodyCreationSettings.mApplyGyroscopicForce)
  174. body->SetApplyGyroscopicForce(true);
  175. if (inBodyCreationSettings.mEnhancedInternalEdgeRemoval)
  176. body->SetEnhancedInternalEdgeRemoval(true);
  177. SetBodyObjectLayerInternal(*body, inBodyCreationSettings.mObjectLayer);
  178. body->mObjectLayer = inBodyCreationSettings.mObjectLayer;
  179. body->mCollisionGroup = inBodyCreationSettings.mCollisionGroup;
  180. if (inBodyCreationSettings.HasMassProperties())
  181. {
  182. MotionProperties *mp = body->mMotionProperties;
  183. mp->SetLinearDamping(inBodyCreationSettings.mLinearDamping);
  184. mp->SetAngularDamping(inBodyCreationSettings.mAngularDamping);
  185. mp->SetMaxLinearVelocity(inBodyCreationSettings.mMaxLinearVelocity);
  186. mp->SetMaxAngularVelocity(inBodyCreationSettings.mMaxAngularVelocity);
  187. mp->SetMassProperties(inBodyCreationSettings.mAllowedDOFs, inBodyCreationSettings.GetMassProperties());
  188. mp->SetLinearVelocity(inBodyCreationSettings.mLinearVelocity); // Needs to happen after setting the max linear/angular velocity and setting allowed DOFs
  189. mp->SetAngularVelocity(inBodyCreationSettings.mAngularVelocity);
  190. mp->SetGravityFactor(inBodyCreationSettings.mGravityFactor);
  191. mp->SetNumVelocityStepsOverride(inBodyCreationSettings.mNumVelocityStepsOverride);
  192. mp->SetNumPositionStepsOverride(inBodyCreationSettings.mNumPositionStepsOverride);
  193. mp->mMotionQuality = inBodyCreationSettings.mMotionQuality;
  194. mp->mAllowSleeping = inBodyCreationSettings.mAllowSleeping;
  195. JPH_IF_ENABLE_ASSERTS(mp->mCachedBodyType = body->mBodyType;)
  196. JPH_IF_ENABLE_ASSERTS(mp->mCachedMotionType = body->mMotionType;)
  197. }
  198. // Position body
  199. body->SetPositionAndRotationInternal(inBodyCreationSettings.mPosition, inBodyCreationSettings.mRotation);
  200. return body;
  201. }
  202. /// Create a soft body using creation settings. The returned body will not be part of the body manager yet.
  203. Body *BodyManager::AllocateSoftBody(const SoftBodyCreationSettings &inSoftBodyCreationSettings) const
  204. {
  205. // Fill in basic properties
  206. SoftBodyWithMotionPropertiesAndShape *bmp = new SoftBodyWithMotionPropertiesAndShape;
  207. SoftBodyMotionProperties *mp = &bmp->mMotionProperties;
  208. SoftBodyShape *shape = &bmp->mShape;
  209. Body *body = bmp;
  210. shape->mSoftBodyMotionProperties = mp;
  211. body->mBodyType = EBodyType::SoftBody;
  212. body->mMotionProperties = mp;
  213. body->mShape = shape;
  214. body->mUserData = inSoftBodyCreationSettings.mUserData;
  215. body->SetFriction(inSoftBodyCreationSettings.mFriction);
  216. body->SetRestitution(inSoftBodyCreationSettings.mRestitution);
  217. body->mMotionType = EMotionType::Dynamic;
  218. SetBodyObjectLayerInternal(*body, inSoftBodyCreationSettings.mObjectLayer);
  219. body->mObjectLayer = inSoftBodyCreationSettings.mObjectLayer;
  220. body->mCollisionGroup = inSoftBodyCreationSettings.mCollisionGroup;
  221. mp->SetLinearDamping(inSoftBodyCreationSettings.mLinearDamping);
  222. mp->SetAngularDamping(0);
  223. mp->SetMaxLinearVelocity(inSoftBodyCreationSettings.mMaxLinearVelocity);
  224. mp->SetMaxAngularVelocity(FLT_MAX);
  225. mp->SetLinearVelocity(Vec3::sZero());
  226. mp->SetAngularVelocity(Vec3::sZero());
  227. mp->SetGravityFactor(inSoftBodyCreationSettings.mGravityFactor);
  228. mp->mMotionQuality = EMotionQuality::Discrete;
  229. mp->mAllowSleeping = inSoftBodyCreationSettings.mAllowSleeping;
  230. JPH_IF_ENABLE_ASSERTS(mp->mCachedBodyType = body->mBodyType;)
  231. JPH_IF_ENABLE_ASSERTS(mp->mCachedMotionType = body->mMotionType;)
  232. mp->Initialize(inSoftBodyCreationSettings);
  233. body->SetPositionAndRotationInternal(inSoftBodyCreationSettings.mPosition, inSoftBodyCreationSettings.mMakeRotationIdentity? Quat::sIdentity() : inSoftBodyCreationSettings.mRotation);
  234. return body;
  235. }
  236. void BodyManager::FreeBody(Body *inBody) const
  237. {
  238. JPH_ASSERT(inBody->GetID().IsInvalid(), "This function should only be called on a body that doesn't have an ID yet, use DestroyBody otherwise");
  239. sDeleteBody(inBody);
  240. }
  241. bool BodyManager::AddBody(Body *ioBody)
  242. {
  243. // Return error when body was already added
  244. if (!ioBody->GetID().IsInvalid())
  245. return false;
  246. // Determine next free index
  247. uint32 idx;
  248. {
  249. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  250. if (mBodyIDFreeListStart != cBodyIDFreeListEnd)
  251. {
  252. // Pop an item from the freelist
  253. JPH_ASSERT(mBodyIDFreeListStart & cIsFreedBody);
  254. idx = uint32(mBodyIDFreeListStart >> cFreedBodyIndexShift);
  255. JPH_ASSERT(!sIsValidBodyPointer(mBodies[idx]));
  256. mBodyIDFreeListStart = uintptr_t(mBodies[idx]);
  257. mBodies[idx] = ioBody;
  258. }
  259. else
  260. {
  261. if (mBodies.size() < mBodies.capacity())
  262. {
  263. // Allocate a new entry, note that the array should not actually resize since we've reserved it at init time
  264. idx = uint32(mBodies.size());
  265. mBodies.push_back(ioBody);
  266. }
  267. else
  268. {
  269. // Out of bodies
  270. return false;
  271. }
  272. }
  273. // Update cached number of bodies
  274. mNumBodies++;
  275. }
  276. // Get next sequence number and assign the ID
  277. uint8 seq_no = GetNextSequenceNumber(idx);
  278. ioBody->mID = BodyID(idx, seq_no);
  279. return true;
  280. }
  281. bool BodyManager::AddBodyWithCustomID(Body *ioBody, const BodyID &inBodyID)
  282. {
  283. // Return error when body was already added
  284. if (!ioBody->GetID().IsInvalid())
  285. return false;
  286. {
  287. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  288. // Check if index is beyond the max body ID
  289. uint32 idx = inBodyID.GetIndex();
  290. if (idx >= mBodies.capacity())
  291. return false; // Return error
  292. if (idx < mBodies.size())
  293. {
  294. // Body array entry has already been allocated, check if there's a free body here
  295. if (sIsValidBodyPointer(mBodies[idx]))
  296. return false; // Return error
  297. // Remove the entry from the freelist
  298. uintptr_t idx_start = mBodyIDFreeListStart >> cFreedBodyIndexShift;
  299. if (idx == idx_start)
  300. {
  301. // First entry, easy to remove, the start of the list is our next
  302. mBodyIDFreeListStart = uintptr_t(mBodies[idx]);
  303. }
  304. else
  305. {
  306. // Loop over the freelist and find the entry in the freelist pointing to our index
  307. // TODO: This is O(N), see if this becomes a performance problem (don't want to put the freed bodies in a double linked list)
  308. uintptr_t cur, next;
  309. for (cur = idx_start; cur != cBodyIDFreeListEnd >> cFreedBodyIndexShift; cur = next)
  310. {
  311. next = uintptr_t(mBodies[cur]) >> cFreedBodyIndexShift;
  312. if (next == idx)
  313. {
  314. mBodies[cur] = mBodies[idx];
  315. break;
  316. }
  317. }
  318. JPH_ASSERT(cur != cBodyIDFreeListEnd >> cFreedBodyIndexShift);
  319. }
  320. // Put the body in the slot
  321. mBodies[idx] = ioBody;
  322. }
  323. else
  324. {
  325. // Ensure that all body IDs up to this body ID have been allocated and added to the free list
  326. while (idx > mBodies.size())
  327. {
  328. // Push the id onto the freelist
  329. mBodies.push_back((Body *)mBodyIDFreeListStart);
  330. mBodyIDFreeListStart = (uintptr_t(mBodies.size() - 1) << cFreedBodyIndexShift) | cIsFreedBody;
  331. }
  332. // Add the element to the list
  333. mBodies.push_back(ioBody);
  334. }
  335. // Update cached number of bodies
  336. mNumBodies++;
  337. }
  338. // Assign the ID
  339. ioBody->mID = inBodyID;
  340. return true;
  341. }
  342. Body *BodyManager::RemoveBodyInternal(const BodyID &inBodyID)
  343. {
  344. // Get body
  345. uint32 idx = inBodyID.GetIndex();
  346. Body *body = mBodies[idx];
  347. // Validate that it can be removed
  348. JPH_ASSERT(body->GetID() == inBodyID);
  349. JPH_ASSERT(!body->IsActive());
  350. JPH_ASSERT(!body->IsInBroadPhase());
  351. // Push the id onto the freelist
  352. mBodies[idx] = (Body *)mBodyIDFreeListStart;
  353. mBodyIDFreeListStart = (uintptr_t(idx) << cFreedBodyIndexShift) | cIsFreedBody;
  354. return body;
  355. }
  356. #if defined(JPH_DEBUG) && defined(JPH_ENABLE_ASSERTS)
  357. void BodyManager::ValidateFreeList() const
  358. {
  359. // Check that the freelist is correct
  360. size_t num_freed = 0;
  361. for (uintptr_t start = mBodyIDFreeListStart; start != cBodyIDFreeListEnd; start = uintptr_t(mBodies[start >> cFreedBodyIndexShift]))
  362. {
  363. JPH_ASSERT(start & cIsFreedBody);
  364. num_freed++;
  365. }
  366. JPH_ASSERT(mNumBodies == mBodies.size() - num_freed);
  367. }
  368. #endif // defined(JPH_DEBUG) && _defined(JPH_ENABLE_ASSERTS)
  369. void BodyManager::RemoveBodies(const BodyID *inBodyIDs, int inNumber, Body **outBodies)
  370. {
  371. // Don't take lock if no bodies are to be destroyed
  372. if (inNumber <= 0)
  373. return;
  374. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  375. // Update cached number of bodies
  376. JPH_ASSERT(mNumBodies >= (uint)inNumber);
  377. mNumBodies -= inNumber;
  378. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  379. {
  380. // Remove body
  381. Body *body = RemoveBodyInternal(*b);
  382. // Clear the ID
  383. body->mID = BodyID();
  384. // Return the body to the caller
  385. if (outBodies != nullptr)
  386. {
  387. *outBodies = body;
  388. ++outBodies;
  389. }
  390. }
  391. #if defined(JPH_DEBUG) && defined(JPH_ENABLE_ASSERTS)
  392. ValidateFreeList();
  393. #endif // defined(JPH_DEBUG) && _defined(JPH_ENABLE_ASSERTS)
  394. }
  395. void BodyManager::DestroyBodies(const BodyID *inBodyIDs, int inNumber)
  396. {
  397. // Don't take lock if no bodies are to be destroyed
  398. if (inNumber <= 0)
  399. return;
  400. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  401. // Update cached number of bodies
  402. JPH_ASSERT(mNumBodies >= (uint)inNumber);
  403. mNumBodies -= inNumber;
  404. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  405. {
  406. // Remove body
  407. Body *body = RemoveBodyInternal(*b);
  408. // Free the body
  409. sDeleteBody(body);
  410. }
  411. #if defined(JPH_DEBUG) && defined(JPH_ENABLE_ASSERTS)
  412. ValidateFreeList();
  413. #endif // defined(JPH_DEBUG) && _defined(JPH_ENABLE_ASSERTS)
  414. }
  415. void BodyManager::AddBodyToActiveBodies(Body &ioBody)
  416. {
  417. // Select the correct array to use
  418. int type = (int)ioBody.GetBodyType();
  419. atomic<uint32> &num_active_bodies = mNumActiveBodies[type];
  420. BodyID *active_bodies = mActiveBodies[type];
  421. MotionProperties *mp = ioBody.mMotionProperties;
  422. mp->mIndexInActiveBodies = num_active_bodies;
  423. JPH_ASSERT(num_active_bodies < GetMaxBodies());
  424. active_bodies[num_active_bodies] = ioBody.GetID();
  425. num_active_bodies++; // Increment atomic after setting the body ID so that PhysicsSystem::JobFindCollisions (which doesn't lock the mActiveBodiesMutex) will only read valid IDs
  426. // Count CCD bodies
  427. if (mp->GetMotionQuality() == EMotionQuality::LinearCast)
  428. mNumActiveCCDBodies++;
  429. }
  430. void BodyManager::RemoveBodyFromActiveBodies(Body &ioBody)
  431. {
  432. // Select the correct array to use
  433. int type = (int)ioBody.GetBodyType();
  434. atomic<uint32> &num_active_bodies = mNumActiveBodies[type];
  435. BodyID *active_bodies = mActiveBodies[type];
  436. uint32 last_body_index = num_active_bodies - 1;
  437. MotionProperties *mp = ioBody.mMotionProperties;
  438. if (mp->mIndexInActiveBodies != last_body_index)
  439. {
  440. // This is not the last body, use the last body to fill the hole
  441. BodyID last_body_id = active_bodies[last_body_index];
  442. active_bodies[mp->mIndexInActiveBodies] = last_body_id;
  443. // Update that body's index in the active list
  444. Body &last_body = *mBodies[last_body_id.GetIndex()];
  445. JPH_ASSERT(last_body.mMotionProperties->mIndexInActiveBodies == last_body_index);
  446. last_body.mMotionProperties->mIndexInActiveBodies = mp->mIndexInActiveBodies;
  447. }
  448. // Mark this body as no longer active
  449. mp->mIndexInActiveBodies = Body::cInactiveIndex;
  450. // Remove unused element from active bodies list
  451. --num_active_bodies;
  452. // Count CCD bodies
  453. if (mp->GetMotionQuality() == EMotionQuality::LinearCast)
  454. mNumActiveCCDBodies--;
  455. }
  456. void BodyManager::ActivateBodies(const BodyID *inBodyIDs, int inNumber)
  457. {
  458. // Don't take lock if no bodies are to be activated
  459. if (inNumber <= 0)
  460. return;
  461. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  462. JPH_ASSERT(!mActiveBodiesLocked || sOverrideAllowActivation);
  463. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  464. if (!b->IsInvalid())
  465. {
  466. BodyID body_id = *b;
  467. Body &body = *mBodies[body_id.GetIndex()];
  468. JPH_ASSERT(body.GetID() == body_id);
  469. JPH_ASSERT(body.IsInBroadPhase());
  470. if (!body.IsStatic()
  471. && body.mMotionProperties->mIndexInActiveBodies == Body::cInactiveIndex)
  472. {
  473. // Reset sleeping
  474. body.ResetSleepTimer();
  475. AddBodyToActiveBodies(body);
  476. // Call activation listener
  477. if (mActivationListener != nullptr)
  478. mActivationListener->OnBodyActivated(body_id, body.GetUserData());
  479. }
  480. }
  481. }
  482. void BodyManager::DeactivateBodies(const BodyID *inBodyIDs, int inNumber)
  483. {
  484. // Don't take lock if no bodies are to be deactivated
  485. if (inNumber <= 0)
  486. return;
  487. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  488. JPH_ASSERT(!mActiveBodiesLocked || sOverrideAllowDeactivation);
  489. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  490. if (!b->IsInvalid())
  491. {
  492. BodyID body_id = *b;
  493. Body &body = *mBodies[body_id.GetIndex()];
  494. JPH_ASSERT(body.GetID() == body_id);
  495. JPH_ASSERT(body.IsInBroadPhase());
  496. if (body.mMotionProperties != nullptr
  497. && body.mMotionProperties->mIndexInActiveBodies != Body::cInactiveIndex)
  498. {
  499. // Remove the body from the active bodies list
  500. RemoveBodyFromActiveBodies(body);
  501. // Mark this body as no longer active
  502. body.mMotionProperties->mIslandIndex = Body::cInactiveIndex;
  503. // Reset velocity
  504. body.mMotionProperties->mLinearVelocity = Vec3::sZero();
  505. body.mMotionProperties->mAngularVelocity = Vec3::sZero();
  506. // Call activation listener
  507. if (mActivationListener != nullptr)
  508. mActivationListener->OnBodyDeactivated(body_id, body.GetUserData());
  509. }
  510. }
  511. }
  512. void BodyManager::SetMotionQuality(Body &ioBody, EMotionQuality inMotionQuality)
  513. {
  514. MotionProperties *mp = ioBody.GetMotionPropertiesUnchecked();
  515. if (mp != nullptr && mp->GetMotionQuality() != inMotionQuality)
  516. {
  517. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  518. JPH_ASSERT(!mActiveBodiesLocked);
  519. bool is_active = ioBody.IsActive();
  520. if (is_active && mp->GetMotionQuality() == EMotionQuality::LinearCast)
  521. --mNumActiveCCDBodies;
  522. mp->mMotionQuality = inMotionQuality;
  523. if (is_active && mp->GetMotionQuality() == EMotionQuality::LinearCast)
  524. ++mNumActiveCCDBodies;
  525. }
  526. }
  527. void BodyManager::GetActiveBodies(EBodyType inType, BodyIDVector &outBodyIDs) const
  528. {
  529. JPH_PROFILE_FUNCTION();
  530. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  531. const BodyID *active_bodies = mActiveBodies[(int)inType];
  532. outBodyIDs.assign(active_bodies, active_bodies + mNumActiveBodies[(int)inType]);
  533. }
  534. void BodyManager::GetBodyIDs(BodyIDVector &outBodies) const
  535. {
  536. JPH_PROFILE_FUNCTION();
  537. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  538. // Reserve space for all bodies
  539. outBodies.clear();
  540. outBodies.reserve(mNumBodies);
  541. // Iterate the list and find the bodies that are not null
  542. for (const Body *b : mBodies)
  543. if (sIsValidBodyPointer(b))
  544. outBodies.push_back(b->GetID());
  545. // Validate that our reservation was correct
  546. JPH_ASSERT(outBodies.size() == mNumBodies);
  547. }
  548. void BodyManager::SetBodyActivationListener(BodyActivationListener *inListener)
  549. {
  550. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  551. mActivationListener = inListener;
  552. }
  553. BodyManager::MutexMask BodyManager::GetMutexMask(const BodyID *inBodies, int inNumber) const
  554. {
  555. JPH_ASSERT(sizeof(MutexMask) * 8 >= mBodyMutexes.GetNumMutexes(), "MutexMask must have enough bits");
  556. if (inNumber >= (int)mBodyMutexes.GetNumMutexes())
  557. {
  558. // Just lock everything if there are too many bodies
  559. return GetAllBodiesMutexMask();
  560. }
  561. else
  562. {
  563. MutexMask mask = 0;
  564. for (const BodyID *b = inBodies, *b_end = inBodies + inNumber; b < b_end; ++b)
  565. if (!b->IsInvalid())
  566. {
  567. uint32 index = mBodyMutexes.GetMutexIndex(b->GetIndex());
  568. mask |= (MutexMask(1) << index);
  569. }
  570. return mask;
  571. }
  572. }
  573. void BodyManager::LockRead(MutexMask inMutexMask) const
  574. {
  575. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckLock(this, EPhysicsLockTypes::PerBody));
  576. int index = 0;
  577. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  578. if (mask & 1)
  579. mBodyMutexes.GetMutexByIndex(index).lock_shared();
  580. }
  581. void BodyManager::UnlockRead(MutexMask inMutexMask) const
  582. {
  583. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckUnlock(this, EPhysicsLockTypes::PerBody));
  584. int index = 0;
  585. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  586. if (mask & 1)
  587. mBodyMutexes.GetMutexByIndex(index).unlock_shared();
  588. }
  589. void BodyManager::LockWrite(MutexMask inMutexMask) const
  590. {
  591. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckLock(this, EPhysicsLockTypes::PerBody));
  592. int index = 0;
  593. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  594. if (mask & 1)
  595. mBodyMutexes.GetMutexByIndex(index).lock();
  596. }
  597. void BodyManager::UnlockWrite(MutexMask inMutexMask) const
  598. {
  599. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckUnlock(this, EPhysicsLockTypes::PerBody));
  600. int index = 0;
  601. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  602. if (mask & 1)
  603. mBodyMutexes.GetMutexByIndex(index).unlock();
  604. }
  605. void BodyManager::LockAllBodies() const
  606. {
  607. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckLock(this, EPhysicsLockTypes::PerBody));
  608. mBodyMutexes.LockAll();
  609. PhysicsLock::sLock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  610. }
  611. void BodyManager::UnlockAllBodies() const
  612. {
  613. PhysicsLock::sUnlock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  614. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckUnlock(this, EPhysicsLockTypes::PerBody));
  615. mBodyMutexes.UnlockAll();
  616. }
  617. void BodyManager::SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const
  618. {
  619. {
  620. LockAllBodies();
  621. // Determine which bodies to save
  622. Array<const Body *> bodies;
  623. bodies.reserve(mNumBodies);
  624. for (const Body *b : mBodies)
  625. if (sIsValidBodyPointer(b) && b->IsInBroadPhase() && (inFilter == nullptr || inFilter->ShouldSaveBody(*b)))
  626. bodies.push_back(b);
  627. // Write state of bodies
  628. uint32 num_bodies = (uint32)bodies.size();
  629. inStream.Write(num_bodies);
  630. for (const Body *b : bodies)
  631. {
  632. inStream.Write(b->GetID());
  633. inStream.Write(b->IsActive());
  634. b->SaveState(inStream);
  635. }
  636. UnlockAllBodies();
  637. }
  638. }
  639. bool BodyManager::RestoreState(StateRecorder &inStream)
  640. {
  641. BodyIDVector bodies_to_activate, bodies_to_deactivate;
  642. {
  643. LockAllBodies();
  644. if (inStream.IsValidating())
  645. {
  646. // Read state of bodies, note this reads it in a way to be consistent with validation
  647. uint32 old_num_bodies = 0;
  648. for (const Body *b : mBodies)
  649. if (sIsValidBodyPointer(b) && b->IsInBroadPhase())
  650. ++old_num_bodies;
  651. uint32 num_bodies = old_num_bodies; // Initialize to current value for validation
  652. inStream.Read(num_bodies);
  653. if (num_bodies != old_num_bodies)
  654. {
  655. JPH_ASSERT(false, "Cannot handle adding/removing bodies");
  656. UnlockAllBodies();
  657. return false;
  658. }
  659. for (Body *b : mBodies)
  660. if (sIsValidBodyPointer(b) && b->IsInBroadPhase())
  661. {
  662. BodyID body_id = b->GetID(); // Initialize to current value for validation
  663. inStream.Read(body_id);
  664. if (body_id != b->GetID())
  665. {
  666. JPH_ASSERT(false, "Cannot handle adding/removing bodies");
  667. UnlockAllBodies();
  668. return false;
  669. }
  670. bool is_active = b->IsActive(); // Initialize to current value for validation
  671. inStream.Read(is_active);
  672. if (is_active != b->IsActive())
  673. {
  674. if (is_active)
  675. bodies_to_activate.push_back(body_id);
  676. else
  677. bodies_to_deactivate.push_back(body_id);
  678. }
  679. b->RestoreState(inStream);
  680. }
  681. }
  682. else
  683. {
  684. // Not validating, we can be a bit more loose, read number of bodies
  685. uint32 num_bodies = 0;
  686. inStream.Read(num_bodies);
  687. // Iterate over the stored bodies and restore their state
  688. for (uint32 idx = 0; idx < num_bodies; ++idx)
  689. {
  690. BodyID body_id;
  691. inStream.Read(body_id);
  692. Body *b = TryGetBody(body_id);
  693. if (b == nullptr)
  694. {
  695. JPH_ASSERT(false, "Restoring state for non-existing body");
  696. UnlockAllBodies();
  697. return false;
  698. }
  699. bool is_active;
  700. inStream.Read(is_active);
  701. if (is_active != b->IsActive())
  702. {
  703. if (is_active)
  704. bodies_to_activate.push_back(body_id);
  705. else
  706. bodies_to_deactivate.push_back(body_id);
  707. }
  708. b->RestoreState(inStream);
  709. }
  710. }
  711. UnlockAllBodies();
  712. }
  713. {
  714. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  715. for (BodyID body_id : bodies_to_activate)
  716. {
  717. Body *body = TryGetBody(body_id);
  718. AddBodyToActiveBodies(*body);
  719. }
  720. for (BodyID body_id : bodies_to_deactivate)
  721. {
  722. Body *body = TryGetBody(body_id);
  723. RemoveBodyFromActiveBodies(*body);
  724. }
  725. }
  726. return true;
  727. }
  728. void BodyManager::SaveBodyState(const Body &inBody, StateRecorder &inStream) const
  729. {
  730. inStream.Write(inBody.IsActive());
  731. inBody.SaveState(inStream);
  732. }
  733. void BodyManager::RestoreBodyState(Body &ioBody, StateRecorder &inStream)
  734. {
  735. bool is_active = ioBody.IsActive();
  736. inStream.Read(is_active);
  737. ioBody.RestoreState(inStream);
  738. if (is_active != ioBody.IsActive())
  739. {
  740. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  741. JPH_ASSERT(!mActiveBodiesLocked || sOverrideAllowActivation);
  742. if (is_active)
  743. AddBodyToActiveBodies(ioBody);
  744. else
  745. RemoveBodyFromActiveBodies(ioBody);
  746. }
  747. }
  748. #ifdef JPH_DEBUG_RENDERER
  749. void BodyManager::Draw(const DrawSettings &inDrawSettings, const PhysicsSettings &inPhysicsSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter)
  750. {
  751. JPH_PROFILE_FUNCTION();
  752. LockAllBodies();
  753. for (const Body *body : mBodies)
  754. if (sIsValidBodyPointer(body) && body->IsInBroadPhase() && (!inBodyFilter || inBodyFilter->ShouldDraw(*body)))
  755. {
  756. JPH_ASSERT(mBodies[body->GetID().GetIndex()] == body);
  757. bool is_sensor = body->IsSensor();
  758. // Determine drawing mode
  759. Color color;
  760. if (is_sensor)
  761. color = Color::sYellow;
  762. else
  763. switch (inDrawSettings.mDrawShapeColor)
  764. {
  765. case EShapeColor::InstanceColor:
  766. // Each instance has own color
  767. color = Color::sGetDistinctColor(body->mID.GetIndex());
  768. break;
  769. case EShapeColor::ShapeTypeColor:
  770. color = ShapeFunctions::sGet(body->GetShape()->GetSubType()).mColor;
  771. break;
  772. case EShapeColor::MotionTypeColor:
  773. // Determine color based on motion type
  774. switch (body->mMotionType)
  775. {
  776. case EMotionType::Static:
  777. color = Color::sGrey;
  778. break;
  779. case EMotionType::Kinematic:
  780. color = Color::sGreen;
  781. break;
  782. case EMotionType::Dynamic:
  783. color = Color::sGetDistinctColor(body->mID.GetIndex());
  784. break;
  785. default:
  786. JPH_ASSERT(false);
  787. color = Color::sBlack;
  788. break;
  789. }
  790. break;
  791. case EShapeColor::SleepColor:
  792. // Determine color based on motion type
  793. switch (body->mMotionType)
  794. {
  795. case EMotionType::Static:
  796. color = Color::sGrey;
  797. break;
  798. case EMotionType::Kinematic:
  799. color = body->IsActive()? Color::sGreen : Color::sRed;
  800. break;
  801. case EMotionType::Dynamic:
  802. color = body->IsActive()? Color::sYellow : Color::sRed;
  803. break;
  804. default:
  805. JPH_ASSERT(false);
  806. color = Color::sBlack;
  807. break;
  808. }
  809. break;
  810. case EShapeColor::IslandColor:
  811. // Determine color based on motion type
  812. switch (body->mMotionType)
  813. {
  814. case EMotionType::Static:
  815. color = Color::sGrey;
  816. break;
  817. case EMotionType::Kinematic:
  818. case EMotionType::Dynamic:
  819. {
  820. uint32 idx = body->GetMotionProperties()->GetIslandIndexInternal();
  821. color = idx != Body::cInactiveIndex? Color::sGetDistinctColor(idx) : Color::sLightGrey;
  822. }
  823. break;
  824. default:
  825. JPH_ASSERT(false);
  826. color = Color::sBlack;
  827. break;
  828. }
  829. break;
  830. case EShapeColor::MaterialColor:
  831. color = Color::sWhite;
  832. break;
  833. default:
  834. JPH_ASSERT(false);
  835. color = Color::sBlack;
  836. break;
  837. }
  838. // Draw the results of GetSupportFunction
  839. if (inDrawSettings.mDrawGetSupportFunction)
  840. body->mShape->DrawGetSupportFunction(inRenderer, body->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f), color, inDrawSettings.mDrawSupportDirection);
  841. // Draw the results of GetSupportingFace
  842. if (inDrawSettings.mDrawGetSupportingFace)
  843. body->mShape->DrawGetSupportingFace(inRenderer, body->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f));
  844. // Draw the shape
  845. if (inDrawSettings.mDrawShape)
  846. body->mShape->Draw(inRenderer, body->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f), color, inDrawSettings.mDrawShapeColor == EShapeColor::MaterialColor, inDrawSettings.mDrawShapeWireframe || is_sensor);
  847. // Draw bounding box
  848. if (inDrawSettings.mDrawBoundingBox)
  849. inRenderer->DrawWireBox(body->mBounds, color);
  850. // Draw center of mass transform
  851. if (inDrawSettings.mDrawCenterOfMassTransform)
  852. inRenderer->DrawCoordinateSystem(body->GetCenterOfMassTransform(), 0.2f);
  853. // Draw world transform
  854. if (inDrawSettings.mDrawWorldTransform)
  855. inRenderer->DrawCoordinateSystem(body->GetWorldTransform(), 0.2f);
  856. // Draw world space linear and angular velocity
  857. if (inDrawSettings.mDrawVelocity)
  858. {
  859. RVec3 pos = body->GetCenterOfMassPosition();
  860. inRenderer->DrawArrow(pos, pos + body->GetLinearVelocity(), Color::sGreen, 0.1f);
  861. inRenderer->DrawArrow(pos, pos + body->GetAngularVelocity(), Color::sRed, 0.1f);
  862. }
  863. if (inDrawSettings.mDrawMassAndInertia && body->IsDynamic())
  864. {
  865. const MotionProperties *mp = body->GetMotionProperties();
  866. if (mp->GetInverseMass() > 0.0f
  867. && !Vec3::sEquals(mp->GetInverseInertiaDiagonal(), Vec3::sZero()).TestAnyXYZTrue())
  868. {
  869. // Invert mass again
  870. float mass = 1.0f / mp->GetInverseMass();
  871. // Invert diagonal again
  872. Vec3 diagonal = mp->GetInverseInertiaDiagonal().Reciprocal();
  873. // Determine how big of a box has the equivalent inertia
  874. Vec3 box_size = MassProperties::sGetEquivalentSolidBoxSize(mass, diagonal);
  875. // Draw box with equivalent inertia
  876. inRenderer->DrawWireBox(body->GetCenterOfMassTransform() * Mat44::sRotation(mp->GetInertiaRotation()), AABox(-0.5f * box_size, 0.5f * box_size), Color::sOrange);
  877. // Draw mass
  878. inRenderer->DrawText3D(body->GetCenterOfMassPosition(), StringFormat("%.2f", (double)mass), Color::sOrange, 0.2f);
  879. }
  880. }
  881. if (inDrawSettings.mDrawSleepStats && body->IsDynamic() && body->IsActive())
  882. {
  883. // Draw stats to know which bodies could go to sleep
  884. String text = StringFormat("t: %.1f", (double)body->mMotionProperties->mSleepTestTimer);
  885. uint8 g = uint8(Clamp(255.0f * body->mMotionProperties->mSleepTestTimer / inPhysicsSettings.mTimeBeforeSleep, 0.0f, 255.0f));
  886. Color sleep_color = Color(0, 255 - g, g);
  887. inRenderer->DrawText3D(body->GetCenterOfMassPosition(), text, sleep_color, 0.2f);
  888. for (int i = 0; i < 3; ++i)
  889. inRenderer->DrawWireSphere(JPH_IF_DOUBLE_PRECISION(body->mMotionProperties->GetSleepTestOffset() +) body->mMotionProperties->mSleepTestSpheres[i].GetCenter(), body->mMotionProperties->mSleepTestSpheres[i].GetRadius(), sleep_color);
  890. }
  891. if (body->IsSoftBody())
  892. {
  893. const SoftBodyMotionProperties *mp = static_cast<const SoftBodyMotionProperties *>(body->GetMotionProperties());
  894. RMat44 com = body->GetCenterOfMassTransform();
  895. if (inDrawSettings.mDrawSoftBodyVertices)
  896. mp->DrawVertices(inRenderer, com);
  897. if (inDrawSettings.mDrawSoftBodyVertexVelocities)
  898. mp->DrawVertexVelocities(inRenderer, com);
  899. if (inDrawSettings.mDrawSoftBodyEdgeConstraints)
  900. mp->DrawEdgeConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  901. if (inDrawSettings.mDrawSoftBodyBendConstraints)
  902. mp->DrawBendConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  903. if (inDrawSettings.mDrawSoftBodyVolumeConstraints)
  904. mp->DrawVolumeConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  905. if (inDrawSettings.mDrawSoftBodySkinConstraints)
  906. mp->DrawSkinConstraints(inRenderer, com);
  907. if (inDrawSettings.mDrawSoftBodyLRAConstraints)
  908. mp->DrawLRAConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  909. if (inDrawSettings.mDrawSoftBodyPredictedBounds)
  910. mp->DrawPredictedBounds(inRenderer, com);
  911. }
  912. }
  913. UnlockAllBodies();
  914. }
  915. #endif // JPH_DEBUG_RENDERER
  916. void BodyManager::InvalidateContactCacheForBody(Body &ioBody)
  917. {
  918. // If this is the first time we flip the collision cache invalid flag, we need to add it to an internal list to ensure we reset the flag at the end of the physics update
  919. if (ioBody.InvalidateContactCacheInternal())
  920. {
  921. lock_guard lock(mBodiesCacheInvalidMutex);
  922. mBodiesCacheInvalid.push_back(ioBody.GetID());
  923. }
  924. }
  925. void BodyManager::ValidateContactCacheForAllBodies()
  926. {
  927. lock_guard lock(mBodiesCacheInvalidMutex);
  928. for (const BodyID &b : mBodiesCacheInvalid)
  929. {
  930. // The body may have been removed between the call to InvalidateContactCacheForBody and this call, so check if it still exists
  931. Body *body = TryGetBody(b);
  932. if (body != nullptr)
  933. body->ValidateContactCacheInternal();
  934. }
  935. mBodiesCacheInvalid.clear();
  936. }
  937. #ifdef JPH_DEBUG
  938. void BodyManager::ValidateActiveBodyBounds()
  939. {
  940. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  941. for (uint type = 0; type < cBodyTypeCount; ++type)
  942. for (BodyID *id = mActiveBodies[type], *id_end = mActiveBodies[type] + mNumActiveBodies[type]; id < id_end; ++id)
  943. {
  944. const Body *body = mBodies[id->GetIndex()];
  945. AABox cached = body->GetWorldSpaceBounds();
  946. AABox calculated = body->GetShape()->GetWorldSpaceBounds(body->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f));
  947. JPH_ASSERT(cached == calculated);
  948. }
  949. }
  950. #endif // JPH_DEBUG
  951. JPH_NAMESPACE_END