SoftBodyMotionProperties.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/SoftBody/SoftBodyMotionProperties.h>
  6. #include <Jolt/Physics/SoftBody/SoftBodyCreationSettings.h>
  7. #include <Jolt/Physics/SoftBody/SoftBodyContactListener.h>
  8. #include <Jolt/Physics/SoftBody/SoftBodyManifold.h>
  9. #include <Jolt/Physics/PhysicsSystem.h>
  10. #ifdef JPH_DEBUG_RENDERER
  11. #include <Jolt/Renderer/DebugRenderer.h>
  12. #endif // JPH_DEBUG_RENDERER
  13. JPH_NAMESPACE_BEGIN
  14. void SoftBodyMotionProperties::CalculateMassAndInertia()
  15. {
  16. MassProperties mp;
  17. for (const Vertex &v : mVertices)
  18. if (v.mInvMass > 0.0f)
  19. {
  20. Vec3 pos = v.mPosition;
  21. // Accumulate mass
  22. float mass = 1.0f / v.mInvMass;
  23. mp.mMass += mass;
  24. // Inertia tensor, diagonal
  25. // See equations https://en.wikipedia.org/wiki/Moment_of_inertia section 'Inertia Tensor'
  26. for (int i = 0; i < 3; ++i)
  27. mp.mInertia(i, i) += mass * (Square(pos[(i + 1) % 3]) + Square(pos[(i + 2) % 3]));
  28. // Inertia tensor off diagonal
  29. for (int i = 0; i < 3; ++i)
  30. for (int j = 0; j < 3; ++j)
  31. if (i != j)
  32. mp.mInertia(i, j) -= mass * pos[i] * pos[j];
  33. }
  34. else
  35. {
  36. // If one vertex is kinematic, the entire body will have infinite mass and inertia
  37. SetInverseMass(0.0f);
  38. SetInverseInertia(Vec3::sZero(), Quat::sIdentity());
  39. return;
  40. }
  41. SetMassProperties(EAllowedDOFs::All, mp);
  42. }
  43. void SoftBodyMotionProperties::Initialize(const SoftBodyCreationSettings &inSettings)
  44. {
  45. // Store settings
  46. mSettings = inSettings.mSettings;
  47. mNumIterations = inSettings.mNumIterations;
  48. mPressure = inSettings.mPressure;
  49. mUpdatePosition = inSettings.mUpdatePosition;
  50. // Initialize vertices
  51. mVertices.resize(inSettings.mSettings->mVertices.size());
  52. Mat44 rotation = inSettings.mMakeRotationIdentity? Mat44::sRotation(inSettings.mRotation) : Mat44::sIdentity();
  53. for (Array<Vertex>::size_type v = 0, s = mVertices.size(); v < s; ++v)
  54. {
  55. const SoftBodySharedSettings::Vertex &in_vertex = inSettings.mSettings->mVertices[v];
  56. Vertex &out_vertex = mVertices[v];
  57. out_vertex.mPreviousPosition = out_vertex.mPosition = rotation * Vec3(in_vertex.mPosition);
  58. out_vertex.mVelocity = rotation.Multiply3x3(Vec3(in_vertex.mVelocity));
  59. out_vertex.mCollidingShapeIndex = -1;
  60. out_vertex.mHasContact = false;
  61. out_vertex.mLargestPenetration = -FLT_MAX;
  62. out_vertex.mInvMass = in_vertex.mInvMass;
  63. mLocalBounds.Encapsulate(out_vertex.mPosition);
  64. }
  65. // We don't know delta time yet, so we can't predict the bounds and use the local bounds as the predicted bounds
  66. mLocalPredictedBounds = mLocalBounds;
  67. CalculateMassAndInertia();
  68. }
  69. float SoftBodyMotionProperties::GetVolumeTimesSix() const
  70. {
  71. float six_volume = 0.0f;
  72. for (const Face &f : mSettings->mFaces)
  73. {
  74. Vec3 x1 = mVertices[f.mVertex[0]].mPosition;
  75. Vec3 x2 = mVertices[f.mVertex[1]].mPosition;
  76. Vec3 x3 = mVertices[f.mVertex[2]].mPosition;
  77. six_volume += x1.Cross(x2).Dot(x3); // We pick zero as the origin as this is the center of the bounding box so should give good accuracy
  78. }
  79. return six_volume;
  80. }
  81. void SoftBodyMotionProperties::DetermineCollidingShapes(const SoftBodyUpdateContext &inContext, const PhysicsSystem &inSystem)
  82. {
  83. JPH_PROFILE_FUNCTION();
  84. struct Collector : public CollideShapeBodyCollector
  85. {
  86. Collector(const SoftBodyUpdateContext &inContext, const PhysicsSystem &inSystem, Array<CollidingShape> &ioHits) :
  87. mContext(inContext),
  88. mInverseTransform(inContext.mCenterOfMassTransform.InversedRotationTranslation()),
  89. mBodyLockInterface(inSystem.GetBodyLockInterfaceNoLock()),
  90. mCombineFriction(inSystem.GetCombineFriction()),
  91. mCombineRestitution(inSystem.GetCombineRestitution()),
  92. mHits(ioHits)
  93. {
  94. }
  95. virtual void AddHit(const BodyID &inResult) override
  96. {
  97. BodyLockRead lock(mBodyLockInterface, inResult);
  98. if (lock.Succeeded())
  99. {
  100. const Body &soft_body = *mContext.mBody;
  101. const Body &body = lock.GetBody();
  102. if (body.IsRigidBody() // TODO: We should support soft body vs soft body
  103. && soft_body.GetCollisionGroup().CanCollide(body.GetCollisionGroup()))
  104. {
  105. // Call the contact listener to see if we should accept this contact
  106. // If there is no contact listener then we can ignore the contact if the other body is a sensor
  107. SoftBodyContactSettings settings;
  108. settings.mIsSensor = body.IsSensor();
  109. if (mContext.mContactListener == nullptr? !settings.mIsSensor : mContext.mContactListener->OnSoftBodyContactValidate(soft_body, body, settings) == SoftBodyValidateResult::AcceptContact)
  110. {
  111. CollidingShape cs;
  112. cs.mCenterOfMassTransform = (mInverseTransform * body.GetCenterOfMassTransform()).ToMat44();
  113. cs.mShape = body.GetShape();
  114. cs.mBodyID = inResult;
  115. cs.mMotionType = body.GetMotionType();
  116. cs.mIsSensor = settings.mIsSensor;
  117. cs.mUpdateVelocities = false;
  118. cs.mFriction = mCombineFriction(soft_body, SubShapeID(), body, SubShapeID());
  119. cs.mRestitution = mCombineRestitution(soft_body, SubShapeID(), body, SubShapeID());
  120. if (cs.mMotionType == EMotionType::Dynamic)
  121. {
  122. const MotionProperties *mp = body.GetMotionProperties();
  123. cs.mInvMass = settings.mInvMassScale2 * mp->GetInverseMass();
  124. cs.mInvInertia = settings.mInvInertiaScale2 * mp->GetInverseInertiaForRotation(cs.mCenterOfMassTransform.GetRotation());
  125. cs.mSoftBodyInvMassScale = settings.mInvMassScale1;
  126. cs.mOriginalLinearVelocity = cs.mLinearVelocity = mInverseTransform.Multiply3x3(mp->GetLinearVelocity());
  127. cs.mOriginalAngularVelocity = cs.mAngularVelocity = mInverseTransform.Multiply3x3(mp->GetAngularVelocity());
  128. }
  129. mHits.push_back(cs);
  130. }
  131. }
  132. }
  133. }
  134. private:
  135. const SoftBodyUpdateContext &mContext;
  136. RMat44 mInverseTransform;
  137. const BodyLockInterface & mBodyLockInterface;
  138. ContactConstraintManager::CombineFunction mCombineFriction;
  139. ContactConstraintManager::CombineFunction mCombineRestitution;
  140. Array<CollidingShape> & mHits;
  141. };
  142. Collector collector(inContext, inSystem, mCollidingShapes);
  143. AABox bounds = mLocalBounds;
  144. bounds.Encapsulate(mLocalPredictedBounds);
  145. bounds = bounds.Transformed(inContext.mCenterOfMassTransform);
  146. bounds.ExpandBy(Vec3::sReplicate(mSettings->mVertexRadius));
  147. ObjectLayer layer = inContext.mBody->GetObjectLayer();
  148. DefaultBroadPhaseLayerFilter broadphase_layer_filter = inSystem.GetDefaultBroadPhaseLayerFilter(layer);
  149. DefaultObjectLayerFilter object_layer_filter = inSystem.GetDefaultLayerFilter(layer);
  150. inSystem.GetBroadPhaseQuery().CollideAABox(bounds, collector, broadphase_layer_filter, object_layer_filter);
  151. }
  152. void SoftBodyMotionProperties::DetermineCollisionPlanes(const SoftBodyUpdateContext &inContext, uint inVertexStart, uint inNumVertices)
  153. {
  154. JPH_PROFILE_FUNCTION();
  155. // Generate collision planes
  156. for (const CollidingShape &cs : mCollidingShapes)
  157. cs.mShape->CollideSoftBodyVertices(cs.mCenterOfMassTransform, Vec3::sReplicate(1.0f), mVertices.data() + inVertexStart, inNumVertices, inContext.mDeltaTime, inContext.mDisplacementDueToGravity, int(&cs - mCollidingShapes.data()));
  158. }
  159. void SoftBodyMotionProperties::ApplyPressure(const SoftBodyUpdateContext &inContext)
  160. {
  161. JPH_PROFILE_FUNCTION();
  162. float dt = inContext.mSubStepDeltaTime;
  163. float pressure_coefficient = mPressure;
  164. if (pressure_coefficient > 0.0f)
  165. {
  166. // Calculate total volume
  167. float six_volume = GetVolumeTimesSix();
  168. if (six_volume > 0.0f)
  169. {
  170. // Apply pressure
  171. // p = F / A = n R T / V (see https://en.wikipedia.org/wiki/Pressure)
  172. // Our pressure coefficient is n R T so the impulse is:
  173. // P = F dt = pressure_coefficient / V * A * dt
  174. float coefficient = pressure_coefficient * dt / six_volume; // Need to still multiply by 6 for the volume
  175. for (const Face &f : mSettings->mFaces)
  176. {
  177. Vec3 x1 = mVertices[f.mVertex[0]].mPosition;
  178. Vec3 x2 = mVertices[f.mVertex[1]].mPosition;
  179. Vec3 x3 = mVertices[f.mVertex[2]].mPosition;
  180. Vec3 impulse = coefficient * (x2 - x1).Cross(x3 - x1); // Area is half the cross product so need to still divide by 2
  181. for (uint32 i : f.mVertex)
  182. {
  183. Vertex &v = mVertices[i];
  184. v.mVelocity += v.mInvMass * impulse; // Want to divide by 3 because we spread over 3 vertices
  185. }
  186. }
  187. }
  188. }
  189. }
  190. void SoftBodyMotionProperties::IntegratePositions(const SoftBodyUpdateContext &inContext)
  191. {
  192. JPH_PROFILE_FUNCTION();
  193. float dt = inContext.mSubStepDeltaTime;
  194. float linear_damping = max(0.0f, 1.0f - GetLinearDamping() * dt); // See: MotionProperties::ApplyForceTorqueAndDragInternal
  195. // Integrate
  196. Vec3 sub_step_gravity = inContext.mGravity * dt;
  197. for (Vertex &v : mVertices)
  198. if (v.mInvMass > 0.0f)
  199. {
  200. // Gravity
  201. v.mVelocity += sub_step_gravity;
  202. // Damping
  203. v.mVelocity *= linear_damping;
  204. // Integrate
  205. v.mPreviousPosition = v.mPosition;
  206. v.mPosition += v.mVelocity * dt;
  207. }
  208. else
  209. {
  210. // Integrate
  211. v.mPreviousPosition = v.mPosition;
  212. v.mPosition += v.mVelocity * dt;
  213. }
  214. }
  215. void SoftBodyMotionProperties::ApplyVolumeConstraints(const SoftBodyUpdateContext &inContext)
  216. {
  217. JPH_PROFILE_FUNCTION();
  218. float inv_dt_sq = 1.0f / Square(inContext.mSubStepDeltaTime);
  219. // Satisfy volume constraints
  220. for (const Volume &v : mSettings->mVolumeConstraints)
  221. {
  222. Vertex &v1 = mVertices[v.mVertex[0]];
  223. Vertex &v2 = mVertices[v.mVertex[1]];
  224. Vertex &v3 = mVertices[v.mVertex[2]];
  225. Vertex &v4 = mVertices[v.mVertex[3]];
  226. Vec3 x1 = v1.mPosition;
  227. Vec3 x2 = v2.mPosition;
  228. Vec3 x3 = v3.mPosition;
  229. Vec3 x4 = v4.mPosition;
  230. // Calculate constraint equation
  231. Vec3 x1x2 = x2 - x1;
  232. Vec3 x1x3 = x3 - x1;
  233. Vec3 x1x4 = x4 - x1;
  234. float c = abs(x1x2.Cross(x1x3).Dot(x1x4)) - v.mSixRestVolume;
  235. // Calculate gradient of constraint equation
  236. Vec3 d1c = (x4 - x2).Cross(x3 - x2);
  237. Vec3 d2c = x1x3.Cross(x1x4);
  238. Vec3 d3c = x1x4.Cross(x1x2);
  239. Vec3 d4c = x1x2.Cross(x1x3);
  240. float w1 = v1.mInvMass;
  241. float w2 = v2.mInvMass;
  242. float w3 = v3.mInvMass;
  243. float w4 = v4.mInvMass;
  244. JPH_ASSERT(w1 > 0.0f || w2 > 0.0f || w3 > 0.0f || w4 > 0.0f);
  245. // Apply correction
  246. float lambda = -c / (w1 * d1c.LengthSq() + w2 * d2c.LengthSq() + w3 * d3c.LengthSq() + w4 * d4c.LengthSq() + v.mCompliance * inv_dt_sq);
  247. v1.mPosition += lambda * w1 * d1c;
  248. v2.mPosition += lambda * w2 * d2c;
  249. v3.mPosition += lambda * w3 * d3c;
  250. v4.mPosition += lambda * w4 * d4c;
  251. }
  252. }
  253. void SoftBodyMotionProperties::ApplyEdgeConstraints(const SoftBodyUpdateContext &inContext, uint inStartIndex, uint inEndIndex)
  254. {
  255. JPH_PROFILE_FUNCTION();
  256. float inv_dt_sq = 1.0f / Square(inContext.mSubStepDeltaTime);
  257. // Satisfy edge constraints
  258. const Array<Edge> &edge_constraints = mSettings->mEdgeConstraints;
  259. for (uint i = inStartIndex; i < inEndIndex; ++i)
  260. {
  261. const Edge &e = edge_constraints[i];
  262. Vertex &v0 = mVertices[e.mVertex[0]];
  263. Vertex &v1 = mVertices[e.mVertex[1]];
  264. // Calculate current length
  265. Vec3 delta = v1.mPosition - v0.mPosition;
  266. float length = delta.Length();
  267. if (length > 0.0f)
  268. {
  269. // Apply correction
  270. Vec3 correction = delta * (length - e.mRestLength) / (length * (v0.mInvMass + v1.mInvMass + e.mCompliance * inv_dt_sq));
  271. v0.mPosition += v0.mInvMass * correction;
  272. v1.mPosition -= v1.mInvMass * correction;
  273. }
  274. }
  275. }
  276. void SoftBodyMotionProperties::ApplyCollisionConstraintsAndUpdateVelocities(const SoftBodyUpdateContext &inContext)
  277. {
  278. JPH_PROFILE_FUNCTION();
  279. float dt = inContext.mSubStepDeltaTime;
  280. float restitution_treshold = -2.0f * inContext.mGravity.Length() * dt;
  281. float vertex_radius = mSettings->mVertexRadius;
  282. for (Vertex &v : mVertices)
  283. if (v.mInvMass > 0.0f)
  284. {
  285. // Remember previous velocity for restitution calculations
  286. Vec3 prev_v = v.mVelocity;
  287. // XPBD velocity update
  288. v.mVelocity = (v.mPosition - v.mPreviousPosition) / dt;
  289. // Satisfy collision constraint
  290. if (v.mCollidingShapeIndex >= 0)
  291. {
  292. // Check if there is a collision
  293. float projected_distance = -v.mCollisionPlane.SignedDistance(v.mPosition) + vertex_radius;
  294. if (projected_distance > 0.0f)
  295. {
  296. // Remember that there was a collision
  297. v.mHasContact = true;
  298. mHasContact = true;
  299. // Sensors should not have a collision response
  300. CollidingShape &cs = mCollidingShapes[v.mCollidingShapeIndex];
  301. if (!cs.mIsSensor)
  302. {
  303. // Note that we already calculated the velocity, so this does not affect the velocity (next iteration starts by setting previous position to current position)
  304. Vec3 contact_normal = v.mCollisionPlane.GetNormal();
  305. v.mPosition += contact_normal * projected_distance;
  306. // Apply friction as described in Detailed Rigid Body Simulation with Extended Position Based Dynamics - Matthias Muller et al.
  307. // See section 3.6:
  308. // Inverse mass: w1 = 1 / m1, w2 = 1 / m2 + (r2 x n)^T I^-1 (r2 x n) = 0 for a static object
  309. // r2 are the contact point relative to the center of mass of body 2
  310. // Lagrange multiplier for contact: lambda = -c / (w1 + w2)
  311. // Where c is the constraint equation (the distance to the plane, negative because penetrating)
  312. // Contact normal force: fn = lambda / dt^2
  313. // Delta velocity due to friction dv = -vt / |vt| * min(dt * friction * fn * (w1 + w2), |vt|) = -vt * min(-friction * c / (|vt| * dt), 1)
  314. // Note that I think there is an error in the paper, I added a mass term, see: https://github.com/matthias-research/pages/issues/29
  315. // Relative velocity: vr = v1 - v2 - omega2 x r2
  316. // Normal velocity: vn = vr . contact_normal
  317. // Tangential velocity: vt = vr - contact_normal * vn
  318. // Impulse: p = dv / (w1 + w2)
  319. // Changes in particle velocities:
  320. // v1 = v1 + p / m1
  321. // v2 = v2 - p / m2 (no change when colliding with a static body)
  322. // w2 = w2 - I^-1 (r2 x p) (no change when colliding with a static body)
  323. if (cs.mMotionType == EMotionType::Dynamic)
  324. {
  325. // Calculate normal and tangential velocity (equation 30)
  326. Vec3 r2 = v.mPosition - cs.mCenterOfMassTransform.GetTranslation();
  327. Vec3 v2 = cs.GetPointVelocity(r2);
  328. Vec3 relative_velocity = v.mVelocity - v2;
  329. Vec3 v_normal = contact_normal * contact_normal.Dot(relative_velocity);
  330. Vec3 v_tangential = relative_velocity - v_normal;
  331. float v_tangential_length = v_tangential.Length();
  332. // Calculate resulting inverse mass of vertex
  333. float vertex_inv_mass = cs.mSoftBodyInvMassScale * v.mInvMass;
  334. // Calculate inverse effective mass
  335. Vec3 r2_cross_n = r2.Cross(contact_normal);
  336. float w2 = cs.mInvMass + r2_cross_n.Dot(cs.mInvInertia * r2_cross_n);
  337. float w1_plus_w2 = vertex_inv_mass + w2;
  338. // Calculate delta relative velocity due to friction (modified equation 31)
  339. Vec3 dv;
  340. if (v_tangential_length > 0.0f)
  341. dv = v_tangential * min(cs.mFriction * projected_distance / (v_tangential_length * dt), 1.0f);
  342. else
  343. dv = Vec3::sZero();
  344. // Calculate delta relative velocity due to restitution (equation 35)
  345. dv += v_normal;
  346. float prev_v_normal = (prev_v - v2).Dot(contact_normal);
  347. if (prev_v_normal < restitution_treshold)
  348. dv += cs.mRestitution * prev_v_normal * contact_normal;
  349. // Calculate impulse
  350. Vec3 p = dv / w1_plus_w2;
  351. // Apply impulse to particle
  352. v.mVelocity -= p * vertex_inv_mass;
  353. // Apply impulse to rigid body
  354. cs.mLinearVelocity += p * cs.mInvMass;
  355. cs.mAngularVelocity += cs.mInvInertia * r2.Cross(p);
  356. // Mark that the velocities of the body we hit need to be updated
  357. cs.mUpdateVelocities = true;
  358. }
  359. else
  360. {
  361. // Body is not moveable, equations are simpler
  362. // Calculate normal and tangential velocity (equation 30)
  363. Vec3 v_normal = contact_normal * contact_normal.Dot(v.mVelocity);
  364. Vec3 v_tangential = v.mVelocity - v_normal;
  365. float v_tangential_length = v_tangential.Length();
  366. // Apply friction (modified equation 31)
  367. if (v_tangential_length > 0.0f)
  368. v.mVelocity -= v_tangential * min(cs.mFriction * projected_distance / (v_tangential_length * dt), 1.0f);
  369. // Apply restitution (equation 35)
  370. v.mVelocity -= v_normal;
  371. float prev_v_normal = prev_v.Dot(contact_normal);
  372. if (prev_v_normal < restitution_treshold)
  373. v.mVelocity -= cs.mRestitution * prev_v_normal * contact_normal;
  374. }
  375. }
  376. }
  377. }
  378. }
  379. }
  380. void SoftBodyMotionProperties::UpdateSoftBodyState(SoftBodyUpdateContext &ioContext, const PhysicsSettings &inPhysicsSettings)
  381. {
  382. JPH_PROFILE_FUNCTION();
  383. // Contact callback
  384. if (mHasContact && ioContext.mContactListener != nullptr)
  385. ioContext.mContactListener->OnSoftBodyContactAdded(*ioContext.mBody, SoftBodyManifold(this));
  386. // Loop through vertices once more to update the global state
  387. float dt = ioContext.mDeltaTime;
  388. float max_linear_velocity_sq = Square(GetMaxLinearVelocity());
  389. float max_v_sq = 0.0f;
  390. Vec3 linear_velocity = Vec3::sZero(), angular_velocity = Vec3::sZero();
  391. mLocalPredictedBounds = mLocalBounds = { };
  392. mHasContact = false;
  393. for (Vertex &v : mVertices)
  394. {
  395. // Calculate max square velocity
  396. float v_sq = v.mVelocity.LengthSq();
  397. max_v_sq = max(max_v_sq, v_sq);
  398. // Clamp if velocity is too high
  399. if (v_sq > max_linear_velocity_sq)
  400. v.mVelocity *= sqrt(max_linear_velocity_sq / v_sq);
  401. // Calculate local linear/angular velocity
  402. linear_velocity += v.mVelocity;
  403. angular_velocity += v.mPosition.Cross(v.mVelocity);
  404. // Update local bounding box
  405. mLocalBounds.Encapsulate(v.mPosition);
  406. // Create predicted position for the next frame in order to detect collisions before they happen
  407. mLocalPredictedBounds.Encapsulate(v.mPosition + v.mVelocity * dt + ioContext.mDisplacementDueToGravity);
  408. // Reset collision data for the next iteration
  409. v.mCollidingShapeIndex = -1;
  410. v.mHasContact = false;
  411. v.mLargestPenetration = -FLT_MAX;
  412. }
  413. // Calculate linear/angular velocity of the body by averaging all vertices and bringing the value to world space
  414. float num_vertices_divider = float(max(int(mVertices.size()), 1));
  415. SetLinearVelocity(ioContext.mCenterOfMassTransform.Multiply3x3(linear_velocity / num_vertices_divider));
  416. SetAngularVelocity(ioContext.mCenterOfMassTransform.Multiply3x3(angular_velocity / num_vertices_divider));
  417. if (mUpdatePosition)
  418. {
  419. // Shift the body so that the position is the center of the local bounds
  420. Vec3 delta = mLocalBounds.GetCenter();
  421. ioContext.mDeltaPosition = ioContext.mCenterOfMassTransform.Multiply3x3(delta);
  422. for (Vertex &v : mVertices)
  423. v.mPosition -= delta;
  424. // Offset bounds to match new position
  425. mLocalBounds.Translate(-delta);
  426. mLocalPredictedBounds.Translate(-delta);
  427. }
  428. else
  429. ioContext.mDeltaPosition = Vec3::sZero();
  430. // Test if we should go to sleep
  431. if (GetAllowSleeping())
  432. {
  433. if (max_v_sq > inPhysicsSettings.mPointVelocitySleepThreshold)
  434. {
  435. ResetSleepTestTimer();
  436. ioContext.mCanSleep = ECanSleep::CannotSleep;
  437. }
  438. else
  439. ioContext.mCanSleep = AccumulateSleepTime(dt, inPhysicsSettings.mTimeBeforeSleep);
  440. }
  441. else
  442. ioContext.mCanSleep = ECanSleep::CannotSleep;
  443. }
  444. void SoftBodyMotionProperties::UpdateRigidBodyVelocities(const SoftBodyUpdateContext &inContext, PhysicsSystem &inSystem)
  445. {
  446. JPH_PROFILE_FUNCTION();
  447. // Write back velocity deltas
  448. BodyInterface &body_interface = inSystem.GetBodyInterfaceNoLock();
  449. for (const CollidingShape &cs : mCollidingShapes)
  450. if (cs.mUpdateVelocities)
  451. body_interface.AddLinearAndAngularVelocity(cs.mBodyID, inContext.mCenterOfMassTransform.Multiply3x3(cs.mLinearVelocity - cs.mOriginalLinearVelocity), inContext.mCenterOfMassTransform.Multiply3x3(cs.mAngularVelocity - cs.mOriginalAngularVelocity));
  452. // Clear colliding shapes to avoid hanging on to references to shapes
  453. mCollidingShapes.clear();
  454. }
  455. void SoftBodyMotionProperties::InitializeUpdateContext(float inDeltaTime, Body &inSoftBody, const PhysicsSystem &inSystem, SoftBodyUpdateContext &ioContext)
  456. {
  457. JPH_PROFILE_FUNCTION();
  458. // Store body
  459. ioContext.mBody = &inSoftBody;
  460. ioContext.mMotionProperties = this;
  461. ioContext.mContactListener = inSystem.GetSoftBodyContactListener();
  462. // Convert gravity to local space
  463. ioContext.mCenterOfMassTransform = inSoftBody.GetCenterOfMassTransform();
  464. ioContext.mGravity = ioContext.mCenterOfMassTransform.Multiply3x3Transposed(GetGravityFactor() * inSystem.GetGravity());
  465. // Calculate delta time for sub step
  466. ioContext.mDeltaTime = inDeltaTime;
  467. ioContext.mSubStepDeltaTime = inDeltaTime / mNumIterations;
  468. // Calculate total displacement we'll have due to gravity over all sub steps
  469. // The total displacement as produced by our integrator can be written as: Sum(i * g * dt^2, i = 0..mNumIterations).
  470. // This is bigger than 0.5 * g * dt^2 because we first increment the velocity and then update the position
  471. // Using Sum(i, i = 0..n) = n * (n + 1) / 2 we can write this as:
  472. ioContext.mDisplacementDueToGravity = (0.5f * mNumIterations * (mNumIterations + 1) * Square(ioContext.mSubStepDeltaTime)) * ioContext.mGravity;
  473. }
  474. void SoftBodyMotionProperties::StartNextIteration(const SoftBodyUpdateContext &ioContext)
  475. {
  476. ApplyPressure(ioContext);
  477. IntegratePositions(ioContext);
  478. ApplyVolumeConstraints(ioContext);
  479. }
  480. SoftBodyMotionProperties::EStatus SoftBodyMotionProperties::ParallelDetermineCollisionPlanes(SoftBodyUpdateContext &ioContext)
  481. {
  482. // Do a relaxed read first to see if there is any work to do (this prevents us from doing expensive atomic operations and also prevents us from continuously incrementing the counter and overflowing it)
  483. uint num_vertices = (uint)mVertices.size();
  484. if (ioContext.mNextCollisionVertex.load(memory_order_relaxed) < num_vertices)
  485. {
  486. // Fetch next batch of vertices to process
  487. uint next_vertex = ioContext.mNextCollisionVertex.fetch_add(SoftBodyUpdateContext::cVertexCollisionBatch, memory_order_acquire);
  488. if (next_vertex < num_vertices)
  489. {
  490. // Process collision planes
  491. uint num_vertices_to_process = min(SoftBodyUpdateContext::cVertexCollisionBatch, num_vertices - next_vertex);
  492. DetermineCollisionPlanes(ioContext, next_vertex, num_vertices_to_process);
  493. uint vertices_processed = ioContext.mNumCollisionVerticesProcessed.fetch_add(SoftBodyUpdateContext::cVertexCollisionBatch, memory_order_release) + num_vertices_to_process;
  494. if (vertices_processed >= num_vertices)
  495. {
  496. // Start the first iteration
  497. JPH_IF_ENABLE_ASSERTS(uint iteration =) ioContext.mNextIteration.fetch_add(1, memory_order_relaxed);
  498. JPH_ASSERT(iteration == 0);
  499. StartNextIteration(ioContext);
  500. ioContext.mState.store(SoftBodyUpdateContext::EState::ApplyEdgeConstraints, memory_order_release);
  501. }
  502. return EStatus::DidWork;
  503. }
  504. }
  505. return EStatus::NoWork;
  506. }
  507. SoftBodyMotionProperties::EStatus SoftBodyMotionProperties::ParallelApplyEdgeConstraints(SoftBodyUpdateContext &ioContext, const PhysicsSettings &inPhysicsSettings)
  508. {
  509. // Do a relaxed read first to see if there is any work to do (this prevents us from doing expensive atomic operations and also prevents us from continuously incrementing the counter and overflowing it)
  510. uint num_groups = (uint)mSettings->mEdgeGroupEndIndices.size();
  511. JPH_ASSERT(num_groups > 0, "SoftBodySharedSettings::Optimize should have been called!");
  512. uint32 edge_group, edge_start_idx;
  513. SoftBodyUpdateContext::sGetEdgeGroupAndStartIdx(ioContext.mNextEdgeConstraint.load(memory_order_relaxed), edge_group, edge_start_idx);
  514. if (edge_group < num_groups)
  515. {
  516. uint edge_group_size = mSettings->GetEdgeGroupSize(edge_group);
  517. if (edge_start_idx < edge_group_size || edge_group_size == 0)
  518. {
  519. // Fetch the next batch of edges to process
  520. uint64 next_edge_batch = ioContext.mNextEdgeConstraint.fetch_add(SoftBodyUpdateContext::cEdgeConstraintBatch, memory_order_acquire);
  521. SoftBodyUpdateContext::sGetEdgeGroupAndStartIdx(next_edge_batch, edge_group, edge_start_idx);
  522. if (edge_group < num_groups)
  523. {
  524. bool non_parallel_group = edge_group == num_groups - 1; // Last group is the non-parallel group and goes as a whole
  525. edge_group_size = mSettings->GetEdgeGroupSize(edge_group);
  526. if (non_parallel_group? edge_start_idx == 0 : edge_start_idx < edge_group_size)
  527. {
  528. // Process edges
  529. uint num_edges_to_process = non_parallel_group? edge_group_size : min(SoftBodyUpdateContext::cEdgeConstraintBatch, edge_group_size - edge_start_idx);
  530. if (edge_group > 0)
  531. edge_start_idx += mSettings->mEdgeGroupEndIndices[edge_group - 1];
  532. ApplyEdgeConstraints(ioContext, edge_start_idx, edge_start_idx + num_edges_to_process);
  533. // Test if we're at the end of this group
  534. uint edge_constraints_processed = ioContext.mNumEdgeConstraintsProcessed.fetch_add(num_edges_to_process, memory_order_relaxed) + num_edges_to_process;
  535. if (edge_constraints_processed >= edge_group_size)
  536. {
  537. // Non parallel group is the last group (which is also the only group that can be empty)
  538. if (non_parallel_group || mSettings->GetEdgeGroupSize(edge_group + 1) == 0)
  539. {
  540. // Finish the iteration
  541. ApplyCollisionConstraintsAndUpdateVelocities(ioContext);
  542. uint iteration = ioContext.mNextIteration.fetch_add(1, memory_order_relaxed);
  543. if (iteration < mNumIterations)
  544. {
  545. // Start a new iteration
  546. StartNextIteration(ioContext);
  547. // Reset next edge to process
  548. ioContext.mNumEdgeConstraintsProcessed.store(0, memory_order_relaxed);
  549. ioContext.mNextEdgeConstraint.store(0, memory_order_release);
  550. }
  551. else
  552. {
  553. // On final iteration we update the state
  554. UpdateSoftBodyState(ioContext, inPhysicsSettings);
  555. ioContext.mState.store(SoftBodyUpdateContext::EState::Done, memory_order_release);
  556. return EStatus::Done;
  557. }
  558. }
  559. else
  560. {
  561. // Next group
  562. ioContext.mNumEdgeConstraintsProcessed.store(0, memory_order_relaxed);
  563. ioContext.mNextEdgeConstraint.store(SoftBodyUpdateContext::sGetEdgeGroupStart(edge_group + 1), memory_order_release);
  564. }
  565. }
  566. return EStatus::DidWork;
  567. }
  568. }
  569. }
  570. }
  571. return EStatus::NoWork;
  572. }
  573. SoftBodyMotionProperties::EStatus SoftBodyMotionProperties::ParallelUpdate(SoftBodyUpdateContext &ioContext, const PhysicsSettings &inPhysicsSettings)
  574. {
  575. switch (ioContext.mState.load(memory_order_relaxed))
  576. {
  577. case SoftBodyUpdateContext::EState::DetermineCollisionPlanes:
  578. return ParallelDetermineCollisionPlanes(ioContext);
  579. case SoftBodyUpdateContext::EState::ApplyEdgeConstraints:
  580. return ParallelApplyEdgeConstraints(ioContext, inPhysicsSettings);
  581. case SoftBodyUpdateContext::EState::Done:
  582. return EStatus::Done;
  583. default:
  584. JPH_ASSERT(false);
  585. return EStatus::NoWork;
  586. }
  587. }
  588. #ifdef JPH_DEBUG_RENDERER
  589. void SoftBodyMotionProperties::DrawVertices(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform) const
  590. {
  591. for (const Vertex &v : mVertices)
  592. inRenderer->DrawMarker(inCenterOfMassTransform * v.mPosition, v.mInvMass > 0.0f? Color::sGreen : Color::sRed, 0.05f);
  593. }
  594. void SoftBodyMotionProperties::DrawEdgeConstraints(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform) const
  595. {
  596. for (const Edge &e : mSettings->mEdgeConstraints)
  597. inRenderer->DrawLine(inCenterOfMassTransform * mVertices[e.mVertex[0]].mPosition, inCenterOfMassTransform * mVertices[e.mVertex[1]].mPosition, Color::sWhite);
  598. }
  599. void SoftBodyMotionProperties::DrawVolumeConstraints(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform) const
  600. {
  601. for (const Volume &v : mSettings->mVolumeConstraints)
  602. {
  603. RVec3 x1 = inCenterOfMassTransform * mVertices[v.mVertex[0]].mPosition;
  604. RVec3 x2 = inCenterOfMassTransform * mVertices[v.mVertex[1]].mPosition;
  605. RVec3 x3 = inCenterOfMassTransform * mVertices[v.mVertex[2]].mPosition;
  606. RVec3 x4 = inCenterOfMassTransform * mVertices[v.mVertex[3]].mPosition;
  607. inRenderer->DrawTriangle(x1, x3, x2, Color::sYellow, DebugRenderer::ECastShadow::On);
  608. inRenderer->DrawTriangle(x2, x3, x4, Color::sYellow, DebugRenderer::ECastShadow::On);
  609. inRenderer->DrawTriangle(x1, x4, x3, Color::sYellow, DebugRenderer::ECastShadow::On);
  610. inRenderer->DrawTriangle(x1, x2, x4, Color::sYellow, DebugRenderer::ECastShadow::On);
  611. }
  612. }
  613. void SoftBodyMotionProperties::DrawPredictedBounds(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform) const
  614. {
  615. inRenderer->DrawWireBox(inCenterOfMassTransform, mLocalPredictedBounds, Color::sRed);
  616. }
  617. #endif // JPH_DEBUG_RENDERER
  618. void SoftBodyMotionProperties::SaveState(StateRecorder &inStream) const
  619. {
  620. MotionProperties::SaveState(inStream);
  621. for (const Vertex &v : mVertices)
  622. {
  623. inStream.Write(v.mPreviousPosition);
  624. inStream.Write(v.mPosition);
  625. inStream.Write(v.mVelocity);
  626. }
  627. inStream.Write(mLocalBounds.mMin);
  628. inStream.Write(mLocalBounds.mMax);
  629. inStream.Write(mLocalPredictedBounds.mMin);
  630. inStream.Write(mLocalPredictedBounds.mMax);
  631. }
  632. void SoftBodyMotionProperties::RestoreState(StateRecorder &inStream)
  633. {
  634. MotionProperties::RestoreState(inStream);
  635. for (Vertex &v : mVertices)
  636. {
  637. inStream.Read(v.mPreviousPosition);
  638. inStream.Read(v.mPosition);
  639. inStream.Read(v.mVelocity);
  640. }
  641. inStream.Read(mLocalBounds.mMin);
  642. inStream.Read(mLocalBounds.mMax);
  643. inStream.Read(mLocalPredictedBounds.mMin);
  644. inStream.Read(mLocalPredictedBounds.mMax);
  645. }
  646. JPH_NAMESPACE_END