"""The controller ports and the Master System's I/O chip. Sources: the wiki's PeripheralPorts.pmwiki (ports $3F, $DC, $DD), RegionDetection.pmwiki, Port3E.pmwiki and IOPortMapGG.pmwiki ("the wiki" below); FluBBa's VDP test for the H counter latch ("HC change on TH 0->1"). """ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass, field # Joypad buttons as bit numbers in port $DC for pad 1 (the wiki, "Port $DC"). UP, DOWN, LEFT, RIGHT, BUTTON_1, BUTTON_2 = range(6) @dataclass class Joypad: """A standard two-button pad. ``pressed`` holds button numbers (UP ... BUTTON_2).""" pressed: set[int] = field(default_factory=set) def bits(self) -> int: """Six bits, active low: 1 = not pressed.""" return ~sum(1 << button for button in self.pressed) & 0x3F @dataclass class IOChip: """Ports $3F, $DC and $DD of the SMS I/O chip; ports $DC/$DD alone on the SG-1000. ``has_th``: the Master System has TH control via $3F; the SG-1000 and Mark III do not ("This functionality is not present on the Mark III"). ``japanese``: TH pins configured as outputs read back 0 ("bits 7,6 of port $DD are always zero"), which is how software tells a Japanese console (the wiki, "Region detection"). ``reset_button``: present on the SMS1, absent on the SMS2 (reads 1). ``on_th_rise`` is called when either TH pin goes from 0 to 1: the VDP latches its H counter then (FluBBa "HC change on TH 0->1"). """ has_th: bool = True japanese: bool = False reset_button: bool = True pad1: Joypad = field(default_factory=Joypad) pad2: Joypad = field(default_factory=Joypad) reset_pressed: bool = False control: int = 0xFF # $3F: "it defaults to an input-only state" (the wiki) on_th_rise: object = None # -- port $3F ------------------------------------------------------------- def _th_levels(self, control: int) -> tuple[int, int]: """(port A TH, port B TH): the output level when an output, else pulled high.""" a = (control >> 5) & 1 if not control & 0x02 else 1 b = (control >> 7) & 1 if not control & 0x08 else 1 return a, b def write_control(self, value: int) -> None: if not self.has_th: return before = self._th_levels(self.control) self.control = value & 0xFF after = self._th_levels(self.control) rose = (before[0] < after[0]) or (before[1] < after[1]) if rose and callable(self.on_th_rise): self.on_th_rise() # -- ports $DC and $DD ---------------------------------------------------- def read_dc(self) -> int: """Pad 1's six lines and pad 2's up/down (the wiki, "Port $DC").""" value = self.pad1.bits() | (self.pad2.bits() & 0x03) << 6 if self.has_th and not self.control & 0x01: # port A TR as an output reads back value = (value & ~0x20) | ((self.control >> 4) & 1) << 5 return value def read_dd(self) -> int: """Pad 2's other lines, reset, CONT, and the TH inputs (the wiki, "Port $DD").""" value = (self.pad2.bits() >> 2) & 0x0F if self.has_th and not self.control & 0x04: # port B TR as an output value = (value & ~0x08) | ((self.control >> 6) & 1) << 3 value |= 0 if (self.reset_button and self.reset_pressed) else 0x10 value |= 0x20 # CONT: "generally returns 1 on 8-bit hardware" th_a, th_b = self._th_levels(self.control) if self.has_th else (1, 1) if self.japanese: th_a = 0 if not self.control & 0x02 else th_a th_b = 0 if not self.control & 0x08 else th_b return value | th_a << 6 | th_b << 7 # The SC-3000's key matrix (sc3000h section 5): rows 0-6, columns PA0-PA7 then # PB0-PB3. Row 7 is the two joysticks. _KEY_ROWS = ( ("1", "Q", "A", "Z", "ENG DIER'S", ",", "K", "I", "8", None, None, None), ("2", "W", "S", "X", "SPACE", ".", "L", "O", "9", None, None, None), ("3", "E", "D", "C", "HOME CLR", "/", ";", "P", "0", None, None, None), ("4", "R", "F", "V", "INS DEL", "PI", ":", "@", "-", None, None, None), ("5", "T", "G", "B", None, "DOWN", "]", "[", "^", None, None, None), ("6", "Y", "H", "N", None, "LEFT", "CR", None, "YEN", None, None, "FUNC"), ("7", "U", "J", "M", None, "RIGHT", "UP", None, "BREAK", "GRAPH", "CTRL", "SHIFT"), ) SC3000_KEYS = { name: (row, column) for row, names in enumerate(_KEY_ROWS) for column, name in enumerate(names) if name is not None } _SHIFTED = dict(zip("!\"#$%&'()=+*<>?", "123456789-;:,./", strict=True)) def keys_for(character: str) -> tuple[str, ...]: """The keys held to type one character on the SC-3000's keyboard. Letters type as capitals unshifted, as the machine's own BASIC shows them; the shifted symbols are the ones printed on the export keyboard's keycaps. """ if character == " ": return ("SPACE",) if character in "\r\n": return ("CR",) if character in _SHIFTED: return ("SHIFT", _SHIFTED[character]) if character.islower(): return ("SHIFT", character.upper()) if character in SC3000_KEYS: return (character,) raise ValueError(f"no SC-3000 key types {character!r}") @dataclass class PPI8255: """An 8255 programmable peripheral interface in mode 0: three 8-bit ports. The control word says which ports are inputs: bit 4 port A, bit 1 port B, bit 3 port C's upper half, bit 0 its lower half. After reset every port is an input ($9B). Writing a mode word (bit 7 set) clears the output latches; a control write with bit 7 clear sets or resets one bit of port C. What the input pins read is the machine's business, so the owner asks for the latches and directions here and supplies the pins itself. Modes 1 and 2 are not modelled. """ control: int = 0x9B latches: list[int] = field(default_factory=lambda: [0, 0, 0]) @property def a_is_input(self) -> bool: return bool(self.control & 0x10) @property def b_is_input(self) -> bool: return bool(self.control & 0x02) def port_c(self, floating: int = 0xFF) -> int: """Port C's pins: the latch where a half is an output, ``floating`` where not. "When port C is configured as an output, reading it returns the last value written" (sc3000h section 5). """ value = self.latches[2] if self.control & 0x01: value = value & 0xF0 | floating & 0x0F if self.control & 0x08: value = value & 0x0F | floating & 0xF0 return value def write(self, port: int, value: int) -> None: port &= 3 if port < 3: self.latches[port] = value elif value & 0x80: self.control = value self.latches = [0, 0, 0] else: bit = 1 << (value >> 1 & 7) self.latches[2] = self.latches[2] | bit if value & 1 else self.latches[2] & ~bit @dataclass class SC3000Keyboard: """The SC-3000's 8255 and what hangs on it (sc3000h section 5). Port C bits 2-0 go "to 74LS145 to select 1 of 8 keyboard rows"; port A and the low four bits of port B read the selected row, active low, through pull-ups. Row 7 is the two joysticks, whose common pin "is LOW when the seventh keyboard row is selected ... and HIGH otherwise", so software that never touches the 8255 reads joysticks as on an SG-1000: with port C still an input its pins are pulled high. Port B's upper bits: "with no external devices attached, bits 7,6,5 return 0,1,1", and bit 4 (/CONT) is pulled up. ``keys`` holds the names of the keys held (``SC3000_KEYS``). The cassette and printer lines of port C go nowhere, and the matrix's ghost keys (three corners of a rectangle held) are left out. """ pad1: Joypad = field(default_factory=Joypad) pad2: Joypad = field(default_factory=Joypad) keys: set[str] = field(default_factory=set) ppi: PPI8255 = field(default_factory=PPI8255) @property def row(self) -> int: return self.ppi.port_c() & 7 def _columns(self) -> int: """The twelve column lines of the selected row, active low.""" row = self.row if row == 7: return self.pad1.bits() | self.pad2.bits() << 6 pressed = 0 for key in self.keys: key_row, column = SC3000_KEYS[key] if key_row == row: pressed |= 1 << column return ~pressed & 0xFFF def read(self, port: int) -> int: port &= 3 ppi = self.ppi if port == 0: return self._columns() & 0xFF if ppi.a_is_input else ppi.latches[0] if port == 1: return self._columns() >> 8 | 0x70 if ppi.b_is_input else ppi.latches[1] if port == 2: return ppi.port_c() # as an input each half floats high return 0xFF # the control word cannot be read back def write(self, port: int, value: int) -> None: self.ppi.write(port, value) CPU_CLOCK = 3_579_545 # Port $05 bits 6-7 (GearToGearCable.pmwiki). SERIAL_RATES = (4800, 2400, 1200, 300) @dataclass class GameGearPorts: """Ports $00-$06 of the Game Gear (IOPortMapGG.pmwiki; RegionDetection.pmwiki). Port $00: bit 7 is the Start button (0 = pressed), bit 6 the region (0 = Japanese). Ports $01-$05 are the Gear-to-Gear port: data, direction (1 = input), TxDATA, RxDATA and serial control (GearToGearCable.pmwiki), here with nothing plugged in. Port $06 (stereo) belongs to the PSG. No hardware source says what the unconnected pins read or how the EXT connector reaches the pad ports, so this is MAME 0.285's model (sega_md_ioport.cpp, ``gamegear_io_port_device``; sms_m.cpp ``gg_input_port_dc_r``/``dd_r``): a pin set as an output reads back its data bit, an input pin reads 1 (Genesis Plus GX agrees for port $01), and bit 7 reads back the data written. Pins PC0-PC6 are also the second pad's lines: PC0/PC1 are port $DC bits 6-7, PC2-PC5 port $DD bits 0-3, PC6 (TH) port $DD bit 7. Reset values are MAME's ``device_reset``, whose own TODO says they are unproven: data $FF, all pins inputs. The serial transmitter runs with or without a cable. Port $05 bit 0 is "1 if send buffer is occupied" (the wiki): a byte written to port $03 goes straight to the shift register when that is idle; written while a byte is going out, it waits in the buffer with the bit set until that byte's 10 bit times (start, 8 data, stop) at the rate in bits 6-7 have passed. That is MAME 0.285's rule too (``txdata_w``, ``tra_complete``), whose first byte after power-on goes out half a bit sooner. No hardware reading is pinned (open item 16). Bits 1 and 2 (byte received, error) stay 0 with nothing plugged in, and writes do not set bits 0-2 (MAME ``set_s_ctrl``). """ japanese: bool = False start_pressed: bool = False serial: bytearray = field(default_factory=lambda: bytearray(b"\xff\xff\x00\x00\x00")) # The board's count of CPU cycles (3.579545 MHz), for the transmitter. now: Callable[[], int] = lambda: 0 sending_until: int | None = None # when the byte in the shift register is out buffer_full: bool = False def read(self, port: int) -> int: if port == 0: # Bit 5 is NNTS (0 = NTSC) and bits 0-4 are meaningless, per Sega's GG # manual as quoted in MAME's gg_input_port_00_r, which reads them as 0. value = 0 if self.start_pressed else 0x80 value |= 0 if self.japanese else 0x40 return value if port == 1: return self.pins() | (self.serial[0] & 0x80) if port == 5: self._transmit() return (self.serial[4] & 0xF8) | self.buffer_full return self.serial[port - 1] def _byte_time(self) -> int: """CPU cycles for 10 bits at the rate in port $05 bits 6-7.""" return 10 * CPU_CLOCK // SERIAL_RATES[self.serial[4] >> 6] def _transmit(self) -> None: """Bring the transmitter up to now: finished bytes leave, a waiting one follows.""" now = self.now() while self.sending_until is not None and now >= self.sending_until: if self.buffer_full: self.buffer_full = False self.sending_until += self._byte_time() else: self.sending_until = None def pins(self) -> int: """PC0-PC6 as read: outputs their data bit, unconnected inputs 1.""" outputs = ~self.serial[1] & 0x7F return (self.serial[0] & outputs) | (0x7F & ~outputs) def read_dc(self, pad_bits: int) -> int: return (pad_bits & 0x3F) | (self.pins() & 0x03) << 6 def read_dd(self) -> int: pins = self.pins() # Bits 4-6: reset (none on the GG), CONT and port A TH, all 1. return 0x70 | ((pins >> 2) & 0x0F) | ((pins >> 6) & 1) << 7 def write(self, port: int, value: int) -> None: if port == 3: self._transmit() if self.sending_until is None: self.sending_until = self.now() + self._byte_time() else: self.buffer_full = True # a byte already waiting there is lost if 1 <= port <= 5: self.serial[port - 1] = value