Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/RotationEulerConstraintPart.h
22236 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/// Constrains rotation around all axis so that only translation is allowed12///13/// Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.5.114///15/// Constraint equation (eq 129):16///17/// \f[C = \begin{bmatrix}\Delta\theta_x, \Delta\theta_y, \Delta\theta_z\end{bmatrix}\f]18///19/// Jacobian (eq 131):20///21/// \f[J = \begin{bmatrix}0 & -E & 0 & E\end{bmatrix}\f]22///23/// Used terms (here and below, everything in world space):\n24/// delta_theta_* = difference in rotation between initial rotation of bodies 1 and 2.\n25/// x1, x2 = center of mass for the bodies.\n26/// v = [v1, w1, v2, w2].\n27/// v1, v2 = linear velocity of body 1 and 2.\n28/// w1, w2 = angular velocity of body 1 and 2.\n29/// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n30/// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n31/// b = velocity bias.\n32/// \f$\beta\f$ = baumgarte constant.\n33/// E = identity matrix.\n34class RotationEulerConstraintPart35{36private:37/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated38JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const39{40// Apply impulse if delta is not zero41if (inLambda != Vec3::sZero())42{43// Calculate velocity change due to constraint44//45// Impulse:46// P = J^T lambda47//48// Euler velocity integration:49// v' = v + M^-1 P50if (ioBody1.IsDynamic())51ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1.Multiply3x3(inLambda));52if (ioBody2.IsDynamic())53ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2.Multiply3x3(inLambda));54return true;55}5657return false;58}5960public:61/// Return inverse of initial rotation from body 1 to body 2 in body 1 space62static Quat sGetInvInitialOrientation(const Body &inBody1, const Body &inBody2)63{64// q20 = q10 r065// <=> r0 = q10^-1 q2066// <=> r0^-1 = q20^-1 q1067//68// where:69//70// q20 = initial orientation of body 271// q10 = initial orientation of body 172// r0 = initial rotation from body 1 to body 273return inBody2.GetRotation().Conjugated() * inBody1.GetRotation();74}7576/// @brief Return inverse of initial rotation from body 1 to body 2 in body 1 space77/// @param inAxisX1 Reference axis X for body 178/// @param inAxisY1 Reference axis Y for body 179/// @param inAxisX2 Reference axis X for body 280/// @param inAxisY2 Reference axis Y for body 281static Quat sGetInvInitialOrientationXY(Vec3Arg inAxisX1, Vec3Arg inAxisY1, Vec3Arg inAxisX2, Vec3Arg inAxisY2)82{83// Store inverse of initial rotation from body 1 to body 2 in body 1 space:84//85// q20 = q10 r086// <=> r0 = q10^-1 q2087// <=> r0^-1 = q20^-1 q1088//89// where:90//91// q10, q20 = world space initial orientation of body 1 and 292// r0 = initial rotation from body 1 to body 2 in local space of body 193//94// We can also write this in terms of the constraint matrices:95//96// q20 c2 = q10 c197// <=> q20 = q10 c1 c2^-198// => r0 = c1 c2^-199// <=> r0^-1 = c2 c1^-1100//101// where:102//103// c1, c2 = matrix that takes us from body 1 and 2 COM to constraint space 1 and 2104if (inAxisX1 == inAxisX2 && inAxisY1 == inAxisY2)105{106// Axis are the same -> identity transform107return Quat::sIdentity();108}109else110{111Mat44 constraint1(Vec4(inAxisX1, 0), Vec4(inAxisY1, 0), Vec4(inAxisX1.Cross(inAxisY1), 0), Vec4(0, 0, 0, 1));112Mat44 constraint2(Vec4(inAxisX2, 0), Vec4(inAxisY2, 0), Vec4(inAxisX2.Cross(inAxisY2), 0), Vec4(0, 0, 0, 1));113return constraint2.GetQuaternion() * constraint1.GetQuaternion().Conjugated();114}115}116117/// @brief Return inverse of initial rotation from body 1 to body 2 in body 1 space118/// @param inAxisX1 Reference axis X for body 1119/// @param inAxisZ1 Reference axis Z for body 1120/// @param inAxisX2 Reference axis X for body 2121/// @param inAxisZ2 Reference axis Z for body 2122static Quat sGetInvInitialOrientationXZ(Vec3Arg inAxisX1, Vec3Arg inAxisZ1, Vec3Arg inAxisX2, Vec3Arg inAxisZ2)123{124// See comment at sGetInvInitialOrientationXY125if (inAxisX1 == inAxisX2 && inAxisZ1 == inAxisZ2)126{127return Quat::sIdentity();128}129else130{131Mat44 constraint1(Vec4(inAxisX1, 0), Vec4(inAxisZ1.Cross(inAxisX1), 0), Vec4(inAxisZ1, 0), Vec4(0, 0, 0, 1));132Mat44 constraint2(Vec4(inAxisX2, 0), Vec4(inAxisZ2.Cross(inAxisX2), 0), Vec4(inAxisZ2, 0), Vec4(0, 0, 0, 1));133return constraint2.GetQuaternion() * constraint1.GetQuaternion().Conjugated();134}135}136137/// Calculate properties used during the functions below138inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, const Body &inBody2, Mat44Arg inRotation2)139{140// Calculate properties used during constraint solving141mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();142mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();143144// Calculate effective mass: K^-1 = (J M^-1 J^T)^-1145Mat44 inertia_sum = mInvI1 + mInvI2;146if (!mEffectiveMass.SetInversed3x3(inertia_sum))147{148// If a column is zero, the axis is locked and we set the column to identity.149// This does not matter because any impulse will always be multiplied with mInvI1 or mInvI2 which will result in zero for the locked coordinate.150Vec4 zero = Vec4::sZero();151if (inertia_sum.GetColumn4(0) == zero)152inertia_sum.SetColumn4(0, Vec4(1, 0, 0, 0));153if (inertia_sum.GetColumn4(1) == zero)154inertia_sum.SetColumn4(1, Vec4(0, 1, 0, 0));155if (inertia_sum.GetColumn4(2) == zero)156inertia_sum.SetColumn4(2, Vec4(0, 0, 1, 0));157if (!mEffectiveMass.SetInversed3x3(inertia_sum))158Deactivate();159}160}161162/// Deactivate this constraint163inline void Deactivate()164{165mEffectiveMass = Mat44::sZero();166mTotalLambda = Vec3::sZero();167}168169/// Check if constraint is active170inline bool IsActive() const171{172return mEffectiveMass(3, 3) != 0.0f;173}174175/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses176inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)177{178mTotalLambda *= inWarmStartImpulseRatio;179ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);180}181182/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.183inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)184{185// Calculate lagrange multiplier:186//187// lambda = -K^-1 (J v + b)188Vec3 lambda = mEffectiveMass.Multiply3x3(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity());189mTotalLambda += lambda;190return ApplyVelocityStep(ioBody1, ioBody2, lambda);191}192193/// Iteratively update the position constraint. Makes sure C(...) = 0.194inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, QuatArg inInvInitialOrientation, float inBaumgarte) const195{196// Calculate difference in rotation197//198// The rotation should be:199//200// q2 = q1 r0201//202// But because of drift the actual rotation is203//204// q2 = diff q1 r0205// <=> diff = q2 r0^-1 q1^-1206//207// Where:208// q1 = current rotation of body 1209// q2 = current rotation of body 2210// diff = error that needs to be reduced to zero211Quat diff = ioBody2.GetRotation() * inInvInitialOrientation * ioBody1.GetRotation().Conjugated();212213// A quaternion can be seen as:214//215// q = [sin(theta / 2) * v, cos(theta/2)]216//217// Where:218// v = rotation vector219// theta = rotation angle220//221// If we assume theta is small (error is small) then sin(x) = x so an approximation of the error angles is:222Vec3 error = 2.0f * diff.EnsureWPositive().GetXYZ();223if (error != Vec3::sZero())224{225// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:226//227// lambda = -K^-1 * beta / dt * C228//229// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out230Vec3 lambda = -inBaumgarte * mEffectiveMass * error;231232// Directly integrate velocity change for one time step233//234// Euler velocity integration:235// dv = M^-1 P236//237// Impulse:238// P = J^T lambda239//240// Euler position integration:241// x' = x + dv * dt242//243// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and244// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte245// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity246// integrate + a position integrate and then discard the velocity change.247if (ioBody1.IsDynamic())248ioBody1.SubRotationStep(mInvI1.Multiply3x3(lambda));249if (ioBody2.IsDynamic())250ioBody2.AddRotationStep(mInvI2.Multiply3x3(lambda));251return true;252}253254return false;255}256257/// Return lagrange multiplier258Vec3 GetTotalLambda() const259{260return mTotalLambda;261}262263/// Save state of this constraint part264void SaveState(StateRecorder &inStream) const265{266inStream.Write(mTotalLambda);267}268269/// Restore state of this constraint part270void RestoreState(StateRecorder &inStream)271{272inStream.Read(mTotalLambda);273}274275private:276Mat44 mInvI1;277Mat44 mInvI2;278Mat44 mEffectiveMass;279Vec3 mTotalLambda { Vec3::sZero() };280};281282JPH_NAMESPACE_END283284285