Cut 13d fixes: trample threshold, tile repair, AssetHash, impostor wind & LOD perf

This commit is contained in:
Meta Vens 2026-12-06 04:17:58 +01:00
commit 5e7bff860b
6 changed files with 304 additions and 83 deletions

View file

@ -14,12 +14,15 @@ namespace RustToDust.Client;
/// </summary> /// </summary>
public partial class FoliageRenderer : Node3D public partial class FoliageRenderer : Node3D
{ {
public const float Lod0MaxDistanceM = 85f; public const float Lod0MaxDistanceM = 38f;
public const float Lod1MaxDistanceM = 150f; public const float Lod1MaxDistanceM = 95f;
public const float Lod2MaxDistanceM = 550f; public const float Lod2MaxDistanceM = 260f;
public const float ImpostorMaxDistanceM = 1850f; public const float ImpostorMaxDistanceM = 1500f;
public const float StumpMaxDistanceM = 450f; public const float StumpMaxDistanceM = 260f;
private const float RebuildMoveThresholdSq = 10f * 10f; private const float RebuildMoveThresholdSq = 8.0f * 8.0f;
private const float RebuildTurnCosThreshold = 0.866f; // ~30 degrees
private const float FrustumCullMinDistSq = 48.0f * 48.0f;
private const float FrustumRearConeCosSq = 0.35f * 0.35f; // cull rear ~139 deg cone behind camera
private sealed class TreeArchetype private sealed class TreeArchetype
{ {
@ -38,11 +41,12 @@ public partial class FoliageRenderer : Node3D
public QuadMesh ImpostorQuad = null!; public QuadMesh ImpostorQuad = null!;
public BucketState BucketLod0 = null!; public BucketState BucketLod0 = null!;
public BucketState BucketLod1 = null!; public BucketState? BucketLod1;
public BucketState BucketLod2 = null!; public BucketState? BucketLod2;
public BucketState BucketImpostor = null!; public BucketState? BucketImpostor;
public BucketState BucketStump = null!; public BucketState? BucketStump;
public BucketState BucketCharred = null!; public BucketState? BucketCharred;
public int CanonicalArchIdx;
} }
private sealed class BucketState private sealed class BucketState
@ -71,6 +75,7 @@ public partial class FoliageRenderer : Node3D
private PrecomputedTree[] _precomputed = Array.Empty<PrecomputedTree>(); private PrecomputedTree[] _precomputed = Array.Empty<PrecomputedTree>();
private int _lastRenderVersion = -1; private int _lastRenderVersion = -1;
private Vector3 _lastCamPos = new(float.NaN, float.NaN, float.NaN); private Vector3 _lastCamPos = new(float.NaN, float.NaN, float.NaN);
private Vector2 _lastCamFwdXz = new(0f, 1f);
private bool _assetsLoaded; private bool _assetsLoaded;
private bool _assetsLoadAttempted; private bool _assetsLoadAttempted;
@ -99,6 +104,7 @@ public partial class FoliageRenderer : Node3D
{ {
_lastRenderVersion = -1; _lastRenderVersion = -1;
_lastCamPos = new Vector3(float.NaN, float.NaN, float.NaN); _lastCamPos = new Vector3(float.NaN, float.NaN, float.NaN);
_lastCamFwdXz = new Vector2(0f, 1f);
} }
public bool VerifyAllLodsHaveVertexColor(out string error) public bool VerifyAllLodsHaveVertexColor(out string error)
@ -181,15 +187,35 @@ public partial class FoliageRenderer : Node3D
} }
int curVer = destruction?.RenderVersion ?? 0; int curVer = destruction?.RenderVersion ?? 0;
Vector2 camFwdXz = new(0f, 1f);
bool hasCamDir = false;
var cam = GetViewport()?.GetCamera3D();
if (cam is not null)
{
Vector3 fwd = -cam.GlobalTransform.Basis.Z;
float lenSq = fwd.X * fwd.X + fwd.Z * fwd.Z;
if (lenSq > 1e-4f)
{
float inv = 1f / MathF.Sqrt(lenSq);
camFwdXz = new Vector2(fwd.X * inv, fwd.Z * inv);
hasCamDir = true;
}
}
bool movedFar = !_lastCamPos.IsFinite() || _lastCamPos.DistanceSquaredTo(camPos) >= RebuildMoveThresholdSq; bool movedFar = !_lastCamPos.IsFinite() || _lastCamPos.DistanceSquaredTo(camPos) >= RebuildMoveThresholdSq;
if (!movedFar && curVer == _lastRenderVersion) bool turnedFar = hasCamDir && (_lastCamFwdXz.X * camFwdXz.X + _lastCamFwdXz.Y * camFwdXz.Y) < RebuildTurnCosThreshold;
if (!movedFar && !turnedFar && curVer == _lastRenderVersion)
{ {
return; return;
} }
_lastCamPos = camPos; _lastCamPos = camPos;
if (hasCamDir)
{
_lastCamFwdXz = camFwdXz;
}
_lastRenderVersion = curVer; _lastRenderVersion = curVer;
RebuildBuckets(destruction, camPos); RebuildBuckets(destruction, camPos, hasCamDir ? camFwdXz : null);
} }
private void EnsureAssetsLoaded(string sionDir) private void EnsureAssetsLoaded(string sionDir)
@ -290,12 +316,15 @@ public partial class FoliageRenderer : Node3D
ImpostorQuad = impQuad ImpostorQuad = impQuad
}; };
arch.BucketLod0 = CreateBucket($"{slug}_LOD0", arch.Lod0, castShadows: true); arch.BucketLod0 = CreateBucket($"{slug}_LOD0", arch.Lod0, castShadows: true, visibilityEndM: Lod0MaxDistanceM + 8f);
arch.BucketLod1 = CreateBucket($"{slug}_LOD1", arch.Lod1, castShadows: false); if (variant == 0)
arch.BucketLod2 = CreateBucket($"{slug}_LOD2", arch.Lod2, castShadows: false); {
arch.BucketImpostor = CreateBucket($"{slug}_Impostor", arch.ImpostorQuad, castShadows: false); arch.BucketLod1 = CreateBucket($"{slug}_LOD1", arch.Lod1, castShadows: false, visibilityEndM: Lod1MaxDistanceM + 10f);
arch.BucketStump = CreateBucket($"{slug}_Stump", arch.SnappedStump, castShadows: false); arch.BucketLod2 = CreateBucket($"{slug}_LOD2", arch.Lod2, castShadows: false, visibilityEndM: Lod2MaxDistanceM + 12f);
arch.BucketCharred = CreateBucket($"{slug}_Charred", arch.CharredSkeleton, castShadows: true); arch.BucketImpostor = CreateBucket($"{slug}_Impostor", arch.ImpostorQuad, castShadows: false, visibilityEndM: ImpostorMaxDistanceM + 20f);
arch.BucketStump = CreateBucket($"{slug}_Stump", arch.SnappedStump, castShadows: false, visibilityEndM: StumpMaxDistanceM + 10f);
arch.BucketCharred = CreateBucket($"{slug}_Charred", arch.CharredSkeleton, castShadows: true, visibilityEndM: 120f);
}
int idx = _archetypes.Count; int idx = _archetypes.Count;
_archetypes.Add(arch); _archetypes.Add(arch);
@ -305,10 +334,17 @@ public partial class FoliageRenderer : Node3D
} }
} }
for (int a = 0; a < _archetypes.Count; a++)
{
var arch = _archetypes[a];
int canon = _archetypeLookup[Math.Clamp(arch.SpeciesId, 0, 9), 0];
arch.CanonicalArchIdx = canon >= 0 ? canon : a;
}
_assetsLoaded = _archetypes.Count > 0; _assetsLoaded = _archetypes.Count > 0;
} }
private BucketState CreateBucket(string name, Mesh mesh, bool castShadows) private BucketState CreateBucket(string name, Mesh mesh, bool castShadows, float visibilityEndM)
{ {
var mm = new MultiMesh var mm = new MultiMesh
{ {
@ -326,6 +362,8 @@ public partial class FoliageRenderer : Node3D
CastShadow = castShadows CastShadow = castShadows
? GeometryInstance3D.ShadowCastingSetting.On ? GeometryInstance3D.ShadowCastingSetting.On
: GeometryInstance3D.ShadowCastingSetting.Off, : GeometryInstance3D.ShadowCastingSetting.Off,
VisibilityRangeEnd = visibilityEndM,
VisibilityRangeFadeMode = GeometryInstance3D.VisibilityRangeFadeModeEnum.Disabled,
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)), CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false Visible = false
@ -374,17 +412,17 @@ public partial class FoliageRenderer : Node3D
Invalidate(); Invalidate();
} }
private void RebuildBuckets(SionTreeDestructionState? destruction, Vector3 camPos) private void RebuildBuckets(SionTreeDestructionState? destruction, Vector3 camPos, Vector2? camFwdXz)
{ {
for (int a = 0; a < _archetypes.Count; a++) for (int a = 0; a < _archetypes.Count; a++)
{ {
var arch = _archetypes[a]; var arch = _archetypes[a];
arch.BucketLod0.Indices.Clear(); arch.BucketLod0.Indices.Clear();
arch.BucketLod1.Indices.Clear(); arch.BucketLod1?.Indices.Clear();
arch.BucketLod2.Indices.Clear(); arch.BucketLod2?.Indices.Clear();
arch.BucketImpostor.Indices.Clear(); arch.BucketImpostor?.Indices.Clear();
arch.BucketStump.Indices.Clear(); arch.BucketStump?.Indices.Clear();
arch.BucketCharred.Indices.Clear(); arch.BucketCharred?.Indices.Clear();
} }
const float lod0Sq = Lod0MaxDistanceM * Lod0MaxDistanceM; const float lod0Sq = Lod0MaxDistanceM * Lod0MaxDistanceM;
@ -392,6 +430,8 @@ public partial class FoliageRenderer : Node3D
const float lod2Sq = Lod2MaxDistanceM * Lod2MaxDistanceM; const float lod2Sq = Lod2MaxDistanceM * Lod2MaxDistanceM;
const float impSq = ImpostorMaxDistanceM * ImpostorMaxDistanceM; const float impSq = ImpostorMaxDistanceM * ImpostorMaxDistanceM;
const float stumpSq = StumpMaxDistanceM * StumpMaxDistanceM; const float stumpSq = StumpMaxDistanceM * StumpMaxDistanceM;
bool cullCone = camFwdXz.HasValue;
Vector2 fwd = camFwdXz ?? default;
for (int i = 0; i < _precomputed.Length; i++) for (int i = 0; i < _precomputed.Length; i++)
{ {
@ -403,28 +443,37 @@ public partial class FoliageRenderer : Node3D
{ {
continue; continue;
} }
if (cullCone && dSq > FrustumCullMinDistSq)
{
float dot = dx * fwd.X + dz * fwd.Y;
if (dot < 0f && dot * dot > FrustumRearConeCosSq * dSq)
{
continue;
}
}
SionTreeState st = destruction is not null SionTreeState st = destruction is not null
? destruction.GetState((ushort)i) ? destruction.GetState((ushort)i)
: SionTreeState.Intact; : SionTreeState.Intact;
var arch = _archetypes[pt.ArchetypeIdx]; var arch = _archetypes[pt.ArchetypeIdx];
var canonArch = _archetypes[arch.CanonicalArchIdx];
if (st == SionTreeState.Snapped) if (st == SionTreeState.Snapped)
{ {
if (dSq <= stumpSq) if (dSq <= stumpSq && canonArch.BucketStump is not null)
{ {
arch.BucketStump.Indices.Add(i); canonArch.BucketStump.Indices.Add(i);
} }
} }
else if (st == SionTreeState.Charred) else if (st == SionTreeState.Charred)
{ {
if (dSq <= lod2Sq) if (dSq <= lod2Sq && canonArch.BucketCharred is not null)
{ {
arch.BucketCharred.Indices.Add(i); canonArch.BucketCharred.Indices.Add(i);
} }
else else if (canonArch.BucketImpostor is not null)
{ {
arch.BucketImpostor.Indices.Add(i); canonArch.BucketImpostor.Indices.Add(i);
} }
} }
else else
@ -433,17 +482,17 @@ public partial class FoliageRenderer : Node3D
{ {
arch.BucketLod0.Indices.Add(i); arch.BucketLod0.Indices.Add(i);
} }
else if (dSq <= lod1Sq) else if (dSq <= lod1Sq && canonArch.BucketLod1 is not null)
{ {
arch.BucketLod1.Indices.Add(i); canonArch.BucketLod1.Indices.Add(i);
} }
else if (dSq <= lod2Sq) else if (dSq <= lod2Sq && canonArch.BucketLod2 is not null)
{ {
arch.BucketLod2.Indices.Add(i); canonArch.BucketLod2.Indices.Add(i);
} }
else else if (canonArch.BucketImpostor is not null)
{ {
arch.BucketImpostor.Indices.Add(i); canonArch.BucketImpostor.Indices.Add(i);
} }
} }
} }
@ -453,11 +502,11 @@ public partial class FoliageRenderer : Node3D
{ {
var arch = _archetypes[a]; var arch = _archetypes[a];
c0 += CommitBucket(arch.BucketLod0, destruction, forceCharred: false); c0 += CommitBucket(arch.BucketLod0, destruction, forceCharred: false);
c1 += CommitBucket(arch.BucketLod1, destruction, forceCharred: false); if (arch.BucketLod1 is not null) c1 += CommitBucket(arch.BucketLod1, destruction, forceCharred: false);
c2 += CommitBucket(arch.BucketLod2, destruction, forceCharred: false); if (arch.BucketLod2 is not null) c2 += CommitBucket(arch.BucketLod2, destruction, forceCharred: false);
cImp += CommitBucket(arch.BucketImpostor, destruction, forceCharred: false); if (arch.BucketImpostor is not null) cImp += CommitBucket(arch.BucketImpostor, destruction, forceCharred: false);
cStump += CommitBucket(arch.BucketStump, destruction, forceCharred: false); if (arch.BucketStump is not null) cStump += CommitBucket(arch.BucketStump, destruction, forceCharred: false);
cChar += CommitBucket(arch.BucketCharred, destruction, forceCharred: true); if (arch.BucketCharred is not null) cChar += CommitBucket(arch.BucketCharred, destruction, forceCharred: true);
} }
VisibleLod0Count = c0; VisibleLod0Count = c0;
@ -486,12 +535,23 @@ public partial class FoliageRenderer : Node3D
bucket.MultiMesh.VisibleInstanceCount = count; bucket.MultiMesh.VisibleInstanceCount = count;
bucket.Instance.Visible = true; bucket.Instance.Visible = true;
float minX = float.PositiveInfinity, minY = float.PositiveInfinity, minZ = float.PositiveInfinity;
float maxX = float.NegativeInfinity, maxY = float.NegativeInfinity, maxZ = float.NegativeInfinity;
for (int k = 0; k < count; k++) for (int k = 0; k < count; k++)
{ {
int treeIdx = bucket.Indices[k]; int treeIdx = bucket.Indices[k];
ref readonly var pt = ref _precomputed[treeIdx]; ref readonly var pt = ref _precomputed[treeIdx];
bucket.MultiMesh.SetInstanceTransform(k, pt.WorldXform); bucket.MultiMesh.SetInstanceTransform(k, pt.WorldXform);
Vector3 p = pt.Position;
if (p.X < minX) minX = p.X;
if (p.Y < minY) minY = p.Y;
if (p.Z < minZ) minZ = p.Z;
if (p.X > maxX) maxX = p.X;
if (p.Y > maxY) maxY = p.Y;
if (p.Z > maxZ) maxZ = p.Z;
float isChar = forceCharred || (destruction is not null && destruction.GetState((ushort)treeIdx) == SionTreeState.Charred) float isChar = forceCharred || (destruction is not null && destruction.GetState((ushort)treeIdx) == SionTreeState.Charred)
? 1f ? 1f
: 0f; : 0f;
@ -500,6 +560,12 @@ public partial class FoliageRenderer : Node3D
bucket.MultiMesh.SetInstanceCustomData(k, c); bucket.MultiMesh.SetInstanceCustomData(k, c);
} }
var tightAabb = new Aabb(
new Vector3(minX - 14f, minY - 2f, minZ - 14f),
new Vector3((maxX - minX) + 28f, (maxY - minY) + 42f, (maxZ - minZ) + 28f));
bucket.MultiMesh.CustomAabb = tightAabb;
bucket.Instance.CustomAabb = tightAabb;
return count; return count;
} }

