diff --git a/Directory.Build.props b/Directory.Build.props index 047d29f..a6253ad 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,8 +1,16 @@ $(YMIR_ROOT) + $(MSBuildThisFileDirectory)..\Ymir + $(MSBuildThisFileDirectory)..\..\Projects\Ymir $(MSBuildThisFileDirectory)..\Ymir $(CULTLIB_ROOT) + $(MSBuildThisFileDirectory)..\CultLib + $(MSBuildThisFileDirectory)..\..\Projects\CultLib $(MSBuildThisFileDirectory)..\CultLib + $(LODUR_ROOT) + $(MSBuildThisFileDirectory)..\Lodur + $(MSBuildThisFileDirectory)..\..\Projects\Lodur + $(MSBuildThisFileDirectory)..\Lodur diff --git a/client/RustToDust.Client.csproj b/client/RustToDust.Client.csproj index aa56926..f8c9e1c 100644 --- a/client/RustToDust.Client.csproj +++ b/client/RustToDust.Client.csproj @@ -9,5 +9,7 @@ + + diff --git a/client/VehicleRigAnimator.cs b/client/VehicleRigAnimator.cs index ca73f27..2e0abdf 100644 --- a/client/VehicleRigAnimator.cs +++ b/client/VehicleRigAnimator.cs @@ -598,6 +598,22 @@ public static class VehicleRigAnimator float phiR, float velY, float dt) + { + float accelY = dt > 1e-4f ? Math.Clamp((velY - st.PrevVelY) / dt, -25f, 25f) : 0f; + float strideLoadL = 1.0f + 0.42f * MathF.Sin(phiL) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f); + float strideLoadR = 1.0f + 0.42f * MathF.Sin(phiR) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f); + StepBreakerLinkages(visual, strideLoadL, strideLoadR, dt); + } + + /// + /// Steps Breaker's real oleo gas-spring struts, 2-link scissor torque knees, and telescoping recess rams + /// from caller-supplied per-leg vertical load factors (in G, e.g. 1.0 = static weight, 0.0 = swing). + /// + public static void StepBreakerLinkages( + VehicleVisualInstance visual, + float leftLoadG, + float rightLoadG, + float dt) { VehicleMechanismsRecord? mech = visual.Package.Mechanisms; if (mech is null || mech.Struts.Count == 0) @@ -605,15 +621,15 @@ public static class VehicleRigAnimator return; } + RigState st = visual.RigState; BreakerMechRig rig = st.BreakerRig ??= InitBreakerRig(visual, mech); if (!rig.Initialized) { return; } - float accelY = dt > 1e-4f ? Math.Clamp((velY - st.PrevVelY) / dt, -25f, 25f) : 0f; - float strideLoadL = 1.0f + 0.42f * MathF.Sin(phiL) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f); - float strideLoadR = 1.0f + 0.42f * MathF.Sin(phiR) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f); + float strideLoadL = Math.Clamp(leftLoadG, 0f, 3.5f); + float strideLoadR = Math.Clamp(rightLoadG, 0f, 3.5f); // 1. Oleo gas-spring + asymmetric orifice damping (Brokkr mechrig.Model.strut_step) if (dt > 0f) diff --git a/client/tests/WalkBakeoff.cs b/client/tests/WalkBakeoff.cs new file mode 100644 index 0000000..2955576 --- /dev/null +++ b/client/tests/WalkBakeoff.cs @@ -0,0 +1,740 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Godot; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Client.Tests; + +/// +/// Honest side-by-side locomotion bakeoff scene comparing: +/// - LEFT LANE (X = -5m): Option 1 — Full 7-body Lodur.Ragdoll + Ymir VMC / Capture-Point (120 Hz) +/// - RIGHT LANE (X = +5m): Option 2 — Centroidal GRF Virtual-Leg Dynamics on 1 Ymir rigid body (120 Hz) +/// Both use real Breaker (assets/vehicles/breaker/breaker.glb) on shared StaticHeightField track. +/// +public partial class WalkBakeoff : Node3D +{ + private const float PhysicsHz = 120f; + private const float SimDt = 1f / PhysicsHz; + private const int SubStepsPer120Hz = 4; + private const float AutoForwardSpeed = 5.0f; + private const float ShoveTimeS = 3.5f; + private const float ShoveImpulseX = 9500f; // Recoilless right-shoulder hit (~2.5 m/s lateral kick on 3800 kg mech) + private const float CrippleTimeS = 6.5f; + private const float CaptureDurationS = 8.0f; + + private static readonly float[] CaptureKeyTimes = { 0.5f, 2.0f, 3.6f, 4.4f, 6.8f, 7.8f }; + + private WalkBakeoffTrack _track = null!; + private Box3DSoaWorld? _world; + private RagdollVmcController _opt1 = null!; + private CentroidalGrfController _opt2 = null!; + + private VehicleAssetCache _assetCache = null!; + private MultiMeshPartPool _partPool = null!; + private VehicleVisualInstance _vis1 = null!; + private VehicleVisualInstance _vis2 = null!; + private ChassisGrid _grid1 = null!; + private ChassisGrid _grid2 = null!; + + private Camera3D _camera = null!; + private float _camYawDeg = 25f; + private float _camPitchDeg = 12f; + private float _camDist = 16.5f; + private bool _orbitDragging; + private Vector3 _camFocus; + + // Debug/telemetry visual cues + private MeshInstance3D _footMarkerL2 = null!; + private MeshInstance3D _footMarkerR2 = null!; + private MeshInstance3D _grfBarL2 = null!; + private MeshInstance3D _grfBarR2 = null!; + private MeshInstance3D _shoveFlash1 = null!; + private MeshInstance3D _shoveFlash2 = null!; + private float _shoveFlashTimer; + private Label3D _banner1 = null!; + private Label3D _banner2 = null!; + + // HUD + private Label _hudHeader = null!; + private Label _hudLeft = null!; + private Label _hudRight = null!; + private Label _hudFooter = null!; + + // Simulation state + private float _simTime; + private bool _autoTimeline = true; + private bool _shoveTriggered; + private bool _leftCrippled; + private float _manualFwd; + private float _manualStrafe; + private double _opt1IsolatedTotalMsPerTick; + private double _opt2IsolatedTotalMsPerTick; + private BakeoffTelemetry _opt1At60HzEnd; + private bool _captureMode; + + public override void _Ready() + { + SetupLightingAndEnvironment(); + + _track = new WalkBakeoffTrack(); + AddChild(_track.BuildVisualMesh()); + + _assetCache = new VehicleAssetCache(); + _partPool = new MultiMeshPartPool { Name = "BakeoffPartPool" }; + AddChild(_partPool); + + _grid1 = Catalog.CreateWithDefaultLoadout(Catalog.Breaker); + _grid2 = Catalog.CreateWithDefaultLoadout(Catalog.Breaker); + + _vis1 = VehicleVisualInstance.Create(_assetCache, "breaker", VehicleVisualRole.Player); + _vis1.SyncMountedGear(_grid1); + AddChild(_vis1.Root); + + _vis2 = VehicleVisualInstance.Create(_assetCache, "breaker", VehicleVisualRole.Rival); + _vis2.SyncMountedGear(_grid2); + AddChild(_vis2.Root); + + CreateVisualMarkers(); + CreateHud(); + + _camera = new Camera3D + { + Name = "BakeoffCamera", + Current = true, + Fov = 52f, + Near = 0.1f, + Far = 500f + }; + AddChild(_camera); + + // Run fast isolated 60 Hz vs 120 Hz & per-rig CPU probes before live run + RunIsolatedBenchmarks(); + + string[] args = OS.GetCmdlineUserArgs(); + if (args.Contains("--bench-only")) + { + GetTree().Quit(0); + return; + } + + ResetSimulation(autoTimeline: true); + + _captureMode = System.Environment.GetEnvironmentVariable("RTD_WALK_BAKEOFF_CAPTURE") == "1" + || args.Contains("--bakeoff-capture"); + + if (_captureMode) + { + SetProcess(false); + SetPhysicsProcess(false); + _ = RunCaptureSequenceAsync(); + } + } + + public override void _ExitTree() + { + _world?.Dispose(); + _world = null; + _assetCache?.Dispose(); + } + + private void ResetSimulation(bool autoTimeline) + { + _world?.Dispose(); + var (rBodies, rJoints, _) = RagdollVmcController.RequiredCapacity; + _world = new Box3DSoaWorld( + capacity: rBodies + 8, + gravityX: 0f, + gravityY: -BreakerLegGeometry.Gravity, + gravityZ: 0f, + jointCapacity: rJoints + 4, + factCapacity: 256); + + _track.AddToWorld(_world, stableId: 1); + _opt1 = new RagdollVmcController(_world, _track, WalkBakeoffTrack.LeftLaneX, firstStableId: 100); + _opt2 = new CentroidalGrfController(_world, _track, WalkBakeoffTrack.RightLaneX, stableId: 200); + + _simTime = 0f; + _autoTimeline = autoTimeline; + _shoveTriggered = false; + _leftCrippled = false; + _shoveFlashTimer = 0f; + _camFocus = new Vector3(0f, 2.5f, 0f); + + _opt1.SyncVisual(_vis1, 0f, SimDt); + _opt2.SyncVisual(_vis2, 0f); + UpdateCamera(1f); + UpdateVisualMarkersAndHud(0f); + } + + public override void _UnhandledInput(InputEvent @event) + { + if (_captureMode) return; + + if (@event is InputEventKey key && key.Pressed && !key.Echo) + { + switch (key.Keycode) + { + case Key.Space: + TriggerBlastShove(); + break; + case Key.K: + _leftCrippled = !_leftCrippled; + break; + case Key.R: + ResetSimulation(autoTimeline: false); + break; + } + } + else if (@event is InputEventMouseButton mb) + { + if (mb.ButtonIndex == MouseButton.Right) + { + _orbitDragging = mb.Pressed; + } + else if (mb.Pressed && mb.ButtonIndex == MouseButton.WheelUp) + { + _camDist = Math.Clamp(_camDist - 1.0f, 7f, 34f); + } + else if (mb.Pressed && mb.ButtonIndex == MouseButton.WheelDown) + { + _camDist = Math.Clamp(_camDist + 1.0f, 7f, 34f); + } + } + else if (@event is InputEventMouseMotion mm && _orbitDragging) + { + _camYawDeg = Mathf.Wrap(_camYawDeg - mm.Relative.X * 0.35f, -180f, 180f); + _camPitchDeg = Math.Clamp(_camPitchDeg + mm.Relative.Y * 0.25f, 2f, 55f); + } + } + + public override void _PhysicsProcess(double delta) + { + if (_world is null || _captureMode) return; + + // Check manual WASD override + float fwd = 0f, strafe = 0f; + if (Input.IsKeyPressed(Key.W)) fwd += AutoForwardSpeed; + if (Input.IsKeyPressed(Key.S)) fwd -= AutoForwardSpeed; + if (Input.IsKeyPressed(Key.A)) strafe += 2.2f; + if (Input.IsKeyPressed(Key.D)) strafe -= 2.2f; + if (MathF.Abs(fwd) > 0.01f || MathF.Abs(strafe) > 0.01f) + { + _autoTimeline = false; + } + _manualFwd = fwd; + _manualStrafe = strafe; + + // 2 x 120 Hz physics substeps per 60 Hz frame + for (int s = 0; s < 2; s++) + { + StepSingle120HzTick(); + } + } + + public override void _Process(double delta) + { + if (_world is null || _captureMode) return; + + float dt = (float)delta; + _opt1.SyncVisual(_vis1, dt, SimDt); + _opt2.SyncVisual(_vis2, dt); + + UpdateCamera(Math.Clamp(dt * 8f, 0.05f, 1f)); + UpdateVisualMarkersAndHud(dt); + SubmitFrameToPool(); + } + + private void StepSingle120HzTick() + { + if (_world is null) return; + + Vector2 cmdVel; + if (_autoTimeline) + { + float ramp = Math.Clamp((_simTime - 0.18f) / 0.65f, 0f, 1f); + cmdVel = new Vector2(0f, AutoForwardSpeed * ramp); + + if (!_shoveTriggered && _simTime >= ShoveTimeS) + { + _shoveTriggered = true; + TriggerBlastShove(); + } + if (!_leftCrippled && _simTime >= CrippleTimeS) + { + _leftCrippled = true; + } + } + else + { + cmdVel = new Vector2(_manualStrafe, _manualFwd); + } + + _opt1.StepControl(SimDt, cmdVel, _leftCrippled); + _opt2.StepControl(SimDt, cmdVel, _leftCrippled); + _world.Step(SimDt, SubStepsPer120Hz); + _simTime += SimDt; + } + + private void TriggerBlastShove() + { + _opt1.NotifyShove(ShoveImpulseX); + _opt2.NotifyShove(ShoveImpulseX); + _shoveFlashTimer = 0.25f; + } + + private void SubmitFrameToPool() + { + _partPool.BeginFrame(_camera); + _vis1.SubmitToPool(_partPool); + _vis2.SubmitToPool(_partPool); + _partPool.EndFrame(); + } + + private void UpdateCamera(float lerpAlpha) + { + if (_world is null) return; + var v = _world.View; + Vector3 p1 = new(v.PositionX[_opt1.PelvisLane], v.PositionY[_opt1.PelvisLane], v.PositionZ[_opt1.PelvisLane]); + Vector3 p2 = new(v.PositionX[_opt2.BodyLane], v.PositionY[_opt2.BodyLane], v.PositionZ[_opt2.BodyLane]); + Vector3 mid = (p1 + p2) * 0.5f; + // When both rigs are close, frame the shared track midpoint; if one falls behind by >4m, bias toward the upright leader so camera never clips inside it. + float sepZ = MathF.Abs(p2.Z - p1.Z); + float leadWeight = Math.Clamp((sepZ - 4f) / 6f, 0f, 1f); + Vector3 lead = p2.Z >= p1.Z ? p2 : p1; + float focusX = Mathf.Lerp(0f, lead.X * 0.65f, leadWeight); + float focusY = Mathf.Lerp(MathF.Max(p1.Y, p2.Y), lead.Y, leadWeight) - 1.25f; + float focusZ = Mathf.Lerp(mid.Z, lead.Z, leadWeight) + 0.6f; + Vector3 targetFocus = new(focusX, focusY, focusZ); + _camFocus = _camFocus.Lerp(targetFocus, lerpAlpha); + + float yawRad = Mathf.DegToRad(_camYawDeg); + float pitchRad = Mathf.DegToRad(_camPitchDeg); + float cosP = MathF.Cos(pitchRad); + Vector3 offset = new( + MathF.Sin(yawRad) * cosP * _camDist, + MathF.Sin(pitchRad) * _camDist, + MathF.Cos(yawRad) * cosP * _camDist); + + _camera.GlobalPosition = _camFocus + offset; + _camera.LookAt(_camFocus, Vector3.Up); + } + + private void UpdateVisualMarkersAndHud(float dt) + { + if (_world is null) return; + + var t1 = _opt1.ReadTelemetry(_leftCrippled, SimDt); + var t2 = _opt2.ReadTelemetry(_leftCrippled); + + // Option 2 planted foot rings & GRF bars + _footMarkerL2.GlobalPosition = _opt2.LeftFootWorld + new Vector3(0f, 0.04f, 0f); + _footMarkerR2.GlobalPosition = _opt2.RightFootWorld + new Vector3(0f, 0.04f, 0f); + ((StandardMaterial3D)_footMarkerL2.MaterialOverride).AlbedoColor = + _opt2.IsLeftPlanted ? (_leftCrippled ? new Color(1f, 0.25f, 0.2f) : new Color(0.25f, 0.95f, 0.45f)) : new Color(0.55f, 0.55f, 0.6f); + ((StandardMaterial3D)_footMarkerR2.MaterialOverride).AlbedoColor = + _opt2.IsRightPlanted ? new Color(0.25f, 0.95f, 0.45f) : new Color(0.55f, 0.55f, 0.6f); + + float scaleN = 1f / (BreakerLegGeometry.TotalMassKg * BreakerLegGeometry.Gravity); + float hL = Math.Clamp(t2.LeftGrfN * scaleN * 1.4f, 0.05f, 2.6f); + float hR = Math.Clamp(t2.RightGrfN * scaleN * 1.4f, 0.05f, 2.6f); + _grfBarL2.Scale = new Vector3(1f, hL, 1f); + _grfBarL2.GlobalPosition = _opt2.LeftFootWorld + new Vector3(0f, hL * 0.5f, 0f); + _grfBarL2.Visible = _opt2.IsLeftPlanted && t2.LeftGrfN > 100f; + _grfBarR2.Scale = new Vector3(1f, hR, 1f); + _grfBarR2.GlobalPosition = _opt2.RightFootWorld + new Vector3(0f, hR * 0.5f, 0f); + _grfBarR2.Visible = _opt2.IsRightPlanted && t2.RightGrfN > 100f; + + // Blast flash at right shoulder + if (_shoveFlashTimer > 0f) + { + _shoveFlashTimer = Math.Max(0f, _shoveFlashTimer - dt); + var v = _world.View; + Vector3 p1 = new(v.PositionX[_opt1.PelvisLane], v.PositionY[_opt1.PelvisLane], v.PositionZ[_opt1.PelvisLane]); + Vector3 p2 = new(v.PositionX[_opt2.BodyLane], v.PositionY[_opt2.BodyLane], v.PositionZ[_opt2.BodyLane]); + _shoveFlash1.GlobalPosition = p1 + new Vector3(-1.45f, 1.35f, 0.1f); + _shoveFlash2.GlobalPosition = p2 + new Vector3(-1.45f, 1.35f, 0.1f); + float s = 0.6f + 1.8f * (_shoveFlashTimer / 0.25f); + _shoveFlash1.Scale = Vector3.One * s; + _shoveFlash2.Scale = Vector3.One * s; + _shoveFlash1.Visible = true; + _shoveFlash2.Visible = true; + } + else + { + _shoveFlash1.Visible = false; + _shoveFlash2.Visible = false; + } + + // World banners above each Breaker + var view = _world.View; + _banner1.GlobalPosition = new Vector3(view.PositionX[_opt1.PelvisLane], view.PositionY[_opt1.PelvisLane] + 2.85f, view.PositionZ[_opt1.PelvisLane]); + _banner2.GlobalPosition = new Vector3(view.PositionX[_opt2.BodyLane], view.PositionY[_opt2.BodyLane] + 2.85f, view.PositionZ[_opt2.BodyLane]); + + // Left-leg cripple thermal warning on grid + float crippleTemp = _leftCrippled ? 155f : 20f; + _grid1.Temperature[1, 4] = crippleTemp; + _grid1.Temperature[1, 5] = crippleTemp; + _grid2.Temperature[1, 4] = crippleTemp; + _grid2.Temperature[1, 5] = crippleTemp; + + string stage = _simTime switch + { + < 1.2f => "STAGE 1: FLAT STRIDE (5.0 m/s)", + < 3.5f => "STAGE 2: 14 deg RAMP CLIMB (+4.5m)", + < 4.2f => "STAGE 3: RECOILLESS BLAST SHOVE (+9500 N*s)", + < 6.5f => "STAGE 4: RECOVERY & PLATEAU APPROACH", + < 7.3f => "STAGE 5: LEFT LEG CRIPPLED (30%) + DIP/STEP", + _ => "STAGE 6: UPPER PLATEAU FINISH" + }; + if (_leftCrippled && _simTime < CrippleTimeS) stage += " [L-CRIPPLE MANUAL]"; + + _hudHeader.Text = $"t = {_simTime:F2}s | {stage}"; + _hudLeft.Text = + "LEFT LANE (X=-5m): OPT 1 — LODUR RAGDOLL + YMIR VMC (120 Hz)\n" + + $"Dist Z: {t1.DistanceZ,5:F2}m Speed: {t1.SpeedZ,4:F2} m/s Drift X: {t1.LateralX,+5:F2}m\n" + + $"Tilt: {t1.TiltDeg,4:F1} deg MaxFootSlip: {t1.MaxFootSlipM,5:F3}m Fell: {(t1.FellOver ? "YES" : "NO")}\n" + + $"Shove Recov: {(t1.RecoveryTimeS > 0 ? $"{t1.RecoveryTimeS:F2}s" : (_shoveTriggered ? "RECOVERING" : "PENDING"))} Ctrl: {t1.CpuCtrlMsPerTick:F3} ms/tk (Total ~{_opt1IsolatedTotalMsPerTick:F3} ms)\n" + + $"Feet Contact: L={(t1.LeftContact ? "ON" : "--")} R={(t1.RightContact ? "ON" : "--")} L-Actuator: {(_leftCrippled ? "30%" : "100%")}"; + + _hudRight.Text = + "RIGHT LANE (X=+5m): OPT 2 — CENTROIDAL GRF VIRTUAL-LEG (120 Hz)\n" + + $"Dist Z: {t2.DistanceZ,5:F2}m Speed: {t2.SpeedZ,4:F2} m/s Drift X: {t2.LateralX,+5:F2}m\n" + + $"Tilt: {t2.TiltDeg,4:F1} deg MaxFootSlip: {t2.MaxFootSlipM,5:F3}m Fell: {(t2.FellOver ? "YES" : "NO")}\n" + + $"Shove Recov: {(t2.RecoveryTimeS > 0 ? $"{t2.RecoveryTimeS:F2}s" : (_shoveTriggered ? "RECOVERING" : "PENDING"))} Ctrl: {t2.CpuCtrlMsPerTick:F3} ms/tk (Total ~{_opt2IsolatedTotalMsPerTick:F3} ms)\n" + + $"Planted GRF: L={(t2.LeftContact ? $"{t2.LeftGrfN / 1000f:F1}kN" : "SWING")} R={(t2.RightContact ? $"{t2.RightGrfN / 1000f:F1}kN" : "SWING")} L-MaxGRF: {(_leftCrippled ? "30%" : "100%")}"; + + _hudFooter.Text = $"WASD: Drive Both | Space: Blast Shove | K: Cripple Left Leg | R: Reset | RMB-Drag/Wheel: Orbit || Opt1 60Hz ref: fell={(_opt1At60HzEnd.FellOver ? "YES" : "NO")} slip={_opt1At60HzEnd.MaxFootSlipM:F3}m dist={_opt1At60HzEnd.DistanceZ:F1}m"; + } + + private void RunIsolatedBenchmarks() + { + // 1. Measure Option 1 isolated (controller + Ymir step) at 120 Hz AND 60 Hz across full 8s run + var (rBodies, rJoints, _) = RagdollVmcController.RequiredCapacity; + using (var w120 = new Box3DSoaWorld(rBodies + 4, 0f, -BreakerLegGeometry.Gravity, 0f, rJoints + 2, factCapacity: 128)) + { + _track.AddToWorld(w120, 1); + var c1 = new RagdollVmcController(w120, _track, WalkBakeoffTrack.LeftLaneX, 100); + int n = (int)MathF.Round(CaptureDurationS / SimDt); + long t0 = Stopwatch.GetTimestamp(); + for (int i = 0; i < n; i++) + { + float simT = i * SimDt; + float ramp = Math.Clamp((simT - 0.18f) / 0.65f, 0f, 1f); + if (i == (int)MathF.Round(ShoveTimeS / SimDt)) c1.NotifyShove(ShoveImpulseX); + c1.StepControl(SimDt, new Vector2(0f, AutoForwardSpeed * ramp), simT >= CrippleTimeS); + w120.Step(SimDt, SubStepsPer120Hz); + } + long t1 = Stopwatch.GetTimestamp(); + _opt1IsolatedTotalMsPerTick = ((t1 - t0) * 1000.0 / Stopwatch.Frequency) / n; + } + + // Option 1 at 60 Hz (1/60s dt) + const float dt60 = 1f / 60f; + using (var w60 = new Box3DSoaWorld(rBodies + 4, 0f, -BreakerLegGeometry.Gravity, 0f, rJoints + 2, factCapacity: 128)) + { + _track.AddToWorld(w60, 1); + var c60 = new RagdollVmcController(w60, _track, WalkBakeoffTrack.LeftLaneX, 100); + int n = (int)MathF.Round(CaptureDurationS / dt60); + for (int i = 0; i < n; i++) + { + float simT = i * dt60; + float ramp = Math.Clamp((simT - 0.18f) / 0.65f, 0f, 1f); + if (i == (int)MathF.Round(ShoveTimeS / dt60)) c60.NotifyShove(ShoveImpulseX); + c60.StepControl(dt60, new Vector2(0f, AutoForwardSpeed * ramp), simT >= CrippleTimeS); + w60.Step(dt60, SubStepsPer120Hz); + } + _opt1At60HzEnd = c60.ReadTelemetry(true, dt60); + } + + // 2. Measure Option 2 isolated (controller + Ymir step) at 120 Hz across full 8s run + using (var w2 = new Box3DSoaWorld(8, 0f, -BreakerLegGeometry.Gravity, 0f, 0, factCapacity: 64)) + { + _track.AddToWorld(w2, 1); + var c2 = new CentroidalGrfController(w2, _track, WalkBakeoffTrack.RightLaneX, 200); + int n = (int)MathF.Round(CaptureDurationS / SimDt); + long t0 = Stopwatch.GetTimestamp(); + for (int i = 0; i < n; i++) + { + float simT = i * SimDt; + float ramp = Math.Clamp((simT - 0.18f) / 0.65f, 0f, 1f); + if (i == (int)MathF.Round(ShoveTimeS / SimDt)) c2.NotifyShove(ShoveImpulseX); + c2.StepControl(SimDt, new Vector2(0f, AutoForwardSpeed * ramp), simT >= CrippleTimeS); + w2.Step(SimDt, SubStepsPer120Hz); + } + long t1 = Stopwatch.GetTimestamp(); + _opt2IsolatedTotalMsPerTick = ((t1 - t0) * 1000.0 / Stopwatch.Frequency) / n; + } + } + + private async Task RunCaptureSequenceAsync() + { + string framesDir = Path.Combine(Path.GetTempPath(), "walk_bakeoff_frames"); + string keysDir = Path.Combine(Path.GetTempPath(), "walk_bakeoff_keys"); + Directory.CreateDirectory(framesDir); + Directory.CreateDirectory(keysDir); + foreach (string old in Directory.GetFiles(framesDir, "*.png")) File.Delete(old); + foreach (string old in Directory.GetFiles(keysDir, "*.png")) File.Delete(old); + + // Warmup frames so OpenGL 3.3 compiles all shaders before capture + _opt1.SyncVisual(_vis1, 0f, SimDt); + _opt2.SyncVisual(_vis2, 0f); + UpdateCamera(1f); + UpdateVisualMarkersAndHud(0f); + SubmitFrameToPool(); + for (int w = 0; w < 4; w++) + { + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + + const int renderFps = 30; + const int totalFrames = (int)(CaptureDurationS * renderFps); // 240 frames = 8.0s at 30fps + const int physicsTicksPerRenderFrame = 4; // 4 * (1/120) = 1/30s + + var capturedKeys = new HashSet(); + for (int f = 0; f <= totalFrames; f++) + { + _opt1.SyncVisual(_vis1, 1f / renderFps, SimDt); + _opt2.SyncVisual(_vis2, 1f / renderFps); + UpdateCamera(0.35f); + UpdateVisualMarkersAndHud(1f / renderFps); + SubmitFrameToPool(); + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + if (DisplayServer.GetName() != "headless") + { + Image? img = GetViewport().GetTexture()?.GetImage(); + if (img is not null) + { + if (f < totalFrames) + { + img.SavePng(Path.Combine(framesDir, $"frame_{f:D4}.png")); + } + for (int k = 0; k < CaptureKeyTimes.Length; k++) + { + if (!capturedKeys.Contains(k) && _simTime >= CaptureKeyTimes[k] - 0.001f) + { + capturedKeys.Add(k); + img.SavePng(Path.Combine(keysDir, $"key_{k}_{CaptureKeyTimes[k]:F1}s.png")); + var tk1 = _opt1.ReadTelemetry(_leftCrippled, SimDt); + var tk2 = _opt2.ReadTelemetry(_leftCrippled); + GD.Print(string.Create(CultureInfo.InvariantCulture, + $"KEY_MOMENT t={_simTime:F2}s | OPT1 z={tk1.DistanceZ:F2}m v={tk1.SpeedZ:F2} tilt={tk1.TiltDeg:F1} slip={tk1.MaxFootSlipM:F3}m fell={tk1.FellOver} | OPT2 z={tk2.DistanceZ:F2}m v={tk2.SpeedZ:F2} tilt={tk2.TiltDeg:F1} slip={tk2.MaxFootSlipM:F3}m fell={tk2.FellOver}")); + } + } + } + } + + if (f < totalFrames) + { + for (int s = 0; s < physicsTicksPerRenderFrame; s++) + { + StepSingle120HzTick(); + } + } + } + + var final1 = _opt1.ReadTelemetry(_leftCrippled, SimDt); + var final2 = _opt2.ReadTelemetry(_leftCrippled); + GD.Print(string.Create(CultureInfo.InvariantCulture, + $"BAKEOFF_RESULT_OPT1_120HZ: distZ={final1.DistanceZ:F2} speedZ={final1.SpeedZ:F2} maxSlipM={final1.MaxFootSlipM:F4} fellOver={final1.FellOver} recoveryTimeS={final1.RecoveryTimeS:F3} ctrlMsPerTick={final1.CpuCtrlMsPerTick:F4} totalIsoMsPerTick={_opt1IsolatedTotalMsPerTick:F4}")); + GD.Print(string.Create(CultureInfo.InvariantCulture, + $"BAKEOFF_RESULT_OPT1_60HZ: distZ={_opt1At60HzEnd.DistanceZ:F2} speedZ={_opt1At60HzEnd.SpeedZ:F2} maxSlipM={_opt1At60HzEnd.MaxFootSlipM:F4} fellOver={_opt1At60HzEnd.FellOver} recoveryTimeS={_opt1At60HzEnd.RecoveryTimeS:F3} ctrlMsPerTick={_opt1At60HzEnd.CpuCtrlMsPerTick:F4}")); + GD.Print(string.Create(CultureInfo.InvariantCulture, + $"BAKEOFF_RESULT_OPT2_120HZ: distZ={final2.DistanceZ:F2} speedZ={final2.SpeedZ:F2} maxSlipM={final2.MaxFootSlipM:F4} fellOver={final2.FellOver} recoveryTimeS={final2.RecoveryTimeS:F3} ctrlMsPerTick={final2.CpuCtrlMsPerTick:F4} totalIsoMsPerTick={_opt2IsolatedTotalMsPerTick:F4}")); + + GetTree().Quit(0); + } + + private void SetupLightingAndEnvironment() + { + AddChild(new DirectionalLight3D + { + Name = "DesertSun", + LightColor = new Color(1.0f, 0.94f, 0.84f), + LightEnergy = 1.75f, + ShadowEnabled = true, + DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel2Splits, + RotationDegrees = new Vector3(-40f, 34f, 0f) + }); + + AddChild(new DirectionalLight3D + { + Name = "SkyFill", + LightColor = new Color(0.66f, 0.78f, 0.96f), + LightEnergy = 0.55f, + ShadowEnabled = false, + RotationDegrees = new Vector3(-24f, -132f, 0f) + }); + + var skyMat = new ProceduralSkyMaterial + { + SkyTopColor = new Color(0.22f, 0.32f, 0.43f), + SkyHorizonColor = new Color(0.76f, 0.57f, 0.39f), + GroundBottomColor = new Color(0.26f, 0.20f, 0.14f), + GroundHorizonColor = new Color(0.65f, 0.47f, 0.32f) + }; + AddChild(new WorldEnvironment + { + Name = "WorldEnv", + Environment = new Godot.Environment + { + BackgroundMode = Godot.Environment.BGMode.Sky, + Sky = new Sky { SkyMaterial = skyMat }, + AmbientLightSource = Godot.Environment.AmbientSource.Sky, + AmbientLightEnergy = 0.65f + } + }); + } + + private void CreateVisualMarkers() + { + static MeshInstance3D MakeRing(string name, Color color) => new() + { + Name = name, + Mesh = new CylinderMesh { TopRadius = 0.55f, BottomRadius = 0.62f, Height = 0.06f, RadialSegments = 16 }, + MaterialOverride = new StandardMaterial3D { AlbedoColor = color, EmissionEnabled = true, Emission = color * 0.6f }, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + + static MeshInstance3D MakeBar(string name, Color color) => new() + { + Name = name, + Mesh = new CylinderMesh { TopRadius = 0.08f, BottomRadius = 0.08f, Height = 1.0f, RadialSegments = 8 }, + MaterialOverride = new StandardMaterial3D { AlbedoColor = color, EmissionEnabled = true, Emission = color, EmissionEnergyMultiplier = 1.5f }, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + + static MeshInstance3D MakeFlash(string name) => new() + { + Name = name, + Mesh = new SphereMesh { Radius = 0.85f, Height = 1.7f, RadialSegments = 12, Rings = 6 }, + MaterialOverride = new StandardMaterial3D + { + AlbedoColor = new Color(1.0f, 0.48f, 0.12f, 0.85f), + EmissionEnabled = true, + Emission = new Color(1.0f, 0.38f, 0.06f), + EmissionEnergyMultiplier = 3.2f, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }, + Visible = false, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + + _footMarkerL2 = MakeRing("Opt2FootL", new Color(0.25f, 0.95f, 0.45f)); + _footMarkerR2 = MakeRing("Opt2FootR", new Color(0.25f, 0.95f, 0.45f)); + _grfBarL2 = MakeBar("Opt2GrfL", new Color(0.95f, 0.78f, 0.20f)); + _grfBarR2 = MakeBar("Opt2GrfR", new Color(0.95f, 0.78f, 0.20f)); + _shoveFlash1 = MakeFlash("BlastFlash1"); + _shoveFlash2 = MakeFlash("BlastFlash2"); + + AddChild(_footMarkerL2); + AddChild(_footMarkerR2); + AddChild(_grfBarL2); + AddChild(_grfBarR2); + AddChild(_shoveFlash1); + AddChild(_shoveFlash2); + + _banner1 = new Label3D + { + Text = "OPT 1: RAGDOLL + VMC", + FontSize = 54, + PixelSize = 0.01f, + Billboard = BaseMaterial3D.BillboardModeEnum.Enabled, + Modulate = new Color(0.45f, 0.92f, 1.0f), + OutlineModulate = Colors.Black, + OutlineSize = 8 + }; + _banner2 = new Label3D + { + Text = "OPT 2: CENTROIDAL GRF", + FontSize = 54, + PixelSize = 0.01f, + Billboard = BaseMaterial3D.BillboardModeEnum.Enabled, + Modulate = new Color(1.0f, 0.74f, 0.30f), + OutlineModulate = Colors.Black, + OutlineSize = 8 + }; + AddChild(_banner1); + AddChild(_banner2); + } + + private void CreateHud() + { + var layer = new CanvasLayer { Name = "BakeoffHud" }; + AddChild(layer); + + static PanelContainer MakePanel(Color borderCol) + { + var sb = new StyleBoxFlat + { + BgColor = new Color(0.06f, 0.07f, 0.09f, 0.80f), + BorderColor = borderCol, + BorderWidthLeft = 2, + BorderWidthRight = 2, + BorderWidthTop = 2, + BorderWidthBottom = 2, + CornerRadiusTopLeft = 4, + CornerRadiusTopRight = 4, + CornerRadiusBottomLeft = 4, + CornerRadiusBottomRight = 4, + ContentMarginLeft = 10, + ContentMarginRight = 10, + ContentMarginTop = 6, + ContentMarginBottom = 6 + }; + return new PanelContainer().WithStyle(sb); + } + + // Top Header + var topPanel = MakePanel(new Color(0.55f, 0.58f, 0.65f, 0.9f)); + topPanel.AnchorLeft = 0.18f; topPanel.AnchorRight = 0.82f; + topPanel.AnchorTop = 0.015f; topPanel.AnchorBottom = 0.068f; + _hudHeader = new Label { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; + _hudHeader.AddThemeFontSizeOverride("font_size", 16); + topPanel.AddChild(_hudHeader); + layer.AddChild(topPanel); + + // Left Card (Opt 1) + var leftPanel = MakePanel(new Color(0.32f, 0.78f, 0.90f, 0.9f)); + leftPanel.AnchorLeft = 0.015f; leftPanel.AnchorRight = 0.485f; + leftPanel.AnchorTop = 0.08f; leftPanel.AnchorBottom = 0.24f; + _hudLeft = new Label(); + _hudLeft.AddThemeFontSizeOverride("font_size", 13); + leftPanel.AddChild(_hudLeft); + layer.AddChild(leftPanel); + + // Right Card (Opt 2) + var rightPanel = MakePanel(new Color(0.95f, 0.62f, 0.24f, 0.9f)); + rightPanel.AnchorLeft = 0.515f; rightPanel.AnchorRight = 0.985f; + rightPanel.AnchorTop = 0.08f; rightPanel.AnchorBottom = 0.24f; + _hudRight = new Label(); + _hudRight.AddThemeFontSizeOverride("font_size", 13); + rightPanel.AddChild(_hudRight); + layer.AddChild(rightPanel); + + // Bottom Controls & 60 Hz reference + var botPanel = MakePanel(new Color(0.42f, 0.44f, 0.48f, 0.85f)); + botPanel.AnchorLeft = 0.015f; botPanel.AnchorRight = 0.985f; + botPanel.AnchorTop = 0.935f; botPanel.AnchorBottom = 0.985f; + _hudFooter = new Label { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; + _hudFooter.AddThemeFontSizeOverride("font_size", 13); + botPanel.AddChild(_hudFooter); + layer.AddChild(botPanel); + } +} + +file static class PanelStyleExt +{ + public static PanelContainer WithStyle(this PanelContainer p, StyleBox style) + { + p.AddThemeStyleboxOverride("panel", style); + return p; + } +} diff --git a/client/tests/WalkBakeoff.tscn b/client/tests/WalkBakeoff.tscn new file mode 100644 index 0000000..7dcc54c --- /dev/null +++ b/client/tests/WalkBakeoff.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/WalkBakeoff.cs" id="1"] + +[node name="WalkBakeoff" type="Node3D"] +script = ExtResource("1") diff --git a/client/tests/WalkBakeoffControllers.cs b/client/tests/WalkBakeoffControllers.cs new file mode 100644 index 0000000..0eec94e --- /dev/null +++ b/client/tests/WalkBakeoffControllers.cs @@ -0,0 +1,1212 @@ +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] + }; + } +} diff --git a/client/tests/WalkBakeoffTrack.cs b/client/tests/WalkBakeoffTrack.cs new file mode 100644 index 0000000..04e923e --- /dev/null +++ b/client/tests/WalkBakeoffTrack.cs @@ -0,0 +1,270 @@ +using System; +using Godot; +using Ymir.Box3D; + +namespace RustToDust.Client.Tests; + +/// +/// Shared test track for : +/// 20m flat approach (-14m..+6m, spawning at Z=0) -> 14 deg ramp (+4.5m rise over 18.05m) +/// -> flat plateau (24.5m..30.5m) -> gentle -0.38m dip & +0.58m step (30.5m..35.5m) -> upper plateau (to 64m). +/// Registers an exact and builds a matching visual mesh. +/// +public sealed class WalkBakeoffTrack +{ + public const float MinX = -16f; + public const float MaxX = 16f; + public const float MinZ = -16f; + public const float MaxZ = 64f; + public const float GridStep = 0.50f; + public const float TrackFriction = 0.85f; + + public const float LeftLaneX = -5.0f; + public const float RightLaneX = 5.0f; + + private static readonly float RampSlope = MathF.Tan(14f * MathF.PI / 180f); // ~0.249328 + private const float RampRise = 4.50f; + private const float RampZStart = 6.0f; + private static readonly float RampRun = RampRise / RampSlope; // ~18.0485m + private static readonly float RampZEnd = RampZStart + RampRun; // ~24.0485m + private const float RampFillet = 0.60f; + + private const float DipStartZ = 30.5f; + private const float DipBottomZ = 33.0f; + private const float DipEndZ = 35.5f; + private const float DipHeight = 4.12f; + private const float UpperPlateauHeight = 4.70f; + + public int CountX { get; } + public int CountZ { get; } + public float MinHeight { get; } + public float MaxHeight { get; } + public float[] Heights { get; } + + public WalkBakeoffTrack() + { + CountX = (int)MathF.Round((MaxX - MinX) / GridStep) + 1; + CountZ = (int)MathF.Round((MaxZ - MinZ) / GridStep) + 1; + Heights = new float[CountX * CountZ]; + + float minH = float.PositiveInfinity; + float maxH = float.NegativeInfinity; + for (int gz = 0; gz < CountZ; gz++) + { + float wz = MinZ + gz * GridStep; + for (int gx = 0; gx < CountX; gx++) + { + float wx = MinX + gx * GridStep; + float h = EvalHeight(wx, wz); + Heights[gz * CountX + gx] = h; + if (h < minH) minH = h; + if (h > maxH) maxH = h; + } + } + + MinHeight = minH; + MaxHeight = maxH; + } + + public static float EvalHeight(float x, float z) + { + _ = x; + float zA = RampZStart - RampFillet; + float zB = RampZStart + RampFillet; + float zC = RampZEnd - RampFillet; + float zD = RampZEnd + RampFillet; + + if (z <= zA) + { + return 0f; + } + if (z < zB) + { + float d = z - zA; + return RampSlope * d * d / (4f * RampFillet); + } + if (z <= zC) + { + return RampSlope * (z - RampZStart); + } + if (z < zD) + { + float d = zD - z; + return RampRise - RampSlope * d * d / (4f * RampFillet); + } + if (z <= DipStartZ) + { + return RampRise; + } + if (z < DipBottomZ) + { + float t = (z - DipStartZ) / (DipBottomZ - DipStartZ); + float s = 0.5f - 0.5f * MathF.Cos(MathF.PI * t); + return RampRise + (DipHeight - RampRise) * s; + } + if (z < DipEndZ) + { + float t = (z - DipBottomZ) / (DipEndZ - DipBottomZ); + float s = 0.5f - 0.5f * MathF.Cos(MathF.PI * t); + return DipHeight + (UpperPlateauHeight - DipHeight) * s; + } + return UpperPlateauHeight; + } + + /// Bilinear interpolation matching the static heightfield triangles. + public float SampleHeight(float x, float z) + { + float fx = Math.Clamp((x - MinX) / GridStep, 0f, CountX - 1.0001f); + float fz = Math.Clamp((z - MinZ) / GridStep, 0f, CountZ - 1.0001f); + int ix = (int)fx; + int iz = (int)fz; + float tx = fx - ix; + float tz = fz - iz; + float h00 = Heights[iz * CountX + ix]; + float h10 = Heights[iz * CountX + ix + 1]; + float h01 = Heights[(iz + 1) * CountX + ix]; + float h11 = Heights[(iz + 1) * CountX + ix + 1]; + float hx0 = h00 + (h10 - h00) * tx; + float hx1 = h01 + (h11 - h01) * tx; + return hx0 + (hx1 - hx0) * tz; + } + + public Vector3 SampleNormal(float x, float z) + { + const float eps = 0.25f; + float hx0 = SampleHeight(x - eps, z); + float hx1 = SampleHeight(x + eps, z); + float hz0 = SampleHeight(x, z - eps); + float hz1 = SampleHeight(x, z + eps); + return new Vector3(hx0 - hx1, 2f * eps, hz0 - hz1).Normalized(); + } + + public float SampleSlopeZ(float x, float z) + { + const float eps = 0.20f; + return (SampleHeight(x, z + eps) - SampleHeight(x, z - eps)) / (2f * eps); + } + + public Box3DSoaBodyHandle AddToWorld(Box3DSoaWorld world, ulong stableId = 1) + { + return world.AddStaticHeightField( + stableId, + (MinX, 0f, MinZ), + Heights, + CountX, + CountZ, + (GridStep, 1f, GridStep), + MinHeight, + MaxHeight, + friction: TrackFriction, + restitution: 0.02f); + } + + public MeshInstance3D BuildVisualMesh() + { + var st = new SurfaceTool(); + st.Begin(Mesh.PrimitiveType.Triangles); + + for (int gz = 0; gz < CountZ - 1; gz++) + { + float z0 = MinZ + gz * GridStep; + float z1 = z0 + GridStep; + for (int gx = 0; gx < CountX - 1; gx++) + { + float x0 = MinX + gx * GridStep; + float x1 = x0 + GridStep; + + float y00 = Heights[gz * CountX + gx]; + float y10 = Heights[gz * CountX + gx + 1]; + float y01 = Heights[(gz + 1) * CountX + gx]; + float y11 = Heights[(gz + 1) * CountX + gx + 1]; + + AddTriVertex(st, x0, y00, z0); + AddTriVertex(st, x1, y10, z0); + AddTriVertex(st, x1, y11, z1); + + AddTriVertex(st, x0, y00, z0); + AddTriVertex(st, x1, y11, z1); + AddTriVertex(st, x0, y01, z1); + } + } + + st.GenerateNormals(); + var mat = new StandardMaterial3D + { + VertexColorUseAsAlbedo = true, + Roughness = 0.88f, + Metallic = 0.06f + }; + + return new MeshInstance3D + { + Name = "BakeoffTrackMesh", + Mesh = st.Commit(), + MaterialOverride = mat + }; + } + + private void AddTriVertex(SurfaceTool st, float x, float y, float z) + { + st.SetNormal(SampleNormal(x, z)); + st.SetColor(VertexColorAt(x, z)); + st.AddVertex(new Vector3(x, y, z)); + } + + private static Color VertexColorAt(float x, float z) + { + // Desert rock base with subtle 1m grid and distinct lane markings + bool meterGrid = MathF.Abs(x - MathF.Round(x)) < 0.05f || MathF.Abs(z - MathF.Round(z)) < 0.05f; + bool fiveMeterTick = MathF.Abs(z - MathF.Round(z / 5f) * 5f) < 0.14f && MathF.Abs(x) < 9.5f; + + Color col = new(0.36f, 0.30f, 0.24f); + if (z >= RampZStart && z <= RampZEnd) + { + col = new Color(0.41f, 0.33f, 0.25f); + } + else if (z >= DipStartZ && z <= DipEndZ) + { + col = new Color(0.33f, 0.28f, 0.26f); + } + + // Left lane (X = -5m): cool cyan/slate lane rails + float distLeft = MathF.Abs(x - LeftLaneX); + if (distLeft < 2.6f) + { + col = col.Lerp(new Color(0.24f, 0.32f, 0.36f), 0.38f); + if (distLeft > 2.35f) + { + col = new Color(0.28f, 0.72f, 0.84f); + } + } + + // Right lane (X = +5m): warm amber/sand lane rails + float distRight = MathF.Abs(x - RightLaneX); + if (distRight < 2.6f) + { + col = col.Lerp(new Color(0.38f, 0.30f, 0.21f), 0.38f); + if (distRight > 2.35f) + { + col = new Color(0.92f, 0.58f, 0.22f); + } + } + + // Center divider strip + if (MathF.Abs(x) < 0.16f) + { + col = new Color(0.55f, 0.52f, 0.46f); + } + + if (fiveMeterTick) + { + col = col.Lerp(new Color(0.80f, 0.76f, 0.68f), 0.32f); + } + else if (meterGrid) + { + col = col.Darkened(0.08f); + } + + return col; + } +} diff --git a/tools/bakeoff/walk_bakeoff_sheet.png b/tools/bakeoff/walk_bakeoff_sheet.png new file mode 100644 index 0000000..984c672 Binary files /dev/null and b/tools/bakeoff/walk_bakeoff_sheet.png differ