Fix all 6 60 FPS Soul Pass findings and add permanent regression tests

This commit is contained in:
Meta Vens 2026-12-04 23:22:18 +01:00
commit f5d23ce49e
12 changed files with 1031 additions and 305 deletions

View file

@ -28,6 +28,8 @@ public partial class ArenaRenderer : Node3D
public MeshInstance3D? LaserMesh;
public SpectatorStance? LastHaloStance;
public bool LastLaserVisible;
public float RigDtAccum;
public int RigSkipFrames;
}
private sealed class DropVisualEntry
@ -178,30 +180,80 @@ public partial class ArenaRenderer : Node3D
{
ClearChildren(_staticGroup);
// Bucket cover ruins into 4 world quadrants so frustum culling still culls off-screen quadrants
// while collapsing 36 individual MeshInstance3D draw calls down to <= 4.
var quadArrays = new SurfaceTool[4];
for (int i = 0; i < state.ArenaCoverBoxes.Count; i++)
{
var b = state.ArenaCoverBoxes[i];
var mesh = new MeshInstance3D
int qIdx = (b.X >= 0f ? 1 : 0) | (b.Z >= 0f ? 2 : 0);
var st = quadArrays[qIdx];
if (st is null)
{
Mesh = new BoxMesh { Size = new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f) },
MaterialOverride = _coverMat,
Position = new Vector3(b.X, b.Y, b.Z)
};
_staticGroup.AddChild(mesh);
st = new SurfaceTool();
st.Begin(Mesh.PrimitiveType.Triangles);
quadArrays[qIdx] = st;
}
AppendBoxToSurfaceTool(st, new Vector3(b.X, b.Y, b.Z), new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f));
}
for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++)
for (int q = 0; q < 4; q++)
{
var b = state.ArenaBoundaryBoxes[i];
var mesh = new MeshInstance3D
if (quadArrays[q] is null) continue;
quadArrays[q].GenerateNormals();
_staticGroup.AddChild(new MeshInstance3D
{
Mesh = new BoxMesh { Size = new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f) },
MaterialOverride = _bermMat,
Position = new Vector3(b.X, b.Y, b.Z),
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
};
_staticGroup.AddChild(mesh);
Name = $"CoverQuad_{q}",
Mesh = quadArrays[q].Commit(),
MaterialOverride = _coverMat
});
}
if (state.ArenaBoundaryBoxes.Count > 0)
{
var bermSt = new SurfaceTool();
bermSt.Begin(Mesh.PrimitiveType.Triangles);
for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++)
{
var b = state.ArenaBoundaryBoxes[i];
AppendBoxToSurfaceTool(bermSt, new Vector3(b.X, b.Y, b.Z), new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f));
}
bermSt.GenerateNormals();
_staticGroup.AddChild(new MeshInstance3D
{
Name = "BoundaryBerms",
Mesh = bermSt.Commit(),
MaterialOverride = _bermMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
});
}
}
private static void AppendBoxToSurfaceTool(SurfaceTool st, Vector3 center, Vector3 size)
{
Vector3 h = size * 0.5f;
Vector3 p000 = center + new Vector3(-h.X, -h.Y, -h.Z);
Vector3 p100 = center + new Vector3( h.X, -h.Y, -h.Z);
Vector3 p110 = center + new Vector3( h.X, h.Y, -h.Z);
Vector3 p010 = center + new Vector3(-h.X, h.Y, -h.Z);
Vector3 p001 = center + new Vector3(-h.X, -h.Y, h.Z);
Vector3 p101 = center + new Vector3( h.X, -h.Y, h.Z);
Vector3 p111 = center + new Vector3( h.X, h.Y, h.Z);
Vector3 p011 = center + new Vector3(-h.X, h.Y, h.Z);
// +Z, -Z, +X, -X, +Y, -Y (outward CCW in Godot right-handed coords)
AddQuad(st, p001, p101, p111, p011);
AddQuad(st, p100, p000, p010, p110);
AddQuad(st, p101, p100, p110, p111);
AddQuad(st, p000, p001, p011, p010);
AddQuad(st, p011, p111, p110, p010);
AddQuad(st, p000, p100, p101, p001);
}
private static void AddQuad(SurfaceTool st, Vector3 a, Vector3 b, Vector3 c, Vector3 d)
{
st.AddVertex(a); st.AddVertex(b); st.AddVertex(c);
st.AddVertex(a); st.AddVertex(c); st.AddVertex(d);
}
private void ClearDynamicVisuals()
@ -318,22 +370,29 @@ public partial class ArenaRenderer : Node3D
vis.Visual.Root.Rotation = new Vector3(0f, c.Yaw, 0f);
}
bool useStaticLod = false;
bool castShadows = true;
if (hasCam && !c.IsPlayer)
{
float distSq = pos.DistanceSquaredTo(camPos);
useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f;
castShadows = distSq <= 150f * 150f;
}
vis.Visual.SetLodState(useStaticLod, castShadows);
float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f;
bool castShadows = !hasCam || c.IsPlayer || distSq <= 115f * 115f;
vis.Visual.SetLodState(useStaticLod: false, castShadows);
if (!useStaticLod)
vis.Visual.SyncMountedGear(c.Grid);
if (!hasCam || c.IsPlayer || distSq <= 130f * 130f)
{
vis.Visual.SyncMountedGear(c.Grid);
vis.RigDtAccum = 0f;
vis.RigSkipFrames = 0;
VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt);
vis.Visual.SyncDamageAndHeat(c.Grid, _debris, vel);
}
else
{
vis.RigDtAccum += dt;
vis.RigSkipFrames++;
if (vis.RigSkipFrames >= 3)
{
VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, vis.RigDtAccum);
vis.RigDtAccum = 0f;
vis.RigSkipFrames = 0;
}
}
vis.Visual.SyncDamageAndHeat(c.Grid, _debris, vel);
}
}
@ -399,13 +458,18 @@ public partial class ArenaRenderer : Node3D
vis.Visual.Root.Rotation = new Vector3(0f, s.Yaw, 0f);
}
vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel);
bool useStaticLod = false;
bool castShadows = true;
if (hasCam)
{
float distSq = specPos.DistanceSquaredTo(camPos);
useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f;
castShadows = distSq <= 150f * 150f;
castShadows = distSq <= 115f * 115f;
if (s.Stance == SpectatorStance.Neutral && !vis.Visual.HasAnyStrippedCell)
{
useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f;
}
}
vis.Visual.SetLodState(useStaticLod, castShadows);
@ -447,7 +511,6 @@ public partial class ArenaRenderer : Node3D
vis.Visual.SyncMountedGear(s.Grid);
VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis);
vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel);
}
// Status halo
@ -611,9 +674,17 @@ public partial class ArenaRenderer : Node3D
}
if (d.Module is not null)
{
float bob = MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f;
entry.Node.Position = new Vector3(d.X, entry.BaseY + bob, d.Z);
entry.Node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f);
bool visDrop = !hasCam || new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos) <= 240f * 240f;
if (entry.Node.Visible != visDrop)
{
entry.Node.Visible = visDrop;
}
if (visDrop)
{
float bob = MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f;
entry.Node.Position = new Vector3(d.X, entry.BaseY + bob, d.Z);
entry.Node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f);
}
}
else
{
@ -629,7 +700,7 @@ public partial class ArenaRenderer : Node3D
{
float d2 = new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos);
useFarLod = cv.IsStaticLod ? d2 > 126f * 126f : d2 > 130f * 130f;
castShadows = d2 <= 150f * 150f;
castShadows = d2 <= 95f * 95f;
}
cv.SetLodState(useFarLod, castShadows);
}

