Debian Codegraph @

thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/IndependentAxisConstraintPart.h

raw symbols SCIP
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2022 Jorrit Rouwe
3 // SPDX-License-Identifier: MIT
4
5 #pragma once
6
7 #include <Jolt/Physics/Body/Body.h>
8 #include <Jolt/Physics/StateRecorder.h>
9
10 JPH_NAMESPACE_BEGIN
11
12 /// Constraint part to an AxisConstraintPart but both bodies have an independent axis on which the force is applied.
13 ///
14 /// Constraint equation:
15 ///
16 /// \f[C = (x_1 + r_1 - f_1) . n_1 + r (x_2 + r_2 - f_2) \cdot n_2\f]
17 ///
18 /// Calculating the Jacobian:
19 ///
20 /// \f[dC/dt = (v_1 + w_1 \times r_1) \cdot n_1 + (x_1 + r_1 - f_1) \cdot d n_1/dt + r (v_2 + w_2 \times r_2) \cdot n_2 + r (x_2 + r_2 - f_2) \cdot d n_2/dt\f]
21 ///
22 /// Assuming that d n1/dt and d n2/dt are small this becomes:
23 ///
24 /// \f[(v_1 + w_1 \times r_1) \cdot n_1 + r (v_2 + w_2 \times r_2) \cdot n_2\f]
25 /// \f[= v_1 \cdot n_1 + r_1 \times n_1 \cdot w_1 + r v_2 \cdot n_2 + r r_2 \times n_2 \cdot w_2\f]
26 ///
27 /// Jacobian:
28 ///
29 /// \f[J = \begin{bmatrix}n_1 & r_1 \times n_1 & r n_2 & r r_2 \times n_2\end{bmatrix}\f]
30 ///
31 /// Effective mass:
32 ///
33 /// \f[K = m_1^{-1} + r_1 \times n_1 I_1^{-1} r_1 \times n_1 + r^2 m_2^{-1} + r^2 r_2 \times n_2 I_2^{-1} r_2 \times n_2\f]
34 ///
35 /// Used terms (here and below, everything in world space):\n
36 /// n1 = (x1 + r1 - f1) / |x1 + r1 - f1|, axis along which the force is applied for body 1\n
37 /// n2 = (x2 + r2 - f2) / |x2 + r2 - f2|, axis along which the force is applied for body 2\n
38 /// r = ratio how forces are applied between bodies.\n
39 /// x1, x2 = center of mass for the bodies.\n
40 /// v = [v1, w1, v2, w2].\n
41 /// v1, v2 = linear velocity of body 1 and 2.\n
42 /// w1, w2 = angular velocity of body 1 and 2.\n
43 /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
44 /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
45 /// b = velocity bias.\n
46 /// \f$\beta\f$ = baumgarte constant.
47 class IndependentAxisConstraintPart
48 {
49 /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
50 JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inLambda) const
51 {
52 // Apply impulse if delta is not zero
53 if (inLambda != 0.0f)
54 {
55 // Calculate velocity change due to constraint
56 //
57 // Impulse:
58 // P = J^T lambda
59 //
60 // Euler velocity integration:
61 // v' = v + M^-1 P
62 if (ioBody1.IsDynamic())
63 {
64 MotionProperties *mp1 = ioBody1.GetMotionProperties();
65 mp1->AddLinearVelocityStep((mp1->GetInverseMass() * inLambda) * inN1);
66 mp1->AddAngularVelocityStep(mInvI1_R1xN1 * inLambda);
67 }
68 if (ioBody2.IsDynamic())
69 {
70 MotionProperties *mp2 = ioBody2.GetMotionProperties();
71 mp2->AddLinearVelocityStep((inRatio * mp2->GetInverseMass() * inLambda) * inN2);
72 mp2->AddAngularVelocityStep(mInvI2_RatioR2xN2 * inLambda);
73 }
74 return true;
75 }
76
77 return false;
78 }
79
80 public:
81 /// Calculate properties used during the functions below
82 /// @param inBody1 The first body that this constraint is attached to
83 /// @param inBody2 The second body that this constraint is attached to
84 /// @param inR1 The position on which the constraint operates on body 1 relative to COM
85 /// @param inN1 The world space normal in which the constraint operates for body 1
86 /// @param inR2 The position on which the constraint operates on body 1 relative to COM
87 /// @param inN2 The world space normal in which the constraint operates for body 2
88 /// @param inRatio The ratio how forces are applied between bodies
89 inline void CalculateConstraintProperties(const Body &inBody1, const Body &inBody2, Vec3Arg inR1, Vec3Arg inN1, Vec3Arg inR2, Vec3Arg inN2, float inRatio)
90 {
91 JPH_ASSERT(inN1.IsNormalized(1.0e-4f) && inN2.IsNormalized(1.0e-4f));
92
93 float inv_effective_mass = 0.0f;
94
95 if (!inBody1.IsStatic())
96 {
97 const MotionProperties *mp1 = inBody1.GetMotionProperties();
98
99 mR1xN1 = inR1.Cross(inN1);
100 mInvI1_R1xN1 = mp1->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), mR1xN1);
101
102 inv_effective_mass += mp1->GetInverseMass() + mInvI1_R1xN1.Dot(mR1xN1);
103 }
104
105 if (!inBody2.IsStatic())
106 {
107 const MotionProperties *mp2 = inBody2.GetMotionProperties();
108
109 mRatioR2xN2 = inRatio * inR2.Cross(inN2);
110 mInvI2_RatioR2xN2 = mp2->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), mRatioR2xN2);
111
112 inv_effective_mass += Square(inRatio) * mp2->GetInverseMass() + mInvI2_RatioR2xN2.Dot(mRatioR2xN2);
113 }
114
115 // Calculate inverse effective mass: K = J M^-1 J^T
116 if (inv_effective_mass == 0.0f)
117 Deactivate();
118 else
119 mEffectiveMass = 1.0f / inv_effective_mass;
120 }
121
122 /// Deactivate this constraint
123 inline void Deactivate()
124 {
125 mEffectiveMass = 0.0f;
126 mTotalLambda = 0.0f;
127 }
128
129 /// Check if constraint is active
130 inline bool IsActive() const
131 {
132 return mEffectiveMass != 0.0f;
133 }
134
135 /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
136 /// @param ioBody1 The first body that this constraint is attached to
137 /// @param ioBody2 The second body that this constraint is attached to
138 /// @param inN1 The world space normal in which the constraint operates for body 1
139 /// @param inN2 The world space normal in which the constraint operates for body 2
140 /// @param inRatio The ratio how forces are applied between bodies
141 /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
142 inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inWarmStartImpulseRatio)
143 {
144 mTotalLambda *= inWarmStartImpulseRatio;
145 ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, inRatio, mTotalLambda);
146 }
147
148 /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
149 /// @param ioBody1 The first body that this constraint is attached to
150 /// @param ioBody2 The second body that this constraint is attached to
151 /// @param inN1 The world space normal in which the constraint operates for body 1
152 /// @param inN2 The world space normal in which the constraint operates for body 2
153 /// @param inRatio The ratio how forces are applied between bodies
154 /// @param inMinLambda Minimum angular impulse to apply (N m s)
155 /// @param inMaxLambda Maximum angular impulse to apply (N m s)
156 inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inMinLambda, float inMaxLambda)
157 {
158 // Lagrange multiplier is:
159 //
160 // lambda = -K^-1 (J v + b)
161 float lambda = -mEffectiveMass * (inN1.Dot(ioBody1.GetLinearVelocity()) + mR1xN1.Dot(ioBody1.GetAngularVelocity()) + inRatio * inN2.Dot(ioBody2.GetLinearVelocity()) + mRatioR2xN2.Dot(ioBody2.GetAngularVelocity()));
162 float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse
163 lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply
164 mTotalLambda = new_lambda; // Store accumulated impulse
165
166 return ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, inRatio, lambda);
167 }
168
169 /// Return lagrange multiplier
170 float GetTotalLambda() const
171 {
172 return mTotalLambda;
173 }
174
175 /// Iteratively update the position constraint. Makes sure C(...) == 0.
176 /// @param ioBody1 The first body that this constraint is attached to
177 /// @param ioBody2 The second body that this constraint is attached to
178 /// @param inN1 The world space normal in which the constraint operates for body 1
179 /// @param inN2 The world space normal in which the constraint operates for body 2
180 /// @param inRatio The ratio how forces are applied between bodies
181 /// @param inC Value of the constraint equation (C)
182 /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
183 inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inC, float inBaumgarte) const
184 {
185 if (inC != 0.0f)
186 {
187 // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
188 //
189 // lambda = -K^-1 * beta / dt * C
190 //
191 // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
192 float lambda = -mEffectiveMass * inBaumgarte * inC;
193
194 // Directly integrate velocity change for one time step
195 //
196 // Euler velocity integration:
197 // dv = M^-1 P
198 //
199 // Impulse:
200 // P = J^T lambda
201 //
202 // Euler position integration:
203 // x' = x + dv * dt
204 //
205 // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
206 // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
207 // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
208 // integrate + a position integrate and then discard the velocity change.
209 if (ioBody1.IsDynamic())
210 {
211 ioBody1.AddPositionStep((lambda * ioBody1.GetMotionPropertiesUnchecked()->GetInverseMass()) * inN1);
212 ioBody1.AddRotationStep(lambda * mInvI1_R1xN1);
213 }
214 if (ioBody2.IsDynamic())
215 {
216 ioBody2.AddPositionStep((lambda * inRatio * ioBody2.GetMotionPropertiesUnchecked()->GetInverseMass()) * inN2);
217 ioBody2.AddRotationStep(lambda * mInvI2_RatioR2xN2);
218 }
219 return true;
220 }
221
222 return false;
223 }
224
225 /// Save state of this constraint part
226 void SaveState(StateRecorder &inStream) const
227 {
228 inStream.Write(mTotalLambda);
229 }
230
231 /// Restore state of this constraint part
232 void RestoreState(StateRecorder &inStream)
233 {
234 inStream.Read(mTotalLambda);
235 }
236
237 private:
238 Vec3 mR1xN1;
239 Vec3 mInvI1_R1xN1;
240 Vec3 mRatioR2xN2;
241 Vec3 mInvI2_RatioR2xN2;
242 float mEffectiveMass = 0.0f;
243 float mTotalLambda = 0.0f;
244 };
245
246 JPH_NAMESPACE_END