A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: unit tokens on an earth plinth with a white rim and their side's flag, figures at 1400x (refs #197) (#559)
Eyal Golan732ceab8db41
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex afd00fbba..cf697b626 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -81,6 +81,13 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB`Train` borrow what the Treasury lacks, as map actions do. `mvp-slice` moves (the reference player builds Mefalsim by15 March 1949, and the golden now runs to that date); the legacy goldens and `scenario-mvp-absorb-first` do not.The Unity order queue (`SimBridge`) takes both orders, one per unit.+- Map: every army token stands as in demo2 T29: the figures shoulder to shoulder on a round, dark, mottled earth base+ built on the terrain's own triangles (it follows the ground on any hill, no mesa, no gap downhill), a bright white+ ring on the ground just outside it, and its side's flag, drawn unlit, on a pole at the base's back edge, turning about+ the pole to face the camera (owner, 15 October); the figures at 1400x, 1.8 times a block (owner, 14 October; refs+ #197). `units_1948.yaml` gives each unit a `side`; only Israel's flag is drawn, from the 1948 proclamation, and other+ sides fly none until a sourced flag exists. The showcase trio stands off the routes in a kit clearing. Aircraft and+ ships are unchanged.- Desktop release builds from the Mac (refs #54; Phases 0-1 of the plan in PR #482): `Build.LinuxMono` and`Build.WindowsMono` build the Linux and Windows x64 players on Mono (decisions O7, O8) and put the committed IL2CPPsetting back afterwards, anddiff --git a/content/map/units_1948.yaml b/content/map/units_1948.yamlindex 84c16beb4..66417ac0a 100644--- a/content/map/units_1948.yaml+++ b/content/map/units_1948.yaml@@ -30,6 +30,8 @@# Sword, 1961) or the IDF and Defense Establishment Archives. The card computes the same note per anchor.# headgear: the riflemen's headgear, only where a source ties it to the unit (otherwise the uniform default: bush hat,# steel helmet, bush hat; docs/units.md).+# side: whose formation it is: israel (every row here), or egypt, jordan, syria, iraq, lebanon (#226). The token flies+# that side's flag where the repo has a sourced one (Israel's only, for now; docs/units.md, "The plinth and the flag").# hidden: a unit the sources name but do not place; the map does not draw it (owner ruling, 2026-10-11).# status: draft = sourced and checked against the cited text, not yet by a historian.# reviewed_by and reviewed_on (both or neither, beside status): a person's sign-off, their GitHub handle and the day; only@@ -40,6 +42,7 @@ units:name: Golani Brigadenumber: 1st Brigadeservice: army+ side: israelformed: 22 February 1948first_commander: Moshe Mannsector: "Much of the Lower Galilee and the Jezreel Valley, the Jordan Valley and the Hula Valley; headquarters in Yavne'el. In December 1948 it moved to the southern front, at the Julis camp."@@ -77,6 +80,7 @@ units:name: Carmeli Brigadenumber: 2nd Brigadeservice: army+ side: israelformed: 22 February 1948sector: "The Haifa area and the Zevulun district, that is Haifa and the Western Galilee (split from the Levanoni Brigade in February 1948). It took Acre in Operation Ben-Ami (from 13 May 1948; Acre surrendered on the night of 17-18 May), led Operation Brosh against the Syrian bridgehead at Mishmar HaYarden (9-18 July 1948) and fought in Operation Hiram."wikipedia_only: false@@ -116,6 +120,7 @@ units:name: Alexandroni Brigadenumber: 3rd Brigadeservice: army+ side: israelformed: November 1947 (the Haganah's decision of 7 November)sector: "The Sharon region: from the Carmel in the north to the Dan bloc in the south; headquarters at Camp Dora in Netanya. In November 1948 it replaced the Givati Brigade at the Faluja pocket."wikipedia_only: false@@ -147,6 +152,7 @@ units:name: Kiryati Brigadenumber: 4th Brigadeservice: army+ side: israelformed: February 1948sector: "The urban area of Tel Aviv, from the Yarkon River in the north to Bat Yam in the south and Yazur in the east."wikipedia_only: false@@ -170,6 +176,7 @@ units:name: Givati Brigadenumber: 5th Brigadeservice: army+ side: israelformed: December 1947first_commander: Shimon Avidansector: "Moved to the south as the war entered its second stage, concentrated mainly around Gedera, Gan Yavne and Be'er Tuvia."@@ -195,6 +202,7 @@ units:name: Etzioni Brigadenumber: 6th Brigadeservice: army+ side: israelformed: Late 1947first_commander: Yisrael Amirsector: The defence of Jerusalem and its surroundings.@@ -226,6 +234,7 @@ units:name: 7th Brigadenumber: 7th Brigadeservice: army+ side: israelformed: 16 May 1948first_commander: Shlomo Shamirsector: "The battles of Latrun (Operation Bin Nun, 24 May to 1 June 1948), from the headquarters at Hulda; in June 1948 it moved to the northern front, organising for a time at Ein Shemer."@@ -261,6 +270,7 @@ units:name: 8th Brigadenumber: 8th Brigadeservice: army+ side: israelformed: 24 May 1948first_commander: Yitzhak Sadehsector: "The IDF's first armoured brigade: after its founding it trained at Tel Litvinsky (later Tel HaShomer); its first operation was Operation Dani in July 1948, then Yoav, Assaf and Horev in the south. Disbanded in April 1949."@@ -282,6 +292,7 @@ units:name: Oded Brigadenumber: 9th Brigadeservice: army+ side: israelsector: The sources conflict.wikipedia_only: falsestatus: draft@@ -299,6 +310,7 @@ units:name: Harel Brigadenumber: 10th Brigade (Palmach)service: army+ side: israelformed: 16 April 1948first_commander: Yitzhak Rabinsector: "All units in the Jerusalem corridor and hills; in the first half of May 1948 it took the corridor and opened the road to Sha'ar HaGai. Later it fought in Operation Horev."@@ -333,6 +345,7 @@ units:name: Yiftach Brigadenumber: 11th Brigade (Palmach)service: army+ side: israelformed: April 1948sector: "Formed from Palmach battalions of the Jezreel Valley and the eastern valleys; in July 1948 it fought in Operation Dani, which took Lydda and Ramle. Disbanded in May 1949."wikipedia_only: false@@ -358,6 +371,7 @@ units:name: Negev Brigadenumber: 12th Brigade (Palmach)service: army+ side: israelformed: March 1948first_commander: Nahum Sarigsector: "The Negev, in two sectors divided by the Beersheba-Gaza road; brigade headquarters at the Mekorot camp near Nir Am."@@ -386,6 +400,7 @@ units:name: 101 Squadronnumber: First Fighter Squadronservice: air+ side: israelformed: 20 May 1948first_commander: Modi Alonsector: "Formed at Ekron (the former RAF Aqir) in May 1948; first mission 29 May. It flew from a strip near Herzliya from mid-June, and from Hatzor from November 1948."@@ -455,6 +470,7 @@ units:name: INS Haganah (K-20)number: Corvette, commissioned 1948service: navy+ side: israelformed: 1948 (taken over and rearmed by the navy)sector: "Ex-HMCS Norsyd, a modified Flower-class corvette; as the Aliyah Bet ship Haganah it was moored in Haifa harbour until the state was founded, then taken over and rearmed by the navy in 1948."wikipedia_only: true@@ -476,6 +492,7 @@ units:name: INS Wedgwoodnumber: Corvette, commissioned 1948service: navy+ side: israelformed: 1948 (commissioned after independence)sector: "Ex-HMCS Beauharnois, a modified Flower-class corvette; impounded at Haifa until independence, then commissioned in the navy. It fought beside Haganah in Operation Yoav."wikipedia_only: truediff --git a/docs/units.md b/docs/units.mdindex 5403d896c..3ed23999e 100644--- a/docs/units.md+++ b/docs/units.md@@ -29,7 +29,8 @@ Code: `unity/Assets/Scripts/Map/Units/`. The materials are made by `UnitMaterial## Owner rulings (2026-10-11)-1. **Units are Civ-style tokens at about 2,000x real size** (see "Scale").+1. **Units are Civ-style tokens at symbolic scale** (see "Scale"). The 11 October ruling said about 2,000x; the owner's+ decision of 14 October supersedes it: figures at 1.8 times a block, as T29 (1,400x).2. **Promo-quality close-zoom models come from a separate track:** a cloud-GPU AI-3D pipeline (TRELLIS, MIT). Thecode-built miniatures here stay as the far-zoom and fallback version.@@ -193,19 +194,30 @@ checks every anchor and logs each spot and its distance.- **Air:** the squadron flies the slice's loop over its base at security level 4 or 5 and stands parked below that.- **Navy:** a ship is the K-20 corvette model; Wedgwood was the same modified Flower class.- **Badge:** each token has the promo's badge (`UnitBadge`): a dark rounded plate with an ivory glyph (two figures, an- aircraft or a ship). It is turned to face each camera as it renders.+ aircraft or a ship). It is turned to face each camera as it renders. On an army token it sits above the flag's top, a little+ behind the trio and to the side away from the flag's pole as that camera sees it (`UnitLayer.FaceCamera`; review of #559:+ it covered the middle figure's head once the trio stood shoulder to shoulder, and the flag now turns with the camera).+ The map's names keep clear of the badge and the flag where the camera draws them: `GameRoot` turns them to the labels'+ camera before the names are placed, and each token's keep-clear boxes follow (`UnitLayer.KeepClear`). A fixed box round+ every place the camera's yaw could take the badge, about 3.7 km across, pushed Tel Aviv's name off its kit at gameplay03+ (`MapLabelTests.PillsKeepClearOfTheUnitTokens`; test `TheKeepClearBoxesFollowTheBadgeAndTheFlagAsTheCameraTurns`).- **Ring:** the white ring appears only on selection.-- **Slopes (owner question, 2026-10-11).** Each rifleman stands on the highest ground under its boots- (`UnitShowcase.Stand`: the centre plus 48 points on three rings out to the boots' 400 m radius), so no boot sinks into- a hill. Where the ground under the boots falls more than 20 m, the figure stands on a base, as a painted miniature- does. The base is a disc of trodden earth (the palette's `Dust`) of the boots' radius, reaching down to the lowest ground, so the- downhill boot never floats.- - **Steepest spots:** the worst drop is about 0.6–1 km, against a 3.6 km figure, on the 3x relief of the Jerusalem- hills.- - **Tests:** `AFigureStandsOnASteepSlopeWithoutSinking` and `NoRiflemanSinksIntoTheHillsOfTheMap`.- - **Close-ups** (`MapCapture.Promo -units -extraPose …`, at 12 and 20 km): at 6 km the camera sees only boots.-- **Trees (#249).** The kit trees whose crowns reach a drawn figure's boots (its 400 m foot radius, which is also its- base's) are left out at draw time (`VegetationLayer.Hide`), so no orchard grows through a figure. Only the figures drawn+- **Base and flag (demo2 T29, refs #197).** An army token's figures stand shoulder to shoulder on one round earth base+ ringed by a bright white rim (`UnitPlinth`), and the side's flag flies on a pole at the base's back edge (`UnitFlags`).+ See "The base and the flag".+- **Slopes (owner question, 2026-10-11; rounds 3 and 4 of #559).** The base is draped on the terrain's own triangles:+ every heightmap cell under it (79 x 211 m) is split along the diagonal the terrain itself uses there and raised by the lip+ (`UnitPlinth.LipShare`, a twentieth of its radius, about 100 m), the cells at the edge clipped to a 96-sided outline with+ heights from the terrain's planes. So the top follows the ground exactly wherever a token stands, with no grid density+ to tune, and an edge lip of the same height, sampled every 40 m along the outline, closes it to the ground. On a hill it+ neither stands up as a mesa nor leaves a gap downhill. A figure stands on the top at its own point (an uphill boot sets+ into the base, which hides it).+ - **Tests:** `TheBaseFollowsTheGroundOnEveryHillHexOfTheMap` (every hill hex of the map, not only today's spots: the top+ within half the lip of the ground plus the lip, and the 99th percentile within a quarter),+ `TheBaseFollowsTheGroundOnEveryHillToken`, `EveryFigureStandsOnTheDrapedTop` and `NoRiflemanSinksIntoTheHillsOfTheMap`.+ The level discs before stood up to 1,081 m (round 1) or 707 m (round 2) over Harel's valley side; round 3's 32 x 96+ polar grid strayed up to 113 m on the map's hills.+- **Trees (#249).** The kit trees whose crowns reach a drawn token's base are left out at draw time (`VegetationLayer.Hide`), so no orchard grows through a figure. Only the figures drawnthat day clear trees, and they come back when the figure goes. With the `units` toggle off, as in a plain `?shot` run,every tree is drawn. The planting, and so the kits' layout, never changes. Tests:`NoKitTreeGrowsThroughAShownFiguresFeet` and `OnlyTheShownFiguresTreesGoAndTheToggleBringsThemBack`.@@ -295,14 +307,74 @@ which plugs authored models in through the art hook above.Measured 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, 6.0 km) are-sized against the figures, as Civ sizes them, not against each other.+drew our riflemen 113 px tall, so the first round used 2000x. The ring is at 0.66 of a hex's circumradius. The aircraft+(x420, a 4.7 km span) and the ship (x95, 6.0 km) are sized against the figures, as Civ sizes them, not against each other.-**Owner ruling (2026-10-11): units stay Civ-style tokens at about 2,000x.** This is far above the 10–25x ruling for+**Owner ruling (2026-10-11), superseded on 14 October (below): units stay Civ-style tokens at about 2,000x.** This is far above the 10–25x ruling forbuildings 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 strictscale by the owner's ruling, draws units as tokens. The scale is one constant.+**Owner decision (2026-10-14): figures at 1.8 times a block, as T29; it supersedes the 11 October ~2,000x ruling. 1,400x (refs #197).** T29's figures stand about 1.8 times a house. At 2000x ours+stood about 2.5 times the White City blocks beside the showcase trio at close30 (the T54 audit's measure). The block is the+kit's seven-storey heart block, 7 x 3.3 m at the city blocks' 60x, about 1.4 km; on the close30 render it measures about+1.3 km against the figure. So `UnitShowcase.FigureScale = 1400`: a man about 2.5 km tall, 1.8 times that block+(`UnitShowcase.HouseRatio`, pinned to 1.6–2.0 by `TheFiguresStandAbout1Point8TimesAHouse`). A one- or two-storey village+house (100x) is 0.33–0.66 km, so against those the figures still stand about 4–7 times as tall. The token's ring and its+spot are unchanged, so no unit moved; the figures are drawn closer together (below), inside the ground the placer checked.++## The base and the flag++Demo2 T29 (owner's reference) stands every unit on a round earth base ringed in bright white and flies the side's flag on+a pole. Measured on 4x crops of three of its tokens (the 1:12 frame): the base (the ring's outer edge) is 1.41, 1.62 and+1.71 times the trio's width; the trio is about 1.15 figure heights wide (shoulder to shoulder); the ring is about 8% of the+base's radius wide; the flag's cloth is 0.47–0.60 of a figure's height tall and 0.65–0.70 wide, on a pole about 1.5+figures tall standing at the base's back edge. `UnitPlinth` and `UnitFlags` draw the same from code:+- **Figures:** drawn at `UnitShowcase.DrawSpread` (0.19 of a hex's circumradius between neighbours), shoulder to+ shoulder, the trio about 1.15 figure heights wide. The placer still checks a spot at `TrioSpread`, so no spot moved.+ The showcase trio stands the same way.+- **Base:** one draped earth disc per army token (see "Slopes"), its ring 1.45 times the full trio's width across+ (`UnitPlinth.BaseToTrio`; 1.42–1.44 measured on the built tokens, pinned to 1.3–1.7 by `TheBaseHugsTheTrioAsInT29`).+ The earth is the palette's `Earth`, dark and warm as T29's, mottled by smooth value noise over the world in its shade+ rows (no texture). Owner, 2026-10-15: this base (earth 0.45, 0.33, 0.22), the lighter of the two rendered, over a+ darker one (0.38, 0.28, 0.18) that brought the ring nearer T29's contrast but left the figures lighter than their base.+- **Ring:** a band on the ground just outside the base, from 1.02 to 1.10 of its radius, each vertex over the highest ground+ across the band (the selection ring's rule), drawn unlit in white with the selection ring's shader. The selection ring+ is unchanged and still appears only on selection.+- **On renders** (`TheBaseRingAndFlagReadAsT29OnARender`: a 30 km look at Harel's hill token and at the showcase trio,+ through the game's camera, measured as T29 was): see the numbers in PR #559. The bands are T29's own measures, set+ before measuring ours.+- **Flag:** by the unit's `side` in `units_1948.yaml` (`israel` on every row today; the Arab states' sides are known to the+ loader for #226). The cloth is 0.52 of a figure's height tall and 0.72 wide, on a pole 1.5 tall at 0.9 of the base's+ radius, behind the trio and east of the badge (`TheFlagIsAboutHalfAFigureTallOnTheBasesEdge`). The cloth is drawn+ unlit (white, and a blue standing for the proclamation's "dark sky-blue"), so it reads white under the map's light and+ grade as T29's. Owner ruling (2026-10-15): the flag turns about its pole to face the camera (`UnitFlagFacing`), so it+ never shows edge-on as the camera orbits; the pole stays upright at the base's edge.+ - **Use of the flag:** the Flag and Emblem Law, 5709-1949, s. 2(a), forbids using the State flag for commerce, business or+ profession without a permit from the Minister of the Interior (the 1949 text, read on the cited scan; the amended text+ not checked). The game is free and non-commercial; a paid release needs this checked first. Only a side whose 1948+ flag is sourced here gets one, so no flag is invented:+ - Israel: the Provisional Council of State's "Proclamation on the Flag of the State of Israel" of 25 Tishrei 5709+ (28 October 1948), Iton Rishmi No. 32, 10 Heshvan 5709 (12 November 1948), p. 62+ (https://fs.knesset.gov.il/0/law/0_lsr_340940.pdf, read 2026-10-14): 220 cm by 160 cm; white, with two dark+ sky-blue stripes 25 cm broad along its length, 15 cm from the top and the bottom edge; in the middle, equally far from+ both stripes, a Star of David of six sky-blue stripes 5.5 cm broad forming two equilateral triangles whose bases are+ parallel to the stripes. The Flag and Emblem Law, 5709-1949 (Sefer HaChukim No. 8, 24 May 1949, p. 37, s. 1(a);+ https://fs.knesset.gov.il/1/law/1_lsr_208225.pdf, read 2026-10-14) makes that proclaimed flag the State flag "in+ any size". Neither text sets the star's size: it is drawn 69 cm across, as the construction drawing at+ https://en.wikipedia.org/wiki/Flag_of_Israel (checked 2026-10-14), which fits the gazette's own drawing. The same+ design hung at the declaration on 14 May 1948 (https://en.wikipedia.org/wiki/Israeli_Declaration_of_Independence,+ checked 2026-10-14), so it flies from the game's first day. Pinned by `TheIsraeliFlagFollowsTheSpecification`.+ - Egypt, Jordan, Syria, Iraq, Lebanon: no sourced flag yet, so a token of theirs flies none+ (`TheFlagIsTheSidesAndOnlyASourcedFlagIsDrawn`).+- **The showcase trio** (`?units`, `-units`) stands at the land hex nearest its old spot whose base keeps off the+ railways and roads, and the kits keep a clearing there in such a run, as they do for a unit in a town+ (`MapScene.ShowcaseClearing`, `UnitShowcase.Clearing`), so no kit building or route crosses its base+ (`NoKitBuildingOrRailCrossesTheShowcasePlinth`). A plain screenshot keeps every kit.+- **Aircraft and ships** have no base and no flag: they fly or float, and carry their own sourced markings.+- **Cost:** per army token, a draped top (the terrain cells under it, see the PR), its lip and its ring (384), built once+ per roster change and freed with the tokens; one shared flag mesh (about 250). The base, lip and pole in the units' palette material; the ring and the cloth in three+ unlit colours. No texture, no new shader, no per-pixel cost (docs/visual-v1.md, #391), and no per-frame code.+## Colour at map scaleThe uniform's colours (shirt, faded shirt, trousers, bush hat in `UnitPalette`) are darker and browner than the khaki@@ -311,9 +383,8 @@ are black and white, and the kit itself (khaki drill, 37-pattern webbing, the thbelow. Measured on editor renders of both tiers (gameplay03, the showcase trio at 20 km, the 7th Brigade at 15 km,Golani at 12 km, Harel at 15 km in the Judean hills and Etzioni at 30 km), a figure was 0.68–0.82 of the surroundingground's luminance with the old, lighter khaki, and blended into it; it is now 0.50–0.57, and warm (red above green).-Promo 03's figures are about 0.45 (figures round 1, refs #197). The webbing stays pale, as the promo's straps do. A-slope base is painted trodden earth (`Dust`), within 7% of the ground's luminance where measured, so it reads as the-promo's worn patch rather than a dark disc. The aircraft and ship colours are untouched.+Promo 03's figures are about 0.45 (figures round 1, refs #197). The webbing stays pale, as the promo's straps do. The+token's base is painted earth (`Earth`), lighter than the uniforms (it replaced round 1's per-figure slope base). The aircraft and ship colours are untouched.## Sources (checked 2026-10-11)diff --git a/tools/tests/test_units_1948.py b/tools/tests/test_units_1948.pyindex b4725a268..509c09426 100644--- a/tools/tests/test_units_1948.py+++ b/tools/tests/test_units_1948.py@@ -99,3 +99,12 @@ def test_a_window_ends_at_the_earliest_sourced_move():return any(day(a['from']) <= d < day(a['to']) for a in u['anchors'])assert shown('carmeli', date(1948, 7, 10)) and not shown('carmeli', date(1948, 9, 1))assert shown('givati', date(1948, 10, 1)) and not shown('givati', date(1948, 12, 15))++# The sides of 1948 a unit can belong to (UnitData.Sides): Israel and the Arab states whose armies entered the war. Every row+# names its side; the map flies that side's flag where one is sourced (UnitFlags).+SIDES = {'israel', 'egypt', 'jordan', 'syria', 'iraq', 'lebanon'}+++def test_every_unit_names_a_known_side():+ for u in UNITS:+ assert u.get('side') in SIDES, f"{u['id']}: side {u.get('side')!r} is not one of {sorted(SIDES)}"diff --git a/unity/Assets/Editor/MapCapture.cs b/unity/Assets/Editor/MapCapture.csindex 2e07b7f56..7905e2b0c 100644--- a/unity/Assets/Editor/MapCapture.cs+++ b/unity/Assets/Editor/MapCapture.cs@@ -198,6 +198,8 @@ public static class MapCaptureforeach (var pose in Poses(args)){pose.Apply(rig, map.Frame);+ Statecraft.Game.Map.Units.UnitFlagFacing.FaceAll(Camera.main.transform.position); // the flags face this pose's camera (#559)+ foreach (var layer in Object.FindObjectsByType<Statecraft.Game.Map.Units.UnitLayer>(FindObjectsSortMode.None)) layer.FaceCamera(Camera.main); // and the badgesSave(Camera.main, 1920, 1080, Path.Combine(dir, $"{QualitySettings.names[level]}-{pose.Name}.png"));}}diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex b82ab6fee..33b8523c3 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -146,6 +146,11 @@ namespace Statecraft.Game.Map/// keep off them (KitGround.Tokens). Empty before Build.</summary>public IReadOnlyList<(Vector2 centre, float radius)> SettlementFootprints { get; private set; } = new List<(Vector2, float)>();+ /// <summary>Whether the next Build keeps a kit clearing for the units' showcase trio (Units.UnitShowcase.Clearing), as+ /// for a unit in a town: null means only when the run asks for the showcase (?units, -units), so a plain screenshot+ /// keeps every kit (review of #559).</summary>+ public bool? ShowcaseClearing { get; set; }+/// <summary>The railways' and roads' corridors (RouteLayer.Corridors), every route whatever its date, so the units keep/// their figures off them. Empty before Build.</summary>public IReadOnlyList<(List<Vector2> line, float halfWidth)> RouteCorridors { get; private set; } = new List<(List<Vector2>, float)>();@@ -340,6 +345,9 @@ namespace Statecraft.Game.Map(lon, lat) => { var w = Frame.ToWorld(lon, lat, 0); return new Vector2(w.x, w.z); }, hexSizeM);var clearings = new List<(Vector2 centre, float radius)>();var unitRings = new List<(Vector2 centre, float radius)>();+ // The units' showcase trio gets the same clearing at its spot, off the railways and roads, so its base stands+ // clear of the kits (review of #559).+ if (ShowcaseClearing ?? Units.UnitShowcase.Requested()) clearings.Add(Units.UnitShowcase.Clearing(this));if (unitData.Count > 0){var spots = unitGround.Place(unitData, (lon, lat) => { var w = Frame.ToWorld(lon, lat, 0); return new Vector2(w.x, w.z); }, null);diff --git a/unity/Assets/Scripts/Map/Units/MiniatureMesh.cs b/unity/Assets/Scripts/Map/Units/MiniatureMesh.csindex 9a0f57e5c..023b6ae7e 100644--- a/unity/Assets/Scripts/Map/Units/MiniatureMesh.cs+++ b/unity/Assets/Scripts/Map/Units/MiniatureMesh.cs@@ -126,6 +126,25 @@ namespace Statecraft.Game.Map.Unitsreturn this;}+ /// <summary>A flat one-sided facet through <paramref name="poly"/> (convex, or a fan from its first point), already in+ /// place, facing up (or, when <paramref name="outward"/>, away from the local Y axis), painted at shade row+ /// <paramref name="shade"/>: a draped base's top and lip.</summary>+ public MiniatureMesh Facet(IReadOnlyList<Vector3> poly, int slot, float shade, bool outward = false) =>+ Facet(poly, slot, _ => shade, outward);++ /// <summary>As <see cref="Facet(IReadOnlyList{Vector3}, int, float, bool)"/>, each vertex at its own shade row.</summary>+ public MiniatureMesh Facet(IReadOnlyList<Vector3> poly, int slot, Func<Vector3, float> shadeAt, bool outward = false)+ {+ var n = Vector3.Cross(poly[1] - poly[0], poly[poly.Count - 1] - poly[0]).normalized;+ var mid = Vector3.zero; foreach (var p in poly) mid += p; mid /= poly.Count;+ bool flip = outward ? Vector3.Dot(n, new Vector3(mid.x, 0f, mid.z)) < 0f : n.y < 0f;+ if (flip) n = -n;+ int b0 = verts.Count;+ foreach (var p in poly) Add(Matrix4x4.identity, p, n, slot, shadeAt(p));+ for (int i = 1; i < poly.Count - 1; i++) tris.AddRange(new[] { b0, b0 + i, b0 + i + 1 });+ return this;+ }+/// <summary>A flat two-sided polygon (a roundel, a star) in the local XZ plane, placed by <paramref name="m"/>;/// <paramref name="outline"/> is convex or a fan from its first point.</summary>public MiniatureMesh Plate(Matrix4x4 m, IReadOnlyList<Vector2> outline, int slot, float shade = float.NaN)diff --git a/unity/Assets/Scripts/Map/Units/UnitData.cs b/unity/Assets/Scripts/Map/Units/UnitData.csindex 038e4b902..fd5320bbf 100644--- a/unity/Assets/Scripts/Map/Units/UnitData.cs+++ b/unity/Assets/Scripts/Map/Units/UnitData.cs@@ -80,6 +80,9 @@ namespace Statecraft.Game.Map.Unitspublic string Name { get; set; } = "";public string Number { get; set; } = "";public string Service { get; set; } = "";+ /// <summary>Whose formation it is (<see cref="UnitData.Sides"/>): the token flies that side's flag where one is+ /// sourced (<see cref="UnitFlags"/>).</summary>+ public string Side { get; set; } = "";public string? Formed { get; set; }public string? FirstCommander { get; set; }public string Sector { get; set; } = "";@@ -127,6 +130,11 @@ namespace Statecraft.Game.Map.Units{public const string DefaultFileName = "units_1948.yaml";public const string Army = "army", Air = "air", Navy = "navy";+ /// <summary>The sides of 1948 a unit can belong to: Israel and the Arab states whose armies entered the war (the+ /// fronts of <see cref="FrontArmistice"/>, and Iraq). Only Israel's formations are in the file today (#226 adds the+ /// Arab forces).</summary>+ public const string Israel = "israel";+ public static readonly IReadOnlyList<string> Sides = new[] { Israel, "egypt", "jordan", "syria", "iraq", "lebanon" };public const string AviaS199 = "avia-s199", Spitfire = "spitfire";public const string EndBySource = "source", EndByFrontArmistice = "front_armistice";public const string SlouchHat = "slouch_hat", SteelHelmet = "steel_helmet", WoolCap = "wool_cap";@@ -166,7 +174,7 @@ namespace Statecraft.Game.Map.Units}/// <summary>Parses and checks the file. Every problem throws InvalidDataException naming the file and the unit: YAML- /// syntax, unknown or duplicate keys, a bad or duplicate id, an unknown service or aircraft type, a missing name or+ /// syntax, unknown or duplicate keys, a bad or duplicate id, an unknown service, side or aircraft type, a missing name or/// sector, a bad date or an empty window, an anchor off the globe or without a source, a source without url or/// check date, a drawn unit with no anchors, or an air unit without aircraft.</summary>public static List<UnitEntry> Parse(string yaml, string file = DefaultFileName)@@ -187,6 +195,7 @@ namespace Statecraft.Game.Map.Unitsif (!IdRule.IsMatch(u.Id)) throw new InvalidDataException($"{at} id must be lower snake_case");if (!ids.Add(u.Id)) throw new InvalidDataException($"{at} duplicate id");if (!Services.Contains(u.Service)) throw new InvalidDataException($"{at} has unknown service '{u.Service}' (army, air or navy)");+ if (!((IList<string>)Sides).Contains(u.Side)) throw new InvalidDataException($"{at} has unknown side '{u.Side}' ({string.Join(", ", Sides)})");if (string.IsNullOrWhiteSpace(u.Name) || string.IsNullOrWhiteSpace(u.Sector)) throw new InvalidDataException($"{at} needs a name and a sector");var signOff = Statecraft.Sim.ReviewRecord.Problem(u.ReviewedByGiven, u.ReviewedBy, u.ReviewedOnGiven, u.ReviewedOn);if (signOff != null) throw new InvalidDataException($"{at} {signOff.Value.field}: {signOff.Value.message}");diff --git a/unity/Assets/Scripts/Map/Units/UnitFlagFacing.cs b/unity/Assets/Scripts/Map/Units/UnitFlagFacing.csnew file mode 100644index 000000000..bdac7392d--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitFlagFacing.cs@@ -0,0 +1,47 @@+#nullable enable+using System.Collections.Generic;+using UnityEngine;+using UnityEngine.Rendering;++namespace Statecraft.Game.Map.Units+{+ /// <summary>Owner ruling (2026-10-15): "billboard the flag". Turns a token's flag about its pole's vertical axis to face+ /// the camera about to render, so the cloth never shows edge-on as the camera orbits; the pole stays upright and its foot+ /// stays on the base's edge. It works on the camera's position only: no allocation, and nothing when the camera has not+ /// moved since the last turn. Disabled with its token (a hidden layer turns nothing). It runs in the editor too, so the+ /// editor's promo renders and the tests see the flags as play does.</summary>+ [ExecuteAlways]+ public sealed class UnitFlagFacing : MonoBehaviour+ {+ Vector3 lastCamera = new Vector3(float.NaN, 0f, 0f);+ static readonly List<UnitFlagFacing> Live = new List<UnitFlagFacing>();++ void OnEnable() { RenderPipelineManager.beginCameraRendering += Turn; Live.Add(this); }+ void OnDisable() { RenderPipelineManager.beginCameraRendering -= Turn; Live.Remove(this); }++ /// <summary>Turns every live flag to <paramref name="camera"/> now. A turn made as a camera renders shows from its next+ /// frame (unnoticed in play); a still render (the editor's promo captures, the tests) calls this before rendering.</summary>+ public static void FaceAll(Vector3 camera)+ {+ for (int i = 0; i < Live.Count; i++) { Face(Live[i].transform, camera); Live[i].lastCamera = camera; }+ }++ void Turn(ScriptableRenderContext _, Camera cam)+ {+ if (cam == null) return;+ var at = cam.transform.position;+ if (at == lastCamera) return;+ lastCamera = at;+ Face(transform, at);+ }++ /// <summary>Turns <paramref name="flag"/> about the world's vertical so its cloth (local XY plane, its front towards+ /// local -Z) faces <paramref name="camera"/>, seen from above.</summary>+ public static void Face(Transform flag, Vector3 camera)+ {+ var toCam = camera - flag.position; toCam.y = 0f;+ if (toCam.sqrMagnitude < 1f) return;+ flag.rotation = Quaternion.LookRotation(-toCam.normalized, Vector3.up);+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Units/UnitFlagFacing.cs.meta b/unity/Assets/Scripts/Map/Units/UnitFlagFacing.cs.metanew file mode 100644index 000000000..4923c1cae--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitFlagFacing.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 091507b4a4d3d4c8c92a81723b6447c8\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Units/UnitFlags.cs b/unity/Assets/Scripts/Map/Units/UnitFlags.csnew file mode 100644index 000000000..42dd7e6a0--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitFlags.cs@@ -0,0 +1,97 @@+#nullable enable+using System.Collections.Generic;+using UnityEngine;+using P = Statecraft.Game.Map.Units.UnitPalette;++namespace Statecraft.Game.Map.Units+{+ /// <summary>The flag a token flies on a pole from its base, by its side (<see cref="UnitEntry.Side"/>; demo2 T29,+ /// refs #197). Built from code in the units' palette, as the roundels are: no texture ships. A side gets a flag only+ /// where its 1948 design is sourced here; every other side flies none (never an invented flag).+ /// - Israel: the flag the Provisional Council of State proclaimed on 25 Tishrei 5709 (28 October 1948), "Proclamation+ /// on the Flag of the State of Israel", Iton Rishmi No. 32, 10 Heshvan 5709 (12 November 1948), p. 62+ /// (https://fs.knesset.gov.il/0/law/0_lsr_340940.pdf, read 2026-10-14): 220 cm long and 160 cm wide; white, with two+ /// dark sky-blue (tkhelet) stripes 25 cm broad along its whole length, 15 cm from the top and from the bottom edge;+ /// in the middle of the white, equally far from both stripes, a Star of David of six sky-blue stripes 5.5 cm broad+ /// forming two equilateral triangles whose bases are parallel to the stripes. The Flag and Emblem Law, 5709-1949+ /// (Sefer HaChukim No. 8, 28 Iyar 5709 / 24 May 1949, p. 37, s. 1(a); https://fs.knesset.gov.il/1/law/1_lsr_208225.pdf,+ /// read 2026-10-14) makes "the State flag" that proclaimed flag, "in any size". Neither text gives the star's size: it+ /// is drawn 69 cm across, as the construction drawing at https://en.wikipedia.org/wiki/Flag_of_Israel (checked+ /// 2026-10-14), which fits the gazette's own drawing (the star fills most of the white between the stripes). The same+ /// design, the Zionist flag, hung at the declaration on 14 May 1948 ("two flags, later to become the official flag of+ /// Israel", https://en.wikipedia.org/wiki/Israeli_Declaration_of_Independence, checked 2026-10-14), so it flies from+ /// the game's first day. The gazette says only "dark sky-blue" (tkhelet kehe); the cloth's blue+ /// (<see cref="BlueColour"/>) is a choice, a little brighter than the roundel's so it reads unlit.+ /// - Egypt, Jordan, Syria, Iraq, Lebanon: no sourced flag in the repo yet, so none (#226 brings the Arab forces).+ /// Proportions on the token follow T29: the cloth about half a figure's height, the pole about one and a half.</summary>+ public static class UnitFlags+ {+ /// <summary>The mesh is in figure heights (the layer scales it by a figure's drawn height), its origin at the+ /// pole's foot, the flag flying towards +x in the XY plane (facing the camera's south). T29's flags, measured on three+ /// tokens: the cloth 0.47-0.60 of a figure's height tall and 0.65-0.70 wide, the pole about 1.5; here 0.52, 0.72 and+ /// 1.5.</summary>+ public const float PoleHeight = 1.5f, PoleRadius = 0.022f, FlagWidth = 0.72f;+ public const float FlagLeft = PoleRadius, FlagTop = PoleHeight - 0.03f;+ public const float FlagBottom = FlagTop - FlagWidth * 160f / 220f;+ /// <summary>The star's outer points from its centre, in the specification's centimetres (69 cm across).</summary>+ public const float StarOuterCm = 34.5f;+ const float StripeCm = 5.5f, Layer = 0.02f; // the blue a fiftieth of a figure off the white: enough depth for WebGL at 60 km++ static readonly HashSet<string> Sourced = new HashSet<string> { UnitData.Israel };++ public static bool Has(string? side) => side != null && Sourced.Contains(side);++ public static string MeshName(string side) => "UnitFlag/" + side;++ /// <summary>The pole and flag of <paramref name="side"/>, or null when the side has no sourced flag.</summary>+ public static Mesh? Build(string? side)+ {+ if (!Has(side)) return null;+ var m = new MiniatureMesh();+ m.Rod(Vector3.zero, new Vector3(0, PoleHeight, 0), PoleRadius, PoleRadius * 0.8f, P.RifleWood, segments: 8, shade: 0.7f);+ m.Ellipsoid(Matrix4x4.TRS(new Vector3(0, PoleHeight + 0.02f, 0), Quaternion.identity, Vector3.one * 0.035f), P.RifleWood, 8, 4, shade: 0.9f);+ Vector2 F(float xCm, float yCm) => new Vector2(FlagLeft + xCm * FlagWidth / 220f, FlagBottom + yCm * FlagWidth / 220f);+ m.Plate(Plane(0f), new List<Vector2> { F(0, 0), F(220, 0), F(220, 160), F(0, 160) }, P.RoundelWhite, shade: 0.9f);+ foreach (float z in new[] { Layer, -Layer }) // the blue on both faces, a hair off the white+ {+ var at = Plane(z);+ foreach (float y in new[] { 15f, 120f })+ m.Plate(at, new List<Vector2> { F(0, y), F(220, y), F(220, y + 25f), F(0, y + 25f) }, P.RoundelBlue, shade: 0.85f);+ foreach (float turn in new[] { 90f, 270f }) // the upward and the downward triangle, bases horizontal+ for (int k = 0; k < 3; k++)+ {+ Vector2 Corner(int i, float r) { float a = (turn + 120f * i) * Mathf.Deg2Rad; return F(110f + r * Mathf.Cos(a), 80f + r * Mathf.Sin(a)); }+ float inner = StarOuterCm - 2f * StripeCm; // an equilateral triangle's edges moved in by d: its corners by 2d+ m.Plate(at, new List<Vector2> { Corner(k, StarOuterCm), Corner(k + 1, StarOuterCm), Corner(k + 1, inner), Corner(k, inner) }, P.RoundelBlue, shade: 0.85f);+ }+ }+ return Split(m.Build(MeshName(side!)));+ }++ /// <summary>The cloth's colours, drawn unlit (the selection ring's shader) so the flag reads white and blue under+ /// the map's light and grade, as T29's (its white 0.83-0.91 luma). The blue stands for the proclamation's "dark+ /// sky-blue", which gives no value: a choice.</summary>+ public static readonly Color WhiteColour = new Color(1f, 1f, 1f), BlueColour = new Color(0.0f, 0.22f, 0.62f);++ /// <summary>Puts the pole, the white and the blue in submeshes 0, 1 and 2 (the palette, white and blue materials).</summary>+ static Mesh Split(Mesh mesh)+ {+ var uv = mesh.uv; var t = mesh.triangles;+ var parts = new[] { new List<int>(), new List<int>(), new List<int>() };+ float white = P.U(P.RoundelWhite), blue = P.U(P.RoundelBlue);+ for (int i = 0; i < t.Length; i += 3)+ {+ float u = uv[t[i]].x;+ int k = Mathf.Abs(u - white) < 1e-4f ? 1 : Mathf.Abs(u - blue) < 1e-4f ? 2 : 0;+ parts[k].Add(t[i]); parts[k].Add(t[i + 1]); parts[k].Add(t[i + 2]);+ }+ mesh.subMeshCount = 3;+ for (int k = 0; k < 3; k++) mesh.SetTriangles(parts[k], k);+ return mesh;+ }++ /// <summary>Maps a plate's local XZ outline to the XY plane at depth <paramref name="z"/>.</summary>+ static Matrix4x4 Plane(float z) =>+ new Matrix4x4(new Vector4(1, 0, 0, 0), new Vector4(0, 0, -1, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, z, 1));+ }+}diff --git a/unity/Assets/Scripts/Map/Units/UnitFlags.cs.meta b/unity/Assets/Scripts/Map/Units/UnitFlags.cs.metanew file mode 100644index 000000000..6dfda5a1c--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitFlags.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 7a5cb51c86733445fa3e0f031ef4d135\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Units/UnitGround.cs b/unity/Assets/Scripts/Map/Units/UnitGround.csindex 3e8acd7f1..cf638bad0 100644--- a/unity/Assets/Scripts/Map/Units/UnitGround.cs+++ b/unity/Assets/Scripts/Map/Units/UnitGround.cs@@ -16,7 +16,8 @@ namespace Statecraft.Game.Map.Units/// <summary>A footprint's buildings and tinted ground reach 1.1 of its radius (SettlementKits.PaintGround).</summary>public const float FootprintMargin = 1.1f;/// <summary>Clearance (m) between a figure's centre and a railway's or road's corridor: about half a figure's width- /// at <see cref="UnitShowcase.FigureScale"/> (0.6 m x 2000 = 1.2 km across) plus a margin.</summary>+ /// at the first round's 2000x (0.6 m x 2000 = 1.2 km across) plus a margin. Kept when the figures went to 1400x+ /// (refs #197), so no token's spot moved.</summary>public const float FigureClearanceM = 700f;/// <summary>A compact token (beside or in a town) draws its ring and trio at this share of the full size.</summary>public const float CompactScale = 0.5f;diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.csindex 175aadcbf..650d3ec39 100644--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs@@ -31,16 +31,32 @@ namespace Statecraft.Game.Map.UnitsUnitGround ground = null!;IReadOnlyDictionary<UnitAnchor, AnchorSpot> spots = new Dictionary<UnitAnchor, AnchorSpot>();MapRuntimeAssets assets = null!;- Material paint = null!, ringTemplate = null!, badgePlate = null!, badgeGlyph = null!;+ Material paint = null!, ringTemplate = null!, badgePlate = null!, badgeGlyph = null!, rim = null!, flagWhite = null!, flagBlue = null!;readonly Dictionary<string, Mesh> meshes = new Dictionary<string, Mesh>();+ /// <summary>The meshes built for the tokens drawn now (each base's draped top, lip and ring follow its own ground):+ /// destroyed when the tokens are rebuilt and with the layer, so no roster change leaks them (review of #559, M1).</summary>+ readonly List<Mesh> tokenMeshes = new List<Mesh>();List<UnitToken>? roster;List<PlacedToken> placed = new List<PlacedToken>();Transform tokensRoot = null!;readonly List<Transform> badges = new List<Transform>();+ /// <summary>Each badge's home (over the highest figure's feet, at the figures' height and the badge's lift) and how+ /// far behind the trio it sits, away from the camera (review of #559: the badge keeps off the figures' heads from+ /// any view, the camera's yaw and steepness alike), its flag's pole from the middle (zero for none), the flag (null for+ /// none) and the box of the token's pieces that neither turn nor move (null for a flying aircraft alone). In the order+ /// of <see cref="badges"/> and <see cref="keepClear"/>.</summary>+ readonly List<(Vector3 home, float back, Vector3 pole, MeshFilter? flag, Bounds? standing)> badgeHomes = new List<(Vector3, float, Vector3, MeshFilter?, Bounds?)>();+ /// <summary>A badge sits this share of its token's base radius behind the trio, seen from the camera, and+ /// <see cref="BadgeAsideM"/> to the side away from its flag's pole on screen (a compact token's pole cannot stand+ /// further out than its base's edge).</summary>+ public const float BadgeBackShare = 0.6f, BadgeAsideM = 400f, BadgeOverFlagM = 150f;readonly List<(Vector2 centre, float radius)> treeHoles = new List<(Vector2, float)>();List<Bounds[]> keepClear = new List<Bounds[]>();GameObject? ring;bool still;+ /// <summary>The camera pose <see cref="FaceCamera"/> last turned the badges and flags to; a call from the same pose+ /// changes nothing and returns at once (GameRoot calls it every frame). Cleared when the tokens are rebuilt.</summary>+ (Vector3 eye, Quaternion rotation)? facedFor;/// <summary>The tokens drawn now, in the data's order.</summary>public IReadOnlyList<PlacedToken> Tokens => placed;@@ -49,9 +65,11 @@ namespace Statecraft.Game.Map.Units/// <summary>The ground the anchors were placed on.</summary>public UnitGround PlacementGround => ground;/// <summary>The world boxes the map's name pills keep clear of (issue #197), one entry per drawn token: its standing- /// pieces (the figures on their bases, a parked aircraft, the ship; not a flying aircraft, which moves) and its- /// badge, which MapLabelsPresenter projects to one screen rectangle, so no pill sits on a token or between its badge- /// and its figures. A new list whenever the tokens are rebuilt, and empty while the "units" toggle hides the layer.</summary>+ /// pieces (the figures on their bases with the flag, a parked aircraft, the ship; not a flying aircraft, which moves) and+ /// its badge, which MapLabelsPresenter projects to one screen rectangle, so no pill sits on a token or between its badge+ /// and its figures. The badge's box and the flag's part follow them as <see cref="FaceCamera"/> turns them to a camera+ /// (in place: the boxes hold the token as that camera draws it). A new list whenever the tokens are rebuilt, and empty+ /// while the "units" toggle hides the layer.</summary>public IReadOnlyList<Bounds[]> KeepClear => gameObject.activeInHierarchy ? keepClear : (IReadOnlyList<Bounds[]>)Array.Empty<Bounds[]>();/// <summary>The selected unit's id, or null.</summary>public string? Selected { get; private set; }@@ -96,11 +114,16 @@ namespace Statecraft.Game.Map.Unitslayer.ringTemplate = ringTemplate;layer.badgePlate = layer.assets.Own(new Material(ringTemplate) { name = "UnitBadge (plate)", color = UnitBadge.PlateColour });layer.badgeGlyph = layer.assets.Own(new Material(ringTemplate) { name = "UnitBadge (glyph)", color = UnitBadge.GlyphColour });+ layer.rim = layer.assets.Own(new Material(ringTemplate) { name = "UnitPlinthRim", color = UnitPlinth.RimColour });+ layer.flagWhite = layer.assets.Own(new Material(ringTemplate) { name = "UnitFlag (white)", color = UnitFlags.WhiteColour });+ layer.flagBlue = layer.assets.Own(new Material(ringTemplate) { name = "UnitFlag (blue)", color = UnitFlags.BlueColour });+ layer.flagBlue.renderQueue = layer.flagWhite.renderQueue + 1; // the blue over the whitelayer.tokensRoot = new GameObject("Tokens").transform;layer.tokensRoot.SetParent(root.transform, false);// The kit trees under the figures are left out while the layer shows (issue #249), and come back with the layer// off: a plain screenshot run (HiddenInCaptures) keeps every tree, so its checkpoints stay comparable.layer.assets.OnTeardown(() => UnitShowcase.HideTrees(map, ToggleName, Array.Empty<(Vector2, float)>()));+ layer.assets.OnTeardown(layer.FreeTokenMeshes);layer.assets.OnTeardown(VisualToggles.Register(ToggleName, on =>{if (root != null) root.SetActive(on);@@ -122,12 +145,39 @@ namespace Statecraft.Game.Map.Unitsvoid HideTrees() => UnitShowcase.HideTrees(map, ToggleName, gameObject.activeSelf ? treeHoles : (IReadOnlyList<(Vector2, float)>)Array.Empty<(Vector2, float)>());- /// <summary>Turns every badge to face the camera about to render (game, editor capture or scene view alike).</summary>- void FaceBadges(ScriptableRenderContext _, Camera cam)+ /// <summary>Turns every badge to face the camera about to render (game, editor capture or scene view alike) and sets+ /// it behind its trio as that camera sees it. No allocation.</summary>+ void FaceBadges(ScriptableRenderContext _, Camera cam) => FaceCamera(cam);++ /// <summary>As the render callback does: for a still render (the editor's promo captures, the tests), and for the map's+ /// names before they are placed (GameRoot), so the keep-clear boxes hold each badge and flag where this camera draws+ /// them: the badge's box is its own cube, not a box round every place the camera's yaw could take it (that box, about+ /// 3.7 km across, pushed Tel Aviv's name off its kit at gameplay03). No allocation.</summary>+ public void FaceCamera(Camera cam){if (cam == null) return;- var rotation = cam.transform.rotation;- foreach (var b in badges) if (b != null) b.rotation = rotation;+ var eye = cam.transform.position; var rotation = cam.transform.rotation;+ if (facedFor is { } last && last.eye == eye && last.rotation == rotation) return; // nothing moved since the last turn+ facedFor = (eye, rotation);+ var away = cam.transform.forward; away.y = 0f;+ away = away.sqrMagnitude > 1e-6f ? away.normalized : Vector3.forward;+ var right = cam.transform.right; right.y = 0f;+ right = right.sqrMagnitude > 1e-6f ? right.normalized : Vector3.right;+ for (int i = 0; i < badges.Count; i++)+ {+ var b = badges[i]; if (b == null) continue;+ var (home, back, pole, flag, standing) = badgeHomes[i];+ var aside = pole == Vector3.zero ? Vector3.zero : (Vector3.Dot(pole, right) > 0f ? -right : right) * BadgeAsideM;+ var at = home + away * back + aside;+ b.SetPositionAndRotation(at, rotation);+ var boxes = keepClear[i];+ boxes[0] = new Bounds(at, Vector3.one * UnitBadge.SizeM);+ if (flag != null && standing is Bounds s)+ {+ UnitFlagFacing.Face(flag.transform, eye); // as it will turn for this camera+ s.Encapsulate(WorldBox(flag)); boxes[1] = s;+ }+ }}/// <summary>Draws the units for <paramref name="state"/> (read only). Rebuilds the tokens only when the roster@@ -185,13 +235,21 @@ namespace Statecraft.Game.Map.Units{if (!meshes.TryGetValue(key, out var mesh)){- mesh = assets.Own(build());- mesh.UploadMeshData(true); // no CPU copy kept in players+ mesh = UnitPlinth.Upload(assets.Own(build())); // no CPU copy kept in playersmeshes[key] = mesh;}return mesh;}+ /// <summary>Takes a mesh built for one token: freed with the tokens (<see cref="FreeTokenMeshes"/>).</summary>+ Mesh TokenMesh(Mesh m) { tokenMeshes.Add(UnitPlinth.Upload(m)); return m; }++ void FreeTokenMeshes()+ {+ foreach (var m in tokenMeshes) if (m != null) { if (Application.isPlaying) Destroy(m); else DestroyImmediate(m); }+ tokenMeshes.Clear();+ }+static UnitModels.Headgear Hat(string headgear) => headgear switch{UnitData.SlouchHat => UnitModels.Headgear.SlouchHat,@@ -208,7 +266,8 @@ namespace Statecraft.Game.Map.Unitsold.transform.SetParent(null);if (Application.isPlaying) Destroy(old); else DestroyImmediate(old);}- badges.Clear();+ FreeTokenMeshes();+ badges.Clear(); badgeHomes.Clear(); facedFor = null;treeHoles.Clear();keepClear = new List<Bounds[]>(); // a new list, so the labels see the changefloat hex = map.Hexes.hex_size_km * 1000f;@@ -218,24 +277,32 @@ namespace Statecraft.Game.Map.Unitsvar go = new GameObject(t.Unit.Id);go.transform.SetParent(tokensRoot, false);var centre = Centre(p.Spot);+ var foot = centre; // where the badge's height is measured fromfloat top;switch (t.Unit.Service){case UnitData.Army:+ // Demo2 T29's token: the figures stand shoulder to shoulder on one earth base with a bright white+ // rim, under the side's flag (refs #197). The base fits the full trio, whatever the call-up.+ float k = UnitShowcase.DrawSpread * hex * Scale(p.Spot);+ float plinth = UnitPlinth.Radius(UnitPlinth.TrioWidth(UnitShowcase.FigureOffsets(3), k));+ foot.y = UnitPlinth.Build(map, go.transform, centre, plinth, t.Unit.Side, TokenMesh, MeshFor, paint, rim, flagWhite, flagBlue);+ treeHoles.Add((new Vector2(centre.x, centre.z), plinth * UnitPlinth.RimOuter));var offsets = UnitShowcase.FigureOffsets(t.Figures);- float k = UnitShowcase.TrioSpread * hex * Scale(p.Spot);+ float highest = foot.y; // the badge clears the highest figure (on a slope the uphill one stands higher)for (int i = 0; i < offsets.Length; i++){// The pose and heading are the trio position's; the headgear is the unit's (sourced, or the default).- var (_, _, pose, faded, _, heading) = UnitShowcase.Trio[i];+ var (_, _, pose, faded, heading) = UnitShowcase.Trio[i];var hat = Hat(t.Headgear[i]);var type = UnitRoster.RiflemanType(t.Headgear[i]);- var at = UnitShowcase.Stand(map, centre + new Vector3(offsets[i].x, 0, offsets[i].y) * k);- var figure = UnitShowcase.Piece(go.transform, $"Rifleman{i}", type, () => MeshFor($"{type}/{pose}", () => UnitModels.Rifleman(hat, pose, faded, type)),+ var at = centre + new Vector3(offsets[i].x, 0, offsets[i].y) * k;+ at.y = UnitPlinth.FigureY(map, plinth, at.x, at.z);+ highest = Mathf.Max(highest, at.y);+ UnitShowcase.Piece(go.transform, $"Rifleman{i}", type, () => MeshFor($"{type}/{pose}", () => UnitModels.Rifleman(hat, pose, faded, type)),paint, at, Quaternion.Euler(0, heading, 0), UnitShowcase.FigureScale, out _);- UnitShowcase.AddBase(map, figure.transform, at, MeshFor("figure-base", () => UnitShowcase.BaseMesh("UnitFigureBase")), paint);- treeHoles.Add(UnitShowcase.TreeHole(at));}+ foot.y = highest;top = UnitBadge.FigureHeightM * UnitShowcase.FigureScale;break;case UnitData.Air:@@ -250,39 +317,56 @@ namespace Statecraft.Game.Map.Units}var badge = new GameObject("Badge");badge.transform.SetParent(go.transform, false);- badge.transform.position = centre + Vector3.up * (top + UnitBadge.LiftM);+ // Above the figures by the badge's lift, and above the flag's top (the cloth turns with the camera, so at some yaws it+ // stands right behind the badge): the badge's lower edge clears the pole's top by BadgeOverFlagM.+ float lift = top + UnitBadge.LiftM;+ if (t.Unit.Service == UnitData.Army && go.transform.Find(UnitPlinth.FlagName) != null)+ lift = Mathf.Max(lift, UnitFlags.PoleHeight * UnitBadge.FigureHeightM * UnitShowcase.FigureScale + UnitBadge.SizeM / 2f + BadgeOverFlagM);+ var home = foot + Vector3.up * lift;+ float back = t.Unit.Service == UnitData.Army ? BadgeBackShare * UnitPlinth.Radius(UnitPlinth.TrioWidth(UnitShowcase.FigureOffsets(3), UnitShowcase.DrawSpread * hex * Scale(p.Spot))) : 0f;+ badge.transform.position = home + Vector3.forward * back;badge.transform.localScale = Vector3.one * UnitBadge.SizeM;badge.AddComponent<UnitBadge>();- badges.Add(badge.transform);- var cam = Camera.main;- if (cam != null) badge.transform.rotation = cam.transform.rotation;+ var flagT = go.transform.Find(UnitPlinth.FlagName);+ var flag = flagT != null ? flagT.GetComponent<MeshFilter>() : null;+ var pole = flagT != null ? new Vector3(flagT.position.x - centre.x, 0f, flagT.position.z - centre.z) : Vector3.zero;+ var standing = StillBox(go.transform, flag);+ badges.Add(badge.transform); badgeHomes.Add((home, back, pole, flag, standing));AddRenderer(badge.transform, "Plate", MeshFor("badge-plate", UnitBadge.PlateMesh), badgePlate, 0f);AddRenderer(badge.transform, "Glyph", MeshFor("badge-" + t.Unit.Service, () => UnitBadge.GlyphMesh(t.Unit.Service)), badgeGlyph, -UnitBadge.GlyphLift);- keepClear.Add(KeepClearOf(go.transform, badge.transform.position));+ // The badge's cube and the pieces (the flag as it stands now); FaceCamera moves both with the camera.+ var pieces = standing;+ if (flag != null && pieces is Bounds s) { s.Encapsulate(WorldBox(flag)); pieces = s; }+ keepClear.Add(pieces is Bounds p2 ? new[] { new Bounds(badge.transform.position, Vector3.one * UnitBadge.SizeM), p2 }+ : new[] { new Bounds(badge.transform.position, Vector3.one * UnitBadge.SizeM) });}+ FaceCamera(Camera.main); // the badges as the main camera sees them until a render turns themHideTrees();}- /// <summary>A token's keep-clear boxes: the bounds of its pieces that stand still (a flying aircraft is left out)- /// and a cube of the badge's width round the badge's centre, which holds the plate however it is turned. The pieces'- /// bounds come from their meshes and transforms, not Renderer.bounds, which is empty while the layer is inactive (the- /// "units" toggle off when the tokens are built; review of #518).</summary>- static Bounds[] KeepClearOf(Transform token, Vector3 badgeCentre)+ /// <summary>The world box of a mesh's bounds through its transform. From the mesh and the transform, not+ /// Renderer.bounds, which is empty while the layer is inactive (the "units" toggle off when the tokens are built;+ /// review of #518).</summary>+ static Bounds WorldBox(MeshFilter f){- var boxes = new List<Bounds> { new Bounds(badgeCentre, Vector3.one * UnitBadge.SizeM) };- bool any = false; var pieces = default(Bounds);+ var b = f.sharedMesh.bounds; var m = f.transform.localToWorldMatrix; var box = new Bounds(m.MultiplyPoint3x4(b.min), Vector3.zero);+ for (int c = 1; c < 8; c++)+ box.Encapsulate(m.MultiplyPoint3x4(new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z)));+ return box;+ }++ /// <summary>The box of a token's pieces that neither turn nor move (a flying aircraft, the badge and the flag, which+ /// turns to the camera, are left out), or null when it has none.</summary>+ static Bounds? StillBox(Transform token, MeshFilter? flag)+ {+ Bounds? box = null;foreach (var f in token.GetComponentsInChildren<MeshFilter>(true)){- if (f.sharedMesh == null || f.GetComponentInParent<UnitBadge>(true) != null || f.GetComponentInParent<ShowcaseFlight>(true) != null) continue;- var b = f.sharedMesh.bounds; var m = f.transform.localToWorldMatrix;- for (int c = 0; c < 8; c++)- {- var w = m.MultiplyPoint3x4(new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z));- if (any) pieces.Encapsulate(w); else { pieces = new Bounds(w, Vector3.zero); any = true; }- }+ if (f.sharedMesh == null || f == flag || f.GetComponentInParent<UnitBadge>(true) != null || f.GetComponentInParent<ShowcaseFlight>(true) != null) continue;+ var w = WorldBox(f);+ if (box is Bounds b) { b.Encapsulate(w); box = b; } else box = w;}- if (any) boxes.Add(pieces);- return boxes.ToArray();+ return box;}static void AddRenderer(Transform parent, string name, Mesh mesh, Material mat, float z)diff --git a/unity/Assets/Scripts/Map/Units/UnitPalette.cs b/unity/Assets/Scripts/Map/Units/UnitPalette.csindex b78fc373e..66295de6b 100644--- a/unity/Assets/Scripts/Map/Units/UnitPalette.cs+++ b/unity/Assets/Scripts/Map/Units/UnitPalette.cs@@ -17,7 +17,7 @@ namespace Statecraft.Game.Map.Unitspublic 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, MarkingRed = 23, AviaGreen = 24, Dust = 25, Count = 26;+ HullGrey = 19, Deck = 20, Waterline = 21, Funnel = 22, MarkingRed = 23, AviaGreen = 24, Earth = 25, Count = 26;/// <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;@@ -49,7 +49,7 @@ namespace Statecraft.Game.Map.Unitsnew Color(0.30f, 0.31f, 0.32f), // Funnel topnew Color(0.72f, 0.12f, 0.10f), // MarkingRed: 101 Squadron's spinner and rudder stripesnew Color(0.47f, 0.45f, 0.32f), // AviaGreen: the S-199's one khaki green on all surfaces, about RAL 6013 (Efrati pp. 8 and 11: confirmed from an Avia fuel cap; Eduard Info 11/2025 pp. 53-54)- new Color(0.80f, 0.71f, 0.54f), // Dust: the trodden earth a figure's base is painted in, so it reads as the promo's worn patch, not a dark disc+ new Color(0.45f, 0.33f, 0.22f), // Earth: a token's base, the dark warm earth of demo2 T29's bases (rendered about 0.24-0.30 luma there), mottled by its facets' shade rows};/// <summary>u of a slot's column centre.</summary>diff --git a/unity/Assets/Scripts/Map/Units/UnitPlinth.cs b/unity/Assets/Scripts/Map/Units/UnitPlinth.csnew file mode 100644index 000000000..95a4cbc8e--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitPlinth.cs@@ -0,0 +1,277 @@+#nullable enable+using System;+using System.Collections.Generic;+using UnityEngine;++namespace Statecraft.Game.Map.Units+{+ /// <summary>Demo2 T29's token (refs #197): the figures of an army token stand shoulder to shoulder on one round earth+ /// base that hugs them, a bright white ring lies on the ground just outside its edge, and the side's flag flies on a pole+ /// at the base's back edge (<see cref="UnitFlags"/>). The base is draped on the terrain (round 3 of #559): its top+ /// follows the ground under it at <see cref="LipShare"/> of its radius, an edge lip of the same height closes it to the+ /// ground, and the ring is draped too, so on a hill it neither stands up as a mesa nor leaves a gap downhill. Its earth+ /// is mottled by the palette's shade rows (no texture). Low-poly meshes built per token (they follow its ground); the+ /// base in the units' palette material, the ring in the selection ring's unlit material made white (no new shader,+ /// texture or per-pixel cost; docs/visual-v1.md, #391).</summary>+ public static class UnitPlinth+ {+ public const string PlinthName = "Plinth", LipName = "PlinthLip", RimName = "PlinthRim", FlagName = "Flag";+ /// <summary>The ring's outer edge over the trio's width (the outer figures' outer edges), T29's measure: 1.41, 1.62+ /// and 1.71 on three of its tokens (4x crops of the 1:12 frame).</summary>+ public const float BaseToTrio = 1.45f;+ /// <summary>Half a figure's width (m, real size: the Ready pose's rifle across the body is the widest).</summary>+ public const float FigureHalfWidthM = 0.35f;+ /// <summary>The base's top over the ground under it, as a share of its radius (about 100 m): T29's base is a slab+ /// about a tenth of its radius thick seen from above; draped, a twentieth reads as its edge without hiding the ground's+ /// shape.</summary>+ public const float LipShare = 0.05f;+ /// <summary>How far the lip reaches into the ground below the base's edge (m), so no seam shows where the terrain's+ /// rendered surface falls between its samples.</summary>+ public const float LipSinkM = 40f;+ /// <summary>The ring: a band on the ground from <see cref="RimInner"/> to <see cref="RimOuter"/> of the radius, just+ /// outside the base's edge, as T29's (about 8% of the radius wide), <see cref="RimLiftM"/> over the ground.</summary>+ public const float RimInner = 1.02f, RimOuter = 1.10f, RimLiftM = 20f;+ /// <summary>The ring's vertices round it: each takes the highest ground across the band and halfway to its+ /// neighbours (MapBuilder.DrapedRing's rule), so the ground never rises through it between them.</summary>+ public const int RimSegments = 192;+ /// <summary>The ring's colour: unlit white (the selection ring's ivory is 1, 0.95, 0.8).</summary>+ public static readonly Color RimColour = new Color(1f, 1f, 1f);+ /// <summary>The outline's sides (the base's edge, the clip of its top and the line its lip follows), and the lip's+ /// step along it (m): the lip samples the ground every 40 m, so its top meets the draped top's edge.</summary>+ public const int OutlineSides = 96;+ public const float LipStepM = 40f;+ /// <summary>The mottling: each vertex of the top takes a shade row in this range (the palette's dark wash below 0.45,+ /// its base colour above) from smooth value noise over the world (cells of <see cref="MottleCellM"/>), so the earth+ /// shows soft patches, the same every time and continuous across facets.</summary>+ public const float MottleLow = 0.15f, MottleHigh = 0.75f, MottleCellM = 450f;+ /// <summary>Where the flag's pole stands: on the base's back edge (north, away from the camera), at this share of+ /// the radius from the middle, east of the middle by <see cref="FlagEastShare"/> of the radius but never nearer it+ /// than half the badge's width and <see cref="FlagClearOfBadgeM"/>, so the flag flies clear of the badge.</summary>+ public const float FlagEdgeShare = 0.9f, FlagEastShare = 0.3f, FlagClearOfBadgeM = 700f; // 150 and 400 m left the pole's finial touching a badge near the frame's edge at gameplay03++ /// <summary>The trio's width (m) for figures at <paramref name="offsets"/> (in hex circumradii times+ /// <paramref name="spread"/>).</summary>+ public static float TrioWidth(IReadOnlyList<Vector2> offsets, float spread)+ {+ float lo = float.MaxValue, hi = float.MinValue;+ foreach (var o in offsets) { lo = Mathf.Min(lo, o.x * spread); hi = Mathf.Max(hi, o.x * spread); }+ return hi - lo + 2f * FigureHalfWidthM * UnitShowcase.FigureScale;+ }++ /// <summary>The base's radius (m) for a trio of <paramref name="trioWidth"/>: the ring's outer edge at+ /// <see cref="BaseToTrio"/> times the trio's width.</summary>+ public static float Radius(float trioWidth) => BaseToTrio * trioWidth / 2f / RimOuter;++ static float Hash(int i, int j)+ {+ uint h = (uint)(i * 73856093) ^ (uint)(j * 19349663) ^ 0x9E3779B9u;+ h ^= h >> 13; h *= 0x5bd1e995u; h ^= h >> 15;+ return (h & 0xFFFF) / 65535f;+ }++ /// <summary>A shade row in [<see cref="MottleLow"/>, <see cref="MottleHigh"/>] at world (x, z): smooth value noise.</summary>+ public static float Mottle(float x, float z)+ {+ float fx = x / MottleCellM, fz = z / MottleCellM;+ int i = Mathf.FloorToInt(fx), j = Mathf.FloorToInt(fz);+ float u = Mathf.SmoothStep(0f, 1f, fx - i), v = Mathf.SmoothStep(0f, 1f, fz - j);+ float n = Mathf.Lerp(Mathf.Lerp(Hash(i, j), Hash(i + 1, j), u), Mathf.Lerp(Hash(i, j + 1), Hash(i + 1, j + 1), u), v);+ return Mathf.Lerp(MottleLow, MottleHigh, n);+ }++ /// <summary>The terrain's own sample spacing (m): the finer of its heightmap's steps east-west and north-south.</summary>+ public static float TerrainStepM(MapScene map)+ {+ var d = map.Terrain.terrainData; int n = d.heightmapResolution - 1;+ return Mathf.Min(d.size.x / n, d.size.z / n);+ }++ /// <summary>The base's outline: a <see cref="OutlineSides"/>-gon of radius r round c (world x, z), counter-clockwise.</summary>+ static Vector2[] Outline(Vector2 c, float r)+ {+ var o = new Vector2[OutlineSides];+ for (int k = 0; k < OutlineSides; k++) { float a = 2f * Mathf.PI * k / OutlineSides; o[k] = c + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * r; }+ return o;+ }++ static float Cross(Vector2 a, Vector2 b) => a.x * b.y - a.y * b.x;++ /// <summary>The base's top, draped on the terrain's own triangles (round 4 of #559): every heightmap cell under the+ /// disc is split along the diagonal the terrain itself uses there (found from its height at the cell's centre) into the+ /// terrain's two triangles, each raised by the lip and clipped to the outline, a clipped corner taking its height from+ /// its triangle's own plane. So the top follows the ground exactly, wherever the token stands, with no grid to tune; a+ /// base about 2 km across covers some 760 cells. x and z are in the unit disc (the transform scales them by the+ /// radius), y in world metres; smooth normals across the cells' shared corners; mottled shade rows.</summary>+ public static Mesh TopMesh(string name, MapScene map, Vector2 centre, float radius)+ {+ var td = map.Terrain.terrainData; var tp = map.Terrain.transform.position;+ int n = td.heightmapResolution - 1; float dx = td.size.x / n, dz = td.size.z / n, lip = LipShare * radius, u = UnitPalette.U(UnitPalette.Earth);+ var ground = HeightAt(map); var outline = Outline(centre, radius);+ var verts = new List<Vector3>(); var uv = new List<Vector2>(); var tris = new List<int>(); var grid = new Dictionary<long, int>();+ int Add(float x, float y, float z) { verts.Add(new Vector3((x - centre.x) / radius, y + lip, (z - centre.y) / radius)); uv.Add(new Vector2(u, Mottle(x, z))); return verts.Count - 1; }+ int G(int i, int j)+ {+ long key = (long)i * 1_000_003L + j;+ if (!grid.TryGetValue(key, out int k)) { float x = tp.x + i * dx, z = tp.z + j * dz; grid[key] = k = Add(x, ground(x, z), z); }+ return k;+ }+ bool Inside(Vector2 q) { for (int k = 0; k < OutlineSides; k++) if (Cross(outline[(k + 1) % OutlineSides] - outline[k], q - outline[k]) < 0f) return false; return true; }+ void Tri(int a, int b, int c)+ {+ var n3 = Vector3.Cross(verts[b] - verts[a], verts[c] - verts[a]);+ if (n3.y >= 0f) tris.AddRange(new[] { a, b, c }); else tris.AddRange(new[] { a, c, b });+ }+ int i0 = Mathf.Max(0, Mathf.FloorToInt((centre.x - radius - tp.x) / dx)), i1 = Mathf.Min(n - 1, Mathf.CeilToInt((centre.x + radius - tp.x) / dx));+ int j0 = Mathf.Max(0, Mathf.FloorToInt((centre.y - radius - tp.z) / dz)), j1 = Mathf.Min(n - 1, Mathf.CeilToInt((centre.y + radius - tp.z) / dz));+ for (int i = i0; i <= i1; i++)+ for (int j = j0; j <= j1; j++)+ {+ float x0 = tp.x + i * dx, z0 = tp.z + j * dz;+ var near = new Vector2(Mathf.Clamp(centre.x, x0, x0 + dx), Mathf.Clamp(centre.y, z0, z0 + dz));+ if ((near - centre).magnitude > radius) continue; // the cell lies outside the disc+ var c00 = new Vector3(x0, ground(x0, z0), z0); var c10 = new Vector3(x0 + dx, ground(x0 + dx, z0), z0);+ var c01 = new Vector3(x0, ground(x0, z0 + dz), z0 + dz); var c11 = new Vector3(x0 + dx, ground(x0 + dx, z0 + dz), z0 + dz);+ float mid = ground(x0 + dx / 2f, z0 + dz / 2f);+ bool d1 = Mathf.Abs(mid - (c00.y + c11.y) / 2f) <= Mathf.Abs(mid - (c10.y + c01.y) / 2f); // the terrain's own diagonal here+ var cells = d1 ? new[] { (c00, c10, c11, (0, 0), (1, 0), (1, 1)), (c00, c11, c01, (0, 0), (1, 1), (0, 1)) }+ : new[] { (c00, c10, c01, (0, 0), (1, 0), (0, 1)), (c10, c11, c01, (1, 0), (1, 1), (0, 1)) };+ foreach (var (pa, pb, pc, ia, ib, ic) in cells)+ {+ Vector2 A = new Vector2(pa.x, pa.z), B = new Vector2(pb.x, pb.z), Cc = new Vector2(pc.x, pc.z);+ if (Inside(A) && Inside(B) && Inside(Cc)) { Tri(G(i + ia.Item1, j + ia.Item2), G(i + ib.Item1, j + ib.Item2), G(i + ic.Item1, j + ic.Item2)); continue; }+ // Clip the triangle to the outline (Sutherland-Hodgman); heights from the triangle's plane.+ var poly = new List<Vector2> { A, B, Cc };+ for (int k = 0; k < OutlineSides && poly.Count > 0; k++)+ {+ Vector2 e0 = outline[k], e = outline[(k + 1) % OutlineSides] - e0; var outp = new List<Vector2>();+ for (int m = 0; m < poly.Count; m++)+ {+ Vector2 p = poly[m], q = poly[(m + 1) % poly.Count];+ float sp = Cross(e, p - e0), sq = Cross(e, q - e0);+ if (sp >= 0f) outp.Add(p);+ if ((sp >= 0f) != (sq >= 0f)) outp.Add(p + (q - p) * (sp / (sp - sq)));+ }+ poly = outp;+ }+ if (poly.Count < 3) continue;+ float det = (B.y - Cc.y) * (A.x - Cc.x) + (Cc.x - B.x) * (A.y - Cc.y);+ float H(Vector2 q)+ {+ float wa = ((B.y - Cc.y) * (q.x - Cc.x) + (Cc.x - B.x) * (q.y - Cc.y)) / det;+ float wb = ((Cc.y - A.y) * (q.x - Cc.x) + (A.x - Cc.x) * (q.y - Cc.y)) / det;+ return wa * pa.y + wb * pb.y + (1f - wa - wb) * pc.y;+ }+ int f0 = Add(poly[0].x, H(poly[0]), poly[0].y);+ for (int m = 1; m + 1 < poly.Count; m++) Tri(f0, Add(poly[m].x, H(poly[m]), poly[m].y), Add(poly[m + 1].x, H(poly[m + 1]), poly[m + 1].y));+ }+ }+ var mesh = new Mesh { name = name };+ if (verts.Count > 65535) mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;+ mesh.SetVertices(verts); mesh.SetUVs(0, uv); mesh.SetTriangles(tris, 0);+ mesh.RecalculateNormals(); mesh.RecalculateBounds();+ return mesh;+ }++ /// <summary>The edge lip: the band from the top's edge down to <see cref="LipSinkM"/> below the ground, following it.</summary>+ public static Mesh LipMesh(string name, Func<float, float, float> groundAt, Vector2 centre, float radius)+ {+ var m = new MiniatureMesh();+ float lip = LipShare * radius; var outline = Outline(centre, radius);+ var pts = new List<Vector2>();+ for (int k = 0; k < OutlineSides; k++)+ {+ Vector2 a = outline[k], b = outline[(k + 1) % OutlineSides];+ int steps = Mathf.Max(1, Mathf.CeilToInt((b - a).magnitude / LipStepM));+ for (int s = 0; s < steps; s++) pts.Add(Vector2.Lerp(a, b, (float)s / steps));+ }+ Vector3 L(Vector2 p, float dy) => new Vector3((p.x - centre.x) / radius, groundAt(p.x, p.y) + dy, (p.y - centre.y) / radius);+ for (int k = 0; k < pts.Count; k++)+ {+ Vector2 a = pts[k], b = pts[(k + 1) % pts.Count];+ m.Facet(new List<Vector3> { L(a, lip), L(a, -LipSinkM), L(b, -LipSinkM), L(b, lip) }, UnitPalette.Earth, 0.1f, outward: true);+ }+ return m.Build(name);+ }++ /// <summary>The ring: a flat band on the ground from <see cref="RimInner"/> to <see cref="RimOuter"/> of the radius,+ /// <see cref="RimLiftM"/> over it (the ring shader draws both faces, with the selection ring's depth offset).</summary>+ public static Mesh RimMesh(string name, Func<float, float, float> groundAt, Vector2 centre, float radius)+ {+ const int n = RimSegments;+ var verts = new List<Vector3>(2 * n); var tris = new List<int>(6 * n);+ float Across(float step)+ {+ float a = 2f * Mathf.PI * step / n, top = float.MinValue;+ foreach (var r in new[] { RimInner, (RimInner + RimOuter) / 2f, RimOuter })+ top = Mathf.Max(top, groundAt(centre.x + Mathf.Cos(a) * r * radius, centre.y + Mathf.Sin(a) * r * radius));+ return top;+ }+ for (int i = 0; i < n; i++)+ {+ float a = 2f * Mathf.PI * i / n, y = Mathf.Max(Across(i), Mathf.Max(Across(i - 0.5f), Across(i + 0.5f))) + RimLiftM;+ var d = new Vector2(Mathf.Cos(a), Mathf.Sin(a));+ verts.Add(new Vector3(d.x * RimOuter, y, d.y * RimOuter)); verts.Add(new Vector3(d.x * RimInner, y, d.y * RimInner));+ }+ for (int i = 0; i < n; i++)+ {+ int a = 2 * i, b = 2 * ((i + 1) % n);+ tris.AddRange(new[] { a, b, a + 1, a + 1, b, b + 1 });+ }+ var mesh = new Mesh { name = name };+ mesh.SetVertices(verts); mesh.SetTriangles(tris, 0); mesh.RecalculateNormals(); mesh.RecalculateBounds();+ return mesh;+ }++ /// <summary>The highest ground under a figure's boots (0.2 m from its centre at real size).</summary>+ public static float BootsTop(Func<float, float, float> heightAt, float x, float z)+ {+ float r = 0.2f * UnitShowcase.FigureScale, top = heightAt(x, z);+ for (int k = 0; k < 16; k++) { float a = Mathf.PI / 8f * k; top = Mathf.Max(top, heightAt(x + Mathf.Cos(a) * r, z + Mathf.Sin(a) * r)); }+ return top;+ }++ public static Func<float, float, float> HeightAt(MapScene map) =>+ (x, z) => map.Terrain.SampleHeight(new Vector3(x, 0, z)) + map.Terrain.transform.position.y;++ /// <summary>The height a figure standing at (x, z) on a base of <paramref name="radius"/> stands at: on the draped top+ /// at its own point (round 4 of #559; an uphill boot sets into the base, which hides it).</summary>+ public static float FigureY(MapScene map, float radius, float x, float z) => HeightAt(map)(x, z) + LipShare * radius;++ /// <summary>Tests read the built meshes back: true keeps their CPU copy (players free it after the upload).</summary>+ internal static bool KeepMeshesReadable;++ /// <summary>Frees a built mesh's CPU copy after its upload, unless a test reads it back.</summary>+ public static Mesh Upload(Mesh m) { if (!KeepMeshesReadable) m.UploadMeshData(true); return m; }++ /// <summary>Builds the draped base, its lip and its ring, of radius <paramref name="radius"/> at+ /// <paramref name="centre"/> under <paramref name="token"/>, and <paramref name="side"/>'s flag when it has one.+ /// <paramref name="own"/> takes ownership of each per-token mesh; <paramref name="shared"/> returns the shared flag+ /// mesh for a key. Returns the base's top at its centre.</summary>+ public static float Build(MapScene map, Transform token, Vector3 centre, float radius, string side, Func<Mesh, Mesh> own,+ Func<string, Func<Mesh>, Mesh> shared, Material paint, Material rim, Material flagWhite, Material flagBlue)+ {+ var ground = HeightAt(map); var c = new Vector2(centre.x, centre.z);+ var at = new Vector3(centre.x, 0f, centre.z); var scale = new Vector3(radius, 1f, radius);+ UnitShowcase.Piece(token, PlinthName, own(TopMesh("UnitPlinth", map, c, radius)), paint, at, Quaternion.identity, 1f).transform.localScale = scale;+ UnitShowcase.Piece(token, LipName, own(LipMesh("UnitPlinthLip", ground, c, radius)), paint, at, Quaternion.identity, 1f).transform.localScale = scale;+ var ring = UnitShowcase.Piece(token, RimName, own(RimMesh("UnitPlinthRim", ground, c, radius)), rim, at, Quaternion.identity, 1f);+ ring.transform.localScale = scale;+ var r = ring.GetComponent<MeshRenderer>();+ r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; r.receiveShadows = false;+ if (UnitFlags.Has(side))+ {+ float edge = FlagEdgeShare * radius;+ float east = Mathf.Min(edge * 0.95f, Mathf.Max(FlagEastShare * radius, UnitBadge.SizeM / 2f + FlagClearOfBadgeM));+ float north = Mathf.Sqrt(edge * edge - east * east);+ var foot = new Vector3(centre.x + east, 0f, centre.z + north);+ foot.y = FigureY(map, radius, foot.x, foot.z);+ var flag = UnitShowcase.Piece(token, FlagName, shared("unit-flag-" + side, () => UnitFlags.Build(side)!), paint, foot, Quaternion.identity,+ UnitBadge.FigureHeightM * UnitShowcase.FigureScale);+ flag.GetComponent<MeshRenderer>().sharedMaterials = new[] { paint, flagWhite, flagBlue };+ flag.AddComponent<UnitFlagFacing>(); // owner ruling, 2026-10-15: the cloth turns about the pole to face the camera+ var cam = Camera.main; if (cam != null) UnitFlagFacing.Face(flag.transform, cam.transform.position);+ }+ return ground(centre.x, centre.z) + LipShare * radius;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Units/UnitPlinth.cs.meta b/unity/Assets/Scripts/Map/Units/UnitPlinth.cs.metanew file mode 100644index 000000000..634c5e395--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitPlinth.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: f1592806571db479b8c04765dda9acc5\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Units/UnitShowcase.cs b/unity/Assets/Scripts/Map/Units/UnitShowcase.csindex 8767bf34a..f1e2fadc8 100644--- a/unity/Assets/Scripts/Map/Units/UnitShowcase.cs+++ b/unity/Assets/Scripts/Map/Units/UnitShowcase.cs@@ -18,15 +18,30 @@ namespace Statecraft.Game.Map.Units{public const string RootName = "UnitShowcase", ToggleName = "unitshowcase";- /// <summary>Symbolic scale, measured on the promo against the art checkpoint (docs/units.md): at 1920 px wide the- /// promo's riflemen stand about 87 px tall inside a ring about 190 px across; the first checkpoint, at 2600x, drew- /// them 113 px tall. So a man is drawn <see cref="FigureScale"/> times his real size (about 3.6 km at 2000x), and- /// the aircraft and the ship are sized against him, as Civ draws them, not against each other.</summary>- public const float FigureScale = 2000f;+ /// <summary>Symbolic scale: a man is drawn <see cref="FigureScale"/> times his real size (about 2.5 km). The first+ /// round matched promo 03 at 2000x (docs/units.md); demo2 T29 (owner's reference, 14 Oct) stands its figures about+ /// <see cref="HouseRatio"/> times a house, where 2000x stood them about 2.5 times the White City blocks beside the+ /// showcase trio at close30 (T54 audit), so 1400x (refs #197). The aircraft and the ship are sized against him, as+ /// Civ draws them, not against each other.</summary>+ public const float FigureScale = 1400f;+ /// <summary>The house T29's ratio is measured against at close30, as the T54 audit did: the White City block beside+ /// the showcase trio, the kit's seven-storey heart block (7 x 3.3 m at <see cref="Kits.KitScale.DefaultCityBlocks"/>;+ /// measured on the close30 render at about 1,300 m). A two-storey village house is about half of it.</summary>+ public const float ReferenceHouseM = 7f * 3.3f * Kits.KitScale.DefaultCityBlocks;+ /// <summary>A figure's height over <see cref="ReferenceHouseM"/>: about 1.8, as T29.</summary>+ public const float HouseRatio = UnitBadge.FigureHeightM * FigureScale / ReferenceHouseM;public const float AircraftScale = 420f; // span 11.2 m x 420 = 4.7 km: wider than a man is tallpublic 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>+ /// <summary>Trio spacing and the ring, as fractions of the hex circumradius. <see cref="TrioSpread"/> is the spacing+ /// the placer checks a token's spot with (UnitGround), kept so no spot moved.</summary>public const float TrioSpread = 0.40f, RingRadius = 0.66f, RingWidth = 0.035f, RingClearanceM = 25f;+ /// <summary>The spacing the figures are drawn at: shoulder to shoulder, as T29's trios (about 1.15 figure heights+ /// across; ours 1.15 too: 2 x 950 m between the outer figures' centres plus a figure's width, against a 2.5 km man).+ /// Narrower than <see cref="TrioSpread"/>, so the drawn figures stand inside the ground the placer checked.</summary>+ public const float DrawSpread = 0.19f;+ /// <summary>How far (in hexes) from <see cref="TrioAt"/> the showcase trio may move to stand clear of the kits and+ /// the routes (<see cref="TrioSpot"/>).</summary>+ public const float SpotSearchHexes = 2.2f;/// <summary>The flight: a circle of <see cref="LoopRadiusM"/> about <see cref="LoopCentre"/>, at/// <see cref="AltitudeM"/> above the highest ground under it, once every <see cref="LoopSeconds"/>, banked inwards.</summary>public const float LoopRadiusM = 16000f, AltitudeM = 4200f, LoopSeconds = 48f, BankDegrees = 28f;@@ -65,18 +80,18 @@ namespace Statecraft.Game.Map.UnitsRiflemanWoolCapType = "rifleman-1948-wool-cap", SpitfireType = "spitfire-mk9e-101sqn-1948", CorvetteType = "corvette-k20-1948",S199Type = "avia-s199-101sqn-1948";- /// <summary>The rifle trio's three looks, in the order a token adds them (1, 2 or 3 figures): offset (in hex- /// circumradii times <see cref="TrioSpread"/>) and heading.</summary>- internal static readonly (string type, UnitModels.Headgear hat, UnitModels.RiflePose pose, bool faded, UnityEngine.Vector2 offset, float heading)[] Trio =+ /// <summary>The rifle trio's three looks, in the order a token adds them (1, 2 or 3 figures), and their headings.+ /// They stand at <see cref="FigureOffsets"/>, the showcase as an in-play token.</summary>+ internal static readonly (string type, UnitModels.Headgear hat, UnitModels.RiflePose pose, bool faded, float heading)[] Trio ={- (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),+ (RiflemanSlouchHatType, UnitModels.Headgear.SlouchHat, UnitModels.RiflePose.Ready, false, 200f),+ (RiflemanHelmetType, UnitModels.Headgear.SteelHelmet, UnitModels.RiflePose.Grounded, true, 185f),+ (RiflemanWoolCapType, UnitModels.Headgear.WoolCap, UnitModels.RiflePose.Slung, false, 170f),};- /// <summary>Where an in-play token's figures stand (in hex circumradii times <see cref="TrioSpread"/>): one in the- /// middle, two side by side, or three spread across the ring as in promo 03, side by side across the view (the- /// middle one a step back), about 2 km apart so each figure reads on its own (review I6).</summary>+ /// <summary>Where a token's figures stand (in hex circumradii times the spread): one in the middle, two side by side,+ /// or three side by side across the view (the middle one a step back). The placer checks them at+ /// <see cref="TrioSpread"/>; they are drawn at <see cref="DrawSpread"/>, shoulder to shoulder as in T29.</summary>internal static Vector2[] FigureOffsets(int figures) => figures switch{1 => new[] { Vector2.zero },@@ -117,18 +132,25 @@ namespace Statecraft.Game.Map.Unitsvar 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 players+ Mesh Built(Mesh m) { assets.Own(m); return UnitPlinth.Upload(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, around the hex's centre.- var centre = HexCentreNear(map, TrioAt.lon, TrioAt.lat);+ // The trio: three riflemen shoulder to shoulder on their base, under the flag, at the clear spot nearest TrioAt.+ var centre = TrioSpot(map);var looks = Trio;- var holes = new List<(Vector2 centre, float radius)>();+ var offsets = FigureOffsets(looks.Length);+ float plinth = UnitPlinth.Radius(UnitPlinth.TrioWidth(offsets, DrawSpread * hex));+ var rim = assets.Own(new Material(ringTemplate) { name = "UnitPlinthRim", color = UnitPlinth.RimColour });+ var flagWhite = assets.Own(new Material(ringTemplate) { name = "UnitFlag (white)", color = UnitFlags.WhiteColour });+ var flagBlue = assets.Own(new Material(ringTemplate) { name = "UnitFlag (blue)", color = UnitFlags.BlueColour });+ flagBlue.renderQueue = flagWhite.renderQueue + 1; // the blue over the white+ UnitPlinth.Build(map, root.transform, centre, plinth, UnitData.Israel, m => UnitPlinth.Upload(assets.Own(m)), (_, build) => Built(build()), paint, rim, flagWhite, flagBlue);+ var holes = new List<(Vector2 centre, float radius)> { (new Vector2(centre.x, centre.z), plinth * UnitPlinth.RimOuter) };for (int i = 0; i < looks.Length; i++){- var (type, hat, pose, faded, offset, heading) = looks[i];- var p = Stand(map, centre + new Vector3(offset.x, 0, offset.y) * TrioSpread * hex);- holes.Add(TreeHole(p));+ var (type, hat, pose, faded, heading) = looks[i];+ var p = centre + new Vector3(offsets[i].x, 0, offsets[i].y) * DrawSpread * hex;+ p.y = UnitPlinth.FigureY(map, plinth, p.x, p.z);Piece(root.transform, $"Rifleman{i}", type, () => Built(UnitModels.Rifleman(hat, pose, faded, $"Rifleman1948-{i}")),paint, p, Quaternion.Euler(0, heading, 0), FigureScale);}@@ -167,10 +189,6 @@ namespace Statecraft.Game.Map.Unitsstatic readonly IReadOnlyList<(Vector2 centre, float radius)> NoHoles = Array.Empty<(Vector2, float)>();- /// <summary>The ground a figure standing at <paramref name="feet"/> keeps free of kit trees (issue #249): its boots'- /// radius, which is also its base's (<see cref="AddBase"/>). Its legs, body and rifle are far above every crown.</summary>- public static (Vector2 centre, float radius) TreeHole(Vector3 feet) => (new Vector2(feet.x, feet.z), FootRadiusM);-/// <summary>Leaves out the map's kit trees under <paramref name="holes"/> for <paramref name="owner"/> (an empty list/// gives them back), at draw time (Kits.VegetationLayer.Hide), so the kits' layout never changes. A map without kits/// has no trees to hide.</summary>@@ -225,62 +243,45 @@ namespace Statecraft.Game.Map.Unitsreturn 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)- {- p.y = map.Terrain.SampleHeight(p) + map.Terrain.transform.position.y;- return p;- }+ /// <summary>Where the showcase trio stands (review of #559): the centre of the land hex nearest <see cref="TrioAt"/>,+ /// within <see cref="SpotSearchHexes"/>, whose base keeps off every railway's and road's corridor. The kits keep a+ /// clearing there when the run asks for the showcase (<see cref="Clearing"/>, MapScene.ShowcaseClearing), as they do+ /// for a unit standing in a town, so no kit building stands on the base.</summary>+ public static Vector3 TrioSpot(MapScene map) { var c = TrioSpotXZ(map); return Ground(map, new Vector3(c.x, 0f, c.y)); }++ /// <summary>The kits' clearing for the showcase: its spot and its base's reach plus <see cref="ClearingMarginM"/>.</summary>+ public static (Vector2 centre, float radius) Clearing(MapScene map) => (TrioSpotXZ(map), BaseReach(map) + ClearingMarginM);+ public const float ClearingMarginM = 300f;- /// <summary>A figure's boots reach about 0.2 m from its centre: at <see cref="FigureScale"/>, 400 m on the map.</summary>- public const float FootRadiusM = 0.2f * FigureScale;+ static float BaseReach(MapScene map) =>+ UnitPlinth.Radius(UnitPlinth.TrioWidth(FigureOffsets(3), DrawSpread * map.Hexes.hex_size_km * 1000f)) * UnitPlinth.RimOuter;- /// <summary>Where a figure stands at <paramref name="p"/> (world x, z): on the highest ground under its boots- /// (<see cref="StandHeight"/> over <see cref="FootRadiusM"/>), so on a slope no boot sinks into the hill; the downhill- /// boot floats by at most the slope's rise over the foot radius (owner question, 2026-10-11: units on hard terrain).</summary>- public static Vector3 Stand(MapScene map, Vector3 p)+ static Vector2 TrioSpotXZ(MapScene map){- p.y = StandHeight((x, z) => map.Terrain.SampleHeight(new Vector3(x, 0, z)) + map.Terrain.transform.position.y, p.x, p.z, FootRadiusM);- return p;+ float hex = map.Hexes.hex_size_km * 1000f, reach = BaseReach(map);+ var w = map.Frame.ToWorld(TrioAt.lon, TrioAt.lat, 0); var want = new Vector2(w.x, w.z);+ var candidates = map.Hexes.hexes.Where(h => h.land).Select(h => { var c = map.Frame.ToWorld(h.lon, h.lat, 0); return new Vector2(c.x, c.z); })+ .Where(c => (c - want).magnitude <= SpotSearchHexes * hex).OrderBy(c => (c - want).sqrMagnitude).ToList();+ foreach (var c in candidates)+ if (RoutesClear(map, c, reach)) return c;+ return candidates.Count > 0 ? candidates[0] : want;}- /// <summary>The highest of <paramref name="heightAt"/> at (x, z), on two rings inside the circle of radius r (at a- /// half and three quarters of it) and at the corners of a 16-gon drawn round it (at r / cos 11.25 degrees), sixteen- /// points each: on a planar slope no point of the circle is higher, and a ridge under the boots is caught too.</summary>- public static float StandHeight(Func<float, float, float> heightAt, float x, float z, float r) => StandRange(heightAt, x, z, r).top;-- /// <summary>The highest and lowest of the same samples as <see cref="StandHeight"/>: where a figure stands, and- /// how far down the slope under its boots goes (its base reaches there: <see cref="Stand"/>).</summary>- public static (float top, float low) StandRange(Func<float, float, float> heightAt, float x, float z, float r)+ /// <summary>True when a base reaching <paramref name="reach"/> (m) from <paramref name="c"/> keeps off every route+ /// corridor.</summary>+ internal static bool RoutesClear(MapScene map, Vector2 c, float reach){- float top = heightAt(x, z), low = top;- foreach (var ring in new[] { 0.5f * r, 0.75f * r, r / Mathf.Cos(Mathf.PI / 16f) })- for (int k = 0; k < 16; k++)- {- float a = Mathf.PI / 8f * k, h = heightAt(x + Mathf.Cos(a) * ring, z + Mathf.Sin(a) * ring);- top = Mathf.Max(top, h); low = Mathf.Min(low, h);- }- return (top, low);+ foreach (var (line, half) in map.RouteCorridors)+ for (int i = 0; i + 1 < line.Count; i++)+ if (UnitGround.DistanceToSegment(c, line[i], line[i + 1]) < half + reach) return false;+ return true;}- /// <summary>A figure on a slope stands on a base, as a painted miniature does: a short disc in the palette's trodden-earth dust of the- /// boots' radius from its feet down to the lowest ground under them, so the downhill boot never floats. Not drawn- /// on ground flatter than this rise (m).</summary>- public const float BaseFromRiseM = 20f;-- /// <summary>The unit disc a base is drawn with (radius 1, from y = -1 to 0), scaled per figure.</summary>- public static Mesh BaseMesh(string name) =>- new MiniatureMesh().Lathe(Matrix4x4.identity, new List<Vector2> { new Vector2(-1f, 1f), new Vector2(0f, 1f) }, UnitPalette.Dust, 16, shade: 0.55f).Build(name);-- /// <summary>Adds the base under a figure standing at <paramref name="feet"/> when the ground under its boots falls- /// more than <see cref="BaseFromRiseM"/> below them (see <see cref="StandRange"/>).</summary>- internal static void AddBase(MapScene map, Transform figure, Vector3 feet, Mesh mesh, Material paint)+ /// <summary>The point on the terrain under <paramref name="p"/> (world x, z).</summary>+ public static Vector3 Ground(MapScene map, Vector3 p){- var (_, low) = StandRange((x, z) => map.Terrain.SampleHeight(new Vector3(x, 0, z)) + map.Terrain.transform.position.y, feet.x, feet.z, FootRadiusM);- float drop = feet.y - low;- if (drop <= BaseFromRiseM) return;- var go = Piece(figure.parent, "Base" + figure.name, mesh, paint, feet, Quaternion.identity, 1f);- go.transform.localScale = new Vector3(FootRadiusM, drop + 30f, FootRadiusM); // 30 m into the ground: the lowest sample is not the lowest point+ p.y = map.Terrain.SampleHeight(p) + map.Terrain.transform.position.y;+ return p;}/// <summary>The highest ground under the loop (sampled every 5 degrees and at its centre), so the aircraft neverdiff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 6a76c0ef5..7ac1103dc 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -299,9 +299,15 @@ namespace Statecraft.Game.UIvar camRig = rig = cameraController.GetComponent<CameraRig>();Own(new TopBarInset(root, camRig)); // the map is framed below the top barvar mini = minimap = Own(new MinimapPresenter(root, map.Hexes, text));- labels = Own(new MapLabelsPresenter(root, map, cameraController.GetComponent<Camera>(), null,+ var labelCamera = cameraController.GetComponent<Camera>();+ labels = Own(new MapLabelsPresenter(root, map, labelCamera, null,p => MapLabelsPresenter.TipOf(p, n => text.Format("map.today", n), text["map.mixed"], hebrew),- () => unitLayer != null ? unitLayer.KeepClear : null)); // the names keep clear of the unit tokens (issue #197)+ () => // the names keep clear of the unit tokens (issue #197), their badges and flags as this camera will draw them+ {+ if (unitLayer == null) return null;+ unitLayer.FaceCamera(labelCamera);+ return unitLayer.KeepClear;+ }));mini.Clicked += (lon, lat) => { camRig.LookAt = map.Frame.ToWorld(lon, lat, 0); cameraController.Settle(); SyncMinimap(); labels?.Refresh(); }; // the click may come after LateUpdate (review M6)// The minimap's whole-map button: the camera's own farthest zoom, over the middle of the map (no new rule).mini.Overview += () =>diff --git a/unity/Assets/Tests/EditMode/ReviewRecordCasesTests.cs b/unity/Assets/Tests/EditMode/ReviewRecordCasesTests.csindex 49bb8362d..fd31fdc7e 100644--- a/unity/Assets/Tests/EditMode/ReviewRecordCasesTests.cs+++ b/unity/Assets/Tests/EditMode/ReviewRecordCasesTests.cs@@ -53,6 +53,6 @@ public class ReviewRecordCasesTests[TestCaseSource(nameof(Cases))]public void TheUnitsFileAgrees(Case c) => Expect(c, () => UnitData.Parse(- "units:\n- id: a\n name: A\n number: '1'\n service: army\n sector: s\n status: draft\n wikipedia_only: true\n" + Lines(c, " ")+ "units:\n- id: a\n name: A\n number: '1'\n service: army\n side: israel\n sector: s\n status: draft\n wikipedia_only: true\n" + Lines(c, " ")+ " anchors:\n - {place: P, lon: 34.8, lat: 32.0, from: '1948-05-15', to: '1948-06-01', end_basis: source, end_note: n, sources: [{url: 'https://x.org', checked: '2026-10-11'}]}\n", "u.yaml"));}diff --git a/unity/Assets/Tests/EditMode/UnitPlinthTests.cs b/unity/Assets/Tests/EditMode/UnitPlinthTests.csnew file mode 100644index 000000000..edf29a234--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitPlinthTests.cs@@ -0,0 +1,834 @@+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Units;+using Statecraft.Sim;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;++/// <summary>Demo2 T29's token look (refs #197): every army token stands on a round earth plinth with a white rim and flies+/// its side's flag on a pole; a side with no sourced flag flies none. The figures stand about 1.8 times a house+/// (docs/units.md, "The plinth and the flag").</summary>+public class UnitPlinthTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static string CommittedYaml => File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName));+ static readonly DateTime[] Dates = { new DateTime(1948, 5, 29), new DateTime(1948, 7, 12), new DateTime(1948, 12, 4) };++ [SetUp] public void Readable() => UnitPlinth.KeepMeshesReadable = true; // the tests read the built meshes back+ [TearDown] public void Released() => UnitPlinth.KeepMeshesReadable = false;++ static GameState StateAt(DateTime date)+ {+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();+ s.Date = date; s.Rung = 5; s.Mobilization = 0.8;+ return s;+ }++ 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("MapFrame"));+ Statecraft.Game.Map.Kits.KitPopulation.Use(Statecraft.Game.Map.Kits.KitPopulation.Parse(+ File.ReadAllText(Path.Combine(Paths.Content, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName))));+ map.Build();+ return map;+ }++ static Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");++ static bool Painted(Mesh m, int slot) => m.uv.Any(uv => Mathf.Abs(uv.x - UnitPalette.U(slot)) < 1e-4f);++ /// <summary>A token's plinth, rim and flag: the plinth mesh is earth with a white rim; the flag is the side's own.</summary>+ static void AssertPlinth(MapScene map, Transform token, string side, string what)+ {+ var plinth = token.Find(UnitPlinth.PlinthName);+ Assert.IsNotNull(plinth, $"{what}: stands on a plinth");+ var mesh = plinth.GetComponent<MeshFilter>().sharedMesh;+ Assert.IsTrue(Painted(mesh, UnitPalette.Earth), $"{what}: the plinth is earth");+ var rim = token.Find(UnitPlinth.RimName);+ Assert.IsNotNull(rim, $"{what}: the plinth has its white rim");+ Assert.AreEqual(plinth.localScale.x, rim.localScale.x, 0.5f, $"{what}: the rim rings the plinth");+ Assert.IsNotNull(token.Find(UnitPlinth.LipName), $"{what}: the plinth has its edge lip");+ var flag = token.Find(UnitPlinth.FlagName);+ if (UnitFlags.Has(side))+ {+ Assert.IsNotNull(flag, $"{what}: flies its side's flag");+ Assert.AreEqual(UnitFlags.MeshName(side), flag.GetComponent<MeshFilter>().sharedMesh.name, $"{what}: the flag is {side}'s");+ }+ else Assert.IsNull(flag, $"{what}: {side} has no sourced flag, so none is drawn");+ var badge = token.Find("Badge");+ if (flag != null && badge != null) // the flag flies clear of the badge over the trio (a compact token's too)+ Assert.Greater(flag.position.x - badge.position.x, UnitBadge.SizeM / 2f, $"{what}: the flag's pole stands clear of the badge");+ var ground = UnitPlinth.HeightAt(map);+ foreach (var f in token.Cast<Transform>().Where(t => t.name.StartsWith("Rifleman")))+ Assert.AreEqual(ground(f.position.x, f.position.z) + UnitPlinth.LipShare * plinth.localScale.x, f.position.y, 0.5f,+ $"{what}/{f.name}: stands on the draped top at its feet");+ }++ // ---- Every token ----------------------------------------------------------------------------------------------++ /// <summary>On every date checked, every drawn army token has a plinth, a rim and its side's flag; aircraft and ships+ /// have none (they fly or float: deliberate, docs/units.md).</summary>+ [Test]+ public void EveryArmyTokenStandsOnAPlinthWithARimAndItsFlag()+ {+ var map = BuildMap();+ try+ {+ var units = UnitData.Parse(CommittedYaml);+ var layer = UnitLayer.Create(map, units, C.Hexes, still: true);+ int army = 0;+ foreach (var d in Dates)+ {+ layer.Show(C, StateAt(d));+ var tokens = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens");+ foreach (var p in layer.Tokens)+ {+ var t = tokens.Find(p.Token.Unit.Id);+ if (p.Token.Unit.Service == UnitData.Army) { AssertPlinth(map, t, p.Token.Unit.Side, $"{d:yyyy-MM-dd} {t.name}"); army++; }+ else+ {+ Assert.IsNull(t.Find(UnitPlinth.PlinthName), $"{t.name}: no plinth under an aircraft or a ship");+ Assert.IsNull(t.Find(UnitPlinth.FlagName), $"{t.name}: no flag on an aircraft or a ship");+ }+ }+ }+ Assert.Greater(army, 15, "army tokens were checked");+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The showcase trio (the promo captures' -units) has the same plinth and the Israeli flag.</summary>+ [Test]+ public void TheShowcaseTrioStandsOnAPlinthWithTheIsraeliFlag()+ {+ var map = BuildMap();+ try+ {+ var root = UnitShowcase.Spawn(map, still: true);+ AssertPlinth(map, root.transform, UnitData.Israel, "showcase");+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ // ---- The flag matches the side --------------------------------------------------------------------------------++ /// <summary>Every row of the unit file names its side, and every formation in it is Israel's (the file is the IDF's+ /// 1948 order of battle); only Israel has a flag (built from the 1948 specification), so no flag is invented.</summary>+ [Test]+ public void TheFlagIsTheSidesAndOnlyASourcedFlagIsDrawn()+ {+ var units = UnitData.Parse(CommittedYaml);+ Assert.IsTrue(units.All(u => u.Side == UnitData.Israel), "every 1948 formation in the file is Israel's");+ Assert.IsTrue(UnitFlags.Has(UnitData.Israel));+ foreach (var side in UnitData.Sides.Where(s => s != UnitData.Israel))+ {+ Assert.IsFalse(UnitFlags.Has(side), $"{side}: no sourced, licensed flag in the repo, so none");+ Assert.IsNull(UnitFlags.Build(side), side);+ }++ // An Arab side's token (as #226 will add): the same plinth and rim, and no flag.+ var map = BuildMap();+ try+ {+ var egypt = UnitData.Parse(CommittedYaml.Replace("side: israel", "side: egypt"));+ var layer = UnitLayer.Create(map, egypt, C.Hexes, still: true);+ layer.Show(C, StateAt(Dates[0]));+ var tokens = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens");+ var army = layer.Tokens.Where(p => p.Token.Unit.Service == UnitData.Army).ToList();+ Assert.Greater(army.Count, 3);+ foreach (var p in army) AssertPlinth(map, tokens.Find(p.Token.Unit.Id), "egypt", p.Token.Unit.Id);+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The Israeli flag as the Provisional Council's proclamation gives it (220 by 160, two sky-blue stripes 25+ /// broad at 15 from the top and the bottom, a Star of David of six stripes 5.5 broad whose triangles' bases are+ /// parallel to the stripes): every blue vertex lies in a stripe or in the star, every white one in the field.</summary>+ [Test]+ public void TheIsraeliFlagFollowsTheSpecification()+ {+ var m = UnitFlags.Build(UnitData.Israel);+ Assert.IsNotNull(m);+ var v = m!.vertices; var uv = m.uv;+ // To the specification's centimetres, the field's lower corner at the origin (the mesh is in figure heights).+ float k = 220f / UnitFlags.FlagWidth;+ Vector2 Cm(Vector3 p) => new Vector2((p.x - UnitFlags.FlagLeft) * k, (p.y - UnitFlags.FlagBottom) * k);+ int blue = 0, inStripes = 0, inStar = 0;+ for (int i = 0; i < v.Length; i++)+ {+ if (Mathf.Abs(uv[i].x - UnitPalette.U(UnitPalette.RoundelBlue)) > 1e-4f) continue;+ blue++;+ var c = Cm(v[i]);+ Assert.That(c.x, Is.InRange(-0.01f, 220.01f), "blue stays on the field");+ bool stripe = c.y >= 14.99f && c.y <= 40.01f || c.y >= 119.99f && c.y <= 145.01f;+ float r = (c - new Vector2(110f, 80f)).magnitude;+ bool star = r <= UnitFlags.StarOuterCm + 0.01f && r >= UnitFlags.StarOuterCm / 2f - 5.5f * 2f - 0.01f;+ Assert.IsTrue(stripe || star, $"a blue vertex at {c} (cm) is in neither a stripe nor the star");+ if (stripe) inStripes++; else inStar++;+ }+ Assert.AreEqual(2 * 2 * 2 * 4, inStripes, "two stripes, as quads on both faces of the flag (two-sided plates)");+ // The star, against the gazette: two equilateral triangles of 5.5 cm stripes, their bases parallel to the stripes,+ // centred between them; 69 cm across (the construction drawing; the law gives no size).+ var starPts = Enumerable.Range(0, v.Length).Where(i => Mathf.Abs(uv[i].x - UnitPalette.U(UnitPalette.RoundelBlue)) < 1e-4f)+ .Select(i => Cm(v[i])).Where(c => c.y > 41f && c.y < 119f).Select(c => c - new Vector2(110f, 80f)).ToList();+ Assert.AreEqual(69f / 2f, UnitFlags.StarOuterCm, 1e-4f, "69 cm across");+ foreach (var q in starPts)+ Assert.That(Mathf.Min(Mathf.Abs(q.magnitude - 34.5f), Mathf.Abs(q.magnitude - (34.5f - 2f * 5.5f))), Is.LessThan(0.01f),+ $"a star corner at {q.magnitude:0.00} cm from the centre: the outer corners at 34.5, the inner at 34.5 - 2 x 5.5");+ var outerAngles = starPts.Where(q => Mathf.Abs(q.magnitude - 34.5f) < 0.01f).Select(q => Mathf.Repeat(Mathf.Atan2(q.y, q.x) * Mathf.Rad2Deg, 360f)).ToList();+ var innerAngles = starPts.Where(q => Mathf.Abs(q.magnitude - 23.5f) < 0.01f).Select(q => Mathf.Repeat(Mathf.Atan2(q.y, q.x) * Mathf.Rad2Deg, 360f)).ToList();+ foreach (var want in new[] { 30f, 90f, 150f, 210f, 270f, 330f })+ {+ Assert.IsTrue(outerAngles.Any(a => Mathf.Abs(Mathf.DeltaAngle(a, want)) < 0.01f), $"an outer corner at {want} degrees (a point up and down: bases parallel to the stripes)");+ Assert.IsTrue(innerAngles.Any(a => Mathf.Abs(Mathf.DeltaAngle(a, want)) < 0.01f), $"an inner corner at {want} degrees");+ }+ Assert.IsTrue(outerAngles.Concat(innerAngles).All(a => new[] { 30f, 90f, 150f, 210f, 270f, 330f }.Any(w => Mathf.Abs(Mathf.DeltaAngle(a, w)) < 0.01f)), "no other corners: a hollow star of two triangles");+ Assert.AreEqual(6 * 2 * 2 * 4, inStar, "six star stripes, as quads on both faces");+ var white = Enumerable.Range(0, v.Length).Where(i => Mathf.Abs(uv[i].x - UnitPalette.U(UnitPalette.RoundelWhite)) < 1e-4f).Select(i => Cm(v[i])).ToList();+ Assert.AreEqual(0f, white.Min(c => c.x), 0.01f); Assert.AreEqual(220f, white.Max(c => c.x), 0.01f);+ Assert.AreEqual(0f, white.Min(c => c.y), 0.01f); Assert.AreEqual(160f, white.Max(c => c.y), 0.01f, "8:11");+ UnityEngine.Object.DestroyImmediate(m);+ }++ // ---- The scale ------------------------------------------------------------------------------------------------++ /// <summary>T29's figures stand about 1.8 times a house; T54 measured main's at about 2.5 at close30 against the White+ /// City blocks beside the showcase trio (the kit's seven-storey heart block). The ratio of the figure as drawn (its+ /// mesh's height times its scale, read off the built showcase) to that block is pinned to 1.6-2.0.</summary>+ [Test]+ public void TheFiguresStandAbout1Point8TimesAHouse()+ {+ Assert.That(UnitShowcase.HouseRatio, Is.InRange(1.6f, 2.0f), "the constant");+ var map = BuildMap();+ try+ {+ var root = UnitShowcase.Spawn(map, still: true);+ foreach (var i in new[] { 0, 1, 2 })+ {+ var f = root.transform.Find("Rifleman" + i);+ float drawn = f.GetComponent<MeshFilter>().sharedMesh.bounds.size.y * f.lossyScale.y;+ Assert.That(drawn / UnitShowcase.ReferenceHouseM, Is.InRange(1.6f, 2.0f), $"Rifleman{i} as drawn: {drawn:0} m");+ }+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ // ---- The ground -----------------------------------------------------------------------------------------------++ /// <summary>The base's top, in world space, at every vertex, edge midpoint and triangle centre: the points where a+ /// draped surface strays furthest from the ground between its samples.</summary>+ static IEnumerable<Vector3> SurfacePoints(Transform plinth)+ {+ var mesh = plinth.GetComponent<MeshFilter>().sharedMesh; var v = mesh.vertices; var t = mesh.triangles; var m = plinth.localToWorldMatrix;+ for (int i = 0; i < t.Length; i += 3)+ {+ Vector3 a = m.MultiplyPoint3x4(v[t[i]]), b = m.MultiplyPoint3x4(v[t[i + 1]]), c = m.MultiplyPoint3x4(v[t[i + 2]]);+ yield return a; yield return (a + b) / 2f; yield return (b + c) / 2f; yield return (a + c) / 2f; yield return (a + b + c) / 3f;+ }+ }++ /// <summary>Round 3 of #559, T29's base on the ground: on every hill token the map can draw (every army anchor of the+ /// unit file, each shown on its first day; a hill token is one whose ground spreads over <see cref="HillSpreadM"/>+ /// under its base, found from the terrain, not a hand list), the base's top follows the ground under it: at every+ /// vertex, edge midpoint and triangle centre it stands the lip (<see cref="UnitPlinth.LipShare"/> of its radius) over+ /// the ground, within <see cref="DrapeToleranceShare"/> of the lip. Half the lip: the top never dips into the ground and+ /// never floats more than one and a half lips over it, where a level disc stood 1,081 m over Harel's valley side.</summary>+ [Test]+ public void TheBaseFollowsTheGroundOnEveryHillToken()+ {+ var map = BuildMap();+ try+ {+ var units = UnitData.Parse(CommittedYaml);+ var layer = UnitLayer.Create(map, units, C.Hexes, still: true);+ var ground = UnitPlinth.HeightAt(map);+ var days = units.Where(u => u.Service == UnitData.Army && u.Hidden == null).SelectMany(u => u.Anchors)+ .Select(a => UnitData.Day(a.From)).Distinct().OrderBy(d => d).ToList();+ var worst = new Dictionary<string, (float stray, float spread, float tolerance)>();+ foreach (var d in days)+ {+ layer.Show(C, StateAt(d));+ foreach (Transform t in map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens"))+ {+ var plinth = t.Find(UnitPlinth.PlinthName); if (plinth == null) continue;+ float r = plinth.localScale.x, lip = UnitPlinth.LipShare * r, low = float.MaxValue, high = float.MinValue, stray = 0f;+ foreach (var p in SurfacePoints(plinth))+ {+ float g = ground(p.x, p.z);+ low = Mathf.Min(low, g); high = Mathf.Max(high, g);+ stray = Mathf.Max(stray, Mathf.Abs(p.y - g - lip));+ }+ if (high - low < HillSpreadM) continue; // not a hill token+ if (!worst.TryGetValue(t.name, out var w) || stray > w.stray) worst[t.name] = (stray, high - low, DrapeToleranceShare * lip);+ }+ }+ foreach (var kv in worst.OrderByDescending(kv => kv.Value.spread))+ Debug.Log($"UNITS drape {kv.Key}: ground spread {kv.Value.spread:0} m under the base, the top strays at most {kv.Value.stray:0.0} m from the lip (tolerance {kv.Value.tolerance:0} m)");+ CollectionAssert.IsSubsetOf(new[] { "harel", "golani" }, worst.Keys.ToList(), "Harel's and Golani's tokens are hill tokens");+ foreach (var kv in worst) Assert.LessOrEqual(kv.Value.stray, kv.Value.tolerance, $"{kv.Key}: the base strays {kv.Value.stray:0} m from the ground's shape");+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>A token is a hill token when the ground under its base spreads over this much (m).</summary>+ const float HillSpreadM = 100f;+ /// <summary>The most the base's top may stray from the lip over the ground, as a share of the lip.</summary>+ const float DrapeToleranceShare = 0.5f;++ /// <summary>The showcase trio (review of #559) stands clear of the kits and the routes, as an in-play token in a town+ /// does: in a run that asks for it, no kit building (the town census, placed as the map places them, with its clearing)+ /// and no railway or road corridor reaches its plinth.</summary>+ [Test]+ public void NoKitBuildingOrRailCrossesTheShowcasePlinth()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>();+ map.ShowcaseClearing = true; // as a ?units or -units run builds it+ map.Build();+ try+ {+ var root = UnitShowcase.Spawn(map, still: true);+ var plinth = root.transform.Find(UnitPlinth.PlinthName);+ var c = new Vector2(plinth.position.x, plinth.position.z);+ float r = plinth.localScale.x * 1.05f; // with the rim's overhang+ TownCensusTests.Census(map, out var placed);+ var hits = placed.Where(p => !p.InSea && (p.C - c).magnitude < r + 0.5f * Mathf.Sqrt(p.W * p.W + p.D * p.D)).ToList();+ var want = map.Frame.ToWorld(UnitShowcase.TrioAt.lon, UnitShowcase.TrioAt.lat, 0);+ Debug.Log($"UNITS showcase spot {(c - new Vector2(want.x, want.z)).magnitude:0} m from TrioAt, plinth reach {r:0} m");+ foreach (var h in hits)+ Debug.Log($"UNITS showcase hit {h.Id} {h.Kind} at {(h.C - c).magnitude:0} m, size {h.W:0}x{h.D:0}; in a footprint: " ++ string.Join(",", map.SettlementFootprints.Where(f => (f.centre - h.C).magnitude < f.radius * UnitGround.FootprintMargin).Select(f => $"{(f.centre - c).magnitude:0}/{f.radius:0}")));+ Assert.IsEmpty(hits, $"{hits.Count} kit pieces reach the showcase plinth, the first {(hits.Count > 0 ? hits[0].Id + " " + hits[0].Kind : "")}");+ foreach (var (line, half) in map.RouteCorridors)+ for (int i = 0; i + 1 < line.Count; i++)+ Assert.Greater(UnitGround.DistanceToSegment(c, line[i], line[i + 1]), r + half, "a railway or road crosses the showcase plinth");+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ // ---- T29's proportions (review of #559) -------------------------------------------------------------------------++ static float TrioWidth(Transform token)+ {+ float lo = float.MaxValue, hi = float.MinValue;+ foreach (var f in token.Cast<Transform>().Where(t => t.name.StartsWith("Rifleman")))+ {+ var b = f.GetComponent<MeshFilter>().sharedMesh.bounds; var m = f.localToWorldMatrix;+ for (int c = 0; c < 8; c++)+ {+ var w = m.MultiplyPoint3x4(new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z));+ lo = Mathf.Min(lo, w.x); hi = Mathf.Max(hi, w.x);+ }+ }+ return hi - lo;+ }++ /// <summary>T29's base hugs its trio: the rim's outer edge is 1.41, 1.62 and 1.71 times the figures' outer edges on+ /// three of its tokens. Ours, from the built geometry (the figures' meshes as drawn, the rim's outer radius), on every+ /// full-trio army token and the showcase, is pinned to 1.3-1.7.</summary>+ [Test]+ public void TheBaseHugsTheTrioAsInT29()+ {+ var map = BuildMap();+ try+ {+ var layer = UnitLayer.Create(map, UnitData.Parse(CommittedYaml), C.Hexes, still: true);+ layer.Show(C, StateAt(Dates[1]));+ var tokens = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").Cast<Transform>()+ .Where(t => t.Cast<Transform>().Count(f => f.name.StartsWith("Rifleman")) == 3).ToList();+ tokens.Add(UnitShowcase.Spawn(map, still: true).transform);+ Assert.Greater(tokens.Count, 4);+ foreach (var t in tokens)+ {+ float ratio = 2f * t.Find(UnitPlinth.PlinthName).localScale.x * UnitPlinth.RimOuter / TrioWidth(t);+ Debug.Log($"UNITS base/trio {t.name}: {ratio:0.00}");+ Assert.That(ratio, Is.InRange(1.3f, 1.7f), $"{t.name}: base {ratio:0.00} times the trio's width");+ }+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ static float Luma(Color c) => 0.2126f * c.r + 0.7152f * c.g + 0.0722f * c.b;++ /// <summary>The luma at a world point on a render: the brightest (<paramref name="max"/>) or the median of its 3x3+ /// pixels; NaN off screen or behind the camera.</summary>+ static float LumaAt(Texture2D tex, Camera cam, Vector3 world, bool max)+ {+ var v = cam.WorldToViewportPoint(world); var s = new Vector3(v.x * tex.width, v.y * tex.height, v.z); // the render's pixels, not the editor's screen+ int w = max ? 3 : 1; // the ring is a thin band a few pixels off its geometry (the ring shader's depth offset): its brightest pixel within 3 px+ if (s.z <= 0f || s.x < w + 1 || s.y < w + 1 || s.x > tex.width - w - 2 || s.y > tex.height - w - 2) return float.NaN;+ var l = new List<float>();+ for (int dx = -w; dx <= w; dx++) for (int dy = -w; dy <= w; dy++) l.Add(Luma(tex.GetPixel((int)s.x + dx, (int)s.y + dy)));+ l.Sort(); return max ? l[l.Count - 1] : l[l.Count / 2];+ }++ static float Median(IEnumerable<float> v) { var l = v.Where(x => !float.IsNaN(x)).OrderBy(x => x).ToList(); return l.Count == 0 ? float.NaN : l[l.Count / 2]; }++ /// <summary>Round 3 of #559, pinned on renders as T29 was measured: a 30 km look at Harel's hill token and at the showcase+ /// trio on the plain, rendered at 1920 x 1080 through the game's camera (its grade and lighting). Sampled at known world+ /// points: the base's top in front of the figures, the figures' shirts and the flag's white field; the ring as T29's was+ /// measured, from its bright, neutral pixels in the screen box of its front half. The bands are T29's measures (4x crops of the 1:12 frame), set before measuring ours:+ /// base luma 0.24-0.30 (band 0.18-0.36); ring 0.96-0.98 (at least 0.85) and 3.2-4.1 times the base (at least 2.8);+ /// figure torsos 0.15-0.24, 0.5-0.9 of the base (ours are logged, not pinned: an open owner question); flag white+ /// 0.83-0.91 (at least 0.8).</summary>+ [Test]+ public void TheBaseRingAndFlagReadAsT29OnARender()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>();+ map.ShowcaseClearing = true;+ map.Build();+ var rt = new RenderTexture(1920, 1080, 24); var tex = new Texture2D(1920, 1080, TextureFormat.RGB24, false);+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();+ try+ {+ var layer = UnitLayer.Create(map, UnitData.Parse(CommittedYaml), C.Hexes, still: true);+ layer.Show(C, StateAt(Dates[0]));+ var showcase = UnitShowcase.Spawn(map, still: true).transform;+ var tokens = new[] { map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").Find("harel"), showcase };+ foreach (var t in tokens)+ {+ var plinth = t.Find(UnitPlinth.PlinthName); float r = plinth.localScale.x;+ var (lon, lat) = map.Frame.ToLonLat(plinth.position);+ new PromoPose("t", lon, lat, 30000f, 0f).Apply(rig, map.Frame);+ UnitFlagFacing.FaceAll(cam.transform.position); // as the editor's captures do before a still render+ layer.FaceCamera(cam);+ cam.targetTexture = rt; cam.aspect = 1920f / 1080f; // project as the render does (not the editor screen's aspect)+ cam.Render(); RenderTexture.active = rt;+ tex.ReadPixels(new Rect(0, 0, 1920, 1080), 0, 0); tex.Apply();+ RenderTexture.active = null;+ var ground = UnitPlinth.HeightAt(map); var c = plinth.position;+ Vector3 At(float a, float share, float lift) { var p = c + new Vector3(Mathf.Cos(a), 0, Mathf.Sin(a)) * r * share; p.y = ground(p.x, p.z) + lift; return p; }+ var front = Enumerable.Range(0, 15).Select(k => Mathf.Deg2Rad * (205f + 9f * k)).ToList(); // the camera's side+ // The ring's band as built (its vertices stand over the highest ground across it), on the camera's side.+ var rimT = t.Find(UnitPlinth.RimName); var rv = rimT.GetComponent<MeshFilter>().sharedMesh.vertices;+ var bandMids = Enumerable.Range(0, rv.Length / 2).Select(i => rimT.TransformPoint((rv[2 * i] + rv[2 * i + 1]) / 2f))+ .Where(p => p.z < c.z - 0.5f * r).ToList();+ // As T29 was measured: within the screen box of the ring's front half, the mean luma of its bright, neutral+ // pixels (luma over 0.75, chroma under 0.12), and how many there are (a dim or missing ring finds few).+ var px = bandMids.Select(p => cam.WorldToViewportPoint(p)).Where(v => v.z > 0f).Select(v => new Vector2(v.x * tex.width, v.y * tex.height)).ToList();+ int x0 = Mathf.Max(0, (int)px.Min(q => q.x) - 4), x1 = Mathf.Min(tex.width - 1, (int)px.Max(q => q.x) + 4);+ int y0 = Mathf.Max(0, (int)px.Min(q => q.y) - 4), y1 = Mathf.Min(tex.height - 1, (int)px.Max(q => q.y) + 4);+ float sum = 0f; int count = 0;+ for (int x = x0; x <= x1; x++) for (int y = y0; y <= y1; y++)+ {+ var col = tex.GetPixel(x, y); float lu = Luma(col), chroma = Mathf.Max(col.r, Mathf.Max(col.g, col.b)) - Mathf.Min(col.r, Mathf.Min(col.g, col.b));+ if (lu > 0.75f && chroma < 0.12f) { sum += lu; count++; }+ }+ float ring = count > 0 ? sum / count : 0f;+ float bas = Median(front.SelectMany(a => new[] { 0.6f, 0.75f, 0.88f }.Select(sh => LumaAt(tex, cam, At(a, sh, UnitPlinth.LipShare * r), false))));+ float shirt = Median(t.Cast<Transform>().Where(f => f.name.StartsWith("Rifleman")).Select(f => LumaAt(tex, cam, f.TransformPoint(new Vector3(0f, 1.25f, 0.12f)), false)));+ var flag = t.Find(UnitPlinth.FlagName);+ float k2 = UnitFlags.FlagWidth / 220f;+ float white = Median(new[] { (15f, 80f), (205f, 80f), (35f, 50f), (185f, 110f), (60f, 80f), (160f, 80f) }+ .Select(q => LumaAt(tex, cam, flag.TransformPoint(new Vector3(UnitFlags.FlagLeft + q.Item1 * k2, UnitFlags.FlagBottom + q.Item2 * k2, 0f)), false)));+ var png = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"statecraft-unitsrender-{t.name}.png");+ System.IO.File.WriteAllBytes(png, tex.EncodeToPNG());+ Debug.Log($"UNITS render {t.name} saved {png}; ring box {x0}-{x1} x {y0}-{y1}, {count} ring pixels, base at {cam.WorldToViewportPoint(At(front[7], 0.75f, UnitPlinth.LipShare * r))}, flag at {cam.WorldToViewportPoint(flag.TransformPoint(new Vector3(UnitFlags.FlagLeft + 15f * k2, UnitFlags.FlagBottom + 80f * k2, 0f)))}");+ Debug.Log($"UNITS render {t.name}: base {bas:0.000}, ring {ring:0.000} ({ring / bas:0.00}x the base), shirts {shirt:0.000} ({shirt / bas:0.00} of the base), flag white {white:0.000}");+ Assert.That(bas, Is.InRange(0.18f, 0.36f), $"{t.name}: the base's earth is dark, as T29's");+ Assert.GreaterOrEqual(count, 300, $"{t.name}: the ring shows as a band of bright white pixels");+ Assert.GreaterOrEqual(ring, 0.85f, $"{t.name}: the ring is bright");+ Assert.GreaterOrEqual(ring / bas, 2.8f, $"{t.name}: the ring stands out from the base as T29's");+ // The figures against their base are recorded, not pinned: T29's are darker than it (0.5-0.9); on the owner's base+ // A ours read 1.17 at Harel and 0.92 on the plain (the showcase), so on flat ground they barely part from it in+ // brightness. An open owner question in #559 (the look is the owner's), not a test to fit.+ Assert.GreaterOrEqual(white, 0.8f, $"{t.name}: the flag reads white");+ }+ }+ finally { cam.targetTexture = null; cam.ResetAspect(); RenderTexture.active = null; UnityEngine.Object.DestroyImmediate(rt); UnityEngine.Object.DestroyImmediate(tex); UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>T29's flag cloth is 0.47-0.60 of a figure's height tall and 0.65-0.70 wide, on a pole about 1.5 figures+ /// tall at the base's back edge. Ours is pinned to 0.45-0.65 tall and 0.6-0.8 wide, the pole 1.3-1.7, its foot at+ /// 0.85-1.0 of the base's radius on every army token.</summary>+ [Test]+ public void TheFlagIsAboutHalfAFigureTallOnTheBasesEdge()+ {+ float cloth = (UnitFlags.FlagTop - UnitFlags.FlagBottom);+ Assert.That(cloth, Is.InRange(0.45f, 0.65f), "the cloth's height in figure heights");+ Assert.That(UnitFlags.FlagWidth, Is.InRange(0.6f, 0.8f), "the cloth's width in figure heights");+ Assert.That(UnitFlags.PoleHeight, Is.InRange(1.3f, 1.7f), "the pole in figure heights");+ var map = BuildMap();+ try+ {+ var layer = UnitLayer.Create(map, UnitData.Parse(CommittedYaml), C.Hexes, still: true);+ int n = 0;+ foreach (var d in Dates)+ {+ layer.Show(C, StateAt(d));+ foreach (Transform t in map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens"))+ {+ var flag = t.Find(UnitPlinth.FlagName); if (flag == null) continue;+ var plinth = t.Find(UnitPlinth.PlinthName);+ float at = new Vector2(flag.position.x - plinth.position.x, flag.position.z - plinth.position.z).magnitude / plinth.localScale.x;+ Assert.That(at, Is.InRange(0.85f, 1.0f), $"{d:yyyy-MM-dd} {t.name}: the pole on the base's edge");+ Assert.Greater(flag.position.z, plinth.position.z, $"{t.name}: at the back, away from the camera");+ n++;+ }+ }+ Assert.Greater(n, 15);+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ // ---- Round 4 of #559 (personal2's second review) ------------------------------------------------------------++ static int LiveMeshes(string prefix) => Resources.FindObjectsOfTypeAll<Mesh>().Count(m => m != null && m.name.StartsWith(prefix));++ /// <summary>M1: a roster change frees the meshes the last one built. The draped top, its lip and its ring are built per+ /// token (they follow its ground); after six roster changes the live ones are those of the tokens drawn now, not six+ /// times as many.</summary>+ [Test]+ public void ARosterChangeFreesThePerTokenMeshes()+ {+ var map = BuildMap();+ try+ {+ var layer = UnitLayer.Create(map, UnitData.Parse(CommittedYaml), C.Hexes, still: true);+ for (int i = 0; i < 6; i++)+ {+ var s = StateAt(Dates[1]); s.Mobilization = i % 2 == 0 ? 0.8 : 0.3; // the call-up changes the roster+ Assert.IsTrue(layer.Show(C, s), $"rebuild {i}");+ }+ int bases = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").Cast<Transform>().Count(t => t.Find(UnitPlinth.PlinthName) != null);+ int live = LiveMeshes("UnitPlinth");+ Debug.Log($"UNITS meshes: {bases} bases drawn, {live} live base, lip and ring meshes after 6 roster changes");+ Assert.AreEqual(3 * bases, live, "one top, one lip and one ring per drawn base, no more");+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The largest |top - (ground + lip)| over a base built at (x, z) of radius r: at every vertex, edge midpoint+ /// and triangle centre of the mesh UnitPlinth.TopMesh builds there.</summary>+ static float Stray(MapScene map, Vector2 c, float r)+ {+ var ground = UnitPlinth.HeightAt(map); float lip = UnitPlinth.LipShare * r, worst = 0f;+ var mesh = UnitPlinth.TopMesh("probe", map, c, r);+ var v = mesh.vertices; var t = mesh.triangles;+ Vector3 W(int i) => new Vector3(c.x + v[i].x * r, v[i].y, c.y + v[i].z * r);+ for (int i = 0; i < t.Length; i += 3)+ {+ Vector3 a = W(t[i]), b = W(t[i + 1]), d = W(t[i + 2]);+ foreach (var p in new[] { a, (a + b) / 2f, (b + d) / 2f, (a + d) / 2f, (a + b + d) / 3f })+ worst = Mathf.Max(worst, Mathf.Abs(p.y - ground(p.x, p.z) - lip));+ }+ UnityEngine.Object.DestroyImmediate(mesh);+ return worst;+ }++ /// <summary>Should-fix 1: the drape holds wherever a token could stand, not only on today's spots. On every land hex of the+ /// map whose ground spreads more than <see cref="HillSpreadM"/> under a full-size base at its centre, the base's top+ /// strays at most <see cref="DrapeToleranceShare"/> of the lip (half the lip: it never touches the ground and never+ /// floats more than one and a half lips over it), and at the 99th percentile at most a quarter of the lip (headroom).</summary>+ [Test]+ public void TheBaseFollowsTheGroundOnEveryHillHexOfTheMap()+ {+ var map = BuildMap();+ try+ {+ float hex = map.Hexes.hex_size_km * 1000f, r = UnitPlinth.Radius(UnitPlinth.TrioWidth(UnitShowcase.FigureOffsets(3), UnitShowcase.DrawSpread * hex));+ float lip = UnitPlinth.LipShare * r; var ground = UnitPlinth.HeightAt(map);+ var strays = new List<(float stray, double lon, double lat)>();+ foreach (var h in map.Hexes.hexes.Where(h => h.land))+ {+ var w = map.Frame.ToWorld(h.lon, h.lat, 0); var c = new Vector2(w.x, w.z);+ float lo = float.MaxValue, hi = float.MinValue;+ for (int k = 0; k < 16; k++) foreach (var sh in new[] { 0f, 0.5f, 1f })+ {+ float a = Mathf.PI / 8f * k, g = ground(c.x + Mathf.Cos(a) * r * sh, c.y + Mathf.Sin(a) * r * sh);+ lo = Mathf.Min(lo, g); hi = Mathf.Max(hi, g);+ }+ if (hi - lo < HillSpreadM) continue;+ strays.Add((Stray(map, c, r), h.lon, h.lat));+ }+ Assert.Greater(strays.Count, 500, "the map's hill hexes were found (not a vacuous pass)");+ strays.Sort((a, b) => a.stray.CompareTo(b.stray));+ var worst = strays[strays.Count - 1]; float p99 = strays[(int)(0.99f * (strays.Count - 1))].stray, p50 = strays[strays.Count / 2].stray;+ Debug.Log($"UNITS drape map: {strays.Count} hill hexes, stray p50 {p50:0.0} m, p99 {p99:0.0} m, max {worst.stray:0.0} m at {worst.lon:0.000},{worst.lat:0.000} (lip {lip:0} m)");+ Assert.LessOrEqual(worst.stray, DrapeToleranceShare * lip, $"the worst hill hex ({worst.lon:0.000},{worst.lat:0.000})");+ Assert.LessOrEqual(p99, 0.25f * lip, "headroom: the 99th percentile within a quarter of the lip");+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Should-fix 2: a figure stands on the draped top at its own point (the ground there plus the lip), within a+ /// metre, on every army token of the war, and the ground under its boots rises at most a tenth of its height over its+ /// feet (the base hides an uphill boot set into it).</summary>+ [Test]+ public void EveryFigureStandsOnTheDrapedTop()+ {+ var map = BuildMap();+ try+ {+ var units = UnitData.Parse(CommittedYaml);+ var layer = UnitLayer.Create(map, units, C.Hexes, still: true);+ var ground = UnitPlinth.HeightAt(map);+ float h = UnitBadge.FigureHeightM * UnitShowcase.FigureScale, worstFloat = 0f, worstSink = 0f; int n = 0;+ foreach (var d in units.Where(u => u.Service == UnitData.Army && u.Hidden == null).SelectMany(u => u.Anchors).Select(a => UnitData.Day(a.From)).Distinct())+ {+ layer.Show(C, StateAt(d));+ foreach (Transform t in map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens"))+ {+ var plinth = t.Find(UnitPlinth.PlinthName); if (plinth == null) continue;+ float lip = UnitPlinth.LipShare * plinth.localScale.x;+ foreach (var f in t.Cast<Transform>().Where(x => x.name.StartsWith("Rifleman")))+ {+ var p = f.position; float top = ground(p.x, p.z) + lip;+ worstFloat = Mathf.Max(worstFloat, p.y - top);+ Assert.AreEqual(top, p.y, 1f, $"{d:yyyy-MM-dd} {t.name}/{f.name}: on the draped top at its feet");+ float boots = UnitPlinth.BootsTop(ground, p.x, p.z);+ worstSink = Mathf.Max(worstSink, boots - p.y);+ Assert.LessOrEqual(boots - p.y, 0.1f * h, $"{t.name}/{f.name}: the ground under its boots rises {boots - p.y:0} m over its feet");+ n++;+ }+ }+ }+ Debug.Log($"UNITS seat: {n} figures, worst float over the top {worstFloat:0.0} m, worst ground under the boots over the feet {worstSink:0} m");+ Assert.Greater(n, 40);+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The screen rectangle (pixels of a w x h render) of the meshes under <paramref name="parts"/>.</summary>+ static Rect ScreenRect(Camera cam, IEnumerable<Transform> parts, int w, int h)+ {+ float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;+ foreach (var part in parts)+ foreach (var f in part.GetComponentsInChildren<MeshFilter>())+ {+ var m = f.transform.localToWorldMatrix;+ foreach (var p in f.sharedMesh.vertices) // the silhouette's own extent, not its box's+ {+ var v = cam.WorldToViewportPoint(m.MultiplyPoint3x4(p));+ x0 = Mathf.Min(x0, v.x * w); x1 = Mathf.Max(x1, v.x * w); y0 = Mathf.Min(y0, v.y * h); y1 = Mathf.Max(y1, v.y * h);+ }+ }+ return Rect.MinMaxRect(x0, y0, x1, y1);+ }++ /// <summary>Should-fix 3: the badge keeps off the figures and the flag. At gameplay03 and at close30 and a 30 km look at+ /// Harel, each at camera yaw 0, 90 and 180, with the badge and the flag turned to the camera as it renders, the badge's+ /// screen rectangle (its vertices' extent) overlaps neither the figures' nor the flag's.</summary>+ [Test]+ public void TheBadgeKeepsOffTheFiguresAndTheFlag()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>();+ map.Build();+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();+ try+ {+ var layer = UnitLayer.Create(map, UnitData.Parse(CommittedYaml), C.Hexes, still: true);+ layer.Show(C, StateAt(Dates[0]));+ var tokens = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").Cast<Transform>().Where(t => t.Find(UnitPlinth.PlinthName) != null).ToList();+ var harel = tokens.First(t => t.name == "harel").Find(UnitPlinth.PlinthName).position;+ var (hlon, hlat) = map.Frame.ToLonLat(harel);+ int checkedPairs = 0; var judged = new List<string>();+ var poses = new List<PromoPose> { PromoPose.Gameplay03 };+ foreach (var yaw in new[] { 0f, 90f, 180f })+ {+ poses.Add(new PromoPose($"close30y{yaw:0}", 34.83, 32.00, 30000f, yaw));+ poses.Add(new PromoPose($"harel30y{yaw:0}", hlon, hlat, 30000f, yaw));+ }+ cam.aspect = 1920f / 1080f; // project as a 1920 x 1080 render+ foreach (var pose in poses)+ {+ pose.Apply(rig, map.Frame);+ UnitFlagFacing.FaceAll(cam.transform.position); // the flags turn to this camera+ layer.FaceCamera(cam); // and the badges+ foreach (var t in tokens)+ {+ var badge = t.Find("Badge");+ if (cam.WorldToViewportPoint(badge.position).z <= 0f) continue;+ var b = ScreenRect(cam, new[] { badge }, 1920, 1080);+ var figures = ScreenRect(cam, t.Cast<Transform>().Where(x => x.name.StartsWith("Rifleman")), 1920, 1080);+ var screen = new Rect(0, 0, 1920, 1080);+ bool Whole(Rect q) => q.xMin >= 0 && q.yMin >= 0 && q.xMax <= screen.xMax && q.yMax <= screen.yMax;+ if (!Whole(b) || !Whole(figures)) continue; // a token cut by the frame's edge is not judged+ var flag = ScreenRect(cam, new[] { t.Find(UnitPlinth.FlagName) }, 1920, 1080);+ var pl = t.Find(UnitPlinth.PlinthName).position; var fl = t.Find(UnitPlinth.FlagName);+ Debug.Log($"UNITS badge {pose.Name} {t.name}: badge {b.yMin:0}-{b.yMax:0} x {b.xMin:0}-{b.xMax:0}, figures top {figures.yMax:0}, flag {flag.xMin:0}-{flag.xMax:0} x {flag.yMin:0}-{flag.yMax:0}; world badge-centre {badge.position - pl}, pole {fl.position - pl}, base r {t.Find(UnitPlinth.PlinthName).localScale.x:0}");+ Assert.IsFalse(b.Overlaps(figures), $"{pose.Name} {t.name}: the badge covers the figures");+ Assert.IsFalse(b.Overlaps(flag), $"{pose.Name} {t.name}: the badge covers the flag");+ checkedPairs++; judged.Add(pose.Name + "/" + t.name);+ }+ }+ // Not vacuous: every yaw of the Harel look judged Harel's token, and gameplay03 judged its tokens on screen+ // (close30 frames no whole in-play token: those cut by the frame's edge are skipped).+ foreach (var yaw in new[] { 0, 90, 180 }) CollectionAssert.Contains(judged, $"harel30y{yaw}/harel");+ Assert.GreaterOrEqual(judged.Count(j => j.StartsWith("gameplay03/")), 2);+ }+ finally { cam.ResetAspect(); UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Round 4 of #559: the map's names keep clear of each token's badge and flag where the camera draws them. The+ /// badge moves with the camera's yaw and the flag turns to it, so after FaceCamera at yaw 0, 90, 180 and 270 each token's+ /// keep-clear boxes hold its badge's own cube (the badge's width, round its centre: not a box round every place the yaw+ /// could take it, which pushed Tel Aviv's name off its kit at gameplay03) and every vertex of its flag as turned.</summary>+ [Test]+ public void TheKeepClearBoxesFollowTheBadgeAndTheFlagAsTheCameraTurns()+ {+ var map = BuildMap();+ try+ {+ var layer = UnitLayer.Create(map, UnitData.Parse(CommittedYaml), C.Hexes, still: true);+ layer.Show(C, StateAt(Dates[0]));+ var tokens = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens");+ var cam = Camera.main; Assert.IsNotNull(cam, "the default scene's camera");+ int flags = 0;+ foreach (var yaw in new[] { 0f, 90f, 180f, 270f })+ for (int i = 0; i < layer.Tokens.Count; i++)+ {+ var token = tokens.Find(layer.Tokens[i].Token.Unit.Id);+ cam.transform.rotation = Quaternion.Euler(CameraRig.Pitch, yaw, 0f);+ cam.transform.position = token.Find(UnitPlinth.PlinthName) is { } plinth ? plinth.position - cam.transform.forward * 30000f+ : token.Find("Badge").position - cam.transform.forward * 30000f; // a 30 km look at the token+ layer.FaceCamera(cam);+ var boxes = layer.KeepClear[i]; var badge = token.Find("Badge");+ Assert.Less((boxes[0].center - badge.position).magnitude, 1f, $"yaw {yaw} {token.name}: the badge's box is round the badge as drawn");+ Assert.AreEqual(UnitBadge.SizeM, boxes[0].size.x, 1f, $"yaw {yaw} {token.name}: the badge's box is its own width");+ Assert.AreEqual(UnitBadge.SizeM, boxes[0].size.z, 1f, $"yaw {yaw} {token.name}: the badge's box is its own depth");+ var flag = token.Find(UnitPlinth.FlagName); if (flag == null) continue;+ var grown = boxes[1]; grown.Expand(1f);+ var m = flag.localToWorldMatrix;+ foreach (var v in flag.GetComponent<MeshFilter>().sharedMesh.vertices)+ Assert.IsTrue(grown.Contains(m.MultiplyPoint3x4(v)), $"yaw {yaw} {token.name}: the flag as turned is inside the pieces' box");+ flags++;+ }+ Assert.Greater(flags, 20, "every flag at every yaw");+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Owner ruling (2026-10-15): "billboard the flag". At gameplay03 and at a 30 km look at Harel at camera yaw 0,+ /// 90 and 180, each flag turns about its pole as the camera renders: the cloth's normal points at the camera, seen from+ /// above, within 2 degrees; the pole stays upright (the flag's up is the world's); its foot does not move.</summary>+ [Test]+ public void TheFlagTurnsAboutItsPoleToFaceTheCamera()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>();+ map.Build();+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>(); var rt = new RenderTexture(64, 36, 24);+ try+ {+ var layer = UnitLayer.Create(map, UnitData.Parse(CommittedYaml), C.Hexes, still: true);+ layer.Show(C, StateAt(Dates[0]));+ var flags = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").Cast<Transform>().Select(t => t.Find(UnitPlinth.FlagName)).Where(f => f != null).ToList();+ flags.Add(UnitShowcase.Spawn(map, still: true).transform.Find(UnitPlinth.FlagName));+ var feet = flags.Select(f => f.position).ToList();+ var (hlon, hlat) = map.Frame.ToLonLat(flags[0].position);+ int n = 0;+ foreach (var yaw in new[] { 0f, 90f, 180f })+ foreach (var pose in new[] { new PromoPose("g", PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat, PromoPose.Gameplay03.Distance, yaw), new PromoPose("h", hlon, hlat, 30000f, yaw) })+ {+ pose.Apply(rig, map.Frame);+ cam.targetTexture = rt; cam.Render(); cam.targetTexture = null;+ for (int i = 0; i < flags.Count; i++)+ {+ var f = flags[i];+ var toCam = cam.transform.position - f.position; toCam.y = 0f;+ var normal = f.TransformDirection(Vector3.back); normal.y = 0f; // the cloth lies in the flag's XY plane+ float angle = Vector3.Angle(normal, toCam);+ Assert.That(Mathf.Min(angle, 180f - angle), Is.LessThanOrEqualTo(2f), $"yaw {yaw} {f.parent.name}: the cloth faces the camera");+ Assert.Less(angle, 90f, $"yaw {yaw} {f.parent.name}: its front, not its back, so the cloth flies to the camera's right");+ Assert.Greater(Vector3.Dot(f.up, Vector3.up), 0.9999f, $"yaw {yaw} {f.parent.name}: the pole stays upright");+ Assert.Less((f.position - feet[i]).magnitude, 0.01f, $"{f.parent.name}: the pole's foot stays put");+ n++;+ }+ }+ Assert.Greater(n, 30);+ }+ finally { cam.targetTexture = null; UnityEngine.Object.DestroyImmediate(rt); UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Two probe tokens on the steepest ground the review named (personal2, round 3): one anchored at Rosh Pinna and+ /// one at Sha'ar HaGai, placed by the game's own placer from a two-row unit file (test data only). Each base's top follows+ /// the ground within half a metre, its figures stand on it, and a 30 km render of each is saved for the review's sheet.</summary>+ [Test]+ public void ProbeTokensAtRoshPinnaAndShaarHaGaiStandOnTheGround()+ {+ const string Src = "sources: [{url: 'https://example.org/probe', checked: '2026-10-15'}]";+ string Row(string id, string place, double lon, double lat) =>+ $"- {{id: {id}, name: Probe {id}, number: '0', service: army, side: israel, sector: probe, status: draft, wikipedia_only: true, " ++ $"anchors: [{{place: {place}, lon: {lon.ToString(System.Globalization.CultureInfo.InvariantCulture)}, lat: {lat.ToString(System.Globalization.CultureInfo.InvariantCulture)}, " ++ $"from: '1948-05-15', to: '1948-06-30', end_basis: source, end_note: probe, {Src}}}]}}";+ var yaml = "units:\n" + Row("probe_rosh_pinna", "Rosh Pinna", 35.5433, 32.9693) + "\n" + Row("probe_shaar_hagai", "Sha'ar HaGai", 35.03333, 31.81667);+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>();+ map.Build();+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();+ var rt = new RenderTexture(1920, 1080, 24); var tex = new Texture2D(1920, 1080, TextureFormat.RGB24, false);+ try+ {+ var layer = UnitLayer.Create(map, UnitData.Parse(yaml), C.Hexes, still: true);+ layer.Show(C, StateAt(new DateTime(1948, 5, 29)));+ var tokens = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").Cast<Transform>().ToList();+ Assert.AreEqual(2, tokens.Count, "both probes drawn");+ var ground = UnitPlinth.HeightAt(map);+ foreach (var t in tokens)+ {+ var plinth = t.Find(UnitPlinth.PlinthName); float r = plinth.localScale.x, lip = UnitPlinth.LipShare * r, stray = 0f, lo = float.MaxValue, hi = float.MinValue;+ foreach (var p in SurfacePoints(plinth)) { float g = ground(p.x, p.z); lo = Mathf.Min(lo, g); hi = Mathf.Max(hi, g); stray = Mathf.Max(stray, Mathf.Abs(p.y - g - lip)); }+ Debug.Log($"UNITS probe {t.name}: ground spread {hi - lo:0} m under the base, the top strays {stray:0.00} m from the lip");+ Assert.LessOrEqual(stray, 0.5f, $"{t.name}: the top follows the ground");+ foreach (var f in t.Cast<Transform>().Where(x => x.name.StartsWith("Rifleman")))+ Assert.AreEqual(ground(f.position.x, f.position.z) + lip, f.position.y, 1f, $"{t.name}/{f.name}: on the draped top");+ var (lon, lat) = map.Frame.ToLonLat(plinth.position);+ new PromoPose("p", lon, lat, 30000f, 0f).Apply(rig, map.Frame);+ UnitFlagFacing.FaceAll(cam.transform.position);+ foreach (var b in t.GetComponentsInChildren<UnitBadge>()) b.transform.rotation = cam.transform.rotation;+ cam.targetTexture = rt; cam.aspect = 1920f / 1080f; cam.Render(); RenderTexture.active = rt;+ tex.ReadPixels(new Rect(0, 0, 1920, 1080), 0, 0); tex.Apply();+ cam.targetTexture = null; cam.ResetAspect(); RenderTexture.active = null;+ var png = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"statecraft-unitsrender-{t.name}.png");+ System.IO.File.WriteAllBytes(png, tex.EncodeToPNG());+ Debug.Log($"UNITS probe {t.name} at {lon:0.000},{lat:0.000} saved {png}");+ }+ }+ finally { cam.targetTexture = null; RenderTexture.active = null; UnityEngine.Object.DestroyImmediate(rt); UnityEngine.Object.DestroyImmediate(tex); UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The base, its lip, its ring and the flag cost little: the base, lip and ring are built per token (they+ /// follow its ground) and low-poly; the flag is one shared mesh per side; the base, lip and the flag's pole are in the+ /// units' one palette material, the ring and the cloth in three unlit colours shared by every token.</summary>+ [Test]+ public void ThePlinthAndTheFlagAreLowPolyAndShareTheirMaterials()+ {+ var map = BuildMap();+ try+ {+ var layer = UnitLayer.Create(map, UnitData.Parse(CommittedYaml), C.Hexes, still: true);+ layer.Show(C, StateAt(Dates[1]));+ var tokens = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").Cast<Transform>().Where(t => t.Find(UnitPlinth.PlinthName) != null).ToList();+ Assert.Greater(tokens.Count, 4);+ var figureMat = tokens[0].GetComponentsInChildren<MeshRenderer>().First(r => r.name.StartsWith("Rifleman")).sharedMaterial;+ int Tris(Transform t, string n) => t.Find(n).GetComponent<MeshFilter>().sharedMesh.triangles.Length / 3;+ foreach (var t in tokens)+ {+ Assert.AreSame(figureMat, t.Find(UnitPlinth.PlinthName).GetComponent<MeshRenderer>().sharedMaterial, t.name);+ Assert.AreSame(figureMat, t.Find(UnitPlinth.LipName).GetComponent<MeshRenderer>().sharedMaterial, t.name);+ Assert.LessOrEqual(Tris(t, UnitPlinth.PlinthName), 3000, $"{t.name}: the base is low-poly (the terrain's own cells under it)");+ Debug.Log($"UNITS cost {t.name}: top {Tris(t, UnitPlinth.PlinthName)}, lip {Tris(t, UnitPlinth.LipName)}, ring {Tris(t, UnitPlinth.RimName)} triangles");+ Assert.LessOrEqual(Tris(t, UnitPlinth.RimName), 2 * UnitPlinth.RimSegments, $"{t.name}: the ring is a single band");+ }+ Assert.AreEqual(1, tokens.Select(t => t.Find(UnitPlinth.RimName).GetComponent<MeshRenderer>().sharedMaterial).Distinct().Count(), "one ring material");+ var flags = tokens.Select(t => t.Find(UnitPlinth.FlagName)).Where(f => f != null).ToList();+ Assert.AreEqual(1, flags.Select(f => f.GetComponent<MeshFilter>().sharedMesh).Distinct().Count(), "one flag mesh per side");+ Assert.AreEqual(1, flags.Select(f => string.Join(",", f.GetComponent<MeshRenderer>().sharedMaterials.Select(m => m.GetInstanceID()))).Distinct().Count(), "one set of flag materials");+ Assert.AreSame(figureMat, flags[0].GetComponent<MeshRenderer>().sharedMaterials[0], "the pole in the palette");+ Assert.AreSame(Resources.Load<Material>(UnitMaterials.RingResource).shader, flags[0].GetComponent<MeshRenderer>().sharedMaterials[1].shader, "the cloth unlit");+ Assert.Less(flags[0].GetComponent<MeshFilter>().sharedMesh.triangles.Length / 3, 300, "the flag is low-poly");+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }+}diff --git a/unity/Assets/Tests/EditMode/UnitPlinthTests.cs.meta b/unity/Assets/Tests/EditMode/UnitPlinthTests.cs.metanew file mode 100644index 000000000..f11666d28--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitPlinthTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: dd0c5199dbd5146ba95e5c0731039ef8\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs b/unity/Assets/Tests/EditMode/UnitShowcaseTests.csindex b10fcc561..c74d45e23 100644--- a/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs+++ b/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs@@ -136,11 +136,10 @@ public class UnitShowcaseTestsAssert.Greater(c.r / c.g, 1.24f, $"slot {slot}: warm brown, not olive khaki");}Assert.Less(Luma(UnitPalette.Shade(UnitPalette.Trousers, 0.5f)), Luma(UnitPalette.Shade(UnitPalette.Shirt, 0.5f)), "the trousers read darker than the shirt");- Assert.Greater(Luma(UnitPalette.Shade(UnitPalette.Dust, 0.5f)), 1.5f * Luma(UnitPalette.Shade(UnitPalette.Shirt, 0.5f)), "the base is earth, well lighter than the figure");- Assert.Greater(Luma(UnitPalette.Shade(UnitPalette.Dust, 0.5f)), Luma(UnitPalette.Shade(UnitPalette.Deck, 0.5f)) + 0.1f, "not the old dark deck-grey disc");- var disc = UnitShowcase.BaseMesh("base");- Assert.IsTrue(disc.uv.All(uv => Mathf.Abs(uv.x - UnitPalette.U(UnitPalette.Dust)) < 1e-4f), "the base is painted in the dust");- Object.DestroyImmediate(disc);+ Assert.Greater(UnitPalette.Shade(UnitPalette.Earth, 0.5f).r / UnitPalette.Shade(UnitPalette.Earth, 0.5f).g, 1.15f, "warm earth");+ var rows = Enumerable.Range(0, 100).Select(i => UnitPlinth.Mottle(i * 137f, i * 211f)).ToList();+ Assert.That(rows.Min(), Is.GreaterThanOrEqualTo(UnitPlinth.MottleLow)); Assert.That(rows.Max(), Is.LessThanOrEqualTo(UnitPlinth.MottleHigh));+ Assert.Greater(rows.Max() - rows.Min(), 0.3f, "mottled: the earth takes a spread of shade rows across the base");}[Test]@@ -183,7 +182,7 @@ public class UnitShowcaseTestsreturn list;}- /// <summary>Issue #249: the showcase trio leaves out the kit trees under its boots, and its toggle gives them back.</summary>+ /// <summary>Issue #249: the showcase trio leaves out the kit trees under its plinth, and its toggle gives them back.</summary>[Test]public void TheShowcaseTrioStandsClearOfTheTrees(){@@ -195,13 +194,19 @@ public class UnitShowcaseTestsvar veg = map.GetComponentInChildren<Statecraft.Game.Map.Kits.VegetationLayer>(true);Assert.IsNotNull(veg, "the kits and their trees are on");var root = UnitShowcase.Spawn(map, still: true);- var feet = Enumerable.Range(0, 3).Select(i => root.transform.Find("Rifleman" + i).position).Select(p => new Vector2(p.x, p.z)).ToList();+ var plinth = root.transform.Find(UnitPlinth.PlinthName);+ var centre = new Vector2(plinth.position.x, plinth.position.z);+ foreach (var i in new[] { 0, 1, 2 })+ {+ var f = root.transform.Find("Rifleman" + i).position;+ Assert.Less((new Vector2(f.x, f.z) - centre).magnitude + 0.2f * UnitShowcase.FigureScale, plinth.localScale.x, $"Rifleman{i}'s boots are on the plinth");+ }bool Under(Statecraft.Game.Map.Kits.TreeKind k, Matrix4x4 m){- var p = m.GetColumn(3); float reach = UnitShowcase.FootRadiusM + Statecraft.Game.Map.Kits.VegetationLayer.CrownRadius(k, m);- return feet.Any(f => (f - new Vector2(p.x, p.z)).sqrMagnitude < reach * reach);+ var p = m.GetColumn(3); float reach = plinth.localScale.x * UnitPlinth.RimOuter + Statecraft.Game.Map.Kits.VegetationLayer.CrownRadius(k, m);+ return (centre - new Vector2(p.x, p.z)).sqrMagnitude < reach * reach;}- Assert.IsFalse(veg.Drawable().Any(t => Under(t.kind, t.m)), "no drawn tree reaches the trio's boots");+ Assert.IsFalse(veg.Drawable().Any(t => Under(t.kind, t.m)), "no drawn tree reaches the trio's plinth");Assert.AreEqual(veg.Planted().Count(t => Under(t.kind, t.m)), veg.Hidden, "only the trio's trees are left out");VisualToggles.Set(UnitShowcase.ToggleName, false);Assert.AreEqual(0, veg.Hidden, "the showcase off gives them back");@@ -223,9 +228,11 @@ public class UnitShowcaseTestsAssert.IsNotNull(root.transform.Find("Spitfire1948/Propeller"));var plane = root.GetComponentInChildren<ShowcaseFlight>();Assert.AreEqual(UnitShowcase.StillPhase, plane.StillPhase);- // Each figure stands on the highest ground under its boots (UnitShowcase.Stand).+ // Each figure stands on the draped base at its own point (the ground there plus the lip).+ var plinth = root.transform.Find(UnitPlinth.PlinthName);+ Assert.IsNotNull(plinth, "the trio stands on a plinth");foreach (var f in root.GetComponentsInChildren<MeshFilter>().Where(f => f.name.StartsWith("Rifleman")))- Assert.AreEqual(UnitShowcase.Stand(map, f.transform.position).y, f.transform.position.y, 1f, f.name);+ Assert.AreEqual(UnitPlinth.FigureY(map, plinth.localScale.x, f.transform.position.x, f.transform.position.z), f.transform.position.y, 1f, f.name);// The aircraft clears the highest ground under its loop.var loop = map.Frame.ToWorld(UnitShowcase.LoopCentre.lon, UnitShowcase.LoopCentre.lat, 0);Assert.Greater(plane.transform.position.y, UnitShowcase.LoopFloor(map, loop, UnitShowcase.LoopRadiusM) + UnitShowcase.AltitudeM * 0.99f);diff --git a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs b/unity/Assets/Tests/EditMode/UnitsInPlayTests.csindex 2e44499df..ebc9473e5 100644--- a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs+++ b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs@@ -105,10 +105,12 @@ public class UnitsInPlayTests}const string Anchor = "{place: P, lon: 34.8, lat: 32.0, from: '1948-05-15', to: '1948-06-01', end_basis: source, end_note: n, sources: [{url: 'https://x.org', checked: '2026-10-11'}]}";- const string Unit = "units:\n- {id: a, name: A, number: '1', service: army, sector: s, status: draft, wikipedia_only: true, anchors: [";+ const string Unit = "units:\n- {id: a, name: A, number: '1', service: army, side: israel, sector: s, status: draft, wikipedia_only: true, anchors: [";[TestCase("units: []", "no units")]- [TestCase("units:\n- {id: a, name: A, number: '1', service: cavalry, sector: s, status: draft, wikipedia_only: true, anchors: []}", "unknown service 'cavalry'")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: cavalry, side: israel, sector: s, status: draft, wikipedia_only: true, anchors: []}", "unknown service 'cavalry'")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: army, sector: s, status: draft, wikipedia_only: true, anchors: []}", "unknown side ''")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: army, side: atlantis, sector: s, status: draft, wikipedia_only: true, anchors: []}", "unknown side 'atlantis'")][TestCase(Unit + "]}", "'a' has no anchors")][TestCase(Unit + "{place: P, lon: 34.8, lat: 32.0, from: '1948-05-15', to: '1948-06-01', end_basis: source, end_note: n, sources: []}]}", "has no source")][TestCase(Unit + "{place: P, lon: 34.8, lat: 32.0, from: '1948-06-01', to: '1948-05-15', end_basis: source, end_note: n, sources: [{url: 'https://x.org', checked: '2026-10-11'}]}]}", "to must be after from")]@@ -120,15 +122,15 @@ public class UnitsInPlayTests[TestCase(Unit + "{place: P, lon: 34.8, lat: 32.0, from: '1948-05-15', to: '1948-06-01', end_basis: source, sources: [{url: 'https://x.org', checked: '2026-10-11'}]}]}", "no end_note")][TestCase(Unit + "{place: P, lon: 34.8, lat: 32.0, from: '1948-05-15', to: '1949-07-20', end_basis: front_armistice, front: egypt, sources: [{url: 'https://x.org', checked: '2026-10-11'}]}]}", "must end on the egypt armistice, 1949-02-24")][TestCase(Unit + "{place: P, lon: 34.8, lat: 32.0, from: '1948-05-15', to: '1949-02-24', end_basis: front_armistice, front: iraq, sources: [{url: 'https://x.org', checked: '2026-10-11'}]}]}", "needs a front")]- [TestCase("units:\n- {id: a, name: A, number: '1', service: army, sector: s, status: draft, wikipedia_only: true, disbanded: {date: '1948-05-20', sources: [{url: 'https://x.org', checked: '2026-10-11'}]}, anchors: [" + Anchor + "]}", "runs past the unit's disbandment")]- [TestCase("units:\n- {id: a, name: A, number: '1', service: army, sector: s, status: draft, wikipedia_only: true, headgear: [wool_cap, wool_cap, wool_cap], anchors: [" + Anchor + "]}", "headgear has no source")]- [TestCase("units:\n- {id: a, name: A, number: '1', service: air, sector: s, status: draft, wikipedia_only: true, anchors: [" + Anchor + "]}", "without aircraft")]- [TestCase("units:\n- {id: a, name: A, number: '1', service: army, colour: red, sector: s, status: draft, wikipedia_only: true, anchors: []}", "colour")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: army, side: israel, sector: s, status: draft, wikipedia_only: true, disbanded: {date: '1948-05-20', sources: [{url: 'https://x.org', checked: '2026-10-11'}]}, anchors: [" + Anchor + "]}", "runs past the unit's disbandment")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: army, side: israel, sector: s, status: draft, wikipedia_only: true, headgear: [wool_cap, wool_cap, wool_cap], anchors: [" + Anchor + "]}", "headgear has no source")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: air, side: israel, sector: s, status: draft, wikipedia_only: true, anchors: [" + Anchor + "]}", "without aircraft")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: army, side: israel, colour: red, sector: s, status: draft, wikipedia_only: true, anchors: []}", "colour")]// A person's sign-off (#375): both or neither, a GitHub handle (never an email), a day.- [TestCase("units:\n- {id: a, name: A, number: '1', service: army, sector: s, status: draft, reviewed_by: eyalgolan, wikipedia_only: true, anchors: [" + Anchor + "]}", "reviewed_on")]- [TestCase("units:\n- {id: a, name: A, number: '1', service: army, sector: s, status: draft, reviewed_by: [email protected], reviewed_on: '2026-10-15', wikipedia_only: true, anchors: [" + Anchor + "]}", "reviewed_by")]- [TestCase("units:\n- {id: a, name: A, number: '1', service: army, sector: s, status: draft, reviewed_by: eyalgolan, reviewed_on: soon, wikipedia_only: true, anchors: [" + Anchor + "]}", "reviewed_on")]- [TestCase("units:\n- {id: a, name: A, number: '1', service: army, sector: s, status: draft, reviewed_by: '', reviewed_on: '2026-10-15', wikipedia_only: true, anchors: [" + Anchor + "]}", "reviewed_by")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: army, side: israel, sector: s, status: draft, reviewed_by: eyalgolan, wikipedia_only: true, anchors: [" + Anchor + "]}", "reviewed_on")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: army, side: israel, sector: s, status: draft, reviewed_by: [email protected], reviewed_on: '2026-10-15', wikipedia_only: true, anchors: [" + Anchor + "]}", "reviewed_by")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: army, side: israel, sector: s, status: draft, reviewed_by: eyalgolan, reviewed_on: soon, wikipedia_only: true, anchors: [" + Anchor + "]}", "reviewed_on")]+ [TestCase("units:\n- {id: a, name: A, number: '1', service: army, side: israel, sector: s, status: draft, reviewed_by: '', reviewed_on: '2026-10-15', wikipedia_only: true, anchors: [" + Anchor + "]}", "reviewed_by")]public void BadUnitFilesNameTheFileAndTheProblem(string yaml, string expected){var e = Assert.Throws<InvalidDataException>(() => UnitData.Parse(yaml, "u.yaml"));@@ -139,7 +141,7 @@ public class UnitsInPlayTests[Test]public void AUnitSignOffParses(){- var u = UnitData.Parse("units:\n- {id: a, name: A, number: '1', service: army, sector: s, status: draft, reviewed_by: eyalgolan, reviewed_on: '2026-10-15', wikipedia_only: true, anchors: [" + Anchor + "]}", "u.yaml");+ var u = UnitData.Parse("units:\n- {id: a, name: A, number: '1', service: army, side: israel, sector: s, status: draft, reviewed_by: eyalgolan, reviewed_on: '2026-10-15', wikipedia_only: true, anchors: [" + Anchor + "]}", "u.yaml");Assert.AreEqual(("eyalgolan", "2026-10-15"), (u[0].ReviewedBy, u[0].ReviewedOn));}@@ -393,22 +395,6 @@ public class UnitsInPlayTestsAssert.Greater(outside, 0);}- /// <summary>Owner question (units on hard terrain): on a steep slope a figure stands on the highest ground under its- /// boots, so no boot sinks into the hill, and the downhill boot floats by no more than the slope's rise.</summary>- [Test]- public void AFigureStandsOnASteepSlopeWithoutSinking()- {- const float slope = 0.6f, r = UnitShowcase.FootRadiusM; // a 31-degree hillside (steeper than the 3x relief's hills)- float H(float x, float z) => 100f + slope * x + 0.2f * z;- float y = UnitShowcase.StandHeight(H, 1000f, 2000f, r);- for (int k = 0; k < 16; k++)- {- float a = Mathf.PI / 8f * k;- Assert.GreaterOrEqual(y + 0.01f, H(1000f + Mathf.Cos(a) * r * 0.99f, 2000f + Mathf.Sin(a) * r * 0.99f), "no boot sinks into the slope");- }- Assert.LessOrEqual(y - H(1000f, 2000f), Mathf.Sqrt(slope * slope + 0.04f) * r / Mathf.Cos(Mathf.PI / 16f) + 0.01f, "the float is bounded by the slope over the foot");- }-/// <summary>Review of #518: the tokens' keep-clear boxes (what the map's names keep clear of) are right even when the/// tokens are built while the "units" toggle hides the layer, as a ?shot run without &units does before the first/// Show: once the layer is shown again, each token's pieces box is the hull of its drawn pieces (Renderer.bounds, now@@ -445,8 +431,8 @@ public class UnitsInPlayTestsfinally { if (VisualToggles.Names.Contains(UnitLayer.ToggleName)) VisualToggles.Set(UnitLayer.ToggleName, true); UnityEngine.Object.DestroyImmediate(map.gameObject); }}- /// <summary>The same on the map's real hills: every rifleman of every army anchor of the war stands no lower than the- /// ground anywhere under its boots.</summary>+ /// <summary>The same on the map's real hills: every rifleman of every army anchor of the war stands on its token's draped+ /// base at its own point, and the ground under its boots rises at most a tenth of its height over its feet.</summary>[Test]public void NoRiflemanSinksIntoTheHillsOfTheMap(){@@ -461,26 +447,22 @@ public class UnitsInPlayTestsforeach (var f in map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").GetComponentsInChildren<Transform>().Where(t => t.name.StartsWith("Rifleman"))){var p = f.position; float lowest = float.MaxValue;- for (int k = 0; k < 24; k++) // between the stand's sample directions, at 0.9 of the foot radius+ for (int k = 0; k < 24; k++) // round its boots (0.2 m from its centre), at 0.9 of their radius{float a = Mathf.PI / 12f * k + 0.1f;- var q = UnitShowcase.Ground(map, p + new Vector3(Mathf.Cos(a), 0, Mathf.Sin(a)) * UnitShowcase.FootRadiusM * 0.9f);- Assert.LessOrEqual(q.y, p.y + 25f, $"{f.parent.name}/{f.name} on {d:yyyy-MM-dd}: a boot sinks into the ground");+ var q = UnitShowcase.Ground(map, p + new Vector3(Mathf.Cos(a), 0, Mathf.Sin(a)) * 0.2f * UnitShowcase.FigureScale * 0.9f);+ Assert.LessOrEqual(q.y, p.y + 0.1f * UnitBadge.FigureHeightM * UnitShowcase.FigureScale, $"{f.parent.name}/{f.name} on {d:yyyy-MM-dd}: the ground under a boot rises more than the base hides");lowest = Mathf.Min(lowest, q.y);}worstFloat = Mathf.Max(worstFloat, p.y - lowest);- if (p.y - lowest > UnitShowcase.BaseFromRiseM + 25f)- {- var b = f.parent.Find("Base" + f.name);- Assert.IsNotNull(b, $"{f.parent.name}/{f.name}: a figure on a slope stands on a base");- Assert.LessOrEqual(b.position.y - b.localScale.y, lowest + 1f, $"{f.parent.name}/{f.name}: the base reaches the ground downhill");- }+ var plinth = f.parent.Find(UnitPlinth.PlinthName);+ Assert.IsNotNull(plinth, $"{f.parent.name}: the figures stand on a plinth");+ Assert.AreEqual(UnitPlinth.FigureY(map, plinth.localScale.x, p.x, p.z), p.y, 0.5f, $"{f.parent.name}/{f.name}: on the base's top over the ground at its feet");checkedFigures++;}}- Debug.Log($"UNITS slope: {checkedFigures} riflemen, worst float {worstFloat:0} m");+ Debug.Log($"UNITS slope: {checkedFigures} riflemen, worst rise of a figure's feet over the ground at its boots {worstFloat:0} m");Assert.Greater(checkedFigures, 40);- Assert.Less(worstFloat, 1000f, "the ground under a figure's boots drops less than a quarter of its height");}finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }}@@ -498,15 +480,16 @@ public class UnitsInPlayTestsreturn map;}- static List<Vector2> FigureFeet(MapScene map) =>+ /// <summary>The shown army tokens' plinths, as discs (the figures' boots are all on them).</summary>+ static List<(Vector2 centre, float radius)> FigureFeet(MapScene map) =>map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").GetComponentsInChildren<Transform>()- .Where(t => t.name.StartsWith("Rifleman")).Select(t => new Vector2(t.position.x, t.position.z)).ToList();+ .Where(t => t.name == UnitPlinth.PlinthName).Select(t => (new Vector2(t.position.x, t.position.z), t.localScale.x * UnitPlinth.RimOuter)).ToList();- static bool UnderAFigure(Statecraft.Game.Map.Kits.TreeKind kind, Matrix4x4 m, List<Vector2> feet)+ static bool UnderAFigure(Statecraft.Game.Map.Kits.TreeKind kind, Matrix4x4 m, List<(Vector2 centre, float radius)> plinths){var p = m.GetColumn(3); var at = new Vector2(p.x, p.z);- float reach = UnitShowcase.FootRadiusM + Statecraft.Game.Map.Kits.VegetationLayer.CrownRadius(kind, m);- return feet.Any(f => (f - at).sqrMagnitude < reach * reach);+ float crown = Statecraft.Game.Map.Kits.VegetationLayer.CrownRadius(kind, m);+ return plinths.Any(f => (f.centre - at).sqrMagnitude < (f.radius + crown) * (f.radius + crown));}/// <summary>Issue #249: on every date the units are checked on, no kit tree that is drawn has its crown within a shown@@ -581,7 +564,7 @@ public class UnitsInPlayTestsvar o = UnitShowcase.FigureOffsets(3);for (int i = 0; i < 3; i++)for (int j = i + 1; j < 3; j++)- Assert.GreaterOrEqual((o[i] - o[j]).magnitude * step, 1800f, "a figure is about 1.2 km wide at 2,000x: keep a gap");+ Assert.GreaterOrEqual((o[i] - o[j]).magnitude * step, 1800f, "a figure is about 0.85 km wide at 1,400x: keep a gap");Assert.Less(o.Max(v => v.magnitude) * step + 600f, UnitShowcase.RingRadius * 5000f, "the figures stay inside the ring");}