# SPDX-License-Identifier: MIT """Milestone 3: compare the board's frame with Atari800's (a detector) at a named frame. Runs ``atari800_run.py`` (libatari800, GPL, run as an external library; the driver is a GPL tool kept outside this repository, found at $EMU_TOOLS_GPL2/tools/atari800/atari800_run.py) to frame N and saves its 384x240 screen of colour-register values; runs the board to the same frame; aligns the two (Atari800's screen is a window on the scan; the offset is searched once per run and printed) and counts the colour clocks that differ. Atari800 is tier 5: a difference is a question for [AHRM] and Acid5200, never a verdict. python scripts/compare_atari800.py CART --frame 600 [--png-dir DIR] The two half-clock pixels of a colour clock are compared separately (both sides store half-clock pixels). The temporary cartridge and BIOS copies that atari800_run.py writes under tests/detector_runs/atari800/ are removed after the run. """ from __future__ import annotations import argparse import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a5200_python.media import write_png # noqa: E402 from a5200_python.system import Console # noqa: E402 WIDTH, HEIGHT = 384, 240 WORK = ROOT / "tests" / "detector_runs" / "atari800" def atari800_run() -> tuple[list[str], dict[str, str]]: """The command and environment that run atari800_run.py, or exit saying how to find it. atari800_run.py declares libatari800's C API through ctypes, so it is a GPL tool, kept outside this repository since 2026-11-22 (docs/provenance.md). Parts of libatari800 are GPL-2.0-only, so since 2026-11-24 it lives in emu-tools-gpl2, at its fixed path $EMU_TOOLS_GPL2/tools/atari800/atari800_run.py (one variable per tool repository, emu-tools docs/contract.md section 5). It runs with this checkout as A5200_PYTHON_ROOT. Without it this exits with status 3 (a missing input). """ tools = os.environ.get("EMU_TOOLS_GPL2") tool = Path(tools or ".") / "tools" / "atari800" / "atari800_run.py" if not tools or not tool.exists(): print("atari800_run.py is a GPL-2.0-only tool kept outside this repository: set " "EMU_TOOLS_GPL2 (expects $EMU_TOOLS_GPL2/tools/atari800/atari800_run.py)", file=sys.stderr) # fmt: skip raise SystemExit(3) return [sys.executable, str(tool)], dict(os.environ, A5200_PYTHON_ROOT=str(ROOT)) def atari800_frame(cart: str, frames: int, cart_type: int | None) -> bytes: WORK.mkdir(parents=True, exist_ok=True) pgm = WORK / "compare.pgm" prefix, env = atari800_run() command = [ *prefix, cart, "--frames", str(frames), "--every", str(frames), "--pgm", str(pgm), ] if cart_type is not None: command += ["--cart-type", str(cart_type)] try: subprocess.run(command, check=True, capture_output=True, text=True, env=env) data = pgm.read_bytes() finally: for leftover in ("cart.a52", "bios-orig.rom", "bios-a.rom", "compare.pgm"): path = WORK / leftover if path.exists(): path.unlink() header_end = data.index(b"255\n") + 4 return data[header_end:] def best_alignment(ours: bytes, theirs: bytes) -> tuple[int, int, int]: """(x offset in half-clocks, y offset in lines, differing pixels) that fits best.""" best = None for dy in range(0, 262 - HEIGHT + 1): for dx in range(0, 456 - WIDTH + 1, 2): diff = 0 for y in range(0, HEIGHT, 8): # a sparse first pass row = (y + dy) * 456 + dx a = ours[row : row + WIDTH] b = theirs[y * WIDTH : (y + 1) * WIDTH] diff += sum(1 for p, q in zip(a, b) if p != q) if best is None or diff < best[2]: best = (dx, dy, diff) return best def compare(ours: bytes, theirs: bytes, dx: int, dy: int) -> tuple[int, list[int]]: total = 0 rows = [] for y in range(HEIGHT): row = (y + dy) * 456 + dx a = ours[row : row + WIDTH] b = theirs[y * WIDTH : (y + 1) * WIDTH] diff = sum(1 for p, q in zip(a, b) if p != q) total += diff if diff: rows.append(y + dy) return total, rows def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("cart") parser.add_argument("--frame", type=int, default=600) parser.add_argument("--cart-type", type=int) parser.add_argument("--png-dir", type=Path) args = parser.parse_args() theirs = atari800_frame(args.cart, args.frame, args.cart_type) console = Console(args.cart) console.run_frames(args.frame) ours = bytes(console.board.frame) dx, dy, _ = best_alignment(ours, theirs) total, rows = compare(ours, theirs, dx, dy) print(f"{Path(args.cart).name}: frame {args.frame}, offset x={dx // 2} cc y={dy} lines") print( f"differing half-clock pixels: {total} of {WIDTH * HEIGHT}; rows: " f"{rows[:12]}{' ...' if len(rows) > 12 else ''} ({len(rows)} rows)" ) if args.png_dir: args.png_dir.mkdir(parents=True, exist_ok=True) stem = Path(args.cart).stem.replace(" ", "_") write_png(args.png_dir / f"{stem}-{args.frame}-board.png", ours) padded = bytearray(456 * 262) for y in range(HEIGHT): row = (y + dy) * 456 + dx padded[row : row + WIDTH] = theirs[y * WIDTH : (y + 1) * WIDTH] write_png(args.png_dir / f"{stem}-{args.frame}-atari800.png", bytes(padded)) return 0 if __name__ == "__main__": raise SystemExit(main())