Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
ContactConstraintManager.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
17
19#include <atomic>
21
23
24struct PhysicsSettings;
26
28{
29public:
31
33 explicit ContactConstraintManager(const PhysicsSettings &inPhysicsSettings);
35
39 void Init(uint inMaxBodyPairs, uint inMaxContactConstraints);
40
42 void SetContactListener(ContactListener *inListener) { mContactListener = inListener; }
43 ContactListener * GetContactListener() const { return mContactListener; }
44
48 using CombineFunction = float (*)(const Body &inBody1, const SubShapeID &inSubShapeID1, const Body &inBody2, const SubShapeID &inSubShapeID2);
49
52 void SetCombineFriction(CombineFunction inCombineFriction) { mCombineFriction = inCombineFriction; }
53 CombineFunction GetCombineFriction() const { return mCombineFriction; }
54
57 void SetCombineRestitution(CombineFunction inCombineRestitution) { mCombineRestitution = inCombineRestitution; }
58 CombineFunction GetCombineRestitution() const { return mCombineRestitution; }
59
61 uint32 GetMaxConstraints() const { return mMaxConstraints; }
62
64 inline ValidateResult ValidateContactPoint(const Body &inBody1, const Body &inBody2, RVec3Arg inBaseOffset, const CollideShapeResult &inCollisionResult) const
65 {
66 if (mContactListener == nullptr)
67 return ValidateResult::AcceptAllContactsForThisBodyPair;
68
69 return mContactListener->OnContactValidate(inBody1, inBody2, inBaseOffset, inCollisionResult);
70 }
71
73 void PrepareConstraintBuffer(PhysicsUpdateContext *inContext);
74
76 static const int MaxContactPoints = 4;
77
80 {
81 public:
83
84 uint mNumBodyPairs = 0;
85 uint mNumManifolds = 0;
86 EPhysicsUpdateError mErrors = EPhysicsUpdateError::None;
87 };
88
90 ContactAllocator GetContactAllocator() { return mCache[mCacheWriteIdx].GetContactAllocator(); }
91
95 void GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled, bool &outConstraintCreated);
96
98 using BodyPairHandle = void *;
99
102 BodyPairHandle AddBodyPair(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2);
103
145 bool AddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPair, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);
146
151 void FinalizeContactCacheAndCallContactPointRemovedCallbacks(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds);
152
155 bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const;
156
158 uint32 GetNumConstraints() const { return min<uint32>(mNumConstraints, mMaxConstraints); }
159
161 void SortContacts(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd) const;
162
164 inline void GetAffectedBodies(uint32 inConstraintIdx, const Body *&outBody1, const Body *&outBody2) const
165 {
166 const ContactConstraint &constraint = mConstraints[inConstraintIdx];
167 outBody1 = constraint.mBody1;
168 outBody2 = constraint.mBody2;
169 }
170
172 void WarmStartVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio);
173
204 bool SolveVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd);
205
207 void StoreAppliedImpulses(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const;
208
225 bool SolvePositionConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd);
226
228 void RecycleConstraintBuffer();
229
231 void FinishConstraintBuffer();
232
239 void OnCCDContactAdded(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &outSettings);
240
241#ifdef JPH_DEBUG_RENDERER
242 // Drawing properties
243 static bool sDrawContactPoint;
247#endif // JPH_DEBUG_RENDERER
248
250 void SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const;
251
253 bool RestoreState(StateRecorder &inStream);
254
255private:
257 class CachedContactPoint
258 {
259 public:
261 void SaveState(StateRecorder &inStream) const;
262 void RestoreState(StateRecorder &inStream);
263
266 Float3 mPosition1;
267 Float3 mPosition2;
268
270 float mNonPenetrationLambda;
271 Vector<2> mFrictionLambda;
272 };
273
274 static_assert(sizeof(CachedContactPoint) == 36, "Unexpected size");
275 static_assert(alignof(CachedContactPoint) == 4, "Assuming 4 byte aligned");
276
278 class CachedManifold
279 {
280 public:
282 static int sGetRequiredExtraSize(int inNumContactPoints) { return max(0, inNumContactPoints - 1) * sizeof(CachedContactPoint); }
283
285 static int sGetRequiredTotalSize(int inNumContactPoints) { return sizeof(CachedManifold) + sGetRequiredExtraSize(inNumContactPoints); }
286
288 void SaveState(StateRecorder &inStream) const;
289 void RestoreState(StateRecorder &inStream);
290
292 uint32 mNextWithSameBodyPair;
293
296 Float3 mContactNormal;
297
299 enum class EFlags : uint16
300 {
301 ContactPersisted = 1,
302 CCDContact = 2
303 };
304
306 mutable atomic<uint16> mFlags { 0 };
307
309 uint16 mNumContactPoints;
310
312 CachedContactPoint mContactPoints[1];
313 };
314
315 static_assert(sizeof(CachedManifold) == 56, "This structure is expect to not contain any waste due to alignment");
316 static_assert(alignof(CachedManifold) == 4, "Assuming 4 byte aligned");
317
320 using MKeyValue = ManifoldMap::KeyValue;
321 using MKVAndCreated = pair<MKeyValue *, bool>;
322
324 class CachedBodyPair
325 {
326 public:
328 void SaveState(StateRecorder &inStream) const;
329 void RestoreState(StateRecorder &inStream);
330
333 Float3 mDeltaPosition;
334
337 Float3 mDeltaRotation;
338
340 uint32 mFirstCachedManifold;
341 };
342
343 static_assert(sizeof(CachedBodyPair) == 28, "Unexpected size");
344 static_assert(alignof(CachedBodyPair) == 4, "Assuming 4 byte aligned");
345
348 using BPKeyValue = BodyPairMap::KeyValue;
349
351 class ManifoldCache
352 {
353 public:
355 void Init(uint inMaxBodyPairs, uint inMaxContactConstraints, uint inCachedManifoldsSize);
356
358 void Clear();
359
362 void Prepare(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds);
363
365 ContactAllocator GetContactAllocator() { return ContactAllocator(mAllocator, cAllocatorBlockSize); }
366
368 const MKeyValue * Find(const SubShapeIDPair &inKey, uint64 inKeyHash) const;
369 MKeyValue * Create(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints);
370 MKVAndCreated FindOrCreate(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints);
371 uint32 ToHandle(const MKeyValue *inKeyValue) const;
372 const MKeyValue * FromHandle(uint32 inHandle) const;
373
375 const BPKeyValue * Find(const BodyPair &inKey, uint64 inKeyHash) const;
376 BPKeyValue * Create(ContactAllocator &ioContactAllocator, const BodyPair &inKey, uint64 inKeyHash);
377 void GetAllBodyPairsSorted(Array<const BPKeyValue *> &outAll) const;
378 void GetAllManifoldsSorted(const CachedBodyPair &inBodyPair, Array<const MKeyValue *> &outAll) const;
379 void GetAllCCDManifoldsSorted(Array<const MKeyValue *> &outAll) const;
380 void ContactPointRemovedCallbacks(ContactListener *inListener);
381
382#ifdef JPH_ENABLE_ASSERTS
384 uint GetNumManifolds() const { return mCachedManifolds.GetNumKeyValues(); }
385
387 uint GetNumBodyPairs() const { return mCachedBodyPairs.GetNumKeyValues(); }
388
390 void Finalize();
391#endif
392
394 void SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const;
395 bool RestoreState(const ManifoldCache &inReadCache, StateRecorder &inStream);
396
397 private:
399 static constexpr uint32 cAllocatorBlockSize = 4096;
400
402 LFHMAllocator mAllocator;
403
405 ManifoldMap mCachedManifolds { mAllocator };
406
408 BodyPairMap mCachedBodyPairs { mAllocator };
409
410#ifdef JPH_ENABLE_ASSERTS
411 bool mIsFinalized = false;
412#endif
413 };
414
415 ManifoldCache mCache[2];
416 int mCacheWriteIdx = 0;
417
419 class WorldContactPoint
420 {
421 public:
423 void CalculateNonPenetrationConstraintProperties(const Body &inBody1, float inInvMass1, float inInvInertiaScale1, const Body &inBody2, float inInvMass2, float inInvInertiaScale2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal);
424
425 template <EMotionType Type1, EMotionType Type2>
426 JPH_INLINE void TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings, float inMinVelocityForRestitution);
427
429 AxisConstraintPart mNonPenetrationConstraint;
430 AxisConstraintPart mFrictionConstraint1;
431 AxisConstraintPart mFrictionConstraint2;
432
434 CachedContactPoint * mContactPoint;
435 };
436
437 using WorldContactPoints = StaticArray<WorldContactPoint, MaxContactPoints>;
438
440 class ContactConstraint
441 {
442 public:
443 #ifdef JPH_DEBUG_RENDERER
445 void Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const;
446 #endif // JPH_DEBUG_RENDERER
447
449 JPH_INLINE Vec3 GetWorldSpaceNormal() const
450 {
451 return Vec3::sLoadFloat3Unsafe(mWorldSpaceNormal);
452 }
453
455 JPH_INLINE void GetTangents(Vec3 &outTangent1, Vec3 &outTangent2) const
456 {
457 Vec3 ws_normal = GetWorldSpaceNormal();
458 outTangent1 = ws_normal.GetNormalizedPerpendicular();
459 outTangent2 = ws_normal.Cross(outTangent1);
460 }
461
462 Body * mBody1;
463 Body * mBody2;
464 uint64 mSortKey;
465 Float3 mWorldSpaceNormal;
466 float mCombinedFriction;
467 float mInvMass1;
468 float mInvInertiaScale1;
469 float mInvMass2;
470 float mInvInertiaScale2;
471 WorldContactPoints mContactPoints;
472 };
473
475 template <EMotionType Type1, EMotionType Type2>
476 JPH_INLINE void TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2);
477
479 inline void CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2);
480
482 template <EMotionType Type1, EMotionType Type2>
483 bool TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);
484
486 template <EMotionType Type1, EMotionType Type2>
487 JPH_INLINE static void sWarmStartConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio);
488
490 template <EMotionType Type1, EMotionType Type2>
491 JPH_INLINE static bool sSolveVelocityConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2);
492
494 const PhysicsSettings & mPhysicsSettings;
495
497 ContactListener * mContactListener = nullptr;
498
500 CombineFunction mCombineFriction = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return sqrt(inBody1.GetFriction() * inBody2.GetFriction()); };
501 CombineFunction mCombineRestitution = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return max(inBody1.GetRestitution(), inBody2.GetRestitution()); };
502
504 ContactConstraint * mConstraints = nullptr;
505 uint32 mMaxConstraints = 0;
506 atomic<uint32> mNumConstraints { 0 };
507
509 PhysicsUpdateContext * mUpdateContext;
510};
511
ValidateResult
Definition: ContactListener.h:57
#define JPH_EXPORT
Definition: Core.h:214
#define JPH_SUPPRESS_WARNINGS_STD_BEGIN
Definition: Core.h:359
#define JPH_SUPPRESS_WARNINGS_STD_END
Definition: Core.h:371
std::uint64_t uint64
Definition: Core.h:430
unsigned int uint
Definition: Core.h:426
#define JPH_NAMESPACE_END
Definition: Core.h:354
std::uint32_t uint32
Definition: Core.h:429
#define JPH_NAMESPACE_BEGIN
Definition: Core.h:348
std::uint16_t uint16
Definition: Core.h:428
EPhysicsUpdateError
Enum used by PhysicsSystem to report error conditions during the PhysicsSystem::Update call....
Definition: EPhysicsUpdateError.h:11
#define JPH_OVERRIDE_NEW_DELETE
Macro to override the new and delete functions.
Definition: Memory.h:29
std::vector< T, STLAllocator< T > > Array
Definition: STLAllocator.h:81
Definition: AxisConstraintPart.h:43
Definition: Body.h:35
float GetRestitution() const
Restitution (dimensionless number, usually between 0 and 1, 0 = completely inelastic collision respon...
Definition: Body.h:122
float GetFriction() const
Friction (dimensionless number, usually between 0 and 1, 0 = no friction, 1 = friction force equals f...
Definition: Body.h:118
ID of a body. This is a way of reasoning about bodies in a multithreaded simulation while avoiding ra...
Definition: BodyID.h:13
Class that contains all information of two colliding shapes.
Definition: CollideShape.h:19
Class that holds an RGBA color with 8-bits per component.
Definition: Color.h:16
Contacts are allocated in a lock free hash map.
Definition: ContactConstraintManager.h:80
Definition: ContactConstraintManager.h:28
static bool sDrawContactPoint
Definition: ContactConstraintManager.h:243
CombineFunction GetCombineFriction() const
Definition: ContactConstraintManager.h:53
CombineFunction GetCombineRestitution() const
Definition: ContactConstraintManager.h:58
ValidateResult ValidateContactPoint(const Body &inBody1, const Body &inBody2, RVec3Arg inBaseOffset, const CollideShapeResult &inCollisionResult) const
Check with the listener if inBody1 and inBody2 could collide, returns false if not.
Definition: ContactConstraintManager.h:64
uint32 GetMaxConstraints() const
Get the max number of contact constraints that are allowed.
Definition: ContactConstraintManager.h:61
static bool sDrawContactPointReduction
Definition: ContactConstraintManager.h:245
void * BodyPairHandle
Handle used to keep track of the current body pair.
Definition: ContactConstraintManager.h:98
ContactListener * GetContactListener() const
Definition: ContactConstraintManager.h:43
static bool sDrawSupportingFaces
Definition: ContactConstraintManager.h:244
void GetAffectedBodies(uint32 inConstraintIdx, const Body *&outBody1, const Body *&outBody2) const
Get the affected bodies for a given constraint.
Definition: ContactConstraintManager.h:164
uint32 GetNumConstraints() const
Get the number of contact constraints that were found.
Definition: ContactConstraintManager.h:158
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:57
ContactAllocator GetContactAllocator()
Get a new allocator context for storing contacts. Note that you should call this once and then add mu...
Definition: ContactConstraintManager.h:90
static bool sDrawContactManifolds
Definition: ContactConstraintManager.h:246
Definition: ContactListener.h:68
Manifold class, describes the contact surface between two bodies.
Definition: ContactListener.h:20
Definition: ContactListener.h:41
Simple triangle renderer for debugging purposes.
Definition: DebugRenderer.h:30
Class that holds 3 floats. Used as a storage class. Convert to Vec3 for calculations.
Definition: Float3.h:13
Definition: LockFreeHashMap.h:49
LFHMAllocatorContext(LFHMAllocator &inAllocator, uint32 inBlockSize)
Construct a new allocator context.
Definition: LockFreeHashMap.inl:80
Allocator for a lock free hash map.
Definition: LockFreeHashMap.h:14
Definition: LockFreeHashMap.h:72
Holds a 4x4 matrix of floats, but supports also operations on the 3x3 upper left part of the matrix.
Definition: Mat44.h:13
The Body class only keeps track of state for static bodies, the MotionProperties class keeps the addi...
Definition: MotionProperties.h:29
Class that makes another class non-copyable. Usage: Inherit from NonCopyable.
Definition: NonCopyable.h:11
Information used during the Update call.
Definition: PhysicsUpdateContext.h:24
User callbacks that allow determining which parts of the simulation should be saved by a StateRecorde...
Definition: StateRecorder.h:29
Definition: StateRecorder.h:48
Simple variable length array backed by a fixed size buffer.
Definition: StaticArray.h:12
A sub shape id contains a path to an element (usually a triangle or other primitive type) of a compou...
Definition: SubShapeID.h:23
A pair of bodies and their sub shape ID's. Can be used as a key in a map to find a contact point.
Definition: SubShapeIDPair.h:15
Definition: Vec3.h:16
JPH_INLINE Vec3 Cross(Vec3Arg inV2) const
Cross product.
Definition: Vec3.inl:582
JPH_INLINE Vec3 GetNormalizedPerpendicular() const
Get normalized vector that is perpendicular to this vector.
Definition: Vec3.inl:812
static JPH_INLINE Vec3 sLoadFloat3Unsafe(const Float3 &inV)
Load 3 floats from memory (reads 32 bits extra which it doesn't use)
Definition: Vec3.inl:134
Templatized vector class.
Definition: Vector.h:12
Structure that holds a body pair.
Definition: BodyPair.h:14
Definition: PhysicsSettings.h:28