Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/GearConstraintPart.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>89JPH_NAMESPACE_BEGIN1011/// Constraint that constrains two rotations using a gear (rotating in opposite direction)12///13/// Constraint equation:14///15/// C = Rotation1(t) + r Rotation2(t)16///17/// Derivative:18///19/// d/dt C = 020/// <=> w1 . a + r w2 . b = 021///22/// Jacobian:23///24/// \f[J = \begin{bmatrix}0 & a^T & 0 & r b^T\end{bmatrix}\f]25///26/// Used terms (here and below, everything in world space):\n27/// a = axis around which body 1 rotates (normalized).\n28/// b = axis along which body 2 slides (normalized).\n29/// Rotation1(t) = rotation around a of body 1.\n30/// Rotation2(t) = rotation around b of body 2.\n31/// r = ratio between rotation for body 1 and 2.\n32/// v = [v1, w1, v2, w2].\n33/// v1, v2 = linear velocity of body 1 and 2.\n34/// w1, w2 = angular velocity of body 1 and 2.\n35/// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n36/// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n37/// \f$\beta\f$ = baumgarte constant.38class GearConstraintPart39{40/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated41JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const42{43// Apply impulse if delta is not zero44if (inLambda != 0.0f)45{46// Calculate velocity change due to constraint47//48// Impulse:49// P = J^T lambda50//51// Euler velocity integration:52// v' = v + M^-1 P53ioBody1.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI1_A);54ioBody2.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI2_B);55return true;56}5758return false;59}6061public:62/// Calculate properties used during the functions below63/// @param inBody1 The first body that this constraint is attached to64/// @param inBody2 The second body that this constraint is attached to65/// @param inWorldSpaceHingeAxis1 The axis around which body 1 rotates66/// @param inWorldSpaceHingeAxis2 The axis around which body 2 rotates67/// @param inRatio The ratio between rotation and translation68inline void CalculateConstraintProperties(const Body &inBody1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Vec3Arg inWorldSpaceHingeAxis2, float inRatio)69{70JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-4f));71JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-4f));7273// Calculate: I1^-1 a74mInvI1_A = inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceHingeAxis1);7576// Calculate: I2^-1 b77mInvI2_B = inBody2.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), inWorldSpaceHingeAxis2);7879// K^-1 = 1 / (J M^-1 J^T) = 1 / (a^T I1^-1 a + r^2 * b^T I2^-1 b)80float inv_effective_mass = (inWorldSpaceHingeAxis1.Dot(mInvI1_A) + inWorldSpaceHingeAxis2.Dot(mInvI2_B) * Square(inRatio));81if (inv_effective_mass == 0.0f)82Deactivate();83else84mEffectiveMass = 1.0f / inv_effective_mass;85}8687/// Deactivate this constraint88inline void Deactivate()89{90mEffectiveMass = 0.0f;91mTotalLambda = 0.0f;92}9394/// Check if constraint is active95inline bool IsActive() const96{97return mEffectiveMass != 0.0f;98}99100/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses101/// @param ioBody1 The first body that this constraint is attached to102/// @param ioBody2 The second body that this constraint is attached to103/// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame104inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)105{106mTotalLambda *= inWarmStartImpulseRatio;107ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);108}109110/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.111/// @param ioBody1 The first body that this constraint is attached to112/// @param ioBody2 The second body that this constraint is attached to113/// @param inWorldSpaceHingeAxis1 The axis around which body 1 rotates114/// @param inWorldSpaceHingeAxis2 The axis around which body 2 rotates115/// @param inRatio The ratio between rotation and translation116inline bool SolveVelocityConstraint(Body &ioBody1, Vec3Arg inWorldSpaceHingeAxis1, Body &ioBody2, Vec3Arg inWorldSpaceHingeAxis2, float inRatio)117{118// Lagrange multiplier is:119//120// lambda = -K^-1 (J v + b)121float lambda = -mEffectiveMass * (inWorldSpaceHingeAxis1.Dot(ioBody1.GetAngularVelocity()) + inRatio * inWorldSpaceHingeAxis2.Dot(ioBody2.GetAngularVelocity()));122mTotalLambda += lambda; // Store accumulated impulse123124return ApplyVelocityStep(ioBody1, ioBody2, lambda);125}126127/// Return lagrange multiplier128float GetTotalLambda() const129{130return mTotalLambda;131}132133/// Iteratively update the position constraint. Makes sure C(...) == 0.134/// @param ioBody1 The first body that this constraint is attached to135/// @param ioBody2 The second body that this constraint is attached to136/// @param inC Value of the constraint equation (C)137/// @param inBaumgarte Baumgarte constant (fraction of the error to correct)138inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const139{140// Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint141if (inC != 0.0f)142{143// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:144//145// lambda = -K^-1 * beta / dt * C146//147// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out148float lambda = -mEffectiveMass * inBaumgarte * inC;149150// Directly integrate velocity change for one time step151//152// Euler velocity integration:153// dv = M^-1 P154//155// Impulse:156// P = J^T lambda157//158// Euler position integration:159// x' = x + dv * dt160//161// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and162// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte163// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity164// integrate + a position integrate and then discard the velocity change.165if (ioBody1.IsDynamic())166ioBody1.AddRotationStep(lambda * mInvI1_A);167if (ioBody2.IsDynamic())168ioBody2.AddRotationStep(lambda * mInvI2_B);169return true;170}171172return false;173}174175/// Save state of this constraint part176void SaveState(StateRecorder &inStream) const177{178inStream.Write(mTotalLambda);179}180181/// Restore state of this constraint part182void RestoreState(StateRecorder &inStream)183{184inStream.Read(mTotalLambda);185}186187private:188Vec3 mInvI1_A;189Vec3 mInvI2_B;190float mEffectiveMass = 0.0f;191float mTotalLambda = 0.0f;192};193194JPH_NAMESPACE_END195196197