Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/IndependentAxisConstraintPart.h
9913 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2022 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Physics/Body/Body.h>7#include <Jolt/Physics/StateRecorder.h>89JPH_NAMESPACE_BEGIN1011/// Constraint part to an AxisConstraintPart but both bodies have an independent axis on which the force is applied.12///13/// Constraint equation:14///15/// \f[C = (x_1 + r_1 - f_1) . n_1 + r (x_2 + r_2 - f_2) \cdot n_2\f]16///17/// Calculating the Jacobian:18///19/// \f[dC/dt = (v_1 + w_1 \times r_1) \cdot n_1 + (x_1 + r_1 - f_1) \cdot d n_1/dt + r (v_2 + w_2 \times r_2) \cdot n_2 + r (x_2 + r_2 - f_2) \cdot d n_2/dt\f]20///21/// Assuming that d n1/dt and d n2/dt are small this becomes:22///23/// \f[(v_1 + w_1 \times r_1) \cdot n_1 + r (v_2 + w_2 \times r_2) \cdot n_2\f]24/// \f[= v_1 \cdot n_1 + r_1 \times n_1 \cdot w_1 + r v_2 \cdot n_2 + r r_2 \times n_2 \cdot w_2\f]25///26/// Jacobian:27///28/// \f[J = \begin{bmatrix}n_1 & r_1 \times n_1 & r n_2 & r r_2 \times n_2\end{bmatrix}\f]29///30/// Effective mass:31///32/// \f[K = m_1^{-1} + r_1 \times n_1 I_1^{-1} r_1 \times n_1 + r^2 m_2^{-1} + r^2 r_2 \times n_2 I_2^{-1} r_2 \times n_2\f]33///34/// Used terms (here and below, everything in world space):\n35/// n1 = (x1 + r1 - f1) / |x1 + r1 - f1|, axis along which the force is applied for body 1\n36/// n2 = (x2 + r2 - f2) / |x2 + r2 - f2|, axis along which the force is applied for body 2\n37/// r = ratio how forces are applied between bodies.\n38/// x1, x2 = center of mass for the bodies.\n39/// v = [v1, w1, v2, w2].\n40/// v1, v2 = linear velocity of body 1 and 2.\n41/// w1, w2 = angular velocity of body 1 and 2.\n42/// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n43/// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n44/// b = velocity bias.\n45/// \f$\beta\f$ = baumgarte constant.46class IndependentAxisConstraintPart47{48/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated49JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inLambda) const50{51// Apply impulse if delta is not zero52if (inLambda != 0.0f)53{54// Calculate velocity change due to constraint55//56// Impulse:57// P = J^T lambda58//59// Euler velocity integration:60// v' = v + M^-1 P61if (ioBody1.IsDynamic())62{63MotionProperties *mp1 = ioBody1.GetMotionProperties();64mp1->AddLinearVelocityStep((mp1->GetInverseMass() * inLambda) * inN1);65mp1->AddAngularVelocityStep(mInvI1_R1xN1 * inLambda);66}67if (ioBody2.IsDynamic())68{69MotionProperties *mp2 = ioBody2.GetMotionProperties();70mp2->AddLinearVelocityStep((inRatio * mp2->GetInverseMass() * inLambda) * inN2);71mp2->AddAngularVelocityStep(mInvI2_RatioR2xN2 * inLambda);72}73return true;74}7576return false;77}7879public:80/// Calculate properties used during the functions below81/// @param inBody1 The first body that this constraint is attached to82/// @param inBody2 The second body that this constraint is attached to83/// @param inR1 The position on which the constraint operates on body 1 relative to COM84/// @param inN1 The world space normal in which the constraint operates for body 185/// @param inR2 The position on which the constraint operates on body 1 relative to COM86/// @param inN2 The world space normal in which the constraint operates for body 287/// @param inRatio The ratio how forces are applied between bodies88inline void CalculateConstraintProperties(const Body &inBody1, const Body &inBody2, Vec3Arg inR1, Vec3Arg inN1, Vec3Arg inR2, Vec3Arg inN2, float inRatio)89{90JPH_ASSERT(inN1.IsNormalized(1.0e-4f) && inN2.IsNormalized(1.0e-4f));9192float inv_effective_mass = 0.0f;9394if (!inBody1.IsStatic())95{96const MotionProperties *mp1 = inBody1.GetMotionProperties();9798mR1xN1 = inR1.Cross(inN1);99mInvI1_R1xN1 = mp1->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), mR1xN1);100101inv_effective_mass += mp1->GetInverseMass() + mInvI1_R1xN1.Dot(mR1xN1);102}103104if (!inBody2.IsStatic())105{106const MotionProperties *mp2 = inBody2.GetMotionProperties();107108mRatioR2xN2 = inRatio * inR2.Cross(inN2);109mInvI2_RatioR2xN2 = mp2->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), mRatioR2xN2);110111inv_effective_mass += Square(inRatio) * mp2->GetInverseMass() + mInvI2_RatioR2xN2.Dot(mRatioR2xN2);112}113114// Calculate inverse effective mass: K = J M^-1 J^T115if (inv_effective_mass == 0.0f)116Deactivate();117else118mEffectiveMass = 1.0f / inv_effective_mass;119}120121/// Deactivate this constraint122inline void Deactivate()123{124mEffectiveMass = 0.0f;125mTotalLambda = 0.0f;126}127128/// Check if constraint is active129inline bool IsActive() const130{131return mEffectiveMass != 0.0f;132}133134/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses135/// @param ioBody1 The first body that this constraint is attached to136/// @param ioBody2 The second body that this constraint is attached to137/// @param inN1 The world space normal in which the constraint operates for body 1138/// @param inN2 The world space normal in which the constraint operates for body 2139/// @param inRatio The ratio how forces are applied between bodies140/// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame141inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inWarmStartImpulseRatio)142{143mTotalLambda *= inWarmStartImpulseRatio;144ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, inRatio, mTotalLambda);145}146147/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.148/// @param ioBody1 The first body that this constraint is attached to149/// @param ioBody2 The second body that this constraint is attached to150/// @param inN1 The world space normal in which the constraint operates for body 1151/// @param inN2 The world space normal in which the constraint operates for body 2152/// @param inRatio The ratio how forces are applied between bodies153/// @param inMinLambda Minimum angular impulse to apply (N m s)154/// @param inMaxLambda Maximum angular impulse to apply (N m s)155inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inMinLambda, float inMaxLambda)156{157// Lagrange multiplier is:158//159// lambda = -K^-1 (J v + b)160float lambda = -mEffectiveMass * (inN1.Dot(ioBody1.GetLinearVelocity()) + mR1xN1.Dot(ioBody1.GetAngularVelocity()) + inRatio * inN2.Dot(ioBody2.GetLinearVelocity()) + mRatioR2xN2.Dot(ioBody2.GetAngularVelocity()));161float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse162lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply163mTotalLambda = new_lambda; // Store accumulated impulse164165return ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, inRatio, lambda);166}167168/// Return lagrange multiplier169float GetTotalLambda() const170{171return mTotalLambda;172}173174/// Iteratively update the position constraint. Makes sure C(...) == 0.175/// @param ioBody1 The first body that this constraint is attached to176/// @param ioBody2 The second body that this constraint is attached to177/// @param inN1 The world space normal in which the constraint operates for body 1178/// @param inN2 The world space normal in which the constraint operates for body 2179/// @param inRatio The ratio how forces are applied between bodies180/// @param inC Value of the constraint equation (C)181/// @param inBaumgarte Baumgarte constant (fraction of the error to correct)182inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inC, float inBaumgarte) const183{184if (inC != 0.0f)185{186// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:187//188// lambda = -K^-1 * beta / dt * C189//190// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out191float lambda = -mEffectiveMass * inBaumgarte * inC;192193// Directly integrate velocity change for one time step194//195// Euler velocity integration:196// dv = M^-1 P197//198// Impulse:199// P = J^T lambda200//201// Euler position integration:202// x' = x + dv * dt203//204// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and205// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte206// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity207// integrate + a position integrate and then discard the velocity change.208if (ioBody1.IsDynamic())209{210ioBody1.AddPositionStep((lambda * ioBody1.GetMotionPropertiesUnchecked()->GetInverseMass()) * inN1);211ioBody1.AddRotationStep(lambda * mInvI1_R1xN1);212}213if (ioBody2.IsDynamic())214{215ioBody2.AddPositionStep((lambda * inRatio * ioBody2.GetMotionPropertiesUnchecked()->GetInverseMass()) * inN2);216ioBody2.AddRotationStep(lambda * mInvI2_RatioR2xN2);217}218return true;219}220221return false;222}223224/// Save state of this constraint part225void SaveState(StateRecorder &inStream) const226{227inStream.Write(mTotalLambda);228}229230/// Restore state of this constraint part231void RestoreState(StateRecorder &inStream)232{233inStream.Read(mTotalLambda);234}235236private:237Vec3 mR1xN1;238Vec3 mInvI1_R1xN1;239Vec3 mRatioR2xN2;240Vec3 mInvI2_RatioR2xN2;241float mEffectiveMass = 0.0f;242float mTotalLambda = 0.0f;243};244245JPH_NAMESPACE_END246247248