"""A whole console: z80-python's Z80 on a :class:`~sms_python.board.Board`. The CPU is z80-python 0.4.0, embedded through its callables contract. The glue is the only place CPU and devices meet: - before each step, the VDP's INT output (a level) is mirrored onto the CPU's maskable request, and a pause press becomes an NMI (the wiki's PauseButton.pmwiki); - the CPU runs one instruction (or interrupt entry) and returns its T-states; - the devices then advance by those T-states. So a port access inside an instruction sees the devices as they were at the instruction's *start*, the way MAME's logs stamp it (docs/mame-oracle.md, trap 5). Placing each access at its own T-state is milestone 5 (docs/timing.md). The SDSC debug console (ports $FC control, $FD data) is an emulator convention, not hardware; ZEXALL-SMS prints to it (``reference/src/zexall-sms/source/sdsc.inc``), so the system can capture it when asked. """ from __future__ import annotations from z80_python import Z80CPU from .board import Board, Machine from .cartridge import Cartridge SDSC_CONTROL = 0xFC SDSC_DATA = 0xFD # When, inside an I/O instruction, its port access happens: T-states from the start # of the instruction to T3 of its I/O machine cycle (T1, T2, the automatic wait # state TW, then T3, when a read is sampled and a write completes). Machine-cycle # layouts from Zilog UM0080's instruction tables. z80-python returns whole-instruction # totals (docs/timing.md, "Sub-instruction timing"), so the board places the access. IO_ACCESS_T = {0xDB: 4 + 3 + 3, 0xD3: 4 + 3 + 3} # IN A,(n) / OUT (n),A: M1, operand, I/O IO_ACCESS_T_ED = { **{op: 4 + 4 + 3 for op in range(0x40, 0x80) if op & 0x07 == 0x00}, # IN r,(C) **{op: 4 + 4 + 3 for op in range(0x40, 0x80) if op & 0x07 == 0x01}, # OUT (C),r **dict.fromkeys((0xA2, 0xAA, 0xB2, 0xBA), 4 + 5 + 3), # INI/IND/INIR/INDR **dict.fromkeys((0xA3, 0xAB, 0xB3, 0xBB), 4 + 5 + 3 + 3), # OUTI/OUTD/OTIR/OTDR } class System: """Machine + cartridge (+ BIOS), ready to run.""" def __init__(self, machine: Machine, cartridge: Cartridge | None, bios: Cartridge | None = None, *, sdsc_console: bool = False, audio: bool = True, vdp_phase: int = 0, disk: bytearray | None = None) -> None: # fmt: skip self.board = Board(machine, cartridge, bios, audio=audio, disk=disk) # Where in its frame the VDP starts, in mclocks. Real consoles vary; 0 starts # at the top of the active display. The MAME comparisons pass MAME's phase. vdp = self.board.vdp lines, vdp.m = divmod(vdp_phase, 684) vdp.line = lines % vdp.lines_per_frame self.sdsc_console = sdsc_console self.console_text: list[str] = [] self.cpu = Z80CPU( self.board.read_byte, self.board.write_byte, read_port=self._read_port, write_port=self._write_port, ) # A CMOS Z80 drives $FF for OUT (C),0 (z80-python's opt-in, after 0.4.0; # setting the attribute is harmless on a release that does not read it). self.cpu.cmos_out_c_zero = machine.cmos_cpu self.cycles = 0 self.instructions = 0 self._access_t: int | None = None # this step's I/O access T-state, if any self._advanced = 0 # T-states of this step the devices have already run self._int_sampled = False # INT as sampled in the last step's final T-state def _catch_up_to_access(self) -> None: if self._access_t is not None and not self._advanced: self.board.advance(self._access_t) self._advanced = self._access_t def _read_port(self, port: int) -> int: self._catch_up_to_access() return self.board.read_port(port) def _write_port(self, port: int, value: int) -> None: self._catch_up_to_access() port &= 0xFF if self.sdsc_console and port == SDSC_DATA: self.console_text.append(chr(value)) elif not (self.sdsc_console and port == SDSC_CONTROL): self.board.write_port(port, value) def _io_access_t(self) -> int | None: """The T-state of this instruction's port access, from its opcode (or None).""" read = self.board.read_byte pc = self.cpu.pc opcode = read(pc) prefix = 0 if opcode in (0xDD, 0xFD): # a prefix before IN/OUT only adds its 4 T-states prefix, opcode = 4, read((pc + 1) & 0xFFFF) second = read((pc + 1) & 0xFFFF) t = IO_ACCESS_T_ED.get(second) if opcode == 0xED else IO_ACCESS_T.get(opcode) return None if t is None else t + prefix # -- running -------------------------------------------------------------- def step(self) -> int: """One instruction or interrupt entry; returns its T-states.""" board, cpu = self.board, self.cpu if self._int_sampled: cpu.request_maskable_interrupt(0xFF) # the idle data bus: RST 38h in IM 0 else: cpu.clear_maskable_interrupt() if board.nmi: board.nmi = False cpu.request_non_maskable_interrupt() # An interrupt entry or a halted CPU makes no port access; otherwise the # access T-state, if the instruction has one, is looked up before it runs. self._access_t = None if cpu.halted else self._io_access_t() self._advanced = 0 cycles = cpu.step() # "The CPU samples the interrupt signal with the rising edge of the last # clock at the end of any instruction" (Zilog UM0080, "Maskable interrupt"): # INT is read one T-state before the boundary, so a line that rises in the # final T-state is taken an instruction later. FluBBa's "Frame IRQ HCount" # depends on it (the IRQ ends a HALT, whose NOPs quantize it to 4 T-states). board.advance(cycles - self._advanced - 1) self._int_sampled = board.vdp.irq board.advance(1) self.cycles += cycles self.instructions += 1 return cycles def run_frame(self) -> list[list[int]]: """Run until the VDP finishes a frame; return it (rows of RGB888).""" vdp = self.board.vdp vdp.frame_ready = False while not vdp.frame_ready: self.step() return vdp.visible_frame() def run_cycles(self, cycles: int) -> None: target = self.cycles + cycles while self.cycles < target: self.step() @property def console(self) -> str: return "".join(self.console_text)