PhysicsSystem.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 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. Each iteration
  81. /// consists of collision detection followed by inIntegrationSubSteps integration steps.
  82. EPhysicsUpdateError Update(float inDeltaTime, int inCollisionSteps, int inIntegrationSubSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem);
  83. /// Saving state for replay
  84. void SaveState(StateRecorder &inStream) const;
  85. /// Restoring state for replay. Returns false if failed.
  86. bool RestoreState(StateRecorder &inStream);
  87. #ifdef JPH_DEBUG_RENDERER
  88. // Drawing properties
  89. static bool sDrawMotionQualityLinearCast; ///< Draw debug info for objects that perform continuous collision detection through the linear cast motion quality
  90. /// Draw the state of the bodies (debugging purposes)
  91. void DrawBodies(const BodyManager::DrawSettings &inSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter = nullptr) { mBodyManager.Draw(inSettings, mPhysicsSettings, inRenderer, inBodyFilter); }
  92. /// Draw the constraints only (debugging purposes)
  93. void DrawConstraints(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraints(inRenderer); }
  94. /// Draw the constraint limits only (debugging purposes)
  95. void DrawConstraintLimits(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintLimits(inRenderer); }
  96. /// Draw the constraint reference frames only (debugging purposes)
  97. void DrawConstraintReferenceFrame(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintReferenceFrame(inRenderer); }
  98. #endif // JPH_DEBUG_RENDERER
  99. /// Set gravity value
  100. void SetGravity(Vec3Arg inGravity) { mGravity = inGravity; }
  101. Vec3 GetGravity() const { return mGravity; }
  102. /// Returns a locking interface that won't actually lock the body. Use with great care!
  103. inline const BodyLockInterfaceNoLock & GetBodyLockInterfaceNoLock() const { return mBodyLockInterfaceNoLock; }
  104. /// Returns a locking interface that locks the body so other threads cannot modify it.
  105. inline const BodyLockInterfaceLocking & GetBodyLockInterface() const { return mBodyLockInterfaceLocking; }
  106. /// Get an broadphase layer filter that uses the default pair filter and a specified object layer to determine if broadphase layers collide
  107. DefaultBroadPhaseLayerFilter GetDefaultBroadPhaseLayerFilter(ObjectLayer inLayer) const { return DefaultBroadPhaseLayerFilter(*mObjectVsBroadPhaseLayerFilter, inLayer); }
  108. /// Get an object layer filter that uses the default pair filter and a specified layer to determine if layers collide
  109. DefaultObjectLayerFilter GetDefaultLayerFilter(ObjectLayer inLayer) const { return DefaultObjectLayerFilter(*mObjectLayerPairFilter, inLayer); }
  110. /// Gets the current amount of bodies that are in the body manager
  111. uint GetNumBodies() const { return mBodyManager.GetNumBodies(); }
  112. /// Gets the current amount of active bodies that are in the body manager
  113. uint32 GetNumActiveBodies() const { return mBodyManager.GetNumActiveBodies(); }
  114. /// Get the maximum amount of bodies that this physics system supports
  115. uint GetMaxBodies() const { return mBodyManager.GetMaxBodies(); }
  116. /// Helper struct that counts the number of bodies of each type
  117. using BodyStats = BodyManager::BodyStats;
  118. /// Get stats about the bodies in the body manager (slow, iterates through all bodies)
  119. BodyStats GetBodyStats() const { return mBodyManager.GetBodyStats(); }
  120. /// Get copy of the list of all bodies under protection of a lock.
  121. /// @param outBodyIDs On return, this will contain the list of BodyIDs
  122. void GetBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetBodyIDs(outBodyIDs); }
  123. /// Get copy of the list of active bodies under protection of a lock.
  124. /// @param outBodyIDs On return, this will contain the list of BodyIDs
  125. void GetActiveBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetActiveBodies(outBodyIDs); }
  126. /// 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.
  127. /// 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.
  128. /// 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:
  129. /// - 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).
  130. /// - 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).
  131. bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const { return mContactManager.WereBodiesInContact(inBody1ID, inBody2ID); }
  132. #ifdef JPH_TRACK_BROADPHASE_STATS
  133. /// Trace the accumulated broadphase stats to the TTY
  134. void ReportBroadphaseStats() { mBroadPhase->ReportStats(); }
  135. #endif // JPH_TRACK_BROADPHASE_STATS
  136. private:
  137. using CCDBody = PhysicsUpdateContext::SubStep::CCDBody;
  138. // Various job entry points
  139. void JobStepListeners(PhysicsUpdateContext::Step *ioStep);
  140. void JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const;
  141. void JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  142. void JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const;
  143. void JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  144. void JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex);
  145. void JobFinalizeIslands(PhysicsUpdateContext *ioContext);
  146. void JobBodySetIslandIndex();
  147. void JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  148. void JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  149. void JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  150. void JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const;
  151. void JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  152. void JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  153. void JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep);
  154. void JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  155. /// Tries to spawn a new FindCollisions job if max concurrency hasn't been reached yet
  156. void TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const;
  157. using ContactAllocator = ContactConstraintManager::ContactAllocator;
  158. /// Process narrow phase for a single body pair
  159. void ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair);
  160. /// This helper batches up bodies that need to put to sleep to avoid contention on the activation mutex
  161. class BodiesToSleep;
  162. /// Called at the end of JobSolveVelocityConstraints to check if bodies need to go to sleep and to update their bounding box in the broadphase
  163. void CheckSleepAndUpdateBounds(uint32 inIslandIndex, const PhysicsUpdateContext *ioContext, const PhysicsUpdateContext::SubStep *ioSubStep, BodiesToSleep &ioBodiesToSleep);
  164. /// Number of constraints to process at once in JobDetermineActiveConstraints
  165. static constexpr int cDetermineActiveConstraintsBatchSize = 64;
  166. /// Number of bodies to process at once in JobApplyGravity
  167. static constexpr int cApplyGravityBatchSize = 64;
  168. /// Number of active bodies to test for collisions per batch
  169. static constexpr int cActiveBodiesBatchSize = 16;
  170. /// Number of active bodies to integrate velocities for
  171. static constexpr int cIntegrateVelocityBatchSize = 64;
  172. /// Number of contacts that need to be queued before another narrow phase job is started
  173. static constexpr int cNarrowPhaseBatchSize = 16;
  174. /// Number of continuous collision shape casts that need to be queued before another job is started
  175. static constexpr int cNumCCDBodiesPerJob = 4;
  176. /// Broadphase layer filter that decides if two objects can collide
  177. const ObjectVsBroadPhaseLayerFilter *mObjectVsBroadPhaseLayerFilter = nullptr;
  178. /// Object layer filter that decides if two objects can collide
  179. const ObjectLayerPairFilter *mObjectLayerPairFilter = nullptr;
  180. /// The body manager keeps track which bodies are in the simulation
  181. BodyManager mBodyManager;
  182. /// Body locking interfaces
  183. BodyLockInterfaceNoLock mBodyLockInterfaceNoLock { mBodyManager };
  184. BodyLockInterfaceLocking mBodyLockInterfaceLocking { mBodyManager };
  185. /// Body interfaces
  186. BodyInterface mBodyInterfaceNoLock;
  187. BodyInterface mBodyInterfaceLocking;
  188. /// Narrow phase query interface
  189. NarrowPhaseQuery mNarrowPhaseQueryNoLock;
  190. NarrowPhaseQuery mNarrowPhaseQueryLocking;
  191. /// The broadphase does quick collision detection between body pairs
  192. BroadPhase * mBroadPhase = nullptr;
  193. /// Simulation settings
  194. PhysicsSettings mPhysicsSettings;
  195. /// The contact manager resolves all contacts during a simulation step
  196. ContactConstraintManager mContactManager;
  197. /// All non-contact constraints
  198. ConstraintManager mConstraintManager;
  199. /// Keeps track of connected bodies and builds islands for multithreaded velocity/position update
  200. IslandBuilder mIslandBuilder;
  201. /// Will split large islands into smaller groups of bodies that can be processed in parallel
  202. LargeIslandSplitter mLargeIslandSplitter;
  203. /// Mutex protecting mStepListeners
  204. Mutex mStepListenersMutex;
  205. /// List of physics step listeners
  206. using StepListeners = Array<PhysicsStepListener *>;
  207. StepListeners mStepListeners;
  208. /// This is the global gravity vector
  209. Vec3 mGravity = Vec3(0, -9.81f, 0);
  210. /// Previous frame's delta time of one sub step to allow scaling previous frame's constraint impulses
  211. float mPreviousSubStepDeltaTime = 0.0f;
  212. };
  213. JPH_NAMESPACE_END