"""Orchestrator: maps.json -> tiles + web/data/world.json. python tools/build.py # base + every map python tools/build.py customs # just one map python tools/build.py --tiles-only # skip the slow PSD render python tools/build.py shoreline --tiles-only --trim-only python tools/build.py --force-export # re-render even if base.png exists python tools/build.py --stamp-only # record the PSDs behind existing base.pngs Exporting a 1 GB PSD takes minutes, so base.png is reused unless the PSD has changed since it was rendered or --force-export is given. "Changed" is decided from build//base.stamp.json (PSD size, mtime and SHA-256 at export time), not from file mtimes alone: build/ and sources/ are both checked out through Git LFS, so after a fresh clone their mtimes say nothing. A PSD with a new size is re-exported; one with the same size but a new mtime is hashed first. The base layer (`overall`) is a plain image and is always cheap to retile. """ from __future__ import annotations import hashlib import json import sys import export_base import tile from common import BUILD, DATA, ROOT, WORLD_ID, load_config def stamp_path(m: dict): return BUILD / m["id"] / "base.stamp.json" def sha256_of(path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def write_stamp(m: dict) -> None: """Record which PSD bytes the current base.png was rendered from.""" psd = ROOT / m["psd"] if not psd.exists(): return st = psd.stat() stamp = {"psd": m["psd"], "size": st.st_size, "mtime": st.st_mtime, "sha256": sha256_of(psd)} stamp_path(m).write_text(json.dumps(stamp, indent=2), encoding="utf-8") def needs_export(m: dict, force: bool) -> bool: base = BUILD / m["id"] / "base.png" if force or not base.exists(): return True psd = ROOT / m["psd"] if not psd.exists(): return False try: stamp = json.loads(stamp_path(m).read_text(encoding="utf-8")) except (OSError, ValueError): stamp = None st = psd.stat() if not stamp: # No stamp (pre-stamp checkout): fall back to the old mtime rule. return st.st_mtime > base.stat().st_mtime if stamp.get("size") != st.st_size: return True if stamp.get("mtime") == st.st_mtime: return False # Same size, different mtime: usually a fresh checkout. Hash to be sure, # and refresh the stamp so the next run is a cheap stat() again. if sha256_of(psd) != stamp.get("sha256"): return True stamp["mtime"] = st.st_mtime stamp_path(m).write_text(json.dumps(stamp, indent=2), encoding="utf-8") return False def main(argv: list[str]) -> None: trim_only = "--trim-only" in argv tiles_only = "--tiles-only" in argv or trim_only force = "--force-export" in argv stamp_only = "--stamp-only" in argv ids = [a for a in argv if not a.startswith("--")] cfg = load_config() world_m = tile.world_entry(cfg) if stamp_only: for m in cfg.maps: if ids and m["id"] not in ids: continue if (BUILD / m["id"] / "base.png").exists(): write_stamp(m) print(f"[{m['id']}] stamped {m['psd']}") return if ids: targets = [world_m] if WORLD_ID in ids else [] targets += [m for m in cfg.maps if m["id"] in ids] known = {m["id"] for m in cfg.maps} | {WORLD_ID} unknown = set(ids) - known if unknown: raise SystemExit(f"unknown map id(s): {', '.join(sorted(unknown))}") else: targets = [world_m] + cfg.maps if not tiles_only: failed = [] for m in targets: if m["id"] == WORLD_ID: continue if not needs_export(m, force): print(f"[{m['id']}] base.png up to date, skipping export") continue try: export_base.export(m) write_stamp(m) except Exception as exc: # noqa: BLE001 failed.append(m["id"]) print(f"[{m['id']}] EXPORT FAILED -- {type(exc).__name__}: {exc}\n") if failed: print(f"skipping tiling for failed export(s): {', '.join(failed)}\n") targets = [m for m in targets if m["id"] not in failed] entries = [] for m in targets: if m["id"] != WORLD_ID and not (BUILD / m["id"] / "base.png").exists(): print(f"[{m['id']}] no base.png, skipping tiling") continue entries.append(tile.tile_map(cfg, m, trim_only=trim_only)) # Keep maps that weren't part of this run so partial builds don't drop them. by_id = {e["id"]: e for e in entries} world_path = DATA / "world.json" if world_path.exists(): for e in json.loads(world_path.read_text(encoding="utf-8")).get("maps", []): by_id.setdefault(e["id"], e) known = {m["id"] for m in cfg.maps} | {WORLD_ID} maps = [e for e in by_id.values() if e["id"] in known] # Base first so it paints underneath everything else. maps.sort(key=lambda e: (not e.get("base"), -e["size"][0])) ww, wh = cfg.world_size() world = { "tileSize": cfg.tile_size, "maxZoom": cfg.max_zoom, "worldSize": [ww, wh], "cellSize": cfg.cell_size, "rotate": cfg.rotate, "overallScale": cfg.overall_scale, "attribution": cfg.attribution, "maps": maps, } DATA.mkdir(parents=True, exist_ok=True) world_path.write_text(json.dumps(world, indent=2, ensure_ascii=False), encoding="utf-8") print(f"\nwrote {world_path.relative_to(ROOT)}: world {ww}x{wh}, {len(maps)} layer(s)") if __name__ == "__main__": main(sys.argv[1:])