pcengine_rust/
fake_devices.rs

1//! Test devices for the sockets (the reference's docs/sockets.md): every trait is exercised
2//! without any add-on.
3//!
4//! The first group is the reference's `tests/fake_devices.py`, name for name (`FakeCard`,
5//! `FakePort`, `FakeAudioSource`, `FakeController`, `FakePixelPath`, `ScriptedCpu`), used by
6//! tests/sockets.rs as the reference's `tests/test_sockets.py` uses them.
7//!
8//! The second group (`LockstepCard`, `LockstepPort`, `LockstepPath`) are devices a real game
9//! can run on, so that each socket is driven in lockstep with the same device on the
10//! reference's side (`scripts/pce_trace.py` defines them again in Python, line for line): a
11//! card whose RAM replaces the work RAM and that holds the CPU now and then, a port device
12//! with an IRQ2 source of its own and an audio source at another rate, and a pixel path that
13//! decodes the VDC page for two VDCs and mixes their rows. They are not models of any hardware.
14//!
15//! Differences forced by Rust: a device gets `BoardPins` with each call (sockets.rs), so
16//! `FakePort::set_irq2` takes them; the reference's `Alarm` subclass of `FakePort` is its
17//! `alarm_due` field; `ScriptedCpu` owns the board and a `Pins` of its own, and what it was
18//! told of the interrupt lines is `pins.irq_lines()`.
19
20use std::any::Any;
21
22use huc6280::{Bus, Pins};
23use serde::{Deserialize, Serialize};
24
25use crate::board::Board;
26use crate::cards::RomCard;
27use crate::machine::{py_floordiv, HARDWARE_FIRST_PAGE, MASTER_HZ};
28use crate::sockets::{
29    AudioSource, BoardPins, Card, ControllerPort, DeviceState, PageHandler, PixelPath, PortDevice,
30    ResetKind, VideoTiming,
31};
32
33// --- the reference's fakes ------------------------------------------------------------------------
34
35/// A card claiming arbitrary page ranges; every access is recorded.
36pub struct FakeCard {
37    ranges: Vec<(usize, usize)>,
38    pub fill: u8,
39    pub grounds_cd: bool,
40    pub reads: Vec<(u32, i64)>,
41    pub writes: Vec<(u32, u8, i64)>,
42    pub resets: Vec<ResetKind>,
43}
44
45impl FakeCard {
46    pub fn new(ranges: Vec<(usize, usize)>) -> FakeCard {
47        FakeCard {
48            ranges,
49            fill: 0xAA,
50            grounds_cd: true,
51            reads: Vec::new(),
52            writes: Vec::new(),
53            resets: Vec::new(),
54        }
55    }
56}
57
58impl DeviceState for FakeCard {}
59
60impl PageHandler for FakeCard {
61    fn read(&mut self, address: u32, mclk: i64, _pins: &mut BoardPins) -> u8 {
62        self.reads.push((address, mclk));
63        self.fill
64    }
65
66    fn write(&mut self, address: u32, value: u8, mclk: i64, _pins: &mut BoardPins) {
67        self.writes.push((address, value, mclk));
68    }
69}
70
71impl Card for FakeCard {
72    fn grounds_cd(&self) -> bool {
73        self.grounds_cd
74    }
75
76    fn claims(&self) -> Vec<(usize, usize)> {
77        self.ranges.clone()
78    }
79
80    fn reset(&mut self, kind: ResetKind, _pins: &mut BoardPins) {
81        self.resets.push(kind);
82    }
83
84    fn as_any_mut(&mut self) -> &mut dyn Any {
85        self
86    }
87}
88
89/// An expansion-port device: grounds nothing, but its presence pulls the I/O port's D7 low
90/// and it can hold IRQ2.
91pub struct FakePort {
92    ranges: Vec<(usize, usize)>,
93    pub fill: u8,
94    pub present: bool,
95    pub reads: Vec<(u32, i64)>,
96    pub writes: Vec<(u32, u8, i64)>,
97    pub resets: Vec<ResetKind>,
98    pub caught_up: Vec<i64>,
99    /// The reference's `Alarm` subclass: IRQ2 is raised once `catch_up` reaches this time.
100    pub alarm_due: Option<i64>,
101}
102
103impl FakePort {
104    pub fn new(ranges: Vec<(usize, usize)>) -> FakePort {
105        FakePort {
106            ranges,
107            fill: 0xCC,
108            present: true,
109            reads: Vec::new(),
110            writes: Vec::new(),
111            resets: Vec::new(),
112            caught_up: Vec::new(),
113            alarm_due: None,
114        }
115    }
116
117    pub fn set_irq2(&mut self, level: bool, pins: &mut BoardPins) {
118        pins.irq2.set("fake-port", level);
119    }
120}
121
122impl DeviceState for FakePort {}
123
124impl PageHandler for FakePort {
125    fn read(&mut self, address: u32, mclk: i64, _pins: &mut BoardPins) -> u8 {
126        self.reads.push((address, mclk));
127        self.fill
128    }
129
130    fn write(&mut self, address: u32, value: u8, mclk: i64, _pins: &mut BoardPins) {
131        self.writes.push((address, value, mclk));
132    }
133}
134
135impl PortDevice for FakePort {
136    fn present(&self) -> bool {
137        self.present
138    }
139
140    fn claims(&self) -> Vec<(usize, usize)> {
141        self.ranges.clone()
142    }
143
144    fn catch_up(&mut self, mclk: i64, pins: &mut BoardPins) {
145        self.caught_up.push(mclk);
146        if self.alarm_due.is_some_and(|due| mclk >= due) {
147            self.set_irq2(true, pins);
148        }
149    }
150
151    fn reset(&mut self, kind: ResetKind, _pins: &mut BoardPins) {
152        self.resets.push(kind);
153    }
154
155    fn as_any_mut(&mut self) -> &mut dyn Any {
156        self
157    }
158}
159
160#[derive(Default)]
161pub struct FakeAudioSource;
162
163impl DeviceState for FakeAudioSource {}
164
165impl AudioSource for FakeAudioSource {
166    fn rate_hz(&self) -> f64 {
167        44100.0
168    }
169
170    fn gain(&self) -> f64 {
171        0.5
172    }
173
174    fn take_samples(&mut self, _mclk: i64) -> Vec<(i32, i32)> {
175        vec![(1, -1)]
176    }
177}
178
179/// Records SEL/CLR and answers a fixed nibble.
180pub struct FakeController {
181    pub nibble: u8,
182    pub writes: Vec<(bool, bool)>,
183}
184
185impl FakeController {
186    pub fn new(nibble: u8) -> FakeController {
187        FakeController {
188            nibble,
189            writes: Vec::new(),
190        }
191    }
192}
193
194impl DeviceState for FakeController {}
195
196impl ControllerPort for FakeController {
197    fn write(&mut self, sel: bool, clr: bool) {
198        self.writes.push((sel, clr));
199    }
200
201    fn read(&mut self, _sel: bool, _clr: bool) -> u8 {
202        self.nibble
203    }
204
205    fn as_any_mut(&mut self) -> &mut dyn Any {
206        self
207    }
208}
209
210/// Replaces 'VDC 1 straight into the VCE' by mixing two rows: the second wins where its
211/// pixel is non-zero (a stand-in for the SuperGrafx's VPC).
212#[derive(Default)]
213pub struct FakePixelPath {
214    pub lines_seen: usize,
215    pub timings: Vec<VideoTiming>,
216    pub row_counts: Vec<usize>,
217}
218
219fn second_wins(mut rows: Vec<Vec<u16>>) -> Vec<u16> {
220    if rows.len() == 1 {
221        return rows.swap_remove(0);
222    }
223    rows[0]
224        .iter()
225        .zip(rows[1].iter())
226        .map(|(&a, &b)| if b != 0 { b } else { a })
227        .collect()
228}
229
230impl DeviceState for FakePixelPath {}
231
232impl PixelPath for FakePixelPath {
233    fn mix(&mut self, timing: &VideoTiming, rows: Vec<Vec<u16>>) -> Vec<u16> {
234        self.lines_seen += 1;
235        self.timings.push(*timing);
236        self.row_counts.push(rows.len());
237        second_wins(rows)
238    }
239
240    fn as_any_mut(&mut self) -> &mut dyn Any {
241        self
242    }
243}
244
245/// Drives a board's bus the way the core does: one callback per CPU cycle.
246pub struct ScriptedCpu {
247    pub board: Board,
248    pub pins: Pins,
249}
250
251impl ScriptedCpu {
252    #[allow(clippy::field_reassign_with_default)] // `Pins` has private fields
253    pub fn new(mut board: Board, high_speed: bool) -> ScriptedCpu {
254        let mut pins = Pins::default();
255        pins.high_speed = high_speed;
256        pins.set_irq_disable(board.cpu_io.irq.disable);
257        board.deliver_lines(Some(&mut pins), true);
258        ScriptedCpu { board, pins }
259    }
260
261    pub fn read(&mut self, address: u32) -> u8 {
262        self.board.read(address, &mut self.pins)
263    }
264
265    pub fn write(&mut self, address: u32, value: u8) {
266        self.board.write(address, value, &mut self.pins);
267    }
268
269    pub fn idle(&mut self, cycles: usize) {
270        for _ in 0..cycles {
271            self.board.idle(None, &mut self.pins);
272        }
273    }
274}
275
276// --- devices a game can run on, for the lockstep gate -----------------------------------------------
277
278fn decode<T: for<'a> Deserialize<'a>>(data: &[u8]) -> Result<T, String> {
279    bincode::deserialize(data).map_err(|error| format!("a test device's state: {error}"))
280}
281
282/// Socket 1 (and 3, 4): a ROM card that also claims banks $F8-$FB, so the work RAM is the
283/// card's, and that holds the CPU for 3 master clocks on every 4096th write to it.
284pub struct LockstepCard {
285    rom: RomCard,
286    pub ram: Vec<u8>,
287    pub writes: u64,
288}
289
290impl LockstepCard {
291    pub fn new(data: &[u8]) -> Result<LockstepCard, String> {
292        Ok(LockstepCard {
293            rom: RomCard::new(data)?,
294            ram: vec![0; 0x2000],
295            writes: 0,
296        })
297    }
298}
299
300impl DeviceState for LockstepCard {
301    fn save_state(&self) -> Vec<u8> {
302        bincode::serialize(&(&self.ram, self.writes)).unwrap()
303    }
304
305    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
306        (self.ram, self.writes) = decode(data)?;
307        Ok(())
308    }
309
310    fn state_identity(&self) -> String {
311        format!("LockstepCard {}", self.rom.state_identity())
312    }
313}
314
315impl PageHandler for LockstepCard {
316    fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8 {
317        if address >= 0x1F0000 {
318            return self.ram[(address & 0x1FFF) as usize];
319        }
320        self.rom.read(address, mclk, pins)
321    }
322
323    fn write(&mut self, address: u32, value: u8, _mclk: i64, pins: &mut BoardPins) {
324        if address >= 0x1F0000 {
325            self.ram[(address & 0x1FFF) as usize] = value;
326            self.writes += 1;
327            if self.writes % 4096 == 0 {
328                pins.hold(3);
329            }
330        }
331    }
332}
333
334impl Card for LockstepCard {
335    fn grounds_cd(&self) -> bool {
336        true
337    }
338
339    fn claims(&self) -> Vec<(usize, usize)> {
340        vec![(0x0000, 0x0FFF), (0x1F00, 0x1F7F)]
341    }
342
343    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {
344        self.writes = 0;
345    }
346
347    fn as_any_mut(&mut self) -> &mut dyn Any {
348        self
349    }
350}
351
352/// Socket 9: a source at 32 kHz with a gain the mixer applies, a fixed pattern.
353#[derive(Clone, Debug, Default, Serialize, Deserialize)]
354pub struct LockstepTone {
355    pub produced: i64,
356}
357
358impl DeviceState for LockstepTone {}
359
360impl AudioSource for LockstepTone {
361    fn rate_hz(&self) -> f64 {
362        32000.0
363    }
364
365    fn gain(&self) -> f64 {
366        0.25
367    }
368
369    fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)> {
370        let total = py_floordiv(mclk * 32000, MASTER_HZ);
371        let out = (self.produced..total)
372            .map(|i| {
373                (
374                    ((i * 37) % 2001 - 1000) as i32,
375                    ((i * 53) % 1501 - 750) as i32,
376                )
377            })
378            .collect();
379        self.produced = self.produced.max(total);
380        out
381    }
382}
383
384/// Sockets 2, 5, 6 and 9: a port device that claims `$FF:1800-18FF` (one register), is
385/// present (the I/O port's D7 reads low), raises IRQ2 by itself for `WIDTH` master clocks every
386/// `PERIOD`, and owns an audio source.
387pub struct LockstepPort {
388    pub register: u8,
389    pub tone: LockstepTone,
390}
391
392impl LockstepPort {
393    pub const PERIOD: i64 = 300_000;
394    pub const WIDTH: i64 = 700;
395
396    pub fn new() -> LockstepPort {
397        LockstepPort {
398            register: 0,
399            tone: LockstepTone::default(),
400        }
401    }
402}
403
404impl Default for LockstepPort {
405    fn default() -> Self {
406        LockstepPort::new()
407    }
408}
409
410impl DeviceState for LockstepPort {
411    fn save_state(&self) -> Vec<u8> {
412        bincode::serialize(&(self.register, &self.tone)).unwrap()
413    }
414
415    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
416        (self.register, self.tone) = decode(data)?;
417        Ok(())
418    }
419
420    fn state_identity(&self) -> String {
421        "LockstepPort".to_string()
422    }
423}
424
425impl PageHandler for LockstepPort {
426    fn read(&mut self, _address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
427        self.register
428    }
429
430    fn write(&mut self, _address: u32, value: u8, _mclk: i64, _pins: &mut BoardPins) {
431        self.register = value;
432    }
433}
434
435impl PortDevice for LockstepPort {
436    fn present(&self) -> bool {
437        true
438    }
439
440    fn claims(&self) -> Vec<(usize, usize)> {
441        vec![(0x1FF8, 0x1FF8)]
442    }
443
444    fn catch_up(&mut self, mclk: i64, pins: &mut BoardPins) {
445        let level = mclk >= Self::PERIOD && mclk % Self::PERIOD < Self::WIDTH;
446        pins.irq2.set("lockstep-port", level);
447    }
448
449    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {
450        self.register = 0;
451    }
452
453    fn audio_sources(&mut self) -> Vec<&mut dyn AudioSource> {
454        vec![&mut self.tone]
455    }
456
457    fn as_any_mut(&mut self) -> &mut dyn Any {
458        self
459    }
460}
461
462/// [hw: HuC6280 hardware manual] ST0, ST1, ST2 are opcodes $03, $13, $23.
463pub const ST_OPCODES: [u8; 3] = [0x03, 0x13, 0x23];
464
465/// Sockets 3, 7, 8 and 12, on a machine row with two VDCs: the path claims the VDC pages; a
466/// write made by `ST0`-`ST2` goes to both VDCs, any other write to the first only; a read is
467/// the first VDC's, and a status read also reads (and so acknowledges) the second's. The mix
468/// is `FakePixelPath`'s: the second VDC's pixel wins where it is not zero.
469#[derive(Default)]
470pub struct LockstepPath {
471    pub lines_seen: u64,
472}
473
474impl DeviceState for LockstepPath {
475    fn save_state(&self) -> Vec<u8> {
476        bincode::serialize(&self.lines_seen).unwrap()
477    }
478
479    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
480        self.lines_seen = decode(data)?;
481        Ok(())
482    }
483
484    fn state_identity(&self) -> String {
485        "LockstepPath".to_string()
486    }
487}
488
489impl PixelPath for LockstepPath {
490    fn mix(&mut self, _timing: &VideoTiming, rows: Vec<Vec<u16>>) -> Vec<u16> {
491        self.lines_seen += 1;
492        second_wins(rows)
493    }
494
495    fn claims(&self) -> Vec<(usize, usize)> {
496        vec![(HARDWARE_FIRST_PAGE, HARDWARE_FIRST_PAGE + 3)]
497    }
498
499    fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8 {
500        let port = address & 3;
501        let value = pins.vdcs[0].read(port, mclk);
502        if port == 0 {
503            pins.vdcs[1].read(port, mclk);
504        }
505        value
506    }
507
508    fn write(&mut self, address: u32, value: u8, mclk: i64, pins: &mut BoardPins) {
509        let port = address & 3;
510        pins.vdcs[0].write(port, value, mclk);
511        if ST_OPCODES.contains(&pins.opcode) {
512            pins.vdcs[1].write(port, value, mclk);
513        }
514    }
515
516    fn as_any_mut(&mut self) -> &mut dyn Any {
517        self
518    }
519}