View file

@ -59,6 +59,7 @@ public partial class InventoryGridControl : Control
private float[,] _hitPulse = new float[0, 0];
private int _lastSelectedCargoIndex = int.MinValue;
private string? _lastSelectedCargoId;
private int _lastMountedSig = int.MinValue;
private Vector2I? _hoveredCell;
private bool _thermalEnabled;
@ -115,6 +116,9 @@ public partial class InventoryGridControl : Control
}
public float ThermalBlend => _thermalBlend;
internal int LabelsDrawCount => _labelsOverlay.DrawCount;
internal string? GetLastDrawnLabel(string hardpointId) =>
_labelsOverlay.LastDrawnTags.TryGetValue(hardpointId, out string? tag) ? tag : null;
public void SetThermalInstant(bool enabled)
{
@ -216,11 +220,15 @@ public partial class InventoryGridControl : Control
_grid = grid;
_spec = grid.Spec;
_selectedCargoIndex = selectedCargoIndex;
string? selectedCargoId = selectedCargoIndex >= 0 && selectedCargoIndex < grid.Cargo.Count
? grid.Cargo[selectedCargoIndex].Id
: null;
if (gridIdentityChanged)
{
EnsureBackingBuffers(grid);
_lastSelectedCargoIndex = selectedCargoIndex;
_lastSelectedCargoId = selectedCargoId;
_lastMountedSig = ComputeMountedSignature(grid);
SnapshotTemperatures(grid);
PackDataTexture(grid);
@ -233,9 +241,12 @@ public partial class InventoryGridControl : Control
bool dataChanged = DetectHits(grid);
int mountedSig = ComputeMountedSignature(grid);
if (_lastSelectedCargoIndex != selectedCargoIndex || _lastMountedSig != mountedSig)
if (_lastSelectedCargoIndex != selectedCargoIndex ||
!string.Equals(_lastSelectedCargoId, selectedCargoId, StringComparison.Ordinal) ||
_lastMountedSig != mountedSig)
{
_lastSelectedCargoIndex = selectedCargoIndex;
_lastSelectedCargoId = selectedCargoId;
_lastMountedSig = mountedSig;
dataChanged = true;
}
@ -245,7 +256,6 @@ public partial class InventoryGridControl : Control
if (dataChanged)
{
PackDataTexture(grid);
_labelsOverlay.QueueRedraw();
}
if (tempChanged)
{
@ -254,6 +264,7 @@ public partial class InventoryGridControl : Control
}
if (dataChanged || tempChanged)
{
_labelsOverlay.QueueRedraw();
FlushTextures();
}
}
@ -730,11 +741,15 @@ public partial class InventoryGridControl : Control
private sealed partial class LabelsOverlay : Control
{
private readonly InventoryGridControl _owner;
public int DrawCount { get; private set; }
public readonly Dictionary<string, string> LastDrawnTags = new(StringComparer.Ordinal);
public LabelsOverlay(InventoryGridControl owner) => _owner = owner;
public override void _Draw()
{
DrawCount++;
LastDrawnTags.Clear();
var grid = _owner._grid;
if (grid is null) return;
@ -755,6 +770,7 @@ public partial class InventoryGridControl : Control
string tag = mounted is not null
? $"{mounted.Spec.Kind.ToString()[..1]}:{mounted.CurrentTemp:F0}°"
: hp.Kind.ToString()[..3].ToUpperInvariant();
LastDrawnTags[hp.Id] = tag;
Color col = mounted is { Spec.IsImperial: true } ? ColGold : ColTextLight;
col.A = alpha;

View file

@ -88,8 +88,59 @@ public partial class Main : Node3D
}
Reset(_seed);
if (_perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1" && _session is not null)
{
SetupPerfCombatScenario(_session);
}
_perfLastFrameTick = Stopwatch.GetTimestamp();
_perfLastDirtyRebakes = _terrain.DirtyRebakes;
TerrainRenderer.PerfBakeTileMs = 0;
TerrainRenderer.PerfBakeTileCalls = 0;
VehicleVisualInstance.PerfDamageHeatMs = 0;
VehicleVisualInstance.PerfMaterialDupCount = 0;
}
private void SetupPerfCombatScenario(ArenaSession session)
{
var p = session.State.Player;
float fwdX = MathF.Sin(p.Yaw);
float fwdZ = MathF.Cos(p.Yaw);
float rightX = -fwdZ;
float rightZ = fwdX;
for (int i = 1; i <= 8 && i < session.State.Contenders.Count; i++)
{
float dist = 65f + (i % 4) * 11f;
float lat = (i - 4.5f) * 11f;
float tx = p.X + fwdX * dist + rightX * lat;
float tz = p.Z + fwdZ * dist + rightZ * lat;
session.SetContenderPose(session.State.Contenders[i].Id, tx, tz, p.Yaw + MathF.PI);
}
for (int i = 0; i < 6 && i < session.State.Spectators.Spectators.Count; i++)
{
var s = session.State.Spectators.Spectators[i];
float dist = 78f + (i % 3) * 12f;
float lat = (i - 2.5f) * 16f;
float sx = p.X + fwdX * dist + rightX * lat;
float sz = p.Z + fwdZ * dist + rightZ * lat;
session.SetSpectatorPose(s.Id, sx, sz, p.Yaw + MathF.PI);
session.State.Spectators.OnSpectatorDamaged(s, p.Id);
}
var aimTarget = session.State.Contenders[1];
_scriptedInput = new PlayerInput(
Throttle: 0.4f,
Steer: 0f,
AimWorldX: aimTarget.X,
AimWorldZ: aimTarget.Z,
Fire: true,
InteractPickup: false,
Brake: false);
_arena.Sync(session, _elapsedSeconds, 0f);
UpdateCamera(1f);
_hud.Sync(session);
}
public override void _ExitTree()
@ -343,6 +394,7 @@ public partial class Main : Node3D
GD.Print($"TimePhysicsProcessMs: avg={Avg(_perfTimePhysicsProcess):F2}");
GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}");
GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / _perfPhysicsTicks:F2} ai={ArenaSession.PerfAiMs / _perfPhysicsTicks:F2} drive={ArenaSession.PerfDriveMs / _perfPhysicsTicks:F2} world={ArenaSession.PerfWorldMs / _perfPhysicsTicks:F2} sync={ArenaSession.PerfBodySyncMs / _perfPhysicsTicks:F2} detect={ArenaSession.PerfDetectMs / _perfPhysicsTicks:F2} weapons={ArenaSession.PerfWeaponsMs / _perfPhysicsTicks:F2}");
GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} tracers={_session?.State.Tracers.Count ?? 0}");
foreach (var kv in _arena.AssetCache.Vehicles)
{
int tris = 0;

View file

@ -54,6 +54,8 @@ public partial class TerrainRenderer : Node3D
public int BakedTileCount { get; private set; }
public int DirtyRebakes { get; private set; }
public static double PerfBakeTileMs;
public static int PerfBakeTileCalls;
public override void _Ready()
{
@ -117,28 +119,41 @@ public partial class TerrainRenderer : Node3D
const int totalTiles = TerrainField.TileGridCount * TerrainField.TileGridCount;
// 1. Always bake uninitialized tiles immediately
// 1. Always bake uninitialized tiles and structural/crater dirty tiles immediately
ulong structuralMask = terrain.StructuralDirtyTileMask;
for (int tz = 0; tz < TerrainField.TileGridCount; tz++)
{
for (int tx = 0; tx < TerrainField.TileGridCount; tx++)
{
var tile = _tiles[tx, tz];
int version = terrain.TileVersions[tx, tz];
if (tile.BakedVersion < 0 && tile.BakedVersion != version)
bool isUninitialized = tile.BakedVersion < 0 && tile.BakedVersion != version;
ulong bit = 1UL << (tz * TerrainField.TileGridCount + tx);
bool isStructuralDirty = (structuralMask & bit) != 0UL && tile.BakedVersion != version;
if (isUninitialized || isStructuralDirty)
{
BakeTile(tx, tz, tile, terrain);
BakedTileCount++;
if (isUninitialized)
{
BakedTileCount++;
}
else
{
DirtyRebakes++;
}
tile.BakedVersion = version;
terrain.ClearStructuralDirtyTile(tx, tz);
}
}
}
// 2. Budget dynamic tile rebakes (tracks/craters) to <= 2 per Sync in round-robin order
// 2. Budget remaining passive dynamic tile rebakes (tracks/scorch) to <= 2 per Sync in round-robin order
int rebakedThisSync = 0;
bool anyRemainingDirty = false;
int startCursor = _rebakeCursor;
for (int step = 0; step < totalTiles; step++)
{
int idx = (_rebakeCursor + step) % totalTiles;
int idx = (startCursor + step) % totalTiles;
int tx = idx % TerrainField.TileGridCount;
int tz = idx / TerrainField.TileGridCount;
var tile = _tiles[tx, tz];
@ -169,7 +184,7 @@ public partial class TerrainRenderer : Node3D
public void UpdateTileLod(Vector3 camPos)
{
const float nearRadiusSq = 240f * 240f;
const float shadowRadiusSq = 220f * 220f;
const float shadowRadiusSq = 155f * 155f;
for (int tz = 0; tz < TerrainField.TileGridCount; tz++)
{
for (int tx = 0; tx < TerrainField.TileGridCount; tx++)
@ -334,6 +349,7 @@ public partial class TerrainRenderer : Node3D
private void BakeTile(int tx, int tz, TileNode tile, TerrainField terrain)
{
long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0;
ClearCanvasChildren(tile.HeightCanvas);
ClearCanvasChildren(tile.AlbedoCanvas);
@ -393,6 +409,11 @@ public partial class TerrainRenderer : Node3D
tile.HeightViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once;
tile.AlbedoViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once;
if (t0 != 0)
{
PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency;
PerfBakeTileCalls++;
}
}
private static Polygon2D CreateClearQuad(Color color, Shader clearShader, ImageTexture whiteTex)

View file

@ -62,6 +62,7 @@ public sealed class VehicleAssetCache : IDisposable
public required string Id { get; init; }
public required string GlbPath { get; init; }
public required Node3D SceneTemplate { get; init; }
public required ArrayMesh BakedDropMesh { get; init; }
public required Vector3 Size { get; init; }
public required float MinY { get; init; }
public required Vector3 LocalModelForward { get; init; }
@ -444,7 +445,7 @@ public sealed class VehicleAssetCache : IDisposable
// C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template
ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false);
ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true);
ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f);
ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f, targetMinY: minY);
return new VehicleTemplate
{
@ -489,6 +490,7 @@ public sealed class VehicleAssetCache : IDisposable
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
MergeGearSubMeshes(sceneRoot, gearId);
ArrayMesh bakedDropMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false, bakeVertexColor: false);
Vector3 localFwd = new Vector3(0f, 0f, 1f);
return new GearTemplate
@ -496,6 +498,7 @@ public sealed class VehicleAssetCache : IDisposable
Id = gearId,
GlbPath = glbPath,
SceneTemplate = sceneRoot,
BakedDropMesh = bakedDropMesh,
Size = bMax - bMin,
MinY = bMin.Y,
LocalModelForward = localFwd
@ -733,7 +736,8 @@ public sealed class VehicleAssetCache : IDisposable
}
}
// A. Merge static non-detachable sub-meshes per rigid articulated parent
// A. Merge static non-detachable sub-meshes per rigid articulated parent, and collapse PaintTag==0 surfaces on protected structural meshes
var mergedProtectedMeshes = new HashSet<MeshInstance3D>();
foreach (var (rigidParent, items) in staticGroups)
{
if (rigidParent is MeshInstance3D parentMi && CanMergeMeshInstance(parentMi))
@ -748,6 +752,7 @@ public sealed class VehicleAssetCache : IDisposable
{
parentMi.MaterialOverride = null;
parentMi.Mesh = merged;
mergedProtectedMeshes.Add(parentMi);
for (int i = 0; i < items.Count; i++)
{
ReparentChildrenAndRemove(items[i].Mi);
@ -773,6 +778,26 @@ public sealed class VehicleAssetCache : IDisposable
}
}
for (int i = 0; i < allMeshes.Count; i++)
{
MeshInstance3D mi = allMeshes[i];
if (GodotObject.IsInstanceValid(mi) &&
protectedNodes.Contains(mi) &&
!mergedProtectedMeshes.Contains(mi) &&
CanMergeMeshInstance(mi) &&
mi.Mesh is not null &&
mi.Mesh.GetSurfaceCount() > 1)
{
var single = new List<(MeshInstance3D, Transform3D)>(1) { (mi, Transform3D.Identity) };
ArrayMesh? collapsed = BuildMergedArrayMesh(single);
if (collapsed is not null && collapsed.GetSurfaceCount() < mi.Mesh.GetSurfaceCount())
{
mi.MaterialOverride = null;
mi.Mesh = collapsed;
}
}
}
// Prune empty non-protected grouping nodes left behind
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, protectedNodes);
@ -844,7 +869,7 @@ public sealed class VehicleAssetCache : IDisposable
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, keptNodes);
}
private static ArrayMesh BuildBakedStaticMesh(Node3D sceneRoot, bool coarseMaterials = false)
private static ArrayMesh BuildBakedStaticMesh(Node3D sceneRoot, bool coarseMaterials = false, bool bakeVertexColor = true)
{
var allMeshes = new List<MeshInstance3D>();
CollectAllMeshInstances(sceneRoot, allMeshes);
@ -859,7 +884,7 @@ public sealed class VehicleAssetCache : IDisposable
}
}
return BuildMergedArrayMesh(items, coarseMaterials) ?? new ArrayMesh();
return BuildMergedArrayMesh(items, coarseMaterials, bakeVertexColor) ?? new ArrayMesh();
}
private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet<Node> protectedNodes)
@ -895,7 +920,12 @@ public sealed class VehicleAssetCache : IDisposable
int Transparency,
int CullMode);
private static bool TryGetMaterialValueKey(Material mat, bool coarse, out StandardMatKey key)
private static bool TryGetMaterialValueKey(
Material mat,
bool coarse,
bool bakeVertexColor,
out StandardMatKey key,
out Color vertexTint)
{
if (mat is StandardMaterial3D sm &&
sm.AlbedoTexture is null &&
@ -908,14 +938,16 @@ public sealed class VehicleAssetCache : IDisposable
int paintTag = (mName.Contains("olive") || mName.Contains("khaki")) ? 1
: (mName.Contains("signal") || mName.Contains("orange")) ? 2
: 0;
float colorScale = coarse ? 6f : 255f;
float pbrScale = coarse ? 2f : 100f;
bool useVCol = bakeVertexColor && paintTag == 0;
vertexTint = useVCol ? sm.AlbedoColor : Colors.White;
float colorScale = coarse ? 2f : 32f;
float pbrScale = coarse ? 0f : 4f;
key = new StandardMatKey(
paintTag,
(int)MathF.Round(sm.AlbedoColor.R * colorScale),
(int)MathF.Round(sm.AlbedoColor.G * colorScale),
(int)MathF.Round(sm.AlbedoColor.B * colorScale),
(int)MathF.Round(sm.AlbedoColor.A * 10f),
useVCol ? 0 : (int)MathF.Round(sm.AlbedoColor.R * colorScale),
useVCol ? 0 : (int)MathF.Round(sm.AlbedoColor.G * colorScale),
useVCol ? 0 : (int)MathF.Round(sm.AlbedoColor.B * colorScale),
useVCol ? 10 : (int)MathF.Round(sm.AlbedoColor.A * 10f),
(int)MathF.Round(sm.Metallic * pbrScale),
(int)MathF.Round(sm.Roughness * pbrScale),
sm.EmissionEnabled,
@ -928,16 +960,21 @@ public sealed class VehicleAssetCache : IDisposable
return true;
}
key = default;
vertexTint = Colors.White;
return false;
}
private sealed class MaterialSurfaceBucket
{
public required Material? Material;
public readonly List<(Mesh Mesh, int SurfaceIdx, Transform3D RelXf)> Sources = new();
public bool UsesVertexColor;
public readonly List<(Mesh Mesh, int SurfaceIdx, Transform3D RelXf, Color VertexTint)> Sources = new();
}
private static ArrayMesh? BuildMergedArrayMesh(List<(MeshInstance3D Mi, Transform3D RelXf)> items, bool coarseMaterials = false)
private static ArrayMesh? BuildMergedArrayMesh(
List<(MeshInstance3D Mi, Transform3D RelXf)> items,
bool coarseMaterials = false,
bool bakeVertexColor = true)
{
if (items.Count == 0)
{
@ -946,7 +983,7 @@ public sealed class VehicleAssetCache : IDisposable
var buckets = new List<MaterialSurfaceBucket>();
var bucketByMatId = new Dictionary<ulong, MaterialSurfaceBucket>();
var bucketByMatVal = new Dictionary<StandardMatKey, MaterialSurfaceBucket>();
var bucketByMatVal = new Dictionary<(StandardMatKey Key, bool UseVCol), MaterialSurfaceBucket>();
MaterialSurfaceBucket? nullMatBucket = null;
for (int i = 0; i < items.Count; i++)
@ -966,6 +1003,7 @@ public sealed class VehicleAssetCache : IDisposable
}
Material? mat = mi.MaterialOverride ?? mi.GetActiveMaterial(s);
MaterialSurfaceBucket bucket;
Color vTint = Colors.White;
if (mat is null)
{
nullMatBucket ??= new MaterialSurfaceBucket { Material = null };
@ -975,12 +1013,21 @@ public sealed class VehicleAssetCache : IDisposable
}
bucket = nullMatBucket;
}
else if (TryGetMaterialValueKey(mat, coarseMaterials, out var matKey))
else if (TryGetMaterialValueKey(mat, coarseMaterials, bakeVertexColor, out var matKey, out vTint))
{
if (!bucketByMatVal.TryGetValue(matKey, out bucket!))
bool useVCol = bakeVertexColor && matKey.PaintTag == 0;
if (!bucketByMatVal.TryGetValue((matKey, useVCol), out bucket!))
{
bucket = new MaterialSurfaceBucket { Material = mat };
bucketByMatVal[matKey] = bucket;
Material bucketMat = mat;
if (useVCol && mat is StandardMaterial3D sm)
{
var vcMat = (StandardMaterial3D)sm.Duplicate();
vcMat.AlbedoColor = Colors.White;
vcMat.VertexColorUseAsAlbedo = true;
bucketMat = vcMat;
}
bucket = new MaterialSurfaceBucket { Material = bucketMat, UsesVertexColor = useVCol };
bucketByMatVal[(matKey, useVCol)] = bucket;
buckets.Add(bucket);
}
}
@ -994,7 +1041,7 @@ public sealed class VehicleAssetCache : IDisposable
buckets.Add(bucket);
}
}
bucket.Sources.Add((mesh, s, relXf));
bucket.Sources.Add((mesh, s, relXf, vTint));
}
}
@ -1011,14 +1058,14 @@ public sealed class VehicleAssetCache : IDisposable
bool anyTangent = false;
bool anyUv = false;
bool anyUv2 = false;
bool anyColor = false;
bool anyColor = bucket.UsesVertexColor;
int totalVerts = 0;
int totalIndices = 0;
var cachedArrays = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, int VertCount, int IndexCount)>(bucket.Sources.Count);
var cachedArrays = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, Color VTint, int VertCount, int IndexCount)>(bucket.Sources.Count);
for (int s = 0; s < bucket.Sources.Count; s++)
{
var (mesh, surfIdx, relXf) = bucket.Sources[s];
var (mesh, surfIdx, relXf, vTint) = bucket.Sources[s];
var arr = mesh.SurfaceGetArrays(surfIdx);
if (arr.Count <= (int)Mesh.ArrayType.Vertex ||
arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
@ -1045,7 +1092,7 @@ public sealed class VehicleAssetCache : IDisposable
totalVerts += verts.Length;
totalIndices += idxCount;
cachedArrays.Add((arr, relXf, verts.Length, idxCount));
cachedArrays.Add((arr, relXf, vTint, verts.Length, idxCount));
}
if (totalVerts == 0 || totalIndices == 0)
@ -1065,7 +1112,7 @@ public sealed class VehicleAssetCache : IDisposable
int iOffset = 0;
for (int c = 0; c < cachedArrays.Count; c++)
{
var (arr, relXf, vCount, idxCount) = cachedArrays[c];
var (arr, relXf, vTint, vCount, idxCount) = cachedArrays[c];
Vector3[] srcVerts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
bool flipWinding = relXf.Basis.Determinant() < 0f;
Basis normBasis = relXf.Basis.Inverse().Transposed();
@ -1140,11 +1187,20 @@ public sealed class VehicleAssetCache : IDisposable
{
if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray)
{
Array.Copy(arr[(int)Mesh.ArrayType.Color].AsColorArray(), 0, outColors, vOffset, vCount);
Color[] srcC = arr[(int)Mesh.ArrayType.Color].AsColorArray();
if (bucket.UsesVertexColor)
{
for (int v = 0; v < vCount; v++) outColors[vOffset + v] = srcC[v] * vTint;
}
else
{
Array.Copy(srcC, 0, outColors, vOffset, vCount);
}
}
else
{
for (int v = 0; v < vCount; v++) outColors[vOffset + v] = Colors.White;
Color fill = bucket.UsesVertexColor ? vTint : Colors.White;
for (int v = 0; v < vCount; v++) outColors[vOffset + v] = fill;
}
}
@ -1199,7 +1255,7 @@ public sealed class VehicleAssetCache : IDisposable
return outMesh.GetSurfaceCount() > 0 ? outMesh : null;
}
private static ArrayMesh DecimateMeshGrid(ArrayMesh src, float cellSize)
private static ArrayMesh DecimateMeshGrid(ArrayMesh src, float cellSize, float targetMinY)
{
var outMesh = new ArrayMesh();
float invCell = 1f / MathF.Max(0.02f, cellSize);
@ -1223,6 +1279,9 @@ public sealed class VehicleAssetCache : IDisposable
bool hasNorm = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array;
Vector3[]? norms = hasNorm ? arr[(int)Mesh.ArrayType.Normal].AsVector3Array() : null;
bool hasColor = arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray;
Color[]? colors = hasColor ? arr[(int)Mesh.ArrayType.Color].AsColorArray() : null;
bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array;
int[]? indices = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null;
int triVertCount = indices is not null ? indices.Length : verts.Length;
@ -1231,7 +1290,9 @@ public sealed class VehicleAssetCache : IDisposable
var vertToCellIdx = new int[verts.Length];
var accumPos = new List<Vector3>(verts.Length / 2 + 16);
var accumNorm = norms is not null ? new List<Vector3>(verts.Length / 2 + 16) : null;
var accumColor = colors is not null ? new List<Color>(verts.Length / 2 + 16) : null;
var counts = new List<int>(verts.Length / 2 + 16);
var cellMinY = new List<float>(verts.Length / 2 + 16);
for (int v = 0; v < verts.Length; v++)
{
@ -1247,13 +1308,17 @@ public sealed class VehicleAssetCache : IDisposable
cellToNewIdx[key] = ci;
accumPos.Add(p);
if (accumNorm is not null) accumNorm.Add(norms![v]);
if (accumColor is not null) accumColor.Add(colors![v]);
counts.Add(1);
cellMinY.Add(p.Y);
}
else
{
accumPos[ci] += p;
if (accumNorm is not null) accumNorm[ci] += norms![v];
if (accumColor is not null) accumColor[ci] += colors![v];
counts[ci]++;
if (p.Y < cellMinY[ci]) cellMinY[ci] = p.Y;
}
vertToCellIdx[v] = ci;
}
@ -1287,20 +1352,30 @@ public sealed class VehicleAssetCache : IDisposable
var outVerts = new Vector3[accumPos.Count];
Vector3[]? outNorms = accumNorm is not null ? new Vector3[accumPos.Count] : null;
Color[]? outColors = accumColor is not null ? new Color[accumPos.Count] : null;
for (int i = 0; i < accumPos.Count; i++)
{
outVerts[i] = accumPos[i] / counts[i];
Vector3 avg = accumPos[i] / counts[i];
// Preserve exact ground-contacting vertex minY so far LOD ChassisDrops never float or sink
float y = cellMinY[i] <= targetMinY + 0.08f ? cellMinY[i] : avg.Y;
if (y < targetMinY) y = targetMinY;
outVerts[i] = new Vector3(avg.X, y, avg.Z);
if (outNorms is not null)
{
Vector3 n = accumNorm![i];
outNorms[i] = n.LengthSquared() > 1e-8f ? n.Normalized() : Vector3.Up;
}
if (outColors is not null)
{
outColors[i] = accumColor![i] / counts[i];
}
}
var newArr = new Godot.Collections.Array();
newArr.Resize((int)Mesh.ArrayType.Max);
newArr[(int)Mesh.ArrayType.Vertex] = outVerts;
if (outNorms is not null) newArr[(int)Mesh.ArrayType.Normal] = outNorms;
if (outColors is not null) newArr[(int)Mesh.ArrayType.Color] = outColors;
newArr[(int)Mesh.ArrayType.Index] = outIndices.ToArray();
int newSurf = outMesh.GetSurfaceCount();

