ContactConstraintManager.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Constraints/ContactConstraintManager.h>
  6. #include <Jolt/Physics/Body/Body.h>
  7. #include <Jolt/Physics/PhysicsUpdateContext.h>
  8. #include <Jolt/Physics/PhysicsSettings.h>
  9. #include <Jolt/Physics/IslandBuilder.h>
  10. #include <Jolt/Physics/DeterminismLog.h>
  11. #include <Jolt/Core/TempAllocator.h>
  12. #include <Jolt/Core/QuickSort.h>
  13. #ifdef JPH_DEBUG_RENDERER
  14. #include <Jolt/Renderer/DebugRenderer.h>
  15. #endif // JPH_DEBUG_RENDERER
  16. JPH_NAMESPACE_BEGIN
  17. using namespace literals;
  18. #ifdef JPH_DEBUG_RENDERER
  19. bool ContactConstraintManager::sDrawContactPoint = false;
  20. bool ContactConstraintManager::sDrawSupportingFaces = false;
  21. bool ContactConstraintManager::sDrawContactPointReduction = false;
  22. bool ContactConstraintManager::sDrawContactManifolds = false;
  23. #endif // JPH_DEBUG_RENDERER
  24. //#define JPH_MANIFOLD_CACHE_DEBUG
  25. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  26. // ContactConstraintManager::WorldContactPoint
  27. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  28. void ContactConstraintManager::WorldContactPoint::CalculateNonPenetrationConstraintProperties(const Body &inBody1, const Body &inBody2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal)
  29. {
  30. // Calculate collision points relative to body
  31. RVec3 p = 0.5_r * (inWorldSpacePosition1 + inWorldSpacePosition2);
  32. Vec3 r1 = Vec3(p - inBody1.GetCenterOfMassPosition());
  33. Vec3 r2 = Vec3(p - inBody2.GetCenterOfMassPosition());
  34. mNonPenetrationConstraint.CalculateConstraintProperties(inBody1, r1, inBody2, r2, inWorldSpaceNormal);
  35. }
  36. template <EMotionType Type1, EMotionType Type2>
  37. JPH_INLINE void ContactConstraintManager::WorldContactPoint::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)
  38. {
  39. JPH_DET_LOG("TemplatedCalculateFrictionAndNonPenetrationConstraintProperties: p1: " << inWorldSpacePosition1 << " p2: " << inWorldSpacePosition2
  40. << " normal: " << inWorldSpaceNormal << " tangent1: " << inWorldSpaceTangent1 << " tangent2: " << inWorldSpaceTangent2
  41. << " restitution: " << inSettings.mCombinedRestitution << " friction: " << inSettings.mCombinedFriction << " minv: " << inMinVelocityForRestitution
  42. << " surface_vel: " << inSettings.mRelativeLinearSurfaceVelocity << " surface_ang: " << inSettings.mRelativeAngularSurfaceVelocity);
  43. // Calculate collision points relative to body
  44. RVec3 p = 0.5_r * (inWorldSpacePosition1 + inWorldSpacePosition2);
  45. Vec3 r1 = Vec3(p - inBody1.GetCenterOfMassPosition());
  46. Vec3 r2 = Vec3(p - inBody2.GetCenterOfMassPosition());
  47. // Calculate velocity of collision points
  48. Vec3 relative_velocity;
  49. if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)
  50. relative_velocity = inBody2.GetMotionPropertiesUnchecked()->GetPointVelocityCOM(r2) - inBody1.GetMotionPropertiesUnchecked()->GetPointVelocityCOM(r1);
  51. else if constexpr (Type1 != EMotionType::Static)
  52. relative_velocity = -inBody1.GetMotionPropertiesUnchecked()->GetPointVelocityCOM(r1);
  53. else if constexpr (Type2 != EMotionType::Static)
  54. relative_velocity = inBody2.GetMotionPropertiesUnchecked()->GetPointVelocityCOM(r2);
  55. else
  56. {
  57. JPH_ASSERT(false); // Static vs static makes no sense
  58. relative_velocity = Vec3::sZero();
  59. }
  60. float normal_velocity = relative_velocity.Dot(inWorldSpaceNormal);
  61. // How much the shapes are penetrating (> 0 if penetrating, < 0 if separated)
  62. float penetration = Vec3(inWorldSpacePosition1 - inWorldSpacePosition2).Dot(inWorldSpaceNormal);
  63. // If there is no penetration, this is a speculative contact and we will apply a bias to the contact constraint
  64. // so that the constraint becomes relative_velocity . contact normal > -penetration / delta_time
  65. // instead of relative_velocity . contact normal > 0
  66. // See: GDC 2013: "Physics for Game Programmers; Continuous Collision" - Erin Catto
  67. float speculative_contact_velocity_bias = max(0.0f, -penetration / inDeltaTime);
  68. // Determine if the velocity is big enough for restitution
  69. float normal_velocity_bias;
  70. if (inSettings.mCombinedRestitution > 0.0f && normal_velocity < -inMinVelocityForRestitution)
  71. {
  72. // We have a velocity that is big enough for restitution. This is where speculative contacts don't work
  73. // great as we have to decide now if we're going to apply the restitution or not. If the relative
  74. // velocity is big enough for a hit, we apply the restitution (in the end, due to other constraints,
  75. // the objects may actually not collide and we will have applied restitution incorrectly). Another
  76. // artifact that occurs because of this approximation is that the object will bounce from its current
  77. // position rather than from a position where it is touching the other object. This causes the object
  78. // to appear to move faster for 1 frame (the opposite of time stealing).
  79. if (normal_velocity < -speculative_contact_velocity_bias)
  80. normal_velocity_bias = inSettings.mCombinedRestitution * normal_velocity;
  81. else
  82. // In this case we have predicted that we don't hit the other object, but if we do (due to other constraints changing velocities)
  83. // the speculative contact will prevent penetration but will not apply restitution leading to another artifact.
  84. normal_velocity_bias = speculative_contact_velocity_bias;
  85. }
  86. else
  87. {
  88. // No restitution. We can safely apply our contact velocity bias.
  89. normal_velocity_bias = speculative_contact_velocity_bias;
  90. }
  91. mNonPenetrationConstraint.TemplatedCalculateConstraintProperties<Type1, Type2>(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceNormal, normal_velocity_bias);
  92. // Calculate friction part
  93. if (inSettings.mCombinedFriction > 0.0f)
  94. {
  95. // Get surface velocity relative to tangents
  96. Vec3 ws_surface_velocity = inSettings.mRelativeLinearSurfaceVelocity + inSettings.mRelativeAngularSurfaceVelocity.Cross(r1);
  97. float surface_velocity1 = inWorldSpaceTangent1.Dot(ws_surface_velocity);
  98. float surface_velocity2 = inWorldSpaceTangent2.Dot(ws_surface_velocity);
  99. // Implement friction as 2 AxisContraintParts
  100. mFrictionConstraint1.TemplatedCalculateConstraintProperties<Type1, Type2>(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceTangent1, surface_velocity1);
  101. mFrictionConstraint2.TemplatedCalculateConstraintProperties<Type1, Type2>(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceTangent2, surface_velocity2);
  102. }
  103. else
  104. {
  105. // Turn off friction constraint
  106. mFrictionConstraint1.Deactivate();
  107. mFrictionConstraint2.Deactivate();
  108. }
  109. }
  110. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  111. // ContactConstraintManager::ContactConstraint
  112. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  113. #ifdef JPH_DEBUG_RENDERER
  114. void ContactConstraintManager::ContactConstraint::Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const
  115. {
  116. if (mContactPoints.empty())
  117. return;
  118. // Get body transforms
  119. RMat44 transform_body1 = mBody1->GetCenterOfMassTransform();
  120. RMat44 transform_body2 = mBody2->GetCenterOfMassTransform();
  121. RVec3 prev_point = transform_body1 * Vec3::sLoadFloat3Unsafe(mContactPoints.back().mContactPoint->mPosition1);
  122. for (const WorldContactPoint &wcp : mContactPoints)
  123. {
  124. // Test if any lambda from the previous frame was transferred
  125. float radius = wcp.mNonPenetrationConstraint.GetTotalLambda() == 0.0f
  126. && wcp.mFrictionConstraint1.GetTotalLambda() == 0.0f
  127. && wcp.mFrictionConstraint2.GetTotalLambda() == 0.0f? 0.1f : 0.2f;
  128. RVec3 next_point = transform_body1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  129. inRenderer->DrawMarker(next_point, Color::sCyan, radius);
  130. inRenderer->DrawMarker(transform_body2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2), Color::sPurple, radius);
  131. // Draw edge
  132. inRenderer->DrawArrow(prev_point, next_point, inManifoldColor, 0.05f);
  133. prev_point = next_point;
  134. }
  135. // Draw normal
  136. RVec3 wp = transform_body1 * Vec3::sLoadFloat3Unsafe(mContactPoints[0].mContactPoint->mPosition1);
  137. inRenderer->DrawArrow(wp, wp + GetWorldSpaceNormal(), Color::sRed, 0.05f);
  138. // Get tangents
  139. Vec3 t1, t2;
  140. GetTangents(t1, t2);
  141. // Draw tangents
  142. inRenderer->DrawLine(wp, wp + t1, Color::sGreen);
  143. inRenderer->DrawLine(wp, wp + t2, Color::sBlue);
  144. }
  145. #endif // JPH_DEBUG_RENDERER
  146. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  147. // ContactConstraintManager::CachedContactPoint
  148. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  149. void ContactConstraintManager::CachedContactPoint::SaveState(StateRecorder &inStream) const
  150. {
  151. inStream.Write(mPosition1);
  152. inStream.Write(mPosition2);
  153. inStream.Write(mNonPenetrationLambda);
  154. inStream.Write(mFrictionLambda);
  155. }
  156. void ContactConstraintManager::CachedContactPoint::RestoreState(StateRecorder &inStream)
  157. {
  158. inStream.Read(mPosition1);
  159. inStream.Read(mPosition2);
  160. inStream.Read(mNonPenetrationLambda);
  161. inStream.Read(mFrictionLambda);
  162. }
  163. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  164. // ContactConstraintManager::CachedManifold
  165. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  166. void ContactConstraintManager::CachedManifold::SaveState(StateRecorder &inStream) const
  167. {
  168. inStream.Write(mContactNormal);
  169. }
  170. void ContactConstraintManager::CachedManifold::RestoreState(StateRecorder &inStream)
  171. {
  172. inStream.Read(mContactNormal);
  173. }
  174. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  175. // ContactConstraintManager::CachedBodyPair
  176. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  177. void ContactConstraintManager::CachedBodyPair::SaveState(StateRecorder &inStream) const
  178. {
  179. inStream.Write(mDeltaPosition);
  180. inStream.Write(mDeltaRotation);
  181. }
  182. void ContactConstraintManager::CachedBodyPair::RestoreState(StateRecorder &inStream)
  183. {
  184. inStream.Read(mDeltaPosition);
  185. inStream.Read(mDeltaRotation);
  186. }
  187. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  188. // ContactConstraintManager::ManifoldCache
  189. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  190. void ContactConstraintManager::ManifoldCache::Init(uint inMaxBodyPairs, uint inMaxContactConstraints, uint inCachedManifoldsSize)
  191. {
  192. mAllocator.Init(inMaxBodyPairs * sizeof(BodyPairMap::KeyValue) + inCachedManifoldsSize);
  193. mCachedManifolds.Init(GetNextPowerOf2(inMaxContactConstraints));
  194. mCachedBodyPairs.Init(GetNextPowerOf2(inMaxBodyPairs));
  195. }
  196. void ContactConstraintManager::ManifoldCache::Clear()
  197. {
  198. JPH_PROFILE_FUNCTION();
  199. mCachedManifolds.Clear();
  200. mCachedBodyPairs.Clear();
  201. mAllocator.Clear();
  202. #ifdef JPH_ENABLE_ASSERTS
  203. // Mark as incomplete
  204. mIsFinalized = false;
  205. #endif
  206. }
  207. void ContactConstraintManager::ManifoldCache::Prepare(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds)
  208. {
  209. // Minimum amount of buckets to use in the hash map
  210. constexpr uint32 cMinBuckets = 1024;
  211. // Use the next higher power of 2 of amount of objects in the cache from last frame to determine the amount of buckets in this frame
  212. mCachedManifolds.SetNumBuckets(min(max(cMinBuckets, GetNextPowerOf2(inExpectedNumManifolds)), mCachedManifolds.GetMaxBuckets()));
  213. mCachedBodyPairs.SetNumBuckets(min(max(cMinBuckets, GetNextPowerOf2(inExpectedNumBodyPairs)), mCachedBodyPairs.GetMaxBuckets()));
  214. }
  215. const ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::Find(const SubShapeIDPair &inKey, uint64 inKeyHash) const
  216. {
  217. JPH_ASSERT(mIsFinalized);
  218. return mCachedManifolds.Find(inKey, inKeyHash);
  219. }
  220. ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::Create(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints)
  221. {
  222. JPH_ASSERT(!mIsFinalized);
  223. MKeyValue *kv = mCachedManifolds.Create(ioContactAllocator, inKey, inKeyHash, CachedManifold::sGetRequiredExtraSize(inNumContactPoints));
  224. if (kv == nullptr)
  225. {
  226. ioContactAllocator.mErrors |= EPhysicsUpdateError::ManifoldCacheFull;
  227. return nullptr;
  228. }
  229. kv->GetValue().mNumContactPoints = uint16(inNumContactPoints);
  230. ++ioContactAllocator.mNumManifolds;
  231. return kv;
  232. }
  233. ContactConstraintManager::MKVAndCreated ContactConstraintManager::ManifoldCache::FindOrCreate(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints)
  234. {
  235. MKeyValue *kv = const_cast<MKeyValue *>(mCachedManifolds.Find(inKey, inKeyHash));
  236. if (kv != nullptr)
  237. return { kv, false };
  238. return { Create(ioContactAllocator, inKey, inKeyHash, inNumContactPoints), true };
  239. }
  240. uint32 ContactConstraintManager::ManifoldCache::ToHandle(const MKeyValue *inKeyValue) const
  241. {
  242. JPH_ASSERT(!mIsFinalized);
  243. return mCachedManifolds.ToHandle(inKeyValue);
  244. }
  245. const ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::FromHandle(uint32 inHandle) const
  246. {
  247. JPH_ASSERT(mIsFinalized);
  248. return mCachedManifolds.FromHandle(inHandle);
  249. }
  250. const ContactConstraintManager::BPKeyValue *ContactConstraintManager::ManifoldCache::Find(const BodyPair &inKey, uint64 inKeyHash) const
  251. {
  252. JPH_ASSERT(mIsFinalized);
  253. return mCachedBodyPairs.Find(inKey, inKeyHash);
  254. }
  255. ContactConstraintManager::BPKeyValue *ContactConstraintManager::ManifoldCache::Create(ContactAllocator &ioContactAllocator, const BodyPair &inKey, uint64 inKeyHash)
  256. {
  257. JPH_ASSERT(!mIsFinalized);
  258. BPKeyValue *kv = mCachedBodyPairs.Create(ioContactAllocator, inKey, inKeyHash, 0);
  259. if (kv == nullptr)
  260. {
  261. ioContactAllocator.mErrors |= EPhysicsUpdateError::BodyPairCacheFull;
  262. return nullptr;
  263. }
  264. ++ioContactAllocator.mNumBodyPairs;
  265. return kv;
  266. }
  267. void ContactConstraintManager::ManifoldCache::GetAllBodyPairsSorted(Array<const BPKeyValue *> &outAll) const
  268. {
  269. JPH_ASSERT(mIsFinalized);
  270. mCachedBodyPairs.GetAllKeyValues(outAll);
  271. // Sort by key
  272. QuickSort(outAll.begin(), outAll.end(), [](const BPKeyValue *inLHS, const BPKeyValue *inRHS) {
  273. return inLHS->GetKey() < inRHS->GetKey();
  274. });
  275. }
  276. void ContactConstraintManager::ManifoldCache::GetAllManifoldsSorted(const CachedBodyPair &inBodyPair, Array<const MKeyValue *> &outAll) const
  277. {
  278. JPH_ASSERT(mIsFinalized);
  279. // Iterate through the attached manifolds
  280. for (uint32 handle = inBodyPair.mFirstCachedManifold; handle != ManifoldMap::cInvalidHandle; handle = FromHandle(handle)->GetValue().mNextWithSameBodyPair)
  281. {
  282. const MKeyValue *kv = mCachedManifolds.FromHandle(handle);
  283. outAll.push_back(kv);
  284. }
  285. // Sort by key
  286. QuickSort(outAll.begin(), outAll.end(), [](const MKeyValue *inLHS, const MKeyValue *inRHS) {
  287. return inLHS->GetKey() < inRHS->GetKey();
  288. });
  289. }
  290. void ContactConstraintManager::ManifoldCache::GetAllCCDManifoldsSorted(Array<const MKeyValue *> &outAll) const
  291. {
  292. mCachedManifolds.GetAllKeyValues(outAll);
  293. for (int i = (int)outAll.size() - 1; i >= 0; --i)
  294. if ((outAll[i]->GetValue().mFlags & (uint16)CachedManifold::EFlags::CCDContact) == 0)
  295. {
  296. outAll[i] = outAll.back();
  297. outAll.pop_back();
  298. }
  299. // Sort by key
  300. QuickSort(outAll.begin(), outAll.end(), [](const MKeyValue *inLHS, const MKeyValue *inRHS) {
  301. return inLHS->GetKey() < inRHS->GetKey();
  302. });
  303. }
  304. void ContactConstraintManager::ManifoldCache::ContactPointRemovedCallbacks(ContactListener *inListener)
  305. {
  306. JPH_PROFILE_FUNCTION();
  307. for (MKeyValue &kv : mCachedManifolds)
  308. if ((kv.GetValue().mFlags & uint16(CachedManifold::EFlags::ContactPersisted)) == 0)
  309. inListener->OnContactRemoved(kv.GetKey());
  310. }
  311. #ifdef JPH_ENABLE_ASSERTS
  312. void ContactConstraintManager::ManifoldCache::Finalize()
  313. {
  314. mIsFinalized = true;
  315. #ifdef JPH_MANIFOLD_CACHE_DEBUG
  316. Trace("ManifoldMap:");
  317. mCachedManifolds.TraceStats();
  318. Trace("BodyPairMap:");
  319. mCachedBodyPairs.TraceStats();
  320. #endif // JPH_MANIFOLD_CACHE_DEBUG
  321. }
  322. #endif
  323. void ContactConstraintManager::ManifoldCache::SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const
  324. {
  325. JPH_ASSERT(mIsFinalized);
  326. // Get contents of cache
  327. Array<const BPKeyValue *> all_bp;
  328. GetAllBodyPairsSorted(all_bp);
  329. // Determine which ones to save
  330. Array<const BPKeyValue *> selected_bp;
  331. if (inFilter == nullptr)
  332. selected_bp = std::move(all_bp);
  333. else
  334. {
  335. selected_bp.reserve(all_bp.size());
  336. for (const BPKeyValue *bp_kv : all_bp)
  337. if (inFilter->ShouldSaveContact(bp_kv->GetKey().mBodyA, bp_kv->GetKey().mBodyB))
  338. selected_bp.push_back(bp_kv);
  339. }
  340. // Write body pairs
  341. size_t num_body_pairs = selected_bp.size();
  342. inStream.Write(num_body_pairs);
  343. for (const BPKeyValue *bp_kv : selected_bp)
  344. {
  345. // Write body pair key
  346. inStream.Write(bp_kv->GetKey());
  347. // Write body pair
  348. const CachedBodyPair &bp = bp_kv->GetValue();
  349. bp.SaveState(inStream);
  350. // Get attached manifolds
  351. Array<const MKeyValue *> all_m;
  352. GetAllManifoldsSorted(bp, all_m);
  353. // Write num manifolds
  354. size_t num_manifolds = all_m.size();
  355. inStream.Write(num_manifolds);
  356. // Write all manifolds
  357. for (const MKeyValue *m_kv : all_m)
  358. {
  359. // Write key
  360. inStream.Write(m_kv->GetKey());
  361. const CachedManifold &cm = m_kv->GetValue();
  362. JPH_ASSERT((cm.mFlags & (uint16)CachedManifold::EFlags::CCDContact) == 0);
  363. // Write amount of contacts
  364. inStream.Write(cm.mNumContactPoints);
  365. // Write manifold
  366. cm.SaveState(inStream);
  367. // Write contact points
  368. for (uint32 i = 0; i < cm.mNumContactPoints; ++i)
  369. cm.mContactPoints[i].SaveState(inStream);
  370. }
  371. }
  372. // Get CCD manifolds
  373. Array<const MKeyValue *> all_m;
  374. GetAllCCDManifoldsSorted(all_m);
  375. // Determine which ones to save
  376. Array<const MKeyValue *> selected_m;
  377. if (inFilter == nullptr)
  378. selected_m = std::move(all_m);
  379. else
  380. {
  381. selected_m.reserve(all_m.size());
  382. for (const MKeyValue *m_kv : all_m)
  383. if (inFilter->ShouldSaveContact(m_kv->GetKey().GetBody1ID(), m_kv->GetKey().GetBody2ID()))
  384. selected_m.push_back(m_kv);
  385. }
  386. // Write all CCD manifold keys
  387. size_t num_manifolds = selected_m.size();
  388. inStream.Write(num_manifolds);
  389. for (const MKeyValue *m_kv : selected_m)
  390. inStream.Write(m_kv->GetKey());
  391. }
  392. bool ContactConstraintManager::ManifoldCache::RestoreState(const ManifoldCache &inReadCache, StateRecorder &inStream)
  393. {
  394. JPH_ASSERT(!mIsFinalized);
  395. bool success = true;
  396. // Create a contact allocator for restoring the contact cache
  397. ContactAllocator contact_allocator(GetContactAllocator());
  398. // When validating, get all existing body pairs
  399. Array<const BPKeyValue *> all_bp;
  400. if (inStream.IsValidating())
  401. inReadCache.GetAllBodyPairsSorted(all_bp);
  402. // Read amount of body pairs
  403. size_t num_body_pairs;
  404. if (inStream.IsValidating())
  405. num_body_pairs = all_bp.size();
  406. inStream.Read(num_body_pairs);
  407. // Read entire cache
  408. for (size_t i = 0; i < num_body_pairs; ++i)
  409. {
  410. // Read key
  411. BodyPair body_pair_key;
  412. if (inStream.IsValidating() && i < all_bp.size())
  413. body_pair_key = all_bp[i]->GetKey();
  414. inStream.Read(body_pair_key);
  415. // Create new entry for this body pair
  416. uint64 body_pair_hash = body_pair_key.GetHash();
  417. BPKeyValue *bp_kv = Create(contact_allocator, body_pair_key, body_pair_hash);
  418. if (bp_kv == nullptr)
  419. {
  420. // Out of cache space
  421. success = false;
  422. break;
  423. }
  424. CachedBodyPair &bp = bp_kv->GetValue();
  425. // Read body pair
  426. if (inStream.IsValidating() && i < all_bp.size())
  427. memcpy(&bp, &all_bp[i]->GetValue(), sizeof(CachedBodyPair));
  428. bp.RestoreState(inStream);
  429. // When validating, get all existing manifolds
  430. Array<const MKeyValue *> all_m;
  431. if (inStream.IsValidating())
  432. inReadCache.GetAllManifoldsSorted(all_bp[i]->GetValue(), all_m);
  433. // Read amount of manifolds
  434. size_t num_manifolds;
  435. if (inStream.IsValidating())
  436. num_manifolds = all_m.size();
  437. inStream.Read(num_manifolds);
  438. uint32 handle = ManifoldMap::cInvalidHandle;
  439. for (size_t j = 0; j < num_manifolds; ++j)
  440. {
  441. // Read key
  442. SubShapeIDPair sub_shape_key;
  443. if (inStream.IsValidating() && j < all_m.size())
  444. sub_shape_key = all_m[j]->GetKey();
  445. inStream.Read(sub_shape_key);
  446. uint64 sub_shape_key_hash = sub_shape_key.GetHash();
  447. // Read amount of contact points
  448. uint16 num_contact_points;
  449. if (inStream.IsValidating() && j < all_m.size())
  450. num_contact_points = all_m[j]->GetValue().mNumContactPoints;
  451. inStream.Read(num_contact_points);
  452. // Read manifold
  453. MKeyValue *m_kv = Create(contact_allocator, sub_shape_key, sub_shape_key_hash, num_contact_points);
  454. if (m_kv == nullptr)
  455. {
  456. // Out of cache space
  457. success = false;
  458. break;
  459. }
  460. CachedManifold &cm = m_kv->GetValue();
  461. if (inStream.IsValidating() && j < all_m.size())
  462. {
  463. memcpy(&cm, &all_m[j]->GetValue(), CachedManifold::sGetRequiredTotalSize(num_contact_points));
  464. cm.mNumContactPoints = uint16(num_contact_points); // Restore num contact points
  465. }
  466. cm.RestoreState(inStream);
  467. cm.mNextWithSameBodyPair = handle;
  468. handle = ToHandle(m_kv);
  469. // Read contact points
  470. for (uint32 k = 0; k < num_contact_points; ++k)
  471. cm.mContactPoints[k].RestoreState(inStream);
  472. }
  473. bp.mFirstCachedManifold = handle;
  474. }
  475. // When validating, get all existing CCD manifolds
  476. Array<const MKeyValue *> all_m;
  477. if (inStream.IsValidating())
  478. inReadCache.GetAllCCDManifoldsSorted(all_m);
  479. // Read amount of CCD manifolds
  480. size_t num_manifolds;
  481. if (inStream.IsValidating())
  482. num_manifolds = all_m.size();
  483. inStream.Read(num_manifolds);
  484. for (size_t j = 0; j < num_manifolds; ++j)
  485. {
  486. // Read key
  487. SubShapeIDPair sub_shape_key;
  488. if (inStream.IsValidating() && j < all_m.size())
  489. sub_shape_key = all_m[j]->GetKey();
  490. inStream.Read(sub_shape_key);
  491. uint64 sub_shape_key_hash = sub_shape_key.GetHash();
  492. // Create CCD manifold
  493. MKeyValue *m_kv = Create(contact_allocator, sub_shape_key, sub_shape_key_hash, 0);
  494. if (m_kv == nullptr)
  495. {
  496. // Out of cache space
  497. success = false;
  498. break;
  499. }
  500. CachedManifold &cm = m_kv->GetValue();
  501. cm.mFlags |= (uint16)CachedManifold::EFlags::CCDContact;
  502. }
  503. #ifdef JPH_ENABLE_ASSERTS
  504. mIsFinalized = true;
  505. #endif
  506. return success;
  507. }
  508. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  509. // ContactConstraintManager
  510. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  511. ContactConstraintManager::ContactConstraintManager(const PhysicsSettings &inPhysicsSettings) :
  512. mPhysicsSettings(inPhysicsSettings)
  513. {
  514. #ifdef JPH_ENABLE_ASSERTS
  515. // For the first frame mark this empty buffer as finalized
  516. mCache[mCacheWriteIdx ^ 1].Finalize();
  517. #endif
  518. }
  519. ContactConstraintManager::~ContactConstraintManager()
  520. {
  521. JPH_ASSERT(mConstraints == nullptr);
  522. }
  523. void ContactConstraintManager::Init(uint inMaxBodyPairs, uint inMaxContactConstraints)
  524. {
  525. mMaxConstraints = inMaxContactConstraints;
  526. // Calculate worst case cache usage
  527. uint cached_manifolds_size = inMaxContactConstraints * (sizeof(CachedManifold) + (MaxContactPoints - 1) * sizeof(CachedContactPoint));
  528. // Init the caches
  529. mCache[0].Init(inMaxBodyPairs, inMaxContactConstraints, cached_manifolds_size);
  530. mCache[1].Init(inMaxBodyPairs, inMaxContactConstraints, cached_manifolds_size);
  531. }
  532. void ContactConstraintManager::PrepareConstraintBuffer(PhysicsUpdateContext *inContext)
  533. {
  534. // Store context
  535. mUpdateContext = inContext;
  536. // Allocate temporary constraint buffer
  537. JPH_ASSERT(mConstraints == nullptr);
  538. mConstraints = (ContactConstraint *)inContext->mTempAllocator->Allocate(mMaxConstraints * sizeof(ContactConstraint));
  539. }
  540. template <EMotionType Type1, EMotionType Type2>
  541. JPH_INLINE void ContactConstraintManager::TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)
  542. {
  543. // Calculate scaled mass and inertia
  544. float inv_m1;
  545. Mat44 inv_i1;
  546. if constexpr (Type1 == EMotionType::Dynamic)
  547. {
  548. const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();
  549. inv_m1 = inSettings.mInvMassScale1 * mp1->GetInverseMass();
  550. inv_i1 = inSettings.mInvInertiaScale1 * mp1->GetInverseInertiaForRotation(inTransformBody1.GetRotation());
  551. }
  552. else
  553. {
  554. inv_m1 = 0.0f;
  555. inv_i1 = Mat44::sZero();
  556. }
  557. float inv_m2;
  558. Mat44 inv_i2;
  559. if constexpr (Type2 == EMotionType::Dynamic)
  560. {
  561. const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();
  562. inv_m2 = inSettings.mInvMassScale2 * mp2->GetInverseMass();
  563. inv_i2 = inSettings.mInvInertiaScale2 * mp2->GetInverseInertiaForRotation(inTransformBody2.GetRotation());
  564. }
  565. else
  566. {
  567. inv_m2 = 0.0f;
  568. inv_i2 = Mat44::sZero();
  569. }
  570. // Calculate tangents
  571. Vec3 t1, t2;
  572. ioConstraint.GetTangents(t1, t2);
  573. Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();
  574. // Setup velocity constraint properties
  575. float min_velocity_for_restitution = mPhysicsSettings.mMinVelocityForRestitution;
  576. for (WorldContactPoint &wcp : ioConstraint.mContactPoints)
  577. {
  578. RVec3 p1 = inTransformBody1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  579. RVec3 p2 = inTransformBody2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);
  580. wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(inDeltaTime, inBody1, inBody2, inv_m1, inv_m2, inv_i1, inv_i2, p1, p2, ws_normal, t1, t2, inSettings, min_velocity_for_restitution);
  581. }
  582. }
  583. inline void ContactConstraintManager::CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)
  584. {
  585. // Dispatch to the correct templated form
  586. switch (inBody1.GetMotionType())
  587. {
  588. case EMotionType::Dynamic:
  589. switch (inBody2.GetMotionType())
  590. {
  591. case EMotionType::Dynamic:
  592. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  593. break;
  594. case EMotionType::Kinematic:
  595. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Kinematic>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  596. break;
  597. case EMotionType::Static:
  598. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Static>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  599. break;
  600. default:
  601. JPH_ASSERT(false);
  602. break;
  603. }
  604. break;
  605. case EMotionType::Kinematic:
  606. JPH_ASSERT(inBody2.IsDynamic());
  607. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Kinematic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  608. break;
  609. case EMotionType::Static:
  610. JPH_ASSERT(inBody2.IsDynamic());
  611. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Static, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  612. break;
  613. default:
  614. JPH_ASSERT(false);
  615. break;
  616. }
  617. }
  618. void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled, bool &outConstraintCreated)
  619. {
  620. JPH_PROFILE_FUNCTION();
  621. // Start with nothing found and not handled
  622. outConstraintCreated = false;
  623. outPairHandled = false;
  624. // Swap bodies so that body 1 id < body 2 id
  625. Body *body1, *body2;
  626. if (inBody1.GetID() < inBody2.GetID())
  627. {
  628. body1 = &inBody1;
  629. body2 = &inBody2;
  630. }
  631. else
  632. {
  633. body1 = &inBody2;
  634. body2 = &inBody1;
  635. }
  636. // Find the cached body pair
  637. BodyPair body_pair_key(body1->GetID(), body2->GetID());
  638. uint64 body_pair_hash = body_pair_key.GetHash();
  639. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  640. const BPKeyValue *kv = read_cache.Find(body_pair_key, body_pair_hash);
  641. if (kv == nullptr)
  642. return;
  643. const CachedBodyPair &input_cbp = kv->GetValue();
  644. // Get relative translation
  645. Quat inv_r1 = body1->GetRotation().Conjugated();
  646. Vec3 delta_position = inv_r1 * Vec3(body2->GetCenterOfMassPosition() - body1->GetCenterOfMassPosition());
  647. // Get old position delta
  648. Vec3 old_delta_position = Vec3::sLoadFloat3Unsafe(input_cbp.mDeltaPosition);
  649. // Check if bodies are still roughly in the same relative position
  650. if ((delta_position - old_delta_position).LengthSq() > mPhysicsSettings.mBodyPairCacheMaxDeltaPositionSq)
  651. return;
  652. // Determine relative orientation
  653. Quat delta_rotation = inv_r1 * body2->GetRotation();
  654. // Reconstruct old quaternion delta
  655. Quat old_delta_rotation = Quat::sLoadFloat3Unsafe(input_cbp.mDeltaRotation);
  656. // Check if bodies are still roughly in the same relative orientation
  657. // The delta between 2 quaternions p and q is: p q^* = [rotation_axis * sin(angle / 2), cos(angle / 2)]
  658. // From the W component we can extract the angle: cos(angle / 2) = px * qx + py * qy + pz * qz + pw * qw = p . q
  659. // Since we want to abort if the rotation is smaller than -angle or bigger than angle, we can write the comparison as |p . q| < cos(angle / 2)
  660. if (abs(delta_rotation.Dot(old_delta_rotation)) < mPhysicsSettings.mBodyPairCacheCosMaxDeltaRotationDiv2)
  661. return;
  662. // The cache is valid, return that we've handled this body pair
  663. outPairHandled = true;
  664. // Copy the cached body pair to this frame
  665. ManifoldCache &write_cache = mCache[mCacheWriteIdx];
  666. BPKeyValue *output_bp_kv = write_cache.Create(ioContactAllocator, body_pair_key, body_pair_hash);
  667. if (output_bp_kv == nullptr)
  668. return; // Out of cache space
  669. CachedBodyPair *output_cbp = &output_bp_kv->GetValue();
  670. memcpy(output_cbp, &input_cbp, sizeof(CachedBodyPair));
  671. // If there were no contacts, we have handled the contact
  672. if (input_cbp.mFirstCachedManifold == ManifoldMap::cInvalidHandle)
  673. return;
  674. // Get body transforms
  675. RMat44 transform_body1 = body1->GetCenterOfMassTransform();
  676. RMat44 transform_body2 = body2->GetCenterOfMassTransform();
  677. // Get time step
  678. float delta_time = mUpdateContext->mStepDeltaTime;
  679. // Copy manifolds
  680. uint32 output_handle = ManifoldMap::cInvalidHandle;
  681. uint32 input_handle = input_cbp.mFirstCachedManifold;
  682. do
  683. {
  684. JPH_PROFILE("Add Constraint From Cached Manifold");
  685. // Find the existing manifold
  686. const MKeyValue *input_kv = read_cache.FromHandle(input_handle);
  687. const SubShapeIDPair &input_key = input_kv->GetKey();
  688. const CachedManifold &input_cm = input_kv->GetValue();
  689. JPH_ASSERT(input_cm.mNumContactPoints > 0); // There should be contact points in this manifold!
  690. // Create room for manifold in write buffer and copy data
  691. uint64 input_hash = input_key.GetHash();
  692. MKeyValue *output_kv = write_cache.Create(ioContactAllocator, input_key, input_hash, input_cm.mNumContactPoints);
  693. if (output_kv == nullptr)
  694. break; // Out of cache space
  695. CachedManifold *output_cm = &output_kv->GetValue();
  696. memcpy(output_cm, &input_cm, CachedManifold::sGetRequiredTotalSize(input_cm.mNumContactPoints));
  697. // Link the object under the body pairs
  698. output_cm->mNextWithSameBodyPair = output_handle;
  699. output_handle = write_cache.ToHandle(output_kv);
  700. // Calculate default contact settings
  701. ContactSettings settings;
  702. settings.mCombinedFriction = mCombineFriction(*body1, input_key.GetSubShapeID1(), *body2, input_key.GetSubShapeID2());
  703. settings.mCombinedRestitution = mCombineRestitution(*body1, input_key.GetSubShapeID1(), *body2, input_key.GetSubShapeID2());
  704. settings.mIsSensor = body1->IsSensor() || body2->IsSensor();
  705. // Calculate world space contact normal
  706. Vec3 world_space_normal = transform_body2.Multiply3x3(Vec3::sLoadFloat3Unsafe(output_cm->mContactNormal)).Normalized();
  707. // Call contact listener to update settings
  708. if (mContactListener != nullptr)
  709. {
  710. // Convert constraint to manifold structure for callback
  711. ContactManifold manifold;
  712. manifold.mWorldSpaceNormal = world_space_normal;
  713. manifold.mSubShapeID1 = input_key.GetSubShapeID1();
  714. manifold.mSubShapeID2 = input_key.GetSubShapeID2();
  715. manifold.mBaseOffset = transform_body1.GetTranslation();
  716. manifold.mRelativeContactPointsOn1.resize(output_cm->mNumContactPoints);
  717. manifold.mRelativeContactPointsOn2.resize(output_cm->mNumContactPoints);
  718. Mat44 local_transform_body2 = transform_body2.PostTranslated(-manifold.mBaseOffset).ToMat44();
  719. float penetration_depth = -FLT_MAX;
  720. for (uint32 i = 0; i < output_cm->mNumContactPoints; ++i)
  721. {
  722. const CachedContactPoint &ccp = output_cm->mContactPoints[i];
  723. manifold.mRelativeContactPointsOn1[i] = transform_body1.Multiply3x3(Vec3::sLoadFloat3Unsafe(ccp.mPosition1));
  724. manifold.mRelativeContactPointsOn2[i] = local_transform_body2 * Vec3::sLoadFloat3Unsafe(ccp.mPosition2);
  725. penetration_depth = max(penetration_depth, (manifold.mRelativeContactPointsOn1[0] - manifold.mRelativeContactPointsOn2[0]).Dot(world_space_normal));
  726. }
  727. manifold.mPenetrationDepth = penetration_depth; // We don't have the penetration depth anymore, estimate it
  728. // Notify callback
  729. mContactListener->OnContactPersisted(*body1, *body2, manifold, settings);
  730. }
  731. JPH_ASSERT(settings.mIsSensor || !(body1->IsSensor() || body2->IsSensor()), "Sensors cannot be converted into regular bodies by a contact callback!");
  732. if (!settings.mIsSensor // If one of the bodies is a sensor, don't actually create the constraint
  733. && ((body1->IsDynamic() && settings.mInvMassScale1 != 0.0f) // One of the bodies must have mass to be able to create a contact constraint
  734. || (body2->IsDynamic() && settings.mInvMassScale2 != 0.0f)))
  735. {
  736. // Add contact constraint in world space for the solver
  737. uint32 constraint_idx = mNumConstraints++;
  738. if (constraint_idx >= mMaxConstraints)
  739. {
  740. ioContactAllocator.mErrors |= EPhysicsUpdateError::ContactConstraintsFull;
  741. break;
  742. }
  743. // A constraint will be created
  744. outConstraintCreated = true;
  745. ContactConstraint &constraint = mConstraints[constraint_idx];
  746. new (&constraint) ContactConstraint();
  747. constraint.mBody1 = body1;
  748. constraint.mBody2 = body2;
  749. constraint.mSortKey = input_hash;
  750. world_space_normal.StoreFloat3(&constraint.mWorldSpaceNormal);
  751. constraint.mCombinedFriction = settings.mCombinedFriction;
  752. constraint.mContactPoints.resize(output_cm->mNumContactPoints);
  753. for (uint32 i = 0; i < output_cm->mNumContactPoints; ++i)
  754. {
  755. CachedContactPoint &ccp = output_cm->mContactPoints[i];
  756. WorldContactPoint &wcp = constraint.mContactPoints[i];
  757. wcp.mNonPenetrationConstraint.SetTotalLambda(ccp.mNonPenetrationLambda);
  758. wcp.mFrictionConstraint1.SetTotalLambda(ccp.mFrictionLambda[0]);
  759. wcp.mFrictionConstraint2.SetTotalLambda(ccp.mFrictionLambda[1]);
  760. wcp.mContactPoint = &ccp;
  761. }
  762. JPH_DET_LOG("GetContactsFromCache: id1: " << constraint.mBody1->GetID() << " id2: " << constraint.mBody2->GetID() << " key: " << constraint.mSortKey);
  763. // Calculate friction and non-penetration constraint properties for all contact points
  764. CalculateFrictionAndNonPenetrationConstraintProperties(constraint, settings, delta_time, transform_body1, transform_body2, *body1, *body2);
  765. // Notify island builder
  766. mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());
  767. #ifdef JPH_DEBUG_RENDERER
  768. // Draw the manifold
  769. if (sDrawContactManifolds)
  770. constraint.Draw(DebugRenderer::sInstance, Color::sYellow);
  771. #endif // JPH_DEBUG_RENDERER
  772. }
  773. // Mark contact as persisted so that we won't fire OnContactRemoved callbacks
  774. input_cm.mFlags |= (uint16)CachedManifold::EFlags::ContactPersisted;
  775. // Fetch the next manifold
  776. input_handle = input_cm.mNextWithSameBodyPair;
  777. }
  778. while (input_handle != ManifoldMap::cInvalidHandle);
  779. output_cbp->mFirstCachedManifold = output_handle;
  780. }
  781. ContactConstraintManager::BodyPairHandle ContactConstraintManager::AddBodyPair(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2)
  782. {
  783. JPH_PROFILE_FUNCTION();
  784. // Swap bodies so that body 1 id < body 2 id
  785. const Body *body1, *body2;
  786. if (inBody1.GetID() < inBody2.GetID())
  787. {
  788. body1 = &inBody1;
  789. body2 = &inBody2;
  790. }
  791. else
  792. {
  793. body1 = &inBody2;
  794. body2 = &inBody1;
  795. }
  796. // Add an entry
  797. BodyPair body_pair_key(body1->GetID(), body2->GetID());
  798. uint64 body_pair_hash = body_pair_key.GetHash();
  799. BPKeyValue *body_pair_kv = mCache[mCacheWriteIdx].Create(ioContactAllocator, body_pair_key, body_pair_hash);
  800. if (body_pair_kv == nullptr)
  801. return nullptr; // Out of cache space
  802. CachedBodyPair *cbp = &body_pair_kv->GetValue();
  803. cbp->mFirstCachedManifold = ManifoldMap::cInvalidHandle;
  804. // Get relative translation
  805. Quat inv_r1 = body1->GetRotation().Conjugated();
  806. Vec3 delta_position = inv_r1 * Vec3(body2->GetCenterOfMassPosition() - body1->GetCenterOfMassPosition());
  807. // Store it
  808. delta_position.StoreFloat3(&cbp->mDeltaPosition);
  809. // Determine relative orientation
  810. Quat delta_rotation = inv_r1 * body2->GetRotation();
  811. // Store it
  812. delta_rotation.StoreFloat3(&cbp->mDeltaRotation);
  813. return cbp;
  814. }
  815. template <EMotionType Type1, EMotionType Type2>
  816. bool ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold)
  817. {
  818. // Calculate hash
  819. SubShapeIDPair key { inBody1.GetID(), inManifold.mSubShapeID1, inBody2.GetID(), inManifold.mSubShapeID2 };
  820. uint64 key_hash = key.GetHash();
  821. // Determine number of contact points
  822. int num_contact_points = (int)inManifold.mRelativeContactPointsOn1.size();
  823. JPH_ASSERT(num_contact_points <= MaxContactPoints);
  824. JPH_ASSERT(num_contact_points == (int)inManifold.mRelativeContactPointsOn2.size());
  825. // Reserve space for new contact cache entry
  826. // Note that for dynamic vs dynamic we always require the first body to have a lower body id to get a consistent key
  827. // under which to look up the contact
  828. ManifoldCache &write_cache = mCache[mCacheWriteIdx];
  829. MKeyValue *new_manifold_kv = write_cache.Create(ioContactAllocator, key, key_hash, num_contact_points);
  830. if (new_manifold_kv == nullptr)
  831. return false; // Out of cache space
  832. CachedManifold *new_manifold = &new_manifold_kv->GetValue();
  833. // Transform the world space normal to the space of body 2 (this is usually the static body)
  834. RMat44 inverse_transform_body2 = inBody2.GetInverseCenterOfMassTransform();
  835. inverse_transform_body2.Multiply3x3(inManifold.mWorldSpaceNormal).Normalized().StoreFloat3(&new_manifold->mContactNormal);
  836. // Settings object that gets passed to the callback
  837. ContactSettings settings;
  838. settings.mCombinedFriction = mCombineFriction(inBody1, inManifold.mSubShapeID1, inBody2, inManifold.mSubShapeID2);
  839. settings.mCombinedRestitution = mCombineRestitution(inBody1, inManifold.mSubShapeID1, inBody2, inManifold.mSubShapeID2);
  840. settings.mIsSensor = inBody1.IsSensor() || inBody2.IsSensor();
  841. // Get the contact points for the old cache entry
  842. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  843. const MKeyValue *old_manifold_kv = read_cache.Find(key, key_hash);
  844. const CachedContactPoint *ccp_start;
  845. const CachedContactPoint *ccp_end;
  846. if (old_manifold_kv != nullptr)
  847. {
  848. // Call point persisted listener
  849. if (mContactListener != nullptr)
  850. mContactListener->OnContactPersisted(inBody1, inBody2, inManifold, settings);
  851. // Fetch the contact points from the old manifold
  852. const CachedManifold *old_manifold = &old_manifold_kv->GetValue();
  853. ccp_start = old_manifold->mContactPoints;
  854. ccp_end = ccp_start + old_manifold->mNumContactPoints;
  855. // Mark contact as persisted so that we won't fire OnContactRemoved callbacks
  856. old_manifold->mFlags |= (uint16)CachedManifold::EFlags::ContactPersisted;
  857. }
  858. else
  859. {
  860. // Call point added listener
  861. if (mContactListener != nullptr)
  862. mContactListener->OnContactAdded(inBody1, inBody2, inManifold, settings);
  863. // No contact points available from old manifold
  864. ccp_start = nullptr;
  865. ccp_end = nullptr;
  866. }
  867. // Get inverse transform for body 1
  868. RMat44 inverse_transform_body1 = inBody1.GetInverseCenterOfMassTransform();
  869. bool contact_constraint_created = false;
  870. // If one of the bodies is a sensor, don't actually create the constraint
  871. JPH_ASSERT(settings.mIsSensor || !(inBody1.IsSensor() || inBody2.IsSensor()), "Sensors cannot be converted into regular bodies by a contact callback!");
  872. if (settings.mIsSensor)
  873. {
  874. // Store the contact manifold in the cache
  875. for (int i = 0; i < num_contact_points; ++i)
  876. {
  877. // Convert to local space to the body
  878. Vec3 p1 = Vec3(inverse_transform_body1 * (inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn1[i]));
  879. Vec3 p2 = Vec3(inverse_transform_body2 * (inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn2[i]));
  880. // Create new contact point
  881. CachedContactPoint &cp = new_manifold->mContactPoints[i];
  882. p1.StoreFloat3(&cp.mPosition1);
  883. p2.StoreFloat3(&cp.mPosition2);
  884. // We don't use this, but reset them anyway for determinism check
  885. cp.mNonPenetrationLambda = 0.0f;
  886. cp.mFrictionLambda[0] = 0.0f;
  887. cp.mFrictionLambda[1] = 0.0f;
  888. }
  889. }
  890. else if ((inBody1.IsDynamic() && settings.mInvMassScale1 != 0.0f) // One of the bodies must have mass to be able to create a contact constraint
  891. || (inBody2.IsDynamic() && settings.mInvMassScale2 != 0.0f))
  892. {
  893. // Add contact constraint
  894. uint32 constraint_idx = mNumConstraints++;
  895. if (constraint_idx >= mMaxConstraints)
  896. {
  897. ioContactAllocator.mErrors |= EPhysicsUpdateError::ContactConstraintsFull;
  898. // Manifold has been created already, we're not filling it in, so we need to reset the contact number of points.
  899. // Note that we don't hook it up to the body pair cache so that it won't be used as a cache during the next simulation.
  900. new_manifold->mNumContactPoints = 0;
  901. return false;
  902. }
  903. // We will create a contact constraint
  904. contact_constraint_created = true;
  905. ContactConstraint &constraint = mConstraints[constraint_idx];
  906. new (&constraint) ContactConstraint();
  907. constraint.mBody1 = &inBody1;
  908. constraint.mBody2 = &inBody2;
  909. constraint.mSortKey = key_hash;
  910. inManifold.mWorldSpaceNormal.StoreFloat3(&constraint.mWorldSpaceNormal);
  911. constraint.mCombinedFriction = settings.mCombinedFriction;
  912. JPH_DET_LOG("TemplatedAddContactConstraint: id1: " << constraint.mBody1->GetID() << " id2: " << constraint.mBody2->GetID() << " key: " << constraint.mSortKey);
  913. // Notify island builder
  914. mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, inBody1.GetIndexInActiveBodiesInternal(), inBody2.GetIndexInActiveBodiesInternal());
  915. // Get time step
  916. float delta_time = mUpdateContext->mStepDeltaTime;
  917. // Calculate scaled mass and inertia
  918. float inv_m1;
  919. Mat44 inv_i1;
  920. if constexpr (Type1 == EMotionType::Dynamic)
  921. {
  922. const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();
  923. inv_m1 = settings.mInvMassScale1 * mp1->GetInverseMass();
  924. inv_i1 = settings.mInvInertiaScale1 * mp1->GetInverseInertiaForRotation(inverse_transform_body1.Transposed3x3());
  925. }
  926. else
  927. {
  928. inv_m1 = 0.0f;
  929. inv_i1 = Mat44::sZero();
  930. }
  931. float inv_m2;
  932. Mat44 inv_i2;
  933. if constexpr (Type2 == EMotionType::Dynamic)
  934. {
  935. const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();
  936. inv_m2 = settings.mInvMassScale2 * mp2->GetInverseMass();
  937. inv_i2 = settings.mInvInertiaScale2 * mp2->GetInverseInertiaForRotation(inverse_transform_body2.Transposed3x3());
  938. }
  939. else
  940. {
  941. inv_m2 = 0.0f;
  942. inv_i2 = Mat44::sZero();
  943. }
  944. // Calculate tangents
  945. Vec3 t1, t2;
  946. constraint.GetTangents(t1, t2);
  947. constraint.mContactPoints.resize(num_contact_points);
  948. for (int i = 0; i < num_contact_points; ++i)
  949. {
  950. // Convert to world space and set positions
  951. WorldContactPoint &wcp = constraint.mContactPoints[i];
  952. RVec3 p1_ws = inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn1[i];
  953. RVec3 p2_ws = inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn2[i];
  954. // Convert to local space to the body
  955. Vec3 p1_ls = Vec3(inverse_transform_body1 * p1_ws);
  956. Vec3 p2_ls = Vec3(inverse_transform_body2 * p2_ws);
  957. // Check if we have a close contact point from last update
  958. bool lambda_set = false;
  959. for (const CachedContactPoint *ccp = ccp_start; ccp < ccp_end; ccp++)
  960. if (Vec3::sLoadFloat3Unsafe(ccp->mPosition1).IsClose(p1_ls, mPhysicsSettings.mContactPointPreserveLambdaMaxDistSq)
  961. && Vec3::sLoadFloat3Unsafe(ccp->mPosition2).IsClose(p2_ls, mPhysicsSettings.mContactPointPreserveLambdaMaxDistSq))
  962. {
  963. // Get lambdas from previous frame
  964. wcp.mNonPenetrationConstraint.SetTotalLambda(ccp->mNonPenetrationLambda);
  965. wcp.mFrictionConstraint1.SetTotalLambda(ccp->mFrictionLambda[0]);
  966. wcp.mFrictionConstraint2.SetTotalLambda(ccp->mFrictionLambda[1]);
  967. lambda_set = true;
  968. break;
  969. }
  970. if (!lambda_set)
  971. {
  972. wcp.mNonPenetrationConstraint.SetTotalLambda(0.0f);
  973. wcp.mFrictionConstraint1.SetTotalLambda(0.0f);
  974. wcp.mFrictionConstraint2.SetTotalLambda(0.0f);
  975. }
  976. // Create new contact point
  977. CachedContactPoint &cp = new_manifold->mContactPoints[i];
  978. p1_ls.StoreFloat3(&cp.mPosition1);
  979. p2_ls.StoreFloat3(&cp.mPosition2);
  980. wcp.mContactPoint = &cp;
  981. // Setup velocity constraint
  982. wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(delta_time, inBody1, inBody2, inv_m1, inv_m2, inv_i1, inv_i2, p1_ws, p2_ws, inManifold.mWorldSpaceNormal, t1, t2, settings, mPhysicsSettings.mMinVelocityForRestitution);
  983. }
  984. #ifdef JPH_DEBUG_RENDERER
  985. // Draw the manifold
  986. if (sDrawContactManifolds)
  987. constraint.Draw(DebugRenderer::sInstance, Color::sOrange);
  988. #endif // JPH_DEBUG_RENDERER
  989. }
  990. // Store cached contact point in body pair cache
  991. CachedBodyPair *cbp = reinterpret_cast<CachedBodyPair *>(inBodyPairHandle);
  992. new_manifold->mNextWithSameBodyPair = cbp->mFirstCachedManifold;
  993. cbp->mFirstCachedManifold = write_cache.ToHandle(new_manifold_kv);
  994. // A contact constraint was added
  995. return contact_constraint_created;
  996. }
  997. bool ContactConstraintManager::AddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold)
  998. {
  999. JPH_PROFILE_FUNCTION();
  1000. JPH_DET_LOG("AddContactConstraint: id1: " << inBody1.GetID() << " id2: " << inBody2.GetID()
  1001. << " subshape1: " << inManifold.mSubShapeID1 << " subshape2: " << inManifold.mSubShapeID2
  1002. << " normal: " << inManifold.mWorldSpaceNormal << " pendepth: " << inManifold.mPenetrationDepth);
  1003. JPH_ASSERT(inManifold.mWorldSpaceNormal.IsNormalized());
  1004. // Swap bodies so that body 1 id < body 2 id
  1005. const ContactManifold *manifold;
  1006. Body *body1, *body2;
  1007. ContactManifold temp;
  1008. if (inBody2.GetID() < inBody1.GetID())
  1009. {
  1010. body1 = &inBody2;
  1011. body2 = &inBody1;
  1012. temp = inManifold.SwapShapes();
  1013. manifold = &temp;
  1014. }
  1015. else
  1016. {
  1017. body1 = &inBody1;
  1018. body2 = &inBody2;
  1019. manifold = &inManifold;
  1020. }
  1021. // Dispatch to the correct templated form
  1022. // Note: Non-dynamic vs non-dynamic can happen in this case due to one body being a sensor, so we need to have an extended switch case here
  1023. switch (body1->GetMotionType())
  1024. {
  1025. case EMotionType::Dynamic:
  1026. {
  1027. switch (body2->GetMotionType())
  1028. {
  1029. case EMotionType::Dynamic:
  1030. return TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1031. case EMotionType::Kinematic:
  1032. return TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1033. case EMotionType::Static:
  1034. return TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Static>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1035. default:
  1036. JPH_ASSERT(false);
  1037. break;
  1038. }
  1039. break;
  1040. }
  1041. case EMotionType::Kinematic:
  1042. switch (body2->GetMotionType())
  1043. {
  1044. case EMotionType::Dynamic:
  1045. return TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1046. case EMotionType::Kinematic:
  1047. return TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Kinematic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1048. case EMotionType::Static:
  1049. return TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Static>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1050. default:
  1051. JPH_ASSERT(false);
  1052. break;
  1053. }
  1054. break;
  1055. case EMotionType::Static:
  1056. switch (body2->GetMotionType())
  1057. {
  1058. case EMotionType::Dynamic:
  1059. return TemplatedAddContactConstraint<EMotionType::Static, EMotionType::Dynamic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1060. case EMotionType::Kinematic:
  1061. return TemplatedAddContactConstraint<EMotionType::Static, EMotionType::Kinematic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1062. case EMotionType::Static: // Static vs static not possible
  1063. default:
  1064. JPH_ASSERT(false);
  1065. break;
  1066. }
  1067. break;
  1068. default:
  1069. JPH_ASSERT(false);
  1070. break;
  1071. }
  1072. return false;
  1073. }
  1074. void ContactConstraintManager::OnCCDContactAdded(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &outSettings)
  1075. {
  1076. JPH_ASSERT(inManifold.mWorldSpaceNormal.IsNormalized());
  1077. // Calculate contact settings
  1078. outSettings.mCombinedFriction = mCombineFriction(inBody1, inManifold.mSubShapeID1, inBody2, inManifold.mSubShapeID2);
  1079. outSettings.mCombinedRestitution = mCombineRestitution(inBody1, inManifold.mSubShapeID1, inBody2, inManifold.mSubShapeID2);
  1080. outSettings.mIsSensor = false; // For now, no sensors are supported during CCD
  1081. // The remainder of this function only deals with calling contact callbacks, if there's no contact callback we also don't need to do this work
  1082. if (mContactListener != nullptr)
  1083. {
  1084. // Swap bodies so that body 1 id < body 2 id
  1085. const ContactManifold *manifold;
  1086. const Body *body1, *body2;
  1087. ContactManifold temp;
  1088. if (inBody2.GetID() < inBody1.GetID())
  1089. {
  1090. body1 = &inBody2;
  1091. body2 = &inBody1;
  1092. temp = inManifold.SwapShapes();
  1093. manifold = &temp;
  1094. }
  1095. else
  1096. {
  1097. body1 = &inBody1;
  1098. body2 = &inBody2;
  1099. manifold = &inManifold;
  1100. }
  1101. // Calculate hash
  1102. SubShapeIDPair key { body1->GetID(), manifold->mSubShapeID1, body2->GetID(), manifold->mSubShapeID2 };
  1103. uint64 key_hash = key.GetHash();
  1104. // Check if we already created this contact this physics update
  1105. ManifoldCache &write_cache = mCache[mCacheWriteIdx];
  1106. MKVAndCreated new_manifold_kv = write_cache.FindOrCreate(ioContactAllocator, key, key_hash, 0);
  1107. if (new_manifold_kv.second)
  1108. {
  1109. // This contact is new for this physics update, check if previous update we already had this contact.
  1110. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  1111. const MKeyValue *old_manifold_kv = read_cache.Find(key, key_hash);
  1112. if (old_manifold_kv == nullptr)
  1113. {
  1114. // New contact
  1115. mContactListener->OnContactAdded(*body1, *body2, *manifold, outSettings);
  1116. }
  1117. else
  1118. {
  1119. // Existing contact
  1120. mContactListener->OnContactPersisted(*body1, *body2, *manifold, outSettings);
  1121. // Mark contact as persisted so that we won't fire OnContactRemoved callbacks
  1122. old_manifold_kv->GetValue().mFlags |= (uint16)CachedManifold::EFlags::ContactPersisted;
  1123. }
  1124. // Check if the cache is full
  1125. if (new_manifold_kv.first != nullptr)
  1126. {
  1127. // We don't store any contact points in this manifold as it is not for caching impulses, we only need to know that the contact was created
  1128. CachedManifold &new_manifold = new_manifold_kv.first->GetValue();
  1129. new_manifold.mContactNormal = { 0, 0, 0 };
  1130. new_manifold.mFlags |= (uint16)CachedManifold::EFlags::CCDContact;
  1131. }
  1132. }
  1133. else
  1134. {
  1135. // Already found this contact this physics update.
  1136. // Note that we can trigger OnContactPersisted multiple times per physics update, but otherwise we have no way of obtaining the settings
  1137. mContactListener->OnContactPersisted(*body1, *body2, *manifold, outSettings);
  1138. }
  1139. }
  1140. JPH_ASSERT(outSettings.mIsSensor || !(inBody1.IsSensor() || inBody2.IsSensor()), "Sensors cannot be converted into regular bodies by a contact callback!");
  1141. }
  1142. void ContactConstraintManager::SortContacts(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd) const
  1143. {
  1144. JPH_PROFILE_FUNCTION();
  1145. QuickSort(inConstraintIdxBegin, inConstraintIdxEnd, [this](uint32 inLHS, uint32 inRHS) {
  1146. const ContactConstraint &lhs = mConstraints[inLHS];
  1147. const ContactConstraint &rhs = mConstraints[inRHS];
  1148. // Most of the time the sort key will be different so we sort on that
  1149. if (lhs.mSortKey != rhs.mSortKey)
  1150. return lhs.mSortKey < rhs.mSortKey;
  1151. // If they're equal we use the IDs of body 1 to order
  1152. if (lhs.mBody1 != rhs.mBody1)
  1153. return lhs.mBody1->GetID() < rhs.mBody1->GetID();
  1154. // If they're still equal we use the IDs of body 2 to order
  1155. if (lhs.mBody2 != rhs.mBody2)
  1156. return lhs.mBody2->GetID() < rhs.mBody2->GetID();
  1157. JPH_ASSERT(inLHS == inRHS, "Hash collision, ordering will be inconsistent");
  1158. return false;
  1159. });
  1160. }
  1161. void ContactConstraintManager::FinalizeContactCacheAndCallContactPointRemovedCallbacks(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds)
  1162. {
  1163. JPH_PROFILE_FUNCTION();
  1164. #ifdef JPH_ENABLE_ASSERTS
  1165. // Mark cache as finalized
  1166. ManifoldCache &old_write_cache = mCache[mCacheWriteIdx];
  1167. old_write_cache.Finalize();
  1168. // Check that the count of body pairs and manifolds that we tracked outside of the cache (to avoid contention on an atomic) is correct
  1169. JPH_ASSERT(old_write_cache.GetNumBodyPairs() == inExpectedNumBodyPairs);
  1170. JPH_ASSERT(old_write_cache.GetNumManifolds() == inExpectedNumManifolds);
  1171. #endif
  1172. // Buffers are now complete, make write buffer the read buffer
  1173. mCacheWriteIdx ^= 1;
  1174. // Get the old read cache / new write cache
  1175. ManifoldCache &old_read_cache = mCache[mCacheWriteIdx];
  1176. // Call the contact point removal callbacks
  1177. if (mContactListener != nullptr)
  1178. old_read_cache.ContactPointRemovedCallbacks(mContactListener);
  1179. // We're done with the old read cache now
  1180. old_read_cache.Clear();
  1181. // Use the amount of contacts from the last iteration to determine the amount of buckets to use in the hash map for the next iteration
  1182. old_read_cache.Prepare(inExpectedNumBodyPairs, inExpectedNumManifolds);
  1183. }
  1184. bool ContactConstraintManager::WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const
  1185. {
  1186. // The body pair needs to be in the cache and it needs to have a manifold (otherwise it's just a record indicating that there are no collisions)
  1187. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  1188. BodyPair key;
  1189. if (inBody1ID < inBody2ID)
  1190. key = BodyPair(inBody1ID, inBody2ID);
  1191. else
  1192. key = BodyPair(inBody2ID, inBody1ID);
  1193. uint64 key_hash = key.GetHash();
  1194. const BPKeyValue *kv = read_cache.Find(key, key_hash);
  1195. return kv != nullptr && kv->GetValue().mFirstCachedManifold != ManifoldMap::cInvalidHandle;
  1196. }
  1197. template <EMotionType Type1, EMotionType Type2>
  1198. JPH_INLINE void ContactConstraintManager::sWarmStartConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio)
  1199. {
  1200. // Calculate tangents
  1201. Vec3 t1, t2;
  1202. ioConstraint.GetTangents(t1, t2);
  1203. Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();
  1204. for (WorldContactPoint &wcp : ioConstraint.mContactPoints)
  1205. {
  1206. // Warm starting: Apply impulse from last frame
  1207. if (wcp.mFrictionConstraint1.IsActive())
  1208. {
  1209. JPH_ASSERT(wcp.mFrictionConstraint2.IsActive());
  1210. wcp.mFrictionConstraint1.TemplatedWarmStart<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t1, inWarmStartImpulseRatio);
  1211. wcp.mFrictionConstraint2.TemplatedWarmStart<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t2, inWarmStartImpulseRatio);
  1212. }
  1213. wcp.mNonPenetrationConstraint.TemplatedWarmStart<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, ws_normal, inWarmStartImpulseRatio);
  1214. }
  1215. }
  1216. void ContactConstraintManager::WarmStartVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio)
  1217. {
  1218. JPH_PROFILE_FUNCTION();
  1219. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1220. {
  1221. ContactConstraint &constraint = mConstraints[*constraint_idx];
  1222. // Fetch bodies
  1223. Body &body1 = *constraint.mBody1;
  1224. EMotionType motion_type1 = body1.GetMotionType();
  1225. MotionProperties *motion_properties1 = body1.GetMotionPropertiesUnchecked();
  1226. Body &body2 = *constraint.mBody2;
  1227. EMotionType motion_type2 = body2.GetMotionType();
  1228. MotionProperties *motion_properties2 = body2.GetMotionPropertiesUnchecked();
  1229. // Dispatch to the correct templated form
  1230. // Note: Warm starting doesn't differentiate between kinematic/static bodies so we handle both as static bodies
  1231. if (motion_type1 == EMotionType::Dynamic)
  1232. {
  1233. if (motion_type2 == EMotionType::Dynamic)
  1234. sWarmStartConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);
  1235. else
  1236. sWarmStartConstraint<EMotionType::Dynamic, EMotionType::Static>(constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);
  1237. }
  1238. else
  1239. {
  1240. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  1241. sWarmStartConstraint<EMotionType::Static, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);
  1242. }
  1243. }
  1244. }
  1245. template <EMotionType Type1, EMotionType Type2>
  1246. JPH_INLINE bool ContactConstraintManager::sSolveVelocityConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2)
  1247. {
  1248. bool any_impulse_applied = false;
  1249. // Calculate tangents
  1250. Vec3 t1, t2;
  1251. ioConstraint.GetTangents(t1, t2);
  1252. // First apply all friction constraints (non-penetration is more important than friction)
  1253. for (WorldContactPoint &wcp : ioConstraint.mContactPoints)
  1254. {
  1255. // Check if friction is enabled
  1256. if (wcp.mFrictionConstraint1.IsActive())
  1257. {
  1258. JPH_ASSERT(wcp.mFrictionConstraint2.IsActive());
  1259. // Calculate impulse to stop motion in tangential direction
  1260. float lambda1 = wcp.mFrictionConstraint1.TemplatedSolveVelocityConstraintGetTotalLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t1);
  1261. float lambda2 = wcp.mFrictionConstraint2.TemplatedSolveVelocityConstraintGetTotalLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t2);
  1262. float total_lambda_sq = Square(lambda1) + Square(lambda2);
  1263. // Calculate max impulse that can be applied. Note that we're using the non-penetration impulse from the previous iteration here.
  1264. // We do this because non-penetration is more important so is solved last (the last things that are solved in an iterative solver
  1265. // contribute the most).
  1266. float max_lambda_f = ioConstraint.mCombinedFriction * wcp.mNonPenetrationConstraint.GetTotalLambda();
  1267. // If the total lambda that we will apply is too large, scale it back
  1268. if (total_lambda_sq > Square(max_lambda_f))
  1269. {
  1270. float scale = max_lambda_f / sqrt(total_lambda_sq);
  1271. lambda1 *= scale;
  1272. lambda2 *= scale;
  1273. }
  1274. // Apply the friction impulse
  1275. if (wcp.mFrictionConstraint1.TemplatedSolveVelocityConstraintApplyLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t1, lambda1))
  1276. any_impulse_applied = true;
  1277. if (wcp.mFrictionConstraint2.TemplatedSolveVelocityConstraintApplyLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t2, lambda2))
  1278. any_impulse_applied = true;
  1279. }
  1280. }
  1281. Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();
  1282. // Then apply all non-penetration constraints
  1283. for (WorldContactPoint &wcp : ioConstraint.mContactPoints)
  1284. {
  1285. // Solve non penetration velocities
  1286. if (wcp.mNonPenetrationConstraint.TemplatedSolveVelocityConstraint<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, ws_normal, 0.0f, FLT_MAX))
  1287. any_impulse_applied = true;
  1288. }
  1289. return any_impulse_applied;
  1290. }
  1291. bool ContactConstraintManager::SolveVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd)
  1292. {
  1293. JPH_PROFILE_FUNCTION();
  1294. bool any_impulse_applied = false;
  1295. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1296. {
  1297. ContactConstraint &constraint = mConstraints[*constraint_idx];
  1298. // Fetch bodies
  1299. Body &body1 = *constraint.mBody1;
  1300. EMotionType motion_type1 = body1.GetMotionType();
  1301. MotionProperties *motion_properties1 = body1.GetMotionPropertiesUnchecked();
  1302. Body &body2 = *constraint.mBody2;
  1303. EMotionType motion_type2 = body2.GetMotionType();
  1304. MotionProperties *motion_properties2 = body2.GetMotionPropertiesUnchecked();
  1305. // Dispatch to the correct templated form
  1306. switch (motion_type1)
  1307. {
  1308. case EMotionType::Dynamic:
  1309. switch (motion_type2)
  1310. {
  1311. case EMotionType::Dynamic:
  1312. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2);
  1313. break;
  1314. case EMotionType::Kinematic:
  1315. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(constraint, motion_properties1, motion_properties2);
  1316. break;
  1317. case EMotionType::Static:
  1318. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(constraint, motion_properties1, motion_properties2);
  1319. break;
  1320. default:
  1321. JPH_ASSERT(false);
  1322. break;
  1323. }
  1324. break;
  1325. case EMotionType::Kinematic:
  1326. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  1327. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2);
  1328. break;
  1329. case EMotionType::Static:
  1330. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  1331. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2);
  1332. break;
  1333. default:
  1334. JPH_ASSERT(false);
  1335. break;
  1336. }
  1337. }
  1338. return any_impulse_applied;
  1339. }
  1340. void ContactConstraintManager::StoreAppliedImpulses(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const
  1341. {
  1342. // Copy back total applied impulse to cache for the next frame
  1343. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1344. {
  1345. const ContactConstraint &constraint = mConstraints[*constraint_idx];
  1346. for (const WorldContactPoint &wcp : constraint.mContactPoints)
  1347. {
  1348. wcp.mContactPoint->mNonPenetrationLambda = wcp.mNonPenetrationConstraint.GetTotalLambda();
  1349. wcp.mContactPoint->mFrictionLambda[0] = wcp.mFrictionConstraint1.GetTotalLambda();
  1350. wcp.mContactPoint->mFrictionLambda[1] = wcp.mFrictionConstraint2.GetTotalLambda();
  1351. }
  1352. }
  1353. }
  1354. bool ContactConstraintManager::SolvePositionConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd)
  1355. {
  1356. JPH_PROFILE_FUNCTION();
  1357. bool any_impulse_applied = false;
  1358. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1359. {
  1360. ContactConstraint &constraint = mConstraints[*constraint_idx];
  1361. // Fetch bodies
  1362. Body &body1 = *constraint.mBody1;
  1363. Body &body2 = *constraint.mBody2;
  1364. // Get transforms
  1365. RMat44 transform1 = body1.GetCenterOfMassTransform();
  1366. RMat44 transform2 = body2.GetCenterOfMassTransform();
  1367. Vec3 ws_normal = constraint.GetWorldSpaceNormal();
  1368. for (WorldContactPoint &wcp : constraint.mContactPoints)
  1369. {
  1370. // Calculate new contact point positions in world space (the bodies may have moved)
  1371. RVec3 p1 = transform1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  1372. RVec3 p2 = transform2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);
  1373. // Calculate separation along the normal (negative if interpenetrating)
  1374. // Allow a little penetration by default (PhysicsSettings::mPenetrationSlop) to avoid jittering between contact/no-contact which wipes out the contact cache and warm start impulses
  1375. // Clamp penetration to a max PhysicsSettings::mMaxPenetrationDistance so that we don't apply a huge impulse if we're penetrating a lot
  1376. float separation = max(Vec3(p2 - p1).Dot(ws_normal) + mPhysicsSettings.mPenetrationSlop, -mPhysicsSettings.mMaxPenetrationDistance);
  1377. // Only enforce constraint when separation < 0 (otherwise we're apart)
  1378. if (separation < 0.0f)
  1379. {
  1380. // Update constraint properties (bodies may have moved)
  1381. wcp.CalculateNonPenetrationConstraintProperties(body1, body2, p1, p2, ws_normal);
  1382. // Solve position errors
  1383. if (wcp.mNonPenetrationConstraint.SolvePositionConstraint(body1, body2, ws_normal, separation, mPhysicsSettings.mBaumgarte))
  1384. any_impulse_applied = true;
  1385. }
  1386. }
  1387. }
  1388. return any_impulse_applied;
  1389. }
  1390. void ContactConstraintManager::RecycleConstraintBuffer()
  1391. {
  1392. // Reset constraint array
  1393. mNumConstraints = 0;
  1394. }
  1395. void ContactConstraintManager::FinishConstraintBuffer()
  1396. {
  1397. // Free constraints buffer
  1398. mUpdateContext->mTempAllocator->Free(mConstraints, mMaxConstraints * sizeof(ContactConstraint));
  1399. mConstraints = nullptr;
  1400. mNumConstraints = 0;
  1401. // Reset update context
  1402. mUpdateContext = nullptr;
  1403. }
  1404. void ContactConstraintManager::SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const
  1405. {
  1406. mCache[mCacheWriteIdx ^ 1].SaveState(inStream, inFilter);
  1407. }
  1408. bool ContactConstraintManager::RestoreState(StateRecorder &inStream)
  1409. {
  1410. bool success = mCache[mCacheWriteIdx].RestoreState(mCache[mCacheWriteIdx ^ 1], inStream);
  1411. mCacheWriteIdx ^= 1;
  1412. mCache[mCacheWriteIdx].Clear();
  1413. return success;
  1414. }
  1415. JPH_NAMESPACE_END