Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/GearConstraintPart.h
9913 views
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
/// Constraint that constrains two rotations using a gear (rotating in opposite direction)
13
///
14
/// Constraint equation:
15
///
16
/// C = Rotation1(t) + r Rotation2(t)
17
///
18
/// Derivative:
19
///
20
/// d/dt C = 0
21
/// <=> w1 . a + r w2 . b = 0
22
///
23
/// Jacobian:
24
///
25
/// \f[J = \begin{bmatrix}0 & a^T & 0 & r b^T\end{bmatrix}\f]
26
///
27
/// Used terms (here and below, everything in world space):\n
28
/// a = axis around which body 1 rotates (normalized).\n
29
/// b = axis along which body 2 slides (normalized).\n
30
/// Rotation1(t) = rotation around a of body 1.\n
31
/// Rotation2(t) = rotation around b of body 2.\n
32
/// r = ratio between rotation for body 1 and 2.\n
33
/// v = [v1, w1, v2, w2].\n
34
/// v1, v2 = linear velocity of body 1 and 2.\n
35
/// w1, w2 = angular velocity of body 1 and 2.\n
36
/// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
37
/// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
38
/// \f$\beta\f$ = baumgarte constant.
39
class GearConstraintPart
40
{
41
/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
42
JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const
43
{
44
// Apply impulse if delta is not zero
45
if (inLambda != 0.0f)
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
ioBody1.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI1_A);
55
ioBody2.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI2_B);
56
return true;
57
}
58
59
return false;
60
}
61
62
public:
63
/// Calculate properties used during the functions below
64
/// @param inBody1 The first body that this constraint is attached to
65
/// @param inBody2 The second body that this constraint is attached to
66
/// @param inWorldSpaceHingeAxis1 The axis around which body 1 rotates
67
/// @param inWorldSpaceHingeAxis2 The axis around which body 2 rotates
68
/// @param inRatio The ratio between rotation and translation
69
inline void CalculateConstraintProperties(const Body &inBody1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Vec3Arg inWorldSpaceHingeAxis2, float inRatio)
70
{
71
JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-4f));
72
JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-4f));
73
74
// Calculate: I1^-1 a
75
mInvI1_A = inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceHingeAxis1);
76
77
// Calculate: I2^-1 b
78
mInvI2_B = inBody2.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), inWorldSpaceHingeAxis2);
79
80
// K^-1 = 1 / (J M^-1 J^T) = 1 / (a^T I1^-1 a + r^2 * b^T I2^-1 b)
81
float inv_effective_mass = (inWorldSpaceHingeAxis1.Dot(mInvI1_A) + inWorldSpaceHingeAxis2.Dot(mInvI2_B) * Square(inRatio));
82
if (inv_effective_mass == 0.0f)
83
Deactivate();
84
else
85
mEffectiveMass = 1.0f / inv_effective_mass;
86
}
87
88
/// Deactivate this constraint
89
inline void Deactivate()
90
{
91
mEffectiveMass = 0.0f;
92
mTotalLambda = 0.0f;
93
}
94
95
/// Check if constraint is active
96
inline bool IsActive() const
97
{
98
return mEffectiveMass != 0.0f;
99
}
100
101
/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
102
/// @param ioBody1 The first body that this constraint is attached to
103
/// @param ioBody2 The second body that this constraint is attached to
104
/// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
105
inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
106
{
107
mTotalLambda *= inWarmStartImpulseRatio;
108
ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
109
}
110
111
/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
112
/// @param ioBody1 The first body that this constraint is attached to
113
/// @param ioBody2 The second body that this constraint is attached to
114
/// @param inWorldSpaceHingeAxis1 The axis around which body 1 rotates
115
/// @param inWorldSpaceHingeAxis2 The axis around which body 2 rotates
116
/// @param inRatio The ratio between rotation and translation
117
inline bool SolveVelocityConstraint(Body &ioBody1, Vec3Arg inWorldSpaceHingeAxis1, Body &ioBody2, Vec3Arg inWorldSpaceHingeAxis2, float inRatio)
118
{
119
// Lagrange multiplier is:
120
//
121
// lambda = -K^-1 (J v + b)
122
float lambda = -mEffectiveMass * (inWorldSpaceHingeAxis1.Dot(ioBody1.GetAngularVelocity()) + inRatio * inWorldSpaceHingeAxis2.Dot(ioBody2.GetAngularVelocity()));
123
mTotalLambda += lambda; // Store accumulated impulse
124
125
return ApplyVelocityStep(ioBody1, ioBody2, lambda);
126
}
127
128
/// Return lagrange multiplier
129
float GetTotalLambda() const
130
{
131
return mTotalLambda;
132
}
133
134
/// Iteratively update the position constraint. Makes sure C(...) == 0.
135
/// @param ioBody1 The first body that this constraint is attached to
136
/// @param ioBody2 The second body that this constraint is attached to
137
/// @param inC Value of the constraint equation (C)
138
/// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
139
inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const
140
{
141
// Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
142
if (inC != 0.0f)
143
{
144
// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
145
//
146
// lambda = -K^-1 * beta / dt * C
147
//
148
// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
149
float lambda = -mEffectiveMass * inBaumgarte * inC;
150
151
// Directly integrate velocity change for one time step
152
//
153
// Euler velocity integration:
154
// dv = M^-1 P
155
//
156
// Impulse:
157
// P = J^T lambda
158
//
159
// Euler position integration:
160
// x' = x + dv * dt
161
//
162
// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
163
// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
164
// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
165
// integrate + a position integrate and then discard the velocity change.
166
if (ioBody1.IsDynamic())
167
ioBody1.AddRotationStep(lambda * mInvI1_A);
168
if (ioBody2.IsDynamic())
169
ioBody2.AddRotationStep(lambda * mInvI2_B);
170
return true;
171
}
172
173
return false;
174
}
175
176
/// Save state of this constraint part
177
void SaveState(StateRecorder &inStream) const
178
{
179
inStream.Write(mTotalLambda);
180
}
181
182
/// Restore state of this constraint part
183
void RestoreState(StateRecorder &inStream)
184
{
185
inStream.Read(mTotalLambda);
186
}
187
188
private:
189
Vec3 mInvI1_A;
190
Vec3 mInvI2_B;
191
float mEffectiveMass = 0.0f;
192
float mTotalLambda = 0.0f;
193
};
194
195
JPH_NAMESPACE_END
196
197