Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/HingeRotationConstraintPart.h
9913 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Physics/Body/Body.h>7#include <Jolt/Physics/StateRecorder.h>8#include <Jolt/Math/Vector.h>9#include <Jolt/Math/Matrix.h>1011JPH_NAMESPACE_BEGIN1213/**14Constrains rotation around 2 axis so that it only allows rotation around 1 axis1516Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.4.11718Constraint equation (eq 87):1920\f[C = \begin{bmatrix}a_1 \cdot b_2 \\ a_1 \cdot c_2\end{bmatrix}\f]2122Jacobian (eq 90):2324\f[J = \begin{bmatrix}250 & -b_2 \times a_1 & 0 & b_2 \times a_1 \\260 & -c_2 \times a_1 & 0 & c2 \times a_127\end{bmatrix}\f]2829Used terms (here and below, everything in world space):\n30a1 = hinge axis on body 1.\n31b2, c2 = axis perpendicular to hinge axis on body 2.\n32x1, x2 = center of mass for the bodies.\n33v = [v1, w1, v2, w2].\n34v1, v2 = linear velocity of body 1 and 2.\n35w1, w2 = angular velocity of body 1 and 2.\n36M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n37\f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n38b = velocity bias.\n39\f$\beta\f$ = baumgarte constant.\n40E = identity matrix.41**/42class HingeRotationConstraintPart43{44public:45using Vec2 = Vector<2>;46using Mat22 = Matrix<2, 2>;4748private:49/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated50JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, const Vec2 &inLambda) const51{52// Apply impulse if delta is not zero53if (!inLambda.IsZero())54{55// Calculate velocity change due to constraint56//57// Impulse:58// P = J^T lambda59//60// Euler velocity integration:61// v' = v + M^-1 P62Vec3 impulse = mB2xA1 * inLambda[0] + mC2xA1 * inLambda[1];63if (ioBody1.IsDynamic())64ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1.Multiply3x3(impulse));65if (ioBody2.IsDynamic())66ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2.Multiply3x3(impulse));67return true;68}6970return false;71}7273public:74/// Calculate properties used during the functions below75inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inWorldSpaceHingeAxis2)76{77JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-5f));78JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-5f));7980// Calculate hinge axis in world space81mA1 = inWorldSpaceHingeAxis1;82Vec3 a2 = inWorldSpaceHingeAxis2;83float dot = mA1.Dot(a2);84if (dot <= 1.0e-3f)85{86// 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 degrees87Vec3 perp = a2 - dot * mA1;88if (perp.LengthSq() < 1.0e-6f)89{90// mA1 ~ -a2, take random perpendicular91perp = mA1.GetNormalizedPerpendicular();92}9394// Blend in a little bit from mA1 so we're less than 90 degrees apart95a2 = (0.99f * perp.Normalized() + 0.01f * mA1).Normalized();96}97mB2 = a2.GetNormalizedPerpendicular();98mC2 = a2.Cross(mB2);99100// Calculate properties used during constraint solving101mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();102mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();103mB2xA1 = mB2.Cross(mA1);104mC2xA1 = mC2.Cross(mA1);105106// Calculate effective mass: K^-1 = (J M^-1 J^T)^-1107Mat44 summed_inv_inertia = mInvI1 + mInvI2;108Mat22 inv_effective_mass;109inv_effective_mass(0, 0) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));110inv_effective_mass(0, 1) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));111inv_effective_mass(1, 0) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));112inv_effective_mass(1, 1) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));113if (!mEffectiveMass.SetInversed(inv_effective_mass))114Deactivate();115}116117/// Deactivate this constraint118inline void Deactivate()119{120mEffectiveMass.SetZero();121mTotalLambda.SetZero();122}123124/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses125inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)126{127mTotalLambda *= inWarmStartImpulseRatio;128ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);129}130131/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.132inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)133{134// Calculate lagrange multiplier:135//136// lambda = -K^-1 (J v + b)137Vec3 delta_ang = ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity();138Vec2 jv;139jv[0] = mB2xA1.Dot(delta_ang);140jv[1] = mC2xA1.Dot(delta_ang);141Vec2 lambda = mEffectiveMass * jv;142143// Store accumulated lambda144mTotalLambda += lambda;145146return ApplyVelocityStep(ioBody1, ioBody2, lambda);147}148149/// Iteratively update the position constraint. Makes sure C(...) = 0.150inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const151{152// 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)153Vec2 c;154c[0] = mA1.Dot(mB2);155c[1] = mA1.Dot(mC2);156if (!c.IsZero())157{158// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:159//160// lambda = -K^-1 * beta / dt * C161//162// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out163Vec2 lambda = -inBaumgarte * (mEffectiveMass * c);164165// Directly integrate velocity change for one time step166//167// Euler velocity integration:168// dv = M^-1 P169//170// Impulse:171// P = J^T lambda172//173// Euler position integration:174// x' = x + dv * dt175//176// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and177// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte178// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity179// integrate + a position integrate and then discard the velocity change.180Vec3 impulse = mB2xA1 * lambda[0] + mC2xA1 * lambda[1];181if (ioBody1.IsDynamic())182ioBody1.SubRotationStep(mInvI1.Multiply3x3(impulse));183if (ioBody2.IsDynamic())184ioBody2.AddRotationStep(mInvI2.Multiply3x3(impulse));185return true;186}187188return false;189}190191/// Return lagrange multiplier192const Vec2 & GetTotalLambda() const193{194return mTotalLambda;195}196197/// Save state of this constraint part198void SaveState(StateRecorder &inStream) const199{200inStream.Write(mTotalLambda);201}202203/// Restore state of this constraint part204void RestoreState(StateRecorder &inStream)205{206inStream.Read(mTotalLambda);207}208209private:210Vec3 mA1; ///< World space hinge axis for body 1211Vec3 mB2; ///< World space perpendiculars of hinge axis for body 2212Vec3 mC2;213Mat44 mInvI1;214Mat44 mInvI2;215Vec3 mB2xA1;216Vec3 mC2xA1;217Mat22 mEffectiveMass;218Vec2 mTotalLambda { Vec2::sZero() };219};220221JPH_NAMESPACE_END222223224