#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Lockstep rung 4's dot model against rung 3's line renderer, line by line. Rung 3's line renderer (gba_python.ppu.line) is the specification the dot model (gba_python.ppu.dots) must agree with whenever nothing changes while a line is drawn. The board runs with the dot model; at each visible line the line renderer also draws the line, from the registers and memories as they stand when the dot model takes the line's affine reference points (origin + REFERENCE_LATCH, before any dot is fetched). A line is **quiet** when no write that can change the picture (an LCD register, palette RAM, VRAM, OAM; by the CPU or DMA) landed from the previous line's origin (the OBJ fetch for this line runs during the previous line) to the end of this one. Every quiet line must be identical; lines that are not quiet are counted, not compared. A quiet line on which a window's vertical flag (rung 4, U-VID-8) differs from rung 3's per-line compare is counted apart: the two models differ there by design. python scripts/lockstep_pictures.py # rung 3's picture ROMs and scenes python scripts/lockstep_pictures.py ROM.gba ... --frames 300 --bios "$BIOS" """ from __future__ import annotations import argparse import json import os import sys import tempfile from concurrent.futures import ProcessPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) sys.path.insert(0, os.environ.get("GBA_PYTHON_SRC", str(ROOT / "src"))) from board_pictures import PICTURE_ROMS, SCENES from gba_python.board import GBA from gba_python.cartridge.rom import GamePakROM from gba_python.ppu.line import WIDTH, LineRenderer class Lockstep: def __init__(self) -> None: self.writes_at = {} # line -> the write counter at its origin self.previous_origin_writes = 0 self.expected: dict[int, list[int]] = {} self.window_differs: dict[int, bool] = {} self.quiet = self.noisy = self.window_lines = 0 self.mismatches: list[tuple[int, int, int]] = [] # (frame, line, dots) self.frame = 0 def line_origin(self, ppu, y: int) -> None: # The window opens at the previous line's origin. self.writes_at[y] = self.previous_origin_writes self.previous_origin_writes = ppu.dots.writes if y == 0: self.frame += 1 def line_start(self, ppu, y: int) -> None: line = [0] * WIDTH ppu.renderer.render(y, line) self.expected[y] = line dispcnt = ppu.display differs = False for win in (0, 1): if dispcnt & (0x2000 << win): top, bottom = LineRenderer.window_span(ppu.regs[0x22 + win], 160) if (top <= y < bottom) != ppu.dots.win_v[win]: differs = True self.window_differs[y] = differs def line_end(self, ppu, y: int, line: list[int]) -> None: expected = self.expected.pop(y, None) if expected is None: return if ppu.dots.writes != self.writes_at.get(y, -1): self.noisy += 1 return if self.window_differs.get(y): self.window_lines += 1 return self.quiet += 1 dots = sum(1 for a, b in zip(line, expected, strict=True) if a != b) if dots: self.mismatches.append((self.frame, y, dots)) def run_one(job) -> dict: name, rom, bios, frames = job board = GBA(GamePakROM.from_path(str(rom)), bios=bios) lock = Lockstep() board.ppu.lockstep = lock board.run_frames(frames) return { "name": name, "quiet": lock.quiet, "mismatched": len(lock.mismatches), "first": lock.mismatches[:5], "noisy": lock.noisy, "window_rule": lock.window_lines, } def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("roms", nargs="*") parser.add_argument("--bios", default="free") parser.add_argument("--frames", type=int, default=300) parser.add_argument("--scene-frames", type=int, default=120) parser.add_argument("--jobs", type=int, default=8) parser.add_argument("--json", type=Path) args = parser.parse_args() os.environ.setdefault("PYPY_GC_NURSERY", "1M") with tempfile.TemporaryDirectory() as scratch: import referee_run bios_args = referee_run.bios_args(args.bios, Path(scratch)) bios = bios_args[1] if bios_args else "free" if args.roms: jobs = [(Path(r).stem, Path(r), bios, args.frames) for r in args.roms] else: jobs = [(n, ROOT / p, bios, args.frames) for n, p in PICTURE_ROMS.items()] free = ( bios_args[1] if args.bios == "free" else referee_run.bios_args("free", Path(scratch))[1] ) jobs += [ (f"scene-{p.stem}", p, free, args.scene_frames) for p in sorted(SCENES.glob("*.gba")) ] with ProcessPoolExecutor(max_workers=args.jobs) as pool: results = list(pool.map(run_one, jobs)) total_quiet = total_bad = 0 for r in results: total_quiet += r["quiet"] total_bad += r["mismatched"] flag = "ok " if not r["mismatched"] else "BAD" print( f"{flag} {r['name']:36} quiet {r['quiet']:6} mismatched {r['mismatched']:4} " f"not quiet {r['noisy']:6} window rule {r['window_rule']:5} {r['first'][:2]}" ) print(f"{total_quiet - total_bad}/{total_quiet} quiet lines identical in {len(results)} runs") if args.json: args.json.write_text(json.dumps(results, indent=1) + "\n", encoding="utf-8") return 0 if total_bad == 0 else 1 if __name__ == "__main__": sys.exit(main())