View file

@ -90,11 +90,17 @@ void vertex() {
float phase = INSTANCE_CUSTOM.g * 6.2831853 + dot(world_pos.xz, vec2(0.11, 0.17)); float phase = INSTANCE_CUSTOM.g * 6.2831853 + dot(world_pos.xz, vec2(0.11, 0.17));
float sway = sin(TIME * 1.6 + phase) * 0.22 * top_w * top_w; float sway = sin(TIME * 1.6 + phase) * 0.22 * top_w * top_w;
vec3 flow_uv = (world_pos - rtd_flow_origin) * rtd_flow_inv_extent; vec3 flow_uv = (world_pos - rtd_flow_origin) * rtd_flow_inv_extent;
if (all(greaterThanEqual(flow_uv, vec3(0.0))) && all(lessThanEqual(flow_uv, vec3(1.0)))) { vec3 edge_fade = smoothstep(vec3(0.0), vec3(0.10), flow_uv) *
vec4 fs = textureLod(rtd_flow_field, flow_uv, 0.0); smoothstep(vec3(1.0), vec3(0.90), flow_uv);
offset += fs.rgb * (0.04 * top_w); float in_flow = edge_fade.x * edge_fade.y * edge_fade.z;
vec3 local_flow = vec3(0.0);
if (in_flow > 0.001) {
vec4 fs = textureLod(rtd_flow_field, clamp(flow_uv, vec3(0.0), vec3(1.0)), 0.0);
vec3 flow_local = (inverse(MODEL_MATRIX) * vec4(fs.rgb, 0.0)).xyz;
local_flow = flow_local * ((0.04 + fs.a * 0.10) * in_flow * top_w);
} }
offset += normalize(ambient_wind_dir * mat3(MODEL_MATRIX)) * sway; vec3 ambient_local = normalize((inverse(MODEL_MATRIX) * vec4(ambient_wind_dir, 0.0)).xyz);
offset += ambient_local * (sway * mix(1.0, 0.5, in_flow)) + local_flow;
vec3 vertex_to_camera = pivot_to_camera - offset; vec3 vertex_to_camera = pivot_to_camera - offset;
uv_a = frame_uv(direction_a, pivot_to_camera, vertex_to_camera); uv_a = frame_uv(direction_a, pivot_to_camera, vertex_to_camera);

View file

@ -107,12 +107,15 @@ namespace RustToDust.Core
_baseDem = baseDem; _baseDem = baseDem;
BaseDemMinY = baseDemMinY; BaseDemMinY = baseDemMinY;
BaseDemScale = baseDemScale; BaseDemScale = baseDemScale;
AssetFingerprint = !string.IsNullOrWhiteSpace(metadata.DemAssetHash)
? $"sion:{metadata.DemAssetHash}"
: $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}";
_buildings = buildings; _buildings = buildings;
CollisionMeshes = collisionMeshes; CollisionMeshes = collisionMeshes;
Trees = trees ?? SionTreeCatalog.Empty; Trees = trees ?? SionTreeCatalog.Empty;
string baseFingerprint = !string.IsNullOrWhiteSpace(metadata.DemAssetHash)
? $"sion:{metadata.DemAssetHash}"
: $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}";
AssetFingerprint = !string.IsNullOrEmpty(Trees.AssetHash)
? $"{baseFingerprint}:trees:{Trees.AssetHash}"
: baseFingerprint;
_halfExtent = metadata.SizeMeters * 0.5f; _halfExtent = metadata.SizeMeters * 0.5f;
_cellSize = metadata.SizeMeters / SpatialGridRes; _cellSize = metadata.SizeMeters / SpatialGridRes;

