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 MeshInstance3D? LaserMesh;
public SpectatorStance? LastHaloStance; public SpectatorStance? LastHaloStance;
public bool LastLaserVisible; public bool LastLaserVisible;
public float RigDtAccum;
public int RigSkipFrames;
} }
private sealed class DropVisualEntry private sealed class DropVisualEntry
@ -178,30 +180,80 @@ public partial class ArenaRenderer : Node3D
{ {
ClearChildren(_staticGroup); 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++) for (int i = 0; i < state.ArenaCoverBoxes.Count; i++)
{ {
var b = state.ArenaCoverBoxes[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) }, st = new SurfaceTool();
MaterialOverride = _coverMat, st.Begin(Mesh.PrimitiveType.Triangles);
Position = new Vector3(b.X, b.Y, b.Z) quadArrays[qIdx] = st;
}; }
_staticGroup.AddChild(mesh); AppendBoxToSurfaceTool(st, new Vector3(b.X, b.Y, b.Z), new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f));
} }
for (int q = 0; q < 4; q++)
{
if (quadArrays[q] is null) continue;
quadArrays[q].GenerateNormals();
_staticGroup.AddChild(new MeshInstance3D
{
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++) for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++)
{ {
var b = state.ArenaBoundaryBoxes[i]; var b = state.ArenaBoundaryBoxes[i];
var mesh = new MeshInstance3D AppendBoxToSurfaceTool(bermSt, new Vector3(b.X, b.Y, b.Z), new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f));
{
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);
} }
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() private void ClearDynamicVisuals()
@ -318,22 +370,29 @@ public partial class ArenaRenderer : Node3D
vis.Visual.Root.Rotation = new Vector3(0f, c.Yaw, 0f); vis.Visual.Root.Rotation = new Vector3(0f, c.Yaw, 0f);
} }
bool useStaticLod = false; float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f;
bool castShadows = true; bool castShadows = !hasCam || c.IsPlayer || distSq <= 115f * 115f;
if (hasCam && !c.IsPlayer) vis.Visual.SetLodState(useStaticLod: false, castShadows);
{
float distSq = pos.DistanceSquaredTo(camPos);
useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f;
castShadows = distSq <= 150f * 150f;
}
vis.Visual.SetLodState(useStaticLod, castShadows);
if (!useStaticLod)
{
vis.Visual.SyncMountedGear(c.Grid); vis.Visual.SyncMountedGear(c.Grid);
if (!hasCam || c.IsPlayer || distSq <= 130f * 130f)
{
vis.RigDtAccum = 0f;
vis.RigSkipFrames = 0;
VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt); 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.Root.Rotation = new Vector3(0f, s.Yaw, 0f);
} }
vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel);
bool useStaticLod = false; bool useStaticLod = false;
bool castShadows = true; bool castShadows = true;
if (hasCam) if (hasCam)
{ {
float distSq = specPos.DistanceSquaredTo(camPos); float distSq = specPos.DistanceSquaredTo(camPos);
castShadows = distSq <= 115f * 115f;
if (s.Stance == SpectatorStance.Neutral && !vis.Visual.HasAnyStrippedCell)
{
useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f; useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f;
castShadows = distSq <= 150f * 150f; }
} }
vis.Visual.SetLodState(useStaticLod, castShadows); vis.Visual.SetLodState(useStaticLod, castShadows);
@ -447,7 +511,6 @@ public partial class ArenaRenderer : Node3D
vis.Visual.SyncMountedGear(s.Grid); vis.Visual.SyncMountedGear(s.Grid);
VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis); VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis);
vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel);
} }
// Status halo // Status halo
@ -610,11 +673,19 @@ public partial class ArenaRenderer : Node3D
entry.Node.Visible = true; entry.Node.Visible = true;
} }
if (d.Module is not null) if (d.Module is not null)
{
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; 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.Position = new Vector3(d.X, entry.BaseY + bob, d.Z);
entry.Node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f); entry.Node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f);
} }
}
else else
{ {
if (isNew) if (isNew)
@ -629,7 +700,7 @@ public partial class ArenaRenderer : Node3D
{ {
float d2 = new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos); float d2 = new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos);
useFarLod = cv.IsStaticLod ? d2 > 126f * 126f : d2 > 130f * 130f; useFarLod = cv.IsStaticLod ? d2 > 126f * 126f : d2 > 130f * 130f;
castShadows = d2 <= 150f * 150f; castShadows = d2 <= 95f * 95f;
} }
cv.SetLodState(useFarLod, castShadows); cv.SetLodState(useFarLod, castShadows);
} }

View file

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

View file

