DualAxisConstraintPart.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Physics/Body/Body.h>
  5. #include <Jolt/Physics/StateRecorder.h>
  6. #include <Jolt/Math/Vector.h>
  7. #include <Jolt/Math/Matrix.h>
  8. JPH_NAMESPACE_BEGIN
  9. /// Constrains movement on 2 axis
  10. ///
  11. /// @see "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.3.1
  12. ///
  13. /// Constraint equation (eq 51):
  14. ///
  15. /// \f[C = \begin{bmatrix} (p_2 - p_1) \cdot n_1 \\ (p_2 - p_1) \cdot n_2\end{bmatrix}\f]
  16. ///
  17. /// Jacobian (transposed) (eq 55):
  18. ///
  19. /// \f[J^T = \begin{bmatrix}
  20. /// -n_1 & -n_2 \\
  21. /// -(r_1 + u) \times n_1 & -(r_1 + u) \times n_2 \\
  22. /// n_1 & n_2 \\
  23. /// r_2 \times n_1 & r_2 \times n_2
  24. /// \end{bmatrix}\f]
  25. ///
  26. /// Used terms (here and below, everything in world space):\n
  27. /// n1, n2 = constraint axis (normalized).\n
  28. /// p1, p2 = constraint points.\n
  29. /// r1 = p1 - x1.\n
  30. /// r2 = p2 - x2.\n
  31. /// u = x2 + r2 - x1 - r1 = p2 - p1.\n
  32. /// x1, x2 = center of mass for the bodies.\n
  33. /// v = [v1, w1, v2, w2].\n
  34. /// v1, v2 = linear velocity of body 1 and 2.\n
  35. /// w1, w2 = angular velocity of body 1 and 2.\n
  36. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  37. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  38. /// b = velocity bias.\n
  39. /// \f$\beta\f$ = baumgarte constant.
  40. class DualAxisConstraintPart
  41. {
  42. public:
  43. using Vec2 = Vector<2>;
  44. using Mat22 = Matrix<2, 2>;
  45. private:
  46. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  47. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, const Vec2 &inLambda) const
  48. {
  49. // Apply impulse if delta is not zero
  50. if (!inLambda.IsZero())
  51. {
  52. // Calculate velocity change due to constraint
  53. //
  54. // Impulse:
  55. // P = J^T lambda
  56. //
  57. // Euler velocity integration:
  58. // v' = v + M^-1 P
  59. Vec3 impulse = inN1 * inLambda[0] + inN2 * inLambda[1];
  60. if (ioBody1.IsDynamic())
  61. {
  62. MotionProperties *mp1 = ioBody1.GetMotionProperties();
  63. mp1->SubLinearVelocityStep(mp1->GetInverseMass() * impulse);
  64. mp1->SubAngularVelocityStep(mInvI1_R1PlusUxN1 * inLambda[0] + mInvI1_R1PlusUxN2 * inLambda[1]);
  65. }
  66. if (ioBody2.IsDynamic())
  67. {
  68. MotionProperties *mp2 = ioBody2.GetMotionProperties();
  69. mp2->AddLinearVelocityStep(mp2->GetInverseMass() * impulse);
  70. mp2->AddAngularVelocityStep(mInvI2_R2xN1 * inLambda[0] + mInvI2_R2xN2 * inLambda[1]);
  71. }
  72. return true;
  73. }
  74. return false;
  75. }
  76. /// Internal helper function to calculate the lagrange multiplier
  77. inline void CalculateLagrangeMultiplier(const Body &inBody1, const Body &inBody2, Vec3Arg inN1, Vec3Arg inN2, Vec2 &outLambda) const
  78. {
  79. // Calculate lagrange multiplier:
  80. //
  81. // lambda = -K^-1 (J v + b)
  82. Vec3 delta_lin = inBody1.GetLinearVelocity() - inBody2.GetLinearVelocity();
  83. Vec2 jv;
  84. jv[0] = inN1.Dot(delta_lin) + mR1PlusUxN1.Dot(inBody1.GetAngularVelocity()) - mR2xN1.Dot(inBody2.GetAngularVelocity());
  85. jv[1] = inN2.Dot(delta_lin) + mR1PlusUxN2.Dot(inBody1.GetAngularVelocity()) - mR2xN2.Dot(inBody2.GetAngularVelocity());
  86. outLambda = mEffectiveMass * jv;
  87. }
  88. public:
  89. /// Calculate properties used during the functions below
  90. /// All input vectors are in world space
  91. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inR1PlusU, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inR2, Vec3Arg inN1, Vec3Arg inN2)
  92. {
  93. JPH_ASSERT(inN1.IsNormalized(1.0e-5f));
  94. JPH_ASSERT(inN2.IsNormalized(1.0e-5f));
  95. // Calculate properties used during constraint solving
  96. mR1PlusUxN1 = inR1PlusU.Cross(inN1);
  97. mR1PlusUxN2 = inR1PlusU.Cross(inN2);
  98. mR2xN1 = inR2.Cross(inN1);
  99. mR2xN2 = inR2.Cross(inN2);
  100. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1, eq 59
  101. Mat22 inv_effective_mass;
  102. if (inBody1.IsDynamic())
  103. {
  104. const MotionProperties *mp1 = inBody1.GetMotionProperties();
  105. Mat44 inv_i1 = mp1->GetInverseInertiaForRotation(inRotation1);
  106. mInvI1_R1PlusUxN1 = inv_i1.Multiply3x3(mR1PlusUxN1);
  107. mInvI1_R1PlusUxN2 = inv_i1.Multiply3x3(mR1PlusUxN2);
  108. inv_effective_mass(0, 0) = mp1->GetInverseMass() + mR1PlusUxN1.Dot(mInvI1_R1PlusUxN1);
  109. inv_effective_mass(0, 1) = mR1PlusUxN1.Dot(mInvI1_R1PlusUxN2);
  110. inv_effective_mass(1, 0) = mR1PlusUxN2.Dot(mInvI1_R1PlusUxN1);
  111. inv_effective_mass(1, 1) = mp1->GetInverseMass() + mR1PlusUxN2.Dot(mInvI1_R1PlusUxN2);
  112. }
  113. else
  114. {
  115. JPH_IF_DEBUG(mInvI1_R1PlusUxN1 = Vec3::sNaN();)
  116. JPH_IF_DEBUG(mInvI1_R1PlusUxN2 = Vec3::sNaN();)
  117. inv_effective_mass = Mat22::sZero();
  118. }
  119. if (inBody2.IsDynamic())
  120. {
  121. const MotionProperties *mp2 = inBody2.GetMotionProperties();
  122. Mat44 inv_i2 = mp2->GetInverseInertiaForRotation(inRotation2);
  123. mInvI2_R2xN1 = inv_i2.Multiply3x3(mR2xN1);
  124. mInvI2_R2xN2 = inv_i2.Multiply3x3(mR2xN2);
  125. inv_effective_mass(0, 0) += mp2->GetInverseMass() + mR2xN1.Dot(mInvI2_R2xN1);
  126. inv_effective_mass(0, 1) += mR2xN1.Dot(mInvI2_R2xN2);
  127. inv_effective_mass(1, 0) += mR2xN2.Dot(mInvI2_R2xN1);
  128. inv_effective_mass(1, 1) += mp2->GetInverseMass() + mR2xN2.Dot(mInvI2_R2xN2);
  129. }
  130. else
  131. {
  132. JPH_IF_DEBUG(mInvI2_R2xN1 = Vec3::sNaN();)
  133. JPH_IF_DEBUG(mInvI2_R2xN2 = Vec3::sNaN();)
  134. }
  135. if (!mEffectiveMass.SetInversed(inv_effective_mass))
  136. {
  137. JPH_ASSERT(false, "Determinant is zero!");
  138. Deactivate();
  139. }
  140. }
  141. /// Deactivate this constraint
  142. inline void Deactivate()
  143. {
  144. mEffectiveMass.SetZero();
  145. mTotalLambda.SetZero();
  146. }
  147. /// Check if constraint is active
  148. inline bool IsActive() const
  149. {
  150. return !mEffectiveMass.IsZero();
  151. }
  152. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  153. /// All input vectors are in world space
  154. inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inWarmStartImpulseRatio)
  155. {
  156. mTotalLambda *= inWarmStartImpulseRatio;
  157. ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, mTotalLambda);
  158. }
  159. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  160. /// All input vectors are in world space
  161. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2)
  162. {
  163. Vec2 lambda;
  164. CalculateLagrangeMultiplier(ioBody1, ioBody2, inN1, inN2, lambda);
  165. // Store accumulated lambda
  166. mTotalLambda += lambda;
  167. return ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, lambda);
  168. }
  169. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  170. /// All input vectors are in world space
  171. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inU, Vec3Arg inN1, Vec3Arg inN2, float inBaumgarte) const
  172. {
  173. Vec2 c;
  174. c[0] = inU.Dot(inN1);
  175. c[1] = inU.Dot(inN2);
  176. if (!c.IsZero())
  177. {
  178. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  179. //
  180. // lambda = -K^-1 * beta / dt * C
  181. //
  182. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  183. Vec2 lambda = -inBaumgarte * (mEffectiveMass * c);
  184. // Directly integrate velocity change for one time step
  185. //
  186. // Euler velocity integration:
  187. // dv = M^-1 P
  188. //
  189. // Impulse:
  190. // P = J^T lambda
  191. //
  192. // Euler position integration:
  193. // x' = x + dv * dt
  194. //
  195. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  196. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  197. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  198. // integrate + a position integrate and then discard the velocity change.
  199. Vec3 impulse = inN1 * lambda[0] + inN2 * lambda[1];
  200. if (ioBody1.IsDynamic())
  201. {
  202. ioBody1.SubPositionStep(ioBody1.GetMotionProperties()->GetInverseMass() * impulse);
  203. ioBody1.SubRotationStep(mInvI1_R1PlusUxN1 * lambda[0] + mInvI1_R1PlusUxN2 * lambda[1]);
  204. }
  205. if (ioBody2.IsDynamic())
  206. {
  207. ioBody2.AddPositionStep(ioBody2.GetMotionProperties()->GetInverseMass() * impulse);
  208. ioBody2.AddRotationStep(mInvI2_R2xN1 * lambda[0] + mInvI2_R2xN2 * lambda[1]);
  209. }
  210. return true;
  211. }
  212. return false;
  213. }
  214. /// Override total lagrange multiplier, can be used to set the initial value for warm starting
  215. inline void SetTotalLambda(const Vec2 &inLambda)
  216. {
  217. mTotalLambda = inLambda;
  218. }
  219. /// Return lagrange multiplier
  220. inline const Vec2 & GetTotalLambda() const
  221. {
  222. return mTotalLambda;
  223. }
  224. /// Save state of this constraint part
  225. void SaveState(StateRecorder &inStream) const
  226. {
  227. inStream.Write(mTotalLambda);
  228. }
  229. /// Restore state of this constraint part
  230. void RestoreState(StateRecorder &inStream)
  231. {
  232. inStream.Read(mTotalLambda);
  233. }
  234. private:
  235. Vec3 mR1PlusUxN1;
  236. Vec3 mR1PlusUxN2;
  237. Vec3 mR2xN1;
  238. Vec3 mR2xN2;
  239. Vec3 mInvI1_R1PlusUxN1;
  240. Vec3 mInvI1_R1PlusUxN2;
  241. Vec3 mInvI2_R2xN1;
  242. Vec3 mInvI2_R2xN2;
  243. Mat22 mEffectiveMass;
  244. Vec2 mTotalLambda { Vec2::sZero() };
  245. };
  246. JPH_NAMESPACE_END