Cut 13a fix: occupancy-only Sion Box3D tiles, Terrain hit classification, top-96 TerrainRenderer LRU, incremental scar repair, per-map scar ledgers, and crater coalescing parity

This commit is contained in:
Meta Vens 2026-12-06 00:30:37 +01:00
commit 812956bd5a
13 changed files with 751 additions and 105 deletions

View file

@ -13,9 +13,9 @@ namespace RustToDust.Client;
/// </summary> /// </summary>
public partial class SionMapRenderer : Node3D public partial class SionMapRenderer : Node3D
{ {
public const float Lod1DistanceM = 520f; public const float Lod1DistanceM = 400f;
public const float CullDistanceM = 2200f; public const float CullDistanceM = 1750f;
public const float ShadowDistanceM = 360f; public const float ShadowDistanceM = 280f;
private sealed class BuildingTileEntry private sealed class BuildingTileEntry
{ {

View file

@ -61,6 +61,8 @@ public partial class TerrainRenderer : Node3D
public int BakedVisualVersion = -1; public int BakedVisualVersion = -1;
public int LruSlotIndex = -1; public int LruSlotIndex = -1;
public float TileQuads = 192f; public float TileQuads = 192f;
public float SentTileQuads = -1f;
public Vector4 SentNeighborQuads = new(-1f, -1f, -1f, -1f);
} }
private sealed class LruSlot private sealed class LruSlot
@ -119,7 +121,10 @@ public partial class TerrainRenderer : Node3D
private TerrainField? _lastTerrain; private TerrainField? _lastTerrain;
private SionMapData? _lastSionMap; private SionMapData? _lastSionMap;
private Vector3 _lastCamPos;
private int _rebakeCursor; private int _rebakeCursor;
private readonly List<(int Idx, float DistSq)> _scarCandidateScratch = new(256);
private readonly List<(int Slot, float DistSq)> _lodResidentScratch = new(MaxGpuScarTiles);
// Render-thread compute state // Render-thread compute state
private readonly object _jobLock = new(); private readonly object _jobLock = new();
@ -219,6 +224,14 @@ public partial class TerrainRenderer : Node3D
} }
} }
} }
for (int i = 0; i < _lruPool.Length; i++)
{
if (_lruPool[i] is not null)
{
_lruPool[i].AssignedTileIndex = -1;
_lruPool[i].LastUsedSeq = 0;
}
}
BakedTileCount = 0; BakedTileCount = 0;
DirtyRebakes = 0; DirtyRebakes = 0;
_rebakeCursor = 0; _rebakeCursor = 0;
@ -230,8 +243,8 @@ public partial class TerrainRenderer : Node3D
bool mapChanged = !ReferenceEquals(_lastTerrain, terrain) || !ReferenceEquals(_lastSionMap, sionMap); bool mapChanged = !ReferenceEquals(_lastTerrain, terrain) || !ReferenceEquals(_lastSionMap, sionMap);
if (mapChanged) if (mapChanged)
{ {
EnsureGridAllocated(terrain, sionMap);
InvalidateAll(); InvalidateAll();
EnsureGridAllocated(terrain, sionMap);
_lastTerrain = terrain; _lastTerrain = terrain;
_lastSionMap = sionMap; _lastSionMap = sionMap;
} }
@ -244,19 +257,92 @@ public partial class TerrainRenderer : Node3D
int grid = terrain.TileGridCount; int grid = terrain.TileGridCount;
int totalTiles = grid * grid; int totalTiles = grid * grid;
bool isSion = sionMap is not null; bool isSion = sionMap is not null;
float halfTile = _tileSize * 0.5f;
// 1. Structural dirty tiles and uninitialized tiles bake immediately (never throttled) Span<bool> wantSlot = stackalloc bool[totalTiles];
if (!isSion)
{
wantSlot.Fill(true);
}
else
{
_scarCandidateScratch.Clear();
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
if (terrain.GetTileBrushIndices(tx, tz).Count > 0)
{
var tile = _tiles[tx, tz];
float dx = (tile.OriginX + halfTile) - _lastCamPos.X;
float dz = (tile.OriginZ + halfTile) - _lastCamPos.Z;
_scarCandidateScratch.Add((tz * grid + tx, dx * dx + dz * dz));
}
}
}
if (_scarCandidateScratch.Count <= MaxGpuScarTiles)
{
for (int i = 0; i < _scarCandidateScratch.Count; i++)
{
wantSlot[_scarCandidateScratch[i].Idx] = true;
}
}
else
{
_scarCandidateScratch.Sort((a, b) => a.DistSq.CompareTo(b.DistSq));
for (int i = 0; i < MaxGpuScarTiles; i++)
{
wantSlot[_scarCandidateScratch[i].Idx] = true;
}
}
}
// 0. Release LRU slots on tiles outside the active top-96 scarred set (graceful Layer-0 DEM fallback)
for (int tz = 0; tz < grid; tz++) for (int tz = 0; tz < grid; tz++)
{ {
for (int tx = 0; tx < grid; tx++) for (int tx = 0; tx < grid; tx++)
{ {
int idx = tz * grid + tx;
if (!wantSlot[idx])
{
var tile = _tiles[tx, tz];
if (tile.LruSlotIndex >= 0)
{
ReleaseTileSlot(tile);
tile.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex);
tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex);
}
}
}
}
// 1. Structural dirty tiles, uninitialized tiles, and newly promoted top-96 tiles bake immediately (never throttled)
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
var tile = _tiles[tx, tz]; var tile = _tiles[tx, tz];
int structVer = terrain.StructuralTileVersions[tx, tz]; int structVer = terrain.StructuralTileVersions[tx, tz];
int visVer = terrain.VisualTileVersions[tx, tz]; int visVer = terrain.VisualTileVersions[tx, tz];
bool isUninit = tile.BakedVisualVersion < 0; bool isUninit = tile.BakedVisualVersion < 0;
bool isStructDirty = tile.BakedStructuralVersion != structVer;
if (isUninit || isStructDirty) if (!wantSlot[idx])
{
if (isUninit)
{
BakedTileCount++;
}
tile.BakedStructuralVersion = structVer;
tile.BakedVisualVersion = visVer;
continue;
}
bool isStructDirty = tile.BakedStructuralVersion != structVer;
bool needsSlotReacquire = tile.LruSlotIndex < 0;
if (isUninit || isStructDirty || needsSlotReacquire)
{ {
EnqueueTileBake(tx, tz, tile, terrain, isSion); EnqueueTileBake(tx, tz, tile, terrain, isSion);
if (isUninit) if (isUninit)
@ -273,12 +359,16 @@ public partial class TerrainRenderer : Node3D
} }
} }
// 2. Remaining passive visual dirty tiles (Tracks / Scorch) throttled to <= MaxDirtyRebakesPerSync (4) // 2. Remaining passive visual dirty tiles (Tracks / Scorch) inside top-96 throttled to <= MaxDirtyRebakesPerSync (4)
int rebakedThisSync = 0; int rebakedThisSync = 0;
int startCursor = _rebakeCursor; int startCursor = _rebakeCursor;
for (int step = 0; step < totalTiles; step++) for (int step = 0; step < totalTiles; step++)
{ {
int idx = (startCursor + step) % totalTiles; int idx = (startCursor + step) % totalTiles;
if (!wantSlot[idx])
{
continue;
}
int tx = idx % grid; int tx = idx % grid;
int tz = idx / grid; int tz = idx / grid;
var tile = _tiles[tx, tz]; var tile = _tiles[tx, tz];
@ -327,6 +417,7 @@ public partial class TerrainRenderer : Node3D
public void UpdateTileLod(Vector3 camPos) public void UpdateTileLod(Vector3 camPos)
{ {
_lastCamPos = camPos;
if (_tiles is null) if (_tiles is null)
{ {
return; return;
@ -336,6 +427,7 @@ public partial class TerrainRenderer : Node3D
const float midRadiusSq = 780f * 780f; const float midRadiusSq = 780f * 780f;
const float shadowRadiusSq = 360f * 360f; const float shadowRadiusSq = 360f * 360f;
float halfTile = _tileSize * 0.5f; float halfTile = _tileSize * 0.5f;
_lodResidentScratch.Clear();
for (int tz = 0; tz < _gridCount; tz++) for (int tz = 0; tz < _gridCount; tz++)
{ {
@ -348,6 +440,11 @@ public partial class TerrainRenderer : Node3D
float dz = cz - camPos.Z; float dz = cz - camPos.Z;
float d2 = dx * dx + dz * dz; float d2 = dx * dx + dz * dz;
if (tile.LruSlotIndex >= 0)
{
_lodResidentScratch.Add((tile.LruSlotIndex, d2));
}
PlaneMesh desiredMesh; PlaneMesh desiredMesh;
float quads; float quads;
if (d2 <= nearRadiusSq) if (d2 <= nearRadiusSq)
@ -391,9 +488,27 @@ public partial class TerrainRenderer : Node3D
float qRight = tx < _gridCount - 1 ? _tiles[tx + 1, tz].TileQuads : qSelf; float qRight = tx < _gridCount - 1 ? _tiles[tx + 1, tz].TileQuads : qSelf;
float qTop = tz > 0 ? _tiles[tx, tz - 1].TileQuads : qSelf; float qTop = tz > 0 ? _tiles[tx, tz - 1].TileQuads : qSelf;
float qBottom = tz < _gridCount - 1 ? _tiles[tx, tz + 1].TileQuads : qSelf; float qBottom = tz < _gridCount - 1 ? _tiles[tx, tz + 1].TileQuads : qSelf;
var nq = new Vector4(qLeft, qRight, qTop, qBottom);
tile.SurfaceMat.SetShaderParameter("tile_quads", qSelf); if (tile.SentTileQuads != qSelf)
tile.SurfaceMat.SetShaderParameter("neighbor_quads", new Vector4(qLeft, qRight, qTop, qBottom)); {
tile.SurfaceMat.SetShaderParameter("tile_quads", qSelf);
tile.SentTileQuads = qSelf;
}
if (tile.SentNeighborQuads != nq)
{
tile.SurfaceMat.SetShaderParameter("neighbor_quads", nq);
tile.SentNeighborQuads = nq;
}
}
}
if (_lodResidentScratch.Count > 0)
{
_lodResidentScratch.Sort((a, b) => b.DistSq.CompareTo(a.DistSq));
for (int i = 0; i < _lodResidentScratch.Count; i++)
{
_lruPool[_lodResidentScratch[i].Slot].LastUsedSeq = ++_lruClock;
} }
} }
} }

View file

@ -52,7 +52,7 @@ namespace RustToDust.Core
public sealed class ArenaScarLedger public sealed class ArenaScarLedger
{ {
public const int MaxPersistentTerrainScars = 4096; public const int MaxPersistentTerrainScars = 4096;
public const float CraterCoalesceRadiusMeters = 0.75f; public const float CraterCoalesceRadiusMeters = TerrainField.CraterCoalesceRadiusMeters;
private readonly List<TerrainScarEntry> _terrain = new(); private readonly List<TerrainScarEntry> _terrain = new();
private readonly Dictionary<ushort, BuildingScarEntry> _buildings = new(); private readonly Dictionary<ushort, BuildingScarEntry> _buildings = new();
@ -81,6 +81,12 @@ namespace RustToDust.Core
return; return;
} }
if (stampKind == TerrainStampKind.Crater)
{
radius = Math.Clamp(radius, 1.2f, 16f);
depth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f);
}
float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters; float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters;
if (stampKind == TerrainStampKind.Crater || stampKind == TerrainStampKind.Scorch) if (stampKind == TerrainStampKind.Crater || stampKind == TerrainStampKind.Scorch)
{ {

View file

@ -43,6 +43,7 @@ namespace RustToDust.Core
public const float MaxWorldHeight = 52f; public const float MaxWorldHeight = 52f;
public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m
public const int MaxDynamicDecals = 256; public const int MaxDynamicDecals = 256;
public const float CraterCoalesceRadiusMeters = 0.75f;
private readonly record struct BrushPrecomp( private readonly record struct BrushPrecomp(
float CosR, float CosR,
@ -475,6 +476,40 @@ namespace RustToDust.Core
{ {
float clampedR = Math.Clamp(radius, 1.2f, 16f); float clampedR = Math.Clamp(radius, 1.2f, 16f);
float clampedDepth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f); float clampedDepth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f);
const float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters;
for (int i = _brushes.Count - 1; i >= 0; i--)
{
var existing = _brushes[i];
if (existing.Kind != TerrainBrushKind.Crater || !existing.Dynamic)
{
continue;
}
float dx = existing.X - x;
float dz = existing.Z - z;
if (dx * dx + dz * dz < coalesceSq)
{
float newR = MathF.Max(existing.RadiusX, clampedR);
float existingDepth = MathF.Abs(existing.HeightDelta);
float newDepth = MathF.Max(existingDepth, clampedDepth);
if (newR > existing.RadiusX || newDepth > existingDepth)
{
UnregisterBrushFromTiles(i, in existing);
var updated = existing with
{
RadiusX = newR,
RadiusZ = newR,
HeightDelta = -newDepth
};
_brushes[i] = updated;
_brushPrecomps[i] = BrushPrecomp.From(in updated);
RegisterBrushInTiles(i, in updated, incrementTileVersion: true);
}
return;
}
}
AddBrush(new TerrainBrush( AddBrush(new TerrainBrush(
Id: 0, Id: 0,
Kind: TerrainBrushKind.Crater, Kind: TerrainBrushKind.Crater,
@ -605,13 +640,16 @@ namespace RustToDust.Core
float h = SampleBaseHeight(cx, cz); float h = SampleBaseHeight(cx, cz);
WorldToAccelCell(cx, cz, out int acx, out int acz); if (_brushes.Count > 0)
var indices = _cellBrushIndices[acz * AccelGridCount + acx];
for (int i = 0; i < indices.Count; i++)
{ {
int idx = indices[i]; WorldToAccelCell(cx, cz, out int acx, out int acz);
var b = _brushes[idx]; var indices = _cellBrushIndices[acz * AccelGridCount + acx];
h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz); for (int i = 0; i < indices.Count; i++)
{
int idx = indices[i];
var b = _brushes[idx];
h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz);
}
} }
return Math.Clamp(h, MapMinHeight, MapMaxHeight); return Math.Clamp(h, MapMinHeight, MapMaxHeight);

View file

@ -94,6 +94,8 @@ namespace RustToDust.Net
public bool RequestEquipCargo(int cargoIndex, string hardpointId) => public bool RequestEquipCargo(int cargoIndex, string hardpointId) =>
_host.TryEquipHostCargo(cargoIndex, hardpointId); _host.TryEquipHostCargo(cargoIndex, hardpointId);
public void RepairArenaScars() => _host.RepairArenaScars();
public void RequestNewMatch(int seed, ArenaMapKind mapKind) => public void RequestNewMatch(int seed, ArenaMapKind mapKind) =>
_host.ResetMatch(seed, mapKind); _host.ResetMatch(seed, mapKind);

View file

@ -55,8 +55,10 @@ namespace RustToDust.Net
private readonly List<ISimEvent> _hostPendingEvents = new(); private readonly List<ISimEvent> _hostPendingEvents = new();
private readonly List<TerrainStampEvent> _terrainStampHistory = new(); private readonly List<TerrainStampEvent> _terrainStampHistory = new();
private readonly List<int>[,] _tileStampHistory = new List<int>[16, 16]; private readonly List<int>[,] _tileStampHistory = new List<int>[16, 16];
private readonly string? _scarFilePath; private readonly string? _configuredScarPath;
private readonly ArenaMapKind _initialMapKind;
private readonly bool _persistScars; private readonly bool _persistScars;
private readonly Dictionary<ArenaMapKind, ArenaScarLedgerSnapshot> _inMemoryScarsByMap = new();
private readonly int _maxHumans; private readonly int _maxHumans;
private readonly double _autoRestartSec; private readonly double _autoRestartSec;
private readonly bool _allowClientReset; private readonly bool _allowClientReset;
@ -108,9 +110,8 @@ namespace RustToDust.Net
_restartToLobby = restartToLobby; _restartToLobby = restartToLobby;
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4); _squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
_persistScars = persistScars; _persistScars = persistScars;
_scarFilePath = persistScars _configuredScarPath = scarFilePath;
? (string.IsNullOrWhiteSpace(scarFilePath) ? ArenaScarLedgerStore.GetDefaultPath(mapKind) : scarFilePath) _initialMapKind = mapKind;
: null;
for (int tz = 0; tz < 16; tz++) for (int tz = 0; tz < 16; tz++)
{ {
for (int tx = 0; tx < 16; tx++) for (int tx = 0; tx < 16; tx++)
@ -139,20 +140,18 @@ namespace RustToDust.Net
_server.PeerDisconnected += OnTransportPeerDisconnected; _server.PeerDisconnected += OnTransportPeerDisconnected;
ArenaScarLedgerSnapshot? initialScars = null; ArenaScarLedgerSnapshot? initialScars = null;
if (_persistScars && _scarFilePath is not null) string? initScarPath = _persistScars ? ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind) : null;
if (_persistScars && initScarPath is not null)
{ {
string fp = GetAssetFingerprint(seed, mapKind);
if (repairScarsOnStart) if (repairScarsOnStart)
{ {
var emptySnap = new ArenaScarLedgerSnapshot var emptySnap = new ArenaScarLedgerSnapshot { AssetFingerprint = fp };
{ ArenaScarLedgerStore.Save(initScarPath, emptySnap);
AssetFingerprint = mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}"
};
ArenaScarLedgerStore.Save(_scarFilePath, emptySnap);
} }
else else
{ {
string fp = mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}"; initialScars = ArenaScarLedgerStore.Load(initScarPath, fp);
initialScars = ArenaScarLedgerStore.Load(_scarFilePath, fp);
} }
} }
@ -218,16 +217,35 @@ namespace RustToDust.Net
{ {
_hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name; _hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name;
} }
ArenaScarLedgerSnapshot? preservedScars = null; if (repairScars)
if (mapKind == _session.State.MapKind) {
_session.State.RepairArenaScars();
_inMemoryScarsByMap.Remove(mapKind);
}
ArenaMapKind prevMapKind = _session.State.MapKind;
_inMemoryScarsByMap[prevMapKind] = _session.State.ScarLedger.ToSnapshot();
FlushScarLedgerIfDirty();
ArenaScarLedgerSnapshot? preservedScars = null;
if (mapKind == prevMapKind)
{ {
if (repairScars)
{
_session.State.RepairArenaScars();
}
preservedScars = _session.State.ScarLedger.ToSnapshot(); preservedScars = _session.State.ScarLedger.ToSnapshot();
} }
FlushScarLedgerIfDirty(); else if (!repairScars)
{
string expectedFp = GetAssetFingerprint(seed, mapKind);
if (_inMemoryScarsByMap.TryGetValue(mapKind, out var memScars) &&
string.Equals(memScars.AssetFingerprint, expectedFp, StringComparison.Ordinal))
{
preservedScars = memScars;
}
else if (_persistScars)
{
string targetPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind);
preservedScars = ArenaScarLedgerStore.Load(targetPath, expectedFp);
}
}
_session.Dispose(); _session.Dispose();
_session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: preservedScars); _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: preservedScars);
_matchGeneration++; _matchGeneration++;
@ -1949,6 +1967,7 @@ namespace RustToDust.Net
public void RepairArenaScars() public void RepairArenaScars()
{ {
_session.RepairArenaScars(); _session.RepairArenaScars();
_inMemoryScarsByMap.Remove(_session.State.MapKind);
_terrainStampHistory.Clear(); _terrainStampHistory.Clear();
ClearTileStampHistory(); ClearTileStampHistory();
FlushScarLedgerIfDirty(); FlushScarLedgerIfDirty();
@ -2044,17 +2063,58 @@ namespace RustToDust.Net
} }
} }
public static string ResolveScarFilePath(string? configuredPath, ArenaMapKind initialMapKind, ArenaMapKind targetMapKind)
{
if (string.IsNullOrWhiteSpace(configuredPath))
{
return ArenaScarLedgerStore.GetDefaultPath(targetMapKind);
}
string mapTag = targetMapKind == ArenaMapKind.Sion ? "sion" : "desert";
if (configuredPath.EndsWith(Path.DirectorySeparatorChar) ||
configuredPath.EndsWith(Path.AltDirectorySeparatorChar) ||
Directory.Exists(configuredPath))
{
return Path.Combine(configuredPath, $"{mapTag}_scars_default.cultcache");
}
if (targetMapKind == initialMapKind)
{
return configuredPath;
}
string dir = Path.GetDirectoryName(configuredPath) ?? ".";
string fileName = Path.GetFileName(configuredPath);
string initTag = initialMapKind == ArenaMapKind.Sion ? "sion" : "desert";
if (fileName.StartsWith(initTag + "_", StringComparison.OrdinalIgnoreCase))
{
return Path.Combine(dir, mapTag + fileName.Substring(initTag.Length));
}
string stem = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
return Path.Combine(dir, $"{stem}.{mapTag}{ext}");
}
private static string GetAssetFingerprint(int seed, ArenaMapKind mapKind) =>
mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}";
private void FlushScarLedgerIfDirty() private void FlushScarLedgerIfDirty()
{ {
if (!_persistScars || string.IsNullOrWhiteSpace(_scarFilePath)) if (!_persistScars)
{ {
return; return;
} }
if (!_session.State.ScarLedger.IsDirty && File.Exists(_scarFilePath)) string scarPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, _session.State.MapKind);
if (string.IsNullOrWhiteSpace(scarPath))
{ {
return; return;
} }
ArenaScarLedgerStore.Save(_scarFilePath, _session.State.ScarLedger.ToSnapshot()); if (!_session.State.ScarLedger.IsDirty && File.Exists(scarPath))
{
return;
}
ArenaScarLedgerStore.Save(scarPath, _session.State.ScarLedger.ToSnapshot());
_session.State.ScarLedger.IsDirty = false; _session.State.ScarLedger.IsDirty = false;
_lastScarSaveTick = _simTick; _lastScarSaveTick = _simTick;
} }

