RotationQuatConstraintPart.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. /// Quaternion based constraint that constrains rotation around all axis so that only translation is allowed.
  8. ///
  9. /// NOTE: This constraint part is more expensive than the RotationEulerConstraintPart and slightly more correct since
  10. /// RotationEulerConstraintPart::SolvePositionConstraint contains an approximation. In practice the difference
  11. /// is small, so the RotationEulerConstraintPart is probably the better choice.
  12. ///
  13. /// Rotation is fixed between bodies like this:
  14. ///
  15. /// q2 = q1 r0
  16. ///
  17. /// Where:
  18. /// q1, q2 = world space quaternions representing rotation of body 1 and 2.
  19. /// r0 = initial rotation between bodies in local space of body 1, this can be calculated by:
  20. ///
  21. /// q20 = q10 r0
  22. /// <=> r0 = q10^* q20
  23. ///
  24. /// Where:
  25. /// q10, q20 = initial world space rotations of body 1 and 2.
  26. /// q10^* = conjugate of quaternion q10 (which is the same as the inverse for a unit quaternion)
  27. ///
  28. /// We exclusively use the conjugate below:
  29. ///
  30. /// r0^* = q20^* q10
  31. ///
  32. /// The error in the rotation is (in local space of body 1):
  33. ///
  34. /// q2 = q1 error r0
  35. /// <=> error = q1^* q2 r0^*
  36. ///
  37. /// The imaginary part of the quaternion represents the rotation axis * sin(angle / 2). The real part of the quaternion
  38. /// does not add any additional information (we know the quaternion in normalized) and we're removing 3 degrees of freedom
  39. /// so we want 3 parameters. Therefore we define the constraint equation like:
  40. ///
  41. /// C = A q1^* q2 r0^* = 0
  42. ///
  43. /// Where (if you write a quaternion as [real-part, i-part, j-part, k-part]):
  44. ///
  45. /// [0, 1, 0, 0]
  46. /// A = [0, 0, 1, 0]
  47. /// [0, 0, 0, 1]
  48. ///
  49. /// or in our case since we store a quaternion like [i-part, j-part, k-part, real-part]:
  50. ///
  51. /// [1, 0, 0, 0]
  52. /// A = [0, 1, 0, 0]
  53. /// [0, 0, 1, 0]
  54. ///
  55. /// Time derivative:
  56. ///
  57. /// d/dt C = A (q1^* d/dt(q2) + d/dt(q1^*) q2) r0^*
  58. /// = A (q1^* (1/2 W2 q2) + (1/2 W1 q1)^* q2) r0^*
  59. /// = 1/2 A (q1^* W2 q2 + q1^* W1^* q2) r0^*
  60. /// = 1/2 A (q1^* W2 q2 - q1^* W1 * q2) r0^*
  61. /// = 1/2 A ML(q1^*) MR(q2 r0^*) (W2 - W1)
  62. /// = 1/2 A ML(q1^*) MR(q2 r0^*) A^T (w2 - w1)
  63. ///
  64. /// Where:
  65. /// W1 = [0, w1], W2 = [0, w2] (converting angular velocity to imaginary part of quaternion).
  66. /// w1, w2 = angular velocity of body 1 and 2.
  67. /// d/dt(q) = 1/2 W q (time derivative of a quaternion).
  68. /// W^* = -W (conjugate negates angular velocity as quaternion).
  69. /// ML(q): 4x4 matrix so that q * p = ML(q) * p, where q and p are quaternions.
  70. /// MR(p): 4x4 matrix so that q * p = MR(p) * q, where q and p are quaternions.
  71. /// A^T: Transpose of A.
  72. ///
  73. /// Jacobian:
  74. ///
  75. /// J = [0, -1/2 A ML(q1^*) MR(q2 r0^*) A^T, 0, 1/2 A ML(q1^*) MR(q2 r0^*) A^T]
  76. /// = [0, -JP, 0, JP]
  77. ///
  78. /// Suggested reading:
  79. /// - 3D Constraint Derivations for Impulse Solvers - Marijn Tamis
  80. /// - Game Physics Pearls - Section 9 - Quaternion Based Constraints - Claude Lacoursiere
  81. class RotationQuatConstraintPart
  82. {
  83. private:
  84. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  85. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const
  86. {
  87. // Apply impulse if delta is not zero
  88. if (inLambda != Vec3::sZero())
  89. {
  90. // Calculate velocity change due to constraint
  91. //
  92. // Impulse:
  93. // P = J^T lambda
  94. //
  95. // Euler velocity integration:
  96. // v' = v + M^-1 P
  97. if (ioBody1.IsDynamic())
  98. ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1_JPT.Multiply3x3(inLambda));
  99. if (ioBody2.IsDynamic())
  100. ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2_JPT.Multiply3x3(inLambda));
  101. return true;
  102. }
  103. return false;
  104. }
  105. public:
  106. /// Return inverse of initial rotation from body 1 to body 2 in body 1 space
  107. static Quat sGetInvInitialOrientation(const Body &inBody1, const Body &inBody2)
  108. {
  109. // q20 = q10 r0
  110. // <=> r0 = q10^-1 q20
  111. // <=> r0^-1 = q20^-1 q10
  112. //
  113. // where:
  114. //
  115. // q20 = initial orientation of body 2
  116. // q10 = initial orientation of body 1
  117. // r0 = initial rotation rotation from body 1 to body 2
  118. return inBody2.GetRotation().Conjugated() * inBody1.GetRotation();
  119. }
  120. /// Calculate properties used during the functions below
  121. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, const Body &inBody2, Mat44Arg inRotation2, QuatArg inInvInitialOrientation)
  122. {
  123. // Calculate: JP = 1/2 A ML(q1^*) MR(q2 r0^*) A^T
  124. Mat44 jp = (Mat44::sQuatLeftMultiply(0.5f * inBody1.GetRotation().Conjugated()) * Mat44::sQuatRightMultiply(inBody2.GetRotation() * inInvInitialOrientation)).GetRotationSafe();
  125. // Calculate properties used during constraint solving
  126. Mat44 invi1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
  127. Mat44 invi2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
  128. mInvI1_JPT = invi1.Multiply3x3RightTransposed(jp);
  129. mInvI2_JPT = invi2.Multiply3x3RightTransposed(jp);
  130. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
  131. // = (JP * I1^-1 * JP^T + JP * I2^-1 * JP^T)^-1
  132. // = (JP * (I1^-1 + I2^-1) * JP^T)^-1
  133. mEffectiveMass = jp.Multiply3x3(invi1 + invi2).Multiply3x3RightTransposed(jp).Inversed3x3();
  134. mEffectiveMass_JP = mEffectiveMass.Multiply3x3(jp);
  135. }
  136. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  137. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  138. {
  139. mTotalLambda *= inWarmStartImpulseRatio;
  140. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  141. }
  142. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  143. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  144. {
  145. // Calculate lagrange multiplier:
  146. //
  147. // lambda = -K^-1 (J v + b)
  148. Vec3 lambda = mEffectiveMass_JP.Multiply3x3(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity());
  149. mTotalLambda += lambda;
  150. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  151. }
  152. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  153. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, QuatArg inInvInitialOrientation, float inBaumgarte) const
  154. {
  155. // Calculate constraint equation
  156. Vec3 c = (ioBody1.GetRotation().Conjugated() * ioBody2.GetRotation() * inInvInitialOrientation).GetXYZ();
  157. if (c != Vec3::sZero())
  158. {
  159. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  160. //
  161. // lambda = -K^-1 * beta / dt * C
  162. //
  163. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  164. Vec3 lambda = -inBaumgarte * mEffectiveMass * c;
  165. // Directly integrate velocity change for one time step
  166. //
  167. // Euler velocity integration:
  168. // dv = M^-1 P
  169. //
  170. // Impulse:
  171. // P = J^T lambda
  172. //
  173. // Euler position integration:
  174. // x' = x + dv * dt
  175. //
  176. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  177. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  178. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  179. // integrate + a position integrate and then discard the velocity change.
  180. if (ioBody1.IsDynamic())
  181. ioBody1.SubRotationStep(mInvI1_JPT.Multiply3x3(lambda));
  182. if (ioBody2.IsDynamic())
  183. ioBody2.AddRotationStep(mInvI2_JPT.Multiply3x3(lambda));
  184. return true;
  185. }
  186. return false;
  187. }
  188. /// Return lagrange multiplier
  189. Vec3 GetTotalLambda() const
  190. {
  191. return mTotalLambda;
  192. }
  193. /// Save state of this constraint part
  194. void SaveState(StateRecorder &inStream) const
  195. {
  196. inStream.Write(mTotalLambda);
  197. }
  198. /// Restore state of this constraint part
  199. void RestoreState(StateRecorder &inStream)
  200. {
  201. inStream.Read(mTotalLambda);
  202. }
  203. private:
  204. Mat44 mInvI1_JPT;
  205. Mat44 mInvI2_JPT;
  206. Mat44 mEffectiveMass;
  207. Mat44 mEffectiveMass_JP;
  208. Vec3 mTotalLambda { Vec3::sZero() };
  209. };
  210. JPH_NAMESPACE_END