"""Mega Drive VDP facts the encoder and the predictor share. Everything here mirrors ``megadrive_python.render`` (RAMP/LEVELS) and the VDP's data formats; keep in sync with the emulator if those change. """ from __future__ import annotations import numpy as np TILE = 8 WIDTH, HEIGHT = 320, 224 # H40 V28 (decision D1) CELLS_X, CELLS_Y = WIDTH // TILE, HEIGHT // TILE # 40 x 28 = 1120 cells PLANE_W = 64 # name-table width in cells (register 16 = 01) #: Measured DAC output levels (Plutiedev, as pinned in render.py). RAMP = (0, 29, 52, 70, 87, 101, 116, 130, 144, 158, 172, 187, 206, 228, 255) LEVELS = ( np.array(RAMP[0:15:2], dtype=np.int32), # normal np.array(RAMP[0:8], dtype=np.int32), # shadow np.array(RAMP[7:15], dtype=np.int32), # highlight ) NORMAL, SHADOW, HIGHLIGHT = 0, 1, 2 def cram_word(r: int, g: int, b: int) -> int: """A CRAM entry from raw 0-7 channel values: ----BBB-GGG-RRR-.""" return (b << 9) | (g << 5) | (r << 1) def raw_to_rgb(raw: np.ndarray, shade: int) -> np.ndarray: """(..., 3) raw 0-7 channel values -> (..., 3) RGB888 through one shade's ramp.""" return LEVELS[shade][raw.astype(np.int64)] def rgb_to_raw(rgb: np.ndarray) -> np.ndarray: """Nearest raw 0-7 per channel on the *normal* ramp (what CRAM stores).""" levels = LEVELS[NORMAL] return np.argmin(np.abs(rgb[..., None].astype(np.int32) - levels[None, :]), axis=-1).astype(np.uint8) def name_word(tile: int, palette: int, priority: bool, hflip: bool, vflip: bool) -> int: return ( (0x8000 if priority else 0) | (palette << 13) | (0x1000 if vflip else 0) | (0x0800 if hflip else 0) | (tile & 0x7FF) ) def tile_bytes(indices: np.ndarray) -> bytes: """An 8x8 array of 0-15 pen indices -> the VDP's 32-byte 4bpp pattern (row-major, two pixels per byte, high nibble first).""" hi = indices[:, 0::2].astype(np.uint8) << 4 lo = indices[:, 1::2].astype(np.uint8) return (hi | lo).tobytes()