A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: settlement kits and trees in place of the marker boxes (promo look, step 1) (#179)
Eyal Golan02f2e9ac2ecf
diff --git a/ASSETS.yaml b/ASSETS.yamlindex 8c5293a9e..5107f7523 100644--- a/ASSETS.yaml+++ b/ASSETS.yaml@@ -90,10 +90,19 @@ rules:source: "Israel Meteorological Service, data.gov.il dataset 481, via tools/ims_normals.py; licence 'Other (Open)' with no licence URL"status: owner-verifynote: "Decision D6 (the M3 plan's deferred 'Legal review of map-data licences' row). Published 2026-10-10 before the check."- - glob: "content/map/settlement*.yaml"+ - glob: "content/map/settlements_1948.yaml"licence: CC-BY-SA-4.0source: "Coordinates from the Wikipedia API (prop=coordinates) and tools/settlement_hexes.py; per-settlement URLs and check dates in settlements_1948.yaml"status: verified+ - glob: "content/map/settlement_hexes.yaml"+ licence: CC-BY-SA-4.0+ source: "Generated by tools/settlement_hexes.py from settlements_1948.yaml and hexes.json"+ status: verified+ - glob: "content/map/settlement_population_1945.yaml"+ licence: CC-BY-SA-4.0+ source: "Village Statistics, 1945 (Government of Palestine), figures read from https://en.wikipedia.org/wiki/Village_Statistics,_1945 on 2026-10-11; per-row sources in the file"+ status: owner-verify+ note: "Presentation only (settlement kit footprints); the sim never reads it. To be checked against a scan of the 1945 publication."# --- Baked map textures (derived from the heightmap) ---- glob: "unity/Assets/Textures/*"licence: Copernicus-DEMdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 893934cce..44729acb0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB- A runtime quality fallback for slow machines in the browser: when frames stay slower than 30 fps, the game lowers itsrender scale (to 0.9, then 0.8) and then turns the tilt-shift off, and steps back up when frames are comfortably fastagain. Presentation only; `?nofallback` turns it off (#44).+- Map: procedural settlement kits and instanced trees (placeholder art) replace the marker boxes: a white Tel Aviv,+ stone Jaffa with its harbour, Arab towns, moshavot and kibbutzim sized by their 1945 population+ (`content/map/settlement_population_1945.yaml`), with citrus groves, olives, palms and cypresses, at the owner's+ symbolic scale (about 60x real size for city blocks, 100x for houses and trees). Presentation only (#31, #32, #34).- The sea and coast in the promo look: turquoise shallows that deepen to a muted blue offshore, rolling surf filteredso it does not shimmer, a fine chop, and a sand strip with wet sand along every sea-level coast (salt flats at theDead Sea). Presentation only.diff --git a/content/map/settlement_population_1945.yaml b/content/map/settlement_population_1945.yamlnew file mode 100644index 000000000..0573f96c3--- /dev/null+++ b/content/map/settlement_population_1945.yaml@@ -0,0 +1,183 @@+# Population of each place in settlements_1948.yaml in the Mandate government's Village Statistics, 1945 (figures as of+# 1 April 1945). Presentation only: it sizes the settlement kits' footprints (owner ruling: towns spread over hexes in+# proportion to population; unity/Assets/Scripts/Map/Kits/KitPopulation.cs). The sim never reads it: ContentLoader reads+# named files only, so this file is outside the content hash and saves and goldens do not depend on it.+# Primary source: Government of Palestine, Village Statistics, April 1945 (Office of Statistics and Department of Lands;+# reprinted in S. Hadawi, Village Statistics of 1945, PLO Research Center, 1970). No scan of its town totals was reachable+# on 2026-10-11, so every figure was read from the Wikipedia table of the publication and stays owner-verify until it is+# checked against a scan. The page itself warns that locality figures are rough.+settlements:+- id: jerusalem+ population: 157080+ listed_as: "Jerusalem (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: tel_aviv+ population: 166660+ listed_as: "Tel Aviv (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: jaffa+ population: 94310+ listed_as: "Jaffa (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: haifa+ population: 138300+ listed_as: "Haifa (includes Ahuzzat Sir Herbert Samuel)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: acre+ population: 12360+ listed_as: "Acre (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: tiberias+ population: 11310+ listed_as: "Tiberias (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: safed+ population: 11930+ listed_as: "Safad (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: nazareth+ population: 14200+ listed_as: "Nazareth (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: lod+ population: 16780+ listed_as: "Lydda (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: ramla+ population: 15160+ listed_as: "Ramle (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: gaza+ population: 34250+ listed_as: "Gaza (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: beersheba+ population: 5570+ listed_as: "Beersheba"+ note: "The page's Beersheba row is garbled; 5,570 is its most likely reading. Check against the scan."+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: petah_tikva+ population: 17250+ listed_as: "Petah Tiqva (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: rishon_lezion+ population: 8100+ listed_as: "Rishon le Zion (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: zikhron_yaakov+ population: 1740+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: rosh_pinna+ population: 340+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: rehovot+ population: 10020+ listed_as: "Rehovot (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: hadera+ population: 7830+ listed_as: "Hadera (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: netanya+ population: 5070+ listed_as: "Natanya (Urban)"+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: degania_alef+ population: 290+ listed_as: "Deganiya 'A'"+ note: "Deganiya 'A' only (Deganiya 'B', 380, is a separate settlement)."+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: ein_harod+ population: 1060+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: nahalal+ population: 1090+ listed_as: "Nahalal and Shimron"+ note: "Listed together with Shimron; the combined figure is used."+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: hanita+ population: 240+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: revivim+ population: null+ note: "Not listed (founded 1943); the kit takes the smallest footprint."+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'+- id: yad_mordechai+ population: null+ note: "Not listed (founded 1943); the kit takes the smallest footprint."+ status: owner-verify+ sources:+ - url: https://en.wikipedia.org/wiki/Village_Statistics,_1945+ checked: '2026-10-11'diff --git a/docs/dev-setup.md b/docs/dev-setup.mdindex fc8a76e32..d8864377b 100644--- a/docs/dev-setup.md+++ b/docs/dev-setup.md@@ -24,7 +24,7 @@- Page flags: `?golden` (golden check), `?smoke=N` (play N turns through the UI; bare `?smoke` = 5, `?smoke=0` = off),`?profile` (terrain profile), `?camlog` (log the camera distance), `?bootlog` (each boot phase's timing) and `?navlog`(every UI pointer and submit event, screen toggle and map click, with its frame), `?vprofile` (the visual frame-time- profile per feature) and `?shot` (screenshots at the promo poses as `SHOT` console lines). Desktop players take `-golden`,+ profile per feature), `?shot` (screenshots at the promo poses as `SHOT` console lines) and `?kitscale=N`, `?housescale=N`, `?treescale=N` (the settlement kits' symbolic scale for city blocks, houses and trees, clamped to 5–200; defaults 60, 100, 100). In the editor, `MapCapture.Kits` takes `-kitScale`, `-houseScale` and `-treeScale`. Desktop players take `-golden`,`-smoke N`, `-profile`, `-camlog`, `-bootlog`, `-navlog`, `-vprofile` and `-shot`. The console also shows `GAME OK <date> turn <n> hash <h>` at start and `TURN <n> <date> hash <h>` per turn.- Visual checks (docs/visual-v1.md): measure only under the machine lock, which also waits for any open Unity editor:`uv run tools/machine_lock.py --exclusive --wait-unity -- uv run tools/web_check.py <build> --query vprofile --expect "PROFILE visual done" --timeout 1800 --stall 120`diff --git a/docs/m3-rulings.md b/docs/m3-rulings.mdindex a22719b37..b60e4030f 100644--- a/docs/m3-rulings.md+++ b/docs/m3-rulings.md@@ -134,6 +134,7 @@ These are the decisions made while building M3 where the spec or plan was silent- **itch.io upload stays an owner step.** The auto-mode classifier denied further itch.io actions ("Create Public Surface") and the controller did not work around it.- **Promo-quality visuals are the priority after the M3 merge.**- Map scale is Civ-style symbolic: settlements spread over neighbouring hexes by population, buildings and trees about 10–25x real size, and a closer hero zoom. Geography stays real.+ - **Superseded on 2026-10-11** (owner ruling during the art spike): buildings and trees match promo 03's measured scale per class, about 60x real size for city blocks and about 100x for houses and trees (`KitScale` in `unity/Assets/Scripts/Map/Kits/SettlementKits.cs`; measurements in `docs/visual-v1.md`, "Art spike"). Settlements still spread over hexes by population, and geography stays real.- Match the promo skyline where the promo shows it (for example, 1936 Tel Aviv towers).- Order: visual quick wins first (lighting, shadows, tilt-shift, terrain shader with baked AO, sea, colour grade; about 1–2 weeks), then the settlements and vegetation art track (research estimate 17–23 weeks).- Owner art checkpoints are screenshot comparisons against `promo/final/03-gameplay-1936.png`. Work continues past a checkpoint and owner feedback arrives as fix rounds. Cost if wrong: art rework.diff --git a/docs/superpowers/plans/2026-10-11-statecraft-visual-v1.md b/docs/superpowers/plans/2026-10-11-statecraft-visual-v1.mdindex c035f2422..62265d6b4 100644--- a/docs/superpowers/plans/2026-10-11-statecraft-visual-v1.md+++ b/docs/superpowers/plans/2026-10-11-statecraft-visual-v1.md@@ -16,7 +16,7 @@**Spec:** `docs/superpowers/specs/2026-10-09-statecraft-israel-design.md` (§6 Presentation: "overlays the hex grid and blends biomes", "`CameraRig`: diorama pitch, zoom levels and a tilt-shift look", "Visual targets are the approved concept images in `promo/final/`"; §9). **Research input:** `research_notes/M4 visual pipeline/notes.md` (§0 findings, §1 gap analysis, §2 rendering, §2.3 tiers). **Code base:** `main` at `554ca2c` (M3 merged at `4061a8b`, then open-sourced: MIT code, CC BY 4.0 assets, public at github.com/eyalgolan/statecraft-israel). It contains m3-fix's border skirt and the playtest-2 work (`DiagLog` with `?bootlog`/`?navlog`, Input System event merging off with a per-press map queue, the loading state, the event-card restyle in `Statecraft.uss`, `people.yaml` `focus_y`, the flat-array `BiomeBlender`) and M3's last round (`tools/headed.py`, `tools/package_release.py`, the boot-failure line). Read files with `git -C <repo> show 554ca2c:<path>`. **Visual v1 branches from `main` at or after `554ca2c`, in the worktree `.worktrees/visual-v1`** (Phase 0 precondition: `git merge-base --is-ancestor 554ca2c HEAD` succeeds); the Phase 1 track worktrees branch from `visual-v1`, and every task lands on `main` by PR (or merge) after its review: Phase 0 first, then each track's tasks in order, the merge-point and Task 10 last.**Owner rulings (binding, 2026-10-11):**-1. Scale is Civ-style symbolic (settlements sprawl over hexes by population; buildings and trees about 10–25× real; real geography). That is the next art track; this plan must not block it: the camera gains a closer hero zoom (Task 2) and nothing here bakes object scale into terrain or shaders.+1. Scale is Civ-style symbolic (settlements sprawl over hexes by population; buildings and trees about 10–25× real, superseded on 2026-10-11 by about 60× for city blocks and 100× for houses and trees, see `docs/m3-rulings.md`; real geography). That is the next art track; this plan must not block it: the camera gains a closer hero zoom (Task 2) and nothing here bakes object scale into terrain or shaders.2. Where the promo and era accuracy conflict, the promo wins.3. Order: these quick wins first, then the settlement/vegetation art track. Scope is only the items in the Goal.4. Every visual task ends with a scripted, **non-blocking** owner art checkpoint (side-by-side with the promo), plus objective tests where possible: render-sample tests, GLES3 shader compile, the frame-time profile on headless and headed WebGL, and unchanged golden hashes.diff --git a/docs/visual-v1.md b/docs/visual-v1.mdindex e45cb6830..aafd0f7ba 100644--- a/docs/visual-v1.md+++ b/docs/visual-v1.md@@ -1168,3 +1168,57 @@ One line each: ruling - reason.- Bloom, SSAO and the depth/opaque copies off - bloom changed at most 2/255 of any pixel; see "Tier decisions" for the costs.- NOT taken: dropping the bake's R channel - zero memory gain (BC1 either way) and it churns the assets; R stays as the AO reference.- NOT taken: deduplicating the `OpenMap` helper across `SeaTests` and `TerrainShaderTests` - test-only duplication; refactor risk with no behaviour gain.++## Art spike: procedural settlement kits and trees (branch `promo-art`)+Question: can code-generated settlement and vegetation art at Civ-style symbolic scale bring gameplay03 close to promo 03?+Code: `unity/Assets/Scripts/Map/Kits/` (built at load, seeded per settlement id by `KitRandom`, no sim state touched),+`Assets/Shaders/Kit.shader` (`Kit.mat` buildings, `Tree.mat` instanced trees), `KitTests`.+- **Archetypes** (`SettlementKits`): white city (Tel Aviv, Haifa: 2-9 storey flat-roof blocks, ribbon windows and+ balcony lines in the shader, L-shaped wings, roof rooms), old town (Jaffa, Acre, Gaza, Jerusalem: packed stone houses,+ domes; Jaffa's clock tower, belfry, mosque, breakwater, lighthouse and boats), Arab town (tan cubes on slopes, a mosque),+ moshava/kibbutz/moshav (red gable roofs, yards, a water tower; Nahalal as a ring). One merged mesh per settlement; all+ towns share one lot list, so a smaller neighbour never overlaps a bigger town's buildings. The `kits` toggle off shows+ the marker boxes again.+- **Footprint** = (1945 population / 60,000) hexes, floored at 0.08 hex. The populations live in+ `content/map/settlement_population_1945.yaml` (Village Statistics, 1945, read from the Wikipedia table on 2026-10-11:+ owner-verify until checked against a scan; Beersheba's row there is garbled, 5,570 is its likely reading), read through+ `MapInputs.PopulationYaml`. The sim never reads the file: `SaveGameTests.TheKitPopulationFileIsOutsideTheContentHash`, and+ the player's `BOOT OK content 96035735...` is unchanged. Towns share seams (distance over radius), stay on land, and tint+ their ground in the baked biome texture.+- **Trees** (`Vegetation`, `VegetationLayer`): citrus groves in 2x2 patches (every tree of a patch checked for water and+ towns, else one tree) round the coastal-plain towns, olives over the hills (and lone ones on the plain), palms by the+ coastal towns, cypress windbreaks; `Graphics.RenderMeshInstanced` per 30 km tile from `beginCameraRendering`, thinned as+ (110 km / distance)^2 past 110 km. The WebGL cost is per instance, not per triangle (at 25x a 30% triangle cut changed+ nothing; the 2x2 patches took the instances from 51,000 to 21,165 and the gameplay03 cost from 2.9 to 1.3 ms).+- **Scale (owner ruling 2026-10-11, superseding 10-25x):** buildings and trees match promo 03's measured scale per class:+ city blocks about 60x real size, houses and trees about 100x (`KitScale`; landmarks take the city-block scale). Counts+ were tuned at 25x and fall with the square of the scale. `?kitscale=`, `?housescale=`, `?treescale=` (clamped to 5-200)+ override them in the player; `MapCapture.Kits` takes `-kitScale`, `-houseScale`, `-treeScale`.+- **#37:** the kits use the sun's own URP shadow bias, unchanged (review I3: a kit-only bias and receiver offset were+ removed, as the probe could not show a need for them). `KitTests.AKitShadowStartsAtItsWalls` walks out from a lone box's+ shadow-side wall from 1 m in 1 m steps, on both tiers: the first shadowed sample is 3 m out at 12 km (pixel 7 m), 10 m at+ 60 km (pixel 35 m) and 1 m at 250 km, the same as with the old marker material, and the sunlit roof darkens at most 1.9%+ with shadows on (no acne). No bias gap reproduces, so the floating look of the old markers was not a bias gap.+- **Grid readability:** `KitTests.TheGridStaysReadableThroughTownsAndGroves`: at gameplay03, 76 of the 90 land edge+ midpoints whose line shows on bare ground still show it with kits and trees on (84%; the floor is 75%).+- **Measured at the 60x/100x defaults** (`d4e7275`, headless WebGL, `machine_lock.py --exclusive --wait-unity`, load 4-9,+ other sessions running; "none" means every visual feature off, not only the kits and trees):+ gameplay03 all 2.34 ms (p95 3), -trees 2.57, -kits 2.34, none 2.34; diorama02 all 11.22 (p95 12), -trees 10.41, -kits+ 11.35, none 7.29. Trees -0.23 / 0.81 ms and kits 0.00 / -0.13 ms (gameplay03 sits in the ~1 ms clock's bimodal+ 2.0 / 2.4 ms noise, so its negative costs are noise): every feature is within budget, all - none 0.00 / 3.93 ms, p95+ 3 / 12 ms. The `main` build in the same session: gameplay03 all 2.78, diorama02 all 10.12 (so +1.10 ms at diorama02).+ The diorama02 shadow overrun is unchanged (2.95 ms against `main`'s 2.91). Headed DPR 1: all 2.46 / 10.95, trees+ -0.24 / 0.75. Headed DPR 2: all p95 6 / 20 ms (floor 33), trees 0.35 / 0.89. Boot (`headed.py boot --runs 3`, `main`+ then this build): cpu 1 map_build 491 -> 508, first_frame 3631 -> 3610; cpu 4 1874 -> 2035, 6795 -> 6991 (within+ max(300 ms, 50%)). The player logs `KITS buildings=306 vertices=12374 triangles=8556 trees=8147 build_ms=20 plant_ms=19`.+- **After merging `main` with promo-sea and promo-units** (`689880d`, headless, load 18.7 at the start and 4.4 at the end,+ so absolute times are noisy): gameplay03 all 9.57 (p95 11), -trees 8.75, -kits 9.45, none 7.47; diorama02 all 14.99+ (p95 16), -trees 14.28, -kits 15.40, none 10.92. Trees 0.82 / 0.71 ms and kits 0.12 / -0.41 ms stay within budget, as+ do all - none (2.10 / 4.07 ms) and p95 (11 / 16 ms). The rise in "none" (2.34 -> 7.47 ms at gameplay03) is not the kits+ (both "none" runs draw no kits or trees); it should be re-measured on a quiet machine against `main`.+- **Build size** (WebGL, `main` -> this branch): uncompressed +318,885 bytes (+0.44%: wasm +286,873, data +28,978,+ framework.js +3,034); Brotli (quality 11, as shipped) +33,407 bytes (+0.17%: wasm +13,092, data +20,091). No texture or+ model files: everything is generated at load.+- **Authored meshes later:** trees swap as is (`Vegetation.Build(kind)` returns a mesh in real metres). Buildings will need+ `Emit` to return placements (archetype, variant, position, yaw, scale) drawn through the same tile instancing and a+ textured, instanced variant of `Kit.shader`; that refactor waits for the first authored mesh.diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.csindex 299973626..c26b7c40d 100644--- a/sim/Statecraft.Sim.Tests/SaveGameTests.cs+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs@@ -329,6 +329,30 @@ public class SaveGameTestsAssert.Equal(Played(c).State.Hash(), loaded.State.Hash());}+ /// <summary>content/map/settlement_population_1945.yaml sizes the map's settlement kits (presentation only). The sim+ /// never reads it, so it is outside the content hash: editing it cannot break a save or move a golden. Checked on the+ /// fixture and on the real content (with the file removed from a copy).</summary>+ [Fact]+ public void TheKitPopulationFileIsOutsideTheContentHash()+ {+ var dir = Fixture.Write();+ var before = ContentLoader.Load(dir).Hash;+ File.WriteAllText(Path.Combine(dir, "map", "settlement_population_1945.yaml"), "settlements:\n- id: x\n population: 1\n");+ Assert.Equal(before, ContentLoader.Load(dir).Hash);++ var real = RealContentTests.ContentRoot();+ Assert.True(File.Exists(Path.Combine(real, "map", "settlement_population_1945.yaml")));+ var copy = Path.Combine(Path.GetTempPath(), "statecraft-nopop-" + Guid.NewGuid().ToString("N"));+ foreach (var f in Directory.GetFiles(real, "*", SearchOption.AllDirectories))+ {+ var rel = Path.GetRelativePath(real, f);+ if (rel.Replace('\\', '/') == "map/settlement_population_1945.yaml") continue;+ Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(copy, rel))!);+ File.Copy(f, Path.Combine(copy, rel));+ }+ Assert.Equal(ContentLoader.Load(real).Hash, ContentLoader.Load(copy).Hash);+ }+[Fact]public void TheContentHashChangesWithEventsAndSettlements(){diff --git a/tools/tests/test_settlements.py b/tools/tests/test_settlements.pyindex 534a9fe08..eb1b8ab2f 100644--- a/tools/tests/test_settlements.py+++ b/tools/tests/test_settlements.py@@ -38,3 +38,19 @@ def test_shore_settlement_moves_to_nearest_land_neighbour():assert BY_QR[(q0, r0)]["biome"] == "lake" # its own hex is mostly Sea of Galileeq, r = hg.settlement_hex(tiberias["lon"], tiberias["lat"], HEXES)assert (q - q0, r - r0) in hg.NEIGHBOURS+++POPULATION = yaml.safe_load((ROOT / "content" / "map" / "settlement_population_1945.yaml").read_text())["settlements"]+++def test_population_rows_match_the_settlements_and_carry_sources():+ """settlement_population_1945.yaml (the settlement kits' footprints): one row per settlement id, a non-negative+ population or null, a status, and at least one source with an https url and a check date."""+ ids = [r["id"] for r in POPULATION]+ assert len(set(ids)) == len(ids)+ assert set(ids) == {s["id"] for s in TOWNS}+ for r in POPULATION:+ assert r["population"] is None or (isinstance(r["population"], int) and r["population"] >= 0), r["id"]+ assert r["population"] is not None or r.get("note"), f"{r['id']}: a missing figure needs a note"+ assert r["status"] in {"owner-verify", "fact-checked", "verified"}, r["id"]+ assert r["sources"] and all(src["url"].startswith("https://") and src["checked"] for src in r["sources"]), r["id"]diff --git a/unity/Assets/Editor/MapCapture.cs b/unity/Assets/Editor/MapCapture.csindex 2c6de6e31..0d7ae1a3f 100644--- a/unity/Assets/Editor/MapCapture.cs+++ b/unity/Assets/Editor/MapCapture.cs@@ -30,6 +30,7 @@ public static class MapCapturevar controller = Camera.main.gameObject.AddComponent<CameraController>(); // adds the CameraRig it requiresvar map = new GameObject("MapScene").AddComponent<MapScene>();map.Configure(Load(MapMaterials.TerrainPath), Load(MapMaterials.MarkerPath), Load(MapMaterials.SelectionPath), Load(MapMaterials.SeaPath), Load(MapMaterials.BorderLandPath));+ map.ConfigureKits(Load(MapMaterials.KitPath), Load(MapMaterials.TreePath));var boot = new GameObject("Boot").AddComponent<GameBoot>();boot.Configure(map);var placements = new GameObject("Placements").AddComponent<PlacementLayer>();@@ -159,6 +160,42 @@ public static class MapCapturefinally { QualitySettings.SetQualityLevel(saved, true); }}+ /// <summary>Art-track iteration renders (editor, WebGL tier = quality level 0): the promo poses plus a 30 km look at the+ /// promo 03 ground (Jaffa to Ramla), at the symbolic scale given by -kitScale (city blocks), -houseScale and -treeScale (default:+ /// the ruling's KitScale defaults), into -captureDir as kits-<pose>.png. Logs the kit numbers (KITS ...).</summary>+ public static void Kits()+ {+ var args = System.Environment.GetCommandLineArgs();+ string Arg(string name) { int i = System.Array.IndexOf(args, name); return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; }+ var dir = Arg("-captureDir") ?? Path.Combine(CaptureDir, "visual", "kits");+ var ci = System.Globalization.CultureInfo.InvariantCulture;+ if (Arg("-kitScale") is string ks) Statecraft.Game.Map.Kits.KitScale.CityBlocks = Statecraft.Game.Map.Kits.KitScale.Clamp(float.Parse(ks, ci));+ if (Arg("-houseScale") is string hs) Statecraft.Game.Map.Kits.KitScale.Houses = Statecraft.Game.Map.Kits.KitScale.Clamp(float.Parse(hs, ci));+ if (Arg("-treeScale") is string ts) Statecraft.Game.Map.Kits.KitScale.Trees = Statecraft.Game.Map.Kits.KitScale.Clamp(float.Parse(ts, ci));+ int saved = QualitySettings.GetQualityLevel();+ try+ {+ QualitySettings.SetQualityLevel(0, true);+ var map = OpenAndBuild();+ Debug.Log(map.KitStats?.ToString() ?? "KITS none (no kit materials on MapScene)");+ var rig = Camera.main.GetComponent<CameraRig>();+ var poses = new System.Collections.Generic.List<PromoPose>(PromoPose.All)+ {+ new PromoPose("close30", 34.83, 32.00, 30000f, 10f), new PromoPose("hero12", 34.79, 32.06, 12000f, 10f),+ };+ foreach (var pose in poses)+ {+ pose.Apply(rig, map.Frame);+ Save(Camera.main, 1920, 1080, Path.Combine(dir, $"kits-{pose.Name}.png"));+ }+ }+ finally+ {+ QualitySettings.SetQualityLevel(saved, true);+ Statecraft.Game.Map.Kits.KitScale.Reset();+ }+ }+static void Save(Camera cam, int w, int h, string path){var rt = new RenderTexture(w, h, 24); cam.targetTexture = rt; cam.Render();diff --git a/unity/Assets/Editor/MapMaterials.cs b/unity/Assets/Editor/MapMaterials.csindex dc34f7ab6..346388d66 100644--- a/unity/Assets/Editor/MapMaterials.cs+++ b/unity/Assets/Editor/MapMaterials.cs@@ -14,6 +14,8 @@ namespace Statecraft.Game.EditorToolspublic const string SelectionPath = Folder + "/HexSelection.mat";public const string SeaPath = Folder + "/Sea.mat";public const string BorderLandPath = Folder + "/BorderLand.mat";+ public const string KitPath = Folder + "/Kit.mat";+ public const string TreePath = Folder + "/Tree.mat";public static void Create(){@@ -41,6 +43,14 @@ namespace Statecraft.Game.EditorToolsland.SetFloat("_Smoothness", 0f); land.SetFloat("_Metallic", 0f);land.SetFloat("_SpecularHighlights", 1f); land.SetFloat("_EnvironmentReflections", 1f);EditorUtility.SetDirty(land);+ // Settlement kits and trees (art spike): Assets/Shaders/Kit.shader. Buildings are merged static meshes (no tint+ // jitter: each building's colour is in its vertices); trees are GPU-instanced and get a per-instance tint.+ var kit = Make(KitPath, "Statecraft/Kit", Color.white);+ kit.SetFloat("_Jitter", 0f);+ EditorUtility.SetDirty(kit);+ var tree = Make(TreePath, "Statecraft/Kit", Color.white);+ tree.SetFloat("_Jitter", 0.16f); tree.SetFloat("_WindowDark", 0f);+ EditorUtility.SetDirty(tree);AssetDatabase.SaveAssets();}diff --git a/unity/Assets/Map.unity b/unity/Assets/Map.unityindex d5d453ed5..b6900e12d 100644--- a/unity/Assets/Map.unity+++ b/unity/Assets/Map.unity@@ -384,6 +384,8 @@ MonoBehaviour:selectionMaterial: {fileID: 2100000, guid: 6116b1f8c72b244e0a9556c2cdb6b1c5, type: 2}seaMaterial: {fileID: 2100000, guid: 5bb451931546c49d6b2fe35726d07cfd, type: 2}borderLandMaterial: {fileID: 2100000, guid: ed41bb6e0c8274066b408da9b1f5bef2, type: 2}+ kitMaterial: {fileID: 2100000, guid: 24c1cceae1b22492e9c9f2be7c1a6b5e, type: 2}+ treeMaterial: {fileID: 2100000, guid: 2dd15539298814dafa803cdbc57e2426, type: 2}--- !u!4 &1195372453Transform:m_ObjectHideFlags: 0diff --git a/unity/Assets/Materials/Kit.mat b/unity/Assets/Materials/Kit.matnew file mode 100644index 000000000..d51c1cba9--- /dev/null+++ b/unity/Assets/Materials/Kit.mat@@ -0,0 +1,33 @@+%YAML 1.1+%TAG !u! tag:unity3d.com,2011:+--- !u!21 &2100000+Material:+ serializedVersion: 8+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_Name: Kit+ m_Shader: {fileID: 4800000, guid: faec37efeea0d4ef19af13ee3400c978, type: 3}+ m_Parent: {fileID: 0}+ m_ModifiedSerializedProperties: 0+ m_ValidKeywords: []+ m_InvalidKeywords: []+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 1+ m_DoubleSidedGI: 0+ m_CustomRenderQueue: -1+ stringTagMap: {}+ disabledShaderPasses: []+ m_LockedProperties:+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs: []+ m_Ints: []+ m_Floats:+ - _Jitter: 0+ - _WindowDark: 0.55+ m_Colors:+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}+ m_BuildTextureStacks: []+ m_AllowLocking: 1diff --git a/unity/Assets/Materials/Kit.mat.meta b/unity/Assets/Materials/Kit.mat.metanew file mode 100644index 000000000..6126b61dd--- /dev/null+++ b/unity/Assets/Materials/Kit.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 24c1cceae1b22492e9c9f2be7c1a6b5e+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Materials/Tree.mat b/unity/Assets/Materials/Tree.matnew file mode 100644index 000000000..7ba4376cf--- /dev/null+++ b/unity/Assets/Materials/Tree.mat@@ -0,0 +1,33 @@+%YAML 1.1+%TAG !u! tag:unity3d.com,2011:+--- !u!21 &2100000+Material:+ serializedVersion: 8+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_Name: Tree+ m_Shader: {fileID: 4800000, guid: faec37efeea0d4ef19af13ee3400c978, type: 3}+ m_Parent: {fileID: 0}+ m_ModifiedSerializedProperties: 0+ m_ValidKeywords: []+ m_InvalidKeywords: []+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 1+ m_DoubleSidedGI: 0+ m_CustomRenderQueue: -1+ stringTagMap: {}+ disabledShaderPasses: []+ m_LockedProperties:+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs: []+ m_Ints: []+ m_Floats:+ - _Jitter: 0.16+ - _WindowDark: 0+ m_Colors:+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}+ m_BuildTextureStacks: []+ m_AllowLocking: 1diff --git a/unity/Assets/Materials/Tree.mat.meta b/unity/Assets/Materials/Tree.mat.metanew file mode 100644index 000000000..7bf83612b--- /dev/null+++ b/unity/Assets/Materials/Tree.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 2dd15539298814dafa803cdbc57e2426+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.csindex 584281e25..d813d9c05 100644--- a/unity/Assets/Scripts/Boot/GameInputs.cs+++ b/unity/Assets/Scripts/Boot/GameInputs.cs@@ -14,6 +14,9 @@ namespace Statecraft.Game.Bootpublic sealed class MapInputs{public string HeightmapJson = "", HexesJson = "", SettlementsYaml = "";+ /// <summary>content/map/settlement_population_1945.yaml (the settlement kits' footprints; "" when absent). The sim+ /// never reads it.</summary>+ public string PopulationYaml = "";/// <summary>heightmap.r16z as read: packed (HeightmapCodec); HeightmapLoader decodes it when the map is built.</summary>public byte[] HeightmapR16z = new byte[0];}@@ -32,6 +35,8 @@ namespace Statecraft.Game.BootHeightmapR16z = File.ReadAllBytes(Path.Combine(mapDir, HeightmapCodec.FileName)),HexesJson = File.ReadAllText(Path.Combine(contentDir, "map", "hexes.json")),SettlementsYaml = File.ReadAllText(Path.Combine(contentDir, "map", SettlementPlacer.DefaultFileName)),+ PopulationYaml = File.Exists(Path.Combine(contentDir, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName))+ ? File.ReadAllText(Path.Combine(contentDir, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName)) : "",};public static GameInputs FromDisk(string contentDir, string mapDir) =>@@ -49,6 +54,7 @@ namespace Statecraft.Game.Boot{HeightmapJson = heightmapJson, HeightmapR16z = r16z,HexesJson = texts["map/hexes.json"], SettlementsYaml = texts["map/" + SettlementPlacer.DefaultFileName],+ PopulationYaml = texts.TryGetValue("map/" + Statecraft.Game.Map.Kits.KitPopulation.FileName, out var pop) ? pop : "",},};}diff --git a/unity/Assets/Scripts/Map/Kits.meta b/unity/Assets/Scripts/Map/Kits.metanew file mode 100644index 000000000..8153ff360--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: d7d23d3d421fb43eab2d12409edf8ae2+folderAsset: yes+DefaultImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/Kits/KitGround.cs b/unity/Assets/Scripts/Map/Kits/KitGround.csnew file mode 100644index 000000000..12d91c8fe--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitGround.cs@@ -0,0 +1,108 @@+#nullable enable+using System.Collections.Generic;+using UnityEngine;++namespace Statecraft.Game.Map.Kits+{+ /// <summary>What the kits ask of the map while they are built: ground height (world y, exaggerated relief), real+ /// elevation, water, the biome of the hex under a point, and the footprints already claimed by settlements (so groves+ /// stay out of towns). Built once per map build.</summary>+ public sealed class KitGround+ {+ readonly Terrain terrain;+ readonly float terrainY, seaLevelY, exaggeration, elevMinM;+ readonly Dictionary<(int, int), string> biome = new Dictionary<(int, int), string>();+ readonly HexBounds bounds; readonly double hexSizeKm;+ public readonly GeoFrame Frame;+ public readonly float HexSizeM;+ /// <summary>Settlement footprints (centre x, z; radius), claimed in placement order.</summary>+ public readonly List<(Vector2 centre, float radius, string id)> Footprints = new List<(Vector2, float, string)>();++ public KitGround(Terrain terrain, GeoFrame frame, HexFile hexes, float elevMinM)+ {+ this.terrain = terrain; Frame = frame; this.elevMinM = elevMinM;+ terrainY = terrain.transform.position.y;+ exaggeration = MapBuilder.VerticalExaggeration;+ seaLevelY = terrainY + (0f - elevMinM) * exaggeration;+ bounds = hexes.bounds; hexSizeKm = hexes.hex_size_km; HexSizeM = hexes.hex_size_km * 1000f;+ foreach (var h in hexes.hexes) biome[(h.q, h.r)] = h.biome;+ }++ public float Width => Frame.WidthM;+ public float Length => Frame.LengthM;++ public bool Inside(float x, float z) => x > 50f && z > 50f && x < Frame.WidthM - 50f && z < Frame.LengthM - 50f;++ /// <summary>World y of the ground at (x, z).</summary>+ public float Y(float x, float z) => terrain.SampleHeight(new Vector3(x, 0f, z)) + terrainY;++ /// <summary>Real metres above sea level at (x, z) (the heightmap's own elevation, before exaggeration).</summary>+ public float ElevM(float x, float z) => (Y(x, z) - seaLevelY) / exaggeration;++ public string Biome(float x, float z)+ {+ var (lon, lat) = Frame.ToLonLat(new Vector3(x, 0f, z));+ return biome.TryGetValue(HexPicker.FromLonLat(lon, lat, bounds, hexSizeKm), out var b) ? b : "sea";+ }++ /// <summary>Open sea (the heightmap writes it as exactly 0 m: MapBuilder.SeaToleranceM), a lake hex, or off the map.</summary>+ public bool Water(float x, float z)+ {+ if (!Inside(x, z)) return true;+ if (Mathf.Abs(ElevM(x, z)) <= MapBuilder.SeaToleranceM + 0.5f) return true;+ var b = Biome(x, z);+ return b == "lake" || (b == "sea" && ElevM(x, z) < 2f);+ }++ /// <summary>The steepest rise (real metres per real metre) between the four points of a w-wide square around (x, z).</summary>+ public float Slope(float x, float z, float w)+ {+ float h = w * 0.5f;+ float a = ElevM(x - h, z), b = ElevM(x + h, z), c = ElevM(x, z - h), d = ElevM(x, z + h);+ return Mathf.Max(Mathf.Abs(a - b), Mathf.Abs(c - d)) / w;+ }++ /// <summary>True when (x, z) lies within <paramref name="share"/> of any claimed footprint's radius.</summary>+ /// <summary>Every building's and landmark's lot (centre x, z; radius), filled by SettlementKits.Build before the trees+ /// are planted, so no tree grows through a roof (integration bug B9).</summary>+ public readonly List<(Vector2 centre, float radius)> Lots = new List<(Vector2, float)>();++ /// <summary>True when a crown of radius <paramref name="crown"/> at (x, z) would reach into any building's or landmark's+ /// lot. A linear scan: a few hundred lots and about ten thousand trees at load.</summary>+ public bool OnLot(float x, float z, float crown)+ {+ var p = new Vector2(x, z);+ foreach (var (c, r) in Lots) { float d = r + crown; if ((p - c).sqrMagnitude < d * d) return true; }+ return false;+ }++ public bool InTown(float x, float z, float share = 1f)+ {+ foreach (var f in Footprints)+ {+ float r = f.radius * share;+ if ((new Vector2(x, z) - f.centre).sqrMagnitude < r * r) return true;+ }+ return false;+ }++ /// <summary>Distance (m) to the nearest open-sea sample on a ring of 12 directions at up to <paramref name="maxM"/>,+ /// or float.MaxValue: the coast test for palms.</summary>+ public float SeaDistance(float x, float z, float maxM)+ {+ float best = float.MaxValue;+ for (int step = 1; step <= 4; step++)+ {+ float r = maxM * step / 4f;+ for (int i = 0; i < 12; i++)+ {+ float a = i * Mathf.PI / 6f;+ float px = x + Mathf.Cos(a) * r, pz = z + Mathf.Sin(a) * r;+ if (Inside(px, pz) && Mathf.Abs(ElevM(px, pz)) <= MapBuilder.SeaToleranceM + 0.5f) { best = Mathf.Min(best, r); }+ }+ if (best < float.MaxValue) return best;+ }+ return best;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Kits/KitGround.cs.meta b/unity/Assets/Scripts/Map/Kits/KitGround.cs.metanew file mode 100644index 000000000..d0566b63a--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitGround.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: af1840ff3929a46c8aecef2ad8a8247e\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Kits/KitLayer.cs b/unity/Assets/Scripts/Map/Kits/KitLayer.csnew file mode 100644index 000000000..8ff54bf83--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitLayer.cs@@ -0,0 +1,65 @@+#nullable enable+using System.Collections.Generic;+using UnityEngine;+using UnityEngine.Rendering;++namespace Statecraft.Game.Map.Kits+{+ /// <summary>Builds the art spike's procedural layer under a returned "Kits" root: one static mesh per settlement (its+ /// buildings, merged: one draw each, culled by its bounds) drawn with the editor-made Kit.mat, and the instanced trees+ /// (<see cref="VegetationLayer"/>) drawn with Tree.mat. Meshes are owned by the map's MapRuntimeAssets, so a rebuild+ /// frees them. Hides the marker boxes under <paramref name="markers"/> while the kits show. Registers the "kits" and+ /// "trees" visual toggles, so the frame-time profile prices each ("kits" off shows the markers again).</summary>+ public static class KitLayer+ {+ public const string RootName = "Kits", VegetationName = "Vegetation";++ public sealed class Stats+ {+ public int Buildings, Vertices, Triangles, Trees; public float BuildMs, PlantMs;+ public override string ToString() =>+ $"KITS buildings={Buildings} vertices={Vertices} triangles={Triangles} trees={Trees} build_ms={BuildMs:0} plant_ms={PlantMs:0}";+ }++ public static GameObject Build(IReadOnlyList<Settlement> settlements, Terrain terrain, GeoFrame frame, HexFile hexes, float elevMinM,+ Material kitMaterial, Material treeMaterial, MapRuntimeAssets assets, GameObject markers, out Stats stats)+ {+ stats = new Stats();+ var root = new GameObject(RootName);+ var ground = new KitGround(terrain, frame, hexes, elevMinM);+ var clock = System.Diagnostics.Stopwatch.StartNew();+ var built = SettlementKits.Build(settlements, ground, out var lots);+ foreach (var l in lots) ground.Lots.Add((l.centre, l.radius));+ foreach (var (s, mesh, n) in built)+ {+ assets.Own(mesh);+ var go = new GameObject(s.Id);+ go.transform.SetParent(root.transform, false);+ go.AddComponent<MeshFilter>().sharedMesh = mesh;+ var r = go.AddComponent<MeshRenderer>();+ r.sharedMaterial = kitMaterial;+ r.shadowCastingMode = ShadowCastingMode.On;+ stats.Buildings += n; stats.Vertices += mesh.vertexCount; stats.Triangles += (int)mesh.GetIndexCount(0) / 3;+ }+ stats.BuildMs = (float)clock.Elapsed.TotalMilliseconds;+ clock.Restart();+ var trees = Vegetation.Plant(settlements, ground);+ var veg = new GameObject(VegetationName);+ veg.transform.SetParent(root.transform, false);+ var layer = veg.AddComponent<VegetationLayer>();+ layer.Init(trees, treeMaterial, assets);+ stats.Trees = trees.Count;+ stats.PlantMs = (float)clock.Elapsed.TotalMilliseconds;+ // "kits" off shows the placeholder marker boxes again, so a settlement is always drawn by one or the other.+ void ShowKits(bool on)+ {+ if (root != null) foreach (var mr in root.GetComponentsInChildren<MeshRenderer>(true)) mr.enabled = on;+ if (markers != null) foreach (var mr in markers.GetComponentsInChildren<MeshRenderer>(true)) mr.enabled = !on;+ }+ ShowKits(true);+ assets.OnTeardown(VisualToggles.Register("kits", ShowKits));+ assets.OnTeardown(VisualToggles.Register("trees", on => { if (layer != null) layer.Draw = on; }));+ return root;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Kits/KitLayer.cs.meta b/unity/Assets/Scripts/Map/Kits/KitLayer.cs.metanew file mode 100644index 000000000..3c80b3d4d--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitLayer.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: f70893de6f8a94bdaba68d11b4a9630e\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Kits/KitMesh.cs b/unity/Assets/Scripts/Map/Kits/KitMesh.csnew file mode 100644index 000000000..85879e4ce--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitMesh.cs@@ -0,0 +1,233 @@+#nullable enable+using System.Collections.Generic;+using UnityEngine;+using UnityEngine.Rendering;++namespace Statecraft.Game.Map.Kits+{+ /// <summary>Facade styles, carried in the vertex colour's alpha and read by Statecraft/Kit (Kit.shader): which window+ /// pattern a wall gets. Roofs, domes and trees are Plain.</summary>+ public enum Facade : byte { Plain = 0, Stone = 64, Village = 128, WhiteCity = 255 }++ /// <summary>Grows one mesh from procedural parts (boxes, roofs, domes, towers, crowns). Vertex layout: position, normal,+ /// colour (sRGB albedo, alpha = <see cref="Facade"/>), uv0 = a wall's (along, up) position in real metres before the+ /// symbolic scale, so the shader draws storeys and windows at their real proportions on symbolic-size buildings.</summary>+ public sealed class KitMesh+ {+ readonly List<Vector3> pos = new List<Vector3>();+ readonly List<Vector3> nrm = new List<Vector3>();+ readonly List<Color32> col = new List<Color32>();+ readonly List<Vector2> uv = new List<Vector2>();+ readonly List<int> tri = new List<int>();++ public int VertexCount => pos.Count;+ public int TriangleCount => tri.Count / 3;+ /// <summary>Vertices whose normal is not unit length (a degenerate face): the shader would light them as NaN on WebGL 2.</summary>+ public int BadNormals { get { int n = 0; foreach (var v in nrm) if (Mathf.Abs(v.sqrMagnitude - 1f) > 1e-3f) n++; return n; } }++ public Mesh ToMesh(string name)+ {+ var m = new Mesh { name = name, indexFormat = pos.Count > 65000 ? IndexFormat.UInt32 : IndexFormat.UInt16 };+ m.SetVertices(pos); m.SetNormals(nrm); m.SetColors(col); m.SetUVs(0, uv); m.SetTriangles(tri, 0);+ m.RecalculateBounds();+ m.UploadMeshData(true); // no CPU copy: nothing reads the vertices back+ return m;+ }++ int V(Vector3 p, Vector3 n, Color32 c, Vector2 t) { pos.Add(p); nrm.Add(n); col.Add(c); uv.Add(t); return pos.Count - 1; }++ void Quad(int a, int b, int c, int d) { tri.Add(a); tri.Add(b); tri.Add(c); tri.Add(a); tri.Add(c); tri.Add(d); }++ /// <summary>A flat-shaded quad a-b-c-d, clockwise seen from its front (Unity's front-face winding), with a per-corner uv.</summary>+ public void Face(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Color32 colour, Vector2 ta, Vector2 tb, Vector2 tc, Vector2 td)+ {+ // From the diagonals: robust when one edge collapses to a point (a frond's tip), where an edge cross product+ // is zero and its normal would be NaN on WebGL 2 (normalize of zero).+ var n = Vector3.Cross(c - a, d - b).normalized;+ int i = V(a, n, colour, ta); V(b, n, colour, tb); V(c, n, colour, tc); V(d, n, colour, td);+ Quad(i, i + 1, i + 2, i + 3);+ }++ /// <summary>A flat-shaded triangle, clockwise seen from its front.</summary>+ public void Triangle(Vector3 a, Vector3 b, Vector3 c, Color32 colour)+ {+ var n = Vector3.Cross(b - a, c - a).normalized;+ int i = V(a, n, colour, Vector2.zero); V(b, n, colour, Vector2.zero); V(c, n, colour, Vector2.zero);+ tri.Add(i); tri.Add(i + 1); tri.Add(i + 2);+ }++ /// <summary>The walls (and, unless <paramref name="roofed"/>, the flat roof) of a box: footprint centred on+ /// (<paramref name="x"/>, <paramref name="z"/>), <paramref name="w"/> wide along its own x after a yaw of+ /// <paramref name="yawDeg"/>, <paramref name="d"/> deep; walls from <paramref name="bottom"/> (sunk into the slope) to+ /// <paramref name="ground"/> + <paramref name="h"/>. <paramref name="metresPerReal"/> turns world metres into real+ /// metres for the facade uv (the symbolic scale).</summary>+ public void Box(float x, float z, float yawDeg, float w, float d, float bottom, float ground, float h, Color32 wall, Color32 roof,+ Facade facade, float metresPerReal, bool roofed = false)+ {+ var c = Corners(x, z, yawDeg, w, d);+ float top = ground + h;+ var wallC = wall; wallC.a = (byte)facade;+ float vb = (bottom - ground) / metresPerReal, vt = h / metresPerReal;+ for (int i = 0; i < 4; i++)+ {+ var a = c[i]; var b = c[(i + 1) % 4];+ float len = (b - a).magnitude / metresPerReal;+ Face(new Vector3(a.x, bottom, a.y), new Vector3(a.x, top, a.y), new Vector3(b.x, top, b.y), new Vector3(b.x, bottom, b.y), wallC,+ new Vector2(0, vb), new Vector2(0, vt), new Vector2(len, vt), new Vector2(len, vb));+ }+ if (!roofed)+ {+ var r = roof; r.a = 0;+ Face(new Vector3(c[0].x, top, c[0].y), new Vector3(c[3].x, top, c[3].y), new Vector3(c[2].x, top, c[2].y), new Vector3(c[1].x, top, c[1].y), r,+ Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero);+ }+ }++ /// <summary>A gable roof on a w x d box whose walls end at <paramref name="eaves"/>: the ridge runs along the longer+ /// side, <paramref name="rise"/> above the eaves, with a small overhang.</summary>+ public void Gable(float x, float z, float yawDeg, float w, float d, float eaves, float rise, Color32 roof, Color32 gableWall)+ {+ if (d > w) { yawDeg += 90f; (w, d) = (d, w); }+ float ow = w * 1.06f, od = d * 1.12f;+ var c = Corners(x, z, yawDeg, ow, od); // 0 (-w,-d), 1 (+w,-d), 2 (+w,+d), 3 (-w,+d) in local axes+ var r0 = (c[0] + c[3]) * 0.5f; var r1 = (c[1] + c[2]) * 0.5f; // ridge ends+ var g = gableWall; g.a = 0; var rf = roof; rf.a = 0;+ Vector3 P(Vector2 p, float y) => new Vector3(p.x, y, p.y);+ Face(P(c[0], eaves), P(r0, eaves + rise), P(r1, eaves + rise), P(c[1], eaves), rf, Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero);+ Face(P(c[2], eaves), P(r1, eaves + rise), P(r0, eaves + rise), P(c[3], eaves), rf, Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero);+ Triangle(P(c[1], eaves), P(r1, eaves + rise), P(c[2], eaves), g);+ Triangle(P(c[3], eaves), P(r0, eaves + rise), P(c[0], eaves), g);+ }++ /// <summary>A four-sided pyramid cap (a clock tower's or a tiled hip roof).</summary>+ public void Pyramid(float x, float z, float yawDeg, float w, float d, float y, float rise, Color32 colour)+ {+ var c = Corners(x, z, yawDeg, w, d); var apex = new Vector3(x, y + rise, z); colour.a = 0;+ for (int i = 0; i < 4; i++)+ {+ var a = c[i]; var b = c[(i + 1) % 4];+ Triangle(new Vector3(a.x, y, a.y), apex, new Vector3(b.x, y, b.y), colour);+ }+ }++ /// <summary>A smooth hemisphere (a mosque's or a house's dome) of radius r standing on y.</summary>+ public void Dome(float x, float z, float y, float r, Color32 colour, int segments = 10, int rings = 4)+ {+ colour.a = 0;+ int first = pos.Count;+ for (int j = 0; j <= rings; j++)+ {+ float phi = Mathf.PI * 0.5f * j / rings;+ for (int i = 0; i <= segments; i++)+ {+ float th = 2f * Mathf.PI * i / segments;+ var n = new Vector3(Mathf.Cos(phi) * Mathf.Cos(th), Mathf.Sin(phi), Mathf.Cos(phi) * Mathf.Sin(th));+ V(new Vector3(x, y, z) + n * r, n, colour, Vector2.zero);+ }+ }+ for (int j = 0; j < rings; j++)+ for (int i = 0; i < segments; i++)+ {+ int a = first + j * (segments + 1) + i, b = a + 1, c = a + segments + 1, d = c + 1;+ tri.Add(a); tri.Add(c); tri.Add(b); tri.Add(b); tri.Add(c); tri.Add(d);+ }+ }++ /// <summary>An upright prism of <paramref name="sides"/> sides (a minaret's shaft, a palm's trunk, a water tower's+ /// legs), radius r0 at y0 tapering to r1 at y1, smooth-shaded, open at both ends.</summary>+ public void Shaft(Vector3 b0, Vector3 b1, float r0, float r1, Color32 colour, int sides, Facade facade = Facade.Plain, float metresPerReal = 1f)+ {+ colour.a = (byte)facade;+ int first = pos.Count;+ for (int i = 0; i <= sides; i++)+ {+ float th = 2f * Mathf.PI * i / sides;+ var n = new Vector3(Mathf.Cos(th), 0f, Mathf.Sin(th));+ float u = th * r0 / metresPerReal;+ V(b0 + n * r0, n, colour, new Vector2(u, 0f));+ V(b1 + n * r1, n, colour, new Vector2(u, (b1.y - b0.y) / metresPerReal));+ }+ for (int i = 0; i < sides; i++)+ {+ int a = first + 2 * i; Quad(a, a + 1, a + 3, a + 2);+ }+ }++ public void Cone(Vector3 b, float r, float h, Color32 colour, int sides)+ {+ colour.a = 0;+ var apex = b + Vector3.up * h;+ for (int i = 0; i < sides; i++)+ {+ float t0 = 2f * Mathf.PI * i / sides, t1 = 2f * Mathf.PI * (i + 1) / sides;+ Triangle(b + new Vector3(Mathf.Cos(t0), 0, Mathf.Sin(t0)) * r, apex, b + new Vector3(Mathf.Cos(t1), 0, Mathf.Sin(t1)) * r, colour);+ }+ }++ /// <summary>A soft, lumpy crown: a sphere of radius (rx, ry, rz) around <paramref name="centre"/> whose vertices are+ /// pushed in and out by <paramref name="lumps"/> (seeded), with spherical normals so the light rolls over it like+ /// foliage, not facets. <paramref name="speck"/> is the share of faces tinted <paramref name="speckColour"/> (citrus+ /// fruit).</summary>+ public void Crown(Vector3 centre, Vector3 radius, Color32 colour, ref KitRandom rnd, float lumps = 0.12f, int segments = 9, int rings = 6,+ float speck = 0f, Color32 speckColour = default, float flatBottom = 0.35f)+ {+ colour.a = 0; speckColour.a = 0;+ int first = pos.Count;+ var cols = new Color32[(rings + 1) * (segments + 1)];+ for (int j = 0; j <= rings; j++)+ {+ float phi = Mathf.PI * j / rings - Mathf.PI * 0.5f;+ for (int i = 0; i <= segments; i++)+ {+ float th = 2f * Mathf.PI * (i % segments) / segments;+ var n = new Vector3(Mathf.Cos(phi) * Mathf.Cos(th), Mathf.Sin(phi), Mathf.Cos(phi) * Mathf.Sin(th));+ float k = 1f + (j == 0 || j == rings ? 0f : rnd.Range(-lumps, lumps));+ var p = Vector3.Scale(n, radius) * k;+ if (p.y < -radius.y * flatBottom) p.y = -radius.y * flatBottom; // a flatter underside, as clipped trees have+ var c = speck > 0f && rnd.Chance(speck) ? speckColour : colour;+ // Light the underside less: foliage self-shadows.+ float shade = Mathf.Lerp(0.72f, 1.06f, (n.y + 1f) * 0.5f);+ c = new Color32((byte)Mathf.Min(255, c.r * shade), (byte)Mathf.Min(255, c.g * shade), (byte)Mathf.Min(255, c.b * shade), 0);+ V(centre + p, n, c, Vector2.zero);+ }+ }+ for (int j = 0; j < rings; j++)+ for (int i = 0; i < segments; i++)+ {+ int a = first + j * (segments + 1) + i, b = a + 1, c = a + segments + 1, d = c + 1;+ tri.Add(a); tri.Add(c); tri.Add(b); tri.Add(b); tri.Add(c); tri.Add(d);+ }+ }++ /// <summary>A palm frond: a drooping, tapering two-sided blade from the crown <paramref name="top"/> outwards along+ /// the horizontal <paramref name="dir"/>.</summary>+ public void Frond(Vector3 top, Vector3 dir, float length, float width, float droop, Color32 colour)+ {+ colour.a = 0;+ var side = Vector3.Cross(Vector3.up, dir).normalized * width * 0.5f;+ const int n = 4;+ var spine = new Vector3[n + 1];+ for (int i = 0; i <= n; i++)+ {+ float t = (float)i / n;+ spine[i] = top + dir * (length * t) + Vector3.up * (length * (0.25f * t - droop * t * t));+ }+ for (int i = 0; i < n; i++)+ {+ float w0 = Mathf.Sin(Mathf.PI * Mathf.Clamp((float)i / n, 0.15f, 0.92f)), w1 = Mathf.Sin(Mathf.PI * Mathf.Clamp((float)(i + 1) / n, 0.15f, 0.92f));+ var a = spine[i] - side * w0; var b = spine[i] + side * w0; var c = spine[i + 1] + side * w1; var d = spine[i + 1] - side * w1;+ Face(a, b, c, d, colour, Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero);+ Face(d, c, b, a, colour, Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero);+ }+ }++ static Vector2[] Corners(float x, float z, float yawDeg, float w, float d)+ {+ float a = yawDeg * Mathf.Deg2Rad, ca = Mathf.Cos(a), sa = Mathf.Sin(a);+ Vector2 R(float u, float v) => new Vector2(x + u * ca - v * sa, z + u * sa + v * ca);+ float hw = w * 0.5f, hd = d * 0.5f;+ // Anticlockwise seen from above (x east, z north): with (bottom, top) pairs this makes every wall face outward.+ return new[] { R(-hw, -hd), R(hw, -hd), R(hw, hd), R(-hw, hd) };+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Kits/KitMesh.cs.meta b/unity/Assets/Scripts/Map/Kits/KitMesh.cs.metanew file mode 100644index 000000000..5b9f6434c--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitMesh.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 74397b20c35654e159e9eca666a71d0d\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Kits/KitPopulation.cs b/unity/Assets/Scripts/Map/Kits/KitPopulation.csnew file mode 100644index 000000000..6204dbe5b--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitPopulation.cs@@ -0,0 +1,70 @@+#nullable enable+using System.Collections.Generic;+using System.IO;+using System.Text.RegularExpressions;+using YamlDotNet.Core;+using YamlDotNet.Serialization;+using YamlDotNet.Serialization.NamingConventions;++namespace Statecraft.Game.Map.Kits+{+ /// <summary>Population of each settlement, which sizes its kit's footprint (owner ruling: towns spread over hexes in+ /// proportion to population). The figures and their sources live in content/map/settlement_population_1945.yaml+ /// (Village Statistics, 1945; owner-verify), read with the other map inputs (MapInputs.PopulationYaml) and set here by+ /// MapScene.Build before the kits are built. Presentation only: the sim never reads the file.</summary>+ public static class KitPopulation+ {+ public const string FileName = "settlement_population_1945.yaml";+ static readonly HashSet<string> Statuses = new HashSet<string> { "owner-verify", "fact-checked", "verified" };+ static readonly Regex IdRule = new Regex(@"^[a-z][a-z0-9_]*\z");++ public sealed class Row+ {+ public string Id { get; set; } = "";+ public int? Population { get; set; }+ public string ListedAs { get; set; } = "";+ public string Note { get; set; } = "";+ public string Status { get; set; } = "";+ public List<SourceRef> Sources { get; set; } = new List<SourceRef>();+ }++ sealed class Doc { public List<Row> Settlements { get; set; } = new List<Row>(); }++ static Dictionary<string, int> current = new Dictionary<string, int>();++ /// <summary>Parses the file. Every malformed input throws InvalidDataException naming <paramref name="file"/> (and the+ /// id): YAML errors, unknown keys, an empty or non-snake_case or duplicate id, a negative population, a status other+ /// than owner-verify / fact-checked / verified, no sources, a source with an empty url or checked. A null population+ /// (a place the source does not list) is kept out of the table.</summary>+ public static Dictionary<string, int> Parse(string yaml, string file = FileName)+ {+ Doc doc;+ try { doc = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).WithDuplicateKeyChecking().Build().Deserialize<Doc>(yaml); }+ catch (YamlException e) { throw new InvalidDataException($"{file}: {e.Message}", e); }+ if (doc?.Settlements == null || doc.Settlements.Count == 0) throw new InvalidDataException($"{file}: no settlements");+ var table = new Dictionary<string, int>(); var seen = new HashSet<string>();+ foreach (var r in doc.Settlements)+ {+ if (r == null || string.IsNullOrWhiteSpace(r.Id)) throw new InvalidDataException($"{file}: a row has an empty id");+ string at = $"{file}: '{r.Id}'";+ if (!IdRule.IsMatch(r.Id)) throw new InvalidDataException($"{at} id must be lower snake_case");+ if (!seen.Add(r.Id)) throw new InvalidDataException($"{at} duplicate id");+ if (r.Population < 0) throw new InvalidDataException($"{at} population {r.Population} is negative");+ if (!Statuses.Contains(r.Status ?? "")) throw new InvalidDataException($"{at} status '{r.Status}' is not owner-verify, fact-checked or verified");+ if (r.Sources == null || r.Sources.Count == 0) throw new InvalidDataException($"{at} sources is empty");+ for (int i = 0; i < r.Sources.Count; i++)+ if (string.IsNullOrWhiteSpace(r.Sources[i]?.Url) || string.IsNullOrWhiteSpace(r.Sources[i].Checked))+ throw new InvalidDataException($"{at} sources[{i}] needs a url and a checked date");+ if (r.Population.HasValue) table[r.Id] = r.Population.Value;+ }+ return table;+ }++ /// <summary>The table the next kit build reads (MapScene.Build sets it from the map inputs; empty: every place takes+ /// the smallest footprint).</summary>+ public static void Use(Dictionary<string, int> table) => current = table ?? new Dictionary<string, int>();++ /// <summary>The 1945 population, or 0 when the source has none (the kit then takes the smallest footprint).</summary>+ public static int Of(string id) => current.TryGetValue(id, out var n) ? n : 0;+ }+}diff --git a/unity/Assets/Scripts/Map/Kits/KitPopulation.cs.meta b/unity/Assets/Scripts/Map/Kits/KitPopulation.cs.metanew file mode 100644index 000000000..f71cb4738--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitPopulation.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 3d17a8fa9d38f43abbaf8b3d7096010e\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Kits/KitRandom.cs b/unity/Assets/Scripts/Map/Kits/KitRandom.csnew file mode 100644index 000000000..242206225--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitRandom.cs@@ -0,0 +1,41 @@+#nullable enable++namespace Statecraft.Game.Map.Kits+{+ /// <summary>The kits' own deterministic random stream: SplitMix64 seeded by FNV-1a of a string key (a settlement id, a+ /// grove name) and a salt, so the same map draws the same buildings and trees on every load of the same build. Float+ /// maths (Perlin noise, trigonometry) may differ between the WebGL and native players and move a tree or a house past a+ /// threshold: cosmetic only. Presentation only: it shares no state with the sim's <c>Statecraft.Sim.Rng</c>+ /// (GameState.RngState), so no hash can change.</summary>+ public struct KitRandom+ {+ ulong state;++ public KitRandom(string key, ulong salt = 0) { state = Fnv1a(key) ^ (salt * 0x9E3779B97F4A7C15UL); }+ public KitRandom(ulong seed) { state = seed; }++ public static ulong Fnv1a(string s)+ {+ ulong h = 0xCBF29CE484222325UL;+ foreach (char c in s) { h ^= c; h *= 0x100000001B3UL; }+ return h;+ }++ public ulong Next()+ {+ ulong z = state += 0x9E3779B97F4A7C15UL;+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;+ return z ^ (z >> 31);+ }++ /// <summary>Uniform in [0, 1), 24 bits.</summary>+ public float Value() => (Next() >> 40) * (1f / 16777216f);+ public float Range(float min, float max) => min + (max - min) * Value();+ /// <summary>Uniform integer in [min, max).</summary>+ public int Range(int min, int max) => min + (int)((Next() >> 33) % (ulong)(max - min));+ public bool Chance(float p) => Value() < p;+ /// <summary>A sum of two uniforms: a cheap bell shape in [min, max].</summary>+ public float Bell(float min, float max) => min + (max - min) * 0.5f * (Value() + Value());+ }+}diff --git a/unity/Assets/Scripts/Map/Kits/KitRandom.cs.meta b/unity/Assets/Scripts/Map/Kits/KitRandom.cs.metanew file mode 100644index 000000000..fed54957e--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/KitRandom.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 91b326934ecf14ef38e232c9e84fd806\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs b/unity/Assets/Scripts/Map/Kits/SettlementKits.csnew file mode 100644index 000000000..7f0108b6d--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/SettlementKits.cs@@ -0,0 +1,467 @@+#nullable enable+using System.Collections.Generic;+using UnityEngine;++namespace Statecraft.Game.Map.Kits+{+ /// <summary>The four procedural archetypes of the settlement art spike (issues #31, #32).</summary>+ public enum Archetype { WhiteCity, OldTown, ArabTown, Moshava }++ /// <summary>Procedural settlement kits at the owner's symbolic scale (ruling 2026-10-11): buildings about+ /// <see cref="KitScale"/> times their real size (per class), a town's footprint spread over neighbouring hexes in+ /// proportion to its population, geography real (towns stay on land, at their sourced coordinates). Built at load time+ /// from the settlement id's seed (<see cref="KitRandom"/>), so every load of a build draws the same towns; nothing here reads or+ /// writes the sim.</summary>+ public static class SettlementKits+ {+ /// <summary>Settled population per hex of footprint: a town of this many people covers one hex (about 65 km^2).</summary>+ public const float PeoplePerHex = 60000f;+ /// <summary>The smallest footprint, in hexes, so a kibbutz of 240 still reads as a place at the gameplay zoom.</summary>+ public const float MinHexes = 0.08f;++ public static Archetype ArchetypeOf(Settlement s)+ {+ switch (s.Id)+ {+ case "tel_aviv": case "haifa": return Archetype.WhiteCity;+ case "jaffa": case "acre": case "gaza": case "jerusalem": return Archetype.OldTown;+ }+ switch (s.Type)+ {+ case "city": return Archetype.WhiteCity;+ case "arab_town": case "village": return Archetype.ArabTown;+ case "town": return s.Id == "tiberias" || s.Id == "safed" ? Archetype.ArabTown : Archetype.Moshava;+ default: return Archetype.Moshava; // kibbutz, moshav+ }+ }++ /// <summary>Footprint radius (m) of a settlement: the radius of a disc of (population / PeoplePerHex) hexes.</summary>+ public static float FootprintRadiusM(Settlement s, float hexSizeM)+ {+ float hexArea = 1.5f * 1.7320508f * hexSizeM * hexSizeM; // a pointy hex of circumradius hexSizeM+ float hexes = Mathf.Max(MinHexes, KitPopulation.Of(s.Id) / PeoplePerHex);+ return Mathf.Sqrt(hexes * hexArea / Mathf.PI);+ }++ /// <summary>Claims every settlement's footprint on <paramref name="ground"/> (largest first, so a big town's disc is+ /// whole and its small neighbour fits around it) and returns one mesh per settlement, keyed by id.</summary>+ public static List<(Settlement s, Mesh mesh, int buildings)> Build(IReadOnlyList<Settlement> list, KitGround ground) =>+ Build(list, ground, out _);++ /// <summary>As Build, also returning every claimed lot (centre, radius, owning settlement id): buildings and landmarks+ /// of all towns, none overlapping another (tests).</summary>+ public static List<(Settlement s, Mesh mesh, int buildings)> Build(IReadOnlyList<Settlement> list, KitGround ground,+ out List<(Vector2 centre, float radius, string id)> claimed)+ {+ var order = new List<Settlement>(list);+ order.Sort((a, b) => KitPopulation.Of(b.Id).CompareTo(KitPopulation.Of(a.Id)) != 0+ ? KitPopulation.Of(b.Id).CompareTo(KitPopulation.Of(a.Id)) : string.CompareOrdinal(a.Id, b.Id));+ var centres = new Dictionary<string, Vector2>();+ foreach (var s in order)+ {+ var w = ground.Frame.ToWorld(s.Lon, s.Lat, 0);+ centres[s.Id] = new Vector2(w.x, w.z);+ ground.Footprints.Add((centres[s.Id], FootprintRadiusM(s, ground.HexSizeM), s.Id));+ }+ var result = new List<(Settlement, Mesh, int)>();+ // One lot list for every town: a big town's buildings are placed first, and a neighbour's never overlap them.+ var lots = new List<Lot>();+ foreach (var s in order)+ {+ var km = new KitMesh();+ int n = BuildOne(s, centres[s.Id], ground, km, lots);+ result.Add((s, km.ToMesh(s.Id + "_kit"), n));+ }+ claimed = lots.ConvertAll(l => (centre: l.c, radius: l.r, id: l.id));+ return result;+ }++ /// <summary>Tints the ground of each settlement's footprint in the baked biome colour texels (sRGB, row 0 = south):+ /// pale paving and sand in the towns, as in promo 03, fading out over the outer half of the footprint.</summary>+ public static void PaintGround(Color32[] px, int res, GeoFrame frame, IReadOnlyList<Settlement> list, float hexSizeM)+ {+ foreach (var s in list)+ {+ var arch = ArchetypeOf(s);+ var (sand, strength) = arch switch+ {+ Archetype.WhiteCity => (new Color(0.80f, 0.75f, 0.64f), 0.62f),+ Archetype.OldTown => (new Color(0.78f, 0.68f, 0.52f), 0.62f),+ Archetype.ArabTown => (new Color(0.74f, 0.64f, 0.48f), 0.5f),+ _ => (new Color(0.70f, 0.63f, 0.47f), 0.32f),+ };+ var c = frame.ToWorld(s.Lon, s.Lat, 0);+ float R = FootprintRadiusM(s, hexSizeM) * 1.1f;+ int x0 = Mathf.Max(0, Mathf.FloorToInt((c.x - R) / frame.WidthM * res)), x1 = Mathf.Min(res - 1, Mathf.CeilToInt((c.x + R) / frame.WidthM * res));+ int y0 = Mathf.Max(0, Mathf.FloorToInt((c.z - R) / frame.LengthM * res)), y1 = Mathf.Min(res - 1, Mathf.CeilToInt((c.z + R) / frame.LengthM * res));+ for (int y = y0; y <= y1; y++)+ for (int x = x0; x <= x1; x++)+ {+ float wx = (x + 0.5f) / res * frame.WidthM - c.x, wz = (y + 0.5f) / res * frame.LengthM - c.z;+ float d = Mathf.Sqrt(wx * wx + wz * wz) / R;+ if (d >= 1f) continue;+ float w = strength * (1f - Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.5f, 1f, d)));+ int i = y * res + x;+ px[i] = Color32.Lerp(px[i], sand, w);+ }+ }+ }++ sealed class Lot { public Vector2 c; public float r; public string id = ""; }++ static bool FreeAt(List<Lot> lots, Vector2 p, float r)+ {+ foreach (var l in lots) if ((l.c - p).sqrMagnitude < (l.r + r) * (l.r + r)) return false;+ return true;+ }++ /// <summary>A landmark's spot (review N2): the dry spot nearest <paramref name="want"/> (rings out to four radii) that no+ /// lot of any town already holds; claimed for <paramref name="owner"/>. False, and nothing claimed, when there is none:+ /// the landmark is then left out rather than overlapping a bigger neighbour.</summary>+ static bool Claim(List<Lot> lots, Vector2 want, float r, string owner, KitGround ground, out Vector2 at)+ {+ for (int ring = 0; ring <= 8; ring++)+ {+ int around = ring == 0 ? 1 : 8 * ring;+ for (int k = 0; k < around; k++)+ {+ float a = 2f * Mathf.PI * k / around, d = ring * r * 0.5f;+ var p = want + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * d;+ if (!ground.Inside(p.x, p.y) || ground.Water(p.x, p.y) || !FreeAt(lots, p, r)) continue;+ lots.Add(new Lot { c = p, r = r, id = owner }); at = p; return true;+ }+ }+ at = want; return false;+ }++ /// <summary>Places one settlement's buildings into <paramref name="km"/>; returns how many.</summary>+ static int BuildOne(Settlement s, Vector2 centre, KitGround ground, KitMesh km, List<Lot> lots)+ {+ var arch = ArchetypeOf(s);+ var rnd = new KitRandom(s.Id, 1);+ float R = FootprintRadiusM(s, ground.HexSizeM);+ float m = KitScale.For(arch);+ int placed = 0;++ // This settlement's cell: a point belongs to the settlement whose footprint it is deepest inside (distance over+ // radius), so Jaffa and Tel Aviv, or Lod and Ramla, meet along a seam instead of overlapping.+ bool Mine(Vector2 p)+ {+ float mine = (p - centre).magnitude / R;+ foreach (var f in ground.Footprints)+ if (f.id != s.Id && (p - f.centre).magnitude / f.radius < mine) return false;+ return true;+ }+ bool Free(Vector2 p, float r) => FreeAt(lots, p, r);++ // Landmarks first, at the centre (or the nearest dry spot to it).+ var heart = DryNear(centre, ground, R * 0.3f, ref rnd);+ switch (arch)+ {+ case Archetype.OldTown: placed += OldTownLandmarks(s, heart, ground, km, lots, ref rnd); break;+ case Archetype.ArabTown: placed += Mosque(s.Id, heart, ground, km, lots, ref rnd, 1f); break;+ case Archetype.Moshava: placed += WaterTower(s.Id, heart + new Vector2(R * 0.35f, -R * 0.2f), ground, km, lots); break;+ }++ int target = TargetCount(arch, R);+ int attempts = target * 30;+ bool ring = s.Type == "moshav"; // Nahalal's ring of farmsteads round the public buildings+ for (int i = 0; i < attempts && placed < target; i++)+ {+ // The disc grows slowly when the sea or a neighbour eats into it, so the count stays tied to the population.+ float reach = R * (1f + 0.6f * i / attempts);+ float u = rnd.Value(), a = rnd.Range(0f, 2f * Mathf.PI);+ float rr = ring ? reach * rnd.Range(0.55f, 0.75f) : reach * Mathf.Pow(u, arch == Archetype.Moshava ? 0.5f : 0.62f);+ var p = centre + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * rr;+ if (!ground.Inside(p.x, p.y) || ground.Water(p.x, p.y) || !Mine(p)) continue;+ float t = rr / R; // 0 at the heart, 1 at the edge+ var b = Pick(arch, t, ref rnd, m);+ if (!Free(p, b.lotR)) continue;+ if (ground.Slope(p.x, p.y, b.w) > (arch == Archetype.ArabTown || arch == Archetype.OldTown ? 0.6f : 0.35f)) continue;+ // Corner and seaward checks: the whole footprint is dry.+ if (ground.Water(p.x + b.w * 0.5f, p.y) || ground.Water(p.x - b.w * 0.5f, p.y) || ground.Water(p.x, p.y + b.d * 0.5f) || ground.Water(p.x, p.y - b.d * 0.5f)) continue;+ float yaw = arch == Archetype.WhiteCity || arch == Archetype.Moshava+ ? GridYaw(s.Id) + (rnd.Chance(0.15f) ? 90f : 0f) + rnd.Range(-4f, 4f)+ : rnd.Range(0f, 90f);+ lots.Add(new Lot { c = p, r = b.lotR, id = s.Id });+ Emit(arch, p, yaw, b, ground, km, ref rnd);+ placed++;+ }+ return placed;+ }++ /// <summary>Buildings per settlement: the footprint area times the archetype's built-up share over its mean lot.</summary>+ static int TargetCount(Archetype arch, float R)+ {+ float area = Mathf.PI * R * R, m = KitScale.For(arch);+ float lot = arch switch+ {+ Archetype.WhiteCity => 21f * 15f, Archetype.OldTown => 11f * 10f, Archetype.ArabTown => 10f * 9f, _ => 10f * 8f,+ } * m * m;+ float share = arch switch { Archetype.WhiteCity => 0.36f, Archetype.OldTown => 0.46f, Archetype.ArabTown => 0.28f, _ => 0.09f };+ return Mathf.Clamp(Mathf.RoundToInt(area * share / lot), 6, 900);+ }++ /// <summary>The street grid's angle per town (Tel Aviv's Geddes plan runs about 20 degrees off north, parallel to the+ /// shore; the others get a seeded angle).</summary>+ static float GridYaw(string id) => id == "tel_aviv" ? 20f : id == "haifa" ? 35f : new KitRandom(id, 7).Range(0f, 90f);++ struct Spec { public float w, d, h, lotR; public int storeys; }++ static Spec Pick(Archetype arch, float t, ref KitRandom rnd, float m)+ {+ float w, d; int storeys;+ switch (arch)+ {+ case Archetype.WhiteCity:+ w = rnd.Range(15f, 26f); d = rnd.Range(11f, 18f);+ // Taller near the centre; a few landmarks taller still (the promo's skyline, owner ruling: promo wins).+ storeys = Mathf.RoundToInt(Mathf.Lerp(5.2f, 2.2f, t) + rnd.Range(-1.2f, 1.2f));+ if (t < 0.45f && rnd.Chance(0.07f)) storeys = rnd.Range(7, 10);+ storeys = Mathf.Clamp(storeys, 2, 9);+ break;+ case Archetype.OldTown:+ w = rnd.Range(7f, 14f); d = rnd.Range(7f, 12f);+ storeys = Mathf.Clamp(Mathf.RoundToInt(Mathf.Lerp(3.2f, 1.4f, t) + rnd.Range(-0.8f, 0.8f)), 1, 4);+ break;+ case Archetype.ArabTown:+ w = rnd.Range(6.5f, 12f); d = rnd.Range(6f, 10f);+ storeys = rnd.Chance(Mathf.Lerp(0.45f, 0.1f, t)) ? 2 : 1;+ break;+ default:+ w = rnd.Range(8f, 12f); d = rnd.Range(6.5f, 9f);+ storeys = rnd.Chance(0.15f) ? 2 : 1;+ if (rnd.Chance(0.06f)) { w = rnd.Range(18f, 28f); d = rnd.Range(8f, 10f); } // a barn, a dining hall, a packing house+ break;+ }+ float storeyM = 3.3f;+ float gap = arch switch { Archetype.WhiteCity => 1.25f, Archetype.OldTown => 0.92f, Archetype.ArabTown => 1.05f, _ => 2.4f };+ return new Spec+ {+ w = w * m, d = d * m, h = storeys * storeyM * m, storeys = storeys,+ lotR = 0.5f * Mathf.Sqrt(w * w + d * d) * m * gap * (arch == Archetype.OldTown ? 0.8f : 0.72f),+ };+ }++ // sRGB palettes (promo 03: white and cream city, honey stone Jaffa, tan villages, terracotta roofs).+ static Color32 C(float r, float g, float b) => new Color32((byte)(r * 255), (byte)(g * 255), (byte)(b * 255), 255);+ static Color32 Jitter(Color32 c, ref KitRandom rnd, float amount)+ {+ float k = 1f + rnd.Range(-amount, amount), warm = rnd.Range(-amount, amount) * 0.5f;+ return C(Mathf.Clamp01(c.r / 255f * k * (1 + warm)), Mathf.Clamp01(c.g / 255f * k), Mathf.Clamp01(c.b / 255f * k * (1 - warm)));+ }++ static void Emit(Archetype arch, Vector2 p, float yaw, Spec b, KitGround ground, KitMesh km, ref KitRandom rnd)+ {+ float m = KitScale.For(arch);+ var (bottom, top) = GroundSpan(p, yaw, b.w, b.d, ground, m);+ switch (arch)+ {+ case Archetype.WhiteCity:+ {+ var wall = rnd.Chance(0.12f) ? Jitter(C(0.90f, 0.84f, 0.72f), ref rnd, 0.04f) : Jitter(C(0.94f, 0.92f, 0.87f), ref rnd, 0.035f);+ var roof = Jitter(C(0.80f, 0.78f, 0.74f), ref rnd, 0.05f);+ km.Box(p.x, p.y, yaw, b.w, b.d, bottom, top, b.h, wall, roof, Facade.WhiteCity, m);+ // Some blocks are L-shaped: a lower wing at one end, back from the street.+ if (rnd.Chance(0.3f))+ {+ float a = yaw * Mathf.Deg2Rad, side = rnd.Chance(0.5f) ? 1f : -1f;+ float ww = b.w * 0.42f, wd = b.d * 0.8f;+ float u = side * (b.w - ww) * 0.5f, v = (b.d + wd) * 0.5f * 0.92f;+ var wc = new Vector2(p.x + u * Mathf.Cos(a) - v * Mathf.Sin(a), p.y + u * Mathf.Sin(a) + v * Mathf.Cos(a));+ if (!ground.Water(wc.x, wc.y))+ km.Box(wc.x, wc.y, yaw, ww, wd, bottom, top, Mathf.Max(2f * 3.3f * m, b.h - 3.3f * m), wall, roof, Facade.WhiteCity, m);+ }+ // A stair tower or roof room on many Bauhaus blocks, and a parapet's shadow line.+ if (rnd.Chance(0.55f))+ {+ float rw = b.w * rnd.Range(0.25f, 0.4f), rd = b.d * rnd.Range(0.3f, 0.45f);+ km.Box(p.x + b.w * rnd.Range(-0.2f, 0.2f), p.y + b.d * rnd.Range(-0.15f, 0.15f), yaw, rw, rd, top + b.h - 2f, top + b.h, 2.8f * m, wall, roof, Facade.Plain, m);+ }+ break;+ }+ case Archetype.OldTown:+ {+ var wall = Jitter(C(0.83f, 0.72f, 0.54f), ref rnd, 0.06f);+ var roof = Jitter(C(0.86f, 0.77f, 0.60f), ref rnd, 0.05f);+ km.Box(p.x, p.y, yaw, b.w, b.d, bottom, top, b.h, wall, roof, Facade.Stone, m);+ if (rnd.Chance(0.22f)) km.Dome(p.x, p.y, top + b.h - 1f, Mathf.Min(b.w, b.d) * 0.33f, Jitter(C(0.88f, 0.84f, 0.76f), ref rnd, 0.05f));+ else if (rnd.Chance(0.03f)) km.Pyramid(p.x, p.y, yaw, b.w * 1.04f, b.d * 1.04f, top + b.h, 2.2f * m, Jitter(C(0.70f, 0.33f, 0.22f), ref rnd, 0.06f));+ break;+ }+ case Archetype.ArabTown:+ {+ var wall = Jitter(C(0.80f, 0.70f, 0.53f), ref rnd, 0.07f);+ var roof = Jitter(C(0.84f, 0.75f, 0.59f), ref rnd, 0.06f);+ km.Box(p.x, p.y, yaw, b.w, b.d, bottom, top, b.h, wall, roof, Facade.Village, m);+ if (rnd.Chance(0.10f)) km.Dome(p.x, p.y, top + b.h - 1f, Mathf.Min(b.w, b.d) * 0.3f, roof);+ break;+ }+ default:+ {+ var wall = Jitter(C(0.92f, 0.89f, 0.82f), ref rnd, 0.04f);+ var roof = Jitter(C(0.74f, 0.31f, 0.20f), ref rnd, 0.08f);+ km.Box(p.x, p.y, yaw, b.w, b.d, bottom, top, b.h, wall, roof, Facade.Village, m, roofed: true);+ km.Gable(p.x, p.y, yaw, b.w, b.d, top + b.h, Mathf.Min(b.w, b.d) * 0.42f, roof, wall);+ break;+ }+ }+ }++ /// <summary>Wall bottom (sunk 2 m below the lowest corner, so a house on a slope stands on a plinth, not on air) and the+ /// ground level the walls rise from (the highest corner, so the slope never buries a storey).</summary>+ static (float bottom, float ground) GroundSpan(Vector2 p, float yawDeg, float w, float d, KitGround ground, float m)+ {+ float a = yawDeg * Mathf.Deg2Rad, ca = Mathf.Cos(a), sa = Mathf.Sin(a);+ float lo = float.MaxValue, hi = float.MinValue;+ for (int i = 0; i < 5; i++)+ {+ float u = i == 4 ? 0 : ((i & 1) == 0 ? -0.5f : 0.5f) * w, v = i == 4 ? 0 : ((i & 2) == 0 ? -0.5f : 0.5f) * d;+ float y = ground.Y(p.x + u * ca - v * sa, p.y + u * sa + v * ca);+ lo = Mathf.Min(lo, y); hi = Mathf.Max(hi, y);+ }+ return (lo - 2f * m, hi);+ }++ static Vector2 DryNear(Vector2 c, KitGround ground, float within, ref KitRandom rnd)+ {+ if (ground.Inside(c.x, c.y) && !ground.Water(c.x, c.y)) return c;+ for (int i = 0; i < 64; i++)+ {+ float a = rnd.Range(0f, 2f * Mathf.PI), r = within * (i + 1) / 64f;+ var p = c + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * r;+ if (ground.Inside(p.x, p.y) && !ground.Water(p.x, p.y)) return p;+ }+ return c;+ }++ /// <summary>Jaffa: the clock tower (1903-06) by the old town's gate, the Mahmoudiya mosque's minaret and dome, and a+ /// church belfry above the harbour; the other old towns get a mosque.</summary>+ static int OldTownLandmarks(Settlement s, Vector2 heart, KitGround ground, KitMesh km, List<Lot> lots, ref KitRandom rnd)+ {+ float m = KitScale.Landmarks;+ int n = Mosque(s.Id, heart + new Vector2(-5f * m, 6f * m), ground, km, lots, ref rnd, 1.2f);+ if (s.Id == "jaffa")+ {+ var stone = C(0.86f, 0.76f, 0.57f);+ if (!Claim(lots, heart + new Vector2(14f * m, 4f * m), 4.5f * m, s.Id, ground, out var p)) return n;+ float y = ground.Y(p.x, p.y);+ km.Box(p.x, p.y, 15f, 5f * m, 5f * m, y - 2f * m, y, 24f * m, stone, stone, Facade.Stone, m, roofed: true);+ km.Box(p.x, p.y, 15f, 4f * m, 4f * m, y + 24f * m, y + 24f * m, 4f * m, C(0.90f, 0.82f, 0.64f), stone, Facade.Plain, m, roofed: true);+ km.Pyramid(p.x, p.y, 15f, 4.4f * m, 4.4f * m, y + 28f * m, 3.5f * m, C(0.55f, 0.47f, 0.40f));+ n++;+ if (!Claim(lots, heart + new Vector2(-10f * m, -12f * m), 10f * m, s.Id, ground, out var q)) return n;+ float yq = ground.Y(q.x, q.y);+ km.Box(q.x, q.y, 0f, 9f * m, 18f * m, yq - 2f * m, yq, 12f * m, stone, stone, Facade.Stone, m, roofed: true);+ km.Box(q.x, q.y + 7f * m, 0f, 4.5f * m, 4.5f * m, yq + 12f * m, yq + 12f * m, 14f * m, stone, stone, Facade.Stone, m, roofed: true);+ km.Pyramid(q.x, q.y + 7f * m, 0f, 4.8f * m, 4.8f * m, yq + 26f * m, 6f * m, C(0.60f, 0.52f, 0.44f));+ km.Gable(q.x, q.y, 0f, 9f * m, 18f * m, yq + 12f * m, 4f * m, C(0.66f, 0.34f, 0.24f), stone);+ n += 1 + Port(heart, ground, km, ref rnd);+ }+ return n;+ }++ /// <summary>Jaffa's harbour, as promo 03 draws it: a stone breakwater curving out to sea from the shore west of the+ /// old town, a lighthouse at its head, and a few sailing boats inside it.</summary>+ static int Port(Vector2 heart, KitGround ground, KitMesh km, ref KitRandom rnd)+ {+ float m = KitScale.Landmarks;+ var shore = heart;+ for (int i = 0; i < 120 && !ground.Water(shore.x, shore.y); i++) shore.x -= 50f;+ if (!ground.Water(shore.x, shore.y)) return 0;+ float sea = ground.Y(shore.x, shore.y);+ var stone = C(0.74f, 0.70f, 0.62f);+ // A quarter-circle arm: out to the west, then north.+ var c = shore + new Vector2(0f, 60f * m);+ float r = 60f * m;+ Vector2 prev = c + new Vector2(0f, -r);+ for (int k = 1; k <= 9; k++)+ {+ float a = -Mathf.PI * 0.5f - k * (Mathf.PI * 0.5f / 9f);+ var cur = c + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * r;+ var mid = (prev + cur) * 0.5f; var dir = cur - prev;+ float yaw = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;+ km.Box(mid.x, mid.y, yaw, dir.magnitude * 1.08f, 5f * m, sea - 2f * m, sea, 2.2f * m, stone, stone, Facade.Plain, m);+ prev = cur;+ }+ // The lighthouse at the arm's head.+ var white = C(0.93f, 0.92f, 0.88f);+ km.Shaft(new Vector3(prev.x, sea, prev.y), new Vector3(prev.x, sea + 16f * m, prev.y), 2.0f * m, 1.5f * m, white, 10);+ km.Shaft(new Vector3(prev.x, sea + 16f * m, prev.y), new Vector3(prev.x, sea + 19f * m, prev.y), 1.6f * m, 1.6f * m, C(0.30f, 0.32f, 0.30f), 10);+ km.Cone(new Vector3(prev.x, sea + 19f * m, prev.y), 1.9f * m, 2.4f * m, C(0.68f, 0.24f, 0.18f), 10);+ // Sailing boats in and off the harbour.+ int boats = 0;+ for (int i = 0; i < 12 && boats < 5; i++)+ {+ var b = c + new Vector2(rnd.Range(-1.6f, 0.2f) * r, rnd.Range(-1.4f, 0.4f) * r);+ if (!ground.Water(b.x, b.y) || ground.Water(b.x + 40f * m, b.y) == false) continue;+ float yaw = rnd.Range(0f, 360f), L = rnd.Range(9f, 14f) * m;+ km.Box(b.x, b.y, yaw, L, L * 0.32f, sea - 1f * m, sea, 1.6f * m, C(0.42f, 0.30f, 0.20f), C(0.55f, 0.42f, 0.30f), Facade.Plain, m);+ float a = yaw * Mathf.Deg2Rad; var fwd = new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a));+ var mast = new Vector3(b.x, sea + 1.6f * m, b.y);+ km.Shaft(mast, mast + Vector3.up * L * 0.9f, 0.18f * m, 0.12f * m, C(0.35f, 0.28f, 0.20f), 4);+ var sail = C(0.95f, 0.93f, 0.86f);+ var s0 = mast + Vector3.up * L * 0.85f; var s1 = mast + Vector3.up * 0.4f * m; var s2 = mast + fwd * (-L * 0.45f) + Vector3.up * 0.4f * m;+ km.Triangle(s0, s1, s2, sail); km.Triangle(s0, s2, s1, sail);+ boats++;+ }+ return 1;+ }++ static int Mosque(string owner, Vector2 want, KitGround ground, KitMesh km, List<Lot> lots, ref KitRandom rnd, float size)+ {+ float m = KitScale.Landmarks * size;+ if (!Claim(lots, want, 11f * m, owner, ground, out var p)) return 0; // the lot covers the minaret too+ float y = ground.Y(p.x, p.y);+ var stone = Jitter(C(0.87f, 0.80f, 0.66f), ref rnd, 0.03f);+ km.Box(p.x, p.y, 0f, 14f * m, 14f * m, y - 2f * m, y, 7f * m, stone, stone, Facade.Stone, KitScale.Landmarks);+ km.Dome(p.x, p.y, y + 7f * m - 0.5f * m, 5.5f * m, C(0.80f, 0.80f, 0.76f));+ float mx = p.x + 8.5f * m, mz = p.y - 6f * m;+ float my = ground.Y(mx, mz);+ km.Shaft(new Vector3(mx, my - 2f * m, mz), new Vector3(mx, my + 26f * m, mz), 1.6f * m, 1.35f * m, stone, 8);+ km.Shaft(new Vector3(mx, my + 20f * m, mz), new Vector3(mx, my + 21f * m, mz), 2.1f * m, 2.1f * m, stone, 8); // the balcony+ km.Cone(new Vector3(mx, my + 26f * m, mz), 1.5f * m, 4.5f * m, C(0.62f, 0.62f, 0.58f), 8);+ return 1;+ }++ static int WaterTower(string owner, Vector2 want, KitGround ground, KitMesh km, List<Lot> lots)+ {+ float m = KitScale.Houses;+ if (!Claim(lots, want, 4f * m, owner, ground, out var p)) return 0;+ float y = ground.Y(p.x, p.y);+ var concrete = C(0.82f, 0.80f, 0.76f);+ for (int i = 0; i < 4; i++)+ {+ float a = Mathf.PI * 0.5f * i + 0.6f;+ var b = new Vector3(p.x + Mathf.Cos(a) * 2.6f * m, y - 2f * m, p.y + Mathf.Sin(a) * 2.6f * m);+ km.Shaft(b, new Vector3(p.x + Mathf.Cos(a) * 1.8f * m, y + 9f * m, p.y + Mathf.Sin(a) * 1.8f * m), 0.35f * m, 0.3f * m, concrete, 4);+ }+ km.Shaft(new Vector3(p.x, y + 9f * m, p.y), new Vector3(p.x, y + 13.5f * m, p.y), 3f * m, 3f * m, concrete, 10);+ km.Cone(new Vector3(p.x, y + 13.5f * m, p.y), 3.1f * m, 1.2f * m, C(0.66f, 0.64f, 0.60f), 10);+ return 1;+ }+ }++ /// <summary>The symbolic scale per class (owner ruling 2026-10-11, superseding the 10-25x ruling: match promo 03's+ /// measured scale per class): city blocks about 60x their real size, houses and trees about 100x; geography stays real.+ /// Landmarks (a clock tower, a mosque, a harbour) take the city-block scale. Fields, not constants, so the capture tool+ /// and the player's ?kitscale / ?housescale / ?treescale flags (clamped to <see cref="Min"/>..<see cref="Max"/>) can show+ /// another scale. Counts are tuned at <see cref="CountReference"/> and fall with the square of the scale.</summary>+ public static class KitScale+ {+ public const float DefaultCityBlocks = 60f, DefaultHouses = 100f, DefaultTrees = 100f;+ public const float Min = 5f, Max = 200f;+ /// <summary>The scale the building and tree counts were tuned at: a class drawn at k times this has 1/k^2 as many.</summary>+ public const float CountReference = 25f;+ public static float CityBlocks = DefaultCityBlocks;+ public static float Houses = DefaultHouses;+ public static float Trees = DefaultTrees;++ public static float Landmarks => CityBlocks;+ public static float For(Archetype a) => a == Archetype.WhiteCity ? CityBlocks : Houses;++ public static float Clamp(float v) => Mathf.Clamp(v, Min, Max);++ public static void Reset() { CityBlocks = DefaultCityBlocks; Houses = DefaultHouses; Trees = DefaultTrees; }+ }+}diff --git a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs.meta b/unity/Assets/Scripts/Map/Kits/SettlementKits.cs.metanew file mode 100644index 000000000..b78683862--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/SettlementKits.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: e6ed2afdf65dd4df2bf19cc29fe75d5c\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Kits/Vegetation.cs b/unity/Assets/Scripts/Map/Kits/Vegetation.csnew file mode 100644index 000000000..91f9952a1--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/Vegetation.cs@@ -0,0 +1,237 @@+#nullable enable+using System.Collections.Generic;+using UnityEngine;++namespace Statecraft.Game.Map.Kits+{+ /// <summary>CitrusPatch is four citrus trees in a 2 x 2 block of a grove's rows, drawn as one instance: the trees' cost on+ /// WebGL is per instance (the matrices uploaded each frame), not per triangle, so the dense groves are instanced in fours.</summary>+ public enum TreeKind { Citrus, Olive, Palm, Cypress, CitrusPatch }++ /// <summary>Procedural trees at the symbolic scale (issue #34): citrus groves (dense rows of round dark-green trees with+ /// fruit specks) on the coastal plain round the towns, olives scattered over the hills, palms by the shore of the coastal+ /// towns, cypress windbreaks by villages. There is no land-use layer yet (Deferred row "Land-use texture"), so where+ /// each grows is a seeded rule over the biome, elevation, slope and the settlements; every draw is seeded (no+ /// System.Random), so every load of a build grows the same trees.</summary>+ public static class Vegetation+ {+ /// <summary>One tree's mesh in real metres (the instance matrix applies KitScale.Trees).</summary>+ public static Mesh BuildMesh(TreeKind kind) => Build(kind).ToMesh("Tree_" + kind);++ /// <summary>The tree's parts before upload (tests read them).</summary>+ public static KitMesh Build(TreeKind kind)+ {+ var km = new KitMesh();+ var rnd = new KitRandom("tree:" + kind, 3);+ Color32 C(float r, float g, float b) => new Color32((byte)(r * 255), (byte)(g * 255), (byte)(b * 255), 0);+ switch (kind)+ {+ case TreeKind.Citrus:+ CitrusTree(km, Vector3.zero, 1f, ref rnd);+ break;+ case TreeKind.CitrusPatch:+ // A grove's row spacing (GroveStepM) apart, each tree a little off its spot and its own size.+ for (int i = 0; i < 4; i++)+ {+ var at = new Vector3(((i & 1) - 0.5f) * GroveStepM + rnd.Range(-0.3f, 0.3f), 0f, ((i >> 1) - 0.5f) * GroveStepM + rnd.Range(-0.3f, 0.3f));+ CitrusTree(km, at, rnd.Range(0.88f, 1.06f), ref rnd, rnd.Range(0.88f, 1.1f)); // each its own size and shade+ }+ break;+ case TreeKind.Olive:+ km.Shaft(new Vector3(0, -0.6f, 0), new Vector3(0.15f, 1.7f, 0.1f), 0.32f, 0.22f, C(0.36f, 0.31f, 0.25f), 4);+ km.Crown(new Vector3(0.5f, 2.9f, 0.2f), new Vector3(2.0f, 1.5f, 1.9f), C(0.50f, 0.55f, 0.39f), ref rnd, 0.16f, 7, 4);+ km.Crown(new Vector3(-0.8f, 2.6f, -0.4f), new Vector3(1.6f, 1.3f, 1.5f), C(0.46f, 0.52f, 0.37f), ref rnd, 0.18f, 6, 4);+ km.Crown(new Vector3(-0.1f, 3.5f, 0.6f), new Vector3(1.3f, 1.0f, 1.3f), C(0.55f, 0.60f, 0.44f), ref rnd, 0.15f, 6, 3);+ break;+ case TreeKind.Palm:+ {+ var trunk = C(0.48f, 0.40f, 0.30f);+ var mid = new Vector3(0.35f, 6f, 0.1f); var top = new Vector3(0.9f, 11.5f, 0.25f);+ km.Shaft(new Vector3(0, -0.6f, 0), mid, 0.30f, 0.24f, trunk, 6);+ km.Shaft(mid, top, 0.24f, 0.21f, trunk, 6);+ for (int i = 0; i < 9; i++)+ {+ float a = i * Mathf.PI * 2f / 9f + rnd.Range(-0.15f, 0.15f);+ km.Frond(top, new Vector3(Mathf.Cos(a), 0, Mathf.Sin(a)), rnd.Range(3.8f, 4.6f), 1.1f, rnd.Range(0.55f, 0.85f),+ i % 3 == 0 ? C(0.36f, 0.45f, 0.20f) : C(0.28f, 0.40f, 0.17f));+ }+ break;+ }+ default:+ km.Shaft(new Vector3(0, -0.6f, 0), new Vector3(0, 0.8f, 0), 0.2f, 0.18f, C(0.30f, 0.24f, 0.18f), 5);+ km.Crown(new Vector3(0, 4.6f, 0), new Vector3(1.05f, 4.4f, 1.05f), C(0.14f, 0.27f, 0.13f), ref rnd, 0.08f, 7, 7, 0f, default, 0.9f);+ break;+ }+ return km;+ }++ /// <summary>A tree's crown radius in real metres before the symbolic scale (a citrus patch: its four trees' extent).</summary>+ public static float CrownRadiusM(TreeKind k) => k switch+ {+ TreeKind.Citrus => 2.4f, TreeKind.CitrusPatch => 0.5f * GroveStepM * 1.42f + 2.4f, TreeKind.Olive => 2.8f,+ TreeKind.Palm => 4.6f, _ => 1.2f,+ };++ /// <summary>Real metres between the trees of a grove's rows.</summary>+ public const float GroveStepM = 4.9f;++ /// <summary>Promo 03's orange tree: a dark, lumpy crown of three clusters, heavy with fruit.</summary>+ static void CitrusTree(KitMesh km, Vector3 at, float size, ref KitRandom rnd, float shade = 1f)+ {+ Color32 C(float r, float g, float b) => new Color32((byte)(r * 255), (byte)(g * 255), (byte)(b * 255), 0);+ var leaf = C(0.17f * shade, 0.30f * shade, 0.12f * shade); var fruit = C(0.92f, 0.50f, 0.09f);+ km.Shaft(at + new Vector3(0, -0.6f, 0), at + new Vector3(0, 1.0f, 0) * size, 0.18f * size, 0.14f * size, C(0.33f, 0.25f, 0.17f), 4);+ km.Crown(at + new Vector3(0, 2.3f, 0) * size, new Vector3(2.1f, 1.8f, 2.1f) * size, leaf, ref rnd, 0.10f, 7, 5, 0.13f, fruit, 0.55f);+ km.Crown(at + new Vector3(0.9f, 2.9f, 0.5f) * size, new Vector3(1.3f, 1.1f, 1.3f) * size, leaf, ref rnd, 0.12f, 6, 4, 0.16f, fruit, 0.5f);+ km.Crown(at + new Vector3(-0.8f, 2.8f, -0.6f) * size, new Vector3(1.2f, 1.0f, 1.2f) * size, leaf, ref rnd, 0.12f, 6, 4, 0.16f, fruit, 0.5f);+ }++ /// <summary>Where each tree stands: (kind, world matrix) for the whole map, seeded.</summary>+ public static List<(TreeKind kind, Matrix4x4 m)> Plant(IReadOnlyList<Settlement> settlements, KitGround ground)+ {+ var trees = new List<(TreeKind, Matrix4x4)>();+ float s = KitScale.Trees;+ // Counts fall with the square of the tree scale (k = 1 at the default), so a larger tree covers the same ground+ // with fewer instances instead of burying the towns.+ float ks = s / KitScale.CountReference;+ void Add(TreeKind k, float x, float z, ref KitRandom rnd, float size = 1f, float yawDeg = float.NaN)+ {+ // No crown reaches into a building's or landmark's lot (integration bug B9: palms through Tel Aviv's roofs,+ // grove rows through blocks).+ if (ground.OnLot(x, z, CrownRadiusM(k) * s * size * 1.15f)) return;+ float y = ground.Y(x, z);+ var scale = s * size * rnd.Range(0.85f, 1.15f);+ float yaw = float.IsNaN(yawDeg) ? rnd.Range(0f, 360f) : yawDeg;+ trees.Add((k, Matrix4x4.TRS(new Vector3(x, y, z), Quaternion.Euler(0, yaw, 0), new Vector3(scale, scale * rnd.Range(0.9f, 1.1f), scale))));+ }++ // Citrus groves round the coastal-plain towns: rectangular blocks of rows, each grove on its own angle.+ foreach (var st in settlements)+ {+ var c3 = ground.Frame.ToWorld(st.Lon, st.Lat, 0); var c = new Vector2(c3.x, c3.z);+ var biome = ground.Biome(c.x, c.y);+ if (biome != "coastal_plain" && biome != "valley" && biome != "sea") continue;+ if (ground.ElevM(c.x, c.y) > 300f) continue;+ var rnd = new KitRandom(st.Id, 11);+ float R = SettlementKits.FootprintRadiusM(st, ground.HexSizeM);+ int groves = Mathf.Clamp(Mathf.RoundToInt(Mathf.Sqrt(Mathf.Max(KitPopulation.Of(st.Id), 400)) / 9f / ks), 1, 28);+ for (int g = 0, tries = 0; g < groves && tries < groves * 12; tries++)+ {+ float a = rnd.Range(0f, 2f * Mathf.PI), r = R * 0.95f + rnd.Range(0f, 8500f);+ var gc = c + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * r;+ if (!ground.Inside(gc.x, gc.y) || ground.Water(gc.x, gc.y) || ground.InTown(gc.x, gc.y, 0.9f)) continue;+ var gb = ground.Biome(gc.x, gc.y);+ if (gb != "coastal_plain" && gb != "valley" || ground.ElevM(gc.x, gc.y) > 250f || ground.Slope(gc.x, gc.y, 800f) > 0.06f) continue;+ g++;+ float yaw = rnd.Range(0f, 90f) * Mathf.Deg2Rad, ca = Mathf.Cos(yaw), sa = Mathf.Sin(yaw);+ // Grove sizes grow with the square root of the tree scale, so a bigger tree means fewer, not only larger, rows.+ float grow = Mathf.Sqrt(s / KitScale.CountReference);+ float w = rnd.Range(1300f, 3000f) * grow, d = rnd.Range(900f, 2000f) * grow, step = 2f * GroveStepM * s; // one 2 x 2 patch per step+ // A ragged block: each row stops at its own length, and some groves lose a corner (an L shape).+ bool notch = rnd.Chance(0.3f); float nu = rnd.Range(0.1f, 0.3f) * w, nv = rnd.Range(0.1f, 0.3f) * d;+ for (float v = -d / 2; v <= d / 2; v += step)+ {+ float rowEnd = w / 2 - rnd.Range(0f, 0.25f) * w;+ for (float u = -w / 2; u <= rowEnd; u += step)+ {+ if (notch && u > nu && v > nv) continue;+ if (rnd.Chance(0.05f)) continue; // a gap: a well, a packing shed's yard+ float x = gc.x + u * ca - v * sa, z = gc.y + u * sa + v * ca;+ if (ground.Water(x, z) || ground.InTown(x, z, 0.85f)) continue;+ // The patch's rows follow the grove's own angle (yaw is measured clockwise from north in Unity).+ float patchYaw = -yaw * Mathf.Rad2Deg + (rnd.Chance(0.5f) ? 0f : 90f);+ // All four of a patch's trees must stand on dry land outside the towns, or the spot gets one tree.+ float hd = 0.5f * GroveStepM * s * 1.15f; // half the patch's tree spacing, with its scale jitter+ bool whole = true;+ for (int k = 0; k < 4 && whole; k++)+ {+ float du = (k & 1) == 0 ? -hd : hd, dv = (k & 2) == 0 ? -hd : hd;+ float tx = x + du * ca - dv * sa, tz = z + du * sa + dv * ca;+ whole = !ground.Water(tx, tz) && !ground.InTown(tx, tz, 0.85f);+ }+ if (!whole || (u + step > rowEnd && rnd.Chance(0.5f))) Add(TreeKind.Citrus, x, z, ref rnd, rnd.Range(0.9f, 1.05f)); // an edge, or a row thinning out+ else Add(TreeKind.CitrusPatch, x, z, ref rnd, 1f, patchYaw);+ }+ }+ }+ }++ // Olives over the hills and mountains: one jittered cell per 1.2 km, in clumps (Perlin), denser by the old towns.+ {+ var rnd = new KitRandom("olives", 13);+ // About 2.6 crowns apart where they grow (promo 03's hills), but never more than one cell per 1.1 km: at small+ // tree scales the hills would need hundreds of thousands of trees (the WebGL budget, docs/visual-v1.md).+ float cell = Mathf.Max(1100f, 2.6f * 4.5f * s);+ for (float z = cell / 2; z < ground.Length; z += cell)+ for (float x = cell / 2; x < ground.Width; x += cell)+ {+ float px = x + rnd.Range(-0.45f, 0.45f) * cell, pz = z + rnd.Range(-0.45f, 0.45f) * cell;+ float clump = Mathf.PerlinNoise(px / 7000f + 13.1f, pz / 7000f + 7.7f);+ float p = Mathf.Clamp01((clump - 0.30f) * 1.8f) * 0.8f;+ if (p <= 0f && rnd.Value() > 0.03f) continue;+ if (!rnd.Chance(Mathf.Max(p, 0.03f))) continue;+ var b = ground.Biome(px, pz);+ bool plain = b == "coastal_plain";+ if (!plain && b != "hills" && b != "mountains" && b != "valley") continue;+ if (plain && !rnd.Chance(0.35f)) continue; // lone trees between the fields+ float e = ground.ElevM(px, pz);+ if (e < (plain ? 5f : 40f) || e > 950f || ground.Water(px, pz) || ground.InTown(px, pz, 0.9f) || ground.Slope(px, pz, 600f) > 0.35f) continue;+ int n = rnd.Range(1, 4);+ for (int i = 0; i < n; i++)+ {+ float tx = px + rnd.Range(-0.5f, 0.5f) * cell, tz = pz + rnd.Range(-0.5f, 0.5f) * cell;+ if (!ground.Water(tx, tz) && !ground.InTown(tx, tz, 0.85f)) Add(TreeKind.Olive, tx, tz, ref rnd);+ }+ }+ }++ // Palms by the shore of the coastal towns and in their streets; cypress windbreaks by villages and moshavot.+ foreach (var st in settlements)+ {+ var c3 = ground.Frame.ToWorld(st.Lon, st.Lat, 0); var c = new Vector2(c3.x, c3.z);+ var rnd = new KitRandom(st.Id, 17);+ float R = SettlementKits.FootprintRadiusM(st, ground.HexSizeM);+ var arch = SettlementKits.ArchetypeOf(st);+ bool coastal = ground.SeaDistance(c.x, c.y, 6000f) < 6000f;+ float beachKeep = 6.5f * s; // about a palm crown's radius plus the sand strip, in metres+ if (coastal)+ {+ int n = Mathf.Clamp(Mathf.RoundToInt(Mathf.Sqrt(Mathf.Max(KitPopulation.Of(st.Id), 400)) * 0.9f / (ks * ks)), 4, 260);+ for (int i = 0, tries = 0; i < n && tries < n * 10; tries++)+ {+ float a = rnd.Range(0f, 2f * Mathf.PI), r = (R + 2500f) * Mathf.Sqrt(rnd.Value());+ float x = c.x + Mathf.Cos(a) * r, z = c.y + Mathf.Sin(a) * r;+ if (ground.Water(x, z)) continue;+ bool shore = ground.SeaDistance(x, z, 1600f) < 1600f;+ if (!shore && !rnd.Chance(0.35f)) continue; // mostly by the shore, some in the streets+ i++;+ int clump = rnd.Range(1, 4);+ for (int k = 0; k < clump; k++)+ {+ float px = x + rnd.Range(-1f, 1f) * 6f * s, pz = z + rnd.Range(-1f, 1f) * 6f * s;+ // Back from the beach: a crown never overhangs promo-sea's sand strip (review N3).+ if (!ground.Water(px, pz) && ground.SeaDistance(px, pz, beachKeep) >= beachKeep) Add(TreeKind.Palm, px, pz, ref rnd);+ }+ }+ }+ if (arch == Archetype.Moshava || arch == Archetype.ArabTown)+ {+ int rows = Mathf.Max(1, Mathf.RoundToInt((arch == Archetype.Moshava ? 4 : 3) / ks));+ for (int row = 0; row < rows; row++)+ {+ float a = rnd.Range(0f, 2f * Mathf.PI), r = R * rnd.Range(0.5f, 1.15f);+ var o = c + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * r;+ var dir = new Vector2(-Mathf.Sin(a), Mathf.Cos(a));+ int n = rnd.Range(5, 11);+ for (int k = 0; k < n; k++)+ {+ var p = o + dir * ((k - n / 2f) * 3.2f * s);+ if (!ground.Water(p.x, p.y)) Add(TreeKind.Cypress, p.x, p.y, ref rnd, rnd.Range(0.9f, 1.1f));+ }+ }+ }+ }+ return trees;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Kits/Vegetation.cs.meta b/unity/Assets/Scripts/Map/Kits/Vegetation.cs.metanew file mode 100644index 000000000..90cd6f4df--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/Vegetation.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: d26d2b004ca94404aa76daac62a50769\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Kits/VegetationLayer.cs b/unity/Assets/Scripts/Map/Kits/VegetationLayer.csnew file mode 100644index 000000000..4c119f3c8--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/VegetationLayer.cs@@ -0,0 +1,88 @@+#nullable enable+using System.Collections.Generic;+using UnityEngine;+using UnityEngine.Rendering;++namespace Statecraft.Game.Map.Kits+{+ /// <summary>Draws the trees with GPU instancing (Graphics.RenderMeshInstanced, WebGL 2 instanced arrays): one batch list+ /// per tree kind and 30 km tile, each with its own bounds so off-screen tiles are culled. A tile's instances are shuffled+ /// once (seeded), so drawing a prefix thins it evenly: far tiles (the country-wide zoom) draw a share that falls with+ /// distance, where a tree is a pixel or less. Submitted for every camera from RenderPipelineManager.beginCameraRendering,+ /// so editor renders (MapCapture, the render-sample tests) see the trees as the player does.</summary>+ [ExecuteAlways]+ public sealed class VegetationLayer : MonoBehaviour+ {+ public const float TileM = 30000f;+ /// <summary>Tiles nearer than this draw every tree; beyond it the share falls as (ThinStartM / distance)^2.</summary>+ public const float ThinStartM = 110000f;++ sealed class Tile { public TreeKind kind; public Bounds bounds; public Matrix4x4[] m = System.Array.Empty<Matrix4x4>(); }++ readonly List<Tile> tiles = new List<Tile>();+ readonly Dictionary<TreeKind, Mesh> meshes = new Dictionary<TreeKind, Mesh>();+ Material? material;+ public bool Draw { get; set; } = true;+ public int Count { get; private set; }+ /// <summary>Instances submitted for the last camera (a test and profiling aid).</summary>+ public int LastDrawn { get; private set; }++ public void Init(List<(TreeKind kind, Matrix4x4 m)> trees, Material treeMaterial, MapRuntimeAssets assets)+ {+ material = treeMaterial;+ foreach (TreeKind k in System.Enum.GetValues(typeof(TreeKind))) meshes[k] = assets.Own(Vegetation.BuildMesh(k));+ var byTile = new Dictionary<(TreeKind, int, int), List<Matrix4x4>>();+ foreach (var (kind, m) in trees)+ {+ var p = m.GetColumn(3);+ var key = (kind, Mathf.FloorToInt(p.x / TileM), Mathf.FloorToInt(p.z / TileM));+ if (!byTile.TryGetValue(key, out var list)) byTile[key] = list = new List<Matrix4x4>();+ list.Add(m);+ }+ var keys = new List<(TreeKind, int, int)>(byTile.Keys);+ keys.Sort();+ tiles.Clear();+ foreach (var key in keys)+ {+ var list = byTile[key];+ var rnd = new KitRandom($"tile:{key.Item1}:{key.Item2}:{key.Item3}", 19);+ for (int i = list.Count - 1; i > 0; i--) { int j = rnd.Range(0, i + 1); (list[i], list[j]) = (list[j], list[i]); }+ var b = new Bounds((Vector3)list[0].GetColumn(3), Vector3.zero);+ foreach (var m in list) b.Encapsulate((Vector3)m.GetColumn(3));+ b.Expand(new Vector3(400f, 800f, 400f) * (KitScale.Trees / KitScale.CountReference)); // the crowns round the trunk points+ tiles.Add(new Tile { kind = key.Item1, bounds = b, m = list.ToArray() });+ }+ Count = trees.Count;+ }++ void OnEnable() => RenderPipelineManager.beginCameraRendering += Submit;+ void OnDisable() => RenderPipelineManager.beginCameraRendering -= Submit;++ void Submit(ScriptableRenderContext context, Camera cam)+ {+ if (!Draw || material == null || cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;+ var planes = GeometryUtility.CalculateFrustumPlanes(cam);+ var eye = cam.transform.position;+ int drawn = 0;+ foreach (var t in tiles)+ {+ // The shadow pass sees casters outside the view too, so cull on a widened box (the sun is 30 degrees up: a+ // crown's shadow reaches about twice its height).+ var wide = t.bounds; wide.Expand(new Vector3(3000f, 0f, 3000f));+ if (!GeometryUtility.TestPlanesAABB(planes, wide)) continue;+ float d = Mathf.Sqrt(t.bounds.SqrDistance(eye));+ float share = d <= ThinStartM ? 1f : Mathf.Clamp01((ThinStartM / d) * (ThinStartM / d));+ int n = Mathf.Min(t.m.Length, Mathf.CeilToInt(t.m.Length * share));+ if (n <= 0) continue;+ var rp = new RenderParams(material)+ {+ worldBounds = t.bounds, camera = cam, shadowCastingMode = ShadowCastingMode.On, receiveShadows = true,+ layer = gameObject.layer,+ };+ Graphics.RenderMeshInstanced(rp, meshes[t.kind], 0, t.m, n);+ drawn += n;+ }+ LastDrawn = drawn;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Kits/VegetationLayer.cs.meta b/unity/Assets/Scripts/Map/Kits/VegetationLayer.cs.metanew file mode 100644index 000000000..bcde50681--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/VegetationLayer.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 92b8ebd7000554750a11030a47769270\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/MapBuilder.cs b/unity/Assets/Scripts/Map/MapBuilder.csindex ac269f566..d9bf8b69b 100644--- a/unity/Assets/Scripts/Map/MapBuilder.cs+++ b/unity/Assets/Scripts/Map/MapBuilder.cs@@ -53,7 +53,14 @@ namespace Statecraft.Game.Map/// <summary>Builds the map from already-read inputs (HeightmapLoader.Load and LoadHexes over text and bytes), so a/// WebGL build needs no System.IO. Throws InvalidDataException, before creating any object, when the hexes' bounds/// differ from the heightmap's by more than <see cref="BoundsTolerance"/>.</summary>- public static GameObject Build(HeightmapMeta meta, float[,] heights, HexFile hexFile, Material terrainMaterial)+ public static GameObject Build(HeightmapMeta meta, float[,] heights, HexFile hexFile, Material terrainMaterial) =>+ Build(meta, heights, hexFile, terrainMaterial, null);++ /// <summary>As Build, with <paramref name="paintGround"/> given the baked biome colour texels (row 0 = south,+ /// <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){if (meta == null) throw new ArgumentNullException(nameof(meta));if (heights == null) throw new ArgumentNullException(nameof(heights));@@ -79,7 +86,7 @@ namespace Statecraft.Game.Mapterrain.basemapDistance = NoBasemapDistanceM;data.terrainLayers = new[] { NeutralLayer(assets) }; // one layer, one pass: the graph paints from the biome texturedata.alphamapResolution = 16;- MapShaderGlobals.Apply(terrain, meta, hexFile.hex_size_km * 1000f, BakeBiomeTexture(frame, hexFile, assets), assets);+ MapShaderGlobals.Apply(terrain, meta, hexFile.hex_size_km * 1000f, BakeBiomeTexture(frame, hexFile, assets, paintGround), assets);Boot.DiagLog.BootPhase("biome texture baked");return terrainGo;}@@ -132,7 +139,7 @@ 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)+ static Texture2D BakeBiomeTexture(GeoFrame frame, HexFile hexes, MapRuntimeAssets assets, Action<Color32[], int, GeoFrame> paint){var names = new List<string>(Biome.Keys);var colours = new Color[names.Count];@@ -156,6 +163,7 @@ namespace Statecraft.Game.Mapc.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;}diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex 546fd3b0d..15bc08ced 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -12,6 +12,9 @@ namespace Statecraft.Game.Mappublic sealed class MapScene : MonoBehaviour{[SerializeField] Material terrainMaterial, markerMaterial, selectionMaterial, seaMaterial, borderLandMaterial;+ /// <summary>The art spike's procedural settlement kits and trees (Kit.mat, Tree.mat: Statecraft/Kit). Optional: without+ /// them the map keeps the placeholder marker boxes.</summary>+ [SerializeField] Material kitMaterial, treeMaterial;public GeoFrame Frame { get; private set; }/// <summary>hexes.json as the last Build read it (bounds, hex size, biomes).</summary>@@ -94,6 +97,12 @@ namespace Statecraft.Game.MapseaMaterial = sea; borderLandMaterial = borderLand;}+ /// <summary>The settlement kits' and trees' materials (null, null: placeholder markers only).</summary>+ public void ConfigureKits(Material kit, Material tree) { kitMaterial = kit; treeMaterial = tree; }++ /// <summary>The last Build's kit numbers (buildings, vertices, trees, build time), or null without kits.</summary>+ public Kits.KitLayer.Stats KitStats { get; private set; }+/// <summary>Builds from the repository files with System.IO (editor and desktop only).</summary>public void Build() => Build(GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap));@@ -113,17 +122,56 @@ namespace Statecraft.Game.MapDiagLog.BootPhase("heightmap decoded");Hexes = MapBuilder.LoadHexes(inputs.HexesJson, HexesPath);DiagLog.BootPhase("hexes parsed");- var terrainGo = MapBuilder.Build(meta, heights, Hexes, terrainMaterial);+ var list = SettlementPlacer.Parse(inputs.SettlementsYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), SettlementsPath);+ Settlements = list;+ bool kitsOn = kitMaterial != null && treeMaterial != null;+ if (kitsOn)+ {+ if (string.IsNullOrWhiteSpace(inputs.PopulationYaml))+ {+ // Review N1: without the file every town would quietly take the smallest footprint. The editor (and its+ // tests) refuses; a player warns and builds the small towns rather than no map.+ var missing = $"map/{Kits.KitPopulation.FileName} is missing or empty: the settlement kits need it to size the towns";+ if (Application.isEditor) throw new InvalidDataException(missing);+ Debug.LogWarning("KITS " + missing + "; every town takes the smallest footprint");+ }+ Kits.KitPopulation.Use(string.IsNullOrWhiteSpace(inputs.PopulationYaml)+ ? new Dictionary<string, int>() : Kits.KitPopulation.Parse(inputs.PopulationYaml, "map/" + Kits.KitPopulation.FileName));+ }+ float hexSizeM = Hexes.hex_size_km * 1000f;+ var terrainGo = MapBuilder.Build(meta, heights, Hexes, terrainMaterial,+ kitsOn ? (px, res, frame) => Kits.SettlementKits.PaintGround(px, res, frame, list, hexSizeM) : null);terrainGo.transform.SetParent(transform, true);Terrain = terrainGo.GetComponent<Terrain>();var size = Terrain.terrainData.size;AddBorderSkirt(terrainGo, meta.elev_min_m);DiagLog.BootPhase("border skirt");Frame = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, size.x, size.z);- var list = SettlementPlacer.Parse(inputs.SettlementsYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), SettlementsPath);- Settlements = list;- SettlementPlacer.Place(list, Frame, Terrain, markerMaterial).transform.SetParent(transform, true);+ var markers = SettlementPlacer.Place(list, Frame, Terrain, markerMaterial);+ markers.transform.SetParent(transform, true);DiagLog.BootPhase("settlements placed");+ KitStats = null;+ if (kitsOn)+ {+ // ?kitscale=, ?housescale=, ?treescale= in the WebGL player: the same layout at another symbolic scale (city+ // blocks, houses, trees), clamped to KitScale.Min..Max; docs/dev-setup.md lists the flags.+ if (Application.platform == RuntimePlatform.WebGLPlayer)+ {+ var url = Application.absoluteURL;+ int ks = UrlFlags.Int(url, "kitscale"), hs = UrlFlags.Int(url, "housescale"), ts = UrlFlags.Int(url, "treescale");+ if (ks > 0) Kits.KitScale.CityBlocks = Kits.KitScale.Clamp(ks);+ if (hs > 0) Kits.KitScale.Houses = Kits.KitScale.Clamp(hs);+ if (ts > 0) Kits.KitScale.Trees = Kits.KitScale.Clamp(ts);+ }+ // The kits replace the marker boxes; the boxes stay as the labels' and tests' anchors, and come back when the+ // "kits" toggle turns the kits off (so settlements are never left undrawn).+ var kits = Kits.KitLayer.Build(list, Terrain, Frame, Hexes, meta.elev_min_m, kitMaterial, treeMaterial,+ terrainGo.GetComponent<MapRuntimeAssets>(), markers, out var stats);+ kits.transform.SetParent(transform, true);+ KitStats = stats;+ DiagLog.BootPhase("kits built");+ Debug.Log(stats.ToString());+ }if (!cam.TryGetComponent(out CameraRig rig)) rig = cam.gameObject.AddComponent<CameraRig>();rig.LookAt = Frame.ToWorld(34.95, 31.95, 0); rig.Init(); // central Israel: Tel Aviv–Jerusalem corridordiff --git a/unity/Assets/Shaders/Kit.shader b/unity/Assets/Shaders/Kit.shadernew file mode 100644index 000000000..b70ae027c--- /dev/null+++ b/unity/Assets/Shaders/Kit.shader@@ -0,0 +1,160 @@+// Settlement kits and trees (art spike, issues #31 #32 #34 #37). Vertex colour is the sRGB albedo; its alpha picks a+// facade's window pattern (KitMesh.Facade), drawn from uv0 = the wall's (along, up) position in real metres, so storeys and+// windows keep real proportions on symbolic-size buildings, box-filtered so they fade to their mean instead of shimmering+// when a storey is a pixel or two. Lit like the terrain (the sun with its shadows, the trilight ambient through SH) and+// hazed with the terrain's own ScHazeAmount, so kits sit in the same air as the ground. GPU instancing for the trees, with a+// per-instance tint hashed from the instance's origin (no per-instance buffer: WebGL 2 has instanced arrays only).+// Shadows use the sun's own URP bias, unchanged (ApplyShadowBias): KitTests.AKitShadowStartsAtItsWalls finds no gap at+// the walls with it and the hero renders show no acne (#37, review I3), so the kits carry no bias of their own.+Shader "Statecraft/Kit"+{+ Properties+ {+ _BaseColor ("Tint", Color) = (1, 1, 1, 1)+ _Jitter ("Per-instance tint jitter", Range(0, 0.5)) = 0+ _WindowDark ("Window darkness", Range(0, 1)) = 0.55+ }+ SubShader+ {+ Tags { "RenderType" = "Opaque" "Queue" = "Geometry" "RenderPipeline" = "UniversalPipeline" }+ HLSLINCLUDE+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"+ CBUFFER_START(UnityPerMaterial)+ half4 _BaseColor;+ half _Jitter, _WindowDark;+ CBUFFER_END+ ENDHLSL++ Pass+ {+ Name "Kit"+ Tags { "LightMode" = "UniversalForward" }+ HLSLPROGRAM+ #pragma vertex Vert+ #pragma fragment Frag+ #pragma multi_compile_instancing+ #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN+ #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"+ #include "Assets/Shaders/StatecraftMap.hlsl"++ struct Attributes+ {+ float4 positionOS : POSITION; float3 normalOS : NORMAL; half4 color : COLOR; float2 uv : TEXCOORD0;+ UNITY_VERTEX_INPUT_INSTANCE_ID+ };+ struct Varyings+ {+ float4 positionCS : SV_POSITION; float3 positionWS : TEXCOORD0; float3 normalWS : TEXCOORD1;+ half4 color : TEXCOORD2; float2 uv : TEXCOORD3; half tint : TEXCOORD4;+ };++ Varyings Vert(Attributes v)+ {+ Varyings o;+ UNITY_SETUP_INSTANCE_ID(v);+ VertexPositionInputs p = GetVertexPositionInputs(v.positionOS.xyz);+ o.positionCS = p.positionCS; o.positionWS = p.positionWS;+ o.normalWS = TransformObjectToWorldNormal(v.normalOS);+ o.color = v.color; o.uv = v.uv;+ float3 origin = TransformObjectToWorld(float3(0, 0, 0));+ o.tint = ScHash(origin.xz * 0.0137 + 3.1);+ return o;+ }++ // A 1D band [a, b] of a period-1 pattern, box-filtered over the pixel's footprint w (in periods).+ float Band(float x, float a, float b, float w)+ {+ float lo = saturate((frac(x) - a) / max(w, 1e-4) + 0.5), hi = saturate((frac(x) - b) / max(w, 1e-4) + 0.5);+ return lo - hi;+ }++ // Window mask (1 = glass) and its mean over a whole storey, for each facade style.+ float Windows(float style, float2 uv, float2 fw, out float mean)+ {+ float storey = 3.3, bay = style > 0.75 ? 1.7 : (style > 0.4 ? 4.2 : 3.0);+ float wv = fw.y / storey, wu = fw.x / bay;+ float a0, a1, b0, b1;+ if (style > 0.75) { a0 = 0.38; a1 = 0.80; b0 = 0.10; b1 = 0.95; } // white city: ribbon windows+ else if (style > 0.4) { a0 = 0.40; a1 = 0.72; b0 = 0.38; b1 = 0.62; } // village / moshava: a few small windows+ else { a0 = 0.36; a1 = 0.74; b0 = 0.34; b1 = 0.64; } // stone: arched-height windows+ mean = (a1 - a0) * (b1 - b0);+ float m = Band(uv.y / storey, a0, a1, wv) * Band(uv.x / bay, b0, b1, wu);+ // Fade to the mean once a storey is under about three pixels: no moire at the gameplay zoom.+ return lerp(mean, m, saturate(1.5 - wv * 3.0)) * step(0.0, uv.y);+ }++ half4 Frag(Varyings i) : SV_Target+ {+ float3 n = SafeNormalize(i.normalWS); // never NaN, even for a degenerate face+ half3 albedo = SRGBToLinear(i.color.rgb) * _BaseColor.rgb;+ // Per-instance (tree) tint: brighter or darker, a touch warmer or cooler.+ float t = i.tint - 0.5;+ albedo *= 1.0 + _Jitter * t * 2.0;+ albedo.r *= 1.0 + _Jitter * (frac(i.tint * 7.31) - 0.5);+ float style = i.color.a;+ float2 fw = fwidth(i.uv); // outside the branch: derivatives need uniform control flow+ if (style > 0.1)+ {+ float mean;+ float glass = Windows(style, i.uv, fw, mean);+ // White-city balconies: a lighter slab line and its shadow under it, every storey.+ if (style > 0.75)+ {+ float fv = fw.y / 3.3;+ float slab = Band(i.uv.y / 3.3, 0.28, 0.36, fv), under = Band(i.uv.y / 3.3, 0.36, 0.42, fv);+ float fade = saturate(1.5 - fv * 3.0);+ albedo *= 1.0 + 0.10 * lerp(0.08, slab, fade) - 0.22 * lerp(0.06, under, fade);+ }+ albedo *= 1.0 - _WindowDark * glass;+ // Contact darkening in the bottom real 3 m of a wall.+ albedo *= lerp(0.72, 1.0, saturate(i.uv.y / 3.0));+ }+ Light sun = GetMainLight(TransformWorldToShadowCoord(i.positionWS));+ float ndl = saturate(dot(n, sun.direction));+ half3 lit = albedo * (SampleSH(n) + sun.color * ndl * sun.shadowAttenuation);+ float h = _ScHaze.a * ScHazeAmount(i.positionWS);+ return half4(lerp(lit, _ScHaze.rgb, h), 1.0);+ }+ ENDHLSL+ }+ Pass+ {+ Name "ShadowCaster"+ Tags { "LightMode" = "ShadowCaster" }+ ZWrite On ZTest LEqual ColorMask 0+ Cull Back+ HLSLPROGRAM+ #pragma vertex Vert+ #pragma fragment Frag+ #pragma multi_compile_instancing+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl"+ float3 _LightDirection;+ struct Attributes { float4 positionOS : POSITION; float3 normalOS : NORMAL; UNITY_VERTEX_INPUT_INSTANCE_ID };+ float4 Vert(Attributes v) : SV_POSITION+ {+ UNITY_SETUP_INSTANCE_ID(v);+ float3 positionWS = TransformObjectToWorld(v.positionOS.xyz);+ float3 normalWS = TransformObjectToWorldNormal(v.normalOS);+ return ApplyShadowClamping(TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, _LightDirection)));+ }+ half4 Frag() : SV_Target { return 0; }+ ENDHLSL+ }+ Pass+ {+ Name "DepthOnly"+ Tags { "LightMode" = "DepthOnly" }+ ZWrite On+ ColorMask R+ HLSLPROGRAM+ #pragma vertex Vert+ #pragma fragment Frag+ #pragma multi_compile_instancing+ struct Attributes { float4 positionOS : POSITION; UNITY_VERTEX_INPUT_INSTANCE_ID };+ float4 Vert(Attributes v) : SV_POSITION { UNITY_SETUP_INSTANCE_ID(v); return TransformObjectToHClip(v.positionOS.xyz); }+ half Frag() : SV_Target { return 0; }+ ENDHLSL+ }+ }+}diff --git a/unity/Assets/Shaders/Kit.shader.meta b/unity/Assets/Shaders/Kit.shader.metanew file mode 100644index 000000000..f24fdd790--- /dev/null+++ b/unity/Assets/Shaders/Kit.shader.meta@@ -0,0 +1,9 @@+fileFormatVersion: 2+guid: faec37efeea0d4ef19af13ee3400c978+ShaderImporter:+ externalObjects: {}+ defaultTextures: []+ nonModifiableTextures: []+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Tests/EditMode/HexGridTests.cs b/unity/Assets/Tests/EditMode/HexGridTests.csindex 30a9bbfa6..06168fe88 100644--- a/unity/Assets/Tests/EditMode/HexGridTests.cs+++ b/unity/Assets/Tests/EditMode/HexGridTests.cs@@ -1,5 +1,6 @@#nullable enableusing System.Collections;+using System.Linq;using NUnit.Framework;using Statecraft.Game.Map;using UnityEditor;@@ -128,6 +129,8 @@ public class HexGridTestsyield return null;PromoPose.Gameplay03.Apply(rig, map.Frame);rig.TopInset = 0; rig.Apply();+ // The line's profile on the ground itself: the settlement kits and trees (art spike) stand on some edges.+ foreach (var n in new[] { "kits", "trees" }) if (VisualToggles.Names.Contains(n)) VisualToggles.Set(n, false);float size = map.Hexes.hex_size_km * 1000f, inradius = Mathf.Sqrt(3f) / 2f * size;var origin = map.Terrain.transform.position;HexJson? Find(double lon, double lat, System.Func<HexJson, bool> ok)diff --git a/unity/Assets/Tests/EditMode/HudTests.cs b/unity/Assets/Tests/EditMode/HudTests.csindex 4bb1e97f5..bf356525a 100644--- a/unity/Assets/Tests/EditMode/HudTests.cs+++ b/unity/Assets/Tests/EditMode/HudTests.cs@@ -369,6 +369,7 @@ public class HudTests("MinimapPresenter.cs", "Length.Percent(", "the view frame's position and size in percent of the picture (layout, not text)"),("PortraitFraming.cs", "offset / (h - boxH) * 100f", "a portrait's background-position-y in percent (layout, not text)"),("MapShaderGlobals.cs", "RiftHazeTopM = -100f", "a real elevation in metres for the rift haze (shader input, not a displayed number)"),+ ("SettlementKits.cs", "DefaultHouses = 100f", "the owner's symbolic scale for houses and trees (100x real size), not a displayed number"),};[Test]diff --git a/unity/Assets/Tests/EditMode/KitTests.cs b/unity/Assets/Tests/EditMode/KitTests.csnew file mode 100644index 000000000..50d2ba863--- /dev/null+++ b/unity/Assets/Tests/EditMode/KitTests.cs@@ -0,0 +1,409 @@+#nullable enable+using System.Collections;+using System.Collections.Generic;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Kits;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;++/// <summary>The art spike's procedural settlement kits and trees (issues #31 #32 #34 #37): seeded, sized by population, on+/// land, drawn for WebGL 2, and with shadows that start at the walls.</summary>+public class KitTests+{+ [TearDown]+ public void Restore()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ ShadowFit.Restore();+ VisualToggles.Clear();+ KitScale.Reset();+ }++ static MapScene OpenMap()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();+ return map;+ }++ static KitGround Ground(MapScene map) =>+ new KitGround(map.Terrain, map.Frame, map.Hexes, HeightmapLoader.Load(Statecraft.Game.Paths.StreamingMap).meta.elev_min_m);++ [Test]+ public void TheSeedIsTheKeyNotTheClock()+ {+ var a = new KitRandom("tel_aviv", 1); var b = new KitRandom("tel_aviv", 1); var c = new KitRandom("jaffa", 1);+ var sa = Enumerable.Range(0, 64).Select(_ => a.Next()).ToArray();+ CollectionAssert.AreEqual(sa, Enumerable.Range(0, 64).Select(_ => b.Next()).ToArray());+ CollectionAssert.AreNotEqual(sa, Enumerable.Range(0, 64).Select(_ => c.Next()).ToArray());+ var r = new KitRandom("x");+ for (int i = 0; i < 1000; i++) { var v = r.Value(); Assert.That(v, Is.InRange(0f, 0.99999994f)); }+ }++ [Test]+ public void EveryBuildDrawsTheSameTownsAndTrees()+ {+ var map = OpenMap();+ var list = map.Settlements;+ var first = SettlementKits.Build(list, Ground(map)); var second = SettlementKits.Build(list, Ground(map));+ Assert.AreEqual(first.Count, second.Count);+ for (int i = 0; i < first.Count; i++)+ {+ Assert.AreEqual(first[i].s.Id, second[i].s.Id);+ Assert.AreEqual(first[i].buildings, second[i].buildings, first[i].s.Id);+ Assert.AreEqual(first[i].mesh.vertexCount, second[i].mesh.vertexCount, first[i].s.Id);+ Assert.AreEqual(first[i].mesh.bounds, second[i].mesh.bounds, first[i].s.Id);+ }+ foreach (var k in first.Concat(second)) Object.DestroyImmediate(k.mesh);+ var t1 = Vegetation.Plant(list, Ground(map)); var t2 = Vegetation.Plant(list, Ground(map));+ Assert.AreEqual(t1.Count, t2.Count);+ for (int i = 0; i < t1.Count; i++) { Assert.AreEqual(t1[i].kind, t2[i].kind); Assert.AreEqual(t1[i].m, t2[i].m); }+ TestContext.WriteLine(map.KitStats);+ }++ [Test]+ public void TownsSpreadInProportionToTheirPeople()+ {+ var map = OpenMap();+ float hex = map.Hexes.hex_size_km * 1000f;+ var byId = map.Settlements.ToDictionary(s => s.Id);+ float R(string id) => SettlementKits.FootprintRadiusM(byId[id], hex);+ float hexArea = 1.5f * Mathf.Sqrt(3f) * hex * hex;+ // Area in hexes = people / PeoplePerHex (Tel Aviv 166,660 in 1945: about 2.8 hexes), floored for the smallest places.+ Assert.AreEqual(166660f / SettlementKits.PeoplePerHex, Mathf.PI * R("tel_aviv") * R("tel_aviv") / hexArea, 0.01f);+ Assert.AreEqual(94310f / 166660f, (R("jaffa") * R("jaffa")) / (R("tel_aviv") * R("tel_aviv")), 0.001f, "area ratio = population ratio");+ Assert.Greater(R("jaffa"), R("lod")); Assert.Greater(R("lod"), R("rishon_lezion"));+ Assert.AreEqual(R("hanita"), R("revivim"), 1e-3f, "the floor");+ // The kits root: one merged mesh per settlement with Kit.mat, and more buildings in bigger towns.+ var root = map.transform.Find(KitLayer.RootName); Assert.IsNotNull(root);+ var kit = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Kit.mat");+ foreach (var s in map.Settlements)+ {+ var t = root.Find(s.Id); Assert.IsNotNull(t, s.Id);+ var r = t.GetComponent<MeshRenderer>(); Assert.AreSame(kit, r.sharedMaterial, s.Id);+ Assert.Greater(t.GetComponent<MeshFilter>().sharedMesh.vertexCount, 0, s.Id);+ Assert.IsFalse(map.transform.Find("Settlements").Find(s.Id).GetComponent<MeshRenderer>().enabled, s.Id + ": the marker box is hidden");+ }+ int V(string id) => root.Find(id).GetComponent<MeshFilter>().sharedMesh.vertexCount;+ Assert.Greater(V("tel_aviv"), V("petah_tikva")); Assert.Greater(V("jaffa"), V("lod")); Assert.Greater(V("petah_tikva"), V("hanita"));+ TestContext.WriteLine(map.KitStats);+ }++ /// <summary>Review N1: with the kits on, a map without its population file refuses to build in the editor (a player+ /// would warn and give every town the smallest footprint).</summary>+ [Test]+ public void AMissingPopulationFileIsAnErrorInTheEditor()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = Object.FindFirstObjectByType<MapScene>();+ var inputs = Statecraft.Game.Boot.GameInputs.MapFromDisk(Statecraft.Game.Paths.Content, Statecraft.Game.Paths.StreamingMap);+ inputs.PopulationYaml = "";+ var ex = Assert.Throws<System.IO.InvalidDataException>(() => map.Build(inputs));+ StringAssert.Contains(KitPopulation.FileName, ex.Message);+ map.ConfigureKits(null, null); // without the kits the file is not needed (the scene is not saved)+ Assert.DoesNotThrow(() => map.Build(inputs));+ }++ /// <summary>Review N2: no two towns' lots overlap, landmarks (mosques, water towers, Jaffa's clock tower and church)+ /// included: a landmark looks for a free spot near its town's heart and is left out when there is none.</summary>+ [Test]+ public void NoTownsBuildingsOrLandmarksOverlapAnotherTowns()+ {+ var map = OpenMap();+ var built = SettlementKits.Build(map.Settlements, Ground(map), out var lots);+ int overlaps = 0;+ for (int i = 0; i < lots.Count; i++)+ for (int j = i + 1; j < lots.Count; j++)+ if (lots[i].id != lots[j].id && (lots[i].centre - lots[j].centre).magnitude < lots[i].radius + lots[j].radius - 1f) overlaps++;+ foreach (var k in built) Object.DestroyImmediate(k.mesh);+ TestContext.WriteLine($"{lots.Count} lots over {lots.Select(l => l.id).Distinct().Count()} towns");+ Assert.AreEqual(0, overlaps, "lots of different towns overlap");+ Assert.AreEqual(map.Settlements.Count, lots.Select(l => l.id).Distinct().Count(), "every town claimed ground");+ }++ /// <summary>Integration bug B9: palms grew out of Tel Aviv's and Jaffa's roofs and grove rows ran through blocks. No tree+ /// instance stands inside, or reaches with its crown into, any building's or landmark's lot.</summary>+ [Test]+ public void NoTreeGrowsThroughABuildingOrLandmark()+ {+ var map = OpenMap();+ var g = Ground(map);+ var built = SettlementKits.Build(map.Settlements, g, out var lots);+ foreach (var k in built) Object.DestroyImmediate(k.mesh);+ foreach (var l in lots) g.Lots.Add((l.centre, l.radius));+ var trees = Vegetation.Plant(map.Settlements, g);+ int inside = 0, touching = 0;+ foreach (var (kind, m) in trees)+ {+ Vector3 p = m.GetColumn(3); float scale = ((Vector3)m.GetColumn(0)).magnitude;+ foreach (var l in lots)+ {+ float d = (new Vector2(p.x, p.z) - l.centre).magnitude;+ if (d < l.radius) inside++;+ else if (d < l.radius + Vegetation.CrownRadiusM(kind) * scale) touching++;+ }+ }+ TestContext.WriteLine($"{trees.Count} trees against {lots.Count} lots: {inside} inside a lot, {touching} crowns reaching one");+ Assert.AreEqual(0, inside, "trees standing inside a building's or landmark's lot");+ Assert.AreEqual(0, touching, "crowns reaching into a lot");+ Assert.Greater(trees.Count, 3000, "the groves and hills still have their trees");+ }++ /// <summary>Review M6: switching the kits off shows the marker boxes again, so a settlement is never left undrawn.</summary>+ [Test]+ public void TheKitsToggleSwapsKitsAndMarkers()+ {+ var map = OpenMap();+ var kits = map.transform.Find(KitLayer.RootName).GetComponentsInChildren<MeshRenderer>();+ var markers = map.transform.Find("Settlements").GetComponentsInChildren<MeshRenderer>();+ Assert.IsTrue(kits.All(r => r.enabled)); Assert.IsTrue(markers.All(r => !r.enabled));+ VisualToggles.Set("kits", false);+ Assert.IsTrue(kits.All(r => !r.enabled)); Assert.IsTrue(markers.All(r => r.enabled), "the markers come back");+ VisualToggles.Set("kits", true);+ Assert.IsTrue(kits.All(r => r.enabled)); Assert.IsTrue(markers.All(r => !r.enabled));+ }++ /// <summary>Review I2: the populations come from content/map/settlement_population_1945.yaml through the map inputs.</summary>+ [Test]+ public void ThePopulationFileLoadsAndRejectsBadRows()+ {+ var inputs = Statecraft.Game.Boot.GameInputs.MapFromDisk(Statecraft.Game.Paths.Content, Statecraft.Game.Paths.StreamingMap);+ var table = KitPopulation.Parse(inputs.PopulationYaml);+ Assert.AreEqual(166660, table["tel_aviv"]); Assert.AreEqual(94310, table["jaffa"]); Assert.AreEqual(5570, table["beersheba"]);+ Assert.IsFalse(table.ContainsKey("revivim"), "a place the source does not list has no figure");+ Assert.AreEqual(23, table.Count);+ OpenMap();+ Assert.AreEqual(166660, KitPopulation.Of("tel_aviv"), "MapScene.Build hands the table to the kits");+ Assert.AreEqual(0, KitPopulation.Of("revivim"));+ const string src = " sources:\n - url: https://example.org/x\n checked: '2026-10-11'\n";+ void Bad(string yaml, string expect)+ {+ var ex = Assert.Throws<System.IO.InvalidDataException>(() => KitPopulation.Parse(yaml, "pop.yaml"));+ StringAssert.Contains("pop.yaml", ex.Message); StringAssert.Contains(expect, ex.Message);+ }+ Bad("settlements:\n- id: a\n population: -1\n status: owner-verify\n" + src, "negative");+ Bad("settlements:\n- id: a\n population: 1\n status: maybe\n" + src, "status");+ Bad("settlements:\n- id: a\n population: 1\n status: owner-verify\n sources: []\n", "sources");+ Bad("settlements:\n- id: a\n population: 1\n status: owner-verify\n" + src + "- id: a\n population: 2\n status: owner-verify\n" + src, "duplicate");+ Bad("settlements:\n- id: A\n population: 1\n status: owner-verify\n" + src, "snake_case");+ Bad("settlements:\n- id: a\n people: 1\n", "people");+ }++ [Test]+ public void KitsAndTreesStandOnLand()+ {+ var map = OpenMap();+ var g = Ground(map);+ var root = map.transform.Find(KitLayer.RootName);+ foreach (var s in map.Settlements)+ {+ var b = root.Find(s.Id).GetComponent<MeshRenderer>().bounds;+ Assert.Less(b.size.x, 2.6f * SettlementKits.FootprintRadiusM(s, g.HexSizeM) + 2000f, s.Id + ": the town stays within its footprint");+ }+ var trees = Vegetation.Plant(map.Settlements, g);+ Assert.Greater(trees.Count(t => t.kind == TreeKind.Citrus) + 4 * trees.Count(t => t.kind == TreeKind.CitrusPatch), 1000); Assert.Greater(trees.Count(t => t.kind == TreeKind.Olive), 1000);+ Assert.Greater(trees.Count(t => t.kind == TreeKind.Palm), 50); Assert.Greater(trees.Count(t => t.kind == TreeKind.Cypress), 50);+ int wet = 0, inTown = 0;+ foreach (var (kind, m) in trees)+ {+ Vector3 p = m.GetColumn(3);+ if (g.Water(p.x, p.z)) wet++;+ Assert.AreEqual(g.Y(p.x, p.z), p.y, 0.5f, "rooted on the ground");+ if (kind != TreeKind.CitrusPatch) continue;+ // Every tree of a 2x2 patch, not only its centre, stands on land and outside the towns (review M2).+ float d = Vegetation.GroveStepM * 0.5f;+ foreach (var local in new[] { new Vector3(-d, 0, -d), new Vector3(d, 0, -d), new Vector3(-d, 0, d), new Vector3(d, 0, d) })+ {+ var t = m.MultiplyPoint3x4(local);+ if (g.Water(t.x, t.z)) wet++;+ if (g.InTown(t.x, t.z, 0.85f)) inTown++;+ }+ }+ Assert.AreEqual(0, wet, "trees in the water");+ Assert.AreEqual(0, inTown, "patch trees inside a town");+ }++ /// <summary>The WebGL checkpoint drew every palm black: a frond's tip quad collapsed to a point, its edge-based normal was+ /// zero and normalize(0) is NaN on WebGL 2 (the tilt-shift then smeared it into black blocks). No part may have one.</summary>+ [Test]+ public void EveryPartHasAUnitNormal()+ {+ foreach (TreeKind k in System.Enum.GetValues(typeof(TreeKind))) Assert.AreEqual(0, Vegetation.Build(k).BadNormals, k.ToString());+ var km = new KitMesh(); var rnd = new KitRandom("parts");+ km.Box(0, 0, 17f, 500f, 300f, -50f, 0f, 400f, new Color32(255, 255, 255, 255), new Color32(200, 200, 200, 255), Facade.WhiteCity, 25f);+ km.Gable(0, 0, 17f, 500f, 300f, 400f, 120f, new Color32(200, 80, 50, 255), new Color32(255, 255, 255, 255));+ km.Pyramid(0, 0, 0f, 100f, 100f, 0f, 80f, new Color32(255, 255, 255, 255));+ km.Dome(0, 0, 0f, 100f, new Color32(255, 255, 255, 255));+ km.Shaft(Vector3.zero, Vector3.up * 300f, 30f, 20f, new Color32(255, 255, 255, 255), 8);+ km.Cone(Vector3.zero, 30f, 40f, new Color32(255, 255, 255, 255), 8);+ km.Crown(Vector3.zero, Vector3.one * 50f, new Color32(40, 80, 30, 255), ref rnd);+ km.Frond(Vector3.zero, Vector3.right, 100f, 25f, 0.7f, new Color32(40, 80, 30, 255));+ Assert.AreEqual(0, km.BadNormals);+ }++ [Test]+ public void TheKitShaderRunsOnWebGL2()+ {+ var shader = Shader.Find("Statecraft/Kit"); Assert.IsNotNull(shader);+ CollectionAssert.IsEmpty(ShaderChecks.Gles3Errors(shader));+ var tree = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Tree.mat");+ Assert.AreSame(shader, tree.shader); Assert.IsTrue(tree.enableInstancing, "the trees are GPU-instanced");+ }++ [UnityTest]+ public IEnumerator TheTreesAreDrawnAtTheGameplayPoseAndThinnedAtTheOverview()+ {+ var map = OpenMap();+ yield return null;+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();+ var veg = map.GetComponentInChildren<VegetationLayer>(); Assert.IsNotNull(veg);+ PromoPose.Gameplay03.Apply(rig, map.Frame); RenderSample.Render(cam, 320, 180);+ int near = veg.LastDrawn;+ PromoPose.Diorama02.Apply(rig, map.Frame); RenderSample.Render(cam, 320, 180);+ int far = veg.LastDrawn;+ TestContext.WriteLine($"trees {veg.Count}: drawn at gameplay03 {near}, at diorama02 {far}");+ Assert.Greater(near, 1000); Assert.Less(far, veg.Count * 0.6f, "the overview thins the far tiles");+ VisualToggles.Set("trees", false); RenderSample.Render(cam, 320, 180);+ Assert.AreEqual(far, veg.LastDrawn, "the trees toggle stops the draws (no new submission)");+ }++ /// <summary>Review M5: the hex grid stays readable through the towns and groves at gameplay03. Midpoints of the land+ /// hex edges in view; at each, the line shows when switching the grid off changes the 3x3 neighbourhood's luma by more+ /// than 3/255 (HexGridTests' threshold). With kits and trees on, at least <see cref="GridReadableShare"/> of the+ /// midpoints whose line shows on bare ground must still show it (the rest are covered by a building or a crown).</summary>+ public const float GridReadableShare = 0.75f; // measured 84% (76 of 90) at the 2026-10-11 defaults++ [UnityTest]+ public IEnumerator TheGridStaysReadableThroughTownsAndGroves()+ {+ var map = OpenMap();+ yield return null;+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();+ RenderSample.TiltShift(false);+ float size = map.Hexes.hex_size_km * 1000f;+ var origin = map.Terrain.transform.position; var g = Ground(map);+ var look = PromoPose.Gameplay03; var c = map.Frame.ToWorld(look.Lon, look.Lat, 0);+ var mids = new List<Vector3>(); var seen = new HashSet<(int, int)>();+ foreach (var h in map.Hexes.hexes)+ {+ if (!h.land) continue;+ var hc = HexGrid.Centre(h.q, h.r, size);+ for (int i = 0; i < 6; i++)+ {+ var m2 = (HexMath.Corner(hc, size, i) + HexMath.Corner(hc, size, (i + 1) % 6)) * 0.5f;+ var w = HexGrid.ToWorld(m2, origin, map.Frame.LengthM);+ if (Mathf.Abs(w.x - c.x) > 30000f || Mathf.Abs(w.z - c.z) > 30000f || g.Water(w.x, w.z)) continue;+ if (!seen.Add((Mathf.RoundToInt(w.x / 10f), Mathf.RoundToInt(w.z / 10f)))) continue;+ w.y = g.Y(w.x, w.z); mids.Add(w);+ }+ }+ var px = new Vector2[mids.Count];+ bool[] Shows(bool kits)+ {+ VisualToggles.Set("kits", kits); VisualToggles.Set("trees", kits);+ var on = RenderSample.Render(cam, 1920, 1080, mids.ToArray(), px);+ VisualToggles.Set("grid", false);+ var off = RenderSample.Render(cam, 1920, 1080, mids.ToArray(), px);+ VisualToggles.Set("grid", true);+ var shows = new bool[mids.Count];+ for (int i = 0; i < mids.Count; i++)+ {+ int x = (int)px[i].x, y = (int)px[i].y;+ if (x < 2 || y < 2 || x > 1917 || y > 1077) continue;+ float change = 0f;+ for (int dx = -1; dx <= 1; dx++)+ for (int dy = -1; dy <= 1; dy++)+ change = Mathf.Max(change, Mathf.Abs(RenderSample.Luma(on.At(x + dx, y + dy)) - RenderSample.Luma(off.At(x + dx, y + dy))));+ shows[i] = change > 0.012f;+ }+ return shows;+ }+ var bare = Shows(false); var built = Shows(true);+ int baseCount = bare.Count(b => b), kept = Enumerable.Range(0, mids.Count).Count(i => bare[i] && built[i]);+ float share = kept / (float)Mathf.Max(1, baseCount);+ TestContext.WriteLine($"gameplay03: {mids.Count} land edge midpoints in range, line shows at {baseCount} on bare ground, {kept} of them with kits and trees on ({share:P0})");+ Assert.Greater(baseCount, 50, "enough edges in view");+ Assert.GreaterOrEqual(share, GridReadableShare, "the grid is buried under the kits");+ }++ /// <summary>Issue #37 (review I3): with the sun's own URP bias, unchanged, a kit's shadow starts at its walls and its lit+ /// faces show no acne. A lone kit box on the open coastal plain at the hero (12 km), gameplay (60 km) and overview+ /// (250 km) zooms, on both tiers. Walking out from the shadow-side wall along the sun's travel, from 1 m in 1 m steps+ /// to 20 m and then in steps of a twentieth of a shadow texel, the gap is the distance to the first ground sample that+ /// is clearly in shadow (darker, shadows on against off, by 60% of the deep shadow's darkening); it must stay within one+ /// screen pixel, so no lit strip can show. The sunlit roof must not darken with shadows on (acne). The old+ /// marker material (URP Lit) is measured alongside for the record.</summary>+ [UnityTest]+ public IEnumerator AKitShadowStartsAtItsWalls([Values(0, 1)] int level, [Values(12000f, 60000f, 250000f)] float distance)+ {+ int previous = QualitySettings.GetQualityLevel();+ QualitySettings.SetQualityLevel(level, false); // 0 = the web tier (1 cascade, bias 1 / 1), 1 = desktop+ try { yield return Measure(level, distance); }+ finally { QualitySettings.SetQualityLevel(previous, false); }+ }++ IEnumerator Measure(int level, float distance)+ {+ var map = OpenMap();+ yield return null;+ foreach (var n in VisualToggles.Names.Where(n => n != "shadows")) VisualToggles.Set(n, false);+ var g = Ground(map);+ var at = map.Frame.ToWorld(34.70, 31.70, 0);+ float w = distance > 100000f ? 1800f : distance > 30000f ? 600f : 300f, h = w;+ var km = new KitMesh();+ float y = g.Y(at.x, at.z);+ km.Box(at.x, at.z, 0f, w, w, y - 30f, y, h, new Color32(235, 230, 220, 255), new Color32(200, 200, 190, 255), Facade.Plain, 25f);+ var mesh = km.ToMesh("ShadowProbe");+ var kit = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Kit.mat");+ var marker = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/SettlementMarker.mat");+ var go = new GameObject("ShadowProbe"); go.AddComponent<MeshFilter>().sharedMesh = mesh;+ var mr = go.AddComponent<MeshRenderer>(); mr.sharedMaterial = kit;+ try+ {+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();+ rig.LookAt = at; rig.Distance = distance; rig.Yaw = 0f; rig.TopInset = 0f; rig.Apply();+ var sun = MapLighting.FindSun()!; var fall = sun.transform.forward; fall.y = 0f; fall.Normalize();+ // Distance from the centre to the wall along the fall (the fall crosses the wall facing it).+ float toWall = 0.5f * w / Mathf.Max(Mathf.Abs(fall.x), Mathf.Abs(fall.z));+ float texel = 2f * ShadowFit.Distance(cam, UnityEngine.Rendering.Universal.UniversalRenderPipeline.asset!.cascadeBorder) / 2048f;+ var offsets = new List<float>();+ for (int i = 1; i <= 20; i++) offsets.Add(i);+ for (int i = 1; i <= 40; i++) offsets.Add(20f + texel * i / 20f);+ var pts = new List<Vector3>();+ foreach (var o in offsets) { var p = at + fall * (toWall + o); p.y = g.Y(p.x, p.z); pts.Add(p); }+ var deep = at + fall * (toWall + h * 1.2f); deep.y = g.Y(deep.x, deep.z); pts.Add(deep);+ // Two roof samples (the sunlit face the camera sees from this pose; the west wall is edge-on to it): centre and+ // near the sunward edge, where self-shadow acne starts first.+ var roof = new Vector3(at.x, y + h, at.z); pts.Add(roof);+ var roofEdge = new Vector3(at.x, y + h, at.z) - fall * (toWall * 0.85f); pts.Add(roofEdge);+ int deepI = offsets.Count, roofI = deepI + 1, wallI = deepI + 2; // wallI: the roof's sunward edge+ var px = new Vector2[pts.Count];+ float Gap(Material m, out float deepDark, out float wallDark, out float roofDark)+ {+ mr.sharedMaterial = m;+ VisualToggles.Set("shadows", true); var on = RenderSample.Render(cam, 1920, 1080, pts.ToArray(), px);+ VisualToggles.Set("shadows", false); var off = RenderSample.Render(cam, 1920, 1080, pts.ToArray(), px);+ VisualToggles.Set("shadows", true);+ float Dark(int i) => 1f - RenderSample.Luma(on.At((int)px[i].x, (int)px[i].y)) / Mathf.Max(1e-4f, RenderSample.Luma(off.At((int)px[i].x, (int)px[i].y)));+ deepDark = Dark(deepI); wallDark = Dark(wallI); roofDark = Dark(roofI);+ for (int i = 0; i < offsets.Count; i++) if (Dark(i) > 0.6f * deepDark) return offsets[i];+ return float.PositiveInfinity;+ }+ float kitGap = Gap(kit, out var kitDeep, out var kitWall, out var kitRoof);+ float markerGap = Gap(marker, out var markerDeep, out _, out _);+ float metresPerPixel = 2f * distance * Mathf.Tan(CameraRig.Fov * 0.5f * Mathf.Deg2Rad) / 1080f;+ TestContext.WriteLine($"tier {QualitySettings.names[level]}, {distance / 1000f:0} km, {w:0} m box, shadow texel {texel:0} m, pixel {metresPerPixel:0.0} m: " ++ $"first shadowed sample {kitGap:0} m from the wall with Kit.mat (sun's bias), {markerGap:0} m with the marker material; deep shadow darker by " ++ $"{kitDeep:P0} / {markerDeep:P0}; with shadows on the roof darkens {kitRoof:P1} at its centre and {kitWall:P1} by its sunward edge");+ Assert.Greater(kitDeep, 0.15f, "the box casts a shadow at all");+ Assert.LessOrEqual(kitGap, metresPerPixel + 1f, "no lit strip between the wall and its shadow");+ Assert.Less(kitRoof, 0.05f, "acne on the roof"); Assert.Less(kitWall, 0.05f, "acne by the roof's sunward edge");+ }+ finally { Object.DestroyImmediate(go); Object.DestroyImmediate(mesh); }+ }+}diff --git a/unity/Assets/Tests/EditMode/KitTests.cs.meta b/unity/Assets/Tests/EditMode/KitTests.cs.metanew file mode 100644index 000000000..59d86d600--- /dev/null+++ b/unity/Assets/Tests/EditMode/KitTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: fa7e6bd6be0a746d4b7791e0515cf5e9\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/SeaTests.cs b/unity/Assets/Tests/EditMode/SeaTests.csindex 392b5c581..107f56687 100644--- a/unity/Assets/Tests/EditMode/SeaTests.cs+++ b/unity/Assets/Tests/EditMode/SeaTests.cs@@ -1,6 +1,7 @@#nullable enableusing System.Collections;using System.IO;+using System.Linq;using NUnit.Framework;using Statecraft.Game.Map;using UnityEditor;@@ -16,13 +17,16 @@ public class SeaTests[TearDown]public void Reset() { MapShaderGlobals.PinWaterTime(null); RenderSample.TiltShift(true); EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); VisualToggles.Clear(); }- static MapScene OpenMap()+ static MapScene OpenMap(bool reopen = true){- EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ if (reopen) EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);var map = Object.FindFirstObjectByType<MapScene>(); map.Build();// Every render here measures colour or local detail: Track A's tilt-shift blurs the top and bottom bands (task-3// carry m6, applied at the merge point), so it is off; the TearDown turns it back on.RenderSample.TiltShift(false);+ // The water and shore themselves: the settlement kits' shore palms, harbour and town blocks stand on and in front of+ // the coast samples, so they are off for every sea render (the map's teardown removes the switches).+ foreach (var n in new[] { "kits", "trees" }) if (VisualToggles.Names.Contains(n)) VisualToggles.Set(n, false);return map;}@@ -133,13 +137,76 @@ public class SeaTestsAssert.Less(deepSat, 0.7f, "the open sea is muted");}+ /// <summary>Review N3: with the settlement kits on, the beach along Tel Aviv's shore (inside its paved footprint, with its+ /// shore palms) still reads as pale sand. One beach sample per coast-texture row from 32.06 to 32.12 N (Tel Aviv's own+ /// beach: Jaffa's old town and harbour meet the sea south of it, and the Yarkon's mouth lies north of it), 200 m inland of+ /// the shore; a palm crown or a block stands in front of some of them from this pose, so at least+ /// <see cref="SandShareBesideTelAviv"/> of them must be sand, and those must be lighter than open coastal plain outside+ /// every town's footprint (5 km inland at 32.22 N, north of Herzliya) by <see cref="BeachOverPlain"/>.</summary>+ [UnityTest]+ public IEnumerator TheBeachBesideTelAvivStaysSandWithTheKitsOn()+ {+ var map = OpenMap();+ yield return null;+ foreach (var n in new[] { "kits", "trees" }) VisualToggles.Set(n, true);+ var coast = new Texture2D(2, 2);+ coast.LoadImage(File.ReadAllBytes(MapTexturePaths.Coast));+ int RowOf(float lat) => Mathf.FloorToInt((lat - 29.45f) / (33.35f - 29.45f) * coast.height);+ int Shore(int row)+ {+ int c = Mathf.FloorToInt((34.95f - 34.2f) / (35.9f - 34.2f) * coast.width);+ while (c > 0 && coast.GetPixel(c, row).r >= 0.5f) c--;+ return c;+ }+ Vector3 At(int c, int r)+ {+ double lon = 34.2 + (c + 0.5) / 2048.0 * (35.9 - 34.2), lat = 29.45 + (r + 0.5) / 2048.0 * (33.35 - 29.45);+ var w = map.Frame.ToWorld(lon, lat, 0); w.y = map.Terrain.SampleHeight(w); return w;+ }+ var beaches = new System.Collections.Generic.List<Vector3>();+ for (int r = RowOf(32.06f); r <= RowOf(32.12f); r++) beaches.Add(At(Shore(r) + 3, r));+ int rowN = RowOf(32.22f); var plain = At(Shore(rowN) + 60, rowN);+ Object.DestroyImmediate(coast);+ bool Paved(Vector3 p) => map.Settlements.Any(t =>+ {+ var c = map.Frame.ToWorld(t.Lon, t.Lat, 0);+ return new Vector2(p.x - c.x, p.z - c.z).magnitude < 1.1f * Statecraft.Game.Map.Kits.SettlementKits.FootprintRadiusM(t, map.Hexes.hex_size_km * 1000f);+ });+ Assert.IsTrue(beaches.All(Paved), "the beach samples lie inside a town's footprint");+ Assert.IsFalse(Paved(plain), "the plain reference lies outside every footprint");+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();+ rig.LookAt = beaches[beaches.Count / 2]; rig.Distance = 30000f; rig.Yaw = 0; rig.TopInset = 0; rig.Apply();+ var px = new Vector2[beaches.Count];+ var shot = RenderSample.Render(cam, 1920, 1080, beaches.ToArray(), px);+ var sand = new System.Collections.Generic.List<Color>();+ for (int i = 0; i < beaches.Count; i++)+ {+ var c = shot.Mean((int)px[i].x, (int)px[i].y, 1);+ if (Luma(c) > 0.72f && c.b / c.g > 0.62f) sand.Add(c);+ }+ var one = new Vector2[1];+ rig.LookAt = plain; rig.Apply();+ Color l = RenderSample.Render(cam, 960, 540, new[] { plain }, one).Mean((int)one[0].x, (int)one[0].y, 2);+ float share = sand.Count / (float)beaches.Count, sandLuma = sand.Count > 0 ? sand.Average(c => Luma(c)) : 0f;+ TestContext.WriteLine($"{sand.Count} of {beaches.Count} beach samples along Tel Aviv read as sand ({share:P0}), mean luma {sandLuma:0.000}; " ++ $"plain north of Herzliya {l} (luma {Luma(l):0.000})");+ Assert.GreaterOrEqual(share, SandShareBesideTelAviv, "the kits bury Tel Aviv's beach");+ Assert.Greater(sandLuma, Luma(l) + BeachOverPlain, "the beach is lighter than the open plain");+ }++ /// <summary>Floors for TheBeachBesideTelAvivStaysSandWithTheKitsOn.</summary>+ const float SandShareBesideTelAviv = 0.75f, BeachOverPlain = 0.10f;+/// <summary>promo-sea: a sand strip lines the Mediterranean shore (promo 03's beach). Rendered on the same row west of/// Tel Aviv: about 200 m inland of the shore the ground is pale sand, lighter than the plain 5 km inland and less- /// yellow-green than the bare coastal edge it covers.</summary>+ /// yellow-green than the bare coastal edge it covers. The map is built without the settlement kits, which pave the ground+ /// of a town's footprint (Tel Aviv's covers that plain sample).</summary>[UnityTest]public IEnumerator ASandStripLinesTheMediterraneanShore(){- var map = OpenMap();+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ Object.FindFirstObjectByType<MapScene>().ConfigureKits(null, null); // the scene is not saved+ var map = OpenMap(reopen: false);yield return null;var coast = new Texture2D(2, 2);coast.LoadImage(File.ReadAllBytes(MapTexturePaths.Coast)); // readable copy; row 0 = south