using System;
using System.Diagnostics;
using Godot;
using Lodur;
using Lodur.Body.Ymir;
using Ymir.Box3D;
namespace RustToDust.Client.Tests;
public struct BakeoffTelemetry
{
public float SimTimeS;
public float DistanceZ;
public float SpeedZ;
public float LateralX;
public float PelvisY;
public float TiltDeg;
public float MaxFootSlipM;
public bool FellOver;
public float RecoveryTimeS;
public double CpuCtrlMsPerTick;
public bool LeftCrippled;
public bool LeftContact;
public bool RightContact;
public float LeftGrfN;
public float RightGrfN;
}
internal static class BreakerLegGeometry
{
public const float TotalMassKg = 3800f;
public const float Gravity = 9.81f;
public const float HipOffsetX = 1.0809f;
public const float HipHeightInStandingBody = 3.4509f;
public const float ComHeightStanding = 4.10f;
public const float HipOffsetYInCom = HipHeightInStandingBody - ComHeightStanding; // -0.6491m
public const float ThighLen = 1.3203f;
public const float ShinLen = 1.4396f; // 1.5056m GLB rest minus 0.066m static 1G oleo compression
public const float AnkleHeight = 0.6249f;
public const float RideHeightAboveGround = 3.82f; // COM height above terrain (~0.28m crouch)
public const float MaxLegReach = ThighLen + ShinLen - 0.02f;
public static readonly Basis StraightLegBasis = new(Vector3.Right, Vector3.Down, Vector3.Forward);
public static Vector3 ToGodot(Quat q, float x, float y, float z)
{
q.Rotate(x, y, z, out float rx, out float ry, out float rz);
return new Vector3(rx, ry, rz);
}
public static Basis ToGodotBasis(in Quat q) => new(new Quaternion(q.X, q.Y, q.Z, q.W));
public static Quaternion ToGodotQuat(in Quat q) => new(q.X, q.Y, q.Z, q.W);
public static Quat ToLodurQuat(Quaternion q) => new(q.X, q.Y, q.Z, q.W);
///
/// Solves exact analytical 2-bone Law-of-Cosines IK from hip world pos to ankle world pos,
/// returning world bases for thigh (aligned along hip->knee with +X knee bend axis) and shin (knee->ankle).
///
public static void SolveTwoBoneIkWorld(
Vector3 hipWorld,
Vector3 ankleWorld,
Vector3 forwardRef,
Vector3 rightAxisRef,
out Vector3 kneeWorld,
out Basis thighBasis,
out Basis shinBasis)
{
Vector3 delta = ankleWorld - hipWorld;
float dist = delta.Length();
float minReach = MathF.Abs(ShinLen - ThighLen) + 0.12f;
float maxReach = MaxLegReach;
float d = Math.Clamp(dist, minReach, maxReach);
Vector3 dir = dist > 1e-5f ? delta / dist : Vector3.Down;
// Plane normal is lateral leg axis (+X in mech frame); knee bends forward along +Z
Vector3 legX = rightAxisRef;
if (MathF.Abs(legX.Dot(dir)) > 0.96f)
{
legX = forwardRef.Cross(dir);
}
else
{
legX = (legX - dir * legX.Dot(dir));
}
legX = legX.LengthSquared() > 1e-6f ? legX.Normalized() : Vector3.Right;
Vector3 bendFwd = legX.Cross(-dir).Normalized(); // direction perpendicular to dir toward forward
float cosAlpha = Math.Clamp((ThighLen * ThighLen + d * d - ShinLen * ShinLen) / (2f * ThighLen * d), -1f, 1f);
float sinAlpha = MathF.Sqrt(MathF.Max(0f, 1f - cosAlpha * cosAlpha));
Vector3 thighDir = (dir * cosAlpha + bendFwd * sinAlpha).Normalized();
kneeWorld = hipWorld + thighDir * ThighLen;
Vector3 shinDir = (hipWorld + dir * d - kneeWorld).Normalized();
thighBasis = BasisFromDownAndRight(thighDir, legX);
shinBasis = BasisFromDownAndRight(shinDir, legX);
}
public static Basis BasisFromDownAndRight(Vector3 downDir, Vector3 rightX)
{
Vector3 upY = -downDir.Normalized();
Vector3 x = (rightX - upY * rightX.Dot(upY));
x = x.LengthSquared() > 1e-6f ? x.Normalized() : Vector3.Right;
Vector3 z = x.Cross(upY).Normalized();
x = upY.Cross(z).Normalized();
return new Basis(x, upY, z);
}
public static void PoseBreakerVisual(
VehicleVisualInstance visual,
Vector3 pelvisComWorld,
Basis pelvisBasis,
Basis thighBasisL,
Basis shinBasisL,
Basis footBasisL,
Basis thighBasisR,
Basis shinBasisR,
Basis footBasisR,
float leftLoadG,
float rightLoadG,
float dt)
{
visual.ModelRoot.Transform = Transform3D.Identity;
// Align GLB Pelvis origin (0, 3.3626, 0) with the hip-level plane (pelvisCom + HipOffsetYInCom)
Vector3 hipPlaneWorld = pelvisComWorld + pelvisBasis * new Vector3(0f, HipOffsetYInCom, 0f);
Vector3 rootOrigin = hipPlaneWorld - pelvisBasis * new Vector3(0f, 3.3626f, 0f);
visual.Root.GlobalTransform = new Transform3D(pelvisBasis, rootOrigin);
ApplyOneLegVisual(visual, "L", thighBasisL, shinBasisL, footBasisL);
ApplyOneLegVisual(visual, "R", thighBasisR, shinBasisR, footBasisR);
VehicleRigAnimator.StepBreakerLinkages(visual, leftLoadG, rightLoadG, dt);
}
private static void ApplyOneLegVisual(
VehicleVisualInstance visual,
string side,
Basis thighBasis,
Basis shinBasis,
Basis footBasis)
{
if (visual.GetNamedNode($"Leg{side}.Hip") is { } hipNode)
{
hipNode.GlobalTransform = new Transform3D(thighBasis * StraightLegBasis, hipNode.GlobalPosition);
}
if (visual.GetNamedNode($"Leg{side}.Shin") is { } shinNode)
{
shinNode.GlobalTransform = new Transform3D(shinBasis * StraightLegBasis, shinNode.GlobalPosition);
}
if (visual.GetNamedNode($"Leg{side}.Foot") is { } footNode &&
visual.TryGetRestLocal($"Leg{side}.Foot", out var restFoot) &&
footNode.GetParent() is Node3D forkNode)
{
Basis localBasis = forkNode.GlobalBasis.Orthonormalized().Inverse() * (footBasis * StraightLegBasis);
footNode.Transform = new Transform3D(localBasis, restFoot.Origin);
}
}
}
///
/// Option 1: Full 7-body articulated in +
/// Ymir contacts on + Raibert/Capture-Point swing + stance Jacobian-transpose VMC.
///
public sealed class RagdollVmcController
{
public const int PartPelvis = 0;
public const int PartThighL = 1;
public const int PartShinL = 2;
public const int PartFootL = 3;
public const int PartThighR = 4;
public const int PartShinR = 5;
public const int PartFootR = 6;
private readonly Box3DSoaWorld _world;
private readonly WalkBakeoffTrack _track;
private readonly BodyPlan _plan;
private readonly Ragdoll _ragdoll;
private readonly float[] _strengths;
private readonly Quat[] _targets;
private readonly Quat[] _jointFrames;
private readonly Quat[] _jointFramesInv;
private readonly float _startX;
private float _totalMass;
private float _simTime;
private int _stanceLeg; // 0 = L, 1 = R
private float _swingTime;
private float _stepDuration = 0.28f;
private float _doubleSupportBlend = 1f;
private Vector3 _swingStartAnkle;
private bool _shoved;
private float _shoveTime = -1f;
private bool _recovered;
private float _recoveryTimeS = -1f;
private float _fellTimer;
private bool _fellOver;
private float _maxFootSlipM;
private bool _prevContactL;
private bool _prevContactR;
private Vector2 _touchdownXzL;
private Vector2 _touchdownXzR;
private double _cpuMsSum;
private long _ticks;
public RagdollVmcController(Box3DSoaWorld world, WalkBakeoffTrack track, float startX, ulong firstStableId)
{
_world = world;
_track = track;
_startX = startX;
_plan = BuildBreakerBodyPlan();
_ragdoll = Ragdoll.Build(world, _plan, (startX, 0f), firstStableId);
_strengths = new float[_plan.Joints.Count];
_targets = new Quat[_plan.Joints.Count];
_jointFrames = new Quat[_plan.Joints.Count];
_jointFramesInv = new Quat[_plan.Joints.Count];
for (int j = 0; j < _plan.Joints.Count; j++)
{
_targets[j] = Quat.Identity;
_strengths[j] = 1f;
_jointFrames[j] = Ik.JointFrame(_plan.Joints[j]);
_jointFramesInv[j] = _jointFrames[j].Conjugate();
}
var v = _world.View;
for (int p = 0; p < _plan.Parts.Count; p++)
{
_totalMass += v.Mass[_ragdoll.BodyLane(p)];
}
}
public Ragdoll Ragdoll => _ragdoll;
public BodyPlan Plan => _plan;
public int PelvisLane => _ragdoll.BodyLane(PartPelvis);
public float TotalMassKg => _totalMass;
public static (int Bodies, int Joints, int Sensors) RequiredCapacity => Ragdoll.Needs(BuildBreakerBodyPlan());
public static BodyPlan BuildBreakerBodyPlan()
{
var parts = new PartDef[7];
var joints = new JointDef[6];
const float friction = 0.90f;
const float pelvisDensity = 460f;
const float limbDensity = 210f;
// Creation pose stands straight with foot soles at Y = 0
float footCenterY = BreakerLegGeometry.AnkleHeight * 0.5f;
float ankleY = BreakerLegGeometry.AnkleHeight;
float shinCenterY = ankleY + BreakerLegGeometry.ShinLen * 0.5f;
float kneeY = ankleY + BreakerLegGeometry.ShinLen;
float thighCenterY = kneeY + BreakerLegGeometry.ThighLen * 0.5f;
float hipY = kneeY + BreakerLegGeometry.ThighLen; // 3.4509m
float pelvisCenterY = BreakerLegGeometry.ComHeightStanding; // 4.10m
parts[PartPelvis] = new PartDef(
"Pelvis", Lodur.Side.Center, PartShape.Box,
(1.15f, 1.00f, 0.75f), (0f, pelvisCenterY, 0f), Quat.Identity, pelvisDensity, friction, 0f);
for (int sideIdx = 0; sideIdx < 2; sideIdx++)
{
Lodur.Side side = sideIdx == 0 ? Lodur.Side.Left : Lodur.Side.Right;
float sx = sideIdx == 0 ? 1f : -1f;
float hx = sx * BreakerLegGeometry.HipOffsetX;
int thighIdx = sideIdx == 0 ? PartThighL : PartThighR;
int shinIdx = sideIdx == 0 ? PartShinL : PartShinR;
int footIdx = sideIdx == 0 ? PartFootL : PartFootR;
parts[thighIdx] = new PartDef(
"Thigh", side, PartShape.Capsule,
(0.25f, BreakerLegGeometry.ThighLen * 0.5f - 0.25f, 0f),
(hx, thighCenterY, 0f), Quat.Identity, limbDensity, friction, 0f);
parts[shinIdx] = new PartDef(
"Shin", side, PartShape.Capsule,
(0.23f, BreakerLegGeometry.ShinLen * 0.5f - 0.23f, 0f),
(hx, shinCenterY, 0f), Quat.Identity, limbDensity, friction, 0f);
parts[footIdx] = new PartDef(
"Foot", side, PartShape.Box,
(0.32f, footCenterY, 0.68f),
(hx, footCenterY, 0f), Quat.Identity, limbDensity, friction, 0f);
int jBase = sideIdx * 3;
joints[jBase + 0] = new JointDef(
"Hip", side, JointKind.Spherical, PartPelvis, thighIdx,
(hx, hipY, 0f), (0f, 1f, 0f),
-0.35f, 0.35f, 1.25f,
new MuscleGains(98000f, 4800f, 18000f, 1100f, passive: 0.15f));
joints[jBase + 1] = new JointDef(
"Knee", side, JointKind.Revolute, thighIdx, shinIdx,
(hx, kneeY, 0f), (1f, 0f, 0f),
-0.05f, 2.15f, 0f,
new MuscleGains(0f, 0f, 74000f, 3600f, passive: 0.15f));
joints[jBase + 2] = new JointDef(
"Ankle", side, JointKind.Spherical, shinIdx, footIdx,
(hx, ankleY, 0f), (0f, 1f, 0f),
-0.25f, 0.25f, 0.85f,
new MuscleGains(24000f, 850f, 2000f, 140f, passive: 0.20f));
}
return new BodyPlan(parts, joints, Array.Empty());
}
public void NotifyShove(float impulseX)
{
var v = _world.View;
int pel = PelvisLane;
Vector3 pelPos = new(v.PositionX[pel], v.PositionY[pel], v.PositionZ[pel]);
Quaternion pelQ = new(v.RotationX[pel], v.RotationY[pel], v.RotationZ[pel], v.RotationW[pel]);
// Hit right shoulder (-X side, +Y shoulder height above COM)
Vector3 hitWorld = pelPos + pelQ * new Vector3(-1.15f, 1.35f, 0.10f);
_world.ApplyImpulse(pel, (impulseX, 0f, 0f), (hitWorld.X, hitWorld.Y, hitWorld.Z));
_shoved = true;
_shoveTime = _simTime;
_recovered = false;
_recoveryTimeS = -1f;
}
public void StepControl(float dt, Vector2 cmdVelHoriz, bool leftLegCrippled)
{
long t0 = Stopwatch.GetTimestamp();
_simTime += dt;
var v = _world.View;
int pel = PelvisLane;
Vector3 pelPos = new(v.PositionX[pel], v.PositionY[pel], v.PositionZ[pel]);
Quaternion pelQ = new(v.RotationX[pel], v.RotationY[pel], v.RotationZ[pel], v.RotationW[pel]);
Vector3 pelVel = new(v.VelocityX[pel], v.VelocityY[pel], v.VelocityZ[pel]);
Vector3 pelAngVel = new(v.AngularVelocityX[pel], v.AngularVelocityY[pel], v.AngularVelocityZ[pel]);
int footL = _ragdoll.BodyLane(PartFootL);
int footR = _ragdoll.BodyLane(PartFootR);
Vector3 footPosL = new(v.PositionX[footL], v.PositionY[footL], v.PositionZ[footL]);
Vector3 footPosR = new(v.PositionX[footR], v.PositionY[footR], v.PositionZ[footR]);
// Check ONLY real ground (StableId == 1) touching facts so leg-leg brushes never spoof ground contact
bool touchGroundL = false;
bool touchGroundR = false;
foreach (var t in _world.Facts.Touching)
{
if (t.StableIdA == 1)
{
if (t.LaneB == footL) touchGroundL = true;
else if (t.LaneB == footR) touchGroundR = true;
}
else if (t.StableIdB == 1)
{
if (t.LaneA == footL) touchGroundL = true;
else if (t.LaneA == footR) touchGroundR = true;
}
}
bool contactL = touchGroundL && footPosL.Y <= _track.SampleHeight(footPosL.X, footPosL.Z) + BreakerLegGeometry.AnkleHeight * 0.5f + 0.14f;
bool contactR = touchGroundR && footPosR.Y <= _track.SampleHeight(footPosR.X, footPosR.Z) + BreakerLegGeometry.AnkleHeight * 0.5f + 0.14f;
// Honest foot slip measurement during stance contact
UpdateFootSlip(0, contactL, new Vector2(footPosL.X, footPosL.Z));
UpdateFootSlip(1, contactR, new Vector2(footPosR.X, footPosR.Z));
float cmdSpeed = cmdVelHoriz.Length();
bool walking = cmdSpeed > 0.25f || new Vector2(pelVel.X, pelVel.Z).Length() > 0.45f;
// Gait state machine
int swingLeg = 1 - _stanceLeg;
bool swingContact = swingLeg == 0 ? contactL : contactR;
bool stanceContact = _stanceLeg == 0 ? contactL : contactR;
if (_simTime < 0.18f)
{
// Initial brief settle in balanced crouch
_swingTime = 0f;
}
else if (walking)
{
_swingTime += dt;
float u = _swingTime / _stepDuration;
bool earlyTouchdown = u >= 0.72f && swingContact;
bool lateTouchdown = u >= 0.92f && swingContact;
// Never swap stance onto an airborne foot unless falling too far (> 1.8 * T_step)
if (earlyTouchdown || lateTouchdown || u >= 1.8f)
{
_stanceLeg = swingLeg;
swingLeg = 1 - _stanceLeg;
_swingTime = 0f;
_doubleSupportBlend = 0f;
Vector3 newSwingFoot = swingLeg == 0 ? footPosL : footPosR;
_swingStartAnkle = new Vector3(newSwingFoot.X, newSwingFoot.Y + BreakerLegGeometry.AnkleHeight * 0.5f, newSwingFoot.Z);
}
}
_doubleSupportBlend = Math.Min(1f, _doubleSupportBlend + dt / 0.08f);
// Compute desired orientation (facing +Z, mild forward lean when accelerating)
float targetPitch = Math.Clamp((cmdVelHoriz.Y - pelVel.Z) * 0.015f + cmdVelHoriz.Y * 0.008f, -0.04f, 0.06f);
Quaternion targetPelQ = new(Vector3.Right, targetPitch);
Vector3 pelFwd = pelQ * Vector3.Back; // +Z forward in Godot
pelFwd = new Vector3(pelFwd.X, 0f, pelFwd.Z);
if (pelFwd.LengthSquared() < 1e-4f) pelFwd = Vector3.Back;
Vector3 pelRightX = pelQ * Vector3.Right;
float effectiveStepDur = MathF.Abs(pelVel.X - cmdVelHoriz.X) > 1.1f ? 0.24f : _stepDuration;
float uSwing = Math.Clamp(_swingTime / effectiveStepDur, 0f, 1f);
// Actual Ymir Hip joint world position (must be used for IK!)
float realHipSideX = swingLeg == 0 ? BreakerLegGeometry.HipOffsetX : -BreakerLegGeometry.HipOffsetX;
Vector3 swingHipWorld = pelPos + pelQ * new Vector3(realHipSideX, BreakerLegGeometry.HipOffsetYInCom, 0f);
// Desired nominal foot X sits in a +-0.72m corridor around lane/pelvis midline
float nominalFootSideX = walking ? (swingLeg == 0 ? 0.72f : -0.72f) : realHipSideX;
float laneBlendX = Mathf.Lerp(pelPos.X, _startX, 0.25f);
Vector2 horizVel = new(pelVel.X, pelVel.Z);
// Lane-centering feedback expressed as desired lateral velocity
float cmdVelX = cmdVelHoriz.X + (MathF.Abs(cmdVelHoriz.X) < 0.05f ? Math.Clamp(1.35f * (_startX - pelPos.X), -1.8f, 1.8f) : 0f);
// Capture point + Raibert velocity feedback
const float opt1RideHeight = 3.68f;
float omega0 = MathF.Sqrt(BreakerLegGeometry.Gravity / opt1RideHeight);
float kCaptureLat = 0.42f / omega0;
float kCaptureFwd = 0.20f / omega0;
Vector2 stepOffsetHoriz = new(
horizVel.X * (effectiveStepDur * 0.45f) + (horizVel.X - cmdVelX) * kCaptureLat,
horizVel.Y * (effectiveStepDur * 0.85f) + (horizVel.Y - cmdVelHoriz.Y) * kCaptureFwd + 0.25f * cmdVelHoriz.Y * effectiveStepDur);
if (cmdVelHoriz.Y > 0.5f)
{
stepOffsetHoriz.Y = MathF.Max(stepOffsetHoriz.Y, 0.45f * MathF.Max(1.2f, cmdVelHoriz.Y) * effectiveStepDur);
}
if (!walking)
{
stepOffsetHoriz = Vector2.Zero;
}
float targetStepX = laneBlendX + nominalFootSideX + stepOffsetHoriz.X;
float targetStepZ = pelPos.Z + stepOffsetHoriz.Y;
// Prevent swing foot from crossing Pelvis midline or colliding with the planted stance foot!
int stFootLane = _ragdoll.BodyLane(_stanceLeg == 0 ? PartFootL : PartFootR);
float stanceFootX = v.PositionX[stFootLane];
if (swingLeg == 0)
{
float lo = MathF.Max(stanceFootX + 0.80f, pelPos.X + 0.25f);
float hi = MathF.Max(lo, pelPos.X + 1.45f);
targetStepX = Math.Clamp(targetStepX, lo, hi);
}
else
{
float hi = MathF.Min(stanceFootX - 0.80f, pelPos.X - 0.25f);
float lo = MathF.Min(hi, pelPos.X - 1.45f);
targetStepX = Math.Clamp(targetStepX, lo, hi);
}
// Clamp horizontal reach so IK remains physically feasible
Vector2 hipToStep = new(targetStepX - swingHipWorld.X, targetStepZ - swingHipWorld.Z);
if (hipToStep.Length() > 1.85f)
{
hipToStep = hipToStep.Normalized() * 1.85f;
targetStepX = swingHipWorld.X + hipToStep.X;
targetStepZ = swingHipWorld.Z + hipToStep.Y;
}
float groundAtTarget = _track.SampleHeight(targetStepX, targetStepZ);
Vector3 targetAnkle = new(targetStepX, groundAtTarget + BreakerLegGeometry.AnkleHeight, targetStepZ);
if (_swingTime <= dt * 1.5f && _swingStartAnkle == Vector3.Zero)
{
_swingStartAnkle = targetAnkle;
}
// Swing XZ leads vertical touchdown (completes 100% XZ by 74% of swing) with brisk 0.40m clearance
float uHoriz = Math.Clamp(uSwing / 0.74f, 0f, 1f);
float sHoriz = uHoriz * uHoriz * (3f - 2f * uHoriz);
float swingX = Mathf.Lerp(_swingStartAnkle.X, targetAnkle.X, sHoriz);
float swingZ = Mathf.Lerp(_swingStartAnkle.Z, targetAnkle.Z, sHoriz);
float groundUnderSwing = _track.SampleHeight(swingX, swingZ);
float baseAnkleY = Mathf.Lerp(_swingStartAnkle.Y, targetAnkle.Y, sHoriz);
float arcLift = walking ? 0.40f * MathF.Pow(MathF.Max(0f, MathF.Sin(MathF.PI * uSwing)), 0.70f) : 0.06f;
float minSafeAnkleY = groundUnderSwing + BreakerLegGeometry.AnkleHeight + (uSwing < 0.80f ? 0.14f : 0.0f);
Vector3 desiredSwingAnkle = new(swingX, MathF.Max(baseAnkleY + arcLift, minSafeAnkleY), swingZ);
// If swing ran past 1.0 without touching ground, extend downward smoothly
if (_swingTime > _stepDuration)
{
desiredSwingAnkle.Y -= (_swingTime - _stepDuration) * 2.2f;
}
// Solve swing IK relative to current Pelvis orientation -> joint target rotations for Lodur.Ragdoll.Drive
BreakerLegGeometry.SolveTwoBoneIkWorld(
swingHipWorld,
desiredSwingAnkle,
Vector3.Back,
pelRightX,
out _,
out Basis swingThighWorld,
out Basis swingShinWorld);
Quaternion pelQInv = pelQ.Normalized().Inverse();
Quaternion qSwingThigh = swingThighWorld.Orthonormalized().GetRotationQuaternion().Normalized();
Quaternion qSwingShin = swingShinWorld.Orthonormalized().GetRotationQuaternion().Normalized();
Quaternion relSwingThigh = (pelQInv * qSwingThigh).Normalized();
Quaternion relSwingShin = (qSwingThigh.Inverse() * qSwingShin).Normalized();
Vector3 levelRightX = Vector3.Right;
Vector3 swingGroundNormal = _track.SampleNormal(swingX, swingZ);
Basis levelFootWorld = BreakerLegGeometry.BasisFromDownAndRight(-swingGroundNormal, levelRightX);
Quaternion qSwingFoot = levelFootWorld.Orthonormalized().GetRotationQuaternion().Normalized();
Quaternion relSwingFoot = (qSwingShin.Inverse() * qSwingFoot).Normalized();
// Set targets & strengths for both legs
for (int leg = 0; leg < 2; leg++)
{
int jBase = leg * 3;
float crippleScale = (leftLegCrippled && leg == 0) ? 0.30f : 1.0f;
if (_simTime < 0.18f)
{
// Initial settle into crouched athletic stance (Hip -0.25, Knee +0.50, Ankle -0.25 -> ~3.68m height)
_targets[jBase + 0] = ToJointFrameTarget(jBase + 0, new Quaternion(Vector3.Right, -0.25f));
_targets[jBase + 1] = ToJointFrameTarget(jBase + 1, new Quaternion(Vector3.Right, 0.50f));
_targets[jBase + 2] = ToJointFrameTarget(jBase + 2, new Quaternion(Vector3.Right, -0.25f));
_strengths[jBase + 0] = 0.55f * crippleScale;
_strengths[jBase + 1] = 0.70f * crippleScale;
_strengths[jBase + 2] = 0.85f * crippleScale;
}
else if (leg == swingLeg)
{
_targets[jBase + 0] = ToJointFrameTarget(jBase + 0, relSwingThigh);
_targets[jBase + 1] = ToJointFrameTarget(jBase + 1, relSwingShin);
_targets[jBase + 2] = ToJointFrameTarget(jBase + 2, relSwingFoot);
_strengths[jBase + 0] = 1.0f * crippleScale;
_strengths[jBase + 1] = 1.0f * crippleScale;
_strengths[jBase + 2] = 0.30f * crippleScale; // scaled down in swing for Foot inertia stability
}
else
{
// Stance leg: keep Hip/Knee PD around 3.68m crouch so VMC Jacobian-transpose + uprightTorque have authority
// without hitting straight-leg lock or buckling; Ankle keeps foot flat on terrain.
_targets[jBase + 0] = ToJointFrameTarget(jBase + 0, pelQInv * targetPelQ * new Quaternion(Vector3.Right, -0.22f));
_targets[jBase + 1] = ToJointFrameTarget(jBase + 1, new Quaternion(Vector3.Right, 0.46f));
Vector3 stFootPos = leg == 0 ? footPosL : footPosR;
Vector3 stNorm = _track.SampleNormal(stFootPos.X, stFootPos.Z);
int shinLane = _ragdoll.BodyLane(leg == 0 ? PartShinL : PartShinR);
Quaternion shinQ = new Quaternion(v.RotationX[shinLane], v.RotationY[shinLane], v.RotationZ[shinLane], v.RotationW[shinLane]).Normalized();
Basis stFootWant = BreakerLegGeometry.BasisFromDownAndRight(-stNorm, levelRightX);
_targets[jBase + 2] = ToJointFrameTarget(jBase + 2, (shinQ.Inverse() * stFootWant.Orthonormalized().GetRotationQuaternion().Normalized()).Normalized());
_strengths[jBase + 0] = 0.16f * crippleScale;
_strengths[jBase + 1] = 0.55f * crippleScale;
_strengths[jBase + 2] = 0.30f * crippleScale;
}
}
// 1. Lodur PD + gravity feedforward
_ragdoll.Drive(_strengths, _targets);
// 2. Stance Jacobian-transpose VMC + upright virtual spring-damper torque (equal-and-opposite across stance joints)
float groundUnderPel = _track.SampleHeight(pelPos.X, pelPos.Z);
float slopeZ = _track.SampleSlopeZ(pelPos.X, pelPos.Z);
float terrainRateY = slopeZ * pelVel.Z;
float targetComY = groundUnderPel + opt1RideHeight;
float fy = _totalMass * BreakerLegGeometry.Gravity
+ 75000f * (targetComY - pelPos.Y)
+ 18000f * (terrainRateY - pelVel.Y);
fy = Math.Clamp(fy, 0f, _totalMass * BreakerLegGeometry.Gravity * 1.65f);
// Upright virtual spring-damper torque wanted ON Pelvis (clamped so Thigh doesn't fold in single stance)
Quaternion qErr = (targetPelQ * pelQInv).Normalized();
if (qErr.W < 0f) qErr = new Quaternion(-qErr.X, -qErr.Y, -qErr.Z, -qErr.W);
float errSin = MathF.Sqrt(qErr.X * qErr.X + qErr.Y * qErr.Y + qErr.Z * qErr.Z);
float errScale = errSin < 1e-6f ? 2f : 2f * MathF.Atan2(errSin, qErr.W) / errSin;
Vector3 rotErr = new(qErr.X * errScale, qErr.Y * errScale, qErr.Z * errScale);
Vector3 uprightTorque = new(
Math.Clamp(85000f * rotErr.X - 11000f * pelAngVel.X, -42000f, 42000f),
Math.Clamp(45000f * rotErr.Y - 6000f * pelAngVel.Y, -24000f, 24000f),
Math.Clamp(85000f * rotErr.Z - 11000f * pelAngVel.Z, -42000f, 42000f));
float fx = 16000f * (cmdVelX - pelVel.X);
float fz = 16000f * (cmdVelHoriz.Y - pelVel.Z);
// ZMP-feasible horizontal GRF bound coupled with uprightTorque:
// prevents commanding forces that exceed angular-momentum balance about the foot CoP polygon.
int stanceFootLane = _ragdoll.BodyLane(_stanceLeg == 0 ? PartFootL : PartFootR);
Vector3 pStanceFoot = new(v.PositionX[stanceFootLane], v.PositionY[stanceFootLane] - BreakerLegGeometry.AnkleHeight * 0.45f, v.PositionZ[stanceFootLane]);
Vector3 rFoot = pStanceFoot - pelPos;
float ry = Math.Min(-1.5f, rFoot.Y);
const float zmpFootHalfL = 0.68f;
const float zmpFootHalfW = 0.72f;
float fzA = (uprightTorque.X + (rFoot.Z - zmpFootHalfL) * fy) / ry;
float fzB = (uprightTorque.X + (rFoot.Z + zmpFootHalfL) * fy) / ry;
fz = Math.Clamp(fz, Math.Min(fzA, fzB), Math.Max(fzA, fzB));
float fxA = ((rFoot.X - zmpFootHalfW) * fy - uprightTorque.Z) / ry;
float fxB = ((rFoot.X + zmpFootHalfW) * fy - uprightTorque.Z) / ry;
fx = Math.Clamp(fx, Math.Min(fxA, fxB), Math.Max(fxA, fxB));
// Clamp virtual GRF strictly to Coulomb friction cone (ankleTorque is independently capped to foot polygon in ApplyStanceVmc)
float maxHoriz = WalkBakeoffTrack.TrackFriction * fy;
float horizMag = MathF.Sqrt(fx * fx + fz * fz);
if (horizMag > maxHoriz && horizMag > 1e-4f)
{
float scale = maxHoriz / horizMag;
fx *= scale;
fz *= scale;
}
// Distribute VMC to stance leg(s)
if (_simTime < 0.18f)
{
ApplyStanceVmc(0, new Vector3(fx, fy, fz) * 0.5f, uprightTorque * 0.5f, contactL, leftLegCrippled);
ApplyStanceVmc(1, new Vector3(fx, fy, fz) * 0.5f, uprightTorque * 0.5f, contactR, leftLegCrippled);
}
else
{
float wStance = _doubleSupportBlend;
float wOther = 1f - _doubleSupportBlend;
if (wOther > 0.01f && swingContact)
{
ApplyStanceVmc(_stanceLeg, new Vector3(fx, fy, fz) * wStance, uprightTorque * wStance, stanceContact, leftLegCrippled);
ApplyStanceVmc(swingLeg, new Vector3(fx, fy, fz) * wOther, uprightTorque * wOther, swingContact, leftLegCrippled);
}
else
{
ApplyStanceVmc(_stanceLeg, new Vector3(fx, fy, fz), uprightTorque, stanceContact, leftLegCrippled);
}
}
// Metrics update
Vector3 pelUp = pelQ * Vector3.Up;
float tiltDeg = Mathf.RadToDeg(MathF.Acos(Math.Clamp(pelUp.Y, -1f, 1f)));
if (tiltDeg > 68f || pelPos.Y < groundUnderPel + 1.35f)
{
_fellTimer += dt;
if (_fellTimer > 0.25f)
{
_fellOver = true;
}
}
else
{
_fellTimer = 0f;
}
if (_shoved && !_recovered && (_simTime - _shoveTime) > 0.15f)
{
if (tiltDeg < 9f && MathF.Abs(pelVel.X) < 0.55f && !_fellOver)
{
_recovered = true;
_recoveryTimeS = _simTime - _shoveTime;
}
}
long t1 = Stopwatch.GetTimestamp();
_cpuMsSum += (t1 - t0) * 1000.0 / Stopwatch.Frequency;
_ticks++;
}
private void ApplyStanceVmc(int leg, Vector3 fPelvis, Vector3 uprightTorque, bool hasContact, bool leftLegCrippled)
{
float cap = (leftLegCrippled && leg == 0) ? 0.30f : 1.0f;
if (!hasContact)
{
return; // Honest: cannot push against thin air without ground contact!
}
fPelvis *= cap;
uprightTorque *= cap;
var v = _world.View;
int footPart = leg == 0 ? PartFootL : PartFootR;
int footLane = _ragdoll.BodyLane(footPart);
Vector3 pFoot = new(v.PositionX[footLane], v.PositionY[footLane] - BreakerLegGeometry.AnkleHeight * 0.45f, v.PositionZ[footLane]);
int jBase = leg * 3;
// Hip & Knee Jacobian-transpose: tau_child = (p_joint - p_foot) x F_pelvis
for (int k = 0; k < 2; k++)
{
int jLane = _ragdoll.JointLane(jBase + k);
Vector3 pJoint = new(v.JointOriginX[jLane], v.JointOriginY[jLane], v.JointOriginZ[jLane]);
Vector3 tau = (pJoint - pFoot).Cross(fPelvis);
if (_plan.Joints[jBase + k].Kind == JointKind.Revolute)
{
Quat jf = new(v.JointFrameX[jLane], v.JointFrameY[jLane], v.JointFrameZ[jLane], v.JointFrameW[jLane]);
jf.Rotate(0f, 0f, 1f, out float ax, out float ay, out float az);
Vector3 axis = new(ax, ay, az);
tau = axis * tau.Dot(axis);
}
int child = v.JointBodyB[jLane];
int parent = v.JointBodyA[jLane];
v.TorqueX[child] += tau.X; v.TorqueY[child] += tau.Y; v.TorqueZ[child] += tau.Z;
v.TorqueX[parent] -= tau.X; v.TorqueY[parent] -= tau.Y; v.TorqueZ[parent] -= tau.Z;
}
// Upright virtual torque transferred from Foot through Shin+Thigh up to Pelvis,
// with Ankle torque kept well inside the physical foot support polygon so the foot stays flat on terrain!
float maxAnklePitch = 0.45f * 0.68f * Math.Max(0f, fPelvis.Y);
float maxAnkleRoll = 0.45f * 0.32f * Math.Max(0f, fPelvis.Y);
float maxAnkleYaw = 0.25f * WalkBakeoffTrack.TrackFriction * Math.Max(0f, fPelvis.Y);
Vector3 ankleTorque = new(
Math.Clamp(uprightTorque.X, -maxAnklePitch, maxAnklePitch),
Math.Clamp(uprightTorque.Y, -maxAnkleYaw, maxAnkleYaw),
Math.Clamp(uprightTorque.Z, -maxAnkleRoll, maxAnkleRoll));
int hipLane = _ragdoll.JointLane(jBase + 0);
int hipParent = v.JointBodyA[hipLane]; // Pelvis
int hipChild = v.JointBodyB[hipLane]; // Thigh
v.TorqueX[hipParent] += uprightTorque.X; v.TorqueY[hipParent] += uprightTorque.Y; v.TorqueZ[hipParent] += uprightTorque.Z;
v.TorqueX[hipChild] -= uprightTorque.X; v.TorqueY[hipChild] -= uprightTorque.Y; v.TorqueZ[hipChild] -= uprightTorque.Z;
int ankleLane = _ragdoll.JointLane(jBase + 2);
int ankleParent = v.JointBodyA[ankleLane]; // Shin
int ankleChild = v.JointBodyB[ankleLane]; // Foot
v.TorqueX[ankleParent] += ankleTorque.X; v.TorqueY[ankleParent] += ankleTorque.Y; v.TorqueZ[ankleParent] += ankleTorque.Z;
v.TorqueX[ankleChild] -= ankleTorque.X; v.TorqueY[ankleChild] -= ankleTorque.Y; v.TorqueZ[ankleChild] -= ankleTorque.Z;
}
private void UpdateFootSlip(int leg, bool inContact, Vector2 footXz)
{
ref bool prev = ref (leg == 0 ? ref _prevContactL : ref _prevContactR);
ref Vector2 td = ref (leg == 0 ? ref _touchdownXzL : ref _touchdownXzR);
if (inContact)
{
if (!prev)
{
td = footXz;
}
else if (leg == _stanceLeg)
{
float slip = (footXz - td).Length();
if (slip > _maxFootSlipM) _maxFootSlipM = slip;
}
}
prev = inContact;
}
private Quat ToJointFrameTarget(int jointIdx, Quaternion relChildToParent)
{
Quat qRel = BreakerLegGeometry.ToLodurQuat(relChildToParent);
return _jointFramesInv[jointIdx] * qRel * _jointFrames[jointIdx];
}
private static Quaternion shinBasisToFoot(Quaternion shin, Quaternion foot) => shin.Inverse() * foot;
public void SyncVisual(VehicleVisualInstance visual, float dt, float stepDt)
{
var v = _world.View;
Vector3 ReadPos(int p) { int l = _ragdoll.BodyLane(p); return new(v.PositionX[l], v.PositionY[l], v.PositionZ[l]); }
Basis ReadBasis(int p) { int l = _ragdoll.BodyLane(p); return new(new Quaternion(v.RotationX[l], v.RotationY[l], v.RotationZ[l], v.RotationW[l])); }
int fL = _ragdoll.BodyLane(PartFootL);
int fR = _ragdoll.BodyLane(PartFootR);
float weightN = _totalMass * BreakerLegGeometry.Gravity;
float loadL = v.ContactImpulse[fL] / (MathF.Max(1e-4f, stepDt) * weightN);
float loadR = v.ContactImpulse[fR] / (MathF.Max(1e-4f, stepDt) * weightN);
BreakerLegGeometry.PoseBreakerVisual(
visual,
ReadPos(PartPelvis),
ReadBasis(PartPelvis),
ReadBasis(PartThighL),
ReadBasis(PartShinL),
ReadBasis(PartFootL),
ReadBasis(PartThighR),
ReadBasis(PartShinR),
ReadBasis(PartFootR),
loadL,
loadR,
dt);
}
public BakeoffTelemetry ReadTelemetry(bool leftCrippled, float stepDt)
{
var v = _world.View;
int pel = PelvisLane;
int fL = _ragdoll.BodyLane(PartFootL);
int fR = _ragdoll.BodyLane(PartFootR);
Quaternion pelQ = new(v.RotationX[pel], v.RotationY[pel], v.RotationZ[pel], v.RotationW[pel]);
Vector3 pelUp = pelQ * Vector3.Up;
float tiltDeg = Mathf.RadToDeg(MathF.Acos(Math.Clamp(pelUp.Y, -1f, 1f)));
return new BakeoffTelemetry
{
SimTimeS = _simTime,
DistanceZ = v.PositionZ[pel],
SpeedZ = v.VelocityZ[pel],
LateralX = v.PositionX[pel] - _startX,
PelvisY = v.PositionY[pel],
TiltDeg = tiltDeg,
MaxFootSlipM = _maxFootSlipM,
FellOver = _fellOver,
RecoveryTimeS = _shoved ? (_recovered ? _recoveryTimeS : -1f) : 0f,
CpuCtrlMsPerTick = _ticks > 0 ? _cpuMsSum / _ticks : 0.0,
LeftCrippled = leftCrippled,
LeftContact = v.ContactCount[fL] > 0,
RightContact = v.ContactCount[fR] > 0,
LeftGrfN = v.ContactImpulse[fL] / MathF.Max(1e-4f, stepDt),
RightGrfN = v.ContactImpulse[fR] / MathF.Max(1e-4f, stepDt)
};
}
}
///
/// Option 2: Centroidal Ground-Reaction-Force (GRF) Virtual-Leg Dynamics on 1 Ymir rigid body.
/// ZERO arbitrary horizontal thrust or magic hover force: ONLY forces F_i (clamped to Coulomb cone and leg reach)
/// and torques (p_cop_i - p_com) x F_i from planted feet act on the body.
///
public sealed class CentroidalGrfController
{
private const float FootHalfW = 0.45f;
private const float FootHalfL = 0.68f;
private readonly Box3DSoaWorld _world;
private readonly WalkBakeoffTrack _track;
private readonly Box3DSoaBodyHandle _body;
private readonly float _startX;
private readonly float _mass;
private float _simTime;
private readonly bool[] _planted = { true, true };
private readonly Vector3[] _footSole = new Vector3[2];
private readonly Vector3[] _swingStartSole = new Vector3[2];
private readonly Vector3[] _swingTargetSole = new Vector3[2];
private readonly float[] _lastGrfY = new float[2];
private int _stanceLeg;
private float _swingTime;
private float _stepDuration = 0.34f;
private bool _shoved;
private float _shoveTime = -1f;
private bool _recovered;
private float _recoveryTimeS = -1f;
private float _fellTimer;
private bool _fellOver;
private float _maxFootSlipM;
private double _cpuMsSum;
private long _ticks;
public CentroidalGrfController(Box3DSoaWorld world, WalkBakeoffTrack track, float startX, ulong stableId)
{
_world = world;
_track = track;
_startX = startX;
const float hx = 1.20f, hy = 1.05f, hz = 0.78f;
float volume = 8f * hx * hy * hz;
float density = BreakerLegGeometry.TotalMassKg / volume;
float startGround = track.SampleHeight(startX, 0f);
_body = world.AddBox(
stableId,
(startX, startGround + BreakerLegGeometry.RideHeightAboveGround, 0f),
(hx, hy, hz),
density,
friction: 0.75f,
restitution: 0.05f);
_mass = world.View.Mass[_body.Lane];
_footSole[0] = new Vector3(startX + BreakerLegGeometry.HipOffsetX, track.SampleHeight(startX + BreakerLegGeometry.HipOffsetX, 0f), 0f);
_footSole[1] = new Vector3(startX - BreakerLegGeometry.HipOffsetX, track.SampleHeight(startX - BreakerLegGeometry.HipOffsetX, 0f), 0f);
_swingStartSole[0] = _footSole[0];
_swingStartSole[1] = _footSole[1];
_swingTargetSole[0] = _footSole[0];
_swingTargetSole[1] = _footSole[1];
}
public int BodyLane => _body.Lane;
public Vector3 LeftFootWorld => _footSole[0];
public Vector3 RightFootWorld => _footSole[1];
public bool IsLeftPlanted => _planted[0];
public bool IsRightPlanted => _planted[1];
public void NotifyShove(float impulseX)
{
var v = _world.View;
int lane = _body.Lane;
Vector3 comPos = new(v.PositionX[lane], v.PositionY[lane], v.PositionZ[lane]);
Quaternion q = new(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]);
Vector3 hitWorld = comPos + q * new Vector3(-1.15f, 1.35f, 0.10f);
_world.ApplyImpulse(lane, (impulseX, 0f, 0f), (hitWorld.X, hitWorld.Y, hitWorld.Z));
_shoved = true;
_shoveTime = _simTime;
_recovered = false;
_recoveryTimeS = -1f;
}
public void StepControl(float dt, Vector2 cmdVelHoriz, bool leftLegCrippled)
{
long t0 = Stopwatch.GetTimestamp();
_simTime += dt;
var v = _world.View;
int lane = _body.Lane;
Vector3 comPos = new(v.PositionX[lane], v.PositionY[lane], v.PositionZ[lane]);
Quaternion q = new(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]);
Vector3 vel = new(v.VelocityX[lane], v.VelocityY[lane], v.VelocityZ[lane]);
Vector3 angVel = new(v.AngularVelocityX[lane], v.AngularVelocityY[lane], v.AngularVelocityZ[lane]);
Vector3 hipL = comPos + q * new Vector3(BreakerLegGeometry.HipOffsetX, BreakerLegGeometry.HipOffsetYInCom, 0f);
Vector3 hipR = comPos + q * new Vector3(-BreakerLegGeometry.HipOffsetX, BreakerLegGeometry.HipOffsetYInCom, 0f);
float cmdSpeed = cmdVelHoriz.Length();
bool walking = cmdSpeed > 0.25f || new Vector2(vel.X, vel.Z).Length() > 0.45f;
// Gait & Raibert footstep planner
int swingLeg = 1 - _stanceLeg;
if (_simTime < 0.18f)
{
_planted[0] = true;
_planted[1] = true;
_swingTime = 0f;
}
else if (!walking)
{
_planted[0] = true;
_planted[1] = true;
_swingTime = 0f;
}
else
{
_swingTime += dt;
// Accelerate swing cadence during high lateral disturbance (reactive Capture-Point recovery step)
float lateralDisturb = MathF.Abs(vel.X - cmdVelHoriz.X);
float effectiveDur = lateralDisturb > 1.1f ? 0.22f : _stepDuration;
float u = _swingTime / effectiveDur;
if (u >= 1.0f)
{
// Touchdown: plant swing foot exactly at target terrain height, swap stance
_footSole[swingLeg] = new Vector3(
_swingTargetSole[swingLeg].X,
_track.SampleHeight(_swingTargetSole[swingLeg].X, _swingTargetSole[swingLeg].Z),
_swingTargetSole[swingLeg].Z);
_planted[swingLeg] = true;
_stanceLeg = swingLeg;
swingLeg = 1 - _stanceLeg;
_swingTime = 0f;
_swingStartSole[swingLeg] = _footSole[swingLeg];
_planted[swingLeg] = false;
}
else
{
_planted[_stanceLeg] = true;
_planted[swingLeg] = u < 0.10f; // 10% double support overlap at start of step
}
// Update Raibert / Capture-Point target continuously mid-swing for disturbance rejection
if (!_planted[swingLeg])
{
float omega0 = MathF.Sqrt(BreakerLegGeometry.Gravity / BreakerLegGeometry.RideHeightAboveGround);
float kCapture = 0.58f / omega0;
Vector3 swingHip = swingLeg == 0 ? hipL : hipR;
// Narrow gait midline during walk (~0.66m lateral from COM instead of 1.08m) so single-support roll stays small
Vector3 midlinePull = q * new Vector3((swingLeg == 0 ? -0.40f : 0.40f), 0f, 0f);
Vector2 horizVel = new(vel.X, vel.Z);
Vector2 stepOffset = horizVel * (effectiveDur * 0.50f) + (horizVel - cmdVelHoriz) * kCapture;
if (cmdVelHoriz.Y > 0.5f && horizVel.Y < cmdVelHoriz.Y * 0.4f)
{
stepOffset.Y = MathF.Max(stepOffset.Y, 0.25f * cmdVelHoriz.Y * effectiveDur);
}
float tx = swingHip.X + midlinePull.X + stepOffset.X;
float tz = swingHip.Z + midlinePull.Z + stepOffset.Y;
// Clamp horizontal step reach so leg stays within physical reach
Vector2 dStep = new(tx - swingHip.X, tz - swingHip.Z);
if (dStep.Length() > 1.95f)
{
dStep = dStep.Normalized() * 1.95f;
tx = swingHip.X + dStep.X;
tz = swingHip.Z + dStep.Y;
}
_swingTargetSole[swingLeg] = new Vector3(tx, _track.SampleHeight(tx, tz), tz);
float uSwing = Math.Clamp((u - 0.10f) / 0.90f, 0f, 1f);
float s = 0.5f - 0.5f * MathF.Cos(MathF.PI * uSwing);
float sx = Mathf.Lerp(_swingStartSole[swingLeg].X, _swingTargetSole[swingLeg].X, s);
float sz = Mathf.Lerp(_swingStartSole[swingLeg].Z, _swingTargetSole[swingLeg].Z, s);
float syBase = Mathf.Lerp(_swingStartSole[swingLeg].Y, _swingTargetSole[swingLeg].Y, s);
float arcLift = 0.72f * MathF.Sin(MathF.PI * uSwing);
float minGround = _track.SampleHeight(sx, sz);
_footSole[swingLeg] = new Vector3(sx, MathF.Max(syBase + arcLift, minGround + (uSwing < 0.9f ? 0.05f : 0f)), sz);
}
}
// Check max leg reach on planted feet: if body dragged foot beyond L1+L2, foot genuinely slips along terrain!
for (int i = 0; i < 2; i++)
{
if (!_planted[i]) continue;
Vector3 hip = i == 0 ? hipL : hipR;
Vector3 ankle = _footSole[i] + new Vector3(0f, BreakerLegGeometry.AnkleHeight, 0f);
Vector3 diff = ankle - hip;
float dist = diff.Length();
if (dist > BreakerLegGeometry.MaxLegReach)
{
Vector3 clampedAnkle = hip + diff * (BreakerLegGeometry.MaxLegReach / dist);
Vector3 oldSole = _footSole[i];
_footSole[i] = new Vector3(clampedAnkle.X, _track.SampleHeight(clampedAnkle.X, clampedAnkle.Z), clampedAnkle.Z);
float drag = new Vector2(_footSole[i].X - oldSole.X, _footSole[i].Z - oldSole.Z).Length();
if (drag > _maxFootSlipM) _maxFootSlipM = drag;
}
}
// Compute desired centroidal wrench ONLY from planted feet
float groundUnderCom = _track.SampleHeight(comPos.X, comPos.Z);
float slopeZ = _track.SampleSlopeZ(comPos.X, comPos.Z);
float terrainRateY = slopeZ * vel.Z;
float targetY = groundUnderCom + BreakerLegGeometry.RideHeightAboveGround;
float fyDes = _mass * BreakerLegGeometry.Gravity
+ 95000f * (targetY - comPos.Y)
+ 20000f * (terrainRateY - vel.Y);
fyDes = Math.Max(0f, fyDes);
float fxDes = 14000f * (cmdVelHoriz.X - vel.X);
float fzDes = 14000f * (cmdVelHoriz.Y - vel.Z);
if (MathF.Abs(cmdVelHoriz.X) < 0.05f)
{
fxDes += 2800f * (_startX - comPos.X);
}
// Slight natural forward lean when driving forward so COM leads foot for ZMP propulsion
float targetPitch = Math.Clamp((cmdVelHoriz.Y - vel.Z) * 0.025f + cmdVelHoriz.Y * 0.012f, -0.06f, 0.11f);
Quaternion qTarget = new(Vector3.Right, targetPitch);
Quaternion qErr = (qTarget * q.Normalized().Inverse()).Normalized();
if (qErr.W < 0f) qErr = new Quaternion(-qErr.X, -qErr.Y, -qErr.Z, -qErr.W);
float errSin = MathF.Sqrt(qErr.X * qErr.X + qErr.Y * qErr.Y + qErr.Z * qErr.Z);
float errScale = errSin < 1e-6f ? 2f : 2f * MathF.Atan2(errSin, qErr.W) / errSin;
Vector3 rotErr = new(qErr.X * errScale, qErr.Y * errScale, qErr.Z * errScale);
Vector3 torqueDes = new(
42000f * rotErr.X - 7500f * angVel.X,
12000f * rotErr.Y - 2600f * angVel.Y,
42000f * rotErr.Z - 7500f * angVel.Z);
// Allocate strictly to planted feet, enforce max reach, 30% cripple cap, Coulomb friction cone, and physical CoP
float healthyMaxGrf = _mass * BreakerLegGeometry.Gravity * 1.65f;
float[] capMax = { leftLegCrippled ? healthyMaxGrf * 0.30f : healthyMaxGrf, healthyMaxGrf };
float[] weight = new float[2];
float weightSum = 0f;
for (int i = 0; i < 2; i++)
{
if (!_planted[i]) continue;
Vector3 hip = i == 0 ? hipL : hipR;
float dist = ((_footSole[i] + new Vector3(0f, BreakerLegGeometry.AnkleHeight, 0f)) - hip).Length();
if (dist > BreakerLegGeometry.MaxLegReach + 0.05f) continue;
weight[i] = leftLegCrippled && i == 0 ? 0.30f : 1.0f;
weightSum += weight[i];
}
Vector3 totalForce = Vector3.Zero;
Vector3 totalTorque = Vector3.Zero;
_lastGrfY[0] = 0f;
_lastGrfY[1] = 0f;
if (weightSum > 0f)
{
for (int i = 0; i < 2; i++)
{
if (weight[i] <= 0f) continue;
float frac = weight[i] / weightSum;
float fy = Math.Clamp(fyDes * frac, 0f, capMax[i]);
float fx = fxDes * frac;
float fz = fzDes * frac;
Vector3 tWant = torqueDes * frac;
// ZMP-feasible horizontal force bound for this foot so (p_cop - p_com) x F can actually realize tWant
// without exceeding physical foot sole bounds [-FootHalfW..+FootHalfW] x [-FootHalfL..+FootHalfL]:
// Tx = ry * fz - (rz + dz) * fy => fz = (Tx + (rz + dz) * fy) / ry (ry < 0)
// Tz = (rx + dx) * fy - ry * fx => fx = ((rx + dx) * fy - Tz) / ry (ry < 0)
Vector3 r0 = _footSole[i] - comPos;
if (fy > 200f && r0.Y < -0.5f)
{
float fzA = (tWant.X + (r0.Z - FootHalfL) * fy) / r0.Y;
float fzB = (tWant.X + (r0.Z + FootHalfL) * fy) / r0.Y;
fz = Math.Clamp(fz, Math.Min(fzA, fzB), Math.Max(fzA, fzB));
float fxA = ((r0.X - FootHalfW) * fy - tWant.Z) / r0.Y;
float fxB = ((r0.X + FootHalfW) * fy - tWant.Z) / r0.Y;
fx = Math.Clamp(fx, Math.Min(fxA, fxB), Math.Max(fxA, fxB));
}
// Coulomb friction cone clamp: |F_horiz| <= mu * F_y
float maxHoriz = WalkBakeoffTrack.TrackFriction * fy;
float hMag = MathF.Sqrt(fx * fx + fz * fz);
if (hMag > maxHoriz && hMag > 1e-4f)
{
float s = maxHoriz / hMag;
fx *= s;
fz *= s;
}
Vector3 fLeg = new(fx, fy, fz);
// Physical CoP inside foot sole [-FootHalfW..+FootHalfW] x [-FootHalfL..+FootHalfL]
float dxCop = 0f;
float dzCop = 0f;
if (fy > 200f)
{
// (r0 + (dx,0,dz)) x F = T_want => Tx = ry*Fz - (rz+dz)*Fy, Tz = (rx+dx)*Fy - ry*Fx
dzCop = Math.Clamp((r0.Y * fz - tWant.X) / fy - r0.Z, -FootHalfL, FootHalfL);
dxCop = Math.Clamp((tWant.Z + r0.Y * fx) / fy - r0.X, -FootHalfW, FootHalfW);
}
Vector3 pCop = _footSole[i] + new Vector3(dxCop, 0f, dzCop);
Vector3 rCop = pCop - comPos;
Vector3 tLeg = rCop.Cross(fLeg);
// In double support, opposing tangential foot forces generate pure yaw moment within friction cone;
// in single support, sole rotational friction provides bounded yaw stability (~footRadius * mu * fy)
if (weightSum > 0f)
{
float maxSpinYaw = 0.35f * WalkBakeoffTrack.TrackFriction * fy;
tLeg.Y += Math.Clamp(tWant.Y - tLeg.Y, -maxSpinYaw, maxSpinYaw);
}
totalForce += fLeg;
totalTorque += tLeg;
_lastGrfY[i] = fy;
}
}
// Write ONLY planted-foot GRF force & (p_foot - p_com) x F_i torque!
v.ForceX[lane] += totalForce.X;
v.ForceY[lane] += totalForce.Y;
v.ForceZ[lane] += totalForce.Z;
v.TorqueX[lane] += totalTorque.X;
v.TorqueY[lane] += totalTorque.Y;
v.TorqueZ[lane] += totalTorque.Z;
// Readjust fellOver check: a dynamic shove tilt peak is only a fall if the mech fails to stay up or hits ground
Vector3 up = q * Vector3.Up;
float tiltDeg = Mathf.RadToDeg(MathF.Acos(Math.Clamp(up.Y, -1f, 1f)));
if (tiltDeg > 68f || comPos.Y < groundUnderCom + 1.35f)
{
_fellTimer += dt;
if (_fellTimer > 0.25f) _fellOver = true;
}
else
{
_fellTimer = 0f;
}
if (_shoved && !_recovered && (_simTime - _shoveTime) > 0.15f)
{
if (tiltDeg < 9f && MathF.Abs(vel.X) < 0.55f && !_fellOver)
{
_recovered = true;
_recoveryTimeS = _simTime - _shoveTime;
}
}
long t1 = Stopwatch.GetTimestamp();
_cpuMsSum += (t1 - t0) * 1000.0 / Stopwatch.Frequency;
_ticks++;
}
public void SyncVisual(VehicleVisualInstance visual, float dt)
{
var v = _world.View;
int lane = _body.Lane;
Vector3 comPos = new(v.PositionX[lane], v.PositionY[lane], v.PositionZ[lane]);
Quaternion q = new(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]);
Basis torsoBasis = new(q);
Vector3 rightX = torsoBasis.X;
Vector3 fwdZ = torsoBasis.Z;
Vector3 hipL = comPos + torsoBasis * new Vector3(BreakerLegGeometry.HipOffsetX, BreakerLegGeometry.HipOffsetYInCom, 0f);
Vector3 hipR = comPos + torsoBasis * new Vector3(-BreakerLegGeometry.HipOffsetX, BreakerLegGeometry.HipOffsetYInCom, 0f);
Vector3 ankleL = _footSole[0] + new Vector3(0f, BreakerLegGeometry.AnkleHeight, 0f);
Vector3 ankleR = _footSole[1] + new Vector3(0f, BreakerLegGeometry.AnkleHeight, 0f);
BreakerLegGeometry.SolveTwoBoneIkWorld(hipL, ankleL, fwdZ, rightX, out _, out Basis thighL, out Basis shinL);
BreakerLegGeometry.SolveTwoBoneIkWorld(hipR, ankleR, fwdZ, rightX, out _, out Basis thighR, out Basis shinR);
Vector3 normL = _planted[0] ? _track.SampleNormal(_footSole[0].X, _footSole[0].Z) : Vector3.Up;
Vector3 normR = _planted[1] ? _track.SampleNormal(_footSole[1].X, _footSole[1].Z) : Vector3.Up;
Basis footL = BreakerLegGeometry.BasisFromDownAndRight(-normL, rightX);
Basis footR = BreakerLegGeometry.BasisFromDownAndRight(-normR, rightX);
float weightN = _mass * BreakerLegGeometry.Gravity;
BreakerLegGeometry.PoseBreakerVisual(
visual,
comPos,
torsoBasis,
thighL, shinL, footL,
thighR, shinR, footR,
_lastGrfY[0] / weightN,
_lastGrfY[1] / weightN,
dt);
}
public BakeoffTelemetry ReadTelemetry(bool leftCrippled)
{
var v = _world.View;
int lane = _body.Lane;
Quaternion q = new(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]);
Vector3 up = q * Vector3.Up;
float tiltDeg = Mathf.RadToDeg(MathF.Acos(Math.Clamp(up.Y, -1f, 1f)));
return new BakeoffTelemetry
{
SimTimeS = _simTime,
DistanceZ = v.PositionZ[lane],
SpeedZ = v.VelocityZ[lane],
LateralX = v.PositionX[lane] - _startX,
PelvisY = v.PositionY[lane],
TiltDeg = tiltDeg,
MaxFootSlipM = _maxFootSlipM,
FellOver = _fellOver,
RecoveryTimeS = _shoved ? (_recovered ? _recoveryTimeS : -1f) : 0f,
CpuCtrlMsPerTick = _ticks > 0 ? _cpuMsSum / _ticks : 0.0,
LeftCrippled = leftCrippled,
LeftContact = _planted[0],
RightContact = _planted[1],
LeftGrfN = _lastGrfY[0],
RightGrfN = _lastGrfY[1]
};
}
}