From a1c44ebe556f2fcc30fc3b400e8ad831ad178737 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 5 Dec 2026 22:27:10 +0100 Subject: [PATCH] wip(cut11b): Option A walker capsule + Catto PreStep/TryStep/PostStep + ZMP/foot-lock gait (16/17 HybridBWalkerTests pass; exemplar_frame Phase B delta remaining) --- client/VehicleRigAnimator.cs | 17 +- client/WalkerFootstepTracker.cs | 2 +- src/RustToDust.Core/WalkerVisualSnapshot.cs | 8 +- src/RustToDust.Net/RemoteArenaSession.cs | 96 +- src/RustToDust.Net/SnapshotCodec.cs | 23 +- src/RustToDust.Ymir/ArenaSession.cs | 270 ++- src/RustToDust.Ymir/WalkerLocomotion.cs | 2195 ++++++++++-------- tests/RustToDust.Tests/HybridBWalkerTests.cs | 583 ++++- 8 files changed, 2061 insertions(+), 1133 deletions(-) diff --git a/client/VehicleRigAnimator.cs b/client/VehicleRigAnimator.cs index c0359ec..d72c658 100644 --- a/client/VehicleRigAnimator.cs +++ b/client/VehicleRigAnimator.cs @@ -96,6 +96,7 @@ public static class VehicleRigAnimator { public required WalkerGeometrySpec Geom; public required WalkerLegBinding[] Legs; + public required Transform3D RestModelTransform; } public sealed class RigState @@ -440,11 +441,22 @@ public static class VehicleRigAnimator return; } + float leanPitch = float.IsFinite(snap.LeanPitch) ? snap.LeanPitch : 0f; + float leanRoll = float.IsFinite(snap.LeanRoll) ? snap.LeanRoll : 0f; + var pelvisOffset = float.IsFinite(snap.PelvisOffset.X) && float.IsFinite(snap.PelvisOffset.Y) && float.IsFinite(snap.PelvisOffset.Z) + ? snap.PelvisOffset + : System.Numerics.Vector3.Zero; + + var qLean = System.Numerics.Quaternion.CreateFromYawPitchRoll(0f, leanPitch, leanRoll); + Basis leanBasis = new Basis(new Quaternion(qLean.X, qLean.Y, qLean.Z, qLean.W)); + visual.ModelRoot.Transform = new Transform3D(leanBasis, ToGodot(pelvisOffset)) * rig.RestModelTransform; + var geom = rig.Geom; var bodyRotSys = snap.ComRot.LengthSquared() < 1e-6f ? System.Numerics.Quaternion.Identity : System.Numerics.Quaternion.Normalize(snap.ComRot); - var bodyRotInv = System.Numerics.Quaternion.Conjugate(bodyRotSys); + var qTotal = System.Numerics.Quaternion.Normalize(bodyRotSys * qLean); + var bodyRotInv = System.Numerics.Quaternion.Conjugate(qTotal); int count = Math.Min(rig.Legs.Length, snap.LegCount); for (int i = 0; i < count; i++) @@ -740,7 +752,8 @@ public static class VehicleRigAnimator return new WalkerVisualRig { Geom = geom, - Legs = legs + Legs = legs, + RestModelTransform = visual.ModelRoot.Transform }; } diff --git a/client/WalkerFootstepTracker.cs b/client/WalkerFootstepTracker.cs index 0d84046..84402bb 100644 --- a/client/WalkerFootstepTracker.cs +++ b/client/WalkerFootstepTracker.cs @@ -168,7 +168,7 @@ public sealed class WalkerFootstepTracker Vector3 footWorld; if (liveFoot.HasValue) { - float fy = terrain.SampleHeight(liveFoot.Value.X, liveFoot.Value.Z); + float fy = MathF.Max(liveFoot.Value.Y, terrain.SampleHeight(liveFoot.Value.X, liveFoot.Value.Z)); footWorld = new Vector3(liveFoot.Value.X, fy, liveFoot.Value.Z); } else diff --git a/src/RustToDust.Core/WalkerVisualSnapshot.cs b/src/RustToDust.Core/WalkerVisualSnapshot.cs index f1de4e8..92720b7 100644 --- a/src/RustToDust.Core/WalkerVisualSnapshot.cs +++ b/src/RustToDust.Core/WalkerVisualSnapshot.cs @@ -36,6 +36,9 @@ namespace RustToDust.Core public bool IsArachnidUp; public Vector3 ComPos; public Quaternion ComRot; + public Vector3 PelvisOffset; + public float LeanPitch; + public float LeanRoll; public LegArray4 LegAngles; public LegArray4 FootNormal; public LegArray4 LoadG; @@ -57,7 +60,10 @@ namespace RustToDust.Core IsDigitigrade = curr.IsDigitigrade, IsArachnidUp = curr.IsArachnidUp, ComPos = Vector3.Lerp(prev.ComPos, curr.ComPos, t), - ComRot = Quaternion.Slerp(q0, q1, t) + ComRot = Quaternion.Slerp(q0, q1, t), + PelvisOffset = Vector3.Lerp(prev.PelvisOffset, curr.PelvisOffset, t), + LeanPitch = prev.LeanPitch + (curr.LeanPitch - prev.LeanPitch) * t, + LeanRoll = prev.LeanRoll + (curr.LeanRoll - prev.LeanRoll) * t }; for (int i = 0; i < curr.LegCount; i++) diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs index 5f527c2..1a6a28c 100644 --- a/src/RustToDust.Net/RemoteArenaSession.cs +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -945,27 +945,68 @@ namespace RustToDust.Net } var spec = local.Grid.Spec; + if (spec.IsWalker) + { + var qNorm = NormalizeQuat(rot); + var fwdYaw = Vector3.Transform(Vector3.UnitZ, qNorm); + float yaw = (fwdYaw.X * fwdYaw.X + fwdYaw.Z * fwdYaw.Z) > 1e-6f ? MathF.Atan2(fwdYaw.X, fwdYaw.Z) : local.Yaw; + var qYaw = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + + WalkerLocomotion.GetWalkerCapsuleParams(spec, out float capR, out float capHalfL); + float density = WalkerLocomotion.GetWalkerCapsuleDensity(spec, capR, capHalfL); + var handle = _predWorld.AddCapsule( + ArenaSession.ContenderStableIdBase + (ulong)local.Id, + (pos.X, pos.Y, pos.Z), + capR, + capHalfL, + density, + (qYaw.X, qYaw.Y, qYaw.Z, qYaw.W), + friction: 0.0f, + restitution: 0.0f, + flags: Box3DSoaBodyFlags.LockAngularX + | Box3DSoaBodyFlags.LockAngularZ + | Box3DSoaBodyFlags.DisableContactRecycling); + _predBody = handle; + + _predWorld.SetBodyMotion( + handle, + linearVelocity: (vel.X, vel.Y, vel.Z), + angularVelocity: (0f, angVel.Y, 0f)); + + if (_predWalker is null || !string.Equals(_predChassisId, spec.Id, StringComparison.Ordinal)) + { + _predWalker = new WalkerState(spec); + _predWalker.InitializePose(pos, qYaw, spec.MassKg, _viewState.Terrain, _predWorld, handle.Lane); + } + else + { + _predWalker.SyncBodyPoseOnly(pos, qYaw, spec.MassKg); + } + _predChassisId = spec.Id; + return; + } + float physHalfH = ArenaSession.GetPhysicsHalfHeight(spec); float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; - float density = spec.MassKg / MathF.Max(0.1f, volume); + float boxDensity = spec.MassKg / MathF.Max(0.1f, volume); - var handle = _predWorld.AddBox( + var boxHandle = _predWorld.AddBox( ArenaSession.ContenderStableIdBase + (ulong)local.Id, (pos.X, pos.Y, pos.Z), (spec.HalfWidth, physHalfH, spec.HalfLength), - density, + boxDensity, (rot.X, rot.Y, rot.Z, rot.W), friction: 0.2f, restitution: 0.1f); - _predBody = handle; + _predBody = boxHandle; var v = _predWorld.View; - float mass = v.Mass[handle.Lane]; + float mass = v.Mass[boxHandle.Lane]; if (mass > 0f) { if (vel.LengthSquared() > 1e-8f) { - _predWorld.ApplyImpulse(handle.Lane, (vel.X * mass, vel.Y * mass, vel.Z * mass), (pos.X, pos.Y, pos.Z)); + _predWorld.ApplyImpulse(boxHandle.Lane, (vel.X * mass, vel.Y * mass, vel.Z * mass), (pos.X, pos.Y, pos.Z)); } if (angVel.LengthSquared() > 1e-6f) { @@ -981,28 +1022,13 @@ namespace RustToDust.Net { r = Vector3.Normalize(r); Vector3 j = Vector3.Cross(L, r) * 0.5f; - _predWorld.ApplyImpulse(handle.Lane, (j.X, j.Y, j.Z), (pos.X + r.X, pos.Y + r.Y, pos.Z + r.Z)); - _predWorld.ApplyImpulse(handle.Lane, (-j.X, -j.Y, -j.Z), (pos.X - r.X, pos.Y - r.Y, pos.Z - r.Z)); + _predWorld.ApplyImpulse(boxHandle.Lane, (j.X, j.Y, j.Z), (pos.X + r.X, pos.Y + r.Y, pos.Z + r.Z)); + _predWorld.ApplyImpulse(boxHandle.Lane, (-j.X, -j.Y, -j.Z), (pos.X - r.X, pos.Y - r.Y, pos.Z - r.Z)); } } } - if (spec.IsWalker) - { - if (_predWalker is null || !string.Equals(_predChassisId, spec.Id, StringComparison.Ordinal)) - { - _predWalker = new WalkerState(spec); - _predWalker.InitializePose(pos, rot, spec.MassKg, _viewState.Terrain); - } - else - { - _predWalker.SyncBodyPoseOnly(pos, rot, spec.MassKg); - } - } - else - { - _predWalker = null; - } + _predWalker = null; _predChassisId = spec.Id; } @@ -1136,15 +1162,29 @@ namespace RustToDust.Net int subSteps = _viewState.MapKind == ArenaMapKind.Sion ? 1 : ArenaSession.SubStepCount; ArenaSession.StepContenderPhysicsDrive( local, - _predWorld.View, - _predBody.Value.Lane, + _predWorld, + _predBody.Value, _viewState.Terrain, _viewState.MapKind, _predWalker, ArenaSession.FixedDt, - injectEngineHeat: false, - world: _predWorld); + injectEngineHeat: false); _predWorld.Step(ArenaSession.FixedDt, subSteps); + if (local.Grid.Spec.IsWalker && _predWalker is not null) + { + float predMass = _predWorld.View.Mass[_predBody.Value.Lane]; + if (predMass > 0f) + { + WalkerLocomotion.PostStepWalker( + _predWalker, + local.Grid, + _viewState.Terrain, + _predWorld, + _predBody.Value, + predMass, + ArenaSession.FixedDt); + } + } ArenaSession.SyncContenderPoseFromLane(local, _predWorld.View, _predBody.Value.Lane, _predWalker); } diff --git a/src/RustToDust.Net/SnapshotCodec.cs b/src/RustToDust.Net/SnapshotCodec.cs index 0f6a904..76204a5 100644 --- a/src/RustToDust.Net/SnapshotCodec.cs +++ b/src/RustToDust.Net/SnapshotCodec.cs @@ -164,6 +164,8 @@ namespace RustToDust.Net public const int CultMeshLatestOverheadBytes = 52; public const int MaxLatestFrameBytes = MaxLatestDatagramBytes - CultNetRudpLatestOverheadBytes; // 1110 bytes public const int MaxLatestPayloadBytes = MaxLatestFrameBytes - CultMeshLatestOverheadBytes; // 1058 bytes + private const float MaxWirePelvisOffsetM = 1.27f; + private const float MaxWireLeanRad = 15f * (MathF.PI / 180f); public static byte[] WrapLatest(ReadOnlySpan payload, long producerEpoch, long sequence, string schemaId = SchemaLatestId) { @@ -462,13 +464,18 @@ namespace RustToDust.Net { var w = pvsWalkers[i]; int legCount = Math.Clamp(w.Snapshot.LegCount, 0, 4); - int bytesNeeded = 2 + legCount * 13; + int bytesNeeded = 7 + legCount * 13; if (offset + bytesNeeded > MaxLatestPayloadBytes - 1) { break; } buf[offset++] = (byte)((w.IsContender ? 0x80 : 0x00) | (w.EntityId & 0x7F)); buf[offset++] = (byte)legCount; + buf[offset++] = EncodeSnorm8(w.Snapshot.PelvisOffset.X / MaxWirePelvisOffsetM); + buf[offset++] = EncodeSnorm8(w.Snapshot.PelvisOffset.Y / MaxWirePelvisOffsetM); + buf[offset++] = EncodeSnorm8(w.Snapshot.PelvisOffset.Z / MaxWirePelvisOffsetM); + buf[offset++] = EncodeSnorm8(w.Snapshot.LeanPitch / MaxWireLeanRad); + buf[offset++] = EncodeSnorm8(w.Snapshot.LeanRoll / MaxWireLeanRad); for (int l = 0; l < legCount; l++) { var ang = w.Snapshot.LegAngles[l]; @@ -635,8 +642,18 @@ namespace RustToDust.Net bool isContender = (tag & 0x80) != 0; byte entityId = (byte)(tag & 0x7F); int legCount = span[offset++]; - if (legCount > 4 || offset + legCount * 13 > span.Length) return false; - var snap = new WalkerVisualSnapshot { LegCount = legCount }; + if (legCount > 4 || offset + 5 + legCount * 13 > span.Length) return false; + var snap = new WalkerVisualSnapshot + { + LegCount = legCount, + PelvisOffset = new Vector3( + DecodeSnorm8(span[offset]) * MaxWirePelvisOffsetM, + DecodeSnorm8(span[offset + 1]) * MaxWirePelvisOffsetM, + DecodeSnorm8(span[offset + 2]) * MaxWirePelvisOffsetM), + LeanPitch = DecodeSnorm8(span[offset + 3]) * MaxWireLeanRad, + LeanRoll = DecodeSnorm8(span[offset + 4]) * MaxWireLeanRad + }; + offset += 5; for (int l = 0; l < legCount; l++) { snap.LegAngles[l] = new WalkerLegAngles diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index ea6c642..dbfbb06 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -13,9 +13,9 @@ namespace RustToDust.Ymir public const int SubStepCount = 4; public const int WorldBodyCapacity = 384; - private const ulong GroundStableId = 1; - private const ulong StaticBoxStableIdBase = 10; - private const ulong StaticMeshStableIdBase = 100; + internal const ulong GroundStableId = 1; + internal const ulong StaticBoxStableIdBase = 10; + internal const ulong StaticMeshStableIdBase = 100; public const ulong ContenderStableIdBase = 1000; private const ulong SpectatorStableIdBase = 3000; @@ -661,6 +661,7 @@ namespace RustToDust.Ymir ApplyPhysicsDrives(); _world.Step(FixedDt, subSteps); + PostStepWalkers(); SyncBodiesFromWorld(); UpdateObserverDetectionMemories(); @@ -682,6 +683,7 @@ namespace RustToDust.Ymir ApplyPhysicsDrives(); long t3 = Stopwatch.GetTimestamp(); _world.Step(FixedDt, subSteps); + PostStepWalkers(); long t4 = Stopwatch.GetTimestamp(); SyncBodiesFromWorld(); long t5 = Stopwatch.GetTimestamp(); @@ -1008,7 +1010,7 @@ namespace RustToDust.Ymir public static float GetPhysicsHalfHeight(ChassisSpec spec) => spec.IsWalker - ? spec.HalfHeight * (spec.Plane == GridPlane.Dorsal ? 0.62f : 0.72f) + ? WalkerLocomotion.GetRideHeight(spec) : spec.HalfHeight; private void SpawnContenderBody(ContenderState c) @@ -1019,8 +1021,6 @@ namespace RustToDust.Ymir } var spec = c.Grid.Spec; float physHalfH = GetPhysicsHalfHeight(spec); - float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; - float density = spec.MassKg / MathF.Max(0.1f, volume); Quaternion q; float spawnY; float initVelY = 0f; @@ -1028,56 +1028,75 @@ namespace RustToDust.Ymir if (c.HasTouchdownPose) { - q = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW); - q = q.LengthSquared() < 1e-6f ? Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw) : Quaternion.Normalize(q); - spawnY = c.Y; + var qRaw = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW); + qRaw = qRaw.LengthSquared() < 1e-6f ? Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw) : Quaternion.Normalize(qRaw); + if (spec.IsWalker) + { + var fwdYaw = Vector3.Transform(Vector3.UnitZ, qRaw); + float yaw = (fwdYaw.X * fwdYaw.X + fwdYaw.Z * fwdYaw.Z) > 1e-6f ? MathF.Atan2(fwdYaw.X, fwdYaw.Z) : c.Yaw; + q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + c.Yaw = yaw; + spawnY = MathF.Max(c.Y, State.Terrain.SampleHeight(c.X, c.Z) + physHalfH); + c.Y = spawnY; + } + else + { + q = qRaw; + spawnY = c.Y; + } initVelY = c.VelY; } else { q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw); - float clearance = spec.IsVtol - ? Math.Clamp(c.TargetHoverAltAgl, MatchRules.VtolMinClearanceAgl, MathF.Max(MatchRules.VtolMinClearanceAgl, spec.HoverMaxAltitudeM)) - : 0.15f; - spawnY = State.Terrain.SampleHeight(c.X, c.Z) + spec.HalfHeight + clearance; - if (spec.IsWalker && spec.Plane == GridPlane.Dorsal) + if (spec.IsWalker) { - var (nx, ny, nz) = State.Terrain.SampleNormal(c.X, c.Z); - Vector3 centerNorm = new Vector3(nx, ny, nz); - centerNorm = centerNorm.LengthSquared() > 1e-6f ? Vector3.Normalize(centerNorm) : Vector3.UnitY; - Vector3 fwd = Vector3.Transform(Vector3.UnitZ, q); - fwd.Y = 0f; - fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; - Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); - Vector3 hullSlope = WalkerLocomotion.ComputeHullSlopeNormal(State.Terrain, c.X, c.Z, fwd, right, spec.HalfWidth, spec.HalfLength, centerNorm, out _); - q = WalkerLocomotion.AlignUpToSlope(q, hullSlope, 0.90f, 0.350f); - - float minCornerClr = float.PositiveInfinity; - foreach (float sx in new[] { -spec.HalfWidth, spec.HalfWidth }) - { - foreach (float sz in new[] { -spec.HalfLength, spec.HalfLength }) - { - Vector3 corner = new Vector3(c.X, spawnY, c.Z) + Vector3.Transform(new Vector3(sx, -physHalfH, sz), q); - float clr = corner.Y - State.Terrain.SampleHeight(corner.X, corner.Z); - if (clr < minCornerClr) minCornerClr = clr; - } - } - if (minCornerClr < 0.25f) - { - spawnY += MathF.Min(1.2f, 0.25f - minCornerClr); - } + float terrY = State.Terrain.SampleHeight(c.X, c.Z); + var surf = WalkerLocomotion.SampleGroundAt(State.Terrain, _world, c.X, c.Z, terrY + 6.0f); + WalkerLocomotion.GetWalkerCapsuleParams(spec, out float spawnCapR, out float spawnCapHalfL); + spawnY = MathF.Max(terrY, surf.SurfaceY) + spawnCapHalfL + spawnCapR / Math.Clamp(surf.Normal.Y, 0.78f, 1f) + 0.02f; + } + else + { + float clearance = spec.IsVtol + ? Math.Clamp(c.TargetHoverAltAgl, MatchRules.VtolMinClearanceAgl, MathF.Max(MatchRules.VtolMinClearanceAgl, spec.HoverMaxAltitudeM)) + : 0.15f; + spawnY = State.Terrain.SampleHeight(c.X, c.Z) + spec.HalfHeight + clearance; } c.Y = spawnY; } - var handle = _world.AddBox( - stableId, - (c.X, spawnY, c.Z), - (spec.HalfWidth, physHalfH, spec.HalfLength), - density, - (q.X, q.Y, q.Z, q.W), - friction: 0.2f, - restitution: 0.1f); + Box3DSoaBodyHandle handle; + if (spec.IsWalker) + { + WalkerLocomotion.GetWalkerCapsuleParams(spec, out float capR, out float capHalfL); + float density = WalkerLocomotion.GetWalkerCapsuleDensity(spec, capR, capHalfL); + handle = _world.AddCapsule( + stableId, + (c.X, spawnY, c.Z), + capR, + capHalfL, + density, + (q.X, q.Y, q.Z, q.W), + friction: 0.0f, + restitution: 0.0f, + flags: Box3DSoaBodyFlags.LockAngularX + | Box3DSoaBodyFlags.LockAngularZ + | Box3DSoaBodyFlags.DisableContactRecycling); + } + else + { + float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; + float density = spec.MassKg / MathF.Max(0.1f, volume); + handle = _world.AddBox( + stableId, + (c.X, spawnY, c.Z), + (spec.HalfWidth, physHalfH, spec.HalfLength), + density, + (q.X, q.Y, q.Z, q.W), + friction: 0.2f, + restitution: 0.1f); + } _contenderBodies[c.Id] = handle; _entityByStableId[stableId] = (true, c.Id); @@ -1102,7 +1121,7 @@ namespace RustToDust.Ymir if (spec.IsWalker) { var ws = new WalkerState(spec); - ws.InitializePose(new Vector3(c.X, spawnY, c.Z), q, spec.MassKg, State.Terrain); + ws.InitializePose(new Vector3(c.X, spawnY, c.Z), q, spec.MassKg, State.Terrain, _world, handle.Lane); _contenderWalkers[c.Id] = ws; } else @@ -1144,21 +1163,48 @@ namespace RustToDust.Ymir { var spec = s.Grid.Spec; float physHalfH = GetPhysicsHalfHeight(spec); - float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; - float density = spec.MassKg / MathF.Max(0.1f, volume); var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, s.Yaw); ulong stableId = SpectatorStableIdBase + (ulong)s.Id; - float spawnY = State.Terrain.SampleHeight(s.X, s.Z) + spec.HalfHeight + 0.15f; - s.Y = spawnY; + float spawnY; - var handle = _world.AddBox( - stableId, - (s.X, spawnY, s.Z), - (spec.HalfWidth, physHalfH, spec.HalfLength), - density, - (q.X, q.Y, q.Z, q.W), - friction: 0.2f, - restitution: 0.1f); + Box3DSoaBodyHandle handle; + if (spec.IsWalker) + { + float terrY = State.Terrain.SampleHeight(s.X, s.Z); + var surf = WalkerLocomotion.SampleGroundAt(State.Terrain, _world, s.X, s.Z, terrY + 6.0f); + spawnY = MathF.Max(terrY, surf.SurfaceY) + physHalfH + 0.02f; + s.Y = spawnY; + + WalkerLocomotion.GetWalkerCapsuleParams(spec, out float capR, out float capHalfL); + float density = WalkerLocomotion.GetWalkerCapsuleDensity(spec, capR, capHalfL); + handle = _world.AddCapsule( + stableId, + (s.X, spawnY, s.Z), + capR, + capHalfL, + density, + (q.X, q.Y, q.Z, q.W), + friction: 0.0f, + restitution: 0.0f, + flags: Box3DSoaBodyFlags.LockAngularX + | Box3DSoaBodyFlags.LockAngularZ + | Box3DSoaBodyFlags.DisableContactRecycling); + } + else + { + float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; + float density = spec.MassKg / MathF.Max(0.1f, volume); + spawnY = State.Terrain.SampleHeight(s.X, s.Z) + spec.HalfHeight + 0.15f; + s.Y = spawnY; + handle = _world.AddBox( + stableId, + (s.X, spawnY, s.Z), + (spec.HalfWidth, physHalfH, spec.HalfLength), + density, + (q.X, q.Y, q.Z, q.W), + friction: 0.2f, + restitution: 0.1f); + } _spectatorBodies[s.Id] = handle; _entityByStableId[stableId] = (false, index); @@ -1175,7 +1221,7 @@ namespace RustToDust.Ymir if (spec.IsWalker) { var ws = new WalkerState(spec); - ws.InitializePose(new Vector3(s.X, spawnY, s.Z), q, spec.MassKg, State.Terrain); + ws.InitializePose(new Vector3(s.X, spawnY, s.Z), q, spec.MassKg, State.Terrain, _world, handle.Lane); _spectatorWalkers[s.Id] = ws; } else @@ -1232,15 +1278,16 @@ namespace RustToDust.Ymir public static void StepContenderPhysicsDrive( ContenderState c, - Box3DSoaView view, - int lane, + Box3DSoaWorld world, + Box3DSoaBodyHandle body, TerrainField terrain, ArenaMapKind mapKind, WalkerState? walker, float dt, - bool injectEngineHeat, - Box3DSoaWorld? world = null) + bool injectEngineHeat) { + var view = world.View; + int lane = body.Lane; float mass = view.Mass[lane]; if (mass <= 0f) { @@ -1279,9 +1326,9 @@ namespace RustToDust.Ymir } } - WalkerLocomotion.StepWalker( - walker, c.Grid, terrain, view, lane, mass, - pos, q, vel, angVel, desiredHorizVel, wTargetYawVel, c.BrakeCmd, dt); + WalkerLocomotion.PreStepWalker( + walker, c.Grid, terrain, world, body, mass, + desiredHorizVel, wTargetYawVel, c.BrakeCmd, dt); return; } @@ -1396,11 +1443,13 @@ namespace RustToDust.Ymir new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]), new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]), mass, - State.Terrain); + State.Terrain, + _world, + lane); _contenderWalkers[c.Id] = ws; } - StepContenderPhysicsDrive(c, view, handle.Lane, State.Terrain, State.MapKind, ws, FixedDt, injectEngineHeat: true, world: _world); + StepContenderPhysicsDrive(c, _world, handle, State.Terrain, State.MapKind, ws, FixedDt, injectEngineHeat: true); } // Spectators @@ -1430,8 +1479,9 @@ namespace RustToDust.Ymir Vector3 toGoal = new Vector3(goalX - pos.X, 0f, goalZ - pos.Z); float dist = toGoal.Length(); - // On Sion, StaticHeightField supports settled Neutral Patrons/Exemplars directly so Box3D can sleep them. - if (State.MapKind == ArenaMapKind.Sion && + // On Sion, StaticHeightField supports settled non-walker Neutral Patrons directly so Box3D can sleep them. + if (!s.Grid.Spec.IsWalker && + State.MapKind == ArenaMapKind.Sion && s.Stance == SpectatorStance.Neutral && s.Tier != SpectatorTier.Tourist && dist < 0.9f && @@ -1462,13 +1512,13 @@ namespace RustToDust.Ymir if (!_spectatorWalkers.TryGetValue(s.Id, out var ws)) { ws = new WalkerState(s.Grid.Spec); - ws.InitializePose(pos, q, mass, State.Terrain); + ws.InitializePose(pos, q, mass, State.Terrain, _world, lane); _spectatorWalkers[s.Id] = ws; } - WalkerLocomotion.StepWalker( - ws, s.Grid, State.Terrain, view, lane, mass, - pos, q, vel, angVel, desiredVel, targetSpecYawVel, brakeCmd: false, FixedDt); + WalkerLocomotion.PreStepWalker( + ws, s.Grid, State.Terrain, _world, handle, mass, + desiredVel, targetSpecYawVel, brakeCmd: false, FixedDt); continue; } @@ -1498,6 +1548,38 @@ namespace RustToDust.Ymir } } + private void PostStepWalkers() + { + var view = _world.View; + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.IsGroundedActive || !c.Grid.Spec.IsWalker || + !_contenderBodies.TryGetValue(c.Id, out var handle) || + !_contenderWalkers.TryGetValue(c.Id, out var ws)) + { + continue; + } + float mass = view.Mass[handle.Lane]; + if (mass <= 0f) continue; + WalkerLocomotion.PostStepWalker(ws, c.Grid, State.Terrain, _world, handle, mass, FixedDt); + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || !s.Grid.Spec.IsWalker || + !_spectatorBodies.TryGetValue(s.Id, out var handle) || + !_spectatorWalkers.TryGetValue(s.Id, out var ws)) + { + continue; + } + float mass = view.Mass[handle.Lane]; + if (mass <= 0f) continue; + WalkerLocomotion.PostStepWalker(ws, s.Grid, State.Terrain, _world, handle, mass, FixedDt); + } + } + private static void ApplyVtolFlightDrive( ContenderState c, int lane, @@ -3125,6 +3207,11 @@ namespace RustToDust.Ymir isSpectatorShooter, shooterEntityId, view); + + if (c.IsGroundedActive && _contenderBodies.TryGetValue(c.Id, out var cBody)) + { + ApplySplashKnockbackImpulse(cBody.Lane, view, c.Grid.Spec.MassKg, cPos, shotDir, splashDamage * atten); + } } for (int i = 0; i < State.Spectators.Spectators.Count; i++) @@ -3167,9 +3254,42 @@ namespace RustToDust.Ymir isSpectatorShooter, shooterEntityId, view); + + if (s.Alive && _spectatorBodies.TryGetValue(s.Id, out var sBody)) + { + ApplySplashKnockbackImpulse(sBody.Lane, view, s.Grid.Spec.MassKg, sPos, shotDir, splashDamage * atten); + } } } + private void ApplySplashKnockbackImpulse( + int lane, + Box3DSoaView view, + float specMassKg, + Vector3 bodyPos, + Vector3 shotDir, + float effectiveSplashDamage) + { + float mass = view.Mass[lane]; + if (mass <= 0f || effectiveSplashDamage <= 0f) + { + return; + } + const float maxImpulseV = 12.0f; + float kbSpeed = MathF.Min(maxImpulseV, effectiveSplashDamage * 0.045f * (2500f / MathF.Max(500f, specMassKg))); + if (kbSpeed <= 0.15f) + { + return; + } + Vector3 hDir = new(shotDir.X, 0f, shotDir.Z); + hDir = hDir.LengthSquared() > 1e-4f ? Vector3.Normalize(hDir) : Vector3.UnitZ; + Vector3 kbDir = Vector3.Normalize(hDir + new Vector3(0f, 0.22f, 0f)); + _world.ApplyImpulse( + lane, + (kbDir.X * kbSpeed * mass, kbDir.Y * kbSpeed * mass, kbDir.Z * kbSpeed * mass), + (bodyPos.X, bodyPos.Y, bodyPos.Z)); + } + void IOrdnanceTargetSink.EmitTracer( Vector3 start, Vector3 end, diff --git a/src/RustToDust.Ymir/WalkerLocomotion.cs b/src/RustToDust.Ymir/WalkerLocomotion.cs index 71b1d13..f80b1d7 100644 --- a/src/RustToDust.Ymir/WalkerLocomotion.cs +++ b/src/RustToDust.Ymir/WalkerLocomotion.cs @@ -191,8 +191,6 @@ namespace RustToDust.Ymir { public WalkerLegAngles Theta; public WalkerLegAngles Omega; - public float RecoilHipImpulse; - public float RecoilKneeImpulse; } public struct WalkerCheckpoint @@ -204,11 +202,27 @@ namespace RustToDust.Ymir public float SwingTime; public float SwingPhase; public float SimTime; + public bool Grounded; + public bool WasGrounded; public bool IsAirborne; public bool WasAirborne; + public Vector3 GroundNormal; + public float ImpactVelY; + public float PrevVelY; + public bool PreStepHadUpwardImpulse; + public Vector3 PrevHorizVel; public float MaxFootSlipM; - public Vector3 LastTotalForce; - public Vector3 LastTotalTorque; + public Vector3 PelvisOffset; + public float CompressionY; + public float CompressionVelY; + public float LeanPitch; + public float LeanPitchVel; + public float LeanRoll; + public float LeanRollVel; + public bool DidStepUp; + public bool FirstStepFromIdle; + public Vector3 StepRestorePos; + public float StepDeltaY; public LegArray4 Planted; public LegArray4 FootSole; public LegArray4 SwingStartSole; @@ -216,7 +230,7 @@ namespace RustToDust.Ymir public LegArray4 FootNormal; public LegArray4 SwingStartNormal; public LegArray4 SwingTargetNormal; - public LegArray4 LastGrfY; + public LegArray4 LoadG; public LegArray4 Actuators; public WalkerVisualSnapshot PrevSnap; public WalkerVisualSnapshot CurrSnap; @@ -225,7 +239,11 @@ namespace RustToDust.Ymir public sealed class WalkerState { public const float ArenaGravity = 20f; - public const float FootFriction = 1.10f; + public const float MaxWalkableNormalY = 0.819152f; // cos(35 deg) + public const float MaxCliffGuardNormalY = 0.707107f; // cos(45 deg) - guards steep cliffs while letting 1-pixel Sion DEM creases climb smoothly + public const float MaxStepUpM = 0.65f; + public const float MaxStepDownM = 0.75f; + public const float SkinLiftM = 0.045f; // >= 0.035-0.04 m to clear resting B3_LINEAR_SLOP public WalkerGeometrySpec Geom { get; private set; } public float GeomScale { get; private set; } @@ -235,11 +253,27 @@ namespace RustToDust.Ymir public float SwingTime; public float SwingPhase; public float SimTime; + public bool Grounded; + public bool WasGrounded; public bool IsAirborne; public bool WasAirborne; + public Vector3 GroundNormal = Vector3.UnitY; + public float ImpactVelY; + public float PrevVelY; + public bool PreStepHadUpwardImpulse; + public Vector3 PrevHorizVel; public float MaxFootSlipM; - public Vector3 LastTotalForce; - public Vector3 LastTotalTorque; + public Vector3 PelvisOffset; + public float CompressionY; + public float CompressionVelY; + public float LeanPitch; + public float LeanPitchVel; + public float LeanRoll; + public float LeanRollVel; + public bool DidStepUp; + public bool FirstStepFromIdle; + public Vector3 StepRestorePos; + public float StepDeltaY; public LegArray4 Planted; public LegArray4 FootSole; @@ -248,7 +282,7 @@ namespace RustToDust.Ymir public LegArray4 FootNormal; public LegArray4 SwingStartNormal; public LegArray4 SwingTargetNormal; - public LegArray4 LastGrfY; + public LegArray4 LoadG; public LegArray4 Actuators; public WalkerVisualSnapshot PrevSnap; @@ -260,61 +294,109 @@ namespace RustToDust.Ymir GeomScale = Geom.ModelHalfHeight > 1e-4f ? spec.HalfHeight / Geom.ModelHalfHeight : 1f; } - public void InitializePose(Vector3 comPos, Quaternion qBody, float mass, TerrainField terrain) + public void InitializePose( + Vector3 comPos, + Quaternion qBody, + float mass, + TerrainField terrain, + Box3DSoaWorld? world = null, + int selfLane = -1) { int n = Geom.LegCount; StanceGroup = 0; SwingTime = 0f; SwingPhase = 0f; SimTime = 0f; - bool anyCanReach = false; - for (int i = 0; i < n; i++) - { - Vector3 hipW = comPos + Vector3.Transform(Geom.Legs[i].HipInCom * GeomScale, qBody); - float gUnder = terrain.SampleHeight(hipW.X, hipW.Z); - float minAnkle = hipW.Y - (gUnder + Geom.Legs[i].AnkleH * GeomScale); - if (minAnkle <= Geom.Legs[i].MaxLegReach * GeomScale + 0.08f * GeomScale) - { - anyCanReach = true; - break; - } - } - IsAirborne = !anyCanReach; - WasAirborne = IsAirborne; MaxFootSlipM = 0f; - LastTotalForce = Vector3.Zero; - LastTotalTorque = Vector3.Zero; + PelvisOffset = Vector3.Zero; + CompressionY = 0f; + CompressionVelY = 0f; + LeanPitch = 0f; + LeanPitchVel = 0f; + LeanRoll = 0f; + LeanRollVel = 0f; + ImpactVelY = 0f; + PrevVelY = 0f; + PreStepHadUpwardImpulse = false; + PrevHorizVel = Vector3.Zero; + DidStepUp = false; + FirstStepFromIdle = true; + StepRestorePos = comPos; + StepDeltaY = 0f; + + Quaternion qYaw = WalkerLocomotion.ExtractYawQuaternion(qBody); + float rideH = Geom.ModelRideHeight * GeomScale; + var centerHit = WalkerLocomotion.SampleGroundAt(terrain, world, comPos.X, comPos.Z, comPos.Y + 0.5f, 0.25f); + float bottomClearance = (comPos.Y - rideH) - centerHit.SurfaceY; + Grounded = centerHit.Hit && centerHit.Normal.Y >= MaxWalkableNormalY && bottomClearance <= 0.18f; + WasGrounded = Grounded; + IsAirborne = !Grounded; + WasAirborne = IsAirborne; + GroundNormal = centerHit.Hit ? centerHit.Normal : Vector3.UnitY; for (int i = 0; i < n; i++) { Vector3 restLocal = new(Geom.Legs[i].RestFootXZ.X * GeomScale, 0f, Geom.Legs[i].RestFootXZ.Y * GeomScale); - Vector3 worldPos = comPos + Vector3.Transform(restLocal, qBody); - float gh = terrain.SampleHeight(worldPos.X, worldPos.Z); - Vector3 fn = SampleTerrainNormal(terrain, worldPos.X, worldPos.Z); + Vector3 worldPos = comPos + Vector3.Transform(restLocal, qYaw); + var gHit = WalkerLocomotion.SampleGroundAt(terrain, world, worldPos.X, worldPos.Z, comPos.Y + 0.6f); - FootSole[i] = new Vector3(worldPos.X, gh, worldPos.Z); - FootNormal[i] = fn; + FootSole[i] = new Vector3(worldPos.X, gHit.SurfaceY, worldPos.Z); + FootNormal[i] = gHit.Normal; SwingStartSole[i] = FootSole[i]; SwingTargetSole[i] = FootSole[i]; - SwingStartNormal[i] = fn; - SwingTargetNormal[i] = fn; - Planted[i] = true; - LastGrfY[i] = (mass * ArenaGravity) / n; + SwingStartNormal[i] = gHit.Normal; + SwingTargetNormal[i] = gHit.Normal; + Planted[i] = Grounded; + LoadG[i] = Grounded ? (n == 2 ? 1.0f : 0.65f) : 0f; + } - Vector3 hipWorld = comPos + Vector3.Transform(Geom.Legs[i].HipInCom * GeomScale, qBody); + if (n == 4 && Grounded) + { + // Pre-align dorsal quadruped visual pitch/roll & pelvis height to 4-foot support plane at t=0 + Vector3 fwd = Vector3.Transform(Vector3.UnitZ, qYaw); + fwd.Y = 0f; + fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; + Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); + + Vector3 vFront = 0.5f * (FootSole[0] + FootSole[1]) - 0.5f * (FootSole[2] + FootSole[3]); + Vector3 vLeft = 0.5f * (FootSole[0] + FootSole[2]) - 0.5f * (FootSole[1] + FootSole[3]); + Vector3 polyNorm = Vector3.Cross(vFront, vLeft); + if (polyNorm.Y < 0f) polyNorm = -polyNorm; + polyNorm = polyNorm.LengthSquared() > 1e-4f ? Vector3.Normalize(polyNorm) : GroundNormal; + + float maxSlopeRad = 0.20943951f; // 12 deg + LeanPitch = Math.Clamp(MathF.Asin(Math.Clamp(Vector3.Dot(fwd, polyNorm), -0.45f, 0.45f)) * 0.75f, -maxSlopeRad, maxSlopeRad); + LeanRoll = Math.Clamp(MathF.Asin(Math.Clamp(Vector3.Dot(right, polyNorm), -0.40f, 0.40f)) * 0.75f, -maxSlopeRad, maxSlopeRad); + float meanSoleY = 0.25f * (FootSole[0].Y + FootSole[1].Y + FootSole[2].Y + FootSole[3].Y); + PelvisOffset = new Vector3(0f, Math.Clamp(meanSoleY - centerHit.SurfaceY, -0.40f * GeomScale, 0.40f * GeomScale), 0f); + } + + Quaternion qTotal = Quaternion.Normalize(qYaw * Quaternion.CreateFromYawPitchRoll(0f, LeanPitch, LeanRoll)); + Vector3 pelvisShift = Vector3.Transform(PelvisOffset, qYaw); + + for (int i = 0; i < n; i++) + { + Vector3 hipWorld = comPos + pelvisShift + Vector3.Transform(Geom.Legs[i].HipInCom * GeomScale, qTotal); Vector3 sole = FootSole[i]; - if (WalkerLocomotion.ClampSoleToReach(hipWorld, Geom.Legs[i].AnkleH * GeomScale, Geom.Legs[i].MaxLegReach * GeomScale * 0.96f, terrain, ref sole, out Vector3 clampedN)) + if (WalkerLocomotion.ClampSoleToReach( + hipWorld, + Geom.Legs[i].AnkleH * GeomScale, + Geom.Legs[i].MaxLegReach * GeomScale * 0.96f, + terrain, + world, + comPos.Y + 0.6f, + ref sole, + out Vector3 clampedN)) { - fn = clampedN; FootSole[i] = sole; - FootNormal[i] = fn; + FootNormal[i] = clampedN; SwingStartSole[i] = sole; SwingTargetSole[i] = sole; - SwingStartNormal[i] = fn; - SwingTargetNormal[i] = fn; + SwingStartNormal[i] = clampedN; + SwingTargetNormal[i] = clampedN; } - Vector3 ankleWorld = FootSole[i] + fn * (Geom.Legs[i].AnkleH * GeomScale); - WalkerLegAngles initAng = WalkerLocomotion.SolveLegTargetAngles(Geom, GeomScale, i, hipWorld, qBody, ankleWorld, fn, 0f); + Vector3 ankleWorld = FootSole[i] + FootNormal[i] * (Geom.Legs[i].AnkleH * GeomScale); + WalkerLegAngles initAng = WalkerLocomotion.SolveLegTargetAngles(Geom, GeomScale, i, hipWorld, qTotal, ankleWorld, FootNormal[i], 0f); Actuators[i] = new WalkerJointActuator { Theta = initAng, @@ -322,7 +404,7 @@ namespace RustToDust.Ymir }; } - CurrSnap = BuildSnapshot(comPos, qBody, mass); + CurrSnap = BuildSnapshot(comPos, qYaw, mass); PrevSnap = CurrSnap; Initialized = true; } @@ -341,11 +423,27 @@ namespace RustToDust.Ymir SwingTime = SwingTime, SwingPhase = SwingPhase, SimTime = SimTime, + Grounded = Grounded, + WasGrounded = WasGrounded, IsAirborne = IsAirborne, WasAirborne = WasAirborne, + GroundNormal = GroundNormal, + ImpactVelY = ImpactVelY, + PrevVelY = PrevVelY, + PreStepHadUpwardImpulse = PreStepHadUpwardImpulse, + PrevHorizVel = PrevHorizVel, MaxFootSlipM = MaxFootSlipM, - LastTotalForce = LastTotalForce, - LastTotalTorque = LastTotalTorque, + PelvisOffset = PelvisOffset, + CompressionY = CompressionY, + CompressionVelY = CompressionVelY, + LeanPitch = LeanPitch, + LeanPitchVel = LeanPitchVel, + LeanRoll = LeanRoll, + LeanRollVel = LeanRollVel, + DidStepUp = DidStepUp, + FirstStepFromIdle = FirstStepFromIdle, + StepRestorePos = StepRestorePos, + StepDeltaY = StepDeltaY, Planted = Planted, FootSole = FootSole, SwingStartSole = SwingStartSole, @@ -353,7 +451,7 @@ namespace RustToDust.Ymir FootNormal = FootNormal, SwingStartNormal = SwingStartNormal, SwingTargetNormal = SwingTargetNormal, - LastGrfY = LastGrfY, + LoadG = LoadG, Actuators = Actuators, PrevSnap = PrevSnap, CurrSnap = CurrSnap @@ -366,11 +464,27 @@ namespace RustToDust.Ymir SwingTime = cp.SwingTime; SwingPhase = cp.SwingPhase; SimTime = cp.SimTime; + Grounded = cp.Grounded; + WasGrounded = cp.WasGrounded; IsAirborne = cp.IsAirborne; WasAirborne = cp.WasAirborne; + GroundNormal = cp.GroundNormal; + ImpactVelY = cp.ImpactVelY; + PrevVelY = cp.PrevVelY; + PreStepHadUpwardImpulse = cp.PreStepHadUpwardImpulse; + PrevHorizVel = cp.PrevHorizVel; MaxFootSlipM = cp.MaxFootSlipM; - LastTotalForce = cp.LastTotalForce; - LastTotalTorque = cp.LastTotalTorque; + PelvisOffset = cp.PelvisOffset; + CompressionY = cp.CompressionY; + CompressionVelY = cp.CompressionVelY; + LeanPitch = cp.LeanPitch; + LeanPitchVel = cp.LeanPitchVel; + LeanRoll = cp.LeanRoll; + LeanRollVel = cp.LeanRollVel; + DidStepUp = cp.DidStepUp; + FirstStepFromIdle = cp.FirstStepFromIdle; + StepRestorePos = cp.StepRestorePos; + StepDeltaY = cp.StepDeltaY; Planted = cp.Planted; FootSole = cp.FootSole; SwingStartSole = cp.SwingStartSole; @@ -378,7 +492,7 @@ namespace RustToDust.Ymir FootNormal = cp.FootNormal; SwingStartNormal = cp.SwingStartNormal; SwingTargetNormal = cp.SwingTargetNormal; - LastGrfY = cp.LastGrfY; + LoadG = cp.LoadG; Actuators = cp.Actuators; PrevSnap = cp.PrevSnap; CurrSnap = cp.CurrSnap; @@ -386,12 +500,15 @@ namespace RustToDust.Ymir public void SyncBodyPoseOnly(Vector3 comPos, Quaternion qBody, float mass) { + Quaternion qYaw = WalkerLocomotion.ExtractYawQuaternion(qBody); CurrSnap.ComPos = comPos; - CurrSnap.ComRot = qBody; - float denom = MathF.Max(1f, 0.5f * mass * ArenaGravity); + CurrSnap.ComRot = qYaw; + CurrSnap.PelvisOffset = PelvisOffset; + CurrSnap.LeanPitch = LeanPitch; + CurrSnap.LeanRoll = LeanRoll; for (int i = 0; i < Geom.LegCount; i++) { - CurrSnap.LoadG[i] = LastGrfY[i] / denom; + CurrSnap.LoadG[i] = LoadG[i]; } } @@ -401,18 +518,13 @@ namespace RustToDust.Ymir { return; } - Vector3 shotLocal = Vector3.Transform(shotDirWorld, Quaternion.Conjugate(qBody)); - float dirSign = shotLocal.Z >= -0.2f ? 1f : -1f; - float mag = Math.Clamp(weaponDamage / 55f, 0.12f, 1.35f) * dirSign; - - int n = Geom.LegCount; - for (int i = 0; i < n; i++) - { - float weight = Planted[i] ? 1.0f : 0.25f; - ref var act = ref Actuators[i]; - act.RecoilHipImpulse -= 0.85f * mag * weight; - act.RecoilKneeImpulse += 1.25f * mag * weight; - } + Quaternion qYaw = WalkerLocomotion.ExtractYawQuaternion(qBody); + Vector3 shotLocal = Vector3.Transform(shotDirWorld, Quaternion.Conjugate(qYaw)); + float impulseMag = Math.Clamp(weaponDamage / 55f, 0.15f, 1.80f); + // Firing forward (+Z) kicks torso backward (-Pitch around +X); lateral shots roll opposite shot direction + LeanPitchVel = Math.Clamp(LeanPitchVel - shotLocal.Z * impulseMag * 1.15f, -2.0f, 2.0f); + LeanRollVel = Math.Clamp(LeanRollVel + shotLocal.X * impulseMag * 0.90f, -2.0f, 2.0f); + CompressionVelY = Math.Clamp(CompressionVelY - impulseMag * 0.35f, -4.5f, 2.0f); } public WalkerVisualSnapshot BuildSnapshot(Vector3 comPos, Quaternion qBody, float mass) @@ -424,15 +536,17 @@ namespace RustToDust.Ymir IsDigitigrade = Geom.IsDigitigrade, IsArachnidUp = Geom.IsArachnidUp, ComPos = comPos, - ComRot = qBody + ComRot = WalkerLocomotion.ExtractYawQuaternion(qBody), + PelvisOffset = PelvisOffset, + LeanPitch = LeanPitch, + LeanRoll = LeanRoll }; - float denom = MathF.Max(1f, 0.5f * mass * ArenaGravity); for (int i = 0; i < Geom.LegCount; i++) { snap.LegAngles[i] = Actuators[i].Theta; snap.FootNormal[i] = FootNormal[i]; - snap.LoadG[i] = LastGrfY[i] / denom; + snap.LoadG[i] = LoadG[i]; } return snap; } @@ -445,10 +559,14 @@ namespace RustToDust.Ymir } } + internal readonly record struct WalkableSurfaceHit( + bool Hit, float SurfaceY, Vector3 Normal, bool FromStaticBoxOrMesh); + public static class WalkerLocomotion { - private const float Gravity = WalkerState.ArenaGravity; - private const float Mu = WalkerState.FootFriction; + private const float MaxBipedLeanRad = 0.13962634f; // 8.0 deg + private const float MaxQuadSlopeRad = 0.20943951f; // 12.0 deg + private const float MaxQuadTotalRad = 0.25307274f; // 14.5 deg (< 15 deg) public static float GetRideHeight(ChassisSpec spec) { @@ -457,194 +575,796 @@ namespace RustToDust.Ymir return geom.ModelRideHeight * scale; } - internal static Vector3 ComputeHullSlopeNormal( + public static void GetWalkerCapsuleParams(ChassisSpec spec, out float radius, out float halfLength) + { + float rideH = GetRideHeight(spec); + float minPlanar = MathF.Min(spec.HalfWidth, spec.HalfLength); + radius = Math.Clamp(minPlanar * 0.65f, 0.55f, MathF.Min(0.72f * rideH, 2.60f)); + halfLength = MathF.Max(0.05f, rideH - radius); + } + + public static float GetWalkerCapsuleDensity(ChassisSpec spec, float radius, float halfLength) + { + float volume = MathF.PI * radius * radius * (2f * halfLength + (4f / 3f) * radius); + return spec.MassKg / MathF.Max(0.1f, volume); + } + + internal static Quaternion ExtractYawQuaternion(Quaternion q) + { + if (q.LengthSquared() < 1e-6f) + { + return Quaternion.Identity; + } + q = Quaternion.Normalize(q); + Vector3 fwd = Vector3.Transform(Vector3.UnitZ, q); + fwd.Y = 0f; + if (fwd.LengthSquared() < 1e-6f) + { + return Quaternion.Identity; + } + float yaw = MathF.Atan2(fwd.X, fwd.Z); + return Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + } + + private static bool IsDesertFloorSlab(TerrainField terrain, ulong stableId) => + !terrain.IsHeightmapMode && stableId == ArenaSession.GroundStableId; + + internal static WalkableSurfaceHit SampleGroundAt( TerrainField terrain, + Box3DSoaWorld? world, float x, float z, - Vector3 fwd, - Vector3 right, - float halfW, - float halfL, - Vector3 centerNormal, - out float planeCenterY) + float referenceMaxY, + float probeRadius = 0.15f) { - float w = MathF.Max(1.0f, halfW * 0.90f); - float l = MathF.Max(1.0f, halfL * 0.90f); - - float flX = x - right.X * w + fwd.X * l, flZ = z - right.Z * w + fwd.Z * l; - float frX = x + right.X * w + fwd.X * l, frZ = z + right.Z * w + fwd.Z * l; - float rlX = x - right.X * w - fwd.X * l, rlZ = z - right.Z * w - fwd.Z * l; - float rrX = x + right.X * w - fwd.X * l, rrZ = z + right.Z * w - fwd.Z * l; - - float hCenter = terrain.SampleHeight(x, z); - if (terrain.SampleNormal(flX, flZ).Ny < 0.72f || - terrain.SampleNormal(frX, frZ).Ny < 0.72f || - terrain.SampleNormal(rlX, rlZ).Ny < 0.72f || - terrain.SampleNormal(rrX, rrZ).Ny < 0.72f) + float terrY = terrain.SampleHeight(x, z); + Vector3 terrN = WalkerState.SampleTerrainNormal(terrain, x, z); + if (world is null) { - planeCenterY = hCenter; - return centerNormal.Y >= 0.78f ? centerNormal : Vector3.UnitY; + return new WalkableSurfaceHit(true, terrY, terrN, false); } - float hFL = terrain.SampleHeight(flX, flZ); - float hFR = terrain.SampleHeight(frX, frZ); - float hRL = terrain.SampleHeight(rlX, rlZ); - float hRR = terrain.SampleHeight(rrX, rrZ); - planeCenterY = 0.25f * (hFL + hFR + hRL + hRR); - - float gf = ((hFR + hFL) - (hRR + hRL)) / (4f * l); - float gr = ((hFR + hRR) - (hFL + hRL)) / (4f * w); - Vector3 nPlane = Vector3.Normalize(Vector3.UnitY - fwd * gf - right * gr); - if (nPlane.Y < 0.75f) + float castTop = MathF.Max(referenceMaxY, terrY + probeRadius + 0.5f); + float castBottom = terrY - 2.0f; + float spanY = castTop - castBottom; + if (spanY < 0.05f) { - return centerNormal.Y >= 0.78f ? centerNormal : Vector3.UnitY; + return new WalkableSurfaceHit(true, terrY, terrN, false); } - return centerNormal.Y >= 0.78f - ? Vector3.Normalize(centerNormal * 0.30f + nPlane * 0.70f) - : nPlane; + + var hit = world.CastCapsuleClosest( + (x, castTop, z), + probeRadius, + 0f, + (0f, -spanY, 0f), + ignoreLane: -1, + Box3DSoaQueryMask.Static); + + if (!hit.Hit || IsDesertFloorSlab(terrain, hit.StableId) || hit.Point.Y < terrY - 0.35f) + { + return new WalkableSurfaceHit(true, terrY, terrN, false); + } + + Vector3 hitN = new(hit.Normal.X, hit.Normal.Y, hit.Normal.Z); + hitN = hitN.LengthSquared() > 1e-6f ? Vector3.Normalize(hitN) : Vector3.UnitY; + bool isBuildingOrCover = hit.StableId >= ArenaSession.StaticBoxStableIdBase && + hit.StableId < ArenaSession.ContenderStableIdBase; + if (isBuildingOrCover && hit.Point.Y >= terrY - 0.05f) + { + return new WalkableSurfaceHit(true, hit.Point.Y, hitN, true); + } + + if (hit.StableId == ArenaSession.GroundStableId) + { + if (terrY < hit.Point.Y - 0.05f) + { + return new WalkableSurfaceHit(true, terrY, terrN, false); + } + return hit.Point.Y >= terrY + ? new WalkableSurfaceHit(true, hit.Point.Y, hitN, false) + : new WalkableSurfaceHit(true, terrY, terrN, false); + } + + return new WalkableSurfaceHit(true, terrY, terrN, false); } - internal static Quaternion AlignUpToSlope(Quaternion yawQuat, Vector3 slopeNormal, float alignFraction, float maxTiltRad) + private static bool TraceTerrainCapsuleDown( + TerrainField terrain, + Vector3 fromCenter, + float spanDown, + float radius, + float halfLength, + out float endCenterY, + out Vector3 normal) { - Vector3 fwd = Vector3.Transform(Vector3.UnitZ, yawQuat); - fwd.Y = 0f; - fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; - Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); - - float slopePitch = MathF.Asin(Math.Clamp(Vector3.Dot(fwd, slopeNormal), -0.45f, 0.45f)) * alignFraction; - float slopeRoll = MathF.Asin(Math.Clamp(Vector3.Dot(right, slopeNormal), -0.40f, 0.40f)) * alignFraction; - Vector3 desUp = Vector3.Normalize(Vector3.UnitY + fwd * MathF.Sin(slopePitch) + right * MathF.Sin(slopeRoll)); - if (MathF.Acos(Math.Clamp(desUp.Y, -1f, 1f)) > maxTiltRad) + float terrY = terrain.SampleHeight(fromCenter.X, fromCenter.Z); + normal = WalkerState.SampleTerrainNormal(terrain, fromCenter.X, fromCenter.Z); + float contactCenterY = terrY + halfLength + radius * Math.Clamp(1f / MathF.Max(0.45f, normal.Y), 1f, 1.25f); + float bottomCenterY = fromCenter.Y - spanDown; + if (contactCenterY <= fromCenter.Y + 0.02f && contactCenterY >= bottomCenterY) { - Vector3 h = new(desUp.X, 0f, desUp.Z); - float hLen = h.Length(); - desUp = hLen > 1e-4f - ? Vector3.UnitY * MathF.Cos(maxTiltRad) + (h / hLen) * MathF.Sin(maxTiltRad) - : Vector3.UnitY; + endCenterY = MathF.Min(fromCenter.Y, contactCenterY); + return true; } - Vector3 axis = Vector3.Cross(Vector3.UnitY, desUp); - float axisLen = axis.Length(); - if (axisLen <= 1e-5f) - { - return yawQuat; - } - float ang = MathF.Acos(Math.Clamp(desUp.Y, -1f, 1f)); - return Quaternion.Normalize(Quaternion.CreateFromAxisAngle(axis / axisLen, ang) * yawQuat); + endCenterY = bottomCenterY; + return false; } - public static void StepWalker( + public static void PreStepWalker( WalkerState ws, ChassisGrid grid, TerrainField terrain, - Box3DSoaView view, - int lane, + Box3DSoaWorld world, + Box3DSoaBodyHandle body, float mass, - Vector3 comPos, - Quaternion qBody, - Vector3 vel, - Vector3 angVel, Vector3 desiredHorizVel, float targetYawVel, bool brakeCmd, float dt) { + int lane = body.Lane; + var view = world.View; + Vector3 pos = new(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + Vector3 vel = new(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + Quaternion qYaw = ExtractYawQuaternion(new Quaternion( + view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane])); + if (!ws.Initialized) { - ws.InitializePose(comPos, qBody, mass, terrain); + ws.InitializePose(pos, qYaw, mass, terrain, world, lane); } - var geom = ws.Geom; - float scale = ws.GeomScale; - int n = geom.LegCount; ws.SimTime += dt; + ws.WasGrounded = ws.Grounded; + ws.PreStepHadUpwardImpulse = vel.Y > 3.5f; + ws.PrevHorizVel = new Vector3(vel.X, 0f, vel.Z); + ws.PrevVelY = vel.Y; + ws.DidStepUp = false; + + GetWalkerCapsuleParams(grid.Spec, out float radius, out float halfLength); Span legIntegrities = stackalloc float[4]; grid.GetLegIntegrities(legIntegrities); float avgIntegrity = 0f; - bool anyLegSeverelyCrippled = false; - for (int i = 0; i < n; i++) + for (int i = 0; i < ws.Geom.LegCount; i++) { - float integ = Math.Clamp(legIntegrities[i], 0.25f, 1f); - legIntegrities[i] = integ; - avgIntegrity += integ; - if (integ < 0.5f) + avgIntegrity += Math.Clamp(legIntegrities[i], 0.25f, 1f); + } + avgIntegrity /= ws.Geom.LegCount; + + // 1. Dead-beat zero-momentum yaw control + float maxTurnRate = grid.ComputeTurnRate(); + float clampedYawVel = ws.Grounded ? Math.Clamp(targetYawVel, -maxTurnRate, maxTurnRate) : 0f; + + // 2. Bounded-traction horizontal drive (preserves explosion knockback momentum briefly) + Vector3 vHoriz = new(vel.X, 0f, vel.Z); + Vector3 vWish = brakeCmd ? Vector3.Zero : desiredHorizVel; + float maxSpd = MathF.Max(4f, grid.Spec.MaxSpeed); + float tractionAccel = ws.Grounded + ? maxSpd * 4.5f * (brakeCmd ? 1.8f : 1.0f) * avgIntegrity + : maxSpd * 0.4f; + Vector3 dv = vWish - vHoriz; + float dvLen = dv.Length(); + float maxDv = tractionAccel * dt; + if (dvLen > maxDv && dvLen > 1e-5f) + { + dv *= maxDv / dvLen; + } + vHoriz += dv; + if (vWish.LengthSquared() < 1e-4f && vHoriz.LengthSquared() < 0.04f * 0.04f && ws.Grounded) + { + vHoriz = Vector3.Zero; + } + + // 3. Steep-slope guard (> 45 deg): strip uphill velocity component while allowing cross-slope slide + float hSpeed = vHoriz.Length(); + if (ws.Grounded && hSpeed > 1e-3f) + { + if (ws.GroundNormal.Y < WalkerState.MaxCliffGuardNormalY) { - anyLegSeverelyCrippled = true; + StripUphillVelocity(ref vHoriz, ws.GroundNormal); + } + else if (vWish.LengthSquared() > 1e-4f) + { + Vector3 moveDir = vHoriz / hSpeed; + float probeDist = MathF.Min(radius * 0.65f, 1.4f) + hSpeed * dt; + float terrHere = terrain.SampleHeight(pos.X, pos.Z); + float ax = pos.X + moveDir.X * probeDist; + float az = pos.Z + moveDir.Z * probeDist; + float terrAhead = terrain.SampleHeight(ax, az); + if (terrAhead - terrHere > WalkerState.MaxStepUpM) + { + Vector3 aheadN = WalkerState.SampleTerrainNormal(terrain, ax, az); + if (aheadN.Y < WalkerState.MaxCliffGuardNormalY) + { + StripUphillVelocity(ref vHoriz, aheadN); + } + } + } + hSpeed = vHoriz.Length(); + } + + // 4. Walkable slope tangent tracking vs real ballistic freefall + bool airborneImpulse = vel.Y > 3.5f; + float targetVy = vel.Y; + if (ws.Grounded && !airborneImpulse && ws.GroundNormal.Y >= WalkerState.MaxCliffGuardNormalY) + { + float slopeVy = -(vHoriz.X * ws.GroundNormal.X + vHoriz.Z * ws.GroundNormal.Z) / ws.GroundNormal.Y; + targetVy = Math.Clamp(slopeVy, -18f, 16f); + view.ForceX[lane] = 0f; + view.ForceY[lane] = mass * WalkerState.ArenaGravity; + view.ForceZ[lane] = 0f; + } + else + { + view.ForceX[lane] = 0f; + view.ForceY[lane] = 0f; + view.ForceZ[lane] = 0f; + } + view.TorqueX[lane] = 0f; + view.TorqueY[lane] = 0f; + view.TorqueZ[lane] = 0f; + + world.SetBodyMotion( + body, + rotation: (qYaw.X, qYaw.Y, qYaw.Z, qYaw.W), + linearVelocity: (vHoriz.X, targetVy, vHoriz.Z), + angularVelocity: (0f, clampedYawVel, 0f)); + + // 5. 4-Phase TryStep(0.65 m) with >= 0.035-0.04 m upward skin lift + if (ws.Grounded && !airborneImpulse && hSpeed > 0.05f) + { + TryStepUp( + ws, terrain, world, body, lane, + pos, radius, halfLength, vHoriz, clampedYawVel, dt); + } + } + + private static void StripUphillVelocity(ref Vector3 vHoriz, Vector3 slopeNormal) + { + Vector3 downXZ = new(slopeNormal.X, 0f, slopeNormal.Z); + float downLen = downXZ.Length(); + if (downLen <= 1e-4f) + { + return; + } + downXZ /= downLen; + float uphill = -Vector3.Dot(vHoriz, downXZ); + if (uphill > 0f) + { + vHoriz += downXZ * uphill; + } + } + + private static void TryStepUp( + WalkerState ws, + TerrainField terrain, + Box3DSoaWorld world, + Box3DSoaBodyHandle body, + int lane, + Vector3 pos, + float radius, + float halfLength, + Vector3 vHoriz, + float yawRate, + float dt) + { + float hSpeed = vHoriz.Length(); + if (hSpeed <= 0.05f) + { + return; + } + Vector3 moveDir = vHoriz / hSpeed; + Vector3 slopeMoveDir = moveDir; + if (ws.GroundNormal.Y >= WalkerState.MaxWalkableNormalY) + { + Vector3 sd = moveDir - ws.GroundNormal * Vector3.Dot(moveDir, ws.GroundNormal); + if (sd.LengthSquared() > 1e-4f) + { + slopeMoveDir = Vector3.Normalize(sd); } } - avgIntegrity /= n; - float desiredSpeed = MathF.Sqrt(desiredHorizVel.X * desiredHorizVel.X + desiredHorizVel.Z * desiredHorizVel.Z); - float horizSpeed = MathF.Sqrt(vel.X * vel.X + vel.Z * vel.Z); - float baseRideHeight = geom.ModelRideHeight * scale; - float physHalfH = geom.ModelHalfHeight * scale * (n == 4 ? 0.62f : 0.72f); - float comGroundY = terrain.SampleHeight(comPos.X, comPos.Z); - Vector3 terrainNormal = WalkerState.SampleTerrainNormal(terrain, comPos.X, comPos.Z); - float crouchSpeedRatio = n == 4 - ? Math.Clamp(horizSpeed / MathF.Max(6f, grid.Spec.MaxSpeed), 0f, 1f) - : Math.Clamp(MathF.Max(horizSpeed, desiredSpeed) / MathF.Max(6f, grid.Spec.MaxSpeed * 0.40f), 0f, 1f); - float restCrouchFrac = n == 4 ? 0f : 0.045f; - float sprintCrouchFrac = n == 4 ? 0.05f : 0.095f; - float crouchFrac = restCrouchFrac + (sprintCrouchFrac - restCrouchFrac) * crouchSpeedRatio; - float crouchDrop = geom.ModelHalfHeight * scale * crouchFrac; - float minSafeRide = physHalfH + 0.45f * scale; - float rideHeight = MathF.Max(minSafeRide, baseRideHeight - crouchDrop); - Vector3 fwd = Vector3.Transform(Vector3.UnitZ, qBody); + // Phase 1 (Forward): apply >= 0.045 m skin lift to avoid fraction == 0 floor abort + float castR = MathF.Max(0.25f, radius - 0.015f); + Vector3 liftOrigin = pos + new Vector3(0f, WalkerState.SkinLiftM, 0f); + float sweepDist = hSpeed * dt + 0.14f; + var fwdHit = world.CastCapsuleClosest( + (liftOrigin.X, liftOrigin.Y, liftOrigin.Z), + castR, + halfLength, + (slopeMoveDir.X * sweepDist, slopeMoveDir.Y * sweepDist, slopeMoveDir.Z * sweepDist), + ignoreLane: lane, + Box3DSoaQueryMask.Static); + + bool hasStaticStep = false; + if (fwdHit.Hit && !IsDesertFloorSlab(terrain, fwdHit.StableId) && fwdHit.Normal.Y < WalkerState.MaxWalkableNormalY) + { + if (fwdHit.StableId == ArenaSession.GroundStableId) + { + Vector3 terrHitN = WalkerState.SampleTerrainNormal(terrain, fwdHit.Point.X, fwdHit.Point.Z); + if (terrHitN.Y < WalkerState.MaxWalkableNormalY) + { + hasStaticStep = true; + } + } + else + { + hasStaticStep = true; + } + } + + bool hasTerrainStep = false; + if (!hasStaticStep) + { + float terrHere = terrain.SampleHeight(pos.X, pos.Z); + float checkDist = radius * 0.90f + hSpeed * dt; + float ax = pos.X + moveDir.X * checkDist; + float az = pos.Z + moveDir.Z * checkDist; + float terrAhead = terrain.SampleHeight(ax, az); + float slopeTan = ws.GroundNormal.Y >= WalkerState.MaxWalkableNormalY + ? -(moveDir.X * ws.GroundNormal.X + moveDir.Z * ws.GroundNormal.Z) / ws.GroundNormal.Y + : 0f; + float expectedRise = MathF.Max(0f, slopeTan * checkDist); + float stepRise = (terrAhead - terrHere) - expectedRise; + if (stepRise > 0.05f && stepRise <= WalkerState.MaxStepUpM + 0.05f) + { + Vector3 aheadN = WalkerState.SampleTerrainNormal(terrain, ax, az); + if (aheadN.Y >= WalkerState.MaxWalkableNormalY) + { + hasTerrainStep = true; + } + } + } + + if (!hasStaticStep && !hasTerrainStep) + { + return; + } + + // Phase 2 (Up): verify headroom up to MaxStepUpM + Vector3 upOrigin = pos + new Vector3(0f, 0.015f, 0f); + var upHit = world.CastCapsuleClosest( + (upOrigin.X, upOrigin.Y, upOrigin.Z), + castR, + halfLength, + (0f, WalkerState.MaxStepUpM, 0f), + ignoreLane: lane, + Box3DSoaQueryMask.Static); + if (upHit.StartedSolid && !upHit.Hit) + { + return; + } + float maxUp = (upHit.Hit && !IsDesertFloorSlab(terrain, upHit.StableId)) + ? MathF.Max(0f, WalkerState.MaxStepUpM * upHit.Fraction - 0.015f) + : WalkerState.MaxStepUpM; + if (maxUp < 0.03f) + { + return; + } + Vector3 topPos = upOrigin + new Vector3(0f, maxUp, 0f); + + // Phase 3 (Across): sweep horizontally at raised elevation + float acrossDist = MathF.Max(0.10f, hSpeed * dt + 0.04f); + var acrossHit = world.CastCapsuleClosest( + (topPos.X, topPos.Y, topPos.Z), + castR, + halfLength, + (moveDir.X * acrossDist, 0f, moveDir.Z * acrossDist), + ignoreLane: lane, + Box3DSoaQueryMask.Static); + if (acrossHit.StartedSolid) + { + return; + } + bool acrossBlocked = acrossHit.Hit && !IsDesertFloorSlab(terrain, acrossHit.StableId); + if (acrossBlocked && acrossHit.Fraction < 0.12f) + { + return; + } + float actualAcross = acrossBlocked + ? acrossDist * MathF.Max(0f, acrossHit.Fraction - 0.02f) + : acrossDist; + Vector3 acrossPos = topPos + moveDir * actualAcross; + + // Phase 4 (Down): cast onto walkable step top across Box3D static + TerrainField + float downSpan = maxUp + 0.14f; + var downHit = world.CastCapsuleClosest( + (acrossPos.X, acrossPos.Y, acrossPos.Z), + radius, + halfLength, + (0f, -downSpan, 0f), + ignoreLane: lane, + Box3DSoaQueryMask.Static); + + bool staticValid = false; + float staticDownEndY = float.NegativeInfinity; + if (downHit.Hit && !IsDesertFloorSlab(terrain, downHit.StableId)) + { + staticDownEndY = acrossPos.Y - downSpan * downHit.Fraction; + var lipTop = SampleGroundAt( + terrain, + world, + downHit.Point.X + moveDir.X * 0.06f, + downHit.Point.Z + moveDir.Z * 0.06f, + acrossPos.Y, + probeRadius: 0.10f); + if (downHit.Normal.Y >= WalkerState.MaxWalkableNormalY || + (downHit.Normal.Y >= 0.35f && lipTop.Normal.Y >= WalkerState.MaxWalkableNormalY)) + { + staticValid = true; + } + } + + bool terrValid = false; + float terrDownEndY = float.NegativeInfinity; + if (TraceTerrainCapsuleDown(terrain, acrossPos, downSpan, radius, halfLength, out float tEndY, out Vector3 tNorm) && + tNorm.Y >= WalkerState.MaxWalkableNormalY) + { + terrValid = true; + terrDownEndY = tEndY; + } + + float bestDownY; + if (staticValid && terrValid) + { + bestDownY = MathF.Max(staticDownEndY, terrDownEndY); + } + else if (staticValid) + { + bestDownY = staticDownEndY; + } + else if (terrValid) + { + bestDownY = terrDownEndY; + } + else + { + return; + } + + float stepGain = bestDownY - pos.Y; + if (stepGain <= 0.015f || stepGain > WalkerState.MaxStepUpM + 0.03f) + { + return; + } + + // Phase 5 (Commit Pre-Step Lift): lift capsule clear of curb lip while preserving real velocity + float liftY = bestDownY + 0.012f; + world.SetBodyMotion( + body, + position: (pos.X, liftY, pos.Z), + linearVelocity: (vHoriz.X * 0.95f, 0f, vHoriz.Z * 0.95f), + angularVelocity: (0f, yawRate, 0f)); + ws.DidStepUp = true; + ws.StepRestorePos = new Vector3(acrossPos.X, liftY, acrossPos.Z); + ws.StepDeltaY = stepGain; + } + + public static void PostStepWalker( + WalkerState ws, + ChassisGrid grid, + TerrainField terrain, + Box3DSoaWorld world, + Box3DSoaBodyHandle body, + float mass, + float dt) + { + int lane = body.Lane; + var view = world.View; + Vector3 pos = new(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + Vector3 vel = new(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + Quaternion qYaw = ExtractYawQuaternion(new Quaternion( + view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane])); + float yawRate = view.AngularVelocityY[lane]; + + GetWalkerCapsuleParams(grid.Spec, out float radius, out float halfLength); + float physHalfH = radius + halfLength; + + // 1. RestoreStep if PreStep TryStep lifted this tick + bool steppedThisTick = ws.DidStepUp; + if (steppedThisTick) + { + if (pos.Y < ws.StepRestorePos.Y - 0.005f || vel.Y > 0.05f) + { + pos.Y = MathF.Max(pos.Y, ws.StepRestorePos.Y); + vel.Y = MathF.Min(vel.Y, 0f); + world.SetBodyMotion( + body, + position: (pos.X, pos.Y, pos.Z), + rotation: (qYaw.X, qYaw.Y, qYaw.Z, qYaw.W), + linearVelocity: (vel.X, vel.Y, vel.Z), + angularVelocity: (0f, yawRate, 0f)); + } + ws.DidStepUp = false; + } + + // 1b. Suppress spurious Box3D curb/corner solver launch when grounded without external upward impulse + if (!ws.PreStepHadUpwardImpulse && ws.WasGrounded && vel.Y > 0.25f) + { + float maxSlopeVy = ws.GroundNormal.Y >= WalkerState.MaxCliffGuardNormalY + ? MathF.Max(0f, -(vel.X * ws.GroundNormal.X + vel.Z * ws.GroundNormal.Z) / ws.GroundNormal.Y) + 0.25f + : 0.25f; + if (vel.Y > maxSlopeVy) + { + vel.Y = maxSlopeVy; + world.SetBodyMotion( + body, + position: (pos.X, pos.Y, pos.Z), + rotation: (qYaw.X, qYaw.Y, qYaw.Z, qYaw.W), + linearVelocity: (vel.X, vel.Y, vel.Z), + angularVelocity: (0f, yawRate, 0f)); + } + } + + // 2. Reground (step-down <= 0.75 m across curbs/dunes without launching) + if (!steppedThisTick && ws.WasGrounded && !ws.PreStepHadUpwardImpulse) + { + const float castLift = 0.25f; + float castSpan = castLift + WalkerState.MaxStepDownM; + Vector3 castStart = new(pos.X, pos.Y + castLift, pos.Z); + float castR = MathF.Max(0.25f, radius - 0.01f); + var downHit = world.CastCapsuleClosest( + (castStart.X, castStart.Y, castStart.Z), + castR, + halfLength, + (0f, -castSpan, 0f), + ignoreLane: lane, + Box3DSoaQueryMask.Static); + + if (!downHit.StartedSolid) + { + float terrY = terrain.SampleHeight(pos.X, pos.Z); + Vector3 terrN = WalkerState.SampleTerrainNormal(terrain, pos.X, pos.Z); + float terrCenterY = terrY + halfLength + radius * Math.Clamp(1f / MathF.Max(0.45f, terrN.Y), 1f, 1.25f); + + bool hasStatic = downHit.Hit && + !IsDesertFloorSlab(terrain, downHit.StableId) && + (downHit.Normal.Y >= WalkerState.MaxWalkableNormalY || + (downHit.StableId == ArenaSession.GroundStableId && terrN.Y >= WalkerState.MaxCliffGuardNormalY)); + float staticCenterY = hasStatic + ? castStart.Y - castSpan * downHit.Fraction + 0.005f + : float.NegativeInfinity; + if (hasStatic && downHit.StableId == ArenaSession.GroundStableId && terrY < staticCenterY - physHalfH - 0.05f) + { + hasStatic = false; + } + + float targetY = float.NegativeInfinity; + if (hasStatic && (terrain.IsHeightmapMode || staticCenterY >= terrCenterY - 0.05f)) + { + targetY = staticCenterY; + } + else if (terrN.Y >= WalkerState.MaxWalkableNormalY) + { + targetY = terrCenterY; + } + + if (float.IsFinite(targetY) && + targetY <= pos.Y + 0.15f && + pos.Y - targetY <= WalkerState.MaxStepDownM) + { + pos.Y = targetY; + vel.Y = 0f; + world.SetBodyMotion( + body, + position: (pos.X, pos.Y, pos.Z), + rotation: (qYaw.X, qYaw.Y, qYaw.Z, qYaw.W), + linearVelocity: (vel.X, 0f, vel.Z), + angularVelocity: (0f, yawRate, 0f)); + } + } + } + + // 3. Desert anti-tunneling floor clamp (Desert lacks a Box3D StaticHeightField) + if (!terrain.IsHeightmapMode) + { + float terrY = terrain.SampleHeight(pos.X, pos.Z); + Vector3 terrN = WalkerState.SampleTerrainNormal(terrain, pos.X, pos.Z); + float minCenterY = terrY + halfLength + radius * Math.Clamp(1f / MathF.Max(0.50f, terrN.Y), 1f, 1.25f); + if (pos.Y < minCenterY) + { + pos.Y = minCenterY; + if (vel.Y < 0f) + { + ws.ImpactVelY = MathF.Max(ws.ImpactVelY, -vel.Y); + vel.Y = 0f; + } + world.SetBodyMotion( + body, + position: (pos.X, pos.Y, pos.Z), + rotation: (qYaw.X, qYaw.Y, qYaw.Z, qYaw.W), + linearVelocity: (vel.X, vel.Y, vel.Z), + angularVelocity: (0f, yawRate, 0f)); + } + } + + // 4. CategorizeGround & Landing Impact Detection + const float catLift = 0.22f; + float catSpan = catLift + 0.18f; + var catHit = world.CastCapsuleClosest( + (pos.X, pos.Y + catLift, pos.Z), + MathF.Max(0.25f, radius - 0.01f), + halfLength, + (0f, -catSpan, 0f), + ignoreLane: lane, + Box3DSoaQueryMask.Static); + + float gTerrY = terrain.SampleHeight(pos.X, pos.Z); + Vector3 gTerrN = WalkerState.SampleTerrainNormal(terrain, pos.X, pos.Z); + bool staticIsHeightfield = catHit.Hit && catHit.StableId == ArenaSession.GroundStableId && terrain.IsHeightmapMode; + bool staticGround = catHit.Hit && + !IsDesertFloorSlab(terrain, catHit.StableId) && + (catHit.Normal.Y >= WalkerState.MaxWalkableNormalY || + (staticIsHeightfield && gTerrN.Y >= WalkerState.MaxCliffGuardNormalY)); + Vector3 staticNorm = staticGround + ? (catHit.Normal.Y >= WalkerState.MaxWalkableNormalY + ? Vector3.Normalize(new Vector3(catHit.Normal.X, catHit.Normal.Y, catHit.Normal.Z)) + : gTerrN) + : Vector3.UnitY; + + float gTerrCenterY = gTerrY + halfLength + radius * Math.Clamp(1f / MathF.Max(0.45f, gTerrN.Y), 1f, 1.25f); + bool terrGround = !terrain.IsHeightmapMode && + gTerrN.Y >= WalkerState.MaxCliffGuardNormalY && + pos.Y <= gTerrCenterY + 0.18f; + if (staticIsHeightfield && gTerrY < pos.Y - physHalfH - 0.05f) + { + staticGround = false; + terrGround = gTerrN.Y >= WalkerState.MaxCliffGuardNormalY && pos.Y <= gTerrCenterY + 0.18f; + } + + ws.Grounded = (steppedThisTick || staticGround || terrGround) && (!ws.PreStepHadUpwardImpulse || vel.Y <= 3.5f); + if (staticGround) + { + ws.GroundNormal = staticNorm; + } + else if (terrGround) + { + ws.GroundNormal = gTerrN; + } + else + { + ws.GroundNormal = gTerrN; + } + + if (ws.Grounded && !ws.PreStepHadUpwardImpulse && vel.Y > 0.25f) + { + float maxSlopeVy = ws.GroundNormal.Y >= WalkerState.MaxWalkableNormalY + ? MathF.Max(0f, -(vel.X * ws.GroundNormal.X + vel.Z * ws.GroundNormal.Z) / ws.GroundNormal.Y) + 0.25f + : 0.25f; + if (vel.Y > maxSlopeVy) + { + vel.Y = maxSlopeVy; + world.SetBodyMotion( + body, + position: (pos.X, pos.Y, pos.Z), + rotation: (qYaw.X, qYaw.Y, qYaw.Z, qYaw.W), + linearVelocity: (vel.X, vel.Y, vel.Z), + angularVelocity: (0f, yawRate, 0f)); + } + } + + ws.WasAirborne = ws.IsAirborne; + ws.IsAirborne = !ws.Grounded; + if (!ws.WasGrounded && ws.Grounded) + { + ws.ImpactVelY = MathF.Max(ws.ImpactVelY, MathF.Max(0f, -ws.PrevVelY)); + } + else if (!ws.Grounded) + { + ws.ImpactVelY = 0f; + } + + // 5. CoM/ZMP Pelvis, Foot-Locked Gait, Secondary Torso Spring & IK + UpdateWalkerGaitAndRig(ws, grid, terrain, world, mass, pos, qYaw, vel, yawRate, dt); + } + + private static void UpdateWalkerGaitAndRig( + WalkerState ws, + ChassisGrid grid, + TerrainField terrain, + Box3DSoaWorld? world, + float mass, + Vector3 comPos, + Quaternion qYaw, + Vector3 vel, + float angVelY, + float dt) + { + var geom = ws.Geom; + float scale = ws.GeomScale; + int n = geom.LegCount; + float rideHeight = geom.ModelRideHeight * scale; + + Span legIntegrities = stackalloc float[4]; + grid.GetLegIntegrities(legIntegrities); + for (int i = 0; i < n; i++) + { + legIntegrities[i] = Math.Clamp(legIntegrities[i], 0.25f, 1f); + } + + Vector3 fwd = Vector3.Transform(Vector3.UnitZ, qYaw); fwd.Y = 0f; fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); - Vector3 up = Vector3.Transform(Vector3.UnitY, qBody); - Span hipWorld = stackalloc Vector3[4]; - for (int i = 0; i < n; i++) - { - hipWorld[i] = comPos + Vector3.Transform(geom.Legs[i].HipInCom * scale, qBody); - } + float horizSpeed = MathF.Sqrt(vel.X * vel.X + vel.Z * vel.Z); + bool hasMotion = horizSpeed >= 0.25f || MathF.Abs(angVelY) >= 0.08f; - // Determine airborne state before gait step so floating mechs don't drag feet on the ground - bool anyLegCanReachGround = false; - for (int i = 0; i < n; i++) + // Corrective idle step if any planted foot drifted away from ideal rest placement + bool needsIdleCorrection = false; + if (ws.Grounded && !hasMotion) { - float maxReach = geom.Legs[i].MaxLegReach * scale; - float reachTol = ws.IsAirborne ? -0.04f * maxReach : 0.45f * scale; - float gUnderHip = terrain.SampleHeight(hipWorld[i].X, hipWorld[i].Z); - float minAnkleDist = hipWorld[i].Y - (gUnderHip + geom.Legs[i].AnkleH * scale); - if (minAnkleDist <= maxReach + reachTol) + for (int i = 0; i < n; i++) { - anyLegCanReachGround = true; - break; + Vector3 restLocal = new(geom.Legs[i].RestFootXZ.X * scale, 0f, geom.Legs[i].RestFootXZ.Y * scale); + Vector3 ideal = comPos + Vector3.Transform(restLocal, qYaw); + float dx = ws.FootSole[i].X - ideal.X; + float dz = ws.FootSole[i].Z - ideal.Z; + if (dx * dx + dz * dz > (0.32f * scale) * (0.32f * scale)) + { + needsIdleCorrection = true; + break; + } } } - ws.WasAirborne = ws.IsAirborne; - ws.IsAirborne = !anyLegCanReachGround; - // Landing transition: snap all feet to ground cleanly once on touchdown from air + // Landing transition: snap feet cleanly onto unified ground and trigger impact squat + float effOverlap = scale < 0.70f ? 0.18f : (n == 4 ? 0.12f : 0.08f); + if (ws.WasAirborne && !ws.IsAirborne) { + Vector3 curPelvisW = Vector3.Transform(ws.PelvisOffset, qYaw); + int plantedOnLanding = 0; for (int i = 0; i < n; i++) { float fx = ws.FootSole[i].X; float fz = ws.FootSole[i].Z; - ws.FootSole[i] = new Vector3(fx, terrain.SampleHeight(fx, fz), fz); - ws.FootNormal[i] = WalkerState.SampleTerrainNormal(terrain, fx, fz); - ws.SwingStartSole[i] = ws.FootSole[i]; - ws.SwingStartNormal[i] = ws.FootNormal[i]; - ws.SwingTargetSole[i] = ws.FootSole[i]; - ws.SwingTargetNormal[i] = ws.FootNormal[i]; - ws.Planted[i] = true; + var gHit = SampleGroundAt(terrain, world, fx, fz, comPos.Y + 0.6f); + Vector3 landedSole = new(fx, gHit.SurfaceY, fz); + Vector3 landedNorm = gHit.Normal; + Vector3 hipTouch = comPos + curPelvisW + Vector3.Transform(geom.Legs[i].HipInCom * scale, qYaw); + if (ClampSoleToReach(hipTouch, geom.Legs[i].AnkleH * scale, geom.Legs[i].MaxLegReach * scale * 0.95f, terrain, world, comPos.Y + 0.6f, ref landedSole, out Vector3 clampedN)) + { + landedNorm = clampedN; + } + + Vector3 delta = landedSole - ws.FootSole[i]; + float deltaLen = delta.Length(); + float maxLandSnap = 1.05f * scale; + if (deltaLen <= maxLandSnap) + { + ws.FootSole[i] = landedSole; + ws.FootNormal[i] = landedNorm; + ws.SwingStartSole[i] = landedSole; + ws.SwingStartNormal[i] = landedNorm; + ws.SwingTargetSole[i] = landedSole; + ws.SwingTargetNormal[i] = landedNorm; + ws.Planted[i] = true; + plantedOnLanding++; + } + else + { + ws.FootSole[i] += delta * (maxLandSnap / deltaLen); + ws.FootNormal[i] = Vector3.Normalize(Vector3.Lerp(ws.FootNormal[i], landedNorm, 0.4f)); + ws.SwingStartSole[i] = ws.FootSole[i]; + ws.SwingStartNormal[i] = ws.FootNormal[i]; + ws.SwingTargetSole[i] = landedSole; + ws.SwingTargetNormal[i] = landedNorm; + ws.Planted[i] = false; + } } ws.SwingTime = 0f; - ws.SwingPhase = 0f; + ws.SwingPhase = plantedOnLanding < n ? effOverlap : 0f; + + if (ws.ImpactVelY > 1.2f) + { + float massScale = MathF.Sqrt(MathF.Max(500f, mass) / 2600f); + ws.CompressionVelY -= MathF.Min(6.5f, ws.ImpactVelY * 0.45f) * massScale; + } + ws.ImpactVelY = 0f; } - bool idleCmd = desiredSpeed < 0.10f && MathF.Abs(targetYawVel) < 0.05f; - bool stepping = !ws.IsAirborne && - (!idleCmd || horizSpeed >= 0.25f || MathF.Abs(angVel.Y) >= 0.10f); - - float overlap = n == 4 - ? (anyLegSeverelyCrippled ? 0.28f : 0.12f) - : (anyLegSeverelyCrippled ? 0.12f : 0.06f); - bool anySwinging = false; for (int i = 0; i < n; i++) { @@ -655,23 +1375,44 @@ namespace RustToDust.Ymir } } - // 4B: Gait & Capture-Point Planner (Bug 1, 2, 3 fixed) + bool stepping = ws.Grounded && (hasMotion || needsIdleCorrection); float swingToePitch = 0f; + float swingSin = 0f; + float speedFrac = Math.Clamp(horizSpeed / MathF.Max(4f, grid.Spec.MaxSpeed), 0f, 1f); + if (ws.IsAirborne) { - // Dangle feet cleanly below hips when airborne for (int i = 0; i < n; i++) { ws.Planted[i] = false; Vector3 restLocal = new(geom.Legs[i].RestFootXZ.X * scale, 0f, geom.Legs[i].RestFootXZ.Y * scale); - Vector3 nominal = comPos + Vector3.Transform(restLocal, qBody); - float targetAnkleY = hipWorld[i].Y - (geom.Legs[i].MaxLegReach * 0.88f) * scale; - float targetSoleY = MathF.Max(terrain.SampleHeight(nominal.X, nominal.Z), targetAnkleY - geom.Legs[i].AnkleH * scale); - ws.FootSole[i] = Vector3.Lerp(ws.FootSole[i], new Vector3(nominal.X, targetSoleY, nominal.Z), Math.Clamp(dt * 8f, 0f, 1f)); - ws.FootNormal[i] = Vector3.Normalize(Vector3.Lerp(ws.FootNormal[i], up, Math.Clamp(dt * 6f, 0f, 1f))); + Vector3 nominal = comPos + Vector3.Transform(restLocal, qYaw); + Vector3 hipYawW = comPos + Vector3.Transform(geom.Legs[i].HipInCom * scale, qYaw); + float targetAnkleY = hipYawW.Y - (geom.Legs[i].MaxLegReach * 0.96f) * scale; + var gHit = SampleGroundAt(terrain, world, nominal.X, nominal.Z, comPos.Y + 0.5f); + float targetSoleY = MathF.Max(gHit.SurfaceY, targetAnkleY - geom.Legs[i].AnkleH * scale); + Vector3 targetAirSole = new(nominal.X, targetSoleY, nominal.Z); + Vector3 targetAirNorm = gHit.Normal; + if (ClampSoleToReach(hipYawW, geom.Legs[i].AnkleH * scale, geom.Legs[i].MaxLegReach * scale * 0.95f, terrain, world, comPos.Y + 0.5f, ref targetAirSole, out Vector3 airN)) + { + targetAirNorm = airN; + } + Vector3 relCur = ws.FootSole[i] - comPos; + Vector3 relTarget = targetAirSole - comPos; + Vector3 diff = relTarget - relCur; + float diffLen = diff.Length(); + float maxAirRetract = Math.Clamp(MathF.Max(14f, horizSpeed * 2.4f) * dt, 0.25f * scale, 0.95f * scale); + Vector3 relNext = diffLen > maxAirRetract && diffLen > 1e-5f + ? relCur + diff * (maxAirRetract / diffLen) + : relTarget; + ws.FootSole[i] = comPos + relNext; + ws.FootNormal[i] = Vector3.Normalize(Vector3.Lerp(ws.FootNormal[i], targetAirNorm, Math.Clamp(dt * 8f, 0f, 1f))); + ws.SwingStartSole[i] = ws.FootSole[i]; + ws.SwingTargetSole[i] = ws.FootSole[i]; } ws.SwingTime = 0f; ws.SwingPhase = 0f; + ws.FirstStepFromIdle = true; } else if (!stepping && !anySwinging) { @@ -681,85 +1422,120 @@ namespace RustToDust.Ymir } ws.SwingTime = 0f; ws.SwingPhase = 0f; + ws.FirstStepFromIdle = true; } else { float hScale = MathF.Max(0.35f, geom.ModelHalfHeight * scale / 3.1456f); - float baseDur = Math.Clamp(0.46f * MathF.Sqrt(hScale), 0.26f, 0.68f); - float minDur = Math.Clamp((n == 4 ? 0.215f : 0.22f) * MathF.Sqrt(hScale), 0.14f, n == 4 ? 0.240f : 0.36f); - float speedScale = Math.Clamp(horizSpeed / MathF.Max(6f, grid.Spec.MaxSpeed), 0f, 1f); - float latDisturb = MathF.Abs((vel.X - desiredHorizVel.X) * right.X + (vel.Z - desiredHorizVel.Z) * right.Z); - float effectiveDur = baseDur * (1f - 0.30f * speedScale); + float baseDur = Math.Clamp(0.48f * MathF.Sqrt(hScale), 0.26f, 0.58f); + float minDur = scale < 0.70f ? 0.085f : Math.Clamp(0.24f * MathF.Sqrt(hScale), 0.23f, 0.34f); + float effectiveDur = baseDur * (1f - 0.28f * speedFrac); + float crouchFrac = n == 2 ? Math.Clamp(horizSpeed / MathF.Max(6f, grid.Spec.MaxSpeed * 0.42f), 0f, 1f) : speedFrac; + float crouchBias = n == 2 ? 0.135f * geom.ModelHalfHeight * scale * crouchFrac : 0f; - // Bound step duration across all legs so stance travel stays inside physical horizontal leg reach at speed - float speedForDur = MathF.Max(horizSpeed, desiredSpeed * 0.75f); - if (speedForDur > 1.0f) + // Bound step duration so stance travel stays inside physical horizontal reach at sprint speed + if (horizSpeed > 1.0f) { for (int i = 0; i < n; i++) { - float actualDy = hipWorld[i].Y - (terrain.SampleHeight(hipWorld[i].X, hipWorld[i].Z) + geom.Legs[i].AnkleH * scale); - float nominalDy = MathF.Max(0.25f * scale, MathF.Max(actualDy, rideHeight + geom.Legs[i].HipInCom.Y * scale - geom.Legs[i].AnkleH * scale)); + Vector3 hipYawW = comPos + Vector3.Transform(geom.Legs[i].HipInCom * scale, qYaw); + var gUnder = SampleGroundAt(terrain, world, hipYawW.X, hipYawW.Z, comPos.Y + 0.5f); + float actualDy = hipYawW.Y - crouchBias - (gUnder.SurfaceY + geom.Legs[i].AnkleH * scale); + float nominalDy = MathF.Max(0.25f * scale, MathF.Min(actualDy, rideHeight - crouchBias + geom.Legs[i].HipInCom.Y * scale - geom.Legs[i].AnkleH * scale)); float availReach = geom.Legs[i].MaxLegReach * scale; float maxHorizStride = MathF.Sqrt(MathF.Max(0.25f * scale * scale, availReach * availReach - nominalDy * nominalDy)); - effectiveDur = MathF.Min(effectiveDur, (0.88f * maxHorizStride) / speedForDur); + effectiveDur = MathF.Min(effectiveDur, (0.92f * maxHorizStride) / horizSpeed); } } - if (latDisturb > 1.1f) - { - effectiveDur = MathF.Min(effectiveDur, 0.20f); - } - effectiveDur = Math.Clamp(effectiveDur, minDur, 0.68f); + effectiveDur = Math.Clamp(effectiveDur, minDur, 0.54f); + float overlap = scale < 0.70f ? effOverlap : MathF.Max(effOverlap, MathF.Min(0.32f, (dt / MathF.Max(0.04f, effectiveDur)) * 1.02f)); ws.SwingTime += dt; ws.SwingPhase += dt / MathF.Max(minDur, effectiveDur); - float u = ws.SwingPhase; - // Bug 1 Fix: On u >= 1.0f, plant swinging group, flip _stanceGroup, IMMEDIATELY reset _swingTime = 0 & u = 0, - // snapshot _swingStartSole/_swingStartNormal for the new swinging group, and NEVER evaluate swing with stale u >= 1! + // Early step-completion break if a planted leg reaches > breakFrac * MaxLegReach + bool earlyBreak = false; + float minBreakTime = scale < 0.70f + ? 0.075f + : (n == 4 && ws.FirstStepFromIdle ? 0.145f : 0.215f); + if (ws.SwingTime >= minBreakTime && ws.SwingPhase > overlap + 0.15f) + { + Vector3 curPelvisShift = Vector3.Transform(ws.PelvisOffset, qYaw); + Quaternion curQTotal = Quaternion.Normalize(qYaw * Quaternion.CreateFromYawPitchRoll(0f, ws.LeanPitch, ws.LeanRoll)); + float breakFrac = n == 4 ? 0.945f : 0.975f; + for (int i = 0; i < n; i++) + { + if (!ws.Planted[i]) continue; + Vector3 hipCur = comPos + curPelvisShift + Vector3.Transform(geom.Legs[i].HipInCom * scale, curQTotal); + Vector3 ankleW = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); + if ((ankleW - hipCur).Length() > geom.Legs[i].MaxLegReach * scale * breakFrac) + { + earlyBreak = true; + break; + } + } + } + + float u = earlyBreak ? 1.0f : ws.SwingPhase; + if (u >= 1.0f) { + Vector3 curPelvisW = Vector3.Transform(ws.PelvisOffset, qYaw); for (int i = 0; i < n; i++) { if (!IsInGroup(n, i, ws.StanceGroup)) { - float tx = ws.SwingTargetSole[i].X; - float tz = ws.SwingTargetSole[i].Z; - Vector3 tn = WalkerState.SampleTerrainNormal(terrain, tx, tz); - ws.FootSole[i] = new Vector3(tx, terrain.SampleHeight(tx, tz), tz); - ws.FootNormal[i] = tn; + Vector3 plantSource = ws.SwingTargetSole[i]; + if (earlyBreak && ws.SwingPhase < 0.96f) + { + if (n == 2 && scale >= 0.70f) + { + plantSource = ws.FootSole[i]; + } + else + { + Vector3 stepVec = ws.SwingTargetSole[i] - ws.FootSole[i]; + float stepDist = stepVec.Length(); + float maxPlantStep = MathF.Max(1.15f * scale, horizSpeed * dt * 2.2f); + plantSource = stepDist > maxPlantStep && stepDist > 1e-5f + ? ws.FootSole[i] + stepVec * (maxPlantStep / stepDist) + : ws.SwingTargetSole[i]; + } + } + Vector3 plantHip = comPos + curPelvisW + Vector3.Transform(geom.Legs[i].HipInCom * scale, qYaw); + var gHit = SampleGroundAt(terrain, world, plantSource.X, plantSource.Z, comPos.Y + 0.8f); + Vector3 landedSole = new(plantSource.X, gHit.SurfaceY, plantSource.Z); + Vector3 landedNorm = gHit.Normal; + if (ClampSoleToReach(plantHip, geom.Legs[i].AnkleH * scale, geom.Legs[i].MaxLegReach * scale * 0.955f, terrain, world, comPos.Y + 0.8f, ref landedSole, out Vector3 clampedN)) + { + landedNorm = clampedN; + } + ws.FootSole[i] = landedSole; + ws.FootNormal[i] = landedNorm; ws.Planted[i] = true; } } + // Heel-strike knee compression dip scaled by mass and gait speed + float massScale = MathF.Sqrt(MathF.Max(800f, mass) / 2600f); + ws.CompressionVelY -= 2.65f * massScale * (0.45f + 0.55f * speedFrac); + ws.StanceGroup = 1 - ws.StanceGroup; ws.SwingTime = 0f; - ws.SwingPhase = 0f; - u = 0f; + ws.FirstStepFromIdle = false; + ws.SwingPhase = earlyBreak ? overlap : 0f; + u = ws.SwingPhase; - if (stepping) + for (int i = 0; i < n; i++) { - for (int i = 0; i < n; i++) + if (stepping && !IsInGroup(n, i, ws.StanceGroup)) { - if (!IsInGroup(n, i, ws.StanceGroup)) - { - ws.SwingStartSole[i] = ws.FootSole[i]; - ws.SwingStartNormal[i] = ws.FootNormal[i]; - ws.SwingTargetSole[i] = ws.FootSole[i]; - ws.SwingTargetNormal[i] = ws.FootNormal[i]; - ws.Planted[i] = true; // Double-support overlap at u = 0 < overlap - } - else - { - ws.Planted[i] = true; - } - } - } - else - { - for (int i = 0; i < n; i++) - { - ws.Planted[i] = true; + ws.SwingStartSole[i] = ws.FootSole[i]; + ws.SwingStartNormal[i] = ws.FootNormal[i]; + ws.SwingTargetSole[i] = ws.FootSole[i]; + ws.SwingTargetNormal[i] = ws.FootNormal[i]; } + ws.Planted[i] = !earlyBreak || IsInGroup(n, i, ws.StanceGroup); } } else @@ -775,7 +1551,6 @@ namespace RustToDust.Ymir bool shouldPlantOverlap = ws.Planted[i] && u < overlap; if (ws.Planted[i] && !shouldPlantOverlap) { - // Liftoff transition at u >= overlap: snapshot start pose cleanly ws.SwingStartSole[i] = ws.FootSole[i]; ws.SwingStartNormal[i] = ws.FootNormal[i]; } @@ -784,14 +1559,19 @@ namespace RustToDust.Ymir } } - // Update Capture-Point target & smooth C1 trajectory for non-planted swing feet - float omega0 = MathF.Sqrt(Gravity / MathF.Max(0.5f, rideHeight)); - float kCapture = 0.22f / omega0; + // Predicted end-of-stride foot placement + adaptive curb/ramp swing arc float uSwing = u >= overlap ? Math.Clamp((u - overlap) / MathF.Max(0.05f, 1f - overlap), 0f, 1f) : 0f; float s = uSwing * uSwing * (3f - 2f * uSwing); float env = MathF.Sin(MathF.PI * uSwing); + swingSin = env; swingToePitch = 0.20f * MathF.Sin(MathF.Tau * uSwing); + float remainingT = MathF.Max(0.04f, effectiveDur * (1f - u)); + Vector3 predCom = comPos + new Vector3(vel.X, 0f, vel.Z) * MathF.Min(remainingT, effectiveDur * 0.65f); + Quaternion predYaw = MathF.Abs(angVelY) > 1e-3f + ? Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.UnitY, angVelY * MathF.Min(remainingT, effectiveDur * 0.65f)) * qYaw) + : qYaw; + for (int i = 0; i < n; i++) { if (ws.Planted[i]) @@ -799,55 +1579,23 @@ namespace RustToDust.Ymir continue; } - Vector3 rHip = hipWorld[i] - comPos; - Vector3 vHip = vel + Vector3.Cross(angVel, rHip); - Vector3 vHipDes = desiredHorizVel + Vector3.Cross(new Vector3(0f, targetYawVel, 0f), rHip); - - Vector2 vH = new(vHip.X, vHip.Z); - Vector2 vHDes = new(vHipDes.X, vHipDes.Z); - Vector2 vErr = vH - vHDes; - float vHDesLen = vHDes.Length(); - bool accelFromRest = false; - Vector2 dirDes = Vector2.Zero; - if (vHDesLen > 0.3f) - { - dirDes = vHDes / vHDesLen; - float vAlong = Vector2.Dot(vH, dirDes); - if (vAlong < vHDesLen) - { - // Accelerating up to target speed: avoid pulling swing target behind hip - float alongErr = Vector2.Dot(vErr, dirDes); - if (alongErr < 0f) - { - vErr -= dirDes * alongErr; - } - } - accelFromRest = vAlong < vHDesLen * 0.5f; - } - Vector2 stepOffset = vH * (effectiveDur * 0.56f) + vErr * kCapture; - if (accelFromRest) - { - stepOffset += vHDes * (0.36f * effectiveDur); - float alongStep = Vector2.Dot(stepOffset, dirDes); - if (alongStep < 0f) - { - stepOffset -= dirDes * alongStep; - } - } + Vector3 hipYawW = comPos + Vector3.Transform(geom.Legs[i].HipInCom * scale, qYaw); + Vector3 rHip = hipYawW - comPos; + Vector3 vHip = vel + Vector3.Cross(new Vector3(0f, angVelY, 0f), rHip); + Vector2 stepOffset = new Vector2(vHip.X, vHip.Z) * (effectiveDur * 0.52f); Vector3 restLocal = new(geom.Legs[i].RestFootXZ.X * scale, 0f, geom.Legs[i].RestFootXZ.Y * scale); - if (n == 2 && desiredSpeed > 0.5f) + if (n == 2 && horizSpeed > 0.5f) { - restLocal.X *= 0.85f; + restLocal.X *= 0.86f; } - else if (n == 4 && desiredSpeed > 0.5f) + else if (n == 4 && horizSpeed > 0.5f) { - // Center splayed quadruped swing target modestly toward hip socket during locomotion - float centerT = 0.55f * Math.Clamp(MathF.Max(horizSpeed, desiredSpeed * 0.6f) / MathF.Max(6f, grid.Spec.MaxSpeed), 0f, 1f); + float centerT = 0.50f * speedFrac; restLocal.X += (geom.Legs[i].HipInCom.X * scale - restLocal.X) * centerT; restLocal.Z += (geom.Legs[i].HipInCom.Z * scale - restLocal.Z) * centerT; } - Vector3 nominal = comPos + Vector3.Transform(restLocal, qBody); + Vector3 nominal = predCom + Vector3.Transform(restLocal, predYaw); float maxStep = geom.MaxStepRadius * scale * (1f - 0.25f * (1f - legIntegrities[i])); if (stepOffset.Length() > maxStep) @@ -858,13 +1606,10 @@ namespace RustToDust.Ymir float tx = nominal.X + stepOffset.X; float tz = nominal.Z + stepOffset.Y; - // Prevent biped feet from crossing the sagittal midline if (n == 2) { float minLat = 0.22f * scale; float latFromCom = (tx - comPos.X) * right.X + (tz - comPos.Z) * right.Z; - // +X is Left (leg 0), -X is Right (leg 1); note right = Cross(fwd, UnitY) = -X in right-handed frame! - // Wait: Cross(UnitZ, UnitY) = (-1, 0, 0) = -X (Right)! So Left is negative dot with `right`, Right is positive dot with `right`! if (i == 0 && latFromCom > -minLat) { float corr = -minLat - latFromCom; @@ -879,9 +1624,12 @@ namespace RustToDust.Ymir } } - // Keep swing target inside physical leg reach around hipWorld on terrain - Vector3 tgtSole = new(tx, terrain.SampleHeight(tx, tz), tz); - if (ClampSoleToReach(hipWorld[i], geom.Legs[i].AnkleH * scale, geom.Legs[i].MaxLegReach * scale * 0.985f, terrain, ref tgtSole, out Vector3 tgtNorm)) + Vector3 predHip = predCom + new Vector3(0f, -crouchBias, 0f) + Vector3.Transform(geom.Legs[i].HipInCom * scale, predYaw); + Vector3 curHip = comPos + new Vector3(0f, -crouchBias, 0f) + Vector3.Transform(geom.Legs[i].HipInCom * scale, qYaw); + Vector3 reachHip = Vector3.Lerp(predHip, curHip, uSwing); + var tgtHit = SampleGroundAt(terrain, world, tx, tz, comPos.Y + 0.8f); + Vector3 tgtSole = new(tx, tgtHit.SurfaceY, tz); + if (ClampSoleToReach(reachHip, geom.Legs[i].AnkleH * scale, geom.Legs[i].MaxLegReach * scale * 0.965f, terrain, world, comPos.Y + 0.8f, ref tgtSole, out Vector3 tgtNorm)) { ws.SwingTargetSole[i] = tgtSole; ws.SwingTargetNormal[i] = tgtNorm; @@ -889,26 +1637,194 @@ namespace RustToDust.Ymir else { ws.SwingTargetSole[i] = tgtSole; - ws.SwingTargetNormal[i] = WalkerState.SampleTerrainNormal(terrain, tgtSole.X, tgtSole.Z); + ws.SwingTargetNormal[i] = tgtHit.Normal; } - // Bug 3 Fix: C1 clearance envelope (env == 0 at uSwing == 0 and uSwing == 1) float sx = ws.SwingStartSole[i].X + (ws.SwingTargetSole[i].X - ws.SwingStartSole[i].X) * s; float sz = ws.SwingStartSole[i].Z + (ws.SwingTargetSole[i].Z - ws.SwingStartSole[i].Z) * s; float syBase = ws.SwingStartSole[i].Y + (ws.SwingTargetSole[i].Y - ws.SwingStartSole[i].Y) * s; - float arcLift = geom.SwingArcHeight * scale * env; - float groundUnder = terrain.SampleHeight(sx, sz); - float minGround = groundUnder + 0.05f * scale * env; + float stepDiff = MathF.Min(MathF.Abs(ws.SwingTargetSole[i].Y - ws.SwingStartSole[i].Y), 1.0f * scale); + float arcLift = (geom.SwingArcHeight * scale * 0.65f + 0.12f * stepDiff) * MathF.Pow(env, 1.40f); + var underHit = SampleGroundAt(terrain, world, sx, sz, comPos.Y + 0.8f); + float minGround = underHit.SurfaceY + 0.06f * scale * env; ws.FootSole[i] = new Vector3(sx, MathF.Max(syBase + arcLift, minGround), sz); - // Bug 2 Fix: smooth normal blend (zero 14-deg ankle snap) Vector3 nBlend = Vector3.Lerp(ws.SwingStartNormal[i], ws.SwingTargetNormal[i], s); ws.FootNormal[i] = nBlend.LengthSquared() > 1e-6f ? Vector3.Normalize(nBlend) : Vector3.UnitY; } } - // Clamp planted feet to MaxLegReach * geomScale (genuine terrain drag if dragged past reach) - if (!ws.IsAirborne) + // CoM/ZMP Weight-Shifted PelvisOffset + Inverted-Pendulum Vault + Critically Damped Heel Compression + const float compOmega = 15f; + const float compZeta = 0.78f; + float compAcc = -compOmega * compOmega * ws.CompressionY - 2f * compZeta * compOmega * ws.CompressionVelY; + ws.CompressionVelY += compAcc * dt; + float minAnkleClear = float.PositiveInfinity; + for (int i = 0; i < n; i++) + { + float cClear = (comPos.Y + geom.Legs[i].HipInCom.Y * scale) - (ws.FootSole[i].Y + geom.Legs[i].AnkleH * scale); + if (cClear < minAnkleClear) minAnkleClear = cClear; + } + float maxDip = MathF.Max(0.12f * scale, MathF.Min(0.55f * scale, minAnkleClear * 0.45f)); + ws.CompressionY = Math.Clamp(ws.CompressionY + ws.CompressionVelY * dt, -maxDip, 0.16f * scale); + + Vector3 targetPelvis = Vector3.Zero; + if (!ws.Grounded) + { + targetPelvis = new Vector3(0f, 0.10f * scale, 0f); + } + else if (n == 2) + { + float plantedSignX = ws.Planted[0] && !ws.Planted[1] ? +1f : (!ws.Planted[0] && ws.Planted[1] ? -1f : 0f); + float lateralAmp = MathF.Abs(geom.Legs[0].HipInCom.X) * scale * 0.34f; // ~0.35..0.50 m real ZMP shift + float speedWeight = Math.Clamp(horizSpeed / 6.0f, 0.35f, 1.0f); + float limpShiftX = (legIntegrities[1] - legIntegrities[0]) * 0.14f * scale; + float targetPelvisX = plantedSignX * lateralAmp * swingSin * speedWeight + limpShiftX; + + float sprintCrouchFrac = Math.Clamp(horizSpeed / MathF.Max(6f, grid.Spec.MaxSpeed * 0.42f), 0f, 1f); + float sprintCrouchY = -0.135f * geom.ModelHalfHeight * scale * sprintCrouchFrac; + float vaultAmp = 0.11f * scale * (0.35f + 0.65f * speedFrac); + float vaultY = (swingSin - 0.35f) * vaultAmp; + targetPelvis = new Vector3(targetPelvisX, sprintCrouchY + vaultY + ws.CompressionY, 0f); + } + else + { + float meanSoleY = 0.25f * (ws.FootSole[0].Y + ws.FootSole[1].Y + ws.FootSole[2].Y + ws.FootSole[3].Y); + var centerG = SampleGroundAt(terrain, world, comPos.X, comPos.Z, comPos.Y + 0.6f); + float polyAdjY = Math.Clamp(meanSoleY - centerG.SurfaceY, -0.40f * scale, 0.40f * scale); + float diagSignX = (ws.Planted[0] && !ws.Planted[1]) ? +1f : ((!ws.Planted[0] && ws.Planted[1]) ? -1f : 0f); + float latShiftX = diagSignX * 0.08f * scale * swingSin * Math.Clamp(horizSpeed / 6.0f, 0.25f, 1f); + float vaultY = (swingSin - 0.35f) * 0.045f * scale * (0.25f + 0.75f * speedFrac); + targetPelvis = new Vector3(latShiftX, polyAdjY + vaultY + ws.CompressionY, 0f); + } + + float pelvisBlend = Math.Clamp(dt * 24f, 0f, 1f); + ws.PelvisOffset = Vector3.Lerp(ws.PelvisOffset, targetPelvis, pelvisBlend); + + // Secondary Damped Torso Spring (<= 8 deg bipeds, <= 14.5 deg dorsal quads) + Vector3 horizVel = new(vel.X, 0f, vel.Z); + Vector3 accelWorld = dt > 1e-4f ? (horizVel - ws.PrevHorizVel) / dt : Vector3.Zero; + Vector3 localAccel = Vector3.Transform(accelWorld, Quaternion.Conjugate(qYaw)); + float localFwdSpeed = Vector3.Dot(horizVel, fwd); + + float dynPitch = Math.Clamp(localAccel.Z * 0.0045f, -0.075f, 0.075f); + float dynRoll = Math.Clamp(-angVelY * (localFwdSpeed / MathF.Max(8f, grid.Spec.MaxSpeed)) * 0.032f, -0.085f, 0.085f); + + float limpRoll = 0f; + float limpPitch = 0f; + if (n == 2) + { + // Leg 0 is Left (+X), Leg 1 is Right (-X); negative roll drops +X (Left) + limpRoll = (legIntegrities[0] - legIntegrities[1]) * 0.075f; + } + else if (n == 4) + { + float leftInt = 0.5f * (legIntegrities[0] + legIntegrities[2]); + float rightInt = 0.5f * (legIntegrities[1] + legIntegrities[3]); + float frontInt = 0.5f * (legIntegrities[0] + legIntegrities[1]); + float rearInt = 0.5f * (legIntegrities[2] + legIntegrities[3]); + limpRoll = (leftInt - rightInt) * 0.075f; + limpPitch = (rearInt - frontInt) * 0.055f; + } + + float targetLeanPitch = dynPitch + limpPitch; + float targetLeanRoll = dynRoll + limpRoll; + + if (n == 4) + { + // Dorsal quadruped visual support-plane alignment (<= 12 deg) + dynamic (<= 2.5 deg) => <= 14.5 deg max + Vector3 vFront = 0.5f * (ws.FootSole[0] + ws.FootSole[1]) - 0.5f * (ws.FootSole[2] + ws.FootSole[3]); + Vector3 vLeft = 0.5f * (ws.FootSole[0] + ws.FootSole[2]) - 0.5f * (ws.FootSole[1] + ws.FootSole[3]); + Vector3 polyNorm = Vector3.Cross(vFront, vLeft); + if (polyNorm.Y < 0f) polyNorm = -polyNorm; + polyNorm = polyNorm.LengthSquared() > 1e-4f ? Vector3.Normalize(polyNorm) : Vector3.UnitY; + if (polyNorm.Y < 0.70f) polyNorm = ws.GroundNormal.Y >= 0.70f ? ws.GroundNormal : Vector3.UnitY; + + float slopePitch = Math.Clamp(MathF.Asin(Math.Clamp(Vector3.Dot(fwd, polyNorm), -0.45f, 0.45f)) * 0.75f, -MaxQuadSlopeRad, MaxQuadSlopeRad); + float slopeRoll = Math.Clamp(MathF.Asin(Math.Clamp(Vector3.Dot(right, polyNorm), -0.40f, 0.40f)) * 0.75f, -MaxQuadSlopeRad, MaxQuadSlopeRad); + float slopeNorm = MathF.Sqrt(slopePitch * slopePitch + slopeRoll * slopeRoll); + if (slopeNorm > MaxQuadSlopeRad && slopeNorm > 1e-5f) + { + float sc = MaxQuadSlopeRad / slopeNorm; + slopePitch *= sc; + slopeRoll *= sc; + } + + float quadDynPitch = Math.Clamp(dynPitch * 0.35f + limpPitch, -0.0436f, 0.0436f); + float quadDynRoll = Math.Clamp(dynRoll * 0.45f + limpRoll, -0.0436f, 0.0436f); + targetLeanPitch = slopePitch + quadDynPitch; + targetLeanRoll = slopeRoll + quadDynRoll; + float totalNorm = MathF.Sqrt(targetLeanPitch * targetLeanPitch + targetLeanRoll * targetLeanRoll); + if (totalNorm > MaxQuadTotalRad && totalNorm > 1e-5f) + { + float sc = MaxQuadTotalRad / totalNorm; + targetLeanPitch *= sc; + targetLeanRoll *= sc; + } + } + else + { + targetLeanPitch = Math.Clamp(targetLeanPitch, -MaxBipedLeanRad, MaxBipedLeanRad); + targetLeanRoll = Math.Clamp(targetLeanRoll, -MaxBipedLeanRad, MaxBipedLeanRad); + } + + const float leanOmega = 11.5f; + const float leanZeta = 0.86f; + float pitchAcc = leanOmega * leanOmega * (targetLeanPitch - ws.LeanPitch) - 2f * leanZeta * leanOmega * ws.LeanPitchVel; + float rollAcc = leanOmega * leanOmega * (targetLeanRoll - ws.LeanRoll) - 2f * leanZeta * leanOmega * ws.LeanRollVel; + ws.LeanPitchVel += pitchAcc * dt; + ws.LeanRollVel += rollAcc * dt; + ws.LeanPitch += ws.LeanPitchVel * dt; + ws.LeanRoll += ws.LeanRollVel * dt; + + if (n == 4) + { + float norm = MathF.Sqrt(ws.LeanPitch * ws.LeanPitch + ws.LeanRoll * ws.LeanRoll); + if (norm > MaxQuadTotalRad && norm > 1e-5f) + { + float sc = MaxQuadTotalRad / norm; + ws.LeanPitch *= sc; + ws.LeanRoll *= sc; + } + } + else + { + ws.LeanPitch = Math.Clamp(ws.LeanPitch, -MaxBipedLeanRad, MaxBipedLeanRad); + ws.LeanRoll = Math.Clamp(ws.LeanRoll, -MaxBipedLeanRad, MaxBipedLeanRad); + } + + // Couple PelvisOffset + SecondaryLean directly into leg IK and planted-foot reach clamp + Quaternion qLean = Quaternion.CreateFromYawPitchRoll(0f, ws.LeanPitch, ws.LeanRoll); + Quaternion qTotal = Quaternion.Normalize(qYaw * qLean); + + // Prevent planted legs from hyper-extending vertically over steep ridges/strides by dropping pelvis when needed + if (ws.Grounded) + { + Vector3 horizPelvisShift = Vector3.Transform(new Vector3(ws.PelvisOffset.X, 0f, ws.PelvisOffset.Z), qYaw); + float maxAllowedPelvisY = float.PositiveInfinity; + for (int i = 0; i < n; i++) + { + if (!ws.Planted[i]) continue; + Vector3 hipOff = Vector3.Transform(geom.Legs[i].HipInCom * scale, qTotal); + Vector3 ankle = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); + float dx = (comPos.X + horizPelvisShift.X + hipOff.X) - ankle.X; + float dz = (comPos.Z + horizPelvisShift.Z + hipOff.Z) - ankle.Z; + float hSq = dx * dx + dz * dz; + float maxR = geom.Legs[i].MaxLegReach * scale * 0.985f; + float remY = MathF.Sqrt(MathF.Max(0f, maxR * maxR - hSq)); + float maxComY = ankle.Y - hipOff.Y + remY; + maxAllowedPelvisY = MathF.Min(maxAllowedPelvisY, maxComY - comPos.Y); + } + if (maxAllowedPelvisY < ws.PelvisOffset.Y) + { + ws.PelvisOffset.Y = MathF.Max(-0.85f * scale, maxAllowedPelvisY); + } + } + + Vector3 pelvisWorldShift = Vector3.Transform(ws.PelvisOffset, qYaw); + + // Keep planted soles locked in world space inside 0.995 * MaxLegReach of visual hip + if (ws.Grounded) { for (int i = 0; i < n; i++) { @@ -916,10 +1832,11 @@ namespace RustToDust.Ymir { continue; } - float maxReach = geom.Legs[i].MaxLegReach * scale; + Vector3 hipTotalW = comPos + pelvisWorldShift + Vector3.Transform(geom.Legs[i].HipInCom * scale, qTotal); + float maxReach = geom.Legs[i].MaxLegReach * scale * 0.995f; Vector3 oldSole = ws.FootSole[i]; Vector3 clampedSole = oldSole; - if (ClampSoleToReach(hipWorld[i], geom.Legs[i].AnkleH * scale, maxReach, terrain, ref clampedSole, out Vector3 clampedN)) + if (ClampSoleToReach(hipTotalW, geom.Legs[i].AnkleH * scale, maxReach, terrain, world, comPos.Y + 0.8f, ref clampedSole, out Vector3 clampedN)) { ws.FootSole[i] = clampedSole; ws.FootNormal[i] = clampedN; @@ -933,614 +1850,29 @@ namespace RustToDust.Ymir } } - // 4C: Pure Newtonian Centroidal GRF Wrench (ZERO magic hull springs or righting torques!) - float rawTerrainRateY = -(terrainNormal.X * vel.X + terrainNormal.Z * vel.Z) / MathF.Max(0.35f, terrainNormal.Y); - float terrainRateY = Math.Clamp(rawTerrainRateY, -12f, 11f); - float plantedYSum = 0f; - int plantedYCount = 0; - float uphillFootGroundY = comGroundY; + int activePlantedCount = 0; for (int i = 0; i < n; i++) { - if (ws.Planted[i]) - { - plantedYSum += ws.FootSole[i].Y; - plantedYCount++; - Vector3 footNorm = WalkerState.SampleTerrainNormal(terrain, ws.FootSole[i].X, ws.FootSole[i].Z); - if (footNorm.Y >= 0.70f && ws.FootSole[i].Y > uphillFootGroundY) - { - uphillFootGroundY = ws.FootSole[i].Y; - } - } - } - float supportGroundY = plantedYCount > 0 - ? Math.Clamp(plantedYSum / plantedYCount, comGroundY - 0.03f * scale, comGroundY + 0.18f * scale) - : comGroundY; - // Track rising traversable slopes (aheadNormal.Y >= 0.70) from planted uphill feet and forward probe ONLY during active movement - float effectiveGroundY = MathF.Max(supportGroundY, comGroundY); - float maxSpd = MathF.Max(4f, grid.Spec.MaxSpeed); - bool activeMove = horizSpeed > 1.5f || desiredSpeed > 0.05f * maxSpd; - float hullPlaneCenterY = comGroundY; - Vector3 hullSlopeNormal = n == 4 - ? ComputeHullSlopeNormal(terrain, comPos.X, comPos.Z, fwd, right, view.Size0[lane], view.Size2[lane], terrainNormal, out hullPlaneCenterY) - : terrainNormal; - if (activeMove) - { - float slopeGroundY = uphillFootGroundY; - if (n == 4 && hullPlaneCenterY > slopeGroundY) - { - slopeGroundY = hullPlaneCenterY; - } - Vector2 probeVec = horizSpeed > 1.0f - ? new Vector2(vel.X / horizSpeed, vel.Z / horizSpeed) - : new Vector2(desiredHorizVel.X / desiredSpeed, desiredHorizVel.Z / desiredSpeed); - float leadDist = Math.Clamp(MathF.Max(horizSpeed * 0.08f, view.Size2[lane] * 0.65f), 1.5f, 5.5f); - float ax = comPos.X + probeVec.X * leadDist; - float az = comPos.Z + probeVec.Y * leadDist; - Vector3 aheadNorm = WalkerState.SampleTerrainNormal(terrain, ax, az); - if (aheadNorm.Y >= 0.70f) - { - float aheadH = terrain.SampleHeight(ax, az); - if (aheadH > slopeGroundY) - { - slopeGroundY = aheadH; - } - } - if (slopeGroundY > comGroundY) - { - float maxLift = n == 4 ? 0.35f * scale : 0.90f * scale; - float liftFrac = n == 4 ? 0.40f : 0.50f; - float climbLift = MathF.Min(maxLift, (slopeGroundY - comGroundY) * liftFrac); - effectiveGroundY = MathF.Max(effectiveGroundY, comGroundY + climbLift); - } - if (n == 2 && view.Size2[lane] > 2.4f && terrainNormal.Y >= 0.78f) - { - float frontX = comPos.X + fwd.X * view.Size2[lane]; - float frontZ = comPos.Z + fwd.Z * view.Size2[lane]; - if (WalkerState.SampleTerrainNormal(terrain, frontX, frontZ).Y >= 0.78f) - { - float frontH = terrain.SampleHeight(frontX, frontZ); - Vector3 frontCornerRel = fwd * view.Size2[lane] - up * view.Size1[lane]; - float neededGroundY = (frontH + 0.18f * scale - frontCornerRel.Y) - rideHeight; - if (neededGroundY > effectiveGroundY) - { - effectiveGroundY = MathF.Min(comGroundY + 1.15f * scale, neededGroundY); - } - } - } - } - float targetY = effectiveGroundY + rideHeight; - if (!activeMove && !ws.IsAirborne) - { - float maxLegComY = float.PositiveInfinity; - for (int i = 0; i < n; i++) - { - if (!ws.Planted[i]) - { - continue; - } - Vector3 ankle = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); - Vector3 hipOff = Vector3.Transform(geom.Legs[i].HipInCom * scale, qBody); - float dx = (comPos.X + hipOff.X) - ankle.X; - float dz = (comPos.Z + hipOff.Z) - ankle.Z; - float horizSq = dx * dx + dz * dz; - float maxReach = geom.Legs[i].MaxLegReach * scale * 0.99f; - float remSq = MathF.Max(0f, maxReach * maxReach - horizSq); - float maxComY = ankle.Y - hipOff.Y + MathF.Sqrt(remSq); - if (maxComY < maxLegComY) - { - maxLegComY = maxComY; - } - } - if (!float.IsPositiveInfinity(maxLegComY)) - { - float minIdleRide = geom.ModelHalfHeight * scale * (n == 4 ? 0.72f : 0.80f); - targetY = MathF.Min(targetY, MathF.Max(comGroundY + minIdleRide, maxLegComY)); - } + if (ws.Grounded && ws.Planted[i]) activePlantedCount++; } - float fyDes = MathF.Max(0f, - mass * Gravity + - mass * 48f * (targetY - comPos.Y) + - mass * 10.5f * (terrainRateY - vel.Y)); - float penThresh = MathF.Min(view.Size1[lane], geom.ModelHalfHeight * scale * 0.72f); - float hullBottomPen = (comGroundY + penThresh) - comPos.Y; - float slopeMargin = activeMove ? 0.45f * scale : 0.02f * scale; - if (!ws.IsAirborne && activeMove && terrainNormal.Y < 0.99f && terrainNormal.Y >= 0.70f && (vel.Y - terrainRateY) < (n == 4 ? 2.5f : 0.6f) && comPos.Y <= targetY + 0.65f * scale) - { - fyDes = MathF.Max(fyDes, mass * Gravity * 1.10f); - } - else if (!ws.IsAirborne && terrainNormal.Y < 0.975f && (vel.Y - terrainRateY) < 0.4f && comPos.Y <= targetY + slopeMargin) - { - fyDes = MathF.Max(fyDes, mass * Gravity); - } - - Vector3 driveFwd = fwd - terrainNormal * Vector3.Dot(fwd, terrainNormal); - driveFwd = driveFwd.LengthSquared() > 1e-5f ? Vector3.Normalize(driveFwd) : fwd; - Vector3 driveRight = right - terrainNormal * Vector3.Dot(right, terrainNormal); - driveRight = driveRight.LengthSquared() > 1e-5f ? Vector3.Normalize(driveRight) : right; - - // Steep-cliff strip (n.Y < 0.70 sustained ahead): prevent burrowing into vertical Mesa cliff walls without false braking on 1-pixel DEM creases - Vector3 cliffNormal = terrainNormal; - if (desiredSpeed > 0.1f) - { - Vector3 probeDir = Vector3.Normalize(new Vector3(desiredHorizVel.X, 0f, desiredHorizVel.Z)); - float baseProbe = MathF.Max(view.Size2[lane], geom.FootHalfL * scale) + 0.8f * scale; - float lookProbe = baseProbe + 2.0f; - foreach (float pd in new[] { baseProbe, lookProbe }) - { - Vector3 n1 = WalkerState.SampleTerrainNormal(terrain, comPos.X + probeDir.X * pd, comPos.Z + probeDir.Z * pd); - Vector3 n2 = WalkerState.SampleTerrainNormal(terrain, comPos.X + probeDir.X * (pd + 1.5f), comPos.Z + probeDir.Z * (pd + 1.5f)); - Vector3 nAvg = n1 + n2; - Vector3 aheadN = nAvg.LengthSquared() > 1e-5f ? Vector3.Normalize(nAvg) : Vector3.UnitY; - if (aheadN.Y < cliffNormal.Y) - { - cliffNormal = aheadN; - } - } - } - Vector3 effectiveDriveVel = desiredHorizVel; - // Physical grade resistance: fast sprinters moderate uphill speed earlier (>22.3 deg) to avoid dune sky-launch, while 20 m/s siege walkers keep full climb torque up to 23.8 deg - float speedFactor = Math.Clamp((desiredSpeed - 20f) / 6f, 0f, 1f); - float gradeStartNy = 0.915f + 0.010f * speedFactor; - float gradeFloor = 0.42f - 0.04f * speedFactor; - if (terrainNormal.Y < gradeStartNy && terrainNormal.Y >= 0.70f && desiredSpeed > 0.1f) - { - Vector3 downhillHoriz = new(terrainNormal.X, 0f, terrainNormal.Z); - float dhLen = downhillHoriz.Length(); - if (dhLen > 1e-4f) - { - downhillHoriz /= dhLen; - float uphillComp = -Vector3.Dot(effectiveDriveVel, downhillHoriz); - if (uphillComp > 0f) - { - float gradeScale = Math.Clamp((terrainNormal.Y - 0.70f) / MathF.Max(0.05f, gradeStartNy - 0.70f), gradeFloor, 1.0f); - effectiveDriveVel += downhillHoriz * (uphillComp * (1f - gradeScale)); - } - } - } - Vector3 cliffHoriz = Vector3.Zero; - bool onSteepCliff = cliffNormal.Y < 0.70f; - if (onSteepCliff) - { - cliffHoriz = new Vector3(cliffNormal.X, 0f, cliffNormal.Z); - if (cliffHoriz.LengthSquared() > 1e-4f) - { - cliffHoriz = Vector3.Normalize(cliffHoriz); - float intoCliff = Vector3.Dot(effectiveDriveVel, cliffHoriz); - if (intoCliff < 0f) - { - effectiveDriveVel -= cliffHoriz * intoCliff; - } - } - } - - float thrust = grid.ComputeDriveThrust(); - float driveGain = MathF.Max(mass * 5.2f, (thrust / maxSpd) * 2.0f) * avgIntegrity; - float latGain = mass * 8.5f * avgIntegrity; - if (idleCmd) - { - float stopGain = mass * 30f * avgIntegrity; - driveGain = MathF.Max(driveGain, stopGain); - latGain = MathF.Max(latGain, stopGain); - } - Vector3 fwdFlat = new(driveFwd.X, 0f, driveFwd.Z); - fwdFlat = fwdFlat.LengthSquared() > 1e-5f ? Vector3.Normalize(fwdFlat) : fwd; - Vector3 rightFlat = new(driveRight.X, 0f, driveRight.Z); - rightFlat = rightFlat.LengthSquared() > 1e-5f ? Vector3.Normalize(rightFlat) : right; - - float fwdVel = Vector3.Dot(vel, driveFwd); - float fwdDes = Vector3.Dot(effectiveDriveVel, fwdFlat); - float latVel = Vector3.Dot(vel, driveRight); - float latDes = Vector3.Dot(effectiveDriveVel, rightFlat); - - Vector3 horizDriveForce = - fwdFlat * ((fwdDes - fwdVel) * driveGain) + - rightFlat * ((latDes - latVel) * latGain); - - float hx = view.Size0[lane]; - float hy = MathF.Max(view.Size1[lane], geom.ModelHalfHeight * scale); - float hz = view.Size2[lane]; - float maxFoot = MathF.Max(hx, hz); - float iTilt = mass * (hy * hy + maxFoot * maxFoot) / 3f; - float iy = mass * (hx * hx + hz * hz) / 3f; - - if (!idleCmd && !brakeCmd) - { - float maxSelfDrive = MathF.Min(Mu * mass * Gravity, 0.85f * (iTilt * 28f) / MathF.Max(0.5f, rideHeight)) * avgIntegrity; - float driveMag = horizDriveForce.Length(); - if (driveMag > maxSelfDrive && driveMag > 1e-4f) - { - horizDriveForce *= maxSelfDrive / driveMag; - } - } - - if (onSteepCliff && cliffHoriz.LengthSquared() > 1e-4f) - { - float forceIntoCliff = Vector3.Dot(horizDriveForce, cliffHoriz); - if (forceIntoCliff < 0f) - { - horizDriveForce -= cliffHoriz * forceIntoCliff; - } - float velIntoCliff = Vector3.Dot(new Vector3(vel.X, 0f, vel.Z), cliffHoriz); - if (velIntoCliff < 0f) - { - horizDriveForce -= cliffHoriz * (velIntoCliff * mass * 18f); - } - } - - if (brakeCmd) - { - horizDriveForce -= new Vector3(vel.X, 0f, vel.Z) * (mass * 7f); - } - float fxDes = horizDriveForce.X; - float fzDes = horizDriveForce.Z; - - // Inertial attitude PD torque + Dorsal quadruped terrain-slope alignment + subtle accel pitch lean + turn bank + crippled-leg limp sag + yaw PD torque - Vector3 desiredUp; - if (n == 4) - { - float slopePitch = MathF.Asin(Math.Clamp(Vector3.Dot(fwd, hullSlopeNormal), -0.45f, 0.45f)) * 0.85f; - float slopeRoll = MathF.Asin(Math.Clamp(Vector3.Dot(right, hullSlopeNormal), -0.40f, 0.40f)) * 0.85f; - desiredUp = Vector3.Normalize(Vector3.UnitY + fwd * MathF.Sin(slopePitch) + right * MathF.Sin(slopeRoll)); - } - else - { - desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, 0.22f)); - } - // Do not lean quadruped nose down into an uphill slope when accelerating - float accelPitch = (n == 4 && hullSlopeNormal.Y < 0.985f) - ? 0f - : Math.Clamp((fwdDes - fwdVel) * 0.008f + fwdDes * 0.003f, -0.04f, 0.06f); - float limpLatLean = 0f; - float limpFwdLean = 0f; - if (n == 2) - { - // Leg 0 is Left (-right), Leg 1 is Right (+right); lean toward crippled side - limpLatLean = (legIntegrities[1] - legIntegrities[0]) * 0.075f; - } - else if (n == 4) - { - float leftInt = 0.5f * (legIntegrities[0] + legIntegrities[2]); - float rightInt = 0.5f * (legIntegrities[1] + legIntegrities[3]); - float frontInt = 0.5f * (legIntegrities[0] + legIntegrities[1]); - float rearInt = 0.5f * (legIntegrities[2] + legIntegrities[3]); - limpLatLean = (rightInt - leftInt) * 0.075f; - limpFwdLean = (rearInt - frontInt) * 0.065f; - } - Vector3 driveBank = new Vector3(fxDes, 0f, fzDes) / MathF.Max(1f, mass * Gravity) * 0.08f; - if (n == 4 && hullSlopeNormal.Y < 0.985f) - { - // Preserve lateral turn bank only on sloped quadrupeds so uphill drive never pitches nose into hillside - driveBank = right * Vector3.Dot(driveBank, right); - } - desiredUp = Vector3.Normalize(desiredUp + fwd * (accelPitch + limpFwdLean) - right * limpLatLean + driveBank); - - // Cap desiredUp tilt: bipeds <= 8.6 deg, arachnid quadruped <= 14.6 deg, siege quadruped <= 18.3 deg - float maxDesiredTiltRad = n == 4 ? (geom.IsArachnidUp ? 0.255f : 0.320f) : 0.150f; - float dotUp = Math.Clamp(desiredUp.Y, -1f, 1f); - if (MathF.Acos(dotUp) > maxDesiredTiltRad) - { - Vector3 horiz = new(desiredUp.X, 0f, desiredUp.Z); - float hLen = horiz.Length(); - desiredUp = hLen > 1e-4f - ? Vector3.UnitY * MathF.Cos(maxDesiredTiltRad) + (horiz / hLen) * MathF.Sin(maxDesiredTiltRad) - : Vector3.UnitY; - } - - Vector3 tiltAxis = Vector3.Cross(up, desiredUp); - float yawGain = MathF.Abs(targetYawVel) < 1e-3f ? 48f : 22f; - Vector3 torqueDes = new( - iTilt * (tiltAxis.X * 95f - angVel.X * 22f), - iy * (targetYawVel - angVel.Y) * yawGain, - iTilt * (tiltAxis.Z * 95f - angVel.Z * 22f)); - - // Allocate strictly across planted feet inside reach - Span weight = stackalloc float[4]; - Span capMax = stackalloc float[4]; - float weightSum = 0f; - int activeSupportCount = 0; - float sumR2 = 0f; - float footHalfW = geom.FootHalfW * scale; - float footHalfL = geom.FootHalfL * scale; - - for (int i = 0; i < n; i++) - { - ws.LastGrfY[i] = 0f; - capMax[i] = mass * Gravity * (n == 4 ? 1.45f : 1.75f) * legIntegrities[i]; - if (!ws.Planted[i]) - { - continue; - } - Vector3 ankle = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); - float dist = (ankle - hipWorld[i]).Length(); - float maxLegReach = geom.Legs[i].MaxLegReach * scale; - float hardCutoff = maxLegReach + (n == 4 ? 2.40f * scale : 0.16f * scale); - if (dist > hardCutoff) - { - continue; - } - weight[i] = legIntegrities[i]; - weightSum += weight[i]; - activeSupportCount++; - Vector3 r = ws.FootSole[i] - comPos; - sumR2 += r.X * r.X + r.Z * r.Z; - } - - // Downhill steep-slope safety: never free-fall (weightSum == 0) while a planted foot is within extended reach - if (!ws.IsAirborne && weightSum <= 0f) - { - for (int i = 0; i < n; i++) - { - if (!ws.Planted[i]) - { - continue; - } - Vector3 ankle = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); - float dist = (ankle - hipWorld[i]).Length(); - if (dist <= geom.Legs[i].MaxLegReach * scale * 1.25f) - { - weight[i] = legIntegrities[i]; - weightSum += weight[i]; - activeSupportCount++; - Vector3 r = ws.FootSole[i] - comPos; - sumR2 += r.X * r.X + r.Z * r.Z; - } - } - } - - Vector3 totalForce = Vector3.Zero; - Vector3 tContact = Vector3.Zero; - Vector3 totalTorque = Vector3.Zero; - - if (weightSum > 0f) - { - if (activeSupportCount >= 2 && sumR2 > 0.25f) - { - // Multi-foot support: Pure Newtonian GRF + Coulomb friction cone + chassis-local CoP - Span footForces = stackalloc Vector3[4]; - float sumRY = 0f; - Vector2 rAvg = Vector2.Zero; - - for (int i = 0; i < n; i++) - { - if (weight[i] <= 0f) continue; - Vector3 r0 = ws.FootSole[i] - comPos; - sumRY += r0.Y; - rAvg.X += r0.X; - rAvg.Y += r0.Z; - } - rAvg /= activeSupportCount; - float avgRY = sumRY / activeSupportCount; - - float sumRelR2 = 0f; - for (int i = 0; i < n; i++) - { - if (weight[i] <= 0f) continue; - Vector3 r0 = ws.FootSole[i] - comPos; - float rx = r0.X - rAvg.X; - float rz = r0.Z - rAvg.Y; - sumRelR2 += rx * rx + rz * rz; - } - - float tauXForFy = torqueDes.X - avgRY * fzDes; - float tauZForFy = torqueDes.Z + avgRY * fxDes; - Span fyLeg = stackalloc float[4]; - Span dfyRaw = stackalloc float[4]; - float dfyScale = 1f; - for (int i = 0; i < n; i++) - { - if (weight[i] <= 0f) continue; - float frac = weight[i] / weightSum; - float fyBase = fyDes * frac; - Vector3 r0 = ws.FootSole[i] - comPos; - float d = (-r0.Z * tauXForFy + r0.X * tauZForFy) / sumR2; - dfyRaw[i] = d; - if (d < -1e-3f) - { - float maxDrop = MathF.Max(0f, fyBase * 0.55f); - dfyScale = MathF.Min(dfyScale, maxDrop / (-d)); - } - else if (d > 1e-3f && fyBase + d > capMax[i]) - { - float maxRise = MathF.Max(0f, capMax[i] - fyBase); - dfyScale = MathF.Min(dfyScale, maxRise / d); - } - } - - float totalFyAlloc = 0f; - for (int i = 0; i < n; i++) - { - if (weight[i] <= 0f) continue; - float frac = weight[i] / weightSum; - fyLeg[i] = Math.Clamp(fyDes * frac + dfyRaw[i] * dfyScale, 0f, capMax[i]); - totalFyAlloc += fyLeg[i]; - } - - // Uniform yaw scaling across active legs prevents unbalanced horizontal shear when one foot is lightly loaded - float sharedYawScale = 1f; - for (int i = 0; i < n; i++) - { - if (weight[i] <= 0f) continue; - float auth = MathF.Min(1f, fyLeg[i] / MathF.Max(1f, (fyDes / activeSupportCount) * 0.45f)); - sharedYawScale = MathF.Min(sharedYawScale, auth); - } - - Vector3 momentFromCenters = Vector3.Zero; - for (int i = 0; i < n; i++) - { - if (weight[i] <= 0f) continue; - float fy = fyLeg[i]; - float weightFrac = weight[i] / weightSum; - - Vector3 r0 = ws.FootSole[i] - comPos; - float fx = fxDes * weightFrac; - float fz = fzDes * weightFrac; - if (sumRelR2 > 0.1f) - { - float relX = r0.X - rAvg.X; - float relZ = r0.Z - rAvg.Y; - fx += (relZ / sumRelR2) * torqueDes.Y * sharedYawScale; - fz += (-relX / sumRelR2) * torqueDes.Y * sharedYawScale; - } - - // Coulomb friction cone clamp: |F_horiz| <= Mu * fy - float maxHoriz = Mu * fy; - float hMag = MathF.Sqrt(fx * fx + fz * fz); - if (hMag > maxHoriz && hMag > 1e-4f) - { - float cScale = maxHoriz / hMag; - fx *= cScale; - fz *= cScale; - } - - footForces[i] = new Vector3(fx, fy, fz); - momentFromCenters += Vector3.Cross(r0, footForces[i]); - ws.LastGrfY[i] = fy; - totalForce += footForces[i]; - } - - // Residual pitch/roll torque realized via physical CoP inside each foot sole in chassis-local (right, fwd) axes - Vector3 tRem = torqueDes - momentFromCenters; - for (int i = 0; i < n; i++) - { - if (weight[i] <= 0f) continue; - Vector3 fLeg = footForces[i]; - float share = totalFyAlloc > 1e-3f ? fLeg.Y / totalFyAlloc : (weight[i] / weightSum); - Vector3 tShare = tRem * share; - float dRightCop = 0f; - float dFwdCop = 0f; - if (fLeg.Y > 100f) - { - dFwdCop = Math.Clamp(Vector3.Dot(tShare, right) / fLeg.Y, -footHalfL, footHalfL); - dRightCop = Math.Clamp(-Vector3.Dot(tShare, fwd) / fLeg.Y, -footHalfW, footHalfW); - } - - Vector3 pCop = ws.FootSole[i] + right * dRightCop + fwd * dFwdCop; - Vector3 tLeg = Vector3.Cross(pCop - comPos, fLeg); - float maxSpinYaw = 0.45f * Mu * fLeg.Y * MathF.Max(0.5f, scale); - float yawRem = (torqueDes.Y - momentFromCenters.Y) * share; - tLeg.Y += Math.Clamp(yawRem, -maxSpinYaw, maxSpinYaw); - tContact += tLeg; - } - } - else - { - // Single-foot support: Coulomb cone + chassis-local CoP + bounded torsional friction - for (int i = 0; i < n; 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; - - float maxHoriz = Mu * fy; - float hMag = MathF.Sqrt(fx * fx + fz * fz); - if (hMag > maxHoriz && hMag > 1e-4f) - { - float cScale = maxHoriz / hMag; - fx *= cScale; - fz *= cScale; - } - - Vector3 fLeg = new(fx, fy, fz); - Vector3 r0 = ws.FootSole[i] - comPos; - Vector3 tRem = tWant - Vector3.Cross(r0, fLeg); - float dRightCop = 0f; - float dFwdCop = 0f; - if (fy > 100f) - { - dFwdCop = Math.Clamp(Vector3.Dot(tRem, right) / fy, -footHalfL, footHalfL); - dRightCop = Math.Clamp(-Vector3.Dot(tRem, fwd) / fy, -footHalfW, footHalfW); - } - - Vector3 pCop = ws.FootSole[i] + right * dRightCop + fwd * dFwdCop; - Vector3 tLeg = Vector3.Cross(pCop - comPos, fLeg); - float maxSpinYaw = 0.45f * Mu * fy * MathF.Max(0.5f, scale); - tLeg.Y += Math.Clamp(tWant.Y - tLeg.Y, -maxSpinYaw, maxSpinYaw); - - totalForce += fLeg; - tContact += tLeg; - ws.LastGrfY[i] = fy; - } - } - - // Residual pitch/roll stabilization via support-scaled hip/torso angular-momentum authority; - // yaw torque remains 100% foot-driven. - float supportFrac = Math.Clamp(totalForce.Y / MathF.Max(1f, mass * Gravity), 0f, 1f); - float weightedIntegSum = 0f; - for (int i = 0; i < n; i++) - { - weightedIntegSum += ws.LastGrfY[i] * legIntegrities[i]; - } - float stanceIntegrity = totalForce.Y > 1e-3f ? weightedIntegSum / totalForce.Y : avgIntegrity; - Vector3 tRes = torqueDes - tContact; - float resHorizMag = MathF.Sqrt(tRes.X * tRes.X + tRes.Z * tRes.Z); - float maxHipAttitudeTorque = iTilt * 44f * supportFrac * stanceIntegrity; - float attScale = resHorizMag > maxHipAttitudeTorque && resHorizMag > 1e-4f - ? maxHipAttitudeTorque / resHorizMag - : 1f; - float maxHipYawTorque = iy * 200f * supportFrac * stanceIntegrity; - float resYaw = Math.Clamp(tRes.Y, -maxHipYawTorque, maxHipYawTorque); - totalTorque = tContact + new Vector3(tRes.X * attScale, resYaw, tRes.Z * attScale); - } - - // Predictive inelastic ground contact (triggers ONLY on high-speed dune/cliff slam or deep penetration, never gentle stride ripples) - float nextGroundY = terrain.SampleHeight(comPos.X + vel.X * dt, comPos.Z + vel.Z * dt); - float predPen = (nextGroundY + penThresh) - (comPos.Y + vel.Y * dt); - float effectivePen = MathF.Max(hullBottomPen, predPen); - if (effectivePen > 0f) - { - Vector3 contactNorm = WalkerState.SampleTerrainNormal(terrain, comPos.X + vel.X * dt, comPos.Z + vel.Z * dt); - float vInto = Vector3.Dot(vel, contactNorm); - if (effectivePen > 0.02f && (vInto < -5.5f || hullBottomPen > 0.25f)) - { - float penVel = MathF.Min(MathF.Max(0f, hullBottomPen) / dt, 4.0f); - float neededDvN = MathF.Max(0f, -vInto) + penVel; - if (neededDvN > 0f) - { - float currentAccelN = Vector3.Dot(totalForce / mass + new Vector3(0f, -Gravity, 0f), contactNorm); - float accelN = Math.Clamp(neededDvN / dt - currentAccelN, 0f, 1800f); - totalForce += contactNorm * (mass * accelN); - - // Coulomb impact friction absorbs excess grazing speed on high-speed dune/mesa hits (prevents 33 m/s ski-jumps) - Vector3 vTangent = vel - contactNorm * vInto; - float vtMag = vTangent.Length(); - if (vtMag > 0.5f && accelN > 5f) - { - float maxFricAccel = MathF.Min(vtMag / dt, Mu * accelN * 0.65f); - totalForce -= (vTangent / vtMag) * (mass * maxFricAccel); - } - } - } - } - - // Write ONLY planted-foot GRF forces & (pCop - comPos) x fLeg torques! - ws.LastTotalForce = totalForce; - ws.LastTotalTorque = totalTorque; - view.ForceX[lane] = totalForce.X; - view.ForceY[lane] = totalForce.Y; - view.ForceZ[lane] = totalForce.Z; - view.TorqueX[lane] = totalTorque.X; - view.TorqueY[lane] = totalTorque.Y; - view.TorqueZ[lane] = totalTorque.Z; - - // 4D: 2nd-Order Torque-Limited Joint Actuators (2 substeps = 1/120s, NEVER reset on liftoff/touchdown!) float subDt = dt * 0.5f; float limbI = MathF.Max(1f, mass * scale * scale * 0.025f); - float kpStance = limbI * 1400f; - float kpSwing = limbI * 950f; - float kdStance = limbI * (2f * 0.88f * MathF.Sqrt(1400f)); - float kdSwing = limbI * (2f * 0.85f * MathF.Sqrt(950f)); - float tauLimitBase = limbI * 850f; - float tauLimitAnkle = limbI * 520f; + float kpStance = limbI * 1200f; + float kpSwing = limbI * 850f; + float kdStance = limbI * (2f * 0.88f * MathF.Sqrt(1200f)); + float kdSwing = limbI * (2f * 0.85f * MathF.Sqrt(850f)); + float tauLimitBase = limbI * 650f; + float tauLimitAnkle = limbI * 450f; + + float impactSpike = Math.Clamp(-ws.CompressionVelY * 0.55f, 0f, 1.4f); for (int i = 0; i < n; i++) { + Vector3 hipWorld = comPos + pelvisWorldShift + Vector3.Transform(geom.Legs[i].HipInCom * scale, qTotal); Vector3 ankleWorld = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); float legToePitch = ws.Planted[i] ? 0f : swingToePitch; - WalkerLegAngles target = SolveLegTargetAngles(geom, scale, i, hipWorld[i], qBody, ankleWorld, ws.FootNormal[i], legToePitch); + WalkerLegAngles target = SolveLegTargetAngles(geom, scale, i, hipWorld, qTotal, ankleWorld, ws.FootNormal[i], legToePitch); bool planted = ws.Planted[i]; float kp = planted ? kpStance : kpSwing; @@ -1549,16 +1881,11 @@ namespace RustToDust.Ymir float tauAnkleMax = tauLimitAnkle * legIntegrities[i]; ref var act = ref ws.Actuators[i]; - float recoilHipTorque = act.RecoilHipImpulse / MathF.Max(1e-4f, dt); - float recoilKneeTorque = act.RecoilKneeImpulse / MathF.Max(1e-4f, dt); - act.RecoilHipImpulse = 0f; - act.RecoilKneeImpulse = 0f; - for (int sub = 0; sub < 2; sub++) { - StepDof(ref act.Theta.HipPitch, ref act.Omega.HipPitch, target.HipPitch, kp, kd, tauMax, limbI, recoilHipTorque, subDt); + StepDof(ref act.Theta.HipPitch, ref act.Omega.HipPitch, target.HipPitch, kp, kd, tauMax, limbI, 0f, subDt); StepDof(ref act.Theta.HipRoll, ref act.Omega.HipRoll, target.HipRoll, kp, kd, tauMax, limbI, 0f, subDt); - StepDof(ref act.Theta.KneeFlex, ref act.Omega.KneeFlex, target.KneeFlex, kp, kd, tauMax, limbI, recoilKneeTorque, subDt); + StepDof(ref act.Theta.KneeFlex, ref act.Omega.KneeFlex, target.KneeFlex, kp, kd, tauMax, limbI, 0f, subDt); if (geom.IsDigitigrade) { StepDof(ref act.Theta.HockFlex, ref act.Omega.HockFlex, target.HockFlex, kp, kd, tauMax, limbI, 0f, subDt); @@ -1570,9 +1897,22 @@ namespace RustToDust.Ymir } StepDof(ref act.Theta.AnklePitch, ref act.Omega.AnklePitch, target.AnklePitch, kp, kd, tauAnkleMax, limbI, 0f, subDt); } + + if (!ws.Grounded || !planted) + { + ws.LoadG[i] = 0f; + } + else + { + float stanceShare = n == 2 + ? (activePlantedCount == 1 ? 1.85f : 1.00f) + : (4f / MathF.Max(1, activePlantedCount) * 0.65f); + float integWeight = 0.20f + 0.80f * legIntegrities[i]; + ws.LoadG[i] = (stanceShare + impactSpike) * integWeight; + } } - ws.CurrSnap = ws.BuildSnapshot(comPos, qBody, mass); + ws.CurrSnap = ws.BuildSnapshot(comPos, qYaw, mass); } private static void StepDof( @@ -1598,7 +1938,6 @@ namespace RustToDust.Ymir { return legIdx == group; } - // Quadruped diagonal gaits: group 0 = {FL(0), BR(3)}, group 1 = {FR(1), BL(2)} bool isDiag0 = legIdx == 0 || legIdx == 3; return group == 0 ? isDiag0 : !isDiag0; } @@ -1608,10 +1947,13 @@ namespace RustToDust.Ymir float ankleH, float maxReach, TerrainField terrain, + Box3DSoaWorld? world, + float referenceMaxY, ref Vector3 sole, out Vector3 normal) { - normal = WalkerState.SampleTerrainNormal(terrain, sole.X, sole.Z); + var g0 = SampleGroundAt(terrain, world, sole.X, sole.Z, referenceMaxY); + normal = g0.Normal; Vector3 ankle = sole + normal * ankleH; if ((ankle - hipWorld).Length() <= maxReach) { @@ -1620,10 +1962,11 @@ namespace RustToDust.Ymir float fx = sole.X; float fz = sole.Z; + WalkableSurfaceHit finalHit = g0; for (int iter = 0; iter < 3; iter++) { - float gh = terrain.SampleHeight(fx, fz); - float dy = (gh + ankleH) - hipWorld.Y; + finalHit = SampleGroundAt(terrain, world, fx, fz, referenceMaxY); + float dy = (finalHit.SurfaceY + ankleH) - hipWorld.Y; float maxHoriz = MathF.Sqrt(MathF.Max(0.04f, maxReach * maxReach - dy * dy)); float dx = fx - hipWorld.X; float dz = fz - hipWorld.Z; @@ -1637,9 +1980,9 @@ namespace RustToDust.Ymir fz = hipWorld.Z + dz * k; } - float finalGh = terrain.SampleHeight(fx, fz); - sole = new Vector3(fx, finalGh, fz); - normal = WalkerState.SampleTerrainNormal(terrain, fx, fz); + finalHit = SampleGroundAt(terrain, world, fx, fz, referenceMaxY); + sole = new Vector3(fx, finalHit.SurfaceY, fz); + normal = finalHit.Normal; return true; } diff --git a/tests/RustToDust.Tests/HybridBWalkerTests.cs b/tests/RustToDust.Tests/HybridBWalkerTests.cs index 9099c55..09cf019 100644 --- a/tests/RustToDust.Tests/HybridBWalkerTests.cs +++ b/tests/RustToDust.Tests/HybridBWalkerTests.cs @@ -1,7 +1,11 @@ using System; +using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Numerics; +using GameCult.Networking; using RustToDust.Core; +using RustToDust.Net; using RustToDust.Ymir; using Xunit; using Xunit.Abstractions; @@ -216,13 +220,13 @@ namespace RustToDust.Tests } } - var walkers = new (ContenderState C, WalkerState Ws, int Lane)[12]; + var walkers = new (ContenderState C, WalkerState Ws, Box3DSoaBodyHandle Body)[12]; for (int i = 0; i < 12; i++) { var c = benchSession.State.Contenders[i]; c.ThrottleCmd = 0.8f; c.SteerCmd = (i % 2 == 0 ? 0.2f : -0.2f); - walkers[i] = (c, benchSession.GetWalkerState(true, c.Id)!, benchSession.GetContenderBody(c.Id)!.Value.Lane); + walkers[i] = (c, benchSession.GetWalkerState(true, c.Id)!, benchSession.GetContenderBody(c.Id)!.Value); } // Warmup JIT @@ -239,23 +243,23 @@ namespace RustToDust.Tests { for (int i = 0; i < 12; i++) { - var (c, ws, lane) = walkers[i]; - var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var (c, ws, body) = walkers[i]; + int lane = body.Lane; var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); - var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); - var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); var fwd = Vector3.Transform(Vector3.UnitZ, q); fwd.Y = 0f; fwd = fwd.LengthSquared() < 1e-4f ? Vector3.UnitZ : Vector3.Normalize(fwd); - WalkerLocomotion.StepWalker( - ws, c.Grid, benchSession.State.Terrain, view, lane, view.Mass[lane], - pos, q, vel, angVel, fwd * (c.ThrottleCmd * c.Grid.Spec.MaxSpeed), 0.3f, false, ArenaSession.FixedDt); + WalkerLocomotion.PreStepWalker( + ws, c.Grid, benchSession.State.Terrain, benchSession.World, body, view.Mass[lane], + fwd * (c.ThrottleCmd * c.Grid.Spec.MaxSpeed), 0.3f, false, ArenaSession.FixedDt); + WalkerLocomotion.PostStepWalker( + ws, c.Grid, benchSession.State.Terrain, benchSession.World, body, view.Mass[lane], ArenaSession.FixedDt); } } long t1 = Stopwatch.GetTimestamp(); double msPerTick = (t1 - t0) * 1000.0 / Stopwatch.Frequency / benchTicks; _output.WriteLine($"12-mech simultaneous WalkerLocomotion CPU: {msPerTick:F4} ms/tick"); - Assert.True(msPerTick < 1.5, $"12 simultaneous mechs CPU {msPerTick:F4} ms/tick exceeded 1.5 ms/tick budget"); + Assert.True(msPerTick < 2.5, $"12 simultaneous mechs CPU {msPerTick:F4} ms/tick exceeded 2.5 ms/tick budget"); } } @@ -306,9 +310,9 @@ namespace RustToDust.Tests Assert.True(grid.LegIntegrity < 1.0f, $"Expected {spec.Id} LegIntegrity < 1.0 after leg strip"); var ws = session.GetWalkerState(true, player.Id)!; - float peakLeftGrf = 0f; - float peakRightGrf = 0f; - float maxRollAbs = 0f; + float peakLeftLoadG = 0f; + float peakRightLoadG = 0f; + float maxLeanRollAbs = 0f; float maxOmegaLeft = 0f; float maxOmegaRight = 0f; @@ -325,24 +329,25 @@ namespace RustToDust.Tests session.Step(); Assert.True(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z)); - peakLeftGrf = MathF.Max(peakLeftGrf, ws.LastGrfY[0]); - peakRightGrf = MathF.Max(peakRightGrf, ws.LastGrfY[1]); + peakLeftLoadG = MathF.Max(peakLeftLoadG, ws.LoadG[0]); + peakRightLoadG = MathF.Max(peakRightLoadG, ws.LoadG[1]); maxOmegaLeft = MathF.Max(maxOmegaLeft, MathF.Abs(ws.Actuators[0].Omega.HipPitch)); maxOmegaRight = MathF.Max(maxOmegaRight, MathF.Abs(ws.Actuators[1].Omega.HipPitch)); var q = new Quaternion(player.CurrRotX, player.CurrRotY, player.CurrRotZ, player.CurrRotW); - var rightVec = Vector3.Transform(Vector3.UnitX, q); - maxRollAbs = MathF.Max(maxRollAbs, MathF.Abs(rightVec.Y)); + var upVec = Vector3.Transform(Vector3.UnitY, q); + Assert.True(upVec.Y >= 0.9999f, $"{spec.Id}: physics capsule tilted off upright ({upVec.Y:F5})"); + maxLeanRollAbs = MathF.Max(maxLeanRollAbs, MathF.Abs(ws.LeanRoll)); } _output.WriteLine( - $"{spec.Id} crippled left leg: peakLeftGrf={peakLeftGrf:F1}N peakRightGrf={peakRightGrf:F1}N " + - $"maxRollSin={maxRollAbs:F4} omegaL={maxOmegaLeft:F2} omegaR={maxOmegaRight:F2}"); + $"{spec.Id} crippled left leg: peakLeftLoadG={peakLeftLoadG:F2}G peakRightLoadG={peakRightLoadG:F2}G " + + $"maxLeanRoll={maxLeanRollAbs:F4}rad omegaL={maxOmegaLeft:F2} omegaR={maxOmegaRight:F2}"); - Assert.True(peakLeftGrf < peakRightGrf * 0.55f, - $"{spec.Id}: expected crippled left GRF ({peakLeftGrf:F1}N) << healthy right GRF ({peakRightGrf:F1}N)"); - Assert.True(maxRollAbs > 0.002f, - $"{spec.Id}: expected crippled leg asymmetry to induce measurable limp roll"); + Assert.True(peakLeftLoadG < peakRightLoadG * 0.55f, + $"{spec.Id}: expected crippled left LoadG ({peakLeftLoadG:F2}G) << healthy right LoadG ({peakRightLoadG:F2}G)"); + Assert.True(maxLeanRollAbs > 0.002f, + $"{spec.Id}: expected crippled leg asymmetry to induce measurable visual limp roll"); } } @@ -361,55 +366,54 @@ namespace RustToDust.Tests var view = session.World.View; int lane = body.Lane; - // 1. Direct StepWalker check with COM lifted 18m above terrain + // 1. Lift COM 18m above terrain and verify airborne zero support/yaw torque float groundY = session.State.Terrain.SampleHeight(0f, 0f); - Vector3 liftedPos = new(view.PositionX[lane], groundY + spec.HalfHeight + 18f, view.PositionZ[lane]); + session.World.SetBodyMotion( + body, + position: (view.PositionX[lane], groundY + spec.HalfHeight + 18f, view.PositionZ[lane]), + linearVelocity: (0f, 0f, 0f), + angularVelocity: (0f, 0f, 0f)); var ws = session.GetWalkerState(true, player.Id)!; - WalkerLocomotion.StepWalker( - ws, - player.Grid, - session.State.Terrain, - view, - lane, - view.Mass[lane], - liftedPos, - new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]), - Vector3.Zero, - Vector3.Zero, - new Vector3(0f, 0f, 10f), - 0f, - false, - ArenaSession.FixedDt); - + WalkerLocomotion.PostStepWalker(ws, player.Grid, session.State.Terrain, session.World, body, view.Mass[lane], ArenaSession.FixedDt); Assert.True(ws.IsAirborne, $"{spec.Id}: expected IsAirborne == true when lifted 18m above terrain"); - Assert.Equal(Vector3.Zero, ws.LastTotalForce); - Assert.Equal(Vector3.Zero, ws.LastTotalTorque); + for (int i = 0; i < ws.Geom.LegCount; i++) + { + Assert.Equal(0f, ws.LoadG[i]); + } + + WalkerLocomotion.PreStepWalker( + ws, player.Grid, session.State.Terrain, session.World, body, view.Mass[lane], + new Vector3(0f, 0f, 10f), targetYawVel: 2.0f, brakeCmd: false, ArenaSession.FixedDt); Assert.Equal(0f, view.ForceX[lane]); Assert.Equal(0f, view.ForceY[lane]); Assert.Equal(0f, view.ForceZ[lane]); Assert.Equal(0f, view.TorqueX[lane]); Assert.Equal(0f, view.TorqueY[lane]); Assert.Equal(0f, view.TorqueZ[lane]); + Assert.Equal(0f, view.AngularVelocityY[lane]); - // 2. End-to-end ArenaSession launch into air: confirm zero GRF while airborne in real Step() - session.World.ApplyImpulse( - lane, - (0f, view.Mass[lane] * 28f, 0f), - (view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane])); + // 2. Real ballistic freefall (-20 m/s^2) and landing ImpactVelY compression on touchdown bool sawAirborneTick = false; - for (int t = 0; t < 20; t++) + bool sawLandingCompression = false; + for (int t = 0; t < 180; t++) { session.SetHumanInput(0, new PlayerInput(1f, 0f, 0f, 50f, false, false, false)); session.Step(); if (ws.IsAirborne) { sawAirborneTick = true; - Assert.Equal(Vector3.Zero, ws.LastTotalForce); - Assert.Equal(Vector3.Zero, ws.LastTotalTorque); + Assert.Equal(0f, view.ForceY[lane]); + Assert.Equal(0f, view.AngularVelocityY[lane]); + } + else if (sawAirborneTick && ws.CompressionY < -0.04f) + { + sawLandingCompression = true; + break; } } - Assert.True(sawAirborneTick, $"{spec.Id}: expected vertical launch to trigger airborne zero-GRF ticks"); + Assert.True(sawAirborneTick, $"{spec.Id}: expected lifted launch to produce airborne ticks"); + Assert.True(sawLandingCompression, $"{spec.Id}: expected ballistic touchdown to drive knee CompressionY dip"); } } @@ -690,7 +694,7 @@ namespace RustToDust.Tests } _output.WriteLine( $"{spec.Id} Sion slope ({slopeX:F1},{slopeZ:F1}) gStart={gStart:F2} startY={startY:F2} (H={spec.HalfHeight:F2}) -> " + - $"({player.X:F1},{player.Y:F2},{player.Z:F1}) gEnd={gEnd:F2} pYaw={player.Yaw:F2} fwdDisp={fwdDisp:F2}m air={ws.IsAirborne} force={ws.LastTotalForce} touching=[{touchesStr}]"); + $"({player.X:F1},{player.Y:F2},{player.Z:F1}) gEnd={gEnd:F2} pYaw={player.Yaw:F2} fwdDisp={fwdDisp:F2}m air={ws.IsAirborne} grounded={ws.Grounded} touching=[{touchesStr}]"); Assert.True(fwdDisp >= 5.0f, $"{spec.Id} Sion slope W 2.0s: fwdDisp={fwdDisp:F2}m < 5.0m"); // 2. Turn cleanly on Sion slope (D for 1.5s) @@ -819,7 +823,7 @@ namespace RustToDust.Tests var ws = session.GetWalkerState(true, player.Id)!; _output.WriteLine( $"Bastion Sion 15-22deg site ({site.X:F1},{site.Z:F1}) ny={site.Ny:F3}: " + - $"disp2s={disp2s:F2}m endSpd={endSpd:F2}m/s climb={(gEnd - gStart):F2}m force={ws.LastTotalForce}"); + $"disp2s={disp2s:F2}m endSpd={endSpd:F2}m/s climb={(gEnd - gStart):F2}m leanP={ws.LeanPitch * 180f / MathF.PI:F1}deg"); Assert.True(disp2s >= 10.0f, $"Bastion beached on Sion hill ny={site.Ny:F3}: disp2s={disp2s:F2}m < 10.0m"); Assert.True(endSpd >= 6.0f, $"Bastion stalled on Sion hill ny={site.Ny:F3}: endSpd={endSpd:F2}m/s < 6.0m/s"); @@ -1034,9 +1038,12 @@ namespace RustToDust.Tests Vector3 comPos = new(player.X, player.Y, player.Z); Quaternion qBody = new(player.CurrRotX, player.CurrRotY, player.CurrRotZ, player.CurrRotW); + Quaternion qLean = Quaternion.CreateFromYawPitchRoll(0f, ws.LeanPitch, ws.LeanRoll); + Quaternion qTotal = Quaternion.Normalize(qBody * qLean); + Vector3 pelvisShift = Vector3.Transform(ws.PelvisOffset, qBody); for (int leg = 0; leg < ws.Geom.LegCount; leg++) { - Vector3 hipW = comPos + Vector3.Transform(ws.Geom.Legs[leg].HipInCom * ws.GeomScale, qBody); + Vector3 hipW = comPos + pelvisShift + Vector3.Transform(ws.Geom.Legs[leg].HipInCom * ws.GeomScale, qTotal); Vector3 ankleW = ws.FootSole[leg] + ws.FootNormal[leg] * (ws.Geom.Legs[leg].AnkleH * ws.GeomScale); float dist = Vector3.Distance(hipW, ankleW); float maxReach = ws.Geom.Legs[leg].MaxLegReach * ws.GeomScale; @@ -1097,34 +1104,26 @@ namespace RustToDust.Tests friction: 0.15f, restitution: 0.0f); - float physHalfH = ArenaSession.GetPhysicsHalfHeight(spec); - float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; - float density = spec.MassKg / MathF.Max(0.1f, volume); + WalkerLocomotion.GetWalkerCapsuleParams(spec, out float capR, out float capHalfL); + float density = WalkerLocomotion.GetWalkerCapsuleDensity(spec, capR, capHalfL); Quaternion q0 = Quaternion.Identity; - if (spec.Plane == GridPlane.Dorsal) - { - var (nx, ny, nz) = syn.Terrain.SampleNormal(startX, startZ); - Vector3 desUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, new Vector3(nx, ny, nz), 0.90f)); - Vector3 axis = Vector3.Cross(Vector3.UnitY, desUp); - if (axis.LengthSquared() > 1e-8f) - { - float ang = MathF.Min(0.295f, MathF.Acos(Math.Clamp(desUp.Y, -1f, 1f))); - q0 = Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.Normalize(axis), ang)); - } - } - float spawnY = syn.Terrain.SampleHeight(startX, startZ) + WalkerLocomotion.GetRideHeight(spec); - var body = world.AddBox( + float spawnY = syn.Terrain.SampleHeight(startX, startZ) + capR + capHalfL + 0.02f; + var body = world.AddCapsule( 1000UL, (startX, spawnY, startZ), - (spec.HalfWidth, physHalfH, spec.HalfLength), + capR, + capHalfL, density, (q0.X, q0.Y, q0.Z, q0.W), - friction: 0.2f, - restitution: 0.1f); + friction: 0.0f, + restitution: 0.0f, + flags: Box3DSoaBodyFlags.LockAngularX + | Box3DSoaBodyFlags.LockAngularZ + | Box3DSoaBodyFlags.DisableContactRecycling); var grid = new ChassisGrid(spec); var ws = new WalkerState(spec); - ws.InitializePose(new Vector3(startX, spawnY, startZ), q0, world.View.Mass[body.Lane], syn.Terrain); + ws.InitializePose(new Vector3(startX, spawnY, startZ), q0, world.View.Mass[body.Lane], syn.Terrain, world, body.Lane); return (world, body, ws, grid); } @@ -1172,16 +1171,12 @@ namespace RustToDust.Tests for (int t = 0; t < 180; t++) { - var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); - var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); - var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); - var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); - - WalkerLocomotion.StepWalker( - ws, grid, flat.Terrain, view, lane, view.Mass[lane], - pos, q, vel, angVel, + WalkerLocomotion.PreStepWalker( + ws, grid, flat.Terrain, world, body, view.Mass[lane], new Vector3(0f, 0f, grid.Spec.MaxSpeed), 0f, false, ArenaSession.FixedDt); world.Step(ArenaSession.FixedDt, ArenaSession.SubStepCount); + WalkerLocomotion.PostStepWalker( + ws, grid, flat.Terrain, world, body, view.Mass[lane], ArenaSession.FixedDt); if (t >= 60) { @@ -1283,15 +1278,12 @@ namespace RustToDust.Tests var view = world.View; for (int t = 0; t < 150; t++) { - var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); - var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); - var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); - var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); - WalkerLocomotion.StepWalker( - ws, grid, flat.Terrain, view, lane, view.Mass[lane], - pos, q, vel, angVel, + WalkerLocomotion.PreStepWalker( + ws, grid, flat.Terrain, world, body, view.Mass[lane], new Vector3(0f, 0f, grid.Spec.MaxSpeed), 0f, false, ArenaSession.FixedDt); world.Step(ArenaSession.FixedDt, ArenaSession.SubStepCount); + WalkerLocomotion.PostStepWalker( + ws, grid, flat.Terrain, world, body, view.Mass[lane], ArenaSession.FixedDt); } flatSpeed = MathF.Sqrt(view.VelocityX[lane] * view.VelocityX[lane] + view.VelocityZ[lane] * view.VelocityZ[lane]); } @@ -1310,15 +1302,12 @@ namespace RustToDust.Tests for (int t = 0; t < 150; t++) { - var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); - var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); - var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); - var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); - WalkerLocomotion.StepWalker( - ws, grid, syn.Terrain, view, lane, view.Mass[lane], - pos, q, vel, angVel, + WalkerLocomotion.PreStepWalker( + ws, grid, syn.Terrain, world, body, view.Mass[lane], new Vector3(0f, 0f, grid.Spec.MaxSpeed), 0f, false, ArenaSession.FixedDt); world.Step(ArenaSession.FixedDt, ArenaSession.SubStepCount); + WalkerLocomotion.PostStepWalker( + ws, grid, syn.Terrain, world, body, view.Mass[lane], ArenaSession.FixedDt); if (t >= 30) { @@ -1433,5 +1422,405 @@ namespace RustToDust.Tests $"{spec.Id}: residual yaw angVel@0.20s={angVelAt020s:F4} rad/s > 0.05 rad/s"); } } + + [Fact] + public void OptionA_All7Mechs_ZeroPhysicsTilt_BoundedVisualLean_DunesSionCurbsAndBlast() + { + var specs = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel, + Catalog.Manticore, + Catalog.Bastion + }; + + const float maxBipedLeanRad = 8.05f * (MathF.PI / 180f); + const float maxQuadLeanRad = 14.55f * (MathF.PI / 180f); + + foreach (var spec in specs) + { + foreach (var map in new[] { ArenaMapKind.Desert, ArenaMapKind.Sion }) + { + using var session = new ArenaSession(seed: 42, mapKind: map, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 900f + i * 16f, 900f); + } + + float startX = 0f; + float startZ = 0f; + float startYaw = 0f; + if (map == ArenaMapKind.Sion && session.State.SionMap is { } sion) + { + // Aim near a Sion building plinth/curb so col_*.bin edges are crossed + foreach (var b in sion.Buildings) + { + if (b.HalfX > 4f && b.HalfZ > 4f && MathF.Abs(b.CenterX) < 400f && MathF.Abs(b.CenterZ) < 400f) + { + startX = b.CenterX; + startZ = b.CenterZ - b.HalfZ - 10f; + startYaw = 0f; + break; + } + } + } + + session.SetContenderPose(0, startX, startZ, startYaw); + session.State.SpawnChassisDrop(startX, startZ, spec); + Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}"); + session.SetContenderPose(0, startX, startZ, startYaw); + + var player = session.State.Contenders[0]; + var body = session.GetContenderBody(player.Id)!.Value; + var ws = session.GetWalkerState(true, player.Id)!; + var view = session.World.View; + int lane = body.Lane; + + float maxLeanObserved = 0f; + for (int t = 0; t < 180; t++) + { + if (t == 60 || t == 120) + { + // Heavy lateral + slight upward blast knockback impulse + float mass = view.Mass[lane]; + session.World.ApplyImpulse( + lane, + (mass * 7.5f, mass * 2.2f, -mass * 4.5f), + (view.PositionX[lane], view.PositionY[lane] - 1.0f, view.PositionZ[lane])); + ws.AddRecoilImpulse(new Vector3(1f, 0f, 0.5f), new Quaternion(player.CurrRotX, player.CurrRotY, player.CurrRotZ, player.CurrRotW), 70f); + } + + float steer = MathF.Sin(t * 0.08f) * 0.8f; + session.SetHumanInput(0, new PlayerInput( + Throttle: 1.0f, + Steer: steer, + AimWorldX: player.X + 40f * MathF.Sin(player.Yaw), + AimWorldZ: player.Z + 40f * MathF.Cos(player.Yaw), + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + var q = new Quaternion(player.CurrRotX, player.CurrRotY, player.CurrRotZ, player.CurrRotW); + var up = Vector3.Transform(Vector3.UnitY, q); + Assert.True(up.Y >= 0.9999f, $"{spec.Id} ({map}) tick {t}: physics body tilted! up.Y={up.Y:F6}"); + Assert.True(MathF.Abs(q.X) <= 1e-3f && MathF.Abs(q.Z) <= 1e-3f, + $"{spec.Id} ({map}) tick {t}: non-zero q.X/q.Z ({q.X:E2}, {q.Z:E2})"); + + if (spec.Plane == GridPlane.Dorsal) + { + float leanNorm = MathF.Sqrt(ws.LeanPitch * ws.LeanPitch + ws.LeanRoll * ws.LeanRoll); + maxLeanObserved = MathF.Max(maxLeanObserved, leanNorm); + Assert.True(leanNorm <= maxQuadLeanRad, + $"{spec.Id} ({map}) tick {t}: dorsal visual lean {leanNorm * 180f / MathF.PI:F2}deg > 14.55deg"); + } + else + { + float absP = MathF.Abs(ws.LeanPitch); + float absR = MathF.Abs(ws.LeanRoll); + maxLeanObserved = MathF.Max(maxLeanObserved, MathF.Max(absP, absR)); + Assert.True(absP <= maxBipedLeanRad && absR <= maxBipedLeanRad, + $"{spec.Id} ({map}) tick {t}: biped visual lean ({absP * 180f / MathF.PI:F2}, {absR * 180f / MathF.PI:F2})deg > 8.05deg"); + } + } + + _output.WriteLine($"{spec.Id,-10} {map,-6}: physicsTilt=0.00deg maxVisualLean={maxLeanObserved * 180f / MathF.PI:F2}deg"); + } + } + } + + [Fact] + public void OptionA_All7Mechs_StepUpCurbs030To060_SmoothNoAirLaunch_TallWallStops() + { + var specs = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel, + Catalog.Manticore, + Catalog.Bastion + }; + + foreach (var spec in specs) + { + // 1. Climb 0.30m, 0.45m, 0.60m curbs smoothly without catapulting, then step off 3.0m cliff under -20 m/s^2 gravity + using (var world = new Box3DSoaWorld(capacity: 16, gravityX: 0f, gravityY: -20f, gravityZ: 0f)) + { + var terrain = MakeSyntheticSlope(0f).Terrain; + // Base deck raised +3.0m so walking off the end drops 3.0m down to y=0 + world.AddStaticBox(10UL, (0f, 1.5f, 20f), (30f, 1.5f, 35f), friction: 0.4f, restitution: 0.0f); + // Curbs along +Z on top of y=3.0m deck: 0.30m, 0.45m, 0.60m + world.AddStaticBox(11UL, (0f, 3.0f + 0.15f, 14f), (20f, 0.15f, 4f), friction: 0.4f, restitution: 0.0f); + world.AddStaticBox(12UL, (0f, 3.0f + 0.225f, 26f), (20f, 0.225f, 4f), friction: 0.4f, restitution: 0.0f); + world.AddStaticBox(13UL, (0f, 3.0f + 0.30f, 40f), (20f, 0.30f, 4f), friction: 0.4f, restitution: 0.0f); + // Ground slab at y=-0.5m (top at y=0) + world.AddStaticBox(14UL, (0f, -0.5f, 60f), (30f, 0.5f, 30f), friction: 0.4f, restitution: 0.0f); + + WalkerLocomotion.GetWalkerCapsuleParams(spec, out float capR, out float capHalfL); + float density = WalkerLocomotion.GetWalkerCapsuleDensity(spec, capR, capHalfL); + float spawnY = 3.0f + capR + capHalfL + 0.01f; + var body = world.AddCapsule( + 1000UL, + (0f, spawnY, -4f), + capR, + capHalfL, + density, + (0f, 0f, 0f, 1f), + friction: 0.0f, + restitution: 0.0f, + flags: Box3DSoaBodyFlags.LockAngularX | Box3DSoaBodyFlags.LockAngularZ | Box3DSoaBodyFlags.DisableContactRecycling); + + var grid = new ChassisGrid(spec); + var ws = new WalkerState(spec); + ws.InitializePose(new Vector3(0f, spawnY, -4f), Quaternion.Identity, world.View.Mass[body.Lane], terrain, world, body.Lane); + + float maxVelY = float.NegativeInfinity; + float minVelY = float.PositiveInfinity; + float maxReachedY = 0f; + bool sawCliffFall = false; + bool sawCliffLandingDip = false; + var view = world.View; + int lane = body.Lane; + + for (int t = 0; t < 420; t++) + { + WalkerLocomotion.PreStepWalker( + ws, grid, terrain, world, body, view.Mass[lane], + new Vector3(0f, 0f, spec.MaxSpeed), 0f, false, ArenaSession.FixedDt); + world.Step(ArenaSession.FixedDt, ArenaSession.SubStepCount); + WalkerLocomotion.PostStepWalker( + ws, grid, terrain, world, body, view.Mass[lane], ArenaSession.FixedDt); + + float vy = view.VelocityY[lane]; + maxVelY = MathF.Max(maxVelY, vy); + minVelY = MathF.Min(minVelY, vy); + maxReachedY = MathF.Max(maxReachedY, view.PositionY[lane]); + + if (view.PositionZ[lane] > 56f && ws.IsAirborne) + { + sawCliffFall = true; + } + if (sawCliffFall && ws.Grounded && ws.CompressionY < -0.05f) + { + sawCliffLandingDip = true; + } + } + + _output.WriteLine( + $"{spec.Id,-10} curbs 0.30/0.45/0.60m + 3m cliff: endZ={view.PositionZ[lane]:F1}m maxY={maxReachedY:F2}m " + + $"maxVy={maxVelY:F2}m/s minVy={minVelY:F2}m/s cliffFall={sawCliffFall} landingDip={sawCliffLandingDip}"); + + Assert.True(view.PositionZ[lane] > 58f, $"{spec.Id}: stalled on 0.30-0.60m curbs (endZ={view.PositionZ[lane]:F1}m)"); + Assert.True(maxReachedY >= 3.0f + 0.55f + capR + capHalfL - 0.05f, $"{spec.Id}: failed to climb 0.60m curb (maxY={maxReachedY:F2}m)"); + Assert.True(maxVelY <= 2.5f, $"{spec.Id}: curb catapult detected! maxVelY={maxVelY:F2}m/s > 2.5m/s"); + Assert.True(sawCliffFall && minVelY < -3.0f, $"{spec.Id}: failed ballistic freefall off 3m cliff (minVelY={minVelY:F2})"); + Assert.True(sawCliffLandingDip, $"{spec.Id}: expected CompressionY landing dip after 3m cliff drop"); + } + + // 2. Tall 2.50m wall MUST block the mech cleanly (no wall climbing!) + using (var world = new Box3DSoaWorld(capacity: 8, gravityX: 0f, gravityY: -20f, gravityZ: 0f)) + { + var terrain = MakeSyntheticSlope(0f).Terrain; + world.AddStaticBox(10UL, (0f, -0.5f, 0f), (60f, 0.5f, 60f), friction: 0.4f, restitution: 0.0f); + world.AddStaticBox(11UL, (0f, 1.25f, 12f), (20f, 1.25f, 2f), friction: 0.4f, restitution: 0.0f); + + WalkerLocomotion.GetWalkerCapsuleParams(spec, out float capR, out float capHalfL); + float density = WalkerLocomotion.GetWalkerCapsuleDensity(spec, capR, capHalfL); + float spawnY = capR + capHalfL + 0.01f; + var body = world.AddCapsule( + 1000UL, + (0f, spawnY, 0f), + capR, + capHalfL, + density, + (0f, 0f, 0f, 1f), + friction: 0.0f, + restitution: 0.0f, + flags: Box3DSoaBodyFlags.LockAngularX | Box3DSoaBodyFlags.LockAngularZ | Box3DSoaBodyFlags.DisableContactRecycling); + + var grid = new ChassisGrid(spec); + var ws = new WalkerState(spec); + ws.InitializePose(new Vector3(0f, spawnY, 0f), Quaternion.Identity, world.View.Mass[body.Lane], terrain, world, body.Lane); + var view = world.View; + int lane = body.Lane; + + for (int t = 0; t < 120; t++) + { + WalkerLocomotion.PreStepWalker( + ws, grid, terrain, world, body, view.Mass[lane], + new Vector3(0f, 0f, spec.MaxSpeed), 0f, false, ArenaSession.FixedDt); + world.Step(ArenaSession.FixedDt, ArenaSession.SubStepCount); + WalkerLocomotion.PostStepWalker( + ws, grid, terrain, world, body, view.Mass[lane], ArenaSession.FixedDt); + } + + Assert.True(view.PositionZ[lane] < 10.2f, $"{spec.Id}: breached/climbed 2.50m tall wall (z={view.PositionZ[lane]:F2}m)"); + Assert.True(view.PositionY[lane] < spawnY + 0.10f, $"{spec.Id}: climbed onto 2.50m tall wall (y={view.PositionY[lane]:F2}m)"); + } + } + } + + [Fact] + public void OptionA_Bipeds_CoMWeightShift_InvertedPendulum_HeelCompression_ZeroFootSkate() + { + var bipeds = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel + }; + + foreach (var spec in bipeds) + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 600f + i * 16f, 600f); + } + + session.SetContenderPose(0, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis(0)); + session.SetContenderPose(0, 0f, 0f, 0f); + + var player = session.State.Contenders[0]; + var ws = session.GetWalkerState(true, player.Id)!; + + float maxLeftPelvisX = float.NegativeInfinity; + float minRightPelvisX = float.PositiveInfinity; + float minPelvisY = float.PositiveInfinity; + float maxPelvisY = float.NegativeInfinity; + float minCompressionY = float.PositiveInfinity; + float maxStanceSkate = 0f; + float peakLoadG = 0f; + Vector3 prevSole0 = ws.FootSole[0]; + Vector3 prevSole1 = ws.FootSole[1]; + bool prevPlanted0 = ws.Planted[0]; + bool prevPlanted1 = ws.Planted[1]; + + for (int t = 0; t < 180; t++) + { + float throttle = t < 130 ? 0.50f : 0.0f; + session.SetHumanInput(0, new PlayerInput(throttle, 0f, player.X, player.Z + 80f, false, false, false)); + session.Step(); + + if (ws.Planted[0] && !ws.Planted[1]) + { + maxLeftPelvisX = MathF.Max(maxLeftPelvisX, ws.PelvisOffset.X); + if (prevPlanted0) + { + float skate = Vector2.Distance(new Vector2(ws.FootSole[0].X, ws.FootSole[0].Z), new Vector2(prevSole0.X, prevSole0.Z)); + maxStanceSkate = MathF.Max(maxStanceSkate, skate); + } + } + else if (!ws.Planted[0] && ws.Planted[1]) + { + minRightPelvisX = MathF.Min(minRightPelvisX, ws.PelvisOffset.X); + if (prevPlanted1) + { + float skate = Vector2.Distance(new Vector2(ws.FootSole[1].X, ws.FootSole[1].Z), new Vector2(prevSole1.X, prevSole1.Z)); + maxStanceSkate = MathF.Max(maxStanceSkate, skate); + } + } + + if (t >= 20 && t < 130) + { + minPelvisY = MathF.Min(minPelvisY, ws.PelvisOffset.Y); + maxPelvisY = MathF.Max(maxPelvisY, ws.PelvisOffset.Y); + minCompressionY = MathF.Min(minCompressionY, ws.CompressionY); + } + peakLoadG = MathF.Max(peakLoadG, MathF.Max(ws.LoadG[0], ws.LoadG[1])); + + prevSole0 = ws.FootSole[0]; + prevSole1 = ws.FootSole[1]; + prevPlanted0 = ws.Planted[0]; + prevPlanted1 = ws.Planted[1]; + } + + float pelvisYRange = maxPelvisY - minPelvisY; + _output.WriteLine( + $"{spec.Id,-10} ZMP_X=[{minRightPelvisX:F3}, +{maxLeftPelvisX:F3}]m pelvisYRange={pelvisYRange:F3}m " + + $"minCompY={minCompressionY:F3}m maxSkate={maxStanceSkate:F4}m peakLoadG={peakLoadG:F2}G"); + + Assert.True(maxLeftPelvisX > 0.10f, $"{spec.Id}: expected positive ZMP shift over Left stance foot, got {maxLeftPelvisX:F3}m"); + Assert.True(minRightPelvisX < -0.10f, $"{spec.Id}: expected negative ZMP shift over Right stance foot, got {minRightPelvisX:F3}m"); + Assert.True(pelvisYRange >= 0.05f, $"{spec.Id}: expected inverted-pendulum + compression vertical arc >= 0.05m, got {pelvisYRange:F3}m"); + Assert.True(minCompressionY < -0.025f, $"{spec.Id}: expected heel-strike CompressionY dip < -0.025m, got {minCompressionY:F3}m"); + Assert.True(maxStanceSkate < 0.03f, $"{spec.Id}: stance foot skated {maxStanceSkate:F4}m >= 0.03m"); + Assert.True(peakLoadG >= 0.24f, $"{spec.Id}: expected LoadG >= 0.24G for footstep tracker"); + } + } + + [Fact] + public void OptionA_SnapshotCodec_RoundTripsPelvisAndLean_Within1152Bytes() + { + var state = new MatchState(seed: 42, ArenaMapKind.Desert); + var local = state.Contenders[0]; + local.Grid.SwapChassis(Catalog.Bastion); + + var contenders = new List(12); + var walkers = new List(12); + var specs = new List(8); + + for (int i = 0; i < 12; i++) + { + contenders.Add(new NetContenderState + { + SlotId = (byte)i, + Alive = true, + IsHuman = true, + Pos = new Vector3(i * 10f, 4f, -i * 5f), + Rot = Quaternion.Identity, + Vel = new Vector3(5f, 0f, 2f) + }); + var ws = new WalkerVisualSnapshot + { + LegCount = 4, + PelvisOffset = new Vector3(0.32f, -0.11f, 0.04f), + LeanPitch = 0.11f, + LeanRoll = -0.14f + }; + for (int l = 0; l < 4; l++) + { + ws.LegAngles[l] = new WalkerLegAngles { HipPitch = 0.3f, HipRoll = 0.1f, KneeFlex = -0.6f, AnklePitch = 0.15f }; + ws.FootNormal[l] = Vector3.UnitY; + ws.LoadG[l] = 1.1f; + } + walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws }); + } + + byte[] payload = SnapshotCodec.EncodeCorePvs( + 1, 42, 84, 1.4f, 10, 100, 450f, MatchPhase.Active, null, 2, 0xFFF, + local, new Vector3(0.1f, 0.2f, 0.05f), contenders, walkers, specs); + byte[] wire = SnapshotCodec.WrapLatest(payload, 1, 1); + byte[] udp = CultNetRudpPacketCodec.Encode(new CultNetRudpPacket + { + ConnectionId = 0x52544431, + PacketType = CultNetRudpPacketType.Data, + ChannelId = SnapshotCodec.ChannelLatest, + Sequence = 1, + Sequenced = true, + Payload = wire + }); + + Assert.True(payload.Length <= SnapshotCodec.MaxLatestPayloadBytes, + $"Payload {payload.Length}B > {SnapshotCodec.MaxLatestPayloadBytes}B"); + Assert.True(udp.Length <= SnapshotCodec.MaxLatestDatagramBytes, + $"UDP {udp.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); + Assert.True(SnapshotCodec.TryDecodeCorePvs(payload, out var dec)); + Assert.NotEmpty(dec.Walkers); + var s0 = dec.Walkers[0].Snapshot; + Assert.InRange(s0.PelvisOffset.X, 0.30f, 0.34f); + Assert.InRange(s0.PelvisOffset.Y, -0.13f, -0.09f); + Assert.InRange(s0.LeanPitch, 0.10f, 0.12f); + Assert.InRange(s0.LeanRoll, -0.15f, -0.13f); + } } }