"""Set the Rust emulator's frames against BlastEm's: the second opinion on the picture. megadrive-rust-fast and megadrive-python share one renderer model and agree with the encoder's prediction byte for byte, so a frame they both show proves nothing about an emulator built independently. BlastEm is that independent detector (megadrive-python docs/validation.md); its libretro core is driven by megadrive-python's scripts/blastem_frames.py under WSL. This compares the two pictures the way megadrive-python's scripts/compare_frames.py does, but reads the PNGs with Pillow (that script's own reader returns nothing for md-run's files): - BlastEm keeps an 8-line top border, so board row y is BlastEm row y + 8; - the two DACs' output levels differ, so each channel is mapped to its step on the 15-step ramp and a pixel is the same only when all three steps agree; - frame numbers are not a shared clock between emulators, so each board frame is scored against the best of BlastEm's frames N-W..N+W. md-run ROM --machine megadrive2 --frames 10565 --png-dir out/X/rust_frames --png-range 1:10565:200 wsl ~/venv/bin/python scripts/blastem_frames.py CORE ROM out/X/blastem_frames --frames python tools/blastem_compare.py out/X/rust_frames out/X/blastem_frames """ from __future__ import annotations import argparse import re import sys from pathlib import Path import numpy as np from PIL import Image ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from rrmd.vdp import RAMP # noqa: E402 #: BlastEm's output levels for the 15 ramp steps (vdp.c, levels[]). BLASTEM_LEVELS = (0, 27, 49, 71, 87, 103, 119, 130, 146, 157, 174, 190, 206, 228, 255) TOP_BORDER = 8 def step_table(levels: tuple[int, ...]) -> np.ndarray: """256-entry lookup: output level -> ramp step, -1 where no step has that level.""" t = np.full(256, -1, dtype=np.int16) for i, v in enumerate(levels): t[v] = i return t BOARD_T, BLASTEM_T = step_table(RAMP), step_table(BLASTEM_LEVELS) def load_steps(path: Path, table: np.ndarray) -> np.ndarray: return table[np.asarray(Image.open(path).convert("RGB"))] def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("board", type=Path, help="md-run --png-dir output (fNNNNN.png, 320x224)") ap.add_argument("blastem", type=Path, help="blastem_frames.py output (fNNNNN.png, 320x240)") ap.add_argument("--window", type=int, default=6) args = ap.parse_args(argv) have = {int(re.match(r"f(\d+)", p.stem).group(1)): p for p in args.blastem.glob("f*.png")} exact = total = 0 worst = (1.0, None, None) offsets: dict[int, int] = {} for p in sorted(args.board.glob("f*.png")): n = int(re.match(r"f(\d+)", p.stem).group(1)) try: ours = load_steps(p, BOARD_T) except Exception as e: # noqa: BLE001 - an unreadable dump is reported, not fatal print(f"f{n:05d}: unreadable board frame ({e})") continue best = (-1.0, None) for d in range(-args.window, args.window + 1): q = have.get(n + d) if q is None: continue theirs = load_steps(q, BLASTEM_T)[TOP_BORDER : TOP_BORDER + ours.shape[0]] rows = min(ours.shape[0], theirs.shape[0]) same = float(np.mean(np.all(ours[:rows] == theirs[:rows], axis=-1))) if same > best[0]: best = (same, d) if best[1] is None: print(f"f{n:05d}: no BlastEm frame within +-{args.window}") continue total += 1 exact += best[0] == 1.0 offsets[best[1]] = offsets.get(best[1], 0) + 1 if best[0] < worst[0]: worst = (best[0], n, best[1]) if best[0] < 1.0: print(f"f{n:05d}: {100 * best[0]:6.2f} % of pixels on the same ramp step, at BlastEm offset {best[1]:+d}") print(f"{exact} of {total} board frames have a pixel-identical BlastEm frame; offsets {dict(sorted(offsets.items()))}") if worst[1] is not None: print(f"worst: f{worst[1]:05d} at {100 * worst[0]:.2f} % (offset {worst[2]:+d})") return 0 if exact == total else 1 if __name__ == "__main__": raise SystemExit(main())