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 biome colours from a bake at boot, about 310 ms off the map build (refs #321) (#529)

Eyal Golanabe2263d6473
diff --git a/ASSETS.yaml b/ASSETS.yaml
index 8eba4d7b7..3cbf29a96 100644
--- a/ASSETS.yaml
+++ b/ASSETS.yaml
@@ -208,6 +208,11 @@ rules:
source: "tools/land_bake.py (issue #33): the land-use colour and weight (procedural field parcels with farm tracks, garrigue, terraces and scrub) placed by: slope and water from the Copernicus DEM-derived heightmap (Copernicus-DEM); rainfall from CHELSA V2.1 bio12 (CC0-1.0) bias-corrected by the IMS station normals of content/map/precip_stations.json (data.gov.il dataset 481, IMS-data.gov.il, decision D6); content/map/hexes.json biomes (this project's own content, CC-BY-SA-4.0); and the town coordinates of content/map/settlements_1948.yaml (Wikipedia API, CC-BY-SA-4.0) for the citrus belt. Procedural, not AI-generated; attribution in NOTICE"
status: owner-verify
note: "Decision D13 (docs/oss/DECISIONS.md): the owner rules the licence of textures derived from DEM, CHELSA, IMS and coordinate inputs."
+ - glob: "unity/Assets/Resources/Map/BiomeColours.bytes"
+ licence: CC-BY-SA-4.0
+ source: "The biome ground colours (issue #321, #529), baked by Editor BiomeColourBake from the biomes and centres of content/map/hexes.json, the heightmap's bounds (unity/Assets/StreamingAssets/map/heightmap.json) and this project's MapPalette.Ground colours. The biomes are derived by tools/hexgrid.py from the Copernicus DEM GLO-30-derived heightmap (Copernicus-DEM), CHELSA V2.1 bio12 rainfall (CC0-1.0) and the IMS station normals of content/map/precip_stations.json (data.gov.il dataset 481, decision D6); no new facts; attribution in NOTICE"
+ status: owner-verify
+ note: "Decision D13 (docs/oss/DECISIONS.md): the owner rules the licence of data derived from DEM, CHELSA, IMS and coordinate inputs; CC-BY-SA-4.0 is recorded until then."
- glob: "unity/Assets/Textures/*"
licence: Copernicus-DEM
source: "tools/terrain_bake.py from the Copernicus DEM GLO-30-derived heightmap (unity/Assets/StreamingAssets/map/heightmap.*): AO, curvature, sky-view (Map/terrain_bake.png), coast distance (Map/coast.png) and the AO copy (Map/ao.png); the terrain water's mesh samples (Map/terrain_water.bytes, Editor TerrainWaterBake from the same heightmap); attribution in NOTICE"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8f0173a0a..d249fd084 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -241,6 +241,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 biome colours are read from a bake at boot instead of being blended (refs #321), as the routes' ribbons
+ and the water's mesh are. The map looks the same: the bake holds the same texels, and a stale or missing bake is
+ refused with a warning and the colours are blended at load as before. The map build takes about 310 ms less at
+ `--cpu 4` (3050 to 2745 ms under load). `?bootlog` has three more phases: `terrain object created`, `units placed`
+ and `kit buildings built`. Presentation only.
- The map's near (bottom) tilt-shift band is lighter, as on promo 03: gently soft at the play zoom and almost none at the
wide overview, where the foreground is now sharp as on promo 02. On the owner's ruling of 2026-10-14; the far band is
unchanged (#390). Presentation only (#458).
diff --git a/LICENSING.md b/LICENSING.md
index d92516dab..d31d8c768 100644
--- a/LICENSING.md
+++ b/LICENSING.md
@@ -18,6 +18,7 @@ Different parts of this repository are under different licences. Where a file is
| Decision-card and outcome clips | `unity/Assets/StreamingAssets/video/*.mp4` | AI-generated (Veo 3.1 through ElevenLabs; Seedance 2.0 through Dreamina), cut and re-encoded with a burned-in "AI-generated" label; CC0 1.0 under decision D1, used under the owner's ruling D-V in `docs/oss/DECISIONS.md`. Per-file records in `ASSETS.yaml` and `docs/ai-disclosure.md`; the mapping `unity/Assets/Resources/EventVideos/event-videos.yaml` is CC BY 4.0 like the other UI assets; the label `tools/event_videos/ai-bug.png` is CC BY 4.0. |
| Fonts | `unity/Assets/UI/Fonts/` | EB Garamond, [SIL Open Font License 1.1](unity/Assets/UI/Fonts/OFL.txt); Frank Ruhl Libre (`FrankRuhlLibre/`), [SIL Open Font License 1.1](unity/Assets/UI/Fonts/FrankRuhlLibre/OFL.txt) |
| Terrain heightmap | `unity/Assets/StreamingAssets/map/heightmap.*`, `content/map/hexes.json` (elevations) | Derived from Copernicus GLO-30 under the Copernicus DEM licence. Required notice: "produced using Copernicus WorldDEM-30 (c) DLR e.V. 2010-2014 and (c) Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved" |
+| Derived map bakes | `unity/Assets/Resources/Map/BiomeColours.bytes` (biome colours, #529), `unity/Assets/Resources/Routes/RouteRibbons.bytes` (route ribbons, #436) | Made by the editor bakes from the map content (`content/map/`, CC BY-SA 4.0) and the Copernicus-derived heightmap. The hexes' biomes come from the Copernicus DEM, CHELSA V2.1 and the IMS station normals. Recorded as CC BY-SA 4.0 in `ASSETS.yaml`, pending the owner's decision D13 (`docs/oss/DECISIONS.md`; per-file status owner-verify) |
| Precipitation grid | `content/map/precip_bio12.*` | CHELSA V2.1, CC0 1.0 (Karger et al. 2017, 2021; see `tools/README.md`) |
| Rain-gauge data | `content/map/precip_stations.json` | Israel Meteorological Service, data.gov.il dataset 481, under the licence stated on the dataset ("Other (Open)") |
| Unity engine and packages | `unity/Packages/`, `unity/ProjectSettings/` | Configuration only. The Unity engine and its packages are under Unity's own terms and are not included. Two editor-only packages come from OpenUPM under their own licences and are not included either: `com.ivanmurzak.unity.mcp` (Unity-MCP, Apache-2.0) and its dependency `extensions.unity.playerprefsex` (MIT); see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md). No Asset Store content is in this repository. |
diff --git a/docs/oss/DECISIONS.md b/docs/oss/DECISIONS.md
index 327c251fd..908c5afe9 100644
--- a/docs/oss/DECISIONS.md
+++ b/docs/oss/DECISIONS.md
@@ -23,7 +23,7 @@ are already public. If a check fails, the file is removed from the tip with the
- [x] D10 I know that my personal email (commit d42bd6b, `promo/fetch_portraits.py`) and the internal plans, specs and research notes in history are public and cannot be removed (owner ruling: no history rewriting); key rotation is the only remedy for a secret. Decided (owner, 2026-10-10): acknowledged.
- [x] D11 The seven sensitive events (altalena, ten_days, operation_yoav, operation_hiram, operation_horev, bernadotte_assassination, reparations_claim) are sensitivity-reviewed: each event's YAML says `status: sensitivity-reviewed` (docs/m3-release.md, "OWNER STEP: sensitivity review"). The release gate also runs the sim's own check. Decided: the owner signed off all seven on 2026-10-10 for the itch.io build.
- [x] D12 Ruleset bypass. Recommended: the repository admin role bypasses `protect-main` always (you keep merging locally and pushing); everyone else needs review and green checks. Alternative: admins bypass only through a pull request. Decided (owner, 2026-10-10): the recommended admin bypass (`scripts/oss/github/ruleset-main-review.json`).
-- [ ] D13 Licence of the derived land-use texture `unity/Assets/Textures/Map/landuse.png` (`tools/land_bake.py`, issue #33; `ASSETS.yaml` row `owner-verify`). Owner answers four questions. (1) The 1948 settlement coordinates (`content/map/settlements_1948.yaml`, taken from the Wikipedia API, CC BY-SA 4.0) are facts, used only to place the citrus belt near the towns: does share-alike, or the EU database right for about 25 points taken from one source, reach a texture computed from them? (2) D6 found that the data.gov.il licence allows derivatives of the IMS station normals: confirm it covers landuse.png, whose rainfall is CHELSA corrected by them. (3) The Copernicus DEM licence allows redistributing derived products with its attribution (NOTICE carries it), and CHELSA V2.1 is CC0: confirm. (4) Which single `licence:` value does the row take: `Copernicus-DEM` (as now), or the most restrictive input (CC-BY-SA-4.0 if (1) says share-alike applies)? Decided:
+- [ ] D13 Licence of the derived land-use texture `unity/Assets/Textures/Map/landuse.png` (`tools/land_bake.py`, issue #33; `ASSETS.yaml` row `owner-verify`). Owner answers four questions. (1) The 1948 settlement coordinates (`content/map/settlements_1948.yaml`, taken from the Wikipedia API, CC BY-SA 4.0) are facts, used only to place the citrus belt near the towns: does share-alike, or the EU database right for about 25 points taken from one source, reach a texture computed from them? (2) D6 found that the data.gov.il licence allows derivatives of the IMS station normals: confirm it covers landuse.png, whose rainfall is CHELSA corrected by them. (3) The Copernicus DEM licence allows redistributing derived products with its attribution (NOTICE carries it), and CHELSA V2.1 is CC0: confirm. (4) Which single `licence:` value does the row take: `Copernicus-DEM` (as now), or the most restrictive input (CC-BY-SA-4.0 if (1) says share-alike applies)? The same questions cover two derived map bakes, both recorded as `CC-BY-SA-4.0` and `owner-verify` until then: `unity/Assets/Resources/Map/BiomeColours.bytes` (biome colours from `content/map/hexes.json`, whose biomes come from the DEM, CHELSA and the IMS normals; #529) and `unity/Assets/Resources/Routes/RouteRibbons.bytes` (route ribbons on the DEM-derived heightmap; #436). Decided:
- [ ] D-P Portraits: every `owner-verify` row in `ASSETS.portraits.yaml` checked on Commons for its US status, and the `promo/ref/*-src.jpg` and `*-sheet.jpg` provenance confirmed. Check on 2026-10-10: all 26 `owner-verify` rows (13 Government Press Office photos, 1948-1960, each used twice) carry only {{PD-Israel}}/{{PD-IsraelGov}} on Commons, with no US public-domain rationale; the URAA likely restored their US copyright (Israel protected them on 1996-01-01). Verdict: risk in the US. The promo/ref sheets and the AI likenesses in promo/final 04 and 08 derive from them. Needs the owner's call (replace with US-safe sources, see the issue for it). Decided:
- [x] D-B Region border data (`content/map/subdistrict*`, `ASSETS.yaml` row verified). The 1948 sub-districts are digitised from the Survey of Palestine map "Administrative Divisions" (1946, overprinted May 1947) and defined by the Administrative Divisions (Amendment) Proclamation, 1947 (Palestine Gazette No. 1552); area check from Village Statistics 1945. Check on 2026-10-11 (factual, not legal advice): Government of Palestine works got 50 years from publication (Copyright Act 1911, extended to Palestine in 1924), so they are public domain in Israel and the UK since the end of 1997 at the latest; Commons tags scan (a) `06_Palestine-_Administrative_divisions.jpg` {{PD-UK-Gov}} (in the Map template's permission field; NLI accession per Commons "Pal 1143; Pal 1143b; Pal 1196?") and scan (b), the Eran Laor copy (FL147392105), {{PD-UKGov}}{{PD-IsraelGov}}; but, as for D-P, they were protected on 1996-01-01, so a URAA-restored US copyright in the map's drawing (to about 2041-42) is possible. What the repository holds is facts (where legally defined lines run), redrawn by our own method; no image is copied. Also for the owner: the Hebrew and Arabic names (from Wikipedia), the sub-district names as shown (official Gazette English), outlining the Mandate frontier, the Arabic for Samaria District ("لواء السامرة"; "لواء نابلس" is also common), the near-frontier shore hexes (Taba, west of Rafah, the Dead Sea by the Lisan: each follows its nearest land), and moving the entries from `draft` to reviewed. Owner ruling (2026-10-11) on when the layer shows: from the 1948 start until the 1949 armistice lines replace it, each front switching to its armistice line on that agreement's date (Feb-Jul 1949) once that data is built; until then the layer stays, labelled "Mandate sub-districts, 1947" (`content/map/subdistrict_hexes_1948.yaml` `label`, `shown_from`, `shown_until`). Decided (owner-delegated, 2026-10-11): allowed; facts redrawn, no image copied. The repository holds facts (where legally defined lines run), redrawn by our own method from cited sources; no image or drawing is copied or committed, and US copyright does not protect facts (Feist), so a possible URAA copyright in the map's drawing does not reach the data. Further rulings (owner-delegated to the controller, 2026-10-11): the near-frontier shore hexes stay as built (each follows its nearest land); the Mandate frontier outline stays; Samaria District in Arabic stays "لواء السامرة" (no official Arabic Mandate text was reachable online; "لواء نابلس" is the common usage; unverified); the Hebrew and Arabic names from Wikipedia are accepted for now, the source noted per row; the sensitivity review is done (the entries are `sensitivity-reviewed`), while the 1947-48 amendment check stays open. Display rule (controller ruling, owner-delegated, 2026-10-11): the hex that holds a Gazette-listed town always takes that town's sub-district, never `outside` (`tools/borders_bake.py` rule 5; Rafah town's hex is Gaza, Metulla's Safad).
- [ ] D-A The 1949 armistice lines (`content/map/armistice*`, `ASSETS.yaml` row owner-verify). Sources: the four General Armistice Agreements (UNTS vol. 42) and their annexed maps, which are UN documents with symbols and so not copyrighted (UN Administrative Instruction ST/AI/189/Add.9/Rev.2, para. 2; Commons {{PD-UN-doc}}, {{PD-UN-map}}); the Syria map is drawn on a 1:50,000 base of the Service Geographique des FFL, of which nothing is taken but the agreement's own line and zone (drawn by the parties and the UN); the Egypt line uses the Survey of Palestine sheet "Gaza" for three positions (the Wadi Hasi mouth, Deir Suneid, the highway), a Government of Palestine work under D-B; the Lebanon line is the D-B Mandate frontier. Check on 2026-10-11 (factual, not legal advice). Rulings (controller, owner-delegated, and the owner, 2026-10-11): (1) the source plan as built is approved: the agreements and their annexed maps; IBS 46 (1965) only as a named cross-check; (2) Jordan is traced from the low-resolution UNISPAL copy of the signed map 1 (3119 x 8630 px), every feature `source_quality: low_res_scan` and labelled low-accuracy, to be replaced from a full-resolution scan; the Commons "own work" copy ("File:Green Line - Cease Fire Agreement 30 Nov 1948.jpg") is never used without established provenance; Jerusalem (map 2), the no-man's-lands and Mount Scopus are recorded gaps; (3) the 1950 modus vivendi line (S/1471, a signed UN document; sheet 2 from the UN Treaty Collection) is its own feature from 22 Feb 1950, and the 1949 Egypt line south of Gaza stays undrawn; (4) the DMZ part names stand; (5) the sensitivity review is the controller's, after the staff review: entries stay `draft`; (6) the true-polyline overlay is #237, not built now; (7) the Sinai frontier beyond Gaza is not labelled as the Egypt line. Open for the owner: whether a full-resolution Jordan scan is requested from the archives (an outward action). Display, as built: each front switches on its agreement's date (recorded per front in the sub-district layer, `Subdistricts1948.FrontReplaced`); from then its zones are drawn over the sub-districts and the label and info panel name its lines, while the sub-district bands stay as the base (the lines leave gaps). Conventions recorded here: the Jordan line A stages are Art. VI.3 deadlines ('within five / seven / fifteen weeks') and each stretch is shown from its deadline, the actual handover dates not researched; the agreements' own titles ('Egyptian-Israeli', 'Lebanese-Israeli', 'Hashemite Jordan Kingdom-Israel', 'Israeli-Syrian' General Armistice Agreement) are shown in the 'Egypt-Israel' style, a paraphrase; the DMZ part names mix Arabic and Hebrew forms (Tell el Qadi and El Hamma beside Mishmar HaYarden and Ein Gev). Map bases (only the agreements' lines are taken, positions redrawn, no image copied; US copyright does not reach facts): the Syria map's 1:50,000 Service Geographique des FFL base; Jordan map 1's Survey of Palestine 1:250,000 (1946) base, a Government of Palestine work (D-B); the Gaza sheet (D-B); S/1471's base sheets, Survey of Palestine 1:20,000 (rev. 1946) reprinted with a Survey of Israel imprint, an Israeli government reprint of about 1949-50, outside D-B, with a possible US URAA term in the drawing. The Jordan control points' coordinates (Wikidata, CC0; Wikipedia, CC BY-SA) are facts used only to georeference, kept in the MIT tool source.
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index a17715fa4..e94748eec 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -2525,3 +2525,64 @@ whole function, not the arithmetic, as #195 found for the water (3 ms from its s
range did not help. Before adding anything to `StatecraftTerrain.hlsl`, profile it as above against main; prefer changing
baked data the shader already reads in its existing operations (land colours in `tools/land_bake.py`, `MapPalette`), or
moving work out of the function as #195 did.
+
+## Issue #321: boot headroom, the biome colours from a bake
+
+The budget is `map_build_ms` at `--cpu 4` within 2720 ms (Task 1's 1813 ms plus 50%). After #502's hill scatter, main
+measured about 30 ms under it on a quiet machine and over it under load.
+
+**Where the map build goes.** Main `72e2aee`, `tools/headed.py boot --runs 3 --cpu 4`, two rounds under one
+`machine_lock --exclusive` (machine load 4.5-7), median dt of each phase in ms. The branch adds three `?bootlog` markers
+(`terrain object created`, `units placed`, `kit buildings built`) that split the old phases, so its rows are the same
+work in finer pieces.
+
+| phase | main | branch | what it is |
+|---|---|---|---|
+| heightmap decoded | 190-193 | 190-192 | r16z decode (counted from its start) |
+| hexes parsed | 12 | 10-12 | |
+| localities parsed | 81-83 | 78-79 | the baked TSV (#291) |
+| terrain heights set | 1386-1395 | 1390-1400 | `new TerrainData` (about 195 ms, #320's diag) and `SetHeights` |
+| terrain object created | (in the next row) | 82-88 | `Terrain.CreateTerrainGameObject` (the collider) and the layer |
+| biome texture baked | 438-442 | 38-41 | main: the blend of 1024 x 1024 texels; branch: the bake read, the tint, the upload |
+| border skirt | 35-36 | 34-35 | |
+| terrain water | 17-19 | 19-21 | the bake (#320) |
+| settlements placed | 7 | 7-8 | |
+| units placed | (in kits built) | 354-357 | route YAML read and corridors, footprints, unit data and spots |
+| kit buildings built | (in kits built) | 253-260 | `SettlementKits.Build` and the kit meshes |
+| kits built | 812-828 | 216-221 | main: all three rows above; branch: the trees (`Vegetation.Plant`, `VegetationLayer.Init`) |
+| routes built | 47 | 44-46 | the ribbon bake (#436) |
+| map built | 14-15 | 14 | |
+| **map_build_ms** (median of 3) | **3050 / 3073** | **2745 / 2761** | |
+
+The three largest: `terrain heights set` (about 1390 ms, 46%), the kits phase (about 820 ms: units placed 355, kit
+buildings 255, trees 220) and the biome texture (about 440 ms). `first_frame_ms`: main 11225 / 11162, branch
+10821 / 10929.
+
+**The change.** `MapBuilder.BiomePixels` (the BiomeBlender weights of every texel over `MapPalette.Ground`) is baked by
+Editor `BiomeColourBake` into `unity/Assets/Resources/Map/BiomeColours.bytes` (3 MB raw, 71 KB under Brotli -q 11, and
+155 KB more `.data` in a `-compression disabled` build, whose `.data` is LZ4: "SCB1", version, resolution, a
+check of the frame, hex size, blend radius, palette and every hex's centre and biome, then RGB). `MapScene` reads it
+through `BiomeColourFile.Load`; a bake for other inputs is refused with a warning and the colours are blended at load as
+before. The ground tint, the texture and its mipmaps are made as before, from the same texels:
+`BiomeColourBakeTests.TheMapGetsTheSameGroundFromTheBake` compares every texel handed to the tint with and without the
+bake. `tools/tests/test_biome_colour_bake.py` recomputes the header's check in CI, re-blends the texels with a numpy
+port (within 1 per channel: 7 of 3,145,728 channels differ by 1, at x.5 roundings) and pins a fingerprint of the C# that
+makes them, so an edit to the blend fails CI until it is re-baked (review of #529). Re-bake with
+`-executeMethod Statecraft.Game.EditorTools.BiomeColourBake.Bake` after changing `hexes.json`, the heightmap's bounds,
+the palette or the blend.
+
+The biome phase went from about 440 ms to 120 ms (82-88 terrain object, 38-41 the rest); the map build from 3050-3073 to
+2745-2761 ms, about 310 ms less. At this load both are over 2720 ms; on the quieter machine where main measured about
+2690 ms, the same cut leaves about 340 ms of headroom.
+
+**What is left, by expected saving at `--cpu 4`:**
+- `terrain heights set` (about 1390 ms): ship the TerrainData as an asset instead of `SetHeights` at boot. Up to about
+ 1.2 s, but the riskiest: the asset must be copied before the map owns and destroys it, its LOD data must load without
+ a recompute, and the build grows by about 8 MB before compression. Prototype and measure before planning further.
+- `units placed` (about 355 ms): not yet split. Likely the two YAML reads (route paths, units) and the unit spots; a
+ baked runtime form, as #291 did for the localities, would save most of the parse. Low to medium risk, no visible
+ change.
+- The kits (about 255 + 220 ms): bake the kit meshes and tree matrices from their inputs (settlements, localities,
+ population, routes, unit clearings, the `?kitscale` flags fall back). About 300-400 ms, medium risk (many inputs).
+ Without a bake, the hill scatter's per-cell checks could be reordered for 10-20 ms with the same trees.
+- `heightmap decoded` (about 190 ms): smaller, untested.
diff --git a/tools/tests/test_biome_colour_bake.py b/tools/tests/test_biome_colour_bake.py
new file mode 100644
index 000000000..eb6dadf79
--- /dev/null
+++ b/tools/tests/test_biome_colour_bake.py
@@ -0,0 +1,222 @@
+"""The biome colours' bake (unity/Assets/Resources/Map/BiomeColours.bytes, issue #321) is for the shipped map.
+
+The game refuses a bake whose header does not match what it loaded (BiomeColourFile.TryRead: the bake's version, the
+texture's resolution, and BiomeColourFile.Check, FNV-1a over the frame, the hex size, the blend radius, the palette and
+every hex's centre and biome) and then blends the colours at boot, which is slower. CI runs no Unity, so this checks the
+same header here, with the constants read from the C# source: a change to hexes.json, the heightmap's bounds, the palette
+or the blend radius without a re-bake (BiomeColourBake.Bake) fails CI, as the water's and the route ribbons' bakes do.
+
+The header holds the blend's data, not its code. Two more checks cover the code (review of #529, S1):
+- a numpy float32 port of MapBuilder.BiomePixels re-blends the texels from the repository's inputs and compares them with
+ the bake, within 1 per channel (the port and the editor round a few x.5 products differently);
+- a fingerprint of the C# that makes the texels (BiomeBlender, GeoFrame.ToWorld, BiomePixels, BiomeLayerColours,
+ MapPalette.Lit; comments and whitespace left out), so an edit to it fails here until the bake is re-made, the port
+ matches it and the fingerprint is re-pinned. The port alone would not notice an edit made without a re-bake.
+Unity's BiomeColourBakeTests.TheBakedBiomeColoursAreTheOnesTheMapWouldBlend compares every texel exactly."""
+import hashlib
+import json
+import re
+import struct
+from pathlib import Path
+
+import numpy as np
+
+ROOT = Path(__file__).resolve().parents[2]
+BAKE = ROOT / "unity/Assets/Resources/Map/BiomeColours.bytes"
+MAP = ROOT / "unity/Assets/StreamingAssets/map"
+HEXES = ROOT / "content/map/hexes.json"
+SCRIPTS = ROOT / "unity/Assets/Scripts/Map"
+MAGIC = 0x31424353 # "SCB1"
+REBAKE = "run Statecraft.Game.EditorTools.BiomeColourBake.Bake in Unity (BiomeColourFile)"
+
+
+def source(name: str) -> str:
+ return (SCRIPTS / name).read_text()
+
+
+def const(name: str, rel: str) -> str:
+ m = re.search(rf"\b{name}\s*=\s*([0-9]+(?:\.[0-9]+)?)f?\b", source(rel))
+ assert m, f"{name} not found in {rel}"
+ return m.group(1)
+
+
+def f32(v) -> np.float32:
+ return np.float32(v)
+
+
+def palette() -> list[tuple[np.float32, ...]]:
+ """MapPalette.Ground in MapBuilder.Biome's key order: Lit(r, g, b) = min(c * Brightness, MaxChannel), alpha 1."""
+ order = re.findall(r'\["(\w+)"\]\s*=\s*new Color', source("MapBuilder.cs"))
+ lit = dict(re.findall(r'\["(\w+)"\]\s*=\s*Lit\(([^)]*)\)', source("MapPalette.cs")))
+ assert set(order) == set(lit), (order, lit)
+ bright, top = f32(const("Brightness", "MapPalette.cs")), f32(const("MaxChannel", "MapPalette.cs"))
+ out = []
+ for name in order:
+ rgb = [f32(v.strip().rstrip("f")) for v in lit[name].split(",")]
+ out.append(tuple(min(f32(c * bright), top) for c in rgb) + (f32(1.0),))
+ return out
+
+
+def check() -> int:
+ """BiomeColourFile.Check, as a signed int32."""
+ h = 2166136261
+
+ def bits(v: int):
+ nonlocal h
+ v &= 0xFFFFFFFFFFFFFFFF
+ for k in range(8):
+ h = ((h ^ ((v >> (8 * k)) & 0xFF)) * 16777619) & 0xFFFFFFFF
+
+ def single(x: np.float32):
+ bits(struct.unpack("<i", struct.pack("<f", float(x)))[0])
+
+ def double(x: float):
+ bits(struct.unpack("<q", struct.pack("<d", x))[0])
+
+ meta = json.loads((MAP / "heightmap.json").read_text())
+ hexes = json.loads(HEXES.read_text())
+ bits(int(const("BiomeTextureResolution", "MapBuilder.cs")))
+ for k in ("lon0", "lon1", "lat0", "lat1"):
+ double(float(meta[k]))
+ single(f32(f32(meta["width_km"]) * f32(1000))) # MapBuilder.TerrainSize: width_km * 1000f
+ single(f32(f32(meta["length_km"]) * f32(1000)))
+ single(f32(hexes["hex_size_km"]))
+ single(f32(const("BlendRadiusHexes", "BiomeBlender.cs")))
+ for colour in palette():
+ for c in colour:
+ single(c)
+ for hx in hexes["hexes"]:
+ double(float(hx["lon"]))
+ double(float(hx["lat"]))
+ for ch in hx["biome"]:
+ bits(ord(ch))
+ bits(-1)
+ return struct.unpack("<i", struct.pack("<I", h))[0]
+
+
+def test_the_biome_colour_bake_is_for_the_shipped_map():
+ data = BAKE.read_bytes()
+ magic, version, res, baked = struct.unpack_from("<4i", data)
+ assert magic == MAGIC, f"{BAKE.name} is not a biome colour bake"
+ assert version == int(const("Version", "BiomeColourFile.cs")), f"made by another version: {REBAKE}"
+ assert res == int(const("BiomeTextureResolution", "MapBuilder.cs")), f"made at {res} texels a side: {REBAKE}"
+ assert len(data) == 16 + 3 * res * res, "truncated"
+ assert baked == check(), f"made from other hexes, heightmap bounds, palette or blend radius: {REBAKE}"
+
+
+# The fingerprint of the blend's C# code (code_fingerprint). Re-pin only after re-baking (BiomeColourBake.Bake), bumping
+# BiomeColourFile.Version, and checking that test_the_bake_is_the_blend_of_the_shipped_inputs still passes.
+PINNED_CODE = "63e392d75d278b96c016575d47b22b3e76dd4df9cb0af67167f975073174fd17"
+
+
+def method(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, j = 0, i
+ while j < len(text):
+ c = text[j]
+ if c == "{":
+ depth += 1
+ elif c == "}":
+ depth -= 1
+ if depth == 0:
+ return text[i:j + 1]
+ elif c == ";" and depth == 0:
+ return text[i:j + 1]
+ j += 1
+ raise AssertionError(f"{signature}: no end")
+
+
+def code_fingerprint() -> str:
+ parts = [
+ source("BiomeBlender.cs"),
+ method(source("GeoFrame.cs"), "public Vector3 ToWorld("),
+ method(source("MapBuilder.cs"), "public static Color32[] BiomePixels("),
+ method(source("MapBuilder.cs"), "public static Color[] BiomeLayerColours("),
+ method(source("MapPalette.cs"), "static Color Lit("),
+ ]
+ code = "\n".join(re.sub(r"\s+", " ", re.sub(r"//[^\n]*", "", p)).strip() for p in parts)
+ return hashlib.sha256(code.encode()).hexdigest()
+
+
+def test_the_blend_code_is_the_one_the_bake_was_made_with():
+ assert code_fingerprint() == PINNED_CODE, (
+ f"the C# that makes the biome texels changed (fingerprint {code_fingerprint()}): {REBAKE}, bump "
+ "BiomeColourFile.Version, update the numpy port below if the rule changed, then re-pin PINNED_CODE")
+
+
+def reblend() -> np.ndarray:
+ """MapBuilder.BiomePixels in numpy float32 (BiomeBlender.Weights over GeoFrame.ToWorld centres, the palette mix,
+ Color -> Color32): texels (res * res, 3), row 0 = south. From the review of #529 (personal2's port), with the palette,
+ the layer order and the constants read from the C# source."""
+ meta = json.loads((MAP / "heightmap.json").read_text())
+ hexes = json.loads(HEXES.read_text())
+ names = re.findall(r'\["(\w+)"\]\s*=\s*new Color', source("MapBuilder.cs"))
+ cols = np.array([c[:3] for c in palette()], dtype=np.float32)
+ res = int(const("BiomeTextureResolution", "MapBuilder.cs"))
+ W = f32(f32(meta["width_km"]) * f32(1000))
+ L = f32(f32(meta["length_km"]) * f32(1000))
+ lon0, lon1, lat0, lat1 = (float(meta[k]) for k in ("lon0", "lon1", "lat0", "lat1"))
+ cx = np.array([f32((h["lon"] - lon0) / (lon1 - lon0) * float(W)) for h in hexes["hexes"]], dtype=np.float32)
+ cy = np.array([f32((h["lat"] - lat0) / (lat1 - lat0) * float(L)) for h in hexes["hexes"]], dtype=np.float32)
+ lay = np.array([names.index(h["biome"]) for h in hexes["hexes"]])
+ radius = f32(f32(const("BlendRadiusHexes", "BiomeBlender.cs")) * f32(f32(hexes["hex_size_km"]) * f32(1000)))
+ cell = radius
+ kx = np.floor(cx / cell).astype(int)
+ ky = np.floor(cy / cell).astype(int)
+ minX, minY = kx.min(), ky.min()
+ nx, ny = kx.max() - minX + 1, ky.max() - minY + 1
+ cells = [[] for _ in range(nx * ny)]
+ for i in range(len(cx)): # insertion order within each cell, as BiomeBlender
+ cells[(kx[i] - minX) + (ky[i] - minY) * nx].append(i)
+ maxn = max(len(c) for c in cells)
+ tab = -np.ones((nx * ny, maxn), dtype=int)
+ for c, items in enumerate(cells):
+ tab[c, :len(items)] = items
+ xs = np.arange(res, dtype=np.float32)
+ X, Y = np.meshgrid(xs, xs)
+ px = ((X + f32(0.5)) / f32(res) * W).astype(np.float32).ravel()
+ py = ((Y + f32(0.5)) / f32(res) * L).astype(np.float32).ravel()
+ pkx = np.floor(px / cell).astype(int)
+ pky = np.floor(py / cell).astype(int)
+ n = px.size
+ w = np.zeros((len(names), n), dtype=np.float32)
+ total = np.zeros(n, dtype=np.float32)
+ for dx in (-1, 0, 1):
+ gx = pkx + dx - minX
+ for dy in (-1, 0, 1):
+ gy = pky + dy - minY
+ ok = (gx >= 0) & (gx < nx) & (gy >= 0) & (gy < ny)
+ c = np.where(ok, gx + gy * nx, 0)
+ for s in range(maxn):
+ k = np.where(ok, tab[c, s], -1)
+ v = k >= 0
+ kk = np.where(v, k, 0)
+ ddx = (cx[kk] - px).astype(np.float32)
+ ddy = (cy[kk] - py).astype(np.float32)
+ mag = np.sqrt((ddx * ddx + ddy * ddy).astype(np.float64)).astype(np.float32)
+ t = (mag / radius).astype(np.float32)
+ v &= t < f32(1)
+ f = (f32(1) - t * t * (f32(3) - f32(2) * t)).astype(np.float32)
+ for layer in range(len(names)):
+ m = v & (lay[kk] == layer)
+ w[layer] = np.where(m, w[layer] + f, w[layer])
+ total = np.where(v, total + f, total)
+ pos = total > 0
+ w = np.where(pos, w / np.where(pos, total, f32(1)), w).astype(np.float32)
+ for i in np.nonzero(~pos)[0]: # no centre in reach: the nearest centre's biome
+ d = ((cx - px[i]) ** 2 + (cy - py[i]) ** 2).astype(np.float32)
+ w[:, i] = 0
+ w[lay[int(np.argmin(d))], i] = 1
+ rgb = np.zeros((n, 3), dtype=np.float32)
+ for layer in range(len(names)):
+ rgb = (rgb + cols[layer][None, :] * w[layer][:, None]).astype(np.float32)
+ return np.round(np.clip(rgb, 0, 1) * f32(255)).astype(np.uint8)
+
+
+def test_the_bake_is_the_blend_of_the_shipped_inputs():
+ data = BAKE.read_bytes()
+ baked = np.frombuffer(data, dtype=np.uint8, offset=16).reshape(-1, 3)
+ diff = np.abs(reblend().astype(int) - baked.astype(int))
+ assert diff.max() <= 1, f"a texel differs by {diff.max()} from the blend: {REBAKE}"
+ assert int((diff > 0).sum()) <= 64, f"{int((diff > 0).sum())} channels differ by 1 from the blend: {REBAKE}"
diff --git a/unity/Assets/Editor/BiomeColourBake.cs b/unity/Assets/Editor/BiomeColourBake.cs
new file mode 100644
index 000000000..129f0679e
--- /dev/null
+++ b/unity/Assets/Editor/BiomeColourBake.cs
@@ -0,0 +1,31 @@
+using System.IO;
+using Statecraft.Game.Map;
+using UnityEditor;
+
+namespace Statecraft.Game.EditorTools
+{
+ /// <summary>Bakes the biome colours (MapBuilder.BiomePixels) from the shipped hexes and heightmap frame into
+ /// BiomeColourFile.AssetPath, so a player reads them instead of blending them at boot (issue #321). Re-run it whenever
+ /// hexes.json, the heightmap's bounds, MapPalette.Ground or the blend change (BiomeColourBakeTests fails until then;
+ /// the map also falls back to blending them). Run headless:
+ /// Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod
+ /// Statecraft.Game.EditorTools.BiomeColourBake.Bake</summary>
+ public static class BiomeColourBake
+ {
+ public static byte[] Bytes()
+ {
+ var (meta, _) = HeightmapLoader.Load(Paths.StreamingMap);
+ var hexes = MapBuilder.LoadHexes(Path.Combine(Paths.Content, "map", "hexes.json"));
+ var size = MapBuilder.TerrainSize(meta);
+ var frame = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, size.x, size.z);
+ return BiomeColourFile.Bytes(frame, hexes, MapBuilder.BiomePixels(frame, hexes));
+ }
+
+ public static void Bake()
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(BiomeColourFile.AssetPath));
+ File.WriteAllBytes(BiomeColourFile.AssetPath, Bytes());
+ AssetDatabase.ImportAsset(BiomeColourFile.AssetPath);
+ }
+ }
+}
diff --git a/unity/Assets/Editor/BiomeColourBake.cs.meta b/unity/Assets/Editor/BiomeColourBake.cs.meta
new file mode 100644
index 000000000..aedb09be3
--- /dev/null
+++ b/unity/Assets/Editor/BiomeColourBake.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 41b50a70f5e942d1902c93b4c6622be4
diff --git a/unity/Assets/Resources/Map.meta b/unity/Assets/Resources/Map.meta
new file mode 100644
index 000000000..678dd0b20
--- /dev/null
+++ b/unity/Assets/Resources/Map.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: cad9e92b659044faf850a09904d34421
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Resources/Map/BiomeColours.bytes b/unity/Assets/Resources/Map/BiomeColours.bytes
new file mode 100644
index 000000000..b636240c8
Binary files /dev/null and b/unity/Assets/Resources/Map/BiomeColours.bytes differ
diff --git a/unity/Assets/Resources/Map/BiomeColours.bytes.meta b/unity/Assets/Resources/Map/BiomeColours.bytes.meta
new file mode 100644
index 000000000..8a7e5cda7
--- /dev/null
+++ b/unity/Assets/Resources/Map/BiomeColours.bytes.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 8f7b1fe411f67490aa6b73984aa33631
+TextScriptImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Scripts/Map/BiomeBlender.cs b/unity/Assets/Scripts/Map/BiomeBlender.cs
index fb09f4d8c..97ff9a8a2 100644
--- a/unity/Assets/Scripts/Map/BiomeBlender.cs
+++ b/unity/Assets/Scripts/Map/BiomeBlender.cs
@@ -6,7 +6,9 @@ namespace Statecraft.Game.Map
{
/// <summary>Blended biome weights (spec §6): every hex centre within <see cref="BlendRadiusHexes"/> hex radii of a point
/// contributes 1 - smoothstep(distance / radius); weights are normalised to sum to 1. A point no centre reaches (map
- /// edge, beyond the outermost centres) takes the nearest centre's biome. Deterministic: fixed iteration order.</summary>
+ /// edge, beyond the outermost centres) takes the nearest centre's biome. Deterministic: fixed iteration order.
+ /// The biome colours are baked from it (BiomeColourFile): a change to the weights needs a re-bake and a bump of
+ /// BiomeColourFile.Version (tools/tests/test_biome_colour_bake.py fails until then).</summary>
public sealed class BiomeBlender
{
/// <summary>Falloff radius in hex radii. Neighbouring centres are sqrt(3) = 1.732 radii apart, so 1.72 keeps every
diff --git a/unity/Assets/Scripts/Map/BiomeColourFile.cs b/unity/Assets/Scripts/Map/BiomeColourFile.cs
new file mode 100644
index 000000000..56ea5db21
--- /dev/null
+++ b/unity/Assets/Scripts/Map/BiomeColourFile.cs
@@ -0,0 +1,87 @@
+#nullable enable
+using System;
+using System.Buffers.Binary;
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>BiomeColours.bytes (issue #321): MapBuilder.BiomePixels baked by Editor BiomeColourBake, so a player reads the
+ /// biome colours instead of blending them at boot. "SCB1", the version, the resolution and a check of the inputs (the
+ /// frame, the hexes, the blend radius and the palette), all little-endian int32, then each texel's R, G and B, row 0 =
+ /// south (alpha is always 255). A bake for other inputs is refused, and the map blends the colours itself.</summary>
+ public static class BiomeColourFile
+ {
+ public const string Resource = "Map/BiomeColours";
+ public const string AssetPath = "Assets/Resources/Map/BiomeColours.bytes";
+ /// <summary>Bump it when the code that makes the texels changes: MapBuilder.BiomePixels and BiomeLayerColours,
+ /// BiomeBlender, GeoFrame.ToWorld or MapPalette.Lit (their data is checked on its own). The pytest
+ /// tools/tests/test_biome_colour_bake.py pins a fingerprint of that code.</summary>
+ public const int Version = 1;
+ const int Magic = 0x31424353; // "SCB1"
+ const int HeaderBytes = 16;
+
+ public static byte[] Bytes(GeoFrame frame, HexFile hexes, Color32[] px)
+ {
+ int res = MapBuilder.BiomeTextureResolution;
+ if (px.Length != res * res) throw new ArgumentException($"{px.Length} texels, not {res} x {res}", nameof(px));
+ var bytes = new byte[HeaderBytes + 3 * px.Length];
+ var head = new[] { Magic, Version, res, Check(frame, hexes) };
+ for (int k = 0; k < head.Length; k++) BinaryPrimitives.WriteInt32LittleEndian(bytes.AsSpan(4 * k), head[k]);
+ for (int i = 0, o = HeaderBytes; i < px.Length; i++, o += 3) { bytes[o] = px[i].r; bytes[o + 1] = px[i].g; bytes[o + 2] = px[i].b; }
+ return bytes;
+ }
+
+ /// <summary>Fills <paramref name="px"/> from a bake; false (and the reason) when it is not for these inputs.</summary>
+ public static bool TryRead(byte[]? bytes, GeoFrame frame, HexFile hexes, Color32[] px, out string reason)
+ {
+ int res = MapBuilder.BiomeTextureResolution;
+ if (bytes == null || bytes.Length < HeaderBytes) { reason = "missing or short"; return false; }
+ var head = new int[4];
+ for (int k = 0; k < head.Length; k++) head[k] = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(4 * k));
+ if (head[0] != Magic) { reason = "not a biome colour bake"; return false; }
+ if (head[1] != Version) { reason = $"version {head[1]}, this build reads {Version} (re-bake: BiomeColourBake.Bake)"; return false; }
+ if (head[2] != res || px.Length != res * res) { reason = $"made at {head[2]} texels a side, the map takes {res}"; return false; }
+ if (head[3] != Check(frame, hexes)) { reason = "made from other hexes, frame, hex size, blend radius or palette (re-bake: BiomeColourBake.Bake)"; return false; }
+ if (bytes.Length != HeaderBytes + 3L * px.Length) { reason = "truncated"; return false; }
+ for (int i = 0, o = HeaderBytes; i < px.Length; i++, o += 3) px[i] = new Color32(bytes[o], bytes[o + 1], bytes[o + 2], 255);
+ reason = "";
+ return true;
+ }
+
+ /// <summary>The baked texels for these inputs, or null (with a warning) when the bake is missing or for others.</summary>
+ public static Color32[]? Load(GeoFrame frame, HexFile hexes)
+ {
+ var asset = Resources.Load<TextAsset>(Resource);
+ string why = "missing";
+ if (asset != null)
+ {
+ var px = new Color32[MapBuilder.BiomeTextureResolution * MapBuilder.BiomeTextureResolution];
+ bool ok = TryRead(asset.bytes, frame, hexes, px, out why);
+ if (!Application.isEditor) Resources.UnloadAsset(asset); // its bytes were copied; drop the native copy
+ if (ok) return px;
+ }
+ Debug.LogWarning($"MAP {AssetPath}: {why}; blending the biome colours at load");
+ return null;
+ }
+
+ /// <summary>FNV-1a over what the texels depend on: the resolution, the frame's bounds and size, the hex size and blend radius,
+ /// each layer's colour, and every hex's centre and biome.</summary>
+ public static int Check(GeoFrame frame, HexFile hexes)
+ {
+ uint h = 2166136261;
+ void Bits(long v) { for (int k = 0; k < 8; k++) { h ^= (uint)(v >> (8 * k)) & 0xFF; h *= 16777619; } }
+ void Single(float f) => Bits(BitConverter.SingleToInt32Bits(f));
+ Bits(MapBuilder.BiomeTextureResolution);
+ foreach (var d in new[] { frame.Lon0, frame.Lon1, frame.Lat0, frame.Lat1 }) Bits(BitConverter.DoubleToInt64Bits(d));
+ Single(frame.WidthM); Single(frame.LengthM); Single(hexes.hex_size_km); Single(BiomeBlender.BlendRadiusHexes);
+ foreach (var c in MapBuilder.BiomeLayerColours()) { Single(c.r); Single(c.g); Single(c.b); Single(c.a); }
+ foreach (var hex in hexes.hexes)
+ {
+ Bits(BitConverter.DoubleToInt64Bits(hex.lon)); Bits(BitConverter.DoubleToInt64Bits(hex.lat));
+ foreach (var ch in hex.biome) Bits(ch);
+ Bits(-1);
+ }
+ return (int)h;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/BiomeColourFile.cs.meta b/unity/Assets/Scripts/Map/BiomeColourFile.cs.meta
new file mode 100644
index 000000000..64d32a211
--- /dev/null
+++ b/unity/Assets/Scripts/Map/BiomeColourFile.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 04bb6e0cd8994e48bf5b35914d87f91c
diff --git a/unity/Assets/Scripts/Map/GeoFrame.cs b/unity/Assets/Scripts/Map/GeoFrame.cs
index ba5a4eb2b..2129434e0 100644
--- a/unity/Assets/Scripts/Map/GeoFrame.cs
+++ b/unity/Assets/Scripts/Map/GeoFrame.cs
@@ -2,7 +2,9 @@ using UnityEngine;
namespace Statecraft.Game.Map
{
- /// <summary>Equirectangular lon/lat -> world metres. x = east, z = north, origin = south-west corner.</summary>
+ /// <summary>Equirectangular lon/lat -> world metres. x = east, z = north, origin = south-west corner. The biome colours
+ /// are baked from ToWorld's hex centres (BiomeColourFile): a change to it needs a re-bake and a bump of
+ /// BiomeColourFile.Version (tools/tests/test_biome_colour_bake.py fails until then).</summary>
public readonly struct GeoFrame
{
public readonly double Lon0, Lon1, Lat0, Lat1; public readonly float WidthM, LengthM;
diff --git a/unity/Assets/Scripts/Map/Kits/KitLayer.cs b/unity/Assets/Scripts/Map/Kits/KitLayer.cs
index afc15b949..74e8a1652 100644
--- a/unity/Assets/Scripts/Map/Kits/KitLayer.cs
+++ b/unity/Assets/Scripts/Map/Kits/KitLayer.cs
@@ -68,6 +68,7 @@ namespace Statecraft.Game.Map.Kits
stats.Localities = localities.Count; stats.LocalityBuildings = built.LocalityBuildings; stats.Camps = built.Camps; stats.Tents = built.Tents;
stats.Buildings += built.LocalityBuildings + built.Tents;
stats.BuildMs = (float)clock.Elapsed.TotalMilliseconds;
+ Boot.DiagLog.BootPhase("kit buildings built"); // issue #321: the buildings, apart from the trees
clock.Restart();
var all = new List<Settlement>(settlements); all.AddRange(localities);
var trees = Vegetation.Plant(all, ground);
diff --git a/unity/Assets/Scripts/Map/MapBuilder.cs b/unity/Assets/Scripts/Map/MapBuilder.cs
index 2bc38edb6..f381d8721 100644
--- a/unity/Assets/Scripts/Map/MapBuilder.cs
+++ b/unity/Assets/Scripts/Map/MapBuilder.cs
@@ -58,7 +58,12 @@ namespace Statecraft.Game.Map
/// <see cref="BiomeTextureResolution"/> square over the map) before they are uploaded, so the settlement kits can tint
/// the ground of their footprints (art spike) at no cost per frame.</summary>
public static GameObject Build(HeightmapMeta meta, float[,] heights, HexFile hexFile, Material terrainMaterial,
- Action<Color32[], int, GeoFrame> paintGround)
+ Action<Color32[], int, GeoFrame> paintGround) => Build(meta, heights, hexFile, terrainMaterial, paintGround, false);
+
+ /// <summary>As Build; with <paramref name="bakedBiome"/> the biome colours are read from their bake
+ /// (BiomeColourFile, issue #321: boot time) when it was made from these inputs, else blended here.</summary>
+ public static GameObject Build(HeightmapMeta meta, float[,] heights, HexFile hexFile, Material terrainMaterial,
+ Action<Color32[], int, GeoFrame> paintGround, bool bakedBiome)
{
if (meta == null) throw new ArgumentNullException(nameof(meta));
if (heights == null) throw new ArgumentNullException(nameof(heights));
@@ -84,7 +89,8 @@ namespace Statecraft.Game.Map
terrain.basemapDistance = NoBasemapDistanceM;
data.terrainLayers = new[] { NeutralLayer(assets) }; // one layer, one pass: the graph paints from the biome texture
data.alphamapResolution = 16;
- MapShaderGlobals.Apply(terrain, meta, hexFile.hex_size_km * 1000f, BakeBiomeTexture(frame, hexFile, assets, paintGround), assets);
+ Boot.DiagLog.BootPhase("terrain object created"); // issue #321: splits the terrain object from the biome colours
+ MapShaderGlobals.Apply(terrain, meta, hexFile.hex_size_km * 1000f, BakeBiomeTexture(frame, hexFile, assets, paintGround, bakedBiome), assets);
Boot.DiagLog.BootPhase("biome texture baked");
MapBorders.Apply(hexFile, assets); // region borders: none drawn until a layer is given (MapBorders.Use)
return terrainGo;
@@ -137,12 +143,27 @@ namespace Statecraft.Game.Map
/// <summary>The ground colour of every point, blended from the biomes of nearby hex centres (BiomeBlender) in the
/// MapPalette.Ground colours, baked once into an sRGB texture over the whole map (texel row 0 = south) that the
- /// terrain shader samples as _ScBiomeTex. Owned by the map.</summary>
- static Texture2D BakeBiomeTexture(GeoFrame frame, HexFile hexes, MapRuntimeAssets assets, Action<Color32[], int, GeoFrame> paint)
+ /// terrain shader samples as _ScBiomeTex. Owned by the map. With <paramref name="baked"/> the colours come from
+ /// BiomeColourFile when it matches these inputs.</summary>
+ static Texture2D BakeBiomeTexture(GeoFrame frame, HexFile hexes, MapRuntimeAssets assets, Action<Color32[], int, GeoFrame> paint, bool baked)
+ {
+ int res = BiomeTextureResolution;
+ var tex = assets.Own(new Texture2D(res, res, TextureFormat.RGBA32, true, false)
+ { name = "BiomeColour", wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Trilinear });
+ var px = baked ? BiomeColourFile.Load(frame, hexes) : null;
+ px ??= BiomePixels(frame, hexes);
+ paint?.Invoke(px, res, frame);
+ tex.SetPixels32(px); tex.Apply(true, true); // no CPU copy: nothing reads the pixels back (about 5.6 MB on the heap)
+ return tex;
+ }
+
+ /// <summary>The biome colour texels (<see cref="BiomeTextureResolution"/> square, row 0 = south) before the ground
+ /// tint: every texel centre's BiomeBlender weights over the MapPalette.Ground colours. Editor BiomeColourBake bakes
+ /// them (BiomeColourFile).</summary>
+ public static Color32[] BiomePixels(GeoFrame frame, HexFile hexes)
{
var names = new List<string>(Biome.Keys);
- var colours = new Color[names.Count];
- for (int i = 0; i < names.Count; i++) colours[i] = MapPalette.Ground[names[i]];
+ var colours = BiomeLayerColours();
var centres = new List<Vector2>(hexes.hexes.Length); var layerOf = new List<int>(hexes.hexes.Length);
foreach (var h in hexes.hexes)
{
@@ -150,8 +171,6 @@ namespace Statecraft.Game.Map
}
var blender = new BiomeBlender(centres, layerOf, hexes.hex_size_km * 1000f, names.Count);
int res = BiomeTextureResolution;
- var tex = assets.Own(new Texture2D(res, res, TextureFormat.RGBA32, true, false)
- { name = "BiomeColour", wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Trilinear });
var px = new Color32[res * res]; var wts = new float[names.Count];
for (int y = 0; y < res; y++)
for (int x = 0; x < res; x++)
@@ -162,9 +181,17 @@ namespace Statecraft.Game.Map
c.a = 1f;
px[y * res + x] = c;
}
- paint?.Invoke(px, res, frame);
- tex.SetPixels32(px); tex.Apply(true, true); // no CPU copy: nothing reads the pixels back (about 5.6 MB on the heap)
- return tex;
+ return px;
+ }
+
+ /// <summary>The ground colour of each biome layer, in the order of <see cref="BiomeColours"/>' keys (the blend's
+ /// layer indices).</summary>
+ public static Color[] BiomeLayerColours()
+ {
+ var names = new List<string>(Biome.Keys);
+ var colours = new Color[names.Count];
+ for (int i = 0; i < names.Count; i++) colours[i] = MapPalette.Ground[names[i]];
+ return colours;
}
/// <summary>A heightmap sample this close to 0 m is sea (tools/dem_to_heightmap.py writes open sea as exactly 0 m).</summary>
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index 0e56869dc..d2f829cda 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -231,7 +231,7 @@ namespace Statecraft.Game.Map
var tint = System.Diagnostics.Stopwatch.StartNew();
Kits.SettlementKits.PaintGround(px, res, frame, painted, hexSizeM);
Debug.Log(FormattableString.Invariant($"KITS ground_tint_ms={tint.Elapsed.TotalMilliseconds:0.0} places={painted.Count}"));
- } : null);
+ } : null, bakedBiome: true); // the biome colours from their bake (issue #321: boot time)
terrainGo.transform.SetParent(transform, true);
Terrain = terrainGo.GetComponent<Terrain>();
var size = Terrain.terrainData.size;
@@ -269,6 +269,7 @@ namespace Statecraft.Game.Map
}
}
UnitClearings = clearings;
+ DiagLog.BootPhase("units placed"); // issue #321: the routes' corridors, the footprints and the unit spots
if (kitsOn)
{
// ?kitscale=, ?housescale=, ?treescale= in the WebGL player: the same layout at another symbolic scale (city
diff --git a/unity/Assets/Tests/EditMode/BiomeColourBakeTests.cs b/unity/Assets/Tests/EditMode/BiomeColourBakeTests.cs
new file mode 100644
index 000000000..edb362aa6
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/BiomeColourBakeTests.cs
@@ -0,0 +1,93 @@
+#nullable enable
+using System.Collections.Generic;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Map;
+using UnityEditor;
+using UnityEngine;
+
+/// <summary>Issue #321: the biome ground colours (MapBuilder.BiomePixels, about a third of the "biome texture baked" boot
+/// phase's work) are baked into BiomeColours.bytes by Editor BiomeColourBake, so a player reads them instead of blending
+/// a million texels at boot. The bake must be what the map would blend now, texel for texel, so the map looks the same;
+/// a bake made from other inputs is refused and the map blends the colours itself, so it is never wrong, only slower.</summary>
+public class BiomeColourBakeTests
+{
+ static (HeightmapMeta meta, float[,] heights, HexFile hexes, GeoFrame frame) Inputs()
+ {
+ var (meta, heights) = HeightmapLoader.Load(Paths.StreamingMap);
+ var hexes = MapBuilder.LoadHexes(System.IO.Path.Combine(Paths.Content, "map", "hexes.json"));
+ var size = MapBuilder.TerrainSize(meta);
+ return (meta, heights, hexes, new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, size.x, size.z));
+ }
+
+ [Test]
+ public void TheBakedBiomeColoursAreTheOnesTheMapWouldBlend()
+ {
+ var (_, _, hexes, frame) = Inputs();
+ var baked = AssetDatabase.LoadAssetAtPath<TextAsset>(BiomeColourFile.AssetPath);
+ Assert.IsNotNull(baked, BiomeColourFile.AssetPath);
+ var blended = MapBuilder.BiomePixels(frame, hexes);
+ CollectionAssert.AreEqual(BiomeColourFile.Bytes(frame, hexes, blended), baked.bytes,
+ "stale: re-run Statecraft.Game.EditorTools.BiomeColourBake.Bake");
+ var read = new Color32[blended.Length];
+ Assert.IsTrue(BiomeColourFile.TryRead(baked.bytes, frame, hexes, read, out var why), why);
+ for (int i = 0; i < blended.Length; i++)
+ if (!blended[i].Equals(read[i])) Assert.Fail($"texel {i}: baked {read[i]}, blended {blended[i]}");
+ }
+
+ [Test]
+ public void ABakeFromOtherInputsIsRefused()
+ {
+ var (meta, _, hexes, frame) = Inputs();
+ var asset = AssetDatabase.LoadAssetAtPath<TextAsset>(BiomeColourFile.AssetPath);
+ Assert.IsNotNull(asset, BiomeColourFile.AssetPath);
+ var bytes = asset.bytes;
+ var px = new Color32[MapBuilder.BiomeTextureResolution * MapBuilder.BiomeTextureResolution];
+ Assert.IsTrue(BiomeColourFile.TryRead(bytes, frame, hexes, px, out var why), why);
+
+ var h = hexes.hexes[400]; var was = h.biome;
+ h.biome = was == "desert" ? "hills" : "desert";
+ Assert.IsFalse(BiomeColourFile.TryRead(bytes, frame, hexes, px, out why), "another biome");
+ h.biome = was;
+ var wider = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, frame.WidthM + 1f, frame.LengthM);
+ Assert.IsFalse(BiomeColourFile.TryRead(bytes, wider, hexes, px, out why), "another frame");
+ Assert.IsFalse(BiomeColourFile.TryRead(new byte[12], frame, hexes, px, out why), "short");
+ var cut = new byte[bytes.Length - 3]; System.Array.Copy(bytes, cut, cut.Length); // a whole header, a texel short
+ Assert.IsFalse(BiomeColourFile.TryRead(cut, frame, hexes, px, out why), "truncated");
+ StringAssert.Contains("truncated", why);
+ var flipped = (byte[])bytes.Clone(); flipped[0] ^= 1;
+ Assert.IsFalse(BiomeColourFile.TryRead(flipped, frame, hexes, px, out why), "not a bake");
+ }
+
+ /// <summary>The boot path: MapBuilder.Build with the bake hands the ground tint (and so the texture) exactly the texels
+ /// it hands it without, and logs no fallback.</summary>
+ [Test]
+ public void TheMapGetsTheSameGroundFromTheBake()
+ {
+ var (meta, heights, hexes, _) = Inputs();
+ var material = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Terrain.mat");
+ Assert.IsNotNull(material);
+ Color32[] Ground(bool baked)
+ {
+ Color32[]? seen = null;
+ var go = MapBuilder.Build(meta, heights, hexes, material, (px, res, f) => seen = (Color32[])px.Clone(), baked);
+ try { Assert.IsNotNull(seen); return seen!; }
+ finally
+ {
+ go.GetComponent<MapRuntimeAssets>().RunTeardown();
+ Object.DestroyImmediate(go);
+ }
+ }
+ var derived = new List<string>();
+ void Watch(string message, string stack, LogType type) { if (message.Contains("blending the biome colours")) derived.Add(message); }
+ Application.logMessageReceived += Watch;
+ Color32[] fromBake;
+ try { fromBake = Ground(true); }
+ finally { Application.logMessageReceived -= Watch; }
+ CollectionAssert.IsEmpty(derived, "the map uses the bake");
+ var blended = Ground(false);
+ Assert.AreEqual(blended.Length, fromBake.Length);
+ for (int i = 0; i < blended.Length; i++)
+ if (!blended[i].Equals(fromBake[i])) Assert.Fail($"texel {i}: baked {fromBake[i]}, blended {blended[i]}");
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/BiomeColourBakeTests.cs.meta b/unity/Assets/Tests/EditMode/BiomeColourBakeTests.cs.meta
new file mode 100644
index 000000000..a83c2dcbd
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/BiomeColourBakeTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 989d8a0c43f54b6ca2a9b6a372e23fb3