# SPDX-License-Identifier: MIT """BlastEm's 15 output levels, measured from its own pictures (a closed box). ``scripts/compare_frames.py`` maps BlastEm's 0-255 channel levels to the steps of the VDP's 15-step ramp. Until 2026-11-19 it carried those levels as a table taken from BlastEm's source, which is GPL-3.0 and may not be copied into this repository (docs/provenance.md). They are measured here instead: a cartridge built here draws the eight grey levels three ways, normal (high-priority plane), shadow (low-priority plane in shadow/highlight mode) and highlight (palette 3 colour 14 sprites over the normal bars), BlastEm's libretro core (``validation/build_blastem_libretro.sh``) runs it, and the level of each bar is read off its frame. Normal grey c is step 2c, shadow c is step c and highlight c is step 7 + c, so the 24 bars name all 15 steps (some twice, which is checked). The result is cached in ``reference/blastem-levels.json`` (not committed). ``OBSERVED``: BlastEm @ 542164d, run, never read. python scripts/blastem_levels.py [--core reference/build-blastem-libretro/blastem_libretro.so] """ from __future__ import annotations import argparse import json import sys import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path[:0] = [str(ROOT / "src"), str(ROOT / "scripts")] from run_plane_sizes import _vram_command, _w # noqa: E402 CORE = ROOT / "reference/build-blastem-libretro/blastem_libretro.so" CACHE = ROOT / "reference/blastem-levels.json" FRAME = 10 TOP_BORDER = 8 # BlastEm's frame: board row y is its row y + 8 (compare_frames.py) BANDS = (("normal", 0, lambda c: 2 * c), ("shadow", 64, lambda c: c), ("highlight", 128, lambda c: 7 + c)) # fmt: skip def vram() -> bytes: data = bytearray(0x10000) for c in range(8): # tiles 1-8: solid CRAM colour c + 1 data[32 * (c + 1) : 32 * (c + 2)] = bytes([(c + 1) * 0x11]) * 32 for t in range(9, 25): # tiles 9-24: solid colour 14, a 4x4-cell sprite's sixteen data[32 * t : 32 * (t + 1)] = b"\xee" * 32 for row in range(32): # plane A at $C000, 64 cells wide for x in range(40): entry = 1 + x // 5 if not 8 <= row < 16: entry |= 0x8000 # high priority: shown as is (and highlighted by sprites) data[0xC000 + 128 * row + 2 * x : 0xC002 + 128 * row + 2 * x] = entry.to_bytes(2, "big") for n in range(20): # sprites at $F000: 10 across, 2 down, 32x32 each, over rows 128-191 r, c = divmod(n, 10) link = n + 1 if n < 19 else 0 # high priority, palette 3, tile 9: colour 14 is the highlight operator words = (128 + 128 + 32 * r, 0x0F00 | link, 0x8000 | 0x6000 | 9, 128 + 32 * c) data[0xF000 + 8 * n : 0xF008 + 8 * n] = b"".join(w.to_bytes(2, "big") for w in words) return bytes(data) def cartridge() -> bytes: code = bytearray() code += _w(0x46FC, 0x2700) # move.w #$2700,sr # No TMSS write: the core's default console has none, and stops on the unmapped write. code += _w(0x41F9, 0x00C0, 0x0000) # lea $C00000,a0 (data) code += _w(0x43F9, 0x00C0, 0x0004) # lea $C00004,a1 (control) for reg, value in ((0x00, 0x04), (0x01, 0x04), (0x02, 0x30), (0x03, 0x00), (0x04, 0x07), (0x05, 0x78), (0x07, 0x00), (0x0A, 0xFF), (0x0B, 0x00), (0x0C, 0x89), (0x0D, 0x3F), (0x0F, 0x02), (0x10, 0x01), (0x11, 0x00), (0x12, 0x00)): # fmt: skip code += _w(0x32BC, 0x8000 | reg << 8 | value) # move.w #$8rvv,(a1) code += _w(0x47F9, 0x0001, 0x0000) # lea $10000,a3: the data code += _w(0x22BC, *_vram_command(0)) # VRAM write 0 code += _w(0x303C, 0x7FFF) # move.w #$7FFF,d0 code += _w(0x309B, 0x51C8, 0xFFFC) # copy: move.w (a3)+,(a0); dbra d0,copy code += _w(0x22BC, 0xC000, 0x0000) # CRAM write 0 code += _w(0x303C, 0x003F) # move.w #63,d0 code += _w(0x309B, 0x51C8, 0xFFFC) code += _w(0x22BC, 0x4000, 0x0010) # VSRAM write 0: both planes 0 code += _w(0x30BC, 0x0000, 0x30BC, 0x0000) code += _w(0x32BC, 0x8144) # display on, V28 code += _w(0x60FE) # bra.s * rom = bytearray(0x40000) rom[0:4] = (0x00FFFE00).to_bytes(4, "big") rom[4:8] = (0x00000200).to_bytes(4, "big") for vector in range(2, 64): rom[vector * 4 : vector * 4 + 4] = (0x000001F0).to_bytes(4, "big") rom[0x1F0:0x1F4] = bytes.fromhex("4e722700") # stop #$2700 rom[0x100:0x110] = b"SEGA GENESIS " rom[0x200 : 0x200 + len(code)] = code rom[0x10000:0x20000] = vram() cram = [0] * 64 for c in range(8): cram[c + 1] = c << 1 | c << 5 | c << 9 # grey c rom[0x20000:0x20080] = b"".join(w.to_bytes(2, "big") for w in cram) return bytes(rom) def measure(core: Path = CORE) -> list[int]: """The 15 levels, darkest first.""" import blastem_frames from megadrive_python.png import read_png with tempfile.TemporaryDirectory() as tmp: work = Path(tmp) rom = work / "levels.bin" rom.write_bytes(cartridge()) blastem_frames.run(core, rom, work / "out", {FRAME}, False, work) picture = read_png(work / "out" / f"f{FRAME:05d}.png") levels: dict[int, set[int]] = {} for _, top, step in BANDS: row = picture[TOP_BORDER + top + 32] for c in range(8): pixel = row[40 * c + 20] r, g, b = pixel >> 16 & 255, pixel >> 8 & 255, pixel & 255 if not r == g == b: raise RuntimeError(f"bar {c} is not grey: {pixel:06X}") levels.setdefault(step(c), set()).add(r) if sorted(levels) != list(range(15)) or any(len(v) != 1 for v in levels.values()): raise RuntimeError(f"levels not one per step: {levels}") return [next(iter(levels[s])) for s in range(15)] def levels(core: Path = CORE) -> list[int]: """The cached measurement, made if missing.""" if CACHE.exists(): return json.loads(CACHE.read_text())["levels"] found = measure(core) CACHE.write_text(json.dumps({"levels": found, "blastem": "542164d", "frame": FRAME})) return found def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--core", type=Path, default=CORE) args = parser.parse_args() found = measure(args.core) CACHE.write_text(json.dumps({"levels": found, "blastem": "542164d", "frame": FRAME})) print("BlastEm's levels by ramp step:", " ".join(str(v) for v in found)) return 0 if __name__ == "__main__": raise SystemExit(main())