# SPDX-License-Identifier: MIT """A test-only AcidSAP machine: 6502-python, 64 KB of RAM, the POKEY core, a sliver of ANTIC. AcidSAP (Avery Lee, MIT; Acid800 1.2) is Acid800 cut down to what a SAP type D player offers: a 6502, RAM, POKEY, and from ANTIC only WSYNC and VCOUNT. Each standalone test is a ``.sap`` file whose INIT is $2000; it ends by jumping to ``_sap_testEnd`` (address from its ``.lab`` file) with the N flag set for a failure and clear for a pass; its text goes to $1000 (``_disp_putchar``). This module lives in ``tests/`` and is never imported by ``src/`` (decision 6; ``tests/test_acidsap.py`` checks the boundary). It uses 6502-python's public interface only: ``MOS6502(read, write)``, ``step()``, the IRQ request calls and ``note_stall()``. The machine, cycle by cycle (every bus cycle is one callback; the callback performs the access, then ticks POKEY: B0.1): - 114 cycles per scan line, 262 lines (NTSC). - Refresh DMA halts the CPU at cycles 25, 29, ..., 57 of every line, with playfield DMA off [AHRM 4.14 "Memory refresh DMA"]. POKEY still ticks. - WSYNC ($D40A): one more cycle runs, then RDY holds the CPU's next read until cycle 105; a write at cycle 104 or later waits for the next line's 105 [AHRM 4.9]. RDY does not stop write cycles [AHRM 4.9, "Read-modify-write instructions"]. - VCOUNT ($D40B): line / 2, the new value from cycle 111 of the line before; $83 on cycle 111 of the last line [AHRM 4.10]. - /IRQ: the CPU sees in cycle c the line as it stood after tick c - 1 - lag; ``lag`` 0 is the 2-cycle machine of AHRM 5.7 (a 130XE in Acid800's comments), 1 the 3-cycle one (an 800XL). - No NMIs (SAP mode). Other I/O ($D000-$D7FF outside POKEY and ANTIC) reads $FF and ignores writes. POKEY starts as a SAP player leaves it: SKCTL = 3, everything else 0. """ from __future__ import annotations from collections import deque from pathlib import Path from sixfiveohtwo import FLAG_N, MOS6502 from pokey_python import POKEY LINE = 114 LINES = 262 REFRESH = frozenset(range(25, 58, 4)) # AHRM 4.14: nine cycles from 25, every four WSYNC_RELEASE = 105 # AHRM 4.9 WSYNC_DEADLINE = 103 VCOUNT_EARLY = 111 # AHRM 4.10 STUB = 0x0600 # where INIT "returns" to: JMP * (the tests never return) def load_sap(path: Path) -> tuple[dict[str, str], list[tuple[int, bytes]]]: """The header tags and the binary segments of a SAP file.""" data = path.read_bytes() split = data.index(b"\xff\xff") header = {} for line in data[:split].decode("ascii").splitlines(): if line.strip(): key, _, value = line.partition(" ") header[key] = value.strip() segments = [] pos = split while pos + 4 <= len(data): if data[pos] == 0xFF and data[pos + 1] == 0xFF: pos += 2 continue start = data[pos] | data[pos + 1] << 8 end = data[pos + 2] | data[pos + 3] << 8 pos += 4 segments.append((start, data[pos : pos + end - start + 1])) pos += end - start + 1 return header, segments def load_labels(path: Path) -> dict[str, int]: labels = {} for line in path.read_text(encoding="ascii", errors="replace").splitlines(): parts = line.split() if len(parts) == 3: labels[parts[2]] = int(parts[1], 16) return labels class Machine: def __init__(self, sap: Path, lag: int = 0) -> None: header, segments = load_sap(sap) if header.get("TYPE") != "D": raise ValueError(f"{sap.name}: SAP type {header.get('TYPE')}, expected D") self.labels = load_labels(sap.with_suffix(".lab")) self.ram = bytearray(0x10000) for start, data in segments: self.ram[start : start + len(data)] = data self.chip = POKEY() self.chip.write(15, 3) # SKCTL = 3, as a SAP player leaves it self.chip.tick() self.cycle = 0 self.hpos = 0 self.vline = 0 self.rdy: list[tuple[int, int]] = [] # RDY low for reads in cycles [from, until) self.seen = deque([False] * (lag + 1), maxlen=lag + 1) self.cpu_irq = False self.other_io: set[int] = set() self.cpu = MOS6502(self.read, self.write) # INIT is called as a subroutine; it never returns in these tests self.ram[STUB : STUB + 3] = bytes((0x4C, STUB & 0xFF, STUB >> 8)) ret = STUB - 1 self.ram[0x01FF], self.ram[0x01FE] = ret >> 8, ret & 0xFF self.cpu.s = 0xFD self.cpu.pc = int(header["INIT"], 16) # -- time ------------------------------------------------------------ def _tick(self) -> None: self.chip.tick() self.seen.append(self.chip.irq) self.cycle += 1 self.hpos += 1 if self.hpos == LINE: self.hpos = 0 self.vline = (self.vline + 1) % LINES def _sync_irq(self) -> None: level = self.seen[0] if level != self.cpu_irq: self.cpu_irq = level if level: self.cpu.request_maskable_interrupt() else: self.cpu.clear_maskable_interrupt() def _halts(self, is_read: bool) -> None: """Burn the cycles in which the CPU is halted before this access.""" self._sync_irq() stalled = False for _ in range(3 * LINE): # bounded: a WSYNC wait is under two lines rdy = is_read and any(a <= self.cycle < b for a, b in self.rdy) if not rdy and self.hpos not in REFRESH: break if is_read and not stalled: self.cpu.note_stall() stalled = True self._tick() self._sync_irq() if is_read: self.cpu.note_stall() else: raise RuntimeError("the CPU stayed halted for three lines") # -- the bus --------------------------------------------------------- def read(self, address: int) -> int: self._halts(True) page = address >> 8 if page == 0xD2: value = self.chip.read(address & 0x0F) elif page == 0xD4 and address & 0x0F == 0x0B: value = self._vcount() elif 0xD0 <= page <= 0xD7: self.other_io.add(address) value = 0xFF else: value = self.ram[address] self._tick() return value def write(self, address: int, value: int) -> None: self._halts(False) page = address >> 8 if page == 0xD2: self.chip.write(address & 0x0F, value) elif page == 0xD4 and address & 0x0F == 0x0A: self._wsync() elif 0xD0 <= page <= 0xD7: self.other_io.add(address) else: self.ram[address] = value self._tick() def _wsync(self) -> None: # AHRM 4.9: one more cycle runs, then the next read waits for cycle 105 if self.hpos <= WSYNC_DEADLINE: release = self.cycle + WSYNC_RELEASE - self.hpos else: release = self.cycle + LINE - self.hpos + WSYNC_RELEASE windows = [w for w in self.rdy if w[1] > self.cycle] if not any(until == release for _, until in windows): # an RMW's second write, same line windows.append((self.cycle + 2, release)) self.rdy = windows def _vcount(self) -> int: line = self.vline if self.hpos >= VCOUNT_EARLY: # AHRM 4.10, and its end-of-frame anomaly line += 1 if line == LINES and self.hpos > VCOUNT_EARLY: line = 0 return line >> 1 # -- running a test ---------------------------------------------------- def run(self, max_cycles: int = 4_000_000) -> tuple[bool | None, str]: """Run to ``_sap_testEnd``: (True pass / False fail / None out of time, the text).""" end = self.labels["_sap_testEnd"] cpu = self.cpu verdict = None while self.cycle < max_cycles: cpu.step() if cpu.pc == end: verdict = not cpu.p & FLAG_N break return verdict, self.text() def text(self) -> str: out = [] for byte in self.ram[0x1000:0x1400]: if byte == 0: break out.append("\n" if byte == 0x9B else chr(byte) if 32 <= byte < 127 else "?") return "".join(out)