AxisConstraintPart.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Physics/PhysicsSettings.h>
  5. #include <Jolt/Physics/Body/Body.h>
  6. #include <Jolt/Physics/Constraints/ConstraintPart/SpringPart.h>
  7. #include <Jolt/Physics/StateRecorder.h>
  8. JPH_NAMESPACE_BEGIN
  9. /// Constraint that constrains motion along 1 axis
  10. ///
  11. /// @see "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.1.1
  12. /// (we're not using the approximation of eq 27 but instead add the U term as in eq 55)
  13. ///
  14. /// Constraint equation (eq 25):
  15. ///
  16. /// \f[C = (p_2 - p_1) \cdot n\f]
  17. ///
  18. /// Jacobian (eq 28):
  19. ///
  20. /// \f[J = \begin{bmatrix} -n^T & (-(r_1 + u) \times n)^T & n^T & (r_2 \times n)^T \end{bmatrix}\f]
  21. ///
  22. /// Used terms (here and below, everything in world space):\n
  23. /// n = constraint axis (normalized).\n
  24. /// p1, p2 = constraint points.\n
  25. /// r1 = p1 - x1.\n
  26. /// r2 = p2 - x2.\n
  27. /// u = x2 + r2 - x1 - r1 = p2 - p1.\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.
  36. class AxisConstraintPart
  37. {
  38. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  39. template <EMotionType Type1, EMotionType Type2>
  40. JPH_INLINE bool ApplyVelocityStep(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis, float inLambda) const
  41. {
  42. // Apply impulse if delta is not zero
  43. if (inLambda != 0.0f)
  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. if constexpr (Type1 == EMotionType::Dynamic)
  53. {
  54. ioMotionProperties1->SubLinearVelocityStep((inLambda * ioMotionProperties1->GetInverseMass()) * inWorldSpaceAxis);
  55. ioMotionProperties1->SubAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));
  56. }
  57. if constexpr (Type2 == EMotionType::Dynamic)
  58. {
  59. ioMotionProperties2->AddLinearVelocityStep((inLambda * ioMotionProperties2->GetInverseMass()) * inWorldSpaceAxis);
  60. ioMotionProperties2->AddAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));
  61. }
  62. return true;
  63. }
  64. return false;
  65. }
  66. public:
  67. /// Templated form of CalculateConstraintProperties with the motion types baked in
  68. template <EMotionType Type1, EMotionType Type2>
  69. JPH_INLINE void TemplatedCalculateConstraintProperties(float inDeltaTime, const MotionProperties *inMotionProperties1, Mat44Arg inInvI1, Vec3Arg inR1PlusU, const MotionProperties *inMotionProperties2, Mat44Arg inInvI2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f, float inC = 0.0f, float inFrequency = 0.0f, float inDamping = 0.0f)
  70. {
  71. JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-5f));
  72. // Calculate properties used below
  73. Vec3 r1_plus_u_x_axis;
  74. if constexpr (Type1 != EMotionType::Static)
  75. {
  76. r1_plus_u_x_axis = inR1PlusU.Cross(inWorldSpaceAxis);
  77. r1_plus_u_x_axis.StoreFloat3(&mR1PlusUxAxis);
  78. }
  79. else
  80. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mR1PlusUxAxis));
  81. Vec3 r2_x_axis;
  82. if constexpr (Type2 != EMotionType::Static)
  83. {
  84. r2_x_axis = inR2.Cross(inWorldSpaceAxis);
  85. r2_x_axis.StoreFloat3(&mR2xAxis);
  86. }
  87. else
  88. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mR2xAxis));
  89. // Calculate inverse effective mass: K = J M^-1 J^T
  90. float inv_effective_mass;
  91. if constexpr (Type1 == EMotionType::Dynamic)
  92. {
  93. Vec3 invi1_r1_plus_u_x_axis = inInvI1 * r1_plus_u_x_axis;
  94. invi1_r1_plus_u_x_axis.StoreFloat3(&mInvI1_R1PlusUxAxis);
  95. inv_effective_mass = inMotionProperties1->GetInverseMass() + invi1_r1_plus_u_x_axis.Dot(r1_plus_u_x_axis);
  96. }
  97. else
  98. {
  99. (void)r1_plus_u_x_axis; // Fix compiler warning: Not using this (it's not calculated either)
  100. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI1_R1PlusUxAxis);)
  101. inv_effective_mass = 0.0f;
  102. }
  103. if constexpr (Type2 == EMotionType::Dynamic)
  104. {
  105. Vec3 invi2_r2_x_axis = inInvI2 * r2_x_axis;
  106. invi2_r2_x_axis.StoreFloat3(&mInvI2_R2xAxis);
  107. inv_effective_mass += inMotionProperties2->GetInverseMass() + invi2_r2_x_axis.Dot(r2_x_axis);
  108. }
  109. else
  110. {
  111. (void)r2_x_axis; // Fix compiler warning: Not using this (it's not calculated either)
  112. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI2_R2xAxis);)
  113. }
  114. // Calculate effective mass and spring properties
  115. mSpringPart.CalculateSpringProperties(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);
  116. }
  117. /// Calculate properties used during the functions below
  118. /// @param inDeltaTime Time step
  119. /// @param inBody1 The first body that this constraint is attached to
  120. /// @param inBody2 The second body that this constraint is attached to
  121. /// @param inR1PlusU See equations above (r1 + u)
  122. /// @param inR2 See equations above (r2)
  123. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)
  124. /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b
  125. /// @param inC Value of the constraint equation (C). Set to zero if you don't want to drive the constraint to zero with a spring.
  126. /// @param inFrequency Oscillation frequency (Hz). Set to zero if you don't want to drive the constraint to zero with a spring.
  127. /// @param inDamping Damping factor (0 = no damping, 1 = critical damping). Set to zero if you don't want to drive the constraint to zero with a spring.
  128. inline void CalculateConstraintProperties(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f, float inC = 0.0f, float inFrequency = 0.0f, float inDamping = 0.0f)
  129. {
  130. // Dispatch to the correct templated form
  131. switch (inBody1.GetMotionType())
  132. {
  133. case EMotionType::Dynamic:
  134. {
  135. const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();
  136. Mat44 invi1 = inBody1.GetInverseInertia();
  137. switch (inBody2.GetMotionType())
  138. {
  139. case EMotionType::Dynamic:
  140. TemplatedCalculateConstraintProperties<EMotionType::Dynamic, EMotionType::Dynamic>(inDeltaTime, mp1, invi1, inR1PlusU, inBody2.GetMotionPropertiesUnchecked(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  141. break;
  142. case EMotionType::Kinematic:
  143. TemplatedCalculateConstraintProperties<EMotionType::Dynamic, EMotionType::Kinematic>(inDeltaTime, mp1, invi1, inR1PlusU, nullptr, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  144. break;
  145. case EMotionType::Static:
  146. TemplatedCalculateConstraintProperties<EMotionType::Dynamic, EMotionType::Static>(inDeltaTime, mp1, invi1, inR1PlusU, nullptr, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  147. break;
  148. default:
  149. JPH_ASSERT(false);
  150. break;
  151. }
  152. break;
  153. }
  154. case EMotionType::Kinematic:
  155. JPH_ASSERT(inBody2.IsDynamic());
  156. TemplatedCalculateConstraintProperties<EMotionType::Kinematic, EMotionType::Dynamic>(inDeltaTime, nullptr, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  157. break;
  158. case EMotionType::Static:
  159. JPH_ASSERT(inBody2.IsDynamic());
  160. TemplatedCalculateConstraintProperties<EMotionType::Static, EMotionType::Dynamic>(inDeltaTime, nullptr, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  161. break;
  162. default:
  163. JPH_ASSERT(false);
  164. break;
  165. }
  166. }
  167. /// Deactivate this constraint
  168. inline void Deactivate()
  169. {
  170. mEffectiveMass = 0.0f;
  171. mTotalLambda = 0.0f;
  172. }
  173. /// Check if constraint is active
  174. inline bool IsActive() const
  175. {
  176. return mEffectiveMass != 0.0f;
  177. }
  178. /// Templated form of WarmStart with the motion types baked in
  179. template <EMotionType Type1, EMotionType Type2>
  180. inline void TemplatedWarmStart(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)
  181. {
  182. mTotalLambda *= inWarmStartImpulseRatio;
  183. ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, inWorldSpaceAxis, mTotalLambda);
  184. }
  185. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  186. /// @param ioBody1 The first body that this constraint is attached to
  187. /// @param ioBody2 The second body that this constraint is attached to
  188. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)
  189. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  190. inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)
  191. {
  192. EMotionType motion_type1 = ioBody1.GetMotionType();
  193. MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();
  194. EMotionType motion_type2 = ioBody2.GetMotionType();
  195. MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();
  196. // Dispatch to the correct templated form
  197. // Note: Warm starting doesn't differentiate between kinematic/static bodies so we handle both as static bodies
  198. if (motion_type1 == EMotionType::Dynamic)
  199. {
  200. if (motion_type2 == EMotionType::Dynamic)
  201. TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inWarmStartImpulseRatio);
  202. else
  203. TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties2, inWorldSpaceAxis, inWarmStartImpulseRatio);
  204. }
  205. else
  206. {
  207. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  208. TemplatedWarmStart<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inWarmStartImpulseRatio);
  209. }
  210. }
  211. /// Templated form of SolveVelocityConstraint with the motion types baked in
  212. template <EMotionType Type1, EMotionType Type2>
  213. inline bool TemplatedSolveVelocityConstraint(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)
  214. {
  215. // Calculate jacobian multiplied by linear velocity
  216. float jv;
  217. if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)
  218. jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity() - ioMotionProperties2->GetLinearVelocity());
  219. else if constexpr (Type1 != EMotionType::Static)
  220. jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity());
  221. else if constexpr (Type2 != EMotionType::Static)
  222. jv = inWorldSpaceAxis.Dot(-ioMotionProperties2->GetLinearVelocity());
  223. else
  224. JPH_ASSERT(false); // Static vs static is nonsensical!
  225. // Calculate jacobian multiplied by angular velocity
  226. if constexpr (Type1 != EMotionType::Static)
  227. jv += Vec3::sLoadFloat3Unsafe(mR1PlusUxAxis).Dot(ioMotionProperties1->GetAngularVelocity());
  228. if constexpr (Type2 != EMotionType::Static)
  229. jv -= Vec3::sLoadFloat3Unsafe(mR2xAxis).Dot(ioMotionProperties2->GetAngularVelocity());
  230. // Lagrange multiplier is:
  231. //
  232. // lambda = -K^-1 (J v + b)
  233. float lambda = mEffectiveMass * (jv - mSpringPart.GetBias(mTotalLambda));
  234. float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse
  235. lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply
  236. mTotalLambda = new_lambda; // Store accumulated impulse
  237. return ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, inWorldSpaceAxis, lambda);
  238. }
  239. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  240. /// @param ioBody1 The first body that this constraint is attached to
  241. /// @param ioBody2 The second body that this constraint is attached to
  242. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)
  243. /// @param inMinLambda Minimum value of constraint impulse to apply (N s)
  244. /// @param inMaxLambda Maximum value of constraint impulse to apply (N s)
  245. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)
  246. {
  247. EMotionType motion_type1 = ioBody1.GetMotionType();
  248. MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();
  249. EMotionType motion_type2 = ioBody2.GetMotionType();
  250. MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();
  251. // Dispatch to the correct templated form
  252. switch (motion_type1)
  253. {
  254. case EMotionType::Dynamic:
  255. switch (motion_type2)
  256. {
  257. case EMotionType::Dynamic:
  258. return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  259. case EMotionType::Kinematic:
  260. return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  261. case EMotionType::Static:
  262. return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  263. default:
  264. JPH_ASSERT(false);
  265. break;
  266. }
  267. break;
  268. case EMotionType::Kinematic:
  269. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  270. return TemplatedSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  271. case EMotionType::Static:
  272. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  273. return TemplatedSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  274. default:
  275. JPH_ASSERT(false);
  276. break;
  277. }
  278. return false;
  279. }
  280. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  281. /// @param ioBody1 The first body that this constraint is attached to
  282. /// @param ioBody2 The second body that this constraint is attached to
  283. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)
  284. /// @param inC Value of the constraint equation (C)
  285. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  286. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inC, float inBaumgarte) const
  287. {
  288. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  289. if (inC != 0.0f && !mSpringPart.IsActive())
  290. {
  291. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  292. //
  293. // lambda = -K^-1 * beta / dt * C
  294. //
  295. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  296. float lambda = -mEffectiveMass * inBaumgarte * inC;
  297. // Directly integrate velocity change for one time step
  298. //
  299. // Euler velocity integration:
  300. // dv = M^-1 P
  301. //
  302. // Impulse:
  303. // P = J^T lambda
  304. //
  305. // Euler position integration:
  306. // x' = x + dv * dt
  307. //
  308. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  309. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  310. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  311. // integrate + a position integrate and then discard the velocity change.
  312. if (ioBody1.IsDynamic())
  313. {
  314. ioBody1.SubPositionStep((lambda * ioBody1.GetMotionPropertiesUnchecked()->GetInverseMass()) * inWorldSpaceAxis);
  315. ioBody1.SubRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));
  316. }
  317. if (ioBody2.IsDynamic())
  318. {
  319. ioBody2.AddPositionStep((lambda * ioBody2.GetMotionPropertiesUnchecked()->GetInverseMass()) * inWorldSpaceAxis);
  320. ioBody2.AddRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));
  321. }
  322. return true;
  323. }
  324. return false;
  325. }
  326. /// Override total lagrange multiplier, can be used to set the initial value for warm starting
  327. inline void SetTotalLambda(float inLambda)
  328. {
  329. mTotalLambda = inLambda;
  330. }
  331. /// Return lagrange multiplier
  332. inline float GetTotalLambda() const
  333. {
  334. return mTotalLambda;
  335. }
  336. /// Save state of this constraint part
  337. void SaveState(StateRecorder &inStream) const
  338. {
  339. inStream.Write(mTotalLambda);
  340. }
  341. /// Restore state of this constraint part
  342. void RestoreState(StateRecorder &inStream)
  343. {
  344. inStream.Read(mTotalLambda);
  345. }
  346. private:
  347. Float3 mR1PlusUxAxis;
  348. Float3 mR2xAxis;
  349. Float3 mInvI1_R1PlusUxAxis;
  350. Float3 mInvI2_R2xAxis;
  351. float mEffectiveMass = 0.0f;
  352. SpringPart mSpringPart;
  353. float mTotalLambda = 0.0f;
  354. };
  355. JPH_NAMESPACE_END