@ -88,8 +88,59 @@ public partial class Main : Node3D
} }
Reset(_seed); Reset(_seed);
if (_perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1" && _session is not null)
{
SetupPerfCombatScenario(_session);
}
_perfLastFrameTick = Stopwatch.GetTimestamp(); _perfLastFrameTick = Stopwatch.GetTimestamp();
_perfLastDirtyRebakes = _terrain.DirtyRebakes; _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() public override void _ExitTree()
@ -343,6 +394,7 @@ public partial class Main : Node3D
GD.Print($"TimePhysicsProcessMs: avg={Avg(_perfTimePhysicsProcess):F2}"); GD.Print($"TimePhysicsProcessMs: avg={Avg(_perfTimePhysicsProcess):F2}");
GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count: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($"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) foreach (var kv in _arena.AssetCache.Vehicles)
{ {
int tris = 0; int tris = 0;

View file

@ -54,6 +54,8 @@ public partial class TerrainRenderer : Node3D
public int BakedTileCount { get; private set; } public int BakedTileCount { get; private set; }
public int DirtyRebakes { get; private set; } public int DirtyRebakes { get; private set; }
public static double PerfBakeTileMs;
public static int PerfBakeTileCalls;
public override void _Ready() public override void _Ready()
{ {
@ -117,28 +119,41 @@ public partial class TerrainRenderer : Node3D
const int totalTiles = TerrainField.TileGridCount * TerrainField.TileGridCount; 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 tz = 0; tz < TerrainField.TileGridCount; tz++)
{ {
for (int tx = 0; tx < TerrainField.TileGridCount; tx++) for (int tx = 0; tx < TerrainField.TileGridCount; tx++)
{ {
var tile = _tiles[tx, tz]; var tile = _tiles[tx, tz];
int version = terrain.TileVersions[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); BakeTile(tx, tz, tile, terrain);
if (isUninitialized)
{
BakedTileCount++; BakedTileCount++;
}
else
{
DirtyRebakes++;
}
tile.BakedVersion = version; 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; int rebakedThisSync = 0;
bool anyRemainingDirty = false; bool anyRemainingDirty = false;
int startCursor = _rebakeCursor;
for (int step = 0; step < totalTiles; step++) for (int step = 0; step < totalTiles; step++)
{ {
int idx = (_rebakeCursor + step) % totalTiles; int idx = (startCursor + step) % totalTiles;
int tx = idx % TerrainField.TileGridCount; int tx = idx % TerrainField.TileGridCount;
int tz = idx / TerrainField.TileGridCount; int tz = idx / TerrainField.TileGridCount;
var tile = _tiles[tx, tz]; var tile = _tiles[tx, tz];
@ -169,7 +184,7 @@ public partial class TerrainRenderer : Node3D
public void UpdateTileLod(Vector3 camPos) public void UpdateTileLod(Vector3 camPos)
{ {
const float nearRadiusSq = 240f * 240f; 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 tz = 0; tz < TerrainField.TileGridCount; tz++)
{ {
for (int tx = 0; tx < TerrainField.TileGridCount; tx++) 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) 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.HeightCanvas);
ClearCanvasChildren(tile.AlbedoCanvas); ClearCanvasChildren(tile.AlbedoCanvas);
@ -393,6 +409,11 @@ public partial class TerrainRenderer : Node3D
tile.HeightViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; tile.HeightViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once;
tile.AlbedoViewport.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) 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 Id { get; init; }
public required string GlbPath { get; init; } public required string GlbPath { get; init; }
public required Node3D SceneTemplate { get; init; } public required Node3D SceneTemplate { get; init; }
public required ArrayMesh BakedDropMesh { get; init; }
public required Vector3 Size { get; init; } public required Vector3 Size { get; init; }
public required float MinY { get; init; } public required float MinY { get; init; }
public required Vector3 LocalModelForward { 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 // C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template
ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false); ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false);
ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true); 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 return new VehicleTemplate
{ {
@ -489,6 +490,7 @@ public sealed class VehicleAssetCache : IDisposable
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax); ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
MergeGearSubMeshes(sceneRoot, gearId); MergeGearSubMeshes(sceneRoot, gearId);
ArrayMesh bakedDropMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false, bakeVertexColor: false);
Vector3 localFwd = new Vector3(0f, 0f, 1f); Vector3 localFwd = new Vector3(0f, 0f, 1f);
return new GearTemplate return new GearTemplate
@ -496,6 +498,7 @@ public sealed class VehicleAssetCache : IDisposable
Id = gearId, Id = gearId,
GlbPath = glbPath, GlbPath = glbPath,
SceneTemplate = sceneRoot, SceneTemplate = sceneRoot,
BakedDropMesh = bakedDropMesh,
Size = bMax - bMin, Size = bMax - bMin,
MinY = bMin.Y, MinY = bMin.Y,
LocalModelForward = localFwd 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) foreach (var (rigidParent, items) in staticGroups)
{ {
if (rigidParent is MeshInstance3D parentMi && CanMergeMeshInstance(parentMi)) if (rigidParent is MeshInstance3D parentMi && CanMergeMeshInstance(parentMi))
@ -748,6 +752,7 @@ public sealed class VehicleAssetCache : IDisposable
{ {
parentMi.MaterialOverride = null; parentMi.MaterialOverride = null;
parentMi.Mesh = merged; parentMi.Mesh = merged;
mergedProtectedMeshes.Add(parentMi);
for (int i = 0; i < items.Count; i++) for (int i = 0; i < items.Count; i++)
{ {
ReparentChildrenAndRemove(items[i].Mi); 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 // Prune empty non-protected grouping nodes left behind
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, protectedNodes); PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, protectedNodes);
@ -844,7 +869,7 @@ public sealed class VehicleAssetCache : IDisposable
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, keptNodes); 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>(); var allMeshes = new List<MeshInstance3D>();
CollectAllMeshInstances(sceneRoot, allMeshes); 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) private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet<Node> protectedNodes)
@ -895,7 +920,12 @@ public sealed class VehicleAssetCache : IDisposable
int Transparency, int Transparency,
int CullMode); 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 && if (mat is StandardMaterial3D sm &&
sm.AlbedoTexture is null && sm.AlbedoTexture is null &&
@ -908,14 +938,16 @@ public sealed class VehicleAssetCache : IDisposable
int paintTag = (mName.Contains("olive") || mName.Contains("khaki")) ? 1 int paintTag = (mName.Contains("olive") || mName.Contains("khaki")) ? 1
: (mName.Contains("signal") || mName.Contains("orange")) ? 2 : (mName.Contains("signal") || mName.Contains("orange")) ? 2
: 0; : 0;
float colorScale = coarse ? 6f : 255f; bool useVCol = bakeVertexColor && paintTag == 0;
float pbrScale = coarse ? 2f : 100f; vertexTint = useVCol ? sm.AlbedoColor : Colors.White;
float colorScale = coarse ? 2f : 32f;
float pbrScale = coarse ? 0f : 4f;
key = new StandardMatKey( key = new StandardMatKey(
paintTag, paintTag,
(int)MathF.Round(sm.AlbedoColor.R * colorScale), useVCol ? 0 : (int)MathF.Round(sm.AlbedoColor.R * colorScale),
(int)MathF.Round(sm.AlbedoColor.G * colorScale), useVCol ? 0 : (int)MathF.Round(sm.AlbedoColor.G * colorScale),
(int)MathF.Round(sm.AlbedoColor.B * colorScale), useVCol ? 0 : (int)MathF.Round(sm.AlbedoColor.B * colorScale),
(int)MathF.Round(sm.AlbedoColor.A * 10f), useVCol ? 10 : (int)MathF.Round(sm.AlbedoColor.A * 10f),
(int)MathF.Round(sm.Metallic * pbrScale), (int)MathF.Round(sm.Metallic * pbrScale),
(int)MathF.Round(sm.Roughness * pbrScale), (int)MathF.Round(sm.Roughness * pbrScale),
sm.EmissionEnabled, sm.EmissionEnabled,
@ -928,16 +960,21 @@ public sealed class VehicleAssetCache : IDisposable
return true; return true;
} }
key = default; key = default;
vertexTint = Colors.White;
return false; return false;
} }
private sealed class MaterialSurfaceBucket private sealed class MaterialSurfaceBucket
{ {
public required Material? Material; 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) if (items.Count == 0)
{ {
@ -946,7 +983,7 @@ public sealed class VehicleAssetCache : IDisposable
var buckets = new List<MaterialSurfaceBucket>(); var buckets = new List<MaterialSurfaceBucket>();
var bucketByMatId = new Dictionary<ulong, 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; MaterialSurfaceBucket? nullMatBucket = null;
for (int i = 0; i < items.Count; i++) for (int i = 0; i < items.Count; i++)
@ -966,6 +1003,7 @@ public sealed class VehicleAssetCache : IDisposable
} }
Material? mat = mi.MaterialOverride ?? mi.GetActiveMaterial(s); Material? mat = mi.MaterialOverride ?? mi.GetActiveMaterial(s);
MaterialSurfaceBucket bucket; MaterialSurfaceBucket bucket;
Color vTint = Colors.White;
if (mat is null) if (mat is null)
{ {
nullMatBucket ??= new MaterialSurfaceBucket { Material = null }; nullMatBucket ??= new MaterialSurfaceBucket { Material = null };
@ -975,12 +1013,21 @@ public sealed class VehicleAssetCache : IDisposable
} }
bucket = nullMatBucket; 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 }; Material bucketMat = mat;
bucketByMatVal[matKey] = bucket; 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); buckets.Add(bucket);
} }
} }
@ -994,7 +1041,7 @@ public sealed class VehicleAssetCache : IDisposable
buckets.Add(bucket); 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 anyTangent = false;
bool anyUv = false; bool anyUv = false;
bool anyUv2 = false; bool anyUv2 = false;
bool anyColor = false; bool anyColor = bucket.UsesVertexColor;
int totalVerts = 0; int totalVerts = 0;
int totalIndices = 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++) 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); var arr = mesh.SurfaceGetArrays(surfIdx);
if (arr.Count <= (int)Mesh.ArrayType.Vertex || if (arr.Count <= (int)Mesh.ArrayType.Vertex ||
arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
@ -1045,7 +1092,7 @@ public sealed class VehicleAssetCache : IDisposable
totalVerts += verts.Length; totalVerts += verts.Length;
totalIndices += idxCount; totalIndices += idxCount;
cachedArrays.Add((arr, relXf, verts.Length, idxCount)); cachedArrays.Add((arr, relXf, vTint, verts.Length, idxCount));
} }
if (totalVerts == 0 || totalIndices == 0) if (totalVerts == 0 || totalIndices == 0)
@ -1065,7 +1112,7 @@ public sealed class VehicleAssetCache : IDisposable
int iOffset = 0; int iOffset = 0;
for (int c = 0; c < cachedArrays.Count; c++) 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(); Vector3[] srcVerts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
bool flipWinding = relXf.Basis.Determinant() < 0f; bool flipWinding = relXf.Basis.Determinant() < 0f;
Basis normBasis = relXf.Basis.Inverse().Transposed(); 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) 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 else
{ {
for (int v = 0; v < vCount; v++) outColors[vOffset + v] = Colors.White; Array.Copy(srcC, 0, outColors, vOffset, vCount);
}
}
else
{
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; 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(); var outMesh = new ArrayMesh();
float invCell = 1f / MathF.Max(0.02f, cellSize); 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; 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; 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; 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[]? indices = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null;
int triVertCount = indices is not null ? indices.Length : verts.Length; 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 vertToCellIdx = new int[verts.Length];
var accumPos = new List<Vector3>(verts.Length / 2 + 16); var accumPos = new List<Vector3>(verts.Length / 2 + 16);
var accumNorm = norms is not null ? new List<Vector3>(verts.Length / 2 + 16) : null; 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 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++) for (int v = 0; v < verts.Length; v++)
{ {
@ -1247,13 +1308,17 @@ public sealed class VehicleAssetCache : IDisposable
cellToNewIdx[key] = ci; cellToNewIdx[key] = ci;
accumPos.Add(p); accumPos.Add(p);
if (accumNorm is not null) accumNorm.Add(norms![v]); if (accumNorm is not null) accumNorm.Add(norms![v]);
if (accumColor is not null) accumColor.Add(colors![v]);
counts.Add(1); counts.Add(1);
cellMinY.Add(p.Y);
} }
else else
{ {
accumPos[ci] += p; accumPos[ci] += p;
if (accumNorm is not null) accumNorm[ci] += norms![v]; if (accumNorm is not null) accumNorm[ci] += norms![v];
if (accumColor is not null) accumColor[ci] += colors![v];
counts[ci]++; counts[ci]++;
if (p.Y < cellMinY[ci]) cellMinY[ci] = p.Y;
} }
vertToCellIdx[v] = ci; vertToCellIdx[v] = ci;
} }
@ -1287,20 +1352,30 @@ public sealed class VehicleAssetCache : IDisposable
var outVerts = new Vector3[accumPos.Count]; var outVerts = new Vector3[accumPos.Count];
Vector3[]? outNorms = accumNorm is not null ? new Vector3[accumPos.Count] : null; 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++) 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) if (outNorms is not null)
{ {
Vector3 n = accumNorm![i]; Vector3 n = accumNorm![i];
outNorms[i] = n.LengthSquared() > 1e-8f ? n.Normalized() : Vector3.Up; 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(); var newArr = new Godot.Collections.Array();
newArr.Resize((int)Mesh.ArrayType.Max); newArr.Resize((int)Mesh.ArrayType.Max);
newArr[(int)Mesh.ArrayType.Vertex] = outVerts; newArr[(int)Mesh.ArrayType.Vertex] = outVerts;
if (outNorms is not null) newArr[(int)Mesh.ArrayType.Normal] = outNorms; 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(); newArr[(int)Mesh.ArrayType.Index] = outIndices.ToArray();
int newSurf = outMesh.GetSurfaceCount(); int newSurf = outMesh.GetSurfaceCount();

View file

@ -73,6 +73,8 @@ public sealed class VehicleVisualInstance
private readonly VehicleAssetCache _cache; private readonly VehicleAssetCache _cache;
private readonly VehicleAssetCache.VehicleTemplate _template; private readonly VehicleAssetCache.VehicleTemplate _template;
private readonly Dictionary<string, BoundHardpoint> _hardpoints = new(StringComparer.Ordinal); 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, BoundJoint> _joints = new(StringComparer.Ordinal);
private readonly Dictionary<string, Node3D> _namedNodes = new(StringComparer.Ordinal); private readonly Dictionary<string, Node3D> _namedNodes = new(StringComparer.Ordinal);
private readonly Dictionary<string, Transform3D> _restLocalByName = 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 HashSet<string> _shearedHardpoints = new(StringComparer.Ordinal);
private readonly VehicleRigAnimator.RigState _rigState = new(); private readonly VehicleRigAnimator.RigState _rigState = new();
private readonly VehicleVisualRole _role;
private readonly string _chassisId; private readonly string _chassisId;
private MeshInstance3D? _lodStaticMesh; private MeshInstance3D? _lodStaticMesh;
private bool _isStaticLod; private bool _isStaticLod;
private bool _castShadows = true; private bool _castShadows = true;
private bool _hasAnyStrippedCell;
public static double PerfDamageHeatMs;
public static int PerfMaterialDupCount;
private VehicleVisualInstance( private VehicleVisualInstance(
VehicleAssetCache cache, VehicleAssetCache cache,
VehicleAssetCache.VehicleTemplate template, VehicleAssetCache.VehicleTemplate template,
Node3D root, Node3D root,
Node3D modelRoot, Node3D modelRoot,
string chassisId) string chassisId,
VehicleVisualRole role)
{ {
_cache = cache; _cache = cache;
_template = template; _template = template;
Root = root; Root = root;
ModelRoot = modelRoot; ModelRoot = modelRoot;
_chassisId = chassisId; _chassisId = chassisId;
_role = role;
int w = template.Package.GridWidth; int w = template.Package.GridWidth;
int h = template.Package.GridHeight; int h = template.Package.GridHeight;
@ -124,6 +133,7 @@ public sealed class VehicleVisualInstance
public IReadOnlyDictionary<string, BoundJoint> Joints => _joints; public IReadOnlyDictionary<string, BoundJoint> Joints => _joints;
public int BoundHardpointCount => _hardpoints.Count; public int BoundHardpointCount => _hardpoints.Count;
public bool IsStaticLod => _isStaticLod; public bool IsStaticLod => _isStaticLod;
public bool HasAnyStrippedCell => _hasAnyStrippedCell;
public void SetLodState(bool useStaticLod, bool castShadows) public void SetLodState(bool useStaticLod, bool castShadows)
{ {
@ -146,6 +156,10 @@ public sealed class VehicleVisualInstance
} }
return; return;
} }
if (_hasAnyStrippedCell)
{
useStaticLod = false;
}
if (_isStaticLod != useStaticLod) if (_isStaticLod != useStaticLod)
{ {
_isStaticLod = useStaticLod; _isStaticLod = useStaticLod;
@ -197,7 +211,7 @@ public sealed class VehicleVisualInstance
}; };
ApplyRoleTint(dropMesh, role); ApplyRoleTint(dropMesh, role);
root.AddChild(dropMesh); 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) if (template.SceneTemplate.Duplicate() is not Node3D modelRoot)
@ -223,7 +237,7 @@ public sealed class VehicleVisualInstance
} }
root.AddChild(lodMesh); root.AddChild(lodMesh);
var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId) var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId, role)
{ {
_lodStaticMesh = lodMesh _lodStaticMesh = lodMesh
}; };
@ -315,12 +329,14 @@ public sealed class VehicleVisualInstance
throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing anchor node '{rec.AnchorId}'."); throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing anchor node '{rec.AnchorId}'.");
} }
_hardpoints[hp.Id] = new BoundHardpoint var bh = new BoundHardpoint
{ {
Spec = hp, Spec = hp,
AnchorInfo = anchorInfo, AnchorInfo = anchorInfo,
AnchorNode = anchorNode AnchorNode = anchorNode
}; };
_hardpoints[hp.Id] = bh;
_hardpointList.Add(bh);
} }
// Apply role palette tinting to painted hull meshes before binding per-cell damage clones // 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) // Bind detachable exterior armor/shroud parts to their (CellX, CellY)
int w = pkg.GridWidth; int w = pkg.GridWidth;
int h = pkg.GridHeight; 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) foreach (var dp in _template.DetachableParts)
{ {
if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h) if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h)
@ -415,31 +441,26 @@ public sealed class VehicleVisualInstance
/// </summary> /// </summary>
public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity) public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity)
{ {
int w = Math.Min(grid.Spec.Width, _template.Package.GridWidth); long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0;
int h = Math.Min(grid.Spec.Height, _template.Package.GridHeight);
Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position; Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position;
// 1. Part-by-cell detachment & cell scorch/heat tinting // 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];
{
if (!grid.Spec.IsActive(x, y))
{
continue;
}
float armor = grid.Armor[x, y]; float armor = grid.Armor[x, y];
var parts = _cellParts[x, y]; var parts = _cellParts[x, y];
if (!_strippedCells[x, y] && armor <= 0.01f) if (!_strippedCells[x, y] && armor <= 0.01f)
{ {
_strippedCells[x, y] = true; _strippedCells[x, y] = true;
_hasAnyStrippedCell = true;
for (int i = 0; i < parts.Count; i++) for (int i = 0; i < parts.Count; i++)
{ {
var pb = parts[i]; var pb = parts[i];
if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node)) if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node))
{ {
pb.Detached = true; pb.Detached = true;
pb.Node.Visible = true;
debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true); debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true);
} }
} }
@ -452,8 +473,14 @@ public sealed class VehicleVisualInstance
} }
float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]); 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 dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f);
float heatGlow = Math.Clamp((grid.Temperature[x, y] - 65f) / 110f, 0f, 1f); float heatGlow = Math.Clamp((temp - 65f) / 110f, 0f, 1f);
float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f; float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f;
if (dmgFrac < 0.25f && heatGlow < 0.05f) if (dmgFrac < 0.25f && heatGlow < 0.05f)
@ -476,20 +503,22 @@ public sealed class VehicleVisualInstance
ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow); ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow);
} }
} }
}
// 2. Hardpoint shear & mounted gear heat glow // 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)) if (!_shearedHardpoints.Contains(bh.Spec.Id) && !grid.IsHardpointOperational(bh.Spec))
{ {
_shearedHardpoints.Add(bh.Spec.Id); _shearedHardpoints.Add(bh.Spec.Id);
_hasAnyStrippedCell = true;
if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode))
{ {
Node3D sheared = bh.GearNode; Node3D sheared = bh.GearNode;
bh.GearNode = null; bh.GearNode = null;
bh.MountedModuleId = null; bh.MountedModuleId = null;
bh.GearHeatMaterials.Clear(); bh.GearHeatMaterials.Clear();
sheared.Visible = true;
debris.SpawnDetachedPart(sheared, blastOrigin, vehicleVelocity, impulseScale: 1.15f, applyScorch: true); debris.SpawnDetachedPart(sheared, blastOrigin, vehicleVelocity, impulseScale: 1.15f, applyScorch: true);
} }
continue; continue;
@ -510,25 +539,36 @@ public sealed class VehicleVisualInstance
for (int m = 0; m < bh.GearHeatMaterials.Count; m++) for (int m = 0; m < bh.GearHeatMaterials.Count; m++)
{ {
StandardMaterial3D gm = bh.GearHeatMaterials[m]; StandardMaterial3D gm = bh.GearHeatMaterials[m];
gm.EmissionEnabled = heatFrac > 0.02f; 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.Emission = new Color(1.0f, 0.34f, 0.08f);
gm.EmissionEnergyMultiplier = heatFrac * 2.2f; 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) public static Node3D CreateStandaloneGearVisual(VehicleAssetCache cache, ModuleSpec mod)
{ {
var list = new List<StandardMaterial3D>(); var list = new List<StandardMaterial3D>();
GearVisualRecipe recipe = ResolveGearRecipe(mod); GearVisualRecipe recipe = ResolveGearRecipe(mod);
var template = cache.GetOrLoadGear(recipe.GearGlbId); 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}" }; Name = $"GearDrop_{mod.Id}",
} Mesh = template.BakedDropMesh,
node.Name = $"GearDrop_{mod.Id}"; Scale = recipe.VariantScale,
node.Scale = recipe.VariantScale; Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f)
node.Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f); };
if (recipe.PaintTint.HasValue || recipe.AccentTint.HasValue) if (recipe.PaintTint.HasValue || recipe.AccentTint.HasValue)
{ {
ApplyGearVariantTint(node, recipe.PaintTint, recipe.AccentTint, list); ApplyGearVariantTint(node, recipe.PaintTint, recipe.AccentTint, list);
@ -544,10 +584,19 @@ public sealed class VehicleVisualInstance
{ {
GearVisualRecipe recipe = ResolveGearRecipe(mod); GearVisualRecipe recipe = ResolveGearRecipe(mod);
VehicleAssetCache.GearTemplate gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId); VehicleAssetCache.GearTemplate gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId);
if (gearTemplate.SceneTemplate.Duplicate() is not Node3D gearNode) Node3D gearNode;
if (_role == VehicleVisualRole.Player)
{
if (gearTemplate.SceneTemplate.Duplicate() is not Node3D dup)
{ {
throw new InvalidOperationException($"Failed to duplicate gear GLB '{recipe.GearGlbId}'."); 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}"; gearNode.Name = $"Mounted_{mod.Id}_{hp.Id}";
// Compute outward socket normal & desired gear forward direction in vehicle/model space // Compute outward socket normal & desired gear forward direction in vehicle/model space
@ -789,6 +838,7 @@ public sealed class VehicleVisualInstance
StandardMaterial3D copy = src is StandardMaterial3D sm StandardMaterial3D copy = src is StandardMaterial3D sm
? (StandardMaterial3D)sm.Duplicate() ? (StandardMaterial3D)sm.Duplicate()
: new StandardMaterial3D { AlbedoColor = new Color(0.32f, 0.34f, 0.30f), Roughness = 0.6f, Metallic = 0.35f }; : new StandardMaterial3D { AlbedoColor = new Color(0.32f, 0.34f, 0.30f), Roughness = 0.6f, Metallic = 0.35f };
PerfMaterialDupCount++;
binding.Node.SetSurfaceOverrideMaterial(s, copy); binding.Node.SetSurfaceOverrideMaterial(s, copy);
binding.Materials.Add((copy, copy.AlbedoColor, copy.Roughness)); 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); _main.SetPhysicsProcess(true);
await VerifyHudAndShadersAsync(isHeadless); 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(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}"); 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(); gridVp.QueueFree();
// GPU verification for panel_chrome.gdshader // 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"); 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++) for (int i = 0; i < added.Count; i++)
{ {
added[i].PickedUp = true; added[i].PickedUp = true;
@ -929,6 +1056,49 @@ public partial class Smoke : Node
Check(sawPatron, "Expected at least one alive Patron spectator in arena"); 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); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
} }

View file

@ -103,12 +103,9 @@ namespace RustToDust.Core
hasGoal = true; hasGoal = true;
} }
// 2. Find nearest hostile contender with actual line-of-sight (staggered every 3 ticks when tickIndex >= 0) // 2. Find nearest hostile contender with actual live line-of-sight every tick
ContenderState? target = null; ContenderState? target = null;
float bestEnemyDistSq = 215f * 215f; float bestEnemyDistSq = 215f * 215f;
bool refreshLos = tickIndex < 0 || ((ai.Id + tickIndex) % 3 == 0);
if (refreshLos)
{
float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight); float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight);
for (int j = 0; j < state.Contenders.Count; j++) for (int j = 0; j < state.Contenders.Count; j++)
{ {
@ -136,30 +133,6 @@ namespace RustToDust.Core
target = other; target = other;
} }
ai.AiTargetContenderId = target?.Id; ai.AiTargetContenderId = target?.Id;
}
else if (ai.AiTargetContenderId is { } tid && tid >= 0 && tid < state.Contenders.Count)
{
var cached = state.Contenders[tid];
if (cached.Alive && cached.Id != ai.Id)
{
float dx = cached.X - ai.X;
float dz = cached.Z - ai.Z;
float d2 = dx * dx + dz * dz;
if (d2 < bestEnemyDistSq)
{
bestEnemyDistSq = d2;
target = cached;
}
else
{
ai.AiTargetContenderId = null;
}
}
else
{
ai.AiTargetContenderId = null;
}
}
// 3. Scavenge nearby upgrades when safe // 3. Scavenge nearby upgrades when safe
if (!hasGoal && ai.AiScavengeCooldown <= 0f) if (!hasGoal && ai.AiScavengeCooldown <= 0f)

