PhysicsSystem.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Physics/Body/BodyInterface.h>
  5. #include <Physics/Collision/NarrowPhaseQuery.h>
  6. #include <Physics/Collision/ContactListener.h>
  7. #include <Physics/Constraints/ContactConstraintManager.h>
  8. #include <Physics/Constraints/ConstraintManager.h>
  9. #include <Physics/IslandBuilder.h>
  10. #include <Physics/PhysicsUpdateContext.h>
  11. namespace JPH {
  12. class JobSystem;
  13. class StateRecorder;
  14. class TempAllocator;
  15. class PhysicsStepListener;
  16. /// The main class for the physics system. It contains all rigid bodies and simulates them.
  17. ///
  18. /// 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.
  19. class PhysicsSystem : public NonCopyable
  20. {
  21. public:
  22. /// Constructor / Destructor
  23. PhysicsSystem() : mContactManager(mPhysicsSettings) { }
  24. ~PhysicsSystem();
  25. /// Initialize the system.
  26. /// @param inMaxBodies Maximum number of bodies to support.
  27. /// @param inNumBodyMutexes Number of body mutexes to use. Should be a power of 2 in the range [1, 64], use 0 to auto detect.
  28. /// @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
  29. /// @param inMaxContactConstraints Maximum amount of contact constraints to process (anything else will fall through the world)
  30. /// @param inObjectToBroadPhaseLayer Maps object layer to broadphase layer, see ObjectToBroadPhaseLayer.
  31. /// @param inObjectLayerPairFilter Filter callback function that is used to determine if two object layers collide.
  32. void Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const ObjectToBroadPhaseLayer &inObjectToBroadPhaseLayer, ObjectVsBroadPhaseLayerFilter inObjectVsBroadPhaseLayerFilter, ObjectLayerPairFilter inObjectLayerPairFilter);
  33. /// Listener that is notified whenever a body is activated/deactivated
  34. void SetBodyActivationListener(BodyActivationListener *inListener) { mBodyManager.SetBodyActivationListener(inListener); }
  35. BodyActivationListener * GetBodyActivationListener() const { return mBodyManager.GetBodyActivationListener(); }
  36. /// Listener that is notified whenever a contact point between two bodies is added/updated/removed
  37. void SetContactListener(ContactListener *inListener) { mContactManager.SetContactListener(inListener); }
  38. ContactListener * GetContactListener() const { return mContactManager.GetContactListener(); }
  39. /// Set the function that combines the friction of two bodies and returns it
  40. /// Default method is the geometric mean: sqrt(friction1 * friction2).
  41. void SetCombineFriction(ContactConstraintManager::CombineFunction inCombineFriction) { mContactManager.SetCombineFriction(inCombineFriction); }
  42. /// Set the function that combines the restitution of two bodies and returns it
  43. /// Default method is max(restitution1, restitution1)
  44. void SetCombineRestitution(ContactConstraintManager::CombineFunction inCombineRestition) { mContactManager.SetCombineRestitution(inCombineRestition); }
  45. /// Control the main constants of the physics simulation
  46. void SetPhysicsSettings(const PhysicsSettings &inSettings) { mPhysicsSettings = inSettings; }
  47. const PhysicsSettings & GetPhysicsSettings() const { return mPhysicsSettings; }
  48. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  49. /// Set function that converts a broadphase layer to a human readable string for debugging purposes
  50. void SetBroadPhaseLayerToString(BroadPhaseLayerToString inBroadPhaseLayerToString) { mBroadPhase->SetBroadPhaseLayerToString(inBroadPhaseLayerToString); }
  51. #endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
  52. /// Access to the body interface. This interface allows to to create / remove bodies and to change their properties.
  53. BodyInterface & GetBodyInterface() { return mBodyInterfaceLocking; }
  54. BodyInterface & GetBodyInterfaceNoLock() { return mBodyInterfaceNoLock; } ///< Version that does not lock the bodies, use with great care!
  55. /// Access to the broadphase interface that allows coarse collision queries
  56. const BroadPhaseQuery & GetBroadPhaseQuery() const { return *mBroadPhase; }
  57. /// Interface that allows fine collision queries against first the broad phase and then the narrow phase.
  58. const NarrowPhaseQuery & GetNarrowPhaseQuery() const { return mNarrowPhaseQueryLocking; }
  59. const NarrowPhaseQuery & GetNarrowPhaseQueryNoLock() const { return mNarrowPhaseQueryNoLock; } ///< Version that does not lock the bodies, use with great care!
  60. /// Add constraint to the world
  61. void AddConstraint(Constraint *inConstraint) { mConstraintManager.Add(&inConstraint, 1); }
  62. /// Remove constraint from the world
  63. void RemoveConstraint(Constraint *inConstraint) { mConstraintManager.Remove(&inConstraint, 1); }
  64. /// Batch add constraints. Note that the inConstraints array is allowed to have nullptrs, these will be ignored.
  65. void AddConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Add(inConstraints, inNumber); }
  66. /// Batch remove constraints. Note that the inConstraints array is allowed to have nullptrs, these will be ignored.
  67. void RemoveConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Remove(inConstraints, inNumber); }
  68. /// Optimize the broadphase, needed only if you've added many bodies prior to calling Update() for the first time.
  69. void OptimizeBroadPhase();
  70. /// Adds a new step listener
  71. void AddStepListener(PhysicsStepListener *inListener);
  72. /// Removes a step listener
  73. void RemoveStepListener(PhysicsStepListener *inListener);
  74. /// Simulate the system.
  75. /// The world steps for a total of inDeltaTime seconds. This is divided in inCollisionSteps iterations. Each iteration
  76. /// consists of collision detection followed by inIntegrationSubSteps integration steps.
  77. void Update(float inDeltaTime, int inCollisionSteps, int inIntegrationSubSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem);
  78. /// Saving state for replay
  79. void SaveState(StateRecorder &inStream) const;
  80. /// Restoring state for replay. Returns false if failed.
  81. bool RestoreState(StateRecorder &inStream);
  82. #ifdef JPH_DEBUG_RENDERER
  83. // Drawing properties
  84. static bool sDrawMotionQualityLinearCast; ///< Draw debug info for objects that perform continuous collision detection through the linear cast motion quality
  85. /// Draw the state of the bodies (debugging purposes)
  86. void DrawBodies(const BodyManager::DrawSettings &inSettings, DebugRenderer *inRenderer) { mBodyManager.Draw(inSettings, mPhysicsSettings, inRenderer); }
  87. /// Draw the constraints only (debugging purposes)
  88. void DrawConstraints(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraints(inRenderer); }
  89. /// Draw the constraint limits only (debugging purposes)
  90. void DrawConstraintLimits(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintLimits(inRenderer); }
  91. /// Draw the constraint reference frames only (debugging purposes)
  92. void DrawConstraintReferenceFrame(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintReferenceFrame(inRenderer); }
  93. #endif // JPH_DEBUG_RENDERER
  94. /// Set gravity value
  95. void SetGravity(Vec3Arg inGravity) { mGravity = inGravity; }
  96. Vec3 GetGravity() const { return mGravity; }
  97. /// Returns a locking interface that won't actually lock the body. Use with great care!
  98. inline const BodyLockInterfaceNoLock & GetBodyLockInterfaceNoLock() const { return mBodyLockInterfaceNoLock; }
  99. /// Returns a locking interface that locks the body so other threads cannot modify it.
  100. inline const BodyLockInterfaceLocking & GetBodyLockInterface() const { return mBodyLockInterfaceLocking; }
  101. /// Get an broadphase layer filter that uses the default pair filter and a specified object layer to determine if broadphase layers collide
  102. DefaultBroadPhaseLayerFilter GetDefaultBroadPhaseLayerFilter(ObjectLayer inLayer) const { return DefaultBroadPhaseLayerFilter(mObjectVsBroadPhaseLayerFilter, inLayer); }
  103. /// Get an object layer filter that uses the default pair filter and a specified layer to determine if layers collide
  104. DefaultObjectLayerFilter GetDefaultLayerFilter(ObjectLayer inLayer) const { return DefaultObjectLayerFilter(mObjectLayerPairFilter, inLayer); }
  105. /// Gets the current amount of bodies that are in the body manager
  106. uint GetNumBodies() const { return mBodyManager.GetNumBodies(); }
  107. /// Gets the current amount of active bodies that are in the body manager
  108. uint32 GetNumActiveBodies() const { return mBodyManager.GetNumActiveBodies(); }
  109. /// Get the maximum amount of bodies that this physics system supports
  110. uint GetMaxBodies() const { return mBodyManager.GetMaxBodies(); }
  111. /// Helper struct that counts the number of bodies of each type
  112. using BodyStats = BodyManager::BodyStats;
  113. /// Get stats about the bodies in the body manager (slow, iterates through all bodies)
  114. BodyStats GetBodyStats() const { return mBodyManager.GetBodyStats(); }
  115. /// Get copy of the list of all bodies under protection of a lock.
  116. /// @param outBodyIDs On return, this will contain the list of BodyIDs
  117. void GetBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetBodyIDs(outBodyIDs); }
  118. /// Get copy of the list of active bodies under protection of a lock.
  119. /// @param outBodyIDs On return, this will contain the list of BodyIDs
  120. void GetActiveBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetActiveBodies(outBodyIDs); }
  121. #ifdef JPH_TRACK_BROADPHASE_STATS
  122. /// Trace the accumulated broadphase stats to the TTY
  123. void ReportBroadphaseStats() { mBroadPhase->ReportStats(); }
  124. #endif // JPH_TRACK_BROADPHASE_STATS
  125. private:
  126. using CCDBody = PhysicsUpdateContext::SubStep::CCDBody;
  127. // Various job entry points
  128. void JobStepListeners(PhysicsUpdateContext::Step *ioStep);
  129. void JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const;
  130. void JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  131. void JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep);
  132. void JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
  133. void JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex);
  134. void JobFinalizeIslands(PhysicsUpdateContext *ioContext);
  135. void JobBodySetIslandIndex(PhysicsUpdateContext *ioContext);
  136. void JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  137. void JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const;
  138. void JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  139. void JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const;
  140. void JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  141. void JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  142. void JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep);
  143. void JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
  144. /// Tries to spawn a new FindCollisions job if max concurrency hasn't been reached yet
  145. void TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const;
  146. using ContactAllocator = ContactConstraintManager::ContactAllocator;
  147. /// Process narrow phase for a single body pair
  148. void ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair);
  149. /// Number of constraints to process at once in JobDetermineActiveConstraints
  150. static constexpr int cDetermineActiveConstraintsBatchSize = 64;
  151. /// Number of bodies to process at once in JobApplyGravity
  152. static constexpr int cApplyGravityBatchSize = 64;
  153. /// Number of active bodies to test for collisions per batch
  154. static constexpr int cActiveBodiesBatchSize = 16;
  155. /// Number of active bodies to integrate velocities for
  156. static constexpr int cIntegrateVelocityBatchSize = 64;
  157. /// Number of contacts that need to be queued before another narrow phase job is started
  158. static constexpr int cNarrowPhaseBatchSize = 16;
  159. /// Number of continuous collision shape casts that need to be queued before another job is started
  160. static constexpr int cNumCCDBodiesPerJob = 4;
  161. /// Broadphase layer filter that decides if two objects can collide
  162. ObjectVsBroadPhaseLayerFilter mObjectVsBroadPhaseLayerFilter = nullptr;
  163. /// Object layer filter that decides if two objects can collide
  164. ObjectLayerPairFilter mObjectLayerPairFilter = nullptr;
  165. /// The body manager keeps track which bodies are in the simulation
  166. BodyManager mBodyManager;
  167. /// Body locking interfaces
  168. BodyLockInterfaceNoLock mBodyLockInterfaceNoLock { mBodyManager };
  169. BodyLockInterfaceLocking mBodyLockInterfaceLocking { mBodyManager };
  170. /// Body interfaces
  171. BodyInterface mBodyInterfaceNoLock;
  172. BodyInterface mBodyInterfaceLocking;
  173. /// Narrow phase query interface
  174. NarrowPhaseQuery mNarrowPhaseQueryNoLock;
  175. NarrowPhaseQuery mNarrowPhaseQueryLocking;
  176. /// The broadphase does quick collision detection between body pairs
  177. BroadPhase * mBroadPhase = nullptr;
  178. /// The contact manager resolves all contacts during a simulation step
  179. ContactConstraintManager mContactManager;
  180. /// All non-contact constraints
  181. ConstraintManager mConstraintManager;
  182. /// Keeps track of connected bodies and builds islands for multithreaded velocity/position update
  183. IslandBuilder mIslandBuilder;
  184. /// Mutex protecting mStepListeners
  185. Mutex mStepListenersMutex;
  186. /// List of physics step listeners
  187. using StepListeners = vector<PhysicsStepListener *>;
  188. StepListeners mStepListeners;
  189. /// This is the global gravity vector
  190. Vec3 mGravity = Vec3(0, -9.81f, 0);
  191. /// Previous frame's delta time of one sub step to allow scaling previous frame's constraint impulses
  192. float mPreviousSubStepDeltaTime = 0.0f;
  193. /// Simulation settings
  194. PhysicsSettings mPhysicsSettings;
  195. };
  196. } // JPH