View file

@ -98,7 +98,6 @@ namespace RustToDust.Ymir
public void RepairArenaScars() public void RepairArenaScars()
{ {
State.RepairArenaScars(); State.RepairArenaScars();
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: Box3DPhysicsTileSync.MaxTiles);
} }
public static bool IsStaticWorldStableId(ulong stableId) => public static bool IsStaticWorldStableId(ulong stableId) =>
@ -110,12 +109,6 @@ namespace RustToDust.Ymir
public Box3DSoaRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) public Box3DSoaRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
{ {
float len = translation.Length();
if (len > 1e-4f && State.Terrain.IsHeightmapMode)
{
Vector3 dir = translation / len;
_tileSync.EnsureTilesAlongRay(_world, State.Terrain, origin.X, origin.Z, dir.X, dir.Z, len);
}
return _world.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); return _world.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
} }
@ -538,7 +531,6 @@ namespace RustToDust.Ymir
if (State.SionMap is { } sionMap && if (State.SionMap is { } sionMap &&
sionMap.IntersectsAnyBuildingAabb(ax, ay, az, dir.X, dir.Y, dir.Z, dist)) sionMap.IntersectsAnyBuildingAabb(ax, ay, az, dir.X, dir.Y, dir.Z, dist))
{ {
_tileSync.EnsureTilesAlongRay(_world, State.Terrain, ax, az, dir.X, dir.Z, dist);
Vector3 castOrigin = new(ax, ay, az); Vector3 castOrigin = new(ax, ay, az);
float remaining = dist; float remaining = dist;
for (int hop = 0; hop < 4 && remaining > 0.25f; hop++) for (int hop = 0; hop < 4 && remaining > 0.25f; hop++)
@ -773,21 +765,9 @@ namespace RustToDust.Ymir
{ {
if (tileSync is not null && warmAllActors && state.Terrain.IsHeightmapMode) if (tileSync is not null && warmAllActors && state.Terrain.IsHeightmapMode)
{ {
for (int i = 0; i < state.Contenders.Count; i++) Span<bool> needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
{ MarkPhysicsOccupancyTiles(state, needed);
var c = state.Contenders[i]; tileSync.SyncNeededTiles(world, state.Terrain, needed);
tileSync.EnsureTileRegion(world, state.Terrain, c.X, c.Z, halfTileRadius: 1);
}
for (int i = 0; i < state.Spectators.Spectators.Count; i++)
{
var s = state.Spectators.Spectators[i];
tileSync.EnsureTileRegion(world, state.Terrain, s.X, s.Z, halfTileRadius: 1);
}
for (int i = 0; i < state.OrbitalDrop.ActivePods.Count; i++)
{
var pod = state.OrbitalDrop.ActivePods[i];
tileSync.EnsureTileRegion(world, state.Terrain, pod.X, pod.Z, halfTileRadius: 0);
}
} }
ulong boxId = StaticBoxStableIdBase; ulong boxId = StaticBoxStableIdBase;
@ -871,6 +851,17 @@ namespace RustToDust.Ymir
_contenderWalkers.Remove(c.Id); _contenderWalkers.Remove(c.Id);
if (c.IsGroundedActive) if (c.IsGroundedActive)
{ {
if (State.Terrain.IsHeightmapMode)
{
if (c.IsHuman)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 1);
}
else
{
_tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 0);
}
}
SpawnContenderBody(c); SpawnContenderBody(c);
} }
} }
@ -924,42 +915,58 @@ namespace RustToDust.Ymir
} }
} }
private static void MarkPhysicsOccupancyTiles(MatchState state, Span<bool> needed)
{
needed.Clear();
var terrain = state.Terrain;
for (int i = 0; i < state.Contenders.Count; i++)
{
var c = state.Contenders[i];
if (!c.IsGroundedActive)
{
continue;
}
if (c.IsHuman)
{
Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 28f);
}
else
{
Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 16f);
}
}
for (int i = 0; i < state.Spectators.Spectators.Count; i++)
{
var s = state.Spectators.Spectators[i];
if (s.Alive && s.Stance != SpectatorStance.Neutral)
{
Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, s.X, s.Z, marginMeters: 8f);
}
}
for (int i = 0; i < state.OrbitalDrop.ActivePods.Count; i++)
{
var pod = state.OrbitalDrop.ActivePods[i];
if (pod.Y - terrain.SampleHeight(pod.X, pod.Z) <= 80f)
{
Box3DPhysicsTileSync.MarkTileRegion(terrain, needed, pod.X, pod.Z, halfTileRadius: 0);
}
}
}
private void EnsureActivePhysicsTilesAndFlush() private void EnsureActivePhysicsTilesAndFlush()
{ {
if (!State.Terrain.IsHeightmapMode) if (!State.Terrain.IsHeightmapMode)
{ {
return; return;
} }
for (int i = 0; i < State.Contenders.Count; i++) Span<bool> needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
{ MarkPhysicsOccupancyTiles(State, needed);
var c = State.Contenders[i]; _tileSync.SyncNeededTiles(_world, State.Terrain, needed);
if (c.Alive)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 1);
}
}
for (int i = 0; i < State.Spectators.Spectators.Count; i++)
{
var s = State.Spectators.Spectators[i];
if (s.Alive)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, s.X, s.Z, halfTileRadius: 1);
}
}
for (int i = 0; i < State.OrbitalDrop.ActivePods.Count; i++)
{
var pod = State.OrbitalDrop.ActivePods[i];
_tileSync.EnsureTileRegion(_world, State.Terrain, pod.X, pod.Z, halfTileRadius: 0);
}
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: 4); _tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: 4);
} }
public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY) public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY)
{ {
if (State.Terrain.IsHeightmapMode)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, x, z, halfTileRadius: 0);
}
return QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY); return QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY);
} }
@ -1504,7 +1511,8 @@ namespace RustToDust.Ymir
Vector3 toGoal = new Vector3(goalX - pos.X, 0f, goalZ - pos.Z); Vector3 toGoal = new Vector3(goalX - pos.X, 0f, goalZ - pos.Z);
float dist = toGoal.Length(); float dist = toGoal.Length();
// On Sion, StaticHeightField supports settled Neutral Patrons/Exemplars directly so Box3D can sleep them. // On Sion, StaticHeightField supports settled Neutral Patrons/Exemplars directly so Box3D can sleep them,
// provided the underlying heightfield tile is currently resident.
if (State.MapKind == ArenaMapKind.Sion && if (State.MapKind == ArenaMapKind.Sion &&
s.Stance == SpectatorStance.Neutral && s.Stance == SpectatorStance.Neutral &&
s.Tier != SpectatorTier.Tourist && s.Tier != SpectatorTier.Tourist &&
@ -1513,13 +1521,17 @@ namespace RustToDust.Ymir
angVel.LengthSquared() < 0.09f && angVel.LengthSquared() < 0.09f &&
up.Y > 0.90f) up.Y > 0.90f)
{ {
view.ForceX[lane] = 0f; State.Terrain.MapWorldToTile(pos.X, pos.Z, out int stx, out int stz);
view.ForceY[lane] = 0f; if (_tileSync.TryGetResidentHandle(stx, stz, State.Terrain.TileGridCount, out _))
view.ForceZ[lane] = 0f; {
view.TorqueX[lane] = 0f; view.ForceX[lane] = 0f;
view.TorqueY[lane] = 0f; view.ForceY[lane] = 0f;
view.TorqueZ[lane] = 0f; view.ForceZ[lane] = 0f;
continue; view.TorqueX[lane] = 0f;
view.TorqueY[lane] = 0f;
view.TorqueZ[lane] = 0f;
continue;
}
} }
Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero; Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero;
@ -3402,14 +3414,6 @@ namespace RustToDust.Ymir
} }
} }
void IOrdnanceTargetSink.EnsurePhysicsTilesAlongRay(Vector3 origin, Vector3 dir, float distance)
{
if (State.Terrain.IsHeightmapMode)
{
_tileSync.EnsureTilesAlongRay(_world, State.Terrain, origin.X, origin.Z, dir.X, dir.Z, distance);
}
}
private static Vector3 ComputeBoxFaceNormal( private static Vector3 ComputeBoxFaceNormal(
(float X, float Y, float Z) hitPoint, (float X, float Y, float Z) hitPoint,
int lane, int lane,

View file

@ -16,6 +16,9 @@ namespace RustToDust.Ymir
private readonly int[] _syncedStructuralVersions = new int[MaxTiles]; private readonly int[] _syncedStructuralVersions = new int[MaxTiles];
private float[]? _scratchHeights; private float[]? _scratchHeights;
public static bool IsHeightfieldTileStableId(ulong stableId) =>
stableId >= HeightfieldTileStableIdBase && stableId < HeightfieldTileStableIdBase + MaxTiles;
public int ResidentTileCount { get; private set; } public int ResidentTileCount { get; private set; }
public bool TryGetResidentHandle(int tx, int tz, int tileGridCount, out Box3DSoaBodyHandle handle) public bool TryGetResidentHandle(int tx, int tz, int tileGridCount, out Box3DSoaBodyHandle handle)
@ -123,6 +126,88 @@ namespace RustToDust.Ymir
} }
} }
public static void MarkTileRegion(TerrainField terrain, Span<bool> needed, float worldX, float worldZ, int halfTileRadius)
{
if (!terrain.IsHeightmapMode)
{
return;
}
terrain.MapWorldToTile(worldX, worldZ, out int cx, out int cz);
int grid = terrain.TileGridCount;
int minTx = Math.Max(0, cx - halfTileRadius);
int maxTx = Math.Min(grid - 1, cx + halfTileRadius);
int minTz = Math.Max(0, cz - halfTileRadius);
int maxTz = Math.Min(grid - 1, cz + halfTileRadius);
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
needed[tz * grid + tx] = true;
}
}
}
public static void MarkTileFootprint(TerrainField terrain, Span<bool> needed, float worldX, float worldZ, float marginMeters)
{
if (!terrain.IsHeightmapMode)
{
return;
}
float half = terrain.MapHalfExtent;
float r = MathF.Max(0f, marginMeters);
terrain.MapWorldToTile(Math.Clamp(worldX - r, -half, half), Math.Clamp(worldZ - r, -half, half), out int minTx, out int minTz);
terrain.MapWorldToTile(Math.Clamp(worldX + r, -half, half), Math.Clamp(worldZ + r, -half, half), out int maxTx, out int maxTz);
int grid = terrain.TileGridCount;
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
needed[tz * grid + tx] = true;
}
}
}
public void SyncNeededTiles(Box3DSoaWorld world, TerrainField terrain, ReadOnlySpan<bool> needed)
{
if (!terrain.IsHeightmapMode)
{
return;
}
int grid = terrain.TileGridCount;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (_residentFlags[idx] && !needed[idx])
{
world.RemoveBody(_residentHandles[idx]);
_residentHandles[idx] = default;
_residentFlags[idx] = false;
_syncedStructuralVersions[idx] = 0;
ResidentTileCount--;
}
}
}
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (needed[idx] && !_residentFlags[idx])
{
EnsureTileResident(world, terrain, tx, tz);
}
}
}
}
public void EnsureTilesAlongRay( public void EnsureTilesAlongRay(
Box3DSoaWorld world, Box3DSoaWorld world,
TerrainField terrain, TerrainField terrain,
@ -152,8 +237,8 @@ namespace RustToDust.Ymir
float ez = oz + dz * tMax; float ez = oz + dz * tMax;
terrain.MapWorldToTile(ex, ez, out int endTx, out int endTz); terrain.MapWorldToTile(ex, ez, out int endTx, out int endTz);
int stepX = dx > 1e-6f ? 1 : (dx < -1e-6f ? -1 : 0); int stepX = dx > 1e-9f ? 1 : (dx < -1e-9f ? -1 : 0);
int stepZ = dz > 1e-6f ? 1 : (dz < -1e-6f ? -1 : 0); int stepZ = dz > 1e-9f ? 1 : (dz < -1e-9f ? -1 : 0);
float tDeltaX = stepX != 0 ? tileSize / MathF.Abs(dx) : float.PositiveInfinity; float tDeltaX = stepX != 0 ? tileSize / MathF.Abs(dx) : float.PositiveInfinity;
float tDeltaZ = stepZ != 0 ? tileSize / MathF.Abs(dz) : float.PositiveInfinity; float tDeltaZ = stepZ != 0 ? tileSize / MathF.Abs(dz) : float.PositiveInfinity;
@ -190,6 +275,11 @@ namespace RustToDust.Ymir
break; break;
} }
} }
if ((uint)endTx < (uint)grid && (uint)endTz < (uint)grid)
{
EnsureTileResident(world, terrain, endTx, endTz);
}
} }
public int FlushDirtyHeightfields(Box3DSoaWorld world, TerrainField terrain, int maxTilesPerTick = 4) public int FlushDirtyHeightfields(Box3DSoaWorld world, TerrainField terrain, int maxTilesPerTick = 4)
@ -201,6 +291,7 @@ namespace RustToDust.Ymir
int grid = terrain.TileGridCount; int grid = terrain.TileGridCount;
int rebuilt = 0; int rebuilt = 0;
var view = world.View;
for (int tz = 0; tz < grid; tz++) for (int tz = 0; tz < grid; tz++)
{ {
for (int tx = 0; tx < grid; tx++) for (int tx = 0; tx < grid; tx++)
@ -212,6 +303,10 @@ namespace RustToDust.Ymir
} }
if (terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx]) if (terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx])
{ {
if (view.Count >= view.Capacity - 8)
{
return rebuilt;
}
if (EnsureTileResident(world, terrain, tx, tz)) if (EnsureTileResident(world, terrain, tx, tz))
{ {
rebuilt++; rebuilt++;
@ -267,7 +362,7 @@ namespace RustToDust.Ymir
private static bool SlabClip(float o, float d, float minB, float maxB, ref float tMin, ref float tMax) private static bool SlabClip(float o, float d, float minB, float maxB, ref float tMin, ref float tMax)
{ {
if (MathF.Abs(d) < 1e-6f) if (MathF.Abs(d) < 1e-9f)
{ {
return o >= minB && o <= maxB; return o >= minB && o <= maxB;
} }

View file

@ -8,6 +8,7 @@ namespace RustToDust.Ymir
public sealed class LocalArenaSession : IClientArenaSession public sealed class LocalArenaSession : IClientArenaSession
{ {
private readonly List<ISimEvent> _pendingEvents = new(); private readonly List<ISimEvent> _pendingEvents = new();
private readonly Dictionary<ArenaMapKind, ArenaScarLedgerSnapshot> _scarsByMap = new();
public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null, bool skipInitialDrop = false, byte squadSize = 1) public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null, bool skipInitialDrop = false, byte squadSize = 1)
{ {
@ -95,13 +96,21 @@ namespace RustToDust.Ymir
return ok; return ok;
} }
public void RepairArenaScars()
{
Inner.RepairArenaScars();
_scarsByMap.Remove(Inner.State.MapKind);
}
public void RequestNewMatch(int seed, ArenaMapKind mapKind) public void RequestNewMatch(int seed, ArenaMapKind mapKind)
{ {
string? name = LocalContender.Name; string? name = LocalContender.Name;
byte squadSize = Inner.State.SquadSize; byte squadSize = Inner.State.SquadSize;
_scarsByMap[Inner.State.MapKind] = Inner.State.ScarLedger.ToSnapshot();
_scarsByMap.TryGetValue(mapKind, out var initialScars);
_pendingEvents.Clear(); _pendingEvents.Clear();
Inner.Dispose(); Inner.Dispose();
Inner = new ArenaSession(seed, mapKind, slot0Human: true, squadSize: squadSize) Inner = new ArenaSession(seed, mapKind, slot0Human: true, squadSize: squadSize, initialScars: initialScars)
{ {
EnableNetworkPvs = false EnableNetworkPvs = false
}; };

View file

@ -103,7 +103,6 @@ namespace RustToDust.Ymir
bool isSpectatorShooter, bool isSpectatorShooter,
int shooterEntityId); int shooterEntityId);
void StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius); void StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius);
void EnsurePhysicsTilesAlongRay(Vector3 origin, Vector3 dir, float distance);
} }
public struct LiveOrdnanceInstance public struct LiveOrdnanceInstance
@ -764,7 +763,6 @@ namespace RustToDust.Ymir
for (int hop = 0; hop < 4 && remaining > 1e-4f; hop++) for (int hop = 0; hop < 4 && remaining > 1e-4f; hop++)
{ {
_sink.EnsurePhysicsTilesAlongRay(castOrigin, dir, remaining);
var rayHit = _sink.World.CastRayClosest( var rayHit = _sink.World.CastRayClosest(
(castOrigin.X, castOrigin.Y, castOrigin.Z), (castOrigin.X, castOrigin.Y, castOrigin.Z),
(dir.X * remaining, dir.Y * remaining, dir.Z * remaining)); (dir.X * remaining, dir.Y * remaining, dir.Z * remaining));
@ -845,12 +843,13 @@ namespace RustToDust.Ymir
return !inst.Active; return !inst.Active;
} }
bool isTerrainTile = Box3DPhysicsTileSync.IsHeightfieldTileStableId(hitStableId);
inst.Pos = boxPoint; inst.Pos = boxPoint;
HandleProjectileImpact( HandleProjectileImpact(
slotIndex, slotIndex,
HitTargetKind.StaticCover, isTerrainTile ? HitTargetKind.Terrain : HitTargetKind.StaticCover,
(int)hitStableId, isTerrainTile ? -1 : (int)hitStableId,
hitStableId, isTerrainTile ? 0UL : hitStableId,
boxPoint, boxPoint,
boxNormal, boxNormal,
dir); dir);
@ -1292,7 +1291,6 @@ namespace RustToDust.Ymir
for (int hop = 0; hop < 6 && remainingRange > 0.2f; hop++) for (int hop = 0; hop < 6 && remainingRange > 0.2f; hop++)
{ {
_sink.EnsurePhysicsTilesAlongRay(castOrigin, dir, remainingRange);
var rayHit = _sink.World.CastRayClosest( var rayHit = _sink.World.CastRayClosest(
(castOrigin.X, castOrigin.Y, castOrigin.Z), (castOrigin.X, castOrigin.Y, castOrigin.Z),
(dir.X * remainingRange, dir.Y * remainingRange, dir.Z * remainingRange)); (dir.X * remainingRange, dir.Y * remainingRange, dir.Z * remainingRange));
@ -1416,6 +1414,16 @@ namespace RustToDust.Ymir
continue; continue;
} }
if (Box3DPhysicsTileSync.IsHeightfieldTileStableId(rayHit.StableId))
{
hitTerrain = true;
terrainHitX = rayHit.Point.X;
terrainHitY = rayHit.Point.Y;
terrainHitZ = rayHit.Point.Z;
hitAny = false;
break;
}
hitAny = true; hitAny = true;
hitStableId = rayHit.StableId; hitStableId = rayHit.StableId;
hitPoint = rayHit.Point; hitPoint = rayHit.Point;

View file

@ -878,6 +878,45 @@ namespace RustToDust.Tests
$"Expected _predWorld crater impact Y ({predHit.Point.Y:F3}m) to match server ({hostHit.Point.Y:F3}m)"); $"Expected _predWorld crater impact Y ({predHit.Point.Y:F3}m) to match server ({hostHit.Point.Y:F3}m)");
} }
[Fact]
public void Cut13a_OverlappingCraters_CoalesceIdenticallyAcrossLiveHostJoinerAndPostReset()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
const float cx = -120f;
const float cz = 180f;
// Stamp 3 overlapping craters within < 0.75m (coalesce radius)
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx, cz, craterRadius: 4.0f, craterDepth: 1.1f, scorchRadius: 4.5f);
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx + 0.30f, cz - 0.20f, craterRadius: 5.8f, craterDepth: 2.2f, scorchRadius: 6.0f);
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx - 0.15f, cz + 0.25f, craterRadius: 3.0f, craterDepth: 0.7f, scorchRadius: 3.5f);
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
host.StepOnce(nowMs += 16);
float liveHostH = host.Session.State.Terrain.SampleHeight(cx, cz);
float liveHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f);
using var clientA = new RemoteArenaSession(ep, "Joiner");
Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000));
float clientJoinH = clientA.ViewState.Terrain.SampleHeight(cx, cz);
float clientJoinEdgeH = clientA.ViewState.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f);
Assert.True(MathF.Abs(liveHostH - clientJoinH) < 0.001f,
$"Expected liveHostH ({liveHostH:F4}) == clientJoinH ({clientJoinH:F4}) within 0.001m");
Assert.True(MathF.Abs(liveHostEdgeH - clientJoinEdgeH) < 0.001f,
$"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == clientJoinEdgeH ({clientJoinEdgeH:F4}) within 0.001m");
host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false);
float postResetHostH = host.Session.State.Terrain.SampleHeight(cx, cz);
float postResetHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f);
Assert.True(MathF.Abs(liveHostH - postResetHostH) < 0.001f,
$"Expected liveHostH ({liveHostH:F4}) == postResetHostH ({postResetHostH:F4}) within 0.001m");
Assert.True(MathF.Abs(liveHostEdgeH - postResetHostEdgeH) < 0.001f,
$"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == postResetHostEdgeH ({postResetHostEdgeH:F4}) within 0.001m");
}
private static byte[] EncodeRudpLatestDatagram(byte[] frameBytes, uint sequence) => private static byte[] EncodeRudpLatestDatagram(byte[] frameBytes, uint sequence) =>
CultNetRudpPacketCodec.Encode(new CultNetRudpPacket CultNetRudpPacketCodec.Encode(new CultNetRudpPacket
{ {

View file

@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Numerics; using System.Numerics;
@ -146,7 +147,7 @@ namespace RustToDust.Tests
if (kind == Box3DSoaKind.StaticHeightField) hfCount++; if (kind == Box3DSoaKind.StaticHeightField) hfCount++;
else if (kind == Box3DSoaKind.StaticMesh) meshCount++; else if (kind == Box3DSoaKind.StaticMesh) meshCount++;
} }
Assert.InRange(hfCount, 1, 255); Assert.InRange(hfCount, 1, 45);
Assert.Equal(hfCount, session.TileSync.ResidentTileCount); Assert.Equal(hfCount, session.TileSync.ResidentTileCount);
Assert.Equal(36, meshCount); Assert.Equal(36, meshCount);
@ -378,5 +379,274 @@ namespace RustToDust.Tests
} }
} }
} }
[Fact]
public void ValereSlopeHits_ClassifyAsTerrainNeverStaticCover_ForHitscanAndProjectile()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
var sion = session.State.SionMap!;
// Ensure Valere hill heightfield tiles are resident so Box3D heightfields are active on the slope ray
session.TileSync.EnsureTileRegion(session.World, terrain, 113f, -211f, halfTileRadius: 1);
// Find an open-sky steep Valere slope point and an unobstructed muzzle above it (zero buildings on ray)
Vector3 muzzle = default;
Vector3 dir = default;
bool foundSlope = false;
for (float sz = -290f; sz <= -175f && !foundSlope; sz += 6f)
{
for (float sx = 40f; sx <= 185f && !foundSlope; sx += 6f)
{
if (sion.IsInsideAnyBuildingXz(sx, sz, padding: 8.0f))
{
continue;
}
float sh = terrain.SampleHeight(sx, sz);
var (nx, ny, nz) = terrain.SampleNormal(sx, sz);
if (sh < 55f || ny >= 0.88f)
{
continue;
}
Vector3 slopePt = new(sx, sh, sz);
Vector3 nrm = Vector3.Normalize(new Vector3(nx, ny, nz));
Vector3 candMuzzle = slopePt + nrm * 32f + Vector3.UnitY * 8f;
Vector3 candDir = Vector3.Normalize(slopePt - candMuzzle);
float dist = Vector3.Distance(candMuzzle, slopePt) + 5f;
if (!sion.IntersectsAnyBuildingAabb(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist) &&
terrain.Raycast(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist, out float tx, out _, out float tz, out _) &&
!sion.IsInsideAnyBuildingXz(tx, tz, padding: 2.0f))
{
muzzle = candMuzzle;
dir = candDir;
foundSlope = true;
}
}
}
Assert.True(foundSlope, "Expected open-sky steep Valere slope ray unobstructed by buildings");
session.TileSync.EnsureTileRegion(session.World, terrain, muzzle.X, muzzle.Z, halfTileRadius: 1);
var events = new List<ISimEvent>();
session.DrainStepEvents(events);
// 1. Fire hitscan directly into Valere slope
var hitscanSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.RotaryAutocannon);
session.Ordnance.FireWeapon(new OrdnanceFireRequest(
Module: new MountedModule(hitscanSpec.Module, "hp.weapon.main", 0f),
ShooterStableId: ArenaSession.ContenderStableIdBase,
ShooterContender: session.State.Contenders[0],
ShooterLabel: "Tester",
IsSpectatorShooter: false,
ShooterEntityId: 0,
ShooterPos: muzzle,
MuzzlePos: muzzle,
AimDir: dir,
AimDist: 160f,
SpreadRad: 0f,
TargetEntityStableId: 0UL,
RootDef: hitscanSpec.RootNode,
WeaponKey: hitscanSpec.Key));
// 2. Fire ballistic projectile into Valere slope
var projSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.SabotSlugCannon);
session.Ordnance.FireWeapon(new OrdnanceFireRequest(
Module: new MountedModule(projSpec.Module, "hp.weapon.main", 0f),
ShooterStableId: ArenaSession.ContenderStableIdBase,
ShooterContender: session.State.Contenders[0],
ShooterLabel: "Tester",
IsSpectatorShooter: false,
ShooterEntityId: 0,
ShooterPos: muzzle,
MuzzlePos: muzzle,
AimDir: dir,
AimDist: 160f,
SpreadRad: 0f,
TargetEntityStableId: 0UL,
RootDef: projSpec.RootNode,
WeaponKey: projSpec.Key));
var impacts = new List<HitImpactEvent>();
for (int tick = 0; tick < 60; tick++)
{
session.Step();
events.Clear();
session.DrainStepEvents(events);
foreach (var ev in events)
{
if (ev is HitImpactEvent hit)
{
impacts.Add(hit);
}
}
if (impacts.Count >= 2)
{
break;
}
}
Assert.True(impacts.Count >= 2, $"Expected >= 2 slope impacts (hitscan + projectile), got {impacts.Count}");
Assert.All(impacts, h => Assert.Equal((byte)HitTargetKind.Terrain, h.TargetKind));
}
[Fact]
public void RepairArenaScars_ManyScarredTilesRebuildIncrementallyWithoutExhaustingWorldCapacity()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
// Materialize 20 resident tiles in a 5x4 grid and crater all 20
var spots = new List<(float X, float Z, float BaseH)>();
for (int tz = 5; tz <= 8; tz++)
{
for (int tx = 5; tx <= 9; tx++)
{
float wx = -terrain.MapHalfExtent + (tx + 0.5f) * terrain.MapTileSize;
float wz = -terrain.MapHalfExtent + (tz + 0.5f) * terrain.MapTileSize;
session.TileSync.EnsureTileResident(session.World, terrain, tx, tz);
float baseH = terrain.SampleHeight(wx, wz);
spots.Add((wx, wz, baseH));
session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = wx,
Z = wz,
Radius = 5f,
Depth = 1.6f
});
}
}
// Step a few ticks so all 20 craters flush into Box3D heightfields
for (int t = 0; t < 8; t++)
{
session.Step();
}
int viewCountBeforeRepair = session.World.View.Count;
session.RepairArenaScars();
// Zero-step repair must NOT burst-allocate 20+ new Box3D heightfields in the same step
Assert.Equal(viewCountBeforeRepair, session.World.View.Count);
// Step across ticks so incremental FlushDirtyHeightfields(maxTilesPerTick: 4) completes cleanly
for (int t = 0; t < 20; t++)
{
session.Step();
Assert.True(session.World.View.Count < ArenaSession.WorldBodyCapacity - 256,
$"Expected View.Count ({session.World.View.Count}) well below WorldBodyCapacity ({ArenaSession.WorldBodyCapacity}) at tick {t}");
}
foreach (var (wx, wz, baseH) in spots)
{
Assert.Equal(baseH, terrain.SampleHeight(wx, wz), precision: 3);
}
}
[Fact]
public void ServerMatchHost_SionDesertSion_PreservesSionScarsAndDoesNotClobberExplicitScarFile()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-mapswitch-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
string explicitSionPath = Path.Combine(tempDir, "sion_scars_explicit.cultcache");
try
{
const float craterX = -120f;
const float craterZ = 180f;
float sionBaseH;
float sionScarredH;
using (var host = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: explicitSionPath, persistScars: true))
{
sionBaseH = host.Session.State.Terrain.SampleHeight(craterX, craterZ);
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
sionScarredH = host.Session.State.Terrain.SampleHeight(craterX, craterZ);
Assert.True(sionScarredH < sionBaseH - 1.2f);
// Switch Sion -> Desert: Desert must NOT inherit Sion craters, nor overwrite explicitSionPath
float desertBaseH;
host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false);
Assert.Empty(host.Session.State.ScarLedger.Terrain);
desertBaseH = host.Session.State.Terrain.SampleHeight(0f, 0f);
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = 0f,
Z = 0f,
Radius = 4.5f,
Depth = 1.4f
});
float desertScarredH = host.Session.State.Terrain.SampleHeight(0f, 0f);
Assert.True(desertScarredH < desertBaseH - 0.8f);
// Switch Desert -> Sion: Sion craters must be restored cleanly!
host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false);
Assert.Equal(sionScarredH, host.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3);
// Verify explicitSionPath on disk still holds Sion's AssetFingerprint & crater (never clobbered by Desert)
var diskSnap = ArenaScarLedgerStore.Load(explicitSionPath, host.Session.State.SionMap!.AssetFingerprint);
Assert.Single(diskSnap.Terrain);
Assert.Equal(craterX, diskSnap.Terrain[0].X);
Assert.Equal(craterZ, diskSnap.Terrain[0].Z);
}
// Also verify LocalArenaSession & ListenHostArenaSession carry scars across rounds and Sion -> Desert -> Sion
using (var local = new LocalArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, skipInitialDrop: true))
{
local.Inner.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
local.RequestNewMatch(43, ArenaMapKind.Sion);
Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
local.RequestNewMatch(42, ArenaMapKind.Desert);
Assert.Empty(local.ViewState.ScarLedger.Terrain);
local.RequestNewMatch(44, ArenaMapKind.Sion);
Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
local.RepairArenaScars();
local.RequestNewMatch(45, ArenaMapKind.Sion);
Assert.Equal(sionBaseH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
}
using (var listen = new ListenHostArenaSession(IPAddress.Loopback, 0, seed: 42, mapKind: ArenaMapKind.Sion))
{
listen.Host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
listen.RequestNewMatch(43, ArenaMapKind.Desert);
Assert.Empty(listen.ViewState.ScarLedger.Terrain);
listen.RequestNewMatch(44, ArenaMapKind.Sion);
Assert.Equal(sionScarredH, listen.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
}
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
} }
} }

View file

@ -2260,7 +2260,7 @@ def main() -> None:
print( print(
f"[Sion Baker] Summary: {len(manifest_entries)} buildings across {len(non_empty_tiles)} tiles | " f"[Sion Baker] Summary: {len(manifest_entries)} buildings across {len(non_empty_tiles)} tiles | "
f"LOD1+LOD2 GLBs = {combined_glb_bytes/1e6:.2f} MB (< 28 MB limit) | " f"LOD1+LOD2 GLBs = {combined_glb_bytes/1e6:.2f} MB (< 28 MB limit) | "
f"Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< 40 MB limit)" f"Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< 85 MB limit)"
) )
if combined_glb_bytes >= MAX_TILES_GLB_BYTES: if combined_glb_bytes >= MAX_TILES_GLB_BYTES:
raise RuntimeError(f"Combined tile GLB budget exceeded: {combined_glb_bytes} bytes >= {MAX_TILES_GLB_BYTES}") raise RuntimeError(f"Combined tile GLB budget exceeded: {combined_glb_bytes} bytes >= {MAX_TILES_GLB_BYTES}")