A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Units: review fixes, owner rulings and the authored-model hook
eyalgolan9d166aa300c2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1f3faa7a4..32e27d1dc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,7 +23,8 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBagain. Presentation only; `?nofallback` turns it off (#44).- The unit art slice (a showcase for the art track, not gameplay): a 1948 IDF rifle trio with a selection ring, an IAFSpitfire flying a loop with its shadow, and the corvette INS Haganah, built from code as painted miniatures at the- promo's symbolic scale. Shown only with `?units`, in `?shot` screenshots and in editor renders (docs/units.md).+ promo's symbolic scale. Shown only with `?units` (desktop `-units`) and in `tools/art_checkpoint.sh --units`; an+ authored model can replace a code-built one per unit type (docs/units.md).### Changed- The historical AI no longer sends an order the turn's attention cannot cover (the rule the UI's order queue applies),diff --git a/docs/units.md b/docs/units.mdindex 343c166d7..b352731f3 100644--- a/docs/units.md+++ b/docs/units.md@@ -11,22 +11,43 @@ fight is war mode's job (#104, with the sim side in #21). The golden hashes do n## How to see it-- **WebGL:** add `units` to the page URL (`index.html?units`). The art checkpoint's `?shot` shows it too, with the aircraft- held at a fixed point so screenshots repeat. Normal play never shows it.+- **WebGL:** add `units` to the page URL (`index.html?units`). Normal play never shows it, and neither does a plain+ `?shot`: every track's art-checkpoint metrics stay comparable (controller ruling, 2026-10-11).+- **Art checkpoint:** `tools/art_checkpoint.sh --units <name>` adds `&units` to the WebGL screenshots and `-units` to the+ editor renders. With `shot` the aircraft holds a fixed point, so the screenshots repeat.- **Desktop player:** run with `-units`.-- **Editor:** `MapCapture.Promo` (run by `tools/art_checkpoint.sh`) renders it.+- **Editor:** `MapCapture.Promo` renders it when given `-units`.- **Frame cost:** `?vprofile&units` prices it as the `units` toggle (`median(all) - median(-units)`).Code: `unity/Assets/Scripts/Map/Units/`. The materials are made by `UnitMaterialAssets.Create` in`unity/Assets/Resources/Units/`. Tests: `UnitShowcaseTests`.+## Owner rulings (2026-10-11)++1. **Units are Civ-style tokens at about 2,000x real size** (see "Scale").+2. **Promo-quality close-zoom models come from a separate track:** a cloud-GPU AI-3D pipeline (TRELLIS, MIT). The+ code-built miniatures here stay as the far-zoom and fallback version.++**The art hook.** An authored model replaces the code-built one for its unit type when a prefab exists at+`unity/Assets/Resources/Units/Authored/<unit type>`. The unit types are the `*Type` constants in `UnitShowcase`, for+example `rifleman-1948-steel-helmet` and `spitfire-mk9e-101sqn-1948`.++An authored model follows the code-built convention:+- real metres, facing +Z;+- origin on the ground (an aircraft: its centre of gravity);+- its own materials;+- an authored aircraft brings its own propeller.++The showcase places and scales it as it does the code-built model. That is the whole hook: there is no registry beyond+it, and there are no level-of-detail switches yet.+## What is in the slice| Piece | Model | Where (PromoPose.Gameplay03) ||---|---|---|-| Rifle trio | three 1948 IDF riflemen: bush hat with rifle held ready, Mk II steel helmet with rifle grounded, Palmach stocking cap with rifle slung | on the coastal plain east of Tel Aviv (34.88 E, 32.01 N), clear of the settlement labels, inside a white selection ring |-| Aircraft | Supermarine Spitfire LF Mk IX in IAF service, 1948 | a 16 km loop over Tel Aviv and the coast, 4.2 km above the highest ground under it, banked 28 degrees, its shadow cast on the ground by the sun |-| Navy | modified Flower-class corvette INS Haganah (K-20), 1948 | off Jaffa (34.63 E, 32.02 N) |+| Rifle trio | three 1948 IDF riflemen: bush hat with rifle held ready, Mk II steel helmet with rifle grounded, Palmach stocking cap with rifle slung | on the centre of the hex nearest 34.88 E, 32.01 N (east of Tel Aviv, clear of the settlement labels), inside a white selection ring that fits within the hex |+| Aircraft | Supermarine Spitfire LF Mk IXe of 101 Squadron, as from Operation Yoav (October 1948) into January 1949: red spinner, red-and-white rudder, roundel without an outer ring | a 16 km loop over Tel Aviv and the coast, 4.2 km above the highest ground under it, banked 28 degrees, its shadow cast on the ground by the sun |+| Navy | modified Flower-class corvette INS Haganah (K-20), 1948, 63.4 m | off Jaffa (34.63 E, 32.02 N) |Not in the slice:- **The mounted rider.** No 1948 IDF mounted unit was sourced for this slice. The promo's rider belongs to 1936, so it@@ -35,43 +56,38 @@ Not in the slice:## Pipeline choice: code-built miniatures-Three pipelines were tried on this Mac (Apple M5 Pro, 48 GB) on 2026-10-11. Each was placed on the map at the same scale-and rendered at the gameplay zoom and close up. The evidence is in the spike report (agent scratchpad, `units-report.md`).+Three pipelines were tried on a development Mac (Apple M5 Pro, 48 GB) on 2026-10-11. Each was placed on the map at the+same scale and rendered at the gameplay zoom and close up, next to the promo's trio; the table summarises what each+produced. The renders are not in the repository.| Pipeline | Result | Licence ||---|---|---|| (a) Image-to-3D, run locally: TripoSR (MIT code and weights), CPU, about 3.5 s per mesh | Inputs were a promo crop and a 1948 photograph. Out came a blurry blob of about 45,700 triangles with baked vertex colours: the head and rifle were lost to the background cut-out, the side view was a flat card for the rider, and there was no rig. It would need clean, sharp turnaround references, which we cannot make locally, plus manual retopology. | MIT; fine. |-| (a) Hunyuan3D-2, TRELLIS | Not run. Hunyuan3D-2's community licence excludes the EU, the UK and South Korea, which is not compatible with an open project. TRELLIS needs an NVIDIA GPU with CUDA. | Hunyuan3D-2: not compatible. TRELLIS: MIT. |+| (a) Hunyuan3D-2, TRELLIS | Not run locally. Hunyuan3D-2's community licence excludes the EU, the UK and South Korea, which is not compatible with an open project. TRELLIS needs an NVIDIA GPU with CUDA; the owner chose it for the cloud-GPU close-zoom track (rulings above). | Hunyuan3D-2: not compatible. TRELLIS: MIT. || (b) CC0 base meshes: Quaternius Universal Base Characters (free "Standard" kit, CC0) | A clean, rigged body, but a stylised "superhero" figure in underwear, in a T-pose. Every uniform, hat, belt and rifle would have to be modelled by hand in Blender. Kenney's characters are blocky, low-poly figures, which the spec rules out (§6, "no low-poly packs mixed in"). | CC0; fine. || **(c) Code-built from primitives (chosen)** | Lathed limbs and torsos, ellipsoids, boxes and plates, painted from one palette texture with a dark wash at the feet and a dry-brushed highlight on top. One URP Lit material, made at runtime, with no texture file. About 3,600 triangles per figure. Real silhouettes for each headgear and rifle pose. The figures cast and receive shadows. | Our own code, MIT. |**Why (c):** at the gameplay zoom a figure is about 90 px tall. What reads at that size is the silhouette (hat brim,-rifle, stance), the colour blocks (khaki shirt, dark trousers, pale webbing) and the shadow. The code-built figures get-all three close to the promo (see the art checkpoint's side-by-side). They are exact to the sources: each part is a sourced item, and a change is a reviewed line-of code. Era variants (1956 helmets, 1967 Uzis, 1973 flak vests) are parameters. Builds are deterministic, there is no+rifle, stance), the colour blocks (khaki shirt, dark trousers, pale webbing) and the shadow. In the gameplay03+checkpoint the code-built trio matches the promo's trio in size (87 px) and reads with all three. They are exact to the+sources: each part is a sourced item, and a change is a reviewed line of code. Era variants (1956 helmets, 1967 Uzis, 1973 flak vests) are parameters. Builds are deterministic, there is nolicence question, and the build-size cost is code only.**Their limit:** close up (the 6 km hero zoom) they look like wooden mannequins, with faceted limbs and no faces or-folds. The promo's close shots (0:21) show sculpted miniatures. The path past that limit, when the art track gets to it:-hand-sculpted figures in Blender over a CC0 base (b), in the same palette and silhouettes, with the code-built figures kept-as the far LOD.+folds. The promo's close shots (0:21) show sculpted miniatures. The way past that limit is the owner's close-zoom track,+which plugs authored models in through the art hook above.## ScaleMeasured on the promo scaled to 1920 px wide: a rifleman is about 87 px tall, inside a ring about 190 px across. Ourgameplay03 pose frames the same hex count as the promo (about 9 across: see `PromoPose`). The first checkpoint, at 2600x,drew our riflemen 113 px tall. So the slice uses `UnitShowcase.FigureScale = 2000`: a man about 3.6 km tall on 5 km-hexes, with the ring at 0.66 of a hex's circumradius. The aircraft (x420, a 4.7 km span) and the ship (x95, 5.9 km) are+hexes, with the ring at 0.66 of a hex's circumradius. The aircraft (x420, a 4.7 km span) and the ship (x95, 6.0 km) aresized against the figures, as Civ sizes them, not against each other.-**Open question for the owner.** This is far above the "10–25x real" ruling for buildings and trees. At 10–25x a man is-18–45 m tall, which is under one pixel at 60 km. The promo (which wins over strict scale, by the owner's ruling) draws-units as tokens. Options:-1. Keep units as tokens at about 2,000x, as now.-2. Scale units with the zoom, Civ-style, so they keep a constant size on screen.-3. Make them smaller and accept that they only read at the hero zoom.--The slice does (1), and the scale is one constant.+**Owner ruling (2026-10-11): units stay Civ-style tokens at about 2,000x.** This is far above the 10–25x ruling for+buildings and trees. At 10–25x a man is 18–45 m tall, which is under one pixel at 60 km. The promo, which wins over strict+scale by the owner's ruling, draws units as tokens. The scale is one constant.## Sources (checked 2026-10-11)@@ -83,7 +99,8 @@ Uniform and equipment, 1948:https://commons.wikimedia.org/wiki/File:Negev_Brigade_soldiers_1948.jpg- Beersheba, 21 October 1948: brimmed bush hats, khaki shirts and shorts, belts. CC BY 4.0 (National Library of Israel).https://commons.wikimedia.org/wiki/File:1948_Arab-Israeli_War_997008137085905171.jpg-- An IDF soldier, about March 1948: khaki shirt and trousers, web belt, a Lee-Enfield rifle. CC BY 2.5 (PikiWiki).+- A woman fighter in Jerusalem, about March 1948 (photograph by Yehuda Aizenshtark): khaki shirt and trousers, web+ belt, a grenade, and a Lee-Enfield No. 4 rifle (per the Commons category). CC BY 2.5 (PikiWiki).https://commons.wikimedia.org/wiki/File:PikiWiki_Israel_38816_Israel_Defense_Forces.jpgAircraft:@@ -94,15 +111,35 @@ Aircraft:The Spitfire was chosen over it because the promo shows a Spitfire (promo beats era, and both are 1948-correct).- Spitfire Mk IX shape (an elliptical wing, a four-blade propeller): the IAF Museum airframe at Hatzerim. CC BY 2.5.https://commons.wikimedia.org/wiki/File:Spitfire-MkIX-hatzerim-1-1.jpg-- Early IAF roundel: a blue Star of David on a white disc ringed in blue. Public domain.- https://commons.wikimedia.org/wiki/File:IAF_roundel_(early_variant).svg-- **Unverified (single source: the promo):** the two-tone camouflage. The Czech Mk IXs were ex-RAF airframes, but no- source for the scheme they flew in Israel in 1948 has been checked yet. The museum airframe is bare metal in post-war- markings.+ Many IAF IXes had clipped wing tips (Fundekals review, below). The slice keeps the full elliptical wing that the promo+ shows.+- Variant **LF.IXe**, and 101 Squadron's **red spinner** and **red-and-white striped rudder**. Two hobby sources agree:+ - IsraDecal Studio, "Spitfire Mk.IX, Israeli Air Force" (IAF-123, 1:24) marking instructions, May 2023. It lists+ "Spitfire LF.IXe 2011/26, 101 Squadron, January 1949", painted in RAF colours, with a red spinner and the rudder+ painted "in White. Paint Red stripes".+ https://www.isradecal.com/_files/ugd/ddb4b4_42f20e2bc83f4ba895c816e97ad03151.pdf+ - Eduard Info 11/2025: "In preparation for Operation Ten Plagues (October 15-22, 1948), later renamed Operation Yoav,+ 101 Tayeset fighters obtained high visibility markings consisting of red spinners and red and white stripes on the+ rudders". https://info.eduard.com/en/11-2025-1/strana-53+ - A Fundekals decal review also says 101 Squadron "had the white and red stripes on the rudder".+ https://mail.modelingmadness.com/scott/decals/fundekals/fd48idfspit.htm+ - **Unverified:** the stripes' direction. The slice draws them across the rudder.+- Roundel of 1948–49: a blue Star of David on a white disc, the star clear of the disc's edge, **with no outer blue ring**.+ - Flags of the World, citing a 2002 survey of *Born in Battle*: "almost all the roundels show the star within, but not+ reaching the edges of, the white disk ... This includes early planes from the 1948/49 war of independence (like+ Spitfire ...)". It adds: "the only aircraft showing a roundel with a thin blue ring around are Mosquitos and Meteors+ from the 1950ies". https://crwflags.com/fotw/flags/il%5Eairfo.html+ - The Commons "early variant" SVG with the ring is drawn from a Mosquito photograph, a 1950s type, so it is not used.+- **Unverified (one hobby source, IsraDecal):** the camouflage, RAF ocean grey and dark green over medium sea grey. A+ forum report of brown overpaint in theatre is an open question. The museum airframe is bare metal in post-war markings.+ The standard reference, Alex Yofe's *Spitfire Mk. IX in Israeli Air Force Service 1948–1956*, has not been checked.Navy:-- INS Haganah (K-20), ex-HMCS Norsyd, a modified Flower-class corvette, taken over and rearmed by the Israeli Navy in 1948.- The modified Flowers had an upright funnel. https://en.wikipedia.org/wiki/HMCS_Norsyd+- INS Haganah (K-20), ex-HMCS Norsyd, a modified Flower-class corvette, 208 ft (63.4 m) overall, with an upright+ funnel. https://en.wikipedia.org/wiki/HMCS_Norsyd+ - In 1946 it was sold to the Mossad for Aliyah Bet as the *Balboa*, renamed *Haganah*, and carried Holocaust survivors+ towards Mandate Palestine.+ - The Israeli Navy took it over and rearmed it in 1948.- Photograph of K-20 in Haifa harbour, 1948: light grey, mast at the bridge, funnel aft of it. Public domain.https://commons.wikimedia.org/wiki/File:Hagana_K-20_ship_Israel.jpg- Photograph of INS Haganah, about 1949. Public domain. https://commons.wikimedia.org/wiki/File:INSHaganah.jpgdiff --git a/tools/art_checkpoint.sh b/tools/art_checkpoint.shindex fa55d6209..1f5f82aa1 100755--- a/tools/art_checkpoint.sh+++ b/tools/art_checkpoint.sh@@ -3,11 +3,20 @@# the promo poses from the player itself (?shot: the web tier with its UI and labels), editor renders of both quality# tiers, and side-by-side images against the promo with colour-blind simulations. Re-checks both golden hashes in the same# player run and fails if a screenshot is missing or blank. The art log lives in the main checkout's captures/ so every-# worktree appends to one history. Usage: tools/art_checkpoint.sh [--no-build] <checkpoint-name>+# worktree appends to one history. --units adds the unit art slice (docs/units.md) to both the WebGL shots (&units) and the+# editor renders (-units); without it the captures stay comparable across tracks. Usage:+# tools/art_checkpoint.sh [--no-build] [--units] <checkpoint-name>set -euo pipefail-build=1-if [[ "${1:-}" == "--no-build" ]]; then build=0; shift; fi-name="${1:?usage: tools/art_checkpoint.sh [--no-build] <checkpoint-name>}"+build=1; units_query=""; units_arg=()+while [[ "${1:-}" == --* ]]; do+ case "$1" in+ --no-build) build=0 ;;+ --units) units_query="&units"; units_arg=(-units) ;;+ *) echo "art_checkpoint: unknown option $1" >&2; exit 2 ;;+ esac+ shift+done+name="${1:?usage: tools/art_checkpoint.sh [--no-build] [--units] <checkpoint-name>}"root="$(git rev-parse --show-toplevel)"cd "$root"main_root="$(cd "$(git rev-parse --path-format=absolute --git-common-dir)/.." && pwd)"@@ -31,7 +40,7 @@ fi[[ -f unity/Builds/Web-disabled/index.html ]] || { echo "art_checkpoint: no build at unity/Builds/Web-disabled (run without --no-build)" >&2; exit 2; }out="captures/visual/$name"rm -rf "$out"; mkdir -p "$out"-uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&shot" --expect "GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07" --expect "GOLDEN OK 1952 73590e324f19e9959a455a4da79e93d7089dfcf283c13aac02af6b0a624b9767" --expect "SHOT done" --shots "$out" --stall 180 \+uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&shot${units_query}" --expect "GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07" --expect "GOLDEN OK 1952 73590e324f19e9959a455a4da79e93d7089dfcf283c13aac02af6b0a624b9767" --expect "SHOT done" --shots "$out" --stall 180 \--fail 'GOLDEN FAIL|SMOKE FAIL|BOOT FAIL|Statecraft/.*(not supported|Unsupported)|(not supported|Unsupported).*Statecraft/'# The poses come from PromoPose.All's source, so a new pose is checked without editing this script (review M3).poses=$(grep -o 'new PromoPose("[A-Za-z0-9_]*"' unity/Assets/Scripts/Map/PromoPose.cs | cut -d'"' -f2)@@ -39,7 +48,7 @@ poses=$(grep -o 'new PromoPose("[A-Za-z0-9_]*"' unity/Assets/Scripts/Map/PromoPofor pose in $poses; do[[ -s "$out/$pose.png" ]] || { echo "art_checkpoint: $out/$pose.png is missing" >&2; exit 1; }done-shared "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget OSXUniversal -executeMethod MapCapture.Promo -captureDir "$root/$out/editor" -logFile "$root/unity-capture-promo.log"+shared "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget OSXUniversal -executeMethod MapCapture.Promo -captureDir "$root/$out/editor" ${units_arg[@]+"${units_arg[@]}"} -logFile "$root/unity-capture-promo.log"git checkout -- unity/ProjectSettings/QualitySettings.asset # SetQualityLevel may have written m_CurrentQuality (no unstaged edits: checked above)uv run tools/art_compare.py "$out" "$name" --log "$main_root/captures/visual/art-log.tsv"echo "ART CHECKPOINT $name: $(ls "$out"/*-compare*.png "$out"/editor/*-compare*.png | tr '\n' ' ')"diff --git a/unity/Assets/Editor/MapCapture.cs b/unity/Assets/Editor/MapCapture.csindex cdfeba7e6..818a11102 100644--- a/unity/Assets/Editor/MapCapture.cs+++ b/unity/Assets/Editor/MapCapture.cs@@ -105,14 +105,16 @@ public static class MapCapture/// <summary>Renders each promo pose (PromoPose.All) at 1920x1080 once per quality tier (0 = Mobile, the WebGL tier;/// 1 = PC) into <-captureDir> (default captures/visual/editor) as <tier>-<pose>.png. Editor renders show no UI- /// Toolkit labels; tools/art_checkpoint.sh pairs them with the WebGL screenshots, which do.</summary>+ /// Toolkit labels; tools/art_checkpoint.sh pairs them with the WebGL screenshots, which do. With -units it adds the unit+ /// art slice (UnitShowcase), still.</summary>public static void Promo(){var args = System.Environment.GetCommandLineArgs();int at = System.Array.IndexOf(args, "-captureDir");var dir = at >= 0 && at + 1 < args.Length ? args[at + 1] : Path.Combine(CaptureDir, "visual", "editor");var map = OpenAndBuild();- Statecraft.Game.Map.Units.UnitShowcase.Spawn(map, still: true); // the unit art slice, as the ?shot screenshots show it+ // The unit art slice only when asked (-units, from tools/art_checkpoint.sh --units), as ?shot&units shows it.+ if (System.Array.IndexOf(args, "-units") >= 0) Statecraft.Game.Map.Units.UnitShowcase.Spawn(map, still: true);var rig = Camera.main.GetComponent<CameraRig>();int saved = QualitySettings.GetQualityLevel();trydiff --git a/unity/Assets/Scripts/Map/Units/MiniatureMesh.cs b/unity/Assets/Scripts/Map/Units/MiniatureMesh.csindex 74fb6b53e..9a0f57e5c 100644--- a/unity/Assets/Scripts/Map/Units/MiniatureMesh.cs+++ b/unity/Assets/Scripts/Map/Units/MiniatureMesh.cs@@ -18,10 +18,15 @@ namespace Statecraft.Game.Map.Unitsreadonly List<float> shadeOverride = new List<float>(); // NaN: shade by heightreadonly List<int> tris = new List<int>();- public int VertexCount => verts.Count;- public int TriangleCount => tris.Count / 3;+ // The normal matrix of the part being built: every builder places all its vertices with one matrix, so it is+ // inverted once per part, not once per vertex.+ Matrix4x4 normalOf = Matrix4x4.identity, normalMatrix = Matrix4x4.identity;- static Vector3 N(Matrix4x4 m, Vector3 n) => m.inverse.transpose.MultiplyVector(n).normalized;+ Vector3 N(Matrix4x4 m, Vector3 n)+ {+ if (m != normalOf) { normalOf = m; normalMatrix = m.inverse.transpose; }+ return normalMatrix.MultiplyVector(n).normalized;+ }int Add(Matrix4x4 m, Vector3 p, Vector3 n, int slot, float shade){@@ -137,10 +142,10 @@ namespace Statecraft.Game.Map.Units/// <summary>A thin lifting surface along local +X (span) with chord along Z: the leading edge at z = +lead(s), the/// trailing edge at z = -trail(s) for s in [0, 1] from root to tip, thickness <paramref name="thickness"/> times the- /// local chord. <paramref name="topSlot"/> paints each upper panel (by its span and chord index), the lower surface is- /// <paramref name="bottomSlot"/>. Flat-shaded panels, so the camouflage reads as painted patches.</summary>+ /// local chord. <paramref name="topSlot"/> and <paramref name="bottomSlot"/> paint each upper and lower panel by its+ /// span and chord index. Flat-shaded panels, so the camouflage reads as painted patches.</summary>public MiniatureMesh Wing(Matrix4x4 m, Func<float, float> lead, Func<float, float> trail, float span, float thickness,- Func<int, int, int> topSlot, int bottomSlot, int spanSteps = 8, int chordSteps = 3)+ Func<int, int, int> topSlot, Func<int, int, int> bottomSlot, int spanSteps = 8, int chordSteps = 3){Vector3 P(int i, int j, float side){@@ -154,7 +159,7 @@ namespace Statecraft.Game.Map.Unitsfor (int j = 0; j < chordSteps; j++){Quad(m, P(i, j, 1), P(i + 1, j, 1), P(i + 1, j + 1, 1), P(i, j + 1, 1), topSlot(i, j), up: true);- Quad(m, P(i, j, -1), P(i, j + 1, -1), P(i + 1, j + 1, -1), P(i + 1, j, -1), bottomSlot, up: false);+ Quad(m, P(i, j, -1), P(i, j + 1, -1), P(i + 1, j + 1, -1), P(i + 1, j, -1), bottomSlot(i, j), up: false);}return this;}@@ -174,7 +179,12 @@ namespace Statecraft.Game.Map.Units/// highlight; a part built with an explicit shade keeps it. Every triangle is wound here to face along its vertices'/// normals (Unity's front face: Cross(p1 - p0, p2 - p0) points out), so the builders above need not track winding/// through mirrored or rotated matrices.</summary>- public Mesh Build(string name)+ public Mesh Build(string name) => Build(name, float.NaN);++ /// <summary>As <see cref="Build(string)"/>, but every part built without an explicit shade takes+ /// <paramref name="shade"/> instead of its height: for models whose height says nothing about wear (an aircraft's+ /// wings sit lowest in its airframe and would otherwise take the feet's dark wash).</summary>+ public Mesh Build(string name, float shade){float lo = float.MaxValue, hi = float.MinValue;foreach (var p in verts) { lo = Mathf.Min(lo, p.y); hi = Mathf.Max(hi, p.y); }@@ -182,7 +192,7 @@ namespace Statecraft.Game.Map.Unitsvar uv = new List<Vector2>(verts.Count);for (int i = 0; i < verts.Count; i++){- float v = float.IsNaN(shadeOverride[i]) ? (verts[i].y - lo) / range : shadeOverride[i];+ float v = !float.IsNaN(shadeOverride[i]) ? shadeOverride[i] : !float.IsNaN(shade) ? shade : (verts[i].y - lo) / range;uv.Add(new Vector2(UnitPalette.U(slots[i]), Mathf.Clamp01(v)));}var flipped = new int[tris.Count];diff --git a/unity/Assets/Scripts/Map/Units/ShowcaseFlight.cs b/unity/Assets/Scripts/Map/Units/ShowcaseFlight.csindex 0037bf5c3..3340de393 100644--- a/unity/Assets/Scripts/Map/Units/ShowcaseFlight.cs+++ b/unity/Assets/Scripts/Map/Units/ShowcaseFlight.cs@@ -9,7 +9,7 @@ namespace Statecraft.Game.Map.Units{Vector3 centre; float radius, altitude, seconds, bank; Transform? propeller; float? still;- public void Configure(Vector3 centre, float radius, float altitude, float seconds, float bank, Transform propeller, float? stillPhase)+ public void Configure(Vector3 centre, float radius, float altitude, float seconds, float bank, Transform? propeller, float? stillPhase){this.centre = centre; this.radius = radius; this.altitude = altitude; this.seconds = seconds; this.bank = bank;this.propeller = propeller; still = stillPhase;@@ -22,7 +22,7 @@ namespace Statecraft.Game.Map.Units{if (still.HasValue) return;Place(Time.time / seconds % 1f);- if (propeller != null) propeller.localRotation = Quaternion.Euler(0, 0, -Time.time * 1500f);+ if (propeller != null) propeller.localRotation = Quaternion.Euler(0, 0, -Mathf.Repeat(Time.time * 1500f, 360f));}/// <summary>Puts the aircraft at phase <paramref name="t"/> (0..1) of the loop, flying anticlockwise seen from above.</summary>diff --git a/unity/Assets/Scripts/Map/Units/UnitModels.cs b/unity/Assets/Scripts/Map/Units/UnitModels.csindex 741928a37..a289b75d1 100644--- a/unity/Assets/Scripts/Map/Units/UnitModels.cs+++ b/unity/Assets/Scripts/Map/Units/UnitModels.cs@@ -6,7 +6,7 @@ using P = Statecraft.Game.Map.Units.UnitPalette;namespace Statecraft.Game.Map.Units{/// <summary>The unit miniatures, built in real metres (a man 1.78 m tall, the Spitfire's 11.2 m span, the corvette's- /// 62.5 m hull) and scaled up to the map's symbolic scale by <see cref="UnitShowcase"/>. Each model faces +Z with its+ /// 63.4 m hull) and scaled up to the map's symbolic scale by <see cref="UnitShowcase"/>. Each model faces +Z with its/// origin on the ground (the aircraft: its centre of gravity). References and their check dates: docs/units.md./// Rifles, straps and hat brims are thicker than real so they survive at 60 km (a painted miniature's exaggeration).</summary>public static class UnitModels@@ -106,10 +106,13 @@ namespace Statecraft.Game.Map.Unitsm.Rod(Vector3.Lerp(butt, muzzle, 0.34f), muzzle, 0.016f, 0.014f, P.RifleMetal, segments: 5);}- /// <summary>A Supermarine Spitfire LF Mk IX as the IAF flew it in 1948 (sources in docs/units.md): 11.23 m elliptical- /// wing, 9.47 m fuselage, four-blade propeller, two-tone camouflage over a light underside, and the early IAF roundel- /// (a blue Star of David on a white disc ringed in blue) on the wings and fuselage. The propeller is a separate mesh- /// (<see cref="SpitfirePropeller"/>) so it can turn. Faces +Z, centre of gravity at the origin.</summary>+ /// <summary>A Supermarine Spitfire LF Mk IXe of 101 Squadron, IAF, as from Operation Yoav (October 1948) into January+ /// 1949 (sources in docs/units.md): 11.23 m elliptical wing (the promo's; many IAF IXes had clipped tips), 9.47 m+ /// fuselage, four-blade propeller, the squadron's red spinner and red-and-white striped rudder, and the IAF roundel of+ /// 1948-49, a blue Star of David on a white disc with no outer ring, on the wings and fuselage. The camouflage (RAF+ /// ocean grey and dark green over medium sea grey) is UNVERIFIED: one hobby source, and a report of brown overpaint+ /// in theatre is open. The propeller is a separate mesh (<see cref="SpitfirePropeller"/>) so it can turn. Faces +Z,+ /// centre of gravity at the origin. Built with one mid shade (<see cref="AircraftShade"/>), not by height.</summary>public static Mesh Spitfire(string name){var m = new MiniatureMesh();@@ -119,8 +122,8 @@ namespace Statecraft.Game.Map.Unitsm.Lathe(TRS(Vector3.zero, V(90f, 0, 0), V(0.78f, 1f, 1.05f)), body, P.CamoGreen, 12);m.Lathe(TRS(V(0, -0.22f, 0), V(90f, 0, 0), V(0.62f, 1f, 0.72f)), new List<Vector2> { new Vector2(-2.6f, 0.2f), new Vector2(-1.0f, 0.62f),new Vector2(1.6f, 0.62f), new Vector2(2.6f, 0.42f) }, P.Underside, 12);- // Spinner.- m.Lathe(TRS(V(0, 0.02f, 3.0f), V(90f, 0, 0), Vector3.one), new List<Vector2> { new Vector2(0f, 0.36f), new Vector2(0.45f, 0.26f), new Vector2(0.75f, 0f) }, P.PropBlack, 10);+ // Spinner: 101 Squadron red from October 1948.+ m.Lathe(TRS(V(0, 0.02f, 3.0f), V(90f, 0, 0), Vector3.one), new List<Vector2> { new Vector2(0f, 0.36f), new Vector2(0.45f, 0.26f), new Vector2(0.75f, 0f) }, P.MarkingRed, 10);// Canopy.m.Ellipsoid(TRS(V(0, 0.68f, -0.4f), Vector3.zero, V(0.34f, 0.32f, 1.0f)), P.Glass);// Elliptical wing: semi-span 5.6 m, root chord 2.5 m, low on the fuselage, with a 6 degree dihedral.@@ -132,25 +135,26 @@ namespace Statecraft.Game.Map.Unitsforeach (var side in new[] { 1f, -1f }){var w = TRS(V(side * 0.4f, -0.38f, 0.3f), V(0, 0, side * 6f), V(side, 1f, 1f));- m.Wing(w, lead, trail, semi, 0.06f, camo, P.Underside, spanSteps: 12, chordSteps: 4);+ m.Wing(w, lead, trail, semi, 0.06f, camo, (i, j) => P.Underside, spanSteps: 12, chordSteps: 4);// Wing roundel near the tip, on top and below.var rp = w.MultiplyPoint3x4(V(semi * 0.66f, 0.12f, -0.15f));Roundel(m, TRS(rp, V(0, 0, side * 6f), Vector3.one), 0.62f);- Roundel(m, TRS(rp - V(0, 0.24f, 0), V(0, 0, side * 6f), Vector3.one), 0.62f);+ Roundel(m, TRS(rp - V(0, 0.24f, 0), V(0, 0, side * 6f), V(1f, -1f, 1f)), 0.62f); // underneath: stacked downwards// Tailplane: small ellipses.var tp = TRS(V(side * 0.2f, 0.1f, -5.6f), Vector3.zero, V(side, 1f, 1f));m.Wing(tp, s => 0.45f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.02f, s => 0.55f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.02f,- 1.55f, 0.05f, (i, j) => (i + j) % 3 == 0 ? P.CamoGreen : P.CamoGrey, P.Underside, spanSteps: 5, chordSteps: 2);+ 1.55f, 0.05f, (i, j) => (i + j) % 3 == 0 ? P.CamoGreen : P.CamoGrey, (i, j) => P.Underside, spanSteps: 5, chordSteps: 2);// Fuselage roundel.Roundel(m, TRS(V(side * 0.58f, 0.15f, -2.6f), V(0, 0, side * 90f), Vector3.one), 0.48f);// Radiator under each wing.m.Box(TRS(V(side * 1.7f, -0.62f, 0.0f), Vector3.zero, V(0.42f, 0.28f, 1.3f)), P.Underside);}- // Fin and rudder: the elliptic Spitfire fin, a vertical surface.+ // Fin and rudder: the elliptic Spitfire fin, a vertical surface; the rear half (the rudder) striped red and white on+ // both sides. The stripes' direction is not in the sources; they are drawn across the rudder.+ System.Func<int, int, int> fin = (i, j) => j == 0 ? (i % 2 == 0 ? P.CamoGreen : P.CamoGrey) : (i % 2 == 0 ? P.MarkingRed : P.RoundelWhite);m.Wing(TRS(V(0, 0.4f, -5.5f), V(0, 0, 90f), Vector3.one), s => 0.55f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.05f,- s => 0.75f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.05f, 1.55f, 0.05f, (i, j) => i % 2 == 0 ? P.CamoGreen : P.CamoGrey, P.CamoGrey,- spanSteps: 5, chordSteps: 2);- return m.Build(name);+ s => 0.75f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.05f, 1.55f, 0.05f, fin, fin, spanSteps: 5, chordSteps: 2);+ return m.Build(name, AircraftShade);}/// <summary>The Spitfire's four-blade propeller, centred on its hub; turns about +Z. Placed at@@ -161,19 +165,22 @@ namespace Statecraft.Game.Map.Unitsfor (int b = 0; b < 4; b++){var dir = Quaternion.Euler(0, 0, 90f * b + 20f) * Vector3.up;- m.Rod(dir * 0.2f, dir * 1.6f, 0.13f, 0.08f, P.PropBlack, segments: 5, shade: 0.8f);+ m.Rod(dir * 0.2f, dir * 1.6f, 0.13f, 0.08f, P.PropBlack, segments: 5);}- return m.Build(name);+ return m.Build(name, AircraftShade);}public static readonly Vector3 SpitfirePropellerHub = new Vector3(0f, 0.02f, 3.55f);- /// <summary>The early IAF roundel: a blue ring, a white disc and a blue six-pointed star of two triangles, stacked a- /// hair apart so they never z-fight; its plane is the local XZ, facing +Y.</summary>+ /// <summary>The aircraft's one shade row: the palette's base colour, a touch under its top highlight.</summary>+ public const float AircraftShade = 0.72f;++ /// <summary>The IAF roundel of 1948-49: a white disc and a blue six-pointed star of two triangles whose points stay+ /// clear of the disc's edge, with no outer ring (the ring is a 1950s Mosquito and Meteor marking; FOTW, citing Born+ /// in Battle). Stacked a hair apart so they never z-fight; its plane is the local XZ, facing +Y.</summary>static void Roundel(MiniatureMesh m, Matrix4x4 at, float radius){- m.Plate(at, Circle(radius, 20), P.RoundelBlue, shade: 0.8f);- m.Plate(at * T(0, 0.012f, 0), Circle(radius * 0.86f, 20), P.RoundelWhite, shade: 0.8f);+ m.Plate(at, Circle(radius, 20), P.RoundelWhite, shade: 0.8f);for (int k = 0; k < 2; k++){var tri = new List<Vector2>();@@ -182,7 +189,7 @@ namespace Statecraft.Game.Map.Unitsfloat a = Mathf.Deg2Rad * (90f + 60f * k + 120f * i);tri.Add(new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * radius * 0.74f);}- m.Plate(at * T(0, 0.024f + 0.002f * k, 0), tri, P.RoundelBlue, shade: 0.8f);+ m.Plate(at * T(0, 0.012f + 0.002f * k, 0), tri, P.RoundelBlue, shade: 0.8f);}}@@ -194,14 +201,14 @@ namespace Statecraft.Game.Map.Units}/// <summary>A modified Flower-class corvette as the Israeli Navy commissioned it in 1948 (INS Haganah, K-20, ex-HMCS- /// Norsyd; sources in docs/units.md): a 62.5 m hull with a raised forecastle, a bridge, one tall funnel, a mast and a+ /// Norsyd; sources in docs/units.md): a 63.4 m (208 ft) hull with a raised forecastle, a bridge, one tall funnel, a mast and a/// single gun forward. Origin at the waterline amidships, bow towards +Z.</summary>public static Mesh Corvette(string name){var m = new MiniatureMesh();// Hull: a lathe along Z, flattened into a hull section, its keel below the waterline (hidden by the sea).- var hull = new List<Vector2> { new Vector2(-31f, 1.2f), new Vector2(-26f, 4.2f), new Vector2(-10f, 5.0f), new Vector2(8f, 5.0f),- new Vector2(20f, 4.0f), new Vector2(28f, 2.0f), new Vector2(31.2f, 0.2f) };+ var hull = new List<Vector2> { new Vector2(-31.7f, 1.2f), new Vector2(-26f, 4.2f), new Vector2(-10f, 5.0f), new Vector2(8f, 5.0f),+ new Vector2(20f, 4.0f), new Vector2(28.5f, 2.0f), new Vector2(31.7f, 0.2f) };m.Lathe(TRS(V(0, 0.6f, 0), V(90f, 0, 0), V(1f, 1f, 0.95f)), hull, P.HullGrey, 14, shade: 0.75f);m.Lathe(TRS(V(0, -0.2f, 0), V(90f, 0, 0), V(1.01f, 1f, 0.55f)), hull, P.Waterline, 14, shade: 0.5f);// Decks: main deck and raised forecastle.diff --git a/unity/Assets/Scripts/Map/Units/UnitPalette.cs b/unity/Assets/Scripts/Map/Units/UnitPalette.csindex dcb31ae36..83fb953ae 100644--- a/unity/Assets/Scripts/Map/Units/UnitPalette.cs+++ b/unity/Assets/Scripts/Map/Units/UnitPalette.cs@@ -3,17 +3,19 @@ using UnityEngine;namespace Statecraft.Game.Map.Units{- /// <summary>The paint pots of the unit miniatures: one column per slot, one row per shade. The colours follow the- /// references cited in docs/units.md (1948 IDF khaki drill and British 37-pattern webbing; RAF day-fighter camouflage on- /// the Czech-supplied Spitfire LF.IX; the early IAF roundel; Royal Canadian Navy grey on the ex-RCN corvettes), pushed- /// a little warmer and lighter than the photographs so they read at map scale under the warm grade, as the promo's- /// painted figures do. The texture is made at runtime (no file ships), owned by the map.</summary>+ /// <summary>The paint pots of the unit miniatures: one column per slot, one row per shade. Sources are in docs/units.md:+ /// 1948 IDF khaki drill and British 37-pattern webbing (photographs); the IAF roundel (a blue star on a white disc);+ /// 101 Squadron's red spinner and red-and-white rudder (two hobby sources agree). The Spitfire's RAF day-fighter colours+ /// (ocean grey and dark green over medium sea grey) have a single hobby source and are unverified; a forum report of a+ /// brown overpaint in theatre is an open question. The corvette's light grey follows its 1948 photograph. Colours are+ /// pushed a little warmer and lighter than the photographs so they read at map scale under the warm grade, as the+ /// promo's painted figures do. The texture is made at runtime (no file ships), owned by the showcase.</summary>public static class UnitPalette{public const int Skin = 0, Shirt = 1, Trousers = 2, Webbing = 3, Helmet = 4, SlouchHat = 5, WoolCap = 6, Boots = 7,RifleWood = 8, RifleMetal = 9, Hair = 10, ShirtFaded = 11,CamoGrey = 12, CamoGreen = 13, Underside = 14, RoundelWhite = 15, RoundelBlue = 16, PropBlack = 17, Glass = 18,- HullGrey = 19, Deck = 20, Waterline = 21, Funnel = 22, Count = 23;+ HullGrey = 19, Deck = 20, Waterline = 21, Funnel = 22, MarkingRed = 23, Count = 24;/// <summary>Texels per slot along u: the sample at a slot's centre never reaches its neighbours (bilinear, no mips).</summary>public const int SlotWidth = 4, Rows = 32;@@ -43,10 +45,9 @@ namespace Statecraft.Game.Map.Unitsnew Color(0.48f, 0.46f, 0.42f), // Decknew Color(0.12f, 0.12f, 0.13f), // Waterlinenew Color(0.30f, 0.31f, 0.32f), // Funnel top+ new Color(0.72f, 0.12f, 0.10f), // MarkingRed: 101 Squadron's spinner and rudder stripes};- public static Color Colour(int slot) => Base[slot];-/// <summary>u of a slot's column centre.</summary>public static float U(int slot) => (slot * SlotWidth + SlotWidth * 0.5f) / (Count * SlotWidth);@@ -61,7 +62,9 @@ namespace Statecraft.Game.Map.Unitsreturn Color.Lerp(shaded, dust * 0.8f, 0.25f * (1f - Mathf.SmoothStep(0f, 0.12f, v)));}- public static Texture2D MakeTexture()+ /// <summary>The palette texture. <paramref name="readable"/> false frees its CPU copy after the upload (the runtime+ /// path; tests read the pixels back).</summary>+ public static Texture2D MakeTexture(bool readable = true){int w = Count * SlotWidth;var tex = new Texture2D(w, Rows, TextureFormat.RGBA32, false, false)@@ -73,7 +76,7 @@ namespace Statecraft.Game.Map.Unitsvar c = Shade(x / SlotWidth, (y + 0.5f) / Rows); c.a = 1f;px[y * w + x] = c;}- tex.SetPixels(px); tex.Apply(false, false);+ tex.SetPixels(px); tex.Apply(false, !readable);return tex;}}diff --git a/unity/Assets/Scripts/Map/Units/UnitShowcase.cs b/unity/Assets/Scripts/Map/Units/UnitShowcase.csindex 9c50cf9e6..27654f103 100644--- a/unity/Assets/Scripts/Map/Units/UnitShowcase.cs+++ b/unity/Assets/Scripts/Map/Units/UnitShowcase.cs@@ -24,7 +24,7 @@ namespace Statecraft.Game.Map.Units/// the aircraft and the ship are sized against him, as Civ draws them, not against each other.</summary>public const float FigureScale = 2000f;public const float AircraftScale = 420f; // span 11.2 m x 420 = 4.7 km: wider than a man is tall- public const float ShipScale = 95f; // 62.5 m x 95 = 5.9 km: about a hex, like the promo's boats+ public const float ShipScale = 95f; // 63.4 m x 95 = 6.0 km: about a hex, like the promo's boats/// <summary>Trio spacing and the ring, as fractions of the hex circumradius.</summary>public const float TrioSpread = 0.40f, RingRadius = 0.66f, RingWidth = 0.035f, RingClearanceM = 25f;/// <summary>The flight: a circle of <see cref="LoopRadiusM"/> about <see cref="LoopCentre"/>, at@@ -44,74 +44,121 @@ namespace Statecraft.Game.Map.Unitspublic static bool Requested() =>Requested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);+ /// <summary>Only "units" (WebGL URL) or -units (desktop) asks for it. A plain "shot" does not (controller ruling,+ /// 2026-10-11): every track's checkpoint metrics stay comparable, and the units' checkpoint adds the flag+ /// (tools/art_checkpoint.sh --units).</summary>public static bool Requested(string? url, string[] args, bool webgl) =>- webgl ? UrlFlags.Has(url, "units") || UrlFlags.Has(url, "shot") : args.Contains("-units") || args.Contains("-shot");+ webgl ? UrlFlags.Has(url, "units") : args.Contains("-units");/// <summary>True when the flight should hold its still phase (screenshots: the same image every run).</summary>public static bool StillRequested(string? url, string[] args, bool webgl) =>webgl ? UrlFlags.Has(url, "shot") : args.Contains("-shot");- /// <summary>Builds the showcase under the map's terrain (so a map rebuild destroys it), its meshes, palette and- /// materials owned by the terrain's MapRuntimeAssets, and registers the "units" toggle through its teardown.- /// <paramref name="still"/> freezes the flight at <see cref="StillPhase"/>. Returns the root.</summary>+ /// <summary>The art hook (owner ruling, 2026-10-11): promo-quality close-zoom models come from a separate AI-3D track,+ /// and the code-built models stay as the far-zoom and fallback version. A prefab at+ /// Resources/<see cref="AuthoredFolder"/><unit type> replaces the code-built model of that type. It follows the+ /// same convention: real metres, facing +Z, origin on the ground (an aircraft: its centre of gravity), with its own+ /// materials; an authored aircraft brings its own propeller. Without one, the code-built mesh is used. Unit types:+ /// the <c>*Type</c> constants below.</summary>+ public const string AuthoredFolder = "Units/Authored/";+ public const string RiflemanSlouchHatType = "rifleman-1948-slouch-hat", RiflemanHelmetType = "rifleman-1948-steel-helmet",+ RiflemanWoolCapType = "rifleman-1948-wool-cap", SpitfireType = "spitfire-mk9e-101sqn-1948", CorvetteType = "corvette-k20-1948";++ /// <summary>Finds an authored model for a unit type, or null (a seam: tests replace it).</summary>+ internal static Func<string, GameObject?> AuthoredModel = type => Resources.Load<GameObject>(AuthoredFolder + type);++ /// <summary>Builds the showcase under the map's terrain (so a map rebuild destroys it). Its meshes, palette and+ /// material are owned by the showcase root's own MapRuntimeAssets, so destroying the root (a re-spawn or a map+ /// rebuild) frees them, and the "units" toggle is registered through that teardown. The trio stands on the centre of+ /// the hex nearest <see cref="TrioAt"/>. <paramref name="still"/> freezes the flight at <see cref="StillPhase"/>.+ /// Returns the root.</summary>public static GameObject Spawn(MapScene map, bool still){if (map == null || map.Terrain == null || map.Hexes == null) throw new InvalidOperationException("UnitShowcase needs a built map");var terrain = map.Terrain;- var assets = terrain.GetComponent<MapRuntimeAssets>();var old = terrain.transform.Find(RootName);- if (old != null) { if (Application.isPlaying) UnityEngine.Object.Destroy(old.gameObject); else UnityEngine.Object.DestroyImmediate(old.gameObject); }+ if (old != null)+ {+ foreach (var a in old.GetComponentsInChildren<MapRuntimeAssets>(true)) a.RunTeardown();+ old.SetParent(null);+ if (Application.isPlaying) UnityEngine.Object.Destroy(old.gameObject); else UnityEngine.Object.DestroyImmediate(old.gameObject);+ }var template = Resources.Load<Material>(UnitMaterials.MiniatureResource)- ?? throw new InvalidOperationException($"Resources/{UnitMaterials.MiniatureResource}.mat is missing (run UnitMaterials.Create)");+ ?? throw new InvalidOperationException($"Resources/{UnitMaterials.MiniatureResource}.mat is missing (run UnitMaterialAssets.Create)");var ringTemplate = Resources.Load<Material>(UnitMaterials.RingResource)- ?? throw new InvalidOperationException($"Resources/{UnitMaterials.RingResource}.mat is missing (run UnitMaterials.Create)");- var palette = assets.Own(UnitPalette.MakeTexture());- var paint = assets.Own(new Material(template) { name = "UnitMiniature (palette)" });- paint.SetTexture("_BaseMap", palette);+ ?? throw new InvalidOperationException($"Resources/{UnitMaterials.RingResource}.mat is missing (run UnitMaterialAssets.Create)");var root = new GameObject(RootName);root.transform.SetParent(terrain.transform, false);root.transform.position = Vector3.zero; // children are placed in world space+ var assets = root.AddComponent<MapRuntimeAssets>();+ var palette = assets.Own(UnitPalette.MakeTexture(readable: false));+ var paint = assets.Own(new Material(template) { name = "UnitMiniature (palette)" });+ paint.SetTexture("_BaseMap", palette);+ Mesh Built(Mesh m) { assets.Own(m); m.UploadMeshData(true); return m; } // no CPU copy kept in playersfloat hex = map.Hexes.hex_size_km * 1000f;- // The trio: three riflemen in a loose triangle facing the camera's side of south-west, on the hex's centre.- var centre = Ground(map, map.Frame.ToWorld(TrioAt.lon, TrioAt.lat, 0));+ // The trio: three riflemen in a loose triangle facing the camera's side of south-west, around the hex's centre.+ var centre = HexCentreNear(map, TrioAt.lon, TrioAt.lat);var looks = new[]{- (UnitModels.Headgear.SlouchHat, UnitModels.RiflePose.Ready, false, new Vector2(-0.62f, -0.30f), 200f),- (UnitModels.Headgear.SteelHelmet, UnitModels.RiflePose.Grounded, true, new Vector2(0.05f, 0.05f), 185f),- (UnitModels.Headgear.WoolCap, UnitModels.RiflePose.Slung, false, new Vector2(0.66f, -0.40f), 170f),+ (RiflemanSlouchHatType, UnitModels.Headgear.SlouchHat, UnitModels.RiflePose.Ready, false, new Vector2(-0.62f, -0.30f), 200f),+ (RiflemanHelmetType, UnitModels.Headgear.SteelHelmet, UnitModels.RiflePose.Grounded, true, new Vector2(0.05f, 0.05f), 185f),+ (RiflemanWoolCapType, UnitModels.Headgear.WoolCap, UnitModels.RiflePose.Slung, false, new Vector2(0.66f, -0.40f), 170f),};for (int i = 0; i < looks.Length; i++){- var (hat, pose, faded, offset, heading) = looks[i];- var mesh = assets.Own(UnitModels.Rifleman(hat, pose, faded, $"Rifleman1948-{i}"));+ var (type, hat, pose, faded, offset, heading) = looks[i];var p = Ground(map, centre + new Vector3(offset.x, 0, offset.y) * TrioSpread * hex);- Piece(root.transform, $"Rifleman{i}", mesh, paint, p, Quaternion.Euler(0, heading, 0), FigureScale);+ Piece(root.transform, $"Rifleman{i}", type, () => Built(UnitModels.Rifleman(hat, pose, faded, $"Rifleman1948-{i}")),+ paint, p, Quaternion.Euler(0, heading, 0), FigureScale);}Ring(map, assets, ringTemplate, root.transform, centre, RingRadius * hex);- // The aircraft and its propeller.+ // The aircraft and, when code-built, its propeller.var plane = new GameObject("Spitfire1948");plane.transform.SetParent(root.transform, false);- var body = Piece(plane.transform, "Airframe", assets.Own(UnitModels.Spitfire("Spitfire1948")), paint, Vector3.zero, Quaternion.identity, 1f);- body.transform.localPosition = Vector3.zero;- var prop = Piece(plane.transform, "Propeller", assets.Own(UnitModels.SpitfirePropeller("SpitfirePropeller")), paint, Vector3.zero, Quaternion.identity, 1f);- prop.transform.localPosition = UnitModels.SpitfirePropellerHub;+ Piece(plane.transform, "Airframe", SpitfireType, () => Built(UnitModels.Spitfire("Spitfire1948")), paint,+ Vector3.zero, Quaternion.identity, 1f, out bool authoredAircraft);+ Transform? prop = null;+ if (!authoredAircraft)+ {+ prop = Piece(plane.transform, "Propeller", Built(UnitModels.SpitfirePropeller("SpitfirePropeller")), paint, Vector3.zero, Quaternion.identity, 1f).transform;+ prop.localPosition = UnitModels.SpitfirePropellerHub;+ }plane.transform.localScale = Vector3.one * AircraftScale;var loopCentre = map.Frame.ToWorld(LoopCentre.lon, LoopCentre.lat, 0);var flight = plane.AddComponent<ShowcaseFlight>();- flight.Configure(loopCentre, LoopRadiusM, LoopFloor(map, loopCentre, LoopRadiusM) + AltitudeM, LoopSeconds, BankDegrees, prop.transform, still ? StillPhase : (float?)null);+ flight.Configure(loopCentre, LoopRadiusM, LoopFloor(map, loopCentre, LoopRadiusM) + AltitudeM, LoopSeconds, BankDegrees, prop, still ? StillPhase : (float?)null);// The corvette, at the sea surface.var ship = Ground(map, map.Frame.ToWorld(ShipAt.lon, ShipAt.lat, 0));- Piece(root.transform, "Corvette1948", assets.Own(UnitModels.Corvette("CorvetteK20")), paint, ship, Quaternion.Euler(0, ShipHeadingDegrees, 0), ShipScale);+ Piece(root.transform, "Corvette1948", CorvetteType, () => Built(UnitModels.Corvette("CorvetteK20")), paint, ship,+ Quaternion.Euler(0, ShipHeadingDegrees, 0), ShipScale);assets.OnTeardown(VisualToggles.Register(ToggleName, on => { if (root != null) root.SetActive(on); }));return root;}+ /// <summary>One unit model: the authored prefab for <paramref name="type"/> when there is one (the art hook),+ /// otherwise the code-built mesh.</summary>+ static GameObject Piece(Transform parent, string name, string type, Func<Mesh> codeBuilt, Material paint, Vector3 position,+ Quaternion rotation, float scale) => Piece(parent, name, type, codeBuilt, paint, position, rotation, scale, out _);++ static GameObject Piece(Transform parent, string name, string type, Func<Mesh> codeBuilt, Material paint, Vector3 position,+ Quaternion rotation, float scale, out bool authored)+ {+ var prefab = AuthoredModel(type);+ authored = prefab != null;+ if (prefab == null) return Piece(parent, name, codeBuilt(), paint, position, rotation, scale);+ var go = UnityEngine.Object.Instantiate(prefab, parent, false);+ go.name = name;+ go.transform.SetPositionAndRotation(position, rotation);+ go.transform.localScale = Vector3.one * scale;+ return go;+ }+static GameObject Piece(Transform parent, string name, Mesh mesh, Material mat, Vector3 position, Quaternion rotation, float scale){var go = new GameObject(name);@@ -123,6 +170,21 @@ namespace Statecraft.Game.Map.Unitsreturn go;}+ /// <summary>The ground point at the centre of the map hex nearest (<paramref name="lon"/>, <paramref name="lat"/>),+ /// from hexes.json (as MapScene.Select places its outline), so a unit stands in one hex.</summary>+ public static Vector3 HexCentreNear(MapScene map, double lon, double lat)+ {+ var want = map.Frame.ToWorld(lon, lat, 0);+ Vector3 best = want; float bestD = float.MaxValue;+ foreach (var h in map.Hexes.hexes)+ {+ var c = map.Frame.ToWorld(h.lon, h.lat, 0);+ float d = (c.x - want.x) * (c.x - want.x) + (c.z - want.z) * (c.z - want.z);+ if (d < bestD) { bestD = d; best = c; }+ }+ return Ground(map, best);+ }+/// <summary>The point on the terrain under <paramref name="p"/> (world x, z).</summary>public static Vector3 Ground(MapScene map, Vector3 p){@@ -144,17 +206,24 @@ namespace Statecraft.Game.Map.Units}/// <summary>The selection ring: a thin flat band on the ground around the trio, drawn with the hex selection's- /// unlit ivory and depth offset (the promo's white ring), each vertex lifted to the ground under it.</summary>+ /// unlit ivory and depth offset (the promo's white ring). Each vertex sits <see cref="RingClearanceM"/> above the+ /// highest ground sampled across the band at its own angle and halfway to each neighbour, so a ridge between two+ /// vertices cannot rise through the straight edge between them (MapBuilder.DrapedRing's rule).</summary>static void Ring(MapScene map, MapRuntimeAssets assets, Material ringTemplate, Transform parent, Vector3 centre, float radius){const int n = 96;var verts = new List<Vector3>(2 * n); var tris = new List<int>(6 * n);float w = RingWidth * radius / RingRadius;+ float Across(float step)+ {+ float a = 2f * Mathf.PI * step / n; var d = new Vector3(Mathf.Cos(a), 0, Mathf.Sin(a));+ return Mathf.Max(Ground(map, centre + d * (radius + w / 2)).y, Ground(map, centre + d * (radius - w / 2)).y);+ }for (int i = 0; i < n; i++){float a = 2f * Mathf.PI * i / n; var d = new Vector3(Mathf.Cos(a), 0, Mathf.Sin(a));- var outer = Ground(map, centre + d * (radius + w / 2)); var inner = Ground(map, centre + d * (radius - w / 2));- float y = Mathf.Max(outer.y, inner.y) + RingClearanceM;+ float y = Mathf.Max(Across(i), Mathf.Max(Across(i - 0.5f), Across(i + 0.5f))) + RingClearanceM;+ var outer = centre + d * (radius + w / 2); var inner = centre + d * (radius - w / 2);outer.y = y; inner.y = y;verts.Add(outer); verts.Add(inner);}@@ -164,7 +233,7 @@ namespace Statecraft.Game.Map.Unitstris.AddRange(new[] { a, b, a + 1, a + 1, b, b + 1 }); // the ring shader draws both faces}var mesh = assets.Own(new Mesh { name = "UnitSelectionRing" });- mesh.SetVertices(verts); mesh.SetTriangles(tris, 0); mesh.RecalculateBounds();+ mesh.SetVertices(verts); mesh.SetTriangles(tris, 0); mesh.RecalculateBounds(); mesh.UploadMeshData(true);var go = new GameObject("SelectionRing");go.transform.SetParent(parent, false);go.AddComponent<MeshFilter>().sharedMesh = mesh;diff --git a/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs b/unity/Assets/Tests/EditMode/UnitShowcaseTests.csindex 317e52c6f..91fe2a749 100644--- a/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs+++ b/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs@@ -1,3 +1,4 @@+using System.Collections.Generic;using System.Linq;using NUnit.Framework;using Statecraft.Game.Map;@@ -17,16 +18,17 @@ public class UnitShowcaseTests};[Test]- public void ShowcaseIsAskedForOnlyByUnitsOrShot()+ public void ShowcaseIsAskedForOnlyByUnits(){Assert.IsTrue(UnitShowcase.Requested("https://x/index.html?units", new string[0], true));- Assert.IsTrue(UnitShowcase.Requested("https://x/index.html?golden&shot", new string[0], true));+ Assert.IsTrue(UnitShowcase.Requested("https://x/index.html?golden&shot&units", new string[0], true));+ Assert.IsFalse(UnitShowcase.Requested("https://x/index.html?golden&shot", new string[0], true), "a plain ?shot stays comparable across tracks");Assert.IsFalse(UnitShowcase.Requested("https://x/index.html?golden&smoke=5", new string[0], true));Assert.IsFalse(UnitShowcase.Requested("https://x/index.html?vprofile", new string[0], true), "profiles price it only with &units");Assert.IsFalse(UnitShowcase.Requested("https://x/units/index.html?unitsx", new string[0], true));Assert.IsTrue(UnitShowcase.Requested(null, new[] { "player", "-units" }, false));- Assert.IsFalse(UnitShowcase.Requested(null, new[] { "player" }, false));- Assert.IsTrue(UnitShowcase.StillRequested("https://x/?shot", new string[0], true));+ Assert.IsFalse(UnitShowcase.Requested(null, new[] { "player", "-shot" }, false));+ Assert.IsTrue(UnitShowcase.StillRequested("https://x/?shot&units", new string[0], true));Assert.IsFalse(UnitShowcase.StillRequested("https://x/?units", new string[0], true));}@@ -67,6 +69,32 @@ public class UnitShowcaseTests}}+ /// <summary>The builders' normals point out of each solid (the winding test above only checks Build against the+ /// normals, so it cannot catch an inside-out builder). Convex parts, placed by rotated, scaled and mirrored matrices.</summary>+ [Test]+ public void BuilderNormalsPointOutwards()+ {+ var at = Matrix4x4.TRS(new Vector3(3, 1, -2), Quaternion.Euler(20, 35, -10), new Vector3(1.5f, 0.6f, 2f));+ var mirrored = Matrix4x4.TRS(new Vector3(-4, 0, 1), Quaternion.Euler(0, 0, 6), new Vector3(-1f, 1f, 1f));+ var parts = new (string name, MiniatureMesh mesh, Vector3 centre)[]+ {+ ("ellipsoid", new MiniatureMesh().Ellipsoid(at, 0), at.MultiplyPoint3x4(Vector3.zero)),+ ("mirrored ellipsoid", new MiniatureMesh().Ellipsoid(mirrored, 0), mirrored.MultiplyPoint3x4(Vector3.zero)),+ ("capped cone", new MiniatureMesh().Lathe(at, new[] { new Vector2(0f, 1f), new Vector2(2f, 0.4f) }, 0), at.MultiplyPoint3x4(new Vector3(0, 1f, 0))),+ ("tapered rod", new MiniatureMesh().Rod(new Vector3(0, 0, 0), new Vector3(1, 2, 0.5f), 0.3f, 0.2f, 0), new Vector3(0.5f, 1f, 0.25f)),+ ("box", new MiniatureMesh().Box(at, 0), at.MultiplyPoint3x4(Vector3.zero)),+ };+ foreach (var (name, builder, centre) in parts)+ {+ var mesh = builder.Build(name);+ var v = mesh.vertices; var n = mesh.normals;+ int inward = 0;+ for (int i = 0; i < v.Length; i++) if (Vector3.Dot(n[i], v[i] - centre) < -1e-4f) inward++;+ Assert.AreEqual(0, inward, $"{name}: {inward} of {v.Length} normals point inwards");+ Object.DestroyImmediate(mesh);+ }+ }+[Test]public void RiflemanStandsOnTheOriginAtAMansHeight(){@@ -112,13 +140,30 @@ public class UnitShowcaseTestsfinally { Object.DestroyImmediate(go); Object.DestroyImmediate(prop); }}- [Test]- public void SpawnBuildsTheSliceAtGameplay03AndTheToggleHidesIt()+ static MapScene BuildMap(){EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);var map = new GameObject("MapScene").AddComponent<MapScene>();map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("BorderLand"));map.Build();+ return map;+ }++ /// <summary>Everything a spawn made that must be freed with it: meshes, the palette material and its texture.</summary>+ static List<Object> SpawnedAssets(GameObject root)+ {+ var list = new List<Object>();+ foreach (var f in root.GetComponentsInChildren<MeshFilter>(true)) list.Add(f.sharedMesh);+ var paint = root.transform.Find("Rifleman0").GetComponent<MeshRenderer>().sharedMaterial;+ list.Add(paint); list.Add(paint.GetTexture("_BaseMap"));+ Assert.IsTrue(list.All(o => o != null));+ return list;+ }++ [Test]+ public void SpawnBuildsTheSliceAtGameplay03AndTheToggleHidesIt()+ {+ var map = BuildMap();try{var root = UnitShowcase.Spawn(map, still: true);@@ -126,6 +171,7 @@ public class UnitShowcaseTestsAssert.AreEqual(3, root.GetComponentsInChildren<MeshFilter>().Count(f => f.name.StartsWith("Rifleman")));Assert.IsNotNull(root.transform.Find("SelectionRing"));Assert.IsNotNull(root.transform.Find("Corvette1948"));+ Assert.IsNotNull(root.transform.Find("Spitfire1948/Propeller"));var plane = root.GetComponentInChildren<ShowcaseFlight>();Assert.AreEqual(UnitShowcase.StillPhase, plane.StillPhase);// Each figure stands on the ground under it.@@ -147,14 +193,68 @@ public class UnitShowcaseTestsAssert.IsFalse(root.activeSelf);VisualToggles.Set(UnitShowcase.ToggleName, true);Assert.IsTrue(root.activeSelf);- // A second spawn replaces the first rather than stacking.+ // A second spawn replaces the first rather than stacking, and frees the first one's assets.+ var first = SpawnedAssets(root);UnitShowcase.Spawn(map, still: true);int count = 0; foreach (Transform c in map.Terrain.transform) if (c.name == UnitShowcase.RootName) count++;Assert.AreEqual(1, count);+ Assert.IsTrue(first.All(o => o == null), "the replaced spawn's meshes, material and palette are destroyed");+ CollectionAssert.Contains(VisualToggles.Names, UnitShowcase.ToggleName, "the new spawn keeps its switch");}finally { Object.DestroyImmediate(map.gameObject); }CollectionAssert.DoesNotContain(VisualToggles.Names, UnitShowcase.ToggleName, "the map's teardown removes the switch");}+ [Test]+ public void TheTrioStandsOnAHexCentreAndTheMapFreesTheSlice()+ {+ var map = BuildMap();+ List<Object> assets;+ try+ {+ var root = UnitShowcase.Spawn(map, still: true);+ var ring = root.transform.Find("SelectionRing").GetComponent<Renderer>().bounds.center;+ float nearest = float.MaxValue;+ foreach (var h in map.Hexes.hexes)+ {+ var c = map.Frame.ToWorld(h.lon, h.lat, 0);+ nearest = Mathf.Min(nearest, new Vector2(c.x - ring.x, c.z - ring.z).magnitude);+ }+ Assert.Less(nearest, 50f, "the ring (and the trio inside it) is centred on a hex");+ // The ring fits inside its hex: its outer edge is short of the hex's inscribed circle.+ float hex = map.Hexes.hex_size_km * 1000f;+ Assert.Less(UnitShowcase.RingRadius * hex * (1f + UnitShowcase.RingWidth), hex * Mathf.Sqrt(3f) / 2f);+ assets = SpawnedAssets(root);+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ Assert.IsTrue(assets.All(o => o == null), "destroying the map destroys every mesh, the material and the palette");+ }++ [Test]+ public void AnAuthoredModelReplacesTheCodeBuiltOneForItsType()+ {+ var map = BuildMap(); // first: a new scene would destroy the stand-in models+ var helmet = new GameObject("authored-helmet"); new GameObject("AuthoredMarker").transform.SetParent(helmet.transform);+ var spitfire = new GameObject("authored-spitfire"); new GameObject("AuthoredMarker").transform.SetParent(spitfire.transform);+ var saved = UnitShowcase.AuthoredModel;+ UnitShowcase.AuthoredModel = type => type == UnitShowcase.RiflemanHelmetType ? helmet : type == UnitShowcase.SpitfireType ? spitfire : null;+ try+ {+ var root = UnitShowcase.Spawn(map, still: true);+ Assert.IsNotNull(root.transform.Find("Rifleman1/AuthoredMarker"), "the helmet rifleman is the authored model");+ Assert.IsNull(root.transform.Find("Rifleman1").GetComponent<MeshFilter>(), "no code-built mesh for it");+ Assert.IsNotNull(root.transform.Find("Rifleman0").GetComponent<MeshFilter>(), "the others stay code-built");+ Assert.AreEqual(UnitShowcase.FigureScale, root.transform.Find("Rifleman1").localScale.x, 1e-3f, "placed and scaled as the code-built one");+ Assert.IsNotNull(root.transform.Find("Spitfire1948/Airframe/AuthoredMarker"));+ Assert.IsNull(root.transform.Find("Spitfire1948/Propeller"), "an authored aircraft brings its own propeller");+ Assert.IsNotNull(root.transform.Find("Corvette1948").GetComponent<MeshFilter>());+ }+ finally+ {+ UnitShowcase.AuthoredModel = saved;+ Object.DestroyImmediate(map.gameObject); Object.DestroyImmediate(helmet); Object.DestroyImmediate(spitfire);+ }+ }+static Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");}