BodyManager.cpp 33 KB

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