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(unity): WebGL terrain profile; release build, browser checks and the owner's itch.io steps

eyalgoland450566d76b8
diff --git a/docs/dev-setup.md b/docs/dev-setup.md
index e0283d57d..9a5ff65cc 100644
--- a/docs/dev-setup.md
+++ b/docs/dev-setup.md
@@ -11,3 +11,19 @@
## After cloning
- Run `tools/build_sim_for_unity.sh` before opening `unity/`. The sim DLLs are build output and are git-ignored.
+
+## Builds and browser checks (M3)
+- Web build: `"$UNITY" -batchmode -quit -projectPath unity -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression disabled -logFile "$PWD/unity-build-web.log"`
+ (`-compression` is `disabled`, `gzip` or `brotli`; output in `unity/Builds/Web-<compression>/`, about 2 minutes).
+- macOS IL2CPP build: `"$UNITY" -batchmode -quit -projectPath unity -buildTarget OSXUniversal -executeMethod Statecraft.Game.EditorTools.Build.Mac -logFile "$PWD/unity-build-mac.log"`
+ (output `unity/Builds/Mac/Statecraft.app`).
+- Browser check: `uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&smoke=5" --expect "GOLDEN OK 1952" --expect "SMOKE OK 5 turns"`.
+ It uses Chrome for Testing from the Playwright cache (`~/Library/Caches/ms-playwright/chromium-1228` on this Mac;
+ 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). Desktop players take `-golden`, `-smoke N`, `-profile`
+ and `-camlog`. The console also shows `GAME OK <date> turn <n> hash <h>` at start and `TURN <n> <date> hash <h>` per turn.
+- 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/.
+ A Brotli build needs `Content-Encoding: br`; serve it with web_check's handler (command in `docs/m3-release.md`).
diff --git a/docs/m3-release.md b/docs/m3-release.md
new file mode 100644
index 000000000..c749f34b9
--- /dev/null
+++ b/docs/m3-release.md
@@ -0,0 +1,104 @@
+# M3 release: the browser build
+
+## What ships
+- **Folder and zip:** `unity/Builds/Web-brotli/` uses Brotli compression with no decompression fallback. It is zipped as `unity/Builds/statecraft-m3-web.zip`, with `index.html` at the zip root. Both are build output and are not committed.
+- **Built by:** `"$UNITY" -batchmode -quit -projectPath unity -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression brotli -logFile "$PWD/unity-build-web-br.log"`, then `(cd unity/Builds/Web-brotli && rm -f ../statecraft-m3-web.zip && zip -qr ../statecraft-m3-web.zip .)`.
+- **Verified locally by:** `uv run tools/web_check.py unity/Builds/Web-brotli --query "golden&smoke=5" --expect "GOLDEN OK 1950" --expect "GOLDEN OK 1952" --expect "SMOKE OK 5 turns"`. This runs both golden hashes in the WebGL IL2CPP player, then plays five turns through the UI's own buttons.
+ - Result, 2026-10-10: `GOLDEN OK 1950 ee5d0826…`, `GOLDEN OK 1952 91bb6fb5…`, `SMOKE OK 5 turns 1948-06-19 7004c29a…`, then PASS.
+- **Size:**
+ - The folder is 23 MB (`du -sh`) in 36 files. itch.io allows 1,000 files.
+ - The zip is 20 MB (20,862,385 bytes).
+ - `StreamingAssets/map/heightmap.r16` (8 MB) is served as is, outside Unity's compression. Making it smaller is deferred to M5.
+- **Play it locally:** serve the folder with web_check's handler, which sends `Content-Encoding: br` for `*.br`. Plain `python3 -m http.server` does not, so the Brotli build would not load. Then open http://localhost:8000/.
+ ```
+ python3 -c "import sys,functools,http.server; sys.path.insert(0,'tools'); import web_check as w; http.server.ThreadingHTTPServer(('127.0.0.1',8000), functools.partial(w.Handler, directory='unity/Builds/Web-brotli')).serve_forever()"
+ ```
+ The uncompressed build also works with `python3 -m http.server 8000 --directory unity/Builds/Web-disabled`.
+- **Console lines a browser check can rely on:**
+ - `GAME OK <date> turn <n> hash <state hash>` at start (a new game, or the autosave continued).
+ - `TURN <n> <date> hash <state hash>` after every End Turn.
+ - `CAMERA distance=<m> yaw=<deg>` with `?camlog`.
+ - `PROFILE ...` with `?profile`.
+
+## WebGL terrain profile
+Results from `?profile`: 300 frames per setting after 60 warm-up frames, from the diorama camera over central Israel. All runs were in Chrome for Testing 1228 with `--disable-frame-rate-limit --disable-gpu-vsync`.
+
+| `heightmapPixelError` | headless (`web_check.py`) avg / p95 ms | headed, Metal (Apple M5 Pro, 1728x858) avg / p95 ms |
+|---|---|---|
+| 1 (shipped; keeps the hex overlay draped) | 4.92 / 7.00 | 5.38 / 7.00 |
+| 5 (Unity's default) | 1.51 / 2.00 | 2.19 / 4.00 |
+
+**Decision: keep 1.** The p95 is 7 ms, far under the 33 ms of 30 fps (M2 ruling K2: above 1, the hex overlay sinks into valleys).
+
+## Checks in a real browser (headed Chrome for Testing, ANGLE Metal), 2026-10-10
+These were run with a small Chrome DevTools Protocol driver: `uv run --with websockets==15.0.1`, with a temporary profile and a fixed origin, `http://localhost:8765`.
+
+### Rendering
+- The terrain, hex overlay, settlement markers and labels, all UI Toolkit panels and the minimap render. Nothing is magenta.
+- WebGL reports `ANGLE (Apple, ANGLE Metal Renderer: Apple M5 Pro)`.
+- Three hidden URP utility shaders report "not supported on this GPU": `Hidden/CoreSRP/CoreCopy`, `Hidden/Universal Render Pipeline/StencilDitherMaskSeed` and `Hidden/Universal/HDRDebugView`. They report the same in headless Chrome. They serve features this build does not use (HDR debug view, LOD cross-fade dither, a render-graph copy path), and the frame renders correctly without them.
+- The only 404 is `/favicon.ico`.
+
+### Wheel zoom
+- One wheel notch (Chrome sends 100 px) zooms by 10%: 120000 m to 108000 m to 97200 m.
+- A 300 px burst zooms by three steps.
+- The wheel over a panel does not zoom.
+- Before this release a notch moved the camera only 0.08%. The Input System's default scroll behaviour already normalises a notch to 1, and the controller divided by 120 again; that division is now removed.
+
+### Saves
+Each step below passed:
+
+| Step | Result |
+|---|---|
+| (a) Two turns, then a hard reload | Continued on the same turn and hash (turn 2, 1948-05-29). |
+| (b) Tab closed immediately after End Turn's `TURN` line, then a new tab | Continued on turn 3. |
+| (b) Whole browser quit immediately after a turn, then relaunched on the same profile | Continued on turn 4. |
+| (c, local) Same origin, a second upload directory (`/upload-b/`, as an itch.io re-upload does) | Continued on turn 4. |
+| (d) IndexedDB | Database `/idbfs`, store `FILE_DATA`, keys `/idbfs/statecraft-saves` and `/idbfs/statecraft-saves/autosave.txt`. No `JS_FileSystem_Sync` deprecation message. |
+| (e) A private browser context (`Target.createBrowserContext`) | The game starts (a new game) and plays a turn. A second private context starts a new game again; no persistence is expected there. |
+
+Firefox is not installed on the development Mac, so the Firefox check is open.
+
+## OWNER STEP: upload to itch.io
+This needs the owner's itch.io account and is never automated.
+1. Sign in at https://itch.io. Go to Dashboard, then **Create new project**.
+2. Set the title to "Statecraft: Israel (M3 preview)", Kind of project to **HTML**, and Classification to Games.
+3. Under Uploads, upload `unity/Builds/statecraft-m3-web.zip` and tick **This file will be played in the browser**.
+4. Embed options:
+ - Viewport **1920 × 1080**.
+ - Tick **Fullscreen button**.
+ - Leave **SharedArrayBuffer support** off; the build uses no threads.
+5. Visibility & access:
+ - Choose **Draft** first.
+ - Open the page and play a turn. The browser console (DevTools) must show `GAME OK` and then `TURN 1`.
+ - Then choose **Restricted** (password) or **Public**.
+6. Record the page URL below under "Published at".
+
+itch.io serves `.br` files with `Content-Encoding: br`, because it detects the extension, so no server settings are needed.
+
+Published at: (owner fills in)
+
+## Saves on itch.io: the fix and its test
+- **Problem:** on WebGL, `Application.persistentDataPath` is `/idbfs/<MD5 of the page's directory URL>`. itch.io serves every upload from a new URL, so a new upload would hide the saves made with the previous one.
+- **Fix (Task 21):** the autosave lives at the fixed path `/idbfs/statecraft-saves/autosave.txt`.
+ - The template sets `autoSyncPersistentDataPath: true`, so closing the file persists it to IndexedDB.
+ - IndexedDB is per origin, so saves survive re-uploads to the same project and stay separate per browser profile.
+ - The local checks above passed: reload, tab close, browser restart, and a second directory on the same origin.
+- **Test plan (OWNER STEP, after the first two uploads):**
+ 1. Upload A as above. Play two turns (press End Turn twice) and note the date and turn in the top bar.
+ 2. Reload the page. Expected: the game continues on that date. The console line `GAME OK <date> turn <n> hash ...` matches the last `TURN` line.
+ 3. Upload build B to the same project, replacing A. Rebuild first if anything changed.
+ 4. Open the page again with a hard reload. Expected: the game continues on the same date and turn.
+ - If the content changed between A and B, a message reads "This save was made with different game content; the replayed game may differ."
+ - **Pass** if the date and turn match.
+ 5. If the game starts again on 15 May 1948, the fixed folder did not persist across uploads. Record the browser and the page URL here, and use the deferred fallback (a localStorage bridge, or save export and import).
+ 6. Record the result here: date, browser, pass or fail.
+
+Result: (owner fills in)
+
+## Known limits of this build
+- Placeholder settlement markers; per-era art is M4.
+- No Diplomacy screen or legacy report (M4).
+- English only.
+- The headless smoke plays five turns; a full-slice smoke is M4.
+- Three hidden URP utility shaders are unsupported on WebGL 2 (see above).
diff --git a/unity/Assets/Scripts/Map/PixelErrorProfile.cs b/unity/Assets/Scripts/Map/PixelErrorProfile.cs
new file mode 100644
index 000000000..11c029230
--- /dev/null
+++ b/unity/Assets/Scripts/Map/PixelErrorProfile.cs
@@ -0,0 +1,47 @@
+#nullable enable
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>Measures frame time with the terrain's heightmapPixelError at 1 (M2's value, which keeps the hex overlay
+ /// draped visibly) and at Unity's default 5, from the diorama camera over central Israel, then restores the M2 value.
+ /// Logs "PROFILE pixelError=&lt;e&gt; frames=&lt;n&gt; avg_ms=&lt;a&gt; p95_ms=&lt;p&gt;" per setting and "PROFILE done".
+ /// Asked for by "profile" in the WebGL page URL (a whole query parameter, UrlFlags) or -profile on desktop.</summary>
+ public static class PixelErrorProfile
+ {
+ public const int WarmupFrames = 60, MeasuredFrames = 300;
+
+ public static bool Requested() =>
+ Requested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
+
+ public static bool Requested(string? url, string[] args, bool webgl) =>
+ webgl ? Boot.UrlFlags.Has(url, "profile") : args.Contains("-profile");
+
+ public static string Line(float pixelError, List<float> 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 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);
+ }
+
+ public static IEnumerator Run(Terrain terrain)
+ {
+ foreach (var pixelError in new[] { 1f, 5f })
+ {
+ terrain.heightmapPixelError = pixelError;
+ for (int i = 0; i < WarmupFrames; i++) yield return null;
+ var times = new List<float>(MeasuredFrames);
+ for (int i = 0; i < MeasuredFrames; i++) { yield return null; times.Add(Time.unscaledDeltaTime * 1000f); }
+ Debug.Log(Line(pixelError, times));
+ }
+ terrain.heightmapPixelError = MapBuilder.TerrainPixelError;
+ Debug.Log("PROFILE done");
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/PixelErrorProfile.cs.meta b/unity/Assets/Scripts/Map/PixelErrorProfile.cs.meta
new file mode 100644
index 000000000..f511950a0
--- /dev/null
+++ b/unity/Assets/Scripts/Map/PixelErrorProfile.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 5d0306ecb9dc6462b85a4990d126dd7f
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 6285f7c36..89d8654a5 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -152,9 +152,16 @@ namespace Statecraft.Game.UI
mini.Clicked += (lon, lat) => { camRig.LookAt = map.Frame.ToWorld(lon, lat, 0); camRig.Apply(); SyncMinimap(); };
Action onChanged = RenderPlacementsIfChanged;
bridge.Changed += onChanged;
+ // One console line per turn, so a browser run (reload, Continue) can be checked against the hash.
+ Action<IReadOnlyList<Rejection>> onTurn = _ =>
+ Debug.Log(FormattableString.Invariant($"TURN {bridge.State.Turn} {bridge.State.Date:yyyy-MM-dd} hash {bridge.State.Hash()}"));
+ bridge.TurnEnded += onTurn;
+ logCamera = CameraLogRequested();
+ loggedDistance = loggedYaw = float.NaN;
owned.Add(new Undo(() =>
{
bridge.Changed -= onChanged;
+ bridge.TurnEnded -= onTurn;
pointer.HexClicked -= onHex;
if (pointer.IsOverUi == overUi) pointer.IsOverUi = null;
if (cameraController.IsOverUi == overUi) cameraController.IsOverUi = null;
@@ -166,12 +173,13 @@ namespace Statecraft.Game.UI
SyncMinimap();
if (notes.Count > 0) toast.Show(notes);
- Debug.Log(FormattableString.Invariant($"GAME OK {bridge.State.Date:yyyy-MM-dd} turn {bridge.State.Turn}"));
+ Debug.Log(FormattableString.Invariant($"GAME OK {bridge.State.Date:yyyy-MM-dd} turn {bridge.State.Turn} hash {bridge.State.Hash()}"));
if (smoke > 0)
{
if (Application.isPlaying) StartCoroutine(Smoke(root, bridge, card, smoke, Debug.Log));
else Debug.LogWarning("SMOKE FAIL the smoke run needs play mode or a player");
}
+ if (Application.isPlaying && PixelErrorProfile.Requested()) StartCoroutine(PixelErrorProfile.Run(map.Terrain));
}
T Own<T>(T d) where T : IDisposable { owned.Add(d); return d; }
@@ -182,7 +190,7 @@ namespace Statecraft.Game.UI
StopAllCoroutines();
for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
owned.Clear();
- minimap = null; rig = null; drawn = null;
+ minimap = null; rig = null; drawn = null; logCamera = false;
}
/// <summary>Draws the placements only when State.Placements differs from what was drawn (every order and every turn
@@ -202,7 +210,26 @@ namespace Statecraft.Game.UI
minimap.SetView(map.Frame, rig.LookAt, rig.Distance);
}
- void Update() => SyncMinimap();
+ bool logCamera;
+ float loggedDistance = float.NaN, loggedYaw = float.NaN;
+
+ /// <summary>"camlog" in the WebGL page URL (a whole query parameter) or -camlog on desktop: log the camera distance and
+ /// yaw whenever they change (checks the wheel-zoom step in a real browser).</summary>
+ internal static bool CameraLogRequested(string? url, string[] args, bool webgl) =>
+ webgl ? Regex.IsMatch(url ?? "", @"[?&]camlog(?=&|#|=|$)") : Array.IndexOf(args, "-camlog") >= 0;
+
+ static bool CameraLogRequested() =>
+ CameraLogRequested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
+
+ internal static string CameraLine(float distance, float yaw) => FormattableString.Invariant($"CAMERA distance={distance:0} yaw={yaw:0.0}");
+
+ void Update()
+ {
+ SyncMinimap();
+ if (!logCamera || rig == null || (rig.Distance == loggedDistance && rig.Yaw == loggedYaw)) return;
+ loggedDistance = rig.Distance; loggedYaw = rig.Yaw;
+ Debug.Log(CameraLine(rig.Distance, rig.Yaw));
+ }
/// <summary>Plays turns the way a player does: answers each open event by pressing the card's first option button,
/// then presses End Turn. Logs "SMOKE turn &lt;n&gt; &lt;date&gt; refused &lt;k&gt;" per turn through <paramref name="log"/>,
diff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.cs
index bb246264b..b4dadd145 100644
--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs
+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs
@@ -428,4 +428,40 @@ public class GameSceneTests
Assert.AreEqual(0, Desk("Statecraft"));
Assert.AreEqual(0, GameRoot.SmokeTurns("http://localhost/?smoke=5", new[] { "Statecraft" }, false), "desktop reads only the command line");
}
+
+ // Task 24 (persistence gate, zoom check): the start and every turn are logged with the state hash, and ?camlog logs the
+ // camera distance, so a browser run can be checked from the console alone.
+ [Test]
+ public void TheStartAndEachTurnAreLoggedWithTheStateHash()
+ {
+ var lines = new List<string>();
+ Application.LogCallback capture = (m, _, __) => lines.Add(m);
+ Application.logMessageReceived += capture;
+ try
+ {
+ var root = Boot();
+ var start = root.Bridge!.State;
+ root.Bridge.EndTurn();
+ var s = root.Bridge.State;
+ CollectionAssert.Contains(lines, FormattableString.Invariant($"GAME OK {start.Date:yyyy-MM-dd} turn {start.Turn} hash {start.Hash()}"));
+ CollectionAssert.Contains(lines, FormattableString.Invariant($"TURN {s.Turn} {s.Date:yyyy-MM-dd} hash {s.Hash()}"));
+ root.enabled = false;
+ lines.Clear();
+ root.Bridge.EndTurn();
+ Assert.IsFalse(lines.Any(l => l.StartsWith("TURN ")), "a disabled GameRoot logs nothing");
+ }
+ finally { Application.logMessageReceived -= capture; }
+ }
+
+ [Test]
+ public void TheCameraLogIsAWholeQueryParameter()
+ {
+ Assert.IsTrue(GameRoot.CameraLogRequested("http://localhost/?camlog", new string[0], true));
+ Assert.IsTrue(GameRoot.CameraLogRequested("http://localhost/?golden&camlog", new string[0], true));
+ Assert.IsFalse(GameRoot.CameraLogRequested("http://localhost/?camlogs", new string[0], true));
+ Assert.IsFalse(GameRoot.CameraLogRequested("http://localhost/camlog/", new string[0], true));
+ Assert.IsTrue(GameRoot.CameraLogRequested(null, new[] { "x", "-camlog" }, false));
+ Assert.IsFalse(GameRoot.CameraLogRequested(null, new[] { "x" }, false));
+ Assert.AreEqual("CAMERA distance=120000 yaw=0.0", GameRoot.CameraLine(120000f, 0f));
+ }
}
diff --git a/unity/Assets/Tests/EditMode/PixelErrorProfileTests.cs b/unity/Assets/Tests/EditMode/PixelErrorProfileTests.cs
new file mode 100644
index 000000000..0b3108780
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/PixelErrorProfileTests.cs
@@ -0,0 +1,27 @@
+using System.Collections.Generic;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+
+public class PixelErrorProfileTests
+{
+ [Test]
+ public void TheProfileLineReportsAverageAndP95()
+ {
+ var frames = new List<float>();
+ for (int i = 1; i <= 100; i++) frames.Add(i);
+ Assert.AreEqual("PROFILE pixelError=1 frames=100 avg_ms=50.50 p95_ms=95.00", PixelErrorProfile.Line(1f, frames));
+ }
+
+ [TestCase("http://localhost:8000/index.html?profile", true)]
+ [TestCase("http://localhost:8000/index.html?golden&profile", true)]
+ [TestCase("https://html.itch.zone/html/123/profile-pics/index.html", false)]
+ public void TheProfileFlagIsAQueryParameter(string url, bool expected) =>
+ Assert.AreEqual(expected, PixelErrorProfile.Requested(url, new string[0], true));
+
+ [Test]
+ public void DesktopTakesTheCommandLineFlag()
+ {
+ Assert.IsTrue(PixelErrorProfile.Requested(null, new[] { "Statecraft", "-profile" }, false));
+ Assert.IsFalse(PixelErrorProfile.Requested("http://x/?profile", new[] { "Statecraft" }, false));
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/PixelErrorProfileTests.cs.meta b/unity/Assets/Tests/EditMode/PixelErrorProfileTests.cs.meta
new file mode 100644
index 000000000..1a83e4f2a
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/PixelErrorProfileTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 79b2b1ea366434f31955beb34f4452c2
\ No newline at end of file