View file

@ -3,6 +3,7 @@ using System.Buffers.Binary;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Numerics; using System.Numerics;
using System.Security.Cryptography;
namespace RustToDust.Core namespace RustToDust.Core
{ {
@ -65,11 +66,12 @@ namespace RustToDust.Core
private readonly SionTreePlacement[] _trees; private readonly SionTreePlacement[] _trees;
private readonly int[][] _tileTreeIndices; private readonly int[][] _tileTreeIndices;
public static readonly SionTreeCatalog Empty = new(Array.Empty<SionTreePlacement>()); public static readonly SionTreeCatalog Empty = new(Array.Empty<SionTreePlacement>(), string.Empty);
public SionTreeCatalog(SionTreePlacement[] trees) public SionTreeCatalog(SionTreePlacement[] trees, string assetHash = "")
{ {
_trees = trees ?? throw new ArgumentNullException(nameof(trees)); _trees = trees ?? throw new ArgumentNullException(nameof(trees));
AssetHash = assetHash ?? string.Empty;
var buckets = new List<int>[TileCount]; var buckets = new List<int>[TileCount];
for (int i = 0; i < TileCount; i++) for (int i = 0; i < TileCount; i++)
{ {
@ -102,6 +104,7 @@ namespace RustToDust.Core
} }
public int Count => _trees.Length; public int Count => _trees.Length;
public string AssetHash { get; }
public IReadOnlyList<SionTreePlacement> Trees => _trees; public IReadOnlyList<SionTreePlacement> Trees => _trees;
public ReadOnlySpan<SionTreePlacement> AsSpan() => _trees; public ReadOnlySpan<SionTreePlacement> AsSpan() => _trees;
@ -165,7 +168,8 @@ namespace RustToDust.Core
offset += RecordBytes; offset += RecordBytes;
} }
return new SionTreeCatalog(trees); string assetHash = Convert.ToHexString(SHA256.HashData(raw)).Substring(0, 16).ToLowerInvariant();
return new SionTreeCatalog(trees, assetHash);
} }
} }
@ -176,11 +180,12 @@ namespace RustToDust.Core
{ {
public const float MinColliderTrunkRadiusM = 0.20f; public const float MinColliderTrunkRadiusM = 0.20f;
public const float WalkerTrampleMaxTrunkRadiusM = 0.30f; public const float WalkerTrampleMaxTrunkRadiusM = 0.30f;
public const float HeavyWalkerMinMassKg = 30_000f; public const float HeavyWalkerMinMassKg = 3_200f;
private readonly SionTreeCatalog _catalog; private readonly SionTreeCatalog _catalog;
private readonly byte[] _packedStates; private readonly byte[] _packedStates;
private readonly int[] _tileColVersions = new int[SionTreeCatalog.TileCount]; private readonly int[] _tileColVersions = new int[SionTreeCatalog.TileCount];
private readonly Dictionary<ushort, float> _treeDamage = new();
public SionTreeDestructionState(SionTreeCatalog catalog) public SionTreeDestructionState(SionTreeCatalog catalog)
{ {
@ -260,6 +265,7 @@ namespace RustToDust.Core
} }
} }
_treeDamage.Clear();
if (anyChanged) if (anyChanged)
{ {
Array.Clear(_packedStates); Array.Clear(_packedStates);
@ -331,18 +337,34 @@ namespace RustToDust.Core
} }
float dist = MathF.Sqrt(distSq); float dist = MathF.Sqrt(distSq);
float atten = MathF.Max(0f, 1f - dist / effectiveRadius); float shellDist = MathF.Max(0f, dist - t.TrunkRadiusM);
float atten = MathF.Max(0f, 1f - shellDist / effectiveRadius);
float impulse = blastDamage * atten; float impulse = blastDamage * atten;
float snapThreshold = 45f + t.TrunkRadiusM * 220f; if (impulse <= 0f && blastDamage < 25f)
{
continue;
}
float snapThreshold = 35f + t.TrunkRadiusM * 180f;
float totalDmg = _treeDamage.TryGetValue(t.TreeId, out float prevDmg)
? prevDmg + impulse
: impulse;
SionTreeState targetState = cur; SionTreeState targetState = cur;
if ((dist <= snapCoreRadius && blastDamage >= 65f) || impulse >= snapThreshold) if ((dist <= snapCoreRadius && blastDamage >= 65f) || totalDmg >= snapThreshold)
{ {
targetState = SionTreeState.Snapped; targetState = SionTreeState.Snapped;
_treeDamage.Remove(t.TreeId);
} }
else if (cur == SionTreeState.Intact && blastDamage >= 25f) else
{ {
targetState = SionTreeState.Charred; if (impulse > 0f)
{
_treeDamage[t.TreeId] = totalDmg;
}
if (cur == SionTreeState.Intact && blastDamage >= 25f)
{
targetState = SionTreeState.Charred;
}
} }
if (targetState != cur && SetState(t.TreeId, targetState)) if (targetState != cur && SetState(t.TreeId, targetState))

