using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Numerics; using System.Text.Json; using RustToDust.Core; using RustToDust.Net; using RustToDust.Ymir; using Xunit; using Ymir.Box3D; namespace RustToDust.Tests { public sealed class SionTreeTests { [Fact] public void SionTreeCatalog_LoadsWithoutBeechExcludesBuildingsAndMatchesArbresRemarquables() { var sion = SionMapLoader.Load(); var catalog = sion.Trees; 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 string treesBin = Path.Combine(sion.DirectoryPath, "trees_sion.bin"); string treesDir = Path.Combine(sion.DirectoryPath, "trees"); long totalBytes = new FileInfo(treesBin).Length; foreach (var f in Directory.EnumerateFiles(treesDir, "*", SearchOption.AllDirectories)) { totalBytes += new FileInfo(f).Length; } Assert.True(totalBytes <= 13_000_000L, $"Expected Sion tree assets + bin <= 12.4 MiB, got {totalBytes:N0} B"); bool hasSequoia = false; bool hasCedrus = false; bool hasMonumentalPlane = false; // Planta d'en Haut Giant Sequoia: LV95 (2593636.1374, 1120075.402) -> (-513.8626, -25.402) float seqWx = 2593636.1374f - 2594150.0f; float seqWz = 1120050.0f - 1120075.402f; // Pratifori / Cimetiere Lebanon Cedar: LV95 (2593522.9419, 1119968.4164) -> (-627.0581, 81.5836) float cedWx = 2593522.9419f - 2594150.0f; float cedWz = 1120050.0f - 1119968.4164f; // Planta d'en Haut Monumental Avenue (Aesculus/PlatanusMonumental archetype #9): LV95 (2593619.7614, 1120373.0299) float plaWx = 2593619.7614f - 2594150.0f; float plaWz = 1120050.0f - 1120373.0299f; for (int i = 0; i < catalog.Count; i++) { var t = catalog.Trees[i]; Assert.True((byte)t.Species <= (byte)SionTreeSpecies.PlatanusMonumental); string spName = t.Species.ToString(); Assert.DoesNotContain("Fagus", spName, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("Beech", spName, StringComparison.OrdinalIgnoreCase); Assert.False(sion.IsInsideAnyBuildingXz(t.X, t.Z, 0f), $"Tree {t.TreeId} ({t.Species}) placed inside building at ({t.X:F2}, {t.Z:F2})"); Assert.InRange(t.HeightM, 4.0f, 38.0f); Assert.InRange(t.TrunkRadiusM, 0.10f, 1.20f); if (t.Species == SionTreeSpecies.Sequoiadendron && MathF.Sqrt((t.X - seqWx) * (t.X - seqWx) + (t.Z - seqWz) * (t.Z - seqWz)) < 0.25f) { hasSequoia = true; } if (t.Species == SionTreeSpecies.Cedrus && MathF.Sqrt((t.X - cedWx) * (t.X - cedWx) + (t.Z - cedWz) * (t.Z - cedWz)) < 0.25f) { hasCedrus = true; } if (t.Species == SionTreeSpecies.PlatanusMonumental && MathF.Sqrt((t.X - plaWx) * (t.X - plaWx) + (t.Z - plaWz) * (t.Z - plaWz)) < 0.25f) { hasMonumentalPlane = true; } } Assert.True(hasSequoia, "Expected Planta d'en Haut Sequoiadendron at exact Sion coordinates"); Assert.True(hasCedrus, "Expected Lebanon Cedrus at exact Sion coordinates"); Assert.True(hasMonumentalPlane, "Expected En Ville PlatanusMonumental at exact Sion coordinates"); } [Fact] public void SionTreeDestruction_OrdnanceSnapsAndChars_UpdatesBox3DColliderPersistsAndHeals() { string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13d-tree-scar-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(tempDir); string scarPath = Path.Combine(tempDir, "sion_tree_scars.cultcache"); try { ushort targetId = 0; SionTreePlacement targetTree = default; bool foundTarget = false; using (var host = new ServerMatchHost( IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, autoRestartSec: 0, scarFilePath: scarPath, persistScars: true)) { var trees = host.Session.State.SionTrees!; var catalog = trees.Catalog; // Pick an isolated solid tree (TrunkRadiusM >= 0.28m) with no nearby buildings/neighbors on the ray for (int i = 0; i < catalog.Count; i++) { var t = catalog.Trees[i]; if (t.TrunkRadiusM < 0.28f || t.IsMonumental) continue; if (host.Session.State.SionMap!.IsInsideAnyBuildingXz(t.X, t.Z, 12f)) continue; targetTree = t; targetId = t.TreeId; foundTarget = true; break; } Assert.True(foundTarget, "Expected a solid non-monumental tree outside buildings"); host.Session.TileSync.EnsureTreeTileResident(host.Session.World, trees, targetTree.Tx, targetTree.Tz); ulong expectedStableId = Box3DPhysicsTileSync.TreeTileStableIdBase + (ulong)targetTree.TileIndex; // Horizontal ray through the trunk must hit the Box3D tree tile mesh var rayOrigin = new Vector3(targetTree.X - 4.0f, targetTree.Y + 1.4f, targetTree.Z); var raySpan = new Vector3(8.0f, 0f, 0f); var preHit = host.Session.CastWorldRayClosest(rayOrigin, raySpan); Assert.True(preHit.Hit, "Expected horizontal ray to strike solid tree trunk collider"); Assert.Equal(expectedStableId, preHit.StableId); // Artillery blast at trunk base snaps target tree; verify outer char radius on a second tree var hitEvents = new List(); int changed = trees.ApplyBlast(new Vector3(targetTree.X, targetTree.Y + 0.5f, targetTree.Z), splashRadius: 10f, blastDamage: 240f, hitEvents); Assert.True(changed >= 1); Assert.Equal(SionTreeState.Snapped, trees.GetState(targetId)); foreach (var ev in hitEvents) { host.Session.State.ScarLedger.RecordTreeState(ev.TreeId, ev.State); } // Flush dirty tree tiles -> Box3D collider for snapped trunk must be gone host.Session.TileSync.FlushDirtyTreeTiles(host.Session.World, trees, maxTilesPerTick: 4); var postHit = host.Session.CastWorldRayClosest(rayOrigin, raySpan); Assert.False(postHit.Hit && postHit.StableId == expectedStableId && MathF.Abs(postHit.Point.X - targetTree.X) <= targetTree.TrunkRadiusM * 1.5f, "Expected snapped tree trunk collider to be removed from Box3D tile mesh"); // Also test outer thermal char state on a distant intact tree ushort charId = 0; for (int i = 0; i < catalog.Count; i++) { var t = catalog.Trees[i]; if (t.TreeId == targetId || trees.GetState(t.TreeId) != SionTreeState.Intact) continue; if (t.TrunkRadiusM < 0.30f) continue; var evs = new List(); // Blast 8.5m away (outside snapCore, inside charRadius = 1.35 * 9.0) with moderate heat/blast trees.ApplyBlast(new Vector3(t.X + 8.5f, t.Y + 1.0f, t.Z), splashRadius: 9.0f, blastDamage: 60f, evs); if (trees.GetState(t.TreeId) == SionTreeState.Charred) { charId = t.TreeId; host.Session.State.ScarLedger.RecordTreeState(charId, (byte)SionTreeState.Charred); break; } } Assert.NotEqual(0, charId); // ResetMatch must preserve both Snapped and Charred tree scars host.ResetMatch(43, ArenaMapKind.Sion); Assert.Equal(SionTreeState.Snapped, host.Session.State.SionTrees!.GetState(targetId)); Assert.Equal(SionTreeState.Charred, host.Session.State.SionTrees!.GetState(charId)); // RepairArenaScars restores all trees to Intact and restores Box3D trunk collider host.RepairArenaScars(); Assert.Equal(SionTreeState.Intact, host.Session.State.SionTrees!.GetState(targetId)); Assert.Equal(SionTreeState.Intact, host.Session.State.SionTrees!.GetState(charId)); host.Session.TileSync.EnsureTreeTileResident(host.Session.World, host.Session.State.SionTrees, targetTree.Tx, targetTree.Tz); var healedHit = host.Session.CastWorldRayClosest(rayOrigin, raySpan); Assert.True(healedHit.Hit && healedHit.StableId == expectedStableId, "Expected repaired tree trunk collider to be restored in Box3D"); } } finally { if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, recursive: true); } } } [Fact] public void SionTreeDestruction_HeavyWalkerTramplesThinTreesButNotThickOrMonumental() { using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true); 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 thick = default; bool foundThin = false, foundThick = false; foreach (var t in sion.Trees.Trees) { if (!foundThin && t.TrunkRadiusM >= 0.12f && t.TrunkRadiusM < SionTreeDestructionState.WalkerTrampleMaxTrunkRadiusM && !sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.0f)) { thin = t; foundThin = true; } if (!foundThick && t.TrunkRadiusM >= 0.45f && !sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.0f)) { thick = t; foundThick = true; } if (foundThin && foundThick) break; } Assert.True(foundThin && foundThick); // Light walker (Raptor < HeavyWalkerMinMassKg) placed overlapping thin tree must NOT trample it 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)); // Heavy walker (Bastion >= HeavyWalkerMinMassKg) trampling same thin (< 0.30m) tree snaps it cleanly 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)); // Heavy walker overlapping thick (>= 0.30m) tree must NOT trample it session.SetContenderPose(0, thick.X, thick.Z, 0f); session.Step(); 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] public void SionTreeDestruction_SmallArmsCannotFellOrCharMediumOakOrMonumentalSequoia() { var sion = SionMapLoader.Load(); var trees = new SionTreeDestructionState(sion.Trees); SionTreePlacement oak = default; SionTreePlacement sequoia = default; bool foundOak = false, foundSequoia = false; foreach (var t in sion.Trees.Trees) { if (!foundOak && t.Species == SionTreeSpecies.QuercusPubescens && t.TrunkRadiusM >= 0.32f) { oak = t; foundOak = true; } if (!foundSequoia && t.Species == SionTreeSpecies.Sequoiadendron) { sequoia = t; foundSequoia = true; } if (foundOak && foundSequoia) break; } Assert.True(foundOak && foundSequoia); float mgDmg = Catalog.Mg762.WeaponDamage; // 12f (< 25f) var oakHit = new Vector3(oak.X + oak.TrunkRadiusM, oak.Y + 1.0f, oak.Z); var seqHit = new Vector3(sequoia.X + sequoia.TrunkRadiusM, sequoia.Y + 1.0f, sequoia.Z); for (int i = 0; i < 30; i++) { trees.ApplyBlast(oakHit, splashRadius: 2.5f, blastDamage: mgDmg); trees.ApplyBlast(seqHit, splashRadius: 2.5f, blastDamage: mgDmg); } Assert.Equal(SionTreeState.Intact, trees.GetState(oak.TreeId)); Assert.Equal(SionTreeState.Intact, trees.GetState(sequoia.TreeId)); } [Fact] public void CultNet_RemoteClientSyncsTreeScarsInPersistentSnapshotBubbleAndRepair() { using var host = new ServerMatchHost( IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, autoRestartSec: 0, persistScars: false); var hostTrees = host.Session.State.SionTrees!; // Snap a historical tree before client joins var histTree = hostTrees.Catalog.Trees[0]; host.Session.State.ApplyTreeState(histTree.TreeId, SionTreeState.Snapped, recordInLedger: true); using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "TreeTester"); long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); for (int i = 0; i < 120 && !client.IsJoined; i++) { nowMs += 16; host.StepOnce(nowMs); client.BeginRenderFrame(1f / 60f, 0f); System.Threading.Thread.Sleep(5); } Assert.True(client.IsJoined, "Remote client failed to join Sion ServerMatchHost"); Assert.Equal(SionTreeState.Snapped, client.ViewState.SionTrees!.GetState(histTree.TreeId)); // Find a tree near the remote client's local contender (within 576m local geometry bubble) var local = client.LocalContender; SionTreePlacement liveTree = default; bool foundLive = false; foreach (var t in hostTrees.Catalog.Trees) { if (t.TreeId == histTree.TreeId || t.TrunkRadiusM < 0.25f) continue; float dx = t.X - local.X; float dz = t.Z - local.Z; float dist = MathF.Sqrt(dx * dx + dz * dz); if (dist <= 500f) { liveTree = t; foundLive = true; break; } } Assert.True(foundLive, "Expected a solid tree within 500m of local contender"); // Snap it via Ordnance sink on host so TreeStateEvent flows through the 576m bubble ((IOrdnanceTargetSink)host.Session).ApplyTreeImpact( Box3DPhysicsTileSync.TreeTileStableIdBase + (ulong)liveTree.TileIndex, new Vector3(liveTree.X, liveTree.Y + 0.5f, liveTree.Z), splashRadius: 6.0f, damage: 250f); for (int i = 0; i < 60 && client.ViewState.SionTrees!.GetState(liveTree.TreeId) != SionTreeState.Snapped; i++) { nowMs += 16; host.StepOnce(nowMs); client.BeginRenderFrame(1f / 60f, 0f); System.Threading.Thread.Sleep(5); } Assert.Equal(SionTreeState.Snapped, client.ViewState.SionTrees!.GetState(liveTree.TreeId)); // RepairArenaScars propagates to remote client host.RepairArenaScars(); for (int i = 0; i < 60 && client.ViewState.SionTrees!.GetState(liveTree.TreeId) != SionTreeState.Intact; i++) { nowMs += 16; host.StepOnce(nowMs); client.BeginRenderFrame(1f / 60f, 0f); System.Threading.Thread.Sleep(5); } Assert.Equal(SionTreeState.Intact, client.ViewState.SionTrees!.GetState(histTree.TreeId)); Assert.Equal(SionTreeState.Intact, client.ViewState.SionTrees!.GetState(liveTree.TreeId)); } } }