BodyManager.h 14 KB

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