PhysicsSystem.h 15 KB

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