View file

@ -73,6 +73,8 @@ public sealed class VehicleVisualInstance
private readonly VehicleAssetCache _cache;
private readonly VehicleAssetCache.VehicleTemplate _template;
private readonly Dictionary<string, BoundHardpoint> _hardpoints = new(StringComparer.Ordinal);
private readonly List<BoundHardpoint> _hardpointList = new();
private readonly List<(int X, int Y)> _activeCells = new();
private readonly Dictionary<string, BoundJoint> _joints = new(StringComparer.Ordinal);
private readonly Dictionary<string, Node3D> _namedNodes = new(StringComparer.Ordinal);
private readonly Dictionary<string, Transform3D> _restLocalByName = new(StringComparer.Ordinal);
@ -83,23 +85,30 @@ public sealed class VehicleVisualInstance
private readonly HashSet<string> _shearedHardpoints = new(StringComparer.Ordinal);
private readonly VehicleRigAnimator.RigState _rigState = new();
private readonly VehicleVisualRole _role;
private readonly string _chassisId;
private MeshInstance3D? _lodStaticMesh;
private bool _isStaticLod;
private bool _castShadows = true;
private bool _hasAnyStrippedCell;
public static double PerfDamageHeatMs;
public static int PerfMaterialDupCount;
private VehicleVisualInstance(
VehicleAssetCache cache,
VehicleAssetCache.VehicleTemplate template,
Node3D root,
Node3D modelRoot,
string chassisId)
string chassisId,
VehicleVisualRole role)
{
_cache = cache;
_template = template;
Root = root;
ModelRoot = modelRoot;
_chassisId = chassisId;
_role = role;
int w = template.Package.GridWidth;
int h = template.Package.GridHeight;
@ -124,6 +133,7 @@ public sealed class VehicleVisualInstance
public IReadOnlyDictionary<string, BoundJoint> Joints => _joints;
public int BoundHardpointCount => _hardpoints.Count;
public bool IsStaticLod => _isStaticLod;
public bool HasAnyStrippedCell => _hasAnyStrippedCell;
public void SetLodState(bool useStaticLod, bool castShadows)
{
@ -146,6 +156,10 @@ public sealed class VehicleVisualInstance
}
return;
}
if (_hasAnyStrippedCell)
{
useStaticLod = false;
}
if (_isStaticLod != useStaticLod)
{
_isStaticLod = useStaticLod;
@ -197,7 +211,7 @@ public sealed class VehicleVisualInstance
};
ApplyRoleTint(dropMesh, role);
root.AddChild(dropMesh);
return new VehicleVisualInstance(cache, template, root, dropMesh, chassisId);
return new VehicleVisualInstance(cache, template, root, dropMesh, chassisId, role);
}
if (template.SceneTemplate.Duplicate() is not Node3D modelRoot)
@ -223,7 +237,7 @@ public sealed class VehicleVisualInstance
}
root.AddChild(lodMesh);
var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId)
var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId, role)
{
_lodStaticMesh = lodMesh
};
@ -315,12 +329,14 @@ public sealed class VehicleVisualInstance
throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing anchor node '{rec.AnchorId}'.");
}
_hardpoints[hp.Id] = new BoundHardpoint
var bh = new BoundHardpoint
{
Spec = hp,
AnchorInfo = anchorInfo,
AnchorNode = anchorNode
};
_hardpoints[hp.Id] = bh;
_hardpointList.Add(bh);
}
// Apply role palette tinting to painted hull meshes before binding per-cell damage clones
@ -332,6 +348,16 @@ public sealed class VehicleVisualInstance
// Bind detachable exterior armor/shroud parts to their (CellX, CellY)
int w = pkg.GridWidth;
int h = pkg.GridHeight;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
if (spec.IsActive(x, y))
{
_activeCells.Add((x, y));
}
}
}
foreach (var dp in _template.DetachableParts)
{
if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h)
@ -415,81 +441,84 @@ public sealed class VehicleVisualInstance
/// </summary>
public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity)
{
int w = Math.Min(grid.Spec.Width, _template.Package.GridWidth);
int h = Math.Min(grid.Spec.Height, _template.Package.GridHeight);
long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0;
Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position;
// 1. Part-by-cell detachment & cell scorch/heat tinting
for (int y = 0; y < h; y++)
for (int c = 0; c < _activeCells.Count; c++)
{
for (int x = 0; x < w; x++)
var (x, y) = _activeCells[c];
float armor = grid.Armor[x, y];
var parts = _cellParts[x, y];
if (!_strippedCells[x, y] && armor <= 0.01f)
{
if (!grid.Spec.IsActive(x, y))
{
continue;
}
float armor = grid.Armor[x, y];
var parts = _cellParts[x, y];
if (!_strippedCells[x, y] && armor <= 0.01f)
{
_strippedCells[x, y] = true;
for (int i = 0; i < parts.Count; i++)
{
var pb = parts[i];
if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node))
{
pb.Detached = true;
debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true);
}
}
continue;
}
if (parts.Count == 0)
{
continue;
}
float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]);
float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f);
float heatGlow = Math.Clamp((grid.Temperature[x, y] - 65f) / 110f, 0f, 1f);
float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f;
if (dmgFrac < 0.25f && heatGlow < 0.05f)
{
continue;
}
_strippedCells[x, y] = true;
_hasAnyStrippedCell = true;
for (int i = 0; i < parts.Count; i++)
{
var pb = parts[i];
if (pb.Detached || !GodotObject.IsInstanceValid(pb.Node))
if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node))
{
continue;
pb.Detached = true;
pb.Node.Visible = true;
debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true);
}
if (MathF.Abs(pb.LastTintScore - tintScore) < 0.5f)
{
continue;
}
pb.LastTintScore = tintScore;
ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow);
}
continue;
}
if (parts.Count == 0)
{
continue;
}
float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]);
float temp = grid.Temperature[x, y];
if (armor > maxArmor * 0.75f && temp < 70.5f)
{
continue;
}
float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f);
float heatGlow = Math.Clamp((temp - 65f) / 110f, 0f, 1f);
float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f;
if (dmgFrac < 0.25f && heatGlow < 0.05f)
{
continue;
}
for (int i = 0; i < parts.Count; i++)
{
var pb = parts[i];
if (pb.Detached || !GodotObject.IsInstanceValid(pb.Node))
{
continue;
}
if (MathF.Abs(pb.LastTintScore - tintScore) < 0.5f)
{
continue;
}
pb.LastTintScore = tintScore;
ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow);
}
}
// 2. Hardpoint shear & mounted gear heat glow
foreach (var bh in _hardpoints.Values)
for (int i = 0; i < _hardpointList.Count; i++)
{
var bh = _hardpointList[i];
if (!_shearedHardpoints.Contains(bh.Spec.Id) && !grid.IsHardpointOperational(bh.Spec))
{
_shearedHardpoints.Add(bh.Spec.Id);
_hasAnyStrippedCell = true;
if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode))
{
Node3D sheared = bh.GearNode;
bh.GearNode = null;
bh.MountedModuleId = null;
bh.GearHeatMaterials.Clear();
sheared.Visible = true;
debris.SpawnDetachedPart(sheared, blastOrigin, vehicleVelocity, impulseScale: 1.15f, applyScorch: true);
}
continue;
@ -510,11 +539,22 @@ public sealed class VehicleVisualInstance
for (int m = 0; m < bh.GearHeatMaterials.Count; m++)
{
StandardMaterial3D gm = bh.GearHeatMaterials[m];
gm.EmissionEnabled = heatFrac > 0.02f;
gm.Emission = new Color(1.0f, 0.34f, 0.08f);
gm.EmissionEnergyMultiplier = heatFrac * 2.2f;
bool wantEmit = heatFrac > 0.02f;
if (gm.EmissionEnabled != wantEmit || wantEmit)
{
gm.EmissionEnabled = wantEmit;
if (wantEmit)
{
gm.Emission = new Color(1.0f, 0.34f, 0.08f);
gm.EmissionEnergyMultiplier = heatFrac * 2.2f;
}
}
}
}
if (t0 != 0)
{
PerfDamageHeatMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency;
}
}
public static Node3D CreateStandaloneGearVisual(VehicleAssetCache cache, ModuleSpec mod)
@ -522,13 +562,13 @@ public sealed class VehicleVisualInstance
var list = new List<StandardMaterial3D>();
GearVisualRecipe recipe = ResolveGearRecipe(mod);
var template = cache.GetOrLoadGear(recipe.GearGlbId);
if (template.SceneTemplate.Duplicate() is not Node3D node)
var node = new MeshInstance3D
{
return new Node3D { Name = $"Gear_{mod.Id}" };
}
node.Name = $"GearDrop_{mod.Id}";
node.Scale = recipe.VariantScale;
node.Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f);
Name = $"GearDrop_{mod.Id}",
Mesh = template.BakedDropMesh,
Scale = recipe.VariantScale,
Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f)
};
if (recipe.PaintTint.HasValue || recipe.AccentTint.HasValue)
{
ApplyGearVariantTint(node, recipe.PaintTint, recipe.AccentTint, list);
@ -544,9 +584,18 @@ public sealed class VehicleVisualInstance
{
GearVisualRecipe recipe = ResolveGearRecipe(mod);
VehicleAssetCache.GearTemplate gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId);
if (gearTemplate.SceneTemplate.Duplicate() is not Node3D gearNode)
Node3D gearNode;
if (_role == VehicleVisualRole.Player)
{
throw new InvalidOperationException($"Failed to duplicate gear GLB '{recipe.GearGlbId}'.");
if (gearTemplate.SceneTemplate.Duplicate() is not Node3D dup)
{
throw new InvalidOperationException($"Failed to duplicate gear GLB '{recipe.GearGlbId}'.");
}
gearNode = dup;
}
else
{
gearNode = new MeshInstance3D { Mesh = gearTemplate.BakedDropMesh };
}
gearNode.Name = $"Mounted_{mod.Id}_{hp.Id}";
@ -789,6 +838,7 @@ public sealed class VehicleVisualInstance
StandardMaterial3D copy = src is StandardMaterial3D sm
? (StandardMaterial3D)sm.Duplicate()
: new StandardMaterial3D { AlbedoColor = new Color(0.32f, 0.34f, 0.30f), Roughness = 0.6f, Metallic = 0.35f };
PerfMaterialDupCount++;
binding.Node.SetSurfaceOverrideMaterial(s, copy);
binding.Materials.Add((copy, copy.AlbedoColor, copy.Roughness));
}

