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): ship the heightmap packed, 4.1 MB instead of 8.4 MB (#44)

eyalgolanf242c848588a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e1f74028..ec5c11ec8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,3 +22,6 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
### Changed
- The historical AI no longer sends an order the turn's attention cannot cover (the rule the UI's order queue applies),
so the sim never has to refuse one; the golden playthroughs are unchanged.
+- The browser build downloads a smaller heightmap: `heightmap.r16z` (4.1 MB, packed losslessly: row deltas in byte
+ planes, one zlib stream) replaces the raw 8.4 MB `heightmap.r16`, which was served outside Unity's build compression.
+ It decodes to the same bytes, so the terrain is unchanged (#44).
diff --git a/docs/m3-release.md b/docs/m3-release.md
index 465d4ac0e..769cb03dd 100644
--- a/docs/m3-release.md
+++ b/docs/m3-release.md
@@ -21,7 +21,35 @@ start of M4, as a private Draft (owner ruling, 2026-10-10); their sections below
- **Size (merge candidate, a099655):**
- The folder is 23 MB (`du -sh`) in 51 files. itch.io allows 1,000 files.
- The zip is 20 MB (20,941,435 bytes).
- - `StreamingAssets/map/heightmap.r16` (8 MB) is served as is, outside Unity's compression. Making it smaller is deferred to M5.
+ - `StreamingAssets/map/heightmap.r16` (8 MB) was served as is, outside Unity's compression. Issue #44 packed it (below).
+- **Smaller download: the packed heightmap (issue #44, 2026-10-10).** StreamingAssets files are served as they are, so
+ the raw 16-bit grid cost 8,396,802 bytes on every load. It is now `heightmap.r16z` (4,062,705 bytes): the grid's row
+ deltas split into a low-byte and a high-byte plane, in one zlib stream (`tools/heightmap_codec.py` writes it,
+ `HeightmapCodec.cs` decodes it with `System.IO.Compression.DeflateStream`, which IL2CPP backs with its bundled zlib on
+ WebGL too, then checks the size and the Adler-32). It decodes to the old file byte for byte: `MapTests` and
+ `test_heightmap_codec.py` pin the SHA-256 of the raw file (`b6882a77…`), and the terrain tests, goldens and smoke are
+ unchanged.
+ - **Options weighed (same grid, bytes):** raw 8,396,802; zlib of the raw grid 6,284,586; Brotli 11 of the raw grid
+ (what moving it into the `.data` file would give: Unity's Brotli build matches quality 11, 10,988,872 against
+ 10,953,925 for the same `.data`) 4,982,506; row deltas in byte planes + zlib (chosen) 4,062,705; the same planes
+ under Brotli 11 3,822,573. Moving it into `.data` saves less (3.4 MB on the wire against 4.3 MB; 1.3 MB of zip
+ against 2.2 MB), puts the bytes in the file the engine must load before it starts (the StreamingAssets fetch runs
+ beside the content fetches), grows the uncompressed build used for local and CI checks by 8 MB, and moves the file
+ every map tool reads. The Brotli-planes variant would save 0.24 MB more but needs the same decoder plus all of that.
+ - **Size, fb31ce1 -> issue #44 (Brotli build, measured on the folders; the zip is `tools/package_release.py`'s
+ deflate zip of the same files, made without the release gate):** folder 28,310,337 -> 23,954,695 bytes (-4.36 MB,
+ -15%; this is what a browser downloads), zip 25,782,074 -> 23,535,021 bytes (-2.25 MB, -9%; the old zip already
+ deflated the raw grid to about 6.3 MB), 51 files both. The wasm grows by 14 KB (`.wasm.br` 8,622,716 ->
+ 8,636,749: DeflateStream). The zip has grown since a099655 (20.9 MB) with visual v1's baked textures.
+ - **Boot (`uv run tools/headed.py boot --runs 3`, Disabled build, fb31ce1 -> #44; load average 6-12 from other
+ sessions):** `--cpu 1`: `BOOT map_build_ms median=432` -> `480`, `BOOT first_frame_ms median=3580` -> `3646`;
+ `--cpu 4`: `map_build_ms median=1897` -> `2035`, `first_frame_ms median=7320` -> `7401`. The decode is the "heightmap
+ decoded" phase: 7 -> 41 ms at `--cpu 1`, 34 -> 184 ms at `--cpu 4`. Every span stays within the visual v1 boot
+ budget (Task 1 baselines 443 / 3547 ms at `--cpu 1` and 1813 / 6963 ms at `--cpu 4`, plus max(300 ms, 50%)); the
+ tool exits 0 on each. Served from localhost the download is free, so these runs show only the decode's cost; on a
+ real connection 4.3 MB less to fetch is worth far more (3.5 s at 10 Mbit/s).
+ - **Goldens:** `uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&smoke=5"` with the three `--expect`
+ values from `docs/determinism.md`: PASS on both builds (the Brotli build too).
- **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()"
diff --git a/docs/oss/AUDIT.md b/docs/oss/AUDIT.md
index 7f40534e5..20990dd76 100644
--- a/docs/oss/AUDIT.md
+++ b/docs/oss/AUDIT.md
@@ -40,7 +40,7 @@ Owner rulings that frame this audit: no history rewriting and no history enforce
|---|---|---|---|
| Code | `sim/**`, `tools/**`, `unity/Assets/Scripts/**`, `unity/Assets/Editor/**`, `unity/Assets/Tests/**`, `unity/Assets/Shaders/**`, `promo/*.py`, the WebGL template `unity/Assets/WebGLTemplates/Statecraft/index.html` | Written in this repo (owner plus AI agents). The WebGL template is our own HTML using Unity's `{{{ }}}` placeholders. | None. Licence of choice. |
| Content YAML | `content/*.yaml`, `content/events/*.yaml` | Facts with `sources:` URLs and check dates. The prose is ours and paraphrases sources such as en.wikipedia. Wikipedia text is CC BY-SA 4.0, so close paraphrase favours a compatible content licence. | Low. |
-| Map data (derived) | `unity/Assets/StreamingAssets/map/heightmap.r16` (8 MB), `content/map/hexes.json` | Copernicus DEM GLO-30, used under the Copernicus licence with the required attribution text (`promo/CREDITS.md`, `tools/README.md`). | Low, provided the attribution travels. |
+| Map data (derived) | `unity/Assets/StreamingAssets/map/heightmap.r16z` (4 MB; the raw 8 MB `heightmap.r16` until issue #44 packed it), `content/map/hexes.json` | Copernicus DEM GLO-30, used under the Copernicus licence with the required attribution text (`promo/CREDITS.md`, `tools/README.md`). | Low, provided the attribution travels. |
| | `content/map/precip_bio12.{json,u16}` | CHELSA V2.1, CC0, citation requested. | None. |
| | `content/map/precip_stations.json` | IMS via data.gov.il dataset 481, licence "Other (Open)" **with no licence URL**. This is the deferred row: M0–M2 plan line 6282, carried in the M3 plan, line 10816: "Legal review of map-data licences … M5 / owner". | **Open**. Owner verifies the data.gov.il terms of use. |
| | `content/map/settlements_1948.yaml`, `settlement_hexes.yaml` | Coordinates from the Wikipedia API, each with source URLs. | Low (facts). |
diff --git a/scripts/oss/oss_policy.py b/scripts/oss/oss_policy.py
index e5f76d2e0..d6804840c 100755
--- a/scripts/oss/oss_policy.py
+++ b/scripts/oss/oss_policy.py
@@ -51,7 +51,7 @@ REQUIRED_FILES: tuple[str, ...] = (
# Files whose provenance ASSETS.yaml must record (check "assets"). Any file git itself treats as binary counts too.
BINARY_EXTENSIONS = frozenset({
".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tif", ".tiff", ".tga", ".psd", ".exr", ".hdr", ".svg",
- ".mp4", ".mov", ".webm", ".r16", ".u16", ".raw",
+ ".mp4", ".mov", ".webm", ".r16", ".r16z", ".u16", ".raw",
".ttf", ".otf", ".woff", ".woff2",
".wav", ".ogg", ".mp3", ".flac", ".aiff", ".m4a",
".fbx", ".obj", ".blend", ".glb", ".gltf",
diff --git a/tools/README.md b/tools/README.md
index 7eeb0e79f..a1501091b 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -3,7 +3,9 @@
Offline data tools (uv inline-script Python). Run from the repo root.
- `dem_to_heightmap.py` downloads Copernicus GLO-30 tiles into `tools/.cache/dem/` (not committed) and writes
- `unity/Assets/StreamingAssets/map/heightmap.r16` + `heightmap.json`.
+ `unity/Assets/StreamingAssets/map/heightmap.r16z` + `heightmap.json`. The `.r16z` is the 16-bit grid packed losslessly
+ by `heightmap_codec.py` (row deltas in byte planes, one zlib stream: 4.1 MB instead of 8.4 MB, issue #44); every tool
+ reads it through `heightmap_codec.read`, and the game decodes the same layout (`HeightmapCodec.cs`).
- `precip_clip.py` reads the map window of CHELSA V2.1 bio12 (mean annual precipitation 1981-2010) in place over HTTP and
writes `content/map/precip_bio12.u16` + `precip_bio12.json` (committed).
- `ims_normals.py` downloads Israel Meteorological Service rain-gauge records from data.gov.il into `tools/.cache/ims/`
diff --git a/tools/dem_to_heightmap.py b/tools/dem_to_heightmap.py
index 09e1a1ba8..cb7ae5dbd 100644
--- a/tools/dem_to_heightmap.py
+++ b/tools/dem_to_heightmap.py
@@ -2,7 +2,7 @@
# requires-python = ">=3.11"
# dependencies = ["rasterio==1.5.2", "numpy==2.5.3", "requests==2.32.5"]
# ///
-"""Copernicus GLO-30 DEM -> Unity heightmap (16-bit RAW, row 0 = north) + metadata JSON.
+"""Copernicus GLO-30 DEM -> Unity heightmap (16-bit grid, row 0 = north, packed by heightmap_codec) + metadata JSON.
Usage: uv run tools/dem_to_heightmap.py
Tiles are cached in tools/.cache/dem/ (not committed). A tile that returns 404 is open sea."""
@@ -16,6 +16,7 @@ import requests
from rasterio.transform import from_bounds
from rasterio.warp import Resampling, reproject
+import heightmap_codec
from geo import KM_PER_DEG_LAT, KM_PER_DEG_LON_EQ
ROOT = Path(__file__).resolve().parents[1]
@@ -69,7 +70,7 @@ def write_heightmap(elev: np.ndarray, b: dict, out: Path) -> dict:
lo, hi = float(elev.min()), float(elev.max())
raw = np.round((elev - lo) / (hi - lo) * 65535).astype("<u2")
out.mkdir(parents=True, exist_ok=True)
- raw.tofile(out / "heightmap.r16")
+ heightmap_codec.write(out, raw) # packed, lossless (issue #44): the raw grid is never written
meta = {"width": int(elev.shape[1]), "height": int(elev.shape[0]), **b,
"elev_min_m": lo, "elev_max_m": hi,
"width_km": (b["lon1"] - b["lon0"]) * KM_PER_DEG_LON_EQ
@@ -88,7 +89,7 @@ def main() -> None:
if p:
paths.append(p)
meta = write_heightmap(mosaic(paths, BOUNDS, SIZE), BOUNDS, OUT)
- print(f"wrote {OUT / 'heightmap.r16'}: elev {meta['elev_min_m']:.1f}..{meta['elev_max_m']:.1f} m, "
+ print(f"wrote {OUT / heightmap_codec.FILE}: elev {meta['elev_min_m']:.1f}..{meta['elev_max_m']:.1f} m, "
f"{meta['width_km']:.1f} x {meta['length_km']:.1f} km")
diff --git a/tools/heightmap_codec.py b/tools/heightmap_codec.py
new file mode 100644
index 000000000..12cc1ffb4
--- /dev/null
+++ b/tools/heightmap_codec.py
@@ -0,0 +1,50 @@
+"""The packed heightmap file, heightmap.r16z: lossless, about half the size of the raw 16-bit grid (issue #44).
+
+The game reads it at boot (HeightmapCodec.cs decodes the same layout); every tool that needs the elevations reads it here.
+Layout: one zlib stream (RFC 1950, so it carries an Adler-32 of its contents) of the grid's row deltas split into byte
+planes. Each row (row 0 = north) is replaced by its differences d[x] = h[x] - h[x-1] mod 65536 (d[0] = h[0]); the low
+bytes of all deltas come first, then all the high bytes. Smooth terrain gives small deltas, so the high-byte plane is
+mostly 0x00/0xFF and deflate packs both planes far better than the raw grid (8.4 MB -> about 4.1 MB). Decoding is an
+inflate, an interleave and a running sum per row, and returns the original grid bit for bit."""
+import zlib
+from pathlib import Path
+
+import numpy as np
+
+FILE = "heightmap.r16z"
+
+
+def encode(raw: np.ndarray) -> bytes:
+ """Packs an (h, w) uint16 grid."""
+ grid = np.asarray(raw, dtype="<u2")
+ if grid.ndim != 2:
+ raise ValueError(f"a heightmap is a 2-D grid, got shape {grid.shape}")
+ delta = grid.copy()
+ delta[:, 1:] = grid[:, 1:] - grid[:, :-1] # uint16 arithmetic wraps mod 65536
+ planes = delta.astype("<u2").view(np.uint8).reshape(-1, 2).T # row 0: low bytes, row 1: high bytes
+ return zlib.compress(planes.tobytes(), 9)
+
+
+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."""
+ try:
+ planes = zlib.decompress(data)
+ except zlib.error as e:
+ raise ValueError(f"{FILE}: corrupt stream ({e})") from e
+ n = width * height
+ if len(planes) != 2 * n:
+ raise ValueError(f"{FILE}: {len(planes)} bytes after inflating, expected {2 * n}")
+ b = np.frombuffer(planes, dtype=np.uint8)
+ delta = (b[:n].astype(np.uint16) | (b[n:].astype(np.uint16) << 8)).reshape(height, width)
+ return np.cumsum(delta, axis=1, dtype=np.uint16).astype("<u2") # the running sum wraps like the encoder
+
+
+def write(map_dir: Path, raw: np.ndarray) -> Path:
+ path = Path(map_dir) / FILE
+ path.write_bytes(encode(raw))
+ return path
+
+
+def read(map_dir: Path, meta: dict) -> np.ndarray:
+ """The grid of map_dir's heightmap, sized by its heightmap.json `meta`."""
+ return decode((Path(map_dir) / FILE).read_bytes(), meta["width"], meta["height"])
diff --git a/tools/hexgrid.py b/tools/hexgrid.py
index 4a089b578..2514783d4 100644
--- a/tools/hexgrid.py
+++ b/tools/hexgrid.py
@@ -32,6 +32,7 @@ from pathlib import Path
import numpy as np
+import heightmap_codec
from geo import KM_PER_DEG_LAT, KM_PER_DEG_LON_EQ
ROOT = Path(__file__).resolve().parents[1]
@@ -236,7 +237,7 @@ def hex_precip_means(pr: dict, elev: np.ndarray, meta: dict, size: float) -> dic
def load_elevation(map_dir: Path) -> tuple[np.ndarray, dict]:
meta = json.loads((map_dir / "heightmap.json").read_text())
- raw = np.fromfile(map_dir / "heightmap.r16", dtype="<u2").reshape(meta["height"], meta["width"])
+ raw = heightmap_codec.read(map_dir, meta)
elev = meta["elev_min_m"] + raw.astype("float64") / 65535 * (meta["elev_max_m"] - meta["elev_min_m"])
return elev, meta
diff --git a/tools/terrain_bake.py b/tools/terrain_bake.py
index 760d5f599..e96463c9e 100644
--- a/tools/terrain_bake.py
+++ b/tools/terrain_bake.py
@@ -5,7 +5,7 @@
"""Heightmap -> the baked shading textures of the terrain and sea shaders (no network: reads only the committed heightmap).
Usage: uv run tools/terrain_bake.py (about 10 seconds)
-Reads unity/Assets/StreamingAssets/map/heightmap.r16 + heightmap.json; writes, 2048 x 2048, row 0 = north:
+Reads unity/Assets/StreamingAssets/map/heightmap.r16z (heightmap_codec) + heightmap.json; writes, 2048 x 2048, row 0 = north:
unity/Assets/Textures/Map/terrain_bake.png RGB8: R ambient occlusion (horizon search to AO_RADIUS_M; 1 = open),
G curvature (0.5 flat, > 0.5 convex), B sky-view factor (horizon search to SKY_RADIUS_M)
unity/Assets/Textures/Map/ao.png L8: the same ambient occlusion as terrain_bake.png's R, on its own so Unity
@@ -26,6 +26,8 @@ from pathlib import Path
import numpy as np
from PIL import Image
+import heightmap_codec
+
ROOT = Path(__file__).resolve().parents[1]
MAP_DIR = ROOT / "unity" / "Assets" / "StreamingAssets" / "map"
OUT_DIR = ROOT / "unity" / "Assets" / "Textures" / "Map"
@@ -45,7 +47,7 @@ COAST_RANGE_M = 12000.0 # StatecraftMap.hlsl ScCoastRangeM
def load_heightmap(map_dir: Path) -> tuple[np.ndarray, dict]:
meta = json.loads((map_dir / "heightmap.json").read_text())
- raw = np.fromfile(map_dir / "heightmap.r16", dtype="<u2").reshape(meta["height"], meta["width"])
+ raw = heightmap_codec.read(map_dir, meta)
elev = meta["elev_min_m"] + raw.astype(np.float64) / 65535.0 * (meta["elev_max_m"] - meta["elev_min_m"])
return elev.astype(np.float32), meta
diff --git a/tools/tests/test_dem_to_heightmap.py b/tools/tests/test_dem_to_heightmap.py
index 509ef69b5..927116820 100644
--- a/tools/tests/test_dem_to_heightmap.py
+++ b/tools/tests/test_dem_to_heightmap.py
@@ -6,6 +6,7 @@ import rasterio
from rasterio.transform import from_origin
import dem_to_heightmap as dem
+import heightmap_codec as hc
def make_tile(path, lat, lon, value, size=60):
@@ -40,7 +41,8 @@ def test_missing_tile_is_sea_and_mosaic_keeps_north_up(tmp_path):
def test_write_heightmap_normalises_and_writes_metadata(tmp_path):
elev = np.array([[-430.0, 0.0], [570.0, 1000.0]], dtype="float32")
meta = dem.write_heightmap(elev, dem.BOUNDS, tmp_path)
- raw = np.fromfile(tmp_path / "heightmap.r16", dtype="<u2").reshape(2, 2)
+ assert not (tmp_path / "heightmap.r16").exists(), "only the packed heightmap is written (issue #44)"
+ raw = hc.read(tmp_path, {"width": 2, "height": 2})
assert raw[0, 0] == 0 and raw[1, 1] == 65535
assert raw[1, 0] == round((570 + 430) / 1430 * 65535)
on_disk = json.loads((tmp_path / "heightmap.json").read_text())
diff --git a/tools/tests/test_heightmap_codec.py b/tools/tests/test_heightmap_codec.py
new file mode 100644
index 000000000..28efa6e0a
--- /dev/null
+++ b/tools/tests/test_heightmap_codec.py
@@ -0,0 +1,52 @@
+import hashlib
+import zlib
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+import heightmap_codec as hc
+
+MAP = Path(__file__).resolve().parents[2] / "unity" / "Assets" / "StreamingAssets" / "map"
+# SHA-256 of the raw heightmap.r16 (8,396,802 bytes) shipped before issue #44 packed it; the packed file must decode to it.
+RAW_SHA256 = "b6882a77420efa90217cc65a9c353147569094cf16656d4d53c30abe0f41ac9e"
+
+
+def test_round_trip_is_exact_including_wraparound_deltas():
+ rng = np.random.default_rng(44)
+ for shape in [(1, 1), (3, 3), (5, 7), (64, 64)]:
+ raw = rng.integers(0, 65536, size=shape, dtype=np.uint32).astype("<u2")
+ raw.flat[0], raw.flat[-1] = 65535, 0 # the largest jumps, both ways
+ packed = hc.encode(raw)
+ assert np.array_equal(hc.decode(packed, shape[1], shape[0]), raw)
+
+
+def test_layout_is_row_deltas_split_into_low_then_high_byte_planes():
+ raw = np.array([[1, 3], [0x0102, 0x0101]], dtype="<u2")
+ planes = zlib.decompress(hc.encode(raw))
+ # deltas per row (mod 65536): [1, 2], [0x0102, 0xFFFF]
+ assert planes == bytes([1, 2, 0x02, 0xFF]) + bytes([0, 0, 0x01, 0xFF])
+
+
+def test_decode_rejects_a_stream_of_the_wrong_size_or_a_corrupt_one():
+ packed = hc.encode(np.zeros((3, 3), dtype="<u2"))
+ with pytest.raises(ValueError, match="18 bytes after inflating, expected 8"):
+ hc.decode(packed, 2, 2)
+ with pytest.raises(ValueError):
+ hc.decode(packed[:-4] + b"\0\0\0\0", 3, 3) # adler-32 no longer matches
+
+
+def test_write_and_read_use_the_packed_file(tmp_path):
+ raw = np.arange(12, dtype="<u2").reshape(3, 4) * 5000
+ hc.write(tmp_path, raw)
+ assert [p.name for p in tmp_path.iterdir()] == [hc.FILE]
+ assert np.array_equal(hc.read(tmp_path, {"width": 4, "height": 3}), raw)
+
+
+def test_the_shipped_heightmap_decodes_to_the_old_raw_file_byte_for_byte():
+ import json
+ meta = json.loads((MAP / "heightmap.json").read_text())
+ raw = hc.read(MAP, meta)
+ 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
diff --git a/tools/tests/test_hexgrid.py b/tools/tests/test_hexgrid.py
index defa4ee52..38d9d21bd 100644
--- a/tools/tests/test_hexgrid.py
+++ b/tools/tests/test_hexgrid.py
@@ -5,6 +5,7 @@ import numpy as np
import pytest
import hexgrid as hg
+import heightmap_codec as hc
ROOT = Path(__file__).resolve().parents[2]
@@ -69,7 +70,7 @@ def test_build_hexes_on_synthetic_map(tmp_path):
"elev_min_m": 0.0, "elev_max_m": 300.0,
"attribution": "dem-credit"}
(tmp_path / "heightmap.json").write_text(json.dumps(meta))
- np.round(elev / 300.0 * 65535).astype("<u2").tofile(tmp_path / "heightmap.r16")
+ hc.write(tmp_path, np.round(elev / 300.0 * 65535).astype("<u2"))
write_uniform_precip(tmp_path, meta, 500.0)
out = hg.build(tmp_path, 5.0, precip_dir=tmp_path)
assert out["layout"] == "pointy" and out["hex_size_km"] == 5.0
@@ -86,7 +87,7 @@ def synthetic_inputs(d):
meta = {"width": n, "height": n, "lon0": 35.0, "lon1": 35.5, "lat0": 32.2, "lat1": 32.7,
"elev_min_m": 0.0, "elev_max_m": 300.0, "attribution": "dem-credit"}
(d / "heightmap.json").write_text(json.dumps(meta))
- np.full((n, n), 65535, dtype="<u2").tofile(d / "heightmap.r16")
+ hc.write(d, np.full((n, n), 65535, dtype="<u2"))
write_uniform_precip(d, meta, 500.0)
@@ -133,7 +134,7 @@ def test_build_marks_dry_land_desert_wherever_it_is(tmp_path):
"elev_min_m": 0.0, "elev_max_m": 300.0,
"attribution": "dem-credit"}
(tmp_path / "heightmap.json").write_text(json.dumps(meta))
- np.round(elev / 300.0 * 65535).astype("<u2").tofile(tmp_path / "heightmap.r16")
+ hc.write(tmp_path, np.round(elev / 300.0 * 65535).astype("<u2"))
cell = 0.01
w = round(0.5 / cell) + 2; h = round(0.5 / cell) + 2
mm = np.full((h, w), 600.0); mm[h // 2:, :] = 120.0 # dry southern half, far north of any old lat rule
@@ -157,7 +158,7 @@ def test_hex_precip_averages_only_land_cells(tmp_path):
"elev_min_m": 0.0, "elev_max_m": 300.0,
"attribution": "dem-credit"}
(tmp_path / "heightmap.json").write_text(json.dumps(meta))
- np.round(elev / 300.0 * 65535).astype("<u2").tofile(tmp_path / "heightmap.r16")
+ hc.write(tmp_path, np.round(elev / 300.0 * 65535).astype("<u2"))
cell = 0.01
w = round(0.5 / cell) + 2; h = round(0.5 / cell) + 2
lons = 35.0 - cell + (np.arange(w) + 0.5) * cell
diff --git a/tools/tests/test_preview_map.py b/tools/tests/test_preview_map.py
index 60285494b..febc80abb 100644
--- a/tools/tests/test_preview_map.py
+++ b/tools/tests/test_preview_map.py
@@ -5,6 +5,7 @@ from PIL import Image
import hexgrid as hg
import preview_map as pm
+import heightmap_codec as hc
def test_preview_renders_expected_size_and_marks_settlement(tmp_path):
@@ -14,7 +15,7 @@ def test_preview_renders_expected_size_and_marks_settlement(tmp_path):
"elev_min_m": 0.0, "elev_max_m": 300.0,
"attribution": "dem-credit"}
(tmp_path / "heightmap.json").write_text(json.dumps(meta))
- np.round(elev / 300.0 * 65535).astype("<u2").tofile(tmp_path / "heightmap.r16")
+ hc.write(tmp_path, np.round(elev / 300.0 * 65535).astype("<u2"))
cell = 0.01
hg.write_precip(np.full((52, 52), 500.0), 35.0 - cell, 32.7 + cell, cell, tmp_path, {"source": "synthetic", "attribution": "chelsa-credit"})
(tmp_path / "precip_stations.json").write_text(json.dumps({"attribution": "ims-credit", "stations": []}))
diff --git a/tools/tests/test_terrain_bake.py b/tools/tests/test_terrain_bake.py
index 85537a918..7022dbf97 100644
--- a/tools/tests/test_terrain_bake.py
+++ b/tools/tests/test_terrain_bake.py
@@ -6,6 +6,7 @@ import pytest
from PIL import Image
import terrain_bake as tb
+import heightmap_codec as hc
ROOT = Path(__file__).resolve().parents[2]
@@ -149,7 +150,7 @@ def test_main_writes_both_textures_one_texel_smaller_and_deterministically(tmp_p
elev = np.where(x < 8, 0.0, 40.0 + 30.0 * np.sin(y / 3.0) + 20.0 * x).astype(np.float32)
lo, hi = float(elev.min()), float(elev.max())
map_dir = tmp_path / "map"; map_dir.mkdir()
- np.round((elev - lo) / (hi - lo) * 65535).astype("<u2").tofile(map_dir / "heightmap.r16")
+ hc.write(map_dir, np.round((elev - lo) / (hi - lo) * 65535).astype("<u2"))
(map_dir / "heightmap.json").write_text(json.dumps({**meta_for(n, n, 79.0, 211.0), "elev_min_m": lo, "elev_max_m": hi}))
tb.main(map_dir, tmp_path / "a"); tb.main(map_dir, tmp_path / "b")
bake = png(tmp_path / "a" / "terrain_bake.png"); coast = png(tmp_path / "a" / "coast.png")
diff --git a/tools/web_check.py b/tools/web_check.py
index bfd9060a3..a9a23d19f 100644
--- a/tools/web_check.py
+++ b/tools/web_check.py
@@ -92,7 +92,7 @@ class Handler(http.server.SimpleHTTPRequestHandler):
return "application/wasm"
if base.endswith(".js"):
return "application/javascript"
- if base.endswith((".data", ".r16")):
+ if base.endswith((".data", ".r16z")):
return "application/octet-stream"
return super().guess_type(base)
diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.cs
index ea718b962..584281e25 100644
--- a/unity/Assets/Scripts/Boot/GameInputs.cs
+++ b/unity/Assets/Scripts/Boot/GameInputs.cs
@@ -14,7 +14,8 @@ namespace Statecraft.Game.Boot
public sealed class MapInputs
{
public string HeightmapJson = "", HexesJson = "", SettlementsYaml = "";
- public byte[] HeightmapR16 = new byte[0];
+ /// <summary>heightmap.r16z as read: packed (HeightmapCodec); HeightmapLoader decodes it when the map is built.</summary>
+ public byte[] HeightmapR16z = new byte[0];
}
/// <summary>Everything the game loads at start: the sim content and the map inputs. Desktop and the editor read
@@ -28,7 +29,7 @@ namespace Statecraft.Game.Boot
public static MapInputs MapFromDisk(string contentDir, string mapDir) => new MapInputs
{
HeightmapJson = File.ReadAllText(Path.Combine(mapDir, "heightmap.json")),
- HeightmapR16 = File.ReadAllBytes(Path.Combine(mapDir, "heightmap.r16")),
+ HeightmapR16z = File.ReadAllBytes(Path.Combine(mapDir, HeightmapCodec.FileName)),
HexesJson = File.ReadAllText(Path.Combine(contentDir, "map", "hexes.json")),
SettlementsYaml = File.ReadAllText(Path.Combine(contentDir, "map", SettlementPlacer.DefaultFileName)),
};
@@ -36,8 +37,8 @@ namespace Statecraft.Game.Boot
public static GameInputs FromDisk(string contentDir, string mapDir) =>
new GameInputs { Content = ContentLoader.Load(contentDir), Map = MapFromDisk(contentDir, mapDir) };
- /// <summary>Builds the inputs from fetched texts (keys are manifest paths) and heightmap bytes.</summary>
- public static GameInputs FromTexts(IReadOnlyDictionary<string, string> texts, IEnumerable<string> manifest, string heightmapJson, byte[] r16)
+ /// <summary>Builds the inputs from fetched texts (keys are manifest paths) and the packed heightmap's bytes.</summary>
+ public static GameInputs FromTexts(IReadOnlyDictionary<string, string> texts, IEnumerable<string> manifest, string heightmapJson, byte[] r16z)
{
var events = manifest.Where(f => f.StartsWith("events/", StringComparison.Ordinal)).ToList();
var content = ContentLoader.Load(rel => texts.TryGetValue(rel, out var t) ? t : null, events);
@@ -46,7 +47,7 @@ namespace Statecraft.Game.Boot
Content = content,
Map = new MapInputs
{
- HeightmapJson = heightmapJson, HeightmapR16 = r16,
+ HeightmapJson = heightmapJson, HeightmapR16z = r16z,
HexesJson = texts["map/hexes.json"], SettlementsYaml = texts["map/" + SettlementPlacer.DefaultFileName],
},
};
@@ -132,22 +133,22 @@ namespace Statecraft.Game.Boot
var manifest = ContentManifest.Parse(await Text(Start(baseUrl + "/content/" + ContentManifest.FileName), ContentManifest.FileName));
var requests = manifest.Select(f => (file: f, request: Start(baseUrl + "/content/" + f))).ToList();
var meta = Start(baseUrl + "/map/heightmap.json");
- var r16 = Start(baseUrl + "/map/heightmap.r16");
+ var r16z = Start(baseUrl + "/map/" + HeightmapCodec.FileName);
try
{
var texts = new Dictionary<string, string>();
foreach (var (file, request) in requests) texts[file] = await Text(request, file);
var metaText = await Text(meta, "heightmap.json");
- var r16Bytes = await Bytes(r16, "heightmap.r16");
+ var r16zBytes = await Bytes(r16z, HeightmapCodec.FileName);
DiagLog.BootPhase($"downloaded {texts.Count + 3} files");
- var inputs = FromTexts(texts, manifest, metaText, r16Bytes);
+ var inputs = FromTexts(texts, manifest, metaText, r16zBytes);
DiagLog.BootPhase("content parsed and validated");
return inputs;
}
finally
{
foreach (var (_, request) in requests) Release(request);
- Release(meta); Release(r16);
+ Release(meta); Release(r16z);
}
}
}
diff --git a/unity/Assets/Scripts/Map/HeightmapCodec.cs b/unity/Assets/Scripts/Map/HeightmapCodec.cs
new file mode 100644
index 000000000..738ba3e37
--- /dev/null
+++ b/unity/Assets/Scripts/Map/HeightmapCodec.cs
@@ -0,0 +1,94 @@
+#nullable enable
+using System;
+using System.IO;
+using System.IO.Compression;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>The packed heightmap, heightmap.r16z (issue #44): lossless, about half the size of the raw 16-bit grid, so the
+ /// web build downloads 4 MB instead of 8 (StreamingAssets files are served outside Unity's build compression).
+ /// Layout (tools/heightmap_codec.py writes it): one zlib stream (RFC 1950: a 2-byte header, raw deflate, the Adler-32 of
+ /// the contents) of the grid's row deltas split into byte planes. Each row (row 0 = north) holds d[x] = h[x] - h[x-1]
+ /// mod 65536 (d[0] = h[0]); the low bytes of all deltas come first, then all the high bytes. Decoding inflates with
+ /// System.IO.Compression (IL2CPP backs DeflateStream with its bundled zlib on every target, WebGL included), checks the
+ /// size and the Adler-32, then interleaves and sums each row: the original grid bit for bit.</summary>
+ public static class HeightmapCodec
+ {
+ public const string FileName = "heightmap.r16z";
+
+ /// <summary>The grid (row 0 = north, row-major) of a packed <paramref name="width"/> x <paramref name="height"/>
+ /// heightmap. InvalidDataException (naming the file) on a stream that is not one, is corrupt or has the wrong size.</summary>
+ public static ushort[] Decode(byte[] packed, int width, int height)
+ {
+ if (packed == null) throw new ArgumentNullException(nameof(packed));
+ if (width <= 0 || height <= 0) throw new ArgumentOutOfRangeException(nameof(width), $"{width} x {height}");
+ if (packed.Length < 6) throw new InvalidDataException($"{FileName}: {packed.Length} bytes is too short for a zlib stream");
+ int cmf = packed[0], flg = packed[1];
+ if ((cmf & 0x0F) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20) != 0)
+ throw new InvalidDataException($"{FileName}: not a zlib stream (header {cmf:x2} {flg:x2})");
+ int n = checked(width * height);
+ var planes = new byte[checked(2 * n)];
+ int got = 0;
+ bool extra;
+ try
+ {
+ using var body = new MemoryStream(packed, 2, packed.Length - 6, false);
+ using var inflate = new DeflateStream(body, CompressionMode.Decompress);
+ while (got < planes.Length)
+ {
+ int r = inflate.Read(planes, got, planes.Length - got);
+ if (r == 0) break;
+ got += r;
+ }
+ extra = got == planes.Length && inflate.Read(new byte[1], 0, 1) != 0;
+ }
+ catch (InvalidDataException e) { 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]);
+ if (Adler32(planes) != stored) throw new InvalidDataException($"{FileName}: checksum mismatch (corrupt download?)");
+ var raw = new ushort[n];
+ for (int row = 0, i = 0; row < height; row++)
+ {
+ ushort h = 0;
+ for (int x = 0; x < width; x++, i++) { h = (ushort)(h + (planes[i] | planes[n + i] << 8)); raw[i] = h; }
+ }
+ return raw;
+ }
+
+ /// <summary>Packs a row-major grid (the inverse of Decode; the editor and tests use it, the game only decodes).</summary>
+ public static byte[] Encode(ushort[] raw, int width, int height)
+ {
+ if (raw == null) throw new ArgumentNullException(nameof(raw));
+ int n = checked(width * height);
+ if (raw.Length != n) throw new ArgumentException($"{raw.Length} samples for {width} x {height}", nameof(raw));
+ var planes = new byte[2 * n];
+ for (int row = 0, i = 0; row < height; row++)
+ for (int x = 0; x < width; x++, i++)
+ {
+ var d = (ushort)(raw[i] - (x == 0 ? 0 : raw[i - 1]));
+ planes[i] = (byte)d; planes[n + i] = (byte)(d >> 8);
+ }
+ using var output = new MemoryStream();
+ output.WriteByte(0x78); output.WriteByte(0xDA); // deflate, 32 KB window, best compression: (0x78DA % 31 == 0)
+ using (var deflate = new DeflateStream(output, CompressionLevel.Optimal, true)) deflate.Write(planes, 0, planes.Length);
+ var a = Adler32(planes);
+ output.WriteByte((byte)(a >> 24)); output.WriteByte((byte)(a >> 16)); output.WriteByte((byte)(a >> 8)); output.WriteByte((byte)a);
+ return output.ToArray();
+ }
+
+ /// <summary>RFC 1950 Adler-32.</summary>
+ public static uint Adler32(byte[] data)
+ {
+ const uint Mod = 65521; const int Nmax = 5552; // the largest run whose sums cannot overflow 32 bits
+ uint a = 1, b = 0;
+ for (int i = 0; i < data.Length;)
+ {
+ int end = Math.Min(data.Length, i + Nmax);
+ for (; i < end; i++) { a += data[i]; b += a; }
+ a %= Mod; b %= Mod;
+ }
+ return b << 16 | a;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/HeightmapCodec.cs.meta b/unity/Assets/Scripts/Map/HeightmapCodec.cs.meta
new file mode 100644
index 000000000..3878574e6
--- /dev/null
+++ b/unity/Assets/Scripts/Map/HeightmapCodec.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 4c7c8817662b14b099ee8485f541f86d
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/HeightmapLoader.cs b/unity/Assets/Scripts/Map/HeightmapLoader.cs
index 46f0a9300..1cd3c6316 100644
--- a/unity/Assets/Scripts/Map/HeightmapLoader.cs
+++ b/unity/Assets/Scripts/Map/HeightmapLoader.cs
@@ -13,24 +13,23 @@ namespace Statecraft.Game.Map
public static class HeightmapLoader
{
- /// <summary>Reads heightmap.json and heightmap.r16 from <paramref name="dir"/> with System.IO (editor and desktop).</summary>
+ /// <summary>Reads heightmap.json and heightmap.r16z (HeightmapCodec) from <paramref name="dir"/> with System.IO (editor
+ /// and desktop).</summary>
public static (HeightmapMeta meta, float[,] heights) Load(string dir)
{
var metaPath = Path.Combine(dir, "heightmap.json");
- return Load(File.ReadAllText(metaPath), File.ReadAllBytes(Path.Combine(dir, "heightmap.r16")), metaPath);
+ return Load(File.ReadAllText(metaPath), File.ReadAllBytes(Path.Combine(dir, HeightmapCodec.FileName)), metaPath);
}
/// <summary>Parses already-read heightmap inputs (no System.IO, so a WebGL build can pass what UnityWebRequest
- /// fetched). Errors name <paramref name="metaSource"/> for the meta, as the path overload names the file.</summary>
- public static (HeightmapMeta meta, float[,] heights) Load(string metaJson, byte[] r16, string metaSource = "heightmap.json")
+ /// fetched): the meta, then the packed grid (heightmap.r16z), decoded to exactly the raw heights. Errors name
+ /// <paramref name="metaSource"/> for the meta, as the path overload names the file.</summary>
+ public static (HeightmapMeta meta, float[,] heights) Load(string metaJson, byte[] r16z, string metaSource = "heightmap.json")
{
var meta = ParseMeta(metaSource, metaJson);
if (meta.width != meta.height) throw new InvalidDataException($"heightmap.json: width {meta.width} != height {meta.height}");
- if (r16 == null) throw new ArgumentNullException(nameof(r16));
- if (r16.Length != meta.width * meta.height * 2) throw new InvalidDataException($"heightmap.r16: {r16.Length} bytes, expected {meta.width * meta.height * 2}");
- var raw = new ushort[meta.width * meta.height];
- Buffer.BlockCopy(r16, 0, raw, 0, r16.Length); // little-endian on all our targets
- return (meta, ToUnityHeights(raw, meta.width));
+ if (r16z == null) throw new ArgumentNullException(nameof(r16z));
+ return (meta, ToUnityHeights(HeightmapCodec.Decode(r16z, meta.width, meta.height), meta.width));
}
static HeightmapMeta ParseMeta(string path, string text)
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index 2462f297e..546fd3b0d 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -109,7 +109,7 @@ namespace Statecraft.Game.Map
if (cam == null) throw new InvalidOperationException("MapScene needs a camera tagged MainCamera");
Clear();
- var (meta, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16, MetaPath);
+ var (meta, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16z, MetaPath);
DiagLog.BootPhase("heightmap decoded");
Hexes = MapBuilder.LoadHexes(inputs.HexesJson, HexesPath);
DiagLog.BootPhase("hexes parsed");
diff --git a/unity/Assets/StreamingAssets/map/heightmap.r16 b/unity/Assets/StreamingAssets/map/heightmap.r16
deleted file mode 100644
index 9f6faee38..000000000
Binary files a/unity/Assets/StreamingAssets/map/heightmap.r16 and /dev/null differ
diff --git a/unity/Assets/StreamingAssets/map/heightmap.r16z b/unity/Assets/StreamingAssets/map/heightmap.r16z
new file mode 100644
index 000000000..812532423
Binary files /dev/null and b/unity/Assets/StreamingAssets/map/heightmap.r16z differ
diff --git a/unity/Assets/StreamingAssets/map/heightmap.r16.meta b/unity/Assets/StreamingAssets/map/heightmap.r16z.meta
similarity index 100%
rename from unity/Assets/StreamingAssets/map/heightmap.r16.meta
rename to unity/Assets/StreamingAssets/map/heightmap.r16z.meta
diff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs b/unity/Assets/Tests/EditMode/GameInputsTests.cs
index 15c4ac732..03437b2ef 100644
--- a/unity/Assets/Tests/EditMode/GameInputsTests.cs
+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs
@@ -42,7 +42,7 @@ public class GameInputsTests
var site = Path.Combine(Path.GetTempPath(), "statecraft-site-" + System.Guid.NewGuid().ToString("N"));
ContentManifest.Copy(Paths.Content, Path.Combine(site, "content"));
Directory.CreateDirectory(Path.Combine(site, "map"));
- foreach (var f in new[] { "heightmap.json", "heightmap.r16" }) File.Copy(Path.Combine(Paths.StreamingMap, f), Path.Combine(site, "map", f));
+ foreach (var f in new[] { "heightmap.json", "heightmap.r16z" }) File.Copy(Path.Combine(Paths.StreamingMap, f), Path.Combine(site, "map", f));
return site;
}
@@ -56,7 +56,7 @@ public class GameInputsTests
Assert.IsTrue(fetch.IsCompleted, "fetch did not finish within 60 seconds");
var fetched = fetch.GetResult();
var disk = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
- CollectionAssert.AreEqual(disk.Map.HeightmapR16, fetched.Map.HeightmapR16);
+ CollectionAssert.AreEqual(disk.Map.HeightmapR16z, fetched.Map.HeightmapR16z);
Assert.AreEqual(disk.Map.HeightmapJson, fetched.Map.HeightmapJson);
Assert.AreEqual(disk.Map.SettlementsYaml, fetched.Map.SettlementsYaml);
Assert.AreEqual(disk.Map.HexesJson, fetched.Map.HexesJson);
@@ -194,7 +194,7 @@ public class GameInputsTests
var disk = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
Assert.AreEqual(disk.Content.Hash, fetched.Content.Hash);
Assert.AreEqual(Simulation.NewGame(disk.Content, 7, Mode.Historical).Hash(), Simulation.NewGame(fetched.Content, 7, Mode.Historical).Hash());
- CollectionAssert.AreEqual(disk.Map.HeightmapR16, fetched.Map.HeightmapR16);
+ CollectionAssert.AreEqual(disk.Map.HeightmapR16z, fetched.Map.HeightmapR16z);
Assert.AreEqual(0, GameInputs.OpenRequests);
check(server);
}
@@ -209,11 +209,11 @@ public class GameInputsTests
[UnityTest]
public IEnumerator AServerErrorIsRetried() =>
- FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/people.yaml"] = ("503", 1), ["map/heightmap.r16"] = ("500", 2) },
+ FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/people.yaml"] = ("503", 1), ["map/heightmap.r16z"] = ("500", 2) },
server =>
{
Assert.AreEqual(2, server.Hits("content/people.yaml"));
- Assert.AreEqual(3, server.Hits("map/heightmap.r16"));
+ Assert.AreEqual(3, server.Hits("map/heightmap.r16z"));
});
[UnityTest]
diff --git a/unity/Assets/Tests/EditMode/MapTests.cs b/unity/Assets/Tests/EditMode/MapTests.cs
index 09c04a310..43b0d2f50 100644
--- a/unity/Assets/Tests/EditMode/MapTests.cs
+++ b/unity/Assets/Tests/EditMode/MapTests.cs
@@ -41,11 +41,12 @@ public class MapTests
System.IO.Directory.CreateDirectory(dir);
System.IO.File.WriteAllText(System.IO.Path.Combine(dir, "heightmap.json"),
"{\"width\":3,\"height\":3,\"lon0\":34.2,\"lon1\":35.9,\"lat0\":29.45,\"lat1\":33.35,\"elev_min_m\":-427,\"elev_max_m\":2367,\"width_km\":161.5,\"length_km\":431.2,\"attribution\":\"x\"}");
- System.IO.File.WriteAllBytes(System.IO.Path.Combine(dir, "heightmap.r16"), new byte[10]); // 3x3 needs 18 bytes
+ var twoByTwo = HeightmapCodec.Encode(new ushort[4], 2, 2); // a valid stream of 8 bytes; 3x3 needs 18
+ System.IO.File.WriteAllBytes(System.IO.Path.Combine(dir, HeightmapCodec.FileName), twoByTwo);
var ex = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(dir));
- StringAssert.Contains("expected 18", ex.Message);
+ StringAssert.Contains("heightmap.r16z: 8 bytes after inflating, expected 18", ex.Message);
var metaPath = System.IO.Path.Combine(dir, "heightmap.json");
- var fromBytes = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(System.IO.File.ReadAllText(metaPath), new byte[10], metaPath));
+ var fromBytes = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(System.IO.File.ReadAllText(metaPath), twoByTwo, metaPath));
Assert.AreEqual(ex.Message, fromBytes.Message);
}
@@ -235,10 +236,11 @@ public class MapTests
{
var meta = TempFile("heightmap.json", json);
var dir = System.IO.Path.GetDirectoryName(meta);
- System.IO.File.WriteAllBytes(System.IO.Path.Combine(dir, "heightmap.r16"), new byte[18]);
+ var packed = HeightmapCodec.Encode(new ushort[9], 3, 3);
+ System.IO.File.WriteAllBytes(System.IO.Path.Combine(dir, HeightmapCodec.FileName), packed);
var ex = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(dir));
StringAssert.Contains("heightmap.json", ex.Message); StringAssert.Contains(problem, ex.Message);
- var fromText = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(json, new byte[18], meta));
+ var fromText = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(json, packed, meta));
Assert.AreEqual(ex.Message, fromText.Message);
}
@@ -258,7 +260,7 @@ public class MapTests
// --- Text/bytes inputs, for the WebGL build that cannot use System.IO on streamingAssetsPath (final fix 3, I2) ---
static string MetaPath => System.IO.Path.Combine(Paths.StreamingMap, "heightmap.json");
- static string R16Path => System.IO.Path.Combine(Paths.StreamingMap, "heightmap.r16");
+ static string R16Path => System.IO.Path.Combine(Paths.StreamingMap, HeightmapCodec.FileName);
[Test]
public void HeightmapFromBytesMatchesHeightmapFromPath()
@@ -297,6 +299,57 @@ public class MapTests
finally { Object.DestroyImmediate(a); Object.DestroyImmediate(b); }
}
+ // --- The packed heightmap (issue #44): smaller download, the same terrain ---
+
+ /// <summary>SHA-256 of the raw heightmap.r16 (8,396,802 bytes) shipped before issue #44 packed it.</summary>
+ const string RawHeightmapSha256 = "b6882a77420efa90217cc65a9c353147569094cf16656d4d53c30abe0f41ac9e";
+
+ [Test]
+ public void ThePackedHeightmapDecodesToTheOldRawFileByteForByte()
+ {
+ var meta = HeightmapLoader.Load(Paths.StreamingMap).meta;
+ var packed = System.IO.File.ReadAllBytes(R16Path);
+ var raw = HeightmapCodec.Decode(packed, meta.width, meta.height);
+ var bytes = new byte[raw.Length * 2];
+ System.Buffer.BlockCopy(raw, 0, bytes, 0, bytes.Length); // little-endian, as the raw file was
+ using var sha = System.Security.Cryptography.SHA256.Create();
+ Assert.AreEqual(RawHeightmapSha256, System.BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "").ToLowerInvariant());
+ Assert.Less(packed.Length, 0.55 * bytes.Length, "the packed file is about half the raw grid");
+ Assert.IsFalse(System.IO.File.Exists(System.IO.Path.Combine(Paths.StreamingMap, "heightmap.r16")), "the raw file is not shipped beside it");
+ }
+
+ [Test]
+ public void TheCodecRoundTripsWraparoundDeltasAndRejectsACorruptStream()
+ {
+ var rng = new System.Random(44);
+ foreach (var (w, h) in new[] { (1, 1), (3, 3), (5, 7), (64, 64) })
+ {
+ var raw = new ushort[w * h];
+ for (int i = 0; i < raw.Length; i++) raw[i] = (ushort)rng.Next(0, 65536);
+ raw[0] = 65535; raw[raw.Length - 1] = 0;
+ CollectionAssert.AreEqual(raw, HeightmapCodec.Decode(HeightmapCodec.Encode(raw, w, h), w, h), $"{w}x{h}");
+ }
+ var packed = HeightmapCodec.Encode(new ushort[] { 1, 3, 0x0102, 0x0101 }, 2, 2);
+ Assert.AreEqual(1u, HeightmapCodec.Adler32(new byte[0]));
+ Assert.AreEqual(0x11E60398u, HeightmapCodec.Adler32(System.Text.Encoding.ASCII.GetBytes("Wikipedia")), "the RFC 1950 example");
+ var corrupt = (byte[])packed.Clone(); corrupt[corrupt.Length - 1] ^= 1;
+ StringAssert.Contains("checksum", Assert.Throws<System.IO.InvalidDataException>(() => HeightmapCodec.Decode(corrupt, 2, 2)).Message);
+ StringAssert.Contains("not a zlib stream", Assert.Throws<System.IO.InvalidDataException>(() => HeightmapCodec.Decode(new byte[18], 3, 3)).Message);
+ StringAssert.Contains("more than 2 bytes", Assert.Throws<System.IO.InvalidDataException>(() => HeightmapCodec.Decode(packed, 1, 1)).Message);
+ }
+
+ [Test]
+ public void TheCodecReadsWhatThePythonToolWrites()
+ {
+ // tools/tests/test_heightmap_codec.py pins the same layout: row deltas, low-byte plane then high-byte plane.
+ 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);
+ var planes = new byte[8]; int got = 0, r;
+ while ((r = inflate.Read(planes, got, planes.Length - got)) > 0) got += r;
+ CollectionAssert.AreEqual(new byte[] { 1, 2, 0x02, 0xFF, 0, 0, 0x01, 0xFF }, planes);
+ }
+
// --- hexes.json and the heightmap must cover the same area (final fix 3, M3) ---
[TestCase(1e-6, 0, 0, 0)]