View file

@ -154,10 +154,6 @@ namespace RustToDust.Core
{ {
continue; continue;
} }
if (tickIndex >= 0 && spec.Stance == SpectatorStance.Neutral && ((spec.Id + tickIndex) % 6 != 0))
{
continue;
}
if (hasLos is null || hasLos(spec, contender)) if (hasLos is null || hasLos(spec, contender))
{ {
@ -245,7 +241,7 @@ namespace RustToDust.Core
} }
// If full with a stale expired no-LOS watcher while a Neutral watcher has live LOS, rotate one slot. // If full with a stale expired no-LOS watcher while a Neutral watcher has live LOS, rotate one slot.
if (currentCleared == allowedCleared && hasLos is not null && AnyNeutralHasLos(contender, hasLos, tickIndex)) if (currentCleared == allowedCleared && hasLos is not null && AnyNeutralHasLos(contender, hasLos))
{ {
int staleIdx = FindStaleNoLosCleared(contender.Id); int staleIdx = FindStaleNoLosCleared(contender.Id);
if (staleIdx >= 0) if (staleIdx >= 0)
@ -255,7 +251,7 @@ namespace RustToDust.Core
} }
} }
// Pass 1: Spectators with direct live LOS to the offender. // Pass 1: Spectators with direct live LOS to the offender (nearest open-LOS watcher first).
while (currentCleared < allowedCleared) while (currentCleared < allowedCleared)
{ {
int bestIdx = -1; int bestIdx = -1;
@ -268,7 +264,11 @@ namespace RustToDust.Core
{ {
continue; continue;
} }
if (tickIndex >= 0 && ((spec.Id + tickIndex) % 6 != 0))
float dx = spec.X - contender.X;
float dz = spec.Z - contender.Z;
float d2 = dx * dx + dz * dz;
if (d2 >= bestDistSq)
{ {
continue; continue;
} }
@ -278,15 +278,9 @@ namespace RustToDust.Core
continue; continue;
} }
float dx = spec.X - contender.X;
float dz = spec.Z - contender.Z;
float d2 = dx * dx + dz * dz;
if (d2 < bestDistSq)
{
bestDistSq = d2; bestDistSq = d2;
bestIdx = i; bestIdx = i;
} }
}
if (bestIdx < 0) if (bestIdx < 0)
{ {
@ -503,13 +497,12 @@ namespace RustToDust.Core
return bestIdx; return bestIdx;
} }
private bool AnyNeutralHasLos(in RingContact contender, Func<SpectatorState, RingContact, bool> hasLos, int tickIndex) private bool AnyNeutralHasLos(in RingContact contender, Func<SpectatorState, RingContact, bool> hasLos)
{ {
for (int i = 0; i < _spectators.Count; i++) for (int i = 0; i < _spectators.Count; i++)
{ {
var spec = _spectators[i]; var spec = _spectators[i];
if (spec.Alive && spec.Stance == SpectatorStance.Neutral && if (spec.Alive && spec.Stance == SpectatorStance.Neutral &&
(tickIndex < 0 || ((spec.Id + tickIndex) % 6 == 0)) &&
hasLos(spec, contender)) hasLos(spec, contender))
{ {
return true; return true;

View file

@ -36,6 +36,9 @@ namespace RustToDust.Core
public const float HalfExtent = 768f; public const float HalfExtent = 768f;
public const int TileGridCount = 8; public const int TileGridCount = 8;
public const float TileSize = ArenaSize / TileGridCount; // 192m public const float TileSize = ArenaSize / TileGridCount; // 192m
private const int AccelGridCount = 64;
private const float AccelCellSize = ArenaSize / AccelGridCount; // 24m
private const int AccelCellCount = AccelGridCount * AccelGridCount;
public const float MinWorldHeight = -18f; public const float MinWorldHeight = -18f;
public const float MaxWorldHeight = 52f; public const float MaxWorldHeight = 52f;
public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m
@ -63,7 +66,8 @@ namespace RustToDust.Core
private readonly List<TerrainBrush> _brushes = new(); private readonly List<TerrainBrush> _brushes = new();
private readonly List<BrushPrecomp> _brushPrecomps = new(); private readonly List<BrushPrecomp> _brushPrecomps = new();
private readonly List<int>[,] _tileBrushIndices = new List<int>[TileGridCount, TileGridCount]; private readonly List<int>[,] _tileBrushIndices = new List<int>[TileGridCount, TileGridCount];
private readonly float[,] _tileMaxHeight = new float[TileGridCount, TileGridCount]; private readonly List<int>[] _cellBrushIndices = new List<int>[AccelCellCount];
private readonly float[] _cellMaxHeight = new float[AccelCellCount];
private readonly Queue<int> _dynamicDecalSlots = new(); private readonly Queue<int> _dynamicDecalSlots = new();
private int _nextBrushId = 1; private int _nextBrushId = 1;
@ -78,14 +82,26 @@ namespace RustToDust.Core
_tileBrushIndices[tx, tz] = new List<int>(32); _tileBrushIndices[tx, tz] = new List<int>(32);
} }
} }
for (int c = 0; c < AccelCellCount; c++)
{
_cellBrushIndices[c] = new List<int>(4);
}
} }
public ulong Seed { get; } public ulong Seed { get; }
public IReadOnlyList<TerrainBrush> Brushes => _brushes; public IReadOnlyList<TerrainBrush> Brushes => _brushes;
public int[,] TileVersions { get; } public int[,] TileVersions { get; }
public ulong DirtyTileMask { get; private set; } public ulong DirtyTileMask { get; private set; }
public ulong StructuralDirtyTileMask { get; private set; }
public void ClearDirtyMask() => DirtyTileMask = 0UL; public void ClearDirtyMask()
{
DirtyTileMask = 0UL;
StructuralDirtyTileMask = 0UL;
}
public void ClearStructuralDirtyTile(int tx, int tz) =>
StructuralDirtyTileMask &= ~(1UL << (tz * TileGridCount + tx));
public IReadOnlyList<int> GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz]; public IReadOnlyList<int> GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz];
@ -365,18 +381,19 @@ namespace RustToDust.Core
{ {
float cx = Math.Clamp(x, -HalfExtent, HalfExtent); float cx = Math.Clamp(x, -HalfExtent, HalfExtent);
float cz = Math.Clamp(z, -HalfExtent, HalfExtent); float cz = Math.Clamp(z, -HalfExtent, HalfExtent);
WorldToTile(cx, cz, out int tx, out int tz); WorldToAccelCell(cx, cz, out int acx, out int acz);
var indices = _cellBrushIndices[acz * AccelGridCount + acx];
if (indices.Count == 0)
{
return 0f;
}
float h = 0f; float h = 0f;
var indices = _tileBrushIndices[tx, tz];
for (int i = 0; i < indices.Count; i++) for (int i = 0; i < indices.Count; i++)
{ {
int idx = indices[i]; int idx = indices[i];
var b = _brushes[idx]; var b = _brushes[idx];
if (b.Kind == TerrainBrushKind.Scorch)
{
continue;
}
h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz); h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz);
} }
@ -429,8 +446,44 @@ namespace RustToDust.Core
float cx = Math.Clamp(px, -HalfExtent, HalfExtent); float cx = Math.Clamp(px, -HalfExtent, HalfExtent);
float cz = Math.Clamp(pz, -HalfExtent, HalfExtent); float cz = Math.Clamp(pz, -HalfExtent, HalfExtent);
WorldToTile(cx, cz, out int tx, out int tz); WorldToAccelCell(cx, cz, out int acx, out int acz);
if (py <= _tileMaxHeight[tx, tz]) float cellMax = _cellMaxHeight[acz * AccelGridCount + acx] + 0.02f;
// Fast-skip consecutive cells strictly below the ray without sampling brushes
while (py > cellMax + 0.02f &&
ct < maxDistance &&
px >= -HalfExtent && px <= HalfExtent &&
pz >= -HalfExtent && pz <= HalfExtent)
{
float cellMinX = -HalfExtent + acx * AccelCellSize;
float cellMaxX = cellMinX + AccelCellSize;
float cellMinZ = -HalfExtent + acz * AccelCellSize;
float cellMaxZ = cellMinZ + AccelCellSize;
float txExit = dx > 1e-6f ? (cellMaxX - px) / dx : (dx < -1e-6f ? (cellMinX - px) / dx : float.PositiveInfinity);
float tzExit = dz > 1e-6f ? (cellMaxZ - pz) / dz : (dz < -1e-6f ? (cellMinZ - pz) / dz : float.PositiveInfinity);
float tExit = MathF.Min(txExit, tzExit);
float advance = MathF.Min(tExit + 0.02f, maxDistance - ct);
if (advance <= 0.02f)
{
break;
}
float ey = py + dy * advance;
if (ey <= cellMax + 0.02f)
{
break;
}
prevT = ct + MathF.Min(tExit, maxDistance - ct);
ct += advance;
px = ox + dx * ct;
py = oy + dy * ct;
pz = oz + dz * ct;
cx = Math.Clamp(px, -HalfExtent, HalfExtent);
cz = Math.Clamp(pz, -HalfExtent, HalfExtent);
WorldToAccelCell(cx, cz, out acx, out acz);
cellMax = _cellMaxHeight[acz * AccelGridCount + acx] + 0.02f;
}
if (py <= cellMax)
{ {
float diff = py - SampleHeight(px, pz); float diff = py - SampleHeight(px, pz);
if (diff <= 0f) if (diff <= 0f)
@ -469,18 +522,6 @@ namespace RustToDust.Core
} }
float step = ct < 160f ? 1.5f : 2.5f; float step = ct < 160f ? 1.5f : 2.5f;
if (py > _tileMaxHeight[tx, tz] + 1.5f)
{
float farT = MathF.Min(ct + 14f, maxDistance);
float fx = Math.Clamp(ox + dx * farT, -HalfExtent, HalfExtent);
float fz = Math.Clamp(oz + dz * farT, -HalfExtent, HalfExtent);
WorldToTile(fx, fz, out int ftx, out int ftz);
float fy = oy + dy * farT;
if (ftx == tx && ftz == tz && fy > _tileMaxHeight[tx, tz] + 0.5f)
{
step = MathF.Max(step, farT - ct);
}
}
t = ct + step; t = ct + step;
} }
@ -608,40 +649,157 @@ namespace RustToDust.Core
return brush; return brush;
} }
private static float GetBrushMaxPositiveHeight(in TerrainBrush b) => b.Kind switch private static bool TryGetBrushCellBounds(
in TerrainBrush b,
in BrushPrecomp p,
int cx, int cz,
out float cellMaxPositiveHeight)
{ {
TerrainBrushKind.DuneRidge => b.HeightDelta > 0f ? b.HeightDelta * 1.33f : 0f, float minX = -HalfExtent + cx * AccelCellSize;
TerrainBrushKind.Mesa => b.HeightDelta > 0f ? b.HeightDelta : 0f, float maxX = minX + AccelCellSize;
TerrainBrushKind.SalvagePad or TerrainBrushKind.Road or TerrainBrushKind.Track => b.HeightDelta > 0f ? b.HeightDelta : 0f, float minZ = -HalfExtent + cz * AccelCellSize;
TerrainBrushKind.Crater => 0.33f * MathF.Abs(b.HeightDelta), float maxZ = minZ + AccelCellSize;
_ => 0f
};
private void RecomputeTileMaxHeight(int tx, int tz) // Project all 4 cell corners into brush local (lx, lz)
float dx0 = minX - b.X, dx1 = maxX - b.X;
float dz0 = minZ - b.Z, dz1 = maxZ - b.Z;
float lx00 = dx0 * p.CosR + dz0 * p.SinR;
float lx10 = dx1 * p.CosR + dz0 * p.SinR;
float lx01 = dx0 * p.CosR + dz1 * p.SinR;
float lx11 = dx1 * p.CosR + dz1 * p.SinR;
float lz00 = -dx0 * p.SinR + dz0 * p.CosR;
float lz10 = -dx1 * p.SinR + dz0 * p.CosR;
float lz01 = -dx0 * p.SinR + dz1 * p.CosR;
float lz11 = -dx1 * p.SinR + dz1 * p.CosR;
float minLx = MathF.Min(MathF.Min(lx00, lx10), MathF.Min(lx01, lx11));
float maxLx = MathF.Max(MathF.Max(lx00, lx10), MathF.Max(lx01, lx11));
float minLz = MathF.Min(MathF.Min(lz00, lz10), MathF.Min(lz01, lz11));
float maxLz = MathF.Max(MathF.Max(lz00, lz10), MathF.Max(lz01, lz11));
float absMinLx = (minLx <= 0f && maxLx >= 0f) ? 0f : MathF.Min(MathF.Abs(minLx), MathF.Abs(maxLx));
float absMinLz = (minLz <= 0f && maxLz >= 0f) ? 0f : MathF.Min(MathF.Abs(minLz), MathF.Abs(maxLz));
float minU = absMinLx * p.InvRx;
float minV = absMinLz * p.InvRz;
float minR2 = minU * minU + minV * minV;
if (minR2 >= 1f)
{
cellMaxPositiveHeight = 0f;
return false;
}
switch (b.Kind)
{
case TerrainBrushKind.DuneRidge:
{
if (b.HeightDelta <= 0f)
{
cellMaxPositiveHeight = 0f;
}
else
{
float env = 1f - minR2;
env *= env;
float ridge = MathF.Max(0f, 1f - minU * minU);
float maxAsym = MathF.Max(0f, 1f + 0.32f * (maxLx * p.InvRx));
cellMaxPositiveHeight = b.HeightDelta * env * (0.35f + 0.65f * ridge) * maxAsym;
}
break;
}
case TerrainBrushKind.Mesa:
{
if (b.HeightDelta <= 0f)
{
cellMaxPositiveHeight = 0f;
}
else
{
float r = MathF.Sqrt(minR2);
float t = Math.Clamp((1f - r) / 0.45f, 0f, 1f);
cellMaxPositiveHeight = b.HeightDelta * t * t * (3f - 2f * t);
}
break;
}
case TerrainBrushKind.SalvagePad:
case TerrainBrushKind.Road:
case TerrainBrushKind.Track:
{
if (b.HeightDelta <= 0f)
{
cellMaxPositiveHeight = 0f;
}
else
{
float env = 1f - minR2;
cellMaxPositiveHeight = b.HeightDelta * env * env;
}
break;
}
case TerrainBrushKind.Crater:
cellMaxPositiveHeight = 0.33f * MathF.Abs(b.HeightDelta);
break;
default:
cellMaxPositiveHeight = 0f;
break;
}
return true;
}
private void RecomputeCellMaxHeight(int cx, int cz)
{ {
float sum = 0f; float sum = 0f;
var indices = _tileBrushIndices[tx, tz]; int cellIdx = cz * AccelGridCount + cx;
var indices = _cellBrushIndices[cellIdx];
for (int i = 0; i < indices.Count; i++) for (int i = 0; i < indices.Count; i++)
{ {
sum += GetBrushMaxPositiveHeight(_brushes[indices[i]]); int bIdx = indices[i];
if (TryGetBrushCellBounds(_brushes[bIdx], _brushPrecomps[bIdx], cx, cz, out float h))
{
sum += h;
} }
_tileMaxHeight[tx, tz] = Math.Min(MaxWorldHeight, sum + 0.05f); }
_cellMaxHeight[cellIdx] = Math.Min(MaxWorldHeight, sum);
} }
private void RegisterBrushInTiles(int index, in TerrainBrush brush, bool incrementTileVersion) private void RegisterBrushInTiles(int index, in TerrainBrush brush, bool incrementTileVersion)
{ {
float maxPos = GetBrushMaxPositiveHeight(in brush); bool isStructural = brush.Kind != TerrainBrushKind.Track && brush.Kind != TerrainBrushKind.Scorch;
GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz);
for (int tz = minTz; tz <= maxTz; tz++) for (int tz = minTz; tz <= maxTz; tz++)
{ {
for (int tx = minTx; tx <= maxTx; tx++) for (int tx = minTx; tx <= maxTx; tx++)
{ {
_tileBrushIndices[tx, tz].Add(index); _tileBrushIndices[tx, tz].Add(index);
_tileMaxHeight[tx, tz] = Math.Min(MaxWorldHeight, _tileMaxHeight[tx, tz] + maxPos + 0.05f);
if (incrementTileVersion) if (incrementTileVersion)
{ {
TileVersions[tx, tz]++; TileVersions[tx, tz]++;
DirtyTileMask |= 1UL << (tz * TileGridCount + tx); ulong bit = 1UL << (tz * TileGridCount + tx);
DirtyTileMask |= bit;
if (isStructural)
{
StructuralDirtyTileMask |= bit;
}
}
}
}
if (brush.Kind != TerrainBrushKind.Scorch)
{
var precomp = _brushPrecomps[index];
GetBrushAccelBounds(in brush, out int minCx, out int maxCx, out int minCz, out int maxCz);
for (int cz = minCz; cz <= maxCz; cz++)
{
for (int cx = minCx; cx <= maxCx; cx++)
{
if (TryGetBrushCellBounds(in brush, in precomp, cx, cz, out float cellMaxPos))
{
int cellIdx = cz * AccelGridCount + cx;
_cellBrushIndices[cellIdx].Add(index);
_cellMaxHeight[cellIdx] = Math.Min(MaxWorldHeight, _cellMaxHeight[cellIdx] + cellMaxPos);
}
} }
} }
} }
@ -649,19 +807,53 @@ namespace RustToDust.Core
private void UnregisterBrushFromTiles(int index, in TerrainBrush brush) private void UnregisterBrushFromTiles(int index, in TerrainBrush brush)
{ {
bool isStructural = brush.Kind != TerrainBrushKind.Track && brush.Kind != TerrainBrushKind.Scorch;
GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz);
for (int tz = minTz; tz <= maxTz; tz++) for (int tz = minTz; tz <= maxTz; tz++)
{ {
for (int tx = minTx; tx <= maxTx; tx++) for (int tx = minTx; tx <= maxTx; tx++)
{ {
_tileBrushIndices[tx, tz].Remove(index); _tileBrushIndices[tx, tz].Remove(index);
RecomputeTileMaxHeight(tx, tz);
TileVersions[tx, tz]++; TileVersions[tx, tz]++;
DirtyTileMask |= 1UL << (tz * TileGridCount + tx); ulong bit = 1UL << (tz * TileGridCount + tx);
DirtyTileMask |= bit;
if (isStructural)
{
StructuralDirtyTileMask |= bit;
} }
} }
} }
if (brush.Kind != TerrainBrushKind.Scorch)
{
GetBrushAccelBounds(in brush, out int minCx, out int maxCx, out int minCz, out int maxCz);
for (int cz = minCz; cz <= maxCz; cz++)
{
for (int cx = minCx; cx <= maxCx; cx++)
{
int cellIdx = cz * AccelGridCount + cx;
_cellBrushIndices[cellIdx].Remove(index);
RecomputeCellMaxHeight(cx, cz);
}
}
}
}
private static void GetBrushAccelBounds(in TerrainBrush brush, out int minCx, out int maxCx, out int minCz, out int maxCz)
{
float extent = MathF.Max(0.1f, MathF.Max(brush.RadiusX, brush.RadiusZ)) + 0.1f;
WorldToAccelCell(Math.Clamp(brush.X - extent, -HalfExtent, HalfExtent), Math.Clamp(brush.Z - extent, -HalfExtent, HalfExtent), out minCx, out minCz);
WorldToAccelCell(Math.Clamp(brush.X + extent, -HalfExtent, HalfExtent), Math.Clamp(brush.Z + extent, -HalfExtent, HalfExtent), out maxCx, out maxCz);
}
private static void WorldToAccelCell(float x, float z, out int cx, out int cz)
{
float nx = (x + HalfExtent) / AccelCellSize;
float nz = (z + HalfExtent) / AccelCellSize;
cx = Math.Clamp((int)MathF.Floor(nx), 0, AccelGridCount - 1);
cz = Math.Clamp((int)MathF.Floor(nz), 0, AccelGridCount - 1);
}
private static void GetBrushTileBounds(in TerrainBrush brush, out int minTx, out int maxTx, out int minTz, out int maxTz) private static void GetBrushTileBounds(in TerrainBrush brush, out int minTx, out int maxTx, out int minTz, out int maxTz)
{ {
const float gutterPaddingMeters = 3.5f; const float gutterPaddingMeters = 3.5f;

View file

@ -23,8 +23,6 @@ namespace RustToDust.Ymir
private readonly Dictionary<int, Box3DSoaBodyHandle> _spectatorBodies = new(); private readonly Dictionary<int, Box3DSoaBodyHandle> _spectatorBodies = new();
private readonly Dictionary<ulong, (bool IsContender, int Index)> _entityByStableId = new(); private readonly Dictionary<ulong, (bool IsContender, int Index)> _entityByStableId = new();
private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount]; private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount];
private int _stepTick;
private bool _forceFullDetectionRefresh = true;
private bool _disposed; private bool _disposed;
public ArenaSession(int seed = 42) public ArenaSession(int seed = 42)
@ -88,7 +86,6 @@ namespace RustToDust.Ymir
{ {
SpawnContenderBody(c); SpawnContenderBody(c);
} }
_forceFullDetectionRefresh = true;
} }
public void SetSpectatorPose(int spectatorId, float x, float z, float? yaw = null) public void SetSpectatorPose(int spectatorId, float x, float z, float? yaw = null)
@ -122,7 +119,6 @@ namespace RustToDust.Ymir
{ {
SpawnSpectatorBody(index, spec); SpawnSpectatorBody(index, spec);
} }
_forceFullDetectionRefresh = true;
} }
public bool HasLineOfSight(float ax, float ay, float az, float bx, float by, float bz) public bool HasLineOfSight(float ax, float ay, float az, float bx, float by, float bz)
@ -135,17 +131,17 @@ namespace RustToDust.Ymir
} }
Vector3 dir = delta / dist; Vector3 dir = delta / dist;
if (State.Terrain.Raycast( // Only static cover/boundary boxes and terrain block LOS; check fast static AABBs first.
ax, ay, az, if (IntersectsAnyStaticBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist))
dir.X, dir.Y, dir.Z,
MathF.Max(0.1f, dist - 0.5f),
out _, out _, out _, out _))
{ {
return false; return false;
} }
// Only static cover/boundary boxes block LOS; dynamic vehicles do not occlude terrain/cover sightlines. return !State.Terrain.Raycast(
return !IntersectsAnyStaticBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist); ax, ay, az,
dir.X, dir.Y, dir.Z,
MathF.Max(0.1f, dist - 0.5f),
out _, out _, out _, out _);
} }
private bool IntersectsAnyStaticBox(float ox, float oy, float oz, float dx, float dy, float dz, float maxDist) private bool IntersectsAnyStaticBox(float ox, float oy, float oz, float dx, float dy, float dz, float maxDist)
@ -205,7 +201,6 @@ namespace RustToDust.Ymir
{ {
ObjectDisposedException.ThrowIf(_disposed, this); ObjectDisposedException.ThrowIf(_disposed, this);
_stepTick++;
State.Time += FixedDt; State.Time += FixedDt;
MatchRules.AdvanceTracers(State, FixedDt); MatchRules.AdvanceTracers(State, FixedDt);
State.Spectators.UpdateSafeRadius(State.Time); State.Spectators.UpdateSafeRadius(State.Time);
@ -215,7 +210,7 @@ namespace RustToDust.Ymir
{ {
UpdateRingClearance(); UpdateRingClearance();
MatchRules.ApplyPlayerInput(State, input); MatchRules.ApplyPlayerInput(State, input);
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _forceFullDetectionRefresh ? -1 : _stepTick); MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
ApplyPhysicsDrives(); ApplyPhysicsDrives();
_world.Step(FixedDt, SubStepCount); _world.Step(FixedDt, SubStepCount);
@ -233,7 +228,7 @@ namespace RustToDust.Ymir
UpdateRingClearance(); UpdateRingClearance();
long t1 = Stopwatch.GetTimestamp(); long t1 = Stopwatch.GetTimestamp();
MatchRules.ApplyPlayerInput(State, input); MatchRules.ApplyPlayerInput(State, input);
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _forceFullDetectionRefresh ? -1 : _stepTick); MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
long t2 = Stopwatch.GetTimestamp(); long t2 = Stopwatch.GetTimestamp();
ApplyPhysicsDrives(); ApplyPhysicsDrives();
long t3 = Stopwatch.GetTimestamp(); long t3 = Stopwatch.GetTimestamp();
@ -338,7 +333,6 @@ namespace RustToDust.Ymir
{ {
SpawnContenderBody(c); SpawnContenderBody(c);
} }
_forceFullDetectionRefresh = true;
} }
private void SpawnSpectatorBodies() private void SpawnSpectatorBodies()
@ -380,7 +374,7 @@ namespace RustToDust.Ymir
var c = State.Contenders[i]; var c = State.Contenders[i];
contacts[i] = new RingContact(c.Id, c.X, c.Z, c.Alive, c.Y, c.Grid.Spec.HalfHeight); contacts[i] = new RingContact(c.Id, c.X, c.Z, c.Alive, c.Y, c.Grid.Spec.HalfHeight);
} }
State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos, _forceFullDetectionRefresh ? -1 : _stepTick); State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos);
for (int i = 0; i < State.Spectators.Spectators.Count; i++) for (int i = 0; i < State.Spectators.Spectators.Count; i++)
{ {
@ -1073,19 +1067,6 @@ namespace RustToDust.Ymir
float dxC = c.X - p.X; float dxC = c.X - p.X;
float dzC = c.Z - p.Z; float dzC = c.Z - p.Z;
float distSqC = dxC * dxC + dzC * dzC; float distSqC = dxC * dxC + dzC * dzC;
int rivalPeriod = distSqC > 240f * 240f ? 6 : 3;
if (!_forceFullDetectionRefresh && ((c.Id + _stepTick) % rivalPeriod != 0))
{
if (!mem.VisibleToPlayer && mem.HasEverBeenSeen)
{
mem.LastSeenAge += FixedDt;
}
else if (mem.VisibleToPlayer && distSqC <= 240f * 240f)
{
detectedBy++;
}
continue;
}
bool playerSees = HasLineOfSight( bool playerSees = HasLineOfSight(
p.X, pEyeY, p.Z, p.X, pEyeY, p.Z,
@ -1099,12 +1080,6 @@ namespace RustToDust.Ymir
mem.LastSeenX = c.X; mem.LastSeenX = c.X;
mem.LastSeenZ = c.Z; mem.LastSeenZ = c.Z;
mem.HasEverBeenSeen = true; mem.HasEverBeenSeen = true;
if (distSqC <= 240f * 240f &&
HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, p.X, pTargetY, p.Z))
{
detectedBy++;
}
} }
else else
{ {
@ -1115,6 +1090,12 @@ namespace RustToDust.Ymir
mem.LastSeenAge += FixedDt; mem.LastSeenAge += FixedDt;
} }
} }
if (distSqC <= 240f * 240f &&
HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, p.X, pTargetY, p.Z))
{
detectedBy++;
}
} }
for (int i = 0; i < State.Spectators.Spectators.Count; i++) for (int i = 0; i < State.Spectators.Spectators.Count; i++)
@ -1129,12 +1110,6 @@ namespace RustToDust.Ymir
continue; continue;
} }
bool checkLosThisTick = _forceFullDetectionRefresh ||
s.Stance != SpectatorStance.Neutral ||
((s.Id + _stepTick) % 12 == 0);
if (checkLosThisTick)
{
bool playerSees = HasLineOfSight( bool playerSees = HasLineOfSight(
p.X, pEyeY, p.Z, p.X, pEyeY, p.Z,
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z); s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z);
@ -1172,11 +1147,6 @@ namespace RustToDust.Ymir
} }
mem.FaintHorizonPing = horizonPing; mem.FaintHorizonPing = horizonPing;
} }
}
else if (!mem.VisibleToPlayer && mem.HasEverBeenSeen)
{
mem.LastSeenAge += FixedDt;
}
if (s.Stance != SpectatorStance.Neutral && if (s.Stance != SpectatorStance.Neutral &&
s.TargetContenderId == p.Id && s.TargetContenderId == p.Id &&
@ -1186,7 +1156,6 @@ namespace RustToDust.Ymir
} }
} }
_forceFullDetectionRefresh = false;
State.PlayerDetectedByCount = detectedBy; State.PlayerDetectedByCount = detectedBy;
} }

