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;
24
29{
30public:
32
34 PhysicsSystem() : mContactManager(mPhysicsSettings) JPH_IF_ENABLE_ASSERTS(, mConstraintManager(&mBodyManager)) { }
36
45 void Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter);
46
48 void SetBodyActivationListener(BodyActivationListener *inListener) { mBodyManager.SetBodyActivationListener(inListener); }
49 BodyActivationListener * GetBodyActivationListener() const { return mBodyManager.GetBodyActivationListener(); }
50
52 void SetContactListener(ContactListener *inListener) { mContactManager.SetContactListener(inListener); }
53 ContactListener * GetContactListener() const { return mContactManager.GetContactListener(); }
54
56 void SetSoftBodyContactListener(SoftBodyContactListener *inListener) { mSoftBodyContactListener = inListener; }
57 SoftBodyContactListener * GetSoftBodyContactListener() const { return mSoftBodyContactListener; }
58
61 void SetCombineFriction(ContactConstraintManager::CombineFunction inCombineFriction) { mContactManager.SetCombineFriction(inCombineFriction); }
62 ContactConstraintManager::CombineFunction GetCombineFriction() const { return mContactManager.GetCombineFriction(); }
63
66 void SetCombineRestitution(ContactConstraintManager::CombineFunction inCombineRestition) { mContactManager.SetCombineRestitution(inCombineRestition); }
67 ContactConstraintManager::CombineFunction GetCombineRestitution() const { return mContactManager.GetCombineRestitution(); }
68
70 void SetPhysicsSettings(const PhysicsSettings &inSettings) { mPhysicsSettings = inSettings; }
71 const PhysicsSettings & GetPhysicsSettings() const { return mPhysicsSettings; }
72
74 const BodyInterface & GetBodyInterface() const { return mBodyInterfaceLocking; }
75 BodyInterface & GetBodyInterface() { return mBodyInterfaceLocking; }
76 const BodyInterface & GetBodyInterfaceNoLock() const { return mBodyInterfaceNoLock; }
77 BodyInterface & GetBodyInterfaceNoLock() { return mBodyInterfaceNoLock; }
78
80 const BroadPhaseQuery & GetBroadPhaseQuery() const { return *mBroadPhase; }
81
83 const NarrowPhaseQuery & GetNarrowPhaseQuery() const { return mNarrowPhaseQueryLocking; }
84 const NarrowPhaseQuery & GetNarrowPhaseQueryNoLock() const { return mNarrowPhaseQueryNoLock; }
85
87 void AddConstraint(Constraint *inConstraint) { mConstraintManager.Add(&inConstraint, 1); }
88
90 void RemoveConstraint(Constraint *inConstraint) { mConstraintManager.Remove(&inConstraint, 1); }
91
93 void AddConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Add(inConstraints, inNumber); }
94
96 void RemoveConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Remove(inConstraints, inNumber); }
97
99 Constraints GetConstraints() const { return mConstraintManager.GetConstraints(); }
100
102 void OptimizeBroadPhase();
103
105 void AddStepListener(PhysicsStepListener *inListener);
106
108 void RemoveStepListener(PhysicsStepListener *inListener);
109
114 EPhysicsUpdateError Update(float inDeltaTime, int inCollisionSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem);
115
117 void SaveState(StateRecorder &inStream, EStateRecorderState inState = EStateRecorderState::All, const StateRecorderFilter *inFilter = nullptr) const;
118
120 bool RestoreState(StateRecorder &inStream);
121
123 void SaveBodyState(const Body &inBody, StateRecorder &inStream) const;
124
126 void RestoreBodyState(Body &ioBody, StateRecorder &inStream);
127
128#ifdef JPH_DEBUG_RENDERER
129 // Drawing properties
131
133 void DrawBodies(const BodyManager::DrawSettings &inSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter = nullptr) { mBodyManager.Draw(inSettings, mPhysicsSettings, inRenderer, inBodyFilter); }
134
136 void DrawConstraints(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraints(inRenderer); }
137
139 void DrawConstraintLimits(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintLimits(inRenderer); }
140
142 void DrawConstraintReferenceFrame(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintReferenceFrame(inRenderer); }
143#endif // JPH_DEBUG_RENDERER
144
146 void SetGravity(Vec3Arg inGravity) { mGravity = inGravity; }
147 Vec3 GetGravity() const { return mGravity; }
148
150 inline const BodyLockInterfaceNoLock & GetBodyLockInterfaceNoLock() const { return mBodyLockInterfaceNoLock; }
151
153 inline const BodyLockInterfaceLocking & GetBodyLockInterface() const { return mBodyLockInterfaceLocking; }
154
156 DefaultBroadPhaseLayerFilter GetDefaultBroadPhaseLayerFilter(ObjectLayer inLayer) const { return DefaultBroadPhaseLayerFilter(*mObjectVsBroadPhaseLayerFilter, inLayer); }
157
159 DefaultObjectLayerFilter GetDefaultLayerFilter(ObjectLayer inLayer) const { return DefaultObjectLayerFilter(*mObjectLayerPairFilter, inLayer); }
160
162 uint GetNumBodies() const { return mBodyManager.GetNumBodies(); }
163
165 uint32 GetNumActiveBodies(EBodyType inType) const { return mBodyManager.GetNumActiveBodies(inType); }
166
168 uint GetMaxBodies() const { return mBodyManager.GetMaxBodies(); }
169
172
174 BodyStats GetBodyStats() const { return mBodyManager.GetBodyStats(); }
175
178 void GetBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetBodyIDs(outBodyIDs); }
179
183 void GetActiveBodies(EBodyType inType, BodyIDVector &outBodyIDs) const { return mBodyManager.GetActiveBodies(inType, outBodyIDs); }
184
187 const BodyID * GetActiveBodiesUnsafe(EBodyType inType) const { return mBodyManager.GetActiveBodiesUnsafe(inType); }
188
194 bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const { return mContactManager.WereBodiesInContact(inBody1ID, inBody2ID); }
195
197 AABox GetBounds() const { return mBroadPhase->GetBounds(); }
198
199#ifdef JPH_TRACK_BROADPHASE_STATS
201 void ReportBroadphaseStats() { mBroadPhase->ReportStats(); }
202#endif // JPH_TRACK_BROADPHASE_STATS
203
204private:
206
207 // Various job entry points
208 void JobStepListeners(PhysicsUpdateContext::Step *ioStep);
209 void JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const;
210 void JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
211 void JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const;
212 void JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
213 void JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex);
214 void JobFinalizeIslands(PhysicsUpdateContext *ioContext);
215 void JobBodySetIslandIndex();
216 void JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
217 void JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
218 void JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
219 void JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep) const;
220 void JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
221 void JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
222 void JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep);
223 void JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
224 void JobSoftBodyPrepare(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
225 void JobSoftBodyCollide(PhysicsUpdateContext *ioContext) const;
226 void JobSoftBodySimulate(PhysicsUpdateContext *ioContext, uint inThreadIndex) const;
227 void JobSoftBodyFinalize(PhysicsUpdateContext *ioContext);
228
230 void TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const;
231
232 using ContactAllocator = ContactConstraintManager::ContactAllocator;
233
235 void ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair);
236
238 class BodiesToSleep;
239
241 void CheckSleepAndUpdateBounds(uint32 inIslandIndex, const PhysicsUpdateContext *ioContext, const PhysicsUpdateContext::Step *ioStep, BodiesToSleep &ioBodiesToSleep);
242
244 static constexpr int cDetermineActiveConstraintsBatchSize = 64;
245
247 static constexpr int cSetupVelocityConstraintsBatchSize = 256;
248
250 static constexpr int cApplyGravityBatchSize = 64;
251
253 static constexpr int cActiveBodiesBatchSize = 16;
254
256 static constexpr int cIntegrateVelocityBatchSize = 64;
257
259 static constexpr int cNarrowPhaseBatchSize = 16;
260
262 static constexpr int cNumCCDBodiesPerJob = 4;
263
265 const ObjectVsBroadPhaseLayerFilter *mObjectVsBroadPhaseLayerFilter = nullptr;
266
268 const ObjectLayerPairFilter *mObjectLayerPairFilter = nullptr;
269
271 BodyManager mBodyManager;
272
274 BodyLockInterfaceNoLock mBodyLockInterfaceNoLock { mBodyManager };
275 BodyLockInterfaceLocking mBodyLockInterfaceLocking { mBodyManager };
276
278 BodyInterface mBodyInterfaceNoLock;
279 BodyInterface mBodyInterfaceLocking;
280
282 NarrowPhaseQuery mNarrowPhaseQueryNoLock;
283 NarrowPhaseQuery mNarrowPhaseQueryLocking;
284
286 BroadPhase * mBroadPhase = nullptr;
287
289 SoftBodyContactListener * mSoftBodyContactListener = nullptr;
290
292 PhysicsSettings mPhysicsSettings;
293
295 ContactConstraintManager mContactManager;
296
298 ConstraintManager mConstraintManager;
299
301 IslandBuilder mIslandBuilder;
302
304 LargeIslandSplitter mLargeIslandSplitter;
305
307 Mutex mStepListenersMutex;
308
310 using StepListeners = Array<PhysicsStepListener *>;
311 StepListeners mStepListeners;
312
314 Vec3 mGravity = Vec3(0, -9.81f, 0);
315
317 float mPreviousStepDeltaTime = 0.0f;
318};
319
Array< BodyID > BodyIDVector
Array of body ID's.
Definition: BodyManager.h:28
EBodyType
Type of body.
Definition: BodyType.h:11
Array< Ref< Constraint > > Constraints
A list of constraints.
Definition: ConstraintManager.h:21
#define JPH_EXPORT
Definition: Core.h:227
unsigned int uint
Definition: Core.h:439
#define JPH_NAMESPACE_END
Definition: Core.h:367
std::uint32_t uint32
Definition: Core.h:442
#define JPH_NAMESPACE_BEGIN
Definition: Core.h:361
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
EStateRecorderState
A bit field that determines which aspects of the simulation to save.
Definition: StateRecorder.h:18
Axis aligned box.
Definition: AABox.h:16
Definition: BodyActivationListener.h:14
Class function to filter out bodies for debug rendering, returns true if body should be rendered.
Definition: BodyFilter.h:89
Definition: Body.h:35
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:35
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:32
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:61
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:103
A constraint manager manages all constraints of the same type.
Definition: ConstraintManager.h:25
Contacts are allocated in a lock free hash map.
Definition: ContactConstraintManager.h:80
Definition: ContactConstraintManager.h:28
float(*)(const Body &inBody1, const SubShapeID &inSubShapeID1, const Body &inBody2, const SubShapeID &inSubShapeID2) CombineFunction
Definition: ContactConstraintManager.h:48
Definition: ContactListener.h:68
Definition: DebugRenderer.h:47
Default filter class that uses the pair filter in combination with a specified layer to filter layers...
Definition: BroadPhaseLayer.h:108
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:25
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:80
A listener class that receives a callback before every physics simulation step.
Definition: PhysicsStepListener.h:13
Definition: PhysicsSystem.h:29
void GetBodies(BodyIDVector &outBodyIDs) const
Definition: PhysicsSystem.h:178
void DrawConstraintReferenceFrame(DebugRenderer *inRenderer)
Draw the constraint reference frames only (debugging purposes)
Definition: PhysicsSystem.h:142
const NarrowPhaseQuery & GetNarrowPhaseQuery() const
Interface that allows fine collision queries against first the broad phase and then the narrow phase.
Definition: PhysicsSystem.h:83
void RemoveConstraints(Constraint **inConstraints, int inNumber)
Batch remove constraints. Note that the inConstraints array is allowed to have nullptrs,...
Definition: PhysicsSystem.h:96
uint GetNumBodies() const
Gets the current amount of bodies that are in the body manager.
Definition: PhysicsSystem.h:162
uint32 GetNumActiveBodies(EBodyType inType) const
Gets the current amount of active bodies that are in the body manager.
Definition: PhysicsSystem.h:165
void SetPhysicsSettings(const PhysicsSettings &inSettings)
Control the main constants of the physics simulation.
Definition: PhysicsSystem.h:70
void SetSoftBodyContactListener(SoftBodyContactListener *inListener)
Listener that is notified whenever a contact point between a soft body and another body.
Definition: PhysicsSystem.h:56
const BodyInterface & GetBodyInterface() const
Access to the body interface. This interface allows to to create / remove bodies and to change their ...
Definition: PhysicsSystem.h:74
const BroadPhaseQuery & GetBroadPhaseQuery() const
Access to the broadphase interface that allows coarse collision queries.
Definition: PhysicsSystem.h:80
const BodyLockInterfaceLocking & GetBodyLockInterface() const
Returns a locking interface that locks the body so other threads cannot modify it.
Definition: PhysicsSystem.h:153
const NarrowPhaseQuery & GetNarrowPhaseQueryNoLock() const
Version that does not lock the bodies, use with great care!
Definition: PhysicsSystem.h:84
void DrawConstraints(DebugRenderer *inRenderer)
Draw the constraints only (debugging purposes)
Definition: PhysicsSystem.h:136
const PhysicsSettings & GetPhysicsSettings() const
Definition: PhysicsSystem.h:71
const BodyInterface & GetBodyInterfaceNoLock() const
Version that does not lock the bodies, use with great care!
Definition: PhysicsSystem.h:76
BodyInterface & GetBodyInterface()
Definition: PhysicsSystem.h:75
void DrawConstraintLimits(DebugRenderer *inRenderer)
Draw the constraint limits only (debugging purposes)
Definition: PhysicsSystem.h:139
Constraints GetConstraints() const
Get a list of all constraints.
Definition: PhysicsSystem.h:99
void AddConstraint(Constraint *inConstraint)
Add constraint to the world.
Definition: PhysicsSystem.h:87
Vec3 GetGravity() const
Definition: PhysicsSystem.h:147
uint GetMaxBodies() const
Get the maximum amount of bodies that this physics system supports.
Definition: PhysicsSystem.h:168
void RemoveConstraint(Constraint *inConstraint)
Remove constraint from the world.
Definition: PhysicsSystem.h:90
AABox GetBounds() const
Get the bounding box of all bodies in the physics system.
Definition: PhysicsSystem.h:197
void DrawBodies(const BodyManager::DrawSettings &inSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter=nullptr)
Draw the state of the bodies (debugging purposes)
Definition: PhysicsSystem.h:133
BodyActivationListener * GetBodyActivationListener() const
Definition: PhysicsSystem.h:49
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:156
BodyInterface & GetBodyInterfaceNoLock()
Version that does not lock the bodies, use with great care!
Definition: PhysicsSystem.h:77
void GetActiveBodies(EBodyType inType, BodyIDVector &outBodyIDs) const
Definition: PhysicsSystem.h:183
ContactConstraintManager::CombineFunction GetCombineRestitution() const
Definition: PhysicsSystem.h:67
void SetCombineRestitution(ContactConstraintManager::CombineFunction inCombineRestition)
Definition: PhysicsSystem.h:66
JPH_OVERRIDE_NEW_DELETE PhysicsSystem()
Constructor / Destructor.
Definition: PhysicsSystem.h:34
static bool sDrawMotionQualityLinearCast
Draw debug info for objects that perform continuous collision detection through the linear cast motio...
Definition: PhysicsSystem.h:130
void SetGravity(Vec3Arg inGravity)
Set gravity value.
Definition: PhysicsSystem.h:146
const BodyLockInterfaceNoLock & GetBodyLockInterfaceNoLock() const
Returns a locking interface that won't actually lock the body. Use with great care!
Definition: PhysicsSystem.h:150
BodyStats GetBodyStats() const
Get stats about the bodies in the body manager (slow, iterates through all bodies)
Definition: PhysicsSystem.h:174
void AddConstraints(Constraint **inConstraints, int inNumber)
Batch add constraints. Note that the inConstraints array is allowed to have nullptrs,...
Definition: PhysicsSystem.h:93
bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const
Definition: PhysicsSystem.h:194
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:159
void SetContactListener(ContactListener *inListener)
Listener that is notified whenever a contact point between two bodies is added/updated/removed.
Definition: PhysicsSystem.h:52
SoftBodyContactListener * GetSoftBodyContactListener() const
Definition: PhysicsSystem.h:57
ContactConstraintManager::CombineFunction GetCombineFriction() const
Definition: PhysicsSystem.h:62
void SetCombineFriction(ContactConstraintManager::CombineFunction inCombineFriction)
Definition: PhysicsSystem.h:61
const BodyID * GetActiveBodiesUnsafe(EBodyType inType) const
Definition: PhysicsSystem.h:187
void SetBodyActivationListener(BodyActivationListener *inListener)
Listener that is notified whenever a body is activated/deactivated.
Definition: PhysicsSystem.h:48
ContactListener * GetContactListener() const
Definition: PhysicsSystem.h:53
Information used during the Update call.
Definition: PhysicsUpdateContext.h:24
Definition: SoftBodyContactListener.h:33
User callbacks that allow determining which parts of the simulation should be saved by a StateRecorde...
Definition: StateRecorder.h:29
Definition: StateRecorder.h:48
Definition: TempAllocator.h:16
Definition: Vec3.h:16
Helper struct that counts the number of bodies of each type.
Definition: BodyManager.h:50
Draw settings.
Definition: BodyManager.h:219
Structure that holds a body pair.
Definition: BodyPair.h:14
Definition: PhysicsSettings.h:28
Contains the information needed to cast a body through the scene to do continuous collision detection...
Definition: PhysicsUpdateContext.h:97
Structure that contains data needed for each collision step.
Definition: PhysicsUpdateContext.h:52