"""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 io import BytesIO 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: """Keep selected layer trees without reviving hidden descendants. Selected layers and their ancestors must be visible so they can render, but descendants retain the visibility saved in the PSD. Forcing every descendant on can composite hidden backup/alternate art over the intended map (Customs Dorms contains exactly such a hidden duplicate floor set). """ 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 # Ancestors (including an exact target) must be enabled. Once we # are below a selected group, preserve each child's authored # visibility instead of turning hidden alternates back on. if ancestor: 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 find_layer(psd, raw_path: str, map_id: str): node = psd for name in raw_path.split("/"): layer = next((child for child in node if child.name == name), None) if layer is None: raise SystemExit( f"[{map_id}] layer path {raw_path!r} matched nothing. " "Run: python tools/psd_tree.py --depth 6" ) node = layer return node def embedded_underlays(psd, paths: list[str], map_id: str): """Expand layered PSB smart objects that psd-tools flattens incorrectly. Interchange's exterior is a four-layer PSB. Re-compositing the outer PSD uses an incomplete cached rendering and drops much of the west side. The internal composite has alpha bounds that exactly match the outer smart object's bbox, so render it explicitly as the bottom map-art layer and keep the outer fixes, boundaries, interiors and inset above it. """ result = [] for path in paths: layer = find_layer(psd, path, map_id) if layer.kind != "smartobject" or layer.smart_object is None: raise SystemExit(f"[{map_id}] underlay {path!r} is not a smart object") if layer.smart_object.filetype not in {"8bps", "8bpb"}: raise SystemExit(f"[{map_id}] underlay {path!r} is not an embedded PSD/PSB") embedded = PSDImage.open(BytesIO(layer.smart_object.data)) image = embedded.composite(viewport=embedded.viewbox, force=True).convert("RGBA") alpha_bbox = image.getchannel("A").getbbox() if alpha_bbox is None: raise SystemExit(f"[{map_id}] underlay {path!r} rendered empty") image = image.crop(alpha_bbox) left, top, right, bottom = layer.bbox expected = (right - left, bottom - top) if image.size != expected: raise SystemExit( f"[{map_id}] underlay {path!r} rendered {image.size}, " f"expected outer bbox {expected}" ) layer.visible = False view_left, view_top, _, _ = psd.viewbox result.append((image, (left - view_left, top - view_top))) print(f"[{map_id}] expanded embedded underlay {path!r}") return result def alpha_composite_clipped(canvas: Image.Image, source: Image.Image, position: tuple[int, int]) -> None: x, y = position left, top = max(0, x), max(0, y) right = min(canvas.width, x + source.width) bottom = min(canvas.height, y + source.height) if right <= left or bottom <= top: return crop = source.crop((left - x, top - y, right - x, bottom - y)) canvas.alpha_composite(crop, (left, top)) 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"]) underlays = embedded_underlays( psd, m.get("baseUnderlaySmartObjects", []), 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. remainder = psd.composite(viewport=psd.viewbox, force=True).convert("RGBA") if underlays: img = Image.new("RGBA", remainder.size, (0, 0, 0, 0)) for underlay, position in underlays: alpha_composite_clipped(img, underlay, position) img.alpha_composite(remainder) else: img = remainder 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:])