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(map): runtime quality fallback on the web tier (#44)

eyalgolan6cec33580964
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec5c11ec8..d00bb3152 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,9 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
- Unity-MCP 0.93.3 (`com.ivanmurzak.unity.mcp`, from OpenUPM) as the standard AI-agent bridge in the editor, local
Custom mode with token auth only (held by `UnityMcpGuard`). It stays offline in batch mode, opens no window there, and is
left out of player builds.
+- A runtime quality fallback for slow machines in the browser: when frames stay slower than 30 fps, the game lowers its
+ render scale (to 0.9, then 0.8) and then turns the tilt-shift off, and steps back up when frames are comfortably fast
+ again. Presentation only; `?nofallback` turns it off (#44).
### Changed
- The historical AI no longer sends an order the turn's attention cannot cover (the rule the UI's order queue applies),
diff --git a/docs/m3-release.md b/docs/m3-release.md
index 769cb03dd..d60ccc61a 100644
--- a/docs/m3-release.md
+++ b/docs/m3-release.md
@@ -60,6 +60,8 @@ start of M4, as a private Draft (owner ruling, 2026-10-10); their sections below
- `TURN <n> <date> hash <state hash>` after every End Turn.
- `CAMERA distance=<m> yaw=<deg>` with `?camlog`.
- `PROFILE ...` with `?profile`.
+ - `QUALITY level=<n> scale=<s> tiltshift=<on|off> p95_ms=<ms>` whenever the runtime quality fallback steps (WebGL only;
+ off with `?nofallback`; docs/visual-v1.md "Runtime quality fallback").
- `BOOT phase=<name> at=<ms> ms dt=<ms> ms` for each boot phase with `?bootlog` (playtest 2, P2-1).
- `NAV f=<frame> ...` with `?navlog`: every raw mouse event, UI pointer and submit event, screen toggle and map click,
with its frame (playtest 2, P2-4).
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 5b856d5a6..e0845ca05 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -14,7 +14,8 @@ Plan: `docs/superpowers/plans/2026-10-11-statecraft-visual-v1.md`. Promo targets
`--stall 120`), headed through `headed.py profile`. Both fix the page's viewport to exactly 1920x1080 CSS pixels at the
DPR over CDP (`Emulation.setDeviceMetricsOverride`, before the page loads), so headed and headless runs draw the same
pixels even when the laptop screen clamps the headed window (its final composite is then scaled; the backbuffer is not).
- Every line states `res=` and the render `scale=`, and both tools FAIL on a `res=` other than 1920x1080 times the DPR
+ The runtime quality fallback (issue #44, "Runtime quality fallback") is off under `?vprofile`, `?profile` and `?shot`,
+ so these see the tier's own scale and tilt-shift. Every line states `res=` and the render `scale=`, and both tools FAIL on a `res=` other than 1920x1080 times the DPR
(and on a stall: no console line for 120 s). Read the `PROFILE summary` lines: a feature costs
`median(all) - median(-name)`. The WebGL frame clock is quantised to about 1 ms: averages are fine, but every p95 is a
whole millisecond, so a p95 budget is only good to about 1 ms.
@@ -715,6 +716,7 @@ beyond budget + the larger spread.
| Baked shading texture | block-compressed | block-compressed | review minor 9: recorded, not changed (mobile browsers are outside the 1920x1080 target) |
| WebGPU, GPU Resident Drawer, compute | not used | not used | research notes 2.1 (an M5 evaluation) |
| Weak GPU | SwiftShader run passes golden and shots | — | `captures/visual/t10-swiftshader` (both GOLDEN OK lines and SHOT done; gameplay03 saturation / contrast / warmth 0.5656 / 0.1960 / 0.0773 against the GPU's 0.5655 / 0.1960 / 0.0771) |
+| Runtime quality fallback (issue #44) | on | off | see "Runtime quality fallback" below: when the frame-time p95 stays over the 30 fps floor, render scale 1.0 -> 0.9 -> 0.8, then the tilt-shift off; back up in reverse |
Colour after the decisions (WebGL `?shot`, t10-tiers against t-merge-r3): diorama02 saturation 0.4694 -> 0.4686, contrast
0.2034 -> 0.2032, warmth 0.1045 -> 0.1038 (bars: warmth 0.087-0.145, saturation <= 0.48); gameplay03 saturation 0.5646 ->
@@ -731,6 +733,51 @@ The `-bloom` lines below come from the temporary toggle (`8d45a93`); in the fina
slower than `all`; the pose runs at about 2 ms, at the WebGL clock's ~1 ms resolution, and the readings look bimodal
(~2.0 / ~2.4 ms). Unexplained; it changes no decision (every gameplay03 cost is far inside its budget).
+### Runtime quality fallback (issue #44)
+The Deferred row "Runtime quality fallback" (review I1), sized by the DPR-2 stress numbers above. `QualityFallback`
+(pure logic) and `QualityFallbackDriver` (feeds it `Time.unscaledDeltaTime`, applies its step), attached by
+`CameraRig.Init` through the map's teardown like the visual toggles.
+- **Steps:** level 0 is the tier (scale 1.0, tilt-shift on); 1: scale 0.9; 2: scale 0.8 (the research's 0.8-1.0 dynamic
+ range, notes 2.3); 3: scale 0.8 and the tilt-shift off. One step per decision, up in reverse. The scale is the active
+ URP asset's `renderScale` (never above the tier's own); the tilt-shift uses its own `TiltShift.FallbackOff`, so stepping
+ up never turns on a tilt-shift the player (`?notiltshift`) or a profile turned off. The map's teardown puts both back.
+- **Window: 3 s, back to back, one decision each.** The p95 of a 3 s window is over only when at least 5% of its frames
+ are (5 of 90 at 30 fps), so a one-off hitch (End Turn's redraw, a GC, a first shader compile) never trips it and a real
+ shortfall does within 3 s. Nothing is measured in the first 3 s after the map is built, or 0.5 s after each change; a
+ frame over 1 s (a hidden tab coming back) drops the window; a window needs at least 10 frames.
+- **Down: p95 > 34 ms.** The floor is 33 ms (30 fps). The WebGL frame clock is quantised to about 1 ms, so exactly 30 fps
+ (a 30 Hz cap from a display or a battery saver, or vsync halving 60 Hz) reads as 33 and 34 ms frames: that meets the
+ floor, and a lower quality could not raise a capped rate.
+- **Up: 3 windows in a row (9 s) with p95 < 20 ms; hysteresis.** One step up draws at most 1.27 times the pixels
+ (0.8 -> 0.9, 0.9 -> 1.0), so a fill-bound 20 ms frame lands near 25 ms, under the floor; the tilt-shift costs under
+ 1.5 ms (`-tiltshift` above: 0.29 ms at DPR 2). Windows between 20 and 34 ms change nothing and restart the count. A step up
+ undone within two windows doubles the windows the next one needs (3, 6, 12 ... at most 48, 2.4 minutes), so a device on
+ the edge settles instead of flipping.
+- **Web tier only.** `QualityFallback.Wanted` is true only in the WebGL player: the desktop tier is the development and
+ capture target (its renders and `-vprofile` must show the tier's own look), and in the editor a scale change would
+ change the URP asset. Even on WebGL it stays off under `?vprofile`, `?profile` and `?shot` (instruments that must see the
+ tier as configured) and with `?nofallback`; every change logs `QUALITY level=<n> scale=<s> tiltshift=<on|off>
+ p95_ms=<ms>`.
+- **Presentation only:** it reads no sim state and writes only the render scale and the tilt-shift flag, so turns, hashes
+ and saves cannot change. The goldens and the 5-turn smoke match with it in the build: `uv run tools/web_check.py
+ unity/Builds/Web-disabled --query "golden&smoke=5"` with the three `--expect` values from `docs/determinism.md`: PASS.
+- **Tests** (`QualityFallbackTests`, EditMode, synthetic frame times): the step order and range, one step per window and
+ not before a full window, nothing during start-up, hitches, a pause and 33/34 ms frames do not trigger, recovery in
+ reverse only after 3 good windows, the dead band holds and restarts the count, a failed step up doubles the wait (capped);
+ integration: no driver in the editor; with the web tier's answer forced, `MapScene.Build` attaches one, its steps reach
+ the URP asset and `TiltShift.FallbackOff` (not `TiltShift.Enabled`), and a rebuild or teardown removes it and restores the
+ scale.
+- **In a real browser** (headed Chrome for Testing, ANGLE Metal, 1920x1080 at DPR 1, under `machine_lock.py --exclusive
+ --wait-unity`, a scratch CDP script on `headed.Browser`): 30 s idle at `--cpu 1`, no `QUALITY` line. With CPU throttling
+ at 20x from t = 30 s: `QUALITY level=1 scale=0.90 tiltshift=on p95_ms=97.00`, `level=2 scale=0.80 tiltshift=on
+ p95_ms=97.00`, `level=3 scale=0.80 tiltshift=off p95_ms=107.00` (level 3 at t = 39.6 s). Throttling lifted at t = 49.6 s:
+ `level=2 ... tiltshift=on p95_ms=17.00`, `level=1 scale=0.90`, `level=0 scale=1.00` (t = 77.4 s, about 9.5 s apart), then
+ no line in the next 15 s. At DPR 2 (the fill-rate stress proxy, frame rate uncapped) 60 s idle: no `QUALITY` line, as the
+ DPR-2 p95 (20 ms at diorama02) is under the floor.
+- **Boot with it (`headed.py boot --runs 3`, on top of the packed heightmap):** `--cpu 1` `BOOT map_build_ms median=472`,
+ `BOOT first_frame_ms median=3609`; `--cpu 4` `map_build_ms median=1983`, `first_frame_ms median=7158`: within the boot
+ budget (exit 0).
+
### Final measurements
Step 1 headless (scale 0.80):
- `PROFILE summary visual=all pose=gameplay03 runs=3 median_avg_ms=2.03 spread_ms=0.16 median_p95_ms=3.00`
diff --git a/unity/Assets/Scripts/Map/CameraRig.cs b/unity/Assets/Scripts/Map/CameraRig.cs
index bdb2467a7..0008581cb 100644
--- a/unity/Assets/Scripts/Map/CameraRig.cs
+++ b/unity/Assets/Scripts/Map/CameraRig.cs
@@ -28,6 +28,10 @@ namespace Statecraft.Game.Map
/// (MapScene registers it with MapRuntimeAssets).</summary>
public Volume Volume { get; private set; }
+ /// <summary>Whether Init attaches the runtime quality fallback (QualityFallback.Wanted: the WebGL tier, no instrument
+ /// running). A seam: the integration test forces the web tier's answer in the editor.</summary>
+ internal static Func<bool> FallbackWanted = QualityFallback.Wanted;
+
public void Init()
{
// Undo actions an earlier Init left behind (Init called outside MapScene.Build) run now instead of piling up.
@@ -52,6 +56,9 @@ namespace Statecraft.Game.Map
TeardownActions.Add(VisualToggles.Register("tiltshift", on => TiltShift.Enabled = on));
TeardownActions.Add(VisualToggles.Register("grade", on => MapGrade.SetActive(vol.profile, on)));
if (TiltShift.OffRequested()) TiltShift.Enabled = false;
+ // After the tilt-shift's Reset, so the map's teardown removes the driver (restoring the tier's render scale and
+ // clearing FallbackOff) before resetting the tilt-shift.
+ TeardownActions.Add(QualityFallbackDriver.Attach(gameObject, FallbackWanted()));
initialised = true;
Apply();
}
diff --git a/unity/Assets/Scripts/Map/QualityFallback.cs b/unity/Assets/Scripts/Map/QualityFallback.cs
new file mode 100644
index 000000000..6aa2f6351
--- /dev/null
+++ b/unity/Assets/Scripts/Map/QualityFallback.cs
@@ -0,0 +1,142 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using Statecraft.Game.Boot;
+using UnityEngine;
+using UnityEngine.Rendering.Universal;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>The web tier's runtime quality fallback (issue #44; visual v1 Deferred row "Runtime quality fallback"):
+ /// when the frame-time p95 stays over the 30 fps floor, lower the render scale, then turn the tilt-shift off; when it
+ /// stays comfortably under, step back up in reverse. Pure logic (frame times in, a step out), so tests drive it with
+ /// synthetic frames; QualityFallbackDriver feeds it the player's frames and applies its step. Presentation only: it
+ /// reads nothing from the sim and changes no sim state, so turns, hashes and saves are the same on every step.
+ ///
+ /// Why these numbers (docs/visual-v1.md "Runtime quality fallback"):
+ /// - Window 3 s: the p95 of a 3 s window needs at least 5% of the frames slow (5 of 90 at 30 fps), so a one-off hitch
+ /// (an End Turn redraw, a GC, a first shader compile: 1-2 frames) never trips it, while a real shortfall (every frame
+ /// slow) does within 3 s. Windows are back to back; one decision per window.
+ /// - Step down when a window's p95 is over the 30 fps floor (33 ms, research notes 2.3) by more than the WebGL clock's
+ /// resolution: p95 > OverMs = 34 ms. The WebGL frame clock is quantised to about 1 ms, so exactly 30 fps (a display
+ /// or a battery saver capping the page at 30 Hz, or vsync halving 60 Hz) reads as 33 and 34 ms frames: that meets
+ /// the floor, and lowering the quality could not raise a capped rate anyway.
+ /// - Step up only after RecoverWindows windows in a row with p95 &lt; 20 ms. 20 ms is the hysteresis: one step up
+ /// (0.8 -> 0.9 or 0.9 -> 1.0) draws at most 1.27 times the pixels, so a fill-bound frame at 20 ms lands at about 25 ms,
+ /// under the floor; the tilt-shift costs under 1.5 ms. Between 20 and 34 ms nothing changes (the dead band).
+ /// - Settle: frames in the first 0.5 s after a change are not measured (the change reallocates render targets), nor
+ /// the first 3 s after start (scene load and shader compiles).
+ /// - A frame over 1 s is a pause (a hidden tab, a stalled load), not load: it drops the window.
+ /// - Anti-oscillation: a step up that is undone within two windows doubles the windows the next step up needs
+ /// (3, 6, 12 ... at most 48, 2.4 minutes), so a device on the edge settles instead of flipping every 10 s.</summary>
+ public sealed class QualityFallback
+ {
+ public readonly struct Step
+ {
+ public readonly float RenderScale; public readonly bool TiltShift;
+ public Step(float renderScale, bool tiltShift) { RenderScale = renderScale; TiltShift = tiltShift; }
+ public override string ToString() => string.Format(CultureInfo.InvariantCulture, "scale={0:0.00} tiltshift={1}", RenderScale, TiltShift ? "on" : "off");
+ }
+
+ /// <summary>Level 0 is the tier's own look; each level down costs less. Render scale first, within the research's
+ /// 0.8-1.0 dynamic range (notes 2.3), then the tilt-shift.</summary>
+ public static readonly IReadOnlyList<Step> Steps = new[] { new Step(1f, true), new Step(0.9f, true), new Step(0.8f, true), new Step(0.8f, false) };
+
+ public const float FloorMs = 33f, OverMs = 34f, RecoverMs = 20f, WindowSeconds = 3f, SettleSeconds = 0.5f, StartupSeconds = 3f, PauseMs = 1000f;
+ public const int MinWindowFrames = 10, RecoverWindows = 3, MaxRecoverWindows = 48, FailedRecoveryWindows = 2;
+
+ public int Level { get; private set; }
+ public Step Current => Steps[Level];
+ /// <summary>The p95 of the last complete window (NaN before the first).</summary>
+ public float LastP95 { get; private set; } = float.NaN;
+ /// <summary>Windows measured so far (diagnostics and tests).</summary>
+ public int Windows { get; private set; }
+ /// <summary>Windows in a row under RecoverMs that the next step up needs (doubles after a failed step up).</summary>
+ public int RecoverNeeded { get; private set; } = RecoverWindows;
+
+ readonly List<float> window = new List<float>();
+ float windowMs, settleMs = StartupSeconds * 1000f;
+ int goodWindows, windowsSinceStepUp = int.MaxValue;
+
+ /// <summary>Feeds one frame's time in ms; true when it moved Level (the caller then applies Current).</summary>
+ public bool Feed(float frameMs)
+ {
+ if (float.IsNaN(frameMs) || frameMs < 0f) return false;
+ if (frameMs > PauseMs) { window.Clear(); windowMs = 0f; return false; }
+ if (settleMs > 0f) { settleMs -= frameMs; return false; }
+ window.Add(frameMs); windowMs += frameMs;
+ if (windowMs < WindowSeconds * 1000f) return false;
+ bool enough = window.Count >= MinWindowFrames;
+ var p95 = enough ? FrameStats.Summary(window).p95 : float.NaN;
+ window.Clear(); windowMs = 0f;
+ if (!enough) return false;
+ LastP95 = p95; Windows++;
+ if (windowsSinceStepUp < int.MaxValue) windowsSinceStepUp++;
+ if (p95 > OverMs)
+ {
+ goodWindows = 0;
+ if (Level == Steps.Count - 1) return false;
+ if (windowsSinceStepUp <= FailedRecoveryWindows) RecoverNeeded = Math.Min(RecoverNeeded * 2, MaxRecoverWindows);
+ windowsSinceStepUp = int.MaxValue;
+ return Move(+1);
+ }
+ if (p95 >= RecoverMs || Level == 0) { goodWindows = 0; return false; }
+ if (++goodWindows < RecoverNeeded) return false;
+ goodWindows = 0; windowsSinceStepUp = 0;
+ return Move(-1);
+ }
+
+ bool Move(int by) { Level += by; settleMs = SettleSeconds * 1000f; return true; }
+
+ /// <summary>Whether the fallback runs: the WebGL tier only (the desktop tier is the development and capture target, and
+ /// in the editor a render-scale change would write the URP asset), and never under an instrument that must see the
+ /// tier's own look (?vprofile, ?profile, ?shot) or with ?nofallback.</summary>
+ public static bool Wanted(string? url, bool webgl) =>
+ webgl && !UrlFlags.Has(url, "vprofile") && !UrlFlags.Has(url, "profile") && !UrlFlags.Has(url, "shot") && !UrlFlags.Has(url, "nofallback");
+
+ public static bool Wanted() => Wanted(Application.absoluteURL, Application.platform == RuntimePlatform.WebGLPlayer);
+
+ public string Line() => string.Format(CultureInfo.InvariantCulture, "QUALITY level={0} {1} p95_ms={2:0.00}", Level, Current, LastP95);
+ }
+
+ /// <summary>Feeds QualityFallback the player's frame times (unscaled, so a paused game still counts) and applies its step:
+ /// the active URP asset's render scale (never above the tier's own) and TiltShift.FallbackOff. CameraRig.Init attaches it
+ /// to the map camera through Attach, whose undo (run by the map's teardown) removes it and puts both back.</summary>
+ public sealed class QualityFallbackDriver : MonoBehaviour
+ {
+ public QualityFallback Controller { get; } = new QualityFallback();
+ float tierScale = 1f;
+ Action<float> setScale = _ => { };
+
+ /// <summary>Adds the driver to <paramref name="camera"/> when <paramref name="wanted"/> (QualityFallback.Wanted());
+ /// returns the undo for the map's teardown (a no-op when not wanted).</summary>
+ public static Action Attach(GameObject camera, bool wanted)
+ {
+ if (!wanted) return () => { };
+ var asset = UniversalRenderPipeline.asset;
+ var driver = camera.AddComponent<QualityFallbackDriver>();
+ driver.tierScale = asset != null ? asset.renderScale : 1f;
+ driver.setScale = s => { if (asset != null) asset.renderScale = s; };
+ var tierScale = driver.tierScale;
+ return () =>
+ {
+ if (asset != null) asset.renderScale = tierScale;
+ TiltShift.FallbackOff = false;
+ if (driver != null) { if (Application.isPlaying) Destroy(driver); else DestroyImmediate(driver); }
+ };
+ }
+
+ /// <summary>Feeds one frame (tests call it; Update feeds the real frames).</summary>
+ public void Feed(float frameMs)
+ {
+ if (!Controller.Feed(frameMs)) return;
+ var step = Controller.Current;
+ setScale(Mathf.Min(tierScale, step.RenderScale));
+ TiltShift.FallbackOff = !step.TiltShift;
+ Debug.Log(Controller.Line());
+ }
+
+ void Update() => Feed(Time.unscaledDeltaTime * 1000f);
+ }
+}
diff --git a/unity/Assets/Scripts/Map/QualityFallback.cs.meta b/unity/Assets/Scripts/Map/QualityFallback.cs.meta
new file mode 100644
index 000000000..bad2e135b
--- /dev/null
+++ b/unity/Assets/Scripts/Map/QualityFallback.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 214669bd2e558411aa1ea36ee8d8fe9b
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/TiltShift.cs b/unity/Assets/Scripts/Map/TiltShift.cs
index 4cb993824..e65bbc324 100644
--- a/unity/Assets/Scripts/Map/TiltShift.cs
+++ b/unity/Assets/Scripts/Map/TiltShift.cs
@@ -19,6 +19,11 @@ namespace Statecraft.Game.Map
public const float MaxRadiusUv = 14f / 1080f;
public const float FullStrengthDistanceM = 60000f, MinStrength = 0.35f;
public static bool Enabled = true;
+ /// <summary>Set by the web tier's runtime quality fallback (QualityFallbackDriver) at its last step. Kept apart from
+ /// Enabled (the "tiltshift" toggle, ?notiltshift), so stepping back up never turns on a tilt-shift the player or a
+ /// profile turned off. The blur draws only when Enabled and not FallbackOff.</summary>
+ public static bool FallbackOff;
+ public static bool Draws => Enabled && !FallbackOff;
/// <summary>HLSL smoothstep(p.y, p.y + p.z, |y - p.x|); a zero feather is a step at the half-width.</summary>
public static float Weight(float y, Vector4 p)
@@ -45,6 +50,7 @@ namespace Statecraft.Game.Map
public static void Reset()
{
Enabled = true;
+ FallbackOff = false;
Shader.SetGlobalVector(ParamsId, Vector4.zero);
}
diff --git a/unity/Assets/Scripts/Map/TiltShiftFeature.cs b/unity/Assets/Scripts/Map/TiltShiftFeature.cs
index 376e67f12..f14a3302b 100644
--- a/unity/Assets/Scripts/Map/TiltShiftFeature.cs
+++ b/unity/Assets/Scripts/Map/TiltShiftFeature.cs
@@ -23,7 +23,7 @@ namespace Statecraft.Game.Map
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
{
- if (material == null || pass == null || !TiltShift.Enabled || !TiltShift.HasBand) return;
+ if (material == null || pass == null || !TiltShift.Draws || !TiltShift.HasBand) return;
// Scene-view and preview cameras get no pass, so they are not forced onto an intermediate texture (review m2).
if (renderingData.cameraData.cameraType != CameraType.Game) return;
pass.Setup(material, downsample);
diff --git a/unity/Assets/Tests/EditMode/QualityFallbackTests.cs b/unity/Assets/Tests/EditMode/QualityFallbackTests.cs
new file mode 100644
index 000000000..7df0aaa1a
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/QualityFallbackTests.cs
@@ -0,0 +1,233 @@
+#nullable enable
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.Rendering.Universal;
+
+/// <summary>Issue #44: the web tier's runtime quality fallback. The controller is pure logic, so these feed it synthetic
+/// frame times (no rendering); the last tests check where it is wired.</summary>
+public class QualityFallbackTests
+{
+ const float Fine = 16f, Slow = 45f, Edge = 25f;
+
+ /// <summary>Frames of <paramref name="ms"/> for <paramref name="seconds"/>; returns the levels it moved through.</summary>
+ static int[] Run(QualityFallback q, float ms, float seconds)
+ {
+ var levels = new System.Collections.Generic.List<int>();
+ for (float t = 0; t < seconds * 1000f; t += ms) if (q.Feed(ms)) levels.Add(q.Level);
+ return levels.ToArray();
+ }
+
+ /// <summary>Frames of <paramref name="ms"/> until <paramref name="count"/> more windows are measured; returns the levels it
+ /// moved through. <paramref name="before"/> frames open each window (hitches).</summary>
+ static int[] Windows(QualityFallback q, float ms, int count, params float[] before)
+ {
+ var levels = new System.Collections.Generic.List<int>();
+ for (int w = 0; w < count; w++)
+ {
+ int at = q.Windows;
+ foreach (var b in before) if (q.Feed(b)) levels.Add(q.Level);
+ while (q.Windows == at) if (q.Feed(ms)) levels.Add(q.Level);
+ }
+ return levels.ToArray();
+ }
+
+ /// <summary>A controller past its start-up settle (3 s of fine frames).</summary>
+ static QualityFallback Started() { var q = new QualityFallback(); Run(q, Fine, QualityFallback.StartupSeconds); return q; }
+
+ [Test]
+ public void TheStepsLowerTheRenderScaleWithinTheResearchRangeThenTurnTheTiltShiftOff()
+ {
+ var s = QualityFallback.Steps;
+ Assert.AreEqual(4, s.Count);
+ Assert.AreEqual((1f, true), (s[0].RenderScale, s[0].TiltShift), "level 0 is the tier's own look");
+ for (int i = 1; i < s.Count; i++)
+ {
+ Assert.That(s[i].RenderScale, Is.InRange(0.8f, 1f), "research notes 2.3: 0.8-1.0 dynamic");
+ Assert.LessOrEqual(s[i].RenderScale, s[i - 1].RenderScale);
+ }
+ int firstTiltOff = s.ToList().FindIndex(x => !x.TiltShift);
+ Assert.AreEqual(s.Count - 1, firstTiltOff, "the tilt-shift goes last");
+ Assert.AreEqual(0.8f, s[firstTiltOff - 1].RenderScale, "only once the scale is at its floor");
+ }
+
+ [Test]
+ public void SustainedSlowFramesStepDownOneLevelPerWindowInOrder()
+ {
+ var q = Started();
+ var levels = Run(q, Slow, 60f);
+ CollectionAssert.AreEqual(new[] { 1, 2, 3 }, levels, "one step per window, never past the last");
+ Assert.AreEqual(3, q.Level); Assert.IsFalse(q.Current.TiltShift); Assert.AreEqual(0.8f, q.Current.RenderScale);
+ Assert.AreEqual(Slow, q.LastP95);
+ }
+
+ [Test]
+ public void TheFirstStepComesAfterOneFullWindowNotBefore()
+ {
+ var q = Started();
+ Assert.IsEmpty(Run(q, Slow, QualityFallback.WindowSeconds - 0.1f));
+ Assert.AreEqual(0, q.Level);
+ CollectionAssert.AreEqual(new[] { 1 }, Run(q, Slow, 0.2f));
+ }
+
+ [Test]
+ public void NothingIsMeasuredDuringStartUp()
+ {
+ var q = new QualityFallback();
+ Assert.IsEmpty(Run(q, Slow, QualityFallback.StartupSeconds), "scene load and shader compiles are not load");
+ Assert.AreEqual(0, q.Level);
+ }
+
+ [Test]
+ public void HitchesAPauseAndFramesJustAtTheBudgetDoNotTrigger()
+ {
+ var q = Started();
+ // 3 hitches of 200 ms in every window of 60 fps frames: 3 of ~150 frames slow, under 5%.
+ Assert.IsEmpty(Windows(q, Fine, 5, 200f, 200f, 200f), "one-off hitches");
+ Assert.AreEqual(0, q.Level);
+ q.Feed(30000f); // a hidden tab coming back
+ Run(q, Fine, 10f);
+ Assert.AreEqual(0, q.Level, "a pause");
+ Assert.IsEmpty(Run(q, QualityFallback.FloorMs, 30f), "33 ms frames meet the 30 fps floor");
+ for (int i = 0; i < 2000; i++) q.Feed(i % 3 == 0 ? 33f : 34f); // a 30 Hz cap as the 1 ms WebGL clock reads it
+ Assert.AreEqual(0, q.Level, "33.3 ms frames read as 33 and 34 ms: at the floor, not over it");
+ var steps = Run(q, QualityFallback.OverMs + 1f, 2 * QualityFallback.WindowSeconds);
+ Assert.IsNotEmpty(steps, "35 ms is over"); Assert.AreEqual(1, steps[0]);
+ }
+
+ [Test]
+ public void ItRecoversInReverseOnlyAfterSustainedComfortableFrames()
+ {
+ var q = Started();
+ CollectionAssert.AreEqual(new[] { 1, 2, 3 }, Windows(q, Slow, 3));
+ int n = QualityFallback.RecoverWindows;
+ Assert.IsEmpty(Windows(q, Fine, n - 1), "two good windows are not enough");
+ CollectionAssert.AreEqual(new[] { 2 }, Windows(q, Fine, 1), "the third one steps up: the tilt-shift comes back first");
+ Assert.IsTrue(q.Current.TiltShift); Assert.AreEqual(0.8f, q.Current.RenderScale);
+ CollectionAssert.AreEqual(new[] { 1 }, Windows(q, Fine, n), "then the render scale, in reverse");
+ CollectionAssert.AreEqual(new[] { 0 }, Windows(q, Fine, n));
+ Assert.AreEqual(1f, q.Current.RenderScale);
+ Assert.IsEmpty(Windows(q, Fine, 10), "level 0 is the top");
+ }
+
+ [Test]
+ public void FramesBetweenTheRecoveryLineAndTheBudgetHoldTheLevel()
+ {
+ var q = Started();
+ CollectionAssert.AreEqual(new[] { 1 }, Windows(q, Slow, 1));
+ Assert.IsEmpty(Windows(q, Edge, 20), "the dead band between 20 and 34 ms: no step either way");
+ int n = QualityFallback.RecoverWindows;
+ Assert.IsEmpty(Windows(q, Fine, n - 1));
+ Assert.IsEmpty(Windows(q, Edge, 1));
+ Assert.IsEmpty(Windows(q, Fine, n - 1), "a dead-band window restarted the run of good windows");
+ CollectionAssert.AreEqual(new[] { 0 }, Windows(q, Fine, 1));
+ }
+
+ [Test]
+ public void AStepUpThatFailsDoublesTheWaitForTheNextOne()
+ {
+ var q = Started();
+ CollectionAssert.AreEqual(new[] { 1 }, Windows(q, Slow, 1));
+ Assert.AreEqual(QualityFallback.RecoverWindows, q.RecoverNeeded);
+ // A step up that holds for more than two windows is not a failed one.
+ CollectionAssert.AreEqual(new[] { 0 }, Windows(q, Fine, q.RecoverNeeded));
+ Assert.IsEmpty(Windows(q, Fine, QualityFallback.FailedRecoveryWindows));
+ CollectionAssert.AreEqual(new[] { 1 }, Windows(q, Slow, 1));
+ Assert.AreEqual(QualityFallback.RecoverWindows, q.RecoverNeeded);
+ // A device on the edge: fine at the lower step, slow again right after stepping up.
+ for (int cycle = 1; cycle <= 6; cycle++)
+ {
+ CollectionAssert.AreEqual(new[] { 0 }, Windows(q, Fine, q.RecoverNeeded), $"cycle {cycle}: up after RecoverNeeded windows");
+ CollectionAssert.AreEqual(new[] { 1 }, Windows(q, Slow, 1), $"cycle {cycle}: back down");
+ Assert.AreEqual(System.Math.Min(QualityFallback.RecoverWindows << cycle, QualityFallback.MaxRecoverWindows), q.RecoverNeeded);
+ }
+ Assert.AreEqual(QualityFallback.MaxRecoverWindows, q.RecoverNeeded, "capped");
+ }
+
+ [Test]
+ public void ItRunsOnTheWebTierOnlyAndNeverUnderTheInstruments()
+ {
+ Assert.IsTrue(QualityFallback.Wanted("http://localhost:8000/", webgl: true));
+ Assert.IsTrue(QualityFallback.Wanted("http://localhost:8000/?golden&smoke=5", webgl: true), "a golden run renders; the sim is untouched");
+ Assert.IsFalse(QualityFallback.Wanted("http://localhost:8000/", webgl: false), "desktop and the editor");
+ foreach (var flag in new[] { "vprofile", "profile", "shot", "nofallback" })
+ Assert.IsFalse(QualityFallback.Wanted("http://localhost:8000/?bootlog&" + flag, webgl: true), flag);
+ Assert.IsTrue(QualityFallback.Wanted("http://localhost:8000/?profiles", webgl: true), "whole query parameters only");
+ }
+
+ [TearDown]
+ public void Reset()
+ {
+ TiltShift.Reset();
+ VisualToggles.Clear();
+ }
+
+ /// <summary>Integration: CameraRig.Init wires the fallback into the map's lifecycle through Attach and the map's
+ /// teardown, like the visual toggles. In the editor (not the WebGL tier) a built map has no driver. With the web tier's
+ /// answer forced (the FallbackWanted seam), the map's camera gets one, it applies its steps to the active URP asset and
+ /// to TiltShift.FallbackOff (never the player's tilt-shift toggle), and tearing the map down removes it and puts the
+ /// tier's render scale back.</summary>
+ [Test]
+ public void TheMapWiresItOnTheWebTierOnlyAndItsTeardownPutsTheTierBack()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();
+ var cam = Camera.main!.gameObject;
+ Assert.IsNull(cam.GetComponent<QualityFallbackDriver>(), "the editor is not the web tier: no driver");
+
+ var asset = UniversalRenderPipeline.asset;
+ Assert.IsNotNull(asset);
+ float tierScale = asset!.renderScale;
+ var wanted = CameraRig.FallbackWanted;
+ try
+ {
+ CameraRig.FallbackWanted = () => true;
+ map.Build();
+ var drivers = cam.GetComponents<QualityFallbackDriver>();
+ Assert.AreEqual(1, drivers.Length, "the rebuild's teardown removed nothing it should keep, and added one driver");
+ var driver = drivers[0];
+ for (float t = 0; t < 60_000f; t += Slow) driver.Feed(Slow);
+ Assert.AreEqual(3, driver.Controller.Level);
+ Assert.AreEqual(Mathf.Min(tierScale, 0.8f), asset.renderScale, 1e-6f);
+ Assert.IsTrue(TiltShift.FallbackOff);
+ Assert.IsTrue(TiltShift.Enabled, "the tilt-shift toggle (the player's and the profile's) is left alone");
+
+ map.Build(); // a rebuild tears the old map down first: one driver, back at level 0
+ Assert.AreEqual(1, cam.GetComponents<QualityFallbackDriver>().Length);
+ Assert.AreEqual(tierScale, asset.renderScale, "the old map's teardown put the tier's scale back");
+ Assert.IsFalse(TiltShift.FallbackOff);
+
+ map.Clear(go => Object.DestroyImmediate(go));
+ Assert.IsNull(cam.GetComponent<QualityFallbackDriver>(), "the map's teardown removes the driver");
+ Assert.AreEqual(tierScale, asset.renderScale);
+ }
+ finally
+ {
+ CameraRig.FallbackWanted = wanted;
+ asset.renderScale = tierScale;
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ }
+ }
+
+ [Test]
+ public void TheAttachUndoIsSafeToRunTwiceAndANotWantedAttachAddsNothing()
+ {
+ var go = new GameObject("cam");
+ try
+ {
+ QualityFallbackDriver.Attach(go, wanted: false)();
+ Assert.IsNull(go.GetComponent<QualityFallbackDriver>());
+ var asset = UniversalRenderPipeline.asset!;
+ float tierScale = asset.renderScale;
+ var undo = QualityFallbackDriver.Attach(go, wanted: true);
+ Assert.IsNotNull(go.GetComponent<QualityFallbackDriver>());
+ undo(); undo();
+ Assert.IsNull(go.GetComponent<QualityFallbackDriver>());
+ Assert.AreEqual(tierScale, asset.renderScale);
+ }
+ finally { Object.DestroyImmediate(go); }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/QualityFallbackTests.cs.meta b/unity/Assets/Tests/EditMode/QualityFallbackTests.cs.meta
new file mode 100644
index 000000000..2a113e146
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/QualityFallbackTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d20db9cb18c204a73b40794e7dcdd45d
\ No newline at end of file