"""Shared helpers: config loading and the world-grid maths. The whole project rests on one idea: every map is tiled independently, but all maps share a single world coordinate space so they can sit side by side on one big canvas. That works because placements are snapped to a grid of `cellSize` world pixels, where cellSize = tileSize * 2 ** maxZoom At that cell size, a map parked in grid cell (gx, gy) has a tile-index offset of exactly `gx * 2**z` / `gy * 2**z` at every zoom level z -- always a whole number. So a map's own tile pyramid, numbered from its own top-left corner, drops into the world grid with no resampling and no re-tiling of its neighbours. Adding a map therefore never touches the tiles of any other map. """ from __future__ import annotations import json from pathlib import Path ROOT = Path(__file__).resolve().parent.parent CONFIG = ROOT / "maps.json" BUILD = ROOT / "build" TILES = ROOT / "web" / "tiles" DATA = ROOT / "web" / "data" class Config: def __init__(self, raw: dict): self.tile_size: int = raw.get("tileSize", 256) self.max_zoom: int = raw.get("maxZoom", 5) self.grid_cols: int = raw.get("gridCols", 4) self.attribution: str = raw.get("attribution", "") self.maps: list[dict] = raw["maps"] @property def cell_size(self) -> int: """World pixels per grid cell. Also the largest map we can hold.""" return self.tile_size * 2**self.max_zoom def assign_cells(self) -> None: """Fill in any missing `cell` by walking the grid left-to-right.""" taken = {tuple(m["cell"]) for m in self.maps if m.get("cell")} cursor = 0 for m in self.maps: if m.get("cell"): continue while (cursor % self.grid_cols, cursor // self.grid_cols) in taken: cursor += 1 cell = (cursor % self.grid_cols, cursor // self.grid_cols) m["cell"] = list(cell) taken.add(cell) def origin(self, m: dict) -> tuple[int, int]: gx, gy = m["cell"] return gx * self.cell_size, gy * self.cell_size def load_config() -> Config: cfg = Config(json.loads(CONFIG.read_text(encoding="utf-8"))) cfg.assign_cells() return cfg 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")