pcengine_rust/
cards.rs

1//! HuCards: the standard ROM card, Street Fighter II', Populous and Tennokoe (`cards.py`).
2//!
3//! A card is on the CPU's physical bus: PA20 is its chip enable, so it answers banks $00-$7F (the
4//! 1 MiB window = pages 0x0000-0x0FFF); there is no header (docs/cartridge.md). Mirroring of
5//! smaller images:
6//!
7//! - 384 KiB: the first 256 KiB fills banks $00-$3F twice, the last 128 KiB fills $40-$7F four
8//!   times [emu: MAME `pce_slot.cpp` rom_map_setup `0 1 0 1 2 2 2 2`; Mednafen `huc.cpp`].
9//! - 512 KiB: $00-$3F straight, $40-$7F the upper 256 KiB twice [emu: Mednafen; MAME generic].
10//! - other power-of-two sizes: mirrored to fill the window.
11//! - anything else (768 KiB, odd homebrew sizes): U18, provisional: banks repeat modulo the image.
12//!
13//! All tier 3-4; confirmed only by games running.
14//!
15//! Differences forced by Rust: the mapper cards hold a `RomCard` where the reference subclasses
16//! it; a card's identity in a save state is the SHA-1 and length of its image, computed once
17//! when it is built (the reference hashes the bytes each time it saves); `from_path` is left to
18//! the caller (`std::fs::read`).
19
20use std::any::Any;
21
22use serde::Deserialize;
23use sha1::{Digest, Sha1};
24
25use crate::sockets::{BoardPins, Card, DeviceState, PageHandler, ResetKind};
26
27pub const BANK: usize = 8 * 1024;
28pub const WINDOW_BANKS: usize = 128; // $00-$7F
29pub const COPIER_HEADER: usize = 512;
30
31/// A 512-byte copier header is the only thing to strip (size mod 8192 = 512).
32pub fn strip_copier_header(data: &[u8]) -> &[u8] {
33    if data.len() % BANK == COPIER_HEADER {
34        &data[COPIER_HEADER..]
35    } else {
36        data
37    }
38}
39
40/// For each of the 128 banks of the window, which 8 KiB bank of the image answers.
41pub fn bank_map(rom_banks: usize) -> Vec<usize> {
42    if rom_banks == 48 {
43        // 384 KiB
44        return (0..WINDOW_BANKS)
45            .map(|b| if b < 64 { b % 32 } else { 32 + (b % 16) })
46            .collect();
47    }
48    if rom_banks == 64 {
49        // 512 KiB
50        return (0..WINDOW_BANKS)
51            .map(|b| if b < 64 { b } else { 32 + (b % 32) })
52            .collect();
53    }
54    (0..WINDOW_BANKS).map(|b| b % rom_banks).collect()
55}
56
57fn rom_identity(kind: &str, data: &[u8]) -> String {
58    let digest = Sha1::digest(data);
59    let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect();
60    format!("{kind} rom {hex} length {}", data.len())
61}
62
63fn decode<T: for<'a> Deserialize<'a>>(data: &[u8]) -> Result<T, String> {
64    bincode::deserialize(data).map_err(|error| format!("a card's state: {error}"))
65}
66
67/// The standard HuCard: ROM only, mirrored to fill the window.
68pub struct RomCard {
69    pub data: Vec<u8>,
70    map: Vec<usize>,
71    identity: String,
72}
73
74impl RomCard {
75    pub fn new(data: &[u8]) -> Result<RomCard, String> {
76        let mut data = strip_copier_header(data).to_vec();
77        if data.is_empty() {
78            return Err("an empty HuCard image; an empty slot is no card".to_string());
79        }
80        if data.len() % BANK != 0 {
81            // U18: pad a ragged image with zeros
82            data.resize(data.len() + BANK - data.len() % BANK, 0);
83        }
84        let map = bank_map(data.len() / BANK);
85        let identity = rom_identity("RomCard", &data);
86        Ok(RomCard {
87            data,
88            map,
89            identity,
90        })
91    }
92
93    /// The fork: for each of the 128 banks of the window, where in `data` it starts (the
94    /// board reads a lent image by it: board.rs, `lend_rom`).
95    pub(crate) fn bank_offsets(&self) -> [u32; WINDOW_BANKS] {
96        let mut offsets = [0; WINDOW_BANKS];
97        for (offset, bank) in offsets.iter_mut().zip(&self.map) {
98            *offset = (bank * BANK) as u32;
99        }
100        offsets
101    }
102
103    #[inline]
104    fn rom_read(&self, address: u32) -> u8 {
105        let bank = ((address >> 13) & 0x7F) as usize;
106        self.data[self.map[bank] * BANK + (address & 0x1FFF) as usize]
107    }
108}
109
110impl DeviceState for RomCard {
111    fn state_identity(&self) -> String {
112        self.identity.clone()
113    }
114}
115
116impl PageHandler for RomCard {
117    fn read(&mut self, address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
118        self.rom_read(address)
119    }
120
121    fn write(&mut self, _address: u32, _value: u8, _mclk: i64, _pins: &mut BoardPins) {
122        // a plain ROM ignores writes
123    }
124}
125
126impl Card for RomCard {
127    fn grounds_cd(&self) -> bool {
128        true // [doc: wiki HuCard pinout] a card grounds /CD
129    }
130
131    fn claims(&self) -> Vec<(usize, usize)> {
132        vec![(0x0000, 0x0FFF)]
133    }
134
135    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {}
136
137    fn as_any_mut(&mut self) -> &mut dyn Any {
138        self
139    }
140}
141
142// --- the mappers beyond plain ROM (M5) ----------------------------------------------------------
143
144/// [emu: Mednafen huc.cpp sf2_threshold] an image this big has the mapper
145pub const SF2_THRESHOLD: usize = 2048 * 1024;
146pub const SF2_FIXED: usize = 512 * 1024;
147
148/// Street Fighter II' Champion Edition (2.5 MiB) and the larger homebrew form.
149///
150/// The first 512 KiB answer banks $00-$3F; banks $40-$7F show one of the further 512 KiB pages,
151/// chosen by a write to bank $00 at $1FF0-$1FFF (the page is the low bits of the address). MAME's
152/// `pce_sf2` decodes $1FF0-$1FF3 and four pages; Mednafen decodes $1FF0-$1FFF and masks by the
153/// page count: the same for the real card. [emu: both; no manufacturer document]
154/// (docs/cartridge.md)
155pub struct Sf2Card {
156    pub data: Vec<u8>,
157    pub page_mask: usize,
158    pub page: usize,
159    identity: String,
160}
161
162impl Sf2Card {
163    pub fn new(data: &[u8]) -> Result<Sf2Card, String> {
164        let mut data = strip_copier_header(data).to_vec();
165        if data.len() < SF2_THRESHOLD {
166            return Err("an SF2 image is at least 2 MiB".to_string());
167        }
168        // whole 512 KiB pages after the fixed part
169        let pages = (data.len() - SF2_FIXED).div_ceil(SF2_FIXED);
170        // a power of two, as Mednafen rounds the image up
171        let pages = pages.next_power_of_two();
172        data.resize(SF2_FIXED * (1 + pages), 0);
173        let identity = rom_identity("Sf2Card", &data);
174        Ok(Sf2Card {
175            data,
176            page_mask: pages - 1,
177            page: 0,
178            identity,
179        })
180    }
181}
182
183impl DeviceState for Sf2Card {
184    fn save_state(&self) -> Vec<u8> {
185        bincode::serialize(&self.page).unwrap()
186    }
187
188    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
189        self.page = decode(data)?;
190        Ok(())
191    }
192
193    fn state_identity(&self) -> String {
194        self.identity.clone()
195    }
196}
197
198impl PageHandler for Sf2Card {
199    fn read(&mut self, address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
200        let offset = (address & 0xFFFFF) as usize;
201        if offset < SF2_FIXED {
202            return self.data[offset];
203        }
204        self.data[offset + self.page * SF2_FIXED] // banks $40-$7F: the chosen page
205    }
206
207    fn write(&mut self, address: u32, _value: u8, _mclk: i64, _pins: &mut BoardPins) {
208        if address & 0x1FFFF0 == 0x1FF0 {
209            // bank $00, $1FF0-$1FFF
210            self.page = (address & 0xF) as usize & self.page_mask;
211        }
212    }
213}
214
215impl Card for Sf2Card {
216    fn grounds_cd(&self) -> bool {
217        true
218    }
219
220    fn claims(&self) -> Vec<(usize, usize)> {
221        vec![(0x0000, 0x0FFF)]
222    }
223
224    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {
225        self.page = 0;
226    }
227
228    fn as_any_mut(&mut self) -> &mut dyn Any {
229        self
230    }
231}
232
233/// Populous: 32 KiB of battery RAM in banks $40-$43 (four 8 KiB banks, not mirrored);
234/// the rest as a plain card. [emu: Mednafen: detected by "POPULOUS" at $1F26; MAME `pce_populous`
235/// at $80000-$87FFF.] Power-up contents are Mednafen's $FF (U7: arbitrary for a battery RAM).
236pub struct PopulousCard {
237    pub rom: RomCard,
238    pub ram: Vec<u8>,
239    identity: String,
240}
241
242impl PopulousCard {
243    pub fn new(data: &[u8]) -> Result<PopulousCard, String> {
244        let rom = RomCard::new(data)?;
245        let identity = rom_identity("PopulousCard", &rom.data);
246        Ok(PopulousCard {
247            rom,
248            ram: vec![0xFF; 0x8000],
249            identity,
250        })
251    }
252}
253
254impl DeviceState for PopulousCard {
255    fn save_state(&self) -> Vec<u8> {
256        self.ram.clone()
257    }
258
259    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
260        if data.len() != self.ram.len() {
261            return Err("a Populous card's state of another size".to_string());
262        }
263        self.ram.copy_from_slice(data);
264        Ok(())
265    }
266
267    fn state_identity(&self) -> String {
268        self.identity.clone()
269    }
270}
271
272impl PageHandler for PopulousCard {
273    fn read(&mut self, address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
274        if (0x40..=0x43).contains(&(address >> 13)) {
275            return self.ram[(address & 0x7FFF) as usize];
276        }
277        self.rom.rom_read(address)
278    }
279
280    fn write(&mut self, address: u32, value: u8, _mclk: i64, _pins: &mut BoardPins) {
281        if (0x40..=0x43).contains(&(address >> 13)) {
282            self.ram[(address & 0x7FFF) as usize] = value;
283        }
284    }
285}
286
287impl Card for PopulousCard {
288    fn grounds_cd(&self) -> bool {
289        true
290    }
291
292    fn claims(&self) -> Vec<(usize, usize)> {
293        vec![(0x0000, 0x0FFF)]
294    }
295
296    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {}
297
298    fn as_any_mut(&mut self) -> &mut dyn Any {
299        self
300    }
301}
302
303/// Tennokoe Bank: a 512 KiB HuCard with 8 KiB of backup RAM (four 2 KiB banks) at $80000-$81FFF
304/// of the card's space (banks $40, mirrored through the 64 KiB up to $8FFFF), locked at power-up
305/// (reads $FF, writes ignored); a write of a non-zero value anywhere in $F0000-$FFFFF unlocks it, a
306/// zero locks it. [emu: MAME `pce_tennokoe`, whose own comment calls the lock "a complete guess"
307/// (U29, tier 5); none in the library, so only unit-tested.]
308pub struct TennokoeCard {
309    pub rom: RomCard,
310    pub ram: Vec<u8>,
311    pub locked: bool,
312    identity: String,
313}
314
315impl TennokoeCard {
316    pub fn new(data: &[u8]) -> Result<TennokoeCard, String> {
317        let rom = RomCard::new(data)?;
318        let identity = rom_identity("TennokoeCard", &rom.data);
319        Ok(TennokoeCard {
320            rom,
321            ram: vec![0xFF; 0x2000],
322            locked: true,
323            identity,
324        })
325    }
326}
327
328impl DeviceState for TennokoeCard {
329    fn save_state(&self) -> Vec<u8> {
330        bincode::serialize(&(&self.ram, self.locked)).unwrap()
331    }
332
333    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
334        let (ram, locked): (Vec<u8>, bool) = decode(data)?;
335        if ram.len() != self.ram.len() {
336            return Err("a Tennokoe card's state of another size".to_string());
337        }
338        self.ram = ram;
339        self.locked = locked;
340        Ok(())
341    }
342
343    fn state_identity(&self) -> String {
344        self.identity.clone()
345    }
346}
347
348impl PageHandler for TennokoeCard {
349    fn read(&mut self, address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
350        let bank = (address >> 13) & 0x7F;
351        if bank < 0x40 {
352            return self.rom.rom_read(address);
353        }
354        if bank < 0x48 {
355            return if self.locked {
356                0xFF
357            } else {
358                self.ram[(address & 0x1FFF) as usize]
359            };
360        }
361        0xFF // nothing else is decoded above the ROM
362    }
363
364    fn write(&mut self, address: u32, value: u8, _mclk: i64, _pins: &mut BoardPins) {
365        let offset = address & 0xFFFFF;
366        if (0x80000..0x90000).contains(&offset) {
367            if !self.locked {
368                self.ram[(address & 0x1FFF) as usize] = value;
369            }
370        } else if offset >= 0xF0000 {
371            self.locked = value == 0;
372        }
373    }
374}
375
376impl Card for TennokoeCard {
377    fn grounds_cd(&self) -> bool {
378        true
379    }
380
381    fn claims(&self) -> Vec<(usize, usize)> {
382        vec![(0x0000, 0x0FFF)]
383    }
384
385    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {
386        self.locked = true;
387    }
388
389    fn as_any_mut(&mut self) -> &mut dyn Any {
390        self
391    }
392}
393
394/// The card an image is: SF2 from 2 MiB up (Mednafen's threshold), Populous by its title string
395/// at $1F26, else a plain ROM. Tennokoe has no detection (no header): build it explicitly.
396pub fn make_card(data: &[u8]) -> Result<Box<dyn Card>, String> {
397    let body = strip_copier_header(data);
398    if body.len() >= SF2_THRESHOLD {
399        return Ok(Box::new(Sf2Card::new(data)?));
400    }
401    if body.len() >= 0x1F26 + 8 && &body[0x1F26..0x1F26 + 8] == b"POPULOUS" {
402        return Ok(Box::new(PopulousCard::new(data)?));
403    }
404    Ok(Box::new(RomCard::new(data)?))
405}