Add honest side-by-side Breaker locomotion bakeoff (Lodur Ragdoll+VMC vs Centroidal GRF)

This commit is contained in:
Meta Vens 2026-12-05 01:51:14 +01:00
commit bd08c16315
8 changed files with 2257 additions and 3 deletions

View file

@ -1,8 +1,16 @@
<Project>
<PropertyGroup>
<YmirRoot Condition="'$(YmirRoot)' == '' and '$(YMIR_ROOT)' != ''">$(YMIR_ROOT)</YmirRoot>
<YmirRoot Condition="'$(YmirRoot)' == '' and Exists('$(MSBuildThisFileDirectory)..\Ymir')">$(MSBuildThisFileDirectory)..\Ymir</YmirRoot>
<YmirRoot Condition="'$(YmirRoot)' == '' and Exists('$(MSBuildThisFileDirectory)..\..\Projects\Ymir')">$(MSBuildThisFileDirectory)..\..\Projects\Ymir</YmirRoot>
<YmirRoot Condition="'$(YmirRoot)' == ''">$(MSBuildThisFileDirectory)..\Ymir</YmirRoot>
<CultLibRoot Condition="'$(CultLibRoot)' == '' and '$(CULTLIB_ROOT)' != ''">$(CULTLIB_ROOT)</CultLibRoot>
<CultLibRoot Condition="'$(CultLibRoot)' == '' and Exists('$(MSBuildThisFileDirectory)..\CultLib')">$(MSBuildThisFileDirectory)..\CultLib</CultLibRoot>
<CultLibRoot Condition="'$(CultLibRoot)' == '' and Exists('$(MSBuildThisFileDirectory)..\..\Projects\CultLib')">$(MSBuildThisFileDirectory)..\..\Projects\CultLib</CultLibRoot>
<CultLibRoot Condition="'$(CultLibRoot)' == ''">$(MSBuildThisFileDirectory)..\CultLib</CultLibRoot>
<LodurRoot Condition="'$(LodurRoot)' == '' and '$(LODUR_ROOT)' != ''">$(LODUR_ROOT)</LodurRoot>
<LodurRoot Condition="'$(LodurRoot)' == '' and Exists('$(MSBuildThisFileDirectory)..\Lodur')">$(MSBuildThisFileDirectory)..\Lodur</LodurRoot>
<LodurRoot Condition="'$(LodurRoot)' == '' and Exists('$(MSBuildThisFileDirectory)..\..\Projects\Lodur')">$(MSBuildThisFileDirectory)..\..\Projects\Lodur</LodurRoot>
<LodurRoot Condition="'$(LodurRoot)' == ''">$(MSBuildThisFileDirectory)..\Lodur</LodurRoot>
</PropertyGroup>
</Project>

View file

@ -9,5 +9,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />
<ProjectReference Include="$(LodurRoot)\src\Lodur.Core\Lodur.Core.csproj" />
<ProjectReference Include="$(LodurRoot)\src\Lodur.Body.Ymir\Lodur.Body.Ymir.csproj" />
</ItemGroup>
</Project>

View file

@ -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);
}
/// <summary>
/// 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).
/// </summary>
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)

740
client/tests/WalkBakeoff.cs Normal file
View file

@ -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;
/// <summary>
/// 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.
/// </summary>
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<int>();
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;
}
}

View file

@ -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")

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,270 @@
using System;
using Godot;
using Ymir.Box3D;
namespace RustToDust.Client.Tests;
/// <summary>
/// Shared test track for <see cref="WalkBakeoff"/>:
/// 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 &amp; +0.58m step (30.5m..35.5m) -> upper plateau (to 64m).
/// Registers an exact <see cref="Box3DSoaWorld.AddStaticHeightField"/> and builds a matching visual mesh.
/// </summary>
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;
}
/// <summary>Bilinear interpolation matching the static heightfield triangles.</summary>
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;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB