pcengine_rust/
board.rs

1//! The board: one timeline in master clocks, the page table, and the devices around the CPU
2//! (`board.py`).
3//!
4//! The CPU core (huc6280-rust) calls `read`, `write` and `idle` once per CPU cycle with a
5//! 21-bit physical address. **The board prices the cycle**: 12 master clocks at low speed, 3 at high
6//! speed (`pins.high_speed`), plus the VDC/VCE stretch and any `hold`, all inside the callback; it
7//! never adds `step()`'s return on top (the reference's docs/handoff-brief.md, the bus contract).
8//!
9//! Where inside a cycle a device sees the access is U21 (provisional): the base cycle elapses, then
10//! the access happens at that instant, then the stretch cycle for a VDC or VCE address elapses.
11//!
12//! Differences forced by Rust:
13//!
14//! - **The CPU owns the board** (`cpu.bus`), so the board cannot hold the CPU. What the
15//!   reference's board does to its CPU (`set_irq_lines`, `irq_disable`, reading `high_speed`)
16//!   goes through the `Pins` each bus callback is handed, at the same points of the cycle and
17//!   in the same order; `attach_cpu` is `System::new`'s. With no CPU (`advance` called on a
18//!   bare board, as the reference's tests do) the lines are tracked and nothing is delivered.
19//! - **The decode is here**: `page_read` and `page_write` turn the page table's `Handler` names
20//!   into calls (pagetable.rs).
21//! - **The constructor's keyword arguments** are the fields of `BoardOptions`, which also
22//!   carries the switches the reference keeps as class attributes (`Psg`'s, `Timer`'s).
23//! - **The pixel path** is the board's field (`pixel_path`); the capture is handed the mixed
24//!   row. **The mixer** is handed the sources in the reference's order: the PSG, the port
25//!   device's own, then `audio_sources`.
26//! - **The VDC's wait** (issue 0004): the reference's VDC calls the board's `_serve_vram` from
27//!   inside the access; here the access stops at that point and the board serves the chip and
28//!   makes the decode again (`page_read`, `page_write`, `sockets::VdcAccess`, vdc/chip.rs).
29//! - **`bus_log`** is the tap the reference's scripts make by wrapping the three callables
30//!   (`scripts/state_roundtrip.py`, `observe`): when it is `Some`, every cycle appends the same
31//!   words.
32//!
33//! **The speed fork's shortcuts** (none in the base board; each says so where it is, as "the
34//! fork"): the event horizon (`wake`, `events_at`, `horizon`, `touch`), under which a CPU cycle
35//! only moves the clock; the quiet access (`quiet_page`: work RAM, this crate's own cards, a
36//! `RomCard`'s image on loan, `lend_rom`), which skips `finish_access`; the port device's
37//! cycle (`port_catch_up` alone before the horizon); the direct pixel path in `end_row`; and
38//! the bus callbacks split into a short quiet case and the rest (`*_in_full`). All of them
39//! skip work only where the base board's would have found nothing to do: the state after
40//! every cycle is the base board's (tests/fork.rs).
41
42use huc6280::{Bus, Pins};
43
44use crate::cards::{PopulousCard, RomCard, Sf2Card, TennokoeCard};
45use crate::cpu_io::CpuIo;
46use crate::hardware_page::map_hardware_page;
47use crate::machine::{
48    Machine, ADDRESS_MASK, CPU_CLOCKS_HIGH, CPU_CLOCKS_LOW, HARDWARE_FIRST_PAGE, HSYNC_CLOCKS,
49    LINE_CLOCKS, PAGE_BITS, PC_ENGINE,
50};
51use crate::mixer::Mixer;
52use crate::mt::PythonRandom;
53use crate::pagetable::{Handler, PageTable, Ram};
54use crate::psg::{Psg, PsgSwitches};
55use crate::sockets::{
56    AudioSource, BoardPins, Card, CardSlot, ControllerPort, DirectPath, IrqLine, PixelPath,
57    PortDevice, ResetKind, VdcAccess, VideoTiming,
58};
59use crate::vce::Vce;
60use crate::vdc::Vdc;
61use crate::video::{Capture, Timeline};
62
63/// The reference's `Board(...)` arguments, with its defaults.
64pub struct BoardOptions {
65    pub machine: Machine,
66    pub card: Option<Box<dyn Card>>,
67    pub port: Option<Box<dyn PortDevice>>,
68    pub pad: Option<Box<dyn ControllerPort>>,
69    pub pixel_path: Option<Box<dyn PixelPath>>,
70    /// `None` powers up with zeros (U7, deterministic); a seed randomises RAM, VRAM, the
71    /// sprite table and the colour table reproducibly (Python's `random.Random(seed)`).
72    pub power_on_seed: Option<i64>,
73    /// The raster line at time zero (U1: the real power-up phase is not published).
74    pub start_line: i64,
75    pub start_offset: i64,
76    /// U19: see `vdc::sequencer::Sequencer::vblank_dots`.
77    pub vblank_dots: Option<i64>,
78    pub vertical_at_line_start: bool,
79    /// C7: see vdc/dma.rs.
80    pub dma_resumes: bool,
81    /// The PSG's switches (class attributes of the reference's `Psg`).
82    pub psg: PsgSwitches,
83    /// C25 (the reference's `Timer.underflow_window_mclk`).
84    pub timer_underflow_window_mclk: i64,
85}
86
87impl Default for BoardOptions {
88    fn default() -> Self {
89        BoardOptions {
90            machine: PC_ENGINE,
91            card: None,
92            port: None,
93            pad: None,
94            pixel_path: None,
95            power_on_seed: None,
96            start_line: 0,
97            start_offset: 0,
98            vblank_dots: Some(-8),
99            vertical_at_line_start: false,
100            dma_resumes: true,
101            psg: PsgSwitches::default(),
102            timer_underflow_window_mclk: 15,
103        }
104    }
105}
106
107pub struct Board {
108    pub machine: Machine,
109    pub mclk: i64,
110    pub(crate) held: i64,
111    pub(crate) lines: (bool, bool, bool),
112    /// set by the first new line
113    pub(crate) row_end: Option<i64>,
114    /// VideoTiming of the line whose row is still being drawn
115    pub(crate) row_timing: Option<VideoTiming>,
116    pub irq2: IrqLine,
117    pub vce: Vce,
118    /// One VDC instance per `machine.vdc_count` (docs/sockets.md socket 12). `vdcs[0]` is the
119    /// first; the others are run, synced and read for pixels and IRQ1 by the board, but have
120    /// no decode of their own: an add-on (the SuperGrafx's VPC) claims their pages.
121    pub vdcs: Vec<Vdc>,
122    /// The VDC accesses of the decode being made (issue 0004; sockets.rs).
123    pub(crate) vdc_access: VdcAccess,
124    pub psg: Psg,
125    pub cpu_io: CpuIo,
126    pub ram: Ram,
127    pub slot: CardSlot,
128    pub port: Option<Box<dyn PortDevice>>,
129    /// Further mixer inputs, after the PSG and the port device's own.
130    pub audio_sources: Vec<Box<dyn AudioSource>>,
131    pub mixer: Mixer,
132    pub timeline: Timeline,
133    pub capture: Capture,
134    pub pixel_path: Box<dyn PixelPath>,
135    pub pages: PageTable,
136    /// The opcode the CPU is running, as the last bus callback's `Pins` showed it.
137    pub(crate) opcode: u8,
138    /// When `Some`, every CPU cycle appends: for a read or a write `address << 8 | value`
139    /// then `mclk << 2 | kind` (0 read, 1 write); for an idle cycle `mclk << 2 | 2` alone.
140    pub bus_log: Option<Vec<u64>>,
141    /// When `Some`, every CPU cycle appends (kind, address, value, mclk): kind 0 read, 1 write,
142    /// 2 idle (address and value 0). The lockstep gate's per-cycle mode.
143    pub bus_detail: Option<Vec<(u8, u32, u8, i64)>>,
144    /// The fork's event horizon: no device has anything to do before this master clock
145    /// (`horizon`), so a CPU cycle that ends before it only moves the clock. `i64::MIN` when
146    /// it is not known (`touch`), which sends the next cycle through `run_to` as the base
147    /// board does every cycle.
148    pub(crate) wake: i64,
149    /// The horizon proper (`horizon`): `wake` is this, or "every cycle" with a device on the
150    /// expansion port, whose `catch_up` is then all a cycle before `events_at` runs.
151    pub(crate) events_at: i64,
152    /// Something outside a bus access may have left a hold or a line for the next access to
153    /// apply (the host through `board_mut()`, a port device's `catch_up`): the next access
154    /// finishes in full, whatever its page.
155    pub(crate) unsettled: bool,
156    /// The card is one of this crate's own (`card_is_plain`): its accesses finish like work
157    /// RAM's.
158    pub(crate) plain_card: bool,
159    /// The pixel path is this crate's `DirectPath` (VDC 1 straight into the VCE): `end_row`
160    /// hands the capture the VDC's row itself.
161    pub(crate) direct_path: bool,
162    /// `touch` was called: `plain_card`, `direct_path` and the loan below are decided again
163    /// when the board next runs (`decide`), after whatever the host is changing.
164    pub(crate) stale: bool,
165    /// A `RomCard`'s image, on loan to the board while it runs (`lend_rom`): the card's
166    /// `data` is empty meanwhile, and `touch` gives it back before anything can look.
167    pub(crate) rom: Vec<u8>,
168    pub(crate) rom_offsets: [u32; 128],
169    pub(crate) rom_lent: bool,
170}
171
172impl Board {
173    pub fn new(options: BoardOptions) -> Result<Board, String> {
174        let machine = options.machine;
175        let mut rng = options.power_on_seed.map(PythonRandom::new);
176
177        let vce = Vce::new(rng.as_mut());
178        let vdcs: Vec<Vdc> = (0..machine.vdc_count)
179            .map(|_| {
180                let mut vdc = Vdc::new(
181                    rng.as_mut(),
182                    options.vblank_dots,
183                    options.vertical_at_line_start,
184                    options.dma_resumes,
185                );
186                vdc.serve = true; // the reference's `serve=self._serve_vram`
187                vdc
188            })
189            .collect();
190        if vdcs.is_empty() {
191            return Err("a machine has at least one VDC".to_string());
192        }
193        let psg = Psg::new(44100.0, options.psg);
194        let mut cpu_io = CpuIo::new(machine.country_pc_engine, options.pad);
195        cpu_io.timer.underflow_window_mclk = options.timer_underflow_window_mclk;
196        let mut ram = Ram::new(machine.work_ram_bytes);
197        if let Some(rng) = rng.as_mut() {
198            for byte in ram.data.iter_mut() {
199                *byte = rng.getrandbits(8) as u8;
200            }
201        }
202        let timeline = Timeline::new(&machine, &vce, options.start_line, options.start_offset)?;
203        let capture = Capture::new(&vce);
204
205        let mut pages = PageTable::new();
206        // [hw: pcetech 3] banks $F8-$FB work RAM ($F9-$FB mirror $F8), $FF the hardware page.
207        pages.set_base(0x1F00, 0x1F7F, Handler::Ram);
208        map_hardware_page(&mut pages);
209        if let Some(card) = options.card.as_ref() {
210            for (first, last) in card.claims() {
211                pages.claim(first, last, Handler::Card)?;
212            }
213        }
214        if let Some(port) = options.port.as_ref() {
215            for (first, last) in port.claims() {
216                pages.claim(first, last, Handler::Port)?;
217            }
218        }
219        let pixel_path = options.pixel_path.unwrap_or_else(|| Box::new(DirectPath));
220        for (first, last) in pixel_path.claims() {
221            pages.claim(first, last, Handler::PixelPath)?;
222        }
223
224        let mut board = Board {
225            machine,
226            mclk: 0,
227            held: 0,
228            lines: (false, false, false),
229            row_end: None,
230            row_timing: None,
231            irq2: IrqLine::new("IRQ2"),
232            vce,
233            vdcs,
234            vdc_access: VdcAccess::default(),
235            psg,
236            cpu_io,
237            ram,
238            slot: CardSlot::new(options.card),
239            port: options.port,
240            audio_sources: Vec::new(),
241            mixer: Mixer::default(),
242            timeline,
243            capture,
244            pixel_path,
245            pages,
246            opcode: 0,
247            bus_log: None,
248            bus_detail: None,
249            wake: i64::MIN,
250            events_at: i64::MIN,
251            unsettled: true,
252            plain_card: false,
253            direct_path: false,
254            stale: true,
255            rom: Vec::new(),
256            rom_offsets: [0; 128],
257            rom_lent: false,
258        };
259        board.touch();
260        let divider = board.vce.dot_divider();
261        for vdc in board.vdcs.iter_mut() {
262            vdc.hsync(board.timeline.line_start, divider);
263            if board.timeline.line >= board.timeline.frame_lines - 3 {
264                vdc.vsync();
265            }
266        }
267        Ok(board)
268    }
269
270    /// The first VDC (the reference's `board.vdc`).
271    pub fn vdc(&mut self) -> &mut Vdc {
272        self.touch();
273        &mut self.vdcs[0]
274    }
275
276    /// The board was reached from outside a bus access (the host, a loaded state): forget the
277    /// event horizon, and let the next access finish in full. `System::board_mut`, `step`,
278    /// `run_frame` and `run_until` call it; a host that changes the board through
279    /// `system.cpu.bus` and then calls `system.cpu.step()` itself must too.
280    #[inline]
281    pub fn touch(&mut self) {
282        self.wake = i64::MIN;
283        self.events_at = i64::MIN;
284        self.unsettled = true;
285        self.stale = true;
286        if self.rom_lent {
287            self.return_rom();
288        }
289    }
290
291    /// What `touch` left to decide, at the first cycle after it (the host has finished).
292    #[cold]
293    fn decide(&mut self) {
294        self.stale = false;
295        self.plain_card = self.card_is_plain();
296        self.direct_path = self.pixel_path.as_any_mut().is::<DirectPath>();
297        self.lend_rom();
298    }
299
300    /// The fork: a `RomCard`'s read is `data[offset of the bank + offset in it]`; the board
301    /// does it itself, without the call through the card's trait, by taking the image for as
302    /// long as it runs. Nothing can tell: the card is reached only through the board
303    /// (`board_mut()` and the other ways in call `touch`, which gives the image back first),
304    /// through `&Board` (which cannot reach a card's fields), or by a port device or a
305    /// replacement pixel path through their pins, and with either there is no loan.
306    fn lend_rom(&mut self) {
307        if self.port.is_some() || !self.direct_path || self.rom_lent {
308            return;
309        }
310        let Some(card) = self.slot.card.as_mut() else {
311            return;
312        };
313        if let Some(card) = card.as_any_mut().downcast_mut::<RomCard>() {
314            self.rom_offsets = card.bank_offsets();
315            self.rom = std::mem::take(&mut card.data);
316            self.rom_lent = true;
317        }
318    }
319
320    fn return_rom(&mut self) {
321        self.rom_lent = false;
322        let rom = std::mem::take(&mut self.rom);
323        if let Some(card) = self.slot.card.as_mut() {
324            if let Some(card) = card.as_any_mut().downcast_mut::<RomCard>() {
325                card.data = rom;
326            }
327        }
328    }
329
330    /// `RomCard::read` on the lent image.
331    #[inline(always)]
332    fn rom_read(&self, address: u32) -> u8 {
333        let offset = self.rom_offsets[((address >> 13) & 0x7F) as usize];
334        self.rom[offset as usize + (address & 0x1FFF) as usize]
335    }
336
337    /// The fork: the card in the slot is this crate's own `RomCard`, `Sf2Card`, `PopulousCard`
338    /// or `TennokoeCard`, whose accesses use nothing of the `BoardPins` they are handed: no
339    /// hold, no interrupt line, no VDC. Any other card (an add-on's, a test's) may, and its
340    /// accesses finish in full.
341    fn card_is_plain(&mut self) -> bool {
342        self.slot.card.as_mut().is_some_and(|card| {
343            let card = card.as_any_mut();
344            card.is::<RomCard>()
345                || card.is::<Sf2Card>()
346                || card.is::<PopulousCard>()
347                || card.is::<TennokoeCard>()
348        })
349    }
350
351    /// The earliest master clock at which `run_to` has anything to do but the port device's
352    /// `catch_up`: the next line, the end of the row being drawn, each VDC's next event, the
353    /// timer's next tick (every tick, not only the underflow: the count is state).
354    /// `i64::MIN` (every cycle) while a VRAM DMA runs or waits, which moves words or its own
355    /// clock at every catch-up.
356    fn horizon(&self) -> i64 {
357        let mut at = self.timeline.next_line_start();
358        if let Some(row_at) = self.row_end {
359            at = at.min(row_at);
360        }
361        for vdc in self.vdcs.iter() {
362            if vdc.dma.running {
363                return i64::MIN;
364            }
365            if let Some(vdc_at) = vdc.next_event() {
366                at = at.min(vdc_at);
367            }
368        }
369        if let Some(tick_at) = self.cpu_io.timer.next_tick() {
370            at = at.min(tick_at);
371        }
372        at
373    }
374
375    /// Recompute the horizon. A device on the expansion port is promised a `catch_up` at
376    /// every advance (socket 5), so with one every cycle wakes.
377    #[inline]
378    fn look_ahead(&mut self) {
379        self.events_at = self.horizon();
380        self.wake = if self.port.is_some() {
381            i64::MIN
382        } else {
383            self.events_at
384        };
385    }
386
387    /// Mixed stereo samples (44.1 kHz) of every audio source up to the clock now.
388    pub fn take_audio(&mut self) -> Vec<(i16, i16)> {
389        let mut sources: Vec<&mut dyn AudioSource> = vec![&mut self.psg];
390        if let Some(port) = self.port.as_mut() {
391            sources.extend(port.audio_sources());
392        }
393        for source in self.audio_sources.iter_mut() {
394            sources.push(source.as_mut());
395        }
396        self.mixer.take(self.mclk, sources)
397    }
398
399    /// The buttons held on pad `port` (`ControllerPort::set_pressed`; the reference's host
400    /// sets `pad.pressed` on the object it kept).
401    pub fn set_pressed(&mut self, port: usize, pressed: u16) {
402        if let Some(device) = self.cpu_io.port.device.as_mut() {
403            device.set_pressed(port, pressed);
404        }
405    }
406
407    // -- the decode -------------------------------------------------------------------------------
408
409    fn cd_attached(&self) -> bool {
410        self.port.as_ref().is_some_and(|port| port.present())
411    }
412
413    /// The reference's `pages.read`: one decode for every bus master. A VDC access that stops
414    /// to wait (`Vdc::serve_wanted`) is served and the decode made again (issue 0004).
415    pub fn page_read(&mut self, address: u32, mclk: i64) -> u8 {
416        self.vdc_access.begin();
417        loop {
418            let value = self.decode_read(address, mclk);
419            match self.vdc_waiting() {
420                None => return value,
421                Some(index) => self.serve_access(index, mclk),
422            }
423        }
424    }
425
426    /// The reference's `pages.write`; a VDC's wait as in `page_read`.
427    pub fn page_write(&mut self, address: u32, value: u8, mclk: i64) {
428        self.vdc_access.begin();
429        loop {
430            self.decode_write(address, value, mclk);
431            match self.vdc_waiting() {
432                None => return,
433                Some(index) => self.serve_access(index, mclk),
434            }
435        }
436    }
437
438    /// The VDC whose access stopped to wait, if any: as `VdcAccess` saw it, or (a device that
439    /// called `Vdc::read` or `write` itself, not `BoardPins::vdc_read` or `vdc_write`) as the
440    /// chip says; such an access is made again with the device's `mclk`.
441    #[inline]
442    fn vdc_waiting(&self) -> Option<usize> {
443        self.vdc_access
444            .stopped()
445            .or_else(|| self.vdcs.iter().position(|vdc| vdc.serve_wanted))
446    }
447
448    /// The rest of the reference's `Vdc._data_access` with `serve` wired: `served =
449    /// serve(chip)`, the CPU held for `served - mclk` if positive, and the stopped access made at
450    /// `max(served, mclk)` when the decode is made again.
451    fn serve_access(&mut self, index: usize, mclk: i64) {
452        self.vdcs[index].serve_wanted = false;
453        let served = self.serve_vram(index);
454        if served > mclk {
455            // The fork: not `hold`, whose `touch` is for a hold left from outside an access;
456            // `finish_access` applies this one and recomputes the horizon.
457            self.held += served - mclk;
458        }
459        self.vdc_access.again(index, served.max(mclk));
460    }
461
462    fn decode_read(&mut self, address: u32, mclk: i64) -> u8 {
463        let address = address & ADDRESS_MASK;
464        match self.pages.handler(address) {
465            Handler::Unmapped => 0xFF,
466            Handler::Ram => self.ram.read(address),
467            Handler::Vdc => self.vdc_access.read(&mut self.vdcs, 0, address & 3, mclk),
468            Handler::Vce => self.vce.read(address & 7, mclk),
469            Handler::CpuIo => {
470                let cd_attached = self.cd_attached();
471                self.cpu_io.read(address & 0x1FFF, mclk, cd_attached)
472            }
473            Handler::Card if self.rom_lent => self.rom_read(address),
474            Handler::Card => {
475                let Board {
476                    slot,
477                    irq2,
478                    held,
479                    vdcs,
480                    vdc_access,
481                    opcode,
482                    ..
483                } = self;
484                let mut pins = BoardPins {
485                    irq2,
486                    held,
487                    vdcs,
488                    access: vdc_access,
489                    opcode: *opcode,
490                    card: None,
491                };
492                match slot.card.as_mut() {
493                    Some(card) => card.read(address, mclk, &mut pins),
494                    None => 0xFF,
495                }
496            }
497            Handler::Port => {
498                let Board {
499                    slot,
500                    port,
501                    irq2,
502                    held,
503                    vdcs,
504                    vdc_access,
505                    opcode,
506                    ..
507                } = self;
508                let mut pins = BoardPins {
509                    irq2,
510                    held,
511                    vdcs,
512                    access: vdc_access,
513                    opcode: *opcode,
514                    card: slot.card.as_deref_mut(),
515                };
516                match port.as_mut() {
517                    Some(port) => port.read(address, mclk, &mut pins),
518                    None => 0xFF,
519                }
520            }
521            Handler::PixelPath => {
522                let Board {
523                    slot,
524                    pixel_path,
525                    irq2,
526                    held,
527                    vdcs,
528                    vdc_access,
529                    opcode,
530                    ..
531                } = self;
532                let mut pins = BoardPins {
533                    irq2,
534                    held,
535                    vdcs,
536                    access: vdc_access,
537                    opcode: *opcode,
538                    card: slot.card.as_deref_mut(),
539                };
540                pixel_path.read(address, mclk, &mut pins)
541            }
542        }
543    }
544
545    fn decode_write(&mut self, address: u32, value: u8, mclk: i64) {
546        let address = address & ADDRESS_MASK;
547        match self.pages.handler(address) {
548            Handler::Unmapped => {}
549            Handler::Ram => self.ram.write(address, value),
550            Handler::Vdc => self
551                .vdc_access
552                .write(&mut self.vdcs, 0, address & 3, value, mclk),
553            Handler::Vce => self.vce.write(address & 7, value, mclk),
554            Handler::CpuIo => self
555                .cpu_io
556                .write(address & 0x1FFF, value, mclk, &mut self.psg),
557            Handler::Card if self.rom_lent => {} // a plain ROM ignores writes
558            Handler::Card => {
559                let Board {
560                    slot,
561                    irq2,
562                    held,
563                    vdcs,
564                    vdc_access,
565                    opcode,
566                    ..
567                } = self;
568                let mut pins = BoardPins {
569                    irq2,
570                    held,
571                    vdcs,
572                    access: vdc_access,
573                    opcode: *opcode,
574                    card: None,
575                };
576                if let Some(card) = slot.card.as_mut() {
577                    card.write(address, value, mclk, &mut pins);
578                }
579            }
580            Handler::Port => {
581                let Board {
582                    slot,
583                    port,
584                    irq2,
585                    held,
586                    vdcs,
587                    vdc_access,
588                    opcode,
589                    ..
590                } = self;
591                let mut pins = BoardPins {
592                    irq2,
593                    held,
594                    vdcs,
595                    access: vdc_access,
596                    opcode: *opcode,
597                    card: slot.card.as_deref_mut(),
598                };
599                if let Some(port) = port.as_mut() {
600                    port.write(address, value, mclk, &mut pins);
601                }
602            }
603            Handler::PixelPath => {
604                let Board {
605                    slot,
606                    pixel_path,
607                    irq2,
608                    held,
609                    vdcs,
610                    vdc_access,
611                    opcode,
612                    ..
613                } = self;
614                let mut pins = BoardPins {
615                    irq2,
616                    held,
617                    vdcs,
618                    access: vdc_access,
619                    opcode: *opcode,
620                    card: slot.card.as_deref_mut(),
621                };
622                pixel_path.write(address, value, mclk, &mut pins);
623            }
624        }
625    }
626
627    // -- the CPU ----------------------------------------------------------------------------------
628
629    #[inline]
630    fn cycle_clocks(pins: &Pins) -> i64 {
631        if pins.high_speed {
632            CPU_CLOCKS_HIGH
633        } else {
634            CPU_CLOCKS_LOW
635        }
636    }
637
638    /// The fork's shortcut: an access to work RAM or to one of this crate's own cards, with
639    /// nothing waiting (nothing left by the host, `Board::hold` included, or by a port
640    /// device's `catch_up`), has nothing to finish: no stretch (the page is below the hardware
641    /// page), no hold, no line or disable mask it could have changed, nothing scheduled.
642    #[inline(always)]
643    fn quiet_page(&self, address: u32) -> Quiet {
644        if self.unsettled || (address >> PAGE_BITS) as usize >= HARDWARE_FIRST_PAGE {
645            return Quiet::No;
646        }
647        match self.pages.handler(address) {
648            Handler::Ram => Quiet::Ram,
649            Handler::Card if self.rom_lent => Quiet::Rom,
650            Handler::Card if self.plain_card => Quiet::Card,
651            _ => Quiet::No,
652        }
653    }
654
655    /// The pins a card is handed (`page_read` and `page_write` make the same).
656    #[inline(always)]
657    fn card_pins(&mut self) -> (Option<&mut Box<dyn Card>>, BoardPins<'_>) {
658        let Board {
659            slot,
660            irq2,
661            held,
662            vdcs,
663            vdc_access,
664            opcode,
665            ..
666        } = self;
667        (
668            slot.card.as_mut(),
669            BoardPins {
670                irq2,
671                held,
672                vdcs,
673                access: vdc_access,
674                opcode: *opcode,
675                card: None,
676            },
677        )
678    }
679
680    fn finish_access(&mut self, address: u32, cycle: i64, pins: &mut Pins) {
681        // The disable mask a write to $1402 left (the reference's `_irq_disable_changed`,
682        // called from inside the write: nothing has touched the CPU since).
683        if self.cpu_io.irq.mask_changed {
684            self.cpu_io.irq.mask_changed = false;
685            pins.set_irq_disable(self.cpu_io.irq.disable);
686        }
687        // [hw: pcetech 3 note 3] a VDC or VCE access takes one more cycle, reads and writes.
688        // C4: ares charges it only outside burst mode and only for the VDC; Mednafen charges
689        // a statistical VRAM penalty. MacDonald's rule, tier 2, is this model's.
690        let page = (address >> PAGE_BITS) as usize;
691        if (HARDWARE_FIRST_PAGE..HARDWARE_FIRST_PAGE + 8).contains(&page) {
692            self.held += cycle;
693        }
694        for vdc in self.vdcs.iter_mut() {
695            self.held += vdc.take_hold();
696        }
697        // The fork: the access may have scheduled something (a VRAM commit, the timer's start).
698        self.wake = i64::MIN;
699        self.events_at = i64::MIN;
700        if self.held != 0 {
701            let held = std::mem::take(&mut self.held);
702            self.advance_with(held, Some(&mut *pins));
703        }
704        // the access itself (a status read) may have changed a line
705        self.deliver_lines(Some(pins), false);
706        if self.events_at == i64::MIN {
707            self.look_ahead();
708        }
709        self.unsettled = false;
710    }
711
712    /// A device stretches the current cycle (RDY low); applied when the access returns.
713    pub fn hold(&mut self, clocks: i64) {
714        self.held += clocks;
715        self.touch();
716    }
717
718    // -- time -------------------------------------------------------------------------------------
719
720    /// Let `clocks` master clocks pass and run every device up to the new time, with no CPU
721    /// to hand the interrupt lines to (the reference's `advance` on a board without one).
722    pub fn advance(&mut self, clocks: i64) {
723        self.touch();
724        self.advance_with(clocks, None);
725    }
726
727    /// The fork's shortcut: a cycle that ends before the event horizon (`wake`) moves the
728    /// clock and nothing else. The base board runs `run_to` and `deliver_lines` every cycle;
729    /// before the horizon both find nothing to do (`horizon` says why).
730    #[inline(always)]
731    fn advance_with(&mut self, clocks: i64, pins: Option<&mut Pins>) {
732        self.mclk += clocks;
733        if self.mclk < self.wake {
734            return;
735        }
736        self.advance_events(pins);
737    }
738
739    #[inline(never)]
740    fn advance_events(&mut self, pins: Option<&mut Pins>) {
741        if self.stale {
742            self.decide();
743        }
744        if self.mclk < self.events_at {
745            // Only with a port device: nothing is due but its `catch_up`, which may raise
746            // IRQ2, hold the CPU or reach a VDC, so the lines and the horizon follow.
747            self.port_catch_up(self.mclk);
748        } else {
749            self.run_to(self.mclk);
750        }
751        self.deliver_lines(pins, false);
752        self.look_ahead();
753    }
754
755    fn run_to(&mut self, target: i64) {
756        while self.step(target).is_some() {}
757        self.settle(target);
758    }
759
760    /// Handle the earliest event due at or before `target` and return its time; `None` if
761    /// nothing is due.
762    fn step(&mut self, target: i64) -> Option<i64> {
763        let line_at = self.timeline.next_line_start();
764        let row_at = self.row_end;
765        let mut vdc_at = self.vdcs[0].next_event();
766        for other in &self.vdcs[1..] {
767            if let Some(at) = other.next_event() {
768                if vdc_at.is_none_or(|first| at < first) {
769                    vdc_at = Some(at);
770                }
771            }
772        }
773        let timer_at = self.cpu_io.next_event();
774        if let Some(row_at) = row_at
775            .filter(|&at| at <= target && at <= line_at && vdc_at.is_none_or(|vdc_at| at <= vdc_at))
776        {
777            self.end_row(row_at);
778            return Some(row_at);
779        }
780        if line_at <= target && vdc_at.is_none_or(|at| line_at <= at) {
781            self.new_line(line_at);
782            return Some(line_at);
783        }
784        if let Some(vdc_at) = vdc_at.filter(|&at| at <= target) {
785            for chip in self.vdcs.iter_mut() {
786                chip.catch_up(vdc_at);
787            }
788            return Some(vdc_at);
789        }
790        if let Some(timer_at) = timer_at.filter(|&at| at <= target) {
791            self.cpu_io.catch_up(timer_at);
792            return Some(timer_at);
793        }
794        None
795    }
796
797    /// A VDC holds the CPU (/BUSY on RDY) until its pending VRAM access is served: run every
798    /// device, the line clock included, event by event until then, and return that time. The
799    /// held clocks reach `mclk` when the access returns (`hold`); issue 0004.
800    pub(crate) fn serve_vram(&mut self, index: usize) -> i64 {
801        let mut now = self.mclk;
802        while self.vdcs[index].bsy() {
803            // the next line start always exists: this always moves
804            if let Some(at) = self.step(1 << 62) {
805                now = now.max(at);
806            }
807        }
808        self.settle(now);
809        now
810    }
811
812    fn settle(&mut self, target: i64) {
813        for chip in self.vdcs.iter_mut() {
814            chip.catch_up(target);
815        }
816        self.cpu_io.catch_up(target);
817        self.port_catch_up(target);
818    }
819
820    /// socket 5, issue 0002: a port device acts by itself
821    fn port_catch_up(&mut self, target: i64) {
822        let Board {
823            slot,
824            port,
825            irq2,
826            held,
827            vdcs,
828            vdc_access,
829            opcode,
830            ..
831        } = self;
832        if let Some(port) = port.as_mut() {
833            let mut pins = BoardPins {
834                irq2,
835                held,
836                vdcs,
837                access: vdc_access,
838                opcode: *opcode,
839                card: slot.card.as_deref_mut(),
840            };
841            port.catch_up(target, &mut pins);
842            // The fork: a hold it left (its own, or a VDC's from an access it made) is for
843            // the next access to apply, whatever its page.
844            if *held != 0 || vdcs.iter().any(|vdc| vdc.holding()) {
845                self.unsettled = true;
846            }
847        }
848    }
849
850    fn new_line(&mut self, at: i64) {
851        for vdc in self.vdcs.iter_mut() {
852            vdc.catch_up(at);
853        }
854        // the line that is ending; its row ends 237 clocks later
855        self.row_timing = Some(self.timeline.timing(&self.vce));
856        self.row_end = Some(at + HSYNC_CLOCKS);
857        self.timeline.advance(&self.vce);
858        let divider = self.vce.dot_divider();
859        let vsync = self.timeline.line == self.timeline.frame_lines - 3;
860        for vdc in self.vdcs.iter_mut() {
861            vdc.hsync(at, divider);
862            if vsync {
863                vdc.vsync(); // [emu: Mednafen] after the hsync of the same line
864            }
865        }
866    }
867
868    /// The previous line's picture row ends as this line's sync does: hand it to the capture
869    /// before the VDC starts the new line's geometry (events at `at` itself wait).
870    fn end_row(&mut self, at: i64) {
871        for vdc in self.vdcs.iter_mut() {
872            vdc.catch_up(at - 1);
873        }
874        let timing = self.row_timing.expect("a row ends after a line began");
875        let dots = (LINE_CLOCKS / timing.dot_divider) as usize;
876        if self.direct_path {
877            // The fork: `DirectPath::mix` returns the first VDC's row, so the capture reads
878            // it where it lies (the base board copies every VDC's row for the path).
879            match self.vdcs[0].drawn_row(dots) {
880                Some(row) => self.capture.finish_line(&timing, row, &mut self.vce),
881                None => {
882                    let row = self.vdcs[0].pixel_row(dots);
883                    self.capture.finish_line(&timing, &row, &mut self.vce);
884                }
885            }
886            self.row_end = None;
887            return;
888        }
889        let rows: Vec<Vec<u16>> = self.vdcs.iter().map(|vdc| vdc.pixel_row(dots)).collect();
890        let row = self.pixel_path.mix(&timing, rows);
891        self.capture.finish_line(&timing, &row, &mut self.vce);
892        self.row_end = None;
893    }
894
895    // -- interrupts -------------------------------------------------------------------------------
896
897    /// (IRQ1, IRQ2, TIQ) as the interrupt controller sees them, before the mask.
898    pub fn lines(&self) -> (bool, bool, bool) {
899        // IRQ1 is shared by every VDC (wired-OR; each is acknowledged by reading its status).
900        (
901            self.vdcs.iter().any(|vdc| vdc.irq1()),
902            self.irq2.level(),
903            self.cpu_io.tiq(),
904        )
905    }
906
907    pub(crate) fn deliver_lines(&mut self, pins: Option<&mut Pins>, force: bool) {
908        let lines = self.lines();
909        self.cpu_io.irq.irq1 = lines.0;
910        self.cpu_io.irq.irq2 = lines.1;
911        if lines != self.lines || force {
912            if let Some(pins) = pins {
913                pins.set_irq_lines(lines.0, lines.1, lines.2);
914            }
915        }
916        self.lines = lines;
917    }
918
919    // -- reset ------------------------------------------------------------------------------------
920
921    /// Tell the socket devices of a reset event; at power-on also the CPU's on-die timer,
922    /// interrupt controller, I/O port and I/O buffer.
923    ///
924    /// Not a power cycle (issue 0004): the board is built at power-on, and construction is the
925    /// power-on state of the VDC, VCE, PSG and RAM (U7: zeros, or the seed's values). None of
926    /// them is put back here: RAM has no reset; the VCE has no reset pin [wiki: VCE pinout];
927    /// the VDC has /RST [wiki: VDC pinout] but Hudson's manual says nothing of what it clears,
928    /// and the PSG manual is silent too; the PC Engine has no reset button (`ResetKind`). A host
929    /// that wants to power the machine on again builds a new `Board`.
930    pub fn reset(&mut self, kind: ResetKind) {
931        self.touch();
932        let Board {
933            slot,
934            port,
935            pixel_path,
936            irq2,
937            held,
938            vdcs,
939            vdc_access,
940            opcode,
941            ..
942        } = self;
943        if let Some(card) = slot.card.as_mut() {
944            let mut pins = BoardPins {
945                irq2,
946                held,
947                vdcs,
948                access: vdc_access,
949                opcode: *opcode,
950                card: None,
951            };
952            card.reset(kind, &mut pins);
953        }
954        if let Some(port) = port.as_mut() {
955            let mut pins = BoardPins {
956                irq2,
957                held,
958                vdcs,
959                access: vdc_access,
960                opcode: *opcode,
961                card: slot.card.as_deref_mut(),
962            };
963            port.reset(kind, &mut pins);
964        }
965        let mut pins = BoardPins {
966            irq2,
967            held,
968            vdcs,
969            access: vdc_access,
970            opcode: *opcode,
971            card: slot.card.as_deref_mut(),
972        };
973        pixel_path.reset(kind, &mut pins);
974        if kind == ResetKind::PowerOn {
975            self.cpu_io.reset();
976        }
977    }
978}
979
980/// What `quiet_page` finds: work RAM, a lent ROM image (`lend_rom`), another plain card.
981#[derive(Clone, Copy, PartialEq, Eq)]
982enum Quiet {
983    No,
984    Ram,
985    Rom,
986    Card,
987}
988
989// The fork: each callback is a short quiet case (the cycle ends before the event horizon and
990// the access, if any, is work RAM's or a plain card's) that keeps no register across a call,
991// and the rest out of line (`*_in_full`), which is the base board's callback.
992impl Board {
993    /// The gate's taps are on.
994    #[inline(always)]
995    fn tapped(&self) -> bool {
996        self.bus_log.is_some() | self.bus_detail.is_some()
997    }
998
999    /// `kind` 0 read, 1 write, 2 idle (address and value 0, and not in the log's first word).
1000    #[cold]
1001    #[inline(never)]
1002    fn tap(&mut self, kind: u8, address: u32, value: u8) -> u8 {
1003        if let Some(log) = self.bus_log.as_mut() {
1004            if kind != 2 {
1005                log.push((address as u64) << 8 | value as u64);
1006            }
1007            log.push((self.mclk as u64) << 2 | kind as u64);
1008        }
1009        if let Some(detail) = self.bus_detail.as_mut() {
1010            detail.push((kind, address, value, self.mclk));
1011        }
1012        value
1013    }
1014
1015    #[inline(never)]
1016    fn quiet_card_read(&mut self, address: u32) -> u8 {
1017        let mclk = self.mclk;
1018        let (card, mut pins) = self.card_pins();
1019        let value = match card {
1020            Some(card) => card.read(address & ADDRESS_MASK, mclk, &mut pins),
1021            None => 0xFF,
1022        };
1023        if self.tapped() {
1024            self.tap(0, address, value);
1025        }
1026        value
1027    }
1028
1029    #[inline(never)]
1030    fn quiet_card_write(&mut self, address: u32, value: u8) {
1031        let mclk = self.mclk;
1032        let (card, mut pins) = self.card_pins();
1033        if let Some(card) = card {
1034            card.write(address & ADDRESS_MASK, value, mclk, &mut pins);
1035        }
1036        if self.tapped() {
1037            self.tap(1, address, value);
1038        }
1039    }
1040
1041    /// The clock has moved by `cycle` already.
1042    #[inline(never)]
1043    fn read_in_full(&mut self, address: u32, cycle: i64, pins: &mut Pins) -> u8 {
1044        if self.mclk >= self.wake {
1045            self.advance_events(Some(pins));
1046        }
1047        let address_in = address & ADDRESS_MASK;
1048        let value = match self.quiet_page(address_in) {
1049            Quiet::Ram => self.ram.read(address_in),
1050            Quiet::Rom => self.rom_read(address_in),
1051            Quiet::Card => return self.quiet_card_read(address),
1052            Quiet::No => {
1053                let value = self.page_read(address, self.mclk);
1054                self.finish_access(address, cycle, pins);
1055                value
1056            }
1057        };
1058        if self.tapped() {
1059            self.tap(0, address, value);
1060        }
1061        value
1062    }
1063
1064    #[inline(never)]
1065    fn write_in_full(&mut self, address: u32, value: u8, cycle: i64, pins: &mut Pins) {
1066        if self.mclk >= self.wake {
1067            self.advance_events(Some(pins));
1068        }
1069        let address_in = address & ADDRESS_MASK;
1070        match self.quiet_page(address_in) {
1071            Quiet::Ram => self.ram.write(address_in, value),
1072            Quiet::Rom => {} // a plain ROM ignores writes
1073            Quiet::Card => return self.quiet_card_write(address, value),
1074            Quiet::No => {
1075                self.page_write(address, value, self.mclk);
1076                self.finish_access(address, cycle, pins);
1077            }
1078        }
1079        if self.tapped() {
1080            self.tap(1, address, value);
1081        }
1082    }
1083
1084    #[inline(never)]
1085    fn idle_in_full(&mut self, pins: &mut Pins) {
1086        if self.mclk >= self.wake {
1087            self.advance_events(Some(pins));
1088        }
1089        if self.tapped() {
1090            self.tap(2, 0, 0);
1091        }
1092    }
1093}
1094
1095impl Bus for Board {
1096    fn read(&mut self, address: u32, pins: &mut Pins) -> u8 {
1097        self.opcode = pins.opcode();
1098        let cycle = Board::cycle_clocks(pins);
1099        self.mclk += cycle;
1100        if self.mclk < self.wake {
1101            let address_in = address & ADDRESS_MASK;
1102            match self.quiet_page(address_in) {
1103                Quiet::Ram => {
1104                    let value = self.ram.read(address_in);
1105                    if self.tapped() {
1106                        return self.tap(0, address, value);
1107                    }
1108                    return value;
1109                }
1110                Quiet::Rom => {
1111                    let value = self.rom_read(address_in);
1112                    if self.tapped() {
1113                        return self.tap(0, address, value);
1114                    }
1115                    return value;
1116                }
1117                Quiet::Card => return self.quiet_card_read(address),
1118                Quiet::No => {}
1119            }
1120        }
1121        self.read_in_full(address, cycle, pins)
1122    }
1123
1124    fn write(&mut self, address: u32, value: u8, pins: &mut Pins) {
1125        self.opcode = pins.opcode();
1126        let cycle = Board::cycle_clocks(pins);
1127        self.mclk += cycle;
1128        if self.mclk < self.wake {
1129            let address_in = address & ADDRESS_MASK;
1130            match self.quiet_page(address_in) {
1131                Quiet::Ram => {
1132                    self.ram.write(address_in, value);
1133                    if self.tapped() {
1134                        self.tap(1, address, value);
1135                    }
1136                    return;
1137                }
1138                Quiet::Rom => {
1139                    if self.tapped() {
1140                        self.tap(1, address, value);
1141                    }
1142                    return;
1143                }
1144                Quiet::Card => return self.quiet_card_write(address, value),
1145                Quiet::No => {}
1146            }
1147        }
1148        self.write_in_full(address, value, cycle, pins)
1149    }
1150
1151    /// A cycle with no bus transfer (internal cycle or dummy read: nothing reacts).
1152    fn idle(&mut self, _address: Option<u32>, pins: &mut Pins) {
1153        self.opcode = pins.opcode();
1154        self.mclk += Board::cycle_clocks(pins);
1155        if self.mclk < self.wake && !self.tapped() {
1156            return;
1157        }
1158        self.idle_in_full(pins)
1159    }
1160}