Skip to content

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

map: units in normal play — brigade tokens, figures and 1948 aircraft (refs #197) (#250)

Eyal Golan8474b8b05088
diff --git a/ASSETS.yaml b/ASSETS.yaml
index 30f2fe9ad..555db99bd 100644
--- a/ASSETS.yaml
+++ b/ASSETS.yaml
@@ -123,6 +123,11 @@ rules:
source: "Railways and main roads of May 1948 (issue #35): traced by tools/routes_1948.py on the Survey of Palestine 1:250,000 map of 1946 (public domain; scans and georeferencing by Palestine Open Maps, https://palopenmaps.org/en/maps?basemap=pal250k1946) between waypoints at Wikipedia API (CC BY-SA) and Wikidata (CC0) coordinates; per-route sources and check dates in routes_1948.yaml"
status: verified
note: "Public domain checked 2026-10-11: PD-UKGov (expired Crown copyright: 50 years from publication for published works, which HMSO treats as worldwide) and PD-scan, as Wikimedia Commons files the 1946 Survey of Palestine sheets (e.g. https://commons.wikimedia.org/wiki/File:Gaza_sh._04,_1946.jpg). Palestine Open Maps' About page calls its maps public domain under the UK Copyright, Designs and Patents Act and publishes no terms of its own for its tiles or georeferencing; the traced lines are our own derivative and copy none of its layers. No OpenStreetMap (ODbL) geometry is copied: OSM and OpenHistoricalMap lines are only measured against (tools/routes_accuracy.py, docs/routes.md)."
+ - glob: "content/map/units_1948.yaml"
+ licence: CC-BY-SA-4.0
+ source: "The 1948 brigades, 101 Squadron and the first navy ships, with their dated positions (docs/units.md, Units in play): facts and place coordinates read from English and Hebrew Wikipedia (CC BY-SA; Wikipedia API prop=coordinates) and Wikidata (CC0), and the S-199 markings from Eduard Info 11/2025 pp. 53-54 (facts only, no text or image copied); per-row sources and check dates in the file"
+ status: owner-verify
+ note: "Presentation only (the map's unit tokens); the sim never reads it, so the content hash does not move (UnitsInPlayTests). Rows marked wikipedia_only are drafts until checked against a published history (Lorch, The Edge of the Sword) or the IDF and Defense Establishment Archives."
# --- Baked map textures (derived from the heightmap) ---
- glob: "unity/Assets/Textures/Map/landuse.png"
licence: Copernicus-DEM
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c11fd17ba..7f93d07fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,12 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
## [Unreleased]
### Added
+- Units in play: the map draws the 1948 brigades, 101 Squadron and the first navy ships as Civ-style tokens at their
+ dated, sourced positions (`content/map/units_1948.yaml`, map-only, outside the content hash). The figures follow the
+ reserve call-up, the squadron flies at security level 4 or 5 (an Avia S-199, then the Spitfire from its first sourced
+ sortie, 15 October 1948), a badge marks each token, and selecting one shows the promo's ring and a read-only card with
+ a link to the Defence screen. Every position ends on a sourced date or on its front's armistice. Screenshot runs show
+ units only with `&units`. The goldens do not move.
- `content/eras.yaml` with the `founding` era (15 May 1948 to 1 January 1957), a `Content.EraAt(date)` lookup, and the end
of the last era: the turn that reaches it ends on it (a turn that would leave under 14 days is lengthened to it), the
game ends with the stable code `era_ended` and the text "The chapter has ended", and later orders are refused. The
diff --git a/content/map/units_1948.yaml b/content/map/units_1948.yaml
new file mode 100644
index 000000000..fb141e958
--- /dev/null
+++ b/content/map/units_1948.yaml
@@ -0,0 +1,424 @@
+# The military formations the map draws in 1948-49 (docs/units.md, "Units in play"). Map-only: the sim never reads this
+# file (ContentLoader reads only its own files), so it does not move the content hash or the goldens. The map reads it
+# (UnitRoster) together with the sim's security level and reserve call-up, and draws one token per unit.
+#
+# Owner rulings (2026-10-11): one token per brigade; the number of figures follows the call-up (1, 2 or 3); an Avia
+# S-199 until the Spitfire's sourced date, then the Spitfire; brigades with no sourced position are listed but hidden;
+# tokens stand only at dated, sourced positions and do not move with operation events; after the armistices only what a
+# source says continued is shown; no orders (the unit panel links to the Defence screen). Controller rulings (review
+# C1, I1, I3, I4): no invented end dates; "since" only from a sourced start; the squadron's bases where two sources agree.
+#
+# anchors: where the unit stood, each a named place a source gives for a dated window. The map draws the unit while the
+# game date is inside one of its windows: from (inclusive) to `to` (exclusive), 'YYYY-MM-DD', quoted. A window that a
+# source opens before the game starts opens on the game's first day (15 May 1948); `since` then gives the sourced start,
+# which the unit's card shows ("since February 1948"). With no `since`, the card gives no start.
+# precision: month marks a window edge that the source gives only as a month (the first of the month is used).
+# end_basis: why a window ends.
+# source: a cited source moves the unit, ends its sector or disbands it; `end_note` says which.
+# front_armistice: no source gives an end, so the window ends on the day the armistice of the front it stood on was
+# signed (`front`: egypt 24 February, lebanon 23 March, jordan 3 April, syria 20 July 1949;
+# https://en.wikipedia.org/wiki/1949_Armistice_Agreements, checked 2026-10-11). This applies the owner's ruling
+# "after the armistices, show only what a source says continued"; no source yet gives a later position.
+# A window also ends no later than the unit's sourced disbandment (`disbanded`).
+# The token stands on its anchor's hex or one next to it, clear of the settlement kits and the railways and roads
+# (UnitPlacer): a presentation offset of at most one hex step, not a claim about the position. Where the nearest such
+# spot would be the other side's ground, `toward` names a sourced place on the unit's own side and `place_hex` the hex
+# next to the anchor on that side ([q, r] in content/map/hexes.json); the token stands in that hex, nearest the place.
+# Coordinates: the place's Wikipedia article (Wikipedia API prop=coordinates), or Wikidata (CC0) where it has none.
+# wikipedia_only: true when every source of the row is a Wikipedia article (English or Hebrew) or a Wikidata item (for
+# coordinates only). Such a row is a draft until checked against a published history (Netanel Lorch, The Edge of the
+# 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).
+# 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.
+units:
+# --- Army: the twelve brigades of 1948 -------------------------------------------------------------------------------
+- id: golani
+ name: Golani Brigade
+ number: 1st Brigade
+ service: army
+ formed: 22 February 1948
+ first_commander: Moshe Mann
+ sector: "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."
+ wikipedia_only: true
+ status: draft
+ anchors:
+ - place: "Yavne'el"
+ lon: 35.49944
+ lat: 32.70944
+ from: '1948-05-15'
+ since: February 1948
+ to: '1948-12-01'
+ precision: month
+ end_basis: source
+ end_note: "he.wiki: in December 1948 the brigade moved to the southern front, to the Julis camp."
+ note: The brigade's headquarters from its formation in February 1948 (en.wiki).
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Golani_Brigade', checked: '2026-10-11'}
+ - {url: 'https://he.wikipedia.org/wiki/%D7%97%D7%98%D7%99%D7%91%D7%AA_%D7%92%D7%95%D7%9C%D7%A0%D7%99', checked: '2026-10-11'}
+ - {url: "https://en.wikipedia.org/wiki/Yavne'el", checked: '2026-10-11'}
+ - place: Julis camp
+ lon: 34.65361
+ lat: 31.68167
+ from: '1948-12-01'
+ since: December 1948
+ to: '1949-02-24'
+ precision: month
+ end_basis: front_armistice
+ front: egypt
+ note: "he.wiki: in December 1948 the brigade moved to the southern front, camped at Julis (Operations Assaf and Horev)."
+ sources:
+ - {url: 'https://he.wikipedia.org/wiki/%D7%97%D7%98%D7%99%D7%91%D7%AA_%D7%92%D7%95%D7%9C%D7%A0%D7%99', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Julis,_Gaza', checked: '2026-10-11'}
+- id: carmeli
+ name: Carmeli Brigade
+ number: 2nd Brigade
+ service: army
+ formed: 22 February 1948
+ sector: The northwest (split from the Levanoni Brigade in February 1948).
+ wikipedia_only: true
+ status: draft
+ hidden: The sources name its sector ("the northwest") but no place or headquarters.
+ anchors: []
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Carmeli_Brigade', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Golani_Brigade', checked: '2026-10-11'}
+- id: alexandroni
+ name: Alexandroni Brigade
+ number: 3rd Brigade
+ service: army
+ formed: November 1947 (the Haganah's decision of 7 November)
+ sector: The Sharon region.
+ wikipedia_only: true
+ status: draft
+ hidden: The sources name its region ("the Sharon") but no place or headquarters.
+ anchors: []
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Alexandroni_Brigade', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Etzioni_Brigade', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Golani_Brigade', checked: '2026-10-11'}
+- id: kiryati
+ name: Kiryati Brigade
+ number: 4th Brigade
+ service: army
+ formed: February 1948
+ sector: "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: true
+ status: draft
+ anchors:
+ - place: Tel Aviv
+ lon: 34.78
+ lat: 32.08
+ from: '1948-05-15'
+ since: February 1948
+ to: '1949-04-03'
+ end_basis: front_armistice
+ front: jordan
+ note: Established in Tel Aviv in February 1948; its border was the city's urban area. The central front was covered by the agreement with Jordan.
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/4th_Armored_Brigade_%22Kiryati%22', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Tel_Aviv', checked: '2026-10-11'}
+- id: givati
+ name: Givati Brigade
+ number: 5th Brigade
+ service: army
+ formed: December 1947
+ first_commander: Shimon Avidan
+ sector: "Moved to the south as the war entered its second stage, concentrated mainly around Gedera, Gan Yavne and Be'er Tuvia."
+ wikipedia_only: true
+ status: draft
+ anchors:
+ - place: Gedera
+ lon: 34.77722
+ lat: 31.81194
+ from: '1948-05-15'
+ to: '1949-02-24'
+ end_basis: front_armistice
+ front: egypt
+ note: "One place picked from the sector: the first of the three the source names. The move south is not dated, so the card gives no start."
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Givati_Brigade', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Gedera', checked: '2026-10-11'}
+- id: etzioni
+ name: Etzioni Brigade
+ number: 6th Brigade
+ service: army
+ formed: Late 1947
+ first_commander: Yisrael Amir
+ sector: The defence of Jerusalem and its surroundings.
+ wikipedia_only: true
+ status: draft
+ anchors:
+ - place: Jerusalem
+ lon: 35.22556
+ lat: 31.77889
+ from: '1948-05-15'
+ since: late 1947
+ to: '1949-04-03'
+ end_basis: front_armistice
+ front: jordan
+ note: Founded in late 1947 as the Field Corps unit responsible for the defence of Jerusalem.
+ toward:
+ place: West Jerusalem
+ lon: 35.21944
+ lat: 31.78194
+ note: "The section of Jerusalem Israel held at the end of the war; without it the token's nearest clear spot fell north-east of the city, by Hizma and Anata, which Jordan held."
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/West_Jerusalem', checked: '2026-10-11'}
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Etzioni_Brigade', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Jerusalem', checked: '2026-10-11'}
+- id: brigade_7
+ name: 7th Brigade
+ number: 7th Brigade
+ service: army
+ formed: 16 May 1948
+ first_commander: Shlomo Shamir
+ sector: "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."
+ wikipedia_only: true
+ status: draft
+ anchors:
+ - place: Hulda (headquarters for the Latrun attacks)
+ lon: 34.88333
+ lat: 31.83222
+ from: '1948-05-24'
+ since: 24 May 1948
+ to: '1948-06-01'
+ end_basis: source
+ end_note: "Operation Bin Nun Alef (24-25 May) and Bin Nun Bet (30 May-1 June); he.wiki: in June 1948 the brigade moved north."
+ note: "The brigade attacked Latrun from the Israeli headquarters at Hulda (Battles of Latrun); Shlomo Shamir led both attacks. Anchored at Hulda, not Latrun: the Arab Legion held Latrun and the ridge behind it (Yalu, Bayt Nuba), and the ground between was contested until the area of Bayt Jiz and Bayt Susin was cleared on 28 May; Sar'a was taken only on 13-14 July."
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Battles_of_Latrun_(1948)', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Hulda,_Israel', checked: '2026-10-12'}
+ - {url: "https://en.wikipedia.org/wiki/Sar'a", checked: '2026-10-12'}
+ - place: Ein Shemer
+ lon: 35.00667
+ lat: 32.46139
+ from: '1948-06-01'
+ since: June 1948
+ to: '1948-07-01'
+ precision: month
+ end_basis: source
+ end_note: "he.wiki: it organised at Ein Shemer \"for a time\" in June 1948; no later place is given."
+ sources:
+ - {url: 'https://he.wikipedia.org/wiki/%D7%97%D7%98%D7%99%D7%91%D7%94_7', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Ein_Shemer', checked: '2026-10-11'}
+- id: brigade_8
+ name: 8th Brigade
+ number: 8th Brigade
+ service: army
+ formed: 24 May 1948
+ first_commander: Yitzhak Sadeh
+ sector: Not stated in the sources.
+ wikipedia_only: true
+ status: draft
+ hidden: The sources give its founding but no sector or headquarters.
+ anchors: []
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/8th_Armored_Brigade_(Israel)', checked: '2026-10-11'}
+- id: oded
+ name: Oded Brigade
+ number: 9th Brigade
+ service: army
+ sector: The sources conflict.
+ wikipedia_only: true
+ status: draft
+ hidden: "The source says it was headquartered in Jerusalem, yet it fought at al-Malkiyya in the north in June 1948."
+ anchors: []
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Oded_Brigade', checked: '2026-10-11'}
+- id: harel
+ name: Harel Brigade
+ number: 10th Brigade (Palmach)
+ service: army
+ formed: 16 April 1948
+ first_commander: Yitzhak Rabin
+ sector: "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."
+ wikipedia_only: true
+ status: draft
+ anchors:
+ - place: "Sha'ar HaGai"
+ lon: 35.03333
+ lat: 31.81667
+ from: '1948-05-15'
+ since: the first half of May 1948
+ to: '1948-12-22'
+ end_basis: source
+ end_note: Operation Horev, from 22 December 1948, in the south; no place is given for the brigade there.
+ note: "One place picked from the sector: the source names the Jerusalem corridor as the sector and Sha'ar HaGai as the end of the road the brigade opened (and as a battalion's name)."
+ place_hex: [-2, 23]
+ toward:
+ place: Saris
+ lon: 35.07389
+ lat: 31.79806
+ note: "Taken in the Haganah offensive of 16-17 April 1948, on the corridor road east of Sha'ar HaGai, where the Harel Brigade's 4th Battalion fought from Kiryat Anavim; without this the token's nearest clear spot fell by Sar'a and Artuf (later the Yalu ridge), not yet taken on 15 May."
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Saris,_Jerusalem', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Kiryat_Anavim', checked: '2026-10-11'}
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Harel_Brigade', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Operation_Horev', checked: '2026-10-11'}
+ - {url: "https://en.wikipedia.org/wiki/Sha'ar_HaGai", checked: '2026-10-11'}
+- id: yiftach
+ name: Yiftach Brigade
+ number: 11th Brigade (Palmach)
+ service: army
+ formed: April 1948
+ sector: "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: true
+ status: draft
+ disbanded: {date: '1949-05-01', precision: month, sources: [{url: 'https://en.wikipedia.org/wiki/Yiftach_Brigade', checked: '2026-10-11'}]}
+ anchors:
+ - place: Lydda
+ lon: 34.88806
+ lat: 31.95194
+ from: '1948-07-11'
+ since: 11 July 1948
+ to: '1948-07-20'
+ end_basis: source
+ end_note: Operation Dani ended on 19 July 1948.
+ note: "The IDF entered Lydda on 11 July 1948 (Lod article); the Operation Danny article has the two towns taken on 10 July. Yiftach approached from the south from 9 July."
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Operation_Danny', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Yiftach_Brigade', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Lod', checked: '2026-10-11'}
+- id: negev
+ name: Negev Brigade
+ number: 12th Brigade (Palmach)
+ service: army
+ formed: March 1948
+ first_commander: Nahum Sarig
+ sector: "The Negev, in two sectors divided by the Beersheba-Gaza road; brigade headquarters at the Mekorot camp near Nir Am."
+ wikipedia_only: false
+ status: draft
+ headgear: [wool_cap, steel_helmet, wool_cap]
+ headgear_sources:
+ - {url: 'https://commons.wikimedia.org/wiki/File:Palmach-negev-instructed2operation.jpg', checked: '2026-10-11'}
+ - {url: 'https://commons.wikimedia.org/wiki/File:Negev_Brigade_soldiers_1948.jpg', checked: '2026-10-11'}
+ anchors:
+ - place: Nir Am (Mekorot camp)
+ lon: 34.58083
+ lat: 31.51944
+ from: '1948-05-15'
+ since: March 1948
+ to: '1949-02-24'
+ end_basis: front_armistice
+ front: egypt
+ note: he.wiki sets up the brigade's headquarters at the Mekorot camp near Nir Am when the brigade was formed.
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Negev_Brigade', checked: '2026-10-11'}
+ - {url: 'https://he.wikipedia.org/wiki/%D7%97%D7%98%D7%99%D7%91%D7%AA_%D7%94%D7%A0%D7%92%D7%91', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Nir_Am', checked: '2026-10-11'}
+# --- Air: the first fighter squadron ---------------------------------------------------------------------------------
+- id: squadron_101
+ name: 101 Squadron
+ number: First Fighter Squadron
+ service: air
+ formed: 20 May 1948
+ first_commander: Modi Alon
+ sector: "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."
+ wikipedia_only: false
+ status: draft
+ aircraft:
+ - type: avia-s199
+ from: '1948-05-20'
+ to: '1948-10-15'
+ note: "The first four arrived on 20 May 1948 and flew first on 29 May (Avia S-199). The type flew on, sporadically, until mid-December (Avia S-199; Eduard p. 54 has one in Operation Horev); the map shows it until the squadron's Spitfires are first sourced in service."
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/Avia_S-199', checked: '2026-10-11'}
+ - {url: 'https://info.eduard.com/en/11-2025-1/strana-53', checked: '2026-10-11'}
+ - {url: 'https://info.eduard.com/en/11-2025-1/strana-54', checked: '2026-10-11'}
+ - type: spitfire
+ from: '1948-10-15'
+ note: "The first Spitfires flew in from Czechoslovakia on 27 September 1948 (Operation Velvetta, he.wiki), unarmed; the first sourced sortie is 15 October 1948, three Spitfires escorting Beaufighters to El Arish (he.wiki Supermarine Spitfire). The squadron flew both the Avias and the Spitfires (he.wiki 101 Squadron). en.wiki's Spitfire operational history has IAF Spitfires in combat on 21 October and calls a 101 Squadron claim that day the IAF's \"first ever aerial victory\", which is wrong: the first victories were on 3 June 1948 (101 Squadron, Avia S-199)."
+ sources:
+ - {url: 'https://he.wikipedia.org/wiki/%D7%A1%D7%95%D7%A4%D7%A8%D7%9E%D7%A8%D7%99%D7%9F_%D7%A1%D7%A4%D7%99%D7%98%D7%A4%D7%99%D7%99%D7%A8', checked: '2026-10-11'}
+ - {url: 'https://he.wikipedia.org/wiki/%D7%9E%D7%91%D7%A6%D7%A2_%D7%95%D7%9C%D7%95%D7%95%D7%98%D7%94', checked: '2026-10-11'}
+ - {url: 'https://he.wikipedia.org/wiki/%D7%98%D7%99%D7%99%D7%A1%D7%AA_101', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Supermarine_Spitfire_operational_history', checked: '2026-10-11'}
+ anchors:
+ - place: Ekron (RAF Aqir)
+ lon: 34.82184
+ lat: 31.83947
+ from: '1948-05-20'
+ since: 20 May 1948
+ to: '1948-05-30'
+ end_basis: source
+ end_note: "en.wiki: the squadron left Ekron after its unassembled aircraft were strafed on 30 May. he.wiki keeps it at Ekron until mid-June (Modi Alon took off from Ekron on 3 June). The map shows no base from 30 May to mid-June, where the two disagree."
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/101_Squadron_(Israel)', checked: '2026-10-11'}
+ - {url: 'https://he.wikipedia.org/wiki/%D7%98%D7%99%D7%99%D7%A1%D7%AA_101', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Tel_Nof_Airbase', checked: '2026-10-11'}
+ - place: Herzliya strip
+ lon: 34.83398
+ lat: 32.18029
+ from: '1948-06-15'
+ since: mid-June 1948
+ to: '1948-11-21'
+ end_basis: source
+ end_note: "Eduard p. 54: the squadron moved to Qastina (Hatzor) on 21 November 1948; he.wiki: November 1948. en.wiki and Eduard p. 53's profile caption say October; he.wiki has Modi Alon killed landing at Herzliya on 16 October, which fits November."
+ note: "Both en.wiki (\"between June and October 1948\") and he.wiki (mid-June, in the first truce) have the squadron here from mid-June; en.wiki says it moved in after 30 May."
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/101_Squadron_(Israel)', checked: '2026-10-11'}
+ - {url: 'https://he.wikipedia.org/wiki/%D7%98%D7%99%D7%99%D7%A1%D7%AA_101', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Herzliya_Airport', checked: '2026-10-11'}
+ - place: Hatzor
+ lon: 34.72722
+ lat: 31.7625
+ from: '1948-11-21'
+ since: 21 November 1948
+ to: '1949-06-01'
+ precision: month
+ end_basis: source
+ end_note: "he.wiki: in June 1949 Hatzor closed and the squadron moved to Ramat David."
+ sources:
+ - {url: 'https://info.eduard.com/en/11-2025-1/strana-54', checked: '2026-10-11'}
+ - {url: 'https://he.wikipedia.org/wiki/%D7%98%D7%99%D7%99%D7%A1%D7%AA_101', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Hatzor_Airbase', checked: '2026-10-11'}
+# --- Navy: the first ships (four ex-Aliyah Bet ships impounded in Haifa harbour; two are named and sourced here) ----
+- id: ins_haganah
+ name: INS Haganah (K-20)
+ number: Corvette, commissioned 1948
+ service: navy
+ formed: 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
+ status: draft
+ anchors:
+ - place: Haifa harbour
+ lon: 35.00448
+ lat: 32.82012
+ from: '1948-05-15'
+ to: '1949-02-24'
+ end_basis: front_armistice
+ front: egypt
+ note: "The navy began the war with four ex-Aliyah Bet ships impounded in Haifa harbour; Haganah fought Egyptian naval forces in Operation Yoav and returned to Haifa for repairs. The sources date its commissioning only to 1948, so the card says \"commissioned 1948\" and gives no start."
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/HMCS_Norsyd', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Israeli_Navy', checked: '2026-10-11'}
+ - {url: 'https://www.wikidata.org/wiki/Q1376739', checked: '2026-10-11'}
+- id: ins_wedgwood
+ name: INS Wedgwood
+ number: Corvette, commissioned 1948
+ service: navy
+ formed: 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: true
+ status: draft
+ to_verify:
+ - "Its Israeli name and pennant number: the Beauharnois article says it served as Hashomer, K 20, which the Norsyd article gives to Haganah; the Norsyd article calls it INS Wedgwood. The map shows the name Wedgwood and no pennant number."
+ anchors:
+ - place: Haifa harbour
+ lon: 35.00448
+ lat: 32.82012
+ from: '1948-05-15'
+ to: '1949-02-24'
+ end_basis: front_armistice
+ front: egypt
+ note: Its sourced actions were against the Egyptian forces (Operation Yoav).
+ sources:
+ - {url: 'https://en.wikipedia.org/wiki/HMCS_Beauharnois_(K540)', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/HMCS_Norsyd', checked: '2026-10-11'}
+ - {url: 'https://en.wikipedia.org/wiki/Israeli_Navy', checked: '2026-10-11'}
+ - {url: 'https://www.wikidata.org/wiki/Q1376739', checked: '2026-10-11'}
diff --git a/docs/superpowers/specs/2026-10-11-units-in-play-design.md b/docs/superpowers/specs/2026-10-11-units-in-play-design.md
new file mode 100644
index 000000000..1dc73aa6f
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-11-units-in-play-design.md
@@ -0,0 +1,195 @@
+# Units in play: design (2026-10-11)
+
+Status: decided and implemented on `units-in-play` (2026-10-11). The rulings are below; the built behaviour, its
+sources and what is left open are in `docs/units.md`, "Units in play".
+
+## Rulings (2026-10-11)
+
+The owner ruled on questions 1–4 and the controller adopted the defaults for 5–7:
+1. One token per brigade.
+2. The figure count follows the call-up (1, 2 or 3).
+3. An Avia S-199 until the Spitfire's sourced date (21 October 1948), then the Spitfire.
+4. The four brigades with no sourced position are hidden; the rest ship.
+5. Dated, sourced positions only; no movement in operation events.
+6. After the armistices, only what a source says continued is shown.
+7. No orders; the unit's card links to the Defence screen.
+
+After the staff review, the controller ruled (2026-10-11):
+- **C1:** no invented end dates. Each window ends at its sourced end, the unit's sourced disbandment or its front's
+ armistice, marked `end_basis: source` or `front_armistice`; the blanket 20 July 1949 is gone.
+- **I1:** "since" only from a sourced start, never the game's first day.
+- **I2:** at most one hex from the sourced anchor, compact beside a town. Never in ground the other side held; until
+ front data exists, the one-hex limit is the guard.
+- **I3:** 101 Squadron's bases where two sources agree (Hatzor from 21 November 1948).
+- **I4:** the Spitfire from its earliest sourced service. That is the first sourced sortie on 15 October 1948; the
+ aircraft arrived on 27 September, unarmed.
+- **I5:** units appear in screenshots and editor renders only when asked for.
+- **I6:** the promo's badge, a wider trio, headgear only where sourced, and the ring for selection only.
+
+Corrections found while implementing:
+- Wedgwood's pennant number: the earlier draft said K-18 without a source. Its two articles conflict (the Beauharnois
+ article gives Hashomer, K 20), so the map shows "INS Wedgwood" and no number.
+- Positions now come with dates from the sources, including Hebrew Wikipedia: Golani at Yavne'el, then Julis from
+ December 1948; the Negev Brigade at the Mekorot camp near Nir Am; the 7th Brigade at Latrun, then Ein Shemer.
+
+Goal: the PR #139 unit art (`docs/units.md`, today behind `?units`) in normal play, looking like
+`promo/final/03-gameplay-1936.png`, driven only by sim state plus sourced map-only data. The sim and goldens do not move.
+
+## 1. What the sim knows
+
+The military in the sim is one national ladder and one number. It has no formations and no positions.
+
+| State | Where |
+|---|---|
+| Security level (rung 1–5) | `GameState.Rung`, sim/Statecraft.Sim/GameState.cs:30; hashed at :88 |
+| UN ceasefire clock (weeks) | `GameState.CeasefireWeeksLeft`, GameState.cs:31; run by SecuritySystem.cs:64-73 |
+| Reserve call-up (0–1) | `GameState.Mobilization`, GameState.cs:32; set by SecuritySystem.cs:44-51 |
+| Minimum call-up per rung | content/rules.yaml:21 `[0.02, 0.05, 0.15, 0.4, 0.8]`; floor applied at SecuritySystem.cs:53-62 |
+| Starting rung | content/rules.yaml:3 (`start_rung: 5`, the war is under way on 1948-05-15) |
+| Orders | `SetMobilization` and `SecurityOrder`, sim/Statecraft.Sim/Commands.cs:31, :38; executed at Simulation.cs:108-117 |
+| Events that set the rung | `EventOption.SetRung`, Content.cs:233; applied at EventSystem.cs:76 (for example operation_horev.yaml:18, second_truce.yaml:18) |
+| Which operations happened | `FiredEvents` and `ChosenOptions`, GameState.cs:35, :38 |
+| Security indicator | content/model.yaml:7 (`security`, national 0–1) |
+
+Brigades exist only as prose in event text ("with five brigades", operation_horev.yaml:3).
+
+**Location data: none.** The sim has no brigades, no air force and no navy. It has no unit identifiers and no
+coordinates. The only things it keeps on hexes are map actions (`Placement`, MapActions.cs:8-15), which are transit
+camps and housing.
+
+## 2. How units appear in normal play
+
+All of this is presentation. A pure function reads `(Content, GameState, UnitData)` and returns a roster of
+`(unit id, art type, hex, figure count, pose)`. The map rebuilds the roster only when its inputs change, in the same way
+that `GameRoot.RenderPlacementsIfChanged` works (unity/Assets/Scripts/UI/GameRoot.cs:226-235).
+
+### Data addition: `content/map/units_1948.yaml` (map-only)
+
+`ContentLoader` hashes only the files it reads (ContentLoader.cs:156-191). It will never read this file, so the content
+hash and the goldens stay fixed. This is the pattern `routes_1948.yaml` already uses (docs/routes.md:17). Each entry has:
+
+- `id`, `name`, `number`, `service` (army, air or navy) and `art_type` (a `UnitShowcase.*Type` constant);
+- `from` and `to` dates: formation and disbandment;
+- `anchors`: a dated list of named places, each resolved to a hex the way `settlement_hexes.yaml` is generated;
+- `sources` (`url` and `checked`) for every date and every anchor.
+
+An entry whose anchor has no source keeps `anchor: null` and draws no token. Positions are never interpolated or guessed.
+
+### Army: one token per brigade, 12 in 1948
+
+Sources checked 2026-10-11, all on en.wikipedia.org:
+
+| Brigade | Sourced sector or base | Source |
+|---|---|---|
+| Golani (1st) | HQ Yavne'el; Lower Galilee, Jezreel, Jordan and Hula valleys | /wiki/Golani_Brigade |
+| Carmeli (2nd) | "the northwest" (split from Levanoni, Feb 1948); no HQ named | /wiki/Carmeli_Brigade, /wiki/Golani_Brigade |
+| Alexandroni (3rd) | "the Sharon region"; no HQ named | /wiki/Golani_Brigade (Plan Dalet section) |
+| Kiryati (4th) | Tel Aviv | /wiki/4th_Armored_Brigade_"Kiryati" |
+| Givati (5th) | from the war's second stage: Gedera, Gan Yavne, Be'er Tuvia | /wiki/Givati_Brigade |
+| Etzioni (6th) | Jerusalem | /wiki/Etzioni_Brigade |
+| 7th | Latrun (May–July 1948) | /wiki/7th_Armored_Brigade_(Israel) |
+| 8th | formed 24 May 1948; no sector named | /wiki/8th_Armored_Brigade_(Israel) |
+| Oded (9th) | conflicting: "headquartered in Jerusalem", yet it fought at al-Malkiyya | /wiki/Oded_Brigade |
+| Harel (10th) | the Jerusalem corridor; formed 16 April 1948 | /wiki/Harel_Brigade |
+| Yiftach (11th) | formed late April 1948 from Jezreel and eastern-valleys battalions; disbanded May 1949 | /wiki/Yiftach_Brigade |
+| Negev (12th) | the Negev, split along the Beersheba–Gaza road | /wiki/Negev_Brigade |
+
+Where the source leaves a gap (Carmeli, Alexandroni and the 8th have no named place, and Oded's sources conflict), the
+anchor must come from Netanel Lorch, *The Edge of the Sword* (1961), or from the IDF and Defense Establishment Archives
+before that token is drawn. The Yiftach article says that 9 of the 12 brigades were disbanded in May 1949. Each brigade's
+`to` date needs its own source.
+
+- **Where:** on the anchor's hex. If two tokens share a hex, the later one by ordinal id moves to the nearest free land
+ hex.
+- **How many figures:** 3 when `Mobilization >= 0.4`, 2 when it is at least 0.15, otherwise 1. The thresholds are the
+ rung floors at rules.yaml:21. The art type is the brigade's (helmet, bush hat or stocking cap).
+- **When they change:** a token appears at its `from` date and goes at its `to` date. It moves only at a sourced, dated
+ anchor change. The figure count changes with a call-up order or a rung change, so on the next turn. Tokens do not
+ follow a player's non-historical event choice; they mark sectors, not manoeuvres.
+
+### Air
+
+101 Squadron, formed 20 May 1948 at IAF Ekron (ex-RAF Aqir), first mission 29 May
+(/wiki/101_Squadron_(Israel)); the IAF itself was founded 28 May 1948 (/wiki/Israeli_Air_Force). The squadron flew the
+Avia S-199 first and the Spitfire later (docs/units.md, "Aircraft").
+
+- One token, at Ekron.
+- At rung 4 or higher it flies the showcase loop over its base. Lower than that, it stands parked.
+- It shows the Spitfire model only from that type's sourced service date. Before then it needs an S-199 (question 3).
+
+### Navy
+
+The navy began with four ex-Aliyah Bet ships impounded in Haifa harbour (/wiki/Israeli_Navy). Three are sourced by
+name: Haganah K-20 (/wiki/HMCS_Norsyd), Wedgwood, Flower class like K-20 (/wiki/HMCS_Beauharnois_(K540)), and the
+flagship Eilat (/wiki/USCGC_Northland_(WPG-49)). Haganah and Wedgwood are drawn off Haifa with the existing corvette model;
+Eilat waits for a model; the fourth ship is not drawn until it is named.
+
+## 3. Interaction
+
+- **Selection:** click a token (`HexPicker`). The existing white ring goes on its hex.
+- **Panel (read-only):** name and number, service, formation date, the sector in the source's words, commanders with
+ dates only where sourced (Golani: Moshe Mann, then Nahum Golan in mid-1948), the national values the token reflects
+ ("Reserve call-up 80% · Security level 5"), and the source links.
+- **Orders: none in this round.** A "Defence" button opens the existing Defence screen
+ (unity/Assets/Scripts/UI/DefencePresenter.cs), where call-up and security orders already live.
+
+## 4. Performance budget
+
+The budget is the one in docs/visual-v1.md:42-44:
+- p95 of 16.7 ms or less at gameplay03 and diorama02 with every feature on;
+- the units feature itself costs 2.5 ms or less (`median(all) - median(-units)` in `?vprofile`).
+
+The worst case is about 12 tokens of 3 figures at about 3,600 triangles each. That is about 130k triangles, plus one
+aircraft and two ships. To stay inside the budget:
+
+- **Shared meshes:** one mesh and one material per art type, drawn instanced (or through the SRP Batcher). That gives
+ about 10 draw calls, plus the shadow pass.
+- **No per-frame CPU work** except the aircraft's single transform. The roster is rebuilt per turn or per order, not per
+ frame.
+- **Fallbacks, in order:** no figure shadows on the low tier; one figure per token beyond the gameplay zoom.
+
+diorama02 already reads 17 ms p95 on a loaded machine (docs/routes.md:220), so measure on an idle machine
+(`machine_lock.py --exclusive`).
+
+## 5. Tests
+
+- **Hash unchanged:** the content hash is the same with and without `units_1948.yaml`. This is the
+ `RouteTests.TheRoutesDoNotMoveTheContentHash` pattern. The goldens stay unchanged.
+- **The roster is pure:** `GameState.Hash()` is equal before and after building the roster. Two builds from equal
+ inputs are equal.
+- **Data lint:** every date and anchor has `url` and `checked`; anchors resolve to land hexes (sea for ships);
+ `art_type` exists; `from` < `to`; ids unique; a null anchor draws nothing.
+- **Roster cases:**
+ - 1948-05-15 at rung 5 with call-up 0.8: every sourced brigade has 3 figures, the aircraft flies, Haganah and Wedgwood are
+ off Haifa;
+ - call-up 0.10: 1 figure each;
+ - after a brigade's `to` date: its token is gone;
+ - at rung 2: the aircraft is parked;
+ - a shared hex: the deterministic offset applies.
+- **Presentation golden:** the roster per turn of the historical playthrough, kept in a separate file under
+ `unity/Assets/Tests`. It is not a sim golden.
+- **Art checkpoint:** a gameplay03 render with units on, plus `?vprofile` against the budget above.
+
+## 6. Owner questions (decided 2026-10-11: see "Rulings" above)
+
+1. **Token granularity:** one per brigade (12), or one per front (north, centre, Jerusalem, south)?
+ *Default: per brigade.*
+2. **Figure count:** driven by call-up, or always a trio as in the promo?
+ *Default: by call-up (1, 2 or 3).*
+3. **Aircraft before the Spitfire's sourced service date:**
+ - (a) build a code-built Avia S-199;
+ - (b) show no aircraft;
+ - (c) show the Spitfire throughout, because the promo beats the era.
+
+ *Default: (a).*
+4. **Tokens with no sourced anchor** (Carmeli, Alexandroni, the 8th, Oded): hide them until Lorch or the archives are
+ checked, or block the feature on that research?
+ *Default: hide them and ship the rest.*
+5. **Movement:** dated sector anchors only, or also move tokens during operation events (Yoav, Hiram, Horev) when they
+ fire?
+ *Default: dated anchors only this round.*
+6. **After the armistices (from mid-1949):** show only the brigades that a source says continued, or hide army tokens
+ at rung 2 and below?
+ *Default: show what is sourced, at its anchor.*
+7. **Orders:** none this round, with a link to the Defence screen. Confirm?
+ *Default: yes.*
diff --git a/docs/units.md b/docs/units.md
index db077b78f..1f09a4677 100644
--- a/docs/units.md
+++ b/docs/units.md
@@ -6,7 +6,8 @@ era-correct riflemen with a selection ring, a mounted rider, and aircraft with I
This page records the slice that matches it, the pipeline choice behind it, the scale, and the sources for every uniform,
aircraft and ship.
-The slice is a **showcase only**. It reads nothing from the sim and changes no game state. Where units stand, move and
+The slice is a **showcase only**. It reads nothing from the sim and changes no game state. Normal play draws the units
+from the sim's state and sourced map-only data with the same models: see "Units in play" below. Where units move and
fight is war mode's job (#104, with the sim side in #21). The golden hashes do not move.
## How to see it
@@ -17,7 +18,11 @@ fight is war mode's job (#104, with the sim side in #21). The golden hashes do n
editor renders. With `shot` the aircraft holds a fixed point, so the screenshots repeat.
- **Desktop player:** run with `-units`.
- **Editor:** `MapCapture.Promo` renders it when given `-units`.
-- **Frame cost:** `?vprofile&units` prices it as the `units` toggle (`median(all) - median(-units)`).
+- **Aircraft close-ups:** `MapCapture.Aircraft` renders the S-199 and the Spitfire alone, from the top, the bottom, the left
+ side and three quarters, into `-captureDir` (default `captures/visual/aircraft`), for checking the markings against the
+ photographs. `MapCapture.Promo -units -unitsDate YYYY-MM-DD` draws the units in play as on that day.
+- **Frame cost:** `?vprofile&units` prices it as the `unitshowcase` toggle (`median(all) - median(-unitshowcase)`). The
+ `units` toggle is the units in play.
Code: `unity/Assets/Scripts/Map/Units/`. The materials are made by `UnitMaterialAssets.Create` in
`unity/Assets/Resources/Units/`. Tests: `UnitShowcaseTests`.
@@ -46,7 +51,7 @@ it, and there are no level-of-detail switches yet.
| Piece | Model | Where (PromoPose.Gameplay03) |
|---|---|---|
| Rifle trio | three 1948 IDF riflemen: bush hat with rifle held ready, Mk II steel helmet with rifle grounded, Palmach stocking cap with rifle slung | on the centre of the hex nearest 34.88 E, 32.01 N (east of Tel Aviv, clear of the settlement labels), inside a white selection ring that fits within the hex |
-| Aircraft | Supermarine Spitfire LF Mk IXe of 101 Squadron, late 1948 – January 1949: red spinner and red-and-white rudder (attested on Spitfires for January 1949), roundel without an outer ring | a 16 km loop over Tel Aviv and the coast, 4.2 km above the highest ground under it, banked 28 degrees, its shadow cast on the ground by the sun |
+| Aircraft | Supermarine Spitfire LF Mk IXe of 101 Squadron, from October 1948: clipped wing, red spinner and diagonal red-and-white rudder stripes, filled Star of David roundels with no outer ring (Efrati pp. 12 and 14) | a 16 km loop over Tel Aviv and the coast, 4.2 km above the highest ground under it, banked 28 degrees, its shadow cast on the ground by the sun |
| Navy | modified Flower-class corvette INS Haganah (K-20), 1948, 63.4 m | off Jaffa (34.63 E, 32.02 N) |
Not in the slice:
@@ -54,6 +59,201 @@ Not in the slice:
waits for the Yishuv era (#49) and a source.
- **Civilian boats.** The owner ruled them out of scope; navy ships are units.
+## Units in play
+
+Normal play draws one token per unit from two inputs: the sim's state and `content/map/units_1948.yaml`.
+- **The state** gives the date, the security level and the reserve call-up (`GameState.Date`, `Rung`, `Mobilization`).
+ Nothing else in the sim describes the military: it has no formations and no positions (design:
+ `docs/superpowers/specs/2026-10-11-units-in-play-design.md`).
+- **The data file** is map-only. `ContentLoader` never reads it, so the content hash and the goldens do not move
+ (`UnitsInPlayTests.TheUnitFileDoesNotMoveTheContentHash`). The WebGL manifest ships it.
+
+Code:
+- `UnitData`: the file.
+- `UnitRoster`: which units show now.
+- `UnitPlacer` and `UnitGround`: each anchor's spot.
+- `UnitLayer`: the tokens and the ring.
+- `UnitBadge`: the badge.
+- `UnitCard` and `InfoPanelPresenter`: the card.
+
+Tests: `UnitsInPlayTests` (EditMode) and `tools/tests/test_units_1948.py` (the data rules, in CI's Python job).
+
+### Rulings (2026-10-11)
+
+The owner ruled:
+1. One token per brigade.
+2. The number of figures follows the call-up: 3 at or above the security-level-4 floor (`rung_min_mobilization`, 0.4),
+ 2 at or above the level-3 floor (0.15), else 1.
+3. 101 Squadron shows an Avia S-199 until the Spitfire's sourced date, then the Spitfire.
+4. The four brigades with no sourced position (Carmeli, Alexandroni, the 8th, Oded) are listed in the file and hidden.
+
+The controller adopted the design's defaults:
+- tokens stand only at dated, sourced positions and do not move with operation events;
+- after the armistices, only what a source says continued is shown;
+- there are no orders: the card links to the Defence screen.
+
+After the staff review the controller ruled:
+- **No invented end dates (C1).** A window ends at the earliest of its sourced end, the unit's sourced disbandment, and
+ the armistice of the front it stood on. Each anchor says which: `end_basis: source` with an `end_note`, or
+ `end_basis: front_armistice` with its `front`. The armistices were signed with Egypt on 24 February 1949, Lebanon on
+ 23 March, Jordan on 3 April and Syria on 20 July (1949 Armistice Agreements). No source yet gives a position after
+ the armistices, so no unit shows after them.
+- **"Since" only from a sourced start (I1).** A window that opens before the game shows from 15 May 1948. The card says
+ "since February 1948" from the anchor's sourced `since`, and gives no start where no source dates the arrival
+ (Givati at Gedera, the ships).
+- **Within one hex (I2).** See "Placement".
+- **The squadron's bases where two sources agree (I3), and the Spitfire from its first sourced service (I4).** See the
+ table.
+- **Plain checkpoints stay comparable (I5).** A screenshot run (`?shot`, `-shot`) switches the units off unless it also
+ asks for them (`&units`, `-units`). The editor's promo renders draw them only with `-units`.
+- **The promo's badge, a wider trio, sourced headgear; the ring stays selection-only (I6).** See "Look".
+
+### What the player sees
+
+| Unit | Positions (dated, from the sources) | Ends |
+|---|---|---|
+| Golani (1st) | Yavne'el (since February 1948); the Julis camp from December 1948 | December 1948 (source); 24 Feb 1949 (Egypt) |
+| Kiryati (4th) | Tel Aviv (since February 1948) | 3 Apr 1949 (Jordan) |
+| Givati (5th) | Gedera, one of the three places its sector names (no start given) | 24 Feb 1949 (Egypt) |
+| Etzioni (6th) | Jerusalem (since late 1947) | 3 Apr 1949 (Jordan) |
+| 7th Brigade | Hulda, its headquarters for the Latrun attacks, 24–31 May 1948; Ein Shemer, June 1948 | sources |
+| Harel (10th) | Sha'ar HaGai, one place picked from the Jerusalem corridor (since the first half of May 1948) | 22 Dec 1948, Operation Horev (source) |
+| Yiftach (11th) | Lydda, 11–19 July 1948 (Operation Dani; the IDF entered Lydda on 11 July) | 20 Jul 1948 (source); disbanded May 1949 |
+| Negev (12th) | the Mekorot camp near Nir Am (since March 1948) | 24 Feb 1949 (Egypt) |
+| 101 Squadron | Ekron, 20–29 May 1948; the Herzliya strip from mid-June; Hatzor from 21 November 1948 | June 1949, the move to Ramat David (source) |
+| INS Haganah, INS Wedgwood | Haifa harbour (commissioned 1948; no start given) | 24 Feb 1949 (Egypt: their sourced actions were against the Egyptian forces) |
+
+**101 Squadron's bases.** The map follows the dates two sources agree on:
+- en.wiki and he.wiki agree it was at Ekron from 20 to 30 May, and at Herzliya from mid-June.
+- Between 30 May and mid-June they disagree. en.wiki says Herzliya after the strafing of 30 May; he.wiki says Ekron,
+ with Modi Alon taking off from there on 3 June. So the map shows no base in that gap.
+- Hatzor from 21 November 1948: Eduard p. 54 and he.wiki ("November"). en.wiki and Eduard p. 53's profile caption say
+ October. he.wiki has Alon killed landing at Herzliya on 16 October, which fits November.
+
+**The aircraft.** The S-199 until 15 October 1948, then the Spitfire.
+- The first Spitfires flew in, unarmed, on 27 September 1948 (Operation Velvetta, he.wiki).
+- The first sourced Spitfire sortie is 15 October: three Spitfires escorting Beaufighters to El Arish (he.wiki
+ Supermarine Spitfire). The squadron flew both types (he.wiki 101 Squadron), and the S-199 flew on sporadically until
+ mid-December (Avia S-199; Eduard p. 54). The ruling allows showing the S-199 until the switch and the Spitfire after.
+- en.wiki's Spitfire operational history calls a 101 Squadron claim of 21 October the IAF's "first ever aerial
+ victory". That is wrong: the first victories were on 3 June 1948, by Modi Alon in an S-199. The file records this.
+
+**Placement** (`UnitPlacer.PlaceAll`). Every anchor is placed once, from the data alone, so a token never moves because
+another unit appears. Its spot is at most one hex step from the sourced place (about 8.7 km between hex centres on 5 km
+hexes). It is the nearest such spot to the place, or to the anchor's sourced `toward` point when it has one (see below).
+The candidates are tried in three rounds:
+1. The centres of the anchor's own hex and its six neighbours, with the token at full size.
+2. If none is clear, those centres plus six points inside each hex, with the token **compact**: half the ring and half
+ the trio's spread, to fit beside a town. Yiftach at Lydda and the squadron at Herzliya stand compact.
+3. If the whole neighbourhood is town, the compact point that reaches least deep into it (then the nearest; with a
+ `toward` point, the nearest to that). The map then keeps a clearing of the compact ring's radius free of the kits'
+ buildings and trees there (`MapScene.UnitClearings`, computed before the kits from the same data), so the token never
+ stands in a building. The clearing may cut only into the anchor's own town, never a neighbour's. Kiryati (Tel Aviv)
+ and Etzioni (West Jerusalem) stand this way.
+
+A spot is clear when:
+- the ring's disc stays off every settlement footprint (the kits' discs, times 1.1);
+- an army token's three figure spots (always three, so the spot does not change with the call-up), or a parked
+ aircraft's centre, are on land and at least 700 m beyond every railway and road corridor;
+- a ship has a sea hex;
+- no other anchor whose window overlaps holds the hex.
+
+**Own side.** The map holds no 1948 front line yet, and the one-hex limit alone does not keep a token on its own side:
+the nearest clear spot can be the other side's ground. So an anchor where that happens has a sourced `toward`, a place on its own side, and where needed a `place_hex`, the hex
+next to the anchor on that side. The token stands at the clear spot nearest that place, in that hex when one is given:
+- Etzioni stands in West Jerusalem, about 2 km west of the place the West Jerusalem article gives, not on the Hizma and
+ Anata side, which Jordan held. It is in town, with a clearing. In every round the placer also tries rings round a
+ `toward` point, every 500 m out to 2.5 km, so a spot can sit between a town's roads near the sourced place.
+- The 7th Brigade is anchored at Hulda, its headquarters for the Latrun attacks (Battles of Latrun), not at Latrun.
+ The Arab Legion held Latrun and the Yalu–Bayt Nuba ridge. The ground between was contested until the Bayt Jiz and
+ Bayt Susin area was cleared on 28 May, and Sar'a was taken only on 13–14 July.
+- Harel stands by Saris on the corridor road, hex (-2,23), taken on 16–17 April 1948. It no longer stands by Sar'a and
+ Artuf.
+
+The test pins Etzioni's distance from the West Jerusalem point, Harel's hex, and the 7th within 2.6 km of Hulda; both
+the 7th and Harel stay more than 3 km from Sar'a. Once dated front data lands, the placer should also reject ground the other side held. `EveryAnchorStandsWithinOneHexClearOfTheTownsAndTheRoutes`
+checks every anchor and logs each spot and its distance.
+
+**Look.**
+- **Models:** the slice's models and the authored-prefab hook.
+- **Army:** a token is 1 to 3 riflemen, spread across the ring as in promo 03, about 2 km apart, so each figure reads on
+ its own.
+- **Headgear:** only the Negev Brigade's is tied to it by a source: knitted stocking caps and Mk II steel helmets, from
+ its two 1948 photographs. Every other brigade has the uniform default (bush hat, steel helmet, bush hat), from the 1948
+ photographs listed under "Sources".
+- **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.
+- **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 dark grey-brown disc (the palette's deck shade) 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.
+
+**Selection and the card.**
+- Clicking a token's hex selects it. The ring goes round it and the hex outline is cleared, so it has one highlight.
+- A second click shows the hex and its map actions. A hidden layer (the `units` toggle off) selects nothing.
+- The card gives the name, the number and the service, where the unit stands (with "since" only from a sourced start),
+ its formation and first commander where sourced, and the sector in the source's words.
+- It also gives the national values the token reflects ("Reserve call-up 80% · security level 5 of 5") and the source
+ hosts, with a draft note that says "Wikipedia only" when the position's own sources are.
+- It has no orders; a button opens the Defence screen.
+
+**The Avia S-199** (`UnitModels.AviaS199`; type `avia-s199-101sqn-1948`):
+- The Bf 109G airframe, 8.94 m long with a 9.92 m span, with the Jumo 211F's wide three-blade paddle propeller and the
+ MG 151 pods under the wings (Avia S-199 article).
+- 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, also has one green.
+- The identification band round the rear fuselage is white, blue, white (Efrati pp. 8 and 11).
+- Filled Star of David roundels sit on both fuselage sides behind the cockpit and under the wings (Efrati pp. 6, 8 and 11,
+ and the 1948 photographs). None sit on top of the wings: over-wing roundels were "standard" on no IAF aircraft from May
+ 1948 to January 1949 (p. 6) and were adopted on the Avias only after the Velvetta Spitfires arrived (pp. 11 and 14).
+- The red spinner, the rudder stripes and the upper-wing roundels of Operation Ten Plagues (from 15 October 1948, Eduard
+ p. 53) are not drawn, because the map shows the Spitfire from that day.
+- The squadron's skull badge on the nose is too small to read at map scale and is left out.
+
+**Cost.** The budget is 2.5 ms or less for the `units` toggle at gameplay03 (docs/visual-v1.md). The measurement was
+headless `?vprofile` on the WebGL build of 943184c, 1920x1080 at DPR 1, 2026-10-11. It ran under the main checkout's
+`machine_lock.py --exclusive --wait-unity`, so no Unity job ran beside it.
+
+| Pose | all | -units | units cost | none |
+|---|---|---|---|---|
+| gameplay03 | 14.74 ms (spread 0.48, p95 17) | 14.14 ms (spread 0.71, p95 15) | 0.60 ms | 11.09 ms |
+| diorama02 | 17.66 ms (spread 0.53, p95 20) | 17.39 ms (spread 0.17, p95 20) | 0.27 ms | 13.18 ms |
+
+- The units cost well under the 2.5 ms budget at both poses. The new-game state draws 6 brigades (up to 18 riflemen,
+ with their badges) and 2 ships.
+- The whole scene's p95 is over 16.7 ms at gameplay03 (17 ms), and at diorama02 even without units (20 ms). The base
+ frame here (`none` 11.09 ms) is slower than in earlier runs. That is a scene-wide matter for the perf track, not
+ this layer's.
+- The layer rebuilds only when the roster changes (a new turn, a call-up or security order). Between those, its only
+ per-frame work is a flying aircraft's transform and turning about ten badges to the camera.
+
+**Left open.**
+- The rows are drafts from Wikipedia (and Eduard and Commons) until a historian checks them against Lorch or the
+ archives.
+- No dated front line: tokens keep within one hex of their sourced place, and three anchors carry a sourced `toward`
+ point to stay on their own side (review MF1).
+- **Kit baseline break:** from 943184c the kits keep the unit clearings in Tel Aviv and West Jerusalem, in plain
+ checkpoints too. So kit metrics before and after that commit are not comparable; this is marked in the art log.
+- Merges still to come (review I7). With promo-borderdata, the info panel's region label must be cleared when a unit
+ card shows. With promo-screens, the wide-screen click guard must cover `ShowUnit` and `UnitLayer.Select` as well as
+ `Show`, and the info panel must keep its `info-defence` button. Both branches add optional `InfoPanelPresenter`
+ parameters, so the call in `GameRoot` should name its arguments.
+- Wedgwood's Israeli name and pennant number conflict between its two articles. The card shows "INS Wedgwood" and no
+ number.
+- No source yet places any unit after the armistices.
+- The Spitfire's red spinner and diagonal rudder stripes date from early October 1948 on the Spitfires themselves
+ (Efrati p. 12); IsraDecal attests them for January 1949.
+- In the historical playthrough the call-up stays at or above 0.4 until the armistices, so the tokens keep three
+ figures.
+
## Pipeline choice: code-built miniatures
Three pipelines were tried on a development Mac (Apple M5 Pro, 48 GB) on 2026-10-11. Each was placed on the map at the
@@ -109,12 +309,14 @@ Aircraft:
- Ferry flights of the Czech Spitfires to Israel (Operation Velvetta, 1948). https://en.wikipedia.org/wiki/Operation_Velvetta
- The Avia S-199 flew first, on 29 May 1948 (Operation Pleshet). https://en.wikipedia.org/wiki/Avia_S-199
The Spitfire was chosen over it because the promo shows a Spitfire (promo beats era, and both are 1948-correct).
-- Spitfire Mk IX shape (an elliptical wing, a four-blade propeller): the IAF Museum airframe at Hatzerim. CC BY 2.5.
+- Spitfire Mk IX shape (a four-blade propeller): the IAF Museum airframe at Hatzerim. CC BY 2.5.
https://commons.wikimedia.org/wiki/File:Spitfire-MkIX-hatzerim-1-1.jpg
- Many IAF IXes had clipped wing tips (Fundekals review, below). The slice keeps the full elliptical wing that the promo
- shows.
+ **Clipped wing (corrected 2026-10-12):** "All Spitfires ferry flown to Israel during the 1948 war were clipped wing
+ Mk.IXe versions" (Efrati p. 14). The clipped tips cut the span by 3 ft 6 in
+ (https://en.wikipedia.org/wiki/Supermarine_Spitfire). The model now has the clipped wing, not the promo's full
+ elliptical one.
- Variant **LF.IXe**, and 101 Squadron's **red spinner** and **red-and-white striped rudder**. On the Spitfires these are
- attested for **January 1949** (IsraDecal); the slice is dated "late 1948 – January 1949".
+ attested for **January 1949** (IsraDecal), and from early October 1948 by Efrati (below).
- IsraDecal Studio, "Spitfire Mk.IX, Israeli Air Force" (IAF-123, 1:24) marking instructions, May 2023. It lists
"Spitfire LF.IXe 2011/26, 101 Squadron, January 1949", painted in RAF colours, with a red spinner and the rudder
painted "in White. Paint Red stripes".
@@ -123,19 +325,36 @@ Aircraft:
101 Tayeset fighters obtained high visibility markings consisting of red spinners and red and white stripes on the
rudders". https://info.eduard.com/en/11-2025-1/strana-53
The page shows the squadron's Avia S-199s ("Messers"), not its Spitfires. So it dates the squadron's markings to
- October 1948, but **on the Spitfires the October 1948 date is unverified**.
+ October 1948. On the Spitfires, Efrati p. 12 confirms that date (below).
- A Fundekals decal review also says 101 Squadron "had the white and red stripes on the rudder".
https://mail.modelingmadness.com/scott/decals/fundekals/fd48idfspit.htm
- - **Unverified:** the stripes' direction. The slice draws them across the rudder.
-- Roundel of 1948–49: a blue Star of David on a white disc, the star clear of the disc's edge, **with no outer blue ring**.
+ - **Diagonal (corrected 2026-10-12):** from early October 1948 the squadron painted "their spinners red and rudders
+ with diagonal red and white stripes" (Efrati p. 12, with the photographs of Spitfires 14 and 17). This also
+ dates the Spitfires' markings to October 1948.
+- Roundel of 1948–49: a **filled** blue Star of David on a white disc, the star clear of the disc's edge, **with no outer
+ blue ring**.
+ - **Filled, not an outline** (checked 2026-10-12, after the owner asked).
+ - Efrati, p. 6, on the Bonanzas after 15 May 1948: "Ground visibility of the open star was poor so he [Boris Senior]
+ suggested that the Star of David be filled resulting in the IAF insignia as applied on IAF aircraft ever since."
+ - Every 1948–49 photograph checked shows the star filled: the S-199s D-120 and D-123 and the Spitfires 14 and 17
+ (Efrati pp. 11–12), and the public-domain S-199 photographs on Commons (below).
+ - An open, outline star was used only briefly before that change. The model draws the filled star, and
+ `UnitsInPlayTests.TheRoundelIsAFilledStarOfDavidOnAWhiteDiscWithNoRing` pins it.
+ - Where the roundels sit:
+ - Spitfire: both fuselage sides and both wing surfaces. The Velvetta Spitfires arrived with over-wing roundels
+ painted over their Czechoslovak ones (Efrati p. 14).
+ - S-199: the fuselage sides and under the wings (see "The Avia S-199" above).
+ - On the fuselage a point is straight up, as in the photographs.
- Flags of the World, citing a 2002 survey of *Born in Battle*: "almost all the roundels show the star within, but not
reaching the edges of, the white disk ... This includes early planes from the 1948/49 war of independence (like
Spitfire ...)". It adds: "the only aircraft showing a roundel with a thin blue ring around are Mosquitos and Meteors
from the 1950ies". https://crwflags.com/fotw/flags/il%5Eairfo.html
- The Commons "early variant" SVG with the ring is drawn from a Mosquito photograph, a 1950s type, so it is not used.
-- **Unverified (one hobby source, IsraDecal):** the camouflage, RAF ocean grey and dark green over medium sea grey. A
- forum report of brown overpaint in theatre is an open question. The museum airframe is bare metal in post-war markings.
- The standard reference, Alex Yofe's *Spitfire Mk. IX in Israeli Air Force Service 1948–1956*, has not been checked.
+- The camouflage, RAF Ocean Grey and Dark Green over Medium Sea Grey, is now **confirmed** for "all Spitfires ferry flown
+ to Israel during the 1948 war" (Efrati p. 14; it was a single hobby source before). Alex Yofe's *Spitfire Mk. IX in
+ Israeli Air Force Service 1948–1956* has still not been checked.
+- Yoav Efrati, *Colors & Markings of the Israeli Air Force* (IAF, 2005), http://files.iaflibrary.org.il/DigitalLibrary/English/ColorsMarkings.pdf: the IAF's own library publishes this reference, which these marking corrections rest on (pages are the
+ book's own numbers).
Navy:
- INS Haganah (K-20), ex-HMCS Norsyd, a modified Flower-class corvette, 208 ft (63.4 m) overall, with an upright
@@ -147,4 +366,28 @@ Navy:
https://commons.wikimedia.org/wiki/File:Hagana_K-20_ship_Israel.jpg
- Photograph of INS Haganah, about 1949. Public domain. https://commons.wikimedia.org/wiki/File:INSHaganah.jpg
+Avia S-199 (units in play):
+- Type, dimensions, the Jumo 211F with its paddle-bladed propeller, the underwing MG 151 kit; the first four arrived on
+ 20 May 1948 and flew first on 29 May; mostly withheld by the end of October 1948.
+ https://en.wikipedia.org/wiki/Avia_S-199
+- Eduard Info 11/2025, p. 53: 101 Squadron at Herzliya (July–August 1948) and Hatzor (October 1948); D-123 in "the same
+ shade of green"; for Operation Ten Plagues (15–22 October 1948) red spinners, red and white rudder stripes, and Star
+ of David roundels "applied atop the wings for the first time". https://info.eduard.com/en/11-2025-1/strana-53
+- Eduard Info 11/2025, p. 54: Avia-built aircraft "bore the standard MNO Smalt Avion 2036.02 paint scheme on all
+ surfaces"; 101 Squadron moved to Qastina (Hatzor) on 21 November 1948. https://info.eduard.com/en/11-2025-1/strana-54
+- Photographs of 101 Squadron S-199s in 1948 (public domain): the white rear-fuselage bands, the roundels on the lower
+ wing surfaces, the paddle propeller.
+ https://commons.wikimedia.org/wiki/File:Avia-S-199-IAF-101Sqn-Tel-Nof-Israel-1948-01.jpg and
+ https://commons.wikimedia.org/wiki/File:Avia_S-199_in_June_1948_(Israeli_Air_Force).png
+- The Spitfire from 15 October 1948, the first sourced sortie (three Spitfires escorting Beaufighters to El Arish).
+ https://he.wikipedia.org/wiki/%D7%A1%D7%95%D7%A4%D7%A8%D7%9E%D7%A8%D7%99%D7%9F_%D7%A1%D7%A4%D7%99%D7%98%D7%A4%D7%99%D7%99%D7%A8
+ The first Spitfires flew in on 27 September 1948 (Operation Velvetta).
+ https://he.wikipedia.org/wiki/%D7%9E%D7%91%D7%A6%D7%A2_%D7%95%D7%9C%D7%95%D7%95%D7%98%D7%94
+ en.wiki's operational history has IAF Spitfires in combat on 21 October, but wrongly calls a claim that day the
+ IAF's first victory: the first were on 3 June 1948.
+ https://en.wikipedia.org/wiki/Supermarine_Spitfire_operational_history
+
+Brigades, the squadron's bases and the ships: every position, date and coordinate has its own sources and check date
+in `content/map/units_1948.yaml`.
+
The photographs are references only: no image file is copied into the repository.
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index df622c47b..d6100ec2e 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -36,9 +36,13 @@ not move.
while `QualitySettings.asset` (and, when it builds, `unity/Assets/Settings` or `ProjectSettings.asset`) has unstaged
changes, restores them on every exit, and takes the pose list from `PromoPose.cs`. Each checkpoint switches the
worktree's build target WebGL -> OSXUniversal (editor renders) and back at the next build, a reimport each way: budget
- a few minutes per checkpoint. `--units` adds the unit art slice (`docs/units.md`): `&units` on the WebGL shots and
- `-units` on the editor renders. Its art-log rows are named `<name>-units`, so they are never compared with plain
- checkpoints, which never show units.
+ a few minutes per checkpoint. `--units` adds the units (`docs/units.md`): `&units` on the WebGL shots and
+ `-units` on the editor renders. That shows both the unit art slice and the units in play as a new game starts.
+ Normal play draws the units in play, but a `?shot` run switches them off unless `&units` is given
+ (`UnitLayer.HiddenInCaptures`), and the editor draws them only with `-units`. So plain checkpoints never show units, and
+ the `--units` rows are named `<name>-units`, so they are never compared with plain ones.
+ The kits do change for the units, though: from units-in-play's 943184c they keep a clearing where a unit stands in a town
+ (Tel Aviv, West Jerusalem; `MapScene.UnitClearings`). That is a kit baseline break in the art log.
## Budgets (proposed; ratified in Task 10: see "Tier decisions")
Measured on the development Mac (Apple silicon, integrated GPU), 1920x1080 at DPR 1, Chrome for Testing:
diff --git a/tools/tests/test_units_1948.py b/tools/tests/test_units_1948.py
new file mode 100644
index 000000000..dea8e8b3e
--- /dev/null
+++ b/tools/tests/test_units_1948.py
@@ -0,0 +1,92 @@
+"""content/map/units_1948.yaml (docs/units.md, "Units in play"): every position is sourced and every window ends for a
+stated reason (review C1). The C# side (UnitData.Parse, UnitsInPlayTests) enforces the same rules in the game; this
+keeps them in CI's Python job too."""
+from datetime import date
+from pathlib import Path
+from urllib.parse import urlparse
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[2]
+UNITS = yaml.safe_load((ROOT / 'content/map/units_1948.yaml').read_text(encoding='utf-8'))['units']
+# The signing day of each front's armistice (https://en.wikipedia.org/wiki/1949_Armistice_Agreements, checked 2026-10-11).
+ARMISTICE = {'egypt': date(1949, 2, 24), 'lebanon': date(1949, 3, 23), 'jordan': date(1949, 4, 3), 'syria': date(1949, 7, 20)}
+GAME_START = date(1948, 5, 15)
+
+
+def day(s):
+ return date.fromisoformat(s)
+
+
+def sources(u):
+ out = list(u.get('sources') or [])
+ for a in u['anchors']:
+ out += a['sources']
+ out += (a.get('toward') or {}).get('sources') or []
+ for t in u.get('aircraft') or []:
+ out += t['sources']
+ out += u.get('headgear_sources') or []
+ out += (u.get('disbanded') or {}).get('sources') or []
+ return out
+
+
+def wiki(s):
+ host = urlparse(s['url']).netloc
+ return host.endswith('.wikipedia.org') or host == 'www.wikidata.org'
+
+
+def test_every_window_ends_for_a_stated_reason():
+ for u in UNITS:
+ for a in u['anchors']:
+ where = f"{u['id']} {a['place']}"
+ assert a['sources'], where
+ assert a.get('end_basis') in ('source', 'front_armistice'), where
+ if a['end_basis'] == 'source':
+ assert a.get('end_note', '').strip(), f'{where}: a source-based end says which source'
+ assert 'front' not in a, where
+ else:
+ assert day(a['to']) == ARMISTICE[a['front']], f"{where}: ends on the {a['front']} armistice"
+ if u.get('disbanded'):
+ assert day(a['to']) <= day(u['disbanded']['date']), f'{where}: runs past its disbandment'
+ assert u['disbanded']['sources'], u['id']
+ assert GAME_START <= day(a['from']) < day(a['to']), where
+
+
+def test_no_blanket_end_date():
+ ends = [day(a['to']) for u in UNITS for a in u['anchors']]
+ syria = [a for u in UNITS for a in u['anchors'] if day(a['to']) == ARMISTICE['syria']]
+ assert all(a.get('front') == 'syria' for a in syria), 'only a Syrian-front window may end on 20 July 1949'
+ assert max(ends) <= ARMISTICE['syria']
+
+
+def test_since_is_never_the_game_start():
+ for u in UNITS:
+ for a in u['anchors']:
+ assert '15 May 1948' not in str(a.get('since', '')), f"{u['id']} {a['place']}"
+
+
+def test_every_source_has_a_url_and_a_check_date_and_wikipedia_only_is_true():
+ for u in UNITS:
+ srcs = sources(u)
+ assert srcs, u['id']
+ for s in srcs:
+ assert s['url'].startswith('https://'), (u['id'], s)
+ assert day(s['checked']) <= date.today(), (u['id'], s)
+ assert u['wikipedia_only'] == all(wiki(s) for s in srcs), f"{u['id']}: wikipedia_only must match its sources"
+
+
+def test_hidden_brigades_and_headgear():
+ assert {u['id'] for u in UNITS if u.get('hidden')} == {'carmeli', 'alexandroni', 'brigade_8', 'oded'}
+ for u in UNITS:
+ if u.get('hidden'):
+ assert u['anchors'] == []
+ if 'headgear' in u:
+ assert u['service'] == 'army' and len(u['headgear']) == 3 and u['headgear_sources'], u['id']
+
+
+def test_a_toward_point_is_sourced_and_says_why():
+ for u in UNITS:
+ for a in u['anchors']:
+ t = a.get('toward')
+ if t:
+ assert t['note'].strip() and t['sources'], f"{u['id']} {a['place']}"
diff --git a/unity/Assets/Editor/MapCapture.cs b/unity/Assets/Editor/MapCapture.cs
index 7d5da851b..25adf5033 100644
--- a/unity/Assets/Editor/MapCapture.cs
+++ b/unity/Assets/Editor/MapCapture.cs
@@ -160,16 +160,22 @@ public static class MapCapture
/// <summary>Renders each promo pose (PromoPose.All) at 1920x1080 once per quality tier (0 = Mobile, the WebGL tier;
/// 1 = PC) into &lt;-captureDir&gt; (default captures/visual/editor) as &lt;tier&gt;-&lt;pose&gt;.png. Editor renders show no UI
- /// Toolkit labels; tools/art_checkpoint.sh pairs them with the WebGL screenshots, which do. With -units it adds the unit
- /// art slice (UnitShowcase), still.</summary>
+ /// Toolkit labels; tools/art_checkpoint.sh pairs them with the WebGL screenshots, which do. Units only with -units (from
+ /// tools/art_checkpoint.sh --units), as ?shot&amp;units shows them, so plain renders stay comparable across tracks: then
+ /// the unit art slice (UnitShowcase) and the units in play as a new game starts (UnitLayer, as the player shows them
+ /// on its first turn), both still.</summary>
public static void Promo()
{
var args = System.Environment.GetCommandLineArgs();
int at = System.Array.IndexOf(args, "-captureDir");
var dir = at >= 0 && at + 1 < args.Length ? args[at + 1] : Path.Combine(CaptureDir, "visual", "editor");
var map = OpenAndBuild();
- // The unit art slice only when asked (-units, from tools/art_checkpoint.sh --units), as ?shot&units shows it.
- if (System.Array.IndexOf(args, "-units") >= 0) Statecraft.Game.Map.Units.UnitShowcase.Spawn(map, still: true);
+ // The unit art slice and the units in play only when asked (-units, from tools/art_checkpoint.sh --units).
+ if (System.Array.IndexOf(args, "-units") >= 0)
+ {
+ Statecraft.Game.Map.Units.UnitShowcase.Spawn(map, still: true);
+ ShowStartUnits(map);
+ }
// The 1948 sub-districts and the 1949 armistice lines, as play draws them (GameRoot.Begin), so the editor renders pair
// with the WebGL shots: on the game's start by default, or on -regionsDate yyyy-MM-dd (a 1949 date shows the
// armistice zones in force then).
@@ -199,6 +205,25 @@ public static class MapCapture
finally { QualitySettings.SetQualityLevel(saved, true); }
}
+ /// <summary>The units in play as a new game starts (golden seed, historical mode): what the player draws on turn 1, or, with
+ /// -unitsDate, on that day.</summary>
+ static void ShowStartUnits(MapScene map)
+ {
+ var content = Statecraft.Sim.ContentLoader.Load(Paths.Content);
+ var units = Statecraft.Game.Map.Units.UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", Statecraft.Game.Map.Units.UnitData.DefaultFileName)));
+ var layer = Statecraft.Game.Map.Units.UnitLayer.Create(map, units, content.Hexes, still: true);
+ var state = Statecraft.Sim.Simulation.NewGame(content, Statecraft.Sim.GoldenRun.Seed, Statecraft.Sim.Mode.Historical);
+ // -unitsDate YYYY-MM-DD: the units as on that day (a render of a unit outside the first turn; the sim never sees it).
+ var args = System.Environment.GetCommandLineArgs();
+ int at = System.Array.IndexOf(args, "-unitsDate");
+ if (at >= 0 && at + 1 < args.Length)
+ {
+ state = state.Clone();
+ state.Date = Statecraft.Game.Map.Units.UnitData.Day(args[at + 1]);
+ }
+ layer.Show(content, state);
+ }
+
/// <summary>PromoPose.All, plus any "-extraPose name:lon:lat:distanceM:yaw" given (close looks while tuning the art, for
/// example the terraces at 20 km; not promo matches). All are parsed before any capture, so a bad one fails first.</summary>
static List<PromoPose> Poses(string[] args)
@@ -266,6 +291,49 @@ public static class MapCapture
}
}
+ /// <summary>Close-ups of the unit aircraft (the Avia S-199 and the Spitfire) alone, top and side, at a size where the
+ /// insignia read, into -captureDir (default captures/visual/aircraft) as &lt;aircraft&gt;-&lt;view&gt;.png: for checking the
+ /// markings against the sourced photographs (docs/units.md).</summary>
+ public static void Aircraft()
+ {
+ var args = System.Environment.GetCommandLineArgs();
+ int at = System.Array.IndexOf(args, "-captureDir");
+ var dir = at >= 0 && at + 1 < args.Length ? args[at + 1] : Path.Combine(CaptureDir, "visual", "aircraft");
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ var sun = new GameObject("Sun").AddComponent<Light>();
+ sun.type = LightType.Directional; sun.intensity = 1.2f; sun.transform.rotation = Quaternion.Euler(50f, -30f, 0f);
+ RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Flat; RenderSettings.ambientLight = new Color(0.55f, 0.55f, 0.55f);
+ var cam = new GameObject("Camera").AddComponent<Camera>();
+ cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = new Color(0.82f, 0.80f, 0.74f); cam.fieldOfView = 30f;
+ var paint = new Material(Resources.Load<Material>(Statecraft.Game.Map.Units.UnitMaterials.MiniatureResource));
+ paint.SetTexture("_BaseMap", Statecraft.Game.Map.Units.UnitPalette.MakeTexture());
+ foreach (var (name, airframe, prop, hub) in new[]
+ {
+ ("avia-s199", Statecraft.Game.Map.Units.UnitModels.AviaS199("s199"), Statecraft.Game.Map.Units.UnitModels.S199Propeller("p"), Statecraft.Game.Map.Units.UnitModels.S199PropellerHub),
+ ("spitfire", Statecraft.Game.Map.Units.UnitModels.Spitfire("spit"), Statecraft.Game.Map.Units.UnitModels.SpitfirePropeller("p"), Statecraft.Game.Map.Units.UnitModels.SpitfirePropellerHub),
+ })
+ {
+ var plane = new GameObject(name);
+ var body = new GameObject("Airframe"); body.transform.SetParent(plane.transform, false);
+ body.AddComponent<MeshFilter>().sharedMesh = airframe; body.AddComponent<MeshRenderer>().sharedMaterial = paint;
+ var p = new GameObject("Propeller"); p.transform.SetParent(plane.transform, false); p.transform.localPosition = hub;
+ p.AddComponent<MeshFilter>().sharedMesh = prop; p.AddComponent<MeshRenderer>().sharedMaterial = paint;
+ foreach (var (view, pos, look) in new[]
+ {
+ ("top", new Vector3(0f, 22f, -0.5f), new Vector3(0f, 0f, -0.5f)),
+ ("bottom", new Vector3(0f, -22f, -0.5f), new Vector3(0f, 0f, -0.5f)),
+ ("side-left", new Vector3(-20f, 2.5f, -1f), new Vector3(0f, 0f, -1f)),
+ ("three-quarter", new Vector3(-13f, 9f, 13f), Vector3.zero),
+ })
+ {
+ cam.transform.position = pos;
+ cam.transform.LookAt(look, Mathf.Abs(pos.y) > 15f ? Vector3.forward : Vector3.up);
+ Save(cam, 1600, 1000, Path.Combine(dir, $"{name}-{view}.png"));
+ }
+ Object.DestroyImmediate(plane);
+ }
+ }
+
static void Save(Camera cam, int w, int h, string path)
{
var rt = new RenderTexture(w, h, 24); cam.targetTexture = rt; cam.Render();
diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.cs
index 599e05b1a..33ee91c26 100644
--- a/unity/Assets/Scripts/Boot/GameInputs.cs
+++ b/unity/Assets/Scripts/Boot/GameInputs.cs
@@ -18,6 +18,9 @@ namespace Statecraft.Game.Boot
public string RegionsYaml = "";
/// <summary>content/map/route_paths_1948.yaml: the traced railways and roads the map draws (issue #35; map-only).</summary>
public string RoutesYaml = "";
+ /// <summary>content/map/units_1948.yaml: the sourced units the map draws in play (docs/units.md; map-only, "" when
+ /// absent).</summary>
+ public string UnitsYaml = "";
/// <summary>content/map/settlement_population_1945.yaml (the settlement kits' footprints; "" when absent). The sim
/// never reads it.</summary>
public string PopulationYaml = "";
@@ -44,6 +47,7 @@ namespace Statecraft.Game.Boot
SettlementsYaml = File.ReadAllText(Path.Combine(contentDir, "map", SettlementPlacer.DefaultFileName)),
RegionsYaml = File.ReadAllText(Path.Combine(contentDir, "map", Subdistricts1948.FileName)),
RoutesYaml = ReadIfExists(Path.Combine(contentDir, "map", Statecraft.Game.Map.Routes.RoutePaths.DefaultFileName)),
+ UnitsYaml = ReadIfExists(Path.Combine(contentDir, "map", Statecraft.Game.Map.Units.UnitData.DefaultFileName)),
PopulationYaml = File.Exists(Path.Combine(contentDir, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName))
? File.ReadAllText(Path.Combine(contentDir, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName)) : "",
ArmisticeYaml = ReadIfExists(Path.Combine(contentDir, "map", Armistice1949.FileName)),
@@ -69,6 +73,7 @@ namespace Statecraft.Game.Boot
HexesJson = texts["map/hexes.json"], SettlementsYaml = texts["map/" + SettlementPlacer.DefaultFileName],
RegionsYaml = texts["map/" + Subdistricts1948.FileName],
RoutesYaml = texts.TryGetValue("map/" + Statecraft.Game.Map.Routes.RoutePaths.DefaultFileName, out var routes) ? routes : "",
+ UnitsYaml = texts.TryGetValue("map/" + Statecraft.Game.Map.Units.UnitData.DefaultFileName, out var unitsYaml) ? unitsYaml : "",
PopulationYaml = texts.TryGetValue("map/" + Statecraft.Game.Map.Kits.KitPopulation.FileName, out var pop) ? pop : "",
ArmisticeYaml = texts.TryGetValue("map/" + Armistice1949.FileName, out var armistice) ? armistice : "",
},
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index 9c1754abb..92321684e 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using Statecraft.Game.Boot;
using UnityEngine;
@@ -44,6 +45,13 @@ namespace Statecraft.Game.Map
/// from z-fighting the terrain.</summary>
public const float SelectionClearanceM = 30f;
+ /// <summary>Hides the selected hex's outline (a selected unit has the ring instead: UnitLayer).</summary>
+ public void ClearSelection()
+ {
+ var found = Terrain != null ? Terrain.transform.Find(SelectionName) : null;
+ if (found != null) found.GetComponent<MeshRenderer>().enabled = false;
+ }
+
/// <summary>Outlines hex (q, r) with a band draped on the terrain (MapBuilder.DrapedRing, HexMath corners) drawn with
/// the editor-made HexSelection.mat, whose depth offset keeps it from z-fighting the ground (no runtime material). The band is sampled at its outer, middle and inner rings and each index
/// takes the highest, so terrain inside the band cannot rise through it. A hex that is not on the map hides it.</summary>
@@ -103,6 +111,19 @@ namespace Statecraft.Game.Map
/// <summary>The settlement kits' and trees' materials (null, null: placeholder markers only).</summary>
public void ConfigureKits(Material kit, Material tree) { kitMaterial = kit; treeMaterial = tree; }
+ /// <summary>Each settlement's footprint on the ground plane (centre x, z; radius m): the kits' discs
+ /// (SettlementKits.FootprintRadiusM), so the units keep their tokens off the buildings (UnitLayer). Empty before Build.</summary>
+ public IReadOnlyList<(Vector2 centre, float radius)> SettlementFootprints { get; private set; } = new List<(Vector2, float)>();
+
+ /// <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)>();
+
+ /// <summary>Where the kits keep their buildings and trees off the units (centre x, z; radius m): the spot of a unit that
+ /// stands in a town (UnitPlacer's last round, UnitGround.ClearingRadius), so no token stands in a building. Empty before
+ /// Build or without the unit file.</summary>
+ public IReadOnlyList<(Vector2 centre, float radius)> UnitClearings { get; private set; } = new List<(Vector2, float)>();
+
/// <summary>The last Build's kit numbers (buildings, vertices, trees, build time), or null without kits.</summary>
public Kits.KitLayer.Stats KitStats { get; private set; }
@@ -172,6 +193,25 @@ namespace Statecraft.Game.Map
KitStats = null;
// The 1948 railways and roads (issue #35), read before the kits so buildings and trees keep off them.
var routes = Routes.RoutePaths.ReadOrNone(inputs.RoutesYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), Debug.LogWarning);
+ RouteCorridors = Routes.RouteLayer.Corridors(Frame, routes);
+ SettlementFootprints = list.Select(s => { var w = Frame.ToWorld(s.Lon, s.Lat, 0); return (new Vector2(w.x, w.z), Kits.SettlementKits.FootprintRadiusM(s, hexSizeM)); }).ToList();
+ // The units' spots depend only on the footprints, the routes and the land, so they are known before the kits:
+ // a unit placed in a town gets a clearing the kits keep free (UnitLayer places it the same way).
+ var unitData = Units.UnitData.ReadOrNone(inputs.UnitsYaml, Debug.LogWarning);
+ var unitHexes = Hexes.hexes.Select(h => new Statecraft.Sim.MapHex { Q = h.q, R = h.r, Lon = h.lon, Lat = h.lat, ElevM = h.elev_m, Land = h.land, Biome = h.biome }).ToList();
+ var unitGround = new Units.UnitGround(SettlementFootprints, RouteCorridors, unitHexes,
+ (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)>();
+ 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);
+ foreach (var kv in spots.OrderBy(k => k.Value.X).ThenBy(k => k.Value.Z))
+ {
+ var c = new Vector2((float)kv.Value.X, (float)kv.Value.Z);
+ if (kv.Value.InTown && !clearings.Exists(x => x.centre == c)) clearings.Add((c, unitGround.ClearingRadius));
+ }
+ }
+ UnitClearings = clearings;
if (kitsOn)
{
// ?kitscale=, ?housescale=, ?treescale= in the WebGL player: the same layout at another symbolic scale (city
@@ -187,7 +227,8 @@ namespace Statecraft.Game.Map
// The kits replace the marker boxes; the boxes stay as the labels' and tests' anchors, and come back when the
// "kits" toggle turns the kits off (so settlements are never left undrawn).
var kits = Kits.KitLayer.Build(list, Terrain, Frame, Hexes, meta.elev_min_m, kitMaterial, treeMaterial,
- terrainGo.GetComponent<MapRuntimeAssets>(), markers, out var stats, Routes.RouteLayer.Corridors(Frame, routes), kitColumns);
+ terrainGo.GetComponent<MapRuntimeAssets>(), markers, out var stats,
+ RouteCorridors.Concat(UnitClearings.Select(c => (new List<Vector2> { c.centre, c.centre + Vector2.right }, c.radius))).ToList(), kitColumns);
kits.transform.SetParent(transform, true);
kitProbe = kits.GetComponentInChildren<MeshRenderer>(true);
KitStats = stats;
diff --git a/unity/Assets/Scripts/Map/Units/UnitBadge.cs b/unity/Assets/Scripts/Map/Units/UnitBadge.cs
new file mode 100644
index 000000000..d6e9824ce
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitBadge.cs
@@ -0,0 +1,96 @@
+#nullable enable
+using System.Collections.Generic;
+using UnityEngine;
+
+namespace Statecraft.Game.Map.Units
+{
+ /// <summary>The promo's unit badge (promo/final/03-gameplay-1936.png): a small dark rounded plate with a light glyph,
+ /// floating over a token so a player sees it is a unit and can click it. Two flat unlit meshes in the local XY plane
+ /// (the plate, and the glyph a little towards the camera), turned to face each camera as it renders (UnitLayer). The
+ /// glyph says the service: two figures for a brigade, an aircraft for the squadron, a ship for the navy.</summary>
+ public sealed class UnitBadge : MonoBehaviour
+ {
+ /// <summary>The plate's width at map scale (m): about a third of a figure's height, as in the promo.</summary>
+ public const float SizeM = 1400f;
+ /// <summary>Clearance (m) between the token's top and the plate's lower edge.</summary>
+ public const float LiftM = 1300f;
+ /// <summary>A rifleman's height (m, real) and the corvette's mast top (m, real): the token's top before scaling.</summary>
+ public const float FigureHeightM = 1.78f, MastHeightM = 21f;
+ /// <summary>The glyph's offset towards the camera, in plate widths.</summary>
+ public const float GlyphLift = 0.02f;
+ /// <summary>The promo badge's dark navy and its ivory glyph (the selection ring's colour).</summary>
+ public static readonly Color PlateColour = new Color(0.10f, 0.13f, 0.20f), GlyphColour = MapScene.SelectionColour;
+
+ /// <summary>A rounded square, 1 x 1 centred on the origin, corner radius 0.22.</summary>
+ public static Mesh PlateMesh()
+ {
+ var outline = new List<Vector2>();
+ const float half = 0.5f, rad = 0.22f; const int steps = 5;
+ var corners = new[] { new Vector2(half - rad, half - rad), new Vector2(-half + rad, half - rad), new Vector2(-half + rad, -half + rad), new Vector2(half - rad, -half + rad) };
+ for (int c = 0; c < 4; c++)
+ for (int s = 0; s <= steps; s++)
+ {
+ float a = Mathf.PI / 2f * (c + (float)s / steps);
+ outline.Add(corners[c] + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * rad);
+ }
+ var m = new Flat();
+ m.Fan(outline);
+ return m.Build("UnitBadgePlate");
+ }
+
+ /// <summary>The service's glyph inside the plate (about 0.6 across).</summary>
+ public static Mesh GlyphMesh(string service)
+ {
+ var m = new Flat();
+ switch (service)
+ {
+ case UnitData.Army: // two standing figures: a head and a tapered body each
+ foreach (var x in new[] { -0.13f, 0.13f })
+ {
+ m.Fan(Circle(new Vector2(x, 0.17f), 0.07f, 12));
+ m.Fan(new List<Vector2> { new Vector2(x - 0.10f, -0.26f), new Vector2(x + 0.10f, -0.26f), new Vector2(x + 0.08f, 0.07f), new Vector2(x - 0.08f, 0.07f) });
+ }
+ break;
+ case UnitData.Air: // an aircraft seen from above: fuselage, wings, tailplane
+ m.Fan(Rect(0f, 0f, 0.07f, 0.56f));
+ m.Fan(Rect(0f, 0.06f, 0.56f, 0.10f));
+ m.Fan(Rect(0f, -0.22f, 0.22f, 0.07f));
+ break;
+ default: // a ship in profile: hull, bridge, funnel
+ m.Fan(new List<Vector2> { new Vector2(-0.30f, -0.04f), new Vector2(0.30f, -0.04f), new Vector2(0.22f, -0.16f), new Vector2(-0.24f, -0.16f) });
+ m.Fan(Rect(0.04f, 0.04f, 0.16f, 0.16f));
+ m.Fan(Rect(-0.10f, 0.08f, 0.08f, 0.24f));
+ break;
+ }
+ return m.Build("UnitBadgeGlyph-" + service);
+ }
+
+ static List<Vector2> Rect(float cx, float cy, float w, float h) => new List<Vector2>
+ { new Vector2(cx - w / 2, cy - h / 2), new Vector2(cx + w / 2, cy - h / 2), new Vector2(cx + w / 2, cy + h / 2), new Vector2(cx - w / 2, cy + h / 2) };
+
+ static List<Vector2> Circle(Vector2 c, float r, int n)
+ {
+ var pts = new List<Vector2>(n);
+ for (int i = 0; i < n; i++) { float a = 2f * Mathf.PI * i / n; pts.Add(c + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * r); }
+ return pts;
+ }
+
+ /// <summary>Convex polygons as triangle fans in the XY plane (the badge shader draws both faces).</summary>
+ sealed class Flat
+ {
+ readonly List<Vector3> verts = new List<Vector3>(); readonly List<int> tris = new List<int>();
+ public void Fan(List<Vector2> outline)
+ {
+ int b = verts.Count;
+ foreach (var p in outline) verts.Add(new Vector3(p.x, p.y, 0f));
+ for (int i = 1; i + 1 < outline.Count; i++) tris.AddRange(new[] { b, b + i, b + i + 1 });
+ }
+ public Mesh Build(string name)
+ {
+ var mesh = new Mesh { name = name };
+ mesh.SetVertices(verts); mesh.SetTriangles(tris, 0); mesh.RecalculateBounds();
+ return mesh;
+ }
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Units/UnitBadge.cs.meta b/unity/Assets/Scripts/Map/Units/UnitBadge.cs.meta
new file mode 100644
index 000000000..7d9265086
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitBadge.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: e92cd8c5d06704e2a91727bd7fe64299
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Units/UnitData.cs b/unity/Assets/Scripts/Map/Units/UnitData.cs
new file mode 100644
index 000000000..02e06ffd7
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitData.cs
@@ -0,0 +1,274 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Text.RegularExpressions;
+using YamlDotNet.Core;
+using YamlDotNet.Serialization;
+using YamlDotNet.Serialization.NamingConventions;
+
+namespace Statecraft.Game.Map.Units
+{
+ /// <summary>A cited source: its URL and the day it was checked.</summary>
+ public sealed class UnitSource
+ {
+ public string Url { get; set; } = "";
+ public string Checked { get; set; } = "";
+ }
+
+ /// <summary>Where a unit stood: a named place for a dated window [From, To).</summary>
+ public sealed class UnitAnchor
+ {
+ public string Place { get; set; } = "";
+ public double Lon { get; set; }
+ public double Lat { get; set; }
+ public string From { get; set; } = "";
+ /// <summary>The sourced start, as the card shows it ("February 1948"), or null when no source dates the arrival
+ /// (the card then gives no start; the game's first day is never shown as one).</summary>
+ public string? Since { get; set; }
+ public string To { get; set; } = "";
+ /// <summary>Why the window ends: <see cref="UnitData.EndBySource"/> (with <see cref="EndNote"/>) or
+ /// <see cref="UnitData.EndByFrontArmistice"/> (with <see cref="Front"/>).</summary>
+ public string EndBasis { get; set; } = "";
+ public string? EndNote { get; set; }
+ public string? Front { get; set; }
+ /// <summary>Which side of the place the token stands on, where the nearest clear spot would be the other side's
+ /// ground: a sourced point the placer moves towards (within the one-hex limit; review MF1), or null.</summary>
+ public UnitToward? Toward { get; set; }
+ /// <summary>The hex [q, r] the token stands on, chosen on the unit's own side next to its place (with
+ /// <see cref="Toward"/> giving the side and its source), or null for the placer's own choice.</summary>
+ public List<int>? PlaceHex { get; set; }
+ /// <summary>"month" when a window edge is known only to the month (the first of the month is used).</summary>
+ public string? Precision { get; set; }
+ public string? Note { get; set; }
+ public List<UnitSource> Sources { get; set; } = new List<UnitSource>();
+ }
+
+ /// <summary>An aircraft type a squadron flew for a dated window.</summary>
+ public sealed class UnitAircraft
+ {
+ public string Type { get; set; } = "";
+ public string From { get; set; } = "";
+ public string? To { get; set; }
+ public string? Note { get; set; }
+ public List<UnitSource> Sources { get; set; } = new List<UnitSource>();
+ }
+
+ /// <summary>A sourced point on the unit's own side of its place (UnitAnchor.Toward).</summary>
+ public sealed class UnitToward
+ {
+ public string Place { get; set; } = "";
+ public double Lon { get; set; }
+ public double Lat { get; set; }
+ public string Note { get; set; } = "";
+ public List<UnitSource> Sources { get; set; } = new List<UnitSource>();
+ }
+
+ /// <summary>A unit's sourced disbandment: no window may run past it.</summary>
+ public sealed class UnitDisbanded
+ {
+ public string Date { get; set; } = "";
+ public string? Precision { get; set; }
+ public List<UnitSource> Sources { get; set; } = new List<UnitSource>();
+ }
+
+ /// <summary>One unit of content/map/units_1948.yaml (docs/units.md, "Units in play").</summary>
+ public sealed class UnitEntry
+ {
+ public string Id { get; set; } = "";
+ public string Name { get; set; } = "";
+ public string Number { get; set; } = "";
+ public string Service { get; set; } = "";
+ public string? Formed { get; set; }
+ public string? FirstCommander { get; set; }
+ public string Sector { get; set; } = "";
+ public bool WikipediaOnly { get; set; }
+ public string Status { get; set; } = "";
+ /// <summary>Why the map does not draw the unit (the sources name it but do not place it), or null.</summary>
+ public string? Hidden { get; set; }
+ public List<string>? ToVerify { get; set; }
+ /// <summary>The riflemen's headgear (<see cref="UnitData.Headgears"/>), only where a source ties it to the unit.</summary>
+ public List<string>? Headgear { get; set; }
+ public List<UnitSource>? HeadgearSources { get; set; }
+ public UnitDisbanded? Disbanded { get; set; }
+ public List<UnitAnchor> Anchors { get; set; } = new List<UnitAnchor>();
+ public List<UnitAircraft>? Aircraft { get; set; }
+ public List<UnitSource>? Sources { get; set; }
+
+ /// <summary>Every source of the row: its own, its anchors' and its aircraft's.</summary>
+ public IEnumerable<UnitSource> AllSources()
+ {
+ if (Sources != null) foreach (var s in Sources) yield return s;
+ foreach (var a in Anchors)
+ {
+ foreach (var s in a.Sources) yield return s;
+ if (a.Toward != null) foreach (var s in a.Toward.Sources) yield return s;
+ }
+ if (Aircraft != null) foreach (var t in Aircraft) foreach (var s in t.Sources) yield return s;
+ if (HeadgearSources != null) foreach (var s in HeadgearSources) yield return s;
+ if (Disbanded != null) foreach (var s in Disbanded.Sources) yield return s;
+ }
+ }
+
+ public sealed class UnitFile { public List<UnitEntry> Units { get; set; } = new List<UnitEntry>(); }
+
+ /// <summary>Reads content/map/units_1948.yaml. The map draws it (UnitRoster, UnitLayer); the sim never reads it, so it
+ /// is not in the content hash (as route_paths_1948.yaml).</summary>
+ public static class UnitData
+ {
+ public const string DefaultFileName = "units_1948.yaml";
+ public const string Army = "army", Air = "air", Navy = "navy";
+ 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";
+ public static readonly IReadOnlyList<string> Headgears = new[] { SlouchHat, SteelHelmet, WoolCap };
+ /// <summary>The uniform default where no source ties headgear to a unit: the 1948 photographs' bush hat and Mk II
+ /// steel helmet (docs/units.md, "Sources").</summary>
+ public static readonly IReadOnlyList<string> DefaultHeadgear = new[] { SlouchHat, SteelHelmet, SlouchHat };
+
+ /// <summary>The day each front's armistice was signed (https://en.wikipedia.org/wiki/1949_Armistice_Agreements,
+ /// checked 2026-10-11). A window with no sourced end ends on its front's day (end_basis: front_armistice).</summary>
+ public static readonly IReadOnlyDictionary<string, DateTime> FrontArmistice = new Dictionary<string, DateTime>
+ {
+ ["egypt"] = new DateTime(1949, 2, 24), ["lebanon"] = new DateTime(1949, 3, 23),
+ ["jordan"] = new DateTime(1949, 4, 3), ["syria"] = new DateTime(1949, 7, 20),
+ };
+ static readonly HashSet<string> Services = new HashSet<string> { Army, Air, Navy };
+ static readonly HashSet<string> AircraftTypes = new HashSet<string> { AviaS199, Spitfire };
+ static readonly Regex IdRule = new Regex(@"^[a-z][a-z0-9_]*\z");
+ static readonly Regex DayRule = new Regex(@"^\d{4}-\d{2}-\d{2}\z");
+
+ /// <summary>A 'YYYY-MM-DD' day. Throws FormatException on anything else.</summary>
+ public static DateTime Day(string? text)
+ {
+ if (text == null || !DayRule.IsMatch(text)) throw new FormatException($"'{text}' is not 'YYYY-MM-DD'");
+ if (!DateTime.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d))
+ throw new FormatException($"'{text}' is not a date");
+ return d;
+ }
+
+ /// <summary>The units, or none (with a warning) when the file is missing or malformed: a cosmetic layer never stops
+ /// the game (as RoutePaths.ReadOrNone).</summary>
+ public static List<UnitEntry> ReadOrNone(string? yaml, Action<string> warn, string file = DefaultFileName)
+ {
+ if (string.IsNullOrWhiteSpace(yaml)) { warn($"{file}: missing, so the map draws no units"); return new List<UnitEntry>(); }
+ try { return Parse(yaml!, file); }
+ catch (InvalidDataException e) { warn($"{e.Message}; the map draws no units"); return new List<UnitEntry>(); }
+ }
+
+ /// <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
+ /// 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)
+ {
+ UnitFile doc;
+ try
+ {
+ doc = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).WithDuplicateKeyChecking()
+ .Build().Deserialize<UnitFile>(yaml);
+ }
+ catch (YamlException e) { throw new InvalidDataException($"{file}: {e.Message}", e); }
+ if (doc?.Units == null || doc.Units.Count == 0) throw new InvalidDataException($"{file}: no units");
+ var ids = new HashSet<string>();
+ foreach (var u in doc.Units)
+ {
+ if (u == null || string.IsNullOrWhiteSpace(u.Id)) throw new InvalidDataException($"{file}: a unit has an empty id");
+ var at = $"{file}: '{u.Id}'";
+ if (!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 (string.IsNullOrWhiteSpace(u.Name) || string.IsNullOrWhiteSpace(u.Sector)) throw new InvalidDataException($"{at} needs a name and a sector");
+ if (u.Disbanded != null)
+ {
+ try { Day(u.Disbanded.Date); }
+ catch (FormatException e) { throw new InvalidDataException($"{at} disbanded: {e.Message}", e); }
+ if (u.Disbanded.Sources == null || u.Disbanded.Sources.Count == 0) throw new InvalidDataException($"{at} disbanded has no source");
+ }
+ u.Anchors ??= new List<UnitAnchor>();
+ if (u.Hidden == null && u.Anchors.Count == 0) throw new InvalidDataException($"{at} has no anchors (give one, or say why it is hidden)");
+ foreach (var a in u.Anchors)
+ {
+ if (a == null || string.IsNullOrWhiteSpace(a.Place)) throw new InvalidDataException($"{at} an anchor has no place");
+ var where = $"{at} anchor '{a.Place}'";
+ Window(where, a.From, a.To, toRequired: true);
+ if (!(a.Lon >= -180 && a.Lon <= 180 && a.Lat >= -90 && a.Lat <= 90)) throw new InvalidDataException($"{where} has bad coordinates");
+ if (a.Precision != null && a.Precision != "month") throw new InvalidDataException($"{where} precision must be 'month' or left out");
+ if (a.Toward != null && (string.IsNullOrWhiteSpace(a.Toward.Note) || a.Toward.Sources == null || a.Toward.Sources.Count == 0))
+ throw new InvalidDataException($"{where} toward needs a note and a source");
+ if (a.PlaceHex != null && (a.PlaceHex.Count != 2 || a.Toward == null))
+ throw new InvalidDataException($"{where} place_hex is [q, r] and needs a toward saying which side and why");
+ if (a.EndBasis == EndBySource)
+ {
+ if (string.IsNullOrWhiteSpace(a.EndNote)) throw new InvalidDataException($"{where} ends by source but has no end_note saying which");
+ if (a.Front != null) throw new InvalidDataException($"{where} ends by source, so it takes no front");
+ }
+ else if (a.EndBasis == EndByFrontArmistice)
+ {
+ if (a.Front == null || !FrontArmistice.TryGetValue(a.Front, out var day)) throw new InvalidDataException($"{where} needs a front (egypt, lebanon, jordan or syria)");
+ if (Day(a.To) != day) throw new InvalidDataException($"{where} must end on the {a.Front} armistice, {day:yyyy-MM-dd}");
+ }
+ else throw new InvalidDataException($"{where} needs end_basis: source or front_armistice");
+ if (u.Disbanded != null && Day(a.To) > Day(u.Disbanded.Date)) throw new InvalidDataException($"{where} runs past the unit's disbandment");
+ a.Sources ??= new List<UnitSource>();
+ if (a.Sources.Count == 0) throw new InvalidDataException($"{where} has no source");
+ }
+ if (u.Service == Air)
+ {
+ if (u.Aircraft == null || u.Aircraft.Count == 0) throw new InvalidDataException($"{at} is an air unit without aircraft");
+ foreach (var t in u.Aircraft)
+ {
+ if (t == null || !AircraftTypes.Contains(t.Type)) throw new InvalidDataException($"{at} has an unknown aircraft type '{t?.Type}'");
+ Window($"{at} aircraft '{t.Type}'", t.From, t.To, toRequired: false);
+ t.Sources ??= new List<UnitSource>();
+ if (t.Sources.Count == 0) throw new InvalidDataException($"{at} aircraft '{t.Type}' has no source");
+ }
+ }
+ else if (u.Aircraft != null) throw new InvalidDataException($"{at} lists aircraft but is not an air unit");
+ if (u.Headgear != null)
+ {
+ if (u.Service != Army || u.Headgear.Count != 3 || u.Headgear.Exists(h => !((IList<string>)Headgears).Contains(h)))
+ throw new InvalidDataException($"{at} headgear must be three of {string.Join(", ", Headgears)}, on an army unit");
+ if (u.HeadgearSources == null || u.HeadgearSources.Count == 0) throw new InvalidDataException($"{at} headgear has no source");
+ }
+ foreach (var s in u.AllSources())
+ {
+ if (s == null || string.IsNullOrWhiteSpace(s.Url) || !s.Url.StartsWith("https://", StringComparison.Ordinal))
+ throw new InvalidDataException($"{at} has a source without an https url");
+ try { Day(s.Checked); }
+ catch (FormatException e) { throw new InvalidDataException($"{at} source {s.Url}: checked {e.Message}", e); }
+ }
+ }
+ return doc.Units;
+ }
+
+ static void Window(string where, string? from, string? to, bool toRequired)
+ {
+ if (toRequired && string.IsNullOrEmpty(to)) throw new InvalidDataException($"{where}: to is empty (give the window's end)");
+ try
+ {
+ var f = Day(from);
+ if (to != null && Day(to) <= f) throw new InvalidDataException($"{where}: to must be after from");
+ }
+ catch (FormatException e) { throw new InvalidDataException($"{where} from/to: {e.Message}", e); }
+ }
+
+ /// <summary>True when every source of the row is a Wikipedia article or a Wikidata item (the file's wikipedia_only).</summary>
+ public static bool IsWikipediaOnly(UnitEntry u) => IsWikipediaOnly(u.AllSources());
+
+ /// <summary>True when every one of <paramref name="sources"/> is a Wikipedia article or a Wikidata item (the card's
+ /// draft note, per anchor).</summary>
+ public static bool IsWikipediaOnly(IEnumerable<UnitSource> sources)
+ {
+ bool any = false;
+ foreach (var s in sources)
+ {
+ any = true;
+ var host = new Uri(s.Url).Host;
+ if (!(host.EndsWith(".wikipedia.org", StringComparison.Ordinal) || host == "www.wikidata.org")) return false;
+ }
+ return any;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Units/UnitData.cs.meta b/unity/Assets/Scripts/Map/Units/UnitData.cs.meta
new file mode 100644
index 000000000..b4fb8cd3e
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitData.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 029ae9fe4b81a453986a00cee7a10a61
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Units/UnitGround.cs b/unity/Assets/Scripts/Map/Units/UnitGround.cs
new file mode 100644
index 000000000..3e8acd7f1
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitGround.cs
@@ -0,0 +1,116 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+using UnityEngine;
+
+namespace Statecraft.Game.Map.Units
+{
+ /// <summary>What a unit token may stand on, from the built map's presentation data only: the settlement footprints
+ /// (the kits' discs), the railways' and roads' corridors, and the hexes' land. The map (MapScene, to keep the kits'
+ /// buildings off a token that stands in a town) and the layer (UnitLayer) both place the units through it, so they
+ /// agree.</summary>
+ public sealed class UnitGround
+ {
+ /// <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>
+ 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;
+
+ readonly IReadOnlyList<(Vector2 centre, float radius)> footprints;
+ readonly (List<Vector2> line, float half, Rect bounds)[] corridors;
+ readonly IReadOnlyList<MapHex> hexes;
+ readonly Vector2[] hexXZ;
+ public readonly float HexSizeM;
+
+ public UnitGround(IReadOnlyList<(Vector2 centre, float radius)> footprints, IReadOnlyList<(List<Vector2> line, float halfWidth)> routeCorridors,
+ IReadOnlyList<MapHex> hexes, Func<double, double, Vector2> toXZ, float hexSizeM)
+ {
+ this.footprints = footprints; this.hexes = hexes; HexSizeM = hexSizeM;
+ hexXZ = hexes.Select(h => toXZ(h.Lon, h.Lat)).ToArray();
+ corridors = routeCorridors.Where(c => c.line.Count > 0).Select(c =>
+ {
+ float minX = c.line.Min(p => p.x), maxX = c.line.Max(p => p.x), minY = c.line.Min(p => p.y), maxY = c.line.Max(p => p.y);
+ float grow = c.halfWidth + FigureClearanceM;
+ return (c.line, c.halfWidth, Rect.MinMaxRect(minX - grow, minY - grow, maxX + grow, maxY + grow));
+ }).ToArray();
+ }
+
+ /// <summary>The ground ring's radius of a token (m).</summary>
+ public float RingRadius(bool compact) => UnitShowcase.RingRadius * HexSizeM * (compact ? CompactScale : 1f);
+
+ /// <summary>The radius (m) the kits keep clear round a token that stands in a town: its compact ring.</summary>
+ public float ClearingRadius => RingRadius(compact: true);
+
+ /// <summary>The figures' ground points of an army token standing at <paramref name="centre"/>: always the full trio,
+ /// so a spot does not change with the call-up.</summary>
+ public Vector2[] FigurePoints(Vector2 centre, bool compact)
+ {
+ float k = UnitShowcase.TrioSpread * HexSizeM * (compact ? CompactScale : 1f);
+ return UnitShowcase.FigureOffsets(3).Select(o => centre + o * k).ToArray();
+ }
+
+ /// <summary>How far (m) the token's ring reaches into the deepest settlement footprint (with its margin); 0 or less
+ /// when it is clear of every town.</summary>
+ public float TownOverlap(Vector2 centre, bool compact)
+ {
+ float worst = float.MinValue, disc = RingRadius(compact);
+ foreach (var (fc, fr) in footprints) worst = Mathf.Max(worst, fr * FootprintMargin + disc - (fc - centre).magnitude);
+ return worst;
+ }
+
+ /// <summary>True when a token of <paramref name="service"/> may stand at <paramref name="centre"/>: its ring off every
+ /// town, except, when <paramref name="inTown"/>, the town its anchor <paramref name="anchor"/> stands in (the kits then
+ /// keep a clearing for it there, never in a neighbouring town), and its figures (an army token's trio, a parked
+ /// aircraft's centre) on land and off the railways and roads. A ship needs only the sea hex the placer already
+ /// checked.</summary>
+ public bool Clear(string service, Vector2 centre, bool compact, bool inTown, Vector2 anchor)
+ {
+ if (service == UnitData.Navy) return true;
+ float disc = RingRadius(compact);
+ foreach (var (fc, fr) in footprints)
+ {
+ bool own = inTown && (fc - anchor).magnitude < fr * FootprintMargin;
+ if (!own && fr * FootprintMargin + disc - (fc - centre).magnitude > 0f) return false;
+ }
+ var points = service == UnitData.Army ? FigurePoints(centre, compact) : new[] { centre };
+ foreach (var p in points)
+ {
+ if (!LandAt(p)) return false;
+ foreach (var (line, half, bounds) in corridors)
+ if (bounds.Contains(p))
+ for (int i = 0; i + 1 < line.Count; i++)
+ if (DistanceToSegment(p, line[i], line[i + 1]) < half + FigureClearanceM) return false;
+ }
+ return true;
+ }
+
+ bool LandAt(Vector2 p)
+ {
+ int best = -1; float bestD = float.MaxValue;
+ for (int i = 0; i < hexXZ.Length; i++)
+ {
+ float d = (hexXZ[i] - p).sqrMagnitude;
+ if (d < bestD) { bestD = d; best = i; }
+ }
+ return best >= 0 && hexes[best].Land;
+ }
+
+ public static float DistanceToSegment(Vector2 p, Vector2 a, Vector2 b)
+ {
+ var ab = b - a; float len2 = ab.sqrMagnitude;
+ float t = len2 > 0f ? Mathf.Clamp01(Vector2.Dot(p - a, ab) / len2) : 0f;
+ return (p - (a + t * ab)).magnitude;
+ }
+
+ /// <summary>Every anchor's spot (UnitPlacer.PlaceAll) on this ground.</summary>
+ public Dictionary<UnitAnchor, AnchorSpot> Place(IReadOnlyList<UnitEntry> units, Func<double, double, Vector2> toXZ, Action<string>? skipped) =>
+ UnitPlacer.PlaceAll(units, hexes, HexSizeM, (lon, lat) => { var v = toXZ(lon, lat); return (v.x, v.y); },
+ (service, x, z, compact, inTown, ax, az) => Clear(service, new Vector2((float)x, (float)z), compact, inTown, new Vector2((float)ax, (float)az)),
+ (x, z) => TownOverlap(new Vector2((float)x, (float)z), compact: true), skipped);
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Units/UnitGround.cs.meta b/unity/Assets/Scripts/Map/Units/UnitGround.cs.meta
new file mode 100644
index 000000000..9fbcbbd8d
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitGround.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 852249aabbcb64ea4897ee058eb712f1
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
new file mode 100644
index 000000000..1e937c02e
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
@@ -0,0 +1,273 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+using UnityEngine;
+using UnityEngine.Rendering;
+
+namespace Statecraft.Game.Map.Units
+{
+ /// <summary>The units in normal play (docs/units.md, "Units in play"): one token per unit that the sourced unit data
+ /// (units_1948.yaml) and the sim's state give now (<see cref="UnitRoster"/>), each on its anchor's spot
+ /// (<see cref="UnitPlacer"/>, computed once from the data), with the #139 models (and the authored-prefab hook):
+ /// riflemen for a brigade, the squadron's aircraft flying a loop over its base or parked on it, a corvette at sea, and
+ /// over each token the promo's badge (a dark plate with the unit's glyph, <see cref="UnitBadge"/>). Selecting a token
+ /// draws the promo's white ring round it (selection only). Presentation only: it reads the state and never writes it
+ /// (UnitsInPlayTests), so the goldens cannot move. Built under the map's terrain, so a map rebuild destroys it; its
+ /// meshes, palette and materials are owned by its own MapRuntimeAssets, which also unregisters its "units" visual
+ /// toggle (the frame profile prices it).</summary>
+ public sealed class UnitLayer : MonoBehaviour
+ {
+ public const string RootName = "Units", ToggleName = "units";
+ /// <summary>A parked aircraft's centre of gravity above the ground, in real metres (on its undercarriage).</summary>
+ public const float ParkedHeightM = 1.4f;
+ public const float ParkedHeadingDegrees = 200f;
+
+ MapScene map = null!;
+ IReadOnlyList<UnitEntry> units = Array.Empty<UnitEntry>();
+ UnitGround ground = null!;
+ Dictionary<UnitAnchor, AnchorSpot> spots = new Dictionary<UnitAnchor, AnchorSpot>();
+ MapRuntimeAssets assets = null!;
+ Material paint = null!, ringTemplate = null!, badgePlate = null!, badgeGlyph = null!;
+ readonly Dictionary<string, Mesh> meshes = new Dictionary<string, Mesh>();
+ List<UnitToken>? roster;
+ List<PlacedToken> placed = new List<PlacedToken>();
+ Transform tokensRoot = null!;
+ readonly List<Transform> badges = new List<Transform>();
+ GameObject? ring;
+ bool still;
+
+ /// <summary>The tokens drawn now, in the data's order.</summary>
+ public IReadOnlyList<PlacedToken> Tokens => placed;
+ /// <summary>Every anchor's spot, from the data alone.</summary>
+ public IReadOnlyDictionary<UnitAnchor, AnchorSpot> Spots => spots;
+ /// <summary>The ground the anchors were placed on.</summary>
+ public UnitGround PlacementGround => ground;
+ /// <summary>The selected unit's id, or null.</summary>
+ public string? Selected { get; private set; }
+
+ /// <summary>Makes the layer under the map's terrain and places every anchor once; <see cref="Show"/> draws the
+ /// tokens. <paramref name="still"/> holds a flying aircraft at <see cref="UnitShowcase.StillPhase"/> (screenshots
+ /// repeat).</summary>
+ public static UnitLayer Create(MapScene map, IReadOnlyList<UnitEntry> units, IReadOnlyList<MapHex> hexes, bool still)
+ {
+ if (map == null || map.Terrain == null || map.Hexes == null) throw new InvalidOperationException("UnitLayer needs a built map");
+ var terrain = map.Terrain;
+ var old = terrain.transform.Find(RootName);
+ if (old != null)
+ {
+ foreach (var a in old.GetComponentsInChildren<MapRuntimeAssets>(true)) a.RunTeardown();
+ old.SetParent(null);
+ if (Application.isPlaying) Destroy(old.gameObject); else DestroyImmediate(old.gameObject);
+ }
+ var template = Resources.Load<Material>(UnitMaterials.MiniatureResource)
+ ?? throw new InvalidOperationException($"Resources/{UnitMaterials.MiniatureResource}.mat is missing (run UnitMaterialAssets.Create)");
+ var ringTemplate = Resources.Load<Material>(UnitMaterials.RingResource)
+ ?? throw new InvalidOperationException($"Resources/{UnitMaterials.RingResource}.mat is missing (run UnitMaterialAssets.Create)");
+ var root = new GameObject(RootName);
+ root.transform.SetParent(terrain.transform, false);
+ root.transform.position = Vector3.zero; // children are placed in world space
+ var layer = root.AddComponent<UnitLayer>();
+ layer.map = map; layer.units = units; layer.still = still;
+ // The same ground and the same placement as MapScene's (which keeps the kits off a token in a town).
+ layer.ground = Ground(map, hexes);
+ layer.spots = layer.ground.Place(units, XZ(map), Debug.LogWarning);
+ layer.assets = root.AddComponent<MapRuntimeAssets>();
+ var palette = layer.assets.Own(UnitPalette.MakeTexture(readable: false));
+ layer.paint = layer.assets.Own(new Material(template) { name = "UnitMiniature (palette)" });
+ layer.paint.SetTexture("_BaseMap", palette);
+ layer.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.tokensRoot = new GameObject("Tokens").transform;
+ layer.tokensRoot.SetParent(root.transform, false);
+ layer.assets.OnTeardown(VisualToggles.Register(ToggleName, on => { if (root != null) root.SetActive(on); }));
+ return layer;
+ }
+
+ /// <summary>True for a screenshot run (?shot, -shot) that does not also ask for the units (units, -units): the
+ /// layer is then switched off, so plain art checkpoints stay comparable (review I5).</summary>
+ public static bool HiddenInCaptures(string? url, string[] args, bool webgl) =>
+ VisualShots.Requested(url, args, webgl) && !UnitShowcase.Requested(url, args, webgl);
+
+ void OnEnable() => RenderPipelineManager.beginCameraRendering += FaceBadges;
+ void OnDisable() => RenderPipelineManager.beginCameraRendering -= FaceBadges;
+
+ /// <summary>Turns every badge to face the camera about to render (game, editor capture or scene view alike).</summary>
+ void FaceBadges(ScriptableRenderContext _, Camera cam)
+ {
+ if (cam == null) return;
+ var rotation = cam.transform.rotation;
+ foreach (var b in badges) if (b != null) b.rotation = rotation;
+ }
+
+ /// <summary>Draws the units for <paramref name="state"/> (read only). Rebuilds the tokens only when the roster
+ /// changed; returns true when it did. A selected unit that is no longer drawn is deselected.</summary>
+ public bool Show(Content content, GameState state)
+ {
+ var now = UnitRoster.Build(units, content, state);
+ if (roster != null && roster.SequenceEqual(now)) return false;
+ roster = now;
+ placed = UnitPlacer.Place(now, spots);
+ Rebuild();
+ if (Selected != null && !placed.Any(p => p.Token.Unit.Id == Selected)) Select(null); else Select(Selected);
+ return true;
+ }
+
+ /// <summary>What a click on hex (q, r) selects: the unit standing there, unless it is already selected (a second
+ /// click shows the hex, so a token never hides the hex's map actions) or the "units" toggle hides the layer; null
+ /// means show the hex.</summary>
+ public string? UnitToSelectAt(int q, int r)
+ {
+ if (!gameObject.activeInHierarchy) return null;
+ var hit = At(q, r);
+ return hit != null && hit.Value.Token.Unit.Id != Selected ? hit.Value.Token.Unit.Id : null;
+ }
+
+ /// <summary>The token on hex (q, r), or null.</summary>
+ public PlacedToken? At(int q, int r)
+ {
+ foreach (var p in placed) if (p.Q == q && p.R == r) return p;
+ return null;
+ }
+
+ /// <summary>Selects a drawn unit by id (the ring goes round it), or clears the selection (null).</summary>
+ public void Select(string? id)
+ {
+ if (ring != null) { ring.transform.SetParent(null); if (Application.isPlaying) Destroy(ring); else DestroyImmediate(ring); ring = null; }
+ var hit = placed.FirstOrDefault(p => p.Token.Unit.Id == id);
+ Selected = id != null && hit.Token != null ? id : null;
+ if (Selected == null) return;
+ float hex = map.Hexes.hex_size_km * 1000f;
+ ring = UnitShowcase.Ring(map, assets, ringTemplate, transform, Centre(hit.Spot), UnitShowcase.RingRadius * hex * Scale(hit.Spot));
+ }
+
+ static float Scale(AnchorSpot s) => s.Compact ? UnitGround.CompactScale : 1f;
+
+ Vector3 Centre(AnchorSpot s) => UnitShowcase.Ground(map, new Vector3((float)s.X, 0f, (float)s.Z));
+
+ /// <summary>The ground the units are placed on (footprints, routes, land) for a built map.</summary>
+ public static UnitGround Ground(MapScene map, IReadOnlyList<MapHex> hexes) =>
+ new UnitGround(map.SettlementFootprints, map.RouteCorridors, hexes, XZ(map), map.Hexes.hex_size_km * 1000f);
+
+ static Func<double, double, Vector2> XZ(MapScene map) => (lon, lat) => { var w = map.Frame.ToWorld(lon, lat, 0); return new Vector2(w.x, w.z); };
+
+ Mesh MeshFor(string key, Func<Mesh> build)
+ {
+ if (!meshes.TryGetValue(key, out var mesh))
+ {
+ mesh = assets.Own(build());
+ mesh.UploadMeshData(true); // no CPU copy kept in players
+ meshes[key] = mesh;
+ }
+ return mesh;
+ }
+
+ static UnitModels.Headgear Hat(string headgear) => headgear switch
+ {
+ UnitData.SlouchHat => UnitModels.Headgear.SlouchHat,
+ UnitData.SteelHelmet => UnitModels.Headgear.SteelHelmet,
+ UnitData.WoolCap => UnitModels.Headgear.WoolCap,
+ _ => throw new ArgumentException($"unknown headgear '{headgear}'", nameof(headgear)),
+ };
+
+ void Rebuild()
+ {
+ for (int i = tokensRoot.childCount - 1; i >= 0; i--)
+ {
+ var old = tokensRoot.GetChild(i).gameObject;
+ old.transform.SetParent(null);
+ if (Application.isPlaying) Destroy(old); else DestroyImmediate(old);
+ }
+ badges.Clear();
+ float hex = map.Hexes.hex_size_km * 1000f;
+ foreach (var p in placed)
+ {
+ var t = p.Token;
+ var go = new GameObject(t.Unit.Id);
+ go.transform.SetParent(tokensRoot, false);
+ var centre = Centre(p.Spot);
+ float top;
+ switch (t.Unit.Service)
+ {
+ case UnitData.Army:
+ var offsets = UnitShowcase.FigureOffsets(t.Figures);
+ float k = UnitShowcase.TrioSpread * hex * Scale(p.Spot);
+ 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 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)),
+ paint, at, Quaternion.Euler(0, heading, 0), UnitShowcase.FigureScale, out _);
+ UnitShowcase.AddBase(map, figure.transform, at, MeshFor("figure-base", () => UnitShowcase.BaseMesh("UnitFigureBase")), paint);
+ }
+ top = UnitBadge.FigureHeightM * UnitShowcase.FigureScale;
+ break;
+ case UnitData.Air:
+ BuildAircraft(go.transform, t, centre);
+ top = UnitBadge.FigureHeightM * UnitShowcase.FigureScale;
+ break;
+ default:
+ UnitShowcase.Piece(go.transform, "Corvette", t.ArtType, () => MeshFor(t.ArtType, () => UnitModels.Corvette(t.ArtType)),
+ paint, centre, Quaternion.Euler(0, UnitShowcase.ShipHeadingDegrees, 0), UnitShowcase.ShipScale, out _);
+ top = UnitBadge.MastHeightM * UnitShowcase.ShipScale;
+ break;
+ }
+ var badge = new GameObject("Badge");
+ badge.transform.SetParent(go.transform, false);
+ badge.transform.position = centre + Vector3.up * (top + UnitBadge.LiftM);
+ 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;
+ 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);
+ }
+ }
+
+ static void AddRenderer(Transform parent, string name, Mesh mesh, Material mat, float z)
+ {
+ var go = new GameObject(name);
+ go.transform.SetParent(parent, false);
+ go.transform.localPosition = new Vector3(0, 0, z);
+ go.AddComponent<MeshFilter>().sharedMesh = mesh;
+ var r = go.AddComponent<MeshRenderer>();
+ r.sharedMaterial = mat;
+ r.shadowCastingMode = ShadowCastingMode.Off;
+ r.receiveShadows = false;
+ }
+
+ void BuildAircraft(Transform parent, UnitToken t, Vector3 baseCentre)
+ {
+ var plane = new GameObject("Aircraft");
+ plane.transform.SetParent(parent, false);
+ bool spitfire = t.ArtType == UnitShowcase.SpitfireType;
+ Func<Mesh> airframe = spitfire ? (Func<Mesh>)(() => UnitModels.Spitfire(t.ArtType))
+ : () => UnitModels.AviaS199(t.ArtType);
+ UnitShowcase.Piece(plane.transform, "Airframe", t.ArtType, () => MeshFor(t.ArtType, airframe), paint, Vector3.zero, Quaternion.identity, 1f, out bool authored);
+ Transform? prop = null;
+ if (!authored)
+ {
+ var propKey = spitfire ? "spitfire-propeller" : "avia-s199-propeller";
+ var propMesh = MeshFor(propKey, spitfire ? (Func<Mesh>)(() => UnitModels.SpitfirePropeller(propKey)) : () => UnitModels.S199Propeller(propKey));
+ prop = UnitShowcase.Piece(plane.transform, "Propeller", propMesh, paint, Vector3.zero, Quaternion.identity, 1f).transform;
+ prop.localPosition = spitfire ? UnitModels.SpitfirePropellerHub : UnitModels.S199PropellerHub;
+ }
+ plane.transform.localScale = Vector3.one * UnitShowcase.AircraftScale;
+ if (t.Flying)
+ {
+ var flight = plane.AddComponent<ShowcaseFlight>();
+ flight.Configure(baseCentre, UnitShowcase.LoopRadiusM, UnitShowcase.LoopFloor(map, baseCentre, UnitShowcase.LoopRadiusM) + UnitShowcase.AltitudeM,
+ UnitShowcase.LoopSeconds, UnitShowcase.BankDegrees, prop, still ? UnitShowcase.StillPhase : (float?)null);
+ }
+ else
+ plane.transform.SetPositionAndRotation(baseCentre + Vector3.up * ParkedHeightM * UnitShowcase.AircraftScale,
+ Quaternion.Euler(0, ParkedHeadingDegrees, 0));
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs.meta b/unity/Assets/Scripts/Map/Units/UnitLayer.cs.meta
new file mode 100644
index 000000000..b93007338
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 92030c9283a6f4de4b102f0f6665ae5f
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Units/UnitModels.cs b/unity/Assets/Scripts/Map/Units/UnitModels.cs
index 39b8db781..2e1837f4e 100644
--- a/unity/Assets/Scripts/Map/Units/UnitModels.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitModels.cs
@@ -106,14 +106,16 @@ namespace Statecraft.Game.Map.Units
m.Rod(Vector3.Lerp(butt, muzzle, 0.34f), muzzle, 0.016f, 0.014f, P.RifleMetal, segments: 5);
}
- /// <summary>A Supermarine Spitfire LF Mk IXe of 101 Squadron, IAF, late 1948 to January 1949 (sources in
- /// docs/units.md; the red spinner and striped rudder are attested on the Spitfires for January 1949, while the
- /// October 1948 date is attested only for the squadron's S-199s): 11.23 m elliptical wing (the promo's; many IAF IXes had clipped tips), 9.47 m
- /// fuselage, four-blade propeller, the squadron's red spinner and red-and-white striped rudder, and the IAF roundel of
- /// 1948-49, a blue Star of David on a white disc with no outer ring, on the wings and fuselage. The camouflage (RAF
- /// ocean grey and dark green over medium sea grey) is UNVERIFIED: one hobby source, and a report of brown overpaint
- /// in theatre is open. The propeller is a separate mesh (<see cref="SpitfirePropeller"/>) so it can turn. Faces +Z,
- /// centre of gravity at the origin. Built with one mid shade (<see cref="AircraftShade"/>), not by height.</summary>
+ /// <summary>A Supermarine Spitfire LF Mk IXe of 101 Squadron, IAF, from October 1948 (Yoav Efrati, Colors &amp;
+ /// Markings of the Israeli Air Force, IAF, 2005, pp. 12-14):
+ /// - the clipped wing every Spitfire flown to Israel in the war had (p. 14), about 10.2 m span;
+ /// - RAF Ocean Grey and Dark Green over Medium Sea Grey (p. 14);
+ /// - from early October 1948 the squadron's red spinner and diagonal red and white rudder stripes (p. 12);
+ /// - filled Star of David roundels with no ring on the fuselage sides and on both wing surfaces; the Velvetta
+ /// Spitfires arrived with over-wing roundels (p. 14).
+ /// The squadron badge on the left cowling is too small to read at map scale and is left out. The propeller is a
+ /// separate mesh (<see cref="SpitfirePropeller"/>) so it can turn. Faces +Z, centre of gravity at the origin.
+ /// Built with one mid shade (<see cref="AircraftShade"/>), not by height.</summary>
public static Mesh Spitfire(string name)
{
var m = new MiniatureMesh();
@@ -123,14 +125,17 @@ namespace Statecraft.Game.Map.Units
m.Lathe(TRS(Vector3.zero, V(90f, 0, 0), V(0.78f, 1f, 1.05f)), body, P.CamoGreen, 12);
m.Lathe(TRS(V(0, -0.22f, 0), V(90f, 0, 0), V(0.62f, 1f, 0.72f)), new List<Vector2> { new Vector2(-2.6f, 0.2f), new Vector2(-1.0f, 0.62f),
new Vector2(1.6f, 0.62f), new Vector2(2.6f, 0.42f) }, P.Underside, 12);
- // Spinner: 101 Squadron red (on its Spitfires by January 1949).
+ // Spinner: 101 Squadron red, from early October 1948 (Efrati p. 12).
m.Lathe(TRS(V(0, 0.02f, 3.0f), V(90f, 0, 0), Vector3.one), new List<Vector2> { new Vector2(0f, 0.36f), new Vector2(0.45f, 0.26f), new Vector2(0.75f, 0f) }, P.MarkingRed, 10);
// Canopy.
m.Ellipsoid(TRS(V(0, 0.68f, -0.4f), Vector3.zero, V(0.34f, 0.32f, 1.0f)), P.Glass);
- // Elliptical wing: semi-span 5.6 m, root chord 2.5 m, low on the fuselage, with a 6 degree dihedral.
- float semi = 5.6f;
- System.Func<float, float> lead = s => 1.05f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.04f;
- System.Func<float, float> trail = s => 1.45f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.04f;
+ // The clipped wing: every Spitfire flown to Israel in the 1948 war was a clipped-wing Mk IXe (Efrati p. 14); the
+ // tips were replaced by fairings that cut the span by 3 ft 6 in (Supermarine Spitfire article). So the elliptical
+ // planform stops at 84% of the full semi-span, square-ended: semi-span 4.7 m beyond the root, low on the fuselage,
+ // with a 6 degree dihedral.
+ float semi = 4.7f; const float clip = 0.84f;
+ System.Func<float, float> lead = s => 1.05f * Mathf.Sqrt(Mathf.Max(0f, 1f - (s * clip) * (s * clip))) + 0.04f;
+ System.Func<float, float> trail = s => 1.45f * Mathf.Sqrt(Mathf.Max(0f, 1f - (s * clip) * (s * clip))) + 0.04f;
// Disruptive camouflage: two smooth waves across span and chord give irregular patches, not a chequerboard.
System.Func<int, int, int> camo = (i, j) => Mathf.Sin(i * 0.9f + j * 1.7f) + Mathf.Sin(i * 0.37f - j * 2.3f + 1.1f) > 0.2f ? P.CamoGreen : P.CamoGrey;
foreach (var side in new[] { 1f, -1f })
@@ -138,26 +143,100 @@ namespace Statecraft.Game.Map.Units
var w = TRS(V(side * 0.4f, -0.38f, 0.3f), V(0, 0, side * 6f), V(side, 1f, 1f));
m.Wing(w, lead, trail, semi, 0.06f, camo, (i, j) => P.Underside, spanSteps: 12, chordSteps: 4);
// Wing roundel near the tip, on top and below.
- var rp = w.MultiplyPoint3x4(V(semi * 0.66f, 0.12f, -0.15f));
+ var rp = w.MultiplyPoint3x4(V(semi * 0.62f, 0.16f, -0.15f));
Roundel(m, TRS(rp, V(0, 0, side * 6f), Vector3.one), 0.62f);
- Roundel(m, TRS(rp - V(0, 0.24f, 0), V(0, 0, side * 6f), V(1f, -1f, 1f)), 0.62f); // underneath: stacked downwards
+ Roundel(m, TRS(rp - V(0, 0.32f, 0), V(0, 0, side * 6f), V(1f, -1f, 1f)), 0.62f); // underneath: stacked downwards
// Tailplane: small ellipses.
var tp = TRS(V(side * 0.2f, 0.1f, -5.6f), Vector3.zero, V(side, 1f, 1f));
m.Wing(tp, s => 0.45f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.02f, s => 0.55f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.02f,
1.55f, 0.05f, (i, j) => (i + j) % 3 == 0 ? P.CamoGreen : P.CamoGrey, (i, j) => P.Underside, spanSteps: 5, chordSteps: 2);
// Fuselage roundel.
- Roundel(m, TRS(V(side * 0.58f, 0.15f, -2.6f), V(0, 0, side * 90f), Vector3.one), 0.48f);
+ Roundel(m, TRS(V(side * 0.58f, 0.15f, -2.6f), V(0, 0, -side * 90f), Vector3.one), 0.48f, turnDegrees: 30f); // its face (local +Y) outwards
// Radiator under each wing.
m.Box(TRS(V(side * 1.7f, -0.62f, 0.0f), Vector3.zero, V(0.42f, 0.28f, 1.3f)), P.Underside);
}
- // Fin and rudder: the elliptic Spitfire fin, a vertical surface; the rear half (the rudder) striped red and white on
- // both sides. The stripes' direction is not in the sources; they are drawn across the rudder.
- System.Func<int, int, int> fin = (i, j) => j == 0 ? (i % 2 == 0 ? P.CamoGreen : P.CamoGrey) : (i % 2 == 0 ? P.MarkingRed : P.RoundelWhite);
+ // Fin and rudder: the elliptic Spitfire fin, a vertical surface; the rear half (the rudder) in DIAGONAL red and white
+ // stripes on both sides, as 101 Squadron painted them from early October 1948 (Efrati p. 12: "rudders with diagonal
+ // red and white stripes"; the photographs of Spitfires 14 and 17, p. 12).
+ System.Func<int, int, int> fin = (i, j) => j < 2 ? (i % 2 == 0 ? P.CamoGreen : P.CamoGrey) : ((i + j) / 2 % 2 == 0 ? P.MarkingRed : P.RoundelWhite);
m.Wing(TRS(V(0, 0.4f, -5.5f), V(0, 0, 90f), Vector3.one), s => 0.55f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.05f,
- s => 0.75f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.05f, 1.55f, 0.05f, fin, fin, spanSteps: 5, chordSteps: 2);
+ s => 0.75f * Mathf.Sqrt(Mathf.Max(0f, 1f - s * s)) + 0.05f, 1.55f, 0.05f, fin, fin, spanSteps: 10, chordSteps: 4);
return m.Build(name, AircraftShade);
}
+ /// <summary>An Avia S-199 of 101 Squadron, IAF, 1948 (sources in docs/units.md): the Bf 109G airframe with the Jumo 211F
+ /// and its wide paddle-bladed propeller (Avia S-199 article), 8.94 m long with a 9.92 m span, one khaki green on all
+ /// surfaces (about RAL 6013: Efrati, Colors &amp; Markings of the Israeli Air Force, 2005, pp. 8 and 11; Eduard Info 11/2025,
+ /// pp. 53-54), the white-blue-white identification band round the rear fuselage, filled Star of David roundels on the
+ /// fuselage sides and under the wings, none on top (Efrati pp. 6, 8, 11, 14: over-wing roundels came only with the
+ /// Velvetta Spitfires in October 1948), and the MG 151 cannon pods under the wings: its
+ /// scheme until mid-October 1948. The red spinner, rudder stripes and upper-wing roundels the squadron's fighters got
+ /// for Operation Ten Plagues (from 15 October, Eduard p. 53) are not drawn: the map shows the Spitfire from that day
+ /// (docs/units.md). The 101 Squadron skull badge on the nose is too small to read at map scale and is left out. The
+ /// propeller is a separate mesh (<see cref="S199Propeller"/>). Faces +Z, centre of gravity at the origin.</summary>
+ public static Mesh AviaS199(string name)
+ {
+ var m = new MiniatureMesh();
+ var shape = TRS(Vector3.zero, V(90f, 0, 0), V(0.70f, 1f, 1.05f));
+ var body = new List<Vector2> { new Vector2(-5.5f, 0.06f), new Vector2(-4.6f, 0.26f), new Vector2(-2.6f, 0.46f), new Vector2(-0.8f, 0.56f),
+ new Vector2(0.9f, 0.58f), new Vector2(2.2f, 0.55f), new Vector2(2.95f, 0.46f) };
+ m.Lathe(shape, body, P.AviaGreen, 12);
+ // The identification band round the rear fuselage: white, blue, white (Efrati p. 11: "the fuselage identification
+ // white-blue-white blue center stripe"; the 1948 photographs show the white bands either side).
+ foreach (var (z, slot) in new[] { (-3.40f, P.RoundelWhite), (-3.62f, P.RoundelBlue), (-3.84f, P.RoundelWhite) })
+ {
+ float r = Mathf.Lerp(0.26f, 0.46f, (z + 4.6f) / 2.0f) + 0.015f;
+ m.Lathe(shape, new List<Vector2> { new Vector2(z - 0.11f, r), new Vector2(z + 0.11f, r) }, slot, 12);
+ }
+ // A roundel on each fuselage side, behind the cockpit (Efrati p. 11: D-120's "left fuselage identification
+ // roundel", D-123's photograph; the Sherut Avir aircraft had roundels "on the sides of the fuselage", p. 6).
+ foreach (var side in new[] { 1f, -1f })
+ Roundel(m, TRS(V(side * 0.42f, 0.10f, -2.15f), V(0, 0, -side * 90f), Vector3.one), 0.42f, turnDegrees: 30f); // its face (local +Y) outwards
+ // Spinner: the big Jumo spinner, in the airframe's green.
+ m.Lathe(TRS(V(0, 0.02f, 2.95f), V(90f, 0, 0), Vector3.one), new List<Vector2> { new Vector2(0f, 0.40f), new Vector2(0.30f, 0.30f), new Vector2(0.55f, 0f) },
+ P.AviaGreen, 10);
+ m.Ellipsoid(TRS(V(0, 0.58f, -0.6f), Vector3.zero, V(0.30f, 0.28f, 0.85f)), P.Glass);
+ // Straight tapered wing with rounded tips: semi-span 4.6 m beyond the fuselage, low on it, 6.5 degree dihedral.
+ float semi = 4.6f;
+ System.Func<float, float> tip = s => s < 0.8f ? 1f : 0.15f + 0.85f * Mathf.Sqrt(Mathf.Max(0f, 1f - Mathf.Pow((s - 0.8f) / 0.2f, 2f)));
+ foreach (var side in new[] { 1f, -1f })
+ {
+ var w = TRS(V(side * 0.35f, -0.40f, 0.25f), V(0, 0, side * 6.5f), V(side, 1f, 1f));
+ m.Wing(w, s => (0.70f - 0.20f * s) * tip(s), s => (1.30f - 0.60f * s) * tip(s), semi, 0.06f, (i, j) => P.AviaGreen, (i, j) => P.AviaGreen,
+ spanSteps: 10, chordSteps: 3);
+ var rp = w.MultiplyPoint3x4(V(semi * 0.62f, 0f, -0.25f));
+ Roundel(m, TRS(rp - V(0, 0.11f, 0), V(0, 0, side * 6.5f), V(1f, -1f, 1f)), 0.48f); // underneath
+ // The MG 151 pod and the radiator under each wing.
+ var pod = w.MultiplyPoint3x4(V(1.65f, -0.12f, 0f));
+ m.Rod(pod + V(0, 0, -0.3f), pod + V(0, 0, 1.0f), 0.10f, 0.07f, P.AviaGreen, segments: 6);
+ m.Box(TRS(w.MultiplyPoint3x4(V(1.0f, -0.14f, -0.5f)), V(0, 0, side * 6.5f), V(0.55f, 0.18f, 0.9f)), P.AviaGreen);
+ // Tailplane.
+ var tp = TRS(V(side * 0.12f, 0.25f, -4.9f), Vector3.zero, V(side, 1f, 1f));
+ m.Wing(tp, s => (0.45f - 0.15f * s) * tip(s), s => (0.45f - 0.10f * s) * tip(s), 1.45f, 0.05f, (i, j) => P.AviaGreen, (i, j) => P.AviaGreen,
+ spanSteps: 5, chordSteps: 2);
+ }
+ // Fin and rudder, in the airframe's green.
+ System.Func<int, int, int> fin = (i, j) => P.AviaGreen;
+ m.Wing(TRS(V(0, 0.35f, -5.05f), V(0, 0, 90f), Vector3.one), s => (0.55f - 0.15f * s) * tip(s), s => (0.55f - 0.10f * s) * tip(s),
+ 1.35f, 0.05f, fin, fin, spanSteps: 5, chordSteps: 2);
+ return m.Build(name, AircraftShade);
+ }
+
+ /// <summary>The S-199's three paddle blades (the Jumo 211F's propeller: Avia S-199 article), centred on its hub; turns
+ /// about +Z. Placed at <see cref="S199PropellerHub"/> in the aircraft's frame.</summary>
+ public static Mesh S199Propeller(string name)
+ {
+ var m = new MiniatureMesh();
+ for (int b = 0; b < 3; b++)
+ {
+ var dir = Quaternion.Euler(0, 0, 120f * b + 30f) * Vector3.up;
+ m.Rod(dir * 0.25f, dir * 1.55f, 0.20f, 0.17f, P.PropBlack, segments: 5);
+ }
+ return m.Build(name, AircraftShade);
+ }
+
+ public static readonly Vector3 S199PropellerHub = new Vector3(0f, 0.02f, 3.5f);
+
/// <summary>The Spitfire's four-blade propeller, centred on its hub; turns about +Z. Placed at
/// <see cref="SpitfirePropellerHub"/> in the aircraft's frame.</summary>
public static Mesh SpitfirePropeller(string name)
@@ -176,22 +255,42 @@ namespace Statecraft.Game.Map.Units
/// <summary>The aircraft's one shade row: the palette's base colour, a touch under its top highlight.</summary>
public const float AircraftShade = 0.72f;
- /// <summary>The IAF roundel of 1948-49: a white disc and a blue six-pointed star of two triangles whose points stay
- /// clear of the disc's edge, with no outer ring (the ring is a 1950s Mosquito and Meteor marking; FOTW, citing Born
- /// in Battle). Stacked a hair apart so they never z-fight; its plane is the local XZ, facing +Y.</summary>
- static void Roundel(MiniatureMesh m, Matrix4x4 at, float radius)
+ /// <summary>The star's points as a share of the roundel's radius: clear of the disc's edge (FOTW, citing Born in
+ /// Battle; the 1948 photographs in Efrati, Colors &amp; Markings of the Israeli Air Force, 2005, pp. 11-14).</summary>
+ public const float RoundelStarShare = 0.74f;
+
+ /// <summary>The two triangles of the roundel's star (radius 1, centred on the origin), each a filled plate.</summary>
+ public static List<Vector2>[] RoundelStar(float turnDegrees = 0f)
{
- m.Plate(at, Circle(radius, 20), P.RoundelWhite, shade: 0.8f);
+ var tris = new List<Vector2>[2];
for (int k = 0; k < 2; k++)
{
- var tri = new List<Vector2>();
+ tris[k] = new List<Vector2>();
for (int i = 0; i < 3; i++)
{
- float a = Mathf.Deg2Rad * (90f + 60f * k + 120f * i);
- tri.Add(new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * radius * 0.74f);
+ float a = Mathf.Deg2Rad * (90f + turnDegrees + 60f * k + 120f * i);
+ tris[k].Add(new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * RoundelStarShare);
}
- m.Plate(at * T(0, 0.012f + 0.002f * k, 0), tri, P.RoundelBlue, shade: 0.8f);
}
+ return tris;
+ }
+
+ /// <summary>The IAF roundel of 1948-49: a white disc with a FILLED blue Star of David, its points clear of the
+ /// disc's edge, and no outer ring.
+ /// - Filled, not an outline: "Ground visibility of the open star was poor so he [Boris Senior] suggested that the
+ /// Star of David be filled resulting in the IAF insignia as applied on IAF aircraft ever since" (Yoav Efrati,
+ /// Colors &amp; Markings of the Israeli Air Force, IAF, 2005, p. 6, on the Bonanzas after 15 May 1948). The 1948
+ /// photographs of 101 Squadron's S-199s and Spitfires (Efrati pp. 11-14; Commons, public domain) show the star
+ /// filled.
+ /// - No ring: a thin blue ring appears only on 1950s Mosquitos and Meteors (FOTW, citing Born in Battle).
+ /// The plates are stacked a hair apart so they never z-fight; the plane is the local XZ, facing +Y.
+ /// <paramref name="turnDegrees"/> 30 sets a point straight up on a fuselage side, as the photographs show.</summary>
+ static void Roundel(MiniatureMesh m, Matrix4x4 at, float radius, float turnDegrees = 0f)
+ {
+ m.Plate(at, Circle(radius, 20), P.RoundelWhite, shade: 0.8f);
+ var star = RoundelStar(turnDegrees);
+ for (int k = 0; k < 2; k++)
+ m.Plate(at * T(0, 0.012f + 0.002f * k, 0), star[k].ConvertAll(v => v * radius), P.RoundelBlue, shade: 0.8f);
}
static List<Vector2> Circle(float r, int n)
diff --git a/unity/Assets/Scripts/Map/Units/UnitPalette.cs b/unity/Assets/Scripts/Map/Units/UnitPalette.cs
index 6036b2881..325271874 100644
--- a/unity/Assets/Scripts/Map/Units/UnitPalette.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitPalette.cs
@@ -5,9 +5,9 @@ namespace Statecraft.Game.Map.Units
{
/// <summary>The paint pots of the unit miniatures: one column per slot, one row per shade. Sources are in docs/units.md:
/// 1948 IDF khaki drill and British 37-pattern webbing (photographs); the IAF roundel (a blue star on a white disc);
- /// 101 Squadron's red spinner and red-and-white rudder (on its Spitfires, January 1949: IsraDecal). The Spitfire's RAF day-fighter colours
- /// (ocean grey and dark green over medium sea grey) have a single hobby source and are unverified; a forum report of a
- /// brown overpaint in theatre is an open question. The corvette's light grey follows its 1948 photograph. Colours are
+ /// 101 Squadron's red spinner and red-and-white rudder (from early October 1948: Efrati, Colors &amp; Markings of the Israeli
+ /// Air Force, p. 12). The Spitfire's RAF day-fighter colours (Ocean Grey and Dark Green over Medium Sea Grey) are
+ /// Efrati's p. 14. The S-199's khaki green is about RAL 6013 (Efrati pp. 8 and 11). The corvette's light grey follows its 1948 photograph. Colours are
/// pushed a little warmer and lighter than the photographs so they read at map scale under the warm grade, as the
/// promo's painted figures do. The texture is made at runtime (no file ships), owned by the showcase.</summary>
public static class UnitPalette
@@ -15,7 +15,7 @@ namespace Statecraft.Game.Map.Units
public const int Skin = 0, Shirt = 1, Trousers = 2, Webbing = 3, Helmet = 4, SlouchHat = 5, WoolCap = 6, Boots = 7,
RifleWood = 8, RifleMetal = 9, Hair = 10, ShirtFaded = 11,
CamoGrey = 12, CamoGreen = 13, Underside = 14, RoundelWhite = 15, RoundelBlue = 16, PropBlack = 17, Glass = 18,
- HullGrey = 19, Deck = 20, Waterline = 21, Funnel = 22, MarkingRed = 23, Count = 24;
+ HullGrey = 19, Deck = 20, Waterline = 21, Funnel = 22, MarkingRed = 23, AviaGreen = 24, Count = 25;
/// <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;
@@ -46,6 +46,7 @@ namespace Statecraft.Game.Map.Units
new Color(0.12f, 0.12f, 0.13f), // Waterline
new Color(0.30f, 0.31f, 0.32f), // Funnel top
new Color(0.72f, 0.12f, 0.10f), // MarkingRed: 101 Squadron's spinner and rudder stripes
+ new 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)
};
/// <summary>u of a slot's column centre.</summary>
diff --git a/unity/Assets/Scripts/Map/Units/UnitPlacer.cs b/unity/Assets/Scripts/Map/Units/UnitPlacer.cs
new file mode 100644
index 000000000..16f34dda2
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitPlacer.cs
@@ -0,0 +1,170 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using Statecraft.Sim;
+
+namespace Statecraft.Game.Map.Units
+{
+ /// <summary>Where an anchor's token stands: its hex, its centre on the ground plane (metres), whether it is drawn
+ /// compact (a smaller ring and a tighter trio, to fit beside a town) and whether it stands in a town (the kits then
+ /// keep a clearing for it).</summary>
+ public readonly struct AnchorSpot : IEquatable<AnchorSpot>
+ {
+ public readonly int Q, R; public readonly double X, Z; public readonly bool Compact, InTown;
+ public AnchorSpot(int q, int r, double x, double z, bool compact, bool inTown = false) { Q = q; R = r; X = x; Z = z; Compact = compact; InTown = inTown; }
+ public bool Equals(AnchorSpot o) => Q == o.Q && R == o.R && X == o.X && Z == o.Z && Compact == o.Compact && InTown == o.InTown;
+ public override bool Equals(object? o) => o is AnchorSpot s && Equals(s);
+ public override int GetHashCode() => HashCode.Combine(Q, R, X, Z, Compact, InTown);
+ public override string ToString() => $"({Q},{R}){(Compact ? " compact" : "")}{(InTown ? " in town" : "")}";
+ }
+
+ /// <summary>A token with its spot.</summary>
+ public readonly struct PlacedToken : IEquatable<PlacedToken>
+ {
+ public readonly UnitToken Token; public readonly AnchorSpot Spot;
+ public PlacedToken(UnitToken token, AnchorSpot spot) { Token = token; Spot = spot; }
+ public int Q => Spot.Q;
+ public int R => Spot.R;
+ public bool Equals(PlacedToken o) => Token.Equals(o.Token) && Spot.Equals(o.Spot);
+ public override bool Equals(object? o) => o is PlacedToken p && Equals(p);
+ public override int GetHashCode() => HashCode.Combine(Token, Spot);
+ public override string ToString() => $"{Token} {Spot}";
+ }
+
+ /// <summary>Puts every anchor of the unit data on one spot, once, from the data alone (review M9: a token never moves
+ /// because another unit appears). The spot lies within one hex step of the anchor point (review I2: about 8.7 km
+ /// between hex centres on 5 km hexes) and is the nearest to it, or, when the anchor has a sourced `toward` point on
+ /// the unit's own side (review MF1), the nearest to that, among the following; an anchor with a sourced `place_hex`
+ /// considers only that hex:
+ /// 1. the centres of the anchor's own hex and its six neighbours, drawn full size;
+ /// 2. then, when none is clear, those centres and eighteen points inside each hex (six on each of
+ /// <see cref="InsideOffsets"/> of the hex circumradius), and rings round a `toward` point, drawn compact;
+ /// 3. then, when the anchor's whole neighbourhood is town (Tel Aviv), the same compact points with the ring allowed
+ /// into the town: the one that reaches least deep into it (then the nearest; with a `toward` point, simply the nearest
+ /// to it) is taken, and the kits keep a clearing for it (MapScene), so the token never stands in a building.
+ /// A spot must be land (sea for a ship), on a hex no other anchor with an overlapping window holds, and clear (the
+ /// caller's test: the ring off the settlement footprints except in round 3, the figures on land and off the railways
+ /// and roads). An anchor with no such spot is left out and reported. The map holds no 1948 front line yet: where the
+ /// nearest spot would be the other side's ground, the anchor's sourced `toward` point keeps the token on its own side
+ /// (docs/units.md). Anchors are placed in the data's order.</summary>
+ public static class UnitPlacer
+ {
+ /// <summary>Hexes from the anchor's own hex (axial distance).</summary>
+ public const int MaxShift = 1;
+ /// <summary>The inside points' distances from a hex centre, as fractions of the circumradius (all inside the
+ /// inradius, 0.87): six points on each ring.</summary>
+ public static readonly double[] InsideOffsets = { 0.25, 0.45, 0.65 };
+
+ /// <param name="toXZ">lon, lat to the map's ground plane (metres).</param>
+ /// <param name="clear">(service, x, z, compact, inTown, anchor x, anchor z): true when a token of that service may
+ /// stand there.</param>
+ /// <param name="townOverlap">(x, z): how deep (m) a compact token there reaches into a town (round 3's ranking).</param>
+ public static Dictionary<UnitAnchor, AnchorSpot> PlaceAll(IReadOnlyList<UnitEntry> units, IReadOnlyList<MapHex> hexes, double hexSizeM,
+ Func<double, double, (double x, double z)> toXZ, Func<string, double, double, bool, bool, double, double, bool> clear,
+ Func<double, double, double> townOverlap, Action<string>? skipped = null)
+ {
+ if (units == null) throw new ArgumentNullException(nameof(units));
+ if (hexes == null || hexes.Count == 0) throw new ArgumentException("no hexes", nameof(hexes));
+ var centres = new (double x, double z)[hexes.Count];
+ for (int i = 0; i < hexes.Count; i++) centres[i] = toXZ(hexes[i].Lon, hexes[i].Lat);
+ double maxOffset = Math.Sqrt(3.0) * hexSizeM + 1.0; // one hex step (plus a metre of rounding)
+ var held = new List<(int q, int r, DateTime from, DateTime to)>();
+ var result = new Dictionary<UnitAnchor, AnchorSpot>();
+ foreach (var u in units)
+ {
+ if (u.Hidden != null) continue;
+ bool sea = u.Service == UnitData.Navy;
+ foreach (var a in u.Anchors)
+ {
+ var p = toXZ(a.Lon, a.Lat);
+ // A sourced point on the unit's own side, when the anchor has one: spots are ranked by distance to it.
+ var target = a.Toward != null ? toXZ(a.Toward.Lon, a.Toward.Lat) : p;
+ DateTime from = UnitData.Day(a.From), to = UnitData.Day(a.To);
+ int home = Nearest(centres, p);
+ var (hq, hr) = (hexes[home].Q, hexes[home].R);
+ AnchorSpot? best = null;
+ foreach (var round in new[] { 1, 2, 3 })
+ {
+ bool compact = round > 1, inTown = round == 3;
+ double bestD = double.MaxValue, bestDepth = double.MaxValue;
+ foreach (var (i, x, z) in Candidates(hexes, centres, hexSizeM, compact, a.Toward != null ? target : ((double, double)?)null))
+ {
+ var h = hexes[i];
+ if (h.Land == sea || MapActions.Distance(h.Q, h.R, hq, hr) > MaxShift) continue;
+ if (a.PlaceHex != null && (h.Q != a.PlaceHex[0] || h.R != a.PlaceHex[1])) continue;
+ if (held.Exists(c => c.q == h.Q && c.r == h.R && c.from < to && from < c.to)) continue;
+ if (Math.Sqrt((x - p.x) * (x - p.x) + (z - p.z) * (z - p.z)) > maxOffset) continue;
+ double d = Math.Sqrt((x - target.x) * (x - target.x) + (z - target.z) * (z - target.z));
+ // Round 3 ranks by depth into the town first (rounded to a metre), then by distance; with a
+ // sourced own-side point it ranks by distance to that alone (the town edge may be the other side's).
+ double overlap = inTown ? Math.Max(0.0, townOverlap(x, z)) : 0.0;
+ double depth = a.Toward == null ? Math.Round(overlap) : 0.0;
+ if (depth > bestDepth || (depth == bestDepth && d > bestD)) continue;
+ // Ties go to the lower (q, r): the result never depends on the hex list's order.
+ if (depth == bestDepth && d == bestD && best != null && (h.Q, h.R).CompareTo((best.Value.Q, best.Value.R)) > 0) continue;
+ if (!clear(u.Service, x, z, compact, inTown, p.x, p.z)) continue;
+ best = new AnchorSpot(h.Q, h.R, x, z, compact, inTown && overlap > 0); bestD = d; bestDepth = depth;
+ }
+ if (best != null) break;
+ if (sea) break; // a ship's sea hex is all its test; rounds 2 and 3 add nothing
+ }
+ if (best == null) { skipped?.Invoke($"UNITS no clear spot within one hex of {a.Place} for {u.Id}; not drawn"); continue; }
+ held.Add((best.Value.Q, best.Value.R, from, to));
+ result[a] = best.Value;
+ }
+ }
+ return result;
+ }
+
+ /// <summary>Within the one-hex limit around a `toward` point (every round): rings every
+ /// <see cref="TowardStepM"/> out to <see cref="TowardReachM"/>, twelve points each, so a spot can sit between a
+ /// town's roads near the sourced place, not only on the hex grid's points.</summary>
+ public const double TowardStepM = 500.0, TowardReachM = 2500.0;
+
+ /// <summary>The round's candidate spots, each with the index of the hex it lies in: every hex centre, and for a
+ /// compact round the points inside each hex; and in every round the rings round the `toward` point.</summary>
+ static IEnumerable<(int i, double x, double z)> Candidates(IReadOnlyList<MapHex> hexes, (double x, double z)[] centres, double hexSizeM,
+ bool compact, (double x, double z)? toward)
+ {
+ for (int i = 0; i < hexes.Count; i++)
+ {
+ yield return (i, centres[i].x, centres[i].z);
+ if (!compact) continue;
+ for (int k = 0; k < 6 * InsideOffsets.Length; k++) { var (x, z) = Inside(centres[i], k, hexSizeM); yield return (i, x, z); }
+ }
+ if (toward == null) yield break; // the rings round a `toward` point are tried in every round
+ var t = toward.Value;
+ for (double rad = 0; rad <= TowardReachM; rad += TowardStepM)
+ for (int k = 0; k < (rad == 0 ? 1 : 12); k++)
+ {
+ double x = t.x + Math.Cos(Math.PI / 6.0 * k) * rad, z = t.z + Math.Sin(Math.PI / 6.0 * k) * rad;
+ yield return (Nearest(centres, (x, z)), x, z);
+ }
+ }
+
+ /// <summary>The tokens on their anchors' spots; a token whose anchor has no spot is left out.</summary>
+ public static List<PlacedToken> Place(IReadOnlyList<UnitToken> tokens, IReadOnlyDictionary<UnitAnchor, AnchorSpot> spots)
+ {
+ var list = new List<PlacedToken>(tokens.Count);
+ foreach (var t in tokens) if (spots.TryGetValue(t.Anchor, out var s)) list.Add(new PlacedToken(t, s));
+ return list;
+ }
+
+ static (double x, double z) Inside((double x, double z) c, int k, double hexSizeM)
+ {
+ double ang = Math.PI / 3.0 * (k % 6), off = InsideOffsets[k / 6] * hexSizeM;
+ return (c.x + Math.Cos(ang) * off, c.z + Math.Sin(ang) * off);
+ }
+
+ static int Nearest((double x, double z)[] centres, (double x, double z) p)
+ {
+ int best = 0; double bestD = double.MaxValue;
+ for (int i = 0; i < centres.Length; i++)
+ {
+ double d = (centres[i].x - p.x) * (centres[i].x - p.x) + (centres[i].z - p.z) * (centres[i].z - p.z);
+ if (d < bestD) { bestD = d; best = i; }
+ }
+ return best;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Units/UnitPlacer.cs.meta b/unity/Assets/Scripts/Map/Units/UnitPlacer.cs.meta
new file mode 100644
index 000000000..8ee51f0b6
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitPlacer.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 7dce77523dae74dbf85cab37c6fe2474
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Units/UnitRoster.cs b/unity/Assets/Scripts/Map/Units/UnitRoster.cs
new file mode 100644
index 000000000..f5cdd7be7
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitRoster.cs
@@ -0,0 +1,121 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+
+namespace Statecraft.Game.Map.Units
+{
+ /// <summary>One unit to draw now: its row, the anchor it stands at, and how it looks.</summary>
+ public sealed class UnitToken : IEquatable<UnitToken>
+ {
+ public UnitEntry Unit { get; }
+ public UnitAnchor Anchor { get; }
+ /// <summary>Riflemen on an army token (1, 2 or 3); 0 for aircraft and ships.</summary>
+ public int Figures { get; }
+ /// <summary>The model's art type (a <c>UnitShowcase.*Type</c> constant; the authored-prefab hook's key).</summary>
+ public string ArtType { get; }
+ /// <summary>An air unit flies over its base (security level 4 or 5) or stands parked on it.</summary>
+ public bool Flying { get; }
+ /// <summary>An army token's riflemen's headgear, one per figure in the trio's order (<see cref="UnitData.Headgears"/>);
+ /// empty for aircraft and ships.</summary>
+ public IReadOnlyList<string> Headgear { get; }
+
+ public UnitToken(UnitEntry unit, UnitAnchor anchor, int figures, string artType, bool flying, IReadOnlyList<string>? headgear = null)
+ {
+ Unit = unit; Anchor = anchor; Figures = figures; ArtType = artType; Flying = flying;
+ Headgear = headgear ?? Array.Empty<string>();
+ }
+
+ public bool Equals(UnitToken? o) => o != null && ReferenceEquals(Unit, o.Unit) && ReferenceEquals(Anchor, o.Anchor)
+ && Figures == o.Figures && ArtType == o.ArtType && Flying == o.Flying && Headgear.SequenceEqual(o.Headgear);
+ public override bool Equals(object? o) => Equals(o as UnitToken);
+ public override int GetHashCode() => HashCode.Combine(Unit.Id, Anchor.Place, Figures, ArtType, Flying);
+ public override string ToString() => $"{Unit.Id}@{Anchor.Place}:{ArtType}x{Figures}{(Headgear.Count > 0 ? "[" + string.Join("/", Headgear) + "]" : "")}{(Flying ? " flying" : "")}";
+ }
+
+ /// <summary>Which units the map draws, from the sim's state and the map-only unit data (docs/units.md, "Units in play").
+ /// Pure and read-only: it reads the date, the security level and the reserve call-up, and never writes the state, so
+ /// the sim and its goldens cannot move (UnitsInPlayTests). Rules (owner, 2026-10-11):
+ /// a unit shows while the date is inside one of its sourced anchor windows, and never when its row is hidden;
+ /// an army token has 3 figures at a call-up of at least the security-level-4 floor (rules.yaml rung_min_mobilization,
+ /// 0.4), 2 at the level-3 floor (0.15), else 1; an air unit flies at security level 4 or 5 and stands parked below it,
+ /// as the aircraft type of its dated window (the Avia S-199, then the Spitfire).</summary>
+ public static class UnitRoster
+ {
+ public const int FlyingFromRung = 4;
+
+ public static List<UnitToken> Build(IReadOnlyList<UnitEntry> units, Content content, GameState state)
+ {
+ if (units == null) throw new ArgumentNullException(nameof(units));
+ if (content == null) throw new ArgumentNullException(nameof(content));
+ if (state == null) throw new ArgumentNullException(nameof(state));
+ return Build(units, content.Rules, state.Date, state.Rung, state.Mobilization);
+ }
+
+ public static List<UnitToken> Build(IReadOnlyList<UnitEntry> units, Rules rules, DateTime date, int rung, double mobilization)
+ {
+ var list = new List<UnitToken>();
+ foreach (var u in units)
+ {
+ if (u.Hidden != null) continue;
+ var anchor = AnchorAt(u, date);
+ if (anchor == null) continue;
+ switch (u.Service)
+ {
+ case UnitData.Army:
+ int figures = FiguresFor(rules, mobilization);
+ var hats = (u.Headgear ?? (IReadOnlyList<string>)UnitData.DefaultHeadgear).Take(figures).ToList();
+ list.Add(new UnitToken(u, anchor, figures, RiflemanType(hats[0]), false, hats));
+ break;
+ case UnitData.Air:
+ var type = AircraftAt(u, date);
+ if (type != null) list.Add(new UnitToken(u, anchor, 0, type, rung >= FlyingFromRung));
+ break;
+ case UnitData.Navy:
+ list.Add(new UnitToken(u, anchor, 0, UnitShowcase.CorvetteType, false));
+ break;
+ }
+ }
+ return list;
+ }
+
+ /// <summary>The art type of a rifleman with <paramref name="headgear"/> (the authored-prefab hook's key).</summary>
+ public static string RiflemanType(string headgear) => headgear switch
+ {
+ UnitData.SlouchHat => UnitShowcase.RiflemanSlouchHatType,
+ UnitData.SteelHelmet => UnitShowcase.RiflemanHelmetType,
+ UnitData.WoolCap => UnitShowcase.RiflemanWoolCapType,
+ _ => throw new ArgumentException($"unknown headgear '{headgear}'", nameof(headgear)),
+ };
+
+ /// <summary>The anchor whose window holds <paramref name="date"/>, or null.</summary>
+ public static UnitAnchor? AnchorAt(UnitEntry u, DateTime date)
+ {
+ foreach (var a in u.Anchors)
+ if (date >= UnitData.Day(a.From) && date < UnitData.Day(a.To)) return a;
+ return null;
+ }
+
+ /// <summary>The art type of the aircraft the unit flew on <paramref name="date"/>, or null between types.</summary>
+ public static string? AircraftAt(UnitEntry u, DateTime date)
+ {
+ if (u.Aircraft == null) return null;
+ foreach (var t in u.Aircraft)
+ {
+ if (date < UnitData.Day(t.From) || (t.To != null && date >= UnitData.Day(t.To))) continue;
+ return t.Type == UnitData.AviaS199 ? UnitShowcase.S199Type : UnitShowcase.SpitfireType;
+ }
+ return null;
+ }
+
+ /// <summary>1, 2 or 3 riflemen: the call-up against the floors of security levels 3 and 4 (rules.yaml).</summary>
+ public static int FiguresFor(Rules rules, double mobilization)
+ {
+ if (rules.RungMinMobilization.Count != 5) throw new ArgumentException("rules need five rung floors", nameof(rules));
+ if (mobilization >= rules.RungMinMobilization[3]) return 3;
+ if (mobilization >= rules.RungMinMobilization[2]) return 2;
+ return 1;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Units/UnitRoster.cs.meta b/unity/Assets/Scripts/Map/Units/UnitRoster.cs.meta
new file mode 100644
index 000000000..8c95f42ec
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/UnitRoster.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: ff79294945065402aa65bb2b92dcffc3
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Units/UnitShowcase.cs b/unity/Assets/Scripts/Map/Units/UnitShowcase.cs
index 27654f103..4acef2a3f 100644
--- a/unity/Assets/Scripts/Map/Units/UnitShowcase.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitShowcase.cs
@@ -9,14 +9,14 @@ namespace Statecraft.Game.Map.Units
{
/// <summary>The unit art slice (owner, 2026-10-11: "make sure the units are like in the promo video"): a 1948 rifle
/// trio with a selection ring, a Spitfire flying a loop with its shadow on the ground, and a corvette at sea, all at
- /// <see cref="PromoPose.Gameplay03"/>. A showcase only: it reads nothing from the sim and places no unit the game state
- /// knows about (where real units stand, move and fight is war mode's job, issue #104). It appears only when asked
- /// for ("units" in the WebGL page URL or -units on desktop), in the art checkpoint's screenshots ("shot") and in the
- /// editor's promo renders; normal play never shows it. Registers the "units" visual toggle, so the frame profile can
- /// price it (?vprofile&amp;units).</summary>
+ /// <see cref="PromoPose.Gameplay03"/>. A showcase only: it reads nothing from the sim. Normal play draws the units the
+ /// sim's state and the sourced unit data give (<see cref="UnitLayer"/>), with the same models; this slice appears only
+ /// when asked for ("units" in the WebGL page URL or -units on desktop), in the art checkpoint's screenshots and in the
+ /// editor's promo renders. Registers the "unitshowcase" visual toggle, so the frame profile can price it
+ /// (?vprofile&amp;units); the "units" toggle is the in-play layer's.</summary>
public static class UnitShowcase
{
- public const string RootName = "UnitShowcase", ToggleName = "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
@@ -62,14 +62,35 @@ namespace Statecraft.Game.Map.Units
/// the <c>*Type</c> constants below.</summary>
public const string AuthoredFolder = "Units/Authored/";
public const string RiflemanSlouchHatType = "rifleman-1948-slouch-hat", RiflemanHelmetType = "rifleman-1948-steel-helmet",
- RiflemanWoolCapType = "rifleman-1948-wool-cap", SpitfireType = "spitfire-mk9e-101sqn-1948", CorvetteType = "corvette-k20-1948";
+ RiflemanWoolCapType = "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 =
+ {
+ (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),
+ };
+
+ /// <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>
+ internal static Vector2[] FigureOffsets(int figures) => figures switch
+ {
+ 1 => new[] { Vector2.zero },
+ 2 => new[] { new Vector2(-0.6f, 0f), new Vector2(0.6f, 0f) },
+ 3 => new[] { new Vector2(-1.0f, -0.1f), new Vector2(0f, 0.2f), new Vector2(1.0f, -0.1f) },
+ _ => throw new ArgumentOutOfRangeException(nameof(figures), "a token has 1, 2 or 3 figures"),
+ };
/// <summary>Finds an authored model for a unit type, or null (a seam: tests replace it).</summary>
internal static Func<string, GameObject?> AuthoredModel = type => Resources.Load<GameObject>(AuthoredFolder + type);
/// <summary>Builds the showcase under the map's terrain (so a map rebuild destroys it). Its meshes, palette and
/// material are owned by the showcase root's own MapRuntimeAssets, so destroying the root (a re-spawn or a map
- /// rebuild) frees them, and the "units" toggle is registered through that teardown. The trio stands on the centre of
+ /// rebuild) frees them, and the "unitshowcase" toggle is registered through that teardown. The trio stands on the centre of
/// the hex nearest <see cref="TrioAt"/>. <paramref name="still"/> freezes the flight at <see cref="StillPhase"/>.
/// Returns the root.</summary>
public static GameObject Spawn(MapScene map, bool still)
@@ -101,16 +122,11 @@ namespace Statecraft.Game.Map.Units
// The trio: three riflemen in a loose triangle facing the camera's side of south-west, around the hex's centre.
var centre = HexCentreNear(map, TrioAt.lon, TrioAt.lat);
- var looks = new[]
- {
- (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),
- };
+ var looks = Trio;
for (int i = 0; i < looks.Length; i++)
{
var (type, hat, pose, faded, offset, heading) = looks[i];
- var p = Ground(map, centre + new Vector3(offset.x, 0, offset.y) * TrioSpread * hex);
+ var p = Stand(map, centre + new Vector3(offset.x, 0, offset.y) * TrioSpread * hex);
Piece(root.transform, $"Rifleman{i}", type, () => Built(UnitModels.Rifleman(hat, pose, faded, $"Rifleman1948-{i}")),
paint, p, Quaternion.Euler(0, heading, 0), FigureScale);
}
@@ -146,7 +162,7 @@ namespace Statecraft.Game.Map.Units
static GameObject Piece(Transform parent, string name, string type, Func<Mesh> codeBuilt, Material paint, Vector3 position,
Quaternion rotation, float scale) => Piece(parent, name, type, codeBuilt, paint, position, rotation, scale, out _);
- static GameObject Piece(Transform parent, string name, string type, Func<Mesh> codeBuilt, Material paint, Vector3 position,
+ internal static GameObject Piece(Transform parent, string name, string type, Func<Mesh> codeBuilt, Material paint, Vector3 position,
Quaternion rotation, float scale, out bool authored)
{
var prefab = AuthoredModel(type);
@@ -159,7 +175,7 @@ namespace Statecraft.Game.Map.Units
return go;
}
- static GameObject Piece(Transform parent, string name, Mesh mesh, Material mat, Vector3 position, Quaternion rotation, float scale)
+ internal static GameObject Piece(Transform parent, string name, Mesh mesh, Material mat, Vector3 position, Quaternion rotation, float scale)
{
var go = new GameObject(name);
go.transform.SetParent(parent, false);
@@ -192,6 +208,57 @@ namespace Statecraft.Game.Map.Units
return p;
}
+ /// <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;
+
+ /// <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)
+ {
+ 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;
+ }
+
+ /// <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)
+ {
+ 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);
+ }
+
+ /// <summary>A figure on a slope stands on a base, as a painted miniature does: a short dark grey-brown disc (the palette deck shade) 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.Deck, 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)
+ {
+ 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
+ }
+
/// <summary>The highest ground under the loop (sampled every 5 degrees and at its centre), so the aircraft never
/// dips into a ridge; its altitude is constant, so its shadow keeps one offset.</summary>
public static float LoopFloor(MapScene map, Vector3 centre, float radius)
@@ -209,7 +276,7 @@ namespace Statecraft.Game.Map.Units
/// unlit ivory and depth offset (the promo's white ring). Each vertex sits <see cref="RingClearanceM"/> above the
/// highest ground sampled across the band at its own angle and halfway to each neighbour, so a ridge between two
/// vertices cannot rise through the straight edge between them (MapBuilder.DrapedRing's rule).</summary>
- static void Ring(MapScene map, MapRuntimeAssets assets, Material ringTemplate, Transform parent, Vector3 centre, float radius)
+ internal static GameObject Ring(MapScene map, MapRuntimeAssets assets, Material ringTemplate, Transform parent, Vector3 centre, float radius)
{
const int n = 96;
var verts = new List<Vector3>(2 * n); var tris = new List<int>(6 * n);
@@ -240,6 +307,7 @@ namespace Statecraft.Game.Map.Units
var r = go.AddComponent<MeshRenderer>();
r.sharedMaterial = ringTemplate;
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
+ return go;
}
}
}
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 60b7ef947..d8529cb92 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -40,6 +40,9 @@ namespace Statecraft.Game.UI
/// <summary>Everything Begin created that must be undone, disposed in reverse order.</summary>
readonly List<IDisposable> owned = new List<IDisposable>();
MinimapPresenter? minimap;
+ Statecraft.Game.Map.Units.UnitLayer? units;
+ /// <summary>The units in play (null before Begin).</summary>
+ internal Statecraft.Game.Map.Units.UnitLayer? Units => units;
MapLabelsPresenter? labels;
ScreenNav? nav;
CameraRig? rig;
@@ -157,7 +160,24 @@ namespace Statecraft.Game.UI
onDate();
bridge.Changed += onDate;
owned.Add(new Undo(() => bridge.Changed -= onDate));
- var info = Own(new InfoPanelPresenter(root, bridge, text, names, regions));
+ // The units in play (docs/units.md): drawn from the state and the sourced unit data, before the info panel so
+ // the layer has followed a change before the panel renders the selected unit's card.
+ var unitLayer = units = Statecraft.Game.Map.Units.UnitLayer.Create(map,
+ Statecraft.Game.Map.Units.UnitData.ReadOrNone(inputs.Map.UnitsYaml, Debug.LogWarning), inputs.Content.Hexes,
+ Statecraft.Game.Map.Units.UnitShowcase.StillRequested(Application.absoluteURL, Environment.GetCommandLineArgs(),
+ Application.platform == RuntimePlatform.WebGLPlayer));
+ // A screenshot run (?shot) leaves the units out unless it also asks for them (&units), so the art log's plain
+ // checkpoints stay comparable across tracks (review I5; tools/art_checkpoint.sh --units).
+ if (Statecraft.Game.Map.Units.UnitLayer.HiddenInCaptures(Application.absoluteURL, Environment.GetCommandLineArgs(),
+ Application.platform == RuntimePlatform.WebGLPlayer))
+ VisualToggles.Set(Statecraft.Game.Map.Units.UnitLayer.ToggleName, false);
+ Action showUnits = () => unitLayer.Show(bridge.Content, bridge.State);
+ bridge.Changed += showUnits;
+ owned.Add(new Undo(() => bridge.Changed -= showUnits));
+ showUnits();
+ var info = Own(new InfoPanelPresenter(root, bridge, text, names, nav: nav,
+ selectedUnit: () => unitLayer.Selected is string id ? unitLayer.Tokens.First(p => p.Token.Unit.Id == id) : (Statecraft.Game.Map.Units.PlacedToken?)null,
+ regions: regions));
// A smoke session never touches the player's save: no autosave, and no New Game (which deletes the autosave).
// Leaving New Game out is safer than handing it a throwaway store: no file is ever deleted, no path has to be
// right on every platform, and the scripted run never presses it.
@@ -178,7 +198,7 @@ namespace Statecraft.Game.UI
cameraController.GroundTop = CameraController.GroundTopOf(terrain);
pointer.Map = map;
pointer.IsOverUi = overUi;
- Action<int, int> onHex = info.Show;
+ Action<int, int> onHex = (q, r) => OnHexClicked(map, unitLayer, info, q, r);
pointer.HexClicked += onHex;
var camRig = rig = cameraController.GetComponent<CameraRig>();
Own(new TopBarInset(root, camRig)); // the map is framed below the top bar
@@ -219,7 +239,7 @@ namespace Statecraft.Game.UI
}
if (Application.isPlaying && PixelErrorProfile.Requested()) StartCoroutine(PixelErrorProfile.Run(map.Terrain));
// The unit art slice at gameplay03 (a showcase, never in normal play; war mode's units are issue #104). Before the
- // instruments, so the frame profile lists its "units" toggle (the profile reads the toggles when it starts).
+ // instruments, so the frame profile lists its "unitshowcase" toggle (the profile reads the toggles when it starts).
if (Application.isPlaying && Statecraft.Game.Map.Units.UnitShowcase.Requested())
Statecraft.Game.Map.Units.UnitShowcase.Spawn(map, Statecraft.Game.Map.Units.UnitShowcase.StillRequested(
Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer));
@@ -233,13 +253,31 @@ namespace Statecraft.Game.UI
T Own<T>(T d) where T : IDisposable { owned.Add(d); return d; }
+ /// <summary>A map click: on a unit's hex it selects the unit (the ring and its card; the hex outline is cleared, so
+ /// the unit has the promo's one highlight); a second click on it, or a click anywhere else, shows the hex (so a token
+ /// never hides the hex's map actions).</summary>
+ internal static void OnHexClicked(MapScene map, Statecraft.Game.Map.Units.UnitLayer units, InfoPanelPresenter info, int q, int r)
+ {
+ if (info.Covered)
+ {
+ // A screen covers the panel: the click moves neither the ring nor the card (#210), and MapPointer's outline
+ // goes back to the hex the panel shows (or away, while it shows a unit).
+ if (info.Selected is (int sq, int sr) && !info.ShowsUnit) map.Select(sq, sr); else map.ClearSelection();
+ return;
+ }
+ var id = units.UnitToSelectAt(q, r);
+ units.Select(id);
+ if (id != null) { map.ClearSelection(); info.ShowUnit(); }
+ else info.Show(q, r);
+ }
+
/// <summary>Disposes every presenter, the autosave and the camera/pointer hooks (newest first). Safe to call twice.</summary>
void Shutdown()
{
StopAllCoroutines();
for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
owned.Clear();
- minimap = null; labels = null; nav = null; rig = null; drawn = null; logCamera = false;
+ minimap = null; labels = null; nav = null; rig = null; drawn = null; units = null; logCamera = false;
// A ?profile run cut short (a stopped coroutine never reaches its restore line) must not leave the terrain at the
// profile's pixel error (Task 24 review M1). Nothing else changes it, so restoring is always right.
if (map != null && map.Terrain != null) map.Terrain.heightmapPixelError = MapBuilder.TerrainPixelError;
diff --git a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs
index 3aa3f7880..2c8af1247 100644
--- a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs
+++ b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using Statecraft.Game.Map;
+using Statecraft.Game.Map.Units;
using Statecraft.Sim;
using UnityEngine.UIElements;
@@ -9,21 +10,28 @@ namespace Statecraft.Game.UI
{
/// <summary>The info panel (bottom-left): the selected hex's land, height and the settlements it owns, what the player
/// built there, and the two map actions (transit camp, housing project) with the reason when one is not possible
- /// (MapActions.Check). Tile yields are deliberately not shown (owner decision, M3 rulings 2).</summary>
+ /// (MapActions.Check). Tile yields are deliberately not shown (owner decision, M3 rulings 2). A selected unit
+ /// (<see cref="ShowUnit"/>) shows its read-only card instead (<see cref="UnitCard"/>): no orders, only a button to the
+ /// Defence screen (owner ruling, 2026-10-11).</summary>
public sealed class InfoPanelPresenter : System.IDisposable
{
readonly VisualElement panel; readonly SimBridge bridge; readonly UiText text;
- readonly Button campButton, housingButton; readonly System.Action onCamp, onHousing;
+ readonly Button campButton, housingButton, defenceButton; readonly System.Action onCamp, onHousing, onDefence;
+ readonly System.Func<PlacedToken?> selectedUnit;
+ bool unitMode;
readonly Label title, subtitle, region, settlements, placement, reason;
readonly UiIcon thumb;
readonly IReadOnlyDictionary<string, string> settlementNames;
readonly MapRegions? regions;
- /// <summary><paramref name="regions"/>: what the map outlines (the 1948 sub-districts and the 1949 armistice lines in
- /// force); the panel names the selected hex's sub-district or armistice zone, and any armistice line through it, with
- /// its agreement (null: no region line).</summary>
+ /// <param name="nav">Opens the Defence screen from a unit's card (null: the button does nothing).</param>
+ /// <param name="selectedUnit">The selected unit's token now (null: none), read at every render so the card follows
+ /// the state.</param>
+ /// <param name="regions">What the map outlines (the 1948 sub-districts and the 1949 armistice lines in force); the
+ /// panel names the selected hex's sub-district or armistice zone, and any armistice line through it, with its
+ /// agreement (null: no region line).</param>
public InfoPanelPresenter(VisualElement root, SimBridge bridge, UiText text, IReadOnlyDictionary<string, string> settlementNames,
- MapRegions? regions = null)
+ ScreenNav? nav = null, System.Func<PlacedToken?>? selectedUnit = null, MapRegions? regions = null)
{
panel = root.Q<VisualElement>("info-panel"); this.bridge = bridge; this.text = text;
this.settlementNames = settlementNames; this.regions = regions;
@@ -33,23 +41,48 @@ namespace Statecraft.Game.UI
campButton = panel.Q<Button>("build-camp"); housingButton = panel.Q<Button>("build-housing");
onCamp = () => Build(MapActions.TransitCamp); onHousing = () => Build(MapActions.Housing);
campButton.clicked += onCamp; housingButton.clicked += onHousing;
+ defenceButton = panel.Q<Button>("info-defence");
+ this.selectedUnit = selectedUnit ?? (() => null);
+ onDefence = () => nav?.Open("defence");
+ defenceButton.clicked += onDefence;
+ defenceButton.text = text["unit.defence"];
bridge.Changed += Render;
Render();
}
/// <summary>Unsubscribes from the bridge and the buttons (the owner calls this when disabled).</summary>
- public void Dispose() { bridge.Changed -= Render; campButton.clicked -= onCamp; housingButton.clicked -= onHousing; }
+ public void Dispose() { bridge.Changed -= Render; campButton.clicked -= onCamp; housingButton.clicked -= onHousing; defenceButton.clicked -= onDefence; }
public (int q, int r)? Selected { get; private set; }
- /// <summary>Shows the hex; ignored while a screen covers the panel (a wide screen, or any screen in the two-row HUD),
- /// so a map click cannot change a panel the player cannot see.</summary>
+ /// <summary>True while the panel shows a unit's card.</summary>
+ public bool ShowsUnit => unitMode && selectedUnit() != null;
+
+ /// <summary>True while a screen covers the panel (a wide screen, or any screen in the two-row HUD): a map click
+ /// then changes neither the hex nor the unit shown (#210; units-in-play merge note).</summary>
+ public bool Covered
+ {
+ get
+ {
+ var hud = panel.parent;
+ return hud != null && (hud.ClassListContains(ScreenNav.WideOpenClass)
+ || (hud.ClassListContains(ScreenNav.ScreenOpenClass) && hud.ClassListContains(HudPresenter.TwoRowClass)));
+ }
+ }
+
+ /// <summary>Shows the hex; ignored while a screen covers the panel, so a map click cannot change a panel the player
+ /// cannot see.</summary>
public void Show(int q, int r)
{
- var hud = panel.parent;
- if (hud != null && (hud.ClassListContains(ScreenNav.WideOpenClass)
- || (hud.ClassListContains(ScreenNav.ScreenOpenClass) && hud.ClassListContains(HudPresenter.TwoRowClass)))) return; // covered (#210)
- Selected = (q, r); Render();
+ if (Covered) return; // covered (#210)
+ unitMode = false; Selected = (q, r); Render();
+ }
+
+ /// <summary>Shows the selected unit's card (the unit comes from the selectedUnit callback); ignored while covered.</summary>
+ public void ShowUnit()
+ {
+ if (Covered) return;
+ unitMode = true; Selected = null; Render();
}
void Build(string action)
@@ -87,6 +120,19 @@ namespace Statecraft.Game.UI
{
var c = bridge.Content; var s = bridge.State;
var camp = campButton; var housing = housingButton;
+ var unit = unitMode ? selectedUnit() : null;
+ defenceButton.style.display = unit != null ? DisplayStyle.Flex : DisplayStyle.None;
+ if (unit != null)
+ {
+ var card = UnitCard.For(unit.Value, s, text);
+ panel.EnableInClassList("info-empty", false);
+ title.text = card.Title; subtitle.text = card.Subtitle; settlements.text = card.Body;
+ region.text = ""; // a unit's card names no sub-district (the last hex's would stay under it)
+ placement.text = card.Footer; reason.text = card.Note;
+ camp.style.display = DisplayStyle.None; housing.style.display = DisplayStyle.None;
+ ShowThumb(null);
+ return;
+ }
panel.EnableInClassList("info-empty", Selected == null);
if (Selected == null)
{
diff --git a/unity/Assets/Scripts/UI/UnitCard.cs b/unity/Assets/Scripts/UI/UnitCard.cs
new file mode 100644
index 000000000..ba8baa44c
--- /dev/null
+++ b/unity/Assets/Scripts/UI/UnitCard.cs
@@ -0,0 +1,44 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Game.Map.Units;
+using Statecraft.Sim;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>The info panel's text for a selected unit (read only; no orders: the panel links to the Defence screen):
+ /// its name, number and service; where it stands, and since when only from a sourced start (the anchor's `since`,
+ /// never the game's first day: review I1); its formation and first commander where sourced; the sector in the
+ /// source's words; the national values its token reflects (the reserve call-up sets its figures, the security level
+ /// whether its aircraft fly); and its sources, with a draft note that says "Wikipedia only" when the position's own
+ /// sources are (review M8).</summary>
+ public sealed class UnitCard
+ {
+ public string Title = "", Subtitle = "", Body = "", Footer = "", Note = "";
+
+ public static UnitCard For(PlacedToken placed, GameState state, UiText text)
+ {
+ var t = placed.Token; var u = t.Unit; var a = t.Anchor;
+ var lines = new List<string>();
+ if (u.Service == UnitData.Air)
+ {
+ var aircraft = text[t.ArtType == UnitShowcase.SpitfireType ? "unit.aircraft.spitfire" : "unit.aircraft.s199"];
+ lines.Add(text.Format(t.Flying ? "unit.flying" : "unit.parked", aircraft));
+ }
+ lines.Add(string.IsNullOrWhiteSpace(a.Since) ? text.Format("unit.position_plain", a.Place) : text.Format("unit.position", a.Place, a.Since!));
+ if (!string.IsNullOrEmpty(u.Formed)) lines.Add(text.Format("unit.formed", u.Formed!));
+ if (!string.IsNullOrEmpty(u.FirstCommander)) lines.Add(text.Format("unit.commander", u.FirstCommander!));
+ lines.Add(u.Sector);
+ var hosts = u.AllSources().Select(s => new Uri(s.Url).Host).Distinct(StringComparer.Ordinal).OrderBy(h => h, StringComparer.Ordinal);
+ return new UnitCard
+ {
+ Title = u.Name,
+ Subtitle = text.Format("unit.subtitle", u.Number, text["unit.service." + u.Service]),
+ Body = string.Join("\n", lines),
+ Footer = text.Format("unit.national", PlayerText.Percent(state.Mobilization), state.Rung) + "\n" + text.Format("unit.sources", string.Join(", ", hosts)),
+ Note = UnitData.IsWikipediaOnly(a.Sources) ? text["unit.draft_wikipedia"] : text["unit.draft"],
+ };
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/UnitCard.cs.meta b/unity/Assets/Scripts/UI/UnitCard.cs.meta
new file mode 100644
index 000000000..cbbc1e28b
--- /dev/null
+++ b/unity/Assets/Scripts/UI/UnitCard.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 5f7215cd0abac4fe89538a83bcf632dc
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/RouteTests.cs b/unity/Assets/Tests/EditMode/RouteTests.cs
index 6586f4607..d92e344f2 100644
--- a/unity/Assets/Tests/EditMode/RouteTests.cs
+++ b/unity/Assets/Tests/EditMode/RouteTests.cs
@@ -291,7 +291,8 @@ public class RouteTests
Assert.IsNotNull(map.KitStats, "Map.unity builds the kits");
var routes = RoutePaths.Parse(CommittedYaml, Bounds);
var corridors = RouteLayer.Corridors(map.Frame, routes);
- Assert.AreEqual(corridors.Sum(c => c.line.Count - 1), map.KitStats.CorridorSegments, "the map hands every route to the kits");
+ // Plus one segment per unit clearing (a unit token in a town: docs/units.md, "Placement").
+ Assert.AreEqual(corridors.Sum(c => c.line.Count - 1) + map.UnitClearings.Count, map.KitStats.CorridorSegments, "the map hands every route to the kits");
Assert.IsTrue(routes.Any(r => r.Id == "burma_road"), "the dated Burma Road keeps its corridor from the start");
// The same placement the map runs, with the same corridors.
diff --git a/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs b/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs
index 91fe2a749..3106f1e0c 100644
--- a/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs
+++ b/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs
@@ -15,6 +15,7 @@ public class UnitShowcaseTests
UnitModels.Rifleman(UnitModels.Headgear.SteelHelmet, UnitModels.RiflePose.Grounded, true, "b"),
UnitModels.Rifleman(UnitModels.Headgear.WoolCap, UnitModels.RiflePose.Slung, false, "c"),
UnitModels.Spitfire("s"), UnitModels.SpitfirePropeller("p"), UnitModels.Corvette("k"),
+ UnitModels.AviaS199("v"), UnitModels.S199Propeller("q"),
};
[Test]
@@ -174,9 +175,9 @@ public class UnitShowcaseTests
Assert.IsNotNull(root.transform.Find("Spitfire1948/Propeller"));
var plane = root.GetComponentInChildren<ShowcaseFlight>();
Assert.AreEqual(UnitShowcase.StillPhase, plane.StillPhase);
- // Each figure stands on the ground under it.
+ // Each figure stands on the highest ground under its boots (UnitShowcase.Stand).
foreach (var f in root.GetComponentsInChildren<MeshFilter>().Where(f => f.name.StartsWith("Rifleman")))
- Assert.AreEqual(UnitShowcase.Ground(map, f.transform.position).y, f.transform.position.y, 1f, f.name);
+ Assert.AreEqual(UnitShowcase.Stand(map, f.transform.position).y, 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.cs
new file mode 100644
index 000000000..34a334c71
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs
@@ -0,0 +1,653 @@
+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.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.UIElements;
+
+/// <summary>The units in play (docs/units.md, "Units in play"): the sourced map-only data, the roster read from the
+/// sim's state, the placement clear of the towns and routes, the layer, the badge, the selection and its read-only card.</summary>
+public class UnitsInPlayTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static string CommittedYaml => File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName));
+ static List<UnitEntry> Units => UnitData.Parse(CommittedYaml);
+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static readonly DateTime LastArmistice = new DateTime(1949, 7, 20);
+
+ static IEnumerable<string> Ids(IEnumerable<UnitToken> tokens) => tokens.Select(t => t.Unit.Id);
+
+ static string Sha256(string text)
+ {
+ using var sha = System.Security.Cryptography.SHA256.Create();
+ return string.Concat(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(text)).Select(b => b.ToString("x2")));
+ }
+
+ /// <summary>A copy of the new-game state at <paramref name="date"/> with the given security level and call-up (a
+ /// fixture for the presentation; the sim never sees it).</summary>
+ static GameState StateAt(DateTime date, int rung, double mobilization)
+ {
+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();
+ s.Date = date; s.Rung = rung; s.Mobilization = mobilization;
+ return s;
+ }
+
+ // ---- The data -----------------------------------------------------------------------------------------------
+
+ /// <summary>Map-only: the sim's content hash is the same with and without the unit file (so it cannot move the
+ /// goldens), and the WebGL manifest ships it (the player reads it).</summary>
+ [Test]
+ public void TheUnitFileDoesNotMoveTheContentHash()
+ {
+ var copy = Path.Combine(Path.GetTempPath(), "statecraft-nounits-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ Statecraft.Game.Boot.ContentManifest.Copy(Paths.Content, copy);
+ var file = Path.Combine(copy, "map", UnitData.DefaultFileName);
+ Assert.IsTrue(File.Exists(file), "the manifest copies the unit file");
+ File.Delete(file);
+ Assert.AreEqual(ContentLoader.Load(Paths.Content).Hash, ContentLoader.Load(copy).Hash);
+ CollectionAssert.Contains(Statecraft.Game.Boot.ContentManifest.Collect(Paths.Content), "map/" + UnitData.DefaultFileName);
+ }
+ finally { if (Directory.Exists(copy)) Directory.Delete(copy, true); }
+ }
+
+ /// <summary>Review C1: every window ends for a reason. A source-based end cites its source and says which; any other
+ /// end is the armistice of the anchor's front (the owner's "after the armistices, only what a source says continued").
+ /// No window runs past its unit's sourced disbandment.</summary>
+ [Test]
+ public void EveryRowIsSourcedDatedAndOnTheMap()
+ {
+ var units = Units;
+ Assert.AreEqual(12, units.Count(u => u.Service == UnitData.Army), "the twelve brigades of 1948");
+ Assert.AreEqual(1, units.Count(u => u.Service == UnitData.Air));
+ Assert.AreEqual(2, units.Count(u => u.Service == UnitData.Navy));
+ CollectionAssert.AreEquivalent(new[] { "carmeli", "alexandroni", "brigade_8", "oded" }, units.Where(u => u.Hidden != null).Select(u => u.Id),
+ "owner ruling: the four brigades with no sourced position are listed and hidden");
+ double lon0 = C.Hexes.Min(h => h.Lon), lon1 = C.Hexes.Max(h => h.Lon), lat0 = C.Hexes.Min(h => h.Lat), lat1 = C.Hexes.Max(h => h.Lat);
+ foreach (var u in units)
+ {
+ Assert.AreEqual("draft", u.Status, u.Id);
+ Assert.AreEqual(UnitData.IsWikipediaOnly(u), u.WikipediaOnly, $"{u.Id}: wikipedia_only must say whether every source is Wikipedia or Wikidata");
+ foreach (var s in u.AllSources())
+ Assert.LessOrEqual(UnitData.Day(s.Checked), DateTime.Today, $"{u.Id}: {s.Url} checked in the future");
+ foreach (var a in u.Anchors)
+ {
+ var at = $"{u.Id} {a.Place}";
+ Assert.That(a.Lon, Is.InRange(lon0, lon1), at);
+ Assert.That(a.Lat, Is.InRange(lat0, lat1), at);
+ Assert.GreaterOrEqual(UnitData.Day(a.From), C.Rules.Start, at);
+ Assert.IsNotEmpty(a.Sources, at);
+ CollectionAssert.Contains(new[] { UnitData.EndBySource, UnitData.EndByFrontArmistice }, a.EndBasis, $"{at}: every window has an end_basis");
+ if (a.EndBasis == UnitData.EndBySource)
+ Assert.IsFalse(string.IsNullOrWhiteSpace(a.EndNote), $"{at}: a source-based end says which source");
+ else
+ Assert.AreEqual(UnitData.FrontArmistice[a.Front], UnitData.Day(a.To), $"{at}: ends on its front's armistice");
+ Assert.LessOrEqual(UnitData.Day(a.To), LastArmistice, at);
+ if (u.Disbanded != null) Assert.LessOrEqual(UnitData.Day(a.To), UnitData.Day(u.Disbanded.Date), $"{at}: after its disbandment");
+ Assert.AreNotEqual("15 May 1948", a.Since, $"{at}: the game's first day is not a sourced arrival");
+ }
+ for (int i = 1; i < u.Anchors.Count; i++)
+ Assert.LessOrEqual(UnitData.Day(u.Anchors[i - 1].To), UnitData.Day(u.Anchors[i].From), $"{u.Id}: anchor windows in order, not overlapping");
+ }
+ Assert.AreEqual(new DateTime(1949, 2, 24), UnitData.FrontArmistice["egypt"]);
+ Assert.AreEqual(new DateTime(1949, 3, 23), UnitData.FrontArmistice["lebanon"]);
+ Assert.AreEqual(new DateTime(1949, 4, 3), UnitData.FrontArmistice["jordan"]);
+ Assert.AreEqual(LastArmistice, UnitData.FrontArmistice["syria"]);
+ }
+
+ 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: [";
+
+ [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(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")]
+ [TestCase(Unit + "{place: P, lon: 34.8, lat: 32.0, from: '1948-5-15', to: '1948-06-01', end_basis: source, end_note: n, sources: [{url: 'https://x.org', checked: '2026-10-11'}]}]}", "from/to")]
+ [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: [{url: 'https://x.org'}]}]}", "checked")]
+ [TestCase(Unit + "{place: P, lon: 34.8, lat: 32.0, from: '1948-05-15', to: '1948-06-01', sources: [{url: 'https://x.org', checked: '2026-10-11'}]}]}", "needs end_basis")]
+ [TestCase(Unit + "{place: P, lon: 34.8, lat: 32.0, from: '1948-05-15', to: ~, end_basis: source, end_note: n, sources: [{url: 'https://x.org', checked: '2026-10-11'}]}]}", "to is empty")]
+ [TestCase(Unit + "{place: P, lon: 34.8, lat: 32.0, from: '1948-05-15', to: '1948-06-01', end_basis: source, end_note: n, toward: {place: T, lon: 34.8, lat: 32.0, note: n, sources: []}, sources: [{url: 'https://x.org', checked: '2026-10-11'}]}]}", "toward needs a note and a source")]
+ [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")]
+ public void BadUnitFilesNameTheFileAndTheProblem(string yaml, string expected)
+ {
+ var e = Assert.Throws<InvalidDataException>(() => UnitData.Parse(yaml, "u.yaml"));
+ StringAssert.StartsWith("u.yaml:", e.Message);
+ StringAssert.Contains(expected, e.Message);
+ }
+
+ [Test]
+ public void AMissingOrBrokenFileDrawsNoUnitsAndWarns()
+ {
+ var warnings = new List<string>();
+ Assert.IsEmpty(UnitData.ReadOrNone("", warnings.Add));
+ Assert.IsEmpty(UnitData.ReadOrNone("units: [", warnings.Add));
+ Assert.AreEqual(2, warnings.Count);
+ }
+
+ // ---- The roster ----------------------------------------------------------------------------------------------
+
+ [Test]
+ public void ANewGameShowsTheSourcedUnitsOfMay1948()
+ {
+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);
+ var tokens = UnitRoster.Build(Units, C, s);
+ CollectionAssert.AreEqual(new[] { "golani", "kiryati", "givati", "etzioni", "harel", "negev", "ins_haganah", "ins_wedgwood" }, Ids(tokens),
+ "on 15 May 1948: no aircraft yet (101 Squadron from 20 May), the 7th Brigade from 24 May, Yiftach only in Operation Dani");
+ Assert.AreEqual(5, s.Rung);
+ Assert.IsTrue(tokens.Where(t => t.Unit.Service == UnitData.Army).All(t => t.Figures == 3), "full war: call-up at least 0.8");
+ Assert.IsTrue(tokens.Where(t => t.Unit.Service == UnitData.Navy).All(t => t.ArtType == UnitShowcase.CorvetteType && t.Anchor.Place == "Haifa harbour"));
+ CollectionAssert.AreEqual(new[] { UnitData.WoolCap, UnitData.SteelHelmet, UnitData.WoolCap }, tokens.Single(t => t.Unit.Id == "negev").Headgear,
+ "the Negev Brigade's headgear is sourced to its 1948 photographs");
+ CollectionAssert.AreEqual(UnitData.DefaultHeadgear, tokens.Single(t => t.Unit.Id == "givati").Headgear, "no source: the uniform default");
+ }
+
+ [TestCase(0.80, 3)]
+ [TestCase(0.40, 3)]
+ [TestCase(0.39, 2)]
+ [TestCase(0.15, 2)]
+ [TestCase(0.10, 1)]
+ [TestCase(0.02, 1)]
+ public void TheFiguresFollowTheCallUp(double mobilization, int figures)
+ {
+ var tokens = UnitRoster.Build(Units, C.Rules, new DateTime(1948, 6, 5), 5, mobilization);
+ Assert.IsTrue(tokens.Where(t => t.Unit.Service == UnitData.Army).All(t => t.Figures == figures && t.Headgear.Count == figures));
+ Assert.IsTrue(tokens.Where(t => t.Unit.Service != UnitData.Army).All(t => t.Figures == 0));
+ }
+
+ /// <summary>Review I3 and I4: the bases where two sources agree (no base from 30 May to mid-June, where they do not),
+ /// and the Spitfire from its first sourced sortie, 15 October 1948.</summary>
+ [Test]
+ public void TheSquadronFliesInWarAndItsAircraftAndBaseFollowTheSources()
+ {
+ UnitToken Squadron(DateTime d, int rung) => UnitRoster.Build(Units, C.Rules, d, rung, 0.8).SingleOrDefault(t => t.Unit.Id == "squadron_101");
+ var may = Squadron(new DateTime(1948, 5, 22), 5);
+ Assert.AreEqual((UnitShowcase.S199Type, "Ekron (RAF Aqir)", true), (may.ArtType, may.Anchor.Place, may.Flying));
+ Assert.IsNull(Squadron(new DateTime(1948, 6, 5), 5), "the sources disagree on its base from 30 May to mid-June");
+ Assert.IsTrue(Squadron(new DateTime(1948, 7, 1), 4).Flying);
+ Assert.IsFalse(Squadron(new DateTime(1948, 7, 1), 3).Flying, "below security level 4 it stands parked");
+ Assert.AreEqual("Herzliya strip", Squadron(new DateTime(1948, 7, 1), 5).Anchor.Place);
+ Assert.AreEqual(UnitShowcase.S199Type, Squadron(new DateTime(1948, 10, 14), 5).ArtType);
+ var oct = Squadron(new DateTime(1948, 10, 16), 5);
+ Assert.AreEqual((UnitShowcase.SpitfireType, "Herzliya strip"), (oct.ArtType, oct.Anchor.Place),
+ "the Spitfire from 15 October 1948; Modi Alon landed at Herzliya on 16 October");
+ Assert.AreEqual("Hatzor", Squadron(new DateTime(1948, 11, 21), 5).Anchor.Place, "Hatzor from 21 November 1948 (Eduard p. 54, he.wiki)");
+ Assert.IsNull(Squadron(new DateTime(1949, 6, 1), 2), "it left Hatzor in June 1949");
+ }
+
+ [Test]
+ public void AfterTheArmisticesOnlyWhatASourceSaysContinuedShows()
+ {
+ CollectionAssert.AreEqual(new[] { "kiryati", "etzioni", "squadron_101" }, Ids(UnitRoster.Build(Units, C.Rules, new DateTime(1949, 2, 24), 4, 0.4)),
+ "the southern brigades and the ships end on the Egypt armistice");
+ CollectionAssert.AreEqual(new[] { "squadron_101" }, Ids(UnitRoster.Build(Units, C.Rules, new DateTime(1949, 4, 3), 2, 0.05)),
+ "the central and Jerusalem brigades end on the Jordan armistice");
+ Assert.IsEmpty(UnitRoster.Build(Units, C.Rules, LastArmistice, 2, 0.05));
+ Assert.IsEmpty(UnitRoster.Build(Units, C.Rules, new DateTime(1951, 1, 1), 1, 0.02));
+ }
+
+ [Test]
+ public void TheRosterNeverChangesTheStateAndTheGoldenHolds()
+ {
+ var units = Units;
+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);
+ var digests = new List<string>();
+ for (int turn = 0; turn < 1000 && s.Date < GoldenRun.Until1950 && s.GameOver == null; turn++)
+ {
+ var before = s.Hash();
+ var tokens = UnitRoster.Build(units, C, s);
+ Assert.AreEqual(before, s.Hash(), $"turn {turn}: building the roster changed the state");
+ digests.Add($"{s.Date:yyyy-MM-dd} {string.Join(",", tokens)}");
+ s = Simulation.Step(C, s, HistoricalAI.Commands(C, s)).State;
+ }
+ Assert.AreEqual(GoldenRun.Hash1950, s.Hash(), "the golden does not move");
+ // The presentation golden: the roster of every turn of the historical playthrough, pinned. A deliberate change to
+ // the unit data or the roster rules updates it (and says why in the commit).
+ var all = string.Join("\n", digests);
+ Debug.Log("UNITS roster golden " + Sha256(all) + "\n" + all);
+ Assert.AreEqual(RosterGolden1950, Sha256(all), "the roster of the historical playthrough changed (see the log for the turns)");
+ }
+
+ /// <summary>Review M4: the historical run's turns are monthly or quarterly in places, so a weekly sweep of the war (at
+ /// full war and full call-up) pins every window too.</summary>
+ [Test]
+ public void AWeeklySweepOfTheWarIsPinned()
+ {
+ var units = Units;
+ var lines = new List<string>();
+ for (var d = C.Rules.Start; d < LastArmistice; d = d.AddDays(7))
+ lines.Add($"{d:yyyy-MM-dd} {string.Join(",", UnitRoster.Build(units, C.Rules, d, 5, 0.8))}");
+ var all = string.Join("\n", lines);
+ Debug.Log("UNITS weekly golden " + Sha256(all) + "\n" + all);
+ Assert.AreEqual(WeeklyGolden, Sha256(all));
+ }
+
+ const string RosterGolden1950 = "ef4544705105a98758dc843120b6e3493c52419d1d4afad28e0b4a3b6e87e01c";
+ const string WeeklyGolden = "2d111a792224b0abd544b2fdfd7469c8f20047cefc5492ea272b79134d6d3c06";
+
+ // ---- Placement, the layer and the card (a built map) ---------------------------------------------------------
+
+ static MapScene BuildMap()
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
+ var map = new GameObject("MapScene").AddComponent<MapScene>();
+ map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("BorderLand"));
+ // The towns' footprints as the game sizes them (its kits read the 1945 populations), whatever an earlier test left.
+ 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");
+
+ /// <summary>Review I2 and M9: every anchor gets one spot, from the data alone, within one hex step of its sourced
+ /// place, clear of the towns' footprints and, for the figures, of the railways and roads by the full clearance; no two
+ /// anchors whose windows overlap share a hex. Each spot and its distance is logged.</summary>
+ [Test]
+ public void EveryAnchorStandsWithinOneHexClearOfTheTownsAndTheRoutes()
+ {
+ var map = BuildMap();
+ try
+ {
+ Assert.IsNotEmpty(map.SettlementFootprints);
+ Assert.IsNotEmpty(map.RouteCorridors);
+ var units = Units;
+ var layer = UnitLayer.Create(map, units, C.Hexes, still: true);
+ float hex = map.Hexes.hex_size_km * 1000f;
+ var hexAt = C.Hexes.ToDictionary(h => (h.Q, h.R));
+ var anchors = units.Where(u => u.Hidden == null).SelectMany(u => u.Anchors.Select(a => (u, a))).ToList();
+ var log = new List<string>();
+ foreach (var (u, a) in anchors)
+ {
+ var at = $"{u.Id} {a.Place}";
+ Assert.IsTrue(layer.Spots.TryGetValue(a, out var s), $"{at}: no spot");
+ var w = map.Frame.ToWorld(a.Lon, a.Lat, 0);
+ var c = new Vector2((float)s.X, (float)s.Z);
+ float km = (c - new Vector2(w.x, w.z)).magnitude / 1000f;
+ var (slon, slat) = map.Frame.ToLonLat(new Vector3((float)s.X, 0, (float)s.Z));
+ log.Add(FormattableString.Invariant($"{at} -> {s} {km:0.0} km at {slon:0.000} E {slat:0.000} N"));
+ Assert.LessOrEqual(km * 1000f, Mathf.Sqrt(3f) * hex + 1f, $"{at}: more than one hex step from its anchor");
+ Assert.AreEqual(u.Service != UnitData.Navy, hexAt[(s.Q, s.R)].Land, $"{at}: land for the army and the air force, sea for ships");
+ if (u.Service == UnitData.Navy) continue;
+ if (s.InTown)
+ {
+ Assert.IsTrue(s.Compact, at);
+ Assert.IsTrue(map.UnitClearings.Any(x => x.centre == c), $"{at}: a token in a town has the kits' clearing, so it stands in no building");
+ }
+ else
+ {
+ float disc = UnitShowcase.RingRadius * hex * (s.Compact ? UnitGround.CompactScale : 1f);
+ foreach (var (fc, fr) in map.SettlementFootprints)
+ Assert.GreaterOrEqual((fc - c).magnitude, fr * UnitGround.FootprintMargin + disc, $"{at}: the ring reaches a town's buildings");
+ }
+ var points = u.Service == UnitData.Army ? layer.PlacementGround.FigurePoints(c, s.Compact) : new[] { c };
+ foreach (var f in points)
+ foreach (var (line, half) in map.RouteCorridors)
+ for (int i = 0; i + 1 < line.Count; i++)
+ Assert.GreaterOrEqual(UnitGround.DistanceToSegment(f, line[i], line[i + 1]), half + UnitGround.FigureClearanceM, $"{at}: a figure stands on a railway or road");
+ }
+ for (int i = 0; i < anchors.Count; i++)
+ for (int j = i + 1; j < anchors.Count; j++)
+ {
+ var (a, b) = (anchors[i].a, anchors[j].a);
+ bool overlap = UnitData.Day(a.From) < UnitData.Day(b.To) && UnitData.Day(b.From) < UnitData.Day(a.To);
+ if (overlap) Assert.AreNotEqual((layer.Spots[a].Q, layer.Spots[a].R), (layer.Spots[b].Q, layer.Spots[b].R), $"{anchors[i].u.Id} and {anchors[j].u.Id} share a hex");
+ }
+ Debug.Log("UNITS spots\n" + string.Join("\n", log));
+ // Review MF1: the anchors whose nearest clear spot was the other side's ground stand on their own side (Etzioni in
+ // West Jerusalem; Harel by Saris on the corridor road), and the 7th Brigade is anchored at Hulda, not Latrun.
+ (int, int) Spot(string id, string place) { var a = anchors.Single(x => x.u.Id == id && x.a.Place == place).a; return (layer.Spots[a].Q, layer.Spots[a].R); }
+ float Km(string id, string place, double lon, double lat)
+ {
+ var sp = layer.Spots[anchors.Single(x => x.u.Id == id && x.a.Place.StartsWith(place)).a];
+ var w = map.Frame.ToWorld(lon, lat, 0);
+ return (new Vector2((float)sp.X, (float)sp.Z) - new Vector2(w.x, w.z)).magnitude / 1000f;
+ }
+ // The 7th Brigade at its Latrun headquarters, Hulda, far from Sar'a (Arab until 13-14 July).
+ Assert.Less(Km("brigade_7", "Hulda", 34.88333, 31.83222), 2.6f, "the 7th stands by Hulda");
+ Assert.Greater(Km("brigade_7", "Hulda", 34.985, 31.77528), 3f, "and well away from Sar'a");
+ Assert.Greater(Km("harel", "Sha'ar HaGai", 34.985, 31.77528), 3f, "Harel well away from Sar'a too");
+ Assert.AreEqual((-2, 23), Spot("harel", "Sha'ar HaGai"));
+ foreach (var (u, a) in anchors.Where(x => x.a.PlaceHex != null))
+ Assert.AreEqual((a.PlaceHex[0], a.PlaceHex[1]), (layer.Spots[a].Q, layer.Spots[a].R), $"{u.Id} {a.Place}: in its place_hex");
+ var etzioni = layer.Spots[anchors.Single(x => x.u.Id == "etzioni").a];
+ var wj = map.Frame.ToWorld(35.21944, 31.78194, 0);
+ Assert.Less((new Vector2((float)etzioni.X, (float)etzioni.Z) - new Vector2(wj.x, wj.z)).magnitude, 2100f, "Etzioni stands in West Jerusalem");
+ Assert.Less(etzioni.X, wj.x, "on the west side of the West Jerusalem point, away from the line");
+ }
+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
+ }
+
+ /// <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>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>
+ [Test]
+ public void NoRiflemanSinksIntoTheHillsOfTheMap()
+ {
+ var map = BuildMap();
+ try
+ {
+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ var checkedFigures = 0; float worstFloat = 0f;
+ foreach (var d in new[] { new DateTime(1948, 5, 29), new DateTime(1948, 6, 5), new DateTime(1948, 7, 12), new DateTime(1948, 12, 4) })
+ {
+ layer.Show(C, StateAt(d, 5, 0.8));
+ foreach (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
+ {
+ 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");
+ 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");
+ }
+ checkedFigures++;
+ }
+ }
+ Debug.Log($"UNITS slope: {checkedFigures} riflemen, worst float {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); }
+ }
+
+ [Test]
+ public void TheTrioIsSpreadSoEachFigureReadsOnItsOwn()
+ {
+ float step = 5000f * UnitShowcase.TrioSpread; // a 5 km hex
+ var 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.Less(o.Max(v => v.magnitude) * step + 600f, UnitShowcase.RingRadius * 5000f, "the figures stay inside the ring");
+ }
+
+ [Test]
+ public void ScreenshotsShowUnitsOnlyWhenAsked()
+ {
+ Assert.IsTrue(UnitLayer.HiddenInCaptures("https://x/?golden&shot", new string[0], true), "plain checkpoints stay comparable");
+ Assert.IsFalse(UnitLayer.HiddenInCaptures("https://x/?golden&shot&units", new string[0], true));
+ Assert.IsFalse(UnitLayer.HiddenInCaptures("https://x/?vprofile", new string[0], true), "the frame profile prices them");
+ Assert.IsFalse(UnitLayer.HiddenInCaptures("https://x/", new string[0], true), "normal play shows them");
+ Assert.IsTrue(UnitLayer.HiddenInCaptures(null, new[] { "player", "-shot" }, false));
+ Assert.IsFalse(UnitLayer.HiddenInCaptures(null, new[] { "player", "-shot", "-units" }, false));
+ }
+
+ [Test]
+ public void TheLayerReadsTheStateNeverWritesItAndRebuildsOnlyOnChange()
+ {
+ var map = BuildMap();
+ try
+ {
+ var session = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ var before = session.State.Hash();
+ Assert.IsTrue(layer.Show(C, session.State));
+ Assert.AreEqual(before, session.State.Hash(), "drawing the units changed the state");
+ Assert.IsFalse(layer.Show(C, session.State), "the same roster draws nothing new");
+ Assert.AreEqual(8, layer.Tokens.Count);
+ var tokens = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens");
+ Assert.AreEqual(8, tokens.childCount);
+ var kiryati = tokens.Find("kiryati");
+ Assert.AreEqual(3, kiryati.Cast<Transform>().Count(t => t.name.StartsWith("Rifleman")), "three riflemen at full call-up");
+ var badge = kiryati.Find("Badge");
+ Assert.IsNotNull(badge, "the promo's badge over every token");
+ Assert.AreEqual(2, badge.GetComponentsInChildren<MeshRenderer>().Length, "a plate and a glyph");
+ Assert.Greater(badge.position.y, kiryati.Find("Rifleman0").position.y + UnitBadge.FigureHeightM * UnitShowcase.FigureScale, "above the figures");
+ for (int i = 0; i < 3; i++)
+ {
+ var b = session.State.Hash();
+ session.Step(HistoricalAI.Commands(C, session.State));
+ var after = session.State.Hash();
+ layer.Show(C, session.State);
+ Assert.AreEqual(after, session.State.Hash(), $"turn {i}: drawing changed the state");
+ Assert.AreNotEqual(b, after);
+ if (i == 0) Assert.IsNotNull(layer.Tokens.FirstOrDefault(p => p.Token.Unit.Id == "squadron_101").Token, "101 Squadron from 20 May 1948");
+ }
+ CollectionAssert.Contains(VisualToggles.Names, UnitLayer.ToggleName);
+ var any = layer.Tokens[0];
+ VisualToggles.Set(UnitLayer.ToggleName, false);
+ Assert.IsFalse(map.Terrain.transform.Find(UnitLayer.RootName).gameObject.activeSelf);
+ Assert.IsNull(layer.UnitToSelectAt(any.Q, any.R), "a hidden unit cannot be selected (review M1)");
+ VisualToggles.Set(UnitLayer.ToggleName, true);
+ Assert.AreEqual(any.Token.Unit.Id, layer.UnitToSelectAt(any.Q, any.R));
+ }
+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
+ CollectionAssert.DoesNotContain(VisualToggles.Names, UnitLayer.ToggleName, "the map's teardown removes the switch");
+ }
+
+ /// <summary>Review I1: "since" only from a sourced start; never the game's first day.</summary>
+ [Test]
+ public void TheCardGivesASinceOnlyFromASourcedStart()
+ {
+ var text = Text;
+ PlacedToken Token(string id, GameState s) => new PlacedToken(UnitRoster.Build(Units, C, s).Single(t => t.Unit.Id == id), default);
+ var start = StateAt(C.Rules.Start, 5, 0.8);
+ var kiryati = UnitCard.For(Token("kiryati", start), start, text);
+ StringAssert.Contains("At Tel Aviv since February 1948", kiryati.Body);
+ StringAssert.DoesNotContain("15 May 1948", kiryati.Body);
+ var givati = UnitCard.For(Token("givati", start), start, text);
+ StringAssert.Contains("At Gedera\n", givati.Body + "\n");
+ StringAssert.DoesNotContain("since", givati.Body.Split('\n').First(l => l.StartsWith("At ")), "its move south is not dated");
+ var latrun = StateAt(new DateTime(1948, 5, 29), 5, 0.8);
+ StringAssert.Contains("At Hulda (headquarters for the Latrun attacks) since 24 May 1948", UnitCard.For(Token("brigade_7", latrun), latrun, text).Body);
+ var ship = UnitCard.For(Token("ins_haganah", start), start, text);
+ StringAssert.Contains("commissioned 1948", ship.Subtitle);
+ StringAssert.Contains("Wikipedia only", kiryati.Note);
+ var hatzor = StateAt(new DateTime(1948, 12, 1), 5, 0.8);
+ StringAssert.DoesNotContain("Wikipedia only", UnitCard.For(Token("squadron_101", hatzor), hatzor, text).Note,
+ "Hatzor's position cites Eduard (review M8: the note is per position)");
+ var july = StateAt(new DateTime(1948, 7, 1), 5, 0.8);
+ StringAssert.Contains("Wikipedia only", UnitCard.For(Token("squadron_101", july), july, text).Note, "Herzliya's position is Wikipedia only");
+ }
+
+ [Test]
+ public void ClickingAUnitSelectsItWithOneHighlightAndTheCardLinksToDefence()
+ {
+ var map = BuildMap();
+ using var ui = new UiTestKit();
+ try
+ {
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ layer.Show(bridge.Content, bridge.State);
+ var nav = new ScreenNav(ui.Root);
+ var subdistricts = Subdistricts1948.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", Subdistricts1948.FileName)));
+ var regions = new MapRegions(subdistricts, Armistice1949.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", Armistice1949.FileName))));
+ regions.Apply(subdistricts.ShownFrom); // shown, as at the game's start
+ var towns = SettlementPlacer.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", SettlementPlacer.DefaultFileName))).ToDictionary(t => t.Id, t => t.Name);
+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, towns, nav: nav,
+ selectedUnit: () => layer.Selected is string id ? layer.Tokens.First(p => p.Token.Unit.Id == id) : (PlacedToken?)null,
+ regions: regions);
+ var root = map.Terrain.transform.Find(UnitLayer.RootName);
+ var golani = layer.Tokens.Single(p => p.Token.Unit.Id == "golani");
+ var tlv = C.SettlementHexes.Single(t => t.Id == "tel_aviv");
+ info.Show(tlv.Q, tlv.R);
+ Assert.IsNotEmpty(ui.Q<Label>("info-region").text, "a hex names its 1948 sub-district");
+ map.Select(golani.Q, golani.R); // MapPointer outlines the hex before it raises HexClicked
+ GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);
+ Assert.AreEqual("golani", layer.Selected);
+ Assert.IsNotNull(root.Find("SelectionRing"), "the promo's white ring round the selected token");
+ Assert.IsFalse(map.Terrain.transform.Find(MapScene.SelectionName).GetComponent<MeshRenderer>().enabled, "one highlight: the ring, not the hex outline (review M2)");
+ Assert.IsTrue(info.ShowsUnit);
+ Assert.AreEqual("", ui.Q<Label>("info-region").text, "a unit's card names no sub-district (review MF2)");
+ var words = ui.Q<VisualElement>("info-panel").Query<Label>().ToList().Select(l => l.text).ToList();
+ Assert.AreEqual("Golani Brigade", ui.Q<Label>("info-title").text);
+ Assert.IsTrue(words.Any(w => w.Contains("At Yavne'el since February 1948")), string.Join(" | ", words));
+ Assert.IsTrue(words.Any(w => w.Contains("Reserve call-up 80%") && w.Contains("security level 5")), string.Join(" | ", words));
+ Assert.IsTrue(words.Any(w => w.Contains("Wikipedia only")), "a Wikipedia-only position says it is a draft");
+ Assert.AreEqual(DisplayStyle.None, ui.Q<Button>("build-camp").style.display.value, "no orders on a unit");
+ var defence = ui.Q<Button>("info-defence");
+ Assert.AreEqual(DisplayStyle.Flex, defence.style.display.value);
+ UiTestKit.Press(defence);
+ Assert.AreEqual("defence", nav.Current);
+ nav.Open(null); // the Defence screen covers the panel; close it before clicking the map again
+ GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);
+ Assert.IsNull(layer.Selected, "a second click shows the hex and its map actions");
+ Assert.IsNull(root.Find("SelectionRing"));
+ Assert.IsFalse(info.ShowsUnit);
+ Assert.AreEqual(DisplayStyle.None, defence.style.display.value);
+ // A screen covering the panel (#210): a click behind it moves neither the ring nor the card.
+ var hud = ui.Q<VisualElement>("info-panel").parent;
+ hud.AddToClassList(ScreenNav.WideOpenClass);
+ var tlvHex = C.SettlementHexes.Single(t => t.Id == "tel_aviv");
+ map.Select(tlvHex.Q, tlvHex.R); // MapPointer outlines the clicked hex (Tel Aviv) before it raises HexClicked
+ GameRoot.OnHexClicked(map, layer, info, tlvHex.Q, tlvHex.R);
+ Assert.IsNull(layer.Selected, "covered: no selection");
+ Assert.AreEqual((golani.Q, golani.R), info.Selected, "covered: the panel keeps its hex");
+ Assert.IsTrue(map.Terrain.transform.Find(MapScene.SelectionName).GetComponent<MeshRenderer>().enabled, "the outline is back on the panel's hex");
+ Assert.IsFalse(info.ShowsUnit);
+ hud.RemoveFromClassList(ScreenNav.WideOpenClass);
+ info.Dispose(); nav.Dispose();
+ }
+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
+ }
+
+ /// <summary>Review M5: a selected unit that leaves the map on a turn is deselected and the card falls back to the hint.</summary>
+ [Test]
+ public void ASelectedUnitThatLeavesTheMapClearsItsCard()
+ {
+ var map = BuildMap();
+ using var ui = new UiTestKit();
+ try
+ {
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(), null,
+ () => layer.Selected is string id ? layer.Tokens.First(p => p.Token.Unit.Id == id) : (PlacedToken?)null);
+ layer.Show(C, StateAt(new DateTime(1948, 7, 12), 5, 0.8));
+ var yiftach = layer.Tokens.Single(p => p.Token.Unit.Id == "yiftach");
+ GameRoot.OnHexClicked(map, layer, info, yiftach.Q, yiftach.R);
+ Assert.IsTrue(info.ShowsUnit);
+ layer.Show(C, StateAt(new DateTime(1948, 7, 24), 5, 0.8)); // Operation Dani is over
+ Assert.IsNull(layer.Selected);
+ Assert.IsNull(map.Terrain.transform.Find(UnitLayer.RootName).Find("SelectionRing"));
+ info.Render();
+ Assert.IsFalse(info.ShowsUnit);
+ Assert.AreEqual(Text["info.hint"], ui.Q<Label>("info-title").text);
+ info.Dispose();
+ }
+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
+ }
+
+ /// <summary>The 1948-49 IAF roundel (owner question, 2026-10-12): a FILLED blue Star of David, not an outline, its
+ /// points clear of the white disc's edge, no outer ring (Efrati, Colors &amp; Markings of the Israeli Air Force, p. 6:
+ /// the open star was filled for ground visibility in May 1948, "as applied on IAF aircraft ever since"; FOTW).</summary>
+ [Test]
+ public void TheRoundelIsAFilledStarOfDavidOnAWhiteDiscWithNoRing()
+ {
+ var star = UnitModels.RoundelStar();
+ Assert.AreEqual(2, star.Length, "two triangles");
+ foreach (var tri in star)
+ {
+ Assert.AreEqual(3, tri.Count, "each triangle is one filled plate (an outline would be a band with a hole)");
+ Assert.IsTrue(Inside(Vector2.zero, tri), "filled: the star covers the disc's centre, which an outline star leaves white");
+ foreach (var v in tri) Assert.AreEqual(UnitModels.RoundelStarShare, v.magnitude, 1e-4f);
+ }
+ Assert.Less(UnitModels.RoundelStarShare, 0.9f, "the points stay clear of the disc's edge");
+ Assert.Greater(UnitModels.RoundelStarShare, 0.6f);
+ var points = star.SelectMany(t => t).Select(v => Mathf.Repeat(Mathf.Atan2(v.y, v.x) * Mathf.Rad2Deg, 360f)).OrderBy(a => a).ToList();
+ for (int i = 0; i < 6; i++) Assert.AreEqual(30f + 60f * i, points[i], 1e-3f, "a six-pointed star, a point straight up the plane's local axis");
+ var turned = UnitModels.RoundelStar(30f).SelectMany(t => t).Select(v => Mathf.Repeat(Mathf.Atan2(v.y, v.x) * Mathf.Rad2Deg, 360f)).ToList();
+ Assert.IsTrue(turned.Any(a => Mathf.Abs(a - 0f) < 1e-3f || Mathf.Abs(a - 360f) < 1e-3f) && turned.Any(a => Mathf.Abs(a - 180f) < 1e-3f),
+ "turned 30 degrees on a fuselage side, a point is straight up on either side");
+ // On the models: six roundels on the Spitfire (two fuselage, two on top of the wings, two under), four on the S-199
+ // (two fuselage, two under the wings: no over-wing roundels before October 1948), each star 2 triangles x 2 faces.
+ var spit = UnitModels.Spitfire("s");
+ try
+ {
+ int blue = spit.uv.Count(uv => Mathf.Abs(uv.x - UnitPalette.U(UnitPalette.RoundelBlue)) < 1e-4f);
+ Assert.AreEqual(6 * 2 * 3 * 2, blue, "six filled stars, no blue ring");
+ var avia = UnitModels.AviaS199("a-wings");
+ try
+ {
+ int wingBlue = avia.vertices.Where((p, i) => Mathf.Abs(p.x) > 1.5f && Mathf.Abs(avia.uv[i].x - UnitPalette.U(UnitPalette.RoundelBlue)) < 1e-4f).Count();
+ Assert.AreEqual(2 * 2 * 3 * 2, wingBlue, "the S-199's wing stars: under the wings only, none on top (Efrati pp. 6, 11)");
+ }
+ finally { UnityEngine.Object.DestroyImmediate(avia); }
+ // The fuselage roundels face outwards: each star sits outside its white disc, not behind it.
+ foreach (var mesh in new[] { spit, UnitModels.AviaS199("a") })
+ {
+ var v = mesh.vertices; var uv = mesh.uv;
+ bool Is(int i, int slot) => Mathf.Abs(uv[i].x - UnitPalette.U(slot)) < 1e-4f;
+ bool Fuselage(Vector3 p) => p.z > -3.0f && p.z < -1.8f && Mathf.Abs(p.y) < 0.7f && Mathf.Abs(p.x) > 0.3f && Mathf.Abs(p.x) < 0.8f;
+ foreach (var side in new[] { 1f, -1f })
+ {
+ var blueX = Enumerable.Range(0, v.Length).Where(i => Is(i, UnitPalette.RoundelBlue) && Fuselage(v[i]) && Mathf.Sign(v[i].x) == side).Select(i => Mathf.Abs(v[i].x)).ToList();
+ var whiteX = Enumerable.Range(0, v.Length).Where(i => Is(i, UnitPalette.RoundelWhite) && Fuselage(v[i]) && Mathf.Sign(v[i].x) == side && Mathf.Abs(v[i].x) > 0.38f).Select(i => Mathf.Abs(v[i].x)).ToList();
+ Assert.IsNotEmpty(blueX, $"{mesh.name}: a fuselage star on side {side}");
+ Assert.Greater(blueX.Min(), whiteX.Max() - 1e-4f, $"{mesh.name}: the star on side {side} is outside its disc");
+ }
+ if (mesh != spit) UnityEngine.Object.DestroyImmediate(mesh);
+ }
+ }
+ finally { UnityEngine.Object.DestroyImmediate(spit); }
+ }
+
+ static bool Inside(Vector2 p, List<Vector2> tri)
+ {
+ float Cross(Vector2 a, Vector2 b, Vector2 c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
+ float d1 = Cross(tri[0], tri[1], p), d2 = Cross(tri[1], tri[2], p), d3 = Cross(tri[2], tri[0], p);
+ return (d1 >= 0 && d2 >= 0 && d3 >= 0) || (d1 <= 0 && d2 <= 0 && d3 <= 0);
+ }
+
+ [Test]
+ public void TheS199IsRepeatableAndToScale()
+ {
+ var plain = UnitModels.AviaS199("a"); var again = UnitModels.AviaS199("b");
+ var prop = UnitModels.S199Propeller("p");
+ try
+ {
+ CollectionAssert.AreEqual(plain.vertices, again.vertices);
+ CollectionAssert.AreEqual(plain.uv, again.uv);
+ var b = plain.bounds;
+ Assert.AreEqual(9.92f, b.size.x, 0.25f, "span (Avia S-199 specifications)");
+ Assert.AreEqual(8.94f, b.size.z, 0.25f, "length");
+ Assert.Less(plain.triangles.Length / 3 + prop.triangles.Length / 3, 6000);
+ int Slot(Mesh m, int slot) => m.uv.Count(uv => Mathf.Abs(uv.x - UnitPalette.U(slot)) < 1e-4f);
+ Assert.AreEqual(0, Slot(plain, UnitPalette.MarkingRed), "no Operation Yoav markings: the map shows the Spitfire from 15 October 1948");
+ Assert.Greater(Slot(plain, UnitPalette.RoundelBlue), 0, "roundels under the wings");
+ Assert.Greater(Slot(plain, UnitPalette.RoundelWhite), 0, "and the white rear-fuselage bands");
+ }
+ finally { foreach (var m in new[] { plain, again, prop }) UnityEngine.Object.DestroyImmediate(m); }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs.meta b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs.meta
new file mode 100644
index 000000000..ea47673bc
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 88c1f39b004e2419b86355f7d52d4cf8
\ No newline at end of file
diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxml
index 71904e478..12ad66dac 100644
--- a/unity/Assets/UI/Game.uxml
+++ b/unity/Assets/UI/Game.uxml
@@ -121,6 +121,7 @@
<ui:VisualElement class="row">
<ui:Button name="build-camp" />
<ui:Button name="build-housing" />
+ <ui:Button name="info-defence" />
</ui:VisualElement>
<ui:Label name="info-reason" class="reason" />
</ui:VisualElement>
diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yaml
index d303a0e53..29eab62f6 100644
--- a/unity/Assets/UI/strings.en.yaml
+++ b/unity/Assets/UI/strings.en.yaml
@@ -112,6 +112,23 @@ info.biome.hills: "Hills"
info.biome.mountains: "Mountains"
info.biome.valley: "Valley"
info.biome.desert: "Desert"
+unit.subtitle: "{0} · {1}"
+unit.service.army: "Army"
+unit.service.air: "Air Force"
+unit.service.navy: "Navy"
+unit.position: "At {0} since {1}"
+unit.position_plain: "At {0}"
+unit.formed: "Formed {0}"
+unit.commander: "First commander: {0}"
+unit.aircraft.s199: "Avia S-199"
+unit.aircraft.spitfire: "Supermarine Spitfire LF Mk IXe"
+unit.flying: "{0}, flying over the base"
+unit.parked: "{0}, on the ground at the base"
+unit.national: "Reserve call-up {0} · security level {1} of 5"
+unit.sources: "Sources: {0}"
+unit.draft_wikipedia: "Draft: from Wikipedia only, not yet checked against a published history"
+unit.draft: "Draft: not yet checked by a historian"
+unit.defence: "Open the Defence screen"
newgame.confirm: "Press New Game again to abandon this game and start over."
newgame.delete_failed: "The old saved game could not be removed; it will be replaced after your next turn."
save.unreadable: "Your saved game could not be loaded ({0}). A new game has started."
diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yaml
index 3a7a70bf2..1454beab4 100644
--- a/unity/Assets/UI/strings.he.yaml
+++ b/unity/Assets/UI/strings.he.yaml
@@ -107,6 +107,23 @@ info.biome.hills: "גבעות"
info.biome.mountains: "הרים"
info.biome.valley: "עמק"
info.biome.desert: "מדבר"
+unit.subtitle: "{0} · {1}"
+unit.service.army: "צבא היבשה"
+unit.service.air: "חיל האוויר"
+unit.service.navy: "חיל הים"
+unit.position: "מיקום: {0}, מאז {1}"
+unit.position_plain: "מיקום: {0}"
+unit.formed: "הוקמה: {0}"
+unit.commander: "מפקד ראשון: {0}"
+unit.aircraft.s199: "אוויה S-199"
+unit.aircraft.spitfire: "ספיטפייר LF Mk IXe"
+unit.flying: "{0}, בטיסה מעל הבסיס"
+unit.parked: "{0}, על הקרקע בבסיס"
+unit.national: "גיוס מילואים {0} · רמת ביטחון {1} מתוך 5"
+unit.sources: "מקורות: {0}"
+unit.draft_wikipedia: "טיוטה: מוויקיפדיה בלבד, טרם נבדק מול מחקר שפורסם"
+unit.draft: "טיוטה: טרם נבדק בידי היסטוריון"
+unit.defence: "פתיחת מסך הביטחון"
newgame.confirm: "יש ללחוץ שוב על משחק חדש כדי לעזוב את המשחק הזה ולהתחיל מחדש."
newgame.delete_failed: "לא ניתן היה להסיר את השמירה הקודמת; היא תוחלף אחרי התור הבא."
save.unreadable: "לא ניתן היה לטעון את המשחק השמור ({0}). משחק חדש התחיל."