// SPDX-License-Identifier: MIT //! The Starpath (Arcadia) Supercharger, AR: 6K of RAM, a 2K BIOS ROM, a cassette input. //! //! Main source: Kevin Horton's mapper document, sections "AR (Starpath //! Supercharger)" and "Supercharger Tape Format" (DOC, cited "Horton"; lines //! 757-1240 of `reference/docs/kevtris-atari-2600-mappers.txt`), written from his //! FPGA console running the real BIOS. Where Horton is silent, MAME 0.285's //! BSD-3-Clause `src/devices/bus/vcs/scharger.cpp` (copyright Fabio Priuli; //! notice in NOTICE) is cited as "MAME scharger.cpp". The Supercharger's BIOS is //! Starpath's firmware: never shipped here; a player supplies it (`bios`). //! //! **Registers** (DOC Horton): $1FF8 is the control register `DDDB BBWE` //! (write delay, bank mode, RAM write enable, ROM power off) and $1FF9 the tape //! input (bit 0; the other bits read 0). Neither can be written directly: the //! cartridge latches the low byte of the address of any access to $1000-$10FF, //! and an access to $1FF8 then copies the latch into the control register ("THERE //! IS NO UPPER LIMIT on the number of cycles" between the two). //! //! **RAM writes** (DOC Horton): after an access to $1000-$10FF, the cartridge //! counts changes of the 13 address lines ("BUS TRANSITIONS", not cycles: a //! repeated address does not count); on the fifth it drives the latched byte onto //! the data bus and into RAM at that address, if writes are enabled and RAM is //! mapped there. The CPU reads the byte the cartridge drives. With writes //! enabled, every access to $1000-$10FF re-latches, so reading there corrupts RAM //! (Horton). The count is cancelled by a control-register access (MAME //! scharger.cpp:137-138) and by a tape read (MAME scharger.cpp:214-215). //! //! **Bank modes** (DOC Horton's table): the two 2K halves of the window show //! RAM bank 3/ROM, 1/ROM, 3/1, 1/3, 3/ROM, 2/ROM, 3/2, 2/3 for modes 0-7. A read //! of the ROM half with the ROM powered off floats (HYPOTHESIS: the PNP switch //! cuts the ROM's supply, so nothing drives the bus; MAME returns $FF). Power-on: //! mode 0, writes disabled, the ROM on (HYPOTHESIS; MAME scharger.cpp:76-86). //! //! **Loading.** Two ways: //! //! - **From tape** with the player's BIOS (`bios` 2K) and a cassette input //! (`tape_level(t) -> bool`, t in CPU cycles). This path is built from //! Horton's description and is UNTESTED here: no BIOS is available to this //! project (docs/claims.md). //! - **"Fast load"**, the shortcut every emulator offers (labelled as such, not //! hardware): the load's pages are copied into RAM as its page table says, and //! the BIOS ROM is replaced by a short stub this project wrote from //! Horton's description of how the BIOS ends a load (copy `CMP $FFF8; JMP //! start` into RIOT RAM at $FA, latch the control byte through $F0xx, jump //! there). Multi-load games run //! their first load only: a later load is requested from the BIOS, whose entry //! points are not documented in any permitted source (HYPOTHESIS-free gap, //! recorded in docs/claims.md). //! //! **The image format** (`.bin`, 8,448 bytes per load; DOC: the dumps //! themselves, every one self-checking): 32 pages of 256 bytes of tape data in //! load order (unused pages padded), then at $2000 the tape header (Horton's //! eight bytes: start address, control word, page count, header checksum, //! multi-load number, progress-bar speed), the page table (Horton's block //! locations, `000B BBRR`) at $2010, and the pages' checksums at $2040. Every //! header and page in the local dumps sums to $55 as Horton says, which is how //! the layout was confirmed. //! //! Rust-forced differences (a2600-python `cartridge/supercharger.py` at //! 28fb095): `parse_load`'s dictionary is [`LoadInfo`]; the constructor returns //! `Result`; the tape input is a boxed closure, kept from the loading console //! when a state is restored (it is the host's). use serde::{Deserialize, Serialize}; use super::connector::{Cartridge, Restore}; use crate::cartridge_state; pub const LOAD_SIZE: usize = 8448; // DOC Horton's Supercharger format: 8K of pages + a 256-byte header block pub const HEADER: usize = 0x2000; // DOC Horton: the tape header follows the 8K of pages pub const WRITE_TRANSITIONS: i32 = 5; // DOC Horton: "it waits 5 address bus transitions" /// Bank mode -> (bank at $1000, bank at $1800); 0-2 are RAM banks 1-3, 3 the ROM /// (DOC Horton's bank-mode table). pub const BANK_MODES: [(usize, usize); 8] = [(2, 3), (0, 3), (2, 0), (0, 2), (2, 3), (1, 3), (2, 1), (1, 2)]; /// One load's header fields (`parse_load`'s dictionary). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LoadInfo { pub start: u16, pub control: u8, pub pages: u8, pub multiload: u8, } /// One load's header and its pages as (block location, 256 bytes). pub fn parse_load(image: &[u8], load: usize) -> Result<(LoadInfo, Vec<(u8, Vec)>), String> { let base = load * LOAD_SIZE; let header = image .get(base + HEADER..(base + HEADER + 8).min(image.len())) .unwrap_or(&[]); if header.len() < 8 || header.iter().map(|&b| b as u32).sum::() & 0xFF != 0x55 { return Err(format!("Supercharger load {load}: header checksum is not $55")); } let info = LoadInfo { start: header[0] as u16 | (header[1] as u16) << 8, control: header[2], pages: header[3], multiload: header[5], }; let mut pages = Vec::new(); for i in 0..info.pages as usize { let byte = |k: usize| image.get(k).copied().ok_or_else(|| format!("index {k} out of range")); let location = byte(base + HEADER + 0x10 + i)?; let end = image.len(); let data = &image[(base + i * 256).min(end)..(base + (i + 1) * 256).min(end)]; let check = byte(base + HEADER + 0x40 + i)?; let sum = location as u32 + check as u32 + data.iter().map(|&b| b as u32).sum::(); if sum & 0xFF != 0x55 { return Err(format!("Supercharger load {load}: page {i} checksum is not $55")); } pages.push((location, data.to_vec())); } Ok((info, pages)) } /// 2K standing in for the BIOS at $1800-$1FFF (this project's code, not Starpath's). /// /// It does what Horton describes the BIOS doing at the end of a load: put /// `CMP $FFF8; JMP start` in RIOT RAM at $FA-$FF (the new bank mode may /// take the ROM away from under the CPU), latch the control byte by reading /// $F0cc, and jump to $FA. pub fn fast_load_stub(start: u16, control: u8) -> Vec { let tail = [0xCD, 0xF8, 0xFF, 0x4C, (start & 0xFF) as u8, (start >> 8) as u8]; let mut code = Vec::new(); for (i, &byte) in tail.iter().enumerate() { code.extend_from_slice(&[0xA9, byte, 0x85, 0xFA + i as u8]); // LDA #byte; STA $FA+i } code.extend_from_slice(&[0xAD, control, 0xF0]); // LDA $F0cc: latch the control byte code.extend_from_slice(&[0x4C, 0xFA, 0x00]); // JMP $00FA let mut rom = code.clone(); rom.resize(0x800, 0); rom[0x7FC] = 0x00; // reset vector: $F800 rom[0x7FD] = 0xF8; rom } /// The cassette input: the level at CPU cycle `t`. pub type TapeLevel = Box bool>; #[derive(Serialize, Deserialize)] pub struct Supercharger { pub image: Vec, pub loads: usize, pub ram: Vec, #[serde(skip)] pub tape_level: Option, pub fast_load: bool, pub rom: Vec, pub latch: u8, pub transitions: i32, pub last_address: i32, pub control: u8, pub write_enable: bool, pub rom_on: bool, pub lower: usize, pub upper: usize, } impl Supercharger { pub fn new( image: &[u8], bios: Option<&[u8]>, tape_level: Option, ram_fill: u8, ) -> Result { if image.len() % LOAD_SIZE != 0 { return Err(format!("AR images are 8448 bytes per load, not {}", image.len())); } let mut ram = vec![ram_fill; 0x1800]; let fast_load = bios.is_none(); let rom = match bios { None => { let (info, pages) = parse_load(image, 0)?; for (location, data) in pages { let (bank, block) = ((location & 3) as usize, ((location >> 2) & 7) as usize); let start = bank * 0x800 + block * 0x100; ram[start..start + 0x100].copy_from_slice(&data); } fast_load_stub(info.start, info.control) } Some(bios) => { if bios.len() != 0x800 { return Err("the Supercharger BIOS is 2048 bytes".to_string()); } bios.to_vec() } }; let mut cart = Supercharger { image: image.to_vec(), loads: image.len() / LOAD_SIZE, ram, tape_level, fast_load, rom, latch: 0, transitions: WRITE_TRANSITIONS + 1, // nothing latched last_address: -1, control: 0, write_enable: false, rom_on: true, lower: 0, upper: 0, }; cart.set_control(0); Ok(cart) } pub fn set_control(&mut self, value: u8) { self.control = value; self.write_enable = value & 0x02 != 0; self.rom_on = value & 0x01 == 0; (self.lower, self.upper) = BANK_MODES[((value >> 2) & 7) as usize]; } } impl Restore for Supercharger { fn restore(&mut self, loaded: Self) { let tape_level = self.tape_level.take(); *self = loaded; self.tape_level = tape_level; } } impl Cartridge for Supercharger { fn name(&self) -> &str { "AR" } fn access(&mut self, address: u16, _value: u8, t: u64, _write: bool) -> Option { if address as i32 != self.last_address { self.last_address = address as i32; if self.transitions <= WRITE_TRANSITIONS { self.transitions += 1; } } if address & 0x1000 == 0 { return None; } if address == 0x1FF8 { self.set_control(self.latch); self.transitions = WRITE_TRANSITIONS + 1; } else if address == 0x1FF9 { self.transitions = WRITE_TRANSITIONS + 1; let level = match self.tape_level.as_mut() { Some(tape) => tape(t), None => false, }; return Some(if level { 1 } else { 0 }); } let offset = (address & 0x7FF) as usize; let bank = if address & 0x800 != 0 { self.upper } else { self.lower }; if self.transitions == WRITE_TRANSITIONS && self.write_enable && bank != 3 { self.ram[bank * 0x800 + offset] = self.latch; return Some(self.latch); } if address & 0xF00 == 0 { self.latch = (address & 0xFF) as u8; self.transitions = 0; } if bank == 3 { return if self.rom_on { Some(self.rom[offset]) } else { None }; } Some(self.ram[bank * 0x800 + offset]) } cartridge_state!(); }