HingeRotationConstraintPart.h 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Body/Body.h>
  6. #include <Jolt/Physics/StateRecorder.h>
  7. #include <Jolt/Math/Vector.h>
  8. #include <Jolt/Math/Matrix.h>
  9. JPH_NAMESPACE_BEGIN
  10. /**
  11. Constrains rotation around 2 axis so that it only allows rotation around 1 axis
  12. Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.4.1
  13. Constraint equation (eq 87):
  14. \f[C = \begin{bmatrix}a_1 \cdot b_2 \\ a_1 \cdot c_2\end{bmatrix}\f]
  15. Jacobian (eq 90):
  16. \f[J = \begin{bmatrix}
  17. 0 & -b_2 \times a_1 & 0 & b_2 \times a_1 \\
  18. 0 & -c_2 \times a_1 & 0 & c2 \times a_1
  19. \end{bmatrix}\f]
  20. Used terms (here and below, everything in world space):\n
  21. a1 = hinge axis on body 1.\n
  22. b2, c2 = axis perpendicular to hinge axis on body 2.\n
  23. x1, x2 = center of mass for the bodies.\n
  24. v = [v1, w1, v2, w2].\n
  25. v1, v2 = linear velocity of body 1 and 2.\n
  26. w1, w2 = angular velocity of body 1 and 2.\n
  27. M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  28. \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  29. b = velocity bias.\n
  30. \f$\beta\f$ = baumgarte constant.\n
  31. E = identity matrix.
  32. **/
  33. class HingeRotationConstraintPart
  34. {
  35. public:
  36. using Vec2 = Vector<2>;
  37. using Mat22 = Matrix<2, 2>;
  38. private:
  39. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  40. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, const Vec2 &inLambda) const
  41. {
  42. // Apply impulse if delta is not zero
  43. if (!inLambda.IsZero())
  44. {
  45. // Calculate velocity change due to constraint
  46. //
  47. // Impulse:
  48. // P = J^T lambda
  49. //
  50. // Euler velocity integration:
  51. // v' = v + M^-1 P
  52. Vec3 impulse = mB2xA1 * inLambda[0] + mC2xA1 * inLambda[1];
  53. if (ioBody1.IsDynamic())
  54. ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1.Multiply3x3(impulse));
  55. if (ioBody2.IsDynamic())
  56. ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2.Multiply3x3(impulse));
  57. return true;
  58. }
  59. return false;
  60. }
  61. public:
  62. /// Calculate properties used during the functions below
  63. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inWorldSpaceHingeAxis2)
  64. {
  65. JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-5f));
  66. JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-5f));
  67. // Calculate hinge axis in world space
  68. mA1 = inWorldSpaceHingeAxis1;
  69. Vec3 a2 = inWorldSpaceHingeAxis2;
  70. float dot = mA1.Dot(a2);
  71. if (dot <= 1.0e-3f)
  72. {
  73. // World space axes are more than 90 degrees apart, get a perpendicular vector in the plane formed by mA1 and a2 as hinge axis until the rotation is less than 90 degrees
  74. Vec3 perp = a2 - dot * mA1;
  75. if (perp.LengthSq() < 1.0e-6f)
  76. {
  77. // mA1 ~ -a2, take random perpendicular
  78. perp = mA1.GetNormalizedPerpendicular();
  79. }
  80. // Blend in a little bit from mA1 so we're less than 90 degrees apart
  81. a2 = (0.99f * perp.Normalized() + 0.01f * mA1).Normalized();
  82. }
  83. mB2 = a2.GetNormalizedPerpendicular();
  84. mC2 = a2.Cross(mB2);
  85. // Calculate properties used during constraint solving
  86. mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
  87. mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
  88. mB2xA1 = mB2.Cross(mA1);
  89. mC2xA1 = mC2.Cross(mA1);
  90. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
  91. Mat44 summed_inv_inertia = mInvI1 + mInvI2;
  92. Mat22 inv_effective_mass;
  93. inv_effective_mass(0, 0) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
  94. inv_effective_mass(0, 1) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
  95. inv_effective_mass(1, 0) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
  96. inv_effective_mass(1, 1) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
  97. if (!mEffectiveMass.SetInversed(inv_effective_mass))
  98. Deactivate();
  99. }
  100. /// Deactivate this constraint
  101. inline void Deactivate()
  102. {
  103. mEffectiveMass.SetZero();
  104. mTotalLambda.SetZero();
  105. }
  106. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  107. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  108. {
  109. mTotalLambda *= inWarmStartImpulseRatio;
  110. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  111. }
  112. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  113. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  114. {
  115. // Calculate lagrange multiplier:
  116. //
  117. // lambda = -K^-1 (J v + b)
  118. Vec3 delta_ang = ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity();
  119. Vec2 jv;
  120. jv[0] = mB2xA1.Dot(delta_ang);
  121. jv[1] = mC2xA1.Dot(delta_ang);
  122. Vec2 lambda = mEffectiveMass * jv;
  123. // Store accumulated lambda
  124. mTotalLambda += lambda;
  125. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  126. }
  127. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  128. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
  129. {
  130. // Constraint needs Axis of body 1 perpendicular to both B and C from body 2 (which are both perpendicular to the Axis of body 2)
  131. Vec2 c;
  132. c[0] = mA1.Dot(mB2);
  133. c[1] = mA1.Dot(mC2);
  134. if (!c.IsZero())
  135. {
  136. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  137. //
  138. // lambda = -K^-1 * beta / dt * C
  139. //
  140. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  141. Vec2 lambda = -inBaumgarte * (mEffectiveMass * c);
  142. // Directly integrate velocity change for one time step
  143. //
  144. // Euler velocity integration:
  145. // dv = M^-1 P
  146. //
  147. // Impulse:
  148. // P = J^T lambda
  149. //
  150. // Euler position integration:
  151. // x' = x + dv * dt
  152. //
  153. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  154. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  155. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  156. // integrate + a position integrate and then discard the velocity change.
  157. Vec3 impulse = mB2xA1 * lambda[0] + mC2xA1 * lambda[1];
  158. if (ioBody1.IsDynamic())
  159. ioBody1.SubRotationStep(mInvI1.Multiply3x3(impulse));
  160. if (ioBody2.IsDynamic())
  161. ioBody2.AddRotationStep(mInvI2.Multiply3x3(impulse));
  162. return true;
  163. }
  164. return false;
  165. }
  166. /// Return lagrange multiplier
  167. const Vec2 & GetTotalLambda() const
  168. {
  169. return mTotalLambda;
  170. }
  171. /// Save state of this constraint part
  172. void SaveState(StateRecorder &inStream) const
  173. {
  174. inStream.Write(mTotalLambda);
  175. }
  176. /// Restore state of this constraint part
  177. void RestoreState(StateRecorder &inStream)
  178. {
  179. inStream.Read(mTotalLambda);
  180. }
  181. private:
  182. Vec3 mA1; ///< World space hinge axis for body 1
  183. Vec3 mB2; ///< World space perpendiculars of hinge axis for body 2
  184. Vec3 mC2;
  185. Mat44 mInvI1;
  186. Mat44 mInvI2;
  187. Vec3 mB2xA1;
  188. Vec3 mC2xA1;
  189. Mat22 mEffectiveMass;
  190. Vec2 mTotalLambda { Vec2::sZero() };
  191. };
  192. JPH_NAMESPACE_END