BodyManager.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Physics/Body/Body.h>
  5. #include <Core/Mutex.h>
  6. #include <Core/MutexArray.h>
  7. namespace JPH {
  8. // Classes
  9. class BodyCreationSettings;
  10. class BodyActivationListener;
  11. struct PhysicsSettings;
  12. #ifdef JPH_DEBUG_RENDERER
  13. class DebugRenderer;
  14. #endif // JPH_DEBUG_RENDERER
  15. /// Array of bodies
  16. using BodyVector = vector<Body *>;
  17. /// Array of body ID's
  18. using BodyIDVector = vector<BodyID>;
  19. /// Class that contains all bodies
  20. class BodyManager : public NonCopyable
  21. {
  22. public:
  23. /// Destructor
  24. ~BodyManager();
  25. /// Initialize the manager
  26. void Init(uint inMaxBodies, uint inNumBodyMutexes);
  27. /// Gets the current amount of bodies that are in the body manager
  28. uint GetNumBodies() const;
  29. /// Gets the max bodies that we can support
  30. uint GetMaxBodies() const { return (uint)mBodies.capacity(); }
  31. /// Helper struct that counts the number of bodies of each type
  32. struct BodyStats
  33. {
  34. uint mNumBodies = 0; ///< Total number of bodies in the body manager
  35. uint mMaxBodies = 0; ///< Max allowed number of bodies in the body manager (as configured in Init(...))
  36. uint mNumBodiesStatic = 0; ///< Number of static bodies
  37. uint mNumBodiesDynamic = 0; ///< Number of dynamic bodies
  38. uint mNumActiveBodiesDynamic = 0; ///< Number of dynamic bodies that are currently active
  39. uint mNumBodiesKinematic = 0; ///< Number of kinematic bodies
  40. uint mNumActiveBodiesKinematic = 0; ///< Number of kinematic bodies that are currently active
  41. };
  42. /// Get stats about the bodies in the body manager (slow, iterates through all bodies)
  43. BodyStats GetBodyStats() const;
  44. /// Create a body.
  45. /// This is a thread safe function. Can return null if there are no more bodies available.
  46. Body * CreateBody(const BodyCreationSettings &inBodyCreationSettings);
  47. /// Mark a list of bodies for destruction and remove it from this manager.
  48. /// This is a thread safe function since the body is not deleted until the next PhysicsSystem::Update() (which will take all locks)
  49. void DestroyBodies(const BodyID *inBodyIDs, int inNumber);
  50. /// Activate a list of bodies.
  51. /// This function should only be called when an exclusive lock for the bodies are held.
  52. void ActivateBodies(const BodyID *inBodyIDs, int inNumber);
  53. /// Deactivate a list of bodies.
  54. /// This function should only be called when an exclusive lock for the bodies are held.
  55. void DeactivateBodies(const BodyID *inBodyIDs, int inNumber);
  56. /// Get copy of the list of active bodies under protection of a lock.
  57. void GetActiveBodies(BodyIDVector &outBodyIDs) const;
  58. /// Get the list of active bodies. Note: Not thread safe. The active bodies list can change at any moment.
  59. const BodyID * GetActiveBodiesUnsafe() const { return mActiveBodies; }
  60. /// Get the number of active bodies.
  61. uint32 GetNumActiveBodies() const { return mNumActiveBodies; }
  62. /// Get the number of active bodies that are using continuous collision detection
  63. uint32 GetNumActiveCCDBodies() const { return mNumActiveCCDBodies; }
  64. /// Listener that is notified whenever a body is activated/deactivated
  65. void SetBodyActivationListener(BodyActivationListener *inListener);
  66. BodyActivationListener * GetBodyActivationListener() const { return mActivationListener; }
  67. /// Check if this is a valid body pointer. When a body is freed the memory that the pointer occupies is reused to store a freelist.
  68. static inline bool sIsValidBodyPointer(const Body *inBody) { return (uintptr_t(inBody) & cIsFreedBody) == 0; }
  69. /// Get all bodies. Note that this can contain invalid body pointers, call sIsValidBodyPointer to check.
  70. const BodyVector & GetBodies() const { return mBodies; }
  71. /// Get all bodies. Note that this can contain invalid body pointers, call sIsValidBodyPointer to check.
  72. BodyVector & GetBodies() { return mBodies; }
  73. /// Get all body IDs under the protection of a lock
  74. void GetBodyIDs(BodyIDVector &outBodies) const;
  75. /// Access a body (not protected by lock)
  76. const Body & GetBody(const BodyID &inID) const { return *mBodies[inID.GetIndex()]; }
  77. /// Access a body (not protected by lock)
  78. Body & GetBody(const BodyID &inID) { return *mBodies[inID.GetIndex()]; }
  79. /// Access a body, will return a nullptr if the body ID is no longer valid (not protected by lock)
  80. const Body * TryGetBody(const BodyID &inID) const { const Body *body = mBodies[inID.GetIndex()]; return sIsValidBodyPointer(body) && body->GetID() == inID? body : nullptr; }
  81. /// Access a body, will return a nullptr if the body ID is no longer valid (not protected by lock)
  82. Body * TryGetBody(const BodyID &inID) { Body *body = mBodies[inID.GetIndex()]; return sIsValidBodyPointer(body) && body->GetID() == inID? body : nullptr; }
  83. /// Access the mutex for a single body
  84. SharedMutex & GetMutexForBody(const BodyID &inID) const { return mBodyMutexes.GetMutexByObjectIndex(inID.GetIndex()); }
  85. /// Bodies are protected using an array of mutexes (so a fixed number, not 1 per body). Each bit in this mask indicates a locked mutex.
  86. using MutexMask = uint64;
  87. ///@name Batch body mutex access (do not use directly)
  88. ///@{
  89. MutexMask GetAllBodiesMutexMask() const { return mBodyMutexes.GetNumMutexes() == sizeof(MutexMask) * 8? ~MutexMask(0) : (MutexMask(1) << mBodyMutexes.GetNumMutexes()) - 1; }
  90. MutexMask GetMutexMask(const BodyID *inBodies, int inNumber) const;
  91. void LockRead(MutexMask inMutexMask) const;
  92. void UnlockRead(MutexMask inMutexMask) const;
  93. void LockWrite(MutexMask inMutexMask) const;
  94. void UnlockWrite(MutexMask inMutexMask) const;
  95. ///@}
  96. /// Lock all bodies. This should only be done during PhysicsSystem::Update().
  97. void LockAllBodies() const;
  98. /// Unlock all bodies. This should only be done during PhysicsSystem::Update().
  99. void UnlockAllBodies() const;
  100. /// Set the Body::EFlags::InvalidateContactCache flag for the specified body. This means that the collision cache is invalid for any body pair involving that body until the next physics step.
  101. void InvalidateContactCacheForBody(Body &ioBody);
  102. /// Reset the Body::EFlags::InvalidateContactCache flag for all bodies. All contact pairs in the contact cache will now by valid again.
  103. void ValidateContactCacheForAllBodies();
  104. /// Saving state for replay
  105. void SaveState(StateRecorder &inStream) const;
  106. /// Restoring state for replay. Returns false if failed.
  107. bool RestoreState(StateRecorder &inStream);
  108. enum class EShapeColor
  109. {
  110. InstanceColor, ///< Random color per instance
  111. ShapeTypeColor, ///< Convex = green, scaled = yellow, compound = orange, mesh = red
  112. MotionTypeColor, ///< Static = grey, keyframed = green, dynamic = random color per instance
  113. SleepColor, ///< Static = grey, keyframed = green, dynamic = yellow, sleeping = red
  114. IslandColor, ///< Static = grey, active = random color per island, sleeping = light grey
  115. MaterialColor, ///< Color as defined by the PhysicsMaterial of the shape
  116. };
  117. #ifdef JPH_DEBUG_RENDERER
  118. /// Draw settings
  119. struct DrawSettings
  120. {
  121. bool mDrawGetSupportFunction = false; ///< Draw the GetSupport() function, used for convex collision detection
  122. bool mDrawSupportDirection = false; ///< When drawing the support function, also draw which direction mapped to a specific support point
  123. bool mDrawGetSupportingFace = false; ///< Draw the faces that were found colliding during collision detection
  124. bool mDrawShape = true; ///< Draw the shapes of all bodies
  125. bool mDrawShapeWireframe = false; ///< When mDrawShape is true and this is true, the shapes will be drawn in wireframe instead of solid.
  126. EShapeColor mDrawShapeColor = EShapeColor::MotionTypeColor; ///< Coloring scheme to use for shapes
  127. bool mDrawBoundingBox = false; ///< Draw a bounding box per body
  128. bool mDrawCenterOfMassTransform = false; ///< Draw the center of mass for each body
  129. bool mDrawWorldTransform = false; ///< Draw the world transform (which can be different than the center of mass) for each body
  130. bool mDrawVelocity = false; ///< Draw the velocity vector for each body
  131. bool mDrawMassAndInertia = false; ///< Draw the mass and inertia (as the box equivalent) for each body
  132. bool mDrawSleepStats = false; ///< Draw stats regarding the sleeping algorithm of each body
  133. bool mDrawNames = false; ///< (Debug only) Draw the object names for each body
  134. };
  135. /// Draw the state of the bodies (debugging purposes)
  136. void Draw(const DrawSettings &inSettings, const PhysicsSettings &inPhysicsSettings, DebugRenderer *inRenderer);
  137. #endif // JPH_DEBUG_RENDERER
  138. #ifdef JPH_ENABLE_ASSERTS
  139. /// Lock the active body list, asserts when Activate/DeactivateBody is called.
  140. void SetActiveBodiesLocked(bool inLocked) { mActiveBodiesLocked = inLocked; }
  141. /// Per thread override of the locked state, to be used by the PhysicsSystem only!
  142. class GrantActiveBodiesAccess
  143. {
  144. public:
  145. inline GrantActiveBodiesAccess(bool inAllowActivation, bool inAllowDeactivation)
  146. {
  147. JPH_ASSERT(!sOverrideAllowActivation);
  148. sOverrideAllowActivation = inAllowActivation;
  149. JPH_ASSERT(!sOverrideAllowDeactivation);
  150. sOverrideAllowDeactivation = inAllowDeactivation;
  151. }
  152. inline ~GrantActiveBodiesAccess()
  153. {
  154. sOverrideAllowActivation = false;
  155. sOverrideAllowDeactivation = false;
  156. }
  157. };
  158. #endif
  159. #ifdef _DEBUG
  160. /// Validate if the cached bounding boxes are correct for all active bodies
  161. void ValidateActiveBodyBounds();
  162. #endif // _DEBUG
  163. private:
  164. /// Increment and get the sequence number of the body
  165. #ifdef __clang__
  166. __attribute__((no_sanitize("implicit-conversion"))) // We intentionally overflow the uint8 sequence number
  167. #endif
  168. inline uint8 GetNextSequenceNumber(int inBodyIndex) { return ++mBodySequenceNumbers[inBodyIndex]; }
  169. /// List of pointers to all bodies. Contains invalid pointers for deleted bodies, check with sIsValidBodyPointer. Note that this array is reserved to the max bodies that is passed in the Init function so that adding bodies will not reallocate the array.
  170. BodyVector mBodies;
  171. /// Current number of allocated bodies
  172. uint mNumBodies = 0;
  173. /// Indicates that there are no more freed body IDs
  174. static constexpr uintptr_t cBodyIDFreeListEnd = ~uintptr_t(0);
  175. /// Bit that indicates a pointer in mBodies is actually the index of the next freed body. We use the lowest bit because we know that Bodies need to be 16 byte aligned so addresses can never end in a 1 bit.
  176. static constexpr uintptr_t cIsFreedBody = uintptr_t(1);
  177. /// Amount of bits to shift to get an index to the next freed body
  178. static constexpr uint cFreedBodyIndexShift = 1;
  179. /// Index of first entry in mBodies that is unused
  180. uintptr_t mBodyIDFreeListStart = cBodyIDFreeListEnd;
  181. /// Protects mBodies array (but not the bodies it points to), mNumBodies and mBodyIDFreeListStart
  182. mutable Mutex mBodiesMutex;
  183. /// An array of mutexes protecting the bodies in the mBodies array
  184. using BodyMutexes = MutexArray<SharedMutex>;
  185. mutable BodyMutexes mBodyMutexes;
  186. /// List of next sequence number for a body ID
  187. vector<uint8> mBodySequenceNumbers;
  188. /// Mutex that protects the mActiveBodies array
  189. mutable Mutex mActiveBodiesMutex;
  190. /// List of all active dynamic bodies (size is equal to max amount of bodies)
  191. BodyID * mActiveBodies = nullptr;
  192. /// How many bodies there are in the list of active bodies
  193. atomic<uint32> mNumActiveBodies = 0;
  194. /// How many of the active bodies have continuous collision detection enabled
  195. uint32 mNumActiveCCDBodies = 0;
  196. /// Mutex that protects the mBodiesCacheInvalid array
  197. mutable Mutex mBodiesCacheInvalidMutex;
  198. /// List of all bodies that should have their cache invalidated
  199. BodyIDVector mBodiesCacheInvalid;
  200. /// Listener that is notified whenever a body is activated/deactivated
  201. BodyActivationListener * mActivationListener = nullptr;
  202. #ifdef JPH_ENABLE_ASSERTS
  203. /// Debug system that tries to limit changes to active bodies during the PhysicsSystem::Update()
  204. bool mActiveBodiesLocked = false;
  205. static thread_local bool sOverrideAllowActivation;
  206. static thread_local bool sOverrideAllowDeactivation;
  207. #endif
  208. };
  209. } // JPH