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.

fix(map): #44 review fix round 1: corrupt-stream errors, 1-3 fps fallback, strict Python decode

eyalgolandcf329b0e796
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index e0845ca05..cacb70feb 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -744,7 +744,9 @@ The Deferred row "Runtime quality fallback" (review I1), sized by the DPR-2 stre
- **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.
+ frame over 1 s (a hidden tab coming back) drops the window; a window needs at least 3 frames, which a full 3 s window
+ of counted frames (each at most 1 s) always has, so the slowest devices (1-3 fps) step down too (fix round 1, review M2;
+ a minimum of 10 had left them with no decision).
- **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.
diff --git a/tools/heightmap_codec.py b/tools/heightmap_codec.py
index 12cc1ffb4..f30e0c483 100644
--- a/tools/heightmap_codec.py
+++ b/tools/heightmap_codec.py
@@ -27,10 +27,15 @@ def encode(raw: np.ndarray) -> bytes:
def decode(data: bytes, width: int, height: int) -> np.ndarray:
"""Unpacks to an (height, width) little-endian uint16 grid; ValueError on a corrupt stream or the wrong size."""
+ d = zlib.decompressobj()
try:
- planes = zlib.decompress(data)
+ planes = d.decompress(data)
except zlib.error as e:
raise ValueError(f"{FILE}: corrupt stream ({e})") from e
+ if not d.eof:
+ raise ValueError(f"{FILE}: the zlib stream ends early")
+ if d.unused_data:
+ raise ValueError(f"{FILE}: {len(d.unused_data)} bytes after the zlib stream") # the game rejects them too
n = width * height
if len(planes) != 2 * n:
raise ValueError(f"{FILE}: {len(planes)} bytes after inflating, expected {2 * n}")
diff --git a/tools/tests/test_heightmap_codec.py b/tools/tests/test_heightmap_codec.py
index 28efa6e0a..b56e2f9df 100644
--- a/tools/tests/test_heightmap_codec.py
+++ b/tools/tests/test_heightmap_codec.py
@@ -50,3 +50,11 @@ def test_the_shipped_heightmap_decodes_to_the_old_raw_file_byte_for_byte():
assert hashlib.sha256(raw.astype("<u2").tobytes()).hexdigest() == RAW_SHA256
assert not (MAP / "heightmap.r16").exists(), "the raw file is replaced, not kept beside the packed one"
assert (MAP / hc.FILE).stat().st_size < 0.55 * raw.nbytes
+
+
+def test_decode_rejects_trailing_bytes_and_a_truncated_stream_like_the_game():
+ packed = hc.encode(np.arange(9, dtype="<u2").reshape(3, 3))
+ with pytest.raises(ValueError, match="after the zlib stream"):
+ hc.decode(packed + b"xx", 3, 3)
+ with pytest.raises(ValueError):
+ hc.decode(packed[:-5], 3, 3)
diff --git a/unity/Assets/Scripts/Map/CameraRig.cs b/unity/Assets/Scripts/Map/CameraRig.cs
index 0008581cb..b8a47b94f 100644
--- a/unity/Assets/Scripts/Map/CameraRig.cs
+++ b/unity/Assets/Scripts/Map/CameraRig.cs
@@ -56,8 +56,7 @@ 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.
+ // The runtime quality fallback (WebGL only); its undo removes the driver and restores the tier's render scale.
TeardownActions.Add(QualityFallbackDriver.Attach(gameObject, FallbackWanted()));
initialised = true;
Apply();
diff --git a/unity/Assets/Scripts/Map/HeightmapCodec.cs b/unity/Assets/Scripts/Map/HeightmapCodec.cs
index 738ba3e37..f30d541b7 100644
--- a/unity/Assets/Scripts/Map/HeightmapCodec.cs
+++ b/unity/Assets/Scripts/Map/HeightmapCodec.cs
@@ -42,7 +42,8 @@ namespace Statecraft.Game.Map
}
extra = got == planes.Length && inflate.Read(new byte[1], 0, 1) != 0;
}
- catch (InvalidDataException e) { throw new InvalidDataException($"{FileName}: corrupt stream ({e.Message})", e); }
+ // .NET reports bad deflate data as InvalidDataException, Mono's native zlib (the editor, IL2CPP players) as IOException.
+ catch (Exception e) when (e is InvalidDataException || e is IOException) { throw new InvalidDataException($"{FileName}: corrupt stream ({e.Message})", e); }
if (got != planes.Length || extra)
throw new InvalidDataException($"{FileName}: {(extra ? "more than " + planes.Length : got.ToString())} bytes after inflating, expected {planes.Length}");
uint stored = (uint)(packed[packed.Length - 4] << 24 | packed[packed.Length - 3] << 16 | packed[packed.Length - 2] << 8 | packed[packed.Length - 1]);
diff --git a/unity/Assets/Scripts/Map/QualityFallback.cs b/unity/Assets/Scripts/Map/QualityFallback.cs
index 6aa2f6351..83e234d17 100644
--- a/unity/Assets/Scripts/Map/QualityFallback.cs
+++ b/unity/Assets/Scripts/Map/QualityFallback.cs
@@ -28,6 +28,10 @@ namespace Statecraft.Game.Map
/// - 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.
+ /// - A window needs MinWindowFrames = 3 frames. With every counted frame at most 1 s, a full 3 s window always has 3,
+ /// so every window counts down to 1 fps (review M2: a minimum of 10 left 1-3 fps devices, the ones that need the
+ /// fallback most, with no decision at all). Few frames make the p95 the slowest frame, but a window that holds under
+ /// 10 frames averages over 300 ms a frame, far over the floor anyway.
/// - 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
@@ -44,7 +48,7 @@ namespace Statecraft.Game.Map
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 const int MinWindowFrames = 3, RecoverWindows = 3, MaxRecoverWindows = 48, FailedRecoveryWindows = 2;
public int Level { get; private set; }
public Step Current => Steps[Level];
diff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.cs
index cf9333ea4..ad6151908 100644
--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs
+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs
@@ -639,7 +639,7 @@ public class GameSceneTests
[TestCase("Could not find file '/Users/a b/x/content/people.yaml'.", "Could not find file 'people.yaml'.")]
[TestCase(@"Could not find file 'C:\Games\Statecraft\StreamingAssets\map\hexes.json'.", "Could not find file 'hexes.json'.")]
- [TestCase("heightmap.r16: Cannot connect to destination host (file:///Users/me/Data/StreamingAssets/map/heightmap.r16)", "heightmap.r16: Cannot connect to destination host (heightmap.r16)")]
+ [TestCase("heightmap.r16z: Cannot connect to destination host (file:///Users/me/Data/StreamingAssets/map/heightmap.r16z)", "heightmap.r16z: Cannot connect to destination host (heightmap.r16z)")]
[TestCase("people.yaml: people[x].name: required", "people.yaml: people[x].name: required")]
[TestCase("manifest.json: HTTP/1.1 404 Not Found (http://localhost:8766/StreamingAssets/content/manifest.json)", "manifest.json: HTTP/1.1 404 Not Found (http://localhost:8766/StreamingAssets/content/manifest.json)")]
public void BootFailureTextKeepsOnlyFileNames(string reason, string shown) => Assert.AreEqual(shown, GameBoot.ForPlayer(reason));
diff --git a/unity/Assets/Tests/EditMode/MapTests.cs b/unity/Assets/Tests/EditMode/MapTests.cs
index 43b0d2f50..6178829c1 100644
--- a/unity/Assets/Tests/EditMode/MapTests.cs
+++ b/unity/Assets/Tests/EditMode/MapTests.cs
@@ -338,10 +338,37 @@ public class MapTests
StringAssert.Contains("more than 2 bytes", Assert.Throws<System.IO.InvalidDataException>(() => HeightmapCodec.Decode(packed, 1, 1)).Message);
}
+ /// <summary>Review M1: a damaged file either fails with an InvalidDataException naming the file, whichever exception the
+ /// platform's DeflateStream raises (Mono's native zlib reports a data error as an IOException), or still decodes to
+ /// exactly the original grid (the size and the Adler-32 of the contents are checked; flipping only the final-block bit,
+ /// for one, leaves the contents intact). Every byte of the file is flipped, one at a time.</summary>
[Test]
- public void TheCodecReadsWhatThePythonToolWrites()
+ public void AByteFlippedAnywhereFailsNamingTheFileOrChangesNothing()
{
- // tools/tests/test_heightmap_codec.py pins the same layout: row deltas, low-byte plane then high-byte plane.
+ var rng = new System.Random(7);
+ var raw = new ushort[32 * 32];
+ for (int i = 0; i < raw.Length; i++) raw[i] = (ushort)(i * 37 + rng.Next(0, 300)); // compressible: Huffman blocks
+ var packed = HeightmapCodec.Encode(raw, 32, 32);
+ int failed = 0, intact = 0;
+ foreach (byte mask in new byte[] { 0x01, 0x10, 0xFF })
+ for (int at = 0; at < packed.Length; at++)
+ {
+ var bad = (byte[])packed.Clone(); bad[at] ^= mask;
+ ushort[] got;
+ try { got = HeightmapCodec.Decode(bad, 32, 32); }
+ catch (System.IO.InvalidDataException e) { StringAssert.StartsWith("heightmap.r16z: ", e.Message, $"byte {at} ^ {mask:x2}"); failed++; continue; }
+ catch (System.Exception e) { Assert.Fail($"byte {at} ^ {mask:x2}: {e.GetType().Name} {e.Message}"); throw; }
+ CollectionAssert.AreEqual(raw, got, $"byte {at} ^ {mask:x2} decoded to a different grid");
+ intact++;
+ }
+ Assert.Greater(failed, 3 * packed.Length * 9 / 10, $"{intact} of {3 * packed.Length} damaged files decoded intact");
+ }
+
+ [Test]
+ public void TheLayoutIsRowDeltasInLowThenHighBytePlanes()
+ {
+ // tools/tests/test_heightmap_codec.py pins the same layout for the Python encoder; the cross-language guarantee is
+ // ThePackedHeightmapDecodesToTheOldRawFileByteForByte (the committed file is written by the Python tool).
var packed = HeightmapCodec.Encode(new ushort[] { 1, 3, 0x0102, 0x0101 }, 2, 2);
using var body = new System.IO.MemoryStream(packed, 2, packed.Length - 6);
using var inflate = new System.IO.Compression.DeflateStream(body, System.IO.Compression.CompressionMode.Decompress);
diff --git a/unity/Assets/Tests/EditMode/QualityFallbackTests.cs b/unity/Assets/Tests/EditMode/QualityFallbackTests.cs
index 7df0aaa1a..6fc032ee2 100644
--- a/unity/Assets/Tests/EditMode/QualityFallbackTests.cs
+++ b/unity/Assets/Tests/EditMode/QualityFallbackTests.cs
@@ -64,6 +64,17 @@ public class QualityFallbackTests
Assert.AreEqual(Slow, q.LastP95);
}
+ /// <summary>Review M2: the slowest devices (1-3 fps) get the fallback too; a 3 s window of such frames holds only 3-6.</summary>
+ [TestCase(500f)] // 2 fps
+ [TestCase(1000f)] // 1 fps
+ [TestCase(333f)] // 3 fps
+ public void VerySlowFramesStillStepDown(float ms)
+ {
+ var q = new QualityFallback();
+ CollectionAssert.AreEqual(new[] { 1, 2, 3 }, Run(q, ms, 60f));
+ Assert.AreEqual(ms, q.LastP95);
+ }
+
[Test]
public void TheFirstStepComesAfterOneFullWindowNotBefore()
{