Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/RotationEulerConstraintPart.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/// 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)^-1145if (!mEffectiveMass.SetInversed3x3(mInvI1 + mInvI2))146Deactivate();147}148149/// Deactivate this constraint150inline void Deactivate()151{152mEffectiveMass = 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.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 difference in rotation184//185// The rotation should be:186//187// q2 = q1 r0188//189// But because of drift the actual rotation is190//191// q2 = diff q1 r0192// <=> diff = q2 r0^-1 q1^-1193//194// Where:195// q1 = current rotation of body 1196// q2 = current rotation of body 2197// diff = error that needs to be reduced to zero198Quat diff = ioBody2.GetRotation() * inInvInitialOrientation * ioBody1.GetRotation().Conjugated();199200// A quaternion can be seen as:201//202// q = [sin(theta / 2) * v, cos(theta/2)]203//204// Where:205// v = rotation vector206// theta = rotation angle207//208// If we assume theta is small (error is small) then sin(x) = x so an approximation of the error angles is:209Vec3 error = 2.0f * diff.EnsureWPositive().GetXYZ();210if (error != Vec3::sZero())211{212// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:213//214// lambda = -K^-1 * beta / dt * C215//216// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out217Vec3 lambda = -inBaumgarte * mEffectiveMass * error;218219// Directly integrate velocity change for one time step220//221// Euler velocity integration:222// dv = M^-1 P223//224// Impulse:225// P = J^T lambda226//227// Euler position integration:228// x' = x + dv * dt229//230// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and231// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte232// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity233// integrate + a position integrate and then discard the velocity change.234if (ioBody1.IsDynamic())235ioBody1.SubRotationStep(mInvI1.Multiply3x3(lambda));236if (ioBody2.IsDynamic())237ioBody2.AddRotationStep(mInvI2.Multiply3x3(lambda));238return true;239}240241return false;242}243244/// Return lagrange multiplier245Vec3 GetTotalLambda() const246{247return mTotalLambda;248}249250/// Save state of this constraint part251void SaveState(StateRecorder &inStream) const252{253inStream.Write(mTotalLambda);254}255256/// Restore state of this constraint part257void RestoreState(StateRecorder &inStream)258{259inStream.Read(mTotalLambda);260}261262private:263Mat44 mInvI1;264Mat44 mInvI2;265Mat44 mEffectiveMass;266Vec3 mTotalLambda { Vec3::sZero() };267};268269JPH_NAMESPACE_END270271272