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#include <Jolt/Math/Vector.h>
18
20#include <atomic>
22
24
25struct PhysicsSettings;
26class PhysicsUpdateContext;
27
32{
33public:
35
37 explicit ContactConstraintManager(const PhysicsSettings &inPhysicsSettings);
39
43 void Init(uint inMaxBodyPairs, uint inMaxContactConstraints);
44
46 void SetContactListener(ContactListener *inListener) { mContactListener = inListener; }
47 ContactListener * GetContactListener() const { return mContactListener; }
48
52 using CombineFunction = float (*)(const Body &inBody1, const SubShapeID &inSubShapeID1, const Body &inBody2, const SubShapeID &inSubShapeID2);
53
56 void SetCombineFriction(CombineFunction inCombineFriction) { mCombineFriction = inCombineFriction; }
57 CombineFunction GetCombineFriction() const { return mCombineFriction; }
58
61 void SetCombineRestitution(CombineFunction inCombineRestitution) { mCombineRestitution = inCombineRestitution; }
62 CombineFunction GetCombineRestitution() const { return mCombineRestitution; }
63
65 uint32 GetMaxConstraints() const { return mMaxConstraints; }
66
68 inline ValidateResult ValidateContactPoint(const Body &inBody1, const Body &inBody2, RVec3Arg inBaseOffset, const CollideShapeResult &inCollisionResult) const
69 {
70 if (mContactListener == nullptr)
72
73 return mContactListener->OnContactValidate(inBody1, inBody2, inBaseOffset, inCollisionResult);
74 }
75
77 void PrepareConstraintBuffer(PhysicsUpdateContext *inContext);
78
80 static const int MaxContactPoints = 4;
81
84 {
85 public:
87
88 uint mNumBodyPairs = 0;
89 uint mNumManifolds = 0;
91 };
92
94 ContactAllocator GetContactAllocator() { return mCache[mCacheWriteIdx].GetContactAllocator(); }
95
98 void GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled);
99
101 using BodyPairHandle = void *;
102
105 BodyPairHandle AddBodyPair(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2);
106
148 void AddContactConstraint(ContactAllocator &ioContactAllocator, bool &ioActivateAndLinkBodies, BodyPairHandle inBodyPair, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);
149
154 void FinalizeContactCacheAndCallContactPointRemovedCallbacks(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds);
155
158 bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const;
159
161 uint32 GetNumConstraints() const { return min<uint32>(uint32(mNumConstraintsAndNextConstraintOffset.load(memory_order_relaxed)), mMaxConstraints); }
162
164 void ConstraintIdxToConstraintOffset(uint32 *ioConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const;
165
167 void SortContacts(uint32 *ioConstraintOffsetBegin, uint32 *inConstraintOffsetEnd) const;
168
170 inline void GetAffectedBodies(uint32 inConstraintOffset, const Body *&outBody1, const Body *&outBody2) const
171 {
172 const ContactConstraintBase &constraint = *reinterpret_cast<const ContactConstraintBase *>(mConstraints + inConstraintOffset);
173 outBody1 = constraint.mBody1;
174 outBody2 = constraint.mBody2;
175 }
176
178 template <class MotionPropertiesCallback>
179 void WarmStartVelocityConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd, float inWarmStartImpulseRatio, MotionPropertiesCallback &ioCallback);
180
211 bool SolveVelocityConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd);
212
214 void StoreAppliedImpulses(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd) const;
215
232 bool SolvePositionConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd);
233
235 void RecycleConstraintBuffer();
236
238 void FinishConstraintBuffer();
239
246 void OnCCDContactAdded(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &outSettings);
247
248#ifdef JPH_DEBUG_RENDERER
249 // Drawing properties
250 static bool sDrawContactPoint;
254#endif // JPH_DEBUG_RENDERER
255
257 void SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const;
258
260 bool RestoreState(StateRecorder &inStream, const StateRecorderFilter *inFilter);
261
262private:
264 class CachedContactPoint
265 {
266 public:
268 void SaveState(StateRecorder &inStream) const;
269 void RestoreState(StateRecorder &inStream);
270
273 Float3 mPosition1;
274 Float3 mPosition2;
275
277 float mNonPenetrationLambda;
278 Vector<2> mFrictionLambda;
279 };
280
281 static_assert(sizeof(CachedContactPoint) == 36, "Unexpected size");
282 static_assert(alignof(CachedContactPoint) == 4, "Assuming 4 byte aligned");
283
285 class CachedManifold
286 {
287 public:
289 static constexpr int sGetRequiredExtraSize(int inNumContactPoints) { return max(0, inNumContactPoints - 1) * sizeof(CachedContactPoint); }
290
292 static constexpr int sGetRequiredTotalSize(int inNumContactPoints) { return sizeof(CachedManifold) + sGetRequiredExtraSize(inNumContactPoints); }
293
295 void SaveState(StateRecorder &inStream) const;
296 void RestoreState(StateRecorder &inStream);
297
299 uint32 mNextWithSameBodyPair;
300
303 Float3 mContactNormal;
304
306 enum class EFlags : uint16
307 {
308 ContactPersisted = 1,
309 CCDContact = 2
310 };
311
313 mutable atomic<uint16> mFlags { 0 };
314
316 uint16 mNumContactPoints;
317
319 CachedContactPoint mContactPoints[1];
320 };
321
322 static_assert(sizeof(CachedManifold) == 56, "This structure is expect to not contain any waste due to alignment");
323 static_assert(alignof(CachedManifold) == 4, "Assuming 4 byte aligned");
324
327 using MKeyValue = ManifoldMap::KeyValue;
328 using MKVAndCreated = std::pair<MKeyValue *, bool>;
329
331 class CachedBodyPair
332 {
333 public:
335 void SaveState(StateRecorder &inStream) const;
336 void RestoreState(StateRecorder &inStream);
337
340 Float3 mDeltaPosition;
341
344 Float3 mDeltaRotation;
345
347 uint32 mFirstCachedManifold;
348 };
349
350 static_assert(sizeof(CachedBodyPair) == 28, "Unexpected size");
351 static_assert(alignof(CachedBodyPair) == 4, "Assuming 4 byte aligned");
352
355 using BPKeyValue = BodyPairMap::KeyValue;
356
358 class ManifoldCache
359 {
360 public:
362 void Init(uint inMaxBodyPairs, uint inMaxContactConstraints, uint inCachedManifoldsSize);
363
365 void Clear();
366
369 void Prepare(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds);
370
372 ContactAllocator GetContactAllocator() { return ContactAllocator(mAllocator, cAllocatorBlockSize); }
373
375 const MKeyValue * Find(const SubShapeIDPair &inKey, uint64 inKeyHash) const;
376 MKeyValue * Create(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints);
377 MKVAndCreated FindOrCreate(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints);
378 uint32 ToHandle(const MKeyValue *inKeyValue) const;
379 const MKeyValue * FromHandle(uint32 inHandle) const;
380
382 const BPKeyValue * Find(const BodyPair &inKey, uint64 inKeyHash) const;
383 BPKeyValue * Create(ContactAllocator &ioContactAllocator, const BodyPair &inKey, uint64 inKeyHash);
384 void GetAllBodyPairsSorted(Array<const BPKeyValue *> &outAll) const;
385 void GetAllManifoldsSorted(const CachedBodyPair &inBodyPair, Array<const MKeyValue *> &outAll) const;
386 void GetAllCCDManifoldsSorted(Array<const MKeyValue *> &outAll) const;
387 void ContactPointRemovedCallbacks(ContactListener *inListener);
388
389#ifdef JPH_ENABLE_ASSERTS
391 uint GetNumManifolds() const { return mCachedManifolds.GetNumKeyValues(); }
392
394 uint GetNumBodyPairs() const { return mCachedBodyPairs.GetNumKeyValues(); }
395
397 void Finalize();
398#endif
399
401 void SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const;
402 bool RestoreState(const ManifoldCache &inReadCache, StateRecorder &inStream, const StateRecorderFilter *inFilter);
403
404 private:
406 static constexpr uint32 cAllocatorBlockSize = 4096;
407
409 LFHMAllocator mAllocator;
410
412 ManifoldMap mCachedManifolds { mAllocator };
413
415 BodyPairMap mCachedBodyPairs { mAllocator };
416
417#ifdef JPH_ENABLE_ASSERTS
418 bool mIsFinalized = false;
419#endif
420 };
421
422 ManifoldCache mCache[2];
423 int mCacheWriteIdx = 0;
424
426 template <EMotionType Type1, EMotionType Type2>
427 class WorldContactPoint
428 {
429 public:
430 using ConstraintPart = ContactConstraintPart<Type1, Type2>;
431
433 JPH_INLINE void CalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, Vec3Arg inGravity, 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);
434
436 ConstraintPart mNonPenetrationConstraint;
437 ConstraintPart mFrictionConstraint1;
438 ConstraintPart mFrictionConstraint2;
439 // Note that this needs to be followed by data of size float, see comment at ContactConstraintPart
440
442 CachedContactPoint * mContactPoint;
443 };
444
445 class ContactConstraintBase
446 {
447 public:
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 uint32 mNumContactPoints;
472 };
473
475 template <EMotionType Type1, EMotionType Type2>
476 class ContactConstraint : public ContactConstraintBase
477 {
478 public:
479 #ifdef JPH_DEBUG_RENDERER
481 void Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const;
482 #endif // JPH_DEBUG_RENDERER
483
484 WorldContactPoint<Type1, Type2> mContactPoints[1];
485 };
486
487public:
489 static constexpr uint32 cMaxConstraintSize = sizeof(ContactConstraint<EMotionType::Dynamic, EMotionType::Dynamic>) + (MaxContactPoints - 1) * sizeof(WorldContactPoint<EMotionType::Dynamic, EMotionType::Dynamic>);
490
492 static constexpr uint cMaxContactConstraintsLimit = ~uint(0) / cMaxConstraintSize;
493
495 static constexpr uint cMaxBodyPairsLimit = ~uint(0) / sizeof(BodyPairMap::KeyValue);
496
497private:
499 template <EMotionType Type1, EMotionType Type2>
500 JPH_INLINE ContactConstraint<Type1, Type2> *CreateConstraint(bool &ioActivateAndLinkBodies, Body &inBody1, Body &inBody2, uint64 inSortKey, Vec3Arg inWorldSpaceNormal, const ContactSettings &inSettings, uint32 inNumContactPoints);
501
503 template <EMotionType Type1, EMotionType Type2>
504 void TemplatedGetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, const CachedBodyPair &inCachedBodyPair, CachedBodyPair &outCachedBodyPair);
505
507 template <EMotionType Type1, EMotionType Type2>
508 void TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, bool &ioActivateAndLinkBodies, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);
509
511 template <EMotionType Type1, EMotionType Type2>
512 static JPH_INLINE void sGetVelocities(const MotionProperties *inMotionProperties1, const MotionProperties *inMotionProperties2, Vec3 &outLinearVelocity1, Vec3 &outAngularVelocity1, Vec3 &outLinearVelocity2, Vec3 &outAngularVelocity2);
513
515 template <EMotionType Type1, EMotionType Type2>
516 static JPH_INLINE void sSetVelocities(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inLinearVelocity1, Vec3Arg inAngularVelocity1, Vec3Arg inLinearVelocity2, Vec3Arg inAngularVelocity2);
517
519 template <EMotionType Type1, EMotionType Type2>
520 static void sWarmStartConstraint(ContactConstraintBase &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio);
521
523 template <EMotionType Type1, EMotionType Type2>
524 static bool sSolveVelocityConstraint(ContactConstraintBase &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2);
525
527 template <EMotionType Type1, EMotionType Type2>
528 static void sStoreAppliedImpulses(ContactConstraintBase &ioConstraint);
529
531 template <EMotionType Type1, EMotionType Type2>
532 static bool sSolvePositionConstraint(ContactConstraintBase &ioConstraint, Body &ioBody1, Body &ioBody2, const PhysicsSettings &inSettings);
533
535 const PhysicsSettings & mPhysicsSettings;
536
538 ContactListener * mContactListener = nullptr;
539
541 CombineFunction mCombineFriction = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return sqrt(inBody1.GetFriction() * inBody2.GetFriction()); };
542 CombineFunction mCombineRestitution = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return max(inBody1.GetRestitution(), inBody2.GetRestitution()); };
543
545 uint8 * mConstraints = nullptr;
546 uint32 * mConstraintIdxToOffset = nullptr;
547 uint32 mMaxConstraints = 0;
548 atomic<uint64> mNumConstraintsAndNextConstraintOffset { 0 }; // Lower 32 bits: number of constraints, upper 32 bits next constraint offset
549
551 PhysicsUpdateContext * mUpdateContext;
552};
553
ValidateResult
Definition ContactListener.h:57
@ AcceptAllContactsForThisBodyPair
Accept this and any further contact points for this body pair.
std::uint8_t uint8
Definition Core.h:506
#define JPH_EXPORT
Definition Core.h:278
#define JPH_SUPPRESS_WARNINGS_STD_BEGIN
Definition Core.h:433
#define JPH_SUPPRESS_WARNINGS_STD_END
Definition Core.h:446
std::uint64_t uint64
Definition Core.h:510
unsigned int uint
Definition Core.h:505
#define JPH_NAMESPACE_END
Definition Core.h:428
std::uint32_t uint32
Definition Core.h:508
#define JPH_NAMESPACE_BEGIN
Definition Core.h:422
std::uint16_t uint16
Definition Core.h:507
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:50
Definition Array.h:36
Definition Body.h:39
float GetRestitution() const
Restitution (dimensionless number, usually between 0 and 1, 0 = completely inelastic collision respon...
Definition Body.h:146
float GetFriction() const
Friction (dimensionless number, usually between 0 and 1, 0 = no friction, 1 = friction force equals f...
Definition Body.h:142
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:84
Definition ContactConstraintManager.h:32
static bool sDrawContactPoint
Definition ContactConstraintManager.h:250
CombineFunction GetCombineFriction() const
Definition ContactConstraintManager.h:57
CombineFunction GetCombineRestitution() const
Definition ContactConstraintManager.h:62
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:68
uint32 GetMaxConstraints() const
Get the max number of contact constraints that are allowed.
Definition ContactConstraintManager.h:65
static bool sDrawContactPointReduction
Definition ContactConstraintManager.h:252
void * BodyPairHandle
Handle used to keep track of the current body pair.
Definition ContactConstraintManager.h:101
void GetAffectedBodies(uint32 inConstraintOffset, const Body *&outBody1, const Body *&outBody2) const
Get the affected bodies for a given constraint.
Definition ContactConstraintManager.h:170
ContactListener * GetContactListener() const
Definition ContactConstraintManager.h:47
static bool sDrawSupportingFaces
Definition ContactConstraintManager.h:251
uint32 GetNumConstraints() const
Get the number of contact constraints that were found.
Definition ContactConstraintManager.h:161
void SetCombineFriction(CombineFunction inCombineFriction)
Definition ContactConstraintManager.h:56
void SetContactListener(ContactListener *inListener)
Listener that is notified whenever a contact point between two bodies is added/updated/removed.
Definition ContactConstraintManager.h:46
float(*)(const Body &inBody1, const SubShapeID &inSubShapeID1, const Body &inBody2, const SubShapeID &inSubShapeID2) CombineFunction
Definition ContactConstraintManager.h:52
void SetCombineRestitution(CombineFunction inCombineRestitution)
Definition ContactConstraintManager.h:61
ContactAllocator GetContactAllocator()
Get a new allocator context for storing contacts. Note that you should call this once and then add mu...
Definition ContactConstraintManager.h:94
static bool sDrawContactManifolds
Definition ContactConstraintManager.h:253
Definition ContactConstraintPart.h:94
Definition ContactListener.h:79
Manifold class, describes the contact surface between two bodies.
Definition ContactListener.h:20
Definition ContactListener.h:41
Definition DebugRenderer.h:47
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:88
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
User callbacks that allow determining which parts of the simulation should be saved by a StateRecorde...
Definition StateRecorder.h:79
Definition StateRecorder.h:110
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:17
JPH_INLINE Vec3 Cross(Vec3Arg inV2) const
Cross product.
Definition Vec3.inl:841
JPH_INLINE Vec3 GetNormalizedPerpendicular() const
Get normalized vector that is perpendicular to this vector.
Definition Vec3.inl:1217
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:167
Templatized vector class.
Definition Vector.h:12
Structure that holds a body pair.
Definition BodyPair.h:14
Definition PhysicsSettings.h:31