View file

@ -198,6 +198,72 @@ public partial class Smoke : Node
}
}
// Regression check (Finding 4): 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants)
// and passive Track throttling preserves DirtyTileMask until all tiles are baked without skipping via _rebakeCursor.
{
// Flush any lingering track rebakes first so baseline is clean
for (int flush = 0; flush < 32 && _main.Session.State.Terrain.DirtyTileMask != 0UL; flush++)
{
_main.Terrain.Sync(_main.Session.State.Terrain);
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
(float Qx, float Qz)[] quadrants = { (-1f, -1f), (1f, -1f), (-1f, 1f), (1f, 1f) };
float[] qGpuBefore = new float[4];
if (!isHeadless)
{
for (int q = 0; q < 4; q++)
{
Check(_main.Terrain.TrySampleBakedHeight(quadrants[q].Qx, quadrants[q].Qz, out qGpuBefore[q]),
$"Expected GPU readback before 4-tile boundary crater at quadrant {q}");
}
}
int rebakes4Before = _main.Terrain.DirtyRebakes;
_main.Session.State.Terrain.StampCrater(0f, 0f, radius: 6f, depth: 1.4f);
_main.Terrain.Sync(_main.Session.State.Terrain); // Sync#1
Check(_main.Terrain.DirtyRebakes == rebakes4Before + 4,
$"Expected 4-tile boundary crater at (0,0) to bake all 4 tiles on Sync#1, got {_main.Terrain.DirtyRebakes - rebakes4Before}");
Check(_main.Session.State.Terrain.StructuralDirtyTileMask == 0UL,
"Expected StructuralDirtyTileMask == 0 after Sync#1 on 4-tile boundary crater");
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
if (!isHeadless)
{
for (int q = 0; q < 4; q++)
{
float qCpu = _main.Session.State.Terrain.SampleHeight(quadrants[q].Qx, quadrants[q].Qz);
bool ok = _main.Terrain.TrySampleBakedHeight(quadrants[q].Qx, quadrants[q].Qz, out float qGpu);
Check(ok, $"Expected GPU readback on quadrant {q} after 4-tile boundary crater");
if (ok)
{
float qErr = MathF.Abs(qGpu - qCpu);
GD.Print($"SMOKE INFO: 4-tile crater Q{q} ({quadrants[q].Qx},{quadrants[q].Qz}) cpu={qCpu:F4}m gpu={qGpu:F4}m err={qErr:F4}m");
Check(qErr <= 0.20f, $"4-tile crater quadrant {q} GPU error {qErr:F4}m > 0.20m");
Check(qGpu < qGpuBefore[q] - 0.35f, $"4-tile crater quadrant {q} did not depress on Sync#1 (before={qGpuBefore[q]:F4}, after={qGpu:F4})");
}
}
}
// Stamp 3 passive tracks in adjacent tiles so _rebakeCursor must advance across Sync#1 and Sync#2 without skipping
int rebakesTrackBefore = _main.Terrain.DirtyRebakes;
_main.Session.State.Terrain.StampTrack(-480f, -480f, 0f, 2f, 3f);
_main.Session.State.Terrain.StampTrack(-288f, -480f, 0f, 2f, 3f);
_main.Session.State.Terrain.StampTrack(-96f, -480f, 0f, 2f, 3f);
_main.Terrain.Sync(_main.Session.State.Terrain);
Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 2,
$"Expected Sync#1 to throttle 3 passive tracks to 2 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}");
Check(_main.Session.State.Terrain.DirtyTileMask != 0UL,
"Expected DirtyTileMask to stay non-zero while 1 passive track tile remains dirty");
_main.Terrain.Sync(_main.Session.State.Terrain);
Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 3,
$"Expected Sync#2 to bake remaining 3rd passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}");
Check(_main.Session.State.Terrain.DirtyTileMask == 0UL,
"Expected DirtyTileMask == 0 after all passive track tiles baked");
}
_main.SetPhysicsProcess(true);
await VerifyHudAndShadersAsync(isHeadless);
@ -409,6 +475,46 @@ public partial class Smoke : Node
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}");
// Finding 5 GPU check: LabelsOverlay redraws on temp-only change & compatibility highlights update when Cargo[0] swaps at unchanged index 0
{
raptorGrid.Cargo.Clear();
Check(raptorGrid.TryAddCargo(Catalog.Autocannon), "Expected Autocannon in Raptor Cargo[0]");
vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0);
vpGrid.SetThermalInstant(false);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
int drawCountBeforeTemp = vpGrid.LabelsDrawCount;
string? tagBeforeTemp = vpGrid.GetLastDrawnLabel("hp.engine.chest");
var cargoImgWeapon = gridVp.GetTexture().GetImage();
// Temp-only change (no armor hit, no mount change)
raptorGrid.InjectHardpointHeat("hp.engine.chest", 4200f);
raptorGrid.StepHeat(0.1f);
vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
int drawCountAfterTemp = vpGrid.LabelsDrawCount;
string? tagAfterTemp = vpGrid.GetLastDrawnLabel("hp.engine.chest");
Check(drawCountAfterTemp > drawCountBeforeTemp,
$"Expected LabelsOverlay to redraw on temp-only change ({drawCountBeforeTemp} -> {drawCountAfterTemp})");
Check(!string.Equals(tagBeforeTemp, tagAfterTemp, StringComparison.Ordinal),
$"Expected engine temp label text to update on temp-only change ('{tagBeforeTemp}' -> '{tagAfterTemp}')");
// Cargo[0] replacement at unchanged selectedCargoIndex == 0 (Weapon -> Radiator)
raptorGrid.Cargo[0] = Catalog.CopperRad;
vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var cargoImgRad = gridVp.GetTexture().GetImage();
int cargoDiff = CountDifferentPixels(cargoImgWeapon, cargoImgRad, 0.05f);
GD.Print($"SMOKE INFO: InventoryGrid Cargo[0] swap diff pixels={cargoDiff}, label '{tagBeforeTemp}'->'{tagAfterTemp}'");
Check(cargoDiff > 50,
$"Expected Cargo[0] replacement at unchanged index 0 to update compatibility highlight pixels (>50), got {cargoDiff}");
}
gridVp.QueueFree();
// GPU verification for panel_chrome.gdshader
@ -789,6 +895,27 @@ public partial class Smoke : Node
}
GD.Print($"SMOKE INFO: ChassisDrop max ground err={maxGroundErr:F4}m across {added.Count} chassis");
// Also verify far LOD (BakedLodFarMesh) ChassisDrop grounding stays <= 0.05m across all 15 chassis
float maxFarGroundErr = 0f;
for (int i = 0; i < added.Count; i++)
{
var d = added[i];
Node3D? dropNode = _main.Arena.GetNodeOrNull<Node3D>($"GroundDrops/Drop_{d.Id}");
Node3D? actorNode = dropNode?.GetNodeOrNull<Node3D>($"Actor_{d.Chassis!.Id}");
MeshInstance3D? dropMesh = actorNode?.GetNodeOrNull<MeshInstance3D>($"Model_{d.Chassis!.Id}");
if (dropNode is not null && actorNode is not null && dropMesh is not null)
{
dropMesh.Mesh = cache.GetOrLoadVehicle(d.Chassis!.Id).BakedLodFarMesh;
float minFarWorldY = ComputeSubtreeMinWorldY(actorNode, dropNode.Position.Y);
float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z);
float err = MathF.Abs(minFarWorldY - terrainY);
if (err > maxFarGroundErr) maxFarGroundErr = err;
Check(err <= 0.05f,
$"Far LOD ChassisDrop '{d.Chassis!.Id}' buried/floating: minFarWorldY={minFarWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m");
}
}
GD.Print($"SMOKE INFO: Far LOD ChassisDrop max ground err={maxFarGroundErr:F4}m across {added.Count} chassis");
for (int i = 0; i < added.Count; i++)
{
added[i].PickedUp = true;
@ -929,6 +1056,49 @@ public partial class Smoke : Node
Check(sawPatron, "Expected at least one alive Patron spectator in arena");
}
// 9. Finding 3: Stripped distant rig (180m) detaches debris immediately without popping armor back on at far LOD
{
var debris = new DebrisSystem { Name = "SmokeDistantStripTest" };
AddChild(debris);
var specGrid = Catalog.CreateWithDefaultLoadout(Catalog.Anvil);
var specVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.SpectatorPatron);
specVis.Root.Position = new Vector3(0f, 0f, 180f);
AddChild(specVis.Root);
specVis.SyncMountedGear(specGrid);
specVis.SetLodState(useStaticLod: true, castShadows: false);
Check(specVis.IsStaticLod && !specVis.ModelRoot.Visible,
"Expected intact distant rig at 180m to start in static far LOD");
int stripCx = -1, stripCy = -1;
for (int cy = 0; cy < specGrid.Spec.Height && stripCx < 0; cy++)
{
for (int cx = 0; cx < specGrid.Spec.Width; cx++)
{
if (specVis.CountDetachablePartsForCell(cx, cy) > 0)
{
stripCx = cx;
stripCy = cy;
break;
}
}
}
Check(stripCx >= 0, "Expected Anvil distant rig to have detachable cell parts");
if (stripCx >= 0)
{
specGrid.Armor[stripCx, stripCy] = 0f;
}
specVis.SyncDamageAndHeat(specGrid, debris, Vector3.Zero);
specVis.SetLodState(useStaticLod: true, castShadows: false);
Check(debris.ActiveCount >= 1,
$"Expected distant stripped rig at 180m to detach debris immediately, got {debris.ActiveCount}");
Check(specVis.HasAnyStrippedCell && !specVis.IsStaticLod && specVis.ModelRoot.Visible,
"Expected distant stripped rig to keep ModelRoot visible without popping armor back on at far LOD");
specVis.Root.QueueFree();
debris.QueueFree();
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}