Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/RotationQuatConstraintPart.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/// Quaternion based constraint that constrains rotation around all axis so that only translation is allowed.12///13/// NOTE: This constraint part is more expensive than the RotationEulerConstraintPart and slightly more correct since14/// RotationEulerConstraintPart::SolvePositionConstraint contains an approximation. In practice the difference15/// is small, so the RotationEulerConstraintPart is probably the better choice.16///17/// Rotation is fixed between bodies like this:18///19/// q2 = q1 r020///21/// Where:22/// q1, q2 = world space quaternions representing rotation of body 1 and 2.23/// r0 = initial rotation between bodies in local space of body 1, this can be calculated by:24///25/// q20 = q10 r026/// <=> r0 = q10^* q2027///28/// Where:29/// q10, q20 = initial world space rotations of body 1 and 2.30/// q10^* = conjugate of quaternion q10 (which is the same as the inverse for a unit quaternion)31///32/// We exclusively use the conjugate below:33///34/// r0^* = q20^* q1035///36/// The error in the rotation is (in local space of body 1):37///38/// q2 = q1 error r039/// <=> error = q1^* q2 r0^*40///41/// The imaginary part of the quaternion represents the rotation axis * sin(angle / 2). The real part of the quaternion42/// does not add any additional information (we know the quaternion in normalized) and we're removing 3 degrees of freedom43/// so we want 3 parameters. Therefore we define the constraint equation like:44///45/// C = A q1^* q2 r0^* = 046///47/// Where (if you write a quaternion as [real-part, i-part, j-part, k-part]):48///49/// [0, 1, 0, 0]50/// A = [0, 0, 1, 0]51/// [0, 0, 0, 1]52///53/// or in our case since we store a quaternion like [i-part, j-part, k-part, real-part]:54///55/// [1, 0, 0, 0]56/// A = [0, 1, 0, 0]57/// [0, 0, 1, 0]58///59/// Time derivative:60///61/// d/dt C = A (q1^* d/dt(q2) + d/dt(q1^*) q2) r0^*62/// = A (q1^* (1/2 W2 q2) + (1/2 W1 q1)^* q2) r0^*63/// = 1/2 A (q1^* W2 q2 + q1^* W1^* q2) r0^*64/// = 1/2 A (q1^* W2 q2 - q1^* W1 * q2) r0^*65/// = 1/2 A ML(q1^*) MR(q2 r0^*) (W2 - W1)66/// = 1/2 A ML(q1^*) MR(q2 r0^*) A^T (w2 - w1)67///68/// Where:69/// W1 = [0, w1], W2 = [0, w2] (converting angular velocity to imaginary part of quaternion).70/// w1, w2 = angular velocity of body 1 and 2.71/// d/dt(q) = 1/2 W q (time derivative of a quaternion).72/// W^* = -W (conjugate negates angular velocity as quaternion).73/// ML(q): 4x4 matrix so that q * p = ML(q) * p, where q and p are quaternions.74/// MR(p): 4x4 matrix so that q * p = MR(p) * q, where q and p are quaternions.75/// A^T: Transpose of A.76///77/// Jacobian:78///79/// J = [0, -1/2 A ML(q1^*) MR(q2 r0^*) A^T, 0, 1/2 A ML(q1^*) MR(q2 r0^*) A^T]80/// = [0, -JP, 0, JP]81///82/// Suggested reading:83/// - 3D Constraint Derivations for Impulse Solvers - Marijn Tamis84/// - Game Physics Pearls - Section 9 - Quaternion Based Constraints - Claude Lacoursiere85class RotationQuatConstraintPart86{87private:88/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated89JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const90{91// Apply impulse if delta is not zero92if (inLambda != Vec3::sZero())93{94// Calculate velocity change due to constraint95//96// Impulse:97// P = J^T lambda98//99// Euler velocity integration:100// v' = v + M^-1 P101if (ioBody1.IsDynamic())102ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1_JPT.Multiply3x3(inLambda));103if (ioBody2.IsDynamic())104ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2_JPT.Multiply3x3(inLambda));105return true;106}107108return false;109}110111public:112/// Return inverse of initial rotation from body 1 to body 2 in body 1 space113static Quat sGetInvInitialOrientation(const Body &inBody1, const Body &inBody2)114{115// q20 = q10 r0116// <=> r0 = q10^-1 q20117// <=> r0^-1 = q20^-1 q10118//119// where:120//121// q20 = initial orientation of body 2122// q10 = initial orientation of body 1123// r0 = initial rotation from body 1 to body 2124return inBody2.GetRotation().Conjugated() * inBody1.GetRotation();125}126127/// Calculate properties used during the functions below128inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, const Body &inBody2, Mat44Arg inRotation2, QuatArg inInvInitialOrientation)129{130// Calculate: JP = 1/2 A ML(q1^*) MR(q2 r0^*) A^T131Mat44 jp = (Mat44::sQuatLeftMultiply(0.5f * inBody1.GetRotation().Conjugated()) * Mat44::sQuatRightMultiply(inBody2.GetRotation() * inInvInitialOrientation)).GetRotationSafe();132133// Calculate properties used during constraint solving134Mat44 inv_i1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();135Mat44 inv_i2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();136mInvI1_JPT = inv_i1.Multiply3x3RightTransposed(jp);137mInvI2_JPT = inv_i2.Multiply3x3RightTransposed(jp);138139// Calculate effective mass: K^-1 = (J M^-1 J^T)^-1140// = (JP * I1^-1 * JP^T + JP * I2^-1 * JP^T)^-1141// = (JP * (I1^-1 + I2^-1) * JP^T)^-1142if (!mEffectiveMass.SetInversed3x3(jp.Multiply3x3(inv_i1 + inv_i2).Multiply3x3RightTransposed(jp)))143Deactivate();144else145mEffectiveMass_JP = mEffectiveMass.Multiply3x3(jp);146}147148/// Deactivate this constraint149inline void Deactivate()150{151mEffectiveMass = Mat44::sZero();152mEffectiveMass_JP = Mat44::sZero();153mTotalLambda = Vec3::sZero();154}155156/// Check if constraint is active157inline bool IsActive() const158{159return mEffectiveMass(3, 3) != 0.0f;160}161162/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses163inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)164{165mTotalLambda *= inWarmStartImpulseRatio;166ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);167}168169/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.170inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)171{172// Calculate lagrange multiplier:173//174// lambda = -K^-1 (J v + b)175Vec3 lambda = mEffectiveMass_JP.Multiply3x3(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity());176mTotalLambda += lambda;177return ApplyVelocityStep(ioBody1, ioBody2, lambda);178}179180/// Iteratively update the position constraint. Makes sure C(...) = 0.181inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, QuatArg inInvInitialOrientation, float inBaumgarte) const182{183// Calculate constraint equation184Vec3 c = (ioBody1.GetRotation().Conjugated() * ioBody2.GetRotation() * inInvInitialOrientation).GetXYZ();185if (c != Vec3::sZero())186{187// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:188//189// lambda = -K^-1 * beta / dt * C190//191// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out192Vec3 lambda = -inBaumgarte * mEffectiveMass * c;193194// Directly integrate velocity change for one time step195//196// Euler velocity integration:197// dv = M^-1 P198//199// Impulse:200// P = J^T lambda201//202// Euler position integration:203// x' = x + dv * dt204//205// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and206// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte207// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity208// integrate + a position integrate and then discard the velocity change.209if (ioBody1.IsDynamic())210ioBody1.SubRotationStep(mInvI1_JPT.Multiply3x3(lambda));211if (ioBody2.IsDynamic())212ioBody2.AddRotationStep(mInvI2_JPT.Multiply3x3(lambda));213return true;214}215216return false;217}218219/// Return lagrange multiplier220Vec3 GetTotalLambda() const221{222return mTotalLambda;223}224225/// Save state of this constraint part226void SaveState(StateRecorder &inStream) const227{228inStream.Write(mTotalLambda);229}230231/// Restore state of this constraint part232void RestoreState(StateRecorder &inStream)233{234inStream.Read(mTotalLambda);235}236237private:238Mat44 mInvI1_JPT;239Mat44 mInvI2_JPT;240Mat44 mEffectiveMass;241Mat44 mEffectiveMass_JP;242Vec3 mTotalLambda { Vec3::sZero() };243};244245JPH_NAMESPACE_END246247248