View file

@ -21,6 +21,7 @@ namespace RustToDust.Ymir
private readonly Box3DSoaBodyHandle[] _treeHandles = new Box3DSoaBodyHandle[MaxTiles]; private readonly Box3DSoaBodyHandle[] _treeHandles = new Box3DSoaBodyHandle[MaxTiles];
private readonly bool[] _treeResidentFlags = new bool[MaxTiles]; private readonly bool[] _treeResidentFlags = new bool[MaxTiles];
private readonly bool[] _treeTileActivated = new bool[MaxTiles];
private readonly int[] _syncedTreeVersions = new int[MaxTiles]; private readonly int[] _syncedTreeVersions = new int[MaxTiles];
private readonly List<Vector3> _scratchTreeVerts = new(512); private readonly List<Vector3> _scratchTreeVerts = new(512);
private readonly List<int> _scratchTreeIndices = new(1536); private readonly List<int> _scratchTreeIndices = new(1536);
@ -73,6 +74,7 @@ namespace RustToDust.Ymir
Array.Clear(_treeHandles); Array.Clear(_treeHandles);
Array.Clear(_treeResidentFlags); Array.Clear(_treeResidentFlags);
Array.Clear(_treeTileActivated);
Array.Clear(_syncedTreeVersions); Array.Clear(_syncedTreeVersions);
ResidentTreeTileCount = 0; ResidentTreeTileCount = 0;
} }
@ -172,7 +174,7 @@ namespace RustToDust.Ymir
int idx = tz * SionTreeCatalog.TileGrid + tx; int idx = tz * SionTreeCatalog.TileGrid + tx;
int curVer = trees.TileColVersions[idx]; int curVer = trees.TileColVersions[idx];
if (_treeResidentFlags[idx] && _syncedTreeVersions[idx] == curVer) if (_treeTileActivated[idx] && _syncedTreeVersions[idx] == curVer)
{ {
return false; return false;
} }
@ -203,6 +205,7 @@ namespace RustToDust.Ymir
ResidentTreeTileCount++; ResidentTreeTileCount++;
} }
_treeTileActivated[idx] = true;
_syncedTreeVersions[idx] = curVer; _syncedTreeVersions[idx] = curVer;
return true; return true;
} }
@ -226,13 +229,17 @@ namespace RustToDust.Ymir
{ {
int idx = tz * grid + tx; int idx = tz * grid + tx;
bool keep = needed[idx] || (!immediate.IsEmpty && immediate[idx]); bool keep = needed[idx] || (!immediate.IsEmpty && immediate[idx]);
if (_treeResidentFlags[idx] && !keep) if (_treeTileActivated[idx] && !keep)
{ {
world.RemoveBody(_treeHandles[idx]); if (_treeResidentFlags[idx])
_treeHandles[idx] = default; {
_treeResidentFlags[idx] = false; world.RemoveBody(_treeHandles[idx]);
_treeHandles[idx] = default;
_treeResidentFlags[idx] = false;
ResidentTreeTileCount--;
}
_treeTileActivated[idx] = false;
_syncedTreeVersions[idx] = 0; _syncedTreeVersions[idx] = 0;
ResidentTreeTileCount--;
} }
} }
} }
@ -244,7 +251,7 @@ namespace RustToDust.Ymir
for (int tx = 0; tx < grid; tx++) for (int tx = 0; tx < grid; tx++)
{ {
int idx = tz * grid + tx; int idx = tz * grid + tx;
if (immediate[idx] && !_treeResidentFlags[idx]) if (immediate[idx] && !_treeTileActivated[idx])
{ {
EnsureTreeTileResident(world, trees, tx, tz); EnsureTreeTileResident(world, trees, tx, tz);
} }
@ -262,7 +269,7 @@ namespace RustToDust.Ymir
return; return;
} }
int idx = tz * grid + tx; int idx = tz * grid + tx;
if (needed[idx] && !_treeResidentFlags[idx]) if (needed[idx] && !_treeTileActivated[idx])
{ {
if (EnsureTreeTileResident(world, trees, tx, tz)) if (EnsureTreeTileResident(world, trees, tx, tz))
{ {
@ -289,7 +296,7 @@ namespace RustToDust.Ymir
int idx = tz * grid + tx; int idx = tz * grid + tx;
if (trees.TileColVersions[idx] != _syncedTreeVersions[idx]) if (trees.TileColVersions[idx] != _syncedTreeVersions[idx])
{ {
if (!_treeResidentFlags[idx]) if (!_treeTileActivated[idx])
{ {
_syncedTreeVersions[idx] = trees.TileColVersions[idx]; _syncedTreeVersions[idx] = trees.TileColVersions[idx];
continue; continue;
@ -332,13 +339,17 @@ namespace RustToDust.Ymir
for (int tx = 0; tx < grid; tx++) for (int tx = 0; tx < grid; tx++)
{ {
int idx = tz * grid + tx; int idx = tz * grid + tx;
if (_treeResidentFlags[idx] && (tx < minTx || tx > maxTx || tz < minTz || tz > maxTz)) if (_treeTileActivated[idx] && (tx < minTx || tx > maxTx || tz < minTz || tz > maxTz))
{ {
world.RemoveBody(_treeHandles[idx]); if (_treeResidentFlags[idx])
_treeHandles[idx] = default; {
_treeResidentFlags[idx] = false; world.RemoveBody(_treeHandles[idx]);
_treeHandles[idx] = default;
_treeResidentFlags[idx] = false;
ResidentTreeTileCount--;
}
_treeTileActivated[idx] = false;
_syncedTreeVersions[idx] = 0; _syncedTreeVersions[idx] = 0;
ResidentTreeTileCount--;
} }
} }
} }

View file

@ -21,6 +21,8 @@ namespace RustToDust.Tests
var catalog = sion.Trees; var catalog = sion.Trees;
Assert.InRange(catalog.Count, 500, SionTreeCatalog.MaxTrees); Assert.InRange(catalog.Count, 500, SionTreeCatalog.MaxTrees);
Assert.False(string.IsNullOrWhiteSpace(catalog.AssetHash));
Assert.Contains($":trees:{catalog.AssetHash}", sion.AssetFingerprint, StringComparison.Ordinal);
// Check binary disk budget + tree assets directory <= 12.4 MiB // Check binary disk budget + tree assets directory <= 12.4 MiB
string treesBin = Path.Combine(sion.DirectoryPath, "trees_sion.bin"); string treesBin = Path.Combine(sion.DirectoryPath, "trees_sion.bin");
@ -191,20 +193,28 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void SionTreeDestruction_HeavyWalkerTramplesThinTreesButNotThickOrMonumental() public void SionTreeDestruction_HeavyWalkerTramplesThinTreesButNotThickOrMonumental()
{ {
var sion = SionMapLoader.Load(); using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
var trees = new SionTreeDestructionState(sion.Trees); var sion = session.State.SionMap!;
var trees = session.State.SionTrees!;
Assert.True(Catalog.Raptor.MassKg < SionTreeDestructionState.HeavyWalkerMinMassKg,
$"Expected Raptor ({Catalog.Raptor.MassKg}kg) < HeavyWalkerMinMassKg");
Assert.True(Catalog.Bastion.MassKg >= SionTreeDestructionState.HeavyWalkerMinMassKg,
$"Expected Bastion ({Catalog.Bastion.MassKg}kg) >= HeavyWalkerMinMassKg");
SionTreePlacement thin = default; SionTreePlacement thin = default;
SionTreePlacement thick = default; SionTreePlacement thick = default;
bool foundThin = false, foundThick = false; bool foundThin = false, foundThick = false;
foreach (var t in sion.Trees.Trees) foreach (var t in sion.Trees.Trees)
{ {
if (!foundThin && t.TrunkRadiusM >= 0.14f && t.TrunkRadiusM < SionTreeDestructionState.WalkerTrampleMaxTrunkRadiusM) if (!foundThin && t.TrunkRadiusM >= 0.12f && t.TrunkRadiusM < SionTreeDestructionState.WalkerTrampleMaxTrunkRadiusM &&
!sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.0f))
{ {
thin = t; thin = t;
foundThin = true; foundThin = true;
} }
if (!foundThick && t.TrunkRadiusM >= 0.45f) if (!foundThick && t.TrunkRadiusM >= 0.45f &&
!sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.0f))
{ {
thick = t; thick = t;
foundThick = true; foundThick = true;
@ -213,19 +223,122 @@ namespace RustToDust.Tests
} }
Assert.True(foundThin && foundThick); Assert.True(foundThin && foundThick);
// Light < 30t mech does not trample // Light walker (Raptor < HeavyWalkerMinMassKg) placed overlapping thin tree must NOT trample it
trees.ApplyWalkerTrample(thin.X, thin.Z, 2.0f, 20_000f); session.SetContenderPose(0, thin.X, thin.Z, 0f);
session.State.SpawnChassisDrop(thin.X, thin.Z, Catalog.Raptor);
Assert.True(session.TrySwapNearbyChassis(0), "Expected swap to Raptor near thin tree");
session.SetContenderPose(0, thin.X, thin.Z, 0f);
session.Step();
Assert.Equal(SionTreeState.Intact, trees.GetState(thin.TreeId)); Assert.Equal(SionTreeState.Intact, trees.GetState(thin.TreeId));
// Heavy >= 30t walker tramples thin (< 0.30m) tree // Heavy walker (Bastion >= HeavyWalkerMinMassKg) trampling same thin (< 0.30m) tree snaps it cleanly
trees.ApplyWalkerTrample(thin.X, thin.Z, 2.0f, 35_000f); session.State.SpawnChassisDrop(thin.X, thin.Z, Catalog.Bastion);
Assert.True(session.TrySwapNearbyChassis(0), "Expected swap to Bastion near thin tree");
session.SetContenderPose(0, thin.X, thin.Z, 0f);
session.Step();
Assert.Equal(SionTreeState.Snapped, trees.GetState(thin.TreeId)); Assert.Equal(SionTreeState.Snapped, trees.GetState(thin.TreeId));
// Heavy walker does NOT trample thick (>= 0.30m) / monumental trees // Heavy walker overlapping thick (>= 0.30m) tree must NOT trample it
trees.ApplyWalkerTrample(thick.X, thick.Z, 2.0f, 65_000f); session.SetContenderPose(0, thick.X, thick.Z, 0f);
session.Step();
Assert.Equal(SionTreeState.Intact, trees.GetState(thick.TreeId)); Assert.Equal(SionTreeState.Intact, trees.GetState(thick.TreeId));
} }
[Fact]
public void SionTreeDestruction_FlushDirtyTreeTiles_RestoresColliderImmediatelyAfterAllTileTreesSnappedAndRepaired()
{
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!;
var trees = session.State.SionTrees!;
// Find an active-near tile or any tile containing solid (>= 0.20m) trees clear of buildings
SionTreePlacement targetTree = default;
bool found = false;
for (int i = 0; i < sion.Trees.Count; i++)
{
var t = sion.Trees.Trees[i];
if (t.TrunkRadiusM >= SionTreeDestructionState.MinColliderTrunkRadiusM &&
!sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.5f))
{
targetTree = t;
found = true;
break;
}
}
Assert.True(found);
// Place contender 0 in the target tile so SyncNeededTreeTiles keeps it needed across Step(),
// and do NOT manually call EnsureTreeTileResident after repair.
session.SetContenderPose(0, targetTree.X + 8.0f, targetTree.Z + 8.0f, 0f);
session.TileSync.EnsureTreeTileResident(session.World, trees, targetTree.Tx, targetTree.Tz);
ulong expectedStableId = Box3DPhysicsTileSync.TreeTileStableIdBase + (ulong)targetTree.TileIndex;
var rayOrigin = new Vector3(targetTree.X - 4.0f, targetTree.Y + 1.4f, targetTree.Z);
var raySpan = new Vector3(8.0f, 0f, 0f);
Assert.Equal(expectedStableId, session.CastWorldRayClosest(rayOrigin, raySpan).StableId);
// Snap EVERY solid tree in that tile -> removes the Box3D body completely (ResidentTreeTileCount drops)
foreach (int idx in sion.Trees.GetTileTreeIndices(targetTree.Tx, targetTree.Tz))
{
var tileTree = sion.Trees.Trees[idx];
if (tileTree.TrunkRadiusM >= SionTreeDestructionState.MinColliderTrunkRadiusM)
{
trees.ApplyBlast(new Vector3(tileTree.X, tileTree.Y + 0.5f, tileTree.Z), splashRadius: 4f, blastDamage: 300f);
}
}
session.TileSync.FlushDirtyTreeTiles(session.World, trees, maxTilesPerTick: 8);
var afterSnapHit = session.CastWorldRayClosest(rayOrigin, raySpan);
Assert.False(afterSnapHit.Hit && afterSnapHit.StableId == expectedStableId,
"Expected Box3D tree tile body to be removed when all collider trees in tile are snapped");
// RepairArenaScars() + Step() (NO manual EnsureTreeTileResident!) must immediately restore Box3D collider
session.RepairArenaScars();
var immediateHit = session.CastWorldRayClosest(rayOrigin, raySpan);
Assert.True(immediateHit.Hit && immediateHit.StableId == expectedStableId,
$"Expected RepairArenaScars FlushDirtyTreeTiles to restore tree collider {expectedStableId}, got Hit={immediateHit.Hit} StableId={immediateHit.StableId}");
session.Step();
var stepHit = session.CastWorldRayClosest(rayOrigin, raySpan);
Assert.True(stepHit.Hit && stepHit.StableId == expectedStableId,
$"Expected tick-0 Step() to keep restored tree collider {expectedStableId}, got Hit={stepHit.Hit} StableId={stepHit.StableId}");
}
[Fact]
public void SionTreeDestruction_CumulativeBlastDamage_TwoColdStartRecoillessHitsSnapMediumTrunk()
{
var sion = SionMapLoader.Load();
var trees = new SionTreeDestructionState(sion.Trees);
SionTreePlacement med = default;
bool found = false;
foreach (var t in sion.Trees.Trees)
{
if (t.TrunkRadiusM >= 0.32f && t.TrunkRadiusM <= 0.39f)
{
med = t;
found = true;
break;
}
}
Assert.True(found, "Expected a medium ~0.35m trunk tree in Sion catalog");
// Cold-start Recoilless shell: WeaponDamage=85 * ~0.65 cold thermal scale = ~55.25 damage (< 65f one-shot core threshold)
float coldRecoillessDmg = Catalog.Recoilless.WeaponDamage * 0.65f;
var hitPoint = new Vector3(med.X + med.TrunkRadiusM, med.Y + 1.0f, med.Z);
// Hit #1: chars the tree without snapping it immediately
trees.ApplyBlast(hitPoint, splashRadius: 2.5f, blastDamage: coldRecoillessDmg);
Assert.Equal(SionTreeState.Charred, trees.GetState(med.TreeId));
// Hit #2: cumulative damage reaches snapThreshold (~98..105) -> cleanly snaps the trunk
trees.ApplyBlast(hitPoint, splashRadius: 2.5f, blastDamage: coldRecoillessDmg);
Assert.Equal(SionTreeState.Snapped, trees.GetState(med.TreeId));
// Repair clears accumulated damage so another single cold-start hit only chars again
trees.RepairAll();
Assert.Equal(SionTreeState.Intact, trees.GetState(med.TreeId));
trees.ApplyBlast(hitPoint, splashRadius: 2.5f, blastDamage: coldRecoillessDmg);
Assert.Equal(SionTreeState.Charred, trees.GetState(med.TreeId));
}
[Fact] [Fact]
public void CultNet_RemoteClientSyncsTreeScarsInPersistentSnapshotBubbleAndRepair() public void CultNet_RemoteClientSyncsTreeScarsInPersistentSnapshotBubbleAndRepair()
{ {