HingeRotationConstraintPart.h 7.4 KB

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