PhysicsSystem.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Body/BodyInterface.h>
  6. #include <Jolt/Physics/Collision/NarrowPhaseQuery.h>
  7. #include <Jolt/Physics/Collision/ContactListener.h>
  8. #include <Jolt/Physics/Constraints/ContactConstraintManager.h>
  9. #include <Jolt/Physics/Constraints/ConstraintManager.h>
  10. #include <Jolt/Physics/IslandBuilder.h>
  11. #include <Jolt/Physics/LargeIslandSplitter.h>
  12. #include <Jolt/Physics/PhysicsUpdateContext.h>
  13. #include <Jolt/Physics/PhysicsSettings.h>
  14. JPH_NAMESPACE_BEGIN
  15. class JobSystem;
  16. class StateRecorder;
  17. class TempAllocator;
  18. class PhysicsStepListener;
  19. /// The main class for the physics system. It contains all rigid bodies and simulates them.
  20. ///
  21. /// The main simulation is performed by the Update() call on multiple threads (if the JobSystem is configured to use them). Please refer to the general architecture overview in the Docs folder for more information.
  22. class JPH_EXPORT PhysicsSystem : public NonCopyable
  23. {
  24. public:
  25. JPH_OVERRIDE_NEW_DELETE
  26. /// Constructor / Destructor
  27. PhysicsSystem() : mContactManager(mPhysicsSettings) JPH_IF_ENABLE_ASSERTS(, mConstraintManager(&mBodyManager)) { }
  28. ~PhysicsSystem();
  29. /// Initialize the system.
  30. /// @param inMaxBodies Maximum number of bodies to support.
  31. /// @param inNumBodyMutexes Number of body mutexes to use. Should be a power of 2 in the range [1, 64], use 0 to auto detect.
  32. /// @param inMaxBodyPairs Maximum amount of body pairs to process (anything else will fall through the world), this number should generally be much higher than the max amount of contact points as there will be lots of bodies close that are not actually touching.
  33. /// @param inMaxContactConstraints Maximum amount of contact constraints to process (anything else will fall through the world).
  34. /// @param inBroadPhaseLayerInterface Information on the mapping of object layers to broad phase layers. Since this is a virtual interface, the instance needs to stay alive during the lifetime of the PhysicsSystem.
  35. /// @param inObjectVsBroadPhaseLayerFilter Filter callback function that is used to determine if an object layer collides with a broad phase layer. Since this is a virtual interface, the instance needs to stay alive during the lifetime of the PhysicsSystem.
  36. /// @param inObjectLayerPairFilter Filter callback function that is used to determine if two object layers collide. Since this is a virtual interface, the instance needs to stay alive during the lifetime of the PhysicsSystem.
  37. void Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter);
  38. /// Listener that is notified whenever a body is activated/deactivated
  39. void SetBodyActivationListener(BodyActivationListener *inListener) { mBodyManager.SetBodyActivationListener(inListener); }
  40. BodyActivationListener * GetBodyActivationListener() const { return mBodyManager.GetBodyActivationListener(); }
  41. /// Listener that is notified whenever a contact point between two bodies is added/updated/removed
  42. void SetContactListener(ContactListener *inListener) { mContactManager.SetContactListener(inListener); }
  43. ContactListener * GetContactListener() const { return mContactManager.GetContactListener(); }
  44. /// Set the function that combines the friction of two bodies and returns it
  45. /// Default method is the geometric mean: sqrt(friction1 * friction2).
  46. void SetCombineFriction(ContactConstraintManager::CombineFunction inCombineFriction) { mContactManager.SetCombineFriction(inCombineFriction); }
  47. /// Set the function that combines the restitution of two bodies and returns it
  48. /// Default method is max(restitution1, restitution1)
  49. void SetCombineRestitution(ContactConstraintManager::CombineFunction inCombineRestition) { mContactManager.SetCombineRestitution(inCombineRestition); }
  50. /// Control the main constants of the physics simulation
  51. void SetPhysicsSettings(const PhysicsSettings &inSettings) { mPhysicsSettings = inSettings; }
  52. const PhysicsSettings & GetPhysicsSettings() const { return mPhysicsSettings; }
  53. /// Access to the body interface. This interface allows to to create / remove bodies and to change their properties.
  54. const BodyInterface & GetBodyInterface() const { return mBodyInterfaceLocking; }
  55. BodyInterface & GetBodyInterface() { return mBodyInterfaceLocking; }
  56. const BodyInterface & GetBodyInterfaceNoLock() const { return mBodyInterfaceNoLock; } ///< Version that does not lock the bodies, use with great care!
  57. BodyInterface & GetBodyInterfaceNoLock() { return mBodyInterfaceNoLock; } ///< Version that does not lock the bodies, use with great care!
  58. /// Access to the broadphase interface that allows coarse collision queries
  59. const BroadPhaseQuery & GetBroadPhaseQuery() const { return *mBroadPhase; }
  60. /// Interface that allows fine collision queries against first the broad phase and then the narrow phase.
  61. const NarrowPhaseQuery & GetNarrowPhaseQuery() const { return mNarrowPhaseQueryLocking; }
  62. const NarrowPhaseQuery & GetNarrowPhaseQueryNoLock() const { return mNarrowPhaseQueryNoLock; } ///< Version that does not lock the bodies, use with great care!
  63. /// Add constraint to the world
  64. void AddConstraint(Constraint *inConstraint) { mConstraintManager.Add(&inConstraint, 1); }
  65. /// Remove constraint from the world
  66. void RemoveConstraint(Constraint *inConstraint) { mConstraintManager.Remove(&inConstraint, 1); }
  67. /// Batch add constraints. Note that the inConstraints array is allowed to have nullptrs, these will be ignored.
  68. void AddConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Add(inConstraints, inNumber); }
  69. /// Batch remove constraints. Note that the inConstraints array is allowed to have nullptrs, these will be ignored.
  70. void RemoveConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Remove(inConstraints, inNumber); }
  71. /// Get a list of all constraints
  72. Constraints GetConstraints() const { return mConstraintManager.GetConstraints(); }
  73. /// Optimize the broadphase, needed only if you've added many bodies prior to calling Update() for the first time.
  74. void OptimizeBroadPhase();
  75. /// Adds a new step listener
  76. void AddStepListener(PhysicsStepListener *inListener);
  77. /// Removes a step listener
  78. void RemoveStepListener(PhysicsStepListener *inListener);
  79. /// Simulate the system.
  80. /// The world steps for a total of inDeltaTime seconds. This is divided in inCollisionSteps iterations.
  81. /// Each iteration consists of collision detection followed by an integration step.
  82. /// This function internally spawns jobs using inJobSystem and waits for them to complete, so no jobs will be running when this function returns.
  83. EPhysicsUpdateError Update(float inDeltaTime, int inCollisionSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem);
  84. /// Saving state for replay
  85. void SaveState(StateRecorder &inStream) const;
  86. /// Restoring state for replay. Returns false if failed.
  87. bool RestoreState(StateRecorder &inStream);
  88. #ifdef JPH_DEBUG_RENDERER
  89. // Drawing properties
  90. static bool sDrawMotionQualityLinearCast; ///< Draw debug info for objects that perform continuous collision detection through the linear cast motion quality
  91. /// Draw the state of the bodies (debugging purposes)
  92. void DrawBodies(const BodyManager::DrawSettings &inSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter = nullptr) { mBodyManager.Draw(inSettings, mPhysicsSettings, inRenderer, inBodyFilter); }
  93. /// Draw the constraints only (debugging purposes)
  94. void DrawConstraints(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraints(inRenderer); }
  95. /// Draw the constraint limits only (debugging purposes)
  96. void DrawConstraintLimits(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintLimits(inRenderer); }
  97. /// Draw the constraint reference frames only (debugging purposes)
  98. void DrawConstraintReferenceFrame(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintReferenceFrame(inRenderer); }
  99. #endif // JPH_DEBUG_RENDERER
  100. /// Set gravity value
  101. void SetGravity(Vec3Arg inGravity) { mGravity = inGravity; }
  102. Vec3 GetGravity() const { return mGravity; }
  103. /// Returns a locking interface that won't actually lock the body. Use with great care!
  104. inline const BodyLockInterfaceNoLock & GetBodyLockInterfaceNoLock() const { return mBodyLockInterfaceNoLock; }
  105. /// Returns a locking interface that locks the body so other threads cannot modify it.
  106. inline const BodyLockInterfaceLocking & GetBodyLockInterface() const { return mBodyLockInterfaceLocking; }
  107. /// Get an broadphase layer filter that uses the default pair filter and a specified object layer to determine if broadphase layers collide
  108. DefaultBroadPhaseLayerFilter GetDefaultBroadPhaseLayerFilter(ObjectLayer inLayer) const { return DefaultBroadPhaseLayerFilter(*mObjectVsBroadPhaseLayerFilter, inLayer); }
  109. /// Get an object layer filter that uses the default pair filter and a specified layer to determine if layers collide
  110. DefaultObjectLayerFilter GetDefaultLayerFilter(ObjectLayer inLayer) const { return DefaultObjectLayerFilter(*mObjectLayerPairFilter, inLayer); }
  111. /// Gets the current amount of bodies that are in the body manager
  112. uint GetNumBodies() const { return mBodyManager.GetNumBodies(); }
  113. /// Gets the current amount of active bodies that are in the body manager
  114. uint32 GetNumActiveBodies() const { return mBodyManager.GetNumActiveBodies(); }
  115. /// Get the maximum amount of bodies that this physics system supports
  116. uint GetMaxBodies() const { return mBodyManager.GetMaxBodies(); }
  117. /// Helper struct that counts the number of bodies of each type
  118. using BodyStats = BodyManager::BodyStats;
  119. /// Get stats about the bodies in the body manager (slow, iterates through all bodies)
  120. BodyStats GetBodyStats() const { return mBodyManager.GetBodyStats(); }
  121. /// Get copy of the list of all bodies under protection of a lock.
  122. /// @param outBodyIDs On return, this will contain the list of BodyIDs
  123. void GetBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetBodyIDs(outBodyIDs); }
  124. /// Get copy of the list of active bodies under protection of a lock.
  125. /// @param outBodyIDs On return, this will contain the list of BodyIDs
  126. void GetActiveBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetActiveBodies(outBodyIDs); }
  127. /// Get the list of active bodies, use GetNumActiveBodies() to find out how long the list is.
  128. /// Note: Not thread safe. The active bodies list can change at any moment when other threads are doing work. Use GetActiveBodies() if you need a thread safe version.
  129. const BodyID * GetActiveBodiesUnsafe() const { return mBodyManager.GetActiveBodiesUnsafe(); }
  130. /// Check if 2 bodies were in contact during the last simulation step. Since contacts are only detected between active bodies, so at least one of the bodies must be active in order for this function to work.
  131. /// It queries the state at the time of the last PhysicsSystem::Update and will return true if the bodies were in contact, even if one of the bodies was moved / removed afterwards.
  132. /// This function can be called from any thread when the PhysicsSystem::Update is not running. During PhysicsSystem::Update this function is only valid during contact callbacks:
  133. /// - During the ContactListener::OnContactAdded callback this function can be used to determine if a different contact pair between the bodies was active in the previous simulation step (function returns true) or if this is the first step that the bodies are touching (function returns false).
  134. /// - During the ContactListener::OnContactRemoved callback this function can be used to determine if this is the last contact pair between the bodies (function returns false) or if there are other contacts still present (function returns true).
  135. bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const { return mContactManager.WereBodiesInContact(inBody1ID, inBody2ID); }
  136. #ifdef JPH_TRACK_BROADPHASE_STATS
  137. /// Trace the accumulated broadphase stats to the TTY
  138. void ReportBroadphaseStats() { mBroadPhase->ReportStats(); }
  139. #endif // JPH_TRACK_BROADPHASE_STATS
  140. private:
  141. using CCDBody = PhysicsUpdateContext::Step::CCDBody;
  142. // Various job entry points
  143. void JobStepListeners(PhysicsUpdateContext::Step *ioStep);
  144. void JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const;
  145. void JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  146. void JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const;
  147. void JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  148. void JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex);
  149. void JobFinalizeIslands(PhysicsUpdateContext *ioContext);
  150. void JobBodySetIslandIndex();
  151. void JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  152. void JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  153. void JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  154. void JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep) const;
  155. void JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  156. void JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  157. void JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep);
  158. void JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  159. /// Tries to spawn a new FindCollisions job if max concurrency hasn't been reached yet
  160. void TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const;
  161. using ContactAllocator = ContactConstraintManager::ContactAllocator;
  162. /// Process narrow phase for a single body pair
  163. void ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair);
  164. /// This helper batches up bodies that need to put to sleep to avoid contention on the activation mutex
  165. class BodiesToSleep;
  166. /// Called at the end of JobSolveVelocityConstraints to check if bodies need to go to sleep and to update their bounding box in the broadphase
  167. void CheckSleepAndUpdateBounds(uint32 inIslandIndex, const PhysicsUpdateContext *ioContext, const PhysicsUpdateContext::Step *ioStep, BodiesToSleep &ioBodiesToSleep);
  168. /// Number of constraints to process at once in JobDetermineActiveConstraints
  169. static constexpr int cDetermineActiveConstraintsBatchSize = 64;
  170. /// Number of bodies to process at once in JobApplyGravity
  171. static constexpr int cApplyGravityBatchSize = 64;
  172. /// Number of active bodies to test for collisions per batch
  173. static constexpr int cActiveBodiesBatchSize = 16;
  174. /// Number of active bodies to integrate velocities for
  175. static constexpr int cIntegrateVelocityBatchSize = 64;
  176. /// Number of contacts that need to be queued before another narrow phase job is started
  177. static constexpr int cNarrowPhaseBatchSize = 16;
  178. /// Number of continuous collision shape casts that need to be queued before another job is started
  179. static constexpr int cNumCCDBodiesPerJob = 4;
  180. /// Broadphase layer filter that decides if two objects can collide
  181. const ObjectVsBroadPhaseLayerFilter *mObjectVsBroadPhaseLayerFilter = nullptr;
  182. /// Object layer filter that decides if two objects can collide
  183. const ObjectLayerPairFilter *mObjectLayerPairFilter = nullptr;
  184. /// The body manager keeps track which bodies are in the simulation
  185. BodyManager mBodyManager;
  186. /// Body locking interfaces
  187. BodyLockInterfaceNoLock mBodyLockInterfaceNoLock { mBodyManager };
  188. BodyLockInterfaceLocking mBodyLockInterfaceLocking { mBodyManager };
  189. /// Body interfaces
  190. BodyInterface mBodyInterfaceNoLock;
  191. BodyInterface mBodyInterfaceLocking;
  192. /// Narrow phase query interface
  193. NarrowPhaseQuery mNarrowPhaseQueryNoLock;
  194. NarrowPhaseQuery mNarrowPhaseQueryLocking;
  195. /// The broadphase does quick collision detection between body pairs
  196. BroadPhase * mBroadPhase = nullptr;
  197. /// Simulation settings
  198. PhysicsSettings mPhysicsSettings;
  199. /// The contact manager resolves all contacts during a simulation step
  200. ContactConstraintManager mContactManager;
  201. /// All non-contact constraints
  202. ConstraintManager mConstraintManager;
  203. /// Keeps track of connected bodies and builds islands for multithreaded velocity/position update
  204. IslandBuilder mIslandBuilder;
  205. /// Will split large islands into smaller groups of bodies that can be processed in parallel
  206. LargeIslandSplitter mLargeIslandSplitter;
  207. /// Mutex protecting mStepListeners
  208. Mutex mStepListenersMutex;
  209. /// List of physics step listeners
  210. using StepListeners = Array<PhysicsStepListener *>;
  211. StepListeners mStepListeners;
  212. /// This is the global gravity vector
  213. Vec3 mGravity = Vec3(0, -9.81f, 0);
  214. /// Previous frame's delta time of one sub step to allow scaling previous frame's constraint impulses
  215. float mPreviousStepDeltaTime = 0.0f;
  216. };
  217. JPH_NAMESPACE_END