#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The lockstep gate's reference side: a7800-python, traced slice by slice. Run on the reference's interpreter (a7800-python's ``.venv-pypy``, which holds 6502-python 828b619, a2600-python 4ad24f2 and pokey-python ea20096), with the reference's ``src`` taken from the clone at ``external/a7800-python`` (checked out at f70eeb2, d6b220d's board with its pins moved after 6502-python's history rewrite of 2026-11-21, the same code; ``--reference-src`` to move it). ``target/release/a7800-trace`` writes the same lines; ``scripts/lockstep.py`` compares them. **7800 mode** (the default): ``System.from_rom`` (BIOS or ``--start direct``); a slice is one MARIA frame (``System.run_frames(1)``), and the inputs of frame ``i + 1`` are applied before slice ``i``. Each line: board time (MARIA clocks, Φ2 periods, HALT and RDY periods, slow cycles), MARIA's frame, line and clock, the CPU's registers, INPTCTRL and the data bus, a CRC-32 of every bus cycle of the slice (packed little-endian u64 ``clock << 26 | kind << 24 | address << 8 | value``; kind 0 CPU read, 1 CPU write, 2 MARIA DMA read) and a CRC-32 of every line MARIA finished in it (all 454 clocks of each). **2600 mode** (``--mode 2600``): ``System2600.from_rom`` (``--start direct`` or ``bios``), unchanged: the reference's own constructor runs, and the 7800 ``System`` it builds is traced from the moment it exists (the module's ``System`` is wrapped, nothing else). Slice 0 is the whole 7800 side up to the hand-off (direct: nothing but the preset; BIOS: the boot); slice ``i >= 1`` is one a2600-python frame (``run_frames(1)``, VSYNC). The line's board time is the 2600 board's (cycles, halted cycles), its picture the TIA's lines; the 7800 side's line uses the 7800 board's. Inputs (frames counted from 1): ``--press FRAME:KEY:FRAMES[:PORT]`` with KEY one of up, down, left, right, b1 (left button), b2 (right button), b12 (both) on the ProLine of PORT (1 or 2), or reset, select, pause on SWCHB; ``--gun FRAME:LINE:CLOCK`` aims a light gun on port 1 from that frame (``--gun FRAME:off`` points it away), ``--pull FRAME:FRAMES`` holds its trigger; a gun is plugged in when either is given. ``--difficulty LR`` sets SWCHB D6/D7 (``a`` = high) at power. ``--audio``: a ``sound.SoundTap`` is attached; each line ends with ``snd=CRC/COUNT`` of the slice's mixed samples (little-endian doubles). ``--detail SLICE`` adds every bus cycle of that slice. ``--fault NAME`` adds a seeded fault to the board (``board.faults``). ``--save-at`` is accepted and ignored (the Rust board's save-state round trip). a7800_trace.py ROM --slices N [--machine ntsc|pal] [--start bios|direct] [--mode 7800|2600] [--as WORDS] [--press ...]... [--gun ...]... [--pull ...]... [--audio] [--detail SLICE] [--fault NAME]... --out FILE """ from __future__ import annotations import argparse import struct import subprocess import sys import zlib from array import array from pathlib import Path PIN = "f70eeb2" KINDS = {"R": 0, "W": 1, "D": 2} def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("rom", type=Path) parser.add_argument("--slices", type=int, required=True) parser.add_argument("--machine", choices=("ntsc", "pal"), default="ntsc") parser.add_argument("--start", choices=("bios", "direct"), default="bios") parser.add_argument("--mode", choices=("7800", "2600"), default="7800") parser.add_argument("--as", dest="override") parser.add_argument("--press", action="append", default=[]) parser.add_argument("--gun", action="append", default=[]) parser.add_argument("--pull", action="append", default=[]) parser.add_argument("--difficulty", default="") parser.add_argument("--audio", action="store_true") parser.add_argument("--detail", type=int, default=-1) parser.add_argument("--fault", action="append", default=[]) parser.add_argument("--save-at", type=int, default=-1, help="ignored: the Rust board's round trip") parser.add_argument("--reference-src", type=Path, default=Path(__file__).resolve().parents[1] / "external" / "a7800-python") parser.add_argument("--out", type=Path, required=True) args = parser.parse_args() git = ["git", "-C", str(args.reference_src)] head = subprocess.run([*git, "rev-parse", "--short=7", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() dirty = subprocess.run([*git, "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 a7800_python # noqa: E402 if not a7800_python.__file__.startswith(str(args.reference_src)): raise SystemExit(f"a7800_python came from {a7800_python.__file__}") from a7800_python import mode2600 # noqa: E402 from a7800_python.cartridge import formats # noqa: E402 from a7800_python.controllers import LightGun # noqa: E402 from a7800_python.machine import NTSC, PAL # noqa: E402 from a7800_python.sound import SoundTap # noqa: E402 from a7800_python.system import System # noqa: E402 machine = NTSC if args.machine == "ntsc" else PAL log = array("Q") lines = bytearray() state = {"tap": None, "gun": None, "system": None} def observe(kind: str, address: int, value: int, clock: int) -> None: log.append((clock << 26) | (KINDS[kind] << 24) | ((address & 0xFFFF) << 8) | value) def on_maria_line(line, pixels, kill) -> None: lines.extend(pixels) def on_tia_line(pixels) -> None: lines.extend(bytes(pixels)) def wire(system) -> None: """Attach the trace and the inputs to a 7800 System as soon as it exists.""" board = system.board board.bus_observers.append(observe) board.maria.on_line = on_maria_line board.faults.update(args.fault) if args.difficulty: for side, bit in zip(args.difficulty, (0x40, 0x80)): if side == "a": board.riot.input_b |= bit else: board.riot.input_b &= ~bit & 0xFF if args.gun or args.pull: state["gun"] = LightGun(board, 0) if args.audio: state["tap"] = SoundTap(board, keep_streams=False).attach() state["system"] = system 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)) aims = [] for item in args.gun: frame, *rest = item.split(":") aims.append((int(frame), None if rest == ["off"] else (int(rest[0]), int(rest[1])))) pulls = [tuple(int(v) for v in item.split(":")) for item in args.pull] def apply(frame: int) -> None: system = state["system"] board = system.board for port in (0, 1): held = {k for f, k, n, p in presses if p == port and f <= frame < f + n} system.controllers.set( port, up="up" in held, down="down" in held, left="left" in held, right="right" in held, left_button=bool(held & {"b1", "b12"}), right_button=bool(held & {"b2", "b12"}), ) # fmt: skip switches = {k for f, k, n, _ in presses if f <= frame < f + n} for key, bit in (("reset", 0x01), ("select", 0x02), ("pause", 0x08)): if key in switches: board.riot.input_b &= ~bit & 0xFF else: board.riot.input_b |= bit gun = state["gun"] if gun is not None: aim = None for f, a in aims: if f <= frame: aim = a trigger = any(f <= frame < f + n for f, n in pulls) gun.set(aim=aim, trigger=trigger) out = args.out.open("w") def finish(index: int, head: str) -> None: bus = zlib.crc32(log.tobytes()) if log else 0 out.write(f"{index} {head} bus={bus:08x}/{len(log)} pic={zlib.crc32(lines):08x}/{len(lines)}") tap = state["tap"] if tap is not None: samples = tap.take() packed = struct.pack(f"<{len(samples)}d", *samples) out.write(f" snd={zlib.crc32(packed):08x}/{len(samples)}") out.write("\n") if index == args.detail: for record in log: kind = "RWD"[(record >> 24) & 3] out.write(f" {record >> 26} {kind} {(record >> 8) & 0xFFFF:04x} {record & 0xFF:02x}\n") del log[:] lines.clear() def cpu_text(cpu) -> str: return (f"pc={cpu.pc:04x} a={cpu.a:02x} x={cpu.x:02x} y={cpu.y:02x} s={cpu.s:02x} " f"p={cpu.p:02x}") # fmt: skip def head7800(system) -> str: board, maria = system.board, system.board.maria return (f"clk={board.clocks} per={board.periods} halt={board.halted_periods} " f"stall={board.stalled_periods} slow={board.slow_cycles} fr={maria.frame} " f"ln={maria.line} c={maria.clock_in_line} {cpu_text(system.cpu)} " f"ictl={board.inptctrl:02x} db={board.data_bus:02x}") # fmt: skip if args.mode == "7800": overrides = formats.parse_as(args.override) if args.override else None system = System.from_rom(args.rom, machine, overrides=overrides, start=args.start) wire(system) for index in range(args.slices): apply(index + 1) system.run_frames(1) finish(index, head7800(system)) else: base = mode2600.System class Traced(base): def __init__(self, *a, **k) -> None: super().__init__(*a, **k) wire(self) mode2600.System = Traced # the module's 7800 System, traced from birth try: data = formats.read_source(args.rom)[1] system = mode2600.System2600.from_rom(data, machine, start=args.start) finally: mode2600.System = base finish(0, head7800(system.system)) system.board.bus_observers.append(observe) system.board.tia.on_line = on_tia_line for index in range(1, args.slices): apply(index) system.run_frames(1) board = system.board finish(index, f"cyc={board.cycles} hcyc={board.halted_cycles} fr={board.tia.frame} " f"ln={board.tia.line} {cpu_text(system.cpu)} db={board.data_bus:02x}") out.close() return 0 if __name__ == "__main__": raise SystemExit(main())