"""PSD -> flat base-map PNG. Keeps only the layers named in `baseLayers` and hides everything else, so no markers, legend, title or captions survive into the tiles. python tools/export_base.py # every map python tools/export_base.py customs # one map `baseLayers` is a list of slash-separated paths from the document root: ["LOCATION"] Customs -- one top-level group ["Background", "3DRENDER"] Interchange -- base image plus render, in order ["re3mr.com/Map&Art"] Woods -- nested inside a wrapper group The re3mr maps do NOT share a naming convention: the base group is variously LOCATION, Baselayer, Day, 3DRENDER, BASEMAP+2DLAYERS or Map&Art, and several maps need more than one top-level layer. Run psd_tree.py per map. `excludeLayers` then hides individual layers by name anywhere in the kept set. That exists because psd-tools renders stroke-only vector shapes as solid fills -- Customs' "Map Borders" paints the whole playable area white. Output: build//base.png (full PSD canvas, uncropped -- tile.py crops) """ from __future__ import annotations import sys import time import importlib from PIL import Image from psd_tools import PSDImage from common import BUILD, ROOT, find_map, load_config # `psd_tools.composite` exports a function called `composite`, which shadows # the submodule of the same name -- so import it explicitly. _psd_composite = importlib.import_module("psd_tools.composite.composite") Image.MAX_IMAGE_PIXELS = None def _patch_stroke_effects() -> None: """Skip stroke layer-effects instead of dying on them. psd-tools feeds a zero-size array into scikit-image's rank filter when a layer carries a stroke effect but has an empty bbox, which raises "The parameter `image` cannot be an empty array" and kills the whole render. Woods hits this. A missing outline is a far better outcome than no map, and the effect is chrome we are dropping anyway. """ original = _psd_composite.Compositor._apply_stroke_effect def safe(self, layer, color, shape, alpha): try: return original(self, layer, color, shape, alpha) except Exception as exc: # noqa: BLE001 - third-party failure mode print(f" (skipped stroke effect on {layer.name!r}: {type(exc).__name__})") return None _psd_composite.Compositor._apply_stroke_effect = safe _patch_stroke_effects() def apply_visibility(psd, keep: list[str], map_id: str) -> None: """Hide every layer that is not on the path to, or inside, a kept layer.""" kept = [tuple(p.split("/")) for p in keep] matched: set[tuple[str, ...]] = set() def walk(node, prefix: tuple[str, ...]): for layer in node: path = prefix + (layer.name,) # Keep a layer if it *is* a target, is an ancestor of one (so the # target is reachable), or is a descendant of one. inside = any(path[:len(t)] == t for t in kept) ancestor = any(t[:len(path)] == path for t in kept) if inside: matched.update(t for t in kept if path[:len(t)] == t) if not (inside or ancestor): layer.visible = False continue layer.visible = True if layer.is_group(): walk(layer, path) walk(psd, ()) for t in kept: if t not in matched: raise SystemExit( f"[{map_id}] baseLayers entry {'/'.join(t)!r} matched nothing. " f"Run: python tools/psd_tree.py --depth 2" ) def hide(psd, names: list[str], map_id: str) -> None: remaining = set(names) seen: set[str] = set() def walk(node): for layer in node: seen.add(layer.name) if layer.name in remaining: layer.visible = False print(f"[{map_id}] excluding {layer.name!r}") elif layer.is_group(): walk(layer) walk(psd) for missing in remaining - seen: print(f"[{map_id}] WARNING: excludeLayers entry {missing!r} matched nothing") def export(m: dict) -> None: psd_path = ROOT / m["psd"] if not psd_path.exists(): raise SystemExit(f"missing source PSD: {psd_path}") out = BUILD / m["id"] / "base.png" out.parent.mkdir(parents=True, exist_ok=True) print(f"[{m['id']}] opening {psd_path.name} ({psd_path.stat().st_size / 1e6:.0f} MB)") t0 = time.time() psd = PSDImage.open(psd_path) keep = m.get("baseLayers") or ([m["baseGroup"]] if m.get("baseGroup") else None) if not keep: raise SystemExit(f"[{m['id']}] needs baseLayers in maps.json") print(f"[{m['id']}] canvas {psd.size[0]}x{psd.size[1]}, keeping {', '.join(map(repr, keep))}") apply_visibility(psd, keep, m["id"]) if m.get("excludeLayers"): hide(psd, m["excludeLayers"], m["id"]) # Keep alpha: these maps are composited onto the overall base map, so # anything outside the map art should show the terrain underneath rather # than an opaque white or black rectangle. img = psd.composite(viewport=psd.viewbox, force=True).convert("RGBA") img.save(out, "PNG", optimize=False, compress_level=1) print(f"[{m['id']}] wrote {out.relative_to(ROOT)} " f"{img.size[0]}x{img.size[1]} in {time.time() - t0:.0f}s\n") def main(argv: list[str]) -> None: cfg = load_config() targets = [find_map(cfg, i) for i in argv] if argv else cfg.maps failed = [] for m in targets: # One unrenderable PSD shouldn't cost you the whole batch -- these # take minutes each. try: export(m) except Exception as exc: # noqa: BLE001 failed.append((m["id"], f"{type(exc).__name__}: {exc}")) print(f"[{m['id']}] FAILED -- {type(exc).__name__}: {exc}\n") if failed: print("failed maps:") for map_id, err in failed: print(f" {map_id}: {err}") raise SystemExit(1) if __name__ == "__main__": main(sys.argv[1:])