# SPDX-License-Identifier: MIT # Cites MAME 0.285 bus/a7800/rom.cpp (BSD-3-Clause, Fabio Priuli) for facts where named; # no code taken. Notice: NOTICE, section 2. """The bank-switching schemes and the $4000 options (milestone 3), and the POKEY socket. Sources (docs/cartridge.md "Schemes"): Stolberg's bankswitching guide v1.40 (DOC: the wiki, tier 3) for the decoders, the A78 v4 header's vocabulary for the options (DOC); MAME 0.285's `bus/a7800/rom.cpp` read as a detector's statement where named (OBSERVED). Every cartridge sees every bus cycle (connector.py) and decodes for itself; MARIA's DMA reads arrive with ``halt`` true and read the same mapping (DOC: [MT84] Figure 2's footnote, the decoder selects during HALT). - **SuperGame** (DOC: Stolberg): 16 KiB banks; a write of n to $8000-$BFFF maps bank n there (n masked to the dump's bank count, so 64 KiB dumps mirror: HYPOTHESIS, a board's latch width would settle it; bank writes OBSERVED equal to MAME 0.285's traces); the last bank is fixed at $C000-$FFFF. $4000-$7FFF by option: nothing (undriven: "some games have nothing connected in this area", Stolberg), 16 KiB RAM, 8 KiB RAM repeated twice, bank 6 fixed ("fixed-bank", EXFIX), or a further ROM bank (144 KiB dumps: the first 16 KiB, so the switchable banks are 1-8 and the fixed one is the last: C9), or a POKEY repeating every 16 bytes (DOC: Stolberg, the A78 v4 header). - **Activision** (78AC, DOC: Stolberg): banks of 16 KiB at $A000-$DFFF chosen by a write to $FF80-$FF87 (the low three address bits; Stolberg is unsure about higher addresses: HYPOTHESIS, U16, they are ignored here; a cartridge's logic chip would settle it); $4000-$5FFF the second 8 KiB of bank 6, $6000-$7FFF its first 8 KiB, $8000-$9FFF the second 8 KiB of bank 7, $E000-$FFFF its first 8 KiB (Stolberg's layout, which is No-Intro's chip order; MAME's list stores these dumps in another order). - **Absolute** (78AB, F-18 Hornet; DOC: Stolberg): the last 32 KiB fixed at $8000; a write of 1 or 2 to $8000 maps the first or second 16 KiB at $4000 (other values and addresses: HYPOTHESIS, U17, ignored; a cartridge's logic chip would settle it). - **Mirror RAM** (Rescue on Fractalus): 2 KiB at $4000-$4FFF as eight 256-byte blocks each appearing twice (DOC: Stolberg; the dump's own accesses agree, C24). Cartridge RAM starts at zero: HYPOTHESIS (U27: a console photograph or capture of Rescue on Fractalus's attract screen would settle it). """ from __future__ import annotations from .connector import Cartridge from .description import CartDescription BANK = 0x4000 # DOC: Stolberg (16 KiB banks) # The cartridge snapshot's layout. 2: the POKEY sockets' state (pokey-python 6ed1ffa's # snapshot()) joins it; 1 (unversioned) held only the bank and the RAM. STATE_VERSION = 2 class Pokey: """A socket for pokey-python's chip (the restarted core; its docs/adoption.md is the interface): A3-A0 as the register number (DOC: 16 registers; the decode and mirrors are the cartridge's, :meth:`Banked._pokey`), the bus access first and then one ``tick()`` per Φ2 period at the cartridge port, stretched TIA/RIOT cycles, RDY repeats and MARIA's DMA periods included (DOC: [1702B] p. 29, C22; during DMA, U10; docs/timing.md "Φ2 periods at the cartridge port"; the board's ``_period_end``). The chip starts as ``POKEY()`` leaves it (every register and counter 0: pokey-python's choice, the chip has no defined power-on state). Not wired: /IRQ (no licensed dump is known to connect it; the A78 v4 header's interrupt field names it for homebrew, and which POKEY its "pokey1" bit means is not settled here), the pot pins (unconnected on a 7800 cartridge: the core's default, never crossing) and /KR1-/KR2 (the core's default, 0).""" def __init__(self) -> None: from pokey_python import C012294, POKEY self.chip = POKEY(C012294) def read(self, register: int) -> int: return self.chip.read(register & 0x0F) def write(self, register: int, value: int) -> None: self.chip.write(register & 0x0F, value) def tick(self) -> None: self.chip.tick() class Banked(Cartridge): """SuperGame, Activision, Absolute, linear-with-options: one class, the scheme as data.""" def __init__(self, desc: CartDescription) -> None: rom = desc.payload self.desc = desc self.name = desc.scheme self.rom = rom self.scheme = desc.scheme self.at_4000 = desc.at_4000 self.banks = max(1, len(rom) // BANK) self.bank = 0 self.ram = bytearray(0x4000 if desc.at_4000 in ("ram16", "ram8-mirror", "mirror-ram-2k") else 0) # fmt: skip self.pokeys: dict[int, Pokey] = {base: Pokey() for base in desc.pokey} self.extra = 1 if (self.scheme == "supergame" and desc.at_4000 == "rom") else 0 if self.scheme == "linear": self.base = 0x10000 - len(rom) def _pokey(self, address: int) -> tuple[Pokey | None, int]: # Decode: mirrored over $4000-$7FFF for the $4000 kind, 16 bytes at $440/$450/$800 # otherwise (DOC: the A78 v4 header's audio field, docs/cartridge.md) for base, chip in self.pokeys.items(): if base == 0x4000: if 0x4000 <= address < 0x8000: return chip, address & 0x0F elif base <= address < base + 0x10: return chip, address & 0x0F return None, 0 def access(self, address: int, data: int, read: bool, halt: bool, t: int) -> int | None: if self.pokeys and address < 0x8000: chip, register = self._pokey(address) if chip is not None: if not read: chip.write(register, data) return None if not (self.scheme == "linear" and address >= self.base): return chip.read(register) # ROM covers $4000 (the 48K and 52K bankset formats): POKEY is write-only # (DOC: the wiki's bankset page, docs/cartridge.md) if address < 0x4000: return self._linear(address) if self.scheme == "linear" and read else None scheme = self.scheme if address < 0x8000: option = self.at_4000 if option == "ram16": if read: return self.ram[address & 0x3FFF] self.ram[address & 0x3FFF] = data return None if option == "ram8-mirror": if read: return self.ram[address & 0x1FFF] self.ram[address & 0x1FFF] = data return None if option == "mirror-ram-2k": # DOC: Stolberg (C24); above $4FFF undriven if address >= 0x5000: return None index = ((address - 0x4000) >> 9) << 8 | (address & 0xFF) if read: return self.ram[index] self.ram[index] = data return None if not read: return None if scheme == "supergame": if option == "rom": return self.rom[address & 0x3FFF] if option == "fixed-bank": # DOC: Stolberg; which dumps: from the dumps (C9) return self.rom[(6 % self.banks) * BANK + (address & 0x3FFF)] return None if scheme == "activision": return self.rom[6 * BANK + ((address + 0x2000) & 0x3FFF)] if scheme == "absolute": return self.rom[self.bank * BANK + (address & 0x3FFF)] return self._linear(address) # $8000-$FFFF if scheme == "supergame": if address < 0xC000: if not read: self.bank = data % (self.banks - self.extra) return None return self.rom[(self.bank + self.extra) * BANK + (address & 0x3FFF)] return self.rom[(self.banks - 1) * BANK + (address & 0x3FFF)] if read else None if scheme == "activision": if not read: if 0xFF80 <= address <= 0xFF87: # DOC: Stolberg; $FF88 up ignored, U16 self.bank = address & 7 return None if address < 0xA000: return self.rom[7 * BANK + 0x2000 + (address & 0x1FFF)] if address < 0xE000: return self.rom[self.bank * BANK + (address - 0xA000)] return self.rom[7 * BANK + (address & 0x1FFF)] if scheme == "absolute": if not read: if address == 0x8000 and data in (1, 2): # DOC: Stolberg; the rest U17 self.bank = data - 1 return None return self.rom[0x8000 + (address - 0x8000)] return self._linear(address) if read else None def _linear(self, address: int) -> int | None: if address >= self.base: return self.rom[address - self.base] return None def tick(self) -> None: for chip in self.pokeys.values(): chip.tick() def snapshot(self) -> dict: return { "version": STATE_VERSION, "bank": self.bank, "ram": bytes(self.ram), "pokeys": {base: socket.chip.snapshot() for base, socket in self.pokeys.items()}, } def restore(self, state: dict) -> None: if state.get("version") != STATE_VERSION: raise ValueError(f"cartridge state version {state.get('version')}, " f"this board reads {STATE_VERSION}") # fmt: skip self.bank = state["bank"] self.ram[:] = state["ram"] for base, chip_state in state["pokeys"].items(): self.pokeys[base].chip.restore(chip_state) class HighScore(Cartridge): """The High Score Cartridge as a pass-through (DOC: wiki "7800 HSC technical reference", "HSC layout"): its 4 KiB ROM at $3000-$3FFF (bring your own, the 'High Score Cartridge' dump, by the table), 2 KiB of battery RAM at $1000-$17FF, and the game cartridge plugged into it for everything else. The RAM is kept in ``save_path`` (under ``~/.local/share/a7800-python/``); a fresh one starts at zero (HYPOTHESIS, U27 class: a new unit's RAM state).""" name = "High Score Cartridge" def __init__(self, rom: bytes, game: Cartridge, save_path=None) -> None: if len(rom) != 0x1000: raise ValueError("the High Score Cartridge ROM is 4 KiB") self.rom = rom self.game = game self.save_path = save_path self.ram = bytearray(0x800) if save_path is not None and save_path.exists(): self.ram[:] = save_path.read_bytes()[:0x800] def access(self, address: int, data: int, read: bool, halt: bool, t: int) -> int | None: game = self.game.access(address, data, read, halt, t) if 0x1000 <= address < 0x1800: if read: return self.ram[address - 0x1000] self.ram[address - 0x1000] = data return None if 0x3000 <= address < 0x4000: return self.rom[address - 0x3000] if read else None return game def tick(self) -> None: self.game.tick() @property def irq(self) -> bool: return self.game.irq def save(self) -> None: if self.save_path is not None: self.save_path.parent.mkdir(parents=True, exist_ok=True) self.save_path.write_bytes(bytes(self.ram)) class Bankset(Cartridge): """Banksets (DOC: the wiki's "Bankset Bankswitching", tier 3): two images, SALLY's then MARIA's, each a SuperGame or linear board; the cartridge shows MARIA's set while MARIA holds the bus (her DMA reads arrive with ``halt`` true; the wiki's switch, "until the second falling edge of PHI2" after HALT falls, lies inside the periods the board already gives MARIA). A bank-select write switches both sets. Bankset RAM (``ram32-halt``): SALLY's 16 KiB at $4000, MARIA's other 16 KiB at $4000, and SALLY's writes to $C000-$FFFF go to MARIA's RAM. A POKEY belongs to SALLY's side; where ROM covers $4000 it is write-only (all DOC: the wiki; judged against the designers' Bankset Test Suite README, DOC; which banks a RAM board's $8000 window reaches is open, U26).""" def __init__(self, desc: CartDescription) -> None: from dataclasses import replace half = len(desc.payload) // 2 at = "ram16" if desc.at_4000 == "ram32-halt" else desc.at_4000 self.desc = desc self.name = f"bankset {desc.scheme}" self.sally = Banked(replace(desc, payload=desc.payload[:half], at_4000=at, bankset=False)) self.maria = Banked(replace(desc, payload=desc.payload[half:], at_4000=at, pokey=(), bankset=False)) # fmt: skip self.bank_ram = desc.at_4000 == "ram32-halt" self.pokeys = self.sally.pokeys # for sound.py's mix def access(self, address: int, data: int, read: bool, halt: bool, t: int) -> int | None: if read: return (self.maria if halt else self.sally).access(address, data, True, halt, t) if self.bank_ram and address >= 0xC000: self.maria.ram[address & 0x3FFF] = data return None if 0x8000 <= address < 0xC000: self.maria.access(address, data, False, halt, t) return self.sally.access(address, data, False, halt, t) def tick(self) -> None: self.sally.tick() def snapshot(self) -> dict: return {"sally": self.sally.snapshot(), "maria": self.maria.snapshot()} def restore(self, state: dict) -> None: self.sally.restore(state["sally"]) self.maria.restore(state["maria"]) def build(desc: CartDescription) -> Cartridge: if desc.scheme not in ("linear", "supergame", "activision", "absolute"): raise NotImplementedError(f"scheme {desc.scheme} arrives in milestone 7") if desc.bankset: return Bankset(desc) return Banked(desc)