A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix(visual): idempotent RunTeardown before Clear destroys, toggle removal tokens, Init clears stale undo actions
eyalgolan0c282ccd3bce
diff --git a/unity/Assets/Scripts/Map/CameraRig.cs b/unity/Assets/Scripts/Map/CameraRig.csindex e3eb517a7..951e24b7f 100644--- a/unity/Assets/Scripts/Map/CameraRig.cs+++ b/unity/Assets/Scripts/Map/CameraRig.cs@@ -31,6 +31,9 @@ namespace Statecraft.Game.Mappublic void Init(){+ // Undo actions an earlier Init left behind (Init called outside MapScene.Build) run now instead of piling up.+ for (int i = TeardownActions.Count - 1; i >= 0; i--) TeardownActions[i]();+ TeardownActions.Clear();var cam = GetComponent<Camera>(); cam.fieldOfView = Fov; cam.farClipPlane = 1_000_000f; cam.nearClipPlane = 50f;// Beyond the terrain the view shows open sea, not a grey void (playtest 1, item 9). At this pitch the top of the// view still looks down, so the sky never shows and a solid clear in the sea biome colour is the whole fix.diff --git a/unity/Assets/Scripts/Map/MapRuntimeAssets.cs b/unity/Assets/Scripts/Map/MapRuntimeAssets.csindex 7d2a77e34..dc818d21b 100644--- a/unity/Assets/Scripts/Map/MapRuntimeAssets.cs+++ b/unity/Assets/Scripts/Map/MapRuntimeAssets.cs@@ -14,14 +14,29 @@ namespace Statecraft.Game.Mappublic T Own<T>(T o) where T : Object { owned.Add(o); return o; }- /// <summary>Runs <paramref name="action"/> when the map is destroyed (newest first), for state the map changes outside- /// itself: the URP asset's shadow distance, global shader values.</summary>+ /// <summary>Runs <paramref name="action"/> when the map is torn down (newest first), for state the map changes outside+ /// itself: the URP asset's shadow distance, global shader values, its VisualToggles switches+ /// (<c>assets.OnTeardown(VisualToggles.Register(...))</c>).</summary>public void OnTeardown(System.Action action) => teardown.Add(action ?? throw new System.ArgumentNullException(nameof(action)));- void OnDestroy()+ /// <summary>Runs the teardown actions now, newest first, and forgets them, so a second call (or OnDestroy) does+ /// nothing. MapScene.Clear calls it before destroying the map: in play mode Destroy is deferred to the end of the+ /// frame, after a rebuilt map's Init has already saved state, so a late teardown would undo the new map's state+ /// (review I1). One action throwing is logged and does not stop the others (review M2).</summary>+ public void RunTeardown(){- for (int i = teardown.Count - 1; i >= 0; i--) teardown[i]();+ var actions = teardown.ToArray();teardown.Clear();+ for (int i = actions.Length - 1; i >= 0; i--)+ {+ try { actions[i](); }+ catch (System.Exception e) { Debug.LogException(e); }+ }+ }++ void OnDestroy()+ {+ RunTeardown();foreach (var o in owned){if (o == null) continue;diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex dd8f4ff6b..1631b46b0 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -151,11 +151,20 @@ namespace Statecraft.Game.Map/// hierarchy rather than remembered fields keeps Build idempotent after a domain reload (R2). The VolumeProfile is/// owned by the terrain's MapRuntimeAssets, so destroying the terrain destroys it.</summary>void Clear()+ {+ if (Application.isPlaying) Clear(go => { go.transform.SetParent(null); Destroy(go); });+ else Clear(go => DestroyImmediate(go));+ }++ /// <summary>Clear with the destroy step given (test seam for the play-mode path, whose Destroy is deferred): each+ /// child's MapRuntimeAssets teardown runs first, so it has run by the time Clear returns (review I1).</summary>+ internal void Clear(Action<GameObject> destroy){for (int i = transform.childCount - 1; i >= 0; i--){var go = transform.GetChild(i).gameObject;- if (Application.isPlaying) { go.transform.SetParent(null); Destroy(go); } else DestroyImmediate(go);+ foreach (var assets in go.GetComponentsInChildren<MapRuntimeAssets>(true)) assets.RunTeardown();+ destroy(go);}Terrain = null;Hexes = null;diff --git a/unity/Assets/Scripts/Map/VisualToggles.cs b/unity/Assets/Scripts/Map/VisualToggles.csindex bd579bda2..3db1f6d93 100644--- a/unity/Assets/Scripts/Map/VisualToggles.cs+++ b/unity/Assets/Scripts/Map/VisualToggles.cs@@ -7,15 +7,23 @@ namespace Statecraft.Game.Map{/// <summary>One on/off switch per visual feature (shadows, tilt-shift, grade, haze, grid...), registered by the feature/// itself, so the visual profile can price each one and tests can isolate it. Names run in ordinal order; registering- /// a name again replaces its switch (a rebuilt map re-registers).</summary>+ /// a name again replaces its switch (a rebuilt map re-registers).+ /// The one pattern (review I2): the map owns its switches through its teardown,+ /// <c>assets.OnTeardown(VisualToggles.Register("grid", on => ...))</c>. Register returns a removal token that removes+ /// the switch only while it is still the one registered, so an old map's teardown never removes a rebuilt map's switch.</summary>public static class VisualToggles{- static readonly SortedDictionary<string, Action<bool>> Switches = new SortedDictionary<string, Action<bool>>(StringComparer.Ordinal);+ sealed class Entry { public readonly Action<bool> Set; public Entry(Action<bool> set) { Set = set; } }- public static void Register(string name, Action<bool> set)+ static readonly SortedDictionary<string, Entry> Switches = new SortedDictionary<string, Entry>(StringComparer.Ordinal);++ /// <summary>Registers (or replaces) the switch; returns its removal token (safe to call more than once).</summary>+ public static Action Register(string name, Action<bool> set){if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("a toggle needs a name", nameof(name));- Switches[name] = set ?? throw new ArgumentNullException(nameof(set));+ var entry = new Entry(set ?? throw new ArgumentNullException(nameof(set)));+ Switches[name] = entry;+ return () => { if (Switches.TryGetValue(name, out var current) && ReferenceEquals(current, entry)) Switches.Remove(name); };}public static void Unregister(string name) => Switches.Remove(name);@@ -23,11 +31,11 @@ namespace Statecraft.Game.Mappublic static void Set(string name, bool on){- if (!Switches.TryGetValue(name, out var set)) throw new KeyNotFoundException($"no visual toggle named '{name}' (known: {string.Join(", ", Switches.Keys)})");- set(on);+ if (!Switches.TryGetValue(name, out var entry)) throw new KeyNotFoundException($"no visual toggle named '{name}' (known: {string.Join(", ", Switches.Keys)})");+ entry.Set(on);}- public static void SetAll(bool on) { foreach (var set in Switches.Values.ToList()) set(on); }+ public static void SetAll(bool on) { foreach (var entry in Switches.Values.ToList()) entry.Set(on); }public static void Clear() => Switches.Clear();}}diff --git a/unity/Assets/Tests/EditMode/VisualHarnessTests.cs b/unity/Assets/Tests/EditMode/VisualHarnessTests.csindex 039294d74..38e83e2d3 100644--- a/unity/Assets/Tests/EditMode/VisualHarnessTests.cs+++ b/unity/Assets/Tests/EditMode/VisualHarnessTests.cs@@ -4,7 +4,9 @@ using System.Linq;using NUnit.Framework;using Statecraft.Game.Map;using UnityEditor;+using System.Text.RegularExpressions;using UnityEngine;+using UnityEngine.TestTools;/// <summary>The visual track's instruments (plan Task 1): profile lines, flags, toggles, screenshot chunks, poses,/// teardown hand-off, the colour metrics and the GLES3 compile check.</summary>@@ -105,6 +107,89 @@ public class VisualHarnessTestsCollectionAssert.AreEqual(new[] { 2, 1 }, order);}+ /// <summary>Review I1: in play mode Clear destroys the old map with a deferred Destroy, so its teardown must run before+ /// Clear returns (not at the end of the frame, after the new map's Init has saved state); running it again on+ /// OnDestroy does nothing (idempotent).</summary>+ [Test]+ public void ClearRunsTheOldMapsTeardownBeforeDestroyingItAndOnlyOnce()+ {+ var root = new GameObject("map"); var scene = root.AddComponent<MapScene>();+ var child = new GameObject("terrain"); child.transform.SetParent(root.transform);+ var assets = child.AddComponent<MapRuntimeAssets>();+ var log = new List<string>();+ assets.OnTeardown(() => log.Add("teardown"));+ try+ {+ scene.Clear(go => log.Add("destroy " + go.name)); // the play-mode path's deferred destroy, recorded+ CollectionAssert.AreEqual(new[] { "teardown", "destroy terrain" }, log);+ assets.RunTeardown();+ }+ finally { Object.DestroyImmediate(root); }+ CollectionAssert.AreEqual(new[] { "teardown", "destroy terrain" }, log, "RunTeardown and OnDestroy do not run it again");+ }++ /// <summary>Review M2: a throwing teardown action is logged, and the others and the owned objects are still released.</summary>+ [Test]+ public void AThrowingTeardownActionDoesNotStopTheOthers()+ {+ var go = new GameObject("assets"); var assets = go.AddComponent<MapRuntimeAssets>();+ var owned = assets.Own(new Texture2D(1, 1));+ var order = new List<int>();+ assets.OnTeardown(() => order.Add(1));+ assets.OnTeardown(() => throw new System.InvalidOperationException("boom"));+ assets.OnTeardown(() => order.Add(3));+ LogAssert.Expect(LogType.Exception, new Regex("boom"));+ Object.DestroyImmediate(go);+ CollectionAssert.AreEqual(new[] { 3, 1 }, order);+ Assert.IsTrue(owned == null, "the owned texture is destroyed");+ }++ /// <summary>Review I2: a map's token removes only its own switch, so an old map's late teardown cannot unregister the+ /// switch a rebuilt map registered under the same name.</summary>+ [Test]+ public void ARemovalTokenRemovesOnlyItsOwnSwitch()+ {+ var log = new List<string>();+ var oldToken = VisualToggles.Register("grid", on => log.Add("old " + on));+ var newToken = VisualToggles.Register("grid", on => log.Add("new " + on));+ oldToken();+ CollectionAssert.AreEqual(new[] { "grid" }, VisualToggles.Names.ToArray());+ VisualToggles.Set("grid", false);+ Assert.AreEqual("new False", log.Last());+ newToken(); newToken();+ CollectionAssert.IsEmpty(VisualToggles.Names);+ }++ [Test]+ public void TheMapOwnsItsTogglesThroughItsTeardown()+ {+ var go = new GameObject("assets"); var assets = go.AddComponent<MapRuntimeAssets>();+ assets.OnTeardown(VisualToggles.Register("haze", _ => { }));+ Object.DestroyImmediate(go);+ CollectionAssert.IsEmpty(VisualToggles.Names);+ }++ /// <summary>Review M8: undo actions an earlier Init left behind (Init called outside MapScene.Build) run on the next+ /// Init instead of piling up.</summary>+ [Test]+ public void InitRunsAndClearsUndoActionsLeftByAnEarlierInit()+ {+ var go = new GameObject("cam", typeof(Camera)); var rig = go.AddComponent<CameraRig>();+ int ran = 0;+ rig.TeardownActions.Add(() => ran++);+ try+ {+ rig.Init();+ Assert.AreEqual(1, ran);+ CollectionAssert.IsEmpty(rig.TeardownActions);+ }+ finally+ {+ if (rig.Volume != null) { Object.DestroyImmediate(rig.Volume.profile); Object.DestroyImmediate(rig.Volume.gameObject); }+ Object.DestroyImmediate(go);+ }+ }+[Test]public void ColourMetricsBehave(){