using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client.Tests;
///
/// Headless Godot smoke test: instantiates Main, drives 60 frames with throttle + fire + crater stamp,
/// verifies terrain tile baking and Ymir physics integration, and exits with code 0 on pass.
/// godot --headless --path client res://tests/Smoke.tscn
///
public partial class Smoke : Node
{
private const double WatchdogSeconds = 60.0;
private readonly List _failures = new();
private Main _main = null!;
private bool _done;
public override void _Ready() => _ = RunAsync();
public override void _Process(double delta)
{
if (!_done && Time.GetTicksMsec() > WatchdogSeconds * 1000.0)
{
Check(false, $"Smoke watchdog timed out after {WatchdogSeconds}s");
Finish();
}
}
private async Task RunAsync()
{
try
{
_main = GD.Load("res://Main.tscn").Instantiate();
AddChild(_main);
if (_main.Failure is { } failure)
{
Check(false, "Main failed to initialize ArenaSession: " + failure);
}
else
{
await RunScenarioAsync();
}
}
catch (Exception ex)
{
Check(false, ex.ToString());
}
Finish();
}
private async Task RunScenarioAsync()
{
Check(Engine.PhysicsTicksPerSecond == 60, $"Expected 60 physics ticks/sec, got {Engine.PhysicsTicksPerSecond}");
Check((string)ProjectSettings.GetSetting("physics/3d/physics_engine") == "Dummy", "Godot 3D physics_engine is not Dummy");
Check(!_main.GetWorld3D().Space.IsValid, "Godot should have no active 3D physics space");
Check(_main.Terrain.BakedTileCount == 64, $"Expected 64 baked terrain tiles, got {_main.Terrain.BakedTileCount}");
var player = _main.Session.State.Player;
float startX = player.X;
float startZ = player.Z;
_main.SetScriptedInput(new PlayerInput(
Throttle: 1f,
Steer: 0.25f,
AimWorldX: startX + 35f,
AimWorldZ: startZ + 10f,
Fire: true,
InteractPickup: false,
Brake: false));
for (int i = 0; i < 60; i++)
{
await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame);
if (_main.Failure is { } f)
{
Check(false, "Session failure during physics loop: " + f);
return;
}
}
float dx = player.X - startX;
float dz = player.Z - startZ;
float displacement = MathF.Sqrt(dx * dx + dz * dz);
Check(displacement > 3f, $"Expected player displacement > 3m after 60 frames, got {displacement:F2}m");
Check(!float.IsNaN(player.X) && !float.IsNaN(player.Y) && !float.IsNaN(player.Z), "Player position became NaN");
// Pause physics during the isolated crater check so AI contender track stamps in other tiles do not race it.
_main.SetScriptedInput(null);
_main.SetPhysicsProcess(false);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
bool isHeadless = DisplayServer.GetName() == "headless";
int rebakesBefore = _main.Terrain.DirtyRebakes;
float cpuBefore = _main.Session.State.Terrain.SampleHeight(-96f, -96f);
float gpuBefore = 0f;
if (!isHeadless)
{
if (_main.Terrain.TryGetHeightImageFormat(out var imgFormat))
{
GD.Print($"SMOKE INFO: HeightViewport format={imgFormat}");
}
bool hasGpuBefore = _main.Terrain.TrySampleBakedHeight(-96f, -96f, out gpuBefore);
Check(hasGpuBefore, "Expected GPU HeightViewport readback to succeed before crater");
if (hasGpuBefore)
{
float beforeErr = MathF.Abs(gpuBefore - cpuBefore);
GD.Print($"SMOKE INFO: Crater-site pre-stamp cpu={cpuBefore:F4}m gpu={gpuBefore:F4}m err={beforeErr:F4}m");
Check(beforeErr <= 0.20f,
$"Expected baked GPU height ({gpuBefore:F4}m) to match CPU height ({cpuBefore:F4}m) before crater within 0.20m");
}
// Verify brushed terrain relief (tallest Mesa/DuneRidge center) so a flat-map bug can never pass
TerrainBrush? reliefBrush = null;
float bestHillCpu = 0f;
foreach (var b in _main.Session.State.Terrain.Brushes)
{
if (b.Kind == TerrainBrushKind.Mesa || (b.Kind == TerrainBrushKind.DuneRidge && b.HeightDelta > 0f))
{
float h = _main.Session.State.Terrain.SampleHeight(b.X, b.Z);
if (h > bestHillCpu)
{
bestHillCpu = h;
reliefBrush = b;
}
}
}
Check(reliefBrush.HasValue && bestHillCpu > 10f, "Expected brushed terrain relief > 10m in generated arena");
if (reliefBrush.HasValue)
{
var rb = reliefBrush.Value;
bool hasGpuHill = _main.Terrain.TrySampleBakedHeight(rb.X, rb.Z, out float gpuHill);
Check(hasGpuHill, "Expected GPU HeightViewport readback to succeed on brushed relief hill/mesa");
if (hasGpuHill)
{
float hillErr = MathF.Abs(gpuHill - bestHillCpu);
GD.Print($"SMOKE INFO: Relief {rb.Kind} at ({rb.X:F1},{rb.Z:F1}) cpu={bestHillCpu:F4}m gpu={gpuHill:F4}m err={hillErr:F4}m");
Check(gpuHill > 10f, $"Expected GPU baked hill height > 10m, got {gpuHill:F4}m");
Check(hillErr <= 0.20f,
$"Expected GPU hill height ({gpuHill:F4}m) to match CPU ({bestHillCpu:F4}m) within 0.20m");
}
}
// Verify tile seam continuity across interior tile boundaries (< 0.01m)
float maxSeamErr = 0f;
float[] boundaries = { -192f, 0f, 192f };
float[] offsets = { -280f, -96f, 96f, 280f };
foreach (float bCoord in boundaries)
{
foreach (float ortho in offsets)
{
if (_main.Terrain.TrySampleBakedHeight(bCoord - 0.0001f, ortho, out float hL) &&
_main.Terrain.TrySampleBakedHeight(bCoord + 0.0001f, ortho, out float hR))
{
maxSeamErr = MathF.Max(maxSeamErr, MathF.Abs(hL - hR));
}
if (_main.Terrain.TrySampleBakedHeight(ortho, bCoord - 0.0001f, out float hD) &&
_main.Terrain.TrySampleBakedHeight(ortho, bCoord + 0.0001f, out float hU))
{
maxSeamErr = MathF.Max(maxSeamErr, MathF.Abs(hD - hU));
}
}
}
GD.Print($"SMOKE INFO: Max tile seam error={maxSeamErr:F5}m");
Check(maxSeamErr < 0.01f, $"Expected tile seam error < 0.01m, got {maxSeamErr:F5}m");
}
_main.Session.State.Terrain.StampCrater(-96f, -96f, radius: 5f, depth: 1.4f);
_main.Terrain.Sync(_main.Session.State.Terrain);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
float cpuAfter = _main.Session.State.Terrain.SampleHeight(-96f, -96f);
Check(cpuAfter < cpuBefore - 0.8f,
$"Expected CPU terrain height to drop after crater stamp (before {cpuBefore:F2}m, after {cpuAfter:F2}m)");
Check(_main.Terrain.DirtyRebakes == rebakesBefore + 1,
$"Expected 1 dirty tile rebake from isolated crater stamp, got {_main.Terrain.DirtyRebakes - rebakesBefore}");
if (!isHeadless)
{
bool hasGpuAfter = _main.Terrain.TrySampleBakedHeight(-96f, -96f, out float gpuAfter);
Check(hasGpuAfter, "Expected GPU HeightViewport readback to succeed after crater");
if (hasGpuAfter)
{
float afterErr = MathF.Abs(gpuAfter - cpuAfter);
GD.Print($"SMOKE INFO: Crater-site post-stamp cpu={cpuAfter:F4}m gpu={gpuAfter:F4}m err={afterErr:F4}m");
Check(afterErr <= 0.20f,
$"Expected baked GPU height ({gpuAfter:F4}m) to match CPU height ({cpuAfter:F4}m) after crater within 0.20m");
Check(gpuAfter < gpuBefore - 0.8f,
$"Expected baked GPU height to drop after crater (before {gpuBefore:F4}m, after {gpuAfter:F4}m)");
}
}
_main.SetPhysicsProcess(true);
await VerifyHudAndShadersAsync(isHeadless);
await VerifyCut3bVehiclesAndMechanismsAsync();
await MaybeCapturePreviewAsync(isHeadless);
await VerifyMaxLoadPaladinGarageAsync();
}
private async Task VerifyHudAndShadersAsync(bool isHeadless)
{
var invShader = _main.Hud.Schematic.ShaderMaterial.Shader;
Check(invShader is not null && !string.IsNullOrWhiteSpace(invShader.Code),
"inventory_grid.gdshader failed to load");
int chromeCount = 0;
foreach (var mat in _main.Hud.GetChromeMaterials())
{
chromeCount++;
Check(mat.Shader is not null && !string.IsNullOrWhiteSpace(mat.Shader.Code),
$"panel_chrome.gdshader failed to load on HUD panel #{chromeCount}");
}
Check(chromeCount == 5, $"Expected 5 ChromePanel materials on HUD, got {chromeCount}");
// Pack a real Ironclad chassis with mounted modules, thermal gradient, stripped cell, and active hit-pulse
var testGrid = new ChassisGrid(Catalog.Ironclad);
Check(testGrid.TryMount(Catalog.Recoilless, "hp.weapon.main"), "Expected Recoilless to mount on hp.weapon.main");
Check(testGrid.TryMount(Catalog.Mg762, "hp.weapon.coax"), "Expected Mg762 to mount on hp.weapon.coax");
Check(testGrid.TryMount(Catalog.TurboCore, "hp.engine.rear"), "Expected TurboCore to mount on hp.engine.rear");
Check(testGrid.TryMount(Catalog.CopperRad, "hp.radiator.l"), "Expected CopperRad to mount on hp.radiator.l");
Check(testGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front"), "Expected WeldedPlate to mount on hp.armor.front");
testGrid.InjectHardpointHeat("hp.engine.rear", 1800f);
testGrid.InjectHardpointHeat("hp.weapon.main", 900f);
testGrid.StepHeat(0.25f);
testGrid.Armor[0, 0] = 0f; // stripped armor cell
var schematic = _main.Hud.Schematic;
schematic.SetGrid(testGrid);
schematic.TriggerHitPulse(1, 1, 1f);
// Hit-testing verification: center of cell (1, 1) must map to (1, 1) and hardpoint "hp.weapon.main"
schematic.ComputeCellLayout(out float cellSize, out Vector2 origin);
Check(cellSize > 10f, $"Expected InventoryGridControl cellSize > 10px, got {cellSize:F2}");
Vector2 probePos = origin + new Vector2(1.5f * cellSize, 1.5f * cellSize);
bool hitCell = schematic.TryGetCellAt(probePos, out var mappedCell);
Check(hitCell && mappedCell == new Vector2I(1, 1),
$"Expected TryGetCellAt to map center of (1,1) to (1,1), got hit={hitCell} cell={mappedCell}");
var mappedHp = schematic.GetHardpointAt(1, 1);
Check(mappedHp is { Id: "hp.weapon.main" },
$"Expected GetHardpointAt(1,1) to return hp.weapon.main, got {mappedHp?.Id ?? "null"}");
// Toggle thermal mode off -> on -> off
_main.Hud.SetThermalMode(true, instant: true);
Check(_main.Hud.ThermalMode && MathF.Abs(schematic.ThermalBlend - 1f) < 0.01f,
"Expected ThermalMode to activate immediately");
_main.Hud.SetThermalMode(false, instant: true);
Check(!_main.Hud.ThermalMode && MathF.Abs(schematic.ThermalBlend) < 0.01f,
"Expected ThermalMode to deactivate immediately");
// Regression check (Finding 3): same-dimension SwapChassis updates _hardpointLookup and clears hover state
schematic._GuiInput(new InputEventMouseMotion { Position = probePos });
Check(schematic.HoveredCell == new Vector2I(1, 1) && schematic.HoveredHardpoint is { Id: "hp.weapon.main" },
$"Expected hover on (1,1)/hp.weapon.main before SwapChassis, got cell={schematic.HoveredCell} hp={schematic.HoveredHardpoint?.Id ?? "null"}");
bool hoverResetEmitted = false;
void OnSwapHoverChanged(Vector2I? cell, HardpointSpec? hp)
{
if (cell is null && hp is null)
{
hoverResetEmitted = true;
}
}
schematic.HoverChanged += OnSwapHoverChanged;
var altTankSpec = Catalog.Ironclad with
{
Id = "ironclad_alt",
Hardpoints = new[]
{
new HardpointSpec("wpn_swapped", HardpointKind.Weapon, 1, 1, 2, 2, 18f)
}
};
testGrid.SwapChassis(altTankSpec);
schematic.SetGrid(testGrid);
schematic.HoverChanged -= OnSwapHoverChanged;
Check(schematic.GetHardpointAt(1, 1) is { Id: "wpn_swapped" },
$"Expected GetHardpointAt(1,1) to update to wpn_swapped after same-dimension SwapChassis, got {schematic.GetHardpointAt(1, 1)?.Id ?? "null"}");
Check(schematic.GetHardpointAt(0, 1) is null,
$"Expected old hardpoint hp.weapon.coax at (0,1) to clear after SwapChassis, got {schematic.GetHardpointAt(0, 1)?.Id ?? "null"}");
Check(schematic.HoveredCell is null && schematic.HoveredHardpoint is null && hoverResetEmitted,
$"Expected SwapChassis to clear hover and emit HoverChanged(null, null), cell={schematic.HoveredCell} emitted={hoverResetEmitted}");
// Re-seed Ironclad grid for GPU tests below
testGrid = new ChassisGrid(Catalog.Ironclad);
Check(testGrid.TryMount(Catalog.Recoilless, "hp.weapon.main"), "Expected Recoilless to remount on hp.weapon.main");
Check(testGrid.TryMount(Catalog.Mg762, "hp.weapon.coax"), "Expected Mg762 to remount on hp.weapon.coax");
Check(testGrid.TryMount(Catalog.TurboCore, "hp.engine.rear"), "Expected TurboCore to remount on hp.engine.rear");
Check(testGrid.TryMount(Catalog.CopperRad, "hp.radiator.l"), "Expected CopperRad to remount on hp.radiator.l");
Check(testGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front"), "Expected WeldedPlate to remount on hp.armor.front");
testGrid.InjectHardpointHeat("hp.engine.rear", 1800f);
testGrid.InjectHardpointHeat("hp.weapon.main", 900f);
testGrid.StepHeat(0.25f);
testGrid.Armor[0, 0] = 0f;
// Restore live player grid to HUD and verify layout has no overlaps or clipping
_main.Hud.Sync(_main.Session);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
Vector2 vpSize = GetViewport().GetVisibleRect().Size;
Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Compact HUD panels overlapped or clipped at {vpSize}");
_main.Hud.ToggleGarage();
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Garage HUD panels overlapped or clipped at {vpSize}");
_main.Hud.ToggleGarage();
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
if (isHeadless)
{
return;
}
// GPU verification on OpenGL 3.3: render isolated InventoryGridControl (tactical + thermal) & panel_chrome.gdshader
var gridVp = new SubViewport
{
Size = new Vector2I(240, 240),
TransparentBg = true,
RenderTargetUpdateMode = SubViewport.UpdateMode.Always
};
var vpGrid = new InventoryGridControl
{
Size = new Vector2(240f, 240f),
CustomMinimumSize = new Vector2(240f, 240f)
};
gridVp.AddChild(vpGrid);
AddChild(gridVp);
vpGrid.SetGrid(testGrid);
vpGrid.TriggerHitPulse(1, 1, 1f);
vpGrid.SetThermalInstant(false);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var tacticalImg = gridVp.GetTexture().GetImage();
int tacticalOpaque = CountNonZeroAlphaPixels(tacticalImg, 0.08f);
GD.Print($"SMOKE INFO: InventoryGrid GPU tactical opaque pixels={tacticalOpaque}");
Check(tacticalOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid tactical shader, got {tacticalOpaque}");
vpGrid.SetThermalInstant(true);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var thermalImg = gridVp.GetTexture().GetImage();
int thermalOpaque = CountNonZeroAlphaPixels(thermalImg, 0.08f);
int modeDiff = CountDifferentPixels(tacticalImg, thermalImg, 0.05f);
GD.Print($"SMOKE INFO: InventoryGrid GPU thermal opaque={thermalOpaque}, diff vs tactical={modeDiff}");
Check(thermalOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid thermal shader, got {thermalOpaque}");
Check(modeDiff > 500, $"Expected thermal conduit toggle to visibly change > 500 pixels, got {modeDiff}");
// Finding 2 GPU check: overheated (350C+, thermal_mode = 1.0f) must obey blend_premul_alpha (out_rgb <= out_a)
testGrid.InjectHardpointHeat("hp.engine.rear", 45000f);
testGrid.InjectHardpointHeat("hp.weapon.main", 25000f);
testGrid.StepHeat(0.05f);
float hotTemp = testGrid.Temperature[1, 3];
Check(hotTemp >= 350f, $"Expected overheated cell >= 350C for premul test, got {hotTemp:F1}C");
vpGrid.SetGrid(testGrid);
vpGrid.SetThermalInstant(true);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var overheatImg = gridVp.GetTexture().GetImage();
int premulViolations = CountPremulViolations(overheatImg, 0.01f);
GD.Print($"SMOKE INFO: InventoryGrid GPU overheat ({hotTemp:F1}C) premul violations={premulViolations}");
Check(premulViolations == 0, $"Expected 0 blend_premul_alpha violations (max(RGB) > A + 0.01) on overheated grid, got {premulViolations}");
// Finding 1 GPU check: asymmetric Raptor chassis with thermal_mode = 1.0f must leave 0 lit pixels in inactive cell holes
var raptorGrid = new ChassisGrid(Catalog.Raptor);
Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_l"), "Expected CopperRad on Raptor hp.radiator.sh_l");
Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_r"), "Expected CopperRad on Raptor hp.radiator.sh_r");
Check(raptorGrid.TryMount(Catalog.Autocannon, "hp.weapon.arm_l"), "Expected Autocannon on Raptor hp.weapon.arm_l");
Check(raptorGrid.TryMount(Catalog.TurboCore, "hp.engine.chest"), "Expected TurboCore on Raptor hp.engine.chest");
Check(raptorGrid.TryMount(Catalog.Autocannon, "hp.weapon.arm_r"), "Expected Autocannon on Raptor hp.weapon.arm_r");
raptorGrid.InjectHardpointHeat("hp.engine.chest", 1800f);
raptorGrid.StepHeat(0.25f);
vpGrid.SetGrid(raptorGrid);
vpGrid.SetThermalInstant(true);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var raptorImg = gridVp.GetTexture().GetImage();
int raptorHoleScanned = 0;
int raptorHoleLit = 0;
int rw = raptorImg.GetWidth();
int rh = raptorImg.GetHeight();
for (int py = 0; py < rh; py++)
{
for (int px = 0; px < rw; px++)
{
if (vpGrid.TryGetCellAt(new Vector2(px + 0.5f, py + 0.5f), out var cell) && !Catalog.Raptor.IsActive(cell.X, cell.Y))
{
raptorHoleScanned++;
Color c = raptorImg.GetPixel(px, py);
if (MathF.Max(MathF.Max(c.R, c.G), MathF.Max(c.B, c.A)) > 0.001f)
{
raptorHoleLit++;
}
}
}
}
GD.Print($"SMOKE INFO: Asymmetric Raptor hole lit pixels={raptorHoleLit} (scanned {raptorHoleScanned} hole px)");
Check(raptorHoleScanned > 1000, $"Expected > 1000 inactive hole pixels scanned on Raptor, got {raptorHoleScanned}");
Check(raptorHoleLit == 0, $"Expected 0 lit/opaque pixels in inactive Raptor cell holes, got {raptorHoleLit}");
gridVp.QueueFree();
// GPU verification for panel_chrome.gdshader
var chromeVp = new SubViewport
{
Size = new Vector2I(240, 120),
TransparentBg = true,
RenderTargetUpdateMode = SubViewport.UpdateMode.Always
};
var chromeShader = GD.Load("res://panel_chrome.gdshader");
var chromeMat = new ShaderMaterial { Shader = chromeShader };
chromeMat.SetShaderParameter("rect_size", new Vector2(240f, 120f));
chromeMat.SetShaderParameter("accent_color", Color.FromHtml("#e08a4a"));
var chromeImgTex = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8);
chromeImgTex.SetPixel(0, 0, Colors.White);
var chromeRect = new TextureRect
{
Texture = ImageTexture.CreateFromImage(chromeImgTex),
Size = new Vector2(240f, 120f),
ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize,
StretchMode = TextureRect.StretchModeEnum.Scale,
Material = chromeMat
};
chromeVp.AddChild(chromeRect);
AddChild(chromeVp);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var chromeImg = chromeVp.GetTexture().GetImage();
int chromeOpaque = CountNonZeroAlphaPixels(chromeImg, 0.08f);
Color cornerPx = chromeImg.GetPixel(2, 2);
Color centerPx = chromeImg.GetPixel(120, 60);
GD.Print($"SMOKE INFO: panel_chrome GPU opaque={chromeOpaque}, corner={cornerPx}, center={centerPx}");
Check(chromeOpaque > 10000, $"Expected > 10000 rendered pixels from panel_chrome.gdshader, got {chromeOpaque}");
Check(cornerPx.R > centerPx.R + 0.25f,
$"Expected L-bracket corner pixel ({cornerPx}) to be accented brighter than panel center ({centerPx})");
chromeVp.QueueFree();
}
private async Task MaybeCapturePreviewAsync(bool isHeadless)
{
if (isHeadless) return;
string? previewPath = null;
foreach (string arg in OS.GetCmdlineUserArgs())
{
const string prefix = "--capture-preview=";
if (arg.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
previewPath = arg[prefix.Length..];
break;
}
}
if (string.IsNullOrWhiteSpace(previewPath))
{
return;
}
if (!_main.Hud.GarageExpanded)
{
_main.Hud.ToggleGarage();
}
// Seed realistic combat telemetry so the preview clearly showcases armor stripping, hit-flash, cargo rack, and thermal heat
var player = _main.Session.State.Player;
var grid = player.Grid;
grid.TryAddCargo(Catalog.TouringPlasma);
grid.TryAddCargo(Catalog.GoldRadiator);
grid.InjectHardpointHeat("hp.engine.rear", 1100f);
grid.InjectHardpointHeat("hp.weapon.roof", 750f);
grid.StepHeat(0.15f);
grid.Armor[0, 0] = 0f;
// Place two nearby rival contenders cleanly in the desert ahead of the player so the preview shows multiple Brokkr GLBs grounded on terrain
float fwdX = MathF.Sin(_main.CameraYaw);
float fwdZ = MathF.Cos(_main.CameraYaw);
float rightX = -fwdZ;
float rightZ = fwdX;
if (_main.Session.State.Contenders.Count > 2)
{
var r1 = _main.Session.State.Contenders[1];
if (r1.Alive)
{
_main.Session.SetContenderPose(r1.Id, player.X + fwdX * 19f - rightX * 5.5f, player.Z + fwdZ * 19f - rightZ * 5.5f, _main.CameraYaw + MathF.PI * 0.82f);
}
var r2 = _main.Session.State.Contenders[2];
if (r2.Alive)
{
_main.Session.SetContenderPose(r2.Id, player.X + fwdX * 26f + rightX * 8.5f, player.Z + fwdZ * 26f + rightZ * 8.5f, _main.CameraYaw - MathF.PI * 0.72f);
}
}
_main.Arena.Sync(_main.Session, 1.5f, 1f / 60f);
_main.Hud.Sync(_main.Session);
_main.Hud.Schematic.TriggerHitPulse(1, 0, 0.9f);
if (_main.Arena.GetContenderVisual(player.Id) is { } pVis)
{
Vector3 vehFwd = pVis.Root.GlobalTransform.Basis.Z.Normalized();
if (pVis.GetMountedGearNode("hp.weapon.roof") is { } roofGun)
{
Vector3 gunFwd = roofGun.GlobalTransform.Basis.Z.Normalized();
GD.Print($"SMOKE INFO: Preview Jackal yaw={player.Yaw:F3} vehFwd={vehFwd} roofGunFwd={gunFwd} dot={vehFwd.Dot(gunFwd):F3}");
}
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var frameImg = GetViewport().GetTexture().GetImage();
var err = frameImg.SavePng(previewPath);
GD.Print($"SMOKE INFO: Saved preview screenshot ({frameImg.GetWidth()}x{frameImg.GetHeight()}) to {previewPath} (err={err})");
Check(err == Error.Ok, $"Failed to save preview screenshot to {previewPath}: {err}");
}
private async Task VerifyCut3bVehiclesAndMechanismsAsync()
{
var cache = _main.Arena.AssetCache;
cache.PreloadAll();
Check(cache.Vehicles.Count == 15, $"Expected 15 cached vehicle GLBs, got {cache.Vehicles.Count}");
Check(cache.Gear.Count == 6, $"Expected 6 cached gear GLBs, got {cache.Gear.Count}");
// 1. All 15 vehicles bind 100% of hardpoint AnchorIds and attach/unmount gear cleanly
foreach (var spec in Catalog.AllChassis)
{
var pkg = Catalog.TryGetPackage(spec.Id);
Check(pkg is not null, $"Missing VehiclePackage for '{spec.Id}'");
if (pkg is null) continue;
var vis = VehicleVisualInstance.Create(cache, spec.Id, VehicleVisualRole.Player);
Check(vis.BoundHardpointCount == spec.Hardpoints.Length,
$"Expected {spec.Hardpoints.Length} bound hardpoints on '{spec.Id}', got {vis.BoundHardpointCount}");
Check(vis.Joints.Count == pkg.Joints.Count,
$"Expected {pkg.Joints.Count} bound joints on '{spec.Id}', got {vis.Joints.Count}");
Check(MathF.Abs(vis.Template.MinY) < 0.05f,
$"Expected grounded GLB MinY ~ 0 on '{spec.Id}', got {vis.Template.MinY:F4}");
var grid = Catalog.CreateWithDefaultLoadout(spec);
vis.SyncMountedGear(grid);
int mountedMeshes = 0;
foreach (var m in grid.Mounted)
{
var gNode = vis.GetMountedGearNode(m.HardpointId);
if (gNode is not null && CountMeshInstances(gNode) > 0)
{
mountedMeshes++;
if (m.Spec.Kind == HardpointKind.Weapon)
{
(string frontPart, string rearPart) = m.Spec.Id switch
{
"mg_762" or "pd_flak" => ("barrel_inner", "receiver"),
"autocannon" or "flak" => ("muzzle_brake_L", "gun_housing"),
"recoilless" => ("sight_tube", "breech_band"),
_ => ("condenser_ring_2", "ivory_cowl")
};
Vector3? frontC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, frontPart);
Vector3? rearC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, rearPart);
Check(frontC.HasValue && rearC.HasValue,
$"Missing weapon submeshes '{frontPart}'/'{rearPart}' on '{spec.Id}.{m.HardpointId}' ({m.Spec.Id})");
if (frontC.HasValue && rearC.HasValue)
{
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}");
}
}
}
}
Check(mountedMeshes == grid.Mounted.Count && mountedMeshes > 0,
$"Expected all {grid.Mounted.Count} default modules on '{spec.Id}' to attach visible gear meshes, got {mountedMeshes}");
// Unmount first module and confirm gear node is removed cleanly
if (grid.Mounted.Count > 0)
{
string removedHp = grid.Mounted[0].HardpointId;
grid.Mounted.RemoveAt(0);
vis.SyncMountedGear(grid);
Check(vis.GetMountedGearNode(removedHp) is null,
$"Expected gear node on '{spec.Id}.{removedHp}' to be removed after unmount");
}
vis.Root.QueueFree();
}
// 2. Rig animator produces real non-zero transforms (> 0.001 rad) with zero NaNs across all mobility archetypes
VerifyRigMotion(cache, "jackal", "joint.wheel_fl",
new VehicleRigDriveInput(new Vector3(0f, 0f, 14f), 0f, 0f, 0f, -1f, 1f, 0f, 1f, 1f / 60f),
minRotRad: 0.001f);
VerifyRigMotion(cache, "hornet", "joint.rotor_l",
new VehicleRigDriveInput(new Vector3(0f, 0f, 10f), 0f, 0f, 0f, 0f, 1f, 1f, 1f, 1f / 60f),
minRotRad: 0.001f);
VerifyRigMotion(cache, "anvil", "joint.turret_yaw",
new VehicleRigDriveInput(Vector3.Zero, 0f, 0.85f, 0f, 0f, 0f, 0f, 1f, 1f / 60f),
minRotRad: 0.001f);
VerifyRigMotion(cache, "manticore", "joint.tail_yaw",
new VehicleRigDriveInput(new Vector3(0f, 0f, 6f), 0f, 0.70f, 18f, 0f, 0.8f, 0f, 1f, 1f / 60f),
minRotRad: 0.001f);
// Breaker: verify oleo strut slide + scissor torque links + recess ram aiming
{
var breakerVis = VehicleVisualInstance.Create(cache, "breaker", VehicleVisualRole.Player);
Node3D? oleo = breakerVis.GetNamedNode("LegL.Oleo");
Node3D? scissorUp = breakerVis.GetNamedNode("LegL.TorqueUp");
Node3D? ram0 = breakerVis.GetNamedNode("LegL.RecessRam0");
Check(oleo is not null && scissorUp is not null && ram0 is not null,
"Expected Breaker LegL.Oleo, LegL.TorqueUp, and LegL.RecessRam0 nodes to resolve");
if (oleo is not null && scissorUp is not null && ram0 is not null)
{
Transform3D oleo0 = oleo.Transform;
Transform3D sc0 = scissorUp.Transform;
Transform3D ramRest = ram0.Transform;
var inp1 = new VehicleRigDriveInput(new Vector3(0f, -6f, 8f), 0f, 0.4f, 10f, 0f, 1f, 0f, 1f, 1f / 60f);
for (int s = 0; s < 10; s++) VehicleRigAnimator.Update(breakerVis, in inp1, Basis.Identity);
var inp2 = new VehicleRigDriveInput(new Vector3(0f, 3f, 8f), 0f, 0.4f, 10f, 0f, 1f, 0f, 1f, 1f / 60f);
for (int s = 0; s < 10; s++) VehicleRigAnimator.Update(breakerVis, in inp2, Basis.Identity);
float oleoDelta = (oleo.Transform.Origin - oleo0.Origin).Length();
float scDelta = sc0.Basis.GetRotationQuaternion().AngleTo(scissorUp.Transform.Basis.GetRotationQuaternion());
float ramDelta = ramRest.Basis.GetRotationQuaternion().AngleTo(ram0.Transform.Basis.GetRotationQuaternion());
GD.Print($"SMOKE INFO: Breaker mech deltas oleo={oleoDelta:F4}m scissor={scDelta:F4}rad ram={ramDelta:F4}rad");
Check(oleoDelta > 0.0005f && !HasNaN(oleo.Transform), $"Expected Breaker LegL.Oleo motion > 0.0005m, got {oleoDelta:F5}");
Check(scDelta > 0.001f && !HasNaN(scissorUp.Transform), $"Expected Breaker LegL.TorqueUp scissor rotation > 0.001rad, got {scDelta:F5}");
Check(ramDelta > 0.001f && !HasNaN(ram0.Transform), $"Expected Breaker LegL.RecessRam0 aim rotation > 0.001rad, got {ramDelta:F5}");
}
breakerVis.Root.QueueFree();
}
// 3. Part-by-cell armor detachment + hardpoint gear shear into DebrisSystem
{
var debris = new DebrisSystem { Name = "SmokeDebrisTest" };
AddChild(debris);
var anvilGrid = Catalog.CreateWithDefaultLoadout(Catalog.Anvil);
var anvilVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.Player);
AddChild(anvilVis.Root);
anvilVis.SyncMountedGear(anvilGrid);
anvilVis.SyncDamageAndHeat(anvilGrid, debris, Vector3.Zero);
Check(debris.ActiveCount == 0, $"Expected 0 debris before armor strip, got {debris.ActiveCount}");
// Pick a cell that has detachable armor/shroud plates
int targetCx = -1, targetCy = -1;
for (int cy = 0; cy < anvilGrid.Spec.Height && targetCx < 0; cy++)
{
for (int cx = 0; cx < anvilGrid.Spec.Width; cx++)
{
if (anvilVis.CountDetachablePartsForCell(cx, cy) > 0)
{
targetCx = cx;
targetCy = cy;
break;
}
}
}
Check(targetCx >= 0, "Expected Anvil to have >= 1 cell with detachable armor/shroud parts");
// Strip that armor cell AND strip weapon hardpoint hp.weapon.siege_l
if (targetCx >= 0)
{
anvilGrid.Armor[targetCx, targetCy] = 0f;
}
var siegeHp = anvilGrid.FindHardpoint("hp.weapon.siege_l")!;
for (int dy = 0; dy < siegeHp.Height; dy++)
{
for (int dx = 0; dx < siegeHp.Width; dx++)
{
anvilGrid.Armor[siegeHp.X + dx, siegeHp.Y + dy] = 0f;
}
}
anvilVis.SyncDamageAndHeat(anvilGrid, debris, new Vector3(2f, 0f, 4f));
Check(debris.ActiveCount >= 2,
$"Expected >= 2 debris pieces (armor plate + sheared weapon gear), got {debris.ActiveCount}");
Check(anvilVis.GetMountedGearNode("hp.weapon.siege_l") is null,
"Expected hp.weapon.siege_l gear to shear off when hardpoint becomes non-operational");
if (debris.GetChildCount() > 0 && debris.GetChild(0) is Node3D firstPiece)
{
Vector3 p0 = firstPiece.Position;
for (int s = 0; s < 25; s++)
{
debris.Step(1f / 60f, _main.Session.State.Terrain);
}
float moved = firstPiece.Position.DistanceTo(p0);
Check(moved > 0.1f && !HasNaN(firstPiece.Transform),
$"Expected debris piece to travel/fall > 0.1m under blast + gravity, got {moved:F3}m");
}
anvilVis.Root.QueueFree();
debris.QueueFree();
}
// 4. Full Paladin hull + gear strip detaches every merged cell armor chunk + mounted gear under 256 cap
{
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);
int activeCellCount = 0;
int expectedCellChunks = 0;
for (int cy = 0; cy < palGrid.Spec.Height; cy++)
{
for (int cx = 0; cx < palGrid.Spec.Width; cx++)
{
if (palGrid.Spec.IsActive(cx, cy))
{
activeCellCount++;
expectedCellChunks += palVis.CountDetachablePartsForCell(cx, cy);
}
palGrid.Armor[cx, cy] = 0f;
}
}
int expectedTotal = expectedCellChunks + palGrid.Mounted.Count;
palVis.SyncDamageAndHeat(palGrid, debris, new Vector3(1f, 0f, 3f));
GD.Print($"SMOKE INFO: Full Paladin strip debris.ActiveCount={debris.ActiveCount} (activeCells={activeCellCount}, cellChunks={expectedCellChunks}, mounted={palGrid.Mounted.Count})");
Check(debris.ActiveCount >= activeCellCount && debris.ActiveCount == expectedTotal && debris.ActiveCount <= 256,
$"Expected full Paladin strip to detach {expectedTotal} (>= {activeCellCount} active cells) 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(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($"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($"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();
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);
}
private void VerifyRigMotion(
VehicleAssetCache cache,
string vehicleId,
string jointId,
VehicleRigDriveInput input,
float minRotRad)
{
var vis = VehicleVisualInstance.Create(cache, vehicleId, VehicleVisualRole.Player);
Check(vis.Joints.TryGetValue(jointId, out var j), $"Missing joint '{jointId}' on '{vehicleId}'");
if (j is not null)
{
Transform3D before = j.Node.Transform;
for (int s = 0; s < 20; s++)
{
VehicleRigAnimator.Update(vis, in input, Basis.Identity);
}
Transform3D after = j.Node.Transform;
float deltaRad = before.Basis.GetRotationQuaternion().AngleTo(after.Basis.GetRotationQuaternion());
GD.Print($"SMOKE INFO: Rig {vehicleId}.{jointId} delta={deltaRad:F4}rad");
Check(deltaRad > minRotRad && !HasNaN(after),
$"Expected {vehicleId}.{jointId} rotation delta > {minRotRad:F4}rad with zero NaNs, got {deltaRad:F5}");
}
vis.Root.QueueFree();
}
private static int CountMeshInstances(Node cur)
{
int count = cur is MeshInstance3D ? 1 : 0;
for (int i = 0; i < cur.GetChildCount(); i++)
{
count += CountMeshInstances(cur.GetChild(i));
}
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)
{
return !t.Origin.IsFinite()
|| !t.Basis.X.IsFinite()
|| !t.Basis.Y.IsFinite()
|| !t.Basis.Z.IsFinite();
}
private async Task VerifyMaxLoadPaladinGarageAsync()
{
var grid = _main.Session.State.Player.Grid;
grid.SwapChassis(Catalog.Paladin);
Check(grid.TryMount(Catalog.TouringPlasma, "hp.weapon.sh_l"), "Expected TouringPlasma on Paladin hp.weapon.sh_l");
Check(grid.TryMount(Catalog.WeldedPlate, "hp.armor.torso"), "Expected WeldedPlate on Paladin hp.armor.torso");
Check(grid.TryMount(Catalog.TouringPlasma, "hp.weapon.sh_r"), "Expected TouringPlasma on Paladin hp.weapon.sh_r");
Check(grid.TryMount(Catalog.GildedLance, "hp.weapon.arm_l"), "Expected GildedLance on Paladin hp.weapon.arm_l");
Check(grid.TryMount(Catalog.NobleCore, "hp.engine.chest"), "Expected NobleCore on Paladin hp.engine.chest");
Check(grid.TryMount(Catalog.GildedLance, "hp.weapon.arm_r"), "Expected GildedLance on Paladin hp.weapon.arm_r");
Check(grid.TryMount(Catalog.GoldRadiator, "hp.radiator.back_l"), "Expected GoldRadiator on Paladin hp.radiator.back_l");
Check(grid.TryMount(Catalog.WeldedPlate, "hp.armor.legs"), "Expected WeldedPlate on Paladin hp.armor.legs");
Check(grid.TryMount(Catalog.GoldRadiator, "hp.radiator.back_r"), "Expected GoldRadiator on Paladin hp.radiator.back_r");
grid.Cargo.Clear();
var cargoSpecs = new[]
{
Catalog.TouringPlasma, Catalog.GoldRadiator, Catalog.GildedLance,
Catalog.NobleCore, Catalog.Recoilless, Catalog.Autocannon,
Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate
};
for (int i = 0; i < cargoSpecs.Length; i++)
{
Check(grid.TryAddCargo(cargoSpecs[i]), $"Expected cargo slot #{i} ({cargoSpecs[i].Name}) to fit on Paladin");
}
if (!_main.Hud.GarageExpanded)
{
_main.Hud.ToggleGarage();
}
_main.Hud.Sync(_main.Session);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
Vector2 vpSize = GetViewport().GetVisibleRect().Size;
Rect2 blRect = _main.Hud.BottomLeftPanelRect;
Rect2 chyronRect = _main.Hud.ChyronPanelRect;
float chyronGap = chyronRect.Position.X - blRect.End.X;
GD.Print($"SMOKE INFO: Max-load Paladin Garage rect={blRect}, chyron gap={chyronGap:F1}px at {vpSize}");
Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Max-load Paladin Garage panels overlapped or clipped at {vpSize}");
Check(blRect.End.X <= 610f, $"Expected max-load Paladin Garage End.X <= 610px, got {blRect.End.X:F1}");
Check(!blRect.HasPoint(vpSize * 0.5f), $"Expected max-load Paladin Garage not to cover viewport center {vpSize * 0.5f}, rect={blRect}");
Check(chyronGap > 80f, $"Expected > 80px breathing room between Garage and Chyron, got {chyronGap:F1}px");
_main.Hud.ToggleGarage();
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
private static int CountPremulViolations(Image img, float tolerance)
{
int count = 0;
int w = img.GetWidth();
int h = img.GetHeight();
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
Color c = img.GetPixel(x, y);
float maxRgb = MathF.Max(c.R, MathF.Max(c.G, c.B));
if (maxRgb > c.A + tolerance)
{
count++;
}
}
}
return count;
}
private static int CountNonZeroAlphaPixels(Image img, float minAlpha)
{
int count = 0;
int w = img.GetWidth();
int h = img.GetHeight();
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
if (img.GetPixel(x, y).A > minAlpha) count++;
}
}
return count;
}
private static int CountDifferentPixels(Image a, Image b, float threshold)
{
int count = 0;
int w = Math.Min(a.GetWidth(), b.GetWidth());
int h = Math.Min(a.GetHeight(), b.GetHeight());
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
Color ca = a.GetPixel(x, y);
Color cb = b.GetPixel(x, y);
float diff = MathF.Abs(ca.R - cb.R) + MathF.Abs(ca.G - cb.G) + MathF.Abs(ca.B - cb.B) + MathF.Abs(ca.A - cb.A);
if (diff > threshold) count++;
}
}
return count;
}
private void Check(bool condition, string message)
{
if (!condition)
{
_failures.Add(message);
}
}
private void Finish()
{
if (_done) return;
_done = true;
foreach (var f in _failures)
{
GD.PrintErr("SMOKE FAIL: " + f);
}
GD.Print(_failures.Count == 0 ? "SMOKE PASS" : $"SMOKE FAILED ({_failures.Count})");
GetTree().Quit(_failures.Count == 0 ? 0 : 1);
}
}