RotationQuatConstraintPart.h 8.1 KB

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