Fix Cut 3b Soul Pass #1 vehicle orientation, grounding, rig, halo, and debris findings

This commit is contained in:
Meta Vens 2026-12-04 21:08:50 +01:00
commit 3e90ba2dc3
6 changed files with 750 additions and 95 deletions

View file

@ -59,6 +59,14 @@ public partial class ArenaRenderer : Node3D
public VehicleVisualInstance? GetSpectatorVisual(int spectatorId) => public VehicleVisualInstance? GetSpectatorVisual(int spectatorId) =>
_spectatorVisuals.TryGetValue(spectatorId, out var vis) ? vis.Visual : null; _spectatorVisuals.TryGetValue(spectatorId, out var vis) ? vis.Visual : null;
internal float? GetSpectatorHaloLocalY(int spectatorId) =>
_spectatorVisuals.TryGetValue(spectatorId, out var vis) && vis.HaloMesh is not null
? vis.HaloMesh.Position.Y
: null;
internal int ActiveDropVisualCount => _dropVisuals.Count;
internal int DropGroupChildCount => _dropsGroup.GetChildCount();
public override void _Ready() public override void _Ready()
{ {
_assetCache = new VehicleAssetCache(); _assetCache = new VehicleAssetCache();
@ -324,8 +332,9 @@ public partial class ArenaRenderer : Node3D
role, role,
visualScale: 1f, visualScale: 1f,
targetHalfHeight: s.Grid.Spec.HalfHeight); targetHalfHeight: s.Grid.Spec.HalfHeight);
instance.SyncMountedGear(s.Grid);
_actorsGroup.AddChild(instance.Root); _actorsGroup.AddChild(instance.Root);
vis = CreateSpectatorVisualWrapper(instance, s.Grid.Spec); vis = CreateSpectatorVisualWrapper(instance);
_spectatorVisuals[s.Id] = vis; _spectatorVisuals[s.Id] = vis;
} }
@ -441,12 +450,9 @@ public partial class ArenaRenderer : Node3D
} }
} }
private ActorVisual CreateSpectatorVisualWrapper(VehicleVisualInstance instance, ChassisSpec spec) private ActorVisual CreateSpectatorVisualWrapper(VehicleVisualInstance instance)
{ {
float modelScale = instance.Template.Package.HalfHeight > 1e-4f float haloY = MathF.Max(2.2f, instance.ComputeMountedMaxY() + 0.85f);
? spec.HalfHeight / instance.Template.Package.HalfHeight
: 1f;
float haloY = MathF.Max(2.2f, instance.Template.MaxY * modelScale - spec.HalfHeight + 0.75f);
var haloMat = new StandardMaterial3D var haloMat = new StandardMaterial3D
{ {
ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded,
@ -498,7 +504,12 @@ public partial class ArenaRenderer : Node3D
{ {
if (_dropVisuals.TryGetValue(d.Id, out var pickedNode)) if (_dropVisuals.TryGetValue(d.Id, out var pickedNode))
{ {
pickedNode.Visible = false; if (GodotObject.IsInstanceValid(pickedNode))
{
pickedNode.GetParent()?.RemoveChild(pickedNode);
pickedNode.QueueFree();
}
_dropVisuals.Remove(d.Id);
} }
continue; continue;
} }

View file

@ -14,7 +14,7 @@ public partial class DebrisSystem : Node3D
private const float Gravity = -20f; private const float Gravity = -20f;
private const float DefaultLifetime = 8.0f; private const float DefaultLifetime = 8.0f;
private const float FadeDuration = 2.0f; private const float FadeDuration = 2.0f;
private const int MaxActiveDebris = 160; private const int MaxActiveDebris = 256;
private sealed class DebrisPiece private sealed class DebrisPiece
{ {

View file

@ -416,10 +416,7 @@ public sealed class VehicleAssetCache : IDisposable
} }
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax); ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
// recoilless.glb has its 0.82m barrel extending along -Z in the exported GLB; mg_762, autocannon, gilded_lance extend along +Z. Vector3 localFwd = new Vector3(0f, 0f, 1f);
Vector3 localFwd = string.Equals(gearId, "recoilless", StringComparison.OrdinalIgnoreCase)
? new Vector3(0f, 0f, -1f)
: new Vector3(0f, 0f, 1f);
return new GearTemplate return new GearTemplate
{ {

View file

@ -73,6 +73,12 @@ public static class VehicleRigAnimator
public readonly List<RamBinding> Rams = new(); public readonly List<RamBinding> Rams = new();
} }
public sealed class WalkerFootSample
{
public required Node3D[] ChainFromModelRoot;
public required Vector3[] LocalPoints;
}
public sealed class RigState public sealed class RigState
{ {
public float WheelSpinRad; public float WheelSpinRad;
@ -89,6 +95,7 @@ public static class VehicleRigAnimator
public float ChassisRollRad; public float ChassisRollRad;
public float ElapsedSeconds; public float ElapsedSeconds;
public BreakerMechRig? BreakerRig; public BreakerMechRig? BreakerRig;
public List<WalkerFootSample>? FootSamples;
} }
public static void Update( public static void Update(
@ -96,7 +103,8 @@ public static class VehicleRigAnimator
ContenderState c, ContenderState c,
Vector3 velocity, Vector3 velocity,
Basis worldBasis, Basis worldBasis,
float dt) float dt,
bool snap = false)
{ {
float aimYawWorld = c.Yaw; float aimYawWorld = c.Yaw;
float dx = c.AimX - c.X; float dx = c.AimX - c.X;
@ -129,15 +137,20 @@ public static class VehicleRigAnimator
DeltaTime: dt, DeltaTime: dt,
IsGrounded: !c.Grid.Spec.IsVtol); IsGrounded: !c.Grid.Spec.IsVtol);
Update(visual, in input, worldBasis); Update(visual, in input, worldBasis, snap);
} }
public static void Update( public static void Update(
VehicleVisualInstance visual, VehicleVisualInstance visual,
in VehicleRigDriveInput input, in VehicleRigDriveInput input,
Basis worldBasis) Basis worldBasis,
bool snap = false)
{ {
float dt = Sanitize(input.DeltaTime, 0f, 0f, 0.1f); float dt = Sanitize(input.DeltaTime, 0f, 0f, 0.1f);
if (!snap && dt <= 0f)
{
return;
}
Vector3 vel = SanitizeVec(input.Velocity); Vector3 vel = SanitizeVec(input.Velocity);
float yaw = Sanitize(input.Yaw, 0f, -MathF.Tau * 4f, MathF.Tau * 4f); 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 aimYawWorld = Sanitize(input.AimYawWorld, yaw, -MathF.Tau * 4f, MathF.Tau * 4f);
@ -365,6 +378,8 @@ public static class VehicleRigAnimator
float dt, float dt,
float blend) float blend)
{ {
EnsureWalkerFootSamples(visual, st);
float targetAmp = Math.Clamp(horizSpeed / 6.5f + MathF.Abs(steerCmd) * 0.32f, 0f, 1f); float targetAmp = Math.Clamp(horizSpeed / 6.5f + MathF.Abs(steerCmd) * 0.32f, 0f, 1f);
st.StrideAmp += (targetAmp - st.StrideAmp) * blend; st.StrideAmp += (targetAmp - st.StrideAmp) * blend;
@ -381,52 +396,61 @@ public static class VehicleRigAnimator
case "breaker": case "breaker":
AnimateBipedLeg(visual, "LegL.Hip", "LegL.Shin", "LegL.Foot", phiL, st.StrideAmp, signX: -1f); AnimateBipedLeg(visual, "LegL.Hip", "LegL.Shin", "LegL.Foot", phiL, st.StrideAmp, signX: -1f);
AnimateBipedLeg(visual, "LegR.Hip", "LegR.Shin", "LegR.Foot", phiR, st.StrideAmp, signX: -1f); AnimateBipedLeg(visual, "LegR.Hip", "LegR.Shin", "LegR.Foot", phiR, st.StrideAmp, signX: -1f);
ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.09f); ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f, rollScale: 0.024f);
StepBreakerMechanisms(visual, st, phiL, phiR, velY, dt); StepBreakerMechanisms(visual, st, phiL, phiR, velY, dt);
ApplyWalkerFloorClearance(visual, st, "Pelvis");
break; break;
case "paladin": case "paladin":
AnimateLocalPitchLeg(visual, "LegL.Upper", "LegL.Lower", "LegL.Ankle", phiL, st.StrideAmp, hipSign: -1f, kneeSign: 1f); AnimateBipedVehicleX(visual, "LegL.Upper", "LegL.Lower", "LegL.Ankle", phiL, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.28f, kneeForwardFlexAmp: 0.08f);
AnimateLocalPitchLeg(visual, "LegR.Upper", "LegR.Lower", "LegR.Ankle", phiR, st.StrideAmp, hipSign: -1f, kneeSign: 1f); AnimateBipedVehicleX(visual, "LegR.Upper", "LegR.Lower", "LegR.Ankle", phiR, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.28f, kneeForwardFlexAmp: 0.08f);
ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.11f); ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.07f, rollScale: 0.020f);
ApplyWalkerFloorClearance(visual, st, "Pelvis");
break; break;
case "raptor": case "raptor":
AnimateLocalPitchLeg(visual, "LegL.Thigh", "LegL.Shin", "LegL.Cannon", phiL, st.StrideAmp, hipSign: 1f, kneeSign: -1f); AnimateBipedVehicleX(visual, "LegL.Thigh", "LegL.Shin", "LegL.Cannon", phiL, st.StrideAmp, hipAmp: 0.20f, kneeLiftAmp: 0.34f, kneeForwardFlexAmp: 0.22f);
AnimateLocalPitchLeg(visual, "LegR.Thigh", "LegR.Shin", "LegR.Cannon", phiR, st.StrideAmp, hipSign: 1f, kneeSign: -1f); AnimateBipedVehicleX(visual, "LegR.Thigh", "LegR.Shin", "LegR.Cannon", phiR, st.StrideAmp, hipAmp: 0.20f, kneeLiftAmp: 0.34f, kneeForwardFlexAmp: 0.22f);
ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.10f); ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f, rollScale: 0.020f);
ApplyWalkerFloorClearance(visual, st, "Pelvis");
break; break;
case "spectre": case "spectre":
AnimateLocalPitchLeg(visual, "LegL.Thigh", "LegL.Shin", "LegL.Cannon", phiL, st.StrideAmp, hipSign: 1f, kneeSign: -1f); AnimateBipedVehicleX(visual, "LegL.Thigh", "LegL.Shin", "LegL.Cannon", phiL, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.32f, kneeForwardFlexAmp: 0f);
AnimateLocalPitchLeg(visual, "LegR.Thigh", "LegR.Shin", "LegR.Cannon", phiR, st.StrideAmp, hipSign: 1f, kneeSign: -1f); AnimateBipedVehicleX(visual, "LegR.Thigh", "LegR.Shin", "LegR.Cannon", phiR, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.32f, kneeForwardFlexAmp: 0f);
ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.08f); ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f, rollScale: 0.020f);
ApplyWalkerFloorClearance(visual, st, "Pelvis");
break; break;
case "kestrel": case "kestrel":
// Kestrel leg meshes are baked under Pelvis; animate Pelvis stride tilt/bob + Torso.pose counter-sway // Kestrel leg meshes are baked under Pelvis; animate Pelvis stride bob/sway with floor clearance
ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.09f); ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.07f, rollScale: 0.024f);
ApplyWalkerFloorClearance(visual, st, "Pelvis");
break; break;
case "manticore": case "manticore":
AnimateLocalPitchLeg(visual, "LegFL.S1", "LegFL.S2", "FootFL", phiL, st.StrideAmp * 0.85f, hipSign: 1f, kneeSign: -1f); AnimateManticoreLeg(visual, "LegFL.S1", "LegFL.S2", "FootFL", phiL, st.StrideAmp, isFront: true);
AnimateLocalPitchLeg(visual, "LegBR.S1", "LegBR.S2", "FootBR", phiL, st.StrideAmp * 0.85f, hipSign: 1f, kneeSign: -1f); AnimateManticoreLeg(visual, "LegBR.S1", "LegBR.S2", "FootBR", phiL, st.StrideAmp, isFront: false);
AnimateLocalPitchLeg(visual, "LegFR.S1", "LegFR.S2", "FootFR", phiR, st.StrideAmp * 0.85f, hipSign: 1f, kneeSign: -1f); AnimateManticoreLeg(visual, "LegFR.S1", "LegFR.S2", "FootFR", phiR, st.StrideAmp, isFront: true);
AnimateLocalPitchLeg(visual, "LegBL.S1", "LegBL.S2", "FootBL", phiR, st.StrideAmp * 0.85f, hipSign: 1f, kneeSign: -1f); AnimateManticoreLeg(visual, "LegBL.S1", "LegBL.S2", "FootBL", phiR, st.StrideAmp, isFront: false);
ApplyPelvisBob(visual, "Hull", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f); ApplyPelvisBob(visual, "Hull", st.StridePhaseRad, st.StrideAmp, bobScale: 0.04f, rollScale: 0.018f);
ApplyWalkerFloorClearance(visual, st, "Hull");
AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blend); AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blend);
break; break;
case "bastion": case "bastion":
AnimateLocalPitchLeg(visual, "Thigh.fl", "Shin.fl", "Ankle.fl", phiL, st.StrideAmp * 0.7f, hipSign: 1f, kneeSign: -1f); AnimateBastionLeg(visual, "Thigh.fl", "Shin.fl", "Ankle.fl", phiL, st.StrideAmp, isFront: true);
AnimateLocalPitchLeg(visual, "Thigh.rr", "Shin.rr", "Ankle.rr", phiL, st.StrideAmp * 0.7f, hipSign: 1f, kneeSign: -1f); AnimateBastionLeg(visual, "Thigh.rr", "Shin.rr", "Ankle.rr", phiL, st.StrideAmp, isFront: false);
AnimateLocalPitchLeg(visual, "Thigh.fr", "Shin.fr", "Ankle.fr", phiR, st.StrideAmp * 0.7f, hipSign: 1f, kneeSign: -1f); AnimateBastionLeg(visual, "Thigh.fr", "Shin.fr", "Ankle.fr", phiR, st.StrideAmp, isFront: true);
AnimateLocalPitchLeg(visual, "Thigh.rl", "Shin.rl", "Ankle.rl", phiR, st.StrideAmp * 0.7f, hipSign: 1f, kneeSign: -1f); AnimateBastionLeg(visual, "Thigh.rl", "Shin.rl", "Ankle.rl", phiR, st.StrideAmp, isFront: false);
ApplyPelvisBob(visual, "Trunk", st.StridePhaseRad, st.StrideAmp, bobScale: 0.07f); ApplyPelvisBob(visual, "Trunk", st.StridePhaseRad, st.StrideAmp, bobScale: 0.05f, rollScale: 0.012f);
ApplyWalkerFloorClearance(visual, st, "Trunk");
break; break;
} }
} }
private static float SwingLift(float phase) => MathF.Max(0f, MathF.Cos(phase));
private static void AnimateBipedLeg( private static void AnimateBipedLeg(
VehicleVisualInstance visual, VehicleVisualInstance visual,
string hipName, string hipName,
@ -445,23 +469,71 @@ public static class VehicleRigAnimator
RotateVehicleAxis(visual, footName, Vector3.Right, footAng * signX); RotateVehicleAxis(visual, footName, Vector3.Right, footAng * signX);
} }
private static void AnimateLocalPitchLeg( private static void AnimateBipedVehicleX(
VehicleVisualInstance visual, VehicleVisualInstance visual,
string thighName, string thighName,
string shinName, string shinName,
string footName, string footName,
float phase, float phase,
float amp, float amp,
float hipSign, float hipAmp,
float kneeSign) float kneeLiftAmp,
float kneeForwardFlexAmp)
{ {
float hipAng = MathF.Sin(phase) * 0.28f * amp * hipSign; float hipAng = -MathF.Sin(phase) * hipAmp * amp;
float kneeAng = MathF.Max(0f, -MathF.Cos(phase)) * 0.34f * amp * kneeSign; float kneeAng = (SwingLift(phase) * kneeLiftAmp + MathF.Max(0f, MathF.Sin(phase)) * kneeForwardFlexAmp) * amp;
float footAng = -(hipAng + kneeAng) * 0.45f; float footAng = -(hipAng + kneeAng);
RotateLocalX(visual, thighName, hipAng); RotateVehicleAxis(visual, thighName, Vector3.Right, hipAng);
RotateLocalX(visual, shinName, kneeAng); RotateVehicleAxis(visual, shinName, Vector3.Right, kneeAng);
RotateLocalX(visual, footName, footAng); RotateVehicleAxis(visual, footName, Vector3.Right, footAng);
}
private static void AnimateManticoreLeg(
VehicleVisualInstance visual,
string s1Name,
string s2Name,
string footName,
float phase,
float amp,
bool isFront)
{
float s2Ang = -MathF.Sin(phase) * 0.22f * amp;
float liftSign = isFront ? -1f : 1f;
float s1Ang = SwingLift(phase) * 0.26f * amp * liftSign;
float footAng = -(s1Ang + s2Ang);
RotateVehicleAxis(visual, s1Name, Vector3.Right, s1Ang);
RotateVehicleAxis(visual, s2Name, Vector3.Right, s2Ang);
RotateVehicleAxis(visual, footName, Vector3.Right, footAng);
}
private static void AnimateBastionLeg(
VehicleVisualInstance visual,
string thighName,
string shinName,
string ankleName,
float phase,
float amp,
bool isFront)
{
float thAng;
float shAng;
if (isFront)
{
thAng = -MathF.Sin(phase) * 0.16f * amp;
shAng = -SwingLift(phase) * 0.14f * amp;
}
else
{
thAng = (MathF.Max(0f, -MathF.Sin(phase)) * 0.14f + SwingLift(phase) * 0.10f) * amp;
shAng = (-MathF.Sin(phase) * 0.16f - SwingLift(phase) * 0.16f) * amp;
}
float anAng = -(thAng + shAng);
RotateVehicleAxis(visual, thighName, Vector3.Right, thAng);
RotateVehicleAxis(visual, shinName, Vector3.Right, shAng);
RotateVehicleAxis(visual, ankleName, Vector3.Right, anAng);
} }
private static void ApplyPelvisBob( private static void ApplyPelvisBob(
@ -469,7 +541,8 @@ public static class VehicleRigAnimator
string rootNodeName, string rootNodeName,
float phase, float phase,
float amp, float amp,
float bobScale) float bobScale,
float rollScale = 0.024f)
{ {
if (visual.GetNamedNode(rootNodeName) is not { } node || if (visual.GetNamedNode(rootNodeName) is not { } node ||
!visual.TryGetRestLocal(rootNodeName, out var rest)) !visual.TryGetRestLocal(rootNodeName, out var rest))
@ -477,8 +550,8 @@ public static class VehicleRigAnimator
return; return;
} }
float bobY = (MathF.Abs(MathF.Sin(phase)) - 0.5f) * bobScale * amp; float bobY = MathF.Abs(MathF.Sin(phase)) * bobScale * amp;
float swayRoll = MathF.Cos(phase) * 0.032f * amp; float swayRoll = MathF.Cos(phase) * rollScale * amp;
Basis roll = new Basis(Vector3.Back, swayRoll); Basis roll = new Basis(Vector3.Back, swayRoll);
node.Transform = new Transform3D(roll * rest.Basis, rest.Origin + new Vector3(0f, bobY, 0f)); node.Transform = new Transform3D(roll * rest.Basis, rest.Origin + new Vector3(0f, bobY, 0f));
} }
@ -543,40 +616,43 @@ public static class VehicleRigAnimator
float strideLoadR = 1.0f + 0.42f * MathF.Sin(phiR) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f); float strideLoadR = 1.0f + 0.42f * MathF.Sin(phiR) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f);
// 1. Oleo gas-spring + asymmetric orifice damping (Brokkr mechrig.Model.strut_step) // 1. Oleo gas-spring + asymmetric orifice damping (Brokkr mechrig.Model.strut_step)
float stepDt = Math.Clamp(dt, 0.001f, 0.05f); if (dt > 0f)
for (int i = 0; i < mech.Struts.Count; i++)
{ {
var sr = mech.Struts[i]; float stepDt = Math.Clamp(dt, 0.001f, 0.05f);
if (!rig.Struts.TryGetValue(sr.Name, out var ss)) for (int i = 0; i < mech.Struts.Count; i++)
{ {
continue; var sr = mech.Struts[i];
} if (!rig.Struts.TryGetValue(sr.Name, out var ss))
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); continue;
ss.Velocity = 0f;
} }
}
if (rig.OleoNodes.TryGetValue(sr.Dof, out var oleo)) float load = string.Equals(sr.Side, "R", StringComparison.OrdinalIgnoreCase) ? strideLoadR : strideLoadL;
{ float w = MathF.Tau * MathF.Max(0.1f, sr.Hertz);
// LegL/R.Oleo local +Y points down toward the foot; compression slides up (-Y) float column = 1.15f * MathF.Max(0.02f, sr.Travel);
oleo.Node.Transform = new Transform3D( float h = stepDt / 16f;
oleo.RestLocal.Basis,
oleo.RestLocal.Origin + new Vector3(0f, -ss.Compression, 0f)); 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));
}
} }
} }
@ -791,15 +867,186 @@ public static class VehicleRigAnimator
node.Transform = new Transform3D(delta * rest.Basis, rest.Origin); node.Transform = new Transform3D(delta * rest.Basis, rest.Origin);
} }
private static void RotateLocalX(VehicleVisualInstance visual, string nodeName, float angleRad) private static void EnsureWalkerFootSamples(VehicleVisualInstance visual, RigState st)
{ {
if (visual.GetNamedNode(nodeName) is not { } node || if (st.FootSamples is not null)
!visual.TryGetRestLocal(nodeName, out var rest))
{ {
return; return;
} }
Basis delta = new Basis(Vector3.Right, angleRad);
node.Transform = new Transform3D(rest.Basis * delta, rest.Origin); var list = new List<WalkerFootSample>();
var stack = new List<Node3D>();
float cutoffY = visual.Template.MinY + 0.75f;
int count = visual.ModelRoot.GetChildCount();
for (int i = 0; i < count; i++)
{
CollectFootSamplesRecursive(visual.ModelRoot.GetChild(i), Transform3D.Identity, cutoffY, stack, list);
}
st.FootSamples = list;
}
private static readonly Vector3[] FootSupportDirs =
{
new(0f, -1f, 0f),
new(0.45f, -1f, 0f),
new(-0.45f, -1f, 0f),
new(0f, -1f, 0.45f),
new(0f, -1f, -0.45f),
new(0.45f, -1f, 0.45f),
new(0.45f, -1f, -0.45f),
new(-0.45f, -1f, 0.45f),
new(-0.45f, -1f, -0.45f),
};
private static void CollectFootSamplesRecursive(
Node cur,
Transform3D parentToModel,
float cutoffY,
List<Node3D> stack,
List<WalkerFootSample> list)
{
Transform3D toModel = parentToModel;
bool pushed = false;
if (cur is Node3D n3d)
{
toModel = parentToModel * n3d.Transform;
stack.Add(n3d);
pushed = true;
}
if (cur is MeshInstance3D mi && mi.Mesh is { } mesh)
{
Aabb aabb = mesh.GetAabb();
float aabbMinY = float.PositiveInfinity;
for (int c = 0; c < 8; c++)
{
Vector3 corner = aabb.Position + new Vector3(
(c & 1) != 0 ? aabb.Size.X : 0f,
(c & 2) != 0 ? aabb.Size.Y : 0f,
(c & 4) != 0 ? aabb.Size.Z : 0f);
float wy = (toModel * corner).Y;
if (wy < aabbMinY)
{
aabbMinY = wy;
}
}
if (aabbMinY < cutoffY)
{
var bestPts = new Vector3[FootSupportDirs.Length];
var bestDots = new float[FootSupportDirs.Length];
for (int d = 0; d < FootSupportDirs.Length; d++)
{
bestDots[d] = float.NegativeInfinity;
}
bool anyVert = false;
int surfCount = mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arrays = mesh.SurfaceGetArrays(s);
if (arrays.Count <= (int)Mesh.ArrayType.Vertex ||
arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
{
continue;
}
Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
for (int v = 0; v < verts.Length; v++)
{
Vector3 localPt = verts[v];
Vector3 mPt = toModel * localPt;
for (int d = 0; d < FootSupportDirs.Length; d++)
{
float score = mPt.Dot(FootSupportDirs[d]);
if (score > bestDots[d])
{
bestDots[d] = score;
bestPts[d] = localPt;
}
}
anyVert = true;
}
}
if (anyVert)
{
var unique = new List<Vector3>(FootSupportDirs.Length);
for (int d = 0; d < bestPts.Length; d++)
{
bool dup = false;
for (int u = 0; u < unique.Count; u++)
{
if ((unique[u] - bestPts[d]).LengthSquared() < 1e-6f)
{
dup = true;
break;
}
}
if (!dup)
{
unique.Add(bestPts[d]);
}
}
list.Add(new WalkerFootSample
{
ChainFromModelRoot = stack.ToArray(),
LocalPoints = unique.ToArray()
});
}
}
}
int childCount = cur.GetChildCount();
for (int i = 0; i < childCount; i++)
{
CollectFootSamplesRecursive(cur.GetChild(i), toModel, cutoffY, stack, list);
}
if (pushed)
{
stack.RemoveAt(stack.Count - 1);
}
}
private static void ApplyWalkerFloorClearance(VehicleVisualInstance visual, RigState st, string rootNodeName)
{
var samples = st.FootSamples;
if (samples is null || samples.Count == 0 || visual.GetNamedNode(rootNodeName) is not { } rootNode)
{
return;
}
float minModelY = float.PositiveInfinity;
for (int i = 0; i < samples.Count; i++)
{
var s = samples[i];
Transform3D toModel = Transform3D.Identity;
for (int k = 0; k < s.ChainFromModelRoot.Length; k++)
{
toModel *= s.ChainFromModelRoot[k].Transform;
}
for (int p = 0; p < s.LocalPoints.Length; p++)
{
float y = (toModel * s.LocalPoints[p]).Y;
if (y < minModelY)
{
minModelY = y;
}
}
}
float restMinY = visual.Template.MinY;
if (float.IsFinite(minModelY) && minModelY < restMinY)
{
Vector3 liftInModel = new Vector3(0f, restMinY - minModelY, 0f);
Vector3 liftInParent = liftInModel;
if (rootNode.GetParent() is Node3D p3 && visual.TryGetRestModel(p3, out var pModel))
{
liftInParent = pModel.Basis.Orthonormalized().Inverse() * liftInModel;
}
rootNode.Transform = new Transform3D(rootNode.Transform.Basis, rootNode.Transform.Origin + liftInParent);
}
} }
private static Quaternion ShortestArcQuat(Vector3 from, Vector3 to) private static Quaternion ShortestArcQuat(Vector3 from, Vector3 to)

