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.

feat(visual): promo poses, feature toggles, ?vprofile with repeats and ?shot, the machine lock, headed profile and boot budget, art checkpoint

eyalgolan33fb0726ae77
diff --git a/docs/dev-setup.md b/docs/dev-setup.md
index 0bcac05a7..0a4e0d881 100644
--- a/docs/dev-setup.md
+++ b/docs/dev-setup.md
@@ -23,8 +23,15 @@
elsewhere `npx playwright install chromium`).
- 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). Desktop players take `-golden`,
- `-smoke N`, `-profile`, `-camlog`, `-bootlog` and `-navlog`. The console also shows `GAME OK <date> turn <n> hash <h>` at start and `TURN <n> <date> hash <h>` per turn.
+ (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`,
+ `-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`
+ (headless), `... -- uv run tools/headed.py profile --build <build> --dpr 1` (headed; `--dpr 2` is the fill-rate stress
+ proxy) and `... -- uv run tools/headed.py boot --build <build> --runs 3 --baseline <ms>` (the boot budget); wrap Unity
+ batch commands in `uv run tools/machine_lock.py --shared -- ...`; `tools/art_checkpoint.sh [--no-build] <name>` for the
+ owner's side-by-side images.
- A player build rewrites some URP asset and player-setting fields as build-time caches; drop them afterwards with
`git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset`.
- Play a build locally: `python3 -m http.server 8000 --directory unity/Builds/Web-disabled`, then open http://localhost:8000/.
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
new file mode 100644
index 000000000..258acb74c
--- /dev/null
+++ b/docs/visual-v1.md
@@ -0,0 +1,53 @@
+# Visual v1: measurements, budgets and checkpoints
+
+Plan: `docs/superpowers/plans/2026-10-11-statecraft-visual-v1.md`. Promo targets: `promo/final/03-gameplay-1936.png`,
+`promo/final/02-map-diorama.png`. Poses: `PromoPose.Gameplay03` (34.86 E, 32.00 N, 60 km, yaw 10) and
+`PromoPose.Diorama02` (35.05 E, 31.55 N, 250 km, yaw 0).
+
+## How to measure
+- Frame time: `?vprofile` (WebGL) or `-vprofile` (desktop player, quits when done), always under
+ `uv run tools/machine_lock.py --exclusive --wait-unity -- ...` (no other Unity job on the machine). Per pose, every
+ configuration (`all`, each toggle off alone as `-<name>`, `none`) runs 3 times in interleaved orders, 300 frames after
+ 60 warm-up frames; Chrome runs with `--disable-frame-rate-limit --disable-gpu-vsync --force-device-scale-factor=1` (headless through
+ `web_check.py`, headed through `headed.py profile`), so times are not capped at the display rate and headed and headless
+ runs draw the same pixels. Every line states `res=` and
+ the render `scale=`. Read the `PROFILE summary` lines: a feature costs `median(all) - median(-name)`.
+- Boot: `uv run tools/headed.py boot --runs 3 [--baseline MS]` (three cold loads in a headed window; the map-build span is
+ heightmap decoded to map built; `--cpu 4` adds CPU throttling as a cheap low-end proxy).
+- Headed frame time: `uv run tools/headed.py profile --dpr 1` (`--dpr 2` is the fill-rate stress proxy). `--wait-unity`
+ also waits for an interactive Unity editor that has any worktree open (it holds `unity/Temp/UnityLockfile`): close it,
+ or the profile waits.
+- Screenshots: `tools/art_checkpoint.sh [--no-build] <name>` (WebGL `?shot` + editor renders of both tiers + side-by-side
+ images and their deuteranopia/protanopia copies under `captures/visual/<name>/`, git-ignored; rows in the main
+ checkout's `captures/visual/art-log.tsv`).
+
+## Budgets (proposed; ratified in Task 10)
+Measured on the development Mac (Apple silicon, integrated GPU), 1920x1080 at DPR 1, Chrome for Testing:
+- headless, all features on: median p95 <= 16.7 ms at both poses, and median(all) - median(none) <= 8 ms;
+- each feature: median(all) - median(-feature) <= 2.5 ms (tilt-shift <= 1.5 ms, labels <= 1 ms); a cost counts as over only
+ when it exceeds the budget plus the larger of the two spreads;
+- headed numbers are recorded, plus a DPR-2 headed run in Task 10 as a fill-rate stress proxy for weaker GPUs; the 30 fps
+ floor for an integrated-GPU laptop (research notes 2.3) is 33 ms p95;
+- boot: the map-build span grows by at most 1,000 ms over the Task 1 baseline (median of 3).
+
+## Baseline (Task 1, before any visual change)
+| Run | Lines |
+|---|---|
+| headless | `PROFILE summary visual=all pose=gameplay03 runs=3 median_avg_ms=2.42 spread_ms=0.68 median_p95_ms=4.00`<br>`PROFILE summary visual=none pose=gameplay03 runs=3 median_avg_ms=2.39 spread_ms=0.86 median_p95_ms=4.00`<br>`PROFILE summary visual=all pose=diorama02 runs=3 median_avg_ms=5.32 spread_ms=0.02 median_p95_ms=7.00`<br>`PROFILE summary visual=none pose=diorama02 runs=3 median_avg_ms=5.33 spread_ms=0.09 median_p95_ms=7.00`<br>run line: `PROFILE visual=all pose=gameplay03 res=1920x937 scale=0.80 rep=0 frames=300 avg_ms=1.73 p95_ms=2.00` |
+| headed (DPR 1) | `PROFILE summary visual=all pose=gameplay03 runs=3 median_avg_ms=1.45 spread_ms=1.16 median_p95_ms=2.00`<br>`PROFILE summary visual=none pose=gameplay03 runs=3 median_avg_ms=1.46 spread_ms=0.33 median_p95_ms=2.00`<br>`PROFILE summary visual=all pose=diorama02 runs=3 median_avg_ms=4.58 spread_ms=0.04 median_p95_ms=6.00`<br>`PROFILE summary visual=none pose=diorama02 runs=3 median_avg_ms=4.58 spread_ms=0.01 median_p95_ms=7.00`<br>run line: `PROFILE visual=all pose=gameplay03 res=1728x860 scale=0.80 rep=0 frames=300 avg_ms=1.45 p95_ms=2.00` |
+| boot | `BOOT map_build_ms median=450 runs=3` |
+
+Notes on the baseline (Task 1, commit base `7e610aa`):
+- **Resolution.** Neither run drew 1920x1080. Headless (`--headless=new --window-size=1920,1080`) reports `res=1920x937`:
+ the window size is the outer window, and the template's full-viewport canvas loses 143 px to the emulated browser UI.
+ The headed window was clamped by the laptop screen to `res=1728x860`. Compare like with like (same tool, same `res=`)
+ until this is settled.
+- **Headed stall.** The first headed attempt stopped producing frames after 4 of 12 runs (presumably Chrome throttling
+ a hidden or occluded window) and timed out at 1,800 s; an unchanged retry (`--timeout 300`) completed. Keep the
+ headed window visible while profiling.
+- No toggles exist yet, so `all` and `none` are the same scene: their difference (and the spreads) is the noise floor.
+
+## Checkpoints
+| Task | Name | Images | Owner verdict |
+|---|---|---|---|
+| 1 | t01-before | captures/visual/t01-before/*-compare*.png | (owner) |
diff --git a/tools/README.md b/tools/README.md
index 365ade20c..85f2541ac 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -16,9 +16,15 @@ Offline data tools (uv inline-script Python). Run from the repo root.
- `package_release.py` zips a Brotli WebGL build for sharing (`unity/Builds/statecraft-m3-web.zip`) and refuses
(exit 1) until every sensitive event is `sensitivity-reviewed` (docs/m3-release.md).
- `preview_map.py` renders the geography check image `tools/.cache/map-preview.png`.
+- `art_compare.py` puts screenshots next to the promo image of their pose, writes deuteranopia and protanopia copies and
+ logs rough colour numbers; `art_checkpoint.sh [--no-build] <name>` builds WebGL, takes the screenshots
+ (`web_check.py --shots`) and runs it (docs/visual-v1.md).
+- `machine_lock.py` serialises frame-time measurements against every other Unity job on the machine (all worktrees,
+ batch runs and open editors).
- `headed.py` drives a WebGL build in a headed Chrome for Testing over CDP (real GPU, real mouse events, a temporary
profile deleted on exit): `boot` (?bootlog phase timings, optional CPU throttling), `navpairs` (same-frame click pairs
- under ?navlog) and `loadshot` (screenshots during the load). Its browser test runs only with `pytest --headed`.
+ under ?navlog), `loadshot` (screenshots during the load) and `profile` (visual v1's `?vprofile` in a headed window at a
+ chosen DPR); `boot --runs N --baseline MS` checks the boot budget. Its browser test runs only with `pytest --headed`.
## Running the tests
@@ -28,7 +34,7 @@ Run from the repo root; this installs every pinned dependency (rasterio included
uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 pytest tools/tests -q
```
-Expected: `109 passed, 1 skipped` (the skipped one is the headed browser check; add `--headed` and `--with websockets==15.0.1` to run it). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
+Expected: `129 passed, 1 skipped` (the skipped one is the headed browser check; add `--headed` and `--with websockets==15.0.1` to run it). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
## Required attribution (Copernicus DEM licence, modified data)
diff --git a/tools/art_checkpoint.sh b/tools/art_checkpoint.sh
new file mode 100755
index 000000000..952ebab6e
--- /dev/null
+++ b/tools/art_checkpoint.sh
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+# Owner art checkpoint (non-blocking): a WebGL build (skipped with --no-build when the task has just built), screenshots at
+# the promo poses from the player itself (?shot: the web tier with its UI and labels), editor renders of both quality
+# tiers, and side-by-side images against the promo with colour-blind simulations. Re-checks both golden hashes in the same
+# 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. Usage: tools/art_checkpoint.sh [--no-build] <checkpoint-name>
+set -euo pipefail
+build=1
+if [[ "${1:-}" == "--no-build" ]]; then build=0; shift; fi
+name="${1:?usage: tools/art_checkpoint.sh [--no-build] <checkpoint-name>}"
+root="$(git rev-parse --show-toplevel)"
+cd "$root"
+main_root="$(cd "$(git rev-parse --path-format=absolute --git-common-dir)/.." && pwd)"
+: "${UNITY:?set UNITY as in docs/dev-setup.md}"
+shared() { uv run tools/machine_lock.py --shared -- "$@"; }
+if [[ $build == 1 ]]; then
+ if ! git diff --quiet -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset; then
+ echo "art_checkpoint: stage your changes under unity/Assets/Settings and ProjectSettings.asset first (the build rewrites them and this script restores them from the index)" >&2
+ exit 2
+ fi
+ shared "$UNITY" -batchmode -quit -projectPath unity -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression disabled -logFile "$root/unity-build-web-art.log"
+ git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset
+ if grep -n "Shader error" "$root/unity-build-web-art.log"; then echo "art_checkpoint: shader errors in the WebGL build" >&2; exit 1; fi
+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" --expect "GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07" --expect "GOLDEN OK 1952 73590e324f19e9959a455a4da79e93d7089dfcf283c13aac02af6b0a624b9767" --expect "SHOT done" --shots "$out" \
+ --fail 'GOLDEN FAIL|SMOKE FAIL|BOOT FAIL|Statecraft/.*(not supported|Unsupported)|(not supported|Unsupported).*Statecraft/'
+for pose in gameplay03 diorama02; do
+ [[ -s "$out/$pose.png" ]] || { echo "art_checkpoint: $out/$pose.png is missing" >&2; exit 1; }
+done
+shared "$UNITY" -batchmode -quit -projectPath unity -buildTarget OSXUniversal -executeMethod MapCapture.Promo -captureDir "$root/$out/editor" -logFile "$root/unity-capture-promo.log"
+git checkout -- unity/ProjectSettings/QualitySettings.asset # SetQualityLevel may have written m_CurrentQuality
+uv run tools/art_compare.py "$out" "$name" --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/tools/art_compare.py b/tools/art_compare.py
new file mode 100644
index 000000000..0f7b05263
--- /dev/null
+++ b/tools/art_compare.py
@@ -0,0 +1,109 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = ["numpy==2.5.3", "pillow==12.3.0"]
+# ///
+"""Owner art checkpoint: puts each screenshot next to the promo image its pose copies, prints rough numbers, and writes
+colour-blind simulations of each comparison.
+
+Usage: uv run tools/art_compare.py <shots-dir> <checkpoint-name> [--log PATH]
+For every PNG under <shots-dir> whose name ends in a pose (gameplay03, diorama02), writes <name>-compare.png beside it
+(screenshot left, promo right, a caption with the numbers), <name>-compare-deuteranopia.png and
+<name>-compare-protanopia.png (Machado, Oliveira and Fernandes 2009, severity 1), and appends a row to the art log
+(default captures/visual/art-log.tsv; art_checkpoint.sh points every worktree at the main checkout's): checkpoint, image,
+saturation, contrast (luma std), warmth (mean R - B), and the palette distance to the promo (total variation between
+8x8x8 RGB histograms; 0 = same palette, 1 = disjoint). The numbers inform the owner's review. Exit code 2 when a
+screenshot is near-uniform (luma std < 0.01: a black or blank WebGL capture), 1 when no screenshot matched a pose."""
+import argparse
+import sys
+from pathlib import Path
+
+import numpy as np
+from PIL import Image, ImageDraw
+
+ROOT = Path(__file__).resolve().parents[1]
+PROMOS = {"gameplay03": ROOT / "promo" / "final" / "03-gameplay-1936.png",
+ "diorama02": ROOT / "promo" / "final" / "02-map-diorama.png"}
+CAPTION_PX, GAP_PX, HEIGHT_PX = 44, 16, 720
+UNIFORM_STD = 0.01
+MACHADO = {
+ "deuteranopia": np.array([[0.367322, 0.860646, -0.227968], [0.280085, 0.672501, 0.047413], [-0.011820, 0.042940, 0.968881]]),
+ "protanopia": np.array([[0.152286, 1.052583, -0.204868], [0.114503, 0.786281, 0.099216], [-0.003882, -0.048116, 1.051998]]),
+}
+
+
+def metrics(img: Image.Image) -> dict[str, float]:
+ rgb = img.convert("RGB")
+ a = np.asarray(rgb, dtype=np.float32) / 255.0
+ s = np.asarray(rgb.convert("HSV"), dtype=np.float32)[..., 1] / 255.0
+ luma = 0.2126 * a[..., 0] + 0.7152 * a[..., 1] + 0.0722 * a[..., 2]
+ return {"saturation": float(s.mean()), "contrast": float(luma.std()), "warmth": float((a[..., 0] - a[..., 2]).mean())}
+
+
+def histogram_distance(a: Image.Image, b: Image.Image, bins: int = 8) -> float:
+ def hist(img: Image.Image) -> np.ndarray:
+ x = (np.asarray(img.convert("RGB").resize((256, 256)), dtype=np.int64) // (256 // bins)).reshape(-1, 3)
+ h = np.bincount(x[:, 0] * bins * bins + x[:, 1] * bins + x[:, 2], minlength=bins ** 3).astype(np.float64)
+ return h / h.sum()
+ return float(0.5 * np.abs(hist(a) - hist(b)).sum())
+
+
+def simulate_cvd(img: Image.Image, kind: str) -> Image.Image:
+ a = np.asarray(img.convert("RGB"), dtype=np.float64) / 255.0
+ lin = np.where(a <= 0.04045, a / 12.92, ((a + 0.055) / 1.055) ** 2.4)
+ out = np.clip(lin @ MACHADO[kind].T, 0.0, 1.0)
+ srgb = np.where(out <= 0.0031308, out * 12.92, 1.055 * out ** (1 / 2.4) - 0.055)
+ return Image.fromarray(np.round(srgb * 255).astype(np.uint8), "RGB")
+
+
+def compose(shot: Image.Image, promo: Image.Image, title: str) -> Image.Image:
+ def fit(img: Image.Image) -> Image.Image:
+ return img.convert("RGB").resize((round(img.width * HEIGHT_PX / img.height), HEIGHT_PX), Image.LANCZOS)
+ left, right = fit(shot), fit(promo)
+ out = Image.new("RGB", (left.width + GAP_PX + right.width, CAPTION_PX + HEIGHT_PX), (14, 22, 38))
+ out.paste(left, (0, CAPTION_PX))
+ out.paste(right, (left.width + GAP_PX, CAPTION_PX))
+ ImageDraw.Draw(out).text((12, 14), title, fill=(230, 214, 170))
+ return out
+
+
+def main(argv: list[str], root: Path = ROOT, promos: dict[str, Path] = PROMOS) -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("shots", type=Path)
+ ap.add_argument("name")
+ ap.add_argument("--log", type=Path)
+ a = ap.parse_args(argv[1:])
+ log = a.log or root / "captures" / "visual" / "art-log.tsv"
+ log.parent.mkdir(parents=True, exist_ok=True)
+ rows, uniform = 0, []
+ for path in sorted(a.shots.rglob("*.png")):
+ if "-compare" in path.stem:
+ continue
+ pose = next((p for p in promos if path.stem.endswith(p)), None)
+ if pose is None:
+ continue
+ shot, promo = Image.open(path), Image.open(promos[pose])
+ m, p, d = metrics(shot), metrics(promo), histogram_distance(shot, promo)
+ if m["contrast"] < UNIFORM_STD:
+ uniform.append(path)
+ print(f"FAIL: {path} is near-uniform (luma std {m['contrast']:.4f}): the capture is blank")
+ continue
+ title = (f"{a.name} | {path.stem} (left) vs {promos[pose].name} (right) | saturation {m['saturation']:.2f}/{p['saturation']:.2f}"
+ f" contrast {m['contrast']:.3f}/{p['contrast']:.3f} warmth {m['warmth']:.3f}/{p['warmth']:.3f} palette distance {d:.2f}")
+ pair = compose(shot, promo, title)
+ pair.save(path.with_name(path.stem + "-compare.png"))
+ for kind in MACHADO:
+ simulate_cvd(pair, kind).save(path.with_name(f"{path.stem}-compare-{kind}.png"))
+ with log.open("a") as f:
+ f.write("\t".join([a.name, str(path), f"{m['saturation']:.4f}", f"{m['contrast']:.4f}", f"{m['warmth']:.4f}", f"{d:.4f}"]) + "\n")
+ print("ART " + title)
+ rows += 1
+ if uniform:
+ return 2
+ if rows == 0:
+ print(f"no screenshot named after a pose ({', '.join(promos)}) under {a.shots}")
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/tools/headed.py b/tools/headed.py
index c3fb90faf..73480ce45 100644
--- a/tools/headed.py
+++ b/tools/headed.py
@@ -10,16 +10,19 @@ serves a WebGL build with web_check's handler, and drives it over one browser-le
boot boot-phase timings from ?bootlog (optionally under CPU throttling): where the start-up time goes
navpairs pairs of clicks on a screen button and a second target, d ms apart or in one frame, under ?navlog
loadshot screenshots during the load and once ready (the loading line, or the boot-failure line)
+ profile visual v1's ?vprofile in a headed 1920x1080 window at --dpr (frame rate uncapped)
Run from the repo root, e.g.:
uv run tools/headed.py boot --build unity/Builds/Web-disabled --cpu 8
uv run tools/headed.py navpairs --build unity/Builds/Web-disabled --cpu 20
+ uv run tools/headed.py boot --build unity/Builds/Web-disabled --runs 3 --baseline 5400
Coordinates are CSS pixels for a 1568x752 window (the playtest window). Used for playtest 2 (P2-1, P2-4) and the final
review evidence; the EditMode tests are the regression guard, this is the in-browser check.
"""
import argparse
import asyncio
import base64
+import statistics
import functools
import http.server
import json
@@ -46,9 +49,48 @@ def burst_events(points):
for (x, y) in points for t in ("mouseMoved", "mousePressed", "mouseReleased")]
+BOOT_PHASE = re.compile(r"BOOT phase=(.+?) at=(\d+) ms dt=(\d+) ms")
+
+
+def browser_flags(profile: str, width: int, height: int, dpr: float | None = None, uncapped: bool = False) -> list[str]:
+ """Chrome flags for a headed run. dpr forces the device pixel ratio (1: the same pixels as a headless run; 2: the
+ visual v1 fill-rate stress proxy); uncapped lifts the display's frame-rate cap for frame-time profiles."""
+ flags = ["--use-angle=metal", "--remote-debugging-port=0", f"--user-data-dir={profile}", "--no-first-run",
+ "--no-default-browser-check", f"--window-size={width},{height}"]
+ if dpr is not None:
+ flags.append(f"--force-device-scale-factor={dpr:g}")
+ if uncapped:
+ flags += ["--disable-frame-rate-limit", "--disable-gpu-vsync"]
+ return flags + ["about:blank"]
+
+
+def boot_phases(lines) -> list[tuple[str, int, int]]:
+ """(name, at ms, dt ms) of every ?bootlog phase among console lines."""
+ return [(m.group(1), int(m.group(2)), int(m.group(3))) for m in map(BOOT_PHASE.search, lines) if m]
+
+
+def map_build_ms(phases) -> int:
+ """The map-build span (visual v1 boot budget): at(map built) - at(heightmap decoded) + dt(heightmap decoded), from the
+ end of the content fetch to the map's last phase."""
+ first: dict[str, tuple[int, int]] = {}
+ for name, at, dt in phases:
+ first.setdefault(name, (at, dt))
+ for need in ("heightmap decoded", "map built"):
+ if need not in first:
+ raise ValueError(f"no '{need}' phase (was ?bootlog in the query?)")
+ return first["map built"][0] - first["heightmap decoded"][0] + first["heightmap decoded"][1]
+
+
+def over_budget(spans, baseline, budget) -> tuple[float, bool]:
+ """(median span, whether it exceeds baseline + budget); never over without a baseline."""
+ median = statistics.median(spans)
+ return median, baseline is not None and median > baseline + budget
+
+
class Browser:
- def __init__(self, build: Path, port=8766, width=WINDOW[0], height=WINDOW[1]):
+ def __init__(self, build: Path, port=8766, width=WINDOW[0], height=WINDOW[1], dpr=None, uncapped=False):
self.build, self.port, self.size = Path(build), port, (width, height)
+ self.dpr, self.uncapped = dpr, uncapped
self.profile = tempfile.mkdtemp(prefix="statecraft-headed-")
self.next_id, self.pending, self.console = 0, {}, []
@@ -58,8 +100,7 @@ class Browser:
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.base = f"http://localhost:{self.port}/"
w, h = self.size
- flags = ["--use-angle=metal", "--remote-debugging-port=0", f"--user-data-dir={self.profile}", "--no-first-run",
- "--no-default-browser-check", f"--window-size={w},{h}", "about:blank"]
+ flags = browser_flags(self.profile, w, h, self.dpr, self.uncapped)
self.proc = subprocess.Popen([str(web_check.find_chrome()), *flags], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
port_file = Path(self.profile) / "DevToolsActivePort"
for _ in range(200):
@@ -143,14 +184,37 @@ class Browser:
async def boot(args):
- async with Browser(args.build) as b:
- sid = await b.open("bootlog", args.cpu)
- await b.wait_for(sid, r"^GAME OK")
- origin = (await b.send("Runtime.evaluate", {"expression": "performance.timeOrigin", "returnByValue": True}, session=sid))["result"]["value"]
- print(f"CPU {args.cpu}x")
- for s, text, ts in b.console:
- if s == sid and (text.startswith("BOOT") or text.startswith("GAME OK")):
- print(f"{ts - origin:8.0f} ms {text[:140]}")
+ """?bootlog timings, args.runs times (each in a fresh profile: a cold load), then the median map-build span; 1 when it
+ exceeds --baseline + --budget."""
+ spans = []
+ for run in range(args.runs):
+ async with Browser(args.build) as b:
+ sid = await b.open("bootlog", args.cpu)
+ await b.wait_for(sid, r"^GAME OK")
+ origin = (await b.send("Runtime.evaluate", {"expression": "performance.timeOrigin", "returnByValue": True}, session=sid))["result"]["value"]
+ print(f"CPU {args.cpu}x, run {run + 1} of {args.runs}")
+ for s, text, ts in b.console:
+ if s == sid and (text.startswith("BOOT") or text.startswith("GAME OK")):
+ print(f"{ts - origin:8.0f} ms {text[:140]}")
+ span = map_build_ms(boot_phases(b.lines(sid)))
+ print(f"BOOT map build {span} ms")
+ spans.append(span)
+ median, over = over_budget(spans, args.baseline, args.budget)
+ print(f"BOOT map_build_ms median={median:.0f} runs={len(spans)}")
+ if over:
+ print(f"OVER BUDGET: {median:.0f} ms > baseline {args.baseline:.0f} + {args.budget:.0f} ms")
+ return 1 if over else 0
+
+
+async def profile(args):
+ """?vprofile (visual v1) in a headed 1920x1080 window at --dpr, frame rate uncapped; prints the PROFILE lines."""
+ async with Browser(args.build, width=1920, height=1080, dpr=args.dpr, uncapped=True) as b:
+ sid = await b.open("vprofile", args.cpu)
+ await b.wait_for(sid, r"^PROFILE visual done", timeout=args.timeout)
+ for line in b.lines(sid):
+ if line.startswith("PROFILE"):
+ print(line)
+ return 0
async def navpairs(args):
@@ -191,13 +255,19 @@ async def loadshot(args):
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- p.add_argument("command", choices=["boot", "navpairs", "loadshot"])
+ p.add_argument("command", choices=["boot", "navpairs", "loadshot", "profile"])
p.add_argument("--build", default=str(REPO / "unity/Builds/Web-disabled"))
p.add_argument("--cpu", type=float, default=1.0, help="CPU throttling rate (1 = none)")
p.add_argument("--out", default="headed", help="screenshot path prefix (loadshot)")
+ p.add_argument("--runs", type=int, default=1, help="boot: cold loads to take the median of")
+ p.add_argument("--baseline", type=float, help="boot: exit 1 when the median map-build span exceeds this + --budget (ms)")
+ p.add_argument("--budget", type=float, default=1000, help="boot: allowed growth over --baseline (ms)")
+ p.add_argument("--dpr", type=float, default=1.0, help="profile: device pixel ratio (2 = the fill-rate stress proxy)")
+ p.add_argument("--timeout", type=float, default=1800, help="profile: seconds to wait for PROFILE visual done")
args = p.parse_args(argv)
- asyncio.run({"boot": boot, "navpairs": navpairs, "loadshot": loadshot}[args.command](args))
+ result = asyncio.run({"boot": boot, "navpairs": navpairs, "loadshot": loadshot, "profile": profile}[args.command](args))
+ return result if isinstance(result, int) else 0
if __name__ == "__main__":
- main()
+ sys.exit(main())
diff --git a/tools/machine_lock.py b/tools/machine_lock.py
new file mode 100644
index 000000000..32920778e
--- /dev/null
+++ b/tools/machine_lock.py
@@ -0,0 +1,91 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+"""One Mac, several worktrees: frame-time runs must not share the machine with Unity imports, builds, test runs or an open
+Unity editor.
+
+Usage: uv run tools/machine_lock.py (--shared | --exclusive) [--wait-unity] [--timeout SECONDS] -- <command> [args...]
+--shared takes the machine lock shared (Unity builds, captures and edit-mode runs); --exclusive takes it alone (frame-time
+profiles and boot budgets) and, with --wait-unity, then waits until no Unity is left running: no batch-mode Unity process,
+and no process (an interactive editor included) holding any worktree's unity/Temp/UnityLockfile. The lock file is
+~/.cache/statecraft/machine.lock (fcntl.flock; STATECRAFT_MACHINE_LOCK overrides it), shared by every worktree of this
+user. Exit code: the command's, or 3 when --wait-unity times out."""
+import argparse
+import fcntl
+import os
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+LOCK = Path(os.environ.get("STATECRAFT_MACHINE_LOCK", str(Path.home() / ".cache" / "statecraft" / "machine.lock")))
+UNITY_BATCH = "Unity.app/Contents/MacOS/Unity .*-batchmode"
+
+
+def parse(argv: list[str]) -> argparse.Namespace:
+ ap = argparse.ArgumentParser()
+ mode = ap.add_mutually_exclusive_group(required=True)
+ mode.add_argument("--shared", action="store_true")
+ mode.add_argument("--exclusive", action="store_true")
+ ap.add_argument("--wait-unity", action="store_true")
+ ap.add_argument("--timeout", type=float, default=3600)
+ ap.add_argument("command", nargs=argparse.REMAINDER)
+ a = ap.parse_args(argv)
+ if a.command and a.command[0] == "--":
+ a.command = a.command[1:]
+ if not a.command:
+ ap.error("no command after --")
+ return a
+
+
+def unity_batch_pids() -> list[int]:
+ r = subprocess.run(["pgrep", "-f", UNITY_BATCH], capture_output=True, text=True)
+ return [int(p) for p in r.stdout.split() if p.isdigit() and int(p) != os.getpid()]
+
+
+def worktrees() -> list[Path]:
+ """Every worktree of this repository, so an editor open in any of them is seen."""
+ r = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, text=True)
+ return [Path(line[len("worktree "):]) for line in r.stdout.splitlines() if line.startswith("worktree ")]
+
+
+def lockfile_holders(roots: list[Path], lsof=None) -> list[int]:
+ """Pids holding any root's unity/Temp/UnityLockfile: every Unity editor with that project open, interactive or batch."""
+ files = [str(p / "unity" / "Temp" / "UnityLockfile") for p in roots if (p / "unity" / "Temp" / "UnityLockfile").exists()]
+ if not files:
+ return []
+ run = lsof or (lambda fs: subprocess.run(["lsof", "-t", *fs], capture_output=True, text=True).stdout)
+ return sorted({int(p) for p in run(files).split() if p.isdigit()})
+
+
+def unity_pids() -> list[int]:
+ return sorted(set(unity_batch_pids()) | set(lockfile_holders(worktrees())))
+
+
+def wait_for_unity(timeout: float, pids=unity_pids, sleep=time.sleep, now=time.monotonic) -> bool:
+ deadline = now() + timeout
+ while True:
+ busy = pids()
+ if not busy:
+ return True
+ if now() >= deadline:
+ return False
+ print(f"machine_lock: waiting for Unity processes {busy} (batch runs, or an editor with a worktree open)", flush=True)
+ sleep(10)
+
+
+def main(argv: list[str] | None = None) -> int:
+ a = parse(sys.argv[1:] if argv is None else argv)
+ LOCK.parent.mkdir(parents=True, exist_ok=True)
+ with open(LOCK, "a+") as f:
+ print(f"machine_lock: taking the machine lock ({'exclusive' if a.exclusive else 'shared'})", flush=True)
+ fcntl.flock(f, fcntl.LOCK_EX if a.exclusive else fcntl.LOCK_SH)
+ if a.wait_unity and not wait_for_unity(a.timeout):
+ print("machine_lock: timed out waiting for Unity")
+ return 3
+ return subprocess.call(a.command)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/tests/test_art_compare.py b/tools/tests/test_art_compare.py
new file mode 100644
index 000000000..be784b609
--- /dev/null
+++ b/tools/tests/test_art_compare.py
@@ -0,0 +1,66 @@
+import numpy as np
+from PIL import Image
+
+import art_compare as ac
+
+
+def solid(rgb, size=(64, 36)):
+ return Image.new("RGB", size, rgb)
+
+
+def noisy(size=(192, 108), seed=1):
+ return Image.fromarray(np.random.default_rng(seed).integers(0, 255, (size[1], size[0], 3), dtype=np.uint8), "RGB")
+
+
+def test_metrics_read_saturation_contrast_and_warmth():
+ grey = ac.metrics(solid((128, 128, 128)))
+ assert grey["saturation"] == 0 and grey["contrast"] == 0 and grey["warmth"] == 0
+ red = ac.metrics(solid((255, 0, 0)))
+ assert red["saturation"] > 0.99 and red["warmth"] > 0.99
+
+
+def test_palette_distance_is_zero_for_the_same_image_and_one_for_disjoint_palettes():
+ a = solid((200, 150, 60))
+ assert ac.histogram_distance(a, a) == 0
+ assert ac.histogram_distance(solid((0, 0, 0)), solid((255, 255, 255))) == 1
+
+
+def test_compose_puts_both_images_at_the_same_height_under_a_caption():
+ out = ac.compose(solid((10, 20, 30), (1920, 1080)), solid((200, 100, 50), (2752, 1536)), "t")
+ assert out.height == ac.CAPTION_PX + ac.HEIGHT_PX
+ assert out.width == round(1920 * ac.HEIGHT_PX / 1080) + ac.GAP_PX + round(2752 * ac.HEIGHT_PX / 1536)
+
+
+def test_colour_blind_simulation_keeps_greys_and_merges_red_with_green():
+ grey = np.asarray(ac.simulate_cvd(solid((128, 128, 128)), "deuteranopia"), dtype=int)
+ assert np.abs(grey - 128).max() <= 1
+ red = np.asarray(ac.simulate_cvd(solid((200, 30, 30)), "protanopia"), dtype=int)[0, 0]
+ green = np.asarray(ac.simulate_cvd(solid((30, 160, 30)), "protanopia"), dtype=int)[0, 0]
+ assert abs(int(red[0]) - int(green[0])) < 100 # 170 apart before simulation
+
+
+def test_main_pairs_each_pose_with_its_promo_logs_a_row_and_writes_cvd_copies(tmp_path):
+ promo = tmp_path / "promo.png"; noisy((275, 153), 2).save(promo)
+ shots = tmp_path / "shots"; (shots / "editor").mkdir(parents=True)
+ noisy().save(shots / "gameplay03.png")
+ noisy(seed=3).save(shots / "editor" / "PC-diorama02.png")
+ noisy(seed=4).save(shots / "unrelated.png")
+ log = tmp_path / "elsewhere" / "art-log.tsv"
+ code = ac.main(["art_compare.py", str(shots), "task-x", "--log", str(log)], root=tmp_path,
+ promos={"gameplay03": promo, "diorama02": promo})
+ assert code == 0
+ for stem in ("gameplay03", "editor/PC-diorama02"):
+ for suffix in ("-compare.png", "-compare-deuteranopia.png", "-compare-protanopia.png"):
+ assert (shots / (stem + suffix)).exists(), stem + suffix
+ rows = log.read_text().splitlines()
+ assert len(rows) == 2 and all(r.startswith("task-x\t") for r in rows)
+ assert ac.main(["art_compare.py", str(shots), "again", "--log", str(log)], root=tmp_path,
+ promos={"gameplay03": promo, "diorama02": promo}) == 0
+ assert not (shots / "gameplay03-compare-compare.png").exists()
+
+
+def test_a_uniform_screenshot_fails(tmp_path):
+ promo = tmp_path / "promo.png"; noisy().save(promo)
+ shots = tmp_path / "shots"; shots.mkdir()
+ solid((0, 0, 0), (192, 108)).save(shots / "gameplay03.png") # a black capture (the WebGL readback failed)
+ assert ac.main(["art_compare.py", str(shots), "t"], root=tmp_path, promos={"gameplay03": promo, "diorama02": promo}) == 2
diff --git a/tools/tests/test_headed.py b/tools/tests/test_headed.py
index 6df7d862f..d2c1b5a6a 100644
--- a/tools/tests/test_headed.py
+++ b/tools/tests/test_headed.py
@@ -24,3 +24,29 @@ def test_every_click_in_one_frame_counts_once():
"""Playtest 2, P2-4, in a real browser: two clicks in one frame each toggle Why exactly once."""
toggles = asyncio.run(headed.navpairs(argparse.Namespace(build=str(BUILD), cpu=1.0)))
assert toggles == {"Why+Why": 2, "Why+map-under-panel": 1, "Why+option": 1}
+
+
+def test_boot_phases_and_the_map_build_span():
+ lines = ["BOOT phase=player started at=900 ms dt=900 ms", "BOOT phase=heightmap decoded at=5200 ms dt=1300 ms",
+ "GAME OK 1948-05-15 turn 0 hash 00", "BOOT phase=map built at=9400 ms dt=300 ms"]
+ phases = headed.boot_phases(lines)
+ assert phases[0] == ("player started", 900, 900)
+ assert headed.map_build_ms(phases) == 9400 - 5200 + 1300
+ with pytest.raises(ValueError, match="map built"):
+ headed.map_build_ms(phases[:2])
+
+
+def test_the_boot_budget_compares_the_median_with_the_baseline():
+ assert headed.over_budget([5500, 5700, 5900], 4800, 1000) == (5700, False) # 5700 <= 5800
+ assert headed.over_budget([5500, 5700, 5900], 4600, 1000) == (5700, True) # 5700 > 5600
+ assert headed.over_budget([5500], None, 1000) == (5500, False)
+
+
+def test_profile_windows_are_uncapped_at_the_requested_dpr():
+ plain = headed.browser_flags("/tmp/p", 1568, 752)
+ assert "--use-angle=metal" in plain and "--window-size=1568,752" in plain and plain[-1] == "about:blank"
+ assert not any("scale-factor" in f or "frame-rate" in f for f in plain), "navpairs and boot keep their old flags"
+ prof = headed.browser_flags("/tmp/p", 1920, 1080, dpr=2, uncapped=True)
+ for flag in ("--force-device-scale-factor=2", "--disable-frame-rate-limit", "--disable-gpu-vsync", "--window-size=1920,1080"):
+ assert flag in prof
+ assert prof[-1] == "about:blank"
diff --git a/tools/tests/test_machine_lock.py b/tools/tests/test_machine_lock.py
new file mode 100644
index 000000000..480bd6cc8
--- /dev/null
+++ b/tools/tests/test_machine_lock.py
@@ -0,0 +1,65 @@
+import fcntl
+import os
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+import machine_lock as ml
+
+
+def test_the_command_follows_the_double_dash_and_a_mode_is_required():
+ a = ml.parse(["--exclusive", "--wait-unity", "--", "uv", "run", "tools/web_check.py", "--query", "vprofile"])
+ assert a.exclusive and a.wait_unity and a.command == ["uv", "run", "tools/web_check.py", "--query", "vprofile"]
+ assert ml.parse(["--shared", "--", "echo", "x"]).command == ["echo", "x"]
+ with pytest.raises(SystemExit):
+ ml.parse(["--", "echo"])
+ with pytest.raises(SystemExit):
+ ml.parse(["--shared"])
+
+
+def test_waiting_ends_when_no_unity_process_is_left():
+ seen = iter([[101, 102], [102], []])
+ clock = iter(range(100))
+ assert ml.wait_for_unity(600, pids=lambda: next(seen), sleep=lambda s: None, now=lambda: next(clock)) is True
+
+
+def test_waiting_gives_up_at_the_timeout():
+ clock = iter(range(0, 1000, 100))
+ assert ml.wait_for_unity(250, pids=lambda: [7], sleep=lambda s: None, now=lambda: next(clock)) is False
+
+
+def test_a_shared_holder_really_blocks_an_exclusive_lock(tmp_path):
+ lock = tmp_path / "machine.lock"
+ env = {**os.environ, "STATECRAFT_MACHINE_LOCK": str(lock)}
+ child = subprocess.Popen([sys.executable, ml.__file__, "--shared", "--", sys.executable, "-c", "import time; time.sleep(5)"],
+ env=env, stdout=subprocess.PIPE, text=True)
+ try:
+ assert "taking the machine lock (shared)" in child.stdout.readline()
+ blocked, deadline = False, time.time() + 4
+ while not blocked and time.time() < deadline:
+ with open(lock, "a+") as f:
+ try:
+ fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ fcntl.flock(f, fcntl.LOCK_UN)
+ time.sleep(0.05)
+ except BlockingIOError:
+ blocked = True
+ assert blocked, "an exclusive lock was granted while the shared holder ran"
+ finally:
+ child.terminate()
+ child.wait(10)
+
+
+def test_an_editor_holding_a_worktree_lockfile_counts_as_unity(tmp_path):
+ temp = tmp_path / "a" / "unity" / "Temp"
+ temp.mkdir(parents=True)
+ (temp / "UnityLockfile").write_text("")
+ (tmp_path / "b").mkdir()
+ asked = []
+ pids = ml.lockfile_holders([tmp_path / "a", tmp_path / "b"], lsof=lambda files: (asked.extend(files), "4242\n4242\n")[1])
+ assert pids == [4242]
+ assert asked == [str(temp / "UnityLockfile")]
+ assert ml.lockfile_holders([tmp_path / "b"], lsof=lambda files: "1\n") == []
diff --git a/tools/tests/test_web_check_shots.py b/tools/tests/test_web_check_shots.py
new file mode 100644
index 000000000..7f46f9ba8
--- /dev/null
+++ b/tools/tests/test_web_check_shots.py
@@ -0,0 +1,63 @@
+import base64
+import hashlib
+
+import pytest
+
+import web_check as wc
+
+
+def shot_lines(name: str, png: bytes, chunk: int = 10) -> list[str]:
+ b64 = base64.b64encode(png).decode()
+ parts = [b64[i:i + chunk] for i in range(0, len(b64), chunk)]
+ return [f"SHOT {name} begin {len(parts)} {hashlib.sha256(png).hexdigest()}"] + \
+ [f"SHOT {name} {i + 1}/{len(parts)} {p}" for i, p in enumerate(parts)]
+
+
+def test_a_shot_is_reassembled_and_written(tmp_path):
+ png = bytes(range(256)) * 3
+ c = wc.ShotCollector(tmp_path)
+ assert all(c.feed(line) for line in shot_lines("gameplay03", png))
+ assert (tmp_path / "gameplay03.png").read_bytes() == png
+ assert c.written == [tmp_path / "gameplay03.png"]
+ assert c.feed("SHOT done") is False # printed and matched by --expect, not consumed
+ assert c.feed("GAME OK 1948-05-15") is False
+
+
+def test_parts_may_arrive_out_of_order(tmp_path):
+ png = b"\x89PNG" + bytes(200)
+ lines = shot_lines("diorama02", png)
+ c = wc.ShotCollector(tmp_path)
+ for line in [lines[0]] + list(reversed(lines[1:])):
+ c.feed(line)
+ assert (tmp_path / "diorama02.png").read_bytes() == png
+
+
+def test_a_cut_line_fails_the_hash(tmp_path):
+ lines = shot_lines("gameplay03", bytes(300))
+ lines[2] = lines[2][:-3]
+ c = wc.ShotCollector(tmp_path)
+ with pytest.raises(ValueError, match="SHA-256"):
+ for line in lines:
+ c.feed(line)
+
+
+def test_a_part_before_its_header_is_an_error(tmp_path):
+ with pytest.raises(ValueError, match="before its begin line"):
+ wc.ShotCollector(tmp_path).feed("SHOT gameplay03 1/2 AAAA")
+
+
+def test_a_lost_part_fails_loudly_at_shot_done(tmp_path):
+ lines = shot_lines("gameplay03", bytes(300))
+ c = wc.ShotCollector(tmp_path)
+ for line in lines[:2] + lines[3:]: # one part line never arrives
+ c.feed(line)
+ with pytest.raises(ValueError, match=r"gameplay03: \d+ of \d+ parts"):
+ c.feed("SHOT done")
+
+
+def test_headless_chrome_runs_uncapped_at_dpr_1():
+ flags = wc.chrome_flags("/tmp/p", swiftshader=False)
+ for flag in ("--headless=new", "--disable-frame-rate-limit", "--disable-gpu-vsync", "--window-size=1920,1080",
+ "--user-data-dir=/tmp/p", "--force-device-scale-factor=1"):
+ assert flag in flags
+ assert "--use-angle=swiftshader" in wc.chrome_flags("/tmp/p", swiftshader=True)
diff --git a/tools/web_check.py b/tools/web_check.py
index 710492d86..8eba52afc 100644
--- a/tools/web_check.py
+++ b/tools/web_check.py
@@ -2,19 +2,23 @@
# requires-python = ">=3.11"
# dependencies = []
# ///
-"""Serve a Unity WebGL build on http://localhost and open it in headless Chrome; pass when the console shows every
-expected line, fail on a failure line or a timeout. Uses Chrome for Testing from the Playwright cache (macOS only, no npm needed) in --headless=new mode (the cached
-chrome-headless-shell has no WebGL for Unity): console messages reach stderr with --enable-logging=stderr --v=1 as
-INFO:CONSOLE... "text", source: ...
+"""Serve a Unity WebGL build on http://localhost and open it in Chrome; pass when the console shows every expected line,
+fail on a failure line or a timeout. Uses Chrome for Testing from the Playwright cache (macOS only, no npm needed) in
+--headless=new mode (the cached chrome-headless-shell has no WebGL for Unity): console messages reach stderr with
+--enable-logging=stderr --v=1 as INFO:CONSOLE... "text", source: ...
Usage (from the repo root):
- uv run tools/web_check.py unity/Builds/Web-disabled --query "golden" --expect "GOLDEN OK 1950" --expect "GOLDEN OK 1952"
+ uv run tools/web_check.py unity/Builds/Web-disabled --query "golden" --expect "GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07" --expect "GOLDEN OK 1952 73590e324f19e9959a455a4da79e93d7089dfcf283c13aac02af6b0a624b9767"
Options: --query Q (page URL query, without '?'), --expect TEXT (repeatable), --fail REGEX (default: GOLDEN FAIL|SMOKE FAIL|BOOT FAIL),
---timeout SECONDS (default 300), --swiftshader (software WebGL when there is no GPU).
+--timeout SECONDS (default 300), --swiftshader (software WebGL when there is no GPU), --shots DIR (reassemble the player's
+"SHOT" console lines, from ?shot, into DIR/<pose>.png; a "SHOT done" with an unfinished shot fails the run). Chrome runs at
+device pixel ratio 1. Headed runs (a visible window, another DPR) go through tools/headed.py.
Pre-compressed builds: *.br and *.gz files are served with Content-Encoding, *.wasm(.br/.gz) as application/wasm.
Brotli needs a secure context; http://localhost is one."""
import argparse
+import base64
import functools
+import hashlib
import http.server
import os
import re
@@ -27,10 +31,12 @@ import threading
import time
from pathlib import Path
-# A console message's first line; Unity's Debug.Log adds a stack trace on later lines, so the closing quote and
-# ", source:" may be far below. Only the first line is matched.
+# A console message's first line; warnings and errors carry a stack trace on later lines (ProjectSetup sets none for
+# Debug.Log), so the closing quote and ", source:" may be far below. Only the first line is matched.
CONSOLE = re.compile(r'INFO:CONSOLE[^\]]*\] "(.*?)(?:", source: .*)?$')
CHROME_GLOB = "ms-playwright/chromium-*/chrome-mac*/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
+SHOT_BEGIN = re.compile(r"^SHOT (\S+) begin (\d+) ([0-9a-f]{64})$")
+SHOT_PART = re.compile(r"^SHOT (\S+) (\d+)/(\d+) (\S+)$")
class Handler(http.server.SimpleHTTPRequestHandler):
@@ -58,6 +64,56 @@ class Handler(http.server.SimpleHTTPRequestHandler):
print("http:", fmt % args)
+class ShotCollector:
+ """Reassembles the PNGs Statecraft.Game.Map.VisualShots logs: "SHOT <pose> begin <n> <sha256>" then n lines
+ "SHOT <pose> <i>/<n> <base64>" (any order). A finished shot is checked against its SHA-256 and written to
+ <out_dir>/<pose>.png (out_dir None: checked, not written)."""
+
+ def __init__(self, out_dir: Path | None):
+ self.out_dir = out_dir
+ self.expect: dict[str, tuple[int, str]] = {}
+ self.parts: dict[str, dict[int, str]] = {}
+ self.written: list[Path] = []
+
+ def feed(self, text: str) -> bool:
+ """True when text was a begin or part line (consumed: too long to print); False for anything else. "SHOT done"
+ while a shot is unfinished (a part line was lost) raises ValueError naming it."""
+ if text == "SHOT done" and self.expect:
+ unfinished = ", ".join(f"{n}: {len(self.parts.get(n, {}))} of {k} parts" for n, (k, _) in self.expect.items())
+ raise ValueError(f"SHOT done with unfinished shots ({unfinished})")
+ m = SHOT_BEGIN.match(text)
+ if m:
+ self.expect[m.group(1)] = (int(m.group(2)), m.group(3))
+ self.parts[m.group(1)] = {}
+ return True
+ m = SHOT_PART.match(text)
+ if not m:
+ return False
+ name, i = m.group(1), int(m.group(2))
+ if name not in self.expect:
+ raise ValueError(f"SHOT {name}: part {i}/{m.group(3)} before its begin line")
+ self.parts[name][i] = m.group(4)
+ if len(self.parts[name]) == self.expect[name][0]:
+ self._finish(name)
+ return True
+
+ def _finish(self, name: str) -> None:
+ n, digest = self.expect.pop(name)
+ parts = self.parts.pop(name)
+ try:
+ png = base64.b64decode("".join(parts[i] for i in range(1, n + 1)), validate=True)
+ except ValueError: # binascii.Error: a cut line leaves invalid base64
+ png = b""
+ if hashlib.sha256(png).hexdigest() != digest:
+ raise ValueError(f"SHOT {name}: SHA-256 mismatch (a console line was cut or lost)")
+ if self.out_dir is not None:
+ self.out_dir.mkdir(parents=True, exist_ok=True)
+ path = self.out_dir / f"{name}.png"
+ path.write_bytes(png)
+ self.written.append(path)
+ print(f"shot: wrote {path}")
+
+
def find_chrome() -> Path:
"""The newest Chrome for Testing in the Playwright cache (macOS, arm64 or x64), by numeric revision."""
found = list(Path.home().joinpath("Library", "Caches").glob(CHROME_GLOB))
@@ -71,6 +127,16 @@ def find_chrome() -> Path:
return max(found, key=revision)
+def chrome_flags(profile: str, swiftshader: bool) -> list[str]:
+ """Headless Chrome at device pixel ratio 1, frame rate uncapped (so frame times are not the display's)."""
+ flags = ["--headless=new", "--enable-logging=stderr", "--v=1", "--no-first-run", "--no-default-browser-check",
+ "--autoplay-policy=no-user-gesture-required", "--window-size=1920,1080", "--force-device-scale-factor=1",
+ "--disable-frame-rate-limit", "--disable-gpu-vsync", f"--user-data-dir={profile}"]
+ if swiftshader:
+ flags += ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"]
+ return flags
+
+
def serve(root: Path) -> http.server.ThreadingHTTPServer:
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Handler, directory=str(root)))
threading.Thread(target=server.serve_forever, daemon=True).start()
@@ -102,16 +168,18 @@ def drain(inbox: queue.Queue) -> list:
return batch
-def watch(inbox, poll, join_reader, expect, fail, timeout, now=time.time, sleep=time.sleep) -> int:
+def watch(inbox, poll, join_reader, expect, fail, timeout, now=time.time, sleep=time.sleep, on_text=None) -> int:
"""The check loop: 0 on PASS, 1 on a failure line, on BROWSER EXITED or on TIMEOUT. poll() is the browser's
returncode (None while running); join_reader() waits briefly for the stderr reader thread to hit EOF, so output
- written just before the exit is still scanned."""
+ written just before the exit is still scanned. on_text(text) -> True consumes a message (it is not printed)."""
pending, deadline = list(expect), now() + timeout
def look():
nonlocal pending
status, pending, texts = scan(drain(inbox), pending, fail)
for t in texts:
+ if on_text is not None and on_text(t):
+ continue
print("console:", t)
if status == "fail":
print(f"FAIL: {texts[-1]}")
@@ -146,24 +214,26 @@ def main() -> int:
ap.add_argument("--fail", default=r"GOLDEN FAIL|SMOKE FAIL|BOOT FAIL")
ap.add_argument("--timeout", type=float, default=300)
ap.add_argument("--swiftshader", action="store_true")
+ ap.add_argument("--shots", type=Path)
a = ap.parse_args()
if not (a.build / "index.html").exists():
sys.exit(f"{a.build}/index.html not found")
server, proc, profile = None, None, tempfile.mkdtemp(prefix="web-check-")
+ shots = ShotCollector(a.shots)
try:
chrome = find_chrome()
server = serve(a.build)
url = f"http://localhost:{server.server_address[1]}/index.html" + (f"?{a.query}" if a.query else "")
- flags = ["--headless=new", "--enable-logging=stderr", "--v=1", "--no-first-run", "--no-default-browser-check",
- "--autoplay-policy=no-user-gesture-required", "--window-size=1920,1080",
- "--disable-frame-rate-limit", "--disable-gpu-vsync", f"--user-data-dir={profile}"]
- if a.swiftshader:
- flags += ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"]
- proc = subprocess.Popen([str(chrome), *flags, url], stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True, errors="replace")
+ proc = subprocess.Popen([str(chrome), *chrome_flags(profile, a.swiftshader), url],
+ stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True, errors="replace")
inbox: queue.Queue = queue.Queue()
reader = threading.Thread(target=lambda: [inbox.put(l) for l in iter(proc.stderr.readline, "")], daemon=True)
reader.start()
- return watch(inbox, proc.poll, lambda: reader.join(2), list(a.expect), re.compile(a.fail), a.timeout)
+ try:
+ return watch(inbox, proc.poll, lambda: reader.join(2), list(a.expect), re.compile(a.fail), a.timeout, on_text=shots.feed)
+ except ValueError as e:
+ print(f"FAIL: {e}")
+ return 1
finally:
if proc is not None:
proc.terminate()
diff --git a/unity/Assets/Editor/MapCapture.cs b/unity/Assets/Editor/MapCapture.cs
index a8046e756..2cadb0678 100644
--- a/unity/Assets/Editor/MapCapture.cs
+++ b/unity/Assets/Editor/MapCapture.cs
@@ -103,6 +103,32 @@ public static class MapCapture
}
}
+ /// <summary>Renders each promo pose (PromoPose.All) at 1920x1080 once per quality tier (0 = Mobile, the WebGL tier;
+ /// 1 = PC) into &lt;-captureDir&gt; (default captures/visual/editor) as &lt;tier&gt;-&lt;pose&gt;.png. Editor renders show no UI
+ /// Toolkit labels; tools/art_checkpoint.sh pairs them with the WebGL screenshots, which do.</summary>
+ public static void Promo()
+ {
+ var args = System.Environment.GetCommandLineArgs();
+ int at = System.Array.IndexOf(args, "-captureDir");
+ var dir = at >= 0 && at + 1 < args.Length ? args[at + 1] : Path.Combine(CaptureDir, "visual", "editor");
+ var map = OpenAndBuild();
+ var rig = Camera.main.GetComponent<CameraRig>();
+ int saved = QualitySettings.GetQualityLevel();
+ try
+ {
+ for (int level = 0; level < QualitySettings.names.Length; level++)
+ {
+ QualitySettings.SetQualityLevel(level, true);
+ foreach (var pose in PromoPose.All)
+ {
+ pose.Apply(rig, map.Frame);
+ Save(Camera.main, 1920, 1080, Path.Combine(dir, $"{QualitySettings.names[level]}-{pose.Name}.png"));
+ }
+ }
+ }
+ finally { QualitySettings.SetQualityLevel(saved, true); }
+ }
+
static void Save(Camera cam, int w, int h, string path)
{
var rt = new RenderTexture(w, h, 24); cam.targetTexture = rt; cam.Render();
diff --git a/unity/Assets/Scripts/Map/CameraRig.cs b/unity/Assets/Scripts/Map/CameraRig.cs
index 48e66dd50..e3eb517a7 100644
--- a/unity/Assets/Scripts/Map/CameraRig.cs
+++ b/unity/Assets/Scripts/Map/CameraRig.cs
@@ -1,3 +1,5 @@
+using System;
+using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
@@ -19,6 +21,10 @@ namespace Statecraft.Game.Map
public const float MaxTopInset = 0.5f;
DepthOfField _dof;
+ /// <summary>Undo actions for state Init changes outside the rig (the URP asset's shadow distance...). MapScene.Build hands
+ /// them to the map's MapRuntimeAssets right after Init, so destroying the map undoes them.</summary>
+ public readonly List<Action> TeardownActions = new List<Action>();
+
/// <summary>The global post-processing volume Init creates. Its runtime VolumeProfile must be owned by the caller
/// (MapScene registers it with MapRuntimeAssets).</summary>
public Volume Volume { get; private set; }
diff --git a/unity/Assets/Scripts/Map/FrameProfile.cs b/unity/Assets/Scripts/Map/FrameProfile.cs
new file mode 100644
index 000000000..5023bb2b2
--- /dev/null
+++ b/unity/Assets/Scripts/Map/FrameProfile.cs
@@ -0,0 +1,90 @@
+#nullable enable
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using Statecraft.Game.Boot;
+using UnityEngine;
+using UnityEngine.Rendering.Universal;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>Prices each visual feature on the real player. At every promo pose it runs every configuration (everything on:
+ /// "all"; each toggle off alone: "-name"; everything off: "none") Repeats times, in a different interleaved order each
+ /// repeat (Order), 300 frames after 60 warm-up frames each, and logs one line per run with the resolution and the URP
+ /// render scale, then one summary line per configuration: the median of the run averages, their spread (max - min) and
+ /// the median p95. A feature costs median(all) - median(-name); it is over a budget only when that exceeds the budget
+ /// plus the larger spread (docs/visual-v1.md). Asked for by "vprofile" in the WebGL page URL (a whole query parameter)
+ /// or -vprofile on desktop, where the player quits when done. Run it under tools/machine_lock.py --exclusive.</summary>
+ public static class FrameProfile
+ {
+ public const int WarmupFrames = 60, MeasuredFrames = 300, Repeats = 3;
+
+ public static bool Requested() =>
+ Requested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
+
+ public static bool Requested(string? url, string[] args, bool webgl) =>
+ webgl ? UrlFlags.Has(url, "vprofile") : args.Contains("-vprofile");
+
+ public static string Line(string label, string pose, string resolution, float renderScale, int rep, IReadOnlyList<float> frameMs)
+ {
+ var (avg, p95) = FrameStats.Summary(frameMs);
+ return string.Format(CultureInfo.InvariantCulture,
+ "PROFILE visual={0} pose={1} res={2} scale={3:0.00} rep={4} frames={5} avg_ms={6:0.00} p95_ms={7:0.00}",
+ label, pose, resolution, renderScale, rep, frameMs.Count, avg, p95);
+ }
+
+ public static string Summary(string label, string pose, IReadOnlyList<(float avg, float p95)> runs)
+ {
+ if (runs == null || runs.Count == 0) throw new ArgumentException("no runs", nameof(runs));
+ float Median(IEnumerable<float> xs) { var s = xs.OrderBy(x => x).ToList(); return s.Count % 2 == 1 ? s[s.Count / 2] : (s[s.Count / 2 - 1] + s[s.Count / 2]) / 2f; }
+ var avgs = runs.Select(r => r.avg).ToList();
+ return string.Format(CultureInfo.InvariantCulture,
+ "PROFILE summary visual={0} pose={1} runs={2} median_avg_ms={3:0.00} spread_ms={4:0.00} median_p95_ms={5:0.00}",
+ label, pose, runs.Count, Median(avgs), avgs.Max() - avgs.Min(), Median(runs.Select(r => r.p95)));
+ }
+
+ /// <summary>Run order of <paramref name="count"/> configurations in repeat <paramref name="rep"/>: forward, reversed,
+ /// then forward from the middle, so no configuration always runs first (warm) or last (hot).</summary>
+ public static IReadOnlyList<int> Order(int count, int rep)
+ {
+ var forward = Enumerable.Range(0, count).ToList();
+ switch (rep % 3)
+ {
+ case 0: return forward;
+ case 1: forward.Reverse(); return forward;
+ default: return forward.Skip(count / 2).Concat(forward.Take(count / 2)).ToList();
+ }
+ }
+
+ public static IEnumerator Run(CameraRig rig, GeoFrame frame, Action<string> log, bool quitWhenDone)
+ {
+ var configs = new List<(string label, string? off)> { ("all", null) };
+ foreach (var name in VisualToggles.Names) configs.Add(("-" + name, name));
+ configs.Add(("none", "*"));
+ foreach (var pose in PromoPose.All)
+ {
+ pose.Apply(rig, frame);
+ var results = configs.ToDictionary(c => c.label, c => new List<(float avg, float p95)>());
+ for (int rep = 0; rep < Repeats; rep++)
+ foreach (var i in Order(configs.Count, rep))
+ {
+ var (label, off) = configs[i];
+ VisualToggles.SetAll(off != "*");
+ if (off != null && off != "*") VisualToggles.Set(off, false);
+ for (int f = 0; f < WarmupFrames; f++) yield return null;
+ var times = new List<float>(MeasuredFrames);
+ for (int f = 0; f < MeasuredFrames; f++) { yield return null; times.Add(Time.unscaledDeltaTime * 1000f); }
+ var scale = UniversalRenderPipeline.asset != null ? UniversalRenderPipeline.asset.renderScale : 1f;
+ log(Line(label, pose.Name, $"{Screen.width}x{Screen.height}", scale, rep, times));
+ results[label].Add(FrameStats.Summary(times));
+ }
+ foreach (var (label, _) in configs) log(Summary(label, pose.Name, results[label]));
+ }
+ VisualToggles.SetAll(true);
+ log("PROFILE visual done");
+ if (quitWhenDone) Application.Quit(0);
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/FrameProfile.cs.meta b/unity/Assets/Scripts/Map/FrameProfile.cs.meta
new file mode 100644
index 000000000..373b1b79d
--- /dev/null
+++ b/unity/Assets/Scripts/Map/FrameProfile.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 96d988a0d8eaa4bc9a6a19538a089e4e
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/FrameStats.cs b/unity/Assets/Scripts/Map/FrameStats.cs
new file mode 100644
index 000000000..7967005ad
--- /dev/null
+++ b/unity/Assets/Scripts/Map/FrameStats.cs
@@ -0,0 +1,20 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>Average and 95th-percentile frame time (ms), shared by the terrain and visual profiles.</summary>
+ public static class FrameStats
+ {
+ public static (float avg, float p95) Summary(IReadOnlyList<float> frameMs)
+ {
+ if (frameMs == null) throw new ArgumentNullException(nameof(frameMs));
+ if (frameMs.Count == 0) throw new ArgumentException("no frames were measured", nameof(frameMs));
+ var sorted = frameMs.OrderBy(x => x).ToList();
+ var p95 = sorted[Math.Min(sorted.Count - 1, (int)Math.Ceiling(sorted.Count * 0.95) - 1)];
+ return (sorted.Average(), p95);
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/FrameStats.cs.meta b/unity/Assets/Scripts/Map/FrameStats.cs.meta
new file mode 100644
index 000000000..eccc06b19
--- /dev/null
+++ b/unity/Assets/Scripts/Map/FrameStats.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 6e7c7fa8308814a1184b29d849797d57
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/MapRuntimeAssets.cs b/unity/Assets/Scripts/Map/MapRuntimeAssets.cs
index 7db38afbe..7d2a77e34 100644
--- a/unity/Assets/Scripts/Map/MapRuntimeAssets.cs
+++ b/unity/Assets/Scripts/Map/MapRuntimeAssets.cs
@@ -10,11 +10,18 @@ namespace Statecraft.Game.Map
public sealed class MapRuntimeAssets : MonoBehaviour
{
readonly List<Object> owned = new List<Object>();
+ readonly List<System.Action> teardown = new List<System.Action>();
public T Own<T>(T o) where T : Object { owned.Add(o); return o; }
+ /// <summary>Runs <paramref name="action"/> when the map is destroyed (newest first), for state the map changes outside
+ /// itself: the URP asset's shadow distance, global shader values.</summary>
+ public void OnTeardown(System.Action action) => teardown.Add(action ?? throw new System.ArgumentNullException(nameof(action)));
+
void OnDestroy()
{
+ for (int i = teardown.Count - 1; i >= 0; i--) teardown[i]();
+ teardown.Clear();
foreach (var o in owned)
{
if (o == null) continue;
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index 67c38527b..dd8f4ff6b 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -126,6 +126,8 @@ namespace Statecraft.Game.Map
var assets = terrainGo.GetComponent<MapRuntimeAssets>();
foreach (var c in rig.Volume.profile.components) assets.Own(c);
assets.Own(rig.Volume.profile);
+ foreach (var undo in rig.TeardownActions) assets.OnTeardown(undo);
+ rig.TeardownActions.Clear();
}
/// <summary>The land and sea past the map's edge (MapBuilder.BuildBorderSkirt), drawn with the editor-made Sea.mat and
diff --git a/unity/Assets/Scripts/Map/PixelErrorProfile.cs b/unity/Assets/Scripts/Map/PixelErrorProfile.cs
index 4f0764003..62e4c5c68 100644
--- a/unity/Assets/Scripts/Map/PixelErrorProfile.cs
+++ b/unity/Assets/Scripts/Map/PixelErrorProfile.cs
@@ -24,12 +24,9 @@ namespace Statecraft.Game.Map
public static string Line(float pixelError, List<float> frameMs)
{
- if (frameMs == null) throw new ArgumentNullException(nameof(frameMs));
- if (frameMs.Count == 0) throw new ArgumentException("no frames were measured", nameof(frameMs));
- var sorted = frameMs.OrderBy(x => x).ToList();
- var p95 = sorted[Math.Min(sorted.Count - 1, (int)Math.Ceiling(sorted.Count * 0.95) - 1)];
+ var (avg, p95) = FrameStats.Summary(frameMs);
return string.Format(CultureInfo.InvariantCulture, "PROFILE pixelError={0:0} frames={1} avg_ms={2:0.00} p95_ms={3:0.00}",
- pixelError, sorted.Count, sorted.Average(), p95);
+ pixelError, frameMs.Count, avg, p95);
}
public static IEnumerator Run(Terrain terrain)
diff --git a/unity/Assets/Scripts/Map/PromoPose.cs b/unity/Assets/Scripts/Map/PromoPose.cs
new file mode 100644
index 000000000..cf25df21a
--- /dev/null
+++ b/unity/Assets/Scripts/Map/PromoPose.cs
@@ -0,0 +1,33 @@
+#nullable enable
+using System.Collections.Generic;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>Fixed camera poses that frame the same ground as the approved promo images, so every art checkpoint compares
+ /// like with like. Yaw 0 looks north (the sea on the left), as both promo images do.</summary>
+ public readonly struct PromoPose
+ {
+ public readonly string Name; public readonly double Lon, Lat; public readonly float Distance, Yaw;
+
+ public PromoPose(string name, double lon, double lat, float distance, float yaw)
+ { Name = name; Lon = lon; Lat = lat; Distance = distance; Yaw = yaw; }
+
+ /// <summary>promo/final/03-gameplay-1936.png: Jaffa and Tel Aviv at the left, Lydda and Ramla to the right, the sea
+ /// top-left, Qalqilya top-right. Matched on hex count (about nine across, so about 60 km), not on geography: the
+ /// promo's Jaffa-to-Ramla spread (about 17 km over 60% of the frame) would need a 25-30 km view, but under the
+ /// owner's symbolic-scale ruling (2026-10-11) settlements will sprawl over neighbouring hexes, so the hex count is
+ /// the scale the art track will match. The 6 km hero zoom stays available for close looks.</summary>
+ public static readonly PromoPose Gameplay03 = new PromoPose("gameplay03", 34.86, 32.00, 60000f, 10f);
+
+ /// <summary>promo/final/02-map-diorama.png: the country from the Negev northwards, the sea on the left, the Dead Sea
+ /// right of centre; the camera's farthest zoom.</summary>
+ public static readonly PromoPose Diorama02 = new PromoPose("diorama02", 35.05, 31.55, CameraController.MaxDistance, 0f);
+
+ public static IReadOnlyList<PromoPose> All { get; } = new[] { Gameplay03, Diorama02 };
+
+ public void Apply(CameraRig rig, GeoFrame frame)
+ {
+ rig.LookAt = frame.ToWorld(Lon, Lat, 0); rig.Distance = Distance; rig.Yaw = Yaw; rig.Apply();
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/PromoPose.cs.meta b/unity/Assets/Scripts/Map/PromoPose.cs.meta
new file mode 100644
index 000000000..40fe7d202
--- /dev/null
+++ b/unity/Assets/Scripts/Map/PromoPose.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 72182be75f377447bac5b13986912598
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/VisualShots.cs b/unity/Assets/Scripts/Map/VisualShots.cs
new file mode 100644
index 000000000..42e44f766
--- /dev/null
+++ b/unity/Assets/Scripts/Map/VisualShots.cs
@@ -0,0 +1,52 @@
+#nullable enable
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Security.Cryptography;
+using Statecraft.Game.Boot;
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>Screenshots of the running player at each promo pose, written to the console as base64 chunks, because a
+ /// WebGL page cannot write files: "SHOT &lt;pose&gt; begin &lt;n&gt; &lt;sha256&gt;", then n lines "SHOT &lt;pose&gt; &lt;i&gt;/&lt;n&gt; &lt;data&gt;",
+ /// and "SHOT done" at the end. tools/web_check.py --shots reassembles and checks them. Asked for by "shot" in the page
+ /// URL or -shot on desktop.</summary>
+ public static class VisualShots
+ {
+ public const int SettleFrames = 30;
+ public const int ChunkChars = 8000; // well under any console line limit; a cut line fails the SHA-256 check
+
+ public static bool Requested() =>
+ Requested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
+
+ public static bool Requested(string? url, string[] args, bool webgl) =>
+ webgl ? UrlFlags.Has(url, "shot") : args.Contains("-shot");
+
+ public static IEnumerable<string> Lines(string name, byte[] png)
+ {
+ var b64 = Convert.ToBase64String(png);
+ int n = Math.Max(1, (b64.Length + ChunkChars - 1) / ChunkChars);
+ string hash;
+ using (var sha = SHA256.Create()) hash = string.Concat(sha.ComputeHash(png).Select(b => b.ToString("x2")));
+ yield return $"SHOT {name} begin {n} {hash}";
+ for (int i = 0; i < n; i++)
+ yield return $"SHOT {name} {i + 1}/{n} {b64.Substring(i * ChunkChars, Math.Min(ChunkChars, b64.Length - i * ChunkChars))}";
+ }
+
+ public static IEnumerator Run(CameraRig rig, GeoFrame frame, Action<string> log)
+ {
+ foreach (var pose in PromoPose.All)
+ {
+ pose.Apply(rig, frame);
+ for (int i = 0; i < SettleFrames; i++) yield return null;
+ yield return new WaitForEndOfFrame();
+ var tex = ScreenCapture.CaptureScreenshotAsTexture();
+ try { foreach (var line in Lines(pose.Name, tex.EncodeToPNG())) log(line); }
+ finally { UnityEngine.Object.Destroy(tex); }
+ }
+ log("SHOT done");
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/VisualShots.cs.meta b/unity/Assets/Scripts/Map/VisualShots.cs.meta
new file mode 100644
index 000000000..c64a87e4d
--- /dev/null
+++ b/unity/Assets/Scripts/Map/VisualShots.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: bbeb6f1e5f1c0435a951ec59a46d3fa7
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/VisualToggles.cs b/unity/Assets/Scripts/Map/VisualToggles.cs
new file mode 100644
index 000000000..bd579bda2
--- /dev/null
+++ b/unity/Assets/Scripts/Map/VisualToggles.cs
@@ -0,0 +1,33 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>One on/off switch per visual feature (shadows, tilt-shift, grade, haze, grid...), registered by the feature
+ /// itself, so the visual profile can price each one and tests can isolate it. Names run in ordinal order; registering
+ /// a name again replaces its switch (a rebuilt map re-registers).</summary>
+ public static class VisualToggles
+ {
+ static readonly SortedDictionary<string, Action<bool>> Switches = new SortedDictionary<string, Action<bool>>(StringComparer.Ordinal);
+
+ public static void Register(string name, Action<bool> set)
+ {
+ if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("a toggle needs a name", nameof(name));
+ Switches[name] = set ?? throw new ArgumentNullException(nameof(set));
+ }
+
+ public static void Unregister(string name) => Switches.Remove(name);
+ public static IReadOnlyList<string> Names => Switches.Keys.ToList();
+
+ public static void Set(string name, bool on)
+ {
+ if (!Switches.TryGetValue(name, out var set)) throw new KeyNotFoundException($"no visual toggle named '{name}' (known: {string.Join(", ", Switches.Keys)})");
+ set(on);
+ }
+
+ public static void SetAll(bool on) { foreach (var set in Switches.Values.ToList()) set(on); }
+ public static void Clear() => Switches.Clear();
+ }
+}
diff --git a/unity/Assets/Scripts/Map/VisualToggles.cs.meta b/unity/Assets/Scripts/Map/VisualToggles.cs.meta
new file mode 100644
index 000000000..ff99d7fa6
--- /dev/null
+++ b/unity/Assets/Scripts/Map/VisualToggles.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 80026ec4600544ba4b0b88d96ad82eed
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 6d189acf1..c53dc3682 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -194,6 +194,10 @@ namespace Statecraft.Game.UI
else Debug.LogWarning("SMOKE FAIL the smoke run needs play mode or a player");
}
if (Application.isPlaying && PixelErrorProfile.Requested()) StartCoroutine(PixelErrorProfile.Run(map.Terrain));
+ // 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));
+ else if (Application.isPlaying && VisualShots.Requested()) StartCoroutine(VisualShots.Run(camRig, map.Frame, Debug.Log));
}
T Own<T>(T d) where T : IDisposable { owned.Add(d); return d; }
diff --git a/unity/Assets/Tests/EditMode/RenderSample.cs b/unity/Assets/Tests/EditMode/RenderSample.cs
new file mode 100644
index 000000000..f8dfc5847
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/RenderSample.cs
@@ -0,0 +1,137 @@
+#nullable enable
+using UnityEngine;
+
+/// <summary>Edit-mode render sampling for the visual tests: renders a camera into a texture and reads the pixels back.
+/// Row 0 is the bottom of the image (viewport y = 0). Luma is Rec. 709 over the stored (display-referred) values.</summary>
+public sealed class RenderSample
+{
+ public readonly int Width, Height;
+ public readonly Color[] Pixels;
+
+ RenderSample(int width, int height, Color[] pixels) { Width = width; Height = height; Pixels = pixels; }
+
+ public static RenderSample Render(Camera cam, int width, int height) => Render(cam, width, height, System.Array.Empty<Vector3>(), System.Array.Empty<Vector2>());
+
+ /// <summary>Renders, and projects each world point to this image's pixels while the camera still targets it.</summary>
+ public static RenderSample Render(Camera cam, int width, int height, Vector3[] world, Vector2[] screenOut)
+ {
+ var rt = new RenderTexture(width, height, 24);
+ var tex = new Texture2D(width, height, TextureFormat.RGB24, false);
+ var oldTarget = cam.targetTexture;
+ try
+ {
+ cam.targetTexture = rt;
+ cam.Render();
+ RenderTexture.active = rt;
+ tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); tex.Apply();
+ for (int i = 0; i < world.Length; i++) { var p = cam.WorldToScreenPoint(world[i]); screenOut[i] = new Vector2(p.x, p.y); }
+ return new RenderSample(width, height, tex.GetPixels());
+ }
+ finally
+ {
+ RenderTexture.active = null; cam.targetTexture = oldTarget;
+ rt.Release(); Object.DestroyImmediate(rt); Object.DestroyImmediate(tex);
+ }
+ }
+
+ public Color At(int x, int y) => Pixels[Mathf.Clamp(y, 0, Height - 1) * Width + Mathf.Clamp(x, 0, Width - 1)];
+
+ /// <summary>The mean colour of the (2 radius + 1)² patch around (cx, cy).</summary>
+ public Color Mean(int cx, int cy, int radius)
+ {
+ Color sum = Color.clear; int n = 0;
+ for (int y = cy - radius; y <= cy + radius; y++)
+ for (int x = cx - radius; x <= cx + radius; x++) { sum += At(x, y); n++; }
+ return sum / n;
+ }
+
+ public static float Luma(Color c) => 0.2126f * c.r + 0.7152f * c.g + 0.0722f * c.b;
+
+ /// <summary>Mean |dL/dx| + |dL/dy| over the rows from y0 to y1 (fractions of the height, 0 = bottom): local contrast,
+ /// which a blur lowers.</summary>
+ public float GradientEnergy(float y0, float y1)
+ {
+ int r0 = Mathf.Clamp(Mathf.FloorToInt(y0 * Height), 0, Height - 2), r1 = Mathf.Clamp(Mathf.CeilToInt(y1 * Height), r0 + 1, Height - 1);
+ double sum = 0; int n = 0;
+ for (int y = r0; y < r1; y++)
+ for (int x = 0; x < Width - 1; x++)
+ {
+ float l = Luma(At(x, y));
+ sum += Mathf.Abs(Luma(At(x + 1, y)) - l) + Mathf.Abs(Luma(At(x, y + 1)) - l); n++;
+ }
+ return (float)(sum / n);
+ }
+
+ /// <summary>Mean luma over a rectangle given as fractions of the image (0 = left / bottom).</summary>
+ public float MeanLuma(float x0, float y0, float x1, float y1)
+ {
+ double sum = 0; int n = 0;
+ for (int y = Mathf.FloorToInt(y0 * Height); y < Mathf.CeilToInt(y1 * Height); y++)
+ for (int x = Mathf.FloorToInt(x0 * Width); x < Mathf.CeilToInt(x1 * Width); x++) { sum += Luma(At(x, y)); n++; }
+ return (float)(sum / n);
+ }
+
+ public float MeanSaturation()
+ {
+ double sum = 0;
+ foreach (var c in Pixels) { Color.RGBToHSV(c, out _, out var s, out _); sum += s; }
+ return (float)(sum / Pixels.Length);
+ }
+
+ public float LumaStd()
+ {
+ double sum = 0, sq = 0;
+ foreach (var c in Pixels) { double l = Luma(c); sum += l; sq += l * l; }
+ double mean = sum / Pixels.Length;
+ return (float)System.Math.Sqrt(System.Math.Max(0, sq / Pixels.Length - mean * mean));
+ }
+
+ /// <summary>Share of pixels whose luma in <paramref name="a"/> is lower than in <paramref name="b"/> by more than <paramref name="by"/>.</summary>
+ public static float FractionDarker(RenderSample a, RenderSample b, float by)
+ {
+ int n = 0;
+ for (int i = 0; i < a.Pixels.Length; i++) if (Luma(a.Pixels[i]) < Luma(b.Pixels[i]) - by) n++;
+ return (float)n / a.Pixels.Length;
+ }
+
+ /// <summary>Share of pixels with any channel at or above <paramref name="level"/> (clipping: 0.995 is the top 8-bit step).</summary>
+ public float FractionClipped(float level)
+ {
+ int n = 0;
+ foreach (var c in Pixels) if (c.r >= level || c.g >= level || c.b >= level) n++;
+ return (float)n / Pixels.Length;
+ }
+
+ static float ToLinear(float c) => c <= 0.04045f ? c / 12.92f : Mathf.Pow((c + 0.055f) / 1.055f, 2.4f);
+ static float ToSrgb(float c) => c <= 0.0031308f ? c * 12.92f : 1.055f * Mathf.Pow(c, 1f / 2.4f) - 0.055f;
+
+ /// <summary>CIELAB (D65) of a display (sRGB) colour.</summary>
+ public static Vector3 Lab(Color srgb)
+ {
+ float r = ToLinear(srgb.r), g = ToLinear(srgb.g), b = ToLinear(srgb.b);
+ float x = (0.4124f * r + 0.3576f * g + 0.1805f * b) / 0.95047f;
+ float y = 0.2126f * r + 0.7152f * g + 0.0722f * b;
+ float z = (0.0193f * r + 0.1192f * g + 0.9505f * b) / 1.08883f;
+ float F(float t) => t > 0.008856f ? Mathf.Pow(t, 1f / 3f) : 7.787f * t + 16f / 116f;
+ float fx = F(x), fy = F(y), fz = F(z);
+ return new Vector3(116f * fy - 16f, 500f * (fx - fy), 200f * (fy - fz));
+ }
+
+ /// <summary>CIE76 colour difference: about 2.3 is just noticeable; 20 or more reads as a different colour at a glance.</summary>
+ public static float DeltaE(Color a, Color b) => Vector3.Distance(Lab(a), Lab(b));
+
+ public enum Cvd { Deuteranopia, Protanopia }
+
+ // Machado, Oliveira and Fernandes (2009), severity 1.0, applied to linear RGB.
+ static readonly float[,] Deutan = { { 0.367322f, 0.860646f, -0.227968f }, { 0.280085f, 0.672501f, 0.047413f }, { -0.011820f, 0.042940f, 0.968881f } };
+ static readonly float[,] Protan = { { 0.152286f, 1.052583f, -0.204868f }, { 0.114503f, 0.786281f, 0.099216f }, { -0.003882f, -0.048116f, 1.051998f } };
+
+ /// <summary>How a display colour looks to a player with full deuteranopia or protanopia.</summary>
+ public static Color SimulateCvd(Color srgb, Cvd kind)
+ {
+ var m = kind == Cvd.Deuteranopia ? Deutan : Protan;
+ float r = ToLinear(srgb.r), g = ToLinear(srgb.g), b = ToLinear(srgb.b);
+ float Row(int i) => Mathf.Clamp01(m[i, 0] * r + m[i, 1] * g + m[i, 2] * b);
+ return new Color(ToSrgb(Row(0)), ToSrgb(Row(1)), ToSrgb(Row(2)), srgb.a);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/RenderSample.cs.meta b/unity/Assets/Tests/EditMode/RenderSample.cs.meta
new file mode 100644
index 000000000..a560ad75c
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/RenderSample.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 6602a0b4a8f3a467083f46aaa5c6b291
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/ShaderChecks.cs b/unity/Assets/Tests/EditMode/ShaderChecks.cs
new file mode 100644
index 000000000..d52e2eaf0
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/ShaderChecks.cs
@@ -0,0 +1,60 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+using UnityEditor;
+using UnityEditor.Rendering;
+using UnityEngine;
+using UnityEngine.Rendering;
+
+/// <summary>Compiles a shader for GLES3 (WebGL 2) and returns the errors. Each pass is compiled for vertex and fragment, in
+/// its base variant and with the main-light-shadow keyword (the variant the web tier draws the map with). A pass whose
+/// source excludes GLES3 (`#pragma exclude_renderers ... gles3 ...`, or `#pragma only_renderers` without gles3) is skipped:
+/// Shader Graph's Terrain Lit target emits DOTS subshaders at target 4.5 that are built for other APIs. The check cannot
+/// pass vacuously: at least one subshader must have passes that are built for GLES3 and all compile.</summary>
+public static class ShaderChecks
+{
+ static readonly string[][] Variants = { Array.Empty<string>(), new[] { "_MAIN_LIGHT_SHADOWS" } };
+ static readonly Regex Exclude = new Regex(@"#pragma\s+exclude_renderers\s+([^\r\n]*)");
+ static readonly Regex Only = new Regex(@"#pragma\s+only_renderers\s+([^\r\n]*)");
+
+ public static bool ExcludesGles3(string passSource)
+ {
+ foreach (Match m in Exclude.Matches(passSource ?? "")) if (Regex.IsMatch(m.Groups[1].Value, @"\bgles3\b")) return true;
+ foreach (Match m in Only.Matches(passSource ?? "")) if (!Regex.IsMatch(m.Groups[1].Value, @"\bgles3\b")) return true;
+ return false;
+ }
+
+ public static List<string> Gles3Errors(Shader shader)
+ {
+ if (shader == null) throw new ArgumentNullException(nameof(shader));
+ var errors = new List<string>();
+ int usable = 0;
+ var data = ShaderUtil.GetShaderData(shader);
+ for (int s = 0; s < data.SubshaderCount; s++)
+ {
+ var sub = data.GetSerializedSubshader(s);
+ var subErrors = new List<string>();
+ int built = 0;
+ for (int p = 0; p < sub.PassCount; p++)
+ {
+ var pass = sub.GetPass(p);
+ if (ExcludesGles3(pass.SourceCode)) continue;
+ built++;
+ foreach (var keywords in Variants)
+ foreach (var stage in new[] { ShaderType.Vertex, ShaderType.Fragment })
+ {
+ var info = pass.CompileVariant(stage, keywords, ShaderCompilerPlatform.GLES3x, BuildTarget.WebGL);
+ var where = $"{shader.name} subshader {s} pass '{pass.Name}' {stage} [{string.Join(" ", keywords)}]";
+ foreach (var m in info.Messages)
+ if (m.severity == ShaderCompilerMessageSeverity.Error) subErrors.Add($"{where}: {m.message} (line {m.line})");
+ if (!info.Success && info.Messages.Length == 0) subErrors.Add($"{where}: failed without a message");
+ }
+ }
+ if (built > 0 && subErrors.Count == 0) usable++;
+ errors.AddRange(subErrors);
+ }
+ if (usable == 0) errors.Add($"{shader.name}: no subshader whose passes are built for GLES3 and all compile");
+ return errors;
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/ShaderChecks.cs.meta b/unity/Assets/Tests/EditMode/ShaderChecks.cs.meta
new file mode 100644
index 000000000..b7b3039a1
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/ShaderChecks.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 559eb96bb034042daa0e9d4648f55f17
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/VisualHarnessTests.cs b/unity/Assets/Tests/EditMode/VisualHarnessTests.cs
new file mode 100644
index 000000000..039294d74
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/VisualHarnessTests.cs
@@ -0,0 +1,156 @@
+#nullable enable
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using UnityEditor;
+using UnityEngine;
+
+/// <summary>The visual track's instruments (plan Task 1): profile lines, flags, toggles, screenshot chunks, poses,
+/// teardown hand-off, the colour metrics and the GLES3 compile check.</summary>
+public class VisualHarnessTests
+{
+ [TearDown] public void ClearToggles() => VisualToggles.Clear();
+
+ [Test]
+ public void ProfileLinesShareTheAverageAndP95AndStateTheResolution()
+ {
+ var frames = Enumerable.Range(1, 100).Select(i => (float)i).ToList();
+ Assert.AreEqual("PROFILE visual=all pose=gameplay03 res=1920x1080 scale=0.80 rep=2 frames=100 avg_ms=50.50 p95_ms=95.00",
+ FrameProfile.Line("all", "gameplay03", "1920x1080", 0.8f, 2, frames));
+ Assert.AreEqual("PROFILE pixelError=1 frames=100 avg_ms=50.50 p95_ms=95.00", PixelErrorProfile.Line(1f, frames));
+ Assert.Throws<System.ArgumentException>(() => FrameStats.Summary(new List<float>()));
+ }
+
+ [Test]
+ public void TheSummaryReportsTheMedianAndTheSpreadOfTheRepeats()
+ {
+ Assert.AreEqual("PROFILE summary visual=-grid pose=diorama02 runs=3 median_avg_ms=6.00 spread_ms=2.00 median_p95_ms=9.00",
+ FrameProfile.Summary("-grid", "diorama02", new[] { (5f, 8f), (7f, 10f), (6f, 9f) }));
+ }
+
+ [Test]
+ public void RepeatsRunTheConfigurationsInInterleavedOrders()
+ {
+ CollectionAssert.AreEqual(new[] { 0, 1, 2, 3 }, FrameProfile.Order(4, 0).ToArray());
+ CollectionAssert.AreEqual(new[] { 3, 2, 1, 0 }, FrameProfile.Order(4, 1).ToArray());
+ CollectionAssert.AreEqual(new[] { 2, 3, 0, 1 }, FrameProfile.Order(4, 2).ToArray());
+ for (int rep = 0; rep < 6; rep++)
+ CollectionAssert.AreEquivalent(Enumerable.Range(0, 7), FrameProfile.Order(7, rep), "each repeat runs every configuration once");
+ }
+
+ [TestCase("http://localhost:8000/index.html?vprofile", true)]
+ [TestCase("http://localhost:8000/index.html?profile", false)]
+ [TestCase("https://html.itch.zone/html/1/vprofile-x/index.html", false)]
+ public void TheVisualProfileFlagIsAWholeQueryParameter(string url, bool expected) =>
+ Assert.AreEqual(expected, FrameProfile.Requested(url, new string[0], true));
+
+ [Test]
+ public void DesktopPlayersTakeDashFlags()
+ {
+ Assert.IsTrue(FrameProfile.Requested(null, new[] { "Statecraft", "-vprofile" }, false));
+ Assert.IsTrue(VisualShots.Requested(null, new[] { "Statecraft", "-shot" }, false));
+ Assert.IsFalse(VisualShots.Requested("http://localhost/index.html?shots", new string[0], true));
+ Assert.IsTrue(VisualShots.Requested("http://localhost/index.html?golden&shot", new string[0], true));
+ }
+
+ [Test]
+ public void TogglesRunInNameOrderAndUnknownNamesThrow()
+ {
+ var log = new List<string>();
+ VisualToggles.Register("tiltshift", on => log.Add("tiltshift " + on));
+ VisualToggles.Register("grade", on => log.Add("grade " + on));
+ CollectionAssert.AreEqual(new[] { "grade", "tiltshift" }, VisualToggles.Names.ToArray());
+ VisualToggles.SetAll(false);
+ CollectionAssert.AreEqual(new[] { "grade False", "tiltshift False" }, log);
+ Assert.Throws<KeyNotFoundException>(() => VisualToggles.Set("fog", true));
+ VisualToggles.Register("grade", on => log.Add("grade again " + on)); // re-registering replaces
+ VisualToggles.Set("grade", true);
+ Assert.AreEqual("grade again True", log.Last());
+ }
+
+ [Test]
+ public void ShotsSplitIntoNumberedChunksAfterAHashedHeader()
+ {
+ var png = new byte[20000]; for (int i = 0; i < png.Length; i++) png[i] = (byte)(i * 7);
+ var lines = VisualShots.Lines("gameplay03", png).ToList();
+ var head = lines[0].Split(' ');
+ Assert.AreEqual(new[] { "SHOT", "gameplay03", "begin" }, head.Take(3).ToArray());
+ int n = int.Parse(head[3]);
+ Assert.AreEqual(64, head[4].Length, "SHA-256 in hex");
+ Assert.AreEqual(n + 1, lines.Count);
+ StringAssert.StartsWith($"SHOT gameplay03 1/{n} ", lines[1]);
+ Assert.IsTrue(lines.Skip(1).All(l => l.Split(' ')[3].Length <= VisualShots.ChunkChars));
+ CollectionAssert.AreEqual(png, System.Convert.FromBase64String(string.Concat(lines.Skip(1).Select(l => l.Split(' ')[3]))));
+ }
+
+ [Test]
+ public void PromoPosesAreInsideTheMapAndTheZoomRange()
+ {
+ Assert.AreEqual(new[] { "gameplay03", "diorama02" }, PromoPose.All.Select(p => p.Name).ToArray());
+ foreach (var p in PromoPose.All)
+ {
+ Assert.That(p.Distance, Is.InRange(CameraController.MinDistance, CameraController.MaxDistance), p.Name);
+ Assert.That(p.Lon, Is.InRange(34.2, 35.9), p.Name); Assert.That(p.Lat, Is.InRange(29.45, 33.35), p.Name);
+ }
+ }
+
+ [Test]
+ public void TheMapRunsItsTeardownActionsNewestFirstWhenDestroyed()
+ {
+ var go = new GameObject("assets"); var assets = go.AddComponent<MapRuntimeAssets>();
+ var order = new List<int>();
+ assets.OnTeardown(() => order.Add(1)); assets.OnTeardown(() => order.Add(2));
+ Object.DestroyImmediate(go);
+ CollectionAssert.AreEqual(new[] { 2, 1 }, order);
+ }
+
+ [Test]
+ public void ColourMetricsBehave()
+ {
+ Assert.AreEqual(0f, RenderSample.DeltaE(Color.grey, Color.grey), 1e-4f);
+ Assert.AreEqual(100f, RenderSample.Lab(Color.white).x, 0.1f, "white is L* 100");
+ Assert.Greater(RenderSample.DeltaE(Color.red, Color.green), 80f);
+ var grey = new Color(0.5f, 0.5f, 0.5f);
+ foreach (var kind in new[] { RenderSample.Cvd.Deuteranopia, RenderSample.Cvd.Protanopia })
+ Assert.Less(RenderSample.DeltaE(grey, RenderSample.SimulateCvd(grey, kind)), 1f, $"{kind} keeps greys");
+ var red = RenderSample.SimulateCvd(new Color(0.8f, 0.1f, 0.1f), RenderSample.Cvd.Deuteranopia);
+ var green = RenderSample.SimulateCvd(new Color(0.1f, 0.6f, 0.1f), RenderSample.Cvd.Deuteranopia);
+ Assert.Less(RenderSample.DeltaE(red, green), RenderSample.DeltaE(new Color(0.8f, 0.1f, 0.1f), new Color(0.1f, 0.6f, 0.1f)) * 0.5f,
+ "red and green move together for a deuteranope");
+ }
+
+ static Shader Make(string source) => ShaderUtil.CreateShaderAsset(source, false);
+ const string Good = "Pass { HLSLPROGRAM\n#pragma vertex v\n#pragma fragment f\nfloat4 v(float4 p : POSITION) : SV_POSITION { return p; }\nfloat4 f() : SV_Target { return 1; }\nENDHLSL }";
+ const string Broken = "Pass { HLSLPROGRAM\n#pragma vertex v\n#pragma fragment f\nfloat4 v(float4 p : POSITION) : SV_POSITION { return p; }\nfloat4 f() : SV_Target { return undefined_symbol; }\nENDHLSL }";
+ const string ExcludedBroken = "Pass { HLSLPROGRAM\n#pragma exclude_renderers gles3 glcore\n#pragma vertex v\n#pragma fragment f\nfloat4 v(float4 p : POSITION) : SV_POSITION { return p; }\nfloat4 f() : SV_Target { return undefined_symbol; }\nENDHLSL }";
+
+ [Test]
+ public void TheGles3CheckPassesAGoodShaderAndCatchesABrokenOne()
+ {
+ CollectionAssert.IsEmpty(ShaderChecks.Gles3Errors(Shader.Find("Statecraft/HexSelection")));
+ var broken = Make("Shader \"Test/Broken\" { SubShader { " + Broken + " } }");
+ try { CollectionAssert.IsNotEmpty(ShaderChecks.Gles3Errors(broken)); }
+ finally { Object.DestroyImmediate(broken); }
+ }
+
+ /// <summary>Negative controls (review C2): a subshader built for other APIs is not this check's business, but a shader
+ /// with nothing built for GLES3 fails.</summary>
+ [Test]
+ public void SubshadersThatExcludeGles3AreSkippedButOneMustCompile()
+ {
+ Assert.IsTrue(ShaderChecks.ExcludesGles3("#pragma target 4.5\n#pragma exclude_renderers gles3 glcore\n"));
+ Assert.IsTrue(ShaderChecks.ExcludesGles3("#pragma only_renderers metal vulkan d3d11\n"));
+ Assert.IsFalse(ShaderChecks.ExcludesGles3("#pragma only_renderers gles3 metal\n#pragma exclude_renderers d3d11\n"));
+ var mixed = Make("Shader \"Test/Mixed\" { SubShader { " + ExcludedBroken + " } SubShader { " + Good + " } }");
+ var none = Make("Shader \"Test/None\" { SubShader { " + ExcludedBroken + " } }");
+ try
+ {
+ CollectionAssert.IsEmpty(ShaderChecks.Gles3Errors(mixed), "the excluded subshader is skipped, the other compiles");
+ var errors = ShaderChecks.Gles3Errors(none);
+ Assert.AreEqual(1, errors.Count, string.Join("\n", errors));
+ StringAssert.Contains("no subshader", errors[0]);
+ }
+ finally { Object.DestroyImmediate(mixed); Object.DestroyImmediate(none); }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/VisualHarnessTests.cs.meta b/unity/Assets/Tests/EditMode/VisualHarnessTests.cs.meta
new file mode 100644
index 000000000..b16dd580a
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/VisualHarnessTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 7c370beab327140478ab549647839d4b
\ No newline at end of file