#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The lockstep gate's reference side: a2600-python, traced slice by slice. Run on the reference's interpreter (external/venv: a2600-python at 4ad24f2 with 6502-python at 828b619, the revision its pyproject pins; 28fb095 and 741419a until 2026-11-22, the same code). A slice is 19,912 CPU cycles of board time (262 lines of 76 cycles): the console runs whole instructions (``System.step``) until ``board.cycles`` reaches the slice's end. Each slice's line holds the CPU state, the board time (cycles, halted cycles, instructions), the TIA's position (line, step in line, frame), the RIOT's timer and port registers, a CRC-32 of every bus cycle of the slice (12 bytes each: kind 0 read / 1 write, address u16, value, cycle u64; little-endian), a CRC-32 of every line the TIA finished in the slice (228 bytes each, blank included) and a CRC-32 of the slice's audio samples (``take_samples()``, little-endian doubles). ``target/release/a2600-trace`` writes the same lines; ``scripts/lockstep.py`` compares them. a2600_trace.py ROM --slices N [--machine KEY] [--scheme S] [--left DEV] [--right DEV] [--input FILE] [--detail SLICE] [--hand-over SLICE] --out FILE The cartridge gets the row's CPU clock (``load(..., cpu_hz=)``, as ``System.from_rom`` passes it), so a DPC's music keeps its hertz on every row. ``--hand-over SLICE``: before that slice runs, a new ``Board`` is built on the running TIA, RIOT, cycle count and data bus, and the running CPU is handed to it with ``System(..., board=, cpu=)``, no power-on (the 7800's 2600 mode); the instruction count is carried over, the board's halted count starts again. ROM is a file (a .zip or .7z holding one ROM is read in place), or ``ARCHIVE.zip::MEMBER``. The scheme is identified as ``cartridge.load`` does (set ``MAME_HASHPATH`` so both sides read the same software list) unless ``--scheme`` names it. KEY: ``ntsc``, ``pal``, ``secam``, a #699 console (``PAL_7800``, ``PAL_JR_84``, ``PAL_JR_91``, ``PAL_L6``, ``PAL_VADER``, ``SECAM_WOODY``) or ``ntsc7800``. Devices as the window has them (play.py): left ``joystick paddles driving booster keypad none``, right ``joystick paddles keypad savekey none`` (the SaveKey in memory only). ``--input FILE``: lines ``SLICE WORD...`` (``;`` starts a comment line), applied in order before that slice runs: ``p0=up+down+left+right+fire`` / ``p1=...`` (``-`` for none; the left port's Booster Grip also takes ``pin5``, ``pin9``), ``wheel=N`` (clicks), ``wheelfire=0|1``, ``pad0=0.25`` (``pad0``-``pad3``), ``padfire0=0|1`` (the paddle buttons, SWCHA D7, D6, D3, D2), ``keys0=1+5+#`` / ``keys1=...`` (the keypad's legends), ``switches=reset+select`` (held; ``-`` releases), ``colour=0|1``, ``diff0=a|b``, ``diff1=a|b``. """ from __future__ import annotations import argparse import struct import zipfile import zlib from pathlib import Path from a2600_python.board import Board from a2600_python.cartridge import load, read_image from a2600_python.controllers import BoosterGrip, DrivingController, Joystick, Keypads, Paddles from a2600_python.machine import CONSOLE_ROWS, NTSC_7800, VCS_NTSC, VCS_PAL, VCS_SECAM from a2600_python.savekey import SaveKey from a2600_python.system import System SLICE_CYCLES = 262 * 76 KEYS = "123456789*0#" def machine_row(key: str): rows = {"ntsc": VCS_NTSC, "pal": VCS_PAL, "secam": VCS_SECAM, "ntsc7800": NTSC_7800} return rows.get(key) or CONSOLE_ROWS[key] def rom_image(text: str) -> bytes: if "::" in text: archive, member = text.split("::", 1) with zipfile.ZipFile(archive) as z: return z.read(member) return read_image(text)[0] def read_inputs(path: Path | None) -> dict[int, list[str]]: out: dict[int, list[str]] = {} if path is None: return out for line in path.read_text().splitlines(): words = line.split() # ';' starts a comment line ('#' is a keypad key) if words and not words[0].startswith(";"): out.setdefault(int(words[0]), []).extend(words[1:]) return out class Devices: """The ports' devices, as play.py's Controls plugs them in.""" def __init__(self, system: System, left: str, right: str) -> None: tia, riot = system.board.tia, system.board.riot clock = system.machine.timing.colour_clock_hz self.tia, self.riot = tia, riot self.left_kind, self.right_kind = left, right self.paddles = Paddles(tia, clock) if "paddles" in (left, right) or left == "booster" else None self.keypads = Keypads(tia, riot) if "keypad" in (left, right) else None self.left = { "joystick": lambda: Joystick(tia, riot, 0), "driving": lambda: DrivingController(tia, riot, 0), "booster": lambda: BoosterGrip(tia, riot, self.paddles, 0), }.get(left, lambda: None)() self.right = Joystick(tia, riot, 1) if right == "joystick" else None self.savekey = SaveKey(riot, system.machine.timing.cpu_hz) if right == "savekey" else None if self.paddles is not None: for i, kind in ((0, left), (2, right)): if kind == "paddles": self.paddles.position[i] = self.paddles.position[i + 1] = 0.5 def apply(self, word: str) -> None: name, _, value = word.partition("=") parts = set() if value == "-" else set(value.split("+")) stick = {k: k in parts for k in ("up", "down", "left", "right", "fire")} riot = self.riot if name == "p0": if self.left_kind == "booster": self.left.set(pin5="pin5" in parts, pin9="pin9" in parts, **stick) else: self.left.set(**stick) elif name == "p1": self.right.set(**stick) elif name == "wheel": self.left.turn(int(value)) elif name == "wheelfire": self.left.press(value == "1") elif name.startswith("padfire"): bit = (0x80, 0x40, 0x08, 0x04)[int(name[7:])] riot.set_input_a(riot.input_a & ~bit if value == "1" else riot.input_a | bit) elif name.startswith("pad"): self.paddles.position[int(name[3:])] = float(value) elif name.startswith("keys"): pressed = self.keypads.pressed[int(name[4:])] pressed.clear() for key in parts: index = KEYS.index(key) pressed.add((index // 3, index % 3)) elif name == "switches": held = (0x01 if "reset" in parts else 0) | (0x02 if "select" in parts else 0) riot.input_b = (riot.input_b | 0x03) & ~held elif name == "colour": riot.input_b = riot.input_b | 0x08 if value == "1" else riot.input_b & ~0x08 elif name in ("diff0", "diff1"): bit = 0x40 if name == "diff0" else 0x80 riot.input_b = riot.input_b | bit if value == "a" else riot.input_b & ~bit else: raise SystemExit(f"unknown input word {word!r}") def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("rom") parser.add_argument("--slices", type=int, required=True) parser.add_argument("--machine", default="ntsc") parser.add_argument("--scheme") parser.add_argument("--left", default="joystick") parser.add_argument("--right", default="joystick") parser.add_argument("--input", type=Path) parser.add_argument("--detail", type=int, default=-1) parser.add_argument("--hand-over", type=int, default=-1) parser.add_argument("--out", type=Path, required=True) args = parser.parse_args() machine = machine_row(args.machine) # The row's clock goes to the cartridge, as System.from_rom passes it (only a # clocked scheme, DPC, takes it). loaded = load(rom_image(args.rom), scheme=args.scheme, cpu_hz=machine.timing.cpu_hz) system = System(loaded.cartridge, machine) devices = Devices(system, args.left, args.right) inputs = read_inputs(args.input) board, tia, cpu = system.board, system.board.tia, system.cpu riot = board.riot bus = bytearray() detail: list[str] = [] detail_on = [False] pack = struct.Struct(" None: bus.extend(pack(0 if kind == "R" else 1, address, value, cycle)) if detail_on[0]: detail.append(f" {kind} {address:04x} {value:02x} {cycle}") board.bus_observers.append(observe) picture = [0, 0] def line(pixels: bytearray) -> None: picture[0] = zlib.crc32(pixels, picture[0]) picture[1] += 1 tia.on_line = line with args.out.open("w") as out: out.write(f"# scheme={loaded.cartridge.name} machine={machine.name}\n") for k in range(args.slices): if k == args.hand_over: # The CPU, TIA and RIOT handed to a new board as they stand # (System(..., board=, cpu=), as tests/test_sockets.py's # mid-run hand-over); the old board no longer sees the bus. old = board board = Board(machine, old.cartridge, tia=old.tia, riot=old.riot, cycles=old.cycles) board.data_bus = old.data_bus board.bus_observers.append(observe) instructions = system.instructions system = System(old.cartridge, machine, board=board, cpu=system.cpu) system.instructions = instructions for word in inputs.get(k, ()): devices.apply(word) detail_on[0] = k == args.detail end = (k + 1) * SLICE_CYCLES while board.cycles < end: system.step() samples = tia.audio.take_samples() sound = zlib.crc32(struct.pack(f"<{len(samples)}d", *samples)) out.write( f"{k} pc={cpu.pc:04x} a={cpu.a:02x} x={cpu.x:02x} y={cpu.y:02x} s={cpu.s:02x} p={cpu.p:02x}" f" cyc={board.cycles} halt={board.halted_cycles} ins={system.instructions}" f" line={tia.line} step={tia.step_in_line} frame={tia.frame}" f" riot={riot.value:02x}/{riot.flags:02x}/{riot.ddr_a:02x}/{riot.out_a:02x}/{riot.input_a:02x}" f" bus={zlib.crc32(bus):08x}/{len(bus) // 12}" f" pic={picture[0]:08x}/{picture[1]} snd={sound:08x}/{len(samples)}\n" ) if detail: out.write("\n".join(detail) + "\n") detail.clear() bus.clear() picture[0] = picture[1] = 0 return 0 if __name__ == "__main__": raise SystemExit(main())