"""The machines: memory map, port decode, and the devices wired together. A :class:`Board` owns RAM, the VDP, the PSG, the I/O chip, the cartridge and an optional BIOS, and presents the four bus callables z80-python 0.4.0 takes: cpu = Z80CPU(board.read_byte, board.write_byte, read_port=board.read_port, write_port=board.write_port) :class:`~sms_python.system.System` does that wiring. The board can also be driven without a CPU, by :meth:`Board.advance` and its bus methods, which is how ``scripts/replay_mame_io.py`` checks it against MAME. Sources: docs/start-here.md, which cites msvdp section 2 (port decode by A7, A6, A0), the wiki's MemoryMap, Port3E, IOPortMap and IOPortMapGG pages, and MAME 0.285's ``sms_m.cpp`` (power-on $3E) and ``sg1000.cpp`` (the SG-1000 map). """ from __future__ import annotations from dataclasses import dataclass from sn76489_python import ( GAME_GEAR_PSG, SEGA_VDP_PSG, SN76489, SN76489AN, YM7101_PSG, PSGVariant, ) from ym2413_python import OPLL, YM2413 from .audio import BoxFilter, FMBoxFilter from .cartridge import Cartridge from .io import GameGearPorts, IOChip, SC3000Keyboard from .sf7000 import SuperControlStation from .vdp import ( SEGA_315_5124, SEGA_315_5246, SEGA_315_5313, SEGA_GAME_GEAR, SEGA_GAME_GEAR_1ASIC_SMS_MODE, SEGA_GAME_GEAR_SMS_MODE, TMS9918A, VDP, VDPVariant, ) OPEN_BUS = 0xFF # Port $3E bits, all active low (the wiki's Port3E.pmwiki; MAME sms.h IO_*). MEM_EXPANSION = 0x80 MEM_CARTRIDGE = 0x40 MEM_CARD = 0x20 MEM_WORK_RAM = 0x10 MEM_BIOS = 0x08 MEM_IO_CHIP = 0x04 @dataclass(frozen=True) class Machine: """One console model as data. ``decode``: "sg1000", "sms", "gamegear" (GG mode) or "gg-sms" (a Game Gear in SMS-compatibility mode: ports as on an SMS with TH control through $3F, but no $3E and no BIOS; MAME 0.285 sms.cpp, the Game Gear's "Master System mode" view) or "md" (a Mega Drive with a Power Base Converter: the same ports, no BIOS, $3E without effect and port $DD bit 5 reading 0; smstech sections 3 and 4). ``cmos_cpu``: the Z80 is a CMOS part (the Game Gear's), for z80-python's ``cmos_out_c_zero`` once a release carries it. ``disk_unit``: an SC-3000 with the SF-7000 in its cartridge slot (sf7000.py); its IPL ROM is the board's ``bios``. ``cpu_clock``: the Z80's clock in Hz where the region does not give it (below). ``fm``: a YM2413 at ports $F0-$F2: "japan" (built into the Japanese Master System), "mark3" (the Mark III's FM Unit), or "" for none (FMBoard below). """ name: str vdp: VDPVariant psg: PSGVariant decode: str ram_size: int = 0x2000 region: str = "NTSC" japanese: bool = False has_th: bool = True reset_button: bool = True mapper_registers: bool = True # writes to $FFFC-$FFFF reach the cartridge cmos_cpu: bool = False fm: str = "" disk_unit: bool = False cpu_clock: int = 0 @property def clock(self) -> int: """The Z80's clock: a third of 10.738635 MHz, or a fifteenth of 53.203424 MHz on the PAL consoles, unless the machine names its own.""" return self.cpu_clock or (3_579_545 if self.region == "NTSC" else 3_546_893) @property def frame_rate(self) -> float: """Frames a second: 228 Z80 cycles a line, 262 or 313 lines.""" return self.clock / 228 / (262 if self.region == "NTSC" else 313) SG1000 = Machine( "SG-1000", TMS9918A, SN76489AN, "sg1000", ram_size=0x400, japanese=True, has_th=False, reset_button=False, mapper_registers=False, ) # fmt: skip # The SC-3000: the SG-1000's chips with 2 KB of RAM, a keyboard and an 8255, and # ports decoded by A7, A6 and A5 alone (sc3000h sections 2 and 4). SC3000 = Machine( "SC-3000", TMS9918A, SN76489AN, "sc3000", ram_size=0x800, japanese=True, has_th=False, reset_button=False, mapper_registers=False, ) # fmt: skip # The PAL SC-3000 has a TMS9929A, 313 lines, on the NTSC machine's crystal: "the # main clock runs at 10.738635 MHz, which is used directly by the TMS9929A", and # the Z80's 3.579545 MHz is a third of it (sc3000h section 2, from a PAL SC-3000H). # So it runs at 50.16 frames a second, not a PAL Master System's 49.70. SC3000_PAL = Machine( "SC-3000 (PAL)", TMS9918A, SN76489AN, "sc3000", ram_size=0x800, region="PAL", japanese=True, has_th=False, reset_button=False, mapper_registers=False, cpu_clock=3_579_545, ) # fmt: skip # The SC-3000 with the SF-7000 Super Control Station: the unit's 64 KB of RAM is # the machine's whole memory (sf7000.py). SF7000 = Machine( "SC-3000 with SF-7000", TMS9918A, SN76489AN, "sc3000", ram_size=0x10000, japanese=True, has_th=False, reset_button=False, mapper_registers=False, disk_unit=True, ) # fmt: skip MARK_III = Machine("Mark III", SEGA_315_5124, SEGA_VDP_PSG, "sms", japanese=True, has_th=False) MARK_III_FM = Machine( "Mark III with FM Unit", SEGA_315_5124, SEGA_VDP_PSG, "sms", japanese=True, has_th=False, fm="mark3", ) # fmt: skip SMS1 = Machine("Master System", SEGA_315_5124, SEGA_VDP_PSG, "sms") SMS2 = Machine("Master System II", SEGA_315_5246, SEGA_VDP_PSG, "sms", reset_button=False) SMS1_PAL = Machine("Master System (PAL)", SEGA_315_5124, SEGA_VDP_PSG, "sms", region="PAL") SMS2_PAL = Machine( "Master System II (PAL)", SEGA_315_5246, SEGA_VDP_PSG, "sms", region="PAL", reset_button=False, ) # fmt: skip SMS_JAPAN = Machine( "Master System (Japan)", SEGA_315_5124, SEGA_VDP_PSG, "sms", japanese=True, fm="japan" ) GAME_GEAR = Machine( "Game Gear", SEGA_GAME_GEAR, GAME_GEAR_PSG, "gamegear", reset_button=False, cmos_cpu=True ) GAME_GEAR_SMS_MODE = Machine( "Game Gear, SMS mode (2 ASIC)", SEGA_GAME_GEAR_SMS_MODE, GAME_GEAR_PSG, "gg-sms", reset_button=False, cmos_cpu=True, ) # fmt: skip GAME_GEAR_1ASIC_SMS_MODE = Machine( "Game Gear, SMS mode (1 ASIC)", SEGA_GAME_GEAR_1ASIC_SMS_MODE, GAME_GEAR_PSG, "gg-sms", reset_button=False, cmos_cpu=True, ) # fmt: skip # The Mega Drive running an SMS cartridge through a Power Base Converter, which # pulls the cartridge slot's /M3 low: the 68000 stays out, the Z80 runs the game, # and the 315-5313 takes Mode 4. The converter adds the pause button (NMI) and no # FM chip (smstech section 1's table). The PSG is the one inside the Mega Drive's # VDP (sn76489-python's YM7101_PSG variant). MEGA_DRIVE_PBC = Machine( "Mega Drive with Power Base Converter", SEGA_315_5313, YM7101_PSG, "md", reset_button=False, ) # fmt: skip MEGA_DRIVE_PBC_PAL = Machine( "Mega Drive with Power Base Converter (PAL)", SEGA_315_5313, YM7101_PSG, "md", region="PAL", reset_button=False, ) # fmt: skip MACHINES = { "sg1000": SG1000, "sc3000": SC3000, "sc3000pal": SC3000_PAL, "sf7000": SF7000, "mark3": MARK_III, "mark3fm": MARK_III_FM, "sms1": SMS1, "sms2": SMS2, "sms1pal": SMS1_PAL, "sms2pal": SMS2_PAL, "smsj": SMS_JAPAN, "gamegear": GAME_GEAR, "ggsms": GAME_GEAR_SMS_MODE, "ggsms1asic": GAME_GEAR_1ASIC_SMS_MODE, "megadrive-pbc": MEGA_DRIVE_PBC, "megadrive-pbc-pal": MEGA_DRIVE_PBC_PAL, } class Board: """Memory, ports and devices for one :class:`Machine`.""" def __init__(self, machine: Machine, cartridge: Cartridge | None, bios: Cartridge | None = None, sample_rate: int = 44_100, audio: bool = True, disk: bytearray | None = None) -> None: # fmt: skip self.machine = machine self.cartridge = cartridge self.bios = bios # A few SG-1000 cartridges carry RAM that replaces the console's (cartridge.py). expansion = cartridge.work_ram if cartridge is not None else None self.ram = expansion if expansion is not None else bytearray(machine.ram_size) self.ram_mask = len(self.ram) - 1 self.vdp = VDP(machine.vdp, machine.region) clock = machine.clock self.psg = SN76489(machine.psg) self.box_filter = BoxFilter(sample_rate, clock) self.io = IOChip( has_th=machine.has_th, japanese=machine.japanese, reset_button=machine.reset_button, on_th_rise=self.vdp.latch_h_counter, ) self.keyboard = SC3000Keyboard(pad1=self.io.pad1, pad2=self.io.pad2) self.disk_unit: SuperControlStation | None = None if machine.disk_unit: if bios is None: raise ValueError("the SF-7000 needs its IPL ROM (bios)") self.disk_unit = SuperControlStation(bios.image, lambda: self.cycles, disk) self.gg_ports = GameGearPorts(japanese=machine.japanese, now=lambda: self.cycles) # The FM unit: a YM2413 on the Z80's own clock (MAME 0.285 sms.cpp: XTAL # 10.738635 MHz / 3), so a T-state is one of its input clocks. self.opll = OPLL(YM2413) if machine.fm else None self.fm_filter = FMBoxFilter(sample_rate, clock) self._psg_waiting: list[tuple[float, float]] = [] self._fm_waiting: list[float] = [] #: Port $F2's two mute bits; power-on $00, the PSG alone (AudioControlPort). self.audio_control = 0 # Power-on $3E as MAME 0.285 sets it (sms_m.cpp machine_reset): with a BIOS, # only BIOS, RAM and I/O are enabled; without one, the cartridge instead. self.memory_control = 0xE0 if bios else 0xA8 self.nmi = False # latched by press_pause(); the CPU glue clears it on acceptance #: False leaves the PSG's generators unclocked (its registers still take #: writes): no samples, and much faster when only the picture or the CPU #: matters. self.audio = audio self.cycles = 0 # -- time ----------------------------------------------------------------- def advance(self, cycles: int) -> None: """Run the VDP and PSG forward by ``cycles`` CPU cycles.""" self.vdp.run(cycles) if self.audio: self.psg.run(cycles) if self.opll is not None: self.opll.run(cycles) self.cycles += cycles def take_samples(self) -> list[tuple[float, float]]: """The finished samples at the host's rate: (left, right), each 0.0-1.0.""" psg = self.box_filter.feed(self.psg.take_samples()) if self.opll is None: return psg return self._mix(psg, self.fm_filter.feed(self.opll.take_outputs())) def _mix(self, psg: list[tuple[float, float]], fm: list[float]) -> list[tuple[float, float]]: """The PSG and the FM unit into one output, as port $F2's mute bits allow. The two resamplers finish their host samples a little apart, so each side's surplus waits for the other. A third of the range each: the PSG (0 to 1) and the FM unit (-1 to 1, centred) together span 0.0-1.0. Music swings the FM unit about +-0.75 (Phantasy Star); a half each clipped it. """ self._psg_waiting += psg self._fm_waiting += fm count = min(len(self._psg_waiting), len(self._fm_waiting)) pairs = zip(self._psg_waiting[:count], self._fm_waiting[:count], strict=True) del self._psg_waiting[:count], self._fm_waiting[:count] psg_on = self.audio_control in (0, 3) fm_on = self.audio_control in (1, 3) out = [] for (left, right), level in pairs: fm_part = (1.0 + level if fm_on else 1.0) / 3 out.append( ( min(1.0, max(0.0, (left / 3 if psg_on else 0.0) + fm_part)), min(1.0, max(0.0, (right / 3 if psg_on else 0.0) + fm_part)), ) ) return out def _read_audio_control(self) -> int: """Port $F2: the mute bits written, and on the Japanese Master System bits 11, 7 and 3 of the 315-5297's counter of C-Sync pulses in bits 7-5 (Charles MacDonald, quoted on SMS Power's AudioControlPort page). One pulse a line is MAME 0.285's model (315_5124.cpp's n_csync once a line); the serrated pulses of vertical sync, if the counter sees them, are not counted. The Mark III's FM Unit has no such counter here: no source says what its bits 7-5 read. """ value = self.audio_control if self.machine.fm == "japan": count = self.vdp.lines_started value |= (count >> 11 & 1) << 7 | (count >> 7 & 1) << 6 | (count >> 3 & 1) << 5 return value @property def irq(self) -> bool: """The Z80's INT line (level): the VDP's output.""" return self.vdp.irq def press_pause(self) -> None: """The pause button: an edge on NMI (the wiki's PauseButton.pmwiki).""" if self.machine.decode != "gamegear": self.nmi = True # -- memory --------------------------------------------------------------- def _slot_device(self) -> Cartridge | None: if self.machine.decode == "sms": if self.bios is not None and not self.memory_control & MEM_BIOS: return self.bios if self.memory_control & MEM_CARTRIDGE: return None return self.cartridge def read_byte(self, address: int) -> int: unit = self.disk_unit if unit is not None: # The 8 KB ROM over the first 16 KB: "presumably mirrored twice" # (sc3000h section 3). MAME 0.285 reads zeros above the ROM instead. if address < 0x4000 and unit.rom_selected: return unit.ipl[address & 0x1FFF] return self.ram[address] if address < 0xC000: device = self._slot_device() return device.read(address) if device is not None else OPEN_BUS if self.memory_control & MEM_WORK_RAM and self.machine.decode == "sms": return OPEN_BUS return self.ram[address & self.ram_mask] def write_byte(self, address: int, value: int) -> None: if self.disk_unit is not None: # A write under the ROM lands in the RAM beneath it: the IPL's memory # test (IPL $0160) writes and reads back $0000-$3FFF with the ROM # switched out, so nothing here says otherwise. MAME drops such writes. self.ram[address] = value return if address < 0xC000: device = self._slot_device() if device is not None: device.write(address, value) return if not (self.memory_control & MEM_WORK_RAM and self.machine.decode == "sms"): self.ram[address & self.ram_mask] = value if address >= 0xFFFC and self.machine.mapper_registers: # The mapper registers sit in the RAM mirror (the wiki's Mappers.pmwiki). # Only the enabled slot's mapper takes the write, as MAME 0.285 does # (sms_m.cpp): the export BIOS pages its own ROM through these registers, # and a cartridge that saw those writes would boot with the wrong banks # (Versus, found by the compatibility sweep). No hardware source is known. if self.machine.decode != "sms": devices = (self.cartridge,) else: devices = ( self.bios if not self.memory_control & MEM_BIOS else None, self.cartridge if not self.memory_control & MEM_CARTRIDGE else None, ) for device in devices: if device is not None: device.write_register(address, value) # -- ports ------------------------------------------------------------------- # # The SC-3000 has its own decode (A7, A6 and A5). Every other machine decodes # A7, A6 and A0 (msvdp section 2): $00-$3F memory and I/O control, $40-$7F the # counters and the PSG, $80-$BF the VDP, $C0-$FF the controller ports. def _read_sc3000(self, port: int) -> int: """The SC-3000: "$C0-DF PPI ... $A0-BF VDP" (sc3000h section 4). Where both answer, "the data returned is from the PPI but has a few bits corrupted" (the PPI's, uncorrupted, here). Where neither does, the SF-7000 answers if it is there; without it the bus holds the byte the refresh cycle left, which is not modelled. """ if not port & 0x20: return self.keyboard.read(port) if not port & 0x40: return self.vdp.read_status() if port & 1 else self.vdp.read_data() if self.disk_unit is not None: return self.disk_unit.read(port) return OPEN_BUS def _write_sc3000(self, port: int, value: int) -> None: """The SC-3000: "data written goes to all devices that are enabled" (sc3000h section 4); the SF-7000 takes $E0-$FF.""" if not port & 0x80: self.psg.write(value) if not port & 0x40: if port & 1: self.vdp.write_control(value) else: self.vdp.write_data(value) if not port & 0x20: self.keyboard.write(port, value) if port >= 0xE0 and self.disk_unit is not None: self.disk_unit.write(port, value) def _read_controller_port(self, port: int) -> int: """$C0-$FF: the controller ports, and port $F2 where there is an FM unit.""" decode = self.machine.decode if port == 0xF2 and self.opll is not None: # Read whether or not the I/O chip is enabled: Phantasy Star's detection # disables it first (FMChipDetection.pmwiki). MAME 0.285 maps $F2 alone. return self._read_audio_control() if decode == "sms" and self.memory_control & MEM_IO_CHIP: return OPEN_BUS if decode in ("gamegear", "gg-sms") and port not in (0xC0, 0xC1, 0xDC, 0xDD): return OPEN_BUS # the Game Gear decodes only these (IOPortMapGG.pmwiki) if decode == "md": # "Reads from $C0 and $DC ... $C1 and $DD"; the rest of $C0-$FF is $FF # with the converter (smstech section 3). if port not in (0xC0, 0xC1, 0xDC, 0xDD): return OPEN_BUS # "Bit 5 returns 0 on a Genesis" (smstech section 4). return self.io.read_dd() & ~0x20 if port & 1 else self.io.read_dc() if decode == "gamegear": # In GG mode the EXT connector is the second pad port (GameGearPorts). if port & 1: return self.gg_ports.read_dd() return self.gg_ports.read_dc(self.io.pad1.bits()) return self.io.read_dd() if port & 1 else self.io.read_dc() def read_port(self, port: int) -> int: port &= 0xFF decode = self.machine.decode if decode == "sc3000": return self._read_sc3000(port) if decode == "gamegear" and port <= 0x06: return self.gg_ports.read(port) if port < 6 else OPEN_BUS if port < 0x40: return OPEN_BUS # SMS1: open bus; SMS2: $FF (IOPortMap.pmwiki) if port < 0x80: if decode == "sg1000": return OPEN_BUS # the TMS9918A has no counters to read return self.vdp.read_h_counter() if port & 1 else self.vdp.read_v_counter() if port < 0xC0: return self.vdp.read_status() if port & 1 else self.vdp.read_data() return self._read_controller_port(port) def write_port(self, port: int, value: int) -> None: port &= 0xFF value &= 0xFF decode = self.machine.decode if decode == "sc3000": self._write_sc3000(port, value) return if decode == "gamegear" and port <= 0x06: if port == 6: self.psg.write_stereo(value) else: self.gg_ports.write(port, value) return if port < 0x40: # $3E/$3F on the SMS. The SG-1000 has nothing here, and neither does the # Game Gear in GG mode (MAME maps only $00-$06 in that view). if decode == "sms": if port & 1: self.io.write_control(value) else: self.memory_control = value elif decode in ("gg-sms", "md") and port & 1: # The Mega Drive's $3E: "Bits 7, 6, 5, 3, and 2 have no effect on a # Genesis, or a Genesis with a PBC" (smstech section 3), and bit 4, # work RAM, is not modelled off. self.io.write_control(value) return if port < 0x80: self.psg.write(value) elif port < 0xC0: if port & 1: self.vdp.write_control(value) else: self.vdp.write_data(value) elif self.opll is not None and port in (0xF0, 0xF1): self.opll.write(port & 1, value) elif self.opll is not None and port == 0xF2: # The Mark III's FM Unit forces bit 1 to 0: the PSG and FM are # exclusive there (AudioControlPort.pmwiki; ApolloBoy's 2020 test reads # back $01 after $03). self.audio_control = value & (0x01 if self.machine.fm == "mark3" else 0x03)