# SPDX-License-Identifier: MIT """Milestone 2: ANTIC's per-line DMA charts, produced from the model. Prints, for each mode group, fetch width and HSCROL value, which cycles of a scan line are DMA, in the layout of [AHRM] 4.14's charts (p. 90-96): one row per HSCROL value, cycles 0-113 left to right. Letters: M missile, D display list, P player, A LMS address, N character name / bitmap byte, C character data, R refresh, V virtual (no HALT), X the extra stop-cycle fetch (C13), '.' the CPU's cycle. The charts are compared by eye with the manual's. python scripts/dma_charts.py [--mode 2] [--subsequent] [--pm] Runs a synthetic BIOS (tests/helpers.py) on the board: no ROM is needed. """ from __future__ import annotations import argparse import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "tests")) from helpers import fake_board # noqa: E402 from a5200_python import antic as A # noqa: E402 LETTER = [ (A.K_EXTRA, "X"), (A.K_REFRESH, "R"), (A.K_MISSILE, "M"), (A.K_DLIST, "D"), (A.K_PLAYER, "P"), (A.K_ADDR, "A"), (A.K_CHAR, "C"), (A.K_NAME, "N"), (A.K_BITMAP, "N"), ] def run(mode: int, width: int, hscrol: int | None, subsequent: bool, pm: bool) -> str: """The chart row as letters, by watching ANTIC's kind on every cycle.""" dmactl = 0x20 | width | (0x0C if pm else 0) ir = 0x40 | mode | (0x10 if hscrol is not None else 0) code = bytes( ( 0xA9, 0x00, 0x8D, 0x02, 0xD4, 0xA9, 0x10, 0x8D, 0x03, 0xD4, 0xA9, hscrol or 0, 0x8D, 0x04, 0xD4, 0xA9, dmactl, 0x8D, 0x00, 0xD4, 0x4C, 0x14, 0xF8, ) ) # fmt: skip board = fake_board(code) board.ram[0x1000:0x1006] = bytes((ir, 0x00, 0x20, 0x41, 0x00, 0x10)) marks = ["."] * 114 antic = board.antic target = 9 if subsequent else 8 original_end = antic.end def end(data: int) -> None: if board.frames == 1 and antic.vcount == target and antic.kind: kind = antic.kind letter = "?" for bit, mark in LETTER: if kind & bit: letter = mark break special = A.K_REFRESH | A.K_MISSILE | A.K_PLAYER | A.K_DLIST | A.K_ADDR if kind & A.K_VIRTUAL and not kind & special: letter = "V" marks[antic.hcount] = letter original_end(data) antic.end = end while board.frames < 2: board.step() return "".join(marks) GROUPS = {2: "2-5", 6: "6-7", 8: "8-9", 10: "A-C", 13: "D-F"} WIDTHS = {1: "narrow", 2: "normal", 3: "wide"} # -- machine comparison with [AHRM]'s printed charts --------------------------- # # [AHRM] 4.14 (2026-01-02 edition, PDF pages 90-96) draws each chart as rows # of flat-coloured cells, one per cycle, in the colours of its legend. The # comparison renders a page with poppler's ``pdftoppm`` (PPM, read here # without any image library), finds the rows by their red cycle-0 cell and # the cycle grid from the header's tick marks, reads each cell's colour at # its centre and compares it with the model's row. Facts read from the # manual (which cycle is which kind of DMA), nothing copied from it. PAGES = { # PDF page -> (modes charted, subsequent lines?) 90: ((2, 3, 4, 5), False), 91: ((2, 3, 4, 5), True), 92: ((6, 7), False), 93: ((6, 7), True), 94: ((8, 9), False), 95: ((10, 11, 12), False), 96: ((13, 14, 15), False), } COLOURS = { # legend colour -> chart class (255, 0, 0): "P", # player/missile graphics (255, 153, 102): "D", # display list DMA (instruction and LMS address) (255, 0, 255): "R", # memory refresh (0, 0, 255): "F", # playfield DMA (bitmap byte, character data) (0, 220, 255): "N", # character map DMA (character name) (255, 255, 153): "V", # virtual DMA (230, 230, 230): ".", # the CPU's cycle } def chart_class(letter: str, mode: int) -> str: """The model's letter as the chart's class.""" if letter in "MP": return "P" if letter in "DA": return "D" if letter == "C": return "F" if letter == "N": return "N" if mode <= 7 else "F" return letter # R, V, '.'; X would show as a mismatch def read_ppm(path: Path) -> tuple[int, int, bytes]: data = path.read_bytes() fields: list[bytes] = [] i = 0 while len(fields) < 4: while data[i : i + 1].isspace(): i += 1 j = i while not data[j : j + 1].isspace(): j += 1 fields.append(data[i:j]) i = j if fields[0] != b"P6" or fields[3] != b"255": raise ValueError(f"{path}: not an 8-bit binary PPM") return int(fields[1]), int(fields[2]), data[i + 1 :] def page_rows(pdf: Path, page: int, scratch: Path) -> list[str]: """Every chart row on one page, top to bottom, as class letters for cycles 0-113.""" root = scratch / f"ahrm-{page}" subprocess.run( [ "pdftoppm", "-f", str(page), "-l", str(page), "-r", "200", "-singlefile", str(pdf), str(root), ], check=True, ) image = root.with_suffix(".ppm") try: w, h, px = read_ppm(image) finally: image.unlink() def at(x: int, y: int) -> tuple[int, ...]: o = 3 * (y * w + x) return tuple(px[o : o + 3]) # The cycle grid: the header row's black ticks stand at cycles 0, 8, ..., 112. # The first pixel row crossing 15 tick runs right of the "HSCR" box; every # chart on these pages shares the grid (checked: the rows' red cycle-0 # cells all fall on it). zero: list[int] = [] for y in range(h): xs = [x for x in range(w) if at(x, y) == (0, 0, 0)] runs = [x for i, x in enumerate(xs) if i == 0 or xs[i - 1] != x - 1] if 15 <= len(runs) <= 17: gaps = [b - a for a, b in zip(runs[-15:], runs[-14:])] if max(gaps) - min(gaps) <= 4 and min(gaps) > 50: # evenly spaced: the grid zero = runs[-15:] break if not zero: raise ValueError(f"page {page}: no chart header found") cell = (zero[14] - zero[0]) / 112 # Rows: bands of y whose cycle-0 cell is red. probe = round(zero[0] + cell / 2) rows = [] y = 0 while y < h: if at(probe, y) == (255, 0, 0): top = y while y < h and at(probe, y) == (255, 0, 0): y += 1 # A chart's rows touch: split the red band by the row pitch # (2.45 cycle cells: 33.5 pixels at 200 dpi on these pages). if y - top < cell: continue # a one-pixel edge line, not a row count = max(1, round((y - top) / (cell * 2.45))) for n in range(count): mid = top + round((n + 0.5) * (y - top) / count) letters = [] for c in range(114): colour = at(round(zero[0] + (c + 0.5) * cell), mid) letters.append(COLOURS.get(colour, "?" if colour != (255, 255, 255) else " ")) rows.append("".join(letters)) y += 1 return rows def compare(pdf: Path) -> int: scratch = ROOT / "tests" / "detector_runs" scratch.mkdir(parents=True, exist_ok=True) total = cells = bad = 0 for page, (modes, subsequent) in PAGES.items(): rows = page_rows(pdf, page, scratch) layout = [(3, 3, h) for h in range(0, 16, 2)] + [(2, 1, h) for h in range(0, 16, 2)] layout.append((1, 1, None)) if len(rows) != len(layout): print(f"page {page}: {len(rows)} chart rows found, {len(layout)} expected") return 2 for mode in modes: wrong = 0 for row, (fetch, width, hscrol) in zip(rows, layout, strict=True): model = "".join( chart_class(ch, mode) for ch in run(mode, width, hscrol, subsequent, True) ) diff = [c for c in range(114) if row[c] != " " and row[c] != model[c]] cells += sum(1 for ch in row if ch != " ") total += 1 if diff: wrong += 1 bad += len(diff) label = "off" if hscrol is None else hscrol print(f"page {page} mode {mode:X} {WIDTHS[fetch]} HSCR {label}: cycles {diff}") print(f" manual {row}\n model {model}") line = "subsequent lines" if subsequent else "mode line" print(f"page {page}: mode {mode:X} {line}: {len(rows) - wrong}/{len(rows)} rows agree") print(f"{total} rows, {cells} cells compared, {bad} cells differ") return 0 if bad == 0 else 1 def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--mode", type=int, choices=sorted(GROUPS), action="append") parser.add_argument("--subsequent", action="store_true", help="a later scan line") parser.add_argument("--pm", action="store_true", help="player/missile DMA on") parser.add_argument( "--compare", type=Path, metavar="AHRM_PDF", help="compare every mode 2-F with the manual's charts (PDF pages 90-96)", ) args = parser.parse_args() if args.compare: return compare(args.compare) ruler = "".join(str(c // 10 % 10) if c % 10 == 0 else " " for c in range(114)) ruler2 = "".join(str(c % 10) for c in range(114)) for mode in args.mode or sorted(GROUPS): # [AHRM]'s charts go by fetch width: the wide chart is a wide (or a # scrolled normal) playfield, the normal chart a scrolled narrow one, # the narrow chart an unscrolled narrow one. for fetch, width, scrolled in ((3, 3, True), (2, 1, True), (1, 1, False)): line = "subsequent lines" if args.subsequent else "mode line" print(f"\nANTIC modes {GROUPS[mode]}, {line}, {WIDTHS[fetch]} playfield") print(f"HSCR {ruler}\n {ruler2}") for hscrol in range(0, 16, 2) if scrolled else [None]: label = "off" if hscrol is None else f"{hscrol:3d}" print(f"{label:>4} {run(mode, width, hscrol, args.subsequent, args.pm)}") return 0 if __name__ == "__main__": raise SystemExit(main())