Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Map: the units file parsed once at boot, shared by the map and the units layer (refs #321) (#560)

Eyal Golan2889cb5fc70a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8b7b41a3e..7b151e530 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -257,6 +257,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
+0.9 ms at the gameplay zoom), not yet on an idle one.
### Changed
+- The units file (`units_1948.yaml`) is parsed once at boot instead of twice: the map keeps its parse and the units
+ layer draws from the same list (refs #321). The units and where they stand are unchanged. The second parse cost about
+ 25 ms at `--cpu 4` between the map and the start screen; the map build itself is unchanged. `?bootlog` has three more
+ phases round the units layer. Presentation only.
- Tel Aviv's 1948 localities (Sheikh Muwannis, Jammasin, Salama, Ramat Gan, Givatayim, Bnei Brak and the rest inside its
footprint) keep their mosques and water towers, at a quarter and three tenths of their size elsewhere, at the street
crossing nearest their hearts (refs #318, owner ruling 2026-10-12). The city's blocks keep their plots round them: core
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 61f4e3b7e..67d316136 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -2756,3 +2756,29 @@ The units' span goes from about 300 to 90 ms. The map build is at least 165 ms s
rounds differ by 165 ms, and the two base rounds spread by 128 ms, so the mean difference (about 240 ms) is not a firm
figure.
`start screen shown` falls by about 120 ms, since the units layer places the tokens again there.
+
+### #321 round 3: the units file parsed once (T52)
+
+`units_1948.yaml` was parsed at boot by the map (`unit data read`, for the unit spots) and again by `GameRoot` for the
+units layer. Three `?bootlog` markers round the layer (`screens wired`, `units layer data read`, `units layer built`),
+one `--exclusive` run of 3 cold loads at `--cpu 4` on main `4875d0e` plus the markers, median ms: the map's parse 31,
+the layer's parse 25, the layer's build 62 (its own run of the unit placer included), and `screens wired` 272.
+
+The map now keeps its parse (`MapScene.UnitEntries`) and `GameRoot` takes it through `MapScene.UnitEntriesFor`, which
+hands back the same list when the text is the one the map read and parses otherwise. `UnitDataOnceTests` checks that
+the layer's list is the map's (it failed with the old second parse), that it holds the same units as a fresh parse,
+field for field, and that a rebuild or other text never hands on a stale parse. New Game replaces only the session;
+the units are content, read once for the layer's life as before.
+
+Base `4875d0e` against the branch, base, branch, branch, base under one `--exclusive` hold (load 2.8-11.9; the first
+base round stalled after one cold load when another process loaded the machine, so the base has four loads):
+
+| | base | branch round 1 | branch round 2 |
+|---|---|---|---|
+| `units layer data read` | (25, the split) | 1 | 1 |
+| map built to start screen shown, per load | 437, 444, 445, 456 | 417, 422, 434 | 415, 416, 419 |
+| `map_build_ms` (median) | 2221 | 2206 | 2214 |
+
+About 25 ms off the time from the map to the start screen; the map build is unchanged, since the parse that stays is the
+map's. Not done: the layer's second run of the unit placer (about 40 ms of `units layer built`) could take the map's
+spots too, and `screens wired` (about 270 ms) is not split yet.
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index 413f4a4f5..eb02cf3ef 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -137,6 +137,18 @@ namespace Statecraft.Game.Map
/// their figures off them. Empty before Build.</summary>
public IReadOnlyList<(List<Vector2> line, float halfWidth)> RouteCorridors { get; private set; } = new List<(List<Vector2>, float)>();
+ /// <summary>The units of content/map/units_1948.yaml as the last Build read them (empty before a build, or when the
+ /// file is missing or malformed). Read only: the units layer draws from this same list (UnitEntriesFor).</summary>
+ public IReadOnlyList<Units.UnitEntry> UnitEntries { get; private set; } = Array.Empty<Units.UnitEntry>();
+ string unitsYamlRead; // null before a build
+
+ /// <summary>The units for <paramref name="yaml"/>: the list the last Build parsed when it read the same text (issue
+ /// #321: the file was parsed twice at boot, here and for the units layer), else a parse of it (UnitData.ReadOrNone,
+ /// warning through <paramref name="warn"/>).</summary>
+ public IReadOnlyList<Units.UnitEntry> UnitEntriesFor(string yaml, Action<string> warn) =>
+ unitsYamlRead != null && string.Equals(yaml, unitsYamlRead, StringComparison.Ordinal)
+ ? UnitEntries : Units.UnitData.ReadOrNone(yaml, warn);
+
/// <summary>Where the kits keep their buildings and trees off the units (centre x, z; radius m): the spot of a unit that
/// stands in a town (UnitPlacer's last round, UnitGround.ClearingRadius), so no token stands in a building. Empty before
/// Build or without the unit file.</summary>
@@ -257,6 +269,7 @@ namespace Statecraft.Game.Map
// a unit placed in a town gets a clearing the kits keep free (UnitLayer places it the same way).
DiagLog.BootPhase("footprints");
var unitData = Units.UnitData.ReadOrNone(inputs.UnitsYaml, Debug.LogWarning);
+ UnitEntries = unitData; unitsYamlRead = inputs.UnitsYaml ?? "";
DiagLog.BootPhase("unit data read");
var unitHexes = Hexes.hexes.Select(h => new Statecraft.Sim.MapHex { Q = h.q, R = h.r, Lon = h.lon, Lat = h.lat, ElevM = h.elev_m, Land = h.land, Biome = h.biome }).ToList();
var unitGround = new Units.UnitGround(SettlementFootprints, RouteCorridors, unitHexes,
@@ -400,6 +413,7 @@ namespace Statecraft.Game.Map
}
Terrain = null;
Hexes = null;
+ UnitEntries = Array.Empty<Units.UnitEntry>(); unitsYamlRead = null;
}
}
}
diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
index de23ed49a..b3c3a578d 100644
--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
@@ -26,6 +26,8 @@ namespace Statecraft.Game.Map.Units
MapScene map = null!;
IReadOnlyList<UnitEntry> units = Array.Empty<UnitEntry>();
+ /// <summary>The unit data the layer draws from (read only; MapScene.UnitEntries when it read the same file).</summary>
+ public IReadOnlyList<UnitEntry> Units => units;
UnitGround ground = null!;
Dictionary<UnitAnchor, AnchorSpot> spots = new Dictionary<UnitAnchor, AnchorSpot>();
MapRuntimeAssets assets = null!;
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 87b3ffe78..b125f61d5 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -190,8 +190,12 @@ namespace Statecraft.Game.UI
owned.Add(new Undo(() => bridge.Changed -= onDate));
// The units in play (docs/units.md): drawn from the state and the sourced unit data, before the info panel so
// the layer has followed a change before the panel renders the selected unit's card.
+ DiagLog.BootPhase("screens wired"); // issue #321: the splits of the units layer
+ // The map's own parse of the unit file when it read this text (issue #321: it was parsed twice at boot).
+ var unitData = map.UnitEntriesFor(inputs.Map.UnitsYaml, Debug.LogWarning);
+ DiagLog.BootPhase("units layer data read");
var unitLayer = units = Statecraft.Game.Map.Units.UnitLayer.Create(map,
- Statecraft.Game.Map.Units.UnitData.ReadOrNone(inputs.Map.UnitsYaml, Debug.LogWarning), inputs.Content.Hexes,
+ unitData, inputs.Content.Hexes,
Statecraft.Game.Map.Units.UnitShowcase.StillRequested(Application.absoluteURL, Environment.GetCommandLineArgs(),
Application.platform == RuntimePlatform.WebGLPlayer));
// A screenshot run (?shot) leaves the units out unless it also asks for them (&units), so the art log's plain
@@ -203,6 +207,7 @@ namespace Statecraft.Game.UI
bridge.Changed += showUnits;
owned.Add(new Undo(() => bridge.Changed -= showUnits));
showUnits();
+ DiagLog.BootPhase("units layer built");
var localitiesAt = LocalitiesAt(map);
var info = Own(new InfoPanelPresenter(root, bridge, text, names, nav: nav,
selectedUnit: () => unitLayer.Selected is string id ? unitLayer.Tokens.First(p => p.Token.Unit.Id == id) : (Statecraft.Game.Map.Units.PlacedToken?)null,
diff --git a/unity/Assets/Tests/EditMode/UnitDataOnceTests.cs b/unity/Assets/Tests/EditMode/UnitDataOnceTests.cs
new file mode 100644
index 000000000..73722b04c
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitDataOnceTests.cs
@@ -0,0 +1,94 @@
+#nullable enable
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Boot;
+using Statecraft.Game.Map;
+using Statecraft.Game.Map.Units;
+using Statecraft.Game.UI;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using Object = UnityEngine.Object;
+
+/// <summary>Issue #321 (T52): content/map/units_1948.yaml was parsed twice at boot, once by the map for the unit spots
+/// (MapScene.Build) and again by GameRoot for the units layer. The map now keeps its parse and hands it on: the units
+/// layer gets the very list the map read (one parse a boot), with the same units as a fresh parse of the file; a layer
+/// started from other unit text than the map read parses its own.</summary>
+public class UnitDataOnceTests
+{
+ string saveDir = "";
+
+ [SetUp]
+ public void SetUp() => saveDir = Path.Combine(Path.GetTempPath(), "statecraft-unitsonce-" + System.Guid.NewGuid().ToString("N"));
+
+ [TearDown]
+ public void TearDown()
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ VisualToggles.Clear();
+ if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);
+ }
+
+ static GameInputs Inputs() => GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+
+ /// <summary>A unit as the layer and the cards read it: its fields, anchors and aircraft, as text to compare.</summary>
+ static string Describe(UnitEntry u) =>
+ string.Join("|", u.Id, u.Name, u.Number, u.Service, u.Formed, u.FirstCommander, u.Sector, u.WikipediaOnly, u.Status, u.Hidden,
+ string.Join(",", u.Headgear ?? new List<string>()), u.Disbanded?.Date,
+ string.Join(";", u.Anchors.Select(a => string.Join("/", a.Place, a.Lon.ToString("R"), a.Lat.ToString("R"), a.From, a.Since, a.To, a.EndBasis,
+ a.EndNote, a.Front, a.Toward?.Place, a.PlaceHex == null ? "" : string.Join(",", a.PlaceHex), a.Precision, a.Note, a.Sources.Count))),
+ string.Join(";", (u.Aircraft ?? new List<UnitAircraft>()).Select(t => t.Type + "/" + t.From + "/" + t.To)),
+ u.AllSources().Count());
+
+ [Test]
+ public void TheUnitsLayerGetsTheMapsParseOfTheUnits()
+ {
+ var inputs = Inputs();
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build(inputs.Map);
+ var root = Object.FindFirstObjectByType<GameRoot>();
+ root.Store = new SaveStore(saveDir);
+ root.Begin(inputs, 0);
+ Assert.IsNotNull(root.Units);
+ Assert.IsNotEmpty(map.UnitEntries);
+ Assert.AreSame(map.UnitEntries, root.Units!.Units, "one parse a boot: the layer's units are the map's list");
+ // The same units as a fresh parse of the file, field for field.
+ var fresh = UnitData.Parse(inputs.Map.UnitsYaml);
+ CollectionAssert.AreEqual(fresh.Select(Describe).ToList(), root.Units.Units.Select(Describe).ToList());
+ }
+
+ [Test]
+ public void OtherUnitTextIsParsedOnItsOwn()
+ {
+ var inputs = Inputs();
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build(inputs.Map);
+ var warnings = new List<string>();
+ Assert.AreSame(map.UnitEntries, map.UnitEntriesFor(inputs.Map.UnitsYaml, warnings.Add));
+ Assert.AreSame(map.UnitEntries, map.UnitEntriesFor(new string(inputs.Map.UnitsYaml.ToCharArray()), warnings.Add), "equal text, another string");
+ var other = map.UnitEntriesFor(inputs.Map.UnitsYaml + "\n# edited\n", warnings.Add);
+ Assert.AreNotSame(map.UnitEntries, other);
+ Assert.AreEqual(map.UnitEntries.Count, other.Count);
+ CollectionAssert.IsEmpty(map.UnitEntriesFor("", warnings.Add));
+ Assert.AreEqual(1, warnings.Count, "the missing file's own warning, once");
+ }
+
+ /// <summary>A map that is cleared or rebuilt from other inputs never hands on a stale parse.</summary>
+ [Test]
+ public void ARebuildReplacesTheParse()
+ {
+ var inputs = Inputs();
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build(inputs.Map);
+ var first = map.UnitEntries;
+ inputs.Map.UnitsYaml = "";
+ map.Build(inputs.Map);
+ CollectionAssert.IsEmpty(map.UnitEntries);
+ Assert.AreNotSame(first, map.UnitEntries);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/UnitDataOnceTests.cs.meta b/unity/Assets/Tests/EditMode/UnitDataOnceTests.cs.meta
new file mode 100644
index 000000000..df58e4e1e
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitDataOnceTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: faf7b1084fa145e5ae193e2f45d3c3e6