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.

Map asset tools refuse bad output instead of reporting success (Fixes #2652) (#2657)

Eyal Golan0c976fb2102c
diff --git a/tools/dem_to_heightmap.py b/tools/dem_to_heightmap.py
index cb7ae5dbd..edffd5be9 100644
--- a/tools/dem_to_heightmap.py
+++ b/tools/dem_to_heightmap.py
@@ -5,7 +5,8 @@
"""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."""
+Tiles are cached in tools/.cache/dem/ (not committed). A tile that returns 404 is open sea.
+No tile data at all, or a flat mosaic, is refused rather than written (#2652)."""
import json
import math
from pathlib import Path
@@ -68,6 +69,8 @@ def mosaic(paths: list[Path], b: dict, size: int) -> np.ndarray:
def write_heightmap(elev: np.ndarray, b: dict, out: Path) -> dict:
lo, hi = float(elev.min()), float(elev.max())
+ if hi == lo:
+ raise ValueError(f"the DEM is flat at {lo:g} m; refusing to write a heightmap")
raw = np.round((elev - lo) / (hi - lo) * 65535).astype("<u2")
out.mkdir(parents=True, exist_ok=True)
heightmap_codec.write(out, raw) # packed, lossless (issue #44): the raw grid is never written
@@ -88,6 +91,8 @@ def main() -> None:
print(f"N{lat} E{lon:03d}: {'sea (404)' if p is None else p.name}")
if p:
paths.append(p)
+ if not paths:
+ raise RuntimeError("no DEM tile has data (every tile answered 404); refusing to write an all-sea heightmap")
meta = write_heightmap(mosaic(paths, BOUNDS, SIZE), BOUNDS, OUT)
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/hex_tiles/make_board.py b/tools/hex_tiles/make_board.py
index 38aafb4d3..964b9279b 100644
--- a/tools/hex_tiles/make_board.py
+++ b/tools/hex_tiles/make_board.py
@@ -22,7 +22,8 @@ localities (content/map/localities_1948.tsv), and the roads follow the traced 19
Hand edits that must survive regeneration go in the sibling <id>.overrides.json (the Hex Painter writes it), applied
last. It has the shape of the map editor's content/map/overrides.yaml (#1099): one list per field (prototype, ground,
unit, facing, region) of {hex: {q, r}, value}. It is presentation only and stays out of content/, so painting a hex never
-moves the content hash. The map editor's own terrain and location overrides are read too, so boards follow the map.
+moves the content hash. Regeneration refuses to write if an override names a hex the board does not have (#2652).
+The map editor's own terrain and location overrides are read too, so boards follow the map.
python3 tools/hex_tiles/make_board.py [--id central_israel] [--lat 31.62 32.48] [--lon 34.4 35.42]
"""
@@ -280,7 +281,7 @@ def overrides_path(board_path):
def apply_overrides(board, overrides):
"""A board's hand edits, in the shape of content/map/overrides.yaml (#1099): one list per field (prototype, ground,
unit, facing, region) of {hex: {q, r}, value}, no hex twice in a list; facing is degrees as a string. Returns the
- edits whose hex the board does not have (reported, not applied)."""
+ edits whose hex the board does not have (not applied; main refuses to write the board)."""
at = {(e['q'], e['r']): e for e in board['hexes']}
unknown = [k for k in overrides if k != 'board' and k not in OVERRIDE_FIELDS]
if unknown: raise ValueError(f"override list '{unknown[0]}' is not one of {OVERRIDE_FIELDS}")
@@ -560,7 +561,11 @@ def main(argv=None):
ov = overrides_path(dst)
if os.path.exists(ov):
with open(ov, encoding='utf-8') as f: missing = apply_overrides(board, json.load(f))
- for field, ed in missing: print(f' {field} override of ({ed["hex"]["q"]},{ed["hex"]["r"]}): no such hex on this board, not applied')
+ for field, ed in missing:
+ print(f'REFUSED: {field} override of ({ed["hex"]["q"]},{ed["hex"]["r"]}): no such hex on this board', file=sys.stderr)
+ if missing:
+ print(f'REFUSED: {ov} names {len(missing)} hex(es) this board does not have; {dst} was not written', file=sys.stderr)
+ return 1
with open(dst, 'w') as f: json.dump(board, f, indent=1)
from collections import Counter
out, roads = board['hexes'], board['roads']
diff --git a/tools/tests/test_dem_to_heightmap.py b/tools/tests/test_dem_to_heightmap.py
index 927116820..6a5f33477 100644
--- a/tools/tests/test_dem_to_heightmap.py
+++ b/tools/tests/test_dem_to_heightmap.py
@@ -52,3 +52,19 @@ def test_write_heightmap_normalises_and_writes_metadata(tmp_path):
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"]
+
+
+def test_main_refuses_when_every_tile_is_missing(monkeypatch):
+ """#2652: every tile answering 404 (a wrong endpoint, say) is refused, not written as an all-sea map."""
+ monkeypatch.setattr(dem, "tiles_for_bounds", lambda _: [(29, 34), (29, 35)])
+ monkeypatch.setattr(dem, "fetch_tile", lambda *_: None)
+ monkeypatch.setattr(dem, "mosaic", lambda *_: pytest.fail("mosaic must not run without tile data"))
+ with pytest.raises(RuntimeError, match="no DEM tile has data"):
+ dem.main()
+
+
+def test_write_heightmap_refuses_a_flat_grid_before_writing(tmp_path):
+ out = tmp_path / "map"
+ with pytest.raises(ValueError, match="the DEM is flat"):
+ dem.write_heightmap(np.zeros((2, 2), dtype="float32"), dem.BOUNDS, out)
+ assert not out.exists()
diff --git a/tools/tests/test_hex_regions.py b/tools/tests/test_hex_regions.py
index 78eef5c25..a2c1c07e9 100644
--- a/tools/tests/test_hex_regions.py
+++ b/tools/tests/test_hex_regions.py
@@ -219,7 +219,7 @@ def edit(q, r, value):
return {"hex": {"q": q, "r": r}, "value": value}
-def test_overrides_are_applied_last_and_survive_regeneration(tmp_path, capsys):
+def test_overrides_are_applied_last_and_survive_regeneration(tmp_path):
out = tmp_path / "israel.json"
mb.main(COUNTRY + ["--out", str(out)])
first = json.loads(out.read_text())
@@ -230,14 +230,13 @@ def test_overrides_are_applied_last_and_survive_regeneration(tmp_path, capsys):
# The shape of content/map/overrides.yaml (#1099): one list per field of {hex: {q, r}, value}.
(tmp_path / "israel.overrides.json").write_text(json.dumps({
"board": "israel",
- "prototype": [edit(*ta, "kibbutz"), edit(999, 999, "kibbutz")],
+ "prototype": [edit(*ta, "kibbutz")],
"ground": [edit(*ta, "plains")],
"unit": [edit(*sq, "")],
"facing": [edit(*sq, "0")],
"region": [edit(ring["q"], ring["r"], "upper_galilee")],
}))
mb.main(COUNTRY + ["--out", str(out)])
- assert "(999,999)" in capsys.readouterr().out
after = {(h["q"], h["r"]): h for h in json.loads(out.read_text())["hexes"]}
assert (after[ta]["prototype"], after[ta]["ground"]) == ("kibbutz", "plains")
assert (after[sq]["unit"], after[sq]["facing"]) == ("", 0.0)
@@ -248,6 +247,16 @@ def test_overrides_are_applied_last_and_survive_regeneration(tmp_path, capsys):
assert all(after[(h["q"], h["r"])] == h for h in first["hexes"] if (h["q"], h["r"]) not in edited)
+def test_an_override_for_a_missing_hex_refuses_and_leaves_the_board_unwritten(tmp_path, capsys):
+ """#2652: a hand edit the regenerated board cannot hold must not be dropped silently."""
+ out = tmp_path / "israel.json"
+ out.write_text("previous board") # a sentinel, so an identical regeneration cannot pass for "not written"
+ (tmp_path / "israel.overrides.json").write_text(json.dumps({"board": "israel", "prototype": [edit(999, 999, "kibbutz")]}))
+ assert mb.main(COUNTRY + ["--out", str(out)]) == 1
+ assert out.read_text() == "previous board"
+ assert "(999,999)" in capsys.readouterr().err
+
+
def test_an_override_of_an_unknown_field_or_a_hex_twice_fails():
board = {"hexes": [{"q": 0, "r": 0, "terrain": "flat"}]}
with pytest.raises(ValueError):