using System; using System.Collections.Generic; using Godot; using RustToDust.Core; using RustToDust.Ymir; namespace RustToDust.Client; public readonly record struct VehicleRigDriveInput( Vector3 Velocity, float Yaw, float AimYawWorld, float AimPitchDeg, float SteerCmd, float ThrottleCmd, float VerticalThrottleCmd, float EngineThermalPerf, float DeltaTime, bool IsGrounded = true); /// /// Drives real-time secondary mechanism animations on /// from live physics state with strict NaN/Inf guards: /// - Wheeled: wheel spin (v / r), front-axle steering, subtle chassis suspension roll/pitch. /// - Turrets/Torsos/Arms: yaw tracking (joint.turret_yaw, joint.torso_yaw) & arm pitch. /// - VTOL: rotor spin scaled by EngineThermalPerf + lift demand, nacelle tilt with acceleration. /// - Walkers/Mechs: pure FK posing from Hybrid B with per-segment /// rest-basis alignment (Q_offset), Manticore tail aiming, and Breaker's real GRF-driven /// oleo strut + 2-link scissor torque links + telescoping recess rams. /// public static class VehicleRigAnimator { public sealed class StrutState { public float Compression; public float Velocity; } public sealed class ScissorBinding { public required Node3D UpperNode; public required Node3D LowerNode; public required Node3D ShinNode; public required Node3D OleoNode; public required Node3D OleoForkNode; public required Transform3D RestLocalUp; public required Transform3D RestLocalLow; public required Vector3 AInShin; public required Vector3 BInOleoFork; public required Vector3 OutInShin; public required float Arm; public required Vector3 DirUp0InShin; public required Vector3 DirLow0InOleoFork; } public sealed class RamBinding { public required Node3D RamNode; public required Node3D LugNode; public required Node3D OleoNode; public required Node3D OleoForkNode; public required Node3D FootNode; public required Transform3D RestLocalRam; public required Vector3 APosInLug; public required Vector3 BPosInFoot; public required Vector3 WantDir0InLug; } public sealed class BreakerMechRig { public bool Initialized; public readonly Dictionary Struts = new(StringComparer.Ordinal); public readonly Dictionary OleoNodes = new(StringComparer.Ordinal); public readonly List Scissors = new(); public readonly List Rams = new(); } public sealed class SegmentBinding { public required Node3D Node; public required Transform3D RestLocal; public required Node3D[] IntermediateBefore; public required Basis QOffset; } public sealed class WalkerLegBinding { public SegmentBinding? Coxa; public required SegmentBinding Thigh; public required SegmentBinding Shin; public SegmentBinding? Cannon; public required SegmentBinding Foot; } public sealed class WalkerVisualRig { public required WalkerGeometrySpec Geom; public required WalkerLegBinding[] Legs; } public sealed class RigState { public float WheelSpinRad; public float SteerRad; public float TurretYawRad; public float ArmPitchRad; public float RotorSpinRad; public float NacelleTiltRad; public float PrevForwardSpeed; public float ChassisPitchRad; public float ChassisRollRad; public float ElapsedSeconds; public BreakerMechRig? BreakerRig; public WalkerVisualRig? WalkerRig; } public static void Update( VehicleVisualInstance visual, ContenderState c, Vector3 velocity, Basis worldBasis, float dt, bool snap = false) { var input = BuildContenderInput(c, velocity, dt); Update(visual, in input, worldBasis, snap); } public static void Update( VehicleVisualInstance visual, ContenderState c, Vector3 velocity, Basis worldBasis, float dt, in WalkerVisualSnapshot walkerSnap, bool snap = false) { var input = BuildContenderInput(c, velocity, dt); Update(visual, in input, worldBasis, in walkerSnap, snap); } private static VehicleRigDriveInput BuildContenderInput(ContenderState c, Vector3 velocity, float dt) { float aimYawWorld = c.Yaw; float dx = c.AimX - c.X; float dz = c.AimZ - c.Z; if (float.IsFinite(dx) && float.IsFinite(dz) && (dx * dx + dz * dz) > 0.01f) { aimYawWorld = MathF.Atan2(dx, dz); } float aimPitchDeg = 0f; if (float.IsFinite(c.AimY)) { float aimOriginY = MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight); float horiz = MathF.Sqrt(dx * dx + dz * dz); if (horiz > 0.1f) { aimPitchDeg = Mathf.RadToDeg(MathF.Atan2(c.AimY - aimOriginY, horiz)); } } return new VehicleRigDriveInput( Velocity: velocity, Yaw: c.Yaw, AimYawWorld: aimYawWorld, AimPitchDeg: aimPitchDeg, SteerCmd: c.SteerCmd, ThrottleCmd: c.ThrottleCmd, VerticalThrottleCmd: c.VerticalThrottleCmd, EngineThermalPerf: c.Grid.ComputeEngineThermalPerformance(), DeltaTime: dt, IsGrounded: !c.Grid.Spec.IsVtol); } public static void Update( VehicleVisualInstance visual, in VehicleRigDriveInput input, Basis worldBasis, bool snap = false) { UpdateCore(visual, in input, worldBasis, hasWalkerSnap: false, in DefaultSnapshot, snap); } public static void Update( VehicleVisualInstance visual, in VehicleRigDriveInput input, Basis worldBasis, in WalkerVisualSnapshot walkerSnap, bool snap = false) { UpdateCore(visual, in input, worldBasis, hasWalkerSnap: true, in walkerSnap, snap); } private static readonly WalkerVisualSnapshot DefaultSnapshot = default; private static void UpdateCore( VehicleVisualInstance visual, in VehicleRigDriveInput input, Basis worldBasis, bool hasWalkerSnap, in WalkerVisualSnapshot walkerSnap, bool snap) { float dt = Sanitize(input.DeltaTime, 0f, 0f, 0.1f); if (!snap && dt <= 0f) { return; } Vector3 vel = SanitizeVec(input.Velocity); float yaw = Sanitize(input.Yaw, 0f, -MathF.Tau * 4f, MathF.Tau * 4f); float aimYawWorld = Sanitize(input.AimYawWorld, yaw, -MathF.Tau * 4f, MathF.Tau * 4f); float aimPitchDeg = Sanitize(input.AimPitchDeg, 0f, -85f, 85f); float steerCmd = Sanitize(input.SteerCmd, 0f, -1f, 1f); float throttleCmd = Sanitize(input.ThrottleCmd, 0f, -1f, 1f); float vertCmd = Sanitize(input.VerticalThrottleCmd, 0f, -1f, 1f); float enginePerf = Sanitize(input.EngineThermalPerf, 1f, 0f, 1f); RigState st = visual.RigState; st.ElapsedSeconds += dt; Vector3 fwd = worldBasis.Z; fwd.Y = 0f; fwd = fwd.LengthSquared() > 1e-5f ? fwd.Normalized() : new Vector3(MathF.Sin(yaw), 0f, MathF.Cos(yaw)); Vector3 right = new(-fwd.Z, 0f, fwd.X); float forwardSpeed = vel.Dot(fwd); float lateralSpeed = vel.Dot(right); float relYaw = MatchRules.NormalizeAngle(aimYawWorld - yaw); float aimPitchRad = Mathf.DegToRad(aimPitchDeg); float blendFast = dt > 0f ? 1f - MathF.Exp(-dt * 10f) : 1f; float blendMed = dt > 0f ? 1f - MathF.Exp(-dt * 7f) : 1f; // 1. Turrets & torsos UpdateTurretAndTorso(visual, st, relYaw, aimPitchRad, blendFast); // 2. Mobility-specific drives var mobility = visual.Package.Mobility; switch (mobility) { case MobilityKind.Wheeled: UpdateWheeled(visual, st, forwardSpeed, lateralSpeed, steerCmd, dt, blendFast); break; case MobilityKind.Vtol: UpdateVtol(visual, st, forwardSpeed, throttleCmd, vertCmd, enginePerf, dt, blendMed); break; case MobilityKind.Walker: if (hasWalkerSnap) { UpdateWalkerFromSnapshot(visual, st, in walkerSnap, relYaw, aimPitchRad, dt, blendMed); } else if (string.Equals(visual.ModelId, "manticore", StringComparison.OrdinalIgnoreCase)) { AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blendMed); } break; case MobilityKind.Tracked: UpdateTrackedSuspension(visual, st, forwardSpeed, lateralSpeed, dt, blendMed); break; } st.PrevForwardSpeed = forwardSpeed; } private static void UpdateTurretAndTorso( VehicleVisualInstance visual, RigState st, float relYaw, float aimPitchRad, float blend) { if (visual.Joints.TryGetValue("joint.turret_yaw", out var turretJoint) || visual.Joints.TryGetValue("joint.torso_yaw", out turretJoint)) { bool fullSpin = turretJoint.MinRad <= -MathF.PI * 0.99f && turretJoint.MaxRad >= MathF.PI * 0.99f; float targetYaw = fullSpin ? relYaw : Math.Clamp(relYaw, turretJoint.MinRad, turretJoint.MaxRad); if (fullSpin) { float diff = MatchRules.NormalizeAngle(targetYaw - st.TurretYawRad); st.TurretYawRad = MatchRules.NormalizeAngle(st.TurretYawRad + diff * blend); } else { st.TurretYawRad += (targetYaw - st.TurretYawRad) * blend; } SetJointAngle(turretJoint, st.TurretYawRad); } st.ArmPitchRad += (aimPitchRad - st.ArmPitchRad) * blend; // Positive elevation (+aimPitchRad) rotates negatively around vehicle +X (raises +Z barrels toward +Y) if (visual.Joints.TryGetValue("joint.arm_l_pitch", out var armL)) { float clampedL = Math.Clamp(-st.ArmPitchRad, armL.MinRad, armL.MaxRad); SetJointAngle(armL, clampedL); } if (visual.Joints.TryGetValue("joint.arm_r_pitch", out var armR)) { float clampedR = Math.Clamp(-st.ArmPitchRad, armR.MinRad, armR.MaxRad); SetJointAngle(armR, clampedR); } } private static void UpdateWheeled( VehicleVisualInstance visual, RigState st, float forwardSpeed, float lateralSpeed, float steerCmd, float dt, float blend) { float radiusSum = 0f; int radiusCount = 0; foreach (var (jid, j) in visual.Joints) { if (jid.StartsWith("joint.wheel_", StringComparison.Ordinal)) { float y = j.RestLocal.Origin.Y; if (y <= 0.05f && j.Node.GetParent() is Node3D p3) { y = p3.Transform.Origin.Y; } if (y > 0.1f) { radiusSum += y; radiusCount++; } } } float wheelRadius = radiusCount > 0 ? radiusSum / radiusCount : 0.45f; st.WheelSpinRad = MathF.IEEERemainder(st.WheelSpinRad + (forwardSpeed / MathF.Max(0.25f, wheelRadius)) * dt, MathF.Tau); float targetSteer = -steerCmd * Mathf.DegToRad(28f); st.SteerRad += (targetSteer - st.SteerRad) * blend; foreach (var (jid, j) in visual.Joints) { if (jid.StartsWith("joint.wheel_", StringComparison.Ordinal)) { SetJointAngle(j, st.WheelSpinRad); } else if (jid.StartsWith("joint.steer_", StringComparison.Ordinal)) { float clampedSteer = Math.Clamp(st.SteerRad, j.MinRad, j.MaxRad); SetJointAngle(j, clampedSteer); } } float accel = dt > 1e-4f ? (forwardSpeed - st.PrevForwardSpeed) / dt : 0f; float targetPitch = Math.Clamp(-accel * 0.0022f, -0.05f, 0.05f); float targetRoll = Math.Clamp(lateralSpeed * 0.0045f + steerCmd * MathF.Min(1f, MathF.Abs(forwardSpeed) / 14f) * 0.035f, -0.06f, 0.06f); st.ChassisPitchRad += (targetPitch - st.ChassisPitchRad) * blend; st.ChassisRollRad += (targetRoll - st.ChassisRollRad) * blend; if (visual.GetNamedNode("Chassis") is { } chassis && visual.TryGetRestLocal("Chassis", out var restChassis)) { Basis tilt = new Basis(Vector3.Right, st.ChassisPitchRad) * new Basis(Vector3.Back, st.ChassisRollRad); chassis.Transform = new Transform3D(tilt * restChassis.Basis, restChassis.Origin); } } private static void UpdateTrackedSuspension( VehicleVisualInstance visual, RigState st, float forwardSpeed, float lateralSpeed, float dt, float blend) { float accel = dt > 1e-4f ? (forwardSpeed - st.PrevForwardSpeed) / dt : 0f; float targetPitch = Math.Clamp(-accel * 0.0018f, -0.045f, 0.045f); float targetRoll = Math.Clamp(lateralSpeed * 0.003f, -0.045f, 0.045f); st.ChassisPitchRad += (targetPitch - st.ChassisPitchRad) * blend; st.ChassisRollRad += (targetRoll - st.ChassisRollRad) * blend; if (visual.GetNamedNode("Chassis") is { } chassis && visual.TryGetRestLocal("Chassis", out var restChassis)) { Basis tilt = new Basis(Vector3.Right, st.ChassisPitchRad) * new Basis(Vector3.Back, st.ChassisRollRad); chassis.Transform = new Transform3D(tilt * restChassis.Basis, restChassis.Origin); } } private static void UpdateVtol( VehicleVisualInstance visual, RigState st, float forwardSpeed, float throttleCmd, float vertCmd, float enginePerf, float dt, float blend) { float rotorSpeed = (5.5f + 18.0f * enginePerf) * (1f + 0.35f * MathF.Max(0f, vertCmd) + 0.16f * MathF.Abs(throttleCmd)); st.RotorSpinRad = MathF.IEEERemainder(st.RotorSpinRad + rotorSpeed * dt, MathF.Tau); float targetTilt = throttleCmd * 0.42f + (forwardSpeed / 42f) * 0.28f; st.NacelleTiltRad += (targetTilt - st.NacelleTiltRad) * blend; foreach (var (jid, j) in visual.Joints) { if (jid.StartsWith("joint.rotor_", StringComparison.Ordinal)) { float dir = (jid.Contains("_r", StringComparison.Ordinal) && !jid.Contains("_rl", StringComparison.Ordinal)) || jid.EndsWith("_rl", StringComparison.Ordinal) ? -1f : 1f; SetJointAngle(j, st.RotorSpinRad * dir); } else if (jid.StartsWith("joint.nacelle_", StringComparison.Ordinal)) { float clampedTilt = Math.Clamp(st.NacelleTiltRad, j.MinRad, j.MaxRad); SetJointAngle(j, clampedTilt); } } } private static void UpdateWalkerFromSnapshot( VehicleVisualInstance visual, RigState st, in WalkerVisualSnapshot snap, float relYaw, float aimPitchRad, float dt, float blend) { var rig = st.WalkerRig ??= InitWalkerRig(visual); if (rig is null) { return; } 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); int count = Math.Min(rig.Legs.Length, snap.LegCount); for (int i = 0; i < count; i++) { var legRig = rig.Legs[i]; var legSpec = geom.Legs[i]; var ang = snap.LegAngles[i]; if (!float.IsFinite(ang.HipPitch) || !float.IsFinite(ang.HipRoll) || !float.IsFinite(ang.KneeFlex) || !float.IsFinite(ang.HockFlex) || !float.IsFinite(ang.AnklePitch)) { continue; } Vector3 footNormModel = ToGodot(System.Numerics.Vector3.Transform(snap.FootNormal[i], bodyRotInv)); footNormModel = footNormModel.LengthSquared() > 1e-6f ? footNormModel.Normalized() : Vector3.Up; Vector3 r0 = ToGodot(legSpec.LegRight0); Vector3 f0 = ToGodot(legSpec.LegFwd0); Basis curModelBasis = Basis.Identity; if (snap.IsArachnidUp) { float coxaYaw = ang.HipRoll; Vector3 legOut = (f0 * MathF.Cos(coxaYaw) + r0 * MathF.Sin(coxaYaw)).Normalized(); Vector3 legRight = (r0 * MathF.Cos(coxaYaw) - f0 * MathF.Sin(coxaYaw)).Normalized(); if (legRig.Coxa is { } coxaSeg) { Basis coxaBasis = BasisFromDownAndRight(-legOut, Vector3.Up.Cross(legOut)) * coxaSeg.QOffset; curModelBasis = ApplySegmentModelBasis(coxaSeg, curModelBasis, coxaBasis); } Vector3 s1Dir = (legOut * MathF.Cos(ang.HipPitch) + Vector3.Up * MathF.Sin(ang.HipPitch)).Normalized(); float s2Elev = ang.HipPitch - ang.KneeFlex; Vector3 s2Dir = (legOut * MathF.Cos(s2Elev) + Vector3.Up * MathF.Sin(s2Elev)).Normalized(); Basis thighBasis = BasisFromDownAndRight(s1Dir, legRight) * legRig.Thigh.QOffset; curModelBasis = ApplySegmentModelBasis(legRig.Thigh, curModelBasis, thighBasis); Basis shinBasis = BasisFromDownAndRight(s2Dir, legRight) * legRig.Shin.QOffset; curModelBasis = ApplySegmentModelBasis(legRig.Shin, curModelBasis, shinBasis); float lat = Math.Clamp(footNormModel.Dot(legRight), -0.85f, 0.85f); float planarMag = MathF.Sqrt(MathF.Max(0.01f, 1f - lat * lat)); Vector3 footUp = (legRight * lat + (Vector3.Up * MathF.Cos(ang.AnklePitch) + legOut * MathF.Sin(ang.AnklePitch)) * planarMag).Normalized(); Basis footBasis = BasisFromDownAndRight(-footUp, legRight) * legRig.Foot.QOffset; ApplySegmentModelBasis(legRig.Foot, curModelBasis, footBasis); } else { float hipRoll = ang.HipRoll; Vector3 legRight = (r0 * MathF.Cos(hipRoll) + Vector3.Up * MathF.Sin(hipRoll)).Normalized(); Vector3 downTilted = (-Vector3.Up * MathF.Cos(hipRoll) + r0 * MathF.Sin(hipRoll)).Normalized(); Vector3 thighDir = (downTilted * MathF.Cos(ang.HipPitch) + f0 * MathF.Sin(ang.HipPitch)).Normalized(); float shinAngle = ang.HipPitch - ang.KneeFlex; Vector3 shinDir = (downTilted * MathF.Cos(shinAngle) + f0 * MathF.Sin(shinAngle)).Normalized(); Basis thighBasis = BasisFromDownAndRight(thighDir, legRight) * legRig.Thigh.QOffset; curModelBasis = ApplySegmentModelBasis(legRig.Thigh, curModelBasis, thighBasis); Basis shinBasis = BasisFromDownAndRight(shinDir, legRight) * legRig.Shin.QOffset; curModelBasis = ApplySegmentModelBasis(legRig.Shin, curModelBasis, shinBasis); if (snap.IsDigitigrade && legRig.Cannon is { } cannonSeg) { float cannonAngle = shinAngle + ang.HockFlex; Vector3 cannonDir = (downTilted * MathF.Cos(cannonAngle) + f0 * MathF.Sin(cannonAngle)).Normalized(); Basis cannonBasis = BasisFromDownAndRight(cannonDir, legRight) * cannonSeg.QOffset; curModelBasis = ApplySegmentModelBasis(cannonSeg, curModelBasis, cannonBasis); } float lat = Math.Clamp(footNormModel.Dot(legRight), -0.85f, 0.85f); float planarMag = MathF.Sqrt(MathF.Max(0.01f, 1f - lat * lat)); Vector3 footUp = (legRight * lat + (Vector3.Up * MathF.Cos(ang.AnklePitch) + f0 * MathF.Sin(ang.AnklePitch)) * planarMag).Normalized(); Basis footBasis = BasisFromDownAndRight(-footUp, legRight) * legRig.Foot.QOffset; ApplySegmentModelBasis(legRig.Foot, curModelBasis, footBasis); } } string id = visual.ModelId; if (string.Equals(id, "manticore", StringComparison.OrdinalIgnoreCase)) { AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blend); } else if (string.Equals(id, "breaker", StringComparison.OrdinalIgnoreCase)) { StepBreakerLinkages(visual, snap.LoadG[0], snap.LoadG[1], dt); } } private static Basis ApplySegmentModelBasis(SegmentBinding seg, Basis curBasisInModel, Basis targetBasisInModel) { for (int i = 0; i < seg.IntermediateBefore.Length; i++) { curBasisInModel *= seg.IntermediateBefore[i].Transform.Basis.Orthonormalized(); } Basis localBasis = curBasisInModel.Inverse() * targetBasisInModel; seg.Node.Transform = new Transform3D(localBasis, seg.RestLocal.Origin); return targetBasisInModel; } private static WalkerVisualRig? InitWalkerRig(VehicleVisualInstance visual) { var geom = WalkerGeometrySpec.GetForChassis(visual.ModelId); string id = visual.ModelId.ToLowerInvariant(); var legs = new WalkerLegBinding[geom.LegCount]; for (int i = 0; i < geom.LegCount; i++) { string? coxaName = null; string thighName, shinName, footName; string? cannonName = null; switch (id) { case "breaker": { string s = i == 0 ? "L" : "R"; thighName = $"Leg{s}.Hip"; shinName = $"Leg{s}.Shin"; footName = $"Leg{s}.Foot"; break; } case "paladin": { string s = i == 0 ? "L" : "R"; thighName = $"Leg{s}.Upper"; shinName = $"Leg{s}.Lower"; footName = $"Leg{s}.Ankle"; break; } case "raptor": case "exemplar_frame": { string s = i == 0 ? "L" : "R"; thighName = $"Leg{s}.Thigh"; shinName = $"Leg{s}.Shin"; cannonName = $"Leg{s}.Cannon"; footName = $"Foot{s}"; break; } case "spectre": { string s = i == 0 ? "L" : "R"; thighName = $"Leg{s}.Thigh"; shinName = $"Leg{s}.Shin"; cannonName = $"Leg{s}.Cannon"; footName = $"Leg{s}.Ankle"; break; } case "kestrel": { string s = i == 0 ? "L" : "R"; thighName = $"Leg{s}.Thigh"; shinName = $"Leg{s}.Shin"; footName = $"Leg{s}.Foot"; break; } case "manticore": { string q = i switch { 0 => "FL", 1 => "FR", 2 => "BL", _ => "BR" }; coxaName = $"Leg{q}.Coxa"; thighName = $"Leg{q}.S1"; shinName = $"Leg{q}.S2"; footName = $"Foot{q}"; break; } case "bastion": { string q = i switch { 0 => "fl", 1 => "fr", 2 => "rl", _ => "rr" }; thighName = $"Thigh.{q}"; shinName = $"Shin.{q}"; footName = $"Ankle.{q}"; break; } default: return null; } if (visual.GetNamedNode(thighName) is not { } thighNode || visual.GetNamedNode(shinName) is not { } shinNode || visual.GetNamedNode(footName) is not { } footNode || !visual.TryGetRestLocal(thighName, out var restThigh) || !visual.TryGetRestLocal(shinName, out var restShin) || !visual.TryGetRestLocal(footName, out var restFoot) || !visual.TryGetRestModel(thighName, out var modelThigh) || !visual.TryGetRestModel(shinName, out var modelShin) || !visual.TryGetRestModel(footName, out var modelFoot)) { return null; } Node3D? cannonNode = null; Transform3D restCannon = Transform3D.Identity; Transform3D modelCannon = Transform3D.Identity; if (cannonName is not null) { if (visual.GetNamedNode(cannonName) is not { } cn || !visual.TryGetRestLocal(cannonName, out restCannon) || !visual.TryGetRestModel(cannonName, out modelCannon)) { return null; } cannonNode = cn; } Node3D? coxaNode = null; Transform3D restCoxa = Transform3D.Identity; Transform3D modelCoxa = Transform3D.Identity; if (coxaName is not null && visual.GetNamedNode(coxaName) is { } cxn && visual.TryGetRestLocal(coxaName, out restCoxa) && visual.TryGetRestModel(coxaName, out modelCoxa)) { coxaNode = cxn; } Vector3 dirRestThigh = (modelShin.Origin - modelThigh.Origin).Normalized(); Vector3 shinEndOrigin = cannonNode is not null ? modelCannon.Origin : modelFoot.Origin; Vector3 dirRestShin = (shinEndOrigin - modelShin.Origin).Normalized(); Vector3 dirRestCannon = cannonNode is not null ? (modelFoot.Origin - modelCannon.Origin).Normalized() : Vector3.Down; Vector3 legRightRest = geom.IsArachnidUp ? dirRestThigh.Cross(Vector3.Up).Normalized() : ToGodot(geom.Legs[i].LegRight0); SegmentBinding? coxaBinding = null; if (coxaNode is not null) { Vector3 rad0 = new(modelFoot.Origin.X - modelThigh.Origin.X, 0f, modelFoot.Origin.Z - modelThigh.Origin.Z); rad0 = rad0.LengthSquared() > 1e-6f ? rad0.Normalized() : ToGodot(geom.Legs[i].LegFwd0); Basis fCoxaRest = BasisFromDownAndRight(-rad0, Vector3.Up.Cross(rad0)); coxaBinding = new SegmentBinding { Node = coxaNode, RestLocal = restCoxa, IntermediateBefore = BuildIntermediateChain(visual.ModelRoot, coxaNode), QOffset = fCoxaRest.Inverse() * modelCoxa.Basis.Orthonormalized() }; } var thighBinding = new SegmentBinding { Node = thighNode, RestLocal = restThigh, IntermediateBefore = BuildIntermediateChain(coxaNode ?? visual.ModelRoot, thighNode), QOffset = BasisFromDownAndRight(dirRestThigh, legRightRest).Inverse() * modelThigh.Basis.Orthonormalized() }; var shinBinding = new SegmentBinding { Node = shinNode, RestLocal = restShin, IntermediateBefore = BuildIntermediateChain(thighNode, shinNode), QOffset = BasisFromDownAndRight(dirRestShin, legRightRest).Inverse() * modelShin.Basis.Orthonormalized() }; SegmentBinding? cannonBinding = null; if (cannonNode is not null) { cannonBinding = new SegmentBinding { Node = cannonNode, RestLocal = restCannon, IntermediateBefore = BuildIntermediateChain(shinNode, cannonNode), QOffset = BasisFromDownAndRight(dirRestCannon, legRightRest).Inverse() * modelCannon.Basis.Orthonormalized() }; } var footBinding = new SegmentBinding { Node = footNode, RestLocal = restFoot, IntermediateBefore = BuildIntermediateChain(cannonNode ?? shinNode, footNode), QOffset = BasisFromDownAndRight(Vector3.Down, legRightRest).Inverse() * modelFoot.Basis.Orthonormalized() }; legs[i] = new WalkerLegBinding { Coxa = coxaBinding, Thigh = thighBinding, Shin = shinBinding, Cannon = cannonBinding, Foot = footBinding }; } return new WalkerVisualRig { Geom = geom, Legs = legs }; } private static Node3D[] BuildIntermediateChain(Node3D ancestorExclusive, Node3D childExclusive) { var list = new List(4); for (Node? cur = childExclusive.GetParent(); cur is Node3D n3d && !ReferenceEquals(cur, ancestorExclusive); cur = cur.GetParent()) { list.Add(n3d); } list.Reverse(); return list.ToArray(); } private static Basis BasisFromDownAndRight(Vector3 downDir, Vector3 rightX) { Vector3 upY = -downDir.Normalized(); Vector3 x = rightX - upY * rightX.Dot(upY); x = x.LengthSquared() > 1e-6f ? x.Normalized() : Vector3.Right; Vector3 z = x.Cross(upY).Normalized(); x = upY.Cross(z).Normalized(); return new Basis(x, upY, z); } private static Vector3 ToGodot(System.Numerics.Vector3 v) => new(v.X, v.Y, v.Z); private static void AnimateManticoreTail( VehicleVisualInstance visual, RigState st, float relYaw, float aimPitchRad, float blend) { if (visual.Joints.TryGetValue("joint.tail_yaw", out var tailYaw)) { float targetTailYaw = Math.Clamp(relYaw, tailYaw.MinRad, tailYaw.MaxRad); st.TurretYawRad += (targetTailYaw - st.TurretYawRad) * blend; SetJointAngle(tailYaw, st.TurretYawRad); } float idleSway = MathF.Sin(st.ElapsedSeconds * 2.1f) * 0.05f; float pitchDrive = aimPitchRad * 0.5f + idleSway; if (visual.Joints.TryGetValue("joint.tail_s1", out var s1)) { SetJointAngle(s1, Math.Clamp(pitchDrive * 0.45f, s1.MinRad, s1.MaxRad)); } if (visual.Joints.TryGetValue("joint.tail_s2", out var s2)) { SetJointAngle(s2, Math.Clamp(-pitchDrive * 0.65f, s2.MinRad, s2.MaxRad)); } if (visual.Joints.TryGetValue("joint.tail_s3", out var s3)) { SetJointAngle(s3, Math.Clamp(-pitchDrive * 0.55f, s3.MinRad, s3.MaxRad)); } if (visual.Joints.TryGetValue("joint.tail_elev", out var elev)) { SetJointAngle(elev, Math.Clamp(-aimPitchRad * 0.85f, elev.MinRad, elev.MaxRad)); } } /// /// Steps Breaker's real oleo gas-spring struts, 2-link scissor torque knees, and telescoping recess rams /// from real Newtonian GRF per-leg load factors (grfN / (0.5f * weightN)). /// public static void StepBreakerLinkages( VehicleVisualInstance visual, float leftLoadG, float rightLoadG, float dt) { VehicleMechanismsRecord? mech = visual.Package.Mechanisms; if (mech is null || mech.Struts.Count == 0) { return; } RigState st = visual.RigState; BreakerMechRig rig = st.BreakerRig ??= InitBreakerRig(visual, mech); if (!rig.Initialized) { return; } float strideLoadL = Math.Clamp(leftLoadG, 0f, 3.5f); float strideLoadR = Math.Clamp(rightLoadG, 0f, 3.5f); // 1. Oleo gas-spring + asymmetric orifice damping (Brokkr mechrig.Model.strut_step) if (dt > 0f) { float stepDt = Math.Clamp(dt, 0.001f, 0.05f); for (int i = 0; i < mech.Struts.Count; i++) { var sr = mech.Struts[i]; if (!rig.Struts.TryGetValue(sr.Name, out var ss)) { continue; } float load = string.Equals(sr.Side, "R", StringComparison.OrdinalIgnoreCase) ? strideLoadR : strideLoadL; float w = MathF.Tau * MathF.Max(0.1f, sr.Hertz); float column = 1.15f * MathF.Max(0.02f, sr.Travel); float h = stepDt / 16f; for (int sub = 0; sub < 16; sub++) { float ratio = Math.Clamp(1f - ss.Compression / column, 0.08f, 2f); float spring = w * w * column * (MathF.Pow(ratio, -1.3f) - 1f) / 1.3f; float c = 2f * sr.DampingRatio * w * (ss.Velocity < 0f ? 1.3f : 1f); ss.Velocity += h * (9.81f * load - spring - c * ss.Velocity); ss.Compression += h * ss.Velocity; if (ss.Compression < 0f || ss.Compression > sr.Travel) { ss.Compression = Math.Clamp(ss.Compression, 0f, sr.Travel); ss.Velocity = 0f; } } if (rig.OleoNodes.TryGetValue(sr.Dof, out var oleo)) { // LegL/R.Oleo local +Y points down toward the foot; compression slides up (-Y) oleo.Node.Transform = new Transform3D( oleo.RestLocal.Basis, oleo.RestLocal.Origin + new Vector3(0f, -ss.Compression, 0f)); } } } // 2. Scissor 2-link torque knees (LegL/R.TorqueUp, LegL/R.TorqueLow) for (int i = 0; i < rig.Scissors.Count; i++) { var sb = rig.Scissors[i]; Transform3D forkInShin = sb.OleoNode.Transform * sb.OleoForkNode.Transform; Vector3 bInShin = forkInShin * sb.BInOleoFork; Vector3 apexInShin = SolveScissorApex(sb.AInShin, bInShin, sb.OutInShin, sb.Arm); Vector3 dirUp = apexInShin - sb.AInShin; if (dirUp.LengthSquared() > 1e-8f) { Quaternion qUp = ShortestArcQuat(sb.DirUp0InShin, dirUp.Normalized()); Basis rotUp = new Basis(qUp); sb.UpperNode.Transform = new Transform3D(rotUp, sb.AInShin - rotUp * sb.AInShin) * sb.RestLocalUp; } Vector3 apexInFork = forkInShin.Inverse() * apexInShin; Vector3 dirLow = apexInFork - sb.BInOleoFork; if (dirLow.LengthSquared() > 1e-8f) { Quaternion qLow = ShortestArcQuat(sb.DirLow0InOleoFork, dirLow.Normalized()); Basis rotLow = new Basis(qLow); sb.LowerNode.Transform = new Transform3D(rotLow, sb.BInOleoFork - rotLow * sb.BInOleoFork) * sb.RestLocalLow; } } // 3. Telescoping recess hydraulic rams (LegL/R.RecessRam0/1) for (int i = 0; i < rig.Rams.Count; i++) { var rb = rig.Rams[i]; Transform3D forkInShin = rb.OleoNode.Transform * rb.OleoForkNode.Transform; Transform3D footInLug = rb.LugNode.Transform.Inverse() * forkInShin * rb.FootNode.Transform; Vector3 bInLug = footInLug * rb.BPosInFoot; Vector3 span = bInLug - rb.APosInLug; if (span.LengthSquared() > 1e-8f) { Quaternion qRam = ShortestArcQuat(rb.WantDir0InLug, span.Normalized()); rb.RamNode.Transform = new Transform3D(new Basis(qRam) * rb.RestLocalRam.Basis, rb.RestLocalRam.Origin); } } } private static BreakerMechRig InitBreakerRig(VehicleVisualInstance visual, VehicleMechanismsRecord mech) { var rig = new BreakerMechRig(); foreach (var sr in mech.Struts) { float w = MathF.Tau * MathF.Max(0.1f, sr.Hertz); float col = 1.15f * MathF.Max(0.02f, sr.Travel); float xRest = col * (1f - MathF.Pow(1f + 1.3f * 9.81f * 1.0f / (w * w * col), -1f / 1.3f)); rig.Struts[sr.Name] = new StrutState { Compression = Math.Clamp(xRest, 0f, sr.Travel), Velocity = 0f }; if (visual.GetNamedNode(sr.Dof) is { } oNode && visual.TryGetRestLocal(sr.Dof, out var oRest)) { rig.OleoNodes[sr.Dof] = (oNode, oRest); } } foreach (var sc in mech.Scissors) { string side = sc.Name.StartsWith("LegR", StringComparison.Ordinal) ? "R" : "L"; string upName = $"Leg{side}.TorqueUp"; string lowName = $"Leg{side}.TorqueLow"; string shinName = $"Leg{side}.Shin"; string oleoName = $"Leg{side}.Oleo"; string forkName = $"Leg{side}.OleoFork"; if (visual.GetNamedNode(upName) is not { } upNode || visual.GetNamedNode(lowName) is not { } lowNode || visual.GetNamedNode(shinName) is not { } shinNode || visual.GetNamedNode(oleoName) is not { } oleoNode || visual.GetNamedNode(forkName) is not { } forkNode || !visual.TryGetRestLocal(upName, out var restUp) || !visual.TryGetRestLocal(lowName, out var restLow) || !visual.TryGetRestModel(shinName, out var shinRestModel) || !visual.TryGetRestModel(forkName, out var forkRestModel) || sc.APos is null || sc.BPos is null || sc.OutDir is null) { continue; } Vector3 aModel = new(sc.APos[0], sc.APos[1], sc.APos[2]); Vector3 bModel = new(sc.BPos[0], sc.BPos[1], sc.BPos[2]); Vector3 outModel = new(sc.OutDir[0], sc.OutDir[1], sc.OutDir[2]); Transform3D shinInv = shinRestModel.Inverse(); Transform3D forkInv = forkRestModel.Inverse(); Vector3 aInShin = shinInv * aModel; Vector3 bRestInShin = shinInv * bModel; Vector3 bInFork = forkInv * bModel; Vector3 outInShin = (shinInv.Basis * outModel).Normalized(); Vector3 apex0InShin = SolveScissorApex(aInShin, bRestInShin, outInShin, sc.Arm); Vector3 apex0InFork = (forkRestModel.Inverse() * shinRestModel) * apex0InShin; Vector3 dirUp0 = (apex0InShin - aInShin).Normalized(); Vector3 dirLow0 = (apex0InFork - bInFork).Normalized(); rig.Scissors.Add(new ScissorBinding { UpperNode = upNode, LowerNode = lowNode, ShinNode = shinNode, OleoNode = oleoNode, OleoForkNode = forkNode, RestLocalUp = restUp, RestLocalLow = restLow, AInShin = aInShin, BInOleoFork = bInFork, OutInShin = outInShin, Arm = sc.Arm, DirUp0InShin = dirUp0, DirLow0InOleoFork = dirLow0 }); } foreach (var r in mech.Rams) { string side = r.Name.StartsWith("LegR", StringComparison.Ordinal) ? "R" : "L"; char idxChar = r.Name[^1]; string lugName = $"Leg{side}.RamLugA{idxChar}"; string oleoName = $"Leg{side}.Oleo"; string forkName = $"Leg{side}.OleoFork"; string footName = $"Leg{side}.Foot"; if (visual.GetNamedNode(r.Name) is not { } ramNode || visual.GetNamedNode(lugName) is not { } lugNode || visual.GetNamedNode(oleoName) is not { } oleoNode || visual.GetNamedNode(forkName) is not { } forkNode || visual.GetNamedNode(footName) is not { } footNode || !visual.TryGetRestLocal(r.Name, out var restRam) || !visual.TryGetRestModel(lugName, out var lugRestModel) || !visual.TryGetRestModel(footName, out var footRestModel) || r.BPos is null) { continue; } Vector3 bModel = new(r.BPos[0], r.BPos[1], r.BPos[2]); Vector3 aInLug = restRam.Origin; Vector3 bInLug0 = lugRestModel.Inverse() * bModel; Vector3 bInFoot = footRestModel.Inverse() * bModel; Vector3 want0 = (bInLug0 - aInLug).Normalized(); rig.Rams.Add(new RamBinding { RamNode = ramNode, LugNode = lugNode, OleoNode = oleoNode, OleoForkNode = forkNode, FootNode = footNode, RestLocalRam = restRam, APosInLug = aInLug, BPosInFoot = bInFoot, WantDir0InLug = want0 }); } rig.Initialized = rig.Struts.Count > 0; return rig; } private static Vector3 SolveScissorApex(Vector3 a, Vector3 b, Vector3 outDir, float arm) { Vector3 u = b - a; float d = u.Length(); if (d < 1e-5f) { return (a + b) * 0.5f + outDir * arm; } u /= d; Vector3 oFlat = outDir - u * outDir.Dot(u); oFlat = oFlat.LengthSquared() > 1e-6f ? oFlat.Normalized() : Vector3.Back; float h = MathF.Sqrt(MathF.Max(arm * arm - (d * 0.5f) * (d * 0.5f), 0f)); return (a + b) * 0.5f + oFlat * h; } private static void SetJointAngle(VehicleVisualInstance.BoundJoint j, float angleRad) { if (!GodotObject.IsInstanceValid(j.Node) || !float.IsFinite(angleRad)) { return; } Basis delta = new Basis(j.AxisInParent, angleRad); j.Node.Transform = new Transform3D(delta * j.RestLocal.Basis, j.RestLocal.Origin); } private static Quaternion ShortestArcQuat(Vector3 from, Vector3 to) { float dot = Math.Clamp(from.Dot(to), -1f, 1f); if (dot > 0.99999f) { return Quaternion.Identity; } if (dot < -0.99999f) { Vector3 ortho = MathF.Abs(from.X) < 0.8f ? Vector3.Right : Vector3.Up; Vector3 axis = from.Cross(ortho).Normalized(); return new Quaternion(axis, MathF.PI); } Vector3 cross = from.Cross(to); return new Quaternion(cross.X, cross.Y, cross.Z, 1f + dot).Normalized(); } private static float Sanitize(float v, float fallback, float min, float max) => float.IsFinite(v) ? Math.Clamp(v, min, max) : fallback; private static Vector3 SanitizeVec(Vector3 v) => new( float.IsFinite(v.X) ? v.X : 0f, float.IsFinite(v.Y) ? v.Y : 0f, float.IsFinite(v.Z) ? v.Z : 0f); }