2
0

ContactConstraintManager.cpp 60 KB

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