251 lines
9.7 KiB
Python
251 lines
9.7 KiB
Python
"""Place a map on the world canvas and cut it into an XYZ tile pyramid.
|
|
|
|
python tools/tile.py # every map plus the base
|
|
python tools/tile.py customs # one map
|
|
|
|
Reads build/<id>/base.png (or the overall image, for the base layer)
|
|
Writes web/tiles/<id>/{z}/{x}/{y}.webp
|
|
build/<id>/trimmed.png and web/tiles-trimmed/<id>/... when trim is set
|
|
|
|
Each map is scaled to the world size implied by its `place` entry and padded
|
|
up-and-left to a cell boundary so its tile grid stays integral -- see
|
|
common.py. Only tiles that actually contain content are visited, so the
|
|
padding is free.
|
|
|
|
A map is only tiled down to its *native* level, the deepest zoom at which we
|
|
are still downscaling the source. Past that the browser upscales, which is
|
|
identical to upscaling here but without storing the tiles. A trim never
|
|
overwrites base.png or its original tiles; it produces a separate raster and
|
|
tile pyramid selected by the normal viewer.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import shutil
|
|
import sys
|
|
|
|
from PIL import Image, ImageChops, ImageDraw
|
|
|
|
from common import BUILD, ROOT, TILES, TRIMMED_TILES, WORLD_ID, Config, find_map, load_config
|
|
|
|
Image.MAX_IMAGE_PIXELS = None
|
|
|
|
WEBP = {"format": "WEBP", "quality": 82, "method": 4}
|
|
|
|
|
|
def minimum_zoom(m: dict, zmax: int, native_level: int) -> int:
|
|
"""First zoom at which a detail layer may be shown and requested.
|
|
|
|
Main maps default to zero so they remain visible in the overview. A nested
|
|
detail view can set ``minZoom`` in maps.json to stay hidden until the user
|
|
zooms close to it.
|
|
"""
|
|
if m["id"] == WORLD_ID:
|
|
return 0
|
|
|
|
configured = m.get("minZoom")
|
|
if configured is None:
|
|
return 0
|
|
if type(configured) is not int or not 0 <= configured <= zmax:
|
|
raise SystemExit(
|
|
f"[{m['id']}] minZoom must be an integer from 0 to {zmax}, got {configured!r}"
|
|
)
|
|
if configured > native_level:
|
|
raise SystemExit(
|
|
f"[{m['id']}] minZoom {configured} is above its native tile level "
|
|
f"{native_level}; lower minZoom or increase the map's source/placed resolution"
|
|
)
|
|
return configured
|
|
|
|
|
|
def load_source(cfg: Config, m: dict) -> tuple[Image.Image, tuple[float, float, float, float]]:
|
|
"""Return (image, world rect x0,y0,x1,y1) for a map or the base layer."""
|
|
if m["id"] == WORLD_ID:
|
|
img = Image.open(cfg.base_image_path()).convert("RGB")
|
|
cfg.set_base_size(img.size)
|
|
if cfg.rotate:
|
|
img = img.rotate(cfg.rotate, expand=True, resample=Image.BICUBIC)
|
|
ww, wh = cfg.world_size()
|
|
return img, (0.0, 0.0, float(ww), float(wh))
|
|
|
|
src = BUILD / m["id"] / "base.png"
|
|
if not src.exists():
|
|
raise SystemExit(f"[{m['id']}] {src.relative_to(ROOT)} missing -- run export_base.py")
|
|
img = Image.open(src).convert("RGBA")
|
|
if m.get("crop"):
|
|
img = img.crop(tuple(m["crop"]))
|
|
|
|
pl = cfg.placement(m)
|
|
tw = pl["width"]
|
|
th = pl["height"] if pl["height"] is not None else tw * img.size[1] / img.size[0]
|
|
return img, (pl["cx"] - tw / 2, pl["cy"] - th / 2, pl["cx"] + tw / 2, pl["cy"] + th / 2)
|
|
|
|
|
|
def render_trimmed_copy(m: dict, img: Image.Image) -> Image.Image | None:
|
|
"""Bake the saved playable polygon into a separate RGBA source image.
|
|
|
|
``base.png`` is deliberately never written. The derived image uses the
|
|
configured outside transparency as real per-pixel alpha, so the normal
|
|
viewer no longer needs a moving CSS clip-path mask.
|
|
"""
|
|
trim = m.get("trim")
|
|
points = trim.get("points", []) if isinstance(trim, dict) else []
|
|
if len(points) < 3:
|
|
return None
|
|
|
|
rgba = img.convert("RGBA")
|
|
width, height = rgba.size
|
|
outside_alpha = round(255 * (1 - float(trim.get("outsideTransparency", 0.75))))
|
|
mask = Image.new("L", rgba.size, outside_alpha)
|
|
polygon = [
|
|
(round(float(x) * (width - 1)), round(float(y) * (height - 1)))
|
|
for x, y in points
|
|
]
|
|
ImageDraw.Draw(mask).polygon(polygon, fill=255)
|
|
rgba.putalpha(ImageChops.multiply(rgba.getchannel("A"), mask))
|
|
|
|
destination = BUILD / m["id"] / "trimmed.png"
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
temporary = destination.with_name(f"{destination.stem}.tmp{destination.suffix}")
|
|
rgba.save(temporary, format="PNG", compress_level=1)
|
|
temporary.replace(destination)
|
|
return rgba
|
|
|
|
|
|
def write_pyramid(
|
|
img: Image.Image,
|
|
out,
|
|
ts: int,
|
|
zmax: int,
|
|
min_zoom: int,
|
|
native_level: int,
|
|
tw: float,
|
|
th: float,
|
|
pad_x: float,
|
|
pad_y: float,
|
|
) -> tuple[int, int, float]:
|
|
"""Write one tile pyramid and return (written, skipped, megabytes)."""
|
|
if out.exists():
|
|
shutil.rmtree(out)
|
|
|
|
written = skipped = 0
|
|
for z in range(min_zoom, native_level + 1):
|
|
s = 2.0 ** (z - zmax)
|
|
cw, ch = max(1, round(tw * s)), max(1, round(th * s))
|
|
level = img.resize((cw, ch), Image.LANCZOS)
|
|
px, py = pad_x * s, pad_y * s
|
|
|
|
tx0, tx1 = math.floor(px / ts), math.ceil((px + cw) / ts)
|
|
ty0, ty1 = math.floor(py / ts), math.ceil((py + ch) / ts)
|
|
for ty in range(ty0, ty1):
|
|
for tx in range(tx0, tx1):
|
|
tile = Image.new("RGBA", (ts, ts), (0, 0, 0, 0))
|
|
tile.paste(level, (round(px - tx * ts), round(py - ty * ts)))
|
|
if not tile.getbbox():
|
|
skipped += 1
|
|
continue
|
|
dst = out / str(z) / str(tx)
|
|
dst.mkdir(parents=True, exist_ok=True)
|
|
# Fully-opaque interior tiles don't need an alpha channel.
|
|
flat = tile.convert("RGB") if tile.getchannel("A").getextrema()[0] == 255 else tile
|
|
flat.save(dst / f"{ty}.webp", **WEBP)
|
|
written += 1
|
|
|
|
size_mb = sum(f.stat().st_size for f in out.rglob("*.webp")) / 1e6 if out.exists() else 0
|
|
return written, skipped, size_mb
|
|
|
|
|
|
def tile_map(cfg: Config, m: dict, trim_only: bool = False) -> dict:
|
|
img, (x0, y0, x1, y1) = load_source(cfg, m)
|
|
tw, th = x1 - x0, y1 - y0
|
|
ts, zmax, cell = cfg.tile_size, cfg.max_zoom, cfg.cell_size
|
|
|
|
# Deepest level worth generating. Plain floor() is too strict: Customs
|
|
# lands at 7.88, and rounding down to 7 would render its 7832 px source at
|
|
# 4240 px, throwing away half the detail. Allowing a quarter-level of slack
|
|
# tolerates up to a 1.19x upscale, which is invisible, to keep that detail.
|
|
native = zmax + math.log2(img.size[0] / tw) if tw > 0 else zmax
|
|
native_level = max(0, min(zmax, math.floor(native + 0.25)))
|
|
|
|
# Main maps are visible throughout the overview. Nested detail views can
|
|
# opt into a later reveal with maps.json minZoom.
|
|
min_zoom = minimum_zoom(m, zmax, native_level)
|
|
|
|
gx, gy = math.floor(x0 / cell), math.floor(y0 / cell)
|
|
pad_x, pad_y = x0 - gx * cell, y0 - gy * cell
|
|
|
|
original_out = TILES / m["id"]
|
|
if trim_only and original_out.exists():
|
|
written = sum(1 for _ in original_out.rglob("*.webp"))
|
|
skipped = 0
|
|
size_mb = sum(f.stat().st_size for f in original_out.rglob("*.webp")) / 1e6
|
|
print(f"[{m['id']:<17}] keeping {written} original tiles unchanged ({size_mb:.1f} MB)")
|
|
else:
|
|
written, skipped, size_mb = write_pyramid(
|
|
img, original_out, ts, zmax, min_zoom, native_level, tw, th, pad_x, pad_y,
|
|
)
|
|
print(f"[{m['id']:<17}] src {img.size[0]}x{img.size[1]} -> world {round(tw)}x{round(th)} "
|
|
f"@({round(x0)},{round(y0)}) z{min_zoom}-{native_level} "
|
|
f"{written} tiles ({skipped} empty), {size_mb:.1f} MB")
|
|
|
|
# Tile URLs are stable across rebuilds but their *contents* are not: move a
|
|
# map's `place` and tiles/<id>/6/17/33.webp is suddenly different imagery.
|
|
# Since tiles are served immutable for a week, a browser that saw the old
|
|
# build would blend it with the new one. This version stamp goes into the
|
|
# URL so a rebuilt map simply gets fresh URLs.
|
|
stamp = f"{x0:.1f},{y0:.1f},{tw:.1f},{th:.1f},{min_zoom},{native_level},{written}"
|
|
if m["id"] != WORLD_ID:
|
|
st = (BUILD / m["id"] / "base.png").stat()
|
|
stamp += f",{int(st.st_mtime)},{st.st_size}"
|
|
else:
|
|
st = cfg.base_image_path().stat()
|
|
stamp += f",{int(st.st_mtime)},{st.st_size},{cfg.rotate},{cfg.overall_scale}"
|
|
|
|
trimmed_version = None
|
|
trimmed = render_trimmed_copy(m, img) if m["id"] != WORLD_ID else None
|
|
if trimmed is not None:
|
|
trim_written, trim_skipped, trim_mb = write_pyramid(
|
|
trimmed, TRIMMED_TILES / m["id"], ts, zmax, min_zoom, native_level,
|
|
tw, th, pad_x, pad_y,
|
|
)
|
|
trim_stamp = stamp + "," + json.dumps(m["trim"], sort_keys=True, separators=(",", ":"))
|
|
trimmed_version = hashlib.sha1(trim_stamp.encode()).hexdigest()[:8]
|
|
print(f"[{m['id']:<17}] permanent trim: {trim_written} tiles "
|
|
f"({trim_skipped} empty), {trim_mb:.1f} MB")
|
|
|
|
return {
|
|
"id": m["id"],
|
|
"name": m["name"],
|
|
"parent": m.get("parent"),
|
|
"cell": [gx, gy],
|
|
"origin": [round(x0), round(y0)],
|
|
"size": [round(tw), round(th)],
|
|
"minZoom": min_zoom,
|
|
"maxNativeZoom": native_level,
|
|
"base": m["id"] == WORLD_ID,
|
|
"version": hashlib.sha1(stamp.encode()).hexdigest()[:8],
|
|
"trimmedVersion": trimmed_version,
|
|
"pxPerMeter": m.get("pxPerMeter"),
|
|
"trim": m.get("trim"),
|
|
}
|
|
|
|
|
|
def world_entry(cfg: Config) -> dict:
|
|
return {"id": WORLD_ID, "name": "Tarkov", "place": None, **cfg.world}
|
|
|
|
|
|
def main(argv: list[str]) -> list[dict]:
|
|
cfg = load_config()
|
|
if argv:
|
|
targets = [world_entry(cfg) if i == WORLD_ID else find_map(cfg, i) for i in argv]
|
|
else:
|
|
targets = [world_entry(cfg)] + cfg.maps
|
|
return [tile_map(cfg, m) for m in targets]
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(sys.argv[1:])
|