#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The lockstep gate's reference side: lynx-python, traced slice by slice. Run on the reference's interpreter (external/venv: lynx-python at af8b8ba, w65c02-python at af0ad6b; the same code as 75b9be7 and 9ca4a2f). A slice is 266,667 ticks of board time (1/60 s of the 16 MHz crystal): the board steps (``board.step()``) until ``board.tick`` reaches the slice's end. Each slice's line holds the CPU registers at its end, the board time, Mikey's interrupt bits and the IRQ line, MAPCTL, the display (frames, measured period, line index), Suzy (sprite busy, engine running, SDONE), the cart port (shift register, counter), a CRC-32 of every CPU bus cycle of the slice (two little-endian u64 per cycle: the board tick after the cycle, then ``kind << 24 | address << 8 | value``, kind 0 read, 1 write), a CRC-32 of the display's frame buffer (12-bit colours, as ``Display.frame``) and a CRC-32 of the 64 KiB RAM. ``target/release/lynx-trace`` writes the same lines; ``scripts/lockstep.py`` compares them. lynx_trace.py CART --slices N [--machine lynx1|lynx2] [--input FILE] [--audio] [--timeline measured|paths] [--detail SLICE] --out FILE The cart is booted as ``python -m lynx_python`` boots it (``__main__.boot``: the real boot ROM by hash through ``$MAME_ROMPATH``, the cart's EEPROM under ``$XDG_DATA_HOME``; the gate gives each run a fresh, empty one). ``--input``: lines ``SLICE NAME...``; before that slice the pressed buttons become exactly NAME... (``-`` for none): up down left right opt1 opt2 b a pause (Suzy's JOYSTICK bits as ``lynx-play`` sets them, pause = SWITCHES bit 0). ``--audio``: Mikey records its samples from the start (``start_audio``) and each line ends with ``snd=CRC/COUNT`` of the slice's samples (little-endian i16). ``--timeline`` sets ``LYNX_SUZY_TIMELINE`` before the reference is imported. ``--eeprom TYPE[:ORG]`` overrides the cart's EEPROM as ``python -m lynx_python --eeprom`` does; with an EEPROM each line ends with ``eep=CRC/WRITES/READS`` (the chip's save image). ``--picture``: each line ends with ``rgb=CRC/WxH`` of the RGB picture turned for the cart's rotation (``picture.rotate``). ``--detail SLICE``: also write every bus cycle of that slice. ``--save-at`` is accepted and ignored (the Rust board's round trip). """ from __future__ import annotations import argparse import os import sys import zlib from array import array from pathlib import Path SLICE_TICKS = 266_667 BUTTONS = { "up": 0x80, "down": 0x40, "left": 0x20, "right": 0x10, "opt1": 0x08, "opt2": 0x04, "b": 0x02, "a": 0x01, } # fmt: skip 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("#")[0].split() if words: out[int(words[0])] = [w for w in words[1:] if w != "-"] return out def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("cart", type=Path) parser.add_argument("--slices", type=int, required=True) parser.add_argument("--machine", default="lynx2") parser.add_argument("--input", type=Path) parser.add_argument("--audio", action="store_true") parser.add_argument("--timeline", choices=("measured", "paths")) parser.add_argument("--eeprom", help="override the cart's EEPROM (TYPE[:ORG], e.g. 93C46:16)") parser.add_argument("--picture", 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("--out", type=Path, required=True) args = parser.parse_args() if args.timeline: os.environ["LYNX_SUZY_TIMELINE"] = args.timeline from lynx_python.__main__ import boot from lynx_python.cart import load if sys.byteorder != "little": raise SystemExit("needs a little-endian host") from lynx_python.picture import rotate description = load(args.cart, overrides={"eeprom": args.eeprom} if args.eeprom else None) board = boot(args.cart, args.machine, description) cpu = board.cpu mikey, suzy, port = board.mikey, board.suzy, board.port display = mikey.display if args.audio: mikey.start_audio(board.tick) log = array("Q") read, write = cpu.read_byte, cpu.write_byte def traced_read(address: int) -> int: value = read(address) log.append(board.tick) log.append((address << 8) | value) return value def traced_write(address: int, value: int) -> None: write(address, value) log.append(board.tick) log.append((1 << 24) | (address << 8) | value) cpu.read_byte, cpu.write_byte = traced_read, traced_write inputs = read_inputs(args.input) step = board.step sent = 0 with args.out.open("w") as out: for index in range(args.slices): if index in inputs: keys = 0 for name in inputs[index]: if name != "pause": keys |= BUTTONS[name] suzy.joystick = keys suzy.switches = (suzy.switches & ~1) | (1 if "pause" in inputs[index] else 0) end = (index + 1) * SLICE_TICKS while board.tick < end: step() bus = zlib.crc32(log.tobytes()) if log else 0 picture = zlib.crc32(bytes(display.frame)) ram = zlib.crc32(bytes(board.ram)) out.write( f"{index} t={board.tick} pc={cpu.pc:04x} a={cpu.a:02x} x={cpu.x:02x} " f"y={cpu.y:02x} s={cpu.s:02x} p={cpu.p:02x} irq={mikey.irq_bits():02x} " f"line={int(board.irq_line)} map={board.mapctl:02x} frames={display.frames} " f"period={display.frame_period} li={display.line_index} " f"busy={suzy.sprite_busy} eng={int(suzy.engine.steps is not None)} " f"sdone={mikey.sdone_pending} cart={port.shift:02x}/{port.counter:03x} " f"bus={bus:08x}/{len(log) // 2} pic={picture:08x} ram={ram:08x}" ) if args.audio: samples = mikey.samples chunk = samples[sent:].tobytes() sent = len(samples) out.write(f" snd={zlib.crc32(chunk):08x}/{len(chunk) // 2}") if port.eeprom is not None: e = port.eeprom out.write(f" eep={zlib.crc32(e.image()):08x}/{e.writes}/{e.reads}") if args.picture: turned, width, height = rotate(display.rgb(), description.rotation) out.write(f" rgb={zlib.crc32(turned):08x}/{width}x{height}") out.write("\n") if index == args.detail: for k in range(0, len(log), 2): word = log[k + 1] out.write( f" {log[k]} {'rw'[word >> 24]} {(word >> 8) & 0xFFFF:04x} {word & 0xFF:02x}\n" ) del log[:] return 0 if __name__ == "__main__": raise SystemExit(main())