Debian Codegraph @

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

raw symbols SCIP
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2021 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 /// Constrains movement along 3 axis
13 ///
14 /// @see "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.2.1
15 ///
16 /// Constraint equation (eq 45):
17 ///
18 /// \f[C = p_2 - p_1\f]
19 ///
20 /// Jacobian (transposed) (eq 47):
21 ///
22 /// \f[J^T = \begin{bmatrix}-E & r1x & E & -r2x^T\end{bmatrix}
23 /// = \begin{bmatrix}-E^T \\ r1x^T \\ E^T \\ -r2x^T\end{bmatrix}
24 /// = \begin{bmatrix}-E \\ -r1x \\ E \\ r2x\end{bmatrix}\f]
25 ///
26 /// Used terms (here and below, everything in world space):\n
27 /// p1, p2 = constraint points.\n
28 /// r1 = p1 - x1.\n
29 /// r2 = p2 - x2.\n
30 /// r1x = 3x3 matrix for which r1x v = r1 x v (cross product).\n
31 /// x1, x2 = center of mass for the bodies.\n
32 /// v = [v1, w1, v2, w2].\n
33 /// v1, v2 = linear velocity of body 1 and 2.\n
34 /// w1, w2 = angular velocity of body 1 and 2.\n
35 /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
36 /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
37 /// b = velocity bias.\n
38 /// \f$\beta\f$ = baumgarte constant.\n
39 /// E = identity matrix.
40 class PointConstraintPart
41 {
42 JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const
43 {
44 // Apply impulse if delta is not zero
45 if (inLambda != Vec3::sZero())
46 {
47 // Calculate velocity change due to constraint
48 //
49 // Impulse:
50 // P = J^T lambda
51 //
52 // Euler velocity integration:
53 // v' = v + M^-1 P
54 if (ioBody1.IsDynamic())
55 {
56 MotionProperties *mp1 = ioBody1.GetMotionProperties();
57 mp1->SubLinearVelocityStep(mp1->GetInverseMass() * inLambda);
58 mp1->SubAngularVelocityStep(mInvI1_R1X * inLambda);
59 }
60 if (ioBody2.IsDynamic())
61 {
62 MotionProperties *mp2 = ioBody2.GetMotionProperties();
63 mp2->AddLinearVelocityStep(mp2->GetInverseMass() * inLambda);
64 mp2->AddAngularVelocityStep(mInvI2_R2X * inLambda);
65 }
66 return true;
67 }
68
69 return false;
70 }
71
72 public:
73 /// Calculate properties used during the functions below
74 /// @param inBody1 The first body that this constraint is attached to
75 /// @param inBody2 The second body that this constraint is attached to
76 /// @param inRotation1 The 3x3 rotation matrix for body 1 (translation part is ignored)
77 /// @param inRotation2 The 3x3 rotation matrix for body 2 (translation part is ignored)
78 /// @param inR1 Local space vector from center of mass to constraint point for body 1
79 /// @param inR2 Local space vector from center of mass to constraint point for body 2
80 inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inR1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inR2)
81 {
82 // Positions where the point constraint acts on (middle point between center of masses) in world space
83 mR1 = inRotation1.Multiply3x3(inR1);
84 mR2 = inRotation2.Multiply3x3(inR2);
85
86 // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
87 // Using: I^-1 = R * Ibody^-1 * R^T
88 float summed_inv_mass;
89 Mat44 inv_effective_mass;
90 if (inBody1.IsDynamic())
91 {
92 const MotionProperties *mp1 = inBody1.GetMotionProperties();
93 Mat44 inv_i1 = mp1->GetInverseInertiaForRotation(inRotation1);
94 summed_inv_mass = mp1->GetInverseMass();
95
96 Mat44 r1x = Mat44::sCrossProduct(mR1);
97 mInvI1_R1X = inv_i1.Multiply3x3(r1x);
98 inv_effective_mass = r1x.Multiply3x3(inv_i1).Multiply3x3RightTransposed(r1x);
99 }
100 else
101 {
102 JPH_IF_DEBUG(mInvI1_R1X = Mat44::sNaN();)
103
104 summed_inv_mass = 0.0f;
105 inv_effective_mass = Mat44::sZero();
106 }
107
108 if (inBody2.IsDynamic())
109 {
110 const MotionProperties *mp2 = inBody2.GetMotionProperties();
111 Mat44 inv_i2 = mp2->GetInverseInertiaForRotation(inRotation2);
112 summed_inv_mass += mp2->GetInverseMass();
113
114 Mat44 r2x = Mat44::sCrossProduct(mR2);
115 mInvI2_R2X = inv_i2.Multiply3x3(r2x);
116 inv_effective_mass += r2x.Multiply3x3(inv_i2).Multiply3x3RightTransposed(r2x);
117 }
118 else
119 {
120 JPH_IF_DEBUG(mInvI2_R2X = Mat44::sNaN();)
121 }
122
123 inv_effective_mass += Mat44::sScale(summed_inv_mass);
124 if (!mEffectiveMass.SetInversed3x3(inv_effective_mass))
125 Deactivate();
126 }
127
128 /// Deactivate this constraint
129 inline void Deactivate()
130 {
131 mEffectiveMass = Mat44::sZero();
132 mTotalLambda = Vec3::sZero();
133 }
134
135 /// Check if constraint is active
136 inline bool IsActive() const
137 {
138 return mEffectiveMass(3, 3) != 0.0f;
139 }
140
141 /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
142 /// @param ioBody1 The first body that this constraint is attached to
143 /// @param ioBody2 The second body that this constraint is attached to
144 /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
145 inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
146 {
147 mTotalLambda *= inWarmStartImpulseRatio;
148 ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
149 }
150
151 /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
152 /// @param ioBody1 The first body that this constraint is attached to
153 /// @param ioBody2 The second body that this constraint is attached to
154 inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
155 {
156 // Calculate lagrange multiplier:
157 //
158 // lambda = -K^-1 (J v + b)
159 Vec3 lambda = mEffectiveMass * (ioBody1.GetLinearVelocity() - mR1.Cross(ioBody1.GetAngularVelocity()) - ioBody2.GetLinearVelocity() + mR2.Cross(ioBody2.GetAngularVelocity()));
160 mTotalLambda += lambda; // Store accumulated lambda
161 return ApplyVelocityStep(ioBody1, ioBody2, lambda);
162 }
163
164 /// Iteratively update the position constraint. Makes sure C(...) = 0.
165 /// @param ioBody1 The first body that this constraint is attached to
166 /// @param ioBody2 The second body that this constraint is attached to
167 /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
168 inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
169 {
170 Vec3 separation = (Vec3(ioBody2.GetCenterOfMassPosition() - ioBody1.GetCenterOfMassPosition()) + mR2 - mR1);
171 if (separation != Vec3::sZero())
172 {
173 // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
174 //
175 // lambda = -K^-1 * beta / dt * C
176 //
177 // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
178 Vec3 lambda = mEffectiveMass * -inBaumgarte * separation;
179
180 // Directly integrate velocity change for one time step
181 //
182 // Euler velocity integration:
183 // dv = M^-1 P
184 //
185 // Impulse:
186 // P = J^T lambda
187 //
188 // Euler position integration:
189 // x' = x + dv * dt
190 //
191 // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
192 // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
193 // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
194 // integrate + a position integrate and then discard the velocity change.
195 if (ioBody1.IsDynamic())
196 {
197 ioBody1.SubPositionStep(ioBody1.GetMotionProperties()->GetInverseMass() * lambda);
198 ioBody1.SubRotationStep(mInvI1_R1X * lambda);
199 }
200 if (ioBody2.IsDynamic())
201 {
202 ioBody2.AddPositionStep(ioBody2.GetMotionProperties()->GetInverseMass() * lambda);
203 ioBody2.AddRotationStep(mInvI2_R2X * lambda);
204 }
205
206 return true;
207 }
208
209 return false;
210 }
211
212 /// Return lagrange multiplier
213 Vec3 GetTotalLambda() const
214 {
215 return mTotalLambda;
216 }
217
218 /// Save state of this constraint part
219 void SaveState(StateRecorder &inStream) const
220 {
221 inStream.Write(mTotalLambda);
222 }
223
224 /// Restore state of this constraint part
225 void RestoreState(StateRecorder &inStream)
226 {
227 inStream.Read(mTotalLambda);
228 }
229
230 private:
231 Vec3 mR1;
232 Vec3 mR2;
233 Mat44 mInvI1_R1X;
234 Mat44 mInvI2_R2X;
235 Mat44 mEffectiveMass;
236 Vec3 mTotalLambda { Vec3::sZero() };
237 };
238
239 JPH_NAMESPACE_END