Files
TarkovMaps/tools/export_base.py
T
Claude e8d8738892 Place all nine maps onto a north-up geographic world canvas
The canvas is no longer an abstract grid of unrelated cells. overall.jpeg is
now the base, rotated 31 degrees so north is up, and every detail map is
scaled and positioned onto its real location. Zoom out for all of Tarkov;
zoom in and the full-resolution re3mr map takes over.

The 31 degrees was measured, not guessed: Customs' detail map is north-up
(its PSD compass confirms it) and runs 2.6:1 east-west, so solving its
259x207 zone outline for the band angle gives 31. rotate_point is verified
sub-pixel against PIL.

Adds Woods, Interchange, Reserve, Shoreline, Shoreline Resort, Lighthouse
and Streets, and moves every source under sources/<id>/.

baseGroup becomes baseLayers, a list of slash-paths. These PSDs share no
naming convention at all -- the base is variously LOCATION, Baselayer, Day,
3DRENDER, BASEMAP+2DLAYERS or Map&Art; several need more than one top-level
layer, and Woods buries its terrain three groups deep. Exports also keep
alpha now, so maps composite onto the terrain instead of sitting in opaque
rectangles.

Placement needs sub-cell precision, but tile grids stay integral only when
a map's origin is a multiple of tileSize * 2^maxZoom (131072 px). So rather
than snapping a map to the grid, the tiler pads it up-and-left to the
nearest cell boundary and visits only tiles holding content: exact
placement, integral grid, no cost. Each map is tiled to its native level
and carries a minZoom, so the overview stays cheap.

Two psd-tools failures worked around: stroke effects on empty-bbox layers
crash scikit-image (patched to skip), and psd_tools.composite exports a
function that shadows its own submodule.

Verified zoom 0-9: 10 layers, zero broken tiles.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-08 04:02:38 -07:00

169 lines
6.0 KiB
Python

"""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/<id>/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 <psd> --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:])