pcengine_rust/sockets.rs
1//! The sockets: narrow traits an add-on crate implements to plug into this
2//! board (`sockets.py`; the reference's docs/sockets.md).
3//!
4//! `pcenginecd-rust` and `supergrafx-rust` depend on this crate and never copy
5//! from it, as the reference's add-ons pin the Python board. Test-only fakes
6//! for each socket live in `src/fake_devices.rs`; the base board implements
7//! only what it uses.
8//!
9//! Numbering follows docs/sockets.md.
10//!
11//! 1. `CardSlot` / `Card` the HuCard slot
12//! 2. `PortDevice` the expansion port (EXT BUS)
13//! 3. `PageHandler` one decode for every bus master (the page table is in pagetable.rs)
14//! 4. `BoardPins::hold` bus timing: wait states go through the board
15//! 5. `PortDevice::catch_up` clock domains: run up to `mclk`, callable inside an access
16//! 6. `IrqLine` interrupt levels, one bit per source, wired-OR
17//! 7. `PixelPath` per-line 9-bit pixels between the VDC(s) and the VCE
18//! 8. `VideoTiming` one record per line
19//! 9. `AudioSource` a source with a changeable rate and gain
20//! 10. `ResetKind` reset events
21//! 11. `ControllerPort` the pad port
22//! 12. Instances `Vdc`, `Vce`, `Psg` hold no module state
23//!
24//! Differences forced by Rust:
25//!
26//! - **`BoardPins` is handed to a device at every call**, not once by `bind`.
27//! The reference's devices keep the board's IRQ2 line and its `hold`
28//! callable; a Rust device cannot hold a reference into the board that owns
29//! it, so each access, `catch_up` and `reset` gets `&mut BoardPins`: the
30//! IRQ2 line, `hold`, the VDC instances (the SuperGrafx's VPC decodes their
31//! page and steers to either), the opcode of the instruction being run (the
32//! VPC steers only `ST0`-`ST2`) and, for the port device and the pixel
33//! path, the card in the slot (a CD unit answers a Super System Card's id
34//! registers from the card). The reference's add-ons reach the same things
35//! through references they were built with.
36//! - **A device that is two things in the reference is one trait object
37//! here.** The reference's `VideoPage` and `Vpc` share state by reference
38//! (one claims the VDC pages, the other is the pixel path); here `PixelPath`
39//! may also claim pages. The CD unit's CD-DA and ADPCM players, appended to
40//! `board.audio_sources` in the reference, are answered by
41//! `PortDevice::audio_sources`, mixed after the PSG and before the board's
42//! own list, which is the reference's order (PSG, CD-DA, ADPCM).
43//! - **Save states** cannot walk an object graph: every socket trait carries
44//! `DeviceState` (bytes out, bytes in, an identity for media), which the
45//! reference gets from `register_package`.
46//! - **Pad input**: the reference's host keeps the pad object and sets
47//! `pad.pressed`; here the board owns the device, so `ControllerPort` has
48//! `set_pressed(port, mask)`.
49
50use std::any::Any;
51use std::collections::BTreeSet;
52
53use serde::{Deserialize, Serialize};
54
55use crate::vdc::Vdc;
56
57// --- 10. Reset ---------------------------------------------------------------------------------
58
59/// The PC Engine has no reset button or reset instruction on the console itself; a
60/// CD unit is reset by a register write inside the add-on (docs/sockets.md). `Button` exists for
61/// the Duo/Shuttle-class consoles (unverified).
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
63pub enum ResetKind {
64 PowerOn,
65 Button,
66}
67
68// --- 6. Interrupts -----------------------------------------------------------------------------
69
70/// A wired-OR level with one bit per source (never a max).
71///
72/// The line is high while any source holds it; a source lowers its own bit when acknowledged.
73#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
74pub struct IrqLine {
75 pub name: String,
76 sources: BTreeSet<String>,
77}
78
79impl IrqLine {
80 pub fn new(name: &str) -> IrqLine {
81 IrqLine {
82 name: name.to_string(),
83 sources: BTreeSet::new(),
84 }
85 }
86
87 pub fn set(&mut self, source: &str, level: bool) {
88 if level {
89 if !self.sources.contains(source) {
90 self.sources.insert(source.to_string());
91 }
92 } else {
93 self.sources.remove(source);
94 }
95 }
96
97 pub fn level(&self) -> bool {
98 !self.sources.is_empty()
99 }
100
101 pub fn sources(&self) -> &BTreeSet<String> {
102 &self.sources
103 }
104}
105
106// --- 3 and 4. The decode and bus timing, seen from a device --------------------------------------
107
108/// What the board hands a card, a port device or the pixel path with every call.
109pub struct BoardPins<'a> {
110 /// The shared IRQ2 level (HuCard, expansion port, CD ADPCM): the device sets its own bit.
111 pub irq2: &'a mut IrqLine,
112 pub(crate) held: &'a mut i64,
113 /// The board's VDC instances (`machine.vdc_count` of them): the SuperGrafx's VPC claims
114 /// their pages and steers each access to one. A device makes its accesses of a VDC's port
115 /// with `vdc_read` and `vdc_write`, not by calling `Vdc::read` and `write` here, so that the
116 /// board's wait reaches them (issue 0004, `VdcAccess`).
117 pub vdcs: &'a mut [Vdc],
118 pub(crate) access: &'a mut VdcAccess,
119 /// The opcode of the instruction the CPU is running (`Pins::opcode`; 0 with no CPU): the
120 /// VPC steers only `ST0`-`ST2`, which the bus cannot tell from stores to `$FF:0000/2/3`.
121 pub opcode: u8,
122 /// The card in the slot, for the port device and the pixel path (`None` for the card's own
123 /// calls and for an empty slot).
124 pub card: Option<&'a mut (dyn Card + 'static)>,
125}
126
127impl BoardPins<'_> {
128 /// Stretch the current CPU cycle by this many master clocks (RDY held low), applied by the
129 /// board once the access returns.
130 pub fn hold(&mut self, clocks: i64) {
131 *self.held += clocks;
132 }
133
134 /// VDC `index`'s `read(offset, mclk)`, through the board's wait (`VdcAccess`).
135 pub fn vdc_read(&mut self, index: usize, offset: u32, mclk: i64) -> u8 {
136 self.access.read(self.vdcs, index, offset, mclk)
137 }
138
139 /// VDC `index`'s `write(offset, value, mclk)`, through the board's wait (`VdcAccess`).
140 pub fn vdc_write(&mut self, index: usize, offset: u32, value: u8, mclk: i64) {
141 self.access.write(self.vdcs, index, offset, value, mclk);
142 }
143}
144
145/// The VDC accesses of one decode, for the board's wait (issue 0004).
146///
147/// In the reference a VDC access that has to wait calls the board (`Board._serve_vram`), which
148/// runs every device event by event, the line clock and the pixel path included, until the
149/// access is served, and the access then goes on; a device that touches two VDCs in one access
150/// (the lockstep pixel path writes both on `ST0`-`ST2`) touches the second after the first's
151/// wait. A Rust device cannot be called again by the board while it is in the middle of an
152/// access, so the access *stops* there instead (vdc/chip.rs, `Vdc::serve_wanted`): every later
153/// VDC access of the decode is skipped (it answers $FF to a device whose access is thrown
154/// away), the board serves the chip, and the board makes the whole decode again. In the new
155/// pass the accesses made before the stop are not made twice: their results are handed back
156/// from the log, in order; the stopped access is made at the time the wait ended; the later
157/// ones are made as the reference makes them after its wait, with the device's own `mclk`.
158/// This asks of a device that an access whose VDC access stops changes nothing of its own
159/// (the VPC's and the lockstep devices' do not); a device's decode is deterministic.
160#[derive(Clone, Debug, Default)]
161pub struct VdcAccess {
162 /// The results of the VDC accesses of this decode, in order (0 for a write).
163 log: Vec<u8>,
164 /// How many of `log` this pass has handed back.
165 cursor: usize,
166 /// The VDC whose access stopped in this pass.
167 stopped: Option<usize>,
168 /// The VDC served and the time its stopped access is made at in the next pass.
169 again: Option<(usize, i64)>,
170}
171
172impl VdcAccess {
173 /// A new decode.
174 pub(crate) fn begin(&mut self) {
175 self.log.clear();
176 self.cursor = 0;
177 self.stopped = None;
178 self.again = None;
179 }
180
181 /// The VDC whose access stopped to wait in the pass just made, if any.
182 #[inline]
183 pub(crate) fn stopped(&self) -> Option<usize> {
184 self.stopped
185 }
186
187 /// The next pass of the decode, after VDC `index` was served at `at`.
188 pub(crate) fn again(&mut self, index: usize, at: i64) {
189 self.cursor = 0;
190 self.stopped = None;
191 self.again = Some((index, at));
192 }
193
194 /// `None` to make the access now (at the time it should be made at), or the answer to hand
195 /// back without making it.
196 #[inline]
197 fn enter(&mut self, index: usize, mclk: &mut i64) -> Option<u8> {
198 if self.stopped.is_some() {
199 return Some(0xFF); // after a stop: made in the next pass
200 }
201 if self.cursor < self.log.len() {
202 let value = self.log[self.cursor];
203 self.cursor += 1;
204 return Some(value); // made before a stop in an earlier pass
205 }
206 if let Some((served, at)) = self.again.take() {
207 debug_assert_eq!(
208 served, index,
209 "the stopped access comes first after the log"
210 );
211 *mclk = at;
212 }
213 None
214 }
215
216 #[inline]
217 fn leave(&mut self, vdc: &Vdc, index: usize, value: u8) -> u8 {
218 if vdc.serve_wanted {
219 self.stopped = Some(index);
220 return 0xFF;
221 }
222 self.log.push(value);
223 self.cursor += 1;
224 value
225 }
226
227 pub(crate) fn read(
228 &mut self,
229 vdcs: &mut [Vdc],
230 index: usize,
231 offset: u32,
232 mut mclk: i64,
233 ) -> u8 {
234 if let Some(value) = self.enter(index, &mut mclk) {
235 return value;
236 }
237 let value = vdcs[index].read(offset, mclk);
238 self.leave(&vdcs[index], index, value)
239 }
240
241 pub(crate) fn write(
242 &mut self,
243 vdcs: &mut [Vdc],
244 index: usize,
245 offset: u32,
246 value: u8,
247 mut mclk: i64,
248 ) {
249 if self.enter(index, &mut mclk).is_some() {
250 return;
251 }
252 vdcs[index].write(offset, value, mclk);
253 self.leave(&vdcs[index], index, 0);
254 }
255}
256
257/// A `BoardPins` with no board behind it: for a device's own tests (this crate's and an
258/// add-on's), which call its `read`, `write` and `catch_up` directly.
259#[derive(Default)]
260pub struct DetachedPins {
261 pub irq2: IrqLine,
262 pub held: i64,
263 pub vdcs: Vec<Vdc>,
264 pub opcode: u8,
265 pub access: VdcAccess,
266}
267
268impl DetachedPins {
269 pub fn pins(&mut self) -> BoardPins<'_> {
270 BoardPins {
271 irq2: &mut self.irq2,
272 held: &mut self.held,
273 vdcs: &mut self.vdcs,
274 access: &mut self.access,
275 opcode: self.opcode,
276 card: None,
277 }
278 }
279}
280
281/// What a save state needs of a socket's device (the reference walks the object graph).
282pub trait DeviceState {
283 /// Everything of the device that changes as the console runs.
284 fn save_state(&self) -> Vec<u8> {
285 Vec::new()
286 }
287
288 /// Put the device in a saved state. A device without state accepts only an empty one.
289 fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
290 if data.is_empty() {
291 Ok(())
292 } else {
293 Err("a state for a device that keeps none".to_string())
294 }
295 }
296
297 /// What the device is and which media it holds (a card's ROM by its SHA-1, a disc by its
298 /// table of contents): a state is refused by a system whose device answers otherwise.
299 fn state_identity(&self) -> String {
300 String::new()
301 }
302}
303
304/// Anything a range of 256-byte pages can be claimed by.
305///
306/// `address` is the 21-bit physical address after the MMU; `mclk` is the master-clock time of
307/// the access, so a device may run itself up to it inside the access (the CD unit's registers
308/// need that).
309pub trait PageHandler {
310 fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8;
311
312 fn write(&mut self, address: u32, value: u8, mclk: i64, pins: &mut BoardPins);
313}
314
315// --- 1. The HuCard slot --------------------------------------------------------------------------
316
317/// A HuCard: standard ROM, SF2, Populous, Tennokoe, a System Card, ...
318///
319/// A card is not confined to the ROM window (a Super System Card claims banks $68-$7F as RAM
320/// and the $18C1-$18C6 id registers), and a claim replaces the page's handler.
321pub trait Card: PageHandler + DeviceState {
322 /// The /CD line: a card grounds it so a CD unit can tell one is inserted.
323 /// [doc: wiki HuCard pinout]
324 fn grounds_cd(&self) -> bool;
325
326 /// Inclusive (first_page, last_page) ranges over the 8192 pages of 256 bytes.
327 fn claims(&self) -> Vec<(usize, usize)>;
328
329 fn reset(&mut self, kind: ResetKind, pins: &mut BoardPins);
330
331 /// For an add-on that knows which card it built (the CD unit and its System Card).
332 fn as_any_mut(&mut self) -> &mut dyn Any;
333}
334
335/// The slot. Empty is a real state: it answers $FF, does not ground /CD, and the I/O
336/// port's CD-sense bit follows the expansion port, not the slot (docs/sockets.md).
337#[derive(Default)]
338pub struct CardSlot {
339 pub card: Option<Box<dyn Card>>,
340}
341
342impl CardSlot {
343 pub fn new(card: Option<Box<dyn Card>>) -> CardSlot {
344 CardSlot { card }
345 }
346
347 pub fn grounds_cd(&self) -> bool {
348 self.card.as_ref().is_some_and(|card| card.grounds_cd())
349 }
350}
351
352// --- 2. The expansion port ---------------------------------------------------------------------
353
354/// The EXT BUS device: A0-A20, D0-D7, /RD, /WR, IRQ2, audio in, K7 (I/O port bit 7).
355///
356/// The video-bus pins (VD0-8, HSYNC, VSYNC, DCK, VCESEL) are not a socket until a device that
357/// uses them is found (U13).
358pub trait PortDevice: PageHandler + DeviceState {
359 /// K7: a device on the port pulls the I/O port's D7 low ("CD unit attached", C6 polarity).
360 fn present(&self) -> bool;
361
362 fn claims(&self) -> Vec<(usize, usize)>;
363
364 /// Socket 5: the device keeps its own rational ratio and remainder and runs up to `mclk`
365 /// when asked; the board asks at every advance (the reference's issue 0002).
366 fn catch_up(&mut self, mclk: i64, pins: &mut BoardPins);
367
368 fn reset(&mut self, kind: ResetKind, pins: &mut BoardPins);
369
370 /// Socket 9: the device's own mixer inputs (CD-DA, ADPCM), in a fixed order; mixed after
371 /// the PSG.
372 fn audio_sources(&mut self) -> Vec<&mut dyn AudioSource> {
373 Vec::new()
374 }
375
376 fn as_any_mut(&mut self) -> &mut dyn Any;
377}
378
379// --- 7 and 8. Pixels and per-line timing ---------------------------------------------------------
380
381/// One record per line, handed to anything that mixes or captures video.
382#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
383pub struct VideoTiming {
384 /// frame counter since power-on
385 pub frame: i64,
386 /// line index within the frame, 0 = first line after the vertical sync
387 pub line: i64,
388 /// master-clock time of the line's start (the VCE's hsync)
389 pub start_mclk: i64,
390 /// master clocks per dot: 4, 3 or 2 (VCE dot clock at the line's start)
391 pub dot_divider: i64,
392 /// 262 or 263
393 pub frame_lines: i64,
394 pub in_vsync: bool,
395}
396
397/// Where the VDC(s) meet the VCE. The default is VDC 1 straight into the VCE; the
398/// SuperGrafx's VPC replaces it, mixing two VDC lines. Line granularity, not dot.
399///
400/// Each row is the VDC's 9-bit pixel values for one line: bit 8 sprite/background, bits 7-4
401/// palette, bits 3-0 colour [hw: sgxtech], with palette index 0x000/0x100 for the
402/// backdrop/overscan colour. Returns the row handed to the VCE.
403///
404/// A path may also claim pages (the VPC decodes `$FF:0000-03FF`): `claims`, `read` and `write`
405/// default to none.
406pub trait PixelPath: DeviceState {
407 fn mix(&mut self, timing: &VideoTiming, rows: Vec<Vec<u16>>) -> Vec<u16>;
408
409 fn claims(&self) -> Vec<(usize, usize)> {
410 Vec::new()
411 }
412
413 fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8 {
414 let _ = (address, mclk, pins);
415 0xFF
416 }
417
418 fn write(&mut self, address: u32, value: u8, mclk: i64, pins: &mut BoardPins) {
419 let _ = (address, value, mclk, pins);
420 }
421
422 /// Called by `Board::reset` after the card and the port device (the reference's add-on
423 /// wrapper resets its VPC itself).
424 fn reset(&mut self, kind: ResetKind, pins: &mut BoardPins) {
425 let _ = (kind, pins);
426 }
427
428 fn as_any_mut(&mut self) -> &mut dyn Any;
429}
430
431/// VDC 1 straight into the VCE.
432#[derive(Default)]
433pub struct DirectPath;
434
435impl DeviceState for DirectPath {}
436
437impl PixelPath for DirectPath {
438 fn mix(&mut self, _timing: &VideoTiming, mut rows: Vec<Vec<u16>>) -> Vec<u16> {
439 rows.swap_remove(0)
440 }
441
442 fn as_any_mut(&mut self) -> &mut dyn Any {
443 self
444 }
445}
446
447// --- 9. Audio ----------------------------------------------------------------------------------
448
449/// A mixer input with a changeable rate and gain. The PSG is board-owned and first in the
450/// list; the CD adds CD-DA (44.1 kHz) and ADPCM (variable).
451pub trait AudioSource: DeviceState {
452 fn rate_hz(&self) -> f64;
453
454 fn gain(&self) -> f64;
455
456 /// True when the source's samples already carry its gain (the PSG): the mixer must not
457 /// apply it a second time.
458 fn applies_gain(&self) -> bool {
459 false
460 }
461
462 /// Stereo samples produced up to `mclk` since the last call.
463 fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)>;
464}
465
466// --- 11. Controllers ---------------------------------------------------------------------------
467
468/// What plugs into the pad port: a 2-button pad, a multitap, a 6-button pad, a mouse.
469///
470/// SEL and CLR are the two lines the console drives ($1000 D0 and D1); the device answers a
471/// 4-bit nibble on D3-D0. The SuperGrafx S-EXP port shares the nibble through a mux and exposes
472/// output bits 2-7 (add-on).
473pub trait ControllerPort: DeviceState {
474 fn write(&mut self, sel: bool, clr: bool);
475
476 fn read(&mut self, sel: bool, clr: bool) -> u8;
477
478 /// The host's side: the buttons held on pad `port` (0 for a pad plugged straight in, 0-4
479 /// behind a multitap), as the bit mask of pads.rs.
480 fn set_pressed(&mut self, port: usize, pressed: u16) {
481 let _ = (port, pressed);
482 }
483
484 fn as_any_mut(&mut self) -> &mut dyn Any;
485}