#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The lockstep gate's reference side: a5200-python, traced slice by slice. Run on the reference's interpreter (a5200-python's .venv-pypy, which holds 6502-python 741419a and pokey-python 6ed1ffa), with the reference's ``src`` taken from the clone at ``external/a5200-python`` (checked out at cf82d44; ``--reference-src`` to move it). A slice is one frame: ``Console.run_frames(1)``. The inputs follow ``scripts/scripted_run.py`` in the reference exactly (frames counted from 1: slice i is frame i + 1). Each line holds the CPU's registers, board time and frame count, ANTIC's position, the board's counters, a CRC-32 of every bus cycle of the slice (packed little-endian u64 ``cycle << 27 | kind << 24 | address << 8 | value``; kind 0 CPU read, 1 CPU write, 2 ANTIC DMA, 3 WSYNC-repeated read, 4 refresh with address 0) and a CRC-32 of the frame buffer. ``target/release/a5200-trace`` writes the same lines; ``scripts/lockstep.py`` compares them. a5200_trace.py ROM --slices N [--machine KEY] [--mapping M] [--plug N] [--press FRAME:KEY:FRAMES[:PORT]]... [--stick FRAME:X:Y[:PORT]]... [--trak FRAME:VX:VY[:PORT]]... [--audio] [--detail SLICE] --out FILE ``--audio``: a ``media.AudioTap`` is attached; each line ends with ``snd=CRC/COUNT`` of the slice's samples. ``--detail SLICE``: also every bus cycle of that slice, one per line. ``--save-at`` and ``--save-mid`` are accepted and ignored (the Rust board's save-state round trips, at a frame boundary and inside a frame). ``--bios FILE`` gives the BIOS image instead of finding it (``Console(..., bios=...)``) and ``--ram ADDR:FILE`` (hex address, repeatable) writes a file into RAM after the console is built: the synthetic case of the reference's tests/test_state.py (``scripts/busy_case.py``). """ from __future__ import annotations import argparse import subprocess import sys import zlib from array import array from pathlib import Path PIN = "cf82d44" def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("rom", type=Path) parser.add_argument("--slices", type=int, required=True) parser.add_argument("--machine", default="a5200") parser.add_argument("--mapping") parser.add_argument("--plug", type=int, default=2) parser.add_argument("--press", action="append", default=[]) parser.add_argument("--stick", action="append", default=[]) parser.add_argument("--trak", action="append", default=[]) parser.add_argument("--audio", action="store_true") parser.add_argument("--detail", type=int, default=-1) parser.add_argument("--save-at", type=int, default=-1, help="ignored: the Rust board's round trip") parser.add_argument("--save-mid", action="append", default=[], help="ignored: the Rust board's mid-frame round trip") parser.add_argument("--bios", type=Path) parser.add_argument("--ram", action="append", default=[]) parser.add_argument("--reference-src", type=Path, default=Path(__file__).resolve().parents[1] / "external" / "a5200-python") parser.add_argument("--out", type=Path, required=True) args = parser.parse_args() head = subprocess.run(["git", "-C", str(args.reference_src), "rev-parse", "--short=7", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() dirty = subprocess.run(["git", "-C", str(args.reference_src), "status", "--porcelain", "src"], capture_output=True, text=True, check=True).stdout.strip() if head != PIN or dirty: raise SystemExit(f"the reference clone is at {head}{' (dirty)' if dirty else ''}, not {PIN}") sys.path.insert(0, str(args.reference_src / "src")) import a5200_python # noqa: E402 if not a5200_python.__file__.startswith(str(args.reference_src)): raise SystemExit(f"a5200_python came from {a5200_python.__file__}") from a5200_python.cartridge import load_cartridge # noqa: E402 from a5200_python.media import AudioTap # noqa: E402 from a5200_python.system import Console # noqa: E402 presses = [] for item in args.press: frame, key, length, *port = item.split(":") presses.append((int(frame), key, int(length), int(port[0]) - 1 if port else 0)) cart = load_cartridge(args.rom, mapping=args.mapping) console = Console(cart, args.machine, bios=args.bios.read_bytes() if args.bios else None) board = console.board for item in args.ram: address, path = item.split(":", 1) data = Path(path).read_bytes() board.ram[int(address, 16) : int(address, 16) + len(data)] = data if args.audio: board.audio = AudioTap(board) log = array("Q") codes = {"R": 0, "W": 1, "D": 2, "S": 3} def observe(kind: str, address: int, value: int, cycle: int) -> None: code = codes[kind] if address < 0: code, address = 4, 0 log.append((cycle << 27) | (code << 24) | ((address & 0xFFFF) << 8) | value) board.bus_observers.append(observe) pads = console.controllers.pads for n in range(min(args.plug, len(pads))): pads[n].plugged = True cpu = board.cpu with args.out.open("w") as out: for index in range(args.slices): frame = index + 1 for port, pad in enumerate(pads): mine = [(f, k, n) for f, k, n, p in presses if p == port and f <= frame < f + n] pad.keys = {k for _, k, _ in mine if k not in ("trigger", "top")} pad.trigger = any(k == "trigger" for _, k, _ in mine) pad.top = any(k == "top" for _, k, _ in mine) for item in args.stick: f, x, y, *rest = item.split(":") port = int(rest[0]) - 1 if rest else 0 if int(f) == frame and port < len(pads): pads[port].x, pads[port].y = float(x), float(y) for item in args.trak: f, vx, vy, *rest = item.split(":") port = int(rest[0]) - 1 if rest else 0 if int(f) == frame and port < len(pads): pads[port].trakball = True pads[port].vx, pads[port].vy = float(vx), float(vy) console.run_frames(1) bus = zlib.crc32(log.tobytes()) if log else 0 pic = zlib.crc32(bytes(board.frame)) antic = board.antic out.write( f"{index} cyc={board.cycles} fr={board.frames} pc={cpu.pc:04x} a={cpu.a:02x} " f"x={cpu.x:02x} y={cpu.y:02x} s={cpu.s:02x} p={cpu.p:02x} jam={int(cpu.halted)} " f"v={antic.vcount} h={antic.hcount} halt={board.halted_cycles} " f"stall={board.stalled_cycles} lost={board.nmis_lost} db={board.data_bus:02x} " f"irq={int(board._irq_line)} bus={bus:08x}/{len(log)} pic={pic:08x}" ) if args.audio: samples = bytes(board.audio.samples) board.audio.samples.clear() out.write(f" snd={zlib.crc32(samples):08x}/{len(samples) // 2}") out.write("\n") if index == args.detail: for record in log: kind = "rwdsf"[(record >> 24) & 7] out.write(f" {record >> 27} {kind} {(record >> 8) & 0xFFFF:04x} {record & 0xFF:02x}\n") del log[:] return 0 if __name__ == "__main__": raise SystemExit(main())