Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/RackAndPinionConstraintPart.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 a rotation to a translation12///13/// Constraint equation:14///15/// C = Theta(t) - r d(t)16///17/// Derivative:18///19/// d/dt C = 020/// <=> w1 . a - r v2 . b = 021///22/// Jacobian:23///24/// \f[J = \begin{bmatrix}0 & a^T & -r b^T & 0\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/// Theta(t) = rotation around a of body 1.\n30/// d(t) = distance body 2 slides.\n31/// r = ratio between rotation and translation.\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 RackAndPinionConstraintPart39{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()->SubLinearVelocityStep(inLambda * mRatio_InvM2_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 inWorldSpaceHingeAxis The axis around which body 1 rotates66/// @param inWorldSpaceSliderAxis The axis along which body 2 slides67/// @param inRatio The ratio between rotation and translation68inline void CalculateConstraintProperties(const Body &inBody1, Vec3Arg inWorldSpaceHingeAxis, const Body &inBody2, Vec3Arg inWorldSpaceSliderAxis, float inRatio)69{70JPH_ASSERT(inWorldSpaceHingeAxis.IsNormalized(1.0e-4f));71JPH_ASSERT(inWorldSpaceSliderAxis.IsNormalized(1.0e-4f));7273// Calculate: I1^-1 a74mInvI1_A = inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceHingeAxis);7576// Calculate: r/m2 b77float inv_m2 = inBody2.GetMotionProperties()->GetInverseMass();78mRatio_InvM2_B = inRatio * inv_m2 * inWorldSpaceSliderAxis;7980// K^-1 = 1 / (J M^-1 J^T) = 1 / (a^T I1^-1 a + 1/m2 * r^2 * b . b)81float inv_effective_mass = (inWorldSpaceHingeAxis.Dot(mInvI1_A) + inv_m2 * Square(inRatio));82if (inv_effective_mass == 0.0f)83Deactivate();84else85mEffectiveMass = 1.0f / inv_effective_mass;86}8788/// Deactivate this constraint89inline void Deactivate()90{91mEffectiveMass = 0.0f;92mTotalLambda = 0.0f;93}9495/// Check if constraint is active96inline bool IsActive() const97{98return mEffectiveMass != 0.0f;99}100101/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses102/// @param ioBody1 The first body that this constraint is attached to103/// @param ioBody2 The second body that this constraint is attached to104/// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame105inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)106{107mTotalLambda *= inWarmStartImpulseRatio;108ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);109}110111/// 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 to113/// @param ioBody2 The second body that this constraint is attached to114/// @param inWorldSpaceHingeAxis The axis around which body 1 rotates115/// @param inWorldSpaceSliderAxis The axis along which body 2 slides116/// @param inRatio The ratio between rotation and translation117inline bool SolveVelocityConstraint(Body &ioBody1, Vec3Arg inWorldSpaceHingeAxis, Body &ioBody2, Vec3Arg inWorldSpaceSliderAxis, float inRatio)118{119// Lagrange multiplier is:120//121// lambda = -K^-1 (J v + b)122float lambda = mEffectiveMass * (inRatio * inWorldSpaceSliderAxis.Dot(ioBody2.GetLinearVelocity()) - inWorldSpaceHingeAxis.Dot(ioBody1.GetAngularVelocity()));123mTotalLambda += lambda; // Store accumulated impulse124125return ApplyVelocityStep(ioBody1, ioBody2, lambda);126}127128/// Return lagrange multiplier129float GetTotalLambda() const130{131return mTotalLambda;132}133134/// Iteratively update the position constraint. Makes sure C(...) == 0.135/// @param ioBody1 The first body that this constraint is attached to136/// @param ioBody2 The second body that this constraint is attached to137/// @param inC Value of the constraint equation (C)138/// @param inBaumgarte Baumgarte constant (fraction of the error to correct)139inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const140{141// Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint142if (inC != 0.0f)143{144// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:145//146// lambda = -K^-1 * beta / dt * C147//148// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out149float lambda = -mEffectiveMass * inBaumgarte * inC;150151// Directly integrate velocity change for one time step152//153// Euler velocity integration:154// dv = M^-1 P155//156// Impulse:157// P = J^T lambda158//159// Euler position integration:160// x' = x + dv * dt161//162// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and163// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte164// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity165// integrate + a position integrate and then discard the velocity change.166if (ioBody1.IsDynamic())167ioBody1.AddRotationStep(lambda * mInvI1_A);168if (ioBody2.IsDynamic())169ioBody2.SubPositionStep(lambda * mRatio_InvM2_B);170return true;171}172173return false;174}175176/// Save state of this constraint part177void SaveState(StateRecorder &inStream) const178{179inStream.Write(mTotalLambda);180}181182/// Restore state of this constraint part183void RestoreState(StateRecorder &inStream)184{185inStream.Read(mTotalLambda);186}187188private:189Vec3 mInvI1_A;190Vec3 mRatio_InvM2_B;191float mEffectiveMass = 0.0f;192float mTotalLambda = 0.0f;193};194195JPH_NAMESPACE_END196197198