View file

@ -130,7 +130,7 @@ public sealed class VehicleVisualInstance
{ {
var template = cache.GetOrLoadVehicle(chassisId); var template = cache.GetOrLoadVehicle(chassisId);
var pkg = template.Package; var pkg = template.Package;
float halfHeight = targetHalfHeight ?? pkg.HalfHeight; float halfHeight = targetHalfHeight ?? (pkg.HalfHeight * visualScale);
float effectiveScale = targetHalfHeight.HasValue && pkg.HalfHeight > 1e-4f float effectiveScale = targetHalfHeight.HasValue && pkg.HalfHeight > 1e-4f
? visualScale * (targetHalfHeight.Value / pkg.HalfHeight) ? visualScale * (targetHalfHeight.Value / pkg.HalfHeight)
: visualScale; : visualScale;
@ -524,7 +524,7 @@ public sealed class VehicleVisualInstance
desiredGearFwd = rightX.Cross(upOut).Normalized(); desiredGearFwd = rightX.Cross(upOut).Normalized();
var desiredModelBasis = new Basis(rightX, upOut, desiredGearFwd); var desiredModelBasis = new Basis(rightX, upOut, desiredGearFwd);
// If the gear GLB's own muzzle points along -Z (recoilless), rotate 180 deg around Y // If the gear GLB's own forward points along -Z, rotate 180 deg around Y
if (gearTemplate.LocalModelForward.Z < 0f) if (gearTemplate.LocalModelForward.Z < 0f)
{ {
desiredModelBasis *= new Basis(Vector3.Up, MathF.PI); desiredModelBasis *= new Basis(Vector3.Up, MathF.PI);
@ -750,4 +750,78 @@ public sealed class VehicleVisualInstance
CollectNodeTransforms(cur.GetChild(i), xf, map); CollectNodeTransforms(cur.GetChild(i), xf, map);
} }
} }
/// <summary>
/// Computes the highest rendered vertex Y in <see cref="Root"/> local space across the hull
/// and all currently mounted gear meshes.
/// </summary>
public float ComputeMountedMaxY()
{
float maxY = float.NegativeInfinity;
AccumulateMaxYRecursive(ModelRoot, Transform3D.Identity, ref maxY);
if (!float.IsFinite(maxY))
{
return ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y;
}
return maxY;
}
private static void AccumulateMaxYRecursive(Node cur, Transform3D parentToRoot, ref float maxY)
{
Transform3D toRoot = parentToRoot;
if (cur is Node3D n3d)
{
if (!n3d.Visible)
{
return;
}
toRoot = parentToRoot * n3d.Transform;
}
if (cur is MeshInstance3D mi && mi.Mesh is { } mesh)
{
int surfCount = mesh.GetSurfaceCount();
bool foundVerts = false;
for (int s = 0; s < surfCount; s++)
{
var arrays = mesh.SurfaceGetArrays(s);
if (arrays.Count > (int)Mesh.ArrayType.Vertex &&
arrays[(int)Mesh.ArrayType.Vertex].VariantType == Variant.Type.PackedVector3Array)
{
Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
for (int v = 0; v < verts.Length; v++)
{
float wy = (toRoot * verts[v]).Y;
if (wy > maxY)
{
maxY = wy;
}
}
foundVerts = true;
}
}
if (!foundVerts)
{
Aabb aabb = mesh.GetAabb();
for (int c = 0; c < 8; c++)
{
Vector3 corner = aabb.Position + new Vector3(
(c & 1) != 0 ? aabb.Size.X : 0f,
(c & 2) != 0 ? aabb.Size.Y : 0f,
(c & 4) != 0 ? aabb.Size.Z : 0f);
float wy = (toRoot * corner).Y;
if (wy > maxY)
{
maxY = wy;
}
}
}
}
int childCount = cur.GetChildCount();
for (int i = 0; i < childCount; i++)
{
AccumulateMaxYRecursive(cur.GetChild(i), toRoot, ref maxY);
}
}
} }

