A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
feat(tools): Copernicus DEM to Unity heightmap
eyalgolan9249c2eee9f9
diff --git a/.gitignore b/.gitignoreindex 96beb8a75..a98a05c6b 100644--- a/.gitignore+++ b/.gitignore@@ -3,3 +3,5 @@ promo/preview/promo/*.log.DS_Store.worktrees/+tools/.cache/+__pycache__/diff --git a/tools/README.md b/tools/README.mdnew file mode 100644index 000000000..c2e0d0363--- /dev/null+++ b/tools/README.md@@ -0,0 +1,15 @@+# tools/++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`.+- `hexgrid.py` writes `content/map/hexes.json` from that heightmap.+- `preview_map.py` renders the geography check image `tools/.cache/map-preview.png`.++## Required attribution (Copernicus DEM licence, modified data)++produced using Copernicus WorldDEM-30 (c) DLR e.V. 2010-2014 and (c) Airbus Defence and Space GmbH 2014-2018+provided under COPERNICUS by the European Union and ESA; all rights reserved++This notice must also appear in the game credits and the Steam page legal notes.diff --git a/tools/dem_to_heightmap.py b/tools/dem_to_heightmap.pynew file mode 100644index 000000000..eb8118783--- /dev/null+++ b/tools/dem_to_heightmap.py@@ -0,0 +1,96 @@+# /// script+# 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.++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."""+import json+import math+from pathlib import Path++import numpy as np+import rasterio+import requests+from rasterio.transform import from_bounds+from rasterio.warp import Resampling, reproject++ROOT = Path(__file__).resolve().parents[1]+CACHE = ROOT / "tools" / ".cache" / "dem"+OUT = ROOT / "unity" / "Assets" / "StreamingAssets" / "map"+BOUNDS = {"lon0": 34.20, "lon1": 35.90, "lat0": 29.45, "lat1": 33.35}+SIZE = 2049 # Unity Terrain heightmap resolution must be 2^n + 1+KM_PER_DEG_LAT = 110.57+KM_PER_DEG_LON_EQ = 111.32+# Required notice for adapted/modified WorldDEM-30 data (Copernicus DEM licence; wording as quoted on+# developers.google.com/earth-engine/datasets/catalog/COPERNICUS_DEM_GLO30_2024_1, checked 2026-10-09).+ATTRIBUTION = ("produced using Copernicus WorldDEM-30 (c) DLR e.V. 2010-2014 and (c) Airbus Defence and Space "+ "GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved")+++def tile_url(lat: int, lon: int) -> str:+ name = f"Copernicus_DSM_COG_10_N{lat:02d}_00_E{lon:03d}_00_DEM"+ return f"https://copernicus-dem-30m.s3.amazonaws.com/{name}/{name}.tif"+++def tiles_for_bounds(b: dict) -> list[tuple[int, int]]:+ return [(lat, lon) for lat in range(math.floor(b["lat0"]), math.ceil(b["lat1"]))+ for lon in range(math.floor(b["lon0"]), math.ceil(b["lon1"]))]+++def fetch_tile(lat: int, lon: int, cache: Path = CACHE) -> Path | None:+ """Download one tile into the cache; None if it does not exist (404 = all sea)."""+ path = cache / f"N{lat:02d}E{lon:03d}.tif"+ if path.exists():+ return path+ r = requests.get(tile_url(lat, lon), timeout=600)+ if r.status_code == 404:+ return None+ r.raise_for_status()+ cache.mkdir(parents=True, exist_ok=True)+ path.write_bytes(r.content)+ return path+++def mosaic(paths: list[Path], b: dict, size: int) -> np.ndarray:+ """Average-resample all tiles onto a size x size lon/lat grid; uncovered cells = 0 m (sea)."""+ dst = np.full((size, size), np.nan, dtype="float32")+ transform = from_bounds(b["lon0"], b["lat0"], b["lon1"], b["lat1"], size, size)+ for p in paths:+ with rasterio.open(p) as src:+ reproject(source=rasterio.band(src, 1), destination=dst, dst_transform=transform,+ dst_crs="EPSG:4326", dst_nodata=np.nan, init_dest_nodata=False,+ resampling=Resampling.average)+ return np.nan_to_num(dst, nan=0.0)+++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")+ 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+ * math.cos(math.radians((b["lat0"] + b["lat1"]) / 2)),+ "length_km": (b["lat1"] - b["lat0"]) * KM_PER_DEG_LAT,+ "attribution": ATTRIBUTION}+ (out / "heightmap.json").write_text(json.dumps(meta, indent=2))+ return meta+++def main() -> None:+ paths = []+ for lat, lon in tiles_for_bounds(BOUNDS):+ p = fetch_tile(lat, lon)+ print(f"N{lat} E{lon:03d}: {'sea (404)' if p is None else p.name}")+ 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, "+ f"{meta['width_km']:.1f} x {meta['length_km']:.1f} km")+++if __name__ == "__main__":+ main()diff --git a/tools/tests/conftest.py b/tools/tests/conftest.pynew file mode 100644index 000000000..5801beaef--- /dev/null+++ b/tools/tests/conftest.py@@ -0,0 +1,4 @@+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))diff --git a/tools/tests/test_dem_to_heightmap.py b/tools/tests/test_dem_to_heightmap.pynew file mode 100644index 000000000..509ef69b5--- /dev/null+++ b/tools/tests/test_dem_to_heightmap.py@@ -0,0 +1,52 @@+import json++import numpy as np+import pytest+import rasterio+from rasterio.transform import from_origin++import dem_to_heightmap as dem+++def make_tile(path, lat, lon, value, size=60):+ """1x1 degree synthetic GeoTIFF whose top-left corner is (lon, lat + 1)."""+ data = np.full((size, size), value, dtype="float32")+ with rasterio.open(path, "w", driver="GTiff", height=size, width=size, count=1, dtype="float32",+ crs="EPSG:4326", transform=from_origin(lon, lat + 1, 1 / size, 1 / size)) as ds:+ ds.write(data, 1)+++def test_tile_url_matches_copernicus_naming():+ assert dem.tile_url(31, 34) == (+ "https://copernicus-dem-30m.s3.amazonaws.com/Copernicus_DSM_COG_10_N31_00_E034_00_DEM/"+ "Copernicus_DSM_COG_10_N31_00_E034_00_DEM.tif")+++def test_tiles_for_bounds_covers_every_degree_cell():+ assert dem.tiles_for_bounds(dem.BOUNDS) == [(lat, lon) for lat in range(29, 34) for lon in (34, 35)]+++def test_missing_tile_is_sea_and_mosaic_keeps_north_up(tmp_path):+ make_tile(tmp_path / "n31e034.tif", 31, 34, 100.0) # southern tile+ make_tile(tmp_path / "n32e034.tif", 32, 34, -50.0) # northern tile+ bounds = {"lon0": 34.0, "lon1": 35.0, "lat0": 30.0, "lat1": 33.0} # lat 30-31 has no tile -> sea+ elev = dem.mosaic([tmp_path / "n31e034.tif", tmp_path / "n32e034.tif"], bounds, 30)+ assert elev.shape == (30, 30)+ assert elev[0, 15] == pytest.approx(-50.0) # row 0 = north edge (lat 33)+ assert elev[15, 15] == pytest.approx(100.0) # middle third = lat 31-32+ assert elev[-1, 15] == 0.0 # no tile: sea level+++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 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())+ assert on_disk == meta+ assert meta["elev_min_m"] == -430.0 and meta["elev_max_m"] == 1000.0+ assert meta["width"] == 2 and meta["height"] == 2+ assert meta["width_km"] == pytest.approx(1.7 * 111.32 * np.cos(np.radians(31.4)), rel=1e-6)+ assert meta["length_km"] == pytest.approx(3.9 * 110.57, rel=1e-6)+ assert "Copernicus" in meta["attribution"]diff --git a/unity/Assets/StreamingAssets/map/heightmap.json b/unity/Assets/StreamingAssets/map/heightmap.jsonnew file mode 100644index 000000000..f256eb83c--- /dev/null+++ b/unity/Assets/StreamingAssets/map/heightmap.json@@ -0,0 +1,13 @@+{+ "width": 2049,+ "height": 2049,+ "lon0": 34.2,+ "lon1": 35.9,+ "lat0": 29.45,+ "lat1": 33.35,+ "elev_min_m": -427.0436706542969,+ "elev_max_m": 2367.419921875,+ "width_km": 161.52936707957164,+ "length_km": 431.2230000000002,+ "attribution": "produced using Copernicus WorldDEM-30 (c) DLR e.V. 2010-2014 and (c) Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved"+}\ No newline at end of filediff --git a/unity/Assets/StreamingAssets/map/heightmap.r16 b/unity/Assets/StreamingAssets/map/heightmap.r16new file mode 100644index 000000000..9f6faee38Binary files /dev/null and b/unity/Assets/StreamingAssets/map/heightmap.r16 differ