View file

@ -420,5 +420,149 @@ namespace RustToDust.Tests
Assert.True(spec.LastKnownTargetZ > spec.Z + 10f, Assert.True(spec.LastKnownTargetZ > spec.Z + 10f,
$"Expected LastKnownTarget to point along incoming +Z direction, got Z={spec.LastKnownTargetZ:F1} vs spec.Z={spec.Z:F1}"); $"Expected LastKnownTarget to point along incoming +Z direction, got Z={spec.LastKnownTargetZ:F1} vs spec.Z={spec.Z:F1}");
} }
[Fact]
public void AiContender_ImmediatelyDropsTrackingAndFiring_OnExactTickLosBreaks()
{
using var session = new ArenaSession(seed: 12);
var box = session.State.ArenaCoverBoxes[0];
var player = session.State.Player;
var ai = session.State.Contenders[1];
// Move other rivals far away so only ai <-> player interaction is isolated
for (int i = 2; i < session.State.Contenders.Count; i++)
{
session.SetContenderPose(session.State.Contenders[i].Id, -680f + i * 8f, -680f);
}
// Ensure both player and AI are low-profile ground vehicles shorter than the cover wall
if (player.Grid.Spec.IsVtol || player.Grid.Spec.HalfHeight * 2f >= box.HalfY * 2f)
{
session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 8f);
session.State.SpawnChassisDrop(box.X, box.Z - box.HalfZ - 8f, Catalog.Jackal);
Assert.True(session.State.TrySwapNearbyChassis(player.Id));
}
if (ai.Grid.Spec.IsVtol || ai.Grid.Spec.HalfHeight * 2f >= box.HalfY * 2f)
{
session.SetContenderPose(ai.Id, box.X + 8f, box.Z - box.HalfZ - 8f);
session.State.SpawnChassisDrop(box.X + 8f, box.Z - box.HalfZ - 8f, Catalog.Jackal);
Assert.True(session.State.TrySwapNearbyChassis(ai.Id));
}
// Test breaking LOS across multiple step-tick phases (would catch any % 3 stagger!)
for (int phase = 0; phase < 3; phase++)
{
// Place both on the same open side of the cover box within firing range (< 165m)
session.SetContenderPose(ai.Id, box.X, box.Z - box.HalfZ - 14f, yaw: 0f);
session.SetContenderPose(player.Id, box.X + 18f, box.Z - box.HalfZ - 14f, yaw: 0f);
// Advance `phase` ticks in open LOS; open-LOS acquisition must be immediate on tick 0!
for (int t = 0; t <= phase; t++)
{
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
Assert.Equal(player.Id, ai.AiTargetContenderId);
Assert.True(ai.FireCmd, $"Expected AI to acquire open-LOS target and fire immediately (phase={phase}, t={t})");
}
// Now break LOS behind the static cover wall while staying within weapon range
session.SetContenderPose(ai.Id, box.X, box.Z - box.HalfZ - 8f, yaw: 0f);
session.SetContenderPose(player.Id, box.X, box.Z + box.HalfZ + 8f, yaw: 0f);
session.State.Tracers.Clear();
for (int occTick = 0; occTick < 6; occTick++)
{
if (occTick > 0)
{
// Move laterally behind cover to verify AI never steers/aims toward hidden coords
session.SetContenderPose(player.Id, box.X + (occTick % 2 == 0 ? 1.5f : -1.5f), box.Z + box.HalfZ + 8f, yaw: 0f);
}
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
Assert.Null(ai.AiTargetContenderId);
Assert.False(ai.FireCmd, $"AI leaked FireCmd on occluded tick {occTick} (phase={phase})");
float aimToHidden = MathF.Sqrt((ai.AimX - player.X) * (ai.AimX - player.X) + (ai.AimZ - player.Z) * (ai.AimZ - player.Z));
Assert.True(aimToHidden > 5f, $"AI aim leaked hidden player coords on occluded tick {occTick} (dist={aimToHidden:F2}m)");
}
}
}
[Fact]
public void PlayerDetectedByCount_StaysExactZero_UnderAsymmetricCover_NoFlicker()
{
using var session = new ArenaSession(seed: 12);
var box = session.State.ArenaCoverBoxes.First(b => b.HalfY >= 2.8f);
var player = session.State.Player;
var rival = session.State.Contenders[1];
// Move all other rivals and spectators far away (> 500m) so only rival <-> player is tested
for (int i = 2; i < session.State.Contenders.Count; i++)
{
session.SetContenderPose(session.State.Contenders[i].Id, -680f + i * 8f, -680f);
}
for (int i = 0; i < session.State.Spectators.Spectators.Count; i++)
{
var s = session.State.Spectators.Spectators[i];
session.SetSpectatorPose(s.Id, (box.X >= 0f ? -1f : 1f) * 680f, (box.Z >= 0f ? -1f : 1f) * 680f);
}
// Medium-tall player (Breaker) right next to the 5.6m bunker sees over it onto a low rival (Jackal) 40m on the far side,
// while the low rival's eye cannot see the Breaker's lower target center behind the bunker.
session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f);
session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Breaker);
Assert.True(session.State.TrySwapNearbyChassis(player.Id));
session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 40f);
session.State.SpawnChassisDrop(rival.X, rival.Z, Catalog.Jackal);
Assert.True(session.State.TrySwapNearbyChassis(rival.Id));
// Confirm asymmetric LOS precondition
Assert.True(session.HasLineOfSight(
player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z,
rival.X, MatchRules.GetTargetAimY(rival.Y, rival.Grid.Spec.HalfHeight), rival.Z));
Assert.False(session.HasLineOfSight(
rival.X, MatchRules.GetObserverEyeY(rival.Y, rival.Grid.Spec.HalfHeight), rival.Z,
player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z));
for (int tick = 0; tick < 18; tick++)
{
// Re-pin poses each tick so drift never alters cover geometry
session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f);
session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 40f);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
Assert.True(session.State.ContenderContacts[rival.Id].VisibleToPlayer);
Assert.Equal(0, session.State.PlayerDetectedByCount);
}
}
[Fact]
public void SpectatorRing_ClearsNearestOpenLosNeutralWatcher_OnFirstTickOutsideSafeRadius()
{
// Test every tick phase 0..5 so % 6 staggering cannot hide
for (int tickIndex = 0; tickIndex < 6; tickIndex++)
{
var ring = new SpectatorRing(seed: 42);
// Pick a spectator whose (Id + tickIndex) % 6 != 0 so % 6 staggering would have skipped it
var targetNearest = ring.Spectators.First(s => (s.Id + tickIndex) % 6 != 0);
// Place contender just outside SafeRadius directly beside targetNearest (within 12m outside => allowedCleared = 1)
float len = MathF.Sqrt(targetNearest.X * targetNearest.X + targetNearest.Z * targetNearest.Z);
float nx = targetNearest.X / len;
float nz = targetNearest.Z / len;
float outR = ring.SafeRadius + 4f;
float cx = nx * outR;
float cz = nz * outR;
ring.UpdateClearance(
new[] { new RingContact(0, cx, cz, true) },
1f / 60f,
static (_, _) => true,
tickIndex: tickIndex);
Assert.Equal(1, ring.CountClearedFor(0));
Assert.Equal(SpectatorStance.Cleared, targetNearest.Stance);
Assert.Equal(0, targetNearest.TargetContenderId);
}
}
} }
} }