View file

@ -562,19 +562,29 @@ public partial class Smoke : Node
mountedMeshes++; mountedMeshes++;
if (m.Spec.Kind == HardpointKind.Weapon) if (m.Spec.Kind == HardpointKind.Weapon)
{ {
var gTemplate = cache.GetOrLoadGear(m.Spec.Id switch (string frontPart, string rearPart) = m.Spec.Id switch
{ {
"mg_762" or "pd_flak" => "mg_762", "mg_762" or "pd_flak" => ("barrel_inner", "receiver"),
"autocannon" or "flak" => "autocannon", "autocannon" or "flak" => ("muzzle_brake_L", "gun_housing"),
"recoilless" => "recoilless", "recoilless" => ("sight_tube", "breech_band"),
_ => "gilded_lance" _ => ("condenser_ring_2", "ivory_cowl")
}); };
// Anchor's model-space transform * gNode local transform * gear's LocalModelForward gives muzzle dir in vehicle space (+Z forward) Vector3? frontC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, frontPart);
var pkgHp = System.Linq.Enumerable.First(pkg.Hardpoints, h => h.Id == m.HardpointId); Vector3? rearC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, rearPart);
Basis anchorBasis = vis.Template.Anchors[pkgHp.AnchorId].ModelSpaceTransform.Basis.Orthonormalized(); Check(frontC.HasValue && rearC.HasValue,
Vector3 muzzleVeh = (anchorBasis * (gNode.Basis.Orthonormalized() * gTemplate.LocalModelForward)).Normalized(); $"Missing weapon submeshes '{frontPart}'/'{rearPart}' on '{spec.Id}.{m.HardpointId}' ({m.Spec.Id})");
Check(muzzleVeh.Z > 0.75f, if (frontC.HasValue && rearC.HasValue)
$"Expected weapon '{m.Spec.Id}' on '{spec.Id}.{m.HardpointId}' to point forward (+Z), got muzzle={muzzleVeh}"); {
Vector3 muzzleDir = (frontC.Value - rearC.Value).Normalized();
if (m.Spec.Id == "recoilless")
{
GD.Print($"SMOKE INFO: recoilless {spec.Id}.{m.HardpointId} sight_tube={frontC.Value} breech={rearC.Value} dir={muzzleDir}");
Check(frontC.Value.Z > rearC.Value.Z + 0.20f,
$"Expected recoilless sight_tube (+Z) ahead of breech_band on '{spec.Id}.{m.HardpointId}', got sight={frontC.Value}, breech={rearC.Value}");
}
Check(muzzleDir.Z > 0.75f,
$"Expected weapon '{m.Spec.Id}' on '{spec.Id}.{m.HardpointId}' mesh geometry to point forward (+Z), got dir={muzzleDir}");
}
} }
} }
} }
@ -700,6 +710,216 @@ public partial class Smoke : Node
debris.QueueFree(); debris.QueueFree();
} }
// 4. Full Paladin hull + gear strip retains >160 pieces without mid-air eviction (MaxActiveDebris = 256)
{
var debris = new DebrisSystem { Name = "SmokePaladinDebrisTest" };
AddChild(debris);
var palGrid = Catalog.CreateWithDefaultLoadout(Catalog.Paladin);
var palVis = VehicleVisualInstance.Create(cache, "paladin", VehicleVisualRole.Player);
AddChild(palVis.Root);
palVis.SyncMountedGear(palGrid);
for (int cy = 0; cy < palGrid.Spec.Height; cy++)
{
for (int cx = 0; cx < palGrid.Spec.Width; cx++)
{
palGrid.Armor[cx, cy] = 0f;
}
}
palVis.SyncDamageAndHeat(palGrid, debris, new Vector3(1f, 0f, 3f));
GD.Print($"SMOKE INFO: Full Paladin strip debris.ActiveCount={debris.ActiveCount}");
Check(debris.ActiveCount > 160 && debris.ActiveCount <= 256,
$"Expected full Paladin strip to retain >160 debris pieces under 256 cap, got {debris.ActiveCount}");
palVis.Root.QueueFree();
debris.QueueFree();
}
// 5. All 15 ChassisDrop salvage wrecks ground within 0.05m of terrain & PickedUp frees drop nodes cleanly
{
var drops = _main.Session.State.GroundDrops;
int baseCount = drops.Count;
_main.Arena.Sync(_main.Session, 1.0f, 1f / 60f);
int dropNodesBefore = _main.Arena.DropGroupChildCount;
int trackedBefore = _main.Arena.ActiveDropVisualCount;
int nextId = 90000;
var added = new List<GroundDrop>(Catalog.AllChassis.Count);
float maxGroundErr = 0f;
for (int i = 0; i < Catalog.AllChassis.Count; i++)
{
var spec = Catalog.AllChassis[i];
float dx = -80f + i * 11f;
float dz = -40f;
var d = new GroundDrop(nextId++, dx, dz, spec, null);
drops.Add(d);
added.Add(d);
}
_main.Arena.Sync(_main.Session, 1.0f, 1f / 60f);
Check(_main.Arena.ActiveDropVisualCount == trackedBefore + added.Count,
$"Expected {trackedBefore + added.Count} tracked drop visuals, got {_main.Arena.ActiveDropVisualCount}");
for (int i = 0; i < added.Count; i++)
{
var d = added[i];
Node3D? dropNode = _main.Arena.GetNodeOrNull<Node3D>($"GroundDrops/Drop_{d.Id}");
Check(dropNode is not null, $"Missing Drop_{d.Id} node for ChassisDrop '{d.Chassis!.Id}'");
if (dropNode is not null)
{
Node3D? actorNode = dropNode.GetNodeOrNull<Node3D>($"Actor_{d.Chassis!.Id}");
Check(actorNode is not null, $"Missing Actor_{d.Chassis!.Id} under Drop_{d.Id}");
if (actorNode is not null)
{
float minWorldY = ComputeSubtreeMinWorldY(actorNode, dropNode.Position.Y);
float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z);
float err = MathF.Abs(minWorldY - terrainY);
if (err > maxGroundErr) maxGroundErr = err;
Check(err <= 0.05f,
$"ChassisDrop '{d.Chassis!.Id}' buried/floating: minWorldY={minWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m");
}
}
}
GD.Print($"SMOKE INFO: ChassisDrop max ground err={maxGroundErr:F4}m across {added.Count} chassis");
for (int i = 0; i < added.Count; i++)
{
added[i].PickedUp = true;
}
_main.Arena.Sync(_main.Session, 1.1f, 1f / 60f);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
Check(_main.Arena.ActiveDropVisualCount == trackedBefore,
$"Expected picked-up drops removed from _dropVisuals ({trackedBefore}), got {_main.Arena.ActiveDropVisualCount}");
Check(_main.Arena.DropGroupChildCount == dropNodesBefore,
$"Expected picked-up drop nodes freed from GroundDrops ({dropNodesBefore}), got {_main.Arena.DropGroupChildCount}");
drops.RemoveRange(baseCount, added.Count);
}
// 6. All 7 walkers stay grounded (minVertexY - restMinY >= -0.05m) and swing along +Z/-Z through a full stride cycle
{
var walkerChecks = new (string Id, string? FootNode, string? PelvisNode, bool CheckSagittal)[]
{
("raptor", "LegL.Cannon", "Pelvis", true),
("spectre", "LegL.Cannon", "Pelvis", true),
("manticore", "FootFL", "Hull", true),
("bastion", "Ankle.fl", "Trunk", true),
("breaker", "LegL.Foot", "Pelvis", true),
("paladin", "LegL.Ankle", "Pelvis", true),
("kestrel", null, null, false),
};
foreach (var (wId, footNodeName, pelvisNodeName, checkSagittal) in walkerChecks)
{
var vis = VehicleVisualInstance.Create(cache, wId, VehicleVisualRole.Player);
float restMinY = ComputeSubtreeMinWorldY(vis.ModelRoot, 0f, relativeToModelRoot: true);
float worstRelMinY = float.PositiveInfinity;
float minFootZ = float.PositiveInfinity, maxFootZ = float.NegativeInfinity;
float minFootX = float.PositiveInfinity, maxFootX = float.NegativeInfinity;
Node3D? footNode = footNodeName is not null ? vis.GetNamedNode(footNodeName) : null;
Node3D? pelvisNode = pelvisNodeName is not null ? vis.GetNamedNode(pelvisNodeName) : null;
var walkInp = new VehicleRigDriveInput(
new Vector3(0f, 0f, 8f), 0f, 0f, 0f, 0f, 1f, 0f, 1f, 0.05f);
for (int step = 0; step < 48; step++)
{
VehicleRigAnimator.Update(vis, in walkInp, Basis.Identity);
float curMinY = ComputeSubtreeMinWorldY(vis.ModelRoot, 0f, relativeToModelRoot: true);
float relMinY = curMinY - restMinY;
if (relMinY < worstRelMinY) worstRelMinY = relMinY;
Check(!float.IsNaN(curMinY), $"NaN vertex Y on walker '{wId}' step {step}");
if (footNode is not null && pelvisNode is not null)
{
Vector3 fPos = TransformPointToAncestor(footNode, pelvisNode, Vector3.Zero);
if (fPos.Z < minFootZ) minFootZ = fPos.Z;
if (fPos.Z > maxFootZ) maxFootZ = fPos.Z;
if (fPos.X < minFootX) minFootX = fPos.X;
if (fPos.X > maxFootX) maxFootX = fPos.X;
}
}
float zSpan = footNode is not null ? maxFootZ - minFootZ : 0f;
float xSpan = footNode is not null ? maxFootX - minFootX : 0f;
GD.Print($"SMOKE INFO: Walker {wId} stride minFootY={worstRelMinY:F4}m zSpan={zSpan:F3}m xSpan={xSpan:F3}m");
Check(worstRelMinY >= -0.05f,
$"Walker '{wId}' foot plunged below rest floor: minRelY={worstRelMinY:F4}m");
if (checkSagittal && footNode is not null)
{
Check(zSpan > 0.12f,
$"Expected walker '{wId}' foot '{footNodeName}' to stride along Z > 0.12m, got {zSpan:F3}m");
Check(xSpan < 0.03f,
$"Expected walker '{wId}' foot '{footNodeName}' to swing cleanly in sagittal plane (xSpan < 0.03m), got {xSpan:F3}m");
}
vis.Root.QueueFree();
}
}
// 7. VehicleRigAnimator.Update with dt == 0 is a strict no-op unless snap == true
{
var anvilVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.Player);
var driveInp = new VehicleRigDriveInput(
new Vector3(0f, 0f, 6f), 0f, 0.2f, 5f, 0.2f, 0.5f, 0f, 1f, 1f / 60f);
for (int s = 0; s < 10; s++)
{
VehicleRigAnimator.Update(anvilVis, in driveInp, Basis.Identity);
}
var beforeTransforms = new Dictionary<string, Transform3D>();
foreach (var (jid, j) in anvilVis.Joints)
{
beforeTransforms[jid] = j.Node.Transform;
}
var zeroDtInp = new VehicleRigDriveInput(
new Vector3(0f, 0f, 12f), 0f, 1.9f, 35f, -1f, 1f, 0f, 1f, 0f);
VehicleRigAnimator.Update(anvilVis, in zeroDtInp, Basis.Identity);
float maxDelta = 0f;
foreach (var (jid, before) in beforeTransforms)
{
Transform3D after = anvilVis.Joints[jid].Node.Transform;
float dOrigin = (after.Origin - before.Origin).Length();
float dRot = before.Basis.GetRotationQuaternion().AngleTo(after.Basis.GetRotationQuaternion());
maxDelta = MathF.Max(maxDelta, MathF.Max(dOrigin, dRot));
}
VehicleRigAnimator.Update(anvilVis, in zeroDtInp, Basis.Identity, snap: true);
Transform3D snapped = anvilVis.Joints["joint.turret_yaw"].Node.Transform;
float snapDelta = beforeTransforms["joint.turret_yaw"].Basis.GetRotationQuaternion()
.AngleTo(snapped.Basis.GetRotationQuaternion());
GD.Print($"SMOKE INFO: Rig dt=0 maxDelta={maxDelta:F6} snapDelta={snapDelta:F4}rad");
Check(maxDelta < 1e-6f, $"Expected dt == 0 Update (snap=false) to be a strict no-op, got maxDelta={maxDelta:F6}");
Check(snapDelta > 0.5f, $"Expected dt == 0 Update (snap=true) to snap turret cleanly, got snapDelta={snapDelta:F4}rad");
anvilVis.Root.QueueFree();
}
// 8. Spectator halo sits >= 0.75m above mounted dorsal gear (including Patron with turbo_core)
{
_main.Arena.Sync(_main.Session, 1.5f, 1f / 60f);
bool sawPatron = false;
foreach (var s in _main.Session.State.Spectators.Spectators)
{
if (!s.Alive) continue;
var vis = _main.Arena.GetSpectatorVisual(s.Id);
float? haloY = _main.Arena.GetSpectatorHaloLocalY(s.Id);
Check(vis is not null && haloY.HasValue, $"Missing spectator visual/halo for spectator #{s.Id}");
if (vis is not null && haloY.HasValue)
{
float topY = vis.ComputeMountedMaxY();
float clearance = haloY.Value - topY;
if (s.Tier == SpectatorTier.Patron)
{
sawPatron = true;
GD.Print($"SMOKE INFO: Spectator #{s.Id} ({s.Tier}/{s.Grid.Spec.Id}) mountedMaxY={topY:F3}m haloY={haloY.Value:F3}m clearance={clearance:F3}m");
}
Check(clearance >= 0.74f,
$"Spectator #{s.Id} ({s.Tier}/{s.Grid.Spec.Id}) halo clearance < 0.74m: topY={topY:F3}m haloY={haloY.Value:F3}m clearance={clearance:F3}m");
}
}
Check(sawPatron, "Expected at least one alive Patron spectator in arena");
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
} }
@ -738,6 +958,112 @@ public partial class Smoke : Node
return count; return count;
} }
private static Vector3 TransformPointToAncestor(Node3D node, Node3D ancestor, Vector3 localPt)
{
Transform3D xf = Transform3D.Identity;
for (Node? cur = node; cur is Node3D n3d && cur != ancestor; cur = cur.GetParent())
{
xf = n3d.Transform * xf;
}
return xf * localPt;
}
private static Vector3? ComputeSubtreeVertexCentroidInAncestor(Node3D subRoot, Node3D ancestor, string partName)
{
Vector3 sum = Vector3.Zero;
int count = 0;
AccumulatePartCentroidRecursive(subRoot, ancestor, partName, ref sum, ref count);
return count > 0 ? sum / count : null;
}
private static void AccumulatePartCentroidRecursive(
Node cur,
Node3D ancestor,
string partName,
ref Vector3 sum,
ref int count)
{
if (cur is MeshInstance3D mi && mi.Mesh is { } mesh &&
mi.Name.ToString().Equals(partName, StringComparison.OrdinalIgnoreCase))
{
Transform3D toAnc = Transform3D.Identity;
for (Node? p = mi; p is Node3D n3d && p != ancestor; p = p.GetParent())
{
toAnc = n3d.Transform * toAnc;
}
int surfCount = mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arrays = mesh.SurfaceGetArrays(s);
if (arrays.Count <= (int)Mesh.ArrayType.Vertex ||
arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
{
continue;
}
Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
for (int v = 0; v < verts.Length; v++)
{
sum += toAnc * verts[v];
count++;
}
}
}
for (int i = 0; i < cur.GetChildCount(); i++)
{
AccumulatePartCentroidRecursive(cur.GetChild(i), ancestor, partName, ref sum, ref count);
}
}
private static float ComputeSubtreeMinWorldY(Node3D root, float baseWorldY, bool relativeToModelRoot = false)
{
float minY = float.PositiveInfinity;
if (relativeToModelRoot)
{
Transform3D id = Transform3D.Identity;
for (int i = 0; i < root.GetChildCount(); i++)
{
AccumulateMinYRecursive(root.GetChild(i), id, ref minY);
}
}
else
{
AccumulateMinYRecursive(root, new Transform3D(Basis.Identity, new Vector3(0f, baseWorldY, 0f)), ref minY);
}
return minY;
}
private static void AccumulateMinYRecursive(Node cur, Transform3D parentXf, ref float minY)
{
Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf;
if (cur is MeshInstance3D mi && mi.Mesh is { } mesh)
{
int surfCount = mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arrays = mesh.SurfaceGetArrays(s);
if (arrays.Count <= (int)Mesh.ArrayType.Vertex ||
arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
{
continue;
}
Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
for (int v = 0; v < verts.Length; v++)
{
float wy = (xf * verts[v]).Y;
if (wy < minY)
{
minY = wy;
}
}
}
}
for (int i = 0; i < cur.GetChildCount(); i++)
{
AccumulateMinYRecursive(cur.GetChild(i), xf, ref minY);
}
}
private static bool HasNaN(Transform3D t) private static bool HasNaN(Transform3D t)
{ {
return !t.Origin.IsFinite() return !t.Origin.IsFinite()