Skip to content

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

Map: region border bands, the drawing layer (promo look, region borders) (#206)

Eyal Golanf7ce6334c5da
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2bb86d9f4..6aa1aa40f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
- Hebrew UI translation data with key and format-token checks; not yet enabled in the game (#12).
- A local multi-size favicon for the WebGL page.
- A portrait of Zalman Shazar: a crop of Yoichi Okamoto's 1966 White House photo (US public domain, PD-USGov; #6).
+- Region borders in the promo look (promo-borders): two-tone outlines along hex edges (a blue band with a white inner
+ stripe, a red-orange band with a cream one), drawn inside each region by the terrain shader from one texel per hex, with
+ a "borders" visual toggle. Visual only. The game ships no region data yet (no invented boundaries: the sourced 1945-48
+ sub-districts, 1949 armistice lines and fronts are a research item), so nothing is drawn in play.
- Hebrew names and sourced birth and death dates for all 29 people (issue #1).
- Successors for offices left by deaths in 1952: Ben-Gurion takes Transportation after Pinkas (14 August 1952) and
Yitzhak Ben-Zvi becomes President on 16 December 1952 after Weizmann; the presidency is vacant in between, while
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 2301410c9..7530b4f09 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -557,6 +557,7 @@ The images live in the owner's local `captures/visual/` folder (git-ignored); ow
| 8 | t08-grid | captures/visual/t08-grid/*-compare*.png, hero06judea.png, hero06negev.png, editor/*-compare*.png | (owner) |
| 8 (fix 1) | t08-grid-r1 | captures/visual/t08-grid-r1/*-compare*.png, hero06judea.png, hero06negev.png, editor/*-compare*.png | (owner) |
| 9 | t09-labels | captures/visual/t09-labels/*-compare*.png | (owner) |
+| borders | promo-borders-before, promo-borders-noproof, promo-borders-r2 | captures/visual/promo-borders-before/*-compare*.png (main 807e300), captures/visual/promo-borders-noproof/*-compare*.png (the branch as played: no data, no border), captures/visual/promo-borders-r2/editor/*-compare*.png (the synthetic `--borderproof` checker, labelled on screen; editor renders only), all at d1973db | (owner) Note: no real region data yet, so play shows no border (see "Region borders"). The earlier promo-borders-proof / -after rows ran on uncommitted work over 807e300 (old ring pattern). |
| merge | t-merge | captures/visual/t-merge/*-compare*.png, hero06judea.png, hero06negev.png, editor/*-compare*.png (before the grade re-tune: t-merge-pre, t-merge-r1) | (owner) Note: the land is one dry-grass gold with no fields, orchards or cities yet; that gap is content (art track), not the grade. |
| merge (fix 1) | t-merge-r3 | captures/visual/t-merge-r3/*-compare*.png (t-merge-r2 = with the rejected border colour) | (owner) Note: olive coastal plain and valleys; the selected hex is now the promo's ivory ring colour, gold stays the UI chrome's. |
| 10 | t10-tiers | captures/visual/t10-tiers/*-compare*.png, hero06judea.png, hero06negev.png, editor/*-compare*.png; weak GPU: captures/visual/t10-swiftshader | (owner) Note: render scale 1.0 on the web (sharper lines and pills); bloom, SSAO and the depth/opaque copies off; the colour is unchanged within 0.001. |
@@ -966,6 +967,145 @@ Final macOS player (SSAO, copies and bloom off):
macOS `-golden`, both builds: `GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07`,
`GOLDEN OK 1952 73590e324f19e9959a455a4da79e93d7089dfcf283c13aac02af6b0a624b9767`.
+## Region borders (promo-borders, art track gap 5)
+Promo 03 outlines regions with coloured bands along hex edges, over the faint hex lattice; promo 02 draws none (its era has
+no such layer), so diorama02 is checked only for staying thin. Measured on promo/final/03-gameplay-1936.png (2752 px wide,
+row and column profiles across the lines):
+
+| Promo 03 band | From the region's edge inwards | Widths (2752 px, mid-depth) | sRGB |
+|---|---|---|---|
+| Blue | blue stripe, white stripe, a grey-blue wash fading inwards | 6 + 6 px, wash about 10 px | 125,140,182 / 251,251,248 |
+| Red-orange | red-orange stripe, cream stripe, a faint warm wash | 4 + 3 px, wash about 8 px | 176,93,61 / 246,188,124 |
+
+Each band lies inside its region, as Civ draws territory, so two outlined regions meet as a double band (blue+white next
+to red+cream: promo 03 near Tel Aviv). The bands are world-space: they widen towards the camera.
+
+**What is drawn.** `MapBorders` (C#) bakes one texel per hex (`RegionHexes`, RGBA8 linear, point-sampled, 47 x 58: r + 256 g
+the region id, b the style) and sets the globals; `StatecraftBorders.hlsl`'s `ScBorderApply`, called last in the terrain
+function, draws the band along each edge whose neighbour is in another region. A pixel farther from its hex's edges than
+the widest band plus wash can reach fetches nothing (exact: a segment is never nearer than its line); one nearer fetches its
+own hex and only the neighbours within reach (one, or two near a corner). The first version fetched all seven texels on
+every land pixel and cost 3.3 ms at gameplay03 (`visual=all` 14.97 against `-borders` 11.64, a loaded machine): over the
+2.5 ms budget. The distance is to the edge segment (corners rounded, so bands join without notches), in pixels
+across the edge (Task 8's anisotropic filter), box-filtered. Stripes and wash are unlit (they replace BaseColor and go out
+as Emission), so they read the same in sun and shadow, as the promo's glowing lines do. A hex in no region (id 0) gets no
+band and stops its neighbours' bands: the coast is never outlined. Bands stay on land: where a boundary between two coastal
+land hexes crosses the shore, the band fades with the water mask (`ScWater`) instead of running up to 4 km out to the hex
+edge (review M7; `BandsStayOffTheWater`). Styles (`MapBorders.Primary` / `Secondary`): band 230 m / 200 m (colour share
+0.5 / 0.6), wash 0.9 / 1.0 of the band at 0.40 / 0.18. The band is at least 2 px wide unless that would make band plus wash
+wider than half a hex's inradius, which wins: below about 8 px of inradius on screen (the far overview) it goes under 2 px
+(review M2). A style with no wash is safe (the wash ramp's width is floored, review M3). The light stripes are set above
+white (sRGB 1.08 / 1.05 red) so the graded result reaches the promo's. Toggle `borders`. `_ScBorders.z` (test seam
+`MapBorders.NoEarlyOut`) turns the early-out off; `TheEarlyOutIsExact` renders both promo poses both ways and finds 0
+pixels apart (review M6). Visual only: no sim state read or written, goldens unchanged.
+
+**Data: none yet, so the game draws no border.** Owner ruling (2026-10-11): no invented political boundaries; borders come
+from real data only (the 1945-48 districts and sub-districts, the 1949 armistice lines when dated, fronts). The repository
+has none of these: `hexes.json` holds elevation, land and biome; `settlements_1948.yaml` points; the armistice events
+(`content/events/armistice_*.yaml`) dates and text but no geometry; the sim has no fronts (war mode, #21 / M4 N4). So
+`MapBorders.Apply` runs on every build with no layer. Against main (review I1, branch merged with main 632edbd, both editor
+renders from the same Library):
+- `MapCapture.SurfFrames` (gameplay03, web tier, the water's clock pinned, 60 frames): **0 of 124,416,000 pixels differ**.
+ The renders are kept in `captures/visual/promo-borders-i1/` (`borders-maincheck/` main, `promo-borders/` the branch,
+ `main2/` main's second `Promo` run).
+- `MapCapture.Promo` (both poses, both tiers; the water's clock is not pinned there): main against the branch differs in
+ 1,334 / 15,089 / 116,761 / 19,904 pixels (Mobile-diorama02, Mobile-gameplay03, PC-diorama02, PC-gameplay03; largest step
+ 26/255 in PC-diorama02, 2/255 elsewhere), and main against a second main run in 513 / 1,737 / 116,542 / 10,498 pixels
+ with the same largest steps: the water's clock, not the branch.
+- Inside the branch, `WithoutRegionDataTheToggleIsANoOp` only shows the toggle does nothing without data.
+- The cost of the no-data path (the hoisted `ddx`/`ddy` and one uniform branch) against main's build is not measured:
+ the machine ran at load 22 with 13 Unity processes from other tracks, so a cross-build difference would be noise. The
+ in-build `all` against `-borders` difference (-0.02 / +0.05 ms) is the noise floor, not that cost.
+
+`BorderProof` is a synthetic pattern for tests and captures only (review I3): a checker of 4 x 4 axial hex blocks
+(parallelograms in a regular lattice over the whole map, unrelated to any town or line), alternately Primary and
+Secondary, land only. While it is drawn the camera carries the label "SYNTHETIC TEST PATTERN — not real boundaries", so
+every capture labels itself: a legacy `TextMesh` (bold, white with a dark drop copy, 3.3% of the frame high) that renders
+under URP, placed before each render from the camera's aspect, 35% down the frame inside the tilt-shift's sharp band
+(legible in `captures/visual/promo-borders-r2/editor/*-gameplay03.png` and `*-diorama02.png`).
+`TheProofLabelRendersAtTheTopLeft` renders it shown and hidden at 1920x1080 and 1440x1080: about 12,800 pixels change in
+the upper left, none elsewhere, and its left end is on screen; `TheProofIsLabelledOnScreenWhileDrawn` checks it goes with
+the toggle and the layer. Only the editor and development builds honour
+its flag (`Application.isEditor || Debug.isDebugBuild`; `AReleaseBuildIgnoresTheProofFlag`): `-borderproof` in the editor's
+promo renders and tests, `tools/art_checkpoint.sh --borderproof` (editor renders; the release WebGL shots ignore it, so the
+WebGL frame profile can no longer draw it), and `?borderproof` / `-borderproof` in a development player.
+
+**Research item: region data (to source, then the owner's sensitivity review).**
+- *What:* per-hex region labels for (a) the sub-districts of Mandatory Palestine at the end of the Mandate (six districts:
+ Galilee, Haifa, Samaria, Jerusalem, Lydda, Gaza; sixteen sub-districts: Acre, Beisan, Nazareth, Safad, Tiberias, Haifa,
+ Jenin, Nablus, Tulkarm, Hebron, Jerusalem, Ramallah, Jaffa, Ramle, Beersheba, Gaza), dated by the Gazette changes of
+ 1942, 1945 and 1947; (b) the 1949 armistice lines, each dated by its agreement (Egypt 24 Feb, Lebanon 23 Mar, Jordan
+ 3 Apr, Syria 20 Jul 1949; the events already in content/); (c) fronts, from war mode's data once #21 defines it.
+- *Sources to check:* Palestine Gazette, Supplement No. 2, No. 1163 (15 Jan 1942) pp. 119-132, No. 1415 (7 Jun 1945)
+ pp. 621-629, No. 1552 (30 Jan 1947) pp. 125-133 (cited by https://en.wikipedia.org/wiki/Districts_of_Mandatory_Palestine,
+ checked 2026-10-11); the Survey of Palestine 1:100,000 sheets (1944-48), which draw district and sub-district boundaries
+ (Princeton Digital Maps, https://maps.princeton.edu/catalog/princeton-dc5999ng80p); UN map "Palestine: Land ownership by
+ sub-districts" (1945 data), https://digitallibrary.un.org/record/498482; the armistice agreements themselves (UN S/1264/Corr.1,
+ S/1296, S/1302/Rev.1, S/1353; per https://en.wikipedia.org/wiki/1949_Armistice_Agreements, checked 2026-10-11), whose
+ lines are given as Palestine-grid map references; whether maps were annexed is to verify. No open, licensed vector file of the sub-districts was found (search 2026-10-11): AUB's
+ "Palestine Population Sources" (2018, https://scholarworks.aub.edu.lb/handle/10938/22154) covers four sub-districts and
+ states no licence; Palestine Open Maps states none either. So the boundaries must be digitised from a primary source
+ (the Gazette schedules or the Survey sheets), with the method and its error recorded; their copyright status (Government
+ of Palestine publications of the 1940s) is a licence question for the owner (docs/oss/DECISIONS.md) before any import.
+- *Shape:* sourced, dated geometry in content (the chapters design's `lines.yaml`, §448, or a polygon file beside it), and a
+ tool that labels each hex by its centre (as `tools/settlement_hexes.py` does for settlements) into the per-hex layer the
+ renderer takes (`RegionLayer`). Every entry is submitted `fact-checked`; the owner sets `sensitivity-reviewed` before a
+ shareable build (chapters design §13).
+- *Limits of the renderer's data seam (review M8), for the data work to plan around:*
+ 1. Two drawn styles (Primary, Secondary) plus None. The 1949 lines set Israel against four neighbours; with two styles
+ the four share the red-orange band (the texel's style byte allows 255, but each new style needs colours that stay
+ apart for colour-blind players, so it is a design task, not a constant). Districts may want a neutral third style.
+ 2. One layer at a time: districts and armistice lines cannot show together.
+ 3. Styles are per region, not per edge: an edge's look comes from the regions on its two sides.
+ 4. Hex snapping moves a line by up to half a hex (see the owner decision below).
+ Follow-up: more styles or per-edge styles when the data and the owner's ruling on snapping need them.
+- *Owner decision needed:* the promo snaps borders to hex edges, but spec §3 (map state) says hex boundaries carry no
+ political meaning and the chapters design draws lines as true polylines. Snapping a line to hex edges moves it by up to
+ half a hex (about 4 km). Options: (1) hex-snapped regions (this renderer, the promo look); (2) true polylines (a separate
+ overlay, not the promo look); (3) both, hex-snapped at the gameplay zoom and true lines in a map mode.
+
+**Measured.**
+- Rendered tests (EditMode, `BorderTests`, 1920x1080 at gameplay03's distance and yaw, tilt-shift off, on the proof's
+ primary-secondary edge (3, 11)-(4, 11) on the flat coastal plain, where the promo's lines are measured): along 9 points
+ of the edge a blue stripe (graded sRGB 0.48, 0.58, 0.79; promo 0.49, 0.55, 0.71), a white one (0.93, 0.91, 0.89; promo
+ 0.98), a red-orange one (0.74, 0.37, 0.18; promo 0.69, 0.36, 0.24), a cream one (0.92, 0.79, 0.53; promo 0.96, 0.74,
+ 0.49). Band widths (median, stripes classified by colour so the wash is not counted): primary **8 px**, secondary
+ **6 px**, against the promo's about 8 and 5 (bounds 6-11 and 3.5-8). Nothing changes 1.2 km or more from the edge; the
+ middle of a coast edge is unchanged (0/134 pixels); no clearly-water pixel moves at gameplay03 (0 of 631,101); diorama02
+ 3.2% of pixels changed (thin, label included); renders repeat exactly.
+- Colour-blind (`GradeTests.ColourBlindPlayersTellTheBorderStylesApart`, Machado 2009 severity 1, deuteranopia and
+ protanopia, five points on a coastal-plain edge and five on a Negev desert edge): blue against red-orange 69-80;
+ primary colour-land 54-77, light-land 38-47, colour-light 44-50; secondary colour-land 9-31, light-land 3-49,
+ colour-light 30-35. Asserted per point: styles >= 15; each band's stronger stripe >= 15 from the land; its two stripes
+ >= 20 apart; its weaker stripe >= 5 unless the stronger one is >= 25. Not both stripes >= 15 (review M5), because a
+ light stripe is meant to be light: on pale Negev sand the promo's cream stripe melts into the ground for normal vision
+ too (3.2-6.1, logged), and the band reads by its red-orange stripe there (19-31). The red-orange is a little more
+ saturated than the promo's (set 0.75, 0.31, 0.13) so it keeps that contrast on olive and on dry grass.
+- Frame cost (WebGL, 1920x1080, headless). Measured on the first, wider version (300 m / 230 m, before the water fade),
+ when the release WebGL player still honoured `?borderproof`; the machine was loaded (`visual=none` 10 ms against
+ Task 8's 2.4 ms `all`), so read the differences:
+ - Seven fetches on every land pixel: gameplay03 `all` 14.97 - `-borders` 11.64 = 3.3 ms, over the 2.5 ms budget; hence
+ the early-out.
+ - With the early-out, the proof drawn: gameplay03 13.33 (spread 0.31) - 12.42 (0.22) = **0.91 ms**, within budget.
+ diorama02 16.93 (1.06) - 15.82 (0.73) = 1.11 ms is within one spread: **not resolved**; re-measure on an idle machine
+ with real data (promo-borderdata), in a development build or a release build with a data layer.
+ - Without data: see I1 above (not measurable against main on this machine).
+- WebGL build: no `Shader error`, no "not supported" line (GLES3: `LOAD_TEXTURE2D` is `texelFetch`, static const arrays,
+ no new derivative use beyond Task 8's `ddx`/`ddy` in uniform control flow); both goldens OK (Hash1952 62f8ec61 since
+ #137), and `golden&smoke=5` passes on the build of d1973db.
+- Texture units with promo-land merged (review M10): the terrain fragment's own textures are 6 (Bake, Coast,
+ Ao and Land through the graph, `_ScBiomeTex`, `_ScRegionTex`; promo-land dropped Tracks), plus URP's (main-light shadow
+ map, reflection probe and the like): about 10-11 by the source, under WebGL2's guaranteed 16. Built, not only counted:
+ a local test merge of d1973db with origin/promo-land 7db1a3a (not pushed) built for WebGL with 0 errors and no
+ `Shader error` (76.0 MB), and booted in Chrome for Testing with `GOLDEN OK 1950` and `GOLDEN OK 1952` and no "not
+ supported" or `Shader` line (web_check's fail pattern).
+- Checkpoints (art-log rows): `promo-borders-before` (main 807e300); `promo-borders-proof` and `promo-borders-after` were run
+ on 807e300's tree plus the then-uncommitted branch, so the art log records 807e300 for them (now marked `807e300+wip`
+ there); the rings in them are the old pattern. The review rounds' checkpoints are on d1973db (art-log rows
+ `promo-borders-noproof` and `promo-borders-r2-borderproof`): `promo-borders-noproof` (no proof: the branch as played,
+ goldens OK) and `promo-borders-r2` (`--borderproof`: the editor renders show the labelled checker; its WebGL shots, a
+ release build, ignore the flag and match `-noproof`'s numbers exactly).
+
## promo-sea: water, surf and beach (art track, open item 3, issue #38)
`ScWaterShade` (`StatecraftMap.hlsl`) is reworked on both sides of the edge, and a new `ScShore` paints the land's shore.
Review round 1 (staff review I1-I2, M1-M8) is folded in; the values below are the shipped ones.
diff --git a/tools/art_checkpoint.sh b/tools/art_checkpoint.sh
index aa90b1f0a..6b1176337 100755
--- a/tools/art_checkpoint.sh
+++ b/tools/art_checkpoint.sh
@@ -5,19 +5,22 @@
# player run and fails if a screenshot is missing or blank. The art log lives in the main checkout's captures/ so every
# worktree appends to one history. --units adds the unit art slice (docs/units.md) to both the WebGL shots (&units) and the
# editor renders (-units), and its art-log rows are named <checkpoint-name>-units, so they cannot be mistaken for plain
-# checkpoints; without it the captures stay comparable across tracks. Usage:
-# tools/art_checkpoint.sh [--no-build] [--units] <checkpoint-name>
+# checkpoints; without it the captures stay comparable across tracks. --borderproof does the same for the region borders'
+# synthetic, labelled proof pattern (rows named <checkpoint-name>-borderproof; docs/visual-v1.md, "Region borders"): only
+# the editor renders (-borderproof) show it, since a release WebGL build ignores &borderproof. Usage:
+# tools/art_checkpoint.sh [--no-build] [--units] [--borderproof] <checkpoint-name>
set -euo pipefail
-build=1; units_query=""; units_arg=()
+build=1; units_query=""; units_arg=(); proof_query=""; proof_arg=()
while [[ "${1:-}" == --* ]]; do
case "$1" in
--no-build) build=0 ;;
--units) units_query="&units"; units_arg=(-units) ;;
+ --borderproof) proof_query="&borderproof"; proof_arg=(-borderproof) ;;
*) echo "art_checkpoint: unknown option $1" >&2; exit 2 ;;
esac
shift
done
-name="${1:?usage: tools/art_checkpoint.sh [--no-build] [--units] <checkpoint-name>}"
+name="${1:?usage: tools/art_checkpoint.sh [--no-build] [--units] [--borderproof] <checkpoint-name>}"
root="$(git rev-parse --show-toplevel)"
cd "$root"
main_root="$(cd "$(git rev-parse --path-format=absolute --git-common-dir)/.." && pwd)"
@@ -41,7 +44,7 @@ fi
[[ -f unity/Builds/Web-disabled/index.html ]] || { echo "art_checkpoint: no build at unity/Builds/Web-disabled (run without --no-build)" >&2; exit 2; }
out="captures/visual/$name"
rm -rf "$out"; mkdir -p "$out"
-uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&shot${units_query}" --expect "GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07" --expect "GOLDEN OK 1952 62f8ec61a14acff4eab503381994a7c94d7a2f786dcfde5c4c19439ac8b4c5e8" --expect "SHOT done" --shots "$out" --stall 180 \
+uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&shot${units_query}${proof_query}" --expect "GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07" --expect "GOLDEN OK 1952 62f8ec61a14acff4eab503381994a7c94d7a2f786dcfde5c4c19439ac8b4c5e8" --expect "SHOT done" --shots "$out" --stall 180 \
--fail 'GOLDEN FAIL|SMOKE FAIL|BOOT FAIL|Statecraft/.*(not supported|Unsupported)|(not supported|Unsupported).*Statecraft/'
# The poses come from PromoPose.All's source, so a new pose is checked without editing this script (review M3).
poses=$(grep -o 'new PromoPose("[A-Za-z0-9_]*"' unity/Assets/Scripts/Map/PromoPose.cs | cut -d'"' -f2)
@@ -49,7 +52,7 @@ poses=$(grep -o 'new PromoPose("[A-Za-z0-9_]*"' unity/Assets/Scripts/Map/PromoPo
for pose in $poses; do
[[ -s "$out/$pose.png" ]] || { echo "art_checkpoint: $out/$pose.png is missing" >&2; exit 1; }
done
-shared "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget OSXUniversal -executeMethod MapCapture.Promo -captureDir "$root/$out/editor" ${units_arg[@]+"${units_arg[@]}"} -logFile "$root/unity-capture-promo.log"
+shared "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget OSXUniversal -executeMethod MapCapture.Promo -captureDir "$root/$out/editor" ${units_arg[@]+"${units_arg[@]}"} ${proof_arg[@]+"${proof_arg[@]}"} -logFile "$root/unity-capture-promo.log"
git checkout -- unity/ProjectSettings/QualitySettings.asset # SetQualityLevel may have written m_CurrentQuality (no unstaged edits: checked above)
-uv run tools/art_compare.py "$out" "$name${units_query:+-units}" --log "$main_root/captures/visual/art-log.tsv"
+uv run tools/art_compare.py "$out" "$name${units_query:+-units}${proof_query:+-borderproof}" --log "$main_root/captures/visual/art-log.tsv"
echo "ART CHECKPOINT $name: $(ls "$out"/*-compare*.png "$out"/editor/*-compare*.png | tr '\n' ' ')"
diff --git a/unity/Assets/Editor/MapCapture.cs b/unity/Assets/Editor/MapCapture.cs
index 709627e5e..6d9dc0041 100644
--- a/unity/Assets/Editor/MapCapture.cs
+++ b/unity/Assets/Editor/MapCapture.cs
@@ -170,6 +170,8 @@ public static class MapCapture
var map = OpenAndBuild();
// The unit art slice only when asked (-units, from tools/art_checkpoint.sh --units), as ?shot&units shows it.
if (System.Array.IndexOf(args, "-units") >= 0) Statecraft.Game.Map.Units.UnitShowcase.Spawn(map, still: true);
+ // The border renderer's synthetic proof only when asked (-borderproof, from tools/art_checkpoint.sh --borderproof).
+ if (System.Array.IndexOf(args, "-" + BorderProof.Flag) >= 0) BorderProof.Show(map);
var rig = Camera.main.GetComponent<CameraRig>();
int saved = QualitySettings.GetQualityLevel();
try
diff --git a/unity/Assets/Scripts/Map/MapBorders.cs b/unity/Assets/Scripts/Map/MapBorders.cs
new file mode 100644
index 000000000..8a2d92279
--- /dev/null
+++ b/unity/Assets/Scripts/Map/MapBorders.cs
@@ -0,0 +1,300 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Game.Boot;
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>How a region is outlined: the promo's blue band with a white inner stripe (Primary), its red-orange band with
+ /// a cream inner stripe (Secondary), or not at all (None: a region that only stops its neighbours' bands from running on,
+ /// e.g. the land past a border that is not drawn from its side).</summary>
+ public enum BorderStyle : byte { None = 0, Primary = 1, Secondary = 2 }
+
+ /// <summary>Which region each hex belongs to, and how each region is outlined: what the border renderer draws. A hex not
+ /// listed belongs to no region, and no band is drawn against it (the coast, the edge of the data). Region ids run from 1
+ /// to <see cref="MaxId"/>. The renderer draws only what a layer says, so a layer must come from real, sourced data (owner
+ /// ruling, 2026-10-11: no invented political boundaries): the 1945-48 districts and sub-districts, the 1949 armistice
+ /// lines when dated, fronts. None is in the repository yet (docs/visual-v1.md, "Region borders"), so the game draws no
+ /// border; <see cref="BorderProof"/> is a synthetic pattern for tests and captures only.</summary>
+ public sealed class RegionLayer
+ {
+ public const int MaxId = 65535; // two texel bytes
+
+ public readonly string Name;
+ /// <summary>A label shown on screen while the layer is drawn (null: none). The synthetic proof sets one, so no
+ /// screenshot of it can pass for real boundaries.</summary>
+ public readonly string? Banner;
+ readonly Dictionary<(int q, int r), int> regionOf;
+ readonly Dictionary<int, BorderStyle> styleOf;
+
+ /// <summary>Throws ArgumentException naming the layer for an id outside 1..MaxId, a hex's region with no style, or an
+ /// undefined style.</summary>
+ public RegionLayer(string name, IReadOnlyDictionary<(int q, int r), int> hexRegions, IReadOnlyDictionary<int, BorderStyle> styles,
+ string? banner = null)
+ {
+ Banner = banner;
+ Name = string.IsNullOrWhiteSpace(name) ? throw new ArgumentException("a region layer needs a name", nameof(name)) : name;
+ if (hexRegions == null) throw new ArgumentNullException(nameof(hexRegions));
+ if (styles == null) throw new ArgumentNullException(nameof(styles));
+ foreach (var kv in styles)
+ {
+ if (kv.Key < 1 || kv.Key > MaxId) throw new ArgumentException($"{name}: region id {kv.Key} outside 1..{MaxId}");
+ if (!Enum.IsDefined(typeof(BorderStyle), kv.Value)) throw new ArgumentException($"{name}: region {kv.Key} has an unknown style {(int)kv.Value}");
+ }
+ foreach (var kv in hexRegions)
+ if (!styles.ContainsKey(kv.Value)) throw new ArgumentException($"{name}: hex ({kv.Key.q}, {kv.Key.r}) is in region {kv.Value}, which has no style");
+ regionOf = new Dictionary<(int q, int r), int>(hexRegions);
+ styleOf = new Dictionary<int, BorderStyle>(styles);
+ }
+
+ /// <summary>The hex's region, or 0 (none).</summary>
+ public int RegionOf(int q, int r) => regionOf.TryGetValue((q, r), out var id) ? id : 0;
+ public BorderStyle StyleOf(int id) => styleOf.TryGetValue(id, out var s) ? s : BorderStyle.None;
+ public IEnumerable<(int q, int r)> Hexes => regionOf.Keys;
+ public int Count => regionOf.Count;
+ }
+
+ /// <summary>The region borders (promo-borders): the promo 03 look of coloured, two-tone bands along hex edges, drawn by
+ /// the terrain shader (StatecraftBorders.hlsl) from one texel per hex. <see cref="Apply"/> runs on every map build
+ /// (MapBuilder.Build, after MapShaderGlobals.Apply): it allocates the hex texture, draws nothing, and registers the "borders" toggle;
+ /// <see cref="Use"/> gives the built map a layer. Visual only: it reads no sim state and changes none.</summary>
+ public static class MapBorders
+ {
+ public const string ToggleName = "borders";
+
+ static readonly int RegionTex = Shader.PropertyToID("_ScRegionTex"), RegionInfo = Shader.PropertyToID("_ScRegionInfo"),
+ Borders = Shader.PropertyToID("_ScBorders"),
+ Colour1 = Shader.PropertyToID("_ScBorderColour1"), Light1 = Shader.PropertyToID("_ScBorderLight1"), Shape1 = Shader.PropertyToID("_ScBorderShape1"),
+ Colour2 = Shader.PropertyToID("_ScBorderColour2"), Light2 = Shader.PropertyToID("_ScBorderLight2"), Shape2 = Shader.PropertyToID("_ScBorderShape2");
+
+ /// <summary>One style's look. Colours are sRGB (above 1: brighter than white before the grade), measured on
+ /// promo/final/03-gameplay-1936.png (2752 px wide) and set so the graded game matches them (docs/visual-v1.md, "Region borders"). BandM is the coloured plus light stripe in metres,
+ /// so the band grows towards the camera as the promo's does; ColourShare the coloured stripe's part of it; Wash the
+ /// wash's width as a multiple of the band, WashStrength its opacity at the band.</summary>
+ public readonly struct Style
+ {
+ public readonly Color Colour, Light; public readonly float BandM, ColourShare, Wash, WashStrength;
+ public Style(Color colour, Color light, float bandM, float colourShare, float wash, float washStrength)
+ { Colour = colour; Light = light; BandM = bandM; ColourShare = colourShare; Wash = wash; WashStrength = washStrength; }
+ }
+
+ /// <summary>The promo's blue line (6 + 6 px of blue and white with a 10 px wash at 2752 px; 125,140,182 and
+ /// 251,251,248): the heavier of the two.</summary>
+ public static readonly Style Primary = new Style(new Color(0.40f, 0.50f, 0.80f), new Color(1.08f, 1.08f, 1.06f), 230f, 0.5f, 0.9f, 0.40f);
+ /// <summary>The promo's red-orange line (4 + 3 px with an 8 px wash; 176,93,61 and 246,188,124), a little more
+ /// saturated than the promo's so it keeps a contrast against both olive and dry-grass ground for colour-blind players
+ /// (GradeTests).</summary>
+ public static readonly Style Secondary = new Style(new Color(0.75f, 0.31f, 0.13f), new Color(1.05f, 0.76f, 0.48f), 200f, 0.6f, 1.0f, 0.18f);
+ /// <summary>The band draws at least MinBandPx wide (the overview), unless that would make it, with its wash, wider than
+ /// MaxShareOfInradius of a hex's inradius: that cap wins (below about 8 px of inradius on screen the band goes under
+ /// 2 px), so a far hex is never filled by its outline.</summary>
+ public const float MinBandPx = 2f, MaxShareOfInradius = 0.5f;
+
+ static Texture2D? texture;
+ static MapRuntimeAssets? owner;
+ static GameObject? banner;
+ static bool hasLayer, toggleOn = true;
+ static bool noEarlyOut;
+
+ /// <summary>Test seam (_ScBorders.z): true draws every pixel the long way, with no early-out, so a test can prove the
+ /// early-out exact (the two renders must match pixel for pixel).</summary>
+ internal static bool NoEarlyOut { get => noEarlyOut; set { noEarlyOut = value; Push(); } }
+ static int qMin, rMin;
+ static readonly HashSet<(int q, int r)> mapHexes = new HashSet<(int q, int r)>();
+
+ /// <summary>The layer the map draws now (null: none).</summary>
+ public static RegionLayer? Current { get; private set; }
+
+ /// <summary>Called by MapBuilder.Build (after MapShaderGlobals.Apply) on every build: a cleared hex texture over hexes.json's (q, r) range (owned
+ /// by the map), the styles' globals, no layer, and the "borders" toggle (on), all undone by the map's teardown.</summary>
+ public static void Apply(HexFile hexes, MapRuntimeAssets assets)
+ {
+ if (hexes == null) throw new ArgumentNullException(nameof(hexes));
+ if (assets == null) throw new ArgumentNullException(nameof(assets));
+ qMin = hexes.hexes.Min(h => h.q); rMin = hexes.hexes.Min(h => h.r);
+ int w = hexes.hexes.Max(h => h.q) - qMin + 1, h = hexes.hexes.Max(x => x.r) - rMin + 1;
+ mapHexes.Clear();
+ foreach (var x in hexes.hexes) mapHexes.Add((x.q, x.r));
+ var tex = assets.Own(new Texture2D(w, h, TextureFormat.RGBA32, false, true)
+ {
+ name = "RegionHexes", filterMode = FilterMode.Point, wrapMode = TextureWrapMode.Clamp,
+ });
+ tex.SetPixels32(new Color32[w * h]); tex.Apply(false, false);
+ texture = tex; owner = assets; banner = null;
+ Current = null; hasLayer = false; toggleOn = true; noEarlyOut = false;
+ Shader.SetGlobalTexture(RegionTex, tex);
+ Shader.SetGlobalVector(RegionInfo, new Vector4(qMin, rMin, w, h));
+ SetStyle(Colour1, Light1, Shape1, Primary);
+ SetStyle(Colour2, Light2, Shape2, Secondary);
+ Push();
+ assets.OnTeardown(VisualToggles.Register(ToggleName, on => { toggleOn = on; Push(); }));
+ assets.OnTeardown(() => { texture = null; owner = null; banner = null; Current = null; hasLayer = false; noEarlyOut = false; Push(); });
+ }
+
+ /// <summary>Draws <paramref name="layer"/> on the built map (null: none). Throws ArgumentException for a hex that is
+ /// not on the map, InvalidOperationException before a map is built.</summary>
+ public static void Use(RegionLayer? layer)
+ {
+ if (texture == null) throw new InvalidOperationException("MapBorders.Use needs a built map");
+ int w = texture.width, h = texture.height;
+ var px = new Color32[w * h];
+ if (layer != null)
+ foreach (var (q, r) in layer.Hexes)
+ {
+ if (!mapHexes.Contains((q, r))) throw new ArgumentException($"{layer.Name}: hex ({q}, {r}) is not on the map");
+ px[(r - rMin) * w + (q - qMin)] = Encode(layer.RegionOf(q, r), layer.StyleOf(layer.RegionOf(q, r)));
+ }
+ texture.SetPixels32(px); texture.Apply(false, false);
+ Current = layer; hasLayer = layer != null && layer.Count > 0;
+ if (banner != null) { DestroyObject(banner); banner = null; }
+ if (layer?.Banner != null && owner != null) banner = Banner.Create(layer.Banner, owner);
+ Push();
+ }
+
+ static void DestroyObject(UnityEngine.Object o) { if (Application.isPlaying) UnityEngine.Object.Destroy(o); else UnityEngine.Object.DestroyImmediate(o); }
+
+ /// <summary>The texel of a hex: r + 256 g the region id, b the style (StatecraftBorders.hlsl, ScRegionAt).</summary>
+ public static Color32 Encode(int id, BorderStyle style) => new Color32((byte)(id & 0xFF), (byte)(id >> 8), (byte)style, 255);
+
+ static void SetStyle(int colour, int light, int shape, Style s)
+ {
+ var c = s.Colour.linear; var l = s.Light.linear;
+ Shader.SetGlobalVector(colour, new Vector4(c.r, c.g, c.b, 1f));
+ Shader.SetGlobalVector(light, new Vector4(l.r, l.g, l.b, 1f));
+ Shader.SetGlobalVector(shape, new Vector4(s.BandM, s.ColourShare, s.Wash, s.WashStrength));
+ }
+
+ static void Push()
+ {
+ bool drawn = toggleOn && hasLayer && texture != null;
+ Shader.SetGlobalVector(Borders, new Vector4(MinBandPx, MaxShareOfInradius, noEarlyOut ? 1f : 0f, drawn ? 1f : 0f));
+ if (banner != null) banner.SetActive(drawn);
+ }
+
+ /// <summary>The banner that labels a layer on screen: white text with a dark drop copy, a child of the main camera
+ /// at a fixed place in view (left, 35% down: inside the tilt-shift's sharp band, so it stays legible), drawn by the camera itself so editor
+ /// renders, tests and players all carry it. Owned by the map (destroyed with it).</summary>
+ static class Banner
+ {
+ public static GameObject? Create(string text, MapRuntimeAssets assets)
+ {
+ var cam = Camera.main;
+ if (cam == null) return null;
+ var root = assets.Own(new GameObject("BorderBanner"));
+ root.transform.SetParent(cam.transform, false);
+ root.transform.localRotation = Quaternion.identity;
+ root.AddComponent<BannerPlacement>().Place(cam);
+ float d = BannerPlacement.Depth(cam), halfH = d * Mathf.Tan(cam.fieldOfView * 0.5f * Mathf.Deg2Rad);
+ var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
+ float height = 0.065f * halfH; // about 3.3% of the screen's height per line
+ Line(root.transform, text, font, height, new Color(0.08f, 0.06f, 0.05f), new Vector3(height * 0.06f, -height * 0.06f, height * 0.01f));
+ Line(root.transform, text, font, height, new Color(1f, 0.98f, 0.9f), Vector3.zero);
+ return root;
+ }
+
+ /// <summary>Keeps the banner at the top left of whatever its camera draws into: placed from the camera's aspect
+ /// just before each of its renders (URP's beginCameraRendering), so a 4:3 window or a 1920x1080 capture both show
+ /// it whole.</summary>
+ [ExecuteAlways]
+ sealed class BannerPlacement : MonoBehaviour
+ {
+ public static float Depth(Camera cam) => cam.nearClipPlane * 4f;
+
+ public void Place(Camera cam)
+ {
+ float d = Depth(cam), halfH = d * Mathf.Tan(cam.fieldOfView * 0.5f * Mathf.Deg2Rad), halfW = halfH * cam.aspect;
+ transform.localPosition = new Vector3(-0.94f * halfW, 0.30f * halfH, d); // 35% down: inside the tilt-shift's sharp band
+ }
+
+ void OnEnable() => UnityEngine.Rendering.RenderPipelineManager.beginCameraRendering += Before;
+ void OnDisable() => UnityEngine.Rendering.RenderPipelineManager.beginCameraRendering -= Before;
+ void Before(UnityEngine.Rendering.ScriptableRenderContext _, Camera cam)
+ {
+ if (this != null && transform.parent == cam.transform) Place(cam);
+ }
+ }
+
+ static void Line(Transform parent, string text, Font font, float height, Color colour, Vector3 offset)
+ {
+ var go = new GameObject("Line");
+ go.transform.SetParent(parent, false);
+ go.transform.localPosition = offset;
+ var tm = go.AddComponent<TextMesh>();
+ tm.text = text; tm.font = font; tm.fontSize = 64; tm.characterSize = height / 6.4f; tm.anchor = TextAnchor.UpperLeft;
+ tm.fontStyle = FontStyle.Bold;
+ tm.color = colour;
+ var mr = go.GetComponent<MeshRenderer>();
+ mr.sharedMaterial = font.material;
+ mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; mr.receiveShadows = false;
+ }
+ }
+ }
+
+ /// <summary>A synthetic region pattern that shows the border renderer at work, for tests and captures only: a checker of
+ /// <see cref="BlockSize"/> x <see cref="BlockSize"/> axial hex blocks (parallelograms, a regular lattice over the whole
+ /// map, unrelated to any town or line), alternately Primary and Secondary; sea and lake hexes in no region. It carries
+ /// the on-screen label <see cref="Label"/> while drawn, and only the editor and development builds honour its flag
+ /// ("borderproof" in the WebGL page URL, -borderproof on desktop and in the editor's promo renders): a release
+ /// (shareable) build never shows it (review I3).</summary>
+ public static class BorderProof
+ {
+ public const string Flag = "borderproof";
+ public const string Label = "SYNTHETIC TEST PATTERN \u2014 not real boundaries";
+ public const int BlockSize = 4;
+
+ public static bool Requested() =>
+ Requested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer,
+ Application.isEditor || Debug.isDebugBuild);
+
+ /// <summary>Whether the flag is given and honoured: never in a release build (<paramref name="devBuild"/> false).</summary>
+ public static bool Requested(string? url, string[] args, bool webgl, bool devBuild) =>
+ devBuild && (webgl ? UrlFlags.Has(url, Flag) : args.Contains("-" + Flag));
+
+ /// <summary>The checker on <paramref name="hexes"/>' land hexes.</summary>
+ public static RegionLayer Build(HexFile hexes)
+ {
+ var regions = new Dictionary<(int q, int r), int>(); var styles = new Dictionary<int, BorderStyle>();
+ foreach (var h in hexes.hexes)
+ {
+ if (!h.land) continue;
+ var (bq, br) = Block(h.q, h.r);
+ int id = 1 + (bq + 64) + 128 * br;
+ regions[(h.q, h.r)] = id;
+ styles[id] = ((bq + br) & 1) == 0 ? BorderStyle.Primary : BorderStyle.Secondary;
+ }
+ return new RegionLayer("border proof (synthetic checker)", regions, styles, Label);
+ }
+
+ /// <summary>The checker block of axial hex (q, r).</summary>
+ public static (int bq, int br) Block(int q, int r) => (FloorDiv(q, BlockSize), FloorDiv(r, BlockSize));
+
+ static int FloorDiv(int a, int b) => a >= 0 ? a / b : -((-a + b - 1) / b);
+
+ /// <summary>The pattern on the built map, drawn at once, with its label.</summary>
+ public static RegionLayer Show(MapScene map)
+ {
+ if (map == null || map.Terrain == null || map.Hexes == null) throw new InvalidOperationException("BorderProof needs a built map");
+ var layer = Build(map.Hexes);
+ MapBorders.Use(layer);
+ return layer;
+ }
+
+ /// <summary>The axial hex under a lon/lat point of the built map.</summary>
+ public static (int q, int r) HexAt(MapScene map, double lon, double lat)
+ {
+ float size = map.Hexes.hex_size_km * 1000f;
+ var p = HexGrid.FromWorld(map.Frame.ToWorld(lon, lat, 0), map.Terrain.transform.position, map.Terrain.terrainData.size.z);
+ var c = HexGrid.NearestCentre(p, size);
+ int r = Mathf.RoundToInt(c.y / (1.5f * size));
+ return (Mathf.RoundToInt((c.x / size - 0.8660254f * r) / 1.7320508f), r);
+ }
+
+ public static int Distance((int q, int r) a, (int q, int r) b)
+ {
+ int dq = a.q - b.q, dr = a.r - b.r;
+ return (Math.Abs(dq) + Math.Abs(dr) + Math.Abs(dq + dr)) / 2;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/MapBorders.cs.meta b/unity/Assets/Scripts/Map/MapBorders.cs.meta
new file mode 100644
index 000000000..152d2cd16
--- /dev/null
+++ b/unity/Assets/Scripts/Map/MapBorders.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: cf80e26042ca74175bb241a9c94913ca
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/MapBuilder.cs b/unity/Assets/Scripts/Map/MapBuilder.cs
index d9bf8b69b..a5bdd4a8f 100644
--- a/unity/Assets/Scripts/Map/MapBuilder.cs
+++ b/unity/Assets/Scripts/Map/MapBuilder.cs
@@ -88,6 +88,7 @@ namespace Statecraft.Game.Map
data.alphamapResolution = 16;
MapShaderGlobals.Apply(terrain, meta, hexFile.hex_size_km * 1000f, BakeBiomeTexture(frame, hexFile, assets, paintGround), assets);
Boot.DiagLog.BootPhase("biome texture baked");
+ MapBorders.Apply(hexFile, assets); // region borders: none drawn until a layer is given (MapBorders.Use)
return terrainGo;
}
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 05d71c174..4532fa5c5 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -203,6 +203,8 @@ namespace Statecraft.Game.UI
if (Application.isPlaying && Statecraft.Game.Map.Units.UnitShowcase.Requested())
Statecraft.Game.Map.Units.UnitShowcase.Spawn(map, Statecraft.Game.Map.Units.UnitShowcase.StillRequested(
Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer));
+ // The border renderer's synthetic, labelled proof (?borderproof / -borderproof): development builds only.
+ if (Application.isPlaying && BorderProof.Requested()) BorderProof.Show(map);
// The visual track's instruments (docs/visual-v1.md): both move the camera, so one per run.
if (Application.isPlaying && FrameProfile.Requested())
StartCoroutine(FrameProfile.Run(camRig, map.Frame, Debug.Log, Application.platform != RuntimePlatform.WebGLPlayer));
diff --git a/unity/Assets/Shaders/StatecraftBorders.hlsl b/unity/Assets/Shaders/StatecraftBorders.hlsl
new file mode 100644
index 000000000..49fffc3f4
--- /dev/null
+++ b/unity/Assets/Shaders/StatecraftBorders.hlsl
@@ -0,0 +1,118 @@
+#ifndef STATECRAFT_BORDERS_INCLUDED
+#define STATECRAFT_BORDERS_INCLUDED
+// Region borders (promo-borders): the promo's two-tone outlines along hex edges, drawn inside each region along every edge
+// it shares with a different region (as Civ draws them, so two outlined regions meet as a double band): a coloured stripe on
+// the edge, a light stripe inside it, then a soft wash of the colour fading inwards. Data driven: MapBorders (C#) bakes one
+// texel per hex (_ScRegionTex) and sets the globals; with no region data, or the "borders" toggle off, _ScBorders.w is 0 and
+// nothing is drawn. Included at the end of StatecraftMap.hlsl; the terrain calls ScBorderApply last.
+
+TEXTURE2D(_ScRegionTex); // one texel per hex, linear RGBA8: r + 256 g the region id (0 = none), b the style (0 = none, 1, 2)
+float4 _ScRegionInfo; // x q of texel column 0, y r of texel row 0, z width, w height (texels)
+float4 _ScBorders; // x least band width (px), y widest band (+ wash) as a share of the hex's inradius,
+ // z 1 = no early-out (tests prove the early-out exact), w 1 = on
+// Per style (1 primary, 2 secondary): Colour rgb the edge stripe (linear); Light rgb the inner stripe; Shape x the band's
+// width (m; colour + light stripes), y the colour stripe's share of it, z the wash's width (times the band's), w its strength.
+float4 _ScBorderColour1, _ScBorderLight1, _ScBorderShape1;
+float4 _ScBorderColour2, _ScBorderLight2, _ScBorderShape2;
+
+// Axial neighbour steps and the outward unit normals of the edges shared with them (p space: x east, y south): tools/
+// hexgrid.py's NEIGHBOURS order.
+static const float2 ScHexSteps[6] = { float2(1, 0), float2(1, -1), float2(0, -1), float2(-1, 0), float2(-1, 1), float2(0, 1) };
+static const float2 ScHexNormals[6] = { float2(1, 0), float2(0.5, -0.8660254), float2(-0.5, -0.8660254), float2(-1, 0),
+ float2(-0.5, 0.8660254), float2(0.5, 0.8660254) };
+
+// Region id and style of axial hex (q, r); (0, 0) off the texture.
+float2 ScRegionAt(float2 qr)
+{
+ int2 t = int2(qr - _ScRegionInfo.xy);
+ if (t.x < 0 || t.y < 0 || t.x >= (int)_ScRegionInfo.z || t.y >= (int)_ScRegionInfo.w) return float2(0.0, 0.0);
+ float4 v = LOAD_TEXTURE2D(_ScRegionTex, t) * 255.0;
+ return float2(round(v.r) + 256.0 * round(v.g), round(v.b));
+}
+
+// The axial hex containing p (cube rounding: ScHexEdgeDistance's layout, p.x east and p.y south of the north-west corner)
+// and p's offset from that hex's centre.
+float2 ScHexAxial(float2 p, float size, out float2 v)
+{
+ float qf = (0.57735027 * p.x - p.y / 3.0) / size;
+ float rf = 0.66666667 * p.y / size;
+ float sf = -qf - rf;
+ float q = round(qf), r = round(rf), s = round(sf);
+ float dq = abs(q - qf), dr = abs(r - rf), ds = abs(s - sf);
+ if (dq > dr && dq > ds) q = -r - s; else if (dr > ds) r = -q - s;
+ v = p - float2(size * (1.7320508 * q + 0.8660254 * r), size * 1.5 * r);
+ return float2(q, r);
+}
+
+// Adds the borders to the terrain's outputs (unlit: the stripes and wash replace BaseColor and go out as Emission, so they
+// read the same in sun and shadow, as the promo's glowing lines do). mapM: metres east and north of the map's south-west
+// corner; water: ScWater's 0 (land) .. 1 (water): bands stay on land, so a boundary that reaches the coast stops at the
+// shore instead of running up to 4 km out to its hex's edge (review M7). Call it in uniform control flow (outside any
+// [branch]): it takes derivatives.
+void ScBorderApply(float2 mapM, float water, inout float3 baseColor, inout float3 emission)
+{
+ float2 p = float2(mapM.x, _ScMap.y - mapM.y);
+ float2 px = ddx(p), py = ddy(p);
+ [branch] if (_ScBorders.w > 0.5)
+ {
+ float size = _ScMapOrigin.w, inradius = 0.8660254 * size;
+ float2 v;
+ float2 qr = ScHexAxial(p, size, v);
+ // How far a band and its wash can reach from an edge (m): the wider style's band (or the least width in pixels, at
+ // up to 1.5x the footprint: the gradient's metres per pixel never exceed sqrt 2 of it) times 1 + its wash, plus a
+ // pixel for the filter. A pixel farther than that from every edge of its hex is in no band (the distance to an edge
+ // segment is never less than to its line), so most pixels fetch no texel at all (review: 7 fetches on every land
+ // pixel cost 3.3 ms at gameplay03).
+ float footprint = max(length(px), length(py));
+ float washMul = 1.0 + max(_ScBorderShape1.z, _ScBorderShape2.z);
+ float reach = max(max(_ScBorderShape1.x, _ScBorderShape2.x), 1.5 * _ScBorders.x * footprint) * washMul + 1.5 * footprint;
+ reach = _ScBorders.z > 0.5 ? 1e9 : reach;
+ float edge = inradius - max(abs(v.x), max(abs(0.5 * v.x + 0.8660254 * v.y), abs(0.5 * v.x - 0.8660254 * v.y)));
+ float2 own = edge < reach && water < 1.0 ? ScRegionAt(qr) : float2(0.0, 0.0);
+ [branch] if (own.x > 0.5 && own.y > 0.5)
+ {
+ float bestPx = 1e9, bestAa = 1.0;
+ [unroll] for (int i = 0; i < 6; i++)
+ {
+ float2 n = ScHexNormals[i];
+ // Only the edges within reach are looked up (one, or two near a corner).
+ if (inradius - dot(v, n) >= reach) continue;
+ float2 other = ScRegionAt(qr + ScHexSteps[i]);
+ if (other.x > 0.5 && other.x != own.x)
+ {
+ // Distance to the edge segment (corners rounded, so two border edges join without a notch), in pixels
+ // along the direction it grows (Task 8's anisotropic filter: metres per pixel across the line).
+ float2 t = float2(-n.y, n.x);
+ float2 closest = n * inradius + t * clamp(dot(v, t), -0.5 * size, 0.5 * size);
+ float2 e = v - closest;
+ float d = length(e);
+ float2 g = d > 1e-3 ? e / d : -n;
+ float aa = max(length(float2(dot(px, g), dot(py, g))), 1e-3);
+ if (d / aa < bestPx) { bestPx = d / aa; bestAa = aa; }
+ }
+ }
+ bool primary = own.y < 1.5;
+ float4 colour = primary ? _ScBorderColour1 : _ScBorderColour2;
+ float4 light = primary ? _ScBorderLight1 : _ScBorderLight2;
+ float4 shape = primary ? _ScBorderShape1 : _ScBorderShape2;
+ // The band is shape.x metres wide (it grows towards the camera, like the promo's), never thinner than the least
+ // width, and the band plus its wash never wider than _ScBorders.y of the inradius (far zooms: a hex stays a hex).
+ float widest = _ScBorders.y * inradius / bestAa;
+ float bandPx = min(max(shape.x / bestAa, _ScBorders.x), widest / (1.0 + shape.z));
+ float washPx = bandPx * shape.z;
+ // Box-filtered stripes: the colour from the edge to shape.y of the band, the light stripe to its end.
+ float cColour = saturate(shape.y * bandPx - bestPx + 0.5);
+ float cBand = saturate(bandPx - bestPx + 0.5);
+ // max(): a style with no wash (shape.z 0) must not make smoothstep divide by zero (review M3).
+ float wash = shape.w * (1.0 - smoothstep(bandPx, bandPx + max(washPx, 1e-3), bestPx)) * (1.0 - cBand);
+ float3 stripe = lerp(light.rgb, colour.rgb, cBand > 0.0 ? cColour / cBand : 0.0);
+ float cover = saturate(cBand + wash);
+ float3 c = cBand > 0.0 || wash > 0.0 ? (stripe * cBand + colour.rgb * wash) / max(cover, 1e-4) : colour.rgb;
+ float a = cover * (1.0 - water);
+ baseColor *= 1.0 - a;
+ emission = lerp(emission, c, a);
+ }
+ }
+}
+
+#endif
diff --git a/unity/Assets/Shaders/StatecraftBorders.hlsl.meta b/unity/Assets/Shaders/StatecraftBorders.hlsl.meta
new file mode 100644
index 000000000..c8d4e4507
--- /dev/null
+++ b/unity/Assets/Shaders/StatecraftBorders.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: d49b526b515ee49d88dd1f3e0f90223c
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Shaders/StatecraftMap.hlsl b/unity/Assets/Shaders/StatecraftMap.hlsl
index f754d091e..92e044c68 100644
--- a/unity/Assets/Shaders/StatecraftMap.hlsl
+++ b/unity/Assets/Shaders/StatecraftMap.hlsl
@@ -302,4 +302,7 @@ float ScGridAmount(float2 mapM, float3 positionWS)
return cover * _ScGrid.w * fade;
}
+// Region borders (promo-borders): their globals and ScBorderApply, which the terrain calls last.
+#include "Assets/Shaders/StatecraftBorders.hlsl"
+
#endif
diff --git a/unity/Assets/Shaders/StatecraftTerrain.hlsl b/unity/Assets/Shaders/StatecraftTerrain.hlsl
index 0933721eb..61411a693 100644
--- a/unity/Assets/Shaders/StatecraftTerrain.hlsl
+++ b/unity/Assets/Shaders/StatecraftTerrain.hlsl
@@ -50,6 +50,7 @@ void StatecraftTerrain_float(float2 UV, float3 PositionWS, float3 NormalWS, Unit
Smoothness = 0.0;
Metallic = water;
Emission = lerp(_ScHaze.rgb * h, waterColour, water);
+ ScBorderApply(mapM, water, BaseColor, Emission); // region borders (StatecraftBorders.hlsl), last: unlit, on land only
}
#endif
diff --git a/unity/Assets/Tests/EditMode/BorderTests.cs b/unity/Assets/Tests/EditMode/BorderTests.cs
new file mode 100644
index 000000000..0cec0a26f
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/BorderTests.cs
@@ -0,0 +1,468 @@
+#nullable enable
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.TestTools;
+
+/// <summary>promo-borders: the region border renderer (MapBorders, StatecraftBorders.hlsl). The rendered tests draw the
+/// synthetic BorderProof rings: the repository holds no real region data yet, and the game draws none.</summary>
+public class BorderTests
+{
+ [TearDown]
+ public void Reset()
+ {
+ MapShaderGlobals.PinWaterTime(null);
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); VisualToggles.Clear();
+ }
+
+ internal static (MapScene map, Camera cam, CameraRig rig) Open()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();
+ MapShaderGlobals.PinWaterTime(100f); // renders compared pixel for pixel: the sea must not move between them
+ var cam = Camera.main;
+ return (map, cam, cam.GetComponent<CameraRig>());
+ }
+
+ [Test]
+ public void ARegionLayerRejectsBadIdsAndRegionsWithoutAStyle()
+ {
+ var hexes = new Dictionary<(int q, int r), int> { [(0, 0)] = 1 };
+ Assert.Throws<System.ArgumentException>(() => new RegionLayer("t", hexes, new Dictionary<int, BorderStyle>()));
+ Assert.Throws<System.ArgumentException>(() => new RegionLayer("t", hexes, new Dictionary<int, BorderStyle> { [1] = BorderStyle.Primary, [0] = BorderStyle.Primary }));
+ Assert.Throws<System.ArgumentException>(() => new RegionLayer("t", hexes, new Dictionary<int, BorderStyle> { [1] = (BorderStyle)7 }));
+ Assert.Throws<System.ArgumentException>(() => new RegionLayer(" ", hexes, new Dictionary<int, BorderStyle> { [1] = BorderStyle.Primary }));
+ var ok = new RegionLayer("t", hexes, new Dictionary<int, BorderStyle> { [1] = BorderStyle.Secondary });
+ Assert.AreEqual(1, ok.RegionOf(0, 0)); Assert.AreEqual(0, ok.RegionOf(1, 0));
+ Assert.AreEqual(BorderStyle.Secondary, ok.StyleOf(1)); Assert.AreEqual(BorderStyle.None, ok.StyleOf(2));
+ }
+
+ [Test]
+ public void AHexTexelCarriesItsRegionInTwoBytesAndItsStyle()
+ {
+ var c = MapBorders.Encode(300, BorderStyle.Secondary);
+ Assert.AreEqual((44, 1, 2, 255), ((int)c.r, (int)c.g, (int)c.b, (int)c.a));
+ Assert.AreEqual(RegionLayer.MaxId, MapBorders.Encode(RegionLayer.MaxId, BorderStyle.None).r + 256 * MapBorders.Encode(RegionLayer.MaxId, BorderStyle.None).g);
+ }
+
+ [Test]
+ public void TheProofIsACheckerOfHexBlocksOnLandOnlyAndLabelledSynthetic()
+ {
+ var (map, _, _) = Open();
+ var layer = BorderProof.Build(map.Hexes);
+ StringAssert.Contains("SYNTHETIC TEST PATTERN", layer.Banner);
+ foreach (var h in map.Hexes.hexes)
+ {
+ int id = layer.RegionOf(h.q, h.r);
+ if (!h.land) { Assert.AreEqual(0, id, $"water hex ({h.q}, {h.r}) is in no region"); continue; }
+ var (bq, br) = BorderProof.Block(h.q, h.r);
+ Assert.AreEqual(((bq + br) & 1) == 0 ? BorderStyle.Primary : BorderStyle.Secondary, layer.StyleOf(id));
+ // Hexes share a region exactly when they share a block.
+ var east = (h.q + 1, h.r);
+ if (layer.RegionOf(east.Item1, east.Item2) != 0)
+ Assert.AreEqual(BorderProof.Block(h.q, h.r) == BorderProof.Block(east.Item1, east.Item2), id == layer.RegionOf(east.Item1, east.Item2));
+ }
+ Assert.AreEqual((0, 0), BorderProof.Block(3, 3)); Assert.AreEqual((-1, 1), BorderProof.Block(-1, 4));
+ Assert.AreEqual((-2, 0), BorderProof.Block(-5, 0));
+ }
+
+ /// <summary>Review I3: a release (shareable) build ignores the proof's flag; the editor and development builds honour it.</summary>
+ [Test]
+ public void AReleaseBuildIgnoresTheProofFlag()
+ {
+ const string url = "https://example.invalid/index.html?golden&borderproof";
+ var args = new[] { "Statecraft", "-borderproof" };
+ Assert.IsFalse(BorderProof.Requested(url, args, webgl: true, devBuild: false));
+ Assert.IsFalse(BorderProof.Requested(url, args, webgl: false, devBuild: false));
+ Assert.IsTrue(BorderProof.Requested(url, args, webgl: true, devBuild: true));
+ Assert.IsTrue(BorderProof.Requested(url, args, webgl: false, devBuild: true));
+ Assert.IsFalse(BorderProof.Requested("https://example.invalid/?borderproofx", new string[0], webgl: true, devBuild: true));
+ }
+
+ /// <summary>Re-review: the label really renders (a legacy TextMesh under URP), in the upper left, at 16:9 and at 4:3:
+ /// the upper-left region changes between renders with the label shown and hidden, nothing else does, and its left end
+ /// is on screen.</summary>
+ [UnityTest]
+ public IEnumerator TheProofLabelRendersAtTheTopLeft()
+ {
+ var (map, cam, rig) = Open();
+ yield return null;
+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();
+ BorderProof.Show(map);
+ var banner = Camera.main.transform.Find("BorderBanner").gameObject;
+ foreach (var (w, h) in new[] { (1920, 1080), (1440, 1080) })
+ {
+ var on = RenderSample.Render(cam, w, h);
+ banner.SetActive(false);
+ var off = RenderSample.Render(cam, w, h);
+ banner.SetActive(true);
+ int topLeft = 0, elsewhere = 0;
+ for (int y = 0; y < h; y++)
+ for (int x = 0; x < w; x++)
+ {
+ Color a = on.At(x, y), b = off.At(x, y);
+ if (Mathf.Max(Mathf.Abs(a.r - b.r), Mathf.Max(Mathf.Abs(a.g - b.g), Mathf.Abs(a.b - b.b))) <= 0.1f) continue;
+ if (x < w * 0.75f && y > h * 0.5f) topLeft++; else elsewhere++; // row 0 is the bottom
+ }
+ TestContext.WriteLine($"{w}x{h}: {topLeft} label pixels at the top left, {elsewhere} elsewhere");
+ Assert.Greater(topLeft, w * h / 2000, $"{w}x{h}: the label draws at the top left");
+ Assert.AreEqual(0, elsewhere, $"{w}x{h}: and nowhere else");
+ // Its left end is on screen: some changed pixel within the first 8% of the width.
+ bool leftEnd = false;
+ for (int y = (int)(h * 0.5f); y < h && !leftEnd; y++)
+ for (int x = 0; x < w * 0.08f && !leftEnd; x++)
+ {
+ Color a = on.At(x, y), b = off.At(x, y);
+ leftEnd = Mathf.Max(Mathf.Abs(a.r - b.r), Mathf.Max(Mathf.Abs(a.g - b.g), Mathf.Abs(a.b - b.b))) > 0.1f;
+ }
+ Assert.IsTrue(leftEnd, $"{w}x{h}: the label starts at the left edge, not off screen");
+ }
+ }
+
+ /// <summary>Review I3: whenever the proof is drawn its label is on screen, and it goes with the drawing.</summary>
+ [Test]
+ public void TheProofIsLabelledOnScreenWhileDrawn()
+ {
+ var (map, _, _) = Open();
+ BorderProof.Show(map);
+ var banner = Camera.main.transform.Find("BorderBanner");
+ Assert.IsNotNull(banner, "the label exists");
+ Assert.IsTrue(banner.gameObject.activeSelf);
+ foreach (var tm in banner.GetComponentsInChildren<TextMesh>(true)) Assert.AreEqual(BorderProof.Label, tm.text);
+ VisualToggles.Set(MapBorders.ToggleName, false);
+ Assert.IsFalse(banner.gameObject.activeSelf, "hidden with the borders");
+ VisualToggles.Set(MapBorders.ToggleName, true);
+ Assert.IsTrue(banner.gameObject.activeSelf);
+ MapBorders.Use(null);
+ Assert.IsTrue(banner == null, "gone with the layer");
+ }
+
+ [Test]
+ public void UseRejectsAHexOffTheMapAndWorksOnlyOnABuiltMap()
+ {
+ var (map, _, _) = Open();
+ var bad = new RegionLayer("t", new Dictionary<(int q, int r), int> { [(500, 500)] = 1 }, new Dictionary<int, BorderStyle> { [1] = BorderStyle.Primary });
+ Assert.Throws<System.ArgumentException>(() => MapBorders.Use(bad));
+ Reset();
+ Assert.Throws<System.InvalidOperationException>(() => MapBorders.Use(null));
+ }
+
+ /// <summary>Without data the "borders" toggle is a no-op: the frame is identical with it on and off (that both run the
+ /// same shader is the point: the branch's frame against main's is checked by the art checkpoints, docs/visual-v1.md,
+ /// "Region borders"). Once a layer is in use the toggle removes it (with its label), and an empty layer draws
+ /// nothing.</summary>
+ [UnityTest]
+ public IEnumerator WithoutRegionDataTheToggleIsANoOp()
+ {
+ var (map, cam, rig) = Open();
+ yield return null;
+ RenderSample.TiltShift(false);
+ CollectionAssert.Contains(VisualToggles.Names, MapBorders.ToggleName);
+ Assert.IsNull(MapBorders.Current);
+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();
+ var on = RenderSample.Render(cam, 480, 270);
+ VisualToggles.Set(MapBorders.ToggleName, false);
+ var off = RenderSample.Render(cam, 480, 270);
+ Assert.AreEqual(0f, Changed(on, off, 0f), "no layer: the toggle changes nothing");
+ VisualToggles.Set(MapBorders.ToggleName, true);
+ BorderProof.Show(map);
+ var proof = RenderSample.Render(cam, 480, 270);
+ Assert.Greater(Changed(proof, off, 0.02f), 0.002f, "the proof draws");
+ VisualToggles.Set(MapBorders.ToggleName, false);
+ Assert.AreEqual(0f, Changed(RenderSample.Render(cam, 480, 270), off, 0f), "the toggle removes a layer in use");
+ VisualToggles.Set(MapBorders.ToggleName, true);
+ MapBorders.Use(new RegionLayer("empty", new Dictionary<(int q, int r), int>(), new Dictionary<int, BorderStyle>()));
+ Assert.AreEqual(0f, Changed(RenderSample.Render(cam, 480, 270), off, 0f), "an empty layer draws nothing");
+ }
+
+ /// <summary>Share of pixels whose largest channel differs by more than <paramref name="by"/>.</summary>
+ internal static float Changed(RenderSample a, RenderSample b, float by)
+ {
+ int n = 0;
+ for (int i = 0; i < a.Pixels.Length; i++)
+ {
+ Color x = a.Pixels[i], y = b.Pixels[i];
+ if (Mathf.Max(Mathf.Abs(x.r - y.r), Mathf.Max(Mathf.Abs(x.g - y.g), Mathf.Abs(x.b - y.b))) > by) n++;
+ }
+ return (float)n / a.Pixels.Length;
+ }
+
+ /// <summary>One walk across a hex edge at one point along it: the pixels from 1.5 km inside the inner hex to 1.5 km inside
+ /// the outer one, with the borders on and off, and each pixel's signed distance (m; negative: the inner hex).</summary>
+ internal sealed class Walk
+ {
+ public readonly List<Color> On = new List<Color>(), Off = new List<Color>();
+ public readonly List<float> SignedM = new List<float>();
+ public readonly List<Vector2> Px = new List<Vector2>();
+ }
+
+ const float WalkM = 1500f, StepM = 10f;
+
+ /// <summary>Walks across the edge between axial hexes <paramref name="inner"/> and <paramref name="outer"/> (neighbours)
+ /// at <paramref name="samples"/> points spread over the middle 60% of the edge, at the camera's current pose, rendering
+ /// at width x height with the proof drawn (on) and the borders off. Distinct pixels only, in walk order.</summary>
+ internal static List<Walk> WalkEdge(MapScene map, Camera cam, (int q, int r) inner, (int q, int r) outer, int samples, int width, int height)
+ {
+ float size = map.Hexes.hex_size_km * 1000f, inradius = Mathf.Sqrt(3f) / 2f * size;
+ var origin = map.Terrain.transform.position;
+ Vector2 ci = HexGrid.Centre(inner.q, inner.r, size), co = HexGrid.Centre(outer.q, outer.r, size);
+ var n = (co - ci).normalized; var t = new Vector2(-n.y, n.x);
+ int steps = Mathf.RoundToInt(2 * WalkM / StepM) + 1;
+ var world = new Vector3[samples * steps]; var signed = new float[world.Length];
+ for (int i = 0; i < samples; i++)
+ for (int k = 0; k < steps; k++)
+ {
+ float u = samples == 1 ? 0f : -0.3f + 0.6f * i / (samples - 1), s = -WalkM + k * StepM;
+ var p = ci + n * (inradius + s) + t * (u * size);
+ var w = HexGrid.ToWorld(p, origin, map.Frame.LengthM);
+ w.y = map.Terrain.SampleHeight(w) + origin.y;
+ world[i * steps + k] = w; signed[i * steps + k] = s;
+ }
+ var px = new Vector2[world.Length];
+ var on = RenderSample.Render(cam, width, height, world, px);
+ VisualToggles.Set(MapBorders.ToggleName, false);
+ var off = RenderSample.Render(cam, width, height, world, px);
+ VisualToggles.Set(MapBorders.ToggleName, true);
+ var walks = new List<Walk>();
+ for (int i = 0; i < samples; i++)
+ {
+ var walk = new Walk(); var seen = new HashSet<(int, int)>();
+ for (int k = 0; k < steps; k++)
+ {
+ var q = px[i * steps + k]; int x = Mathf.FloorToInt(q.x), y = Mathf.FloorToInt(q.y);
+ if (!seen.Add((x, y))) continue;
+ walk.On.Add(on.At(x, y)); walk.Off.Add(off.At(x, y)); walk.SignedM.Add(signed[i * steps + k]); walk.Px.Add(new Vector2(x, y));
+ }
+ walks.Add(walk);
+ }
+ return walks;
+ }
+
+ /// <summary>A primary-secondary edge of the proof: the land hex of <paramref name="biome"/> nearest (lon, lat) that is
+ /// Primary with a Secondary east neighbour of the same biome (their shared edge runs north-south).</summary>
+ internal static ((int q, int r) inner, (int q, int r) outer) ProofEdge(MapScene map, double lon, double lat, string biome)
+ {
+ var layer = MapBorders.Current ?? throw new System.InvalidOperationException("show the proof first");
+ var byHex = map.Hexes.hexes.ToDictionary(h => (h.q, h.r));
+ HexJson? best = null; double bestD = double.MaxValue;
+ foreach (var h in map.Hexes.hexes)
+ {
+ if (!h.land || h.biome != biome || layer.StyleOf(layer.RegionOf(h.q, h.r)) != BorderStyle.Primary) continue;
+ if (!byHex.TryGetValue((h.q + 1, h.r), out var e) || !e.land || e.biome != biome) continue;
+ if (layer.StyleOf(layer.RegionOf(e.q, e.r)) != BorderStyle.Secondary) continue;
+ double d = (h.lon - lon) * (h.lon - lon) + (h.lat - lat) * (h.lat - lat);
+ if (d < bestD) { bestD = d; best = h; }
+ }
+ Assert.IsNotNull(best, $"a {biome} primary-secondary edge");
+ return ((best!.q, best.r), (best.q + 1, best.r));
+ }
+
+ /// <summary>Looks at an edge from gameplay03's distance and yaw (the edge's midpoint in the middle of the frame).</summary>
+ internal static void LookAtEdge(MapScene map, CameraRig rig, (int q, int r) inner)
+ {
+ var h = map.Hexes.hexes.First(x => x.q == inner.q && x.r == inner.r);
+ rig.LookAt = map.Frame.ToWorld(h.lon + 0.04, h.lat, 0); rig.Distance = PromoPose.Gameplay03.Distance; rig.Yaw = PromoPose.Gameplay03.Yaw;
+ rig.TopInset = 0; rig.Apply();
+ }
+
+ /// <summary>What one side of a walk shows: its most saturated border pixel (the coloured stripe), its lightest (the light
+ /// stripe), the land under them (borders off), and how far from the edge (px along the walk) the stripes reach.</summary>
+ internal readonly struct Side
+ {
+ public readonly Color Stripe, Light, Land; public readonly float WidthPx;
+ public Side(Color stripe, Color light, Color land, float widthPx) { Stripe = stripe; Light = light; Land = land; WidthPx = widthPx; }
+ }
+
+ /// <summary>The side of the walk with sign <paramref name="sign"/> (-1 inner, +1 outer). The stripe is the pixel that
+ /// gains most in <paramref name="hue"/> over the land, the light stripe the lightest pixel. The width counts the band's
+ /// pixels: those that gained <paramref name="stripeGain"/> in hue (the coloured stripe) or are light stripe colour (all
+ /// channels >= 0.75 and lighter than the land by deltaE76 >= 8: white or cream, which no wash over this land reaches).</summary>
+ internal static Side Read(Walk w, int sign, System.Func<Color, float> hue, float stripeGain = 0.1f)
+ {
+ int stripe = -1, light = -1, band = 0; float bestHue = float.MinValue, bestLuma = float.MinValue;
+ for (int k = 0; k < w.On.Count; k++)
+ {
+ if (Mathf.Sign(w.SignedM[k]) != sign || Mathf.Abs(w.SignedM[k]) > 900f) continue;
+ float gain = hue(w.On[k]) - hue(w.Off[k]);
+ if (gain > bestHue) { bestHue = gain; stripe = k; }
+ float luma = RenderSample.Luma(w.On[k]);
+ if (luma > bestLuma) { bestLuma = luma; light = k; }
+ var c = w.On[k];
+ bool lighter = Mathf.Min(c.r, Mathf.Min(c.g, c.b * 1.6f)) >= 0.75f && luma > RenderSample.Luma(w.Off[k]) && RenderSample.DeltaE(c, w.Off[k]) >= 8f;
+ if (gain >= stripeGain || lighter) band++;
+ }
+ return new Side(stripe < 0 ? Color.clear : w.On[stripe], light < 0 ? Color.clear : w.On[light], stripe < 0 ? Color.clear : w.Off[stripe], band);
+ }
+
+ internal static float Blueness(Color c) => c.b - c.r;
+ internal static float Redness(Color c) => c.r - c.g;
+
+ /// <summary>The promo 03 look at gameplay03's zoom (1920x1080, tilt-shift off), on a coastal-plain edge (flat, as the
+ /// promo's lines are measured): along the whole edge, the Primary side carries a blue stripe and a near-white one, the
+ /// Secondary side a red-orange stripe and a cream one, each band about its promo width (promo 03 at 1920 px: blue +
+ /// white about 8 px, red + cream about 5 px), the Primary band the wider; deep inside either hex nothing changes.</summary>
+ [UnityTest]
+ public IEnumerator BothStylesFollowTheEdgeAtAboutThePromoWidthAtGameplay03()
+ {
+ var (map, cam, rig) = Open();
+ yield return null;
+ RenderSample.TiltShift(false);
+ var layer = BorderProof.Show(map);
+ var (inner, outer) = ProofEdge(map, PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat, "coastal_plain");
+ LookAtEdge(map, rig, inner);
+ var walks = WalkEdge(map, cam, inner, outer, 9, 1920, 1080);
+ var pw = new List<float>(); var sw = new List<float>();
+ foreach (var w in walks)
+ {
+ var p = Read(w, -1, Blueness, 0.45f); var s = Read(w, +1, Redness); // 0.45: the blue wash gains about 0.3
+ TestContext.WriteLine($"primary stripe {p.Stripe} light {p.Light} land {p.Land} width {p.WidthPx:0.0} px | secondary stripe {s.Stripe} light {s.Light} land {s.Land} width {s.WidthPx:0.0} px");
+ Assert.Greater(Blueness(p.Stripe) - Blueness(p.Land), 0.15f, "a blue stripe on the primary side");
+ Assert.Greater(Mathf.Min(p.Light.r, Mathf.Min(p.Light.g, p.Light.b)), 0.80f, "a near-white stripe on the primary side");
+ Assert.Greater(Redness(s.Stripe) - Redness(s.Land), 0.10f, "a red-orange stripe on the secondary side");
+ Assert.Greater(RenderSample.Luma(s.Light), RenderSample.Luma(s.Land) + 0.03f, "a light cream stripe on the secondary side");
+ Assert.Greater(s.Light.r, s.Light.b + 0.15f, "the secondary light stripe is cream, not white");
+ pw.Add(p.WidthPx); sw.Add(s.WidthPx);
+ // 1.2 km or more from the edge (past the widest wash at this zoom) the borders change nothing.
+ for (int k = 0; k < w.On.Count; k++)
+ if (Mathf.Abs(w.SignedM[k]) >= 1200f) Assert.Less(RenderSample.DeltaE(w.On[k], w.Off[k]), 2f, $"{w.SignedM[k]} m from the edge");
+ }
+ float pm = Median(pw), sm = Median(sw);
+ TestContext.WriteLine($"edge {inner}-{outer}: band widths (median px): primary {pm:0.0}, secondary {sm:0.0}");
+ Assert.That(pm, Is.InRange(6f, 11f), "primary band width (promo about 8 px)");
+ Assert.That(sm, Is.InRange(3.5f, 8f), "secondary band width (promo about 5 px)");
+ Assert.Greater(pm, sm, "the primary band is the heavier");
+ }
+
+ /// <summary>Review M6: the early-out (pixels beyond any band's reach fetch nothing) is exact: with it switched off
+ /// (_ScBorders.z) the proof renders pixel for pixel the same, at both promo poses.</summary>
+ [UnityTest]
+ public IEnumerator TheEarlyOutIsExact()
+ {
+ var (map, cam, rig) = Open();
+ yield return null;
+ RenderSample.TiltShift(false);
+ BorderProof.Show(map);
+ try
+ {
+ foreach (var pose in PromoPose.All)
+ {
+ pose.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();
+ var fast = RenderSample.Render(cam, 960, 540);
+ var again = RenderSample.Render(cam, 960, 540); // control: the same settings twice
+ MapBorders.NoEarlyOut = true;
+ var full = RenderSample.Render(cam, 960, 540);
+ MapBorders.NoEarlyOut = false;
+ float control = Changed(fast, again, 0f), exact = Changed(fast, full, 0f), maxDiff = 0f;
+ for (int i = 0; i < fast.Pixels.Length; i++)
+ {
+ Color a = fast.Pixels[i], b = full.Pixels[i];
+ maxDiff = Mathf.Max(maxDiff, Mathf.Max(Mathf.Abs(a.r - b.r), Mathf.Max(Mathf.Abs(a.g - b.g), Mathf.Abs(a.b - b.b))));
+ }
+ TestContext.WriteLine($"{pose.Name}: early-out vs none {exact:P4} of pixels (largest channel step {maxDiff * 255f:0.0}/255); repeat render {control:P4}");
+ Assert.AreEqual(0f, exact, pose.Name);
+ }
+ }
+ finally { MapBorders.NoEarlyOut = false; }
+ }
+
+ /// <summary>Review M7: bands stay on land. At gameplay03 (where the proof's checker boundaries reach the coast inside
+ /// coastal land hexes) no pixel that is clearly water with the borders off changes with them on.</summary>
+ [UnityTest]
+ public IEnumerator BandsStayOffTheWater()
+ {
+ var (map, cam, rig) = Open();
+ yield return null;
+ RenderSample.TiltShift(false);
+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();
+ VisualToggles.Set(MapBorders.ToggleName, false);
+ var off = RenderSample.Render(cam, 1920, 1080);
+ VisualToggles.Set(MapBorders.ToggleName, true);
+ BorderProof.Show(map);
+ Camera.main.transform.Find("BorderBanner").gameObject.SetActive(false); // the label is not a band
+ var on = RenderSample.Render(cam, 1920, 1080);
+ int water = 0, moved = 0, changed = 0;
+ for (int i = 0; i < on.Pixels.Length; i++)
+ {
+ Color a = off.Pixels[i], b = on.Pixels[i];
+ bool diff = Mathf.Max(Mathf.Abs(a.r - b.r), Mathf.Max(Mathf.Abs(a.g - b.g), Mathf.Abs(a.b - b.b))) > 0.02f;
+ if (diff) changed++;
+ if (a.b - a.r > 0.15f && a.g > a.r) { water++; if (diff) moved++; }
+ }
+ TestContext.WriteLine($"gameplay03: {water} water pixels, {moved} moved; {changed} pixels changed in all");
+ Assert.Greater(water, 100000, "the frame shows the sea");
+ Assert.Greater(changed, 5000, "the proof draws");
+ Assert.AreEqual(0, moved);
+ }
+
+ /// <summary>A hex in a region next to a hex in none (here the coast: the proof leaves the sea out) gets no band: the
+ /// middle of such an edge is unchanged.</summary>
+ [UnityTest]
+ public IEnumerator NoBandRunsAgainstAHexInNoRegion()
+ {
+ var (map, cam, rig) = Open();
+ yield return null;
+ RenderSample.TiltShift(false);
+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();
+ var layer = BorderProof.Show(map);
+ var centre = BorderProof.HexAt(map, PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat);
+ // The coastal land hex nearest the centre whose west neighbour is sea, and whose land neighbours share its region,
+ // so no other border is near that edge.
+ var byHex = map.Hexes.hexes.ToDictionary(h => (h.q, h.r));
+ var steps = new[] { (1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1) };
+ (int q, int r)? land = null;
+ foreach (var h in map.Hexes.hexes.OrderBy(h => BorderProof.Distance((h.q, h.r), centre)))
+ {
+ if (!h.land || !byHex.TryGetValue((h.q - 1, h.r), out var west) || west.land) continue;
+ int id = layer.RegionOf(h.q, h.r);
+ if (steps.Any(d => { int o = layer.RegionOf(h.q + d.Item1, h.r + d.Item2); return o != 0 && o != id; })) continue;
+ land = (h.q, h.r); break;
+ }
+ Assert.IsNotNull(land);
+ var walks = WalkEdge(map, cam, land!.Value, (land.Value.q - 1, land.Value.r), 3, 960, 540);
+ int moved = 0, total = 0;
+ foreach (var w in walks)
+ for (int k = 0; k < w.On.Count; k++) { total++; if (RenderSample.DeltaE(w.On[k], w.Off[k]) >= 2f) moved++; }
+ TestContext.WriteLine($"coast edge at ({land.Value.q}, {land.Value.r}) region {layer.RegionOf(land.Value.q, land.Value.r)}: {moved}/{total} pixels moved");
+ Assert.AreEqual(0, moved);
+ }
+
+ /// <summary>At the farthest zoom (diorama02) the outlines stay visible but thin: they change some of the frame and never
+ /// wash it (promo 03's minimap shows thin region outlines at the overview).</summary>
+ [UnityTest]
+ public IEnumerator AtTheOverviewTheBandsAreThin()
+ {
+ var (map, cam, rig) = Open();
+ yield return null;
+ RenderSample.TiltShift(false);
+ PromoPose.Diorama02.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();
+ VisualToggles.Set(MapBorders.ToggleName, false);
+ var off = RenderSample.Render(cam, 1920, 1080);
+ VisualToggles.Set(MapBorders.ToggleName, true);
+ BorderProof.Show(map);
+ var on = RenderSample.Render(cam, 1920, 1080);
+ float share = Changed(on, off, 0.06f);
+ TestContext.WriteLine($"diorama02: {share:P2} of pixels changed by the proof's outlines");
+ Assert.That(share, Is.InRange(0.01f, 0.15f));
+ }
+
+ /// <summary>The same layer and pose give the same pixels (no time, no randomness in the borders).</summary>
+ [UnityTest]
+ public IEnumerator BordersAreDeterministic()
+ {
+ var (map, cam, rig) = Open();
+ yield return null;
+ RenderSample.TiltShift(false);
+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();
+ BorderProof.Show(map);
+ var a = RenderSample.Render(cam, 480, 270);
+ BorderProof.Show(map);
+ var b = RenderSample.Render(cam, 480, 270);
+ Assert.AreEqual(0f, Changed(a, b, 0f));
+ }
+
+ static float Median(List<float> v) { var s = v.OrderBy(x => x).ToList(); return s[s.Count / 2]; }
+}
diff --git a/unity/Assets/Tests/EditMode/BorderTests.cs.meta b/unity/Assets/Tests/EditMode/BorderTests.cs.meta
new file mode 100644
index 000000000..edd71c78c
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/BorderTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 0d22b9406be8b49b08a385bd21b4a648
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/GradeTests.cs b/unity/Assets/Tests/EditMode/GradeTests.cs
index 0e78a50ca..121d1dbcb 100644
--- a/unity/Assets/Tests/EditMode/GradeTests.cs
+++ b/unity/Assets/Tests/EditMode/GradeTests.cs
@@ -100,7 +100,7 @@ public class GradeTests
/// <summary>Review I9: colour-blind players. Under simulated deuteranopia and protanopia (Machado 2009, severity 1), at
/// the gameplay pose: sea against land, the selection against land and the selection against sea stay at deltaE76 >= 15.
- /// (Borders are not drawn in visual v1; the art track's border task adds its colours here.)</summary>
+ /// (The region borders' colours: ColourBlindPlayersTellTheBorderStylesApart.)</summary>
[UnityTest]
public IEnumerator ColourBlindPlayersStillTellCoastAndSelectionApart()
{
@@ -126,6 +126,55 @@ public class GradeTests
map.Select(-9999, -9999);
}
+ /// <summary>promo-borders: colour-blind players tell the two border styles apart and see each against the land, under
+ /// simulated deuteranopia and protanopia (Machado 2009, severity 1), on two grounds at gameplay03's zoom: a proof edge on
+ /// the olive coastal plain and one on the Negev's pale sand, five points along each. Asserted per point: the blue and
+ /// red-orange stripes >= 15 apart; each band's stronger stripe >= 15 from the land (the bound the coast and the
+ /// selection meet above); its two stripes, dark against light, >= 20 apart, so it reads as a line on any ground; and its
+ /// weaker stripe >= 5 (review M5: a band must not quietly read as one stripe), unless the stronger one stands >= 25 from
+ /// the land. Why not >= 15 for both stripes: a light stripe is meant to be light, and on the Negev's pale sand the
+ /// promo's cream stripe melts into the ground for every player (normal vision logged alongside); the band then reads by
+ /// its red-orange stripe, which the 25 bound holds well clear.</summary>
+ [UnityTest]
+ public IEnumerator ColourBlindPlayersTellTheBorderStylesApart()
+ {
+ var (map, cam, rig) = BorderTests.Open();
+ yield return null;
+ try
+ {
+ VisualToggles.Set("tiltshift", false);
+ BorderProof.Show(map);
+ foreach (var (biome, lon, lat) in new[] { ("coastal_plain", PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat), ("desert", 34.80, 30.90) })
+ {
+ var (inner, outer) = BorderTests.ProofEdge(map, lon, lat, biome);
+ BorderTests.LookAtEdge(map, rig, inner);
+ foreach (var w in BorderTests.WalkEdge(map, cam, inner, outer, 5, 1920, 1080))
+ {
+ var p = BorderTests.Read(w, -1, BorderTests.Blueness, 0.45f); var s = BorderTests.Read(w, +1, BorderTests.Redness);
+ TestContext.WriteLine($"{biome} normal vision: secondary colour-land {RenderSample.DeltaE(s.Stripe, s.Land):0.0}, light-land {RenderSample.DeltaE(s.Light, s.Land):0.0}; primary colour-land {RenderSample.DeltaE(p.Stripe, p.Land):0.0}, light-land {RenderSample.DeltaE(p.Light, p.Land):0.0}");
+ foreach (var kind in new[] { RenderSample.Cvd.Deuteranopia, RenderSample.Cvd.Protanopia })
+ {
+ Color Sim(Color c) => RenderSample.SimulateCvd(c, kind);
+ float styles = RenderSample.DeltaE(Sim(p.Stripe), Sim(s.Stripe));
+ float pColour = RenderSample.DeltaE(Sim(p.Stripe), Sim(p.Land)), pLight = RenderSample.DeltaE(Sim(p.Light), Sim(p.Land));
+ float sColour = RenderSample.DeltaE(Sim(s.Stripe), Sim(s.Land)), sLight = RenderSample.DeltaE(Sim(s.Light), Sim(s.Land));
+ float pPair = RenderSample.DeltaE(Sim(p.Stripe), Sim(p.Light)), sPair = RenderSample.DeltaE(Sim(s.Stripe), Sim(s.Light));
+ TestContext.WriteLine($"{biome} {kind}: blue-orange {styles:0.0}; primary colour-land {pColour:0.0}, light-land {pLight:0.0}, colour-light {pPair:0.0}; secondary colour-land {sColour:0.0}, light-land {sLight:0.0}, colour-light {sPair:0.0}");
+ string at = $"{biome} {kind}";
+ Assert.GreaterOrEqual(styles, 15f, $"{at}: the two styles");
+ Assert.GreaterOrEqual(Mathf.Max(pColour, pLight), 15f, $"{at}: the primary band on land");
+ Assert.GreaterOrEqual(Mathf.Max(sColour, sLight), 15f, $"{at}: the secondary band on land");
+ if (Mathf.Max(pColour, pLight) < 25f) Assert.GreaterOrEqual(Mathf.Min(pColour, pLight), 5f, $"{at}: the primary band's weaker stripe");
+ if (Mathf.Max(sColour, sLight) < 25f) Assert.GreaterOrEqual(Mathf.Min(sColour, sLight), 5f, $"{at}: the secondary band's weaker stripe");
+ Assert.GreaterOrEqual(pPair, 20f, $"{at}: the primary band's two stripes");
+ Assert.GreaterOrEqual(sPair, 20f, $"{at}: the secondary band's two stripes");
+ }
+ }
+ }
+ }
+ finally { MapShaderGlobals.PinWaterTime(null); }
+ }
+
/// <summary>Review I9: with the Neutral tonemapper the sunlit desert does not clip: in the Negev (34.9 E, 30.8 N, 60 km)
/// and at the gameplay pose, under 1% of pixels have any channel at the top 8-bit step. The control: with the grade's
/// tonemapper set to None (which also overrides the pipeline profile's Neutral) the graded Negev does clip.</summary>