Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
PhysicsSystem.h
Go to the documentation of this file.
1// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
16
18
19class JobSystem;
20class StateRecorder;
21class TempAllocator;
23
28{
29public:
31
33 PhysicsSystem() : mContactManager(mPhysicsSettings) JPH_IF_ENABLE_ASSERTS(, mConstraintManager(&mBodyManager)) { }
35
44 void Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter);
45
47 void SetBodyActivationListener(BodyActivationListener *inListener) { mBodyManager.SetBodyActivationListener(inListener); }
49
51 void SetContactListener(ContactListener *inListener) { mContactManager.SetContactListener(inListener); }
52 ContactListener * GetContactListener() const { return mContactManager.GetContactListener(); }
53
56 void SetCombineFriction(ContactConstraintManager::CombineFunction inCombineFriction) { mContactManager.SetCombineFriction(inCombineFriction); }
57
60 void SetCombineRestitution(ContactConstraintManager::CombineFunction inCombineRestition) { mContactManager.SetCombineRestitution(inCombineRestition); }
61
63 void SetPhysicsSettings(const PhysicsSettings &inSettings) { mPhysicsSettings = inSettings; }
64 const PhysicsSettings & GetPhysicsSettings() const { return mPhysicsSettings; }
65
67 const BodyInterface & GetBodyInterface() const { return mBodyInterfaceLocking; }
68 BodyInterface & GetBodyInterface() { return mBodyInterfaceLocking; }
69 const BodyInterface & GetBodyInterfaceNoLock() const { return mBodyInterfaceNoLock; }
70 BodyInterface & GetBodyInterfaceNoLock() { return mBodyInterfaceNoLock; }
71
73 const BroadPhaseQuery & GetBroadPhaseQuery() const { return *mBroadPhase; }
74
76 const NarrowPhaseQuery & GetNarrowPhaseQuery() const { return mNarrowPhaseQueryLocking; }
77 const NarrowPhaseQuery & GetNarrowPhaseQueryNoLock() const { return mNarrowPhaseQueryNoLock; }
78
80 void AddConstraint(Constraint *inConstraint) { mConstraintManager.Add(&inConstraint, 1); }
81
83 void RemoveConstraint(Constraint *inConstraint) { mConstraintManager.Remove(&inConstraint, 1); }
84
86 void AddConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Add(inConstraints, inNumber); }
87
89 void RemoveConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Remove(inConstraints, inNumber); }
90
92 Constraints GetConstraints() const { return mConstraintManager.GetConstraints(); }
93
95 void OptimizeBroadPhase();
96
98 void AddStepListener(PhysicsStepListener *inListener);
99
101 void RemoveStepListener(PhysicsStepListener *inListener);
102
106 EPhysicsUpdateError Update(float inDeltaTime, int inCollisionSteps, int inIntegrationSubSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem);
107
109 void SaveState(StateRecorder &inStream) const;
110
112 bool RestoreState(StateRecorder &inStream);
113
114#ifdef JPH_DEBUG_RENDERER
115 // Drawing properties
117
119 void DrawBodies(const BodyManager::DrawSettings &inSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter = nullptr) { mBodyManager.Draw(inSettings, mPhysicsSettings, inRenderer, inBodyFilter); }
120
122 void DrawConstraints(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraints(inRenderer); }
123
125 void DrawConstraintLimits(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintLimits(inRenderer); }
126
128 void DrawConstraintReferenceFrame(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintReferenceFrame(inRenderer); }
129#endif // JPH_DEBUG_RENDERER
130
132 void SetGravity(Vec3Arg inGravity) { mGravity = inGravity; }
133 Vec3 GetGravity() const { return mGravity; }
134
136 inline const BodyLockInterfaceNoLock & GetBodyLockInterfaceNoLock() const { return mBodyLockInterfaceNoLock; }
137
139 inline const BodyLockInterfaceLocking & GetBodyLockInterface() const { return mBodyLockInterfaceLocking; }
140
142 DefaultBroadPhaseLayerFilter GetDefaultBroadPhaseLayerFilter(ObjectLayer inLayer) const { return DefaultBroadPhaseLayerFilter(*mObjectVsBroadPhaseLayerFilter, inLayer); }
143
145 DefaultObjectLayerFilter GetDefaultLayerFilter(ObjectLayer inLayer) const { return DefaultObjectLayerFilter(*mObjectLayerPairFilter, inLayer); }
146
148 uint GetNumBodies() const { return mBodyManager.GetNumBodies(); }
149
151 uint32 GetNumActiveBodies() const { return mBodyManager.GetNumActiveBodies(); }
152
154 uint GetMaxBodies() const { return mBodyManager.GetMaxBodies(); }
155
158
160 BodyStats GetBodyStats() const { return mBodyManager.GetBodyStats(); }
161
164 void GetBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetBodyIDs(outBodyIDs); }
165
168 void GetActiveBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetActiveBodies(outBodyIDs); }
169
175 bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const { return mContactManager.WereBodiesInContact(inBody1ID, inBody2ID); }
176
177#ifdef JPH_TRACK_BROADPHASE_STATS
179 void ReportBroadphaseStats() { mBroadPhase->ReportStats(); }
180#endif // JPH_TRACK_BROADPHASE_STATS
181
182private:
184
185 // Various job entry points
186 void JobStepListeners(PhysicsUpdateContext::Step *ioStep);
187 void JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const;
188 void JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
189 void JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const;
190 void JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
191 void JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex);
192 void JobFinalizeIslands(PhysicsUpdateContext *ioContext);
193 void JobBodySetIslandIndex();
194 void JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
195 void JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
196 void JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
197 void JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const;
198 void JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
199 void JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
200 void JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep);
201 void JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
202
204 void TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const;
205
206 using ContactAllocator = ContactConstraintManager::ContactAllocator;
207
209 void ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair);
210
212 class BodiesToSleep;
213
215 void CheckSleepAndUpdateBounds(uint32 inIslandIndex, const PhysicsUpdateContext *ioContext, const PhysicsUpdateContext::SubStep *ioSubStep, BodiesToSleep &ioBodiesToSleep);
216
218 static constexpr int cDetermineActiveConstraintsBatchSize = 64;
219
221 static constexpr int cApplyGravityBatchSize = 64;
222
224 static constexpr int cActiveBodiesBatchSize = 16;
225
227 static constexpr int cIntegrateVelocityBatchSize = 64;
228
230 static constexpr int cNarrowPhaseBatchSize = 16;
231
233 static constexpr int cNumCCDBodiesPerJob = 4;
234
236 const ObjectVsBroadPhaseLayerFilter *mObjectVsBroadPhaseLayerFilter = nullptr;
237
239 const ObjectLayerPairFilter *mObjectLayerPairFilter = nullptr;
240
242 BodyManager mBodyManager;
243
245 BodyLockInterfaceNoLock mBodyLockInterfaceNoLock { mBodyManager };
246 BodyLockInterfaceLocking mBodyLockInterfaceLocking { mBodyManager };
247
249 BodyInterface mBodyInterfaceNoLock;
250 BodyInterface mBodyInterfaceLocking;
251
253 NarrowPhaseQuery mNarrowPhaseQueryNoLock;
254 NarrowPhaseQuery mNarrowPhaseQueryLocking;
255
257 BroadPhase * mBroadPhase = nullptr;
258
260 PhysicsSettings mPhysicsSettings;
261
263 ContactConstraintManager mContactManager;
264
266 ConstraintManager mConstraintManager;
267
269 IslandBuilder mIslandBuilder;
270
272 LargeIslandSplitter mLargeIslandSplitter;
273
275 Mutex mStepListenersMutex;
276
278 using StepListeners = Array<PhysicsStepListener *>;
279 StepListeners mStepListeners;
280
282 Vec3 mGravity = Vec3(0, -9.81f, 0);
283
285 float mPreviousSubStepDeltaTime = 0.0f;
286};
287
Array< BodyID > BodyIDVector
Array of body ID's.
Definition: BodyManager.h:26
Array< Ref< Constraint > > Constraints
A list of constraints.
Definition: ConstraintManager.h:20
uint32_t uint32
Definition: Core.h:312
unsigned int uint
Definition: Core.h:309
#define JPH_NAMESPACE_END
Definition: Core.h:240
#define JPH_NAMESPACE_BEGIN
Definition: Core.h:234
EPhysicsUpdateError
Enum used by PhysicsSystem to report error conditions during the PhysicsSystem::Update call....
Definition: EPhysicsUpdateError.h:11
#define JPH_IF_ENABLE_ASSERTS(...)
Definition: IssueReporting.h:35
#define JPH_OVERRIDE_NEW_DELETE
Macro to override the new and delete functions.
Definition: Memory.h:29
uint16 ObjectLayer
Definition: ObjectLayer.h:16
std::vector< T, STLAllocator< T > > Array
Definition: STLAllocator.h:81
Definition: BodyActivationListener.h:14
Class function to filter out bodies for debug rendering, returns true if body should be rendered.
Definition: BodyFilter.h:89
ID of a body. This is a way of reasoning about bodies in a multithreaded simulation while avoiding ra...
Definition: BodyID.h:13
Definition: BodyInterface.h:31
Implementation that uses the body manager to lock the correct mutex for a body.
Definition: BodyLockInterface.h:78
Implementation that performs no locking (assumes the lock has already been taken)
Definition: BodyLockInterface.h:58
Class that contains all bodies.
Definition: BodyManager.h:30
uint GetNumBodies() const
Gets the current amount of bodies that are in the body manager.
Definition: BodyManager.cpp:83
BodyActivationListener * GetBodyActivationListener() const
Definition: BodyManager.h:107
void SetBodyActivationListener(BodyActivationListener *inListener)
Listener that is notified whenever a body is activated/deactivated.
Definition: BodyManager.cpp:534
uint32 GetNumActiveBodies() const
Get the number of active bodies.
Definition: BodyManager.h:100
BodyStats GetBodyStats() const
Get stats about the bodies in the body manager (slow, iterates through all bodies)
Definition: BodyManager.cpp:90
void GetActiveBodies(BodyIDVector &outBodyIDs) const
Get copy of the list of active bodies under protection of a lock.
Definition: BodyManager.cpp:506
void Draw(const DrawSettings &inSettings, const PhysicsSettings &inPhysicsSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter=nullptr)
Draw the state of the bodies (debugging purposes)
Definition: BodyManager.cpp:716
void GetBodyIDs(BodyIDVector &outBodies) const
Get all body IDs under the protection of a lock.
Definition: BodyManager.cpp:515
uint GetMaxBodies() const
Gets the max bodies that we can support.
Definition: BodyManager.h:44
Used to do coarse collision detection operations to quickly prune out bodies that will not collide.
Definition: BroadPhase.h:26
Interface that the application should implement to allow mapping object layers to broadphase layers.
Definition: BroadPhaseLayer.h:56
Definition: BroadPhaseQuery.h:29
Base class for all physics constraints. A constraint removes one or more degrees of freedom for a rig...
Definition: Constraint.h:99
A constraint manager manages all constraints of the same type.
Definition: ConstraintManager.h:24
Constraints GetConstraints() const
Get a list of all constraints.
Definition: ConstraintManager.cpp:62
void DrawConstraintReferenceFrame(DebugRenderer *inRenderer) const
Draw all constraint reference frames.
Definition: ConstraintManager.cpp:218
void Remove(Constraint **inConstraint, int inNumber)
Definition: ConstraintManager.cpp:35
void DrawConstraints(DebugRenderer *inRenderer) const
Draw all constraints.
Definition: ConstraintManager.cpp:198
void DrawConstraintLimits(DebugRenderer *inRenderer) const
Draw all constraint limits.
Definition: ConstraintManager.cpp:208
JPH_OVERRIDE_NEW_DELETE void Add(Constraint **inConstraints, int inNumber)
Definition: ConstraintManager.cpp:16
Contacts are allocated in a lock free hash map.
Definition: ContactConstraintManager.h:78
Definition: ContactConstraintManager.h:28
bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const
Definition: ContactConstraintManager.cpp:1336
ContactListener * GetContactListener() const
Definition: ContactConstraintManager.h:43
void SetCombineFriction(CombineFunction inCombineFriction)
Definition: ContactConstraintManager.h:52
void SetContactListener(ContactListener *inListener)
Listener that is notified whenever a contact point between two bodies is added/updated/removed.
Definition: ContactConstraintManager.h:42
float(*)(const Body &inBody1, const SubShapeID &inSubShapeID1, const Body &inBody2, const SubShapeID &inSubShapeID2) CombineFunction
Definition: ContactConstraintManager.h:48
void SetCombineRestitution(CombineFunction inCombineRestitution)
Definition: ContactConstraintManager.h:56
Definition: ContactListener.h:62
Simple triangle renderer for debugging purposes.
Definition: DebugRenderer.h:25
Default filter class that uses the pair filter in combination with a specified layer to filter layers...
Definition: BroadPhaseLayer.h:103
Default filter class that uses the pair filter in combination with a specified layer to filter layers...
Definition: ObjectLayer.h:64
Keeps track of connected bodies and builds islands for multithreaded velocity/position update.
Definition: IslandBuilder.h:19
Definition: JobSystem.h:70
Definition: LargeIslandSplitter.h:24
Definition: Mutex.h:122
Definition: NarrowPhaseQuery.h:23
Class that makes another class non-copyable. Usage: Inherit from NonCopyable.
Definition: NonCopyable.h:11
Filter class to test if two objects can collide based on their object layer. Used while finding colli...
Definition: ObjectLayer.h:50
Class to test if an object can collide with a broadphase layer. Used while finding collision pairs.
Definition: BroadPhaseLayer.h:75
A listener class that receives a callback before every physics simulation step.
Definition: PhysicsStepListener.h:13
Definition: PhysicsSystem.h:28
void RemoveStepListener(PhysicsStepListener *inListener)
Removes a step listener.
Definition: PhysicsSystem.cpp:108
void GetBodies(BodyIDVector &outBodyIDs) const
Definition: PhysicsSystem.h:164
void DrawConstraintReferenceFrame(DebugRenderer *inRenderer)
Draw the constraint reference frames only (debugging purposes)
Definition: PhysicsSystem.h:128
void AddStepListener(PhysicsStepListener *inListener)
Adds a new step listener.
Definition: PhysicsSystem.cpp:100
const NarrowPhaseQuery & GetNarrowPhaseQuery() const
Interface that allows fine collision queries against first the broad phase and then the narrow phase.
Definition: PhysicsSystem.h:76
void RemoveConstraints(Constraint **inConstraints, int inNumber)
Batch remove constraints. Note that the inConstraints array is allowed to have nullptrs,...
Definition: PhysicsSystem.h:89
uint GetNumBodies() const
Gets the current amount of bodies that are in the body manager.
Definition: PhysicsSystem.h:148
~PhysicsSystem()
Definition: PhysicsSystem.cpp:62
void SetPhysicsSettings(const PhysicsSettings &inSettings)
Control the main constants of the physics simulation.
Definition: PhysicsSystem.h:63
const BodyInterface & GetBodyInterface() const
Access to the body interface. This interface allows to to create / remove bodies and to change their ...
Definition: PhysicsSystem.h:67
const BroadPhaseQuery & GetBroadPhaseQuery() const
Access to the broadphase interface that allows coarse collision queries.
Definition: PhysicsSystem.h:73
const BodyLockInterfaceLocking & GetBodyLockInterface() const
Returns a locking interface that locks the body so other threads cannot modify it.
Definition: PhysicsSystem.h:139
const NarrowPhaseQuery & GetNarrowPhaseQueryNoLock() const
Version that does not lock the bodies, use with great care!
Definition: PhysicsSystem.h:77
void DrawConstraints(DebugRenderer *inRenderer)
Draw the constraints only (debugging purposes)
Definition: PhysicsSystem.h:122
const PhysicsSettings & GetPhysicsSettings() const
Definition: PhysicsSystem.h:64
const BodyInterface & GetBodyInterfaceNoLock() const
Version that does not lock the bodies, use with great care!
Definition: PhysicsSystem.h:69
BodyInterface & GetBodyInterface()
Definition: PhysicsSystem.h:68
void DrawConstraintLimits(DebugRenderer *inRenderer)
Draw the constraint limits only (debugging purposes)
Definition: PhysicsSystem.h:125
bool RestoreState(StateRecorder &inStream)
Restoring state for replay. Returns false if failed.
Definition: PhysicsSystem.cpp:2399
void GetActiveBodies(BodyIDVector &outBodyIDs) const
Definition: PhysicsSystem.h:168
Constraints GetConstraints() const
Get a list of all constraints.
Definition: PhysicsSystem.h:92
void AddConstraint(Constraint *inConstraint)
Add constraint to the world.
Definition: PhysicsSystem.h:80
Vec3 GetGravity() const
Definition: PhysicsSystem.h:133
uint GetMaxBodies() const
Get the maximum amount of bodies that this physics system supports.
Definition: PhysicsSystem.h:154
void RemoveConstraint(Constraint *inConstraint)
Remove constraint from the world.
Definition: PhysicsSystem.h:83
void SaveState(StateRecorder &inStream) const
Saving state for replay.
Definition: PhysicsSystem.cpp:2385
void DrawBodies(const BodyManager::DrawSettings &inSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter=nullptr)
Draw the state of the bodies (debugging purposes)
Definition: PhysicsSystem.h:119
BodyActivationListener * GetBodyActivationListener() const
Definition: PhysicsSystem.h:48
DefaultBroadPhaseLayerFilter GetDefaultBroadPhaseLayerFilter(ObjectLayer inLayer) const
Get an broadphase layer filter that uses the default pair filter and a specified object layer to dete...
Definition: PhysicsSystem.h:142
BodyInterface & GetBodyInterfaceNoLock()
Version that does not lock the bodies, use with great care!
Definition: PhysicsSystem.h:70
void SetCombineRestitution(ContactConstraintManager::CombineFunction inCombineRestition)
Definition: PhysicsSystem.h:60
JPH_OVERRIDE_NEW_DELETE PhysicsSystem()
Constructor / Destructor.
Definition: PhysicsSystem.h:33
void OptimizeBroadPhase()
Optimize the broadphase, needed only if you've added many bodies prior to calling Update() for the fi...
Definition: PhysicsSystem.cpp:95
static bool sDrawMotionQualityLinearCast
Draw debug info for objects that perform continuous collision detection through the linear cast motio...
Definition: PhysicsSystem.h:116
EPhysicsUpdateError Update(float inDeltaTime, int inCollisionSteps, int inIntegrationSubSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem)
Definition: PhysicsSystem.cpp:118
void SetGravity(Vec3Arg inGravity)
Set gravity value.
Definition: PhysicsSystem.h:132
const BodyLockInterfaceNoLock & GetBodyLockInterfaceNoLock() const
Returns a locking interface that won't actually lock the body. Use with great care!
Definition: PhysicsSystem.h:136
BodyStats GetBodyStats() const
Get stats about the bodies in the body manager (slow, iterates through all bodies)
Definition: PhysicsSystem.h:160
void AddConstraints(Constraint **inConstraints, int inNumber)
Batch add constraints. Note that the inConstraints array is allowed to have nullptrs,...
Definition: PhysicsSystem.h:86
bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const
Definition: PhysicsSystem.h:175
DefaultObjectLayerFilter GetDefaultLayerFilter(ObjectLayer inLayer) const
Get an object layer filter that uses the default pair filter and a specified layer to determine if la...
Definition: PhysicsSystem.h:145
void SetContactListener(ContactListener *inListener)
Listener that is notified whenever a contact point between two bodies is added/updated/removed.
Definition: PhysicsSystem.h:51
void SetCombineFriction(ContactConstraintManager::CombineFunction inCombineFriction)
Definition: PhysicsSystem.h:56
void Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter)
Definition: PhysicsSystem.cpp:68
void SetBodyActivationListener(BodyActivationListener *inListener)
Listener that is notified whenever a body is activated/deactivated.
Definition: PhysicsSystem.h:47
ContactListener * GetContactListener() const
Definition: PhysicsSystem.h:52
uint32 GetNumActiveBodies() const
Gets the current amount of active bodies that are in the body manager.
Definition: PhysicsSystem.h:151
Information used during the Update call.
Definition: PhysicsUpdateContext.h:23
Definition: StateRecorder.h:15
Definition: TempAllocator.h:16
Definition: Vec3.h:16
Helper struct that counts the number of bodies of each type.
Definition: BodyManager.h:48
Draw settings.
Definition: BodyManager.h:183
Structure that holds a body pair.
Definition: BodyPair.h:14
Definition: PhysicsSettings.h:28
Structure that contains data needed for each collision step.
Definition: PhysicsUpdateContext.h:100
Contains the information needed to cast a body through the scene to do continuous collision detection...
Definition: PhysicsUpdateContext.h:51
Structure that contains job handles for each integration sub step.
Definition: PhysicsUpdateContext.h:38