Skip to content

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

Map: the region files read from baked runtime forms at boot, about 115 ms before the start screen (refs #321) (#601)

Eyal Golan46ab572f1a5f
diff --git a/ASSETS.yaml b/ASSETS.yaml
index 4b8f8c366..cb160926b 100644
--- a/ASSETS.yaml
+++ b/ASSETS.yaml
@@ -176,17 +176,17 @@ rules:
note: "Decision D6 (the M3 plan's deferred 'Legal review of map-data licences' row). Published 2026-10-10 before the check."
- glob: "content/map/subdistrict*"
licence: CC-BY-SA-4.0
- source: "tools/borders_digitise.py from the Survey of Palestine map 'Administrative Divisions' (1:750,000, 1946, overprinted May 1947; two Commons scans, SHA-256 in the file) per the 1947 Schedule (Palestine Gazette No. 1552); coast from the Copernicus DEM (NOTICE); the hex layer by tools/borders_bake.py; content/ is CC BY-SA 4.0"
+ source: "tools/borders_digitise.py from the Survey of Palestine map 'Administrative Divisions' (1:750,000, 1946, overprinted May 1947; two Commons scans, SHA-256 in the file) per the 1947 Schedule (Palestine Gazette No. 1552); coast from the Copernicus DEM (NOTICE); the hex layer by tools/borders_bake.py; content/ is CC BY-SA 4.0. subdistrict_hexes_1948.tsv is the YAML's baked runtime form (tools/regions_bake.py, issue #321), with the same rows and no new facts"
status: verified
note: "Decision D-B (owner-delegated, 2026-10-11): allowed; facts redrawn, no image copied. Government of Palestine works of 1945-47, public domain in Israel and the UK since 1997; the file holds facts (where legally defined lines run) redrawn by our own method, which a possible US copyright in the map's drawing does not reach (Feist). Hebrew and Arabic names from Wikipedia, noted per row."
- glob: "content/map/armistice*"
licence: CC-BY-SA-4.0
- source: "tools/armistice_digitise.py from the 1949 General Armistice Agreements (UNTS vol. 42) and their annexed maps: Syria, Annex I's MR points and the annexed 1:50,000 map (S/1353/Rev.1: the UN ODS colour scan and the UNISPAL 1-bit scan, SHA-256 in the tool); Lebanon, Art. V.1's international boundary as the Mandate frontier of content/map/subdistricts_1948.geojson; Egypt, Art. VI.1 and VIII.2 with the Survey of Palestine 1:100,000 sheet 9 'Gaza' (Commons, NLI copy) for the Wadi Hasi mouth, Deir Suneid and the highway; the 1950 modus vivendi line from S/1471's signed map (UNISPAL; sheet 2 from the UN Treaty Collection); Jordan from the low-resolution UNISPAL copy of the signed map 1 (source_quality low_res_scan), georeferenced on town coordinates from Wikidata (CC0) and Wikipedia; IBS 46 (1965) a named cross-check only; coast from the Copernicus DEM (NOTICE); the hex layer by tools/armistice_bake.py; content/ is CC BY-SA 4.0"
+ source: "tools/armistice_digitise.py from the 1949 General Armistice Agreements (UNTS vol. 42) and their annexed maps: Syria, Annex I's MR points and the annexed 1:50,000 map (S/1353/Rev.1: the UN ODS colour scan and the UNISPAL 1-bit scan, SHA-256 in the tool); Lebanon, Art. V.1's international boundary as the Mandate frontier of content/map/subdistricts_1948.geojson; Egypt, Art. VI.1 and VIII.2 with the Survey of Palestine 1:100,000 sheet 9 'Gaza' (Commons, NLI copy) for the Wadi Hasi mouth, Deir Suneid and the highway; the 1950 modus vivendi line from S/1471's signed map (UNISPAL; sheet 2 from the UN Treaty Collection); Jordan from the low-resolution UNISPAL copy of the signed map 1 (source_quality low_res_scan), georeferenced on town coordinates from Wikidata (CC0) and Wikipedia; IBS 46 (1965) a named cross-check only; coast from the Copernicus DEM (NOTICE); the hex layer by tools/armistice_bake.py; content/ is CC BY-SA 4.0. armistice_hexes_1949.tsv is the YAML's baked runtime form (tools/regions_bake.py, issue #321), with the same rows and no new facts"
status: verified
note: "Decision D-A: UN documents with symbols are not copyrighted (ST/AI/189/Add.9/Rev.2 para. 2); the Gaza sheet, the Mandate frontier and Jordan map 1's 1:250,000 base fall under D-B (Government of Palestine); S/1471's base sheets are a Survey of Israel reprint of about 1949-50 (outside D-B; facts only taken). Only the lines' positions are taken, redrawn by our own method. Status draft until the owner's fact check and sensitivity review. Decision D-A decided (owner, 2026-10-14, docs/oss/DECISIONS.md): the rulings accepted as recorded; no archive request for a full-resolution Jordan scan now (it can be requested later)."
- glob: "content/map/control*"
licence: CC-BY-SA-4.0
- source: "tools/control_digitise.py from Israel State Archives map 6158/1 ('Palestine: the partition lines and the front lines', 1949, ISA-PMO-GovernmentSecretary-R0005czg; the NYU Faculty Digital Archive copy, hdl 2451/72921, SHA-256 in the tool; source_quality low_res_scan), georeferenced on its printed 10-km Palestine grid; its red (9 July 1948), blue (18 July 1948) and green (end of October 1948) front lines traced; the dates of the operations from Wikipedia; from each 1949 agreement's date the sides of content/map/armistice_lines_1949.geojson (D-A); the Mandate outline of content/map/subdistricts_1948.geojson (D-B); the hex layer by tools/control_bake.py; content/ is CC BY-SA 4.0"
+ source: "tools/control_digitise.py from Israel State Archives map 6158/1 ('Palestine: the partition lines and the front lines', 1949, ISA-PMO-GovernmentSecretary-R0005czg; the NYU Faculty Digital Archive copy, hdl 2451/72921, SHA-256 in the tool; source_quality low_res_scan), georeferenced on its printed 10-km Palestine grid; its red (9 July 1948), blue (18 July 1948) and green (end of October 1948) front lines traced; the dates of the operations from Wikipedia; from each 1949 agreement's date the sides of content/map/armistice_lines_1949.geojson (D-A); the Mandate outline of content/map/subdistricts_1948.geojson (D-B); the hex layer by tools/control_bake.py; content/ is CC BY-SA 4.0. control_hexes_1948_49.tsv is the YAML's baked runtime form (tools/regions_bake.py, issue #321), with the same rows and no new facts"
status: verified
note: "Decision D-C (owner, 2026-10-14): allowed. A 1949 Israeli state work, out of copyright in Israel (Copyright Act 2007 s. 42); a possible URAA US term in its drawing does not reach the facts taken (where a front line ran on a date: Feist); its base is a Survey of Palestine sheet (D-B). Only the lines' positions are taken, redrawn by our own method; no image is copied or committed. Status draft, owner-verify: the owner's fact check and sensitivity review before a shareable build."
- glob: "content/map/settlements_1948.yaml"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 50eddcb09..5215e376a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -307,6 +307,11 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
+0.9 ms at the gameplay zoom), not yet on an idle one.
### Changed
+- The map's region files (the 1948 sub-districts, the 1949 armistice lines, the 1948-49 control areas) are read
+ from baked runtime forms at boot instead of being parsed as YAML (`tools/regions_bake.py`, refs #321), as the
+ localities and the route paths are. The sub-districts are read once, for the camps and the region layers. A stale,
+ cut or missing runtime file is refused with one warning and the YAML is read as before. The borders, the layer
+ labels and the info panel are unchanged. Presentation only.
- The settlements file is parsed once at boot instead of twice: the info panel's settlement names come from the map's
own parse (refs #321). The names are unchanged. Presentation only.
- The units layer takes the unit spots the map placed instead of placing every unit again (refs #321), when it draws
diff --git a/content/map/armistice_hexes_1949.tsv b/content/map/armistice_hexes_1949.tsv
new file mode 100644
index 000000000..dd58a6e96
--- /dev/null
+++ b/content/map/armistice_hexes_1949.tsv
@@ -0,0 +1,33 @@
+# Generated by tools/regions_bake.py from armistice_hexes_1949.yaml. Do not edit: edit the YAML (or rerun its own tool) and
+# rerun this one. The runtime form the map reads at boot (display only, outside the content hash).
+meta version 2
+meta yaml_check -114794802
+meta rows 27
+scalar layer s:armistice_1949
+scalar title s:The 1949 armistice lines that the primary sources allow (true lines, not hex-snapped)
+scalar line s:The true lines are content/map/armistice_lines_1949.geojson (status draft): the agreements and their annexed maps; shown here to the nearest hex edge, up to half a hex (about 4 km) from the true line.
+scalar label s:1949 armistice lines
+item fronts key=s:egypt name=s:Egypt agreement=s:Egypt-Israel General Armistice Agreement signed=s:1949-02-24 shown_from=s:1949-02-24 low_accuracy=s:false note=s:Gap: from Gaza (about MR 102.4-100.1) to the Egyptian frontier the line is not drawn. Art. VI.1 says only 'continuing thus to the Egyptian frontier' and no map of the Memorandum or of the agreement was found. Art. VI.3 bounds it: Israel evacuates its outpost at the Cemetery (MR 0816-0723), so that point is inside the line, and new Israeli outposts may be set up at MR 0836-0700, east of it, so the line reaches the frontier south-east of Rafah, between about N 70 and N 72 km. Carrying the highway's bearing on from Gaza reaches the frontier at about MR 077.7-075.6, north of the Cemetery, and is therefore wrong; a 3-km offset of the coast road through Khan Yunis (MR 083.7-084.2) and Rafah (078.1-077.6), carried on its bearing, reaches the frontier near N 73, also north-west of the Cemetery. The Egyptian-held area is not drawn either, since it needs the whole line. From 22 Feb 1950 the line as drawn on the signed modus vivendi map (S/1471) is a separate feature (egypt_mv1950_demarcation), with its zone A and C lines (egypt_mv1950_zone_lines). Art. VI.4: in the Bethlehem-Hebron area no line was demarcated (left to a later agreement); nothing is drawn there.
+item fronts key=s:lebanon name=s:Lebanon agreement=s:Lebanon-Israel General Armistice Agreement signed=s:1949-03-23 shown_from=s:1949-03-23 low_accuracy=s:false note=s:
+item fronts key=s:jordan name=s:Jordan agreement=s:Hashemite Jordan Kingdom-Israel General Armistice Agreement signed=s:1949-04-03 shown_from=s:1949-04-03 low_accuracy=s:true note=s:Not drawn (legibility, low-resolution scan): the Jerusalem sector (Art. V.1(b): the lines of the 30 November 1948 cease-fire, map 2, not on UNISPAL; on map 1 the city's lines merge into one blot at 51 m a pixel), so the line stops at the city's western edge on both sides; the Israeli and Jordanian lines and the no-man's-land between them, in Jerusalem and at Latrun (map 1 shows a double line at Latrun, but the two cannot be told apart at this resolution; the trace follows the outer drawn loop); the Mount Scopus enclave. To do from map 2 and a full-resolution map 1.
+item fronts key=s:syria name=s:Syria agreement=s:Syria-Israel General Armistice Agreement signed=s:1949-07-20 shown_from=s:1949-07-20 low_accuracy=s:false note=s:
+item zones id=s:1 key=s:syria_dmz_north front=s:syria name=s:Demilitarized Zone (Syria-Israel), northern part: Banias and Tell el Qadi shown_from=s:1949-07-20 style=s:secondary agreement=s:Syria-Israel General Armistice Agreement signed=s:1949-07-20 label_note=s: low_accuracy=s:false
+item zones id=s:2 key=s:syria_dmz_central front=s:syria name=s:Demilitarized Zone (Syria-Israel), central part: Dardara, the Jordan and Mishmar HaYarden shown_from=s:1949-07-20 style=s:secondary agreement=s:Syria-Israel General Armistice Agreement signed=s:1949-07-20 label_note=s: low_accuracy=s:false
+item zones id=s:3 key=s:syria_dmz_south front=s:syria name=s:Demilitarized Zone (Syria-Israel), southern part: Ein Gev and El Hamma shown_from=s:1949-07-20 style=s:secondary agreement=s:Syria-Israel General Armistice Agreement signed=s:1949-07-20 label_note=s: low_accuracy=s:false
+item zones id=s:4 key=s:egypt_el_auja_dmz front=s:egypt name=s:El Auja Demilitarized Zone (Egypt-Israel) shown_from=s:1949-02-24 style=s:secondary agreement=s:Egypt-Israel General Armistice Agreement signed=s:1949-02-24 label_note=s: low_accuracy=s:false
+item lines id=s:1 key=s:lebanon_adl front=s:lebanon name=s:Armistice Demarcation Line (Lebanon-Israel): the international boundary shown_from=s:1949-03-23 agreement=s:Lebanon-Israel General Armistice Agreement signed=s:1949-03-23 label_note=s: low_accuracy=s:false
+item lines id=s:2 key=s:syria_adl front=s:syria name=s:Armistice Demarcation Line (Syria-Israel) shown_from=s:1949-07-20 agreement=s:Syria-Israel General Armistice Agreement signed=s:1949-07-20 label_note=s: low_accuracy=s:false
+item lines id=s:3 key=s:egypt_adl_gaza front=s:egypt name=s:Armistice Demarcation Line (Egypt-Israel) of 1949, Gaza-Rafah area: Wadi Hasi to Gaza shown_from=s:1949-02-24 agreement=s:Egypt-Israel General Armistice Agreement signed=s:1949-02-24 label_note=s: low_accuracy=s:false
+item lines id=s:4 key=s:egypt_mv1950_demarcation front=s:egypt name=s:Demarcation line as drawn on the signed 1950 modus vivendi map (Gaza-Rafah area) shown_from=s:1950-02-22 agreement=s:Modus vivendi to the Egypt-Israel General Armistice Agreement signed=s:1950-02-22 label_note=s:1950 modus vivendi low_accuracy=s:false
+item lines id=s:5 key=s:egypt_mv1950_zone_lines front=s:egypt name=s:Zone A and zone C lines of the 1950 modus vivendi (Gaza-Rafah area) shown_from=s:1950-02-22 agreement=s:Modus vivendi to the Egypt-Israel General Armistice Agreement signed=s:1950-02-22 label_note=s:1950 modus vivendi low_accuracy=s:false
+item lines id=s:6 key=s:jordan_adl_iraqi_c_east front=s:jordan name=s:Armistice Demarcation Line (Jordan-Israel), line A, Zubeiba to the Jordan (Art. VI.3(c), by 17 July 1949) shown_from=s:1949-07-17 agreement=s:Hashemite Jordan Kingdom-Israel General Armistice Agreement signed=s:1949-04-03 label_note=s: low_accuracy=s:true
+item lines id=s:7 key=s:jordan_adl_iraqi_b_wadi_ara front=s:jordan name=s:Armistice Demarcation Line (Jordan-Israel), line A, Wadi Ara, Zubeiba to Baqa (Art. VI.3(b), by 22 May 1949) shown_from=s:1949-05-22 agreement=s:Hashemite Jordan Kingdom-Israel General Armistice Agreement signed=s:1949-04-03 label_note=s: low_accuracy=s:true
+item lines id=s:8 key=s:jordan_adl_iraqi_a_triangle front=s:jordan name=s:Armistice Demarcation Line (Jordan-Israel), line A, Baqa to Kafr Qasim (Art. VI.3(a), by 8 May 1949) shown_from=s:1949-05-08 agreement=s:Hashemite Jordan Kingdom-Israel General Armistice Agreement signed=s:1949-04-03 label_note=s: low_accuracy=s:true
+item lines id=s:9 key=s:jordan_adl_iraqi_c_south front=s:jordan name=s:Armistice Demarcation Line (Jordan-Israel), line A, Kafr Qasim to Kh Deir Arab (Art. VI.3(c), by 17 July 1949) shown_from=s:1949-07-17 agreement=s:Hashemite Jordan Kingdom-Israel General Armistice Agreement signed=s:1949-04-03 label_note=s: low_accuracy=s:true
+item lines id=s:10 key=s:jordan_adl_a_latrun front=s:jordan name=s:Armistice Demarcation Line (Jordan-Israel), Kh Deir Arab to Jerusalem (Latrun) shown_from=s:1949-04-03 agreement=s:Hashemite Jordan Kingdom-Israel General Armistice Agreement signed=s:1949-04-03 label_note=s: low_accuracy=s:true
+item lines id=s:11 key=s:jordan_adl_bc_south front=s:jordan name=s:Armistice Demarcation Line (Jordan-Israel), Jerusalem to the Dead Sea (line B, Hebron-Dead Sea) shown_from=s:1949-04-03 agreement=s:Hashemite Jordan Kingdom-Israel General Armistice Agreement signed=s:1949-04-03 label_note=s: low_accuracy=s:true
+item lines id=s:12 key=s:jordan_adl_d_arava front=s:jordan name=s:Armistice Demarcation Line (Jordan-Israel), the Dead Sea to the Gulf of Aqaba shown_from=s:1949-04-03 agreement=s:Hashemite Jordan Kingdom-Israel General Armistice Agreement signed=s:1949-04-03 label_note=s: low_accuracy=s:true
+scalar no_hex l:syria_dmz_north,syria_dmz_south
+tuples zone_hexes 6 13 5 2;-16 36 4;-15 36 4;-16 37 4;-15 37 4;-16 38 4
+tuples line_hexes 119 8 4 1;9 4 1;10 4 1;11 4 1;12 4 1;13 3 1;14 2 1;14 1 1;15 1 1;15 2 2;15 3 2;14 3 2;14 4 2;13 5 2;13 6 2;12 7 2;12 8 2;11 9 2;10 10 2;11 10 2;-10 26 3;-9 26 3;-9 27 3;-10 27 3;-10 27 4;-13 29 4;-14 31 4;-10 26 5;-9 26 5;-9 27 5;-10 27 5;-13 29 5;-13 30 5;-14 31 5;8 14 6;7 14 6;7 13 6;7 12 6;6 12 6;5 12 6;5 12 7;4 13 7;3 13 7;2 14 7;2 14 8;2 15 8;1 15 8;1 16 8;0 17 8;0 18 8;0 18 9;-1 19 9;-1 20 9;-1 20 10;-2 21 10;-1 21 10;-2 22 10;-3 22 10;-3 23 10;-1 22 10;-1 23 10;0 22 10;-1 24 11;-2 24 11;-3 25 11;-4 25 11;-5 26 11;-5 27 11;-6 28 11;-7 29 11;-7 30 11;-6 29 11;-6 30 11;-5 29 11;-5 30 11;-4 29 11;-3 29 11;-2 28 11;-1 28 11;0 27 11;0 28 11;0 28 12;-1 29 12;-1 30 12;-2 30 12;-2 31 12;-3 32 12;-2 32 12;-3 33 12;-3 34 12;-4 34 12;-4 35 12;-5 36 12;-6 37 12;-7 38 12;-8 39 12;-8 40 12;-9 40 12;-9 41 12;-10 41 12;-10 42 12;-11 43 12;-11 44 12;-12 45 12;-12 46 12;-13 46 12;-13 47 12;-13 48 12;-14 48 12;-14 49 12;-15 49 12;-15 50 12;-16 51 12;-17 52 12;-17 53 12;-18 53 12;-18 54 12;-19 55 12;-19 56 12
+meta body_check 2055728539
diff --git a/content/map/control_hexes_1948_49.tsv b/content/map/control_hexes_1948_49.tsv
new file mode 100644
index 000000000..4883d740e
--- /dev/null
+++ b/content/map/control_hexes_1948_49.tsv
@@ -0,0 +1,28 @@
+# Generated by tools/regions_bake.py from control_hexes_1948_49.yaml. Do not edit: edit the YAML (or rerun its own tool) and
+# rerun this one. The runtime form the map reads at boot (display only, outside the content hash).
+meta version 2
+meta yaml_check -716437882
+meta rows 22
+scalar layer s:control_1948_49
+scalar title s:Who held which areas, 1948-49: the front lines of ISA 6158/1 and, from each agreement's date, the sides of the 1949 armistice lines (true polygons, not hex-snapped)
+scalar meaning s:Military control on a date (owner ruling 2026-10-14), nothing else: not sovereignty, ownership or population. From each armistice the side of the agreement's line, which the agreements themselves say is not a political or territorial boundary (Egypt Art. V.2; Jordan Art. VI.9).
+scalar line s:The true polygons are content/map/control_1948_49.geojson (status draft, owner-verify (sensitivity review before a shareable build)); shown here to the nearest hex edge, up to half a hex (about 4 km) from the true line.
+scalar shown_from s:1948-06-11
+scalar codes s:I Israel; E Egypt, J Jordan, S Syria, V the Arab Liberation Army, M several, A not named (the other side, by holder); c contested; m no-man's land; z demilitarized zone; - no colour (no sourced line)
+item periods id=s:truce1 from=s:1948-06-11 until=s:1948-07-08 legend=s:held line_date=s:1948-07-09 fronts=l:
+item periods id=s:ten_days from=s:1948-07-08 until=s:1948-07-18 legend=s:held line_date=s:1948-07-09 fronts=l:
+item periods id=s:truce2 from=s:1948-07-18 until=s:1948-07-24 legend=s:held line_date=s:1948-07-18 fronts=l:
+item periods id=s:shoter from=s:1948-07-24 until=s:1948-07-26 legend=s:held line_date=s:1948-07-18 fronts=l:
+item periods id=s:truce2b from=s:1948-07-26 until=s:1948-10-15 legend=s:held line_date=s:1948-07-18 fronts=l:
+item periods id=s:yoav from=s:1948-10-15 until=s:1948-10-29 legend=s:held line_date=s:1948-07-18 fronts=l:
+item periods id=s:yoav_hiram from=s:1948-10-29 until=s:1948-10-31 legend=s:held line_date=s:1948-07-18 fronts=l:
+item periods id=s:october from=s:1948-10-31 until=s:1949-02-24 legend=s:held line_date=s:1948-10 fronts=l:
+item periods id=s:arm_1949-02-24 from=s:1949-02-24 until=s:1949-03-23 legend=s:mixed line_date=s:1948-10 fronts=l:egypt
+item periods id=s:arm_1949-03-23 from=s:1949-03-23 until=s:1949-04-03 legend=s:mixed line_date=s:1948-10 fronts=l:egypt,lebanon
+item periods id=s:arm_1949-04-03 from=s:1949-04-03 until=s:1949-05-08 legend=s:mixed line_date=s:1948-10 fronts=l:egypt,jordan,lebanon
+item periods id=s:arm_1949-05-08 from=s:1949-05-08 until=s:1949-05-22 legend=s:mixed line_date=s:1948-10 fronts=l:egypt,jordan,lebanon
+item periods id=s:arm_1949-05-22 from=s:1949-05-22 until=s:1949-07-17 legend=s:mixed line_date=s:1948-10 fronts=l:egypt,jordan,lebanon
+item periods id=s:arm_1949-07-17 from=s:1949-07-17 until=s:1949-07-20 legend=s:mixed line_date=s:1948-10 fronts=l:egypt,jordan,lebanon
+item periods id=s:arm_1949-07-20 from=s:1949-07-20 until=n: legend=s:armistice line_date=s:1948-10 fronts=l:egypt,jordan,lebanon,syria
+tuples hexes 410 15 1 IIIIIIIIIIIIIII;14 2 IIIIIIIIIIIIIII;15 2 IIIIIIIIIIIIIII;14 3 IIIIIIIIIIIIIII;8 4 IIIIIIIIIIIIIII;9 4 VcIIIIIIIIIIIII;10 4 VVVVVVcIIIIIIII;12 4 VVVVVVcIIIIIIII;13 4 IIIIIIIIIIIIIII;8 5 IIIIIIIIIIIIIII;9 5 VVVVVVcIIIIIIII;10 5 VVVVVVcIIIIIIII;11 5 VVVVVVcIIIIIIII;12 5 IIIIIIIIIIIIIII;13 5 SSSSSSSSSSSSSSz;7 6 IIIIIIIIIIIIIII;8 6 VcIIIIIIIIIIIII;9 6 VVVVVVcIIIIIIII;10 6 VVVVVVcIIIIIIII;11 6 VVVVVVcIIIIIIII;12 6 IIIIIIIIIIIIIII;7 7 VcIIIIIIIIIIIII;8 7 VcIIIIIIIIIIIII;9 7 VVVVVVcIIIIIIII;10 7 VVVVVVcIIIIIIII;11 7 IIIIIIIIIIIIIII;5 8 IIIIIIIIIIIIIII;6 8 IIIIIIIIIIIIIII;7 8 VcIIIIIIIIIIIII;8 8 VcIIIIIIIIIIIII;9 8 VcIIIIIIIIIIIII;10 8 VcIIIIIIIIIIIII;12 8 IIIIIIIIIIIIIII;4 9 IIIIIIIIIIIIIII;5 9 IIIIIIIIIIIIIII;6 9 VcIIIIIIIIIIIII;7 9 VcIIIIIIIIIIIII;8 9 VcIIIIIIIIIIIII;9 9 IIIIIIIIIIIIIII;10 9 IIIIIIIIIIIIIII;3 10 IIIIIIIIIIIIIII;4 10 AAAcIIIIIIIIIII;5 10 IIIIIIIIIIIIIII;6 10 IIIIIIIIIIIIIII;7 10 VcIIIIIIIIIIIII;8 10 IIIIIIIIIIIIIII;9 10 IIIIIIIIIIIIIII;10 10 IIIIIIIIIIIIIII;3 11 IIIIIIIIIIIIIII;4 11 IIIIIIIIIIIIIII;5 11 IIIIIIIIIIIIIII;6 11 IIIIIIIIIIIIIII;7 11 IIIIIIIIIIIIIII;8 11 IIIIIIIIIIIIIII;9 11 IIIIIIIIIIIIIII;2 12 IIIIIIIIIIIIIII;3 12 IIIIIIIIIIIIIII;4 12 MMMMMMMMMMJJIII;5 12 MMMMMMMMMMJJJJJ;6 12 IcMMMMMMMMJJJII;7 12 IIIIIIIIIIIIIII;8 12 IIIIIIIIIIIIIII;9 12 IIIIIIIIIIIIIII;1 13 IIIIIIIIIIIIIII;2 13 IIIIIIIIIIIIIII;3 13 MMMMMMMMMMJJIII;4 13 MMMMMMMMMMJJJJJ;5 13 MMMMMMMMMMJJJJJ;6 13 MMMMMMMMMMJJJJJ;7 13 MMMMMMMMMMJJJII;8 13 IIIIIIIIIIIIIII;1 14 IIIIIIIIIIIIIII;2 14 MMMMMMMMMMJIIII;3 14 MMMMMMMMMMJJJJJ;4 14 MMMMMMMMMMJJJJJ;5 14 MMMMMMMMMMJJJJJ;6 14 MMMMMMMMMMJJJJJ;7 14 MMMMMMMMMMJJJJJ;0 15 IIIIIIIIIIIIIII;1 15 IIIIIIIIIIIIIII;2 15 MMMMMMMMMMJJJJJ;3 15 MMMMMMMMMMJJJJJ;4 15 MMMMMMMMMMJJJJJ;5 15 MMMMMMMMMMJJJJJ;6 15 MMMMMMMMMMJJJJJ;7 15 MMMMMMMMMMJJJJJ;-1 16 IIIIIIIIIIIIIII;0 16 IIIIIIIIIIIIIII;1 16 MMMMMMMMMMJIIII;2 16 MMMMMMMMMMJJJJJ;3 16 MMMMMMMMMMJJJJJ;4 16 MMMMMMMMMMJJJJJ;5 16 MMMMMMMMMMJJJJJ;6 16 MMMMMMMMMMJJJJJ;-1 17 IIIIIIIIIIIIIII;0 17 MMMMMMMMMMJJJJJ;1 17 MMMMMMMMMMJJJJJ;2 17 MMMMMMMMMMJJJJJ;3 17 MMMMMMMMMMJJJJJ;4 17 MMMMMMMMMMJJJJJ;5 17 MMMMMMMMMMJJJJJ;6 17 MMMMMMMMMMJJJJJ;-2 18 IIIIIIIIIIIIIII;-1 18 McIIIIIIIIIIIII;0 18 MMMMMMMMMMJJJJJ;1 18 MMMMMMMMMMJJJJJ;2 18 MMMMMMMMMMJJJJJ;3 18 MMMMMMMMMMJJJJJ;4 18 MMMMMMMMMMJJJJJ;5 18 MMMMMMMMMMJJJJJ;-3 19 IIIIIIIIIIIIIII;-2 19 IIIIIIIIIIIIIII;-1 19 MMMMMMMMMMJJJII;0 19 MMMMMMMMMMJJJJJ;1 19 MMMMMMMMMMJJJJJ;2 19 MMMMMMMMMMJJJJJ;3 19 MMMMMMMMMMJJJJJ;4 19 MMMMMMMMMMJJJJJ;5 19 MMMMMMMMMMJJJJJ;-4 20 IIIIIIIIIIIIIII;-3 20 IIIIIIIIIIIIIII;-2 20 McIIIIIIIIIIIII;-1 20 MMMMMMMMMMJJJJJ;0 20 MMMMMMMMMMJJJJJ;1 20 MMMMMMMMMMJJJJJ;2 20 MMMMMMMMMMJJJJJ;3 20 MMMMMMMMMMJJJJJ;4 20 MMMMMMMMMMJJJJJ;-5 21 IIIIIIIIIIIIIII;-4 21 IIIIIIIIIIIIIII;-3 21 McIIIIIIIIIIIII;-2 21 McIIIIIIIIIIIII;-1 21 MMMMMMMMMMJJJJJ;0 21 MMMMMMMMMMJJJJJ;1 21 MMMMMMMMMMJJJJJ;2 21 MMMMMMMMMMJJJJJ;3 21 MMMMMMMMMMJJJJJ;4 21 MMMMMMMMMMJJJJJ;-5 22 IIIIIIIIIIIIIII;-4 22 IIIIIIIIIIIIIII;-3 22 IIIIIIIIIIIIIII;-2 22 MMMMMMMMMMJJJJJ;-1 22 MMMMMMMMMMJJJJJ;0 22 MMMMMMMMMMJJJJJ;1 22 MMMMMMMMMMJJJJJ;2 22 MMMMMMMMMMJJJJJ;3 22 MMMMMMMMMMJJJJJ;-6 23 EEEEEEEEIIIIIII;-5 23 IIIIIIIIIIIIIII;-4 23 IIIIIIIIIIIIIII;-3 23 IIIIIIIIIIIIIII;-2 23 McIIIIIIIIIIIII;-1 23 IIIIIIIIIIIIIII;0 23 MMMMMMMMMMJJJJJ;1 23 MMMMMMMMMMJJJJJ;2 23 MMMMMMMMMMJJJJJ;3 23 MMMMMMMMMMJJJJJ;-7 24 EEEEEEEEIIIIIII;-6 24 IIIIIIIIIIIIIII;-5 24 IIIIIIIIIIIIIII;-4 24 MMMMMccIIIIIIII;-3 24 MMMMMccIIIIIIII;-2 24 MMMMMMMMMMIIIII;-1 24 MMMMMMMMMMJJJJJ;0 24 MMMMMMMMMMJJJJJ;1 24 MMMMMMMMMMJJJJJ;-8 25 EEEEEEEEIIIIIII;-7 25 MMEEEEEEIIIIIII;-6 25 McIIIIIIIIIIIII;-5 25 McIIIIIIIIIIIII;-4 25 MMMMMMMMMMIIIII;-3 25 MMMMMMMMMMJJJJJ;-2 25 MMMMMMMMMMJJJJJ;-1 25 MMMMMMMMMMJJJJJ;0 25 MMMMMMMMMMJJJJJ;1 25 MMMMMMMMMMJJJJJ;-9 26 EEEEEEEEIIIIIII;-8 26 IEEEEIIIIIIIIII;-7 26 MMMMMMMEIIIIIII;-6 26 MMMMMccIIIIIIII;-5 26 MMMMMMMMMMIIIII;-4 26 MMMMMMMMMMJJJJJ;-3 26 MMMMMMMMMMJJJJJ;-2 26 MMMMMMMMMMJJJJJ;-1 26 MMMMMMMMMMJJJJJ;0 26 MMMMMMMMMMJJJJJ;-11 27 EEEEEEEEEEEEEEE;-10 27 EEEEEEEEEEEEEEE;-9 27 IIIIIIIIIIIIIII;-8 27 IIIIIIIIIIIIIII;-7 27 MMMMMccIIIIIIII;-6 27 MMMMMMMMMMIIIII;-5 27 MMMMMMMMMMJJJJJ;-4 27 MMMMMMMMMMJJJJJ;-3 27 MMMMMMMMMMJJJJJ;-2 27 MMMMMMMMMMJJJJJ;-1 27 MMMMMMMMMMJJJJJ;-12 28 EEEEEEEEEEEEEEE;-11 28 EEEEEEEE-------;-10 28 IIIIIIIIIIIIIII;-9 28 IIIIIIIIIIIIIII;-8 28 IIIIIIIIIIIIIII;-7 28 MMMMMMMMMMIIIII;-6 28 MMMMMMMMMMJJJJJ;-5 28 MMMMMMMMMMJJJJJ;-4 28 MMMMMMMMMMJJJJJ;-3 28 MMMMMMMMMMJJJJJ;-2 28 MMMMMMMMMMJJJJJ;-1 28 MMMMMMMMMMIIIII;-13 29 EEEEEEEEEEEEEEE;-12 29 EEEEEEEE-------;-11 29 IIIIIIIIIIIIIII;-10 29 IIIIIIIIIIIIIII;-9 29 IIIIIIIIIIIIIII;-8 29 IIIIIIIIIIIIIII;-7 29 MMMMMMMMMMJJJJJ;-6 29 MMMMMMMMMMJJJJJ;-5 29 MMMMMMMMMMJJJJJ;-4 29 MMMMMMMMMMJJJJJ;-3 29 MMMMMMMMMMIIIII;-2 29 MMMMMMMMMMIIIII;-14 30 EEEEEEEEEEEEEEE;-13 30 EEEEEEEEIIIIIII;-12 30 IIIIIIIIIIIIIII;-11 30 IIIIIIIIIIIIIII;-10 30 IIIIIIIIIIIIIII;-9 30 IIIIIIIIIIIIIII;-8 30 MMMMMccIIIIIIII;-7 30 MMMMMMMMMMIIIII;-6 30 MMMMMMMMMMIIIII;-5 30 MMMMMMMMMMIIIII;-4 30 MMMMMMMMMMIIIII;-3 30 MMMMMMMMMMIIIII;-2 30 MMMMMMMMMMIIIII;-15 31 EEEEEEEEEEEEEEE;-14 31 IIIIIIIIIIIIIII;-13 31 IIIIIIIIIIIIIII;-12 31 IIIIIIIIIIIIIII;-11 31 IIIIIIIIIIIIIII;-10 31 IIIIIIIIIIIIIII;-9 31 MMMMMccIIIIIIII;-8 31 MMMMMccIIIIIIII;-7 31 MMMMMMMMMMIIIII;-6 31 MMMMMMMMMMIIIII;-5 31 MMMMMMMMMMIIIII;-4 31 MMMMMMMMMMIIIII;-3 31 MMMMMMMMMMIIIII;-15 32 EEEEEEEEIIIIIII;-14 32 IIIIIIIIIIIIIII;-13 32 IIIIIIIIIIIIIII;-12 32 IIIIIIIIIIIIIII;-11 32 IIIIIIIIIIIIIII;-10 32 IIIIIIIIIIIIIII;-9 32 IIIIIIIIIIIIIII;-8 32 MMMMMMMMMMIIIII;-7 32 MMMMMMMMMMIIIII;-6 32 MMMMMMMMMMIIIII;-5 32 MMMMMMMMMMIIIII;-4 32 MMMMMMMMMMIIIII;-15 33 EEEEEEEEIIIIIII;-14 33 IIIIIIIIIIIIIII;-13 33 IIIIIIIIIIIIIII;-12 33 IIIIIIIIIIIIIII;-11 33 IIIIIIIIIIIIIII;-10 33 IIIIIIIIIIIIIII;-9 33 MMMMMMMMMMIIIII;-8 33 MMMMMMMMMMIIIII;-7 33 MMMMMMMMMMIIIII;-6 33 MMMMMMMMMMIIIII;-5 33 MMMMMMMMMMIIIII;-4 33 MMMMMMMMMMIIIII;-15 34 ----------IIIII;-14 34 ----------IIIII;-13 34 ----------IIIII;-12 34 ----------IIIII;-11 34 ----------IIIII;-10 34 ----------IIIII;-9 34 ----------IIIII;-8 34 ----------IIIII;-7 34 ----------IIIII;-6 34 ----------IIIII;-5 34 ----------IIIII;-4 34 ----------IIIII;-15 35 --------zzIIIII;-14 35 ----------IIIII;-13 35 ----------IIIII;-12 35 ----------IIIII;-11 35 ----------IIIII;-10 35 ----------IIIII;-9 35 ----------IIIII;-8 35 ----------IIIII;-7 35 ----------IIIII;-6 35 ----------IIIII;-5 35 ----------IIIII;-16 36 --------zzzzzzz;-15 36 --------zzzzzzz;-14 36 ----------IIIII;-13 36 ----------IIIII;-12 36 ----------IIIII;-11 36 ----------IIIII;-10 36 ----------IIIII;-9 36 ----------IIIII;-8 36 ----------IIIII;-7 36 ----------IIIII;-6 36 ----------IIIII;-16 37 --------zzzzzzz;-15 37 --------zzzzzzz;-14 37 ----------IIIII;-13 37 ----------IIIII;-12 37 ----------IIIII;-11 37 ----------IIIII;-10 37 ----------IIIII;-9 37 ----------IIIII;-8 37 ----------IIIII;-7 37 ----------IIIII;-16 38 --------zzzzzzz;-15 38 ----------IIIII;-14 38 ----------IIIII;-13 38 ----------IIIII;-12 38 ----------IIIII;-11 38 ----------IIIII;-10 38 ----------IIIII;-9 38 ----------IIIII;-8 38 ----------IIIII;-7 38 ----------IIIII;-16 39 ----------IIIII;-15 39 ----------IIIII;-14 39 ----------IIIII;-13 39 ----------IIIII;-12 39 ----------IIIII;-11 39 ----------IIIII;-10 39 ----------IIIII;-9 39 ----------IIIII;-8 39 ----------IIIII;-16 40 ----------IIIII;-15 40 ----------IIIII;-14 40 ----------IIIII;-13 40 ----------IIIII;-12 40 ----------IIIII;-11 40 ----------IIIII;-10 40 ----------IIIII;-9 40 ----------IIIII;-17 41 ----------IIIII;-16 41 ----------IIIII;-15 41 ----------IIIII;-14 41 ----------IIIII;-13 41 ----------IIIII;-12 41 ----------IIIII;-11 41 ----------IIIII;-10 41 ----------IIIII;-17 42 ----------IIIII;-16 42 ----------IIIII;-15 42 ----------IIIII;-14 42 ----------IIIII;-13 42 ----------IIIII;-12 42 ----------IIIII;-11 42 ----------IIIII;-17 43 ----------IIIII;-16 43 ----------IIIII;-15 43 ----------IIIII;-14 43 ----------IIIII;-13 43 ----------IIIII;-12 43 ----------IIIII;-11 43 ----------IIIII;-17 44 ----------IIIII;-16 44 ----------IIIII;-15 44 ----------IIIII;-14 44 ----------IIIII;-13 44 ----------IIIII;-12 44 ----------IIIII;-17 45 ----------IIIII;-16 45 ----------IIIII;-15 45 ----------IIIII;-14 45 ----------IIIII;-13 45 ----------IIIII;-12 45 ----------IIIII;-17 46 ----------IIIII;-16 46 ----------IIIII;-15 46 ----------IIIII;-14 46 ----------IIIII;-13 46 ----------IIIII;-18 47 ----------IIIII;-17 47 ----------IIIII;-16 47 ----------IIIII;-15 47 ----------IIIII;-14 47 ----------IIIII;-13 47 ----------IIIII;-18 48 ----------IIIII;-17 48 ----------IIIII;-16 48 ----------IIIII;-15 48 ----------IIIII;-14 48 ----------IIIII;-18 49 ----------IIIII;-17 49 ----------IIIII;-16 49 ----------IIIII;-15 49 ----------IIIII;-18 50 ----------IIIII;-17 50 ----------IIIII;-16 50 ----------IIIII;-18 51 ----------IIIII;-17 51 ----------IIIII;-19 52 ----------IIIII;-18 52 ----------IIIII;-17 52 ----------IIIII;-19 53 ----------IIIII;-18 53 ----------IIIII;-19 54 ----------IIIII;-18 54 ----------IIIII;-19 55 ----------IIIII;-20 56 ----------IIIII
+meta body_check -863194386
diff --git a/content/map/subdistrict_hexes_1948.tsv b/content/map/subdistrict_hexes_1948.tsv
new file mode 100644
index 000000000..77ebed6b1
--- /dev/null
+++ b/content/map/subdistrict_hexes_1948.tsv
@@ -0,0 +1,34 @@
+# Generated by tools/regions_bake.py from subdistrict_hexes_1948.yaml. Do not edit: edit the YAML (or rerun its own tool) and
+# rerun this one. The runtime form the map reads at boot (display only, outside the content hash).
+meta version 2
+meta yaml_check 688267280
+meta rows 28
+scalar layer s:subdistricts_1948
+scalar title s:Sub-districts of Mandatory Palestine in force on 15 May 1948 (true lines, not hex-snapped)
+scalar line s:The true lines are the Survey of Palestine map of the 1947 Administrative Divisions Schedule (content/map/subdistricts_1948.geojson, status sensitivity-reviewed); shown here to the nearest hex edge, up to half a hex (about 4 km) from the true line.
+scalar label s:Mandate sub-districts, 1947
+scalar shown_from s:1948-05-15
+scalar shown_until n:
+item fronts key=s:egypt until=s:1949-02-24
+item fronts key=s:lebanon until=s:1949-03-23
+item fronts key=s:jordan until=s:1949-04-03
+item fronts key=s:syria until=s:1949-07-20
+item regions id=s:1 key=s:acre name=s:Acre Sub-District district=s:Galilee District style=s:primary
+item regions id=s:2 key=s:beisan name=s:Beisan Sub-District district=s:Galilee District style=s:primary
+item regions id=s:3 key=s:nazareth name=s:Nazareth Sub-District district=s:Galilee District style=s:primary
+item regions id=s:4 key=s:safad name=s:Safad Sub-District district=s:Galilee District style=s:primary
+item regions id=s:5 key=s:tiberias name=s:Tiberias Sub-District district=s:Galilee District style=s:primary
+item regions id=s:6 key=s:haifa name=s:Haifa Sub-District district=s:Haifa District style=s:primary
+item regions id=s:7 key=s:jenin name=s:Jenin Sub-District district=s:Samaria District style=s:primary
+item regions id=s:8 key=s:nablus name=s:Nablus Sub-District district=s:Samaria District style=s:primary
+item regions id=s:9 key=s:tulkarm name=s:Tulkarm Sub-District district=s:Samaria District style=s:primary
+item regions id=s:10 key=s:hebron name=s:Hebron Sub-District district=s:Jerusalem District style=s:primary
+item regions id=s:11 key=s:jerusalem name=s:Jerusalem Sub-District district=s:Jerusalem District style=s:primary
+item regions id=s:12 key=s:ramallah name=s:Ramallah Sub-District district=s:Jerusalem District style=s:primary
+item regions id=s:13 key=s:jaffa name=s:Jaffa Sub-District district=s:Lydda District style=s:primary
+item regions id=s:14 key=s:ramle name=s:Ramle Sub-District district=s:Lydda District style=s:primary
+item regions id=s:15 key=s:gaza name=s:Gaza Sub-District district=s:Gaza District style=s:primary
+item regions id=s:16 key=s:beersheba name=s:Beersheba Sub-District district=s:Gaza District style=s:primary
+item regions id=s:17 key=s:outside name=s:Outside Mandatory Palestine district=s: style=s:none
+tuples hexes 870 12 0 17;13 0 17;14 0 17;15 0 17;16 0 17;17 0 17;18 0 17;11 1 17;12 1 17;13 1 17;14 1 17;15 1 4;16 1 17;17 1 17;18 1 17;11 2 17;12 2 17;13 2 17;14 2 4;15 2 4;16 2 17;17 2 17;9 3 17;10 3 17;11 3 17;12 3 17;13 3 17;14 3 4;15 3 17;16 3 17;17 3 17;8 4 1;9 4 1;10 4 1;11 4 17;12 4 4;13 4 4;14 4 17;15 4 17;16 4 17;8 5 1;9 5 1;10 5 4;11 5 4;12 5 4;13 5 4;14 5 17;15 5 17;16 5 17;7 6 1;8 6 1;9 6 1;10 6 1;11 6 4;12 6 4;13 6 17;14 6 17;15 6 17;7 7 1;8 7 1;9 7 1;10 7 5;11 7 5;13 7 17;14 7 17;15 7 17;5 8 6;6 8 6;7 8 6;8 8 1;9 8 3;10 8 5;12 8 5;13 8 17;14 8 17;4 9 6;5 9 6;6 9 6;7 9 3;8 9 3;9 9 5;10 9 5;12 9 17;13 9 17;14 9 17;3 10 6;4 10 6;5 10 6;6 10 3;7 10 3;8 10 3;9 10 5;10 10 5;11 10 17;12 10 17;13 10 17;3 11 6;4 11 6;5 11 6;6 11 3;7 11 3;8 11 2;9 11 2;10 11 17;11 11 17;12 11 17;13 11 17;2 12 6;3 12 6;4 12 7;5 12 7;6 12 7;7 12 2;8 12 2;9 12 2;10 12 17;11 12 17;12 12 17;1 13 6;2 13 6;3 13 9;4 13 7;5 13 7;6 13 7;7 13 7;8 13 2;9 13 17;10 13 17;11 13 17;12 13 17;1 14 9;2 14 9;3 14 9;4 14 7;5 14 7;6 14 7;7 14 8;8 14 17;9 14 17;10 14 17;11 14 17;0 15 9;1 15 9;2 15 9;3 15 7;4 15 7;5 15 8;6 15 8;7 15 8;8 15 17;9 15 17;10 15 17;11 15 17;-1 16 9;0 16 9;1 16 9;2 16 9;3 16 8;4 16 8;5 16 8;6 16 8;7 16 17;8 16 17;9 16 17;10 16 17;-1 17 13;0 17 9;1 17 9;2 17 8;3 17 8;4 17 8;5 17 8;6 17 8;7 17 17;8 17 17;9 17 17;10 17 17;-2 18 13;-1 18 9;0 18 9;1 18 8;2 18 8;3 18 8;4 18 8;5 18 8;6 18 17;7 18 17;8 18 17;9 18 17;-3 19 13;-2 19 13;-1 19 14;0 19 8;1 19 12;2 19 8;3 19 8;4 19 8;5 19 8;6 19 17;7 19 17;8 19 17;9 19 17;-4 20 13;-3 20 13;-2 20 14;-1 20 14;0 20 12;1 20 12;2 20 12;3 20 12;4 20 8;5 20 17;6 20 17;7 20 17;8 20 17;-5 21 14;-4 21 14;-3 21 14;-2 21 14;-1 21 12;0 21 12;1 21 12;2 21 12;3 21 11;4 21 11;5 21 17;6 21 17;7 21 17;8 21 17;-5 22 14;-4 22 14;-3 22 14;-2 22 14;-1 22 11;0 22 11;1 22 11;2 22 12;3 22 11;4 22 17;5 22 17;6 22 17;7 22 17;-6 23 15;-5 23 14;-4 23 14;-3 23 14;-2 23 11;-1 23 11;0 23 11;1 23 11;2 23 11;3 23 11;4 23 17;5 23 17;6 23 17;7 23 17;-7 24 15;-6 24 15;-5 24 10;-4 24 11;-3 24 11;-2 24 11;-1 24 11;0 24 11;1 24 11;4 24 17;5 24 17;6 24 17;-8 25 15;-7 25 15;-6 25 15;-5 25 10;-4 25 10;-3 25 10;-2 25 11;-1 25 11;0 25 11;1 25 11;3 25 17;4 25 17;5 25 17;6 25 17;-9 26 15;-8 26 15;-7 26 15;-6 26 10;-5 26 10;-4 26 10;-3 26 10;-2 26 10;-1 26 11;0 26 11;2 26 17;3 26 17;4 26 17;5 26 17;-11 27 15;-10 27 15;-9 27 15;-8 27 16;-7 27 16;-6 27 10;-5 27 10;-4 27 10;-3 27 10;-2 27 10;-1 27 11;2 27 17;3 27 17;4 27 17;5 27 17;-12 28 15;-11 28 15;-10 28 15;-9 28 16;-8 28 16;-7 28 10;-6 28 10;-5 28 10;-4 28 10;-3 28 10;-2 28 10;-1 28 10;2 28 17;3 28 17;4 28 17;-13 29 15;-12 29 16;-11 29 16;-10 29 16;-9 29 16;-8 29 16;-7 29 16;-6 29 10;-5 29 10;-4 29 10;-3 29 10;-2 29 10;1 29 17;2 29 17;3 29 17;4 29 17;-15 30 17;-14 30 15;-13 30 16;-12 30 16;-11 30 16;-10 30 16;-9 30 16;-8 30 16;-7 30 16;-6 30 10;-5 30 10;-4 30 10;-3 30 10;-2 30 10;-1 30 17;0 30 17;1 30 17;2 30 17;3 30 17;-15 31 15;-14 31 16;-13 31 16;-12 31 16;-11 31 16;-10 31 16;-9 31 16;-8 31 16;-7 31 16;-6 31 16;-5 31 16;-4 31 10;-3 31 10;-2 31 17;-1 31 17;0 31 17;1 31 17;2 31 17;3 31 17;-16 32 17;-15 32 16;-14 32 16;-13 32 16;-12 32 16;-11 32 16;-10 32 16;-9 32 16;-8 32 16;-7 32 16;-6 32 16;-5 32 16;-4 32 16;-1 32 17;0 32 17;1 32 17;2 32 17;-16 33 17;-15 33 16;-14 33 16;-13 33 16;-12 33 16;-11 33 16;-10 33 16;-9 33 16;-8 33 16;-7 33 16;-6 33 16;-5 33 16;-4 33 16;-2 33 17;-1 33 17;0 33 17;1 33 17;2 33 17;-17 34 17;-16 34 17;-15 34 16;-14 34 16;-13 34 16;-12 34 16;-11 34 16;-10 34 16;-9 34 16;-8 34 16;-7 34 16;-6 34 16;-5 34 16;-4 34 16;-3 34 17;-2 34 17;-1 34 17;0 34 17;1 34 17;-17 35 17;-16 35 17;-15 35 16;-14 35 16;-13 35 16;-12 35 16;-11 35 16;-10 35 16;-9 35 16;-8 35 16;-7 35 16;-6 35 16;-5 35 16;-4 35 17;-3 35 17;-2 35 17;-1 35 17;0 35 17;1 35 17;-18 36 17;-17 36 17;-16 36 16;-15 36 16;-14 36 16;-13 36 16;-12 36 16;-11 36 16;-10 36 16;-9 36 16;-8 36 16;-7 36 16;-6 36 16;-5 36 17;-4 36 17;-3 36 17;-2 36 17;-1 36 17;0 36 17;-18 37 17;-17 37 17;-16 37 16;-15 37 16;-14 37 16;-13 37 16;-12 37 16;-11 37 16;-10 37 16;-9 37 16;-8 37 16;-7 37 16;-6 37 17;-5 37 17;-4 37 17;-3 37 17;-2 37 17;-1 37 17;0 37 17;-19 38 17;-18 38 17;-17 38 17;-16 38 16;-15 38 16;-14 38 16;-13 38 16;-12 38 16;-11 38 16;-10 38 16;-9 38 16;-8 38 16;-7 38 16;-6 38 17;-5 38 17;-4 38 17;-3 38 17;-2 38 17;-1 38 17;-19 39 17;-18 39 17;-17 39 17;-16 39 16;-15 39 16;-14 39 16;-13 39 16;-12 39 16;-11 39 16;-10 39 16;-9 39 16;-8 39 16;-7 39 17;-6 39 17;-5 39 17;-4 39 17;-3 39 17;-2 39 17;-1 39 17;-20 40 17;-19 40 17;-18 40 17;-17 40 17;-16 40 16;-15 40 16;-14 40 16;-13 40 16;-12 40 16;-11 40 16;-10 40 16;-9 40 16;-8 40 17;-7 40 17;-6 40 17;-5 40 17;-4 40 17;-3 40 17;-2 40 17;-20 41 17;-19 41 17;-18 41 17;-17 41 16;-16 41 16;-15 41 16;-14 41 16;-13 41 16;-12 41 16;-11 41 16;-10 41 16;-9 41 17;-8 41 17;-7 41 17;-6 41 17;-5 41 17;-4 41 17;-3 41 17;-2 41 17;-21 42 17;-20 42 17;-19 42 17;-18 42 17;-17 42 16;-16 42 16;-15 42 16;-14 42 16;-13 42 16;-12 42 16;-11 42 16;-10 42 17;-9 42 17;-8 42 17;-7 42 17;-6 42 17;-5 42 17;-4 42 17;-3 42 17;-21 43 17;-20 43 17;-19 43 17;-18 43 17;-17 43 16;-16 43 16;-15 43 16;-14 43 16;-13 43 16;-12 43 16;-11 43 16;-10 43 17;-9 43 17;-8 43 17;-7 43 17;-6 43 17;-5 43 17;-4 43 17;-3 43 17;-22 44 17;-21 44 17;-20 44 17;-19 44 17;-18 44 17;-17 44 16;-16 44 16;-15 44 16;-14 44 16;-13 44 16;-12 44 16;-11 44 17;-10 44 17;-9 44 17;-8 44 17;-7 44 17;-6 44 17;-5 44 17;-4 44 17;-22 45 17;-21 45 17;-20 45 17;-19 45 17;-18 45 17;-17 45 16;-16 45 16;-15 45 16;-14 45 16;-13 45 16;-12 45 16;-11 45 17;-10 45 17;-9 45 17;-8 45 17;-7 45 17;-6 45 17;-5 45 17;-4 45 17;-23 46 17;-22 46 17;-21 46 17;-20 46 17;-19 46 17;-18 46 17;-17 46 16;-16 46 16;-15 46 16;-14 46 16;-13 46 16;-12 46 17;-11 46 17;-10 46 17;-9 46 17;-8 46 17;-7 46 17;-6 46 17;-5 46 17;-23 47 17;-22 47 17;-21 47 17;-20 47 17;-19 47 17;-18 47 16;-17 47 16;-16 47 16;-15 47 16;-14 47 16;-13 47 16;-12 47 17;-11 47 17;-10 47 17;-9 47 17;-8 47 17;-7 47 17;-6 47 17;-5 47 17;-24 48 17;-23 48 17;-22 48 17;-21 48 17;-20 48 17;-19 48 17;-18 48 16;-17 48 16;-16 48 16;-15 48 16;-14 48 16;-13 48 17;-12 48 17;-11 48 17;-10 48 17;-9 48 17;-8 48 17;-7 48 17;-6 48 17;-24 49 17;-23 49 17;-22 49 17;-21 49 17;-20 49 17;-19 49 17;-18 49 16;-17 49 16;-16 49 16;-15 49 16;-14 49 17;-13 49 17;-12 49 17;-11 49 17;-10 49 17;-9 49 17;-8 49 17;-7 49 17;-6 49 17;-25 50 17;-24 50 17;-23 50 17;-22 50 17;-21 50 17;-20 50 17;-19 50 17;-18 50 16;-17 50 16;-16 50 16;-15 50 17;-14 50 17;-13 50 17;-12 50 17;-11 50 17;-10 50 17;-9 50 17;-8 50 17;-7 50 17;-25 51 17;-24 51 17;-23 51 17;-22 51 17;-21 51 17;-20 51 17;-19 51 17;-18 51 16;-17 51 16;-16 51 17;-15 51 17;-14 51 17;-13 51 17;-12 51 17;-11 51 17;-10 51 17;-9 51 17;-8 51 17;-7 51 17;-26 52 17;-25 52 17;-24 52 17;-23 52 17;-22 52 17;-21 52 17;-20 52 17;-19 52 16;-18 52 16;-17 52 16;-16 52 17;-15 52 17;-14 52 17;-13 52 17;-12 52 17;-11 52 17;-10 52 17;-9 52 17;-8 52 17;-26 53 17;-25 53 17;-24 53 17;-23 53 17;-22 53 17;-21 53 17;-20 53 17;-19 53 16;-18 53 16;-17 53 17;-16 53 17;-15 53 17;-14 53 17;-13 53 17;-12 53 17;-11 53 17;-10 53 17;-9 53 17;-8 53 17;-27 54 17;-26 54 17;-25 54 17;-24 54 17;-23 54 17;-22 54 17;-21 54 17;-20 54 17;-19 54 16;-18 54 16;-17 54 17;-16 54 17;-15 54 17;-14 54 17;-13 54 17;-12 54 17;-11 54 17;-10 54 17;-9 54 17;-27 55 17;-26 55 17;-25 55 17;-24 55 17;-23 55 17;-22 55 17;-21 55 17;-20 55 17;-19 55 16;-18 55 17;-17 55 17;-16 55 17;-15 55 17;-14 55 17;-13 55 17;-12 55 17;-11 55 17;-10 55 17;-9 55 17;-28 56 17;-27 56 17;-26 56 17;-25 56 17;-24 56 17;-23 56 17;-22 56 17;-21 56 17;-20 56 16;-19 56 17;-18 56 17;-17 56 17;-16 56 17;-15 56 17;-14 56 17;-13 56 17;-12 56 17;-11 56 17;-10 56 17;-28 57 17;-27 57 17;-26 57 17;-25 57 17;-24 57 17;-23 57 17;-22 57 17;-21 57 17;-19 57 17;-18 57 17;-17 57 17;-16 57 17;-15 57 17;-14 57 17;-13 57 17;-12 57 17;-11 57 17;-10 57 17
+meta body_check 1658431546
diff --git a/tools/README.md b/tools/README.md
index 8a35aa81a..2a98d380f 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -18,6 +18,10 @@ Offline data tools (uv inline-script Python). Run from the repo root.
into `tools/.cache/pal250k-1946/`, not committed): it reads the hand-written routes, sources and waypoints in
`content/map/routes_1948.yaml` and writes the traced lines to `content/map/route_paths_1948.yaml` (committed; the map
draws it, the sim never reads it). `--preview` writes each traced segment over the map for checking by eye.
+- `regions_bake.py [--check]` bakes the region files `content/map/subdistrict_hexes_1948.yaml`,
+ `armistice_hexes_1949.yaml` and `control_hexes_1948_49.yaml` into `.tsv` runtime forms beside them (committed), which
+ the map reads at boot (issue #321). Rerun it after `borders_bake.py`, `armistice_bake.py` or `control_bake.py`
+ rewrites one: `test_regions_bake.py` fails a stale file, naming it, and `--check` does the same.
- `route_paths_bake.py [--check]` bakes `content/map/route_paths_1948.yaml` into `content/map/route_paths_1948.tsv`
(committed), the compact runtime form the map reads at boot (issue #321). Rerun it after `routes_1948.py`:
`test_route_paths_bake.py` fails a stale bake, and `--check` does the same.
diff --git a/tools/regions_bake.py b/tools/regions_bake.py
new file mode 100644
index 000000000..1bf09ffab
--- /dev/null
+++ b/tools/regions_bake.py
@@ -0,0 +1,149 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = ["pyyaml==6.0.3"]
+# ///
+"""Bakes the map's region files into compact runtime forms the player reads at boot (issue #321):
+
+ content/map/subdistrict_hexes_1948.yaml -> subdistrict_hexes_1948.tsv (Subdistricts1948)
+ content/map/armistice_hexes_1949.yaml -> armistice_hexes_1949.tsv (Armistice1949)
+ content/map/control_hexes_1948_49.yaml -> control_hexes_1948_49.tsv (Control1948)
+
+The boot budget is the reason (docs/visual-v1.md, "Issue #321"): YamlDotNet over the three files cost about 135 ms at
+cpu 4 between the map and the start screen, and the map's own read of the sub-districts 24 ms more. The YAML files stay
+the source of truth (tools/borders_bake.py, tools/armistice_bake.py and tools/control_bake.py write them) and still ship; each runtime file
+carries its YAML's FNV-1a check (RouteRibbonFile.Check) and this layout's version, and the player reads the YAML instead,
+with a warning, when either does not match, when the file is cut short or when a row is malformed (RegionsRuntime.Read).
+
+The layout is the YAML's own shape, generically, so each class keeps its checks (it builds the same rows from either
+source). One row per line, tab-separated:
+
+ meta version <VERSION>
+ meta yaml_check <signed int32>
+ meta rows <number of data rows>
+ scalar <key> <value> a top-level scalar, or a list of plain scalars
+ item <table> <field>=<value> ... one mapping of a top-level list of mappings
+ tuples <table> <count> <a b c;a b c;...> a top-level list of lists (each element a plain token)
+ empty <key> an empty top-level list
+ meta body_check <signed int32> the last row: FNV-1a over the data rows' UTF-8, each with its '\\n'
+
+A value is "s:" and the scalar's own text (backslash, tab, CR and line feed escaped as \\\\, \\t, \\r, \\n), "n:" for a
+plain null (empty, ~, null, Null or NULL, as YamlDotNet reads one), or "l:" and a comma-separated list of tokens. The
+bake works on the YAML's nodes (yaml.compose), not on PyYAML's resolved values, so every scalar keeps the text
+YamlDotNet sees: YAML 1.1's re-typing (yes, Off, 1_0, 1:30, 0x0F, a datetime) never reaches the runtime file (review of
+#601). The classes then read integers and booleans from that text as their YAML path does. A token holds no space,
+comma, semicolon, tab or line break; the bake refuses one that does.
+
+Usage: uv run tools/regions_bake.py [--check]
+--check exits 1 when a committed runtime file differs from a fresh bake (pytest runs the same comparison:
+tools/tests/test_regions_bake.py).
+"""
+import argparse
+import struct
+import sys
+from pathlib import Path
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[1]
+MAP = ROOT / "content" / "map"
+FILES = ["subdistrict_hexes_1948", "armistice_hexes_1949", "control_hexes_1948_49"]
+VERSION = 2 # RegionsRuntime.Version (2: every scalar as its own text, review of #601)
+
+
+def fnv1a(data: bytes) -> int:
+ """RouteRibbonFile.Check: FNV-1a over the bytes, as a signed int32."""
+ h = 2166136261
+ for b in data:
+ h = ((h ^ b) * 16777619) & 0xFFFFFFFF
+ return struct.unpack("<i", struct.pack("<I", h))[0]
+
+
+def _escape(text: str) -> str:
+ return text.replace("\\", "\\\\").replace("\t", "\\t").replace("\r", "\\r").replace("\n", "\\n")
+
+
+NULLS = {"", "~", "null", "Null", "NULL"}
+
+
+def _scalar(node, where: str):
+ if not isinstance(node, yaml.ScalarNode):
+ raise ValueError(f"{where}: not a scalar")
+ return None if node.style is None and node.value in NULLS else node.value
+
+
+def _token(node, where: str) -> str:
+ text = _scalar(node, where)
+ if not text or any(c in text for c in " ,;\t\r\n"):
+ raise ValueError(f"{where}: {text!r} is not a plain token")
+ return text
+
+
+def _value(node, where: str) -> str:
+ if isinstance(node, yaml.SequenceNode):
+ return "l:" + ",".join(_token(v, where) for v in node.value)
+ text = _scalar(node, where)
+ return "n:" if text is None else "s:" + _escape(text)
+
+
+def bake(name: str, data: bytes) -> str:
+ """The runtime file for a region YAML's bytes: deterministic, so a fresh bake equals the committed file."""
+ root = yaml.compose(data.decode("utf-8"))
+ if not isinstance(root, yaml.MappingNode):
+ raise ValueError(f"{name}.yaml: not a mapping")
+ rows = []
+ for key_node, value in root.value:
+ key = _token(key_node, f"{name}.yaml")
+ where = f"{name}.yaml: {key}"
+ if isinstance(value, yaml.SequenceNode) and not value.value:
+ rows.append(f"empty\t{key}")
+ elif isinstance(value, yaml.SequenceNode) and all(isinstance(v, yaml.MappingNode) for v in value.value):
+ for i, item in enumerate(value.value):
+ fields = []
+ for k, v in item.value:
+ field = _token(k, f"{where}[{i}]")
+ if "=" in field:
+ raise ValueError(f"{where}[{i}]: field name {field!r} holds '='")
+ fields.append(f"{field}={_value(v, f'{where}[{i}].{field}')}")
+ rows.append("\t".join(["item", key] + fields))
+ elif isinstance(value, yaml.SequenceNode) and all(isinstance(v, yaml.SequenceNode) for v in value.value):
+ body = ";".join(" ".join(_token(t, f"{where}[{i}]") for t in v.value) for i, v in enumerate(value.value))
+ rows.append(f"tuples\t{key}\t{len(value.value)}\t{body}")
+ elif isinstance(value, (yaml.ScalarNode, yaml.SequenceNode)):
+ rows.append(f"scalar\t{key}\t{_value(value, where)}")
+ else:
+ raise ValueError(f"{where}: no runtime form for a {type(value).__name__}")
+ out = [
+ f"# Generated by tools/regions_bake.py from {name}.yaml. Do not edit: edit the YAML (or rerun its own tool) and",
+ "# rerun this one. The runtime form the map reads at boot (display only, outside the content hash).",
+ f"meta\tversion\t{VERSION}",
+ f"meta\tyaml_check\t{fnv1a(data)}",
+ f"meta\trows\t{len(rows)}",
+ ]
+ out += rows
+ out.append(f"meta\tbody_check\t{fnv1a(''.join(r + chr(10) for r in rows).encode('utf-8'))}")
+ return "\n".join(out) + "\n"
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("--check", action="store_true", help="fail when a committed runtime file is stale")
+ args = ap.parse_args()
+ stale = 0
+ for name in FILES:
+ fresh = bake(name, (MAP / f"{name}.yaml").read_bytes())
+ runtime = MAP / f"{name}.tsv"
+ if args.check:
+ current = runtime.read_text(encoding="utf-8") if runtime.exists() else ""
+ if current != fresh:
+ print(f"{runtime.relative_to(ROOT)} is stale: run uv run tools/regions_bake.py", file=sys.stderr)
+ stale = 1
+ continue
+ runtime.write_text(fresh, encoding="utf-8", newline="\n")
+ print(f"wrote {runtime.relative_to(ROOT)} ({len(fresh)} characters)")
+ if args.check and not stale:
+ print("the region runtime files are up to date")
+ return stale
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/tests/test_regions_bake.py b/tools/tests/test_regions_bake.py
new file mode 100644
index 000000000..6417fa684
--- /dev/null
+++ b/tools/tests/test_regions_bake.py
@@ -0,0 +1,140 @@
+"""The region files' runtime forms (content/map/{subdistrict_hexes_1948,armistice_hexes_1949,control_hexes_1948_49}.tsv,
+issue #321) are the bakes of the shipped YAML.
+
+The player reads the runtime files at boot instead of parsing the YAML, and refuses one (reading its YAML, with a
+warning: slower, never wrong) when its version or its check of the YAML does not match, or when it is cut short or
+malformed (RegionsRuntime.Read). CI runs no Unity, so this checks here:
+- each committed file is a fresh bake of its YAML (tools/regions_bake.py --check). The region YAML is generated data
+ (tools/borders_bake.py, tools/control_bake.py) and may change again: the failure names the stale file and the command
+ that re-bakes it;
+- the bake's VERSION is RegionsRuntime.Version;
+- each file ends with its body_check over its data rows, and a digit cut off changes it;
+- a fingerprint of the C# that reads the runtime files (RegionsRuntime, and each class's FromRuntime, ParseRuntime and
+ ReadRuntimeOrYaml; comments and whitespace left out), so a change to the reader fails here until someone checks the
+ classes still give the YAML's objects (Unity's RegionsRuntimeTests compares them field by field), bumps the version if
+ the layout changed, re-bakes and re-pins. The bake checks the files' data; it cannot check the C# that reads them.
+"""
+import hashlib
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "tools"))
+import regions_bake as bake # noqa: E402
+
+MAP_SCRIPTS = ROOT / "unity/Assets/Scripts/Map"
+REBAKE = "run uv run tools/regions_bake.py and commit the .tsv"
+
+# The fingerprint of the readers (code_fingerprint). Re-pin only after RegionsRuntimeTests passes in Unity, with
+# RegionsRuntime.Version and regions_bake.VERSION bumped together if the runtime layout changed.
+PINNED_CODE = "688bfe4efcf6459b5b5de21812c92c1b1e5a906204e0145ac531d55b5f3d35d2"
+
+
+def member(text: str, signature: str) -> str:
+ """The text of the member starting at signature, through its closing brace, or its ';' for an expression body."""
+ i = text.index(signature)
+ depth = 0
+ for j in range(i, len(text)):
+ c = text[j]
+ if c == "{":
+ depth += 1
+ elif c == "}":
+ depth -= 1
+ if depth == 0 and text[j + 1:j + 2] != ";":
+ return text[i:j + 1]
+ if depth == 0:
+ return text[i:j + 2]
+ elif c == ";" and depth == 0:
+ return text[i:j + 1]
+ raise AssertionError(f"{signature}: no end")
+
+
+def code_fingerprint() -> str:
+ parts = [(MAP_SCRIPTS / "RegionsRuntime.cs").read_text()]
+ for name, cls in (("Subdistricts1948.cs", "Subdistricts1948"), ("Armistice1949.cs", "Armistice1949"), ("Control1948.cs", "Control1948")):
+ text = (MAP_SCRIPTS / name).read_text()
+ parts += [
+ member(text, "static FileDoc FromRuntime("),
+ member(text, f"public static {cls} ParseRuntime("),
+ member(text, f"public static {cls} ReadRuntimeOrYaml("),
+ ]
+ parts.append(member((MAP_SCRIPTS / "Routes/RouteRibbonFile.cs").read_text(), "public static int Check("))
+ code = "\n".join(re.sub(r"\s+", " ", re.sub(r"//[^\n]*", "", p)).strip() for p in parts)
+ return hashlib.sha256(code.encode()).hexdigest()
+
+
[email protected]("name", bake.FILES)
+def test_each_runtime_file_is_the_bake_of_its_yaml(name):
+ runtime = bake.MAP / f"{name}.tsv"
+ assert runtime.exists(), f"content/map/{name}.tsv is missing: {REBAKE}"
+ fresh = bake.bake(name, (bake.MAP / f"{name}.yaml").read_bytes())
+ assert runtime.read_text(encoding="utf-8") == fresh, (
+ f"content/map/{name}.tsv is stale: content/map/{name}.yaml changed after it was baked. {REBAKE}. "
+ "(The game still works with a stale file, reading the YAML with a warning, but boot is slower.)")
+
+
+def test_the_bake_and_the_reader_share_a_version():
+ m = re.search(r"\bVersion\s*=\s*(\d+)\b", (MAP_SCRIPTS / "RegionsRuntime.cs").read_text())
+ assert m and int(m.group(1)) == bake.VERSION, "RegionsRuntime.Version and regions_bake.VERSION differ"
+
+
[email protected]("name", bake.FILES)
+def test_each_file_ends_with_its_body_check(name):
+ lines = (bake.MAP / f"{name}.tsv").read_text(encoding="utf-8").rstrip("\n").split("\n")
+ kind, key, value = lines[-1].split("\t")
+ assert (kind, key) == ("meta", "body_check")
+ rows = [line for line in lines if line and not line.startswith("#") and not line.startswith("meta\t")]
+ body = lambda rs: bake.fnv1a("".join(r + "\n" for r in rs).encode("utf-8"))
+ assert int(value) == body(rows)
+ last = rows[-1]
+ digit = max(i for i, c in enumerate(last) if c.isdigit())
+ assert body(rows[:-1] + [last[:digit] + last[digit + 1:]]) != int(value), "a digit cut off changes body_check"
+
+
+def test_the_readers_are_the_ones_the_runtime_files_were_checked_against():
+ assert code_fingerprint() == PINNED_CODE, (
+ f"the C# that reads the region runtime files changed (fingerprint {code_fingerprint()}): run RegionsRuntimeTests in "
+ "Unity, bump the version on both sides if the layout changed, re-bake, then re-pin PINNED_CODE")
+
+
+def test_the_yaml_check_is_the_ribbon_bakes():
+ """The runtime files' yaml_check is the same FNV-1a the other bakes use for their source text."""
+ from test_route_ribbon_bake import fnv1a
+ for name in bake.FILES:
+ data = (bake.MAP / f"{name}.yaml").read_bytes()
+ assert bake.fnv1a(data) == fnv1a(data)
+
+
+def _rows(tsv: str):
+ return [line for line in tsv.split("\n") if line and not line.startswith("#") and not line.startswith("meta\t")]
+
+
+# Review of #601, S1: PyYAML's YAML 1.1 resolver re-types plain scalars that YamlDotNet reads into the classes' string
+# fields as their text. Each case is one edit to a shipped file; the bake must keep the scalar's own text, as the YAML path
+# does (0x0F then stays "0x0F", which Control1948 refuses on both paths; a datetime keeps its space).
+YAML_11_CASES = [
+ ("subdistrict_hexes_1948", 'name: "Acre Sub-District"', "name: yes", "name=s:yes"),
+ ("subdistrict_hexes_1948", 'district: "Galilee District", style: primary }\n - { id: 2', 'district: Off, style: primary }\n - { id: 2', "district=s:Off"),
+ ("subdistrict_hexes_1948", "key: acre,", "key: 1_0,", "key=s:1_0"),
+ ("armistice_hexes_1949", "signed: 1949-03-23, shown_from: 1949-03-23", "signed: 1949-03-23 00:00:00, shown_from: 1949-03-23", "signed=s:1949-03-23 00:00:00"),
+ ("control_hexes_1948_49", ' - [15, 1, "IIIIIIIIIIIIIII"]', ' - [0x0F, 1, "IIIIIIIIIIIIIII"]', "0x0F 1 IIIIIIIIIIIIIII"),
+]
+
+
[email protected]("name,old,new,expected", YAML_11_CASES)
+def test_the_bake_keeps_plain_scalars_as_text(name, old, new, expected):
+ text = (bake.MAP / f"{name}.yaml").read_text(encoding="utf-8")
+ assert old in text, f"{name}: the case's anchor is gone"
+ tsv = bake.bake(name, text.replace(old, new, 1).encode("utf-8"))
+ assert expected in "\n".join(_rows(tsv))
+
+
+def test_the_bake_keeps_a_sexagesimal_looking_note_as_text():
+ text = (bake.MAP / "armistice_hexes_1949.yaml").read_text(encoding="utf-8")
+ m = re.search(r'note: ("[^"]*"|[^,}\n]*)', text)
+ assert m
+ tsv = bake.bake("armistice_hexes_1949", (text[:m.start()] + "note: 1:30" + text[m.end():]).encode("utf-8"))
+ assert "note=s:1:30" in "\n".join(_rows(tsv))
diff --git a/unity/Assets/Scripts/Boot/ContentManifest.cs b/unity/Assets/Scripts/Boot/ContentManifest.cs
index 7549415d5..14249d852 100644
--- a/unity/Assets/Scripts/Boot/ContentManifest.cs
+++ b/unity/Assets/Scripts/Boot/ContentManifest.cs
@@ -23,8 +23,10 @@ namespace Statecraft.Game.Boot
public static readonly IReadOnlyCollection<string> ToolInputs = new HashSet<string> { "map/routes_1948.yaml", "map/localities_1948.yaml" };
/// <summary>Baked map files that are not YAML, listed when present: the runtime forms of the 1948 localities and of the
- /// route paths (boot budget). The route paths' YAML still ships: the runtime file is checked against it.</summary>
- public static readonly IReadOnlyList<string> RuntimeData = new[] { "map/localities_1948.tsv", "map/route_paths_1948.tsv" };
+ /// route paths and the region files (boot budget, issue #321). Their YAML still ships: each runtime file is checked
+ /// against it.</summary>
+ public static readonly IReadOnlyList<string> RuntimeData = new[] { "map/localities_1948.tsv", "map/route_paths_1948.tsv",
+ "map/subdistrict_hexes_1948.tsv", "map/armistice_hexes_1949.tsv", "map/control_hexes_1948_49.tsv" };
[Serializable] sealed class ManifestJson { public string[] files = new string[0]; }
diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.cs
index f8694e61f..af8af14d0 100644
--- a/unity/Assets/Scripts/Boot/GameInputs.cs
+++ b/unity/Assets/Scripts/Boot/GameInputs.cs
@@ -16,6 +16,9 @@ namespace Statecraft.Game.Boot
public string HeightmapJson = "", HexesJson = "", SettlementsYaml = "";
/// <summary>content/map/subdistrict_hexes_1948.yaml: the 1948 sub-districts the map outlines (display only).</summary>
public string RegionsYaml = "";
+ /// <summary>The baked runtime forms of the region files the map reads at boot (tools/regions_bake.py; issue #321;
+ /// "" when absent: the YAML is read, with a warning).</summary>
+ public string RegionsTsv = "", ArmisticeTsv = "", ControlTsv = "";
/// <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/route_paths_1948.tsv, the baked runtime form of RoutesYaml the map reads at boot (issue #321;
@@ -62,6 +65,9 @@ namespace Statecraft.Game.Boot
? File.ReadAllText(Path.Combine(contentDir, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName)) : "",
LocalitiesTsv = ReadIfExists(Path.Combine(contentDir, "map", Statecraft.Game.Map.Kits.Localities.RuntimeFileName)),
ArmisticeYaml = ReadIfExists(Path.Combine(contentDir, "map", Armistice1949.FileName)),
+ RegionsTsv = ReadIfExists(Path.Combine(contentDir, "map", Subdistricts1948.RuntimeFileName)),
+ ArmisticeTsv = ReadIfExists(Path.Combine(contentDir, "map", Armistice1949.RuntimeFileName)),
+ ControlTsv = ReadIfExists(Path.Combine(contentDir, "map", Control1948.RuntimeFileName)),
ControlYaml = ReadIfExists(Path.Combine(contentDir, "map", Control1948.FileName)),
};
@@ -90,6 +96,9 @@ namespace Statecraft.Game.Boot
PopulationYaml = texts.TryGetValue("map/" + Statecraft.Game.Map.Kits.KitPopulation.FileName, out var pop) ? pop : "",
LocalitiesTsv = texts.TryGetValue("map/" + Statecraft.Game.Map.Kits.Localities.RuntimeFileName, out var loc) ? loc : "",
ArmisticeYaml = texts.TryGetValue("map/" + Armistice1949.FileName, out var armistice) ? armistice : "",
+ RegionsTsv = texts.TryGetValue("map/" + Subdistricts1948.RuntimeFileName, out var regionsTsv) ? regionsTsv : "",
+ ArmisticeTsv = texts.TryGetValue("map/" + Armistice1949.RuntimeFileName, out var armisticeTsv) ? armisticeTsv : "",
+ ControlTsv = texts.TryGetValue("map/" + Control1948.RuntimeFileName, out var controlTsv) ? controlTsv : "",
ControlYaml = texts.TryGetValue("map/" + Control1948.FileName, out var control) ? control : "",
},
};
diff --git a/unity/Assets/Scripts/Map/Armistice1949.cs b/unity/Assets/Scripts/Map/Armistice1949.cs
index 699ade48e..a9d066c12 100644
--- a/unity/Assets/Scripts/Map/Armistice1949.cs
+++ b/unity/Assets/Scripts/Map/Armistice1949.cs
@@ -20,6 +20,45 @@ namespace Statecraft.Game.Map
{
public const string FileName = "armistice_hexes_1949.yaml";
+ /// <summary>The baked runtime form of the file the player reads at boot (tools/regions_bake.py; issue #321).</summary>
+ public const string RuntimeFileName = "armistice_hexes_1949.tsv";
+
+ /// <summary>Parses the runtime file made from <paramref name="yaml"/> with the same checks as <see cref="Parse"/>;
+ /// throws InvalidDataException when it is of another version, made from another YAML, cut short or malformed.</summary>
+ public static Armistice1949 ParseRuntime(string tsv, string yaml)
+ {
+ var d = RegionsRuntime.Read(tsv, yaml, RuntimeFileName);
+ var doc = FromRuntime(d);
+ d.Done();
+ return Build(doc);
+ }
+
+ /// <summary>The boot read: the runtime file when it is for this YAML, else (one warning) the YAML.</summary>
+ public static Armistice1949 ReadRuntimeOrYaml(string? tsv, string yaml, System.Action<string> warn) =>
+ RegionsRuntime.ReadOrYaml(tsv, yaml, RuntimeFileName, d => { var doc = FromRuntime(d); d.Done(); return doc; }, Build, Parse, warn);
+
+ static FileDoc FromRuntime(RegionsRuntime.Doc d)
+ {
+ var absent = new ItemRow(); // the YAML path's defaults for a field the row leaves out (review of #601)
+ ItemRow Item(RegionsRuntime.Row r) => new ItemRow
+ {
+ Id = r.Int("id", 0), Key = r.Str("key", "")!, Front = r.Str("front", "")!, Name = r.Str("name", "")!,
+ ShownFrom = r.Str("shown_from", absent.ShownFrom)!, Style = r.Str("style", absent.Style)!, Agreement = r.Str("agreement", absent.Agreement),
+ Signed = r.Str("signed", null), LabelNote = r.Str("label_note", "")!, LowAccuracy = r.Bool("low_accuracy", false),
+ };
+ return new FileDoc
+ {
+ Layer = d.Str("layer", "")!, Title = d.Str("title", "")!, Line = d.Str("line", "")!, Label = d.Str("label", "")!,
+ Fronts = d.Items("fronts", r => new FrontRow
+ {
+ Key = r.Str("key", "")!, Name = r.Str("name", "")!, Agreement = r.Str("agreement", "")!, Signed = r.Str("signed", "")!,
+ ShownFrom = r.Str("shown_from", null), LowAccuracy = r.Bool("low_accuracy", false), Note = r.Str("note", "")!,
+ }),
+ Zones = d.Items("zones", Item), Lines = d.Items("lines", Item), NoHex = d.List("no_hex"),
+ ZoneHexes = d.Ints("zone_hexes"), LineHexes = d.Ints("line_hexes"),
+ };
+ }
+
public sealed class Front
{
public string Key = "", Name = "", Agreement = "", Note = ""; public DateTime Signed; public DateTime? ShownFrom;
@@ -43,6 +82,9 @@ namespace Statecraft.Game.Map
public readonly IReadOnlyList<Item> Zones, Lines;
readonly Dictionary<(int q, int r), Item> zoneAt;
readonly Dictionary<(int q, int r), List<Item>> linesAt;
+ /// <summary>The zone and line hexes as read (a test aid: the runtime file must give the YAML's, issue #321).</summary>
+ internal IReadOnlyDictionary<(int q, int r), Item> ZoneHexes => zoneAt;
+ internal IReadOnlyDictionary<(int q, int r), List<Item>> LineHexes => linesAt;
Armistice1949(string title, string line, string label, List<Front> fronts, List<Item> zones, List<Item> lines,
Dictionary<(int q, int r), Item> zoneAt, Dictionary<(int q, int r), List<Item>> linesAt)
@@ -79,6 +121,12 @@ namespace Statecraft.Game.Map
FileDoc? doc;
try { doc = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).WithDuplicateKeyChecking().Build().Deserialize<FileDoc>(yaml); }
catch (YamlException e) { throw new InvalidDataException($"{FileName}: line {e.Start.Line}: {e.InnerException?.Message ?? e.Message}", e); }
+ return Build(doc);
+ }
+
+ /// <summary>The checks and the object, from the file's rows (the YAML's or the runtime file's: RegionsRuntime).</summary>
+ static Armistice1949 Build(FileDoc? doc)
+ {
if (doc == null || string.IsNullOrWhiteSpace(doc.Layer)) throw new InvalidDataException($"{FileName}: no layer");
if (string.IsNullOrWhiteSpace(doc.Label)) throw new InvalidDataException($"{FileName}: no label (the layer is labelled on screen)");
if (doc.Fronts.Count == 0) throw new InvalidDataException($"{FileName}: no fronts");
diff --git a/unity/Assets/Scripts/Map/Control1948.cs b/unity/Assets/Scripts/Map/Control1948.cs
index 4a48e3a70..4780bbba4 100644
--- a/unity/Assets/Scripts/Map/Control1948.cs
+++ b/unity/Assets/Scripts/Map/Control1948.cs
@@ -20,6 +20,35 @@ namespace Statecraft.Game.Map
{
public const string FileName = "control_hexes_1948_49.yaml";
+ /// <summary>The baked runtime form of the file the player reads at boot (tools/regions_bake.py; issue #321).</summary>
+ public const string RuntimeFileName = "control_hexes_1948_49.tsv";
+
+ /// <summary>Parses the runtime file made from <paramref name="yaml"/> with the same checks as <see cref="Parse"/>;
+ /// throws InvalidDataException when it is of another version, made from another YAML, cut short or malformed.</summary>
+ public static Control1948 ParseRuntime(string tsv, string yaml)
+ {
+ var d = RegionsRuntime.Read(tsv, yaml, RuntimeFileName);
+ var doc = FromRuntime(d);
+ d.Done();
+ return Build(doc);
+ }
+
+ /// <summary>The boot read: the runtime file when it is for this YAML, else (one warning) the YAML.</summary>
+ public static Control1948 ReadRuntimeOrYaml(string? tsv, string yaml, System.Action<string> warn) =>
+ RegionsRuntime.ReadOrYaml(tsv, yaml, RuntimeFileName, d => { var doc = FromRuntime(d); d.Done(); return doc; }, Build, Parse, warn);
+
+ static FileDoc FromRuntime(RegionsRuntime.Doc d) => new FileDoc
+ {
+ Layer = d.Str("layer", "")!, Title = d.Str("title", "")!, Meaning = d.Str("meaning", "")!, Line = d.Str("line", "")!,
+ ShownFrom = d.Str("shown_from", "")!, Codes = d.Str("codes", "")!,
+ Periods = d.Items("periods", r => new PeriodRow
+ {
+ Id = r.Str("id", "")!, From = r.Str("from", "")!, Until = r.Str("until", null), Legend = r.Str("legend", "")!,
+ LineDate = r.Str("line_date", "")!, Fronts = r.List("fronts"),
+ }),
+ Hexes = d.Strings("hexes"),
+ };
+
/// <summary>What a hex is on a date. Holder: the other side's holder when the sources name one, else null.</summary>
/// <summary>None: a hex of Mandatory Palestine with no sourced line on the date (no colour); OffData: a hex outside the
/// data (beyond the frontier, the sea).</summary>
@@ -49,6 +78,8 @@ namespace Statecraft.Game.Map
public readonly DateTime ShownFrom;
public readonly IReadOnlyList<Period> Periods;
readonly Dictionary<(int q, int r), string> codes;
+ /// <summary>Each hex's codes as read (a test aid: the runtime file must give the YAML's, issue #321).</summary>
+ internal IReadOnlyDictionary<(int q, int r), string> Codes => codes;
readonly RegionLayer?[] layers;
IReadOnlyCollection<(int q, int r)> outside = Array.Empty<(int, int)>();
@@ -108,6 +139,12 @@ namespace Statecraft.Game.Map
FileDoc? doc;
try { doc = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).WithDuplicateKeyChecking().Build().Deserialize<FileDoc>(yaml); }
catch (YamlException e) { throw new InvalidDataException($"{FileName}: line {e.Start.Line}: {e.InnerException?.Message ?? e.Message}", e); }
+ return Build(doc);
+ }
+
+ /// <summary>The checks and the object, from the file's rows (the YAML's or the runtime file's: RegionsRuntime).</summary>
+ static Control1948 Build(FileDoc? doc)
+ {
if (doc == null || string.IsNullOrWhiteSpace(doc.Layer)) throw new InvalidDataException($"{FileName}: no layer");
if (doc.Periods.Count == 0) throw new InvalidDataException($"{FileName}: no periods");
var periods = new List<Period>();
diff --git a/unity/Assets/Scripts/Map/Kits/Localities.cs b/unity/Assets/Scripts/Map/Kits/Localities.cs
index 133a82cfb..6867cc1a7 100644
--- a/unity/Assets/Scripts/Map/Kits/Localities.cs
+++ b/unity/Assets/Scripts/Map/Kits/Localities.cs
@@ -95,10 +95,10 @@ namespace Statecraft.Game.Map.Kits
}
}
- /// <summary>As FillHexes, from the sub-district file's text, read with the event reader below (boot budget: the map
- /// build reads only each region's key and style and the hexes' regions; GameRoot's Subdistricts1948.Parse validates
- /// the whole file later in the same boot). KitTests checks both give the same hexes.</summary>
- public static void FillHexes(Doc doc, string regionsYaml, HexFile hexes, string file = FileName)
+ /// <summary>As FillHexes, from the sub-district file's text, read with the event reader below: a test aid since issue
+ /// #321 (the map reads the sub-districts' runtime form and calls the overload above). KitTests checks the two give the
+ /// same hexes.</summary>
+ internal static void FillHexes(Doc doc, string regionsYaml, HexFile hexes, string file = FileName)
{
const string regionsFile = Subdistricts1948.FileName;
YMap root;
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index d877e27d9..526f663e9 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -151,6 +151,18 @@ namespace Statecraft.Game.Map
public IReadOnlyList<Units.UnitEntry> UnitEntries { get; private set; } = Array.Empty<Units.UnitEntry>();
string unitsYamlRead; // null before a build
+ /// <summary>The 1948 sub-districts as the last Build read them for the Bedouin camps' hexes (null when it did not:
+ /// no kits, or no sub-district file). Read only: GameRoot's region layers draw from this same object.</summary>
+ public Subdistricts1948 Subdistricts { get; private set; }
+ string regionsYamlRead; // null before a build, or when Build did not read the file
+
+ /// <summary>The sub-districts for <paramref name="yaml"/>: the object the last Build read when it read the same text
+ /// (issue #321: the file was read twice at boot), else read from <paramref name="tsv"/> or the YAML
+ /// (Subdistricts1948.ReadRuntimeOrYaml, warning through <paramref name="warn"/>).</summary>
+ public Subdistricts1948 SubdistrictsFor(string tsv, string yaml, Action<string> warn) =>
+ regionsYamlRead != null && Subdistricts != null && string.Equals(yaml, regionsYamlRead, StringComparison.Ordinal)
+ ? Subdistricts : Subdistricts1948.ReadRuntimeOrYaml(tsv, yaml, warn);
+
/// <summary>The unit spots the last Build placed (UnitGround.Place over <see cref="UnitEntries"/>, keyed by their
/// anchors; an anchor it could not place has none) and the hexes it placed them on. The units layer takes them instead
/// of placing again when it draws the same units on the same hexes (issue #321; UnitSpotsFor).</summary>
@@ -263,7 +275,14 @@ namespace Statecraft.Game.Map
// The camps' areas are the sub-districts as the region layer draws them (review I4: no copy in the
// localities file).
if (string.IsNullOrWhiteSpace(inputs.RegionsYaml)) { localities.Encampments.Clear(); Debug.LogWarning($"KITS map/{Subdistricts1948.FileName} is missing: no Bedouin camps"); }
- else Kits.Localities.FillHexes(localities, inputs.RegionsYaml, Hexes, "map/" + Kits.Localities.FileName);
+ else
+ {
+ // The camps' hexes from the sub-districts, read once from their runtime form (issue #321) and handed on
+ // to GameRoot's region layers (SubdistrictsFor).
+ Subdistricts = Subdistricts1948.ReadRuntimeOrYaml(inputs.RegionsTsv, inputs.RegionsYaml, Debug.LogWarning);
+ regionsYamlRead = inputs.RegionsYaml;
+ Kits.Localities.FillHexes(localities, Subdistricts, Hexes, "map/" + Kits.Localities.FileName);
+ }
}
Kits.Localities.Use(localities.Places); // on every build, so a map without the kits inherits nothing (review M13)
if (kitsOn) DiagLog.BootPhase("localities parsed");
@@ -452,6 +471,7 @@ namespace Statecraft.Game.Map
Hexes = null;
settlementsYamlRead = null;
UnitEntries = Array.Empty<Units.UnitEntry>(); unitsYamlRead = null;
+ Subdistricts = null; regionsYamlRead = null;
UnitSpots = new Dictionary<Units.UnitAnchor, Units.AnchorSpot>(); UnitHexes = Array.Empty<Statecraft.Sim.MapHex>();
}
}
diff --git a/unity/Assets/Scripts/Map/RegionsRuntime.cs b/unity/Assets/Scripts/Map/RegionsRuntime.cs
new file mode 100644
index 000000000..bdb0f78e8
--- /dev/null
+++ b/unity/Assets/Scripts/Map/RegionsRuntime.cs
@@ -0,0 +1,301 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Text;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>The runtime form of the map's region files (tools/regions_bake.py; issue #321): subdistrict_hexes_1948,
+ /// armistice_hexes_1949 and control_hexes_1948_49 as .tsv beside their YAML, read at boot instead of the YAML. The
+ /// layout is the YAML's own shape (top-level scalars, lists of mappings, lists of lists), so each class builds the same
+ /// rows from either source and keeps its own checks. <see cref="Read"/> refuses a file of another version, made from
+ /// another YAML (the YAML's FNV-1a check), with another row count, without its last body_check row or not matching it
+ /// (a file cut anywhere, even inside a number), or with a malformed row; the classes then read the YAML, with one
+ /// warning.</summary>
+ public static class RegionsRuntime
+ {
+ /// <summary>Bump it, with tools/regions_bake.py's VERSION, when the layout or its reading changes;
+ /// tools/tests/test_regions_bake.py pins a fingerprint of this reader and of the classes' runtime mapping.</summary>
+ public const int Version = 2; // 2: every scalar as its own text (review of #601)
+
+ /// <summary>A value: a scalar's own text (null for a plain null) or a list of tokens. Integers and booleans are read
+ /// from the text as the classes' YAML path reads them.</summary>
+ public sealed class Value
+ {
+ public char Kind; public string? Text; public List<string>? Items;
+ }
+
+ /// <summary>One mapping of a top-level list; <see cref="Done"/> refuses a field the caller did not read (YamlDotNet
+ /// refuses an unknown key in the YAML the same way).</summary>
+ public sealed class Row
+ {
+ readonly string file; readonly int line;
+ readonly Dictionary<string, Value> fields = new Dictionary<string, Value>();
+ readonly HashSet<string> read = new HashSet<string>();
+ internal Row(string file, int line) { this.file = file; this.line = line; }
+ internal void Add(string key, Value v)
+ {
+ if (fields.ContainsKey(key)) throw new InvalidDataException($"{file}:{line}: field '{key}' twice");
+ fields[key] = v;
+ }
+ Value? Get(string key, char kind)
+ {
+ read.Add(key);
+ if (!fields.TryGetValue(key, out var v)) return null;
+ if ((kind == 'l') != (v.Kind == 'l')) throw new InvalidDataException($"{file}:{line}: field '{key}' is not of the expected type");
+ return v;
+ }
+ /// <summary>The field's text; <paramref name="absent"/> when the row has no such field (the YAML class's default).</summary>
+ public string? Str(string key, string? absent) { var v = Get(key, 's'); return v == null ? absent : v.Text; }
+ /// <summary>An integer field from its text (a decimal integer only; anything else, as YamlDotNet's 0x0F, is refused
+ /// and the YAML read instead).</summary>
+ public int Int(string key, int absent)
+ {
+ var v = Get(key, 's');
+ if (v == null) return absent;
+ return v.Text != null && DecimalInt(v.Text, out var n) ? n
+ : throw new InvalidDataException($"{file}:{line}: field '{key}' '{v.Text}' is not an integer");
+ }
+ /// <summary>A boolean field from its text, "true" or "false" only (anything else is refused and the YAML read).</summary>
+ public bool Bool(string key, bool absent)
+ {
+ var v = Get(key, 's');
+ if (v == null) return absent;
+ return v.Text == "true" ? true : v.Text == "false" ? false
+ : throw new InvalidDataException($"{file}:{line}: field '{key}' '{v.Text}' is not true or false");
+ }
+ public List<string> List(string key) { var v = Get(key, 'l'); return v == null ? new List<string>() : new List<string>(v.Items!); }
+ public void Done()
+ {
+ foreach (var k in fields.Keys) if (!read.Contains(k)) throw new InvalidDataException($"{file}:{line}: unknown field '{k}'");
+ }
+ }
+
+ /// <summary>A read runtime file: its top-level scalars, lists of mappings and lists of lists, by key.</summary>
+ public sealed class Doc
+ {
+ readonly string file;
+ readonly Dictionary<string, Value> scalars = new Dictionary<string, Value>();
+ readonly Dictionary<string, List<Row>> items = new Dictionary<string, List<Row>>();
+ readonly Dictionary<string, List<string[]>> tuples = new Dictionary<string, List<string[]>>();
+ readonly HashSet<string> keys = new HashSet<string>(), read = new HashSet<string>();
+ internal Doc(string file) { this.file = file; }
+ internal void Key(string key, int line)
+ {
+ if (!keys.Add(key)) throw new InvalidDataException($"{file}:{line}: key '{key}' twice");
+ }
+ internal void Scalar(string key, Value v, int line) { Key(key, line); scalars[key] = v; }
+ internal List<Row> ItemsOf(string key, int line)
+ {
+ if (!items.TryGetValue(key, out var list)) { Key(key, line); items[key] = list = new List<Row>(); }
+ return list;
+ }
+ internal void Tuples(string key, List<string[]> rows, int line) { Key(key, line); tuples[key] = rows; }
+ internal void Empty(string key, int line) { Key(key, line); }
+
+ public string? Str(string key, string? absent)
+ {
+ read.Add(key);
+ if (!scalars.TryGetValue(key, out var v)) return absent;
+ if (v.Kind == 'l') throw new InvalidDataException($"{file}: '{key}' is not a string");
+ return v.Text;
+ }
+ public List<string> List(string key)
+ {
+ read.Add(key);
+ if (!scalars.TryGetValue(key, out var v)) return new List<string>();
+ if (v.Kind != 'l') throw new InvalidDataException($"{file}: '{key}' is not a list");
+ return new List<string>(v.Items!);
+ }
+ /// <summary>The mappings of a top-level list, each read by <paramref name="map"/> (which must read every field).</summary>
+ public List<T> Items<T>(string key, Func<Row, T> map)
+ {
+ read.Add(key);
+ var list = new List<T>();
+ if (items.TryGetValue(key, out var rows)) foreach (var r in rows) { list.Add(map(r)); r.Done(); }
+ return list;
+ }
+ /// <summary>The elements of a top-level list of lists, as their tokens.</summary>
+ public List<List<string>> Strings(string key)
+ {
+ read.Add(key);
+ var list = new List<List<string>>();
+ if (tuples.TryGetValue(key, out var rows)) foreach (var r in rows) list.Add(new List<string>(r));
+ return list;
+ }
+ public List<List<int>> Ints(string key)
+ {
+ var list = new List<List<int>>();
+ foreach (var r in Strings(key))
+ {
+ var ints = new List<int>(r.Count);
+ foreach (var t in r)
+ ints.Add(DecimalInt(t, out var n) ? n
+ : throw new InvalidDataException($"{file}: '{key}' holds '{t}', not an integer"));
+ list.Add(ints);
+ }
+ return list;
+ }
+ /// <summary>Refuses a key the class did not read (YamlDotNet refuses an unknown key the same way).</summary>
+ public void Done()
+ {
+ foreach (var k in keys) if (!read.Contains(k)) throw new InvalidDataException($"{file}: unknown key '{k}'");
+ }
+ }
+
+ /// <summary>A plain decimal integer, read as the YAML path reads it. A leading zero is refused: YamlDotNet (the
+ /// region classes' deserializer, 18.1.0) reads "012" as octal 10 and "08" not at all, where this would read 12 and 8
+ /// (review of #601); such a file then falls back to the YAML.</summary>
+ internal static bool DecimalInt(string text, out int n)
+ {
+ n = 0;
+ int i = text.Length > 0 && (text[0] == '+' || text[0] == '-') ? 1 : 0;
+ if (text.Length > i + 1 && text[i] == '0') return false;
+ return int.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out n);
+ }
+
+ /// <summary>FNV-1a over the UTF-8 bytes of the data rows, each followed by '\n' (tools/regions_bake.py's body_check).</summary>
+ public static int BodyCheck(IEnumerable<string> rows)
+ {
+ uint h = 2166136261;
+ foreach (var row in rows)
+ {
+ foreach (var b in Encoding.UTF8.GetBytes(row)) { h ^= b; h *= 16777619; }
+ h ^= (byte)'\n'; h *= 16777619;
+ }
+ return (int)h;
+ }
+
+ /// <summary>Reads a runtime file made from <paramref name="yaml"/>; throws InvalidDataException naming
+ /// <paramref name="file"/> (and the line, for a malformed row) otherwise.</summary>
+ public static Doc Read(string tsv, string yaml, string file)
+ {
+ var doc = new Doc(file);
+ int? version = null, check = null, count = null, body = null;
+ var rows = new List<string>();
+ var lines = tsv.Split('\n');
+ // The version first, so a file of another layout says so rather than failing on a row it cannot read (review of #601).
+ foreach (var l in lines)
+ if (l.StartsWith("meta\tversion\t", StringComparison.Ordinal))
+ {
+ var v = l.TrimEnd('\r').Substring("meta\tversion\t".Length);
+ if (v != Version.ToString(CultureInfo.InvariantCulture))
+ throw new InvalidDataException($"{file}: version {v}, this build reads {Version} (re-bake: tools/regions_bake.py)");
+ break;
+ }
+ int Int(string text, string what, int line) =>
+ int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v)
+ ? v : throw new InvalidDataException($"{file}:{line}: {what} '{text}' is not an integer");
+ for (int i = 0; i < lines.Length; i++)
+ {
+ var text = lines[i].TrimEnd('\r');
+ if (text.Length == 0 || text[0] == '#') continue;
+ int line = i + 1;
+ if (body != null) throw new InvalidDataException($"{file}:{line}: a row after body_check, which must be the last");
+ var c = text.Split('\t');
+ if (c[0] == "meta")
+ {
+ if (c.Length != 3) throw new InvalidDataException($"{file}:{line}: a meta row has {c.Length} fields, not 3");
+ switch (c[1])
+ {
+ case "version": version = Int(c[2], "version", line); break;
+ case "yaml_check": check = Int(c[2], "yaml_check", line); break;
+ case "rows": count = Int(c[2], "rows", line); break;
+ case "body_check": body = Int(c[2], "body_check", line); break;
+ default: throw new InvalidDataException($"{file}:{line}: unknown meta '{c[1]}'");
+ }
+ continue;
+ }
+ rows.Add(text);
+ switch (c[0])
+ {
+ case "scalar":
+ if (c.Length != 3) throw new InvalidDataException($"{file}:{line}: a scalar row has {c.Length} fields, not 3");
+ doc.Scalar(c[1], Parse(c[2], file, line), line);
+ break;
+ case "item":
+ if (c.Length < 2) throw new InvalidDataException($"{file}:{line}: an item row has no table");
+ var row = new Row(file, line);
+ for (int k = 2; k < c.Length; k++)
+ {
+ int eq = c[k].IndexOf('=');
+ if (eq <= 0) throw new InvalidDataException($"{file}:{line}: field '{c[k]}' is not name=value");
+ row.Add(c[k].Substring(0, eq), Parse(c[k].Substring(eq + 1), file, line));
+ }
+ doc.ItemsOf(c[1], line).Add(row);
+ break;
+ case "tuples":
+ if (c.Length != 4) throw new InvalidDataException($"{file}:{line}: a tuples row has {c.Length} fields, not 4");
+ int n = Int(c[2], "count", line);
+ var parts = c[3].Length == 0 ? Array.Empty<string>() : c[3].Split(';');
+ if (parts.Length != n) throw new InvalidDataException($"{file}:{line}: {parts.Length} tuples, the row says {n}");
+ var tuples = new List<string[]>(parts.Length);
+ foreach (var p in parts) tuples.Add(p.Split(' '));
+ doc.Tuples(c[1], tuples, line);
+ break;
+ case "empty":
+ if (c.Length != 2) throw new InvalidDataException($"{file}:{line}: an empty row has {c.Length} fields, not 2");
+ doc.Empty(c[1], line);
+ break;
+ default: throw new InvalidDataException($"{file}:{line}: unknown row '{c[0]}'");
+ }
+ }
+ if (version == null || check == null || count == null) throw new InvalidDataException($"{file}: no version, yaml_check or rows row");
+ if (version != Version) throw new InvalidDataException($"{file}: version {version}, this build reads {Version} (re-bake: tools/regions_bake.py)");
+ if (check != Routes.RouteRibbonFile.Check(yaml)) throw new InvalidDataException($"{file}: made from another YAML (re-bake: tools/regions_bake.py)");
+ if (rows.Count != count) throw new InvalidDataException($"{file}: {rows.Count} rows, the file says {count}");
+ if (body == null) throw new InvalidDataException($"{file}: no body_check row at the end (cut short?)");
+ if (body != BodyCheck(rows)) throw new InvalidDataException($"{file}: the rows do not match body_check (cut short or edited?)");
+ return doc;
+ }
+
+ static Value Parse(string text, string file, int line)
+ {
+ if (text.Length < 2 || text[1] != ':') throw new InvalidDataException($"{file}:{line}: value '{text}' has no type");
+ var body = text.Substring(2);
+ switch (text[0])
+ {
+ case 's': return new Value { Kind = 's', Text = Unescape(body, file, line) };
+ case 'n':
+ if (body.Length != 0) throw new InvalidDataException($"{file}:{line}: a null with text");
+ return new Value { Kind = 'n', Text = null };
+ case 'l': return new Value { Kind = 'l', Items = body.Length == 0 ? new List<string>() : new List<string>(body.Split(',')) };
+ default: throw new InvalidDataException($"{file}:{line}: unknown type '{text[0]}'");
+ }
+ }
+
+ static string Unescape(string s, string file, int line)
+ {
+ if (s.IndexOf('\\') < 0) return s;
+ var b = new StringBuilder(s.Length);
+ for (int i = 0; i < s.Length; i++)
+ {
+ if (s[i] != '\\') { b.Append(s[i]); continue; }
+ if (++i >= s.Length) throw new InvalidDataException($"{file}:{line}: a trailing backslash");
+ b.Append(s[i] switch
+ {
+ '\\' => '\\', 't' => '\t', 'r' => '\r', 'n' => '\n',
+ _ => throw new InvalidDataException($"{file}:{line}: unknown escape '\\{s[i]}'"),
+ });
+ }
+ return b.ToString();
+ }
+
+ /// <summary>The boot read for a region file: the class's rows from the runtime file (<paramref name="rows"/>, which
+ /// reads every field and calls Done) when it is for this YAML, else, with one warning through <paramref name="warn"/>,
+ /// <paramref name="parse"/> over the YAML. Then <paramref name="build"/>, the class's checks, outside the fallback: a
+ /// content error is the YAML's own (both sources would fail it), so it throws as the YAML path does, with no warning
+ /// and no second read (review of #601).</summary>
+ public static T ReadOrYaml<TDoc, T>(string? tsv, string yaml, string file, Func<Doc, TDoc> rows, Func<TDoc, T> build,
+ Func<string, T> parse, Action<string> warn)
+ {
+ if (string.IsNullOrWhiteSpace(tsv)) { warn($"{file}: missing; reading the YAML"); return parse(yaml); }
+ TDoc doc;
+ try { doc = rows(Read(tsv!, yaml, file)); }
+ catch (InvalidDataException e) { warn($"{e.Message}; reading the YAML"); return parse(yaml); }
+ return build(doc);
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/RegionsRuntime.cs.meta b/unity/Assets/Scripts/Map/RegionsRuntime.cs.meta
new file mode 100644
index 000000000..5f733d5d2
--- /dev/null
+++ b/unity/Assets/Scripts/Map/RegionsRuntime.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: fcd7af552dcc4fd89593e90954f44ae9
diff --git a/unity/Assets/Scripts/Map/Subdistricts1948.cs b/unity/Assets/Scripts/Map/Subdistricts1948.cs
index 1bb2f36c1..d5aa6c5e3 100644
--- a/unity/Assets/Scripts/Map/Subdistricts1948.cs
+++ b/unity/Assets/Scripts/Map/Subdistricts1948.cs
@@ -23,6 +23,35 @@ namespace Statecraft.Game.Map
{
public const string FileName = "subdistrict_hexes_1948.yaml";
+ /// <summary>The baked runtime form of the file the player reads at boot (tools/regions_bake.py; issue #321).</summary>
+ public const string RuntimeFileName = "subdistrict_hexes_1948.tsv";
+
+ /// <summary>Parses the runtime file made from <paramref name="yaml"/> with the same checks as <see cref="Parse"/>;
+ /// throws InvalidDataException when it is of another version, made from another YAML, cut short or malformed.</summary>
+ public static Subdistricts1948 ParseRuntime(string tsv, string yaml)
+ {
+ var d = RegionsRuntime.Read(tsv, yaml, RuntimeFileName);
+ var doc = FromRuntime(d);
+ d.Done();
+ return Build(doc);
+ }
+
+ /// <summary>The boot read: the runtime file when it is for this YAML, else (one warning) the YAML.</summary>
+ public static Subdistricts1948 ReadRuntimeOrYaml(string? tsv, string yaml, System.Action<string> warn) =>
+ RegionsRuntime.ReadOrYaml(tsv, yaml, RuntimeFileName, d => { var doc = FromRuntime(d); d.Done(); return doc; }, Build, Parse, warn);
+
+ static FileDoc FromRuntime(RegionsRuntime.Doc d) => new FileDoc
+ {
+ Layer = d.Str("layer", "")!, Title = d.Str("title", "")!, Line = d.Str("line", "")!, Label = d.Str("label", "")!,
+ ShownFrom = d.Str("shown_from", "")!, ShownUntil = d.Str("shown_until", null),
+ Fronts = d.Items("fronts", r => new FrontRow { Key = r.Str("key", "")!, Until = r.Str("until", null) }),
+ Regions = d.Items("regions", r => new FileRow
+ {
+ Id = r.Int("id", 0), Key = r.Str("key", "")!, Name = r.Str("name", "")!, District = r.Str("district", "")!, Style = r.Str("style", "")!,
+ }),
+ Hexes = d.Ints("hexes"),
+ };
+
public sealed class Region
{
public int Id; public string Key = "", Name = "", District = ""; public BorderStyle Style;
@@ -66,6 +95,12 @@ namespace Statecraft.Game.Map
FileDoc? doc;
try { doc = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).WithDuplicateKeyChecking().Build().Deserialize<FileDoc>(yaml); }
catch (YamlException e) { throw new InvalidDataException($"{FileName}: line {e.Start.Line}: {e.InnerException?.Message ?? e.Message}", e); }
+ return Build(doc);
+ }
+
+ /// <summary>The checks and the object, from the file's rows (the YAML's or the runtime file's: RegionsRuntime).</summary>
+ static Subdistricts1948 Build(FileDoc? doc)
+ {
if (doc == null || string.IsNullOrWhiteSpace(doc.Layer)) throw new InvalidDataException($"{FileName}: no layer");
if (doc.Regions.Count == 0) throw new InvalidDataException($"{FileName}: no regions");
if (string.IsNullOrWhiteSpace(doc.Label)) throw new InvalidDataException($"{FileName}: no label (the layer is labelled on screen)");
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index f9b620052..318000b78 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -45,6 +45,8 @@ namespace Statecraft.Game.UI
Statecraft.Game.Map.Units.UnitLayer? units;
/// <summary>The units in play (null before Begin).</summary>
internal Statecraft.Game.Map.Units.UnitLayer? Units => units;
+ /// <summary>The map's region layers (sub-districts, armistice, control; null before Begin): a test aid.</summary>
+ internal MapRegions? Regions { get; private set; }
MapLabelsPresenter? labels;
ScreenNav? nav;
StartScreenPresenter? start;
@@ -216,9 +218,11 @@ namespace Statecraft.Game.UI
// where the line exists (display only: the sim never reads them; docs/visual-v1.md, owner rulings 2026-10-11).
// Since the owner's rulings of 2026-10-14 the areas are coloured by side from 11 June 1948 (control_hexes_1948_49.yaml),
// with the legend in the label.
- var regions = new MapRegions(Subdistricts1948.Parse(inputs.Map.RegionsYaml),
- string.IsNullOrWhiteSpace(inputs.Map.ArmisticeYaml) ? null : Armistice1949.Parse(inputs.Map.ArmisticeYaml),
- string.IsNullOrWhiteSpace(inputs.Map.ControlYaml) ? null : Control1948.Parse(inputs.Map.ControlYaml));
+ // From their runtime forms when they match the YAML (issue #321: boot time), the sub-districts as the map read them.
+ var regions = new MapRegions(map.SubdistrictsFor(inputs.Map.RegionsTsv, inputs.Map.RegionsYaml, Debug.LogWarning),
+ string.IsNullOrWhiteSpace(inputs.Map.ArmisticeYaml) ? null : Armistice1949.ReadRuntimeOrYaml(inputs.Map.ArmisticeTsv, inputs.Map.ArmisticeYaml, Debug.LogWarning),
+ string.IsNullOrWhiteSpace(inputs.Map.ControlYaml) ? null : Control1948.ReadRuntimeOrYaml(inputs.Map.ControlTsv, inputs.Map.ControlYaml, Debug.LogWarning));
+ Regions = regions;
var layerLabel = root.Q<Label>("map-layer");
Action onDate = () =>
{
@@ -376,7 +380,7 @@ namespace Statecraft.Game.UI
StopAllCoroutines();
for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
owned.Clear();
- minimap = null; labels = null; nav = null; start = null; card = null; outcomes = null; rig = null; drawn = null; units = null; logCamera = false;
+ minimap = null; labels = null; nav = null; start = null; card = null; outcomes = null; rig = null; drawn = null; units = null; Regions = 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/Tests/EditMode/RegionsRuntimeTests.cs b/unity/Assets/Tests/EditMode/RegionsRuntimeTests.cs
new file mode 100644
index 000000000..dafa3eb16
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/RegionsRuntimeTests.cs
@@ -0,0 +1,233 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Boot;
+using Statecraft.Game.Map;
+using Statecraft.Game.UI;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using Object = UnityEngine.Object;
+
+/// <summary>Issue #321 (T58): the map's region files (the 1948 sub-districts, the 1949 armistice lines, the 1948-49 control
+/// areas) are read at boot from their baked runtime forms (tools/regions_bake.py) instead of YamlDotNet over the YAML
+/// (about 160 ms at cpu 4: 135 in GameRoot, 24 in the map). Each runtime file must give exactly the YAML's object, field by field; one that does not match
+/// its YAML (its check or its version), is cut short anywhere or is malformed is refused with one warning and the YAML is
+/// read. The map reads the sub-districts once and GameRoot's region layers take that object.</summary>
+public class RegionsRuntimeTests
+{
+ string saveDir = "";
+
+ [SetUp]
+ public void SetUp() => saveDir = Path.Combine(Path.GetTempPath(), "statecraft-regions-" + Guid.NewGuid().ToString("N"));
+
+ [TearDown]
+ public void TearDown()
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ VisualToggles.Clear();
+ if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);
+ }
+
+ static GameInputs Inputs() => GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+
+ static string D(DateTime? d) => d?.ToString("yyyy-MM-dd") ?? "null";
+
+ /// <summary>Everything a Subdistricts1948 holds that the map, the camps and the region layers read.</summary>
+ static string Describe(Subdistricts1948 s) => string.Join("\n",
+ new[] { s.Title, s.Line, s.Label, D(s.ShownFrom), D(s.ShownUntil), s.Layer.Name }
+ .Concat(s.Fronts.OrderBy(f => f.Key, StringComparer.Ordinal).Select(f => f.Key + "=" + D(f.Value)))
+ .Concat(s.Regions.OrderBy(r => r.Id).Select(r => $"{r.Id}|{r.Key}|{r.Name}|{r.District}|{r.Style}|{s.Layer.StyleOf(r.Id)}"))
+ .Concat(s.Layer.Hexes.OrderBy(h => h.r).ThenBy(h => h.q).Select(h => $"{h.q},{h.r}:{s.Layer.RegionOf(h.q, h.r)}")));
+
+ static string Describe(Armistice1949 a)
+ {
+ string Item(Armistice1949.Item i) =>
+ $"{i.Id}|{i.Key}|{i.Name}|{i.Front.Key}|{D(i.ShownFrom)}|{i.Style}|{i.Agreement}|{i.LabelNote}|{D(i.Signed)}|{i.LowAccuracy}";
+ return string.Join("\n",
+ new[] { a.Title, a.Line, a.Label }
+ .Concat(a.Fronts.Select(f => $"{f.Key}|{f.Name}|{f.Agreement}|{f.Note}|{D(f.Signed)}|{D(f.ShownFrom)}|{f.LowAccuracy}"))
+ .Concat(a.Zones.Select(Item)).Concat(a.Lines.Select(Item))
+ .Concat(a.ZoneHexes.OrderBy(k => k.Key.r).ThenBy(k => k.Key.q).Select(k => $"z {k.Key.q},{k.Key.r}:{k.Value.Id}"))
+ .Concat(a.LineHexes.OrderBy(k => k.Key.r).ThenBy(k => k.Key.q).Select(k => $"l {k.Key.q},{k.Key.r}:{string.Join(",", k.Value.Select(x => x.Id))}")));
+ }
+
+ static string Describe(Control1948 c) => string.Join("\n",
+ new[] { c.Title, c.Line, c.Meaning, D(c.ShownFrom) }
+ .Concat(c.Periods.Select(p => $"{p.Id}|{D(p.From)}|{D(p.Until)}|{p.Legend}|{p.LineDate}|{string.Join(",", p.Fronts)}"))
+ .Concat(c.Codes.OrderBy(k => k.Key.r).ThenBy(k => k.Key.q).Select(k => $"{k.Key.q},{k.Key.r}:{k.Value}")));
+
+ /// <summary>The three files: their runtime and YAML texts, the runtime read, the YAML parse and the boot read.</summary>
+ static IEnumerable<(string name, string tsv, string yaml, Func<string, string, string> runtime, Func<string, string> yamlRead,
+ Func<string, string, Action<string>, string> boot)> Files(MapInputs m)
+ {
+ yield return ("subdistricts", m.RegionsTsv, m.RegionsYaml, (t, y) => Describe(Subdistricts1948.ParseRuntime(t, y)),
+ y => Describe(Subdistricts1948.Parse(y)), (t, y, w) => Describe(Subdistricts1948.ReadRuntimeOrYaml(t, y, w)));
+ yield return ("armistice", m.ArmisticeTsv, m.ArmisticeYaml, (t, y) => Describe(Armistice1949.ParseRuntime(t, y)),
+ y => Describe(Armistice1949.Parse(y)), (t, y, w) => Describe(Armistice1949.ReadRuntimeOrYaml(t, y, w)));
+ yield return ("control", m.ControlTsv, m.ControlYaml, (t, y) => Describe(Control1948.ParseRuntime(t, y)),
+ y => Describe(Control1948.Parse(y)), (t, y, w) => Describe(Control1948.ReadRuntimeOrYaml(t, y, w)));
+ }
+
+ [Test]
+ public void EachRuntimeFileGivesTheYamlsObjectFieldByField()
+ {
+ foreach (var (name, tsv, yaml, runtime, yamlRead, _) in Files(Inputs().Map))
+ {
+ Assert.IsNotEmpty(tsv, $"{name}: the runtime file (tools/regions_bake.py)");
+ Assert.AreEqual(yamlRead(yaml), runtime(tsv, yaml), name);
+ }
+ }
+
+ /// <summary>A runtime file for another YAML, of another version, cut inside its last number (the file ending there, or
+ /// the rows after it kept), two bytes short, with a malformed row, or missing: one warning, and the YAML's object.</summary>
+ [Test]
+ public void AStaleCutOrBrokenRuntimeFileFallsBackToTheYamlWithOneWarning()
+ {
+ foreach (var (name, tsv, yaml, _, yamlRead, boot) in Files(Inputs().Map))
+ {
+ var expected = yamlRead(yaml);
+ var lines = tsv.Split('\n');
+ int last = Array.FindLastIndex(lines, l => l.Length > 0 && !l.StartsWith("meta\t") && !l.StartsWith("#"));
+ string lastRow = lines[last];
+ int digit = lastRow.Length - 1;
+ while (digit > 0 && !char.IsDigit(lastRow[digit])) digit--;
+ Assert.Greater(digit, 0, $"{name}: the last data row ends in a number");
+ string Cut(int keepRows) => string.Join("\n", lines.Take(last)) + "\n"
+ + (keepRows > 0 ? lastRow.Remove(digit, 1) + "\n" + string.Join("\n", lines.Skip(last + 1)) : lastRow.Substring(0, digit));
+ var cases = new (string tsv, string yaml, string why)[]
+ {
+ (tsv, yaml + "\n# an edit after the bake\n", "made from another YAML"),
+ (tsv.Replace($"meta\tversion\t{RegionsRuntime.Version}\n", $"meta\tversion\t{RegionsRuntime.Version + 1}\n"), yaml, "version"),
+ (Cut(0), yaml, "cut inside the last number, the file ending there"),
+ (Cut(1), yaml, "the last number a digit short, the rows after it kept"),
+ (tsv.Substring(0, tsv.Length - 2), yaml, "two bytes off the end"),
+ (tsv.Replace("\nscalar\t", "\nscalar\tx\t"), yaml, "a malformed row"),
+ ("", yaml, "missing"),
+ };
+ foreach (var (t, y, why) in cases)
+ {
+ Assert.IsFalse(t == tsv && y == yaml, $"{name}: {why} changes the runtime file or its YAML");
+ var warnings = new List<string>();
+ var got = boot(t, y, warnings.Add);
+ Assert.AreEqual(1, warnings.Count, $"{name}: {why}: {string.Join(" | ", warnings)}");
+ StringAssert.Contains("reading the YAML", warnings[0], $"{name}: {why}");
+ Assert.AreEqual(y == yaml ? expected : yamlRead(y), got, $"{name}: {why}");
+ }
+ var none = new List<string>();
+ Assert.AreEqual(expected, boot(tsv, yaml, none.Add), $"{name}: the shipped file");
+ CollectionAssert.IsEmpty(none, $"{name}: the shipped file is read without a warning");
+ }
+ }
+
+ /// <summary>Review of #601: a leading zero. The game's YAML path (YamlDotNet 18.1.0, the region classes' own deserializer)
+ /// reads an integer with a leading zero as octal: checked with that DLL and Subdistricts1948.Parse's builder chain,
+ /// "id: 010" gives 8, "[012, 0, 17]" gives q = 10, "[-012, 0, 17]" gives -10, and "id: 08" throws. The runtime reader
+ /// would read 12, so it refuses such a number and the YAML is read (one warning). Each case edits the YAML and its
+ /// runtime file alike (yaml_check and body_check made again), so only the number's reading differs.</summary>
+ [Test]
+ public void ALeadingZeroIsReadAsTheYamlPathReadsIt()
+ {
+ var m = Inputs().Map;
+ foreach (var (yamlOld, yamlNew, tsvOld, tsvNew, why) in new[]
+ {
+ (" - [12, 0, 17]\n", " - [012, 0, 17]\n", "\t870\t12 0 17;", "\t870\t012 0 17;", "a hex's q, 012 (octal 10 on the YAML path)"),
+ ("{ id: 17, key: outside,", "{ id: 021, key: outside,", "id=s:17\tkey=s:outside", "id=s:021\tkey=s:outside", "a region id, 021 (octal 17)"),
+ })
+ {
+ StringAssert.Contains(yamlOld, m.RegionsYaml, why); StringAssert.Contains(tsvOld, m.RegionsTsv, why);
+ var yaml = m.RegionsYaml.Replace(yamlOld, yamlNew);
+ var lines = Rebody(m.RegionsTsv.Replace(tsvOld, tsvNew)).Split('\n');
+ int check = Array.FindIndex(lines, l => l.StartsWith("meta\tyaml_check\t"));
+ lines[check] = "meta\tyaml_check\t" + Statecraft.Game.Map.Routes.RouteRibbonFile.Check(yaml).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ var warnings = new List<string>();
+ var got = Describe(Subdistricts1948.ReadRuntimeOrYaml(string.Join("\n", lines), yaml, warnings.Add));
+ Assert.AreEqual(Describe(Subdistricts1948.Parse(yaml)), got, why);
+ Assert.AreEqual(1, warnings.Count, $"{why}: {string.Join(" | ", warnings)}");
+ }
+ }
+
+ /// <summary>Review of #601: a runtime file of another version says so, before any row it cannot read (a version 1 file's
+ /// typed values are not version 2's).</summary>
+ [Test]
+ public void AnOldVersionIsNamedFirst()
+ {
+ var m = Inputs().Map;
+ var old = m.RegionsTsv.Replace($"meta\tversion\t{RegionsRuntime.Version}\n", "meta\tversion\t1\n").Replace("id=s:1\t", "id=i:1\t");
+ var warnings = new List<string>();
+ Subdistricts1948.ReadRuntimeOrYaml(old, m.RegionsYaml, warnings.Add);
+ Assert.AreEqual(1, warnings.Count);
+ StringAssert.Contains($"version 1, this build reads {RegionsRuntime.Version}", warnings[0]);
+ }
+
+ /// <summary>A field the class does not read is refused, as YamlDotNet refuses an unknown key: the YAML is read.</summary>
+ [Test]
+ public void AnUnknownFieldIsRefused()
+ {
+ var m = Inputs().Map;
+ var lines = m.RegionsTsv.Split('\n').ToList();
+ int at = lines.FindIndex(l => l.StartsWith("item\tregions\t"));
+ lines[at] += "\tcolour=s:red";
+ var e = Assert.Throws<InvalidDataException>(() => Subdistricts1948.ParseRuntime(Rebody(string.Join("\n", lines)), m.RegionsYaml));
+ StringAssert.Contains("unknown field 'colour'", e!.Message);
+ }
+
+ /// <summary>A runtime file with its body_check made again for edited rows (a test aid: the map then shows which file it
+ /// read).</summary>
+ static string Rebody(string tsv)
+ {
+ var lines = tsv.Split('\n').ToList();
+ var rows = lines.Where(l => l.Length > 0 && !l.StartsWith("#") && !l.StartsWith("meta\t")).ToList();
+ int body = lines.FindIndex(l => l.StartsWith("meta\tbody_check\t"));
+ lines[body] = "meta\tbody_check\t" + RegionsRuntime.BodyCheck(rows).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ return string.Join("\n", lines);
+ }
+
+ /// <summary>MapScene's and GameRoot's own paths read the runtime files: each file gets one edited name in its runtime
+ /// form alone (body_check made again, yaml_check still the YAML's), and the booted game shows the edited names. A map or
+ /// a GameRoot that went back to the YAML would show the YAML's names. The region layers take the map's sub-districts.</summary>
+ [Test]
+ public void TheMapAndGameRootReadTheRuntimeFiles()
+ {
+ var inputs = Inputs(); var m = inputs.Map;
+ m.RegionsTsv = Rebody(m.RegionsTsv.Replace("name=s:Acre Sub-District", "name=s:Acre (runtime)"));
+ m.ArmisticeTsv = Rebody(m.ArmisticeTsv.Replace("name=s:Egypt\t", "name=s:Egypt (runtime)\t"));
+ m.ControlTsv = Rebody(m.ControlTsv.Replace("id=s:truce1\t", "id=s:truce1x\t"));
+ foreach (var (tsv, before) in new[] { (m.RegionsTsv, "Acre (runtime)"), (m.ArmisticeTsv, "Egypt (runtime)"), (m.ControlTsv, "truce1x") })
+ StringAssert.Contains(before, tsv);
+ var fallbacks = new List<string>();
+ void Watch(string message, string stack, LogType type) { if (message.Contains("reading the YAML")) fallbacks.Add(message); }
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ Application.logMessageReceived += Watch;
+ GameRoot root;
+ try
+ {
+ map.Build(m);
+ root = Object.FindFirstObjectByType<GameRoot>();
+ root.Store = new SaveStore(saveDir);
+ root.Begin(inputs, 0);
+ }
+ finally { Application.logMessageReceived -= Watch; }
+ CollectionAssert.IsEmpty(fallbacks);
+ Assert.IsNotNull(map.Subdistricts, "the map read the sub-districts for the camps");
+ Assert.AreEqual("Acre (runtime)", map.Subdistricts!.Regions.Single(r => r.Key == "acre").Name, "the map read the runtime file");
+ var regions = root.Regions!;
+ Assert.AreSame(map.Subdistricts, regions.Subdistricts, "GameRoot took the map's sub-districts");
+ Assert.AreEqual("Egypt (runtime)", regions.Armistice!.FrontOf("egypt")!.Name, "GameRoot read the armistice runtime file");
+ Assert.AreEqual("truce1x", regions.Control!.Periods[0].Id, "GameRoot read the control runtime file");
+ }
+
+ /// <summary>The manifest ships the runtime files to the player, beside their YAML (each is checked against it).</summary>
+ [Test]
+ public void TheManifestShipsTheRuntimeFiles()
+ {
+ var files = ContentManifest.Collect(Paths.Content);
+ foreach (var f in new[] { Subdistricts1948.RuntimeFileName, Armistice1949.RuntimeFileName, Control1948.RuntimeFileName,
+ Subdistricts1948.FileName, Armistice1949.FileName, Control1948.FileName })
+ CollectionAssert.Contains(files, "map/" + f);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/RegionsRuntimeTests.cs.meta b/unity/Assets/Tests/EditMode/RegionsRuntimeTests.cs.meta
new file mode 100644
index 000000000..c39d38f66
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/RegionsRuntimeTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 08de8520d8a0469b89d4a3c66cdf8e7c