Files

138 lines
4.7 KiB
Python

"""Shared helpers: config loading and world placement maths.
Every map is tiled independently but they all share one world coordinate
space, so unrelated maps sit on a single pannable canvas.
The base of that canvas is `overall.jpeg`, rotated to put north at the top.
World pixels are overall-map pixels multiplied by `overallScale`, chosen so the
densest detail map lands at roughly its native resolution.
Alignment relies on one property: a map's tile-index offset must be a whole
number of tiles at every zoom level. That holds when a map's pyramid origin is
a multiple of
cellSize = tileSize * 2 ** maxZoom
which is far too coarse to position a map with. So instead of *moving* a map to
the grid, we pad it: the raster is padded up-and-left to the nearest cell
boundary, and `tile.py` only visits tiles that actually contain content. The
map lands exactly where it should, the grid stays integral, and the padding
costs nothing.
"""
from __future__ import annotations
import json
import math
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CONFIG = ROOT / "maps.json"
BUILD = ROOT / "build"
TILES = ROOT / "web" / "tiles"
TRIMMED_TILES = ROOT / "web" / "tiles-trimmed"
DATA = ROOT / "web" / "data"
WORLD_ID = "overall"
def rotate_point(x: float, y: float, w: int, h: int, deg: float) -> tuple[float, float]:
"""Where (x, y) ends up after PIL's rotate(deg, expand=True) on a w x h image."""
th = math.radians(deg)
c, s = math.cos(th), math.sin(th)
w2 = w * abs(c) + h * abs(s)
h2 = w * abs(s) + h * abs(c)
dx, dy = x - w / 2.0, y - h / 2.0
return (dx * c + dy * s) + w2 / 2.0, (-dx * s + dy * c) + h2 / 2.0
def unrotate_point(rx: float, ry: float, w: int, h: int, deg: float) -> tuple[float, float]:
"""Inverse of rotate_point: rotated-frame coords back to source coords."""
th = math.radians(deg)
c, s = math.cos(th), math.sin(th)
w2 = w * abs(c) + h * abs(s)
h2 = w * abs(s) + h * abs(c)
u, v = rx - w2 / 2.0, ry - h2 / 2.0
return (u * c - v * s) + w / 2.0, (u * s + v * c) + h / 2.0
def rotated_size(w: int, h: int, deg: float) -> tuple[int, int]:
th = math.radians(deg)
c, s = abs(math.cos(th)), abs(math.sin(th))
return round(w * c + h * s), round(w * s + h * c)
class Config:
def __init__(self, raw: dict):
self.tile_size: int = raw.get("tileSize", 256)
self.max_zoom: int = raw.get("maxZoom", 8)
self.underlay_zoom: int = raw.get("underlayZoom", 2)
self.attribution: str = raw.get("attribution", "")
self.world: dict = raw.get("world", {})
self.maps: list[dict] = raw["maps"]
self._base_size: tuple[int, int] | None = None
# --- world geometry ------------------------------------------------
@property
def cell_size(self) -> int:
return self.tile_size * 2**self.max_zoom
@property
def rotate(self) -> float:
return float(self.world.get("rotate", 0))
@property
def overall_scale(self) -> float:
return float(self.world.get("overallScale", 1))
def base_image_path(self) -> Path:
return ROOT / self.world["image"]
def set_base_size(self, size: tuple[int, int]) -> None:
"""Original (unrotated) overall.jpeg size, needed for placement."""
self._base_size = size
def base_size(self) -> tuple[int, int]:
if self._base_size is None:
from PIL import Image
with Image.open(self.base_image_path()) as im:
self._base_size = im.size
return self._base_size
def world_size(self) -> tuple[int, int]:
w, h = rotated_size(*self.base_size(), self.rotate)
s = self.overall_scale
return round(w * s), round(h * s)
def placement(self, m: dict) -> dict:
"""Target rect of a map in world pixels.
`place` is in ROTATED overall-map pixels -- i.e. the north-up image you
actually look at when picking positions (tools/place_preview.py renders
it with a grid). Authoring against the unrotated source is far harder
to eyeball, so the rotation is already baked in here.
"""
p = m["place"]
s = self.overall_scale
return {
"cx": p["cx"] * s,
"cy": p["cy"] * s,
"width": p["w"] * s,
"height": p["h"] * s if p.get("h") is not None else None,
}
def rotated_base_size(self) -> tuple[int, int]:
return rotated_size(*self.base_size(), self.rotate)
def load_config() -> Config:
return Config(json.loads(CONFIG.read_text(encoding="utf-8")))
def find_map(cfg: Config, map_id: str) -> dict:
for m in cfg.maps:
if m["id"] == map_id:
return m
raise SystemExit(f"no map with id {map_id!r} in maps.json")