"""Rasterize palette-key sprite grids to cached pygame Surfaces (plan.md Rendering). `get(name, frame, tile)` builds a Surface once (keyed by name+frame+tile) and caches it. The renderer blits the cached surface directly. Pixel-art is kept crisp with nearest-neighbour `transform.scale` (never smoothscale). """ from __future__ import annotations try: import pygame except Exception: # pragma: no cover pygame = None # type: ignore from data import sprites as S from data.constants import PALETTE, TILE as _TILE _cache: dict = {} def get(name: str, frame: int = 0, tile: int = _TILE): """Return the cached Surface for `name` scaled to `tile`x`tile`.""" if pygame is None: return None key = (name, frame, tile) cached = _cache.get(key) if cached is not None: return cached grid = S.grid(name, frame) h = len(grid) w = max(len(r) for r in grid) if grid else 1 w = max(1, w) cell = 3 # fixed >=2 internal px/cell; crisp nearest-scale to any tile size surf = pygame.Surface((w * cell, h * cell), pygame.SRCALPHA) for y, row in enumerate(grid): for x, ch in enumerate(row): col = PALETTE.get(ch) if col is not None: pygame.draw.rect(surf, col, (x * cell, y * cell, cell, cell)) if (w * cell, h * cell) != (tile, tile): surf = pygame.transform.scale(surf, (tile, tile)) _cache[key] = surf return surf def frame_count(name: str) -> int: return S.frames_count(name) def warm(tile: int = _TILE) -> None: """Pre-rasterize every sprite frame so the first frame is hitch-free.""" if pygame is None: return for name in S.NAMES: for f in range(S.frames_count(name)): get(name, f, tile)