ContactConstraintManager.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Core/StaticArray.h>
  5. #include <Jolt/Core/LockFreeHashMap.h>
  6. #include <Jolt/Physics/Body/BodyPair.h>
  7. #include <Jolt/Physics/Collision/Shape/SubShapeIDPair.h>
  8. #include <Jolt/Physics/Collision/ManifoldBetweenTwoFaces.h>
  9. #include <Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h>
  10. #include <Jolt/Physics/Constraints/ConstraintPart/DualAxisConstraintPart.h>
  11. #include <Jolt/Core/HashCombine.h>
  12. #include <Jolt/Core/NonCopyable.h>
  13. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  14. #include <atomic>
  15. JPH_SUPPRESS_WARNINGS_STD_END
  16. JPH_NAMESPACE_BEGIN
  17. struct PhysicsSettings;
  18. class PhysicsUpdateContext;
  19. class ContactConstraintManager : public NonCopyable
  20. {
  21. public:
  22. /// Constructor
  23. explicit ContactConstraintManager(const PhysicsSettings &inPhysicsSettings);
  24. ~ContactConstraintManager();
  25. /// Initialize the system.
  26. /// @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
  27. /// @param inMaxContactConstraints Maximum amount of contact constraints to process (anything else will fall through the world)
  28. void Init(uint inMaxBodyPairs, uint inMaxContactConstraints);
  29. /// Listener that is notified whenever a contact point between two bodies is added/updated/removed
  30. void SetContactListener(ContactListener *inListener) { mContactListener = inListener; }
  31. ContactListener * GetContactListener() const { return mContactListener; }
  32. /// Callback function to combine the restitution or friction of two bodies
  33. /// Note that when merging manifolds (when PhysicsSettings::mUseManifoldReduction is true) you will only get a callback for the merged manifold.
  34. /// It is not possible in that case to get all sub shape ID pairs that were colliding, you'll get the first encountered pair.
  35. using CombineFunction = float (*)(const Body &inBody1, const SubShapeID &inSubShapeID1, const Body &inBody2, const SubShapeID &inSubShapeID2);
  36. /// Set the function that combines the friction of two bodies and returns it
  37. /// Default method is the geometric mean: sqrt(friction1 * friction2).
  38. void SetCombineFriction(CombineFunction inCombineFriction) { mCombineFriction = inCombineFriction; }
  39. /// Set the function that combines the restitution of two bodies and returns it
  40. /// Default method is max(restitution1, restitution1)
  41. void SetCombineRestitution(CombineFunction inCombineRestitution) { mCombineRestitution = inCombineRestitution; }
  42. /// Get the max number of contact constraints that are allowed
  43. uint32 GetMaxConstraints() const { return mMaxConstraints; }
  44. /// Check with the listener if inBody1 and inBody2 could collide, returns false if not
  45. inline ValidateResult ValidateContactPoint(const Body &inBody1, const Body &inBody2, const CollideShapeResult &inCollisionResult) const
  46. {
  47. if (mContactListener == nullptr)
  48. return ValidateResult::AcceptAllContactsForThisBodyPair;
  49. return mContactListener->OnContactValidate(inBody1, inBody2, inCollisionResult);
  50. }
  51. /// Sets up the constraint buffer. Should be called before starting collision detection.
  52. void PrepareConstraintBuffer(PhysicsUpdateContext *inContext);
  53. /// Max 4 contact points are needed for a stable manifold
  54. static const int MaxContactPoints = 4;
  55. /// Contacts are allocated in a lock free hash map
  56. class ContactAllocator : public LFHMAllocatorContext
  57. {
  58. public:
  59. using LFHMAllocatorContext::LFHMAllocatorContext;
  60. uint mNumBodyPairs = 0; ///< Total number of body pairs added using this allocator
  61. uint mNumManifolds = 0; ///< Total number of manifolds added using this allocator
  62. };
  63. /// Get a new allocator context for storing contacts. Note that you should call this once and then add multiple contacts using the context.
  64. ContactAllocator GetContactAllocator() { return mCache[mCacheWriteIdx].GetContactAllocator(); }
  65. /// Check if the contact points from the previous frame are reusable and if so copy them.
  66. /// When the cache was usable and the pair has been handled: outPairHandled = true.
  67. /// When a contact constraint was produced: outConstraintCreated = true.
  68. void GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled, bool &outConstraintCreated);
  69. /// Handle used to keep track of the current body pair
  70. using BodyPairHandle = void *;
  71. /// Create a handle for a colliding body pair so that contact constraints can be added between them.
  72. /// Needs to be called once per body pair per frame before calling AddContactConstraint.
  73. BodyPairHandle AddBodyPair(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2);
  74. /// Add a contact constraint for this frame.
  75. ///
  76. /// @param ioContactAllocator The allocator that reserves memory for the contacts
  77. /// @param inBodyPair The handle for the contact cache for this body pair
  78. /// @param inBody1 The first body that is colliding
  79. /// @param inBody2 The second body that is colliding
  80. /// @param inManifold The manifold that describes the collision
  81. /// @return true if a contact constraint was created (can be false in the case of a sensor)
  82. ///
  83. /// This is using the approach described in 'Modeling and Solving Constraints' by Erin Catto presented at GDC 2009 (and later years with slight modifications).
  84. /// We're using the formulas from slide 50 - 53 combined.
  85. ///
  86. /// Euler velocity integration:
  87. ///
  88. /// v1' = v1 + M^-1 P
  89. ///
  90. /// Impulse:
  91. ///
  92. /// P = J^T lambda
  93. ///
  94. /// Constraint force:
  95. ///
  96. /// lambda = -K^-1 J v1
  97. ///
  98. /// Inverse effective mass:
  99. ///
  100. /// K = J M^-1 J^T
  101. ///
  102. /// Constraint equation (limits movement in 1 axis):
  103. ///
  104. /// C = (p2 - p1) . n
  105. ///
  106. /// Jacobian (for position constraint)
  107. ///
  108. /// J = [-n, -r1 x n, n, r2 x n]
  109. ///
  110. /// n = contact normal (pointing away from body 1).
  111. /// p1, p2 = positions of collision on body 1 and 2.
  112. /// r1, r2 = contact point relative to center of mass of body 1 and body 2 (r1 = p1 - x1, r2 = p2 - x2).
  113. /// v1, v2 = (linear velocity, angular velocity): 6 vectors containing linear and angular velocity for body 1 and 2.
  114. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].
  115. bool AddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPair, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);
  116. /// Finalizes the contact cache, the contact cache that was generated during the calls to AddContactConstraint in this update
  117. /// will be used from now on to read from.
  118. /// inExpectedNumBodyPairs / inExpectedNumManifolds are the amount of body pairs / manifolds found in the previous step and is used to determine the amount of buckets the contact cache hash map will use.
  119. void FinalizeContactCache(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds);
  120. /// Notifies the listener of any contact points that were removed. Needs to be callsed after FinalizeContactCache().
  121. void ContactPointRemovedCallbacks();
  122. /// Get the number of contact constraints that were found
  123. uint32 GetNumConstraints() const { return min<uint32>(mNumConstraints, mMaxConstraints); }
  124. /// Sort contact constraints deterministically
  125. void SortContacts(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd) const;
  126. /// AddContactConstraint will also setup the velocity constraints for the first sub step. For subsequent sub steps this function must be called prior to warm starting the constraint.
  127. void SetupVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inDeltaTime);
  128. /// Apply last frame's impulses as an initial guess for this frame's impulses
  129. void WarmStartVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio);
  130. /// Solve velocity constraints, when almost nothing changes this should only apply very small impulses
  131. /// since we're warm starting with the total impulse applied in the last frame above.
  132. ///
  133. /// Friction wise we're using the Coulomb friction model which says that:
  134. ///
  135. /// |F_T| <= mu |F_N|
  136. ///
  137. /// Where F_T is the tangential force, F_N is the normal force and mu is the friction coefficient
  138. ///
  139. /// In impulse terms this becomes:
  140. ///
  141. /// |lambda_T| <= mu |lambda_N|
  142. ///
  143. /// And the constraint that needs to be applied is exactly the same as a non penetration constraint
  144. /// except that we use a tangent instead of a normal. The tangent should point in the direction of the
  145. /// tangential velocity of the point:
  146. ///
  147. /// J = [-T, -r1 x T, T, r2 x T]
  148. ///
  149. /// Where T is the tangent.
  150. ///
  151. /// See slide 42 and 43.
  152. ///
  153. /// Restitution is implemented as a velocity bias (see slide 41):
  154. ///
  155. /// b = e v_n^-
  156. ///
  157. /// e = the restitution coefficient, v_n^- is the normal velocity prior to the collision
  158. ///
  159. /// Restitution is only applied when v_n^- is large enough and the points are moving towards collision
  160. bool SolveVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd);
  161. /// Save back the lambdas to the contact cache for the next warm start
  162. void StoreAppliedImpulses(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const;
  163. /// Solve position constraints.
  164. /// This is using the approach described in 'Modeling and Solving Constraints' by Erin Catto presented at GDC 2007.
  165. /// On slide 78 it is suggested to split up the Baumgarte stabilization for positional drift so that it does not
  166. /// actually add to the momentum. We combine an Euler velocity integrate + a position integrate and then discard the velocity
  167. /// change.
  168. ///
  169. /// Constraint force:
  170. ///
  171. /// lambda = -K^-1 b
  172. ///
  173. /// Baumgarte stabilization:
  174. ///
  175. /// b = beta / dt C
  176. ///
  177. /// beta = baumgarte stabilization factor.
  178. /// dt = delta time.
  179. bool SolvePositionConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd);
  180. /// Recycle the constraint buffer. Should be called between collision simulation steps.
  181. void RecycleConstraintBuffer();
  182. /// Terminate the constraint buffer. Should be called after simulation ends.
  183. void FinishConstraintBuffer();
  184. /// Called by continuous collision detection to notify the contact listener that a contact was added
  185. /// @param ioContactAllocator The allocator that reserves memory for the contacts
  186. /// @param inBody1 The first body that is colliding
  187. /// @param inBody2 The second body that is colliding
  188. /// @param inManifold The manifold that describes the collision
  189. /// @param outSettings The calculated contact settings (may be overridden by the contact listener)
  190. void OnCCDContactAdded(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &outSettings);
  191. #ifdef JPH_DEBUG_RENDERER
  192. // Drawing properties
  193. static bool sDrawContactPoint;
  194. static bool sDrawSupportingFaces;
  195. static bool sDrawContactPointReduction;
  196. static bool sDrawContactManifolds;
  197. #endif // JPH_DEBUG_RENDERER
  198. /// Saving state for replay
  199. void SaveState(StateRecorder &inStream) const;
  200. /// Restoring state for replay. Returns false when failed.
  201. bool RestoreState(StateRecorder &inStream);
  202. private:
  203. /// Local space contact point, used for caching impulses
  204. class CachedContactPoint
  205. {
  206. public:
  207. /// Saving / restoring state for replay
  208. void SaveState(StateRecorder &inStream) const;
  209. void RestoreState(StateRecorder &inStream);
  210. /// Local space positions on body 1 and 2.
  211. /// Note: these values are read through sLoadFloat3Unsafe.
  212. Float3 mPosition1;
  213. Float3 mPosition2;
  214. /// Total applied impulse during the last update that it was used
  215. float mNonPenetrationLambda;
  216. Vector<2> mFrictionLambda;
  217. };
  218. static_assert(sizeof(CachedContactPoint) == 36, "Unexpected size");
  219. static_assert(alignof(CachedContactPoint) == 4, "Assuming 4 byte aligned");
  220. /// A single cached manifold
  221. class CachedManifold
  222. {
  223. public:
  224. /// Calculate size in bytes needed beyond the size of the class to store inNumContactPoints
  225. static int sGetRequiredExtraSize(int inNumContactPoints) { return max(0, inNumContactPoints - 1) * sizeof(CachedContactPoint); }
  226. /// Calculate total class size needed for storing inNumContactPoints
  227. static int sGetRequiredTotalSize(int inNumContactPoints) { return sizeof(CachedManifold) + sGetRequiredExtraSize(inNumContactPoints); }
  228. /// Saving / restoring state for replay
  229. void SaveState(StateRecorder &inStream) const;
  230. void RestoreState(StateRecorder &inStream);
  231. /// Handle to next cached contact points in ManifoldCache::mCachedManifolds for the same body pair
  232. uint32 mNextWithSameBodyPair;
  233. /// Contact normal in the space of 2.
  234. /// Note: this value is read through sLoadFloat3Unsafe.
  235. Float3 mContactNormal;
  236. /// Flags for this cached manifold
  237. enum class EFlags : uint16
  238. {
  239. ContactPersisted = 1, ///< If this cache entry was reused in the next simulation update
  240. CCDContact = 2 ///< This is a cached manifold reported by continuous collision detection and was only used to create a contact callback
  241. };
  242. /// @see EFlags
  243. mutable atomic<uint16> mFlags { 0 };
  244. /// Number of contact points in the array below
  245. uint16 mNumContactPoints;
  246. /// Contact points that this manifold consists of
  247. CachedContactPoint mContactPoints[1];
  248. };
  249. static_assert(sizeof(CachedManifold) == 56, "This structure is expect to not contain any waste due to alignment");
  250. static_assert(alignof(CachedManifold) == 4, "Assuming 4 byte aligned");
  251. /// Define a map that maps SubShapeIDPair -> manifold
  252. using ManifoldMap = LockFreeHashMap<SubShapeIDPair, CachedManifold>;
  253. using MKeyValue = ManifoldMap::KeyValue;
  254. using MKVAndCreated = pair<MKeyValue *, bool>;
  255. /// Start of list of contact points for a particular pair of bodies
  256. class CachedBodyPair
  257. {
  258. public:
  259. /// Saving / restoring state for replay
  260. void SaveState(StateRecorder &inStream) const;
  261. void RestoreState(StateRecorder &inStream);
  262. /// Local space position difference from Body A to Body B.
  263. /// Note: this value is read through sLoadFloat3Unsafe
  264. Float3 mDeltaPosition;
  265. /// Local space rotation difference from Body A to Body B, fourth component of quaternion is not stored but is guaranteed >= 0.
  266. /// Note: this value is read through sLoadFloat3Unsafe
  267. Float3 mDeltaRotation;
  268. /// Handle to first manifold in ManifoldCache::mCachedManifolds
  269. uint32 mFirstCachedManifold;
  270. };
  271. static_assert(sizeof(CachedBodyPair) == 28, "Unexpected size");
  272. static_assert(alignof(CachedBodyPair) == 4, "Assuming 4 byte aligned");
  273. /// Define a map that maps BodyPair -> CachedBodyPair
  274. using BodyPairMap = LockFreeHashMap<BodyPair, CachedBodyPair>;
  275. using BPKeyValue = BodyPairMap::KeyValue;
  276. /// Holds all caches that are needed to quickly find cached body pairs / manifolds
  277. class ManifoldCache
  278. {
  279. public:
  280. /// Initialize the cache
  281. void Init(uint inMaxBodyPairs, uint inMaxContactConstraints, uint inCachedManifoldsSize);
  282. /// Reset all entries from the cache
  283. void Clear();
  284. /// Prepare cache before creating new contacts.
  285. /// inExpectedNumBodyPairs / inExpectedNumManifolds are the amount of body pairs / manifolds found in the previous step and is used to determine the amount of buckets the contact cache hash map will use.
  286. void Prepare(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds);
  287. /// Get a new allocator context for storing contacts. Note that you should call this once and then add multiple contacts using the context.
  288. ContactAllocator GetContactAllocator() { return ContactAllocator(mAllocator, cAllocatorBlockSize); }
  289. /// Find / create cached entry for SubShapeIDPair -> CachedManifold
  290. const MKeyValue * Find(const SubShapeIDPair &inKey, size_t inKeyHash) const;
  291. MKeyValue * Create(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, size_t inKeyHash, int inNumContactPoints);
  292. MKVAndCreated FindOrCreate(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, size_t inKeyHash, int inNumContactPoints);
  293. uint32 ToHandle(const MKeyValue *inKeyValue) const;
  294. const MKeyValue * FromHandle(uint32 inHandle) const;
  295. /// Find / create entry for BodyPair -> CachedBodyPair
  296. const BPKeyValue * Find(const BodyPair &inKey, size_t inKeyHash) const;
  297. BPKeyValue * Create(ContactAllocator &ioContactAllocator, const BodyPair &inKey, size_t inKeyHash);
  298. void GetAllBodyPairsSorted(vector<const BPKeyValue *> &outAll) const;
  299. void GetAllManifoldsSorted(const CachedBodyPair &inBodyPair, vector<const MKeyValue *> &outAll) const;
  300. void GetAllCCDManifoldsSorted(vector<const MKeyValue *> &outAll) const;
  301. void ContactPointRemovedCallbacks(ContactListener *inListener);
  302. #ifdef JPH_ENABLE_ASSERTS
  303. /// Get the amount of manifolds in the cache
  304. uint GetNumManifolds() const { return mCachedManifolds.GetNumKeyValues(); }
  305. /// Get the amount of body pairs in the cache
  306. uint GetNumBodyPairs() const { return mCachedBodyPairs.GetNumKeyValues(); }
  307. /// Before a cache is finalized you can only do Create(), after only Find() or Clear()
  308. void Finalize();
  309. #endif
  310. /// Saving / restoring state for replay
  311. void SaveState(StateRecorder &inStream) const;
  312. bool RestoreState(const ManifoldCache &inReadCache, StateRecorder &inStream);
  313. private:
  314. /// Block size used when allocating new blocks in the contact cache
  315. static constexpr uint32 cAllocatorBlockSize = 4096;
  316. /// Allocator used by both mCachedManifolds and mCachedBodyPairs, this makes it more likely that a body pair and its manifolds are close in memory
  317. LFHMAllocator mAllocator;
  318. /// Simple hash map for SubShapeIDPair -> CachedManifold
  319. ManifoldMap mCachedManifolds { mAllocator };
  320. /// Simple hash map for BodyPair -> CachedBodyPair
  321. BodyPairMap mCachedBodyPairs { mAllocator };
  322. #ifdef JPH_ENABLE_ASSERTS
  323. bool mIsFinalized = false; ///< Marks if this buffer is complete
  324. #endif
  325. };
  326. ManifoldCache mCache[2]; ///< We have one cache to read from and one to write to
  327. int mCacheWriteIdx = 0; ///< Which cache we're currently writing to
  328. /// World space contact point, used for solving penetrations
  329. class WorldContactPoint
  330. {
  331. public:
  332. /// Calculate constraint properties below
  333. void CalculateNonPenetrationConstraintProperties(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpacePosition1, Vec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal);
  334. template <EMotionType Type1, EMotionType Type2>
  335. JPH_INLINE void CalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, const Body &inBody1, const Body &inBody2, Mat44Arg inInvI1, Mat44Arg inInvI2, Vec3Arg inWorldSpacePosition1, Vec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, float inCombinedRestitution, float inCombinedFriction, float inMinVelocityForRestitution);
  336. /// The constraint parts
  337. AxisConstraintPart mNonPenetrationConstraint;
  338. AxisConstraintPart mFrictionConstraint1;
  339. AxisConstraintPart mFrictionConstraint2;
  340. /// Contact cache
  341. CachedContactPoint * mContactPoint;
  342. };
  343. using WorldContactPoints = StaticArray<WorldContactPoint, MaxContactPoints>;
  344. /// Contact constraint class, used for solving penetrations
  345. class ContactConstraint
  346. {
  347. public:
  348. #ifdef JPH_DEBUG_RENDERER
  349. /// Draw the state of the contact constraint
  350. void Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const;
  351. #endif // JPH_DEBUG_RENDERER
  352. /// Get the tangents for this contact constraint
  353. JPH_INLINE void GetTangents(Vec3 &outTangent1, Vec3 &outTangent2) const
  354. {
  355. outTangent1 = mWorldSpaceNormal.GetNormalizedPerpendicular();
  356. outTangent2 = mWorldSpaceNormal.Cross(outTangent1);
  357. }
  358. Vec3 mWorldSpaceNormal;
  359. Body * mBody1;
  360. Body * mBody2;
  361. size_t mSortKey;
  362. float mCombinedFriction;
  363. float mCombinedRestitution;
  364. WorldContactPoints mContactPoints;
  365. };
  366. /// Internal helper function to calculate the friction and non-penetration constraint properties. Templated to the motion type to reduce the amount of branches and calculations.
  367. template <EMotionType Type1, EMotionType Type2>
  368. JPH_INLINE void TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, float inDeltaTime, Mat44Arg inTransformBody1, Mat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2, Mat44Arg inInvI1, Mat44Arg inInvI2);
  369. /// Internal helper function to calculate the friction and non-penetration constraint properties.
  370. inline void CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, float inDeltaTime, Mat44Arg inTransformBody1, Mat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2);
  371. /// Internal helper function to add a contact constraint. Templated to the motion type to reduce the amount of branches and calculations.
  372. template <EMotionType Type1, EMotionType Type2>
  373. bool TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold, Mat44Arg inInvI1, Mat44Arg inInvI2);
  374. /// Internal helper function to warm start contact constraint. Templated to the motion type to reduce the amount of branches and calculations.
  375. template <EMotionType Type1, EMotionType Type2>
  376. JPH_INLINE static void sWarmStartConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio);
  377. /// Internal helper function to solve a single contact constraint. Templated to the motion type to reduce the amount of branches and calculations.
  378. template <EMotionType Type1, EMotionType Type2>
  379. JPH_INLINE static bool sSolveVelocityConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2);
  380. /// The main physics settings instance
  381. const PhysicsSettings & mPhysicsSettings;
  382. /// Listener that is notified whenever a contact point between two bodies is added/updated/removed
  383. ContactListener * mContactListener = nullptr;
  384. /// Functions that are used to combine friction and restitution of 2 bodies
  385. CombineFunction mCombineFriction = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return sqrt(inBody1.GetFriction() * inBody2.GetFriction()); };
  386. CombineFunction mCombineRestitution = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return max(inBody1.GetRestitution(), inBody2.GetRestitution()); };
  387. /// The constraints that were added this frame
  388. ContactConstraint * mConstraints = nullptr;
  389. uint32 mMaxConstraints = 0;
  390. atomic<uint32> mNumConstraints { 0 };
  391. /// Context used for this physics update
  392. PhysicsUpdateContext * mUpdateContext;
  393. };
  394. JPH_NAMESPACE_END