Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
HingeRotationConstraintPart.h
Go to the documentation of this file.
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
9#include <Jolt/Math/Vector.h>
10#include <Jolt/Math/Matrix.h>
11
13
44{
45public:
46 using Vec2 = Vector<2>;
48
49private:
51 JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, const Vec2 &inLambda) const
52 {
53 // Apply impulse if delta is not zero
54 if (!inLambda.IsZero())
55 {
56 // Calculate velocity change due to constraint
57 //
58 // Impulse:
59 // P = J^T lambda
60 //
61 // Euler velocity integration:
62 // v' = v + M^-1 P
63 Vec3 impulse = mB2xA1 * inLambda[0] + mC2xA1 * inLambda[1];
64 if (ioBody1.IsDynamic())
65 ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1.Multiply3x3(impulse));
66 if (ioBody2.IsDynamic())
67 ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2.Multiply3x3(impulse));
68 return true;
69 }
70
71 return false;
72 }
73
74public:
76 inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inWorldSpaceHingeAxis2)
77 {
78 JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-5f));
79 JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-5f));
80
81 // Calculate hinge axis in world space
82 mA1 = inWorldSpaceHingeAxis1;
83 Vec3 a2 = inWorldSpaceHingeAxis2;
84 float dot = mA1.Dot(a2);
85 if (dot <= 1.0e-3f)
86 {
87 // World space axes are more than 90 degrees apart, get a perpendicular vector in the plane formed by mA1 and a2 as hinge axis until the rotation is less than 90 degrees
88 Vec3 perp = a2 - dot * mA1;
89 if (perp.LengthSq() < 1.0e-6f)
90 {
91 // mA1 ~ -a2, take random perpendicular
92 perp = mA1.GetNormalizedPerpendicular();
93 }
94
95 // Blend in a little bit from mA1 so we're less than 90 degrees apart
96 a2 = (0.99f * perp.Normalized() + 0.01f * mA1).Normalized();
97 }
99 mC2 = a2.Cross(mB2);
100
101 // Calculate properties used during constraint solving
102 mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
103 mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
104 mB2xA1 = mB2.Cross(mA1);
105 mC2xA1 = mC2.Cross(mA1);
106
107 // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
108 Mat44 summed_inv_inertia = mInvI1 + mInvI2;
109 Mat22 inv_effective_mass;
110 inv_effective_mass(0, 0) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
111 inv_effective_mass(0, 1) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
112 inv_effective_mass(1, 0) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
113 inv_effective_mass(1, 1) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
114 if (!mEffectiveMass.SetInversed(inv_effective_mass))
115 Deactivate();
116 }
117
119 inline void Deactivate()
120 {
121 mEffectiveMass.SetZero();
122 mTotalLambda.SetZero();
123 }
124
126 inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
127 {
128 mTotalLambda *= inWarmStartImpulseRatio;
129 ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
130 }
131
133 inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
134 {
135 // Calculate lagrange multiplier:
136 //
137 // lambda = -K^-1 (J v + b)
138 Vec3 delta_ang = ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity();
139 Vec2 jv;
140 jv[0] = mB2xA1.Dot(delta_ang);
141 jv[1] = mC2xA1.Dot(delta_ang);
142 Vec2 lambda = mEffectiveMass * jv;
143
144 // Store accumulated lambda
145 mTotalLambda += lambda;
146
147 return ApplyVelocityStep(ioBody1, ioBody2, lambda);
148 }
149
151 inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
152 {
153 // Constraint needs Axis of body 1 perpendicular to both B and C from body 2 (which are both perpendicular to the Axis of body 2)
154 Vec2 c;
155 c[0] = mA1.Dot(mB2);
156 c[1] = mA1.Dot(mC2);
157 if (!c.IsZero())
158 {
159 // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
160 //
161 // lambda = -K^-1 * beta / dt * C
162 //
163 // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
164 Vec2 lambda = -inBaumgarte * (mEffectiveMass * c);
165
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 Vec3 impulse = mB2xA1 * lambda[0] + mC2xA1 * lambda[1];
182 if (ioBody1.IsDynamic())
183 ioBody1.SubRotationStep(mInvI1.Multiply3x3(impulse));
184 if (ioBody2.IsDynamic())
185 ioBody2.AddRotationStep(mInvI2.Multiply3x3(impulse));
186 return true;
187 }
188
189 return false;
190 }
191
193 const Vec2 & GetTotalLambda() const
194 {
195 return mTotalLambda;
196 }
197
199 void SaveState(StateRecorder &inStream) const
200 {
201 inStream.Write(mTotalLambda);
202 }
203
206 {
207 inStream.Read(mTotalLambda);
208 }
209
210private:
211 Vec3 mA1;
212 Vec3 mB2;
213 Vec3 mC2;
214 Mat44 mInvI1;
215 Mat44 mInvI2;
216 Vec3 mB2xA1;
217 Vec3 mC2xA1;
218 Mat22 mEffectiveMass;
219 Vec2 mTotalLambda { Vec2::sZero() };
220};
221
#define JPH_NAMESPACE_END
Definition: Core.h:367
#define JPH_NAMESPACE_BEGIN
Definition: Core.h:361
#define JPH_ASSERT(...)
Definition: IssueReporting.h:33
Definition: Body.h:35
const MotionProperties * GetMotionProperties() const
Access to the motion properties.
Definition: Body.h:255
bool IsDynamic() const
Check if this body is dynamic, which means that it moves and forces can act on it.
Definition: Body.h:67
void AddRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
Update rotation using an Euler step (using during position integrate & constraint solving)
Definition: Body.inl:81
void SubRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
Definition: Body.inl:100
Vec3 GetAngularVelocity() const
Get world space angular velocity of the center of mass (unit: rad/s)
Definition: Body.h:159
Definition: HingeRotationConstraintPart.h:44
bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
Iteratively update the position constraint. Makes sure C(...) = 0.
Definition: HingeRotationConstraintPart.h:151
void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inWorldSpaceHingeAxis2)
Calculate properties used during the functions below.
Definition: HingeRotationConstraintPart.h:76
void Deactivate()
Deactivate this constraint.
Definition: HingeRotationConstraintPart.h:119
void SaveState(StateRecorder &inStream) const
Save state of this constraint part.
Definition: HingeRotationConstraintPart.h:199
void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses.
Definition: HingeRotationConstraintPart.h:126
const Vec2 & GetTotalLambda() const
Return lagrange multiplier.
Definition: HingeRotationConstraintPart.h:193
bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equ...
Definition: HingeRotationConstraintPart.h:133
Matrix< 2, 2 > Mat22
Definition: HingeRotationConstraintPart.h:47
void RestoreState(StateRecorder &inStream)
Restore state of this constraint part.
Definition: HingeRotationConstraintPart.h:205
Vector< 2 > Vec2
Definition: HingeRotationConstraintPart.h:46
Holds a 4x4 matrix of floats, but supports also operations on the 3x3 upper left part of the matrix.
Definition: Mat44.h:13
static JPH_INLINE Mat44 sZero()
Zero matrix.
Definition: Mat44.inl:30
JPH_INLINE Vec3 Multiply3x3(Vec3Arg inV) const
Multiply vector by only 3x3 part of the matrix.
Definition: Mat44.inl:316
bool SetInversed(const Matrix &inM)
Inverse matrix.
Definition: Matrix.h:200
void SetZero()
Zero matrix.
Definition: Matrix.h:26
void SubAngularVelocityStep(Vec3Arg inAngularVelocityChange)
Definition: MotionProperties.h:194
Mat44 GetInverseInertiaForRotation(Mat44Arg inRotation) const
Get inverse inertia matrix ( ) for a given object rotation (translation will be ignored)....
Definition: MotionProperties.inl:59
void AddAngularVelocityStep(Vec3Arg inAngularVelocityChange)
Definition: MotionProperties.h:193
Definition: StateRecorder.h:48
void Read(T &outT)
Read a primitive (e.g. float, int, etc.) from the binary stream.
Definition: StreamIn.h:29
void Write(const T &inT)
Write a primitive (e.g. float, int, etc.) to the binary stream.
Definition: StreamOut.h:26
Definition: Vec3.h:16
JPH_INLINE float Dot(Vec3Arg inV2) const
Dot product.
Definition: Vec3.inl:637
JPH_INLINE Vec3 Normalized() const
Normalize vector.
Definition: Vec3.inl:694
JPH_INLINE Vec3 Cross(Vec3Arg inV2) const
Cross product.
Definition: Vec3.inl:582
JPH_INLINE Vec3 GetNormalizedPerpendicular() const
Get normalized vector that is perpendicular to this vector.
Definition: Vec3.inl:812
JPH_INLINE bool IsNormalized(float inTolerance=1.0e-6f) const
Test if vector is normalized.
Definition: Vec3.inl:737
JPH_INLINE float LengthSq() const
Squared length of vector.
Definition: Vec3.inl:653
void SetZero()
Vector with all zeros.
Definition: Vector.h:22
bool IsZero() const
Test if vector consists of all zeros.
Definition: Vector.h:69
static Vector sZero()
Definition: Vector.h:28