GearConstraintPart.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. JPH_NAMESPACE_BEGIN
  7. /// Constraint that constrains two rotations using a gear (rotating in opposite direction)
  8. ///
  9. /// Constraint equation:
  10. ///
  11. /// C = Rotation1(t) + r Rotation2(t)
  12. ///
  13. /// Derivative:
  14. ///
  15. /// d/dt C = 0
  16. /// <=> w1 . a + r w2 . b = 0
  17. ///
  18. /// Jacobian:
  19. ///
  20. /// \f[J = \begin{bmatrix}0 & a^T & 0 & r b^T\end{bmatrix}\f]
  21. ///
  22. /// Used terms (here and below, everything in world space):\n
  23. /// a = axis around which body 1 rotates (normalized).\n
  24. /// b = axis along which body 2 slides (normalized).\n
  25. /// Rotation1(t) = rotation around a of body 1.\n
  26. /// Rotation2(t) = rotation around b of body 2.\n
  27. /// r = ratio between rotation for body 1 and 2.\n
  28. /// v = [v1, w1, v2, w2].\n
  29. /// v1, v2 = linear velocity of body 1 and 2.\n
  30. /// w1, w2 = angular velocity of body 1 and 2.\n
  31. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  32. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  33. /// \f$\beta\f$ = baumgarte constant.
  34. class GearConstraintPart
  35. {
  36. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  37. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const
  38. {
  39. // Apply impulse if delta is not zero
  40. if (inLambda != 0.0f)
  41. {
  42. // Calculate velocity change due to constraint
  43. //
  44. // Impulse:
  45. // P = J^T lambda
  46. //
  47. // Euler velocity integration:
  48. // v' = v + M^-1 P
  49. ioBody1.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI1_A);
  50. ioBody2.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI2_B);
  51. return true;
  52. }
  53. return false;
  54. }
  55. public:
  56. /// Calculate properties used during the functions below
  57. /// @param inBody1 The first body that this constraint is attached to
  58. /// @param inBody2 The second body that this constraint is attached to
  59. /// @param inWorldSpaceHingeAxis1 The axis around which body 1 rotates
  60. /// @param inWorldSpaceHingeAxis2 The axis around which body 2 rotates
  61. /// @param inRatio The ratio between rotation and translation
  62. inline void CalculateConstraintProperties(const Body &inBody1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Vec3Arg inWorldSpaceHingeAxis2, float inRatio)
  63. {
  64. JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-4f));
  65. JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-4f));
  66. // Calculate: I1^-1 a
  67. mInvI1_A = inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceHingeAxis1);
  68. // Calculate: I2^-1 b
  69. mInvI2_B = inBody2.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), inWorldSpaceHingeAxis2);
  70. // K^-1 = 1 / (J M^-1 J^T) = 1 / (a^T I1^-1 a + r^2 * b^T I2^-1 b)
  71. mEffectiveMass = 1.0f / (inWorldSpaceHingeAxis1.Dot(mInvI1_A) + inWorldSpaceHingeAxis2.Dot(mInvI2_B) * Square(inRatio));
  72. }
  73. /// Deactivate this constraint
  74. inline void Deactivate()
  75. {
  76. mEffectiveMass = 0.0f;
  77. mTotalLambda = 0.0f;
  78. }
  79. /// Check if constraint is active
  80. inline bool IsActive() const
  81. {
  82. return mEffectiveMass != 0.0f;
  83. }
  84. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  85. /// @param ioBody1 The first body that this constraint is attached to
  86. /// @param ioBody2 The second body that this constraint is attached to
  87. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  88. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  89. {
  90. mTotalLambda *= inWarmStartImpulseRatio;
  91. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  92. }
  93. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  94. /// @param ioBody1 The first body that this constraint is attached to
  95. /// @param ioBody2 The second body that this constraint is attached to
  96. /// @param inWorldSpaceHingeAxis1 The axis around which body 1 rotates
  97. /// @param inWorldSpaceHingeAxis2 The axis around which body 2 rotates
  98. /// @param inRatio The ratio between rotation and translation
  99. inline bool SolveVelocityConstraint(Body &ioBody1, Vec3Arg inWorldSpaceHingeAxis1, Body &ioBody2, Vec3Arg inWorldSpaceHingeAxis2, float inRatio)
  100. {
  101. // Lagrange multiplier is:
  102. //
  103. // lambda = -K^-1 (J v + b)
  104. float lambda = -mEffectiveMass * (inWorldSpaceHingeAxis1.Dot(ioBody1.GetAngularVelocity()) + inRatio * inWorldSpaceHingeAxis2.Dot(ioBody2.GetAngularVelocity()));
  105. mTotalLambda += lambda; // Store accumulated impulse
  106. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  107. }
  108. /// Return lagrange multiplier
  109. float GetTotalLambda() const
  110. {
  111. return mTotalLambda;
  112. }
  113. /// Iteratively update the position constraint. Makes sure C(...) == 0.
  114. /// @param ioBody1 The first body that this constraint is attached to
  115. /// @param ioBody2 The second body that this constraint is attached to
  116. /// @param inC Value of the constraint equation (C)
  117. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  118. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const
  119. {
  120. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  121. if (inC != 0.0f)
  122. {
  123. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  124. //
  125. // lambda = -K^-1 * beta / dt * C
  126. //
  127. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  128. float lambda = -mEffectiveMass * inBaumgarte * inC;
  129. // Directly integrate velocity change for one time step
  130. //
  131. // Euler velocity integration:
  132. // dv = M^-1 P
  133. //
  134. // Impulse:
  135. // P = J^T lambda
  136. //
  137. // Euler position integration:
  138. // x' = x + dv * dt
  139. //
  140. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  141. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  142. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  143. // integrate + a position integrate and then discard the velocity change.
  144. if (ioBody1.IsDynamic())
  145. ioBody1.AddRotationStep(lambda * mInvI1_A);
  146. if (ioBody2.IsDynamic())
  147. ioBody2.AddRotationStep(lambda * mInvI2_B);
  148. return true;
  149. }
  150. return false;
  151. }
  152. /// Save state of this constraint part
  153. void SaveState(StateRecorder &inStream) const
  154. {
  155. inStream.Write(mTotalLambda);
  156. }
  157. /// Restore state of this constraint part
  158. void RestoreState(StateRecorder &inStream)
  159. {
  160. inStream.Read(mTotalLambda);
  161. }
  162. private:
  163. Vec3 mInvI1_A;
  164. Vec3 mInvI2_B;
  165. float mEffectiveMass = 0.0f;
  166. float mTotalLambda = 0.0f;
  167. };
  168. JPH_NAMESPACE_END