pcengine_rust/vdc/
chip.rs

1//! The HuC6270 VDC as the CPU sees it: the bus port, VRAM access, status, IRQ1 (`vdc/chip.py`).
2//!
3//! Instances, not module state: a SuperGrafx has two, a PC-FX may one day pin this module.
4//!
5//! Bus ($FF:0000-03FF, 4-byte mirror) [hw: pcetech 5]:
6//!
7//! ```text
8//! $0  write: register select (low 5 bits); read: status
9//! $1  unused, reads 0
10//! $2  data LSB     $3  data MSB
11//! ```
12//!
13//! Provisional (U1, tier 5): the VDC's CPU access schedule in active display. Hudson's table and
14//! MacDonald's give the mode-0 slot order (CPU, BAT, CPU, ?, CPU, CG0, CPU, CG1) but not the
15//! phase against the line. A VRAM data access made during the display width is *accepted* at once
16//! and *committed* at the next CPU slot of an 8-dot cycle counted from the display start; BSY
17//! (status bit 6) is set until then; a second data access while one is pending holds the CPU
18//! (RDY) until the first commits. Mednafen instead charges a statistical 1-cycle penalty (C4).
19//!
20//! Differences forced by Rust: the reference's `hold` callable (the board's) is an accumulator
21//! here, `held`, which the board takes when the access returns (`take_hold`): the reference's
22//! board applies its own sum at the same point.
23//!
24//! **The board's wait** (issue 0004): the reference's `serve` callable, which runs the whole
25//! board from inside an access until this chip's pending access is served, cannot be called
26//! here: the board owns this chip and is borrowed for the access (and the device that made it,
27//! the SuperGrafx's VPC, is called again by the board during the wait, to mix a line). `serve`
28//! is a flag instead (wiring, not state: the board sets it on its VDCs). An access that would
29//! wait, with the flag set, stops where the reference's `_data_access` would call `serve`,
30//! having done only what the reference has done by then, and raises `serve_wanted`. The board
31//! then serves the chip (`Board::serve_vram`), holds the CPU for `served - mclk`, and makes the
32//! whole decode again; `sockets::VdcAccess` hands back the results of the VDC accesses made
33//! before the stop, makes the stopped one at `max(served, mclk)`, where nothing is pending and
34//! it runs through as the reference's continues, and makes the later ones as the reference
35//! does after its wait.
36
37use serde::{Deserialize, Serialize};
38
39use crate::machine::{py_floordiv, HSYNC_CLOCKS};
40use crate::mt::PythonRandom;
41use crate::vdc::dma::DmaEngine;
42use crate::vdc::regs as r;
43use crate::vdc::sequencer::{Event, Sequencer, VPhase};
44use crate::vdc::{background, sprites};
45
46/// [hw: pcetech 5] 64 KiB; the upper half of the 128 KiB space mirrors it
47pub const VRAM_WORDS: usize = 0x8000;
48
49/// [hw: pcetech 5.1 register $09] CPU slots within the 8-dot cycle, by VRAM access mode
50/// (MWR D1-D0): mode 0 "CPU BAT CPU ??? CPU CG0 CPU CG1", modes 1 and 2 "BAT CPU CG0 CG1" over
51/// two dots each, mode 3 none for the CPU (four-dot accesses, BAT then CG).
52pub const CPU_SLOTS: [&[i64]; 4] = [&[0, 2, 4, 6], &[2], &[2], &[]];
53
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55pub struct Vdc {
56    pub regs: r::VdcRegisters,
57    held: i64,
58    pub vram: Vec<u16>,
59    pub sat: Vec<u16>,
60    pub status: u8,
61    /// master-clock time of the sequencer event being handled
62    pub now: i64,
63    pub seq: Sequencer,
64    pub dma: DmaEngine,
65    // [emu: Mednafen BG_YMoo, BG_YOffset, BG_XOffset] the scroll as the line latched it
66    pub(crate) bg_y: i64,
67    pub(crate) need_bg_y_step: bool,
68    pub(crate) bg_y_offset: i64,
69    pub(crate) bg_x_offset: i64,
70    /// MWR as the vertical sync latched it
71    pub(crate) mwr_cache: u16,
72    pub(crate) row: Option<Vec<u16>>,
73    pub(crate) sprite_entries: Vec<sprites::Entry>,
74    /// A pending CPU VRAM write: (address, word)
75    pub(crate) pending_write: Option<(u16, u16)>,
76    pub(crate) pending_read: Option<u16>,
77    pub(crate) commit_at: i64,
78    /// The board's wait (issue 0004; the reference's `serve`): set by the board on its VDCs.
79    /// Unset (a VDC on its own, with no sync to deliver), a wait runs the chip's own events
80    /// (`wait_alone`). Wiring, not state: not in a save state, and a loaded state keeps it.
81    #[serde(skip)]
82    pub serve: bool,
83    /// An access stopped at its wait for the board to serve this chip (see the module's notes).
84    #[serde(skip)]
85    pub serve_wanted: bool,
86}
87
88/// The earlier of two optional times.
89#[inline]
90fn earlier(a: Option<i64>, b: Option<i64>) -> Option<i64> {
91    match (a, b) {
92        (Some(a), Some(b)) => Some(a.min(b)),
93        (a, None) => a,
94        (None, b) => b,
95    }
96}
97
98impl Vdc {
99    /// The reference's defaults: `vblank_dots = Some(-8)`, `vertical_at_line_start = false`,
100    /// `dma_resumes = true`.
101    pub fn new(
102        power_on: Option<&mut PythonRandom>,
103        vblank_dots: Option<i64>,
104        vertical_at_line_start: bool,
105        dma_resumes: bool,
106    ) -> Vdc {
107        // U7: zeros by default, random on request.
108        let (vram, sat) = match power_on {
109            None => (vec![0; VRAM_WORDS], vec![0; 256]),
110            Some(rng) => {
111                let vram = (0..VRAM_WORDS)
112                    .map(|_| rng.getrandbits(16) as u16)
113                    .collect();
114                let sat = (0..256).map(|_| rng.getrandbits(16) as u16).collect();
115                (vram, sat)
116            }
117        };
118        Vdc {
119            regs: r::VdcRegisters::new(),
120            held: 0,
121            vram,
122            sat,
123            status: 0,
124            now: 0,
125            seq: Sequencer::new(vblank_dots, vertical_at_line_start),
126            dma: DmaEngine::new(dma_resumes),
127            bg_y: 0,
128            need_bg_y_step: false,
129            bg_y_offset: 0,
130            bg_x_offset: 0,
131            mwr_cache: 0,
132            row: None,
133            sprite_entries: Vec::new(),
134            pending_write: None,
135            pending_read: None,
136            commit_at: 0,
137            serve: false,
138            serve_wanted: false,
139        }
140    }
141
142    /// The master clocks the accesses since the last call asked the CPU to wait (the
143    /// reference's `hold` callable, summed).
144    pub fn take_hold(&mut self) -> i64 {
145        std::mem::take(&mut self.held)
146    }
147
148    /// The fork: a hold is waiting for `take_hold`.
149    #[inline]
150    pub(crate) fn holding(&self) -> bool {
151        self.held != 0
152    }
153
154    fn hold(&mut self, clocks: i64) {
155        self.held += clocks;
156    }
157
158    // -- outputs --------------------------------------------------------------------------------
159
160    /// The /IRQ pin: held until the status port is read.
161    #[inline]
162    pub fn irq1(&self) -> bool {
163        self.status & r::IRQ_BITS != 0
164    }
165
166    #[inline]
167    pub fn bsy(&self) -> bool {
168        self.pending_write.is_some() || self.pending_read.is_some()
169    }
170
171    /// The fork: the earliest of the three by hand (the base board folds an array of options
172    /// through an iterator, which the compiler does not flatten).
173    #[inline]
174    pub fn next_event(&self) -> Option<i64> {
175        earlier(
176            earlier(self.seq_next_event(), self.commit_event()),
177            self.dma_next_event(),
178        )
179    }
180
181    #[inline]
182    fn commit_event(&self) -> Option<i64> {
183        if self.bsy() {
184            Some(self.commit_at)
185        } else {
186            None
187        }
188    }
189
190    pub fn catch_up(&mut self, mclk: i64) {
191        loop {
192            let seq_t = self.seq_next_event();
193            let dma_t = self.dma_next_event();
194            let commit_t = self.commit_event();
195            let due = earlier(earlier(seq_t, dma_t), commit_t).filter(|&t| t <= mclk);
196            let Some(t) = due else {
197                self.dma_advance(mclk);
198                return;
199            };
200            if dma_t == Some(t) {
201                self.dma_advance(t);
202            } else if commit_t == Some(t) && seq_t.is_none_or(|seq_t| t <= seq_t) {
203                self.commit_pending();
204            } else {
205                self.dma_advance(t);
206                self.seq_run_to(t);
207            }
208        }
209    }
210
211    // -- the sync generator's calls (the VCE's line clock) ----------------------------------------
212
213    pub fn hsync(&mut self, mclk: i64, divider: i64) {
214        self.seq_hsync(mclk, divider);
215    }
216
217    pub fn vsync(&mut self) {
218        self.seq_vsync();
219        self.need_bg_y_step = false;
220        self.mwr_cache = self.regs.mwr();
221    }
222
223    // -- events from the sequencer ----------------------------------------------------------------
224
225    pub(crate) fn vblank_test(&mut self) {
226        if self.regs.cr() & r::CR_VBLANK_IRQ != 0 {
227            self.status |= r::VD;
228        }
229    }
230
231    pub(crate) fn raster_test(&mut self, count: i64) {
232        // [hw: pcetech 5.1] RCR is compared with the line counted from $40 at the first active
233        // line; values outside $40-$146 never match.
234        if count == self.regs.rcr() - 0x40 && self.regs.cr() & r::CR_RASTER_IRQ != 0 {
235            self.status |= r::RR;
236        }
237    }
238
239    pub(crate) fn latch_byr(&mut self) {
240        self.step_bg_y();
241        self.bg_y_offset = self.bg_y;
242    }
243
244    pub(crate) fn latch_bxr(&mut self) {
245        self.bg_x_offset = (self.regs.value[r::BXR] & 0x3FF) as i64;
246    }
247
248    fn step_bg_y(&mut self) {
249        if self.need_bg_y_step {
250            self.need_bg_y_step = false;
251            self.bg_y = if self.seq.rcr_count == 0 {
252                (self.regs.value[r::BYR] & 0x1FF) as i64
253            } else {
254                self.bg_y + 1
255            };
256        }
257    }
258
259    pub(crate) fn line_counter_step(&mut self, _count: i64) {
260        self.step_bg_y();
261        self.need_bg_y_step = true;
262    }
263
264    /// The scan for the next line's sprites, with the overflow flag and the narrow-display
265    /// budget (U3: Mesen2's: the VDC fetches 4, 4, 8 or 16 dots per entry between the end of
266    /// one line's display width and 16 dots before the next line's).
267    pub(crate) fn fetch_sprites(&mut self, line: i64) {
268        let seq = &self.seq;
269        let dots = 1365 / seq.divider;
270        let previous_end = py_floordiv(seq.active_end - seq.origin - HSYNC_CLOCKS, seq.divider);
271        let next_start = dots + 8 + (self.regs.hds() + 1) * 8 - 16;
272        let budget = 0.max(next_start - previous_end)
273            / sprites::CLOCKS_PER_SPRITE[((self.mwr_cache >> 2) & 3) as usize];
274        // The fork: into the last line's list (`scan` allocates one).
275        let overflow = sprites::scan_into(
276            &mut self.sprite_entries,
277            &self.vram,
278            VRAM_WORDS,
279            &self.sat,
280            line,
281            self.mwr_cache,
282            budget as usize,
283        );
284        if overflow && self.regs.cr() & r::CR_OVERFLOW_IRQ != 0 {
285            self.status |= r::OR;
286        }
287    }
288
289    pub(crate) fn collision_hit(&mut self) {
290        if self.regs.cr() & r::CR_COLLISION_IRQ != 0 {
291            self.status |= r::CR_FLAG;
292        }
293    }
294
295    pub(crate) fn display_started(&mut self) {
296        self.dma_display_started(self.now);
297    }
298
299    pub(crate) fn display_ended(&mut self) {
300        self.dma_display_ended(self.now);
301    }
302
303    pub(crate) fn burst_began(&mut self) {
304        self.dma_advance(self.now);
305    }
306
307    /// The 9-bit pixels of this line, drawn as the display width begins. [hw: pcetech 5.2, 6]
308    /// Backdrop (background colour 0, $000) inside the width if either layer is on, overscan
309    /// (sprite colour 0, $100) otherwise and outside.
310    pub(crate) fn render_line(&mut self) {
311        let seq = &self.seq;
312        let dots = (1365 / seq.divider) as usize;
313        // The fork: the last line's buffer again (the base board allocates a row a line).
314        let mut row = self.row.take().unwrap_or_default();
315        row.clear();
316        row.resize(dots, 0x100u16);
317        if !seq.display_line {
318            self.row = Some(row);
319            return;
320        }
321        let row_start = seq.origin + HSYNC_CLOCKS;
322        let first = py_floordiv(seq.active_start - row_start, seq.divider);
323        let width = py_floordiv(seq.active_end - seq.active_start, seq.divider);
324        let cr = seq.cr_cache;
325        let divider = seq.divider;
326        let end = (first + width).min(dots as i64);
327        if first >= end {
328            // Not reachable: a display start at or past the row's end is later than the next
329            // line's sync, which drops this line's events before `render_line` runs
330            // (sequencer.rs, `seq_leave_hsync`; the reference's comment cites issue 0004: the hdw
331            // event lands at most at the row's last dot). Kept so the slices below cannot panic.
332            self.row = Some(row);
333            return;
334        }
335        let (first_index, end_index) = (first as usize, end as usize);
336        // The fork: drawn into the row itself (the base board draws the whole width apart and
337        // copies what fits).
338        let shown = &mut row[first_index..end_index];
339        if cr & 0x80 != 0 {
340            background::row_into(
341                &self.vram,
342                VRAM_WORDS,
343                self.mwr_cache,
344                self.bg_x_offset,
345                self.bg_y_offset,
346                shown,
347            );
348        } else {
349            // sprites only, or neither layer inside a non-burst display period: the backdrop.
350            // [emu: Mednafen, Mesen2 and Beetle all show colour 0 of the background palette when
351            // both layers are off (Space Harrier's last 12 lines); pcetech 5.2 says overscan: C30]
352            shown.fill(0x000);
353        }
354        let mut collision = None;
355        if cr & 0x40 != 0 && !self.sprite_entries.is_empty() {
356            let hit = sprites::draw(&self.sprite_entries, end - first, &mut row, first_index);
357            if let Some(hit) = hit {
358                if self.regs.cr() & r::CR_COLLISION_IRQ != 0 {
359                    // the flag rises when the beam reaches the pixel (Mesen2 runs the VDC per CPU cycle
360                    // for this; Mednafen raises it as the line is drawn): U3
361                    collision = Some(row_start + (first + hit) * divider);
362                }
363            }
364        }
365        self.row = Some(row);
366        if let Some(when) = collision {
367            self.seq_schedule(when.max(self.now), Event::Collision);
368        }
369    }
370
371    /// Commit a waiting CPU access unless a transfer holds the VRAM (Mednafen's
372    /// `CheckAndCommitPending`: nothing is committed while the SAT or VRAM DMA runs).
373    pub(crate) fn commit_unless_dma(&mut self) {
374        if !self.dma.busy() {
375            self.commit_pending();
376        }
377    }
378
379    pub(crate) fn commit_pending(&mut self) {
380        if let Some((address, word)) = self.pending_write.take() {
381            if (address as usize) < VRAM_WORDS {
382                // [hw] writes to the mirrored half are ignored
383                self.vram[address as usize] = word;
384            }
385        }
386        if let Some(address) = self.pending_read.take() {
387            // Mirrored reads "sometimes return corrupted data" [hw]; U23: this model reads 0.
388            self.regs.read_buffer = if (address as usize) < VRAM_WORDS {
389                self.vram[address as usize]
390            } else {
391                0
392            };
393        }
394    }
395
396    // -- the CPU's port ---------------------------------------------------------------------------
397
398    pub fn read(&mut self, offset: u32, mut mclk: i64) -> u8 {
399        self.catch_up(mclk);
400        let port = offset & 3;
401        if port == 0 {
402            let value = self.status | if self.bsy() { r::BSY } else { 0 };
403            self.status &= !r::IRQ_BITS;
404            return value;
405        }
406        if port == 1 {
407            return 0;
408        }
409        let msb = port == 3;
410        if self.serve
411            && (self.pending_read.is_some()
412                || (msb && self.regs.select as usize == r::VRW && self.bsy()))
413        {
414            // one of the two `data_access` calls below would wait: the board serves it first
415            self.serve_wanted = true;
416            return 0xFF;
417        }
418        if self.pending_read.is_some() {
419            // The word the last MARR write or VRR read asked for is not in the buffer yet (it
420            // waits for a CPU slot or a DMA): the CPU waits for it rather than reading the old
421            // word. The manual's read sequence and both Mednafen and Mesen2 ("D&D Order of the
422            // Griffon breaks without this") agree; the model's slot wait made the case possible.
423            mclk = self.data_access(mclk);
424        }
425        let value = if msb {
426            (self.regs.read_buffer >> 8) as u8
427        } else {
428            (self.regs.read_buffer & 0xFF) as u8
429        };
430        if msb && self.regs.select as usize == r::VRW {
431            // [hw: pcetech 5.1 $02] after the MSB read MARR advances and the next word is read
432            mclk = self.data_access(mclk);
433            self.regs.value[r::MARR] = self.regs.value[r::MARR].wrapping_add(self.regs.increment());
434            self.pending_read = Some(self.regs.value[r::MARR]);
435            self.schedule_commit(mclk);
436        }
437        value
438    }
439
440    pub fn write(&mut self, offset: u32, value: u8, mut mclk: i64) {
441        self.catch_up(mclk);
442        let port = offset & 3;
443        if port == 0 {
444            self.regs.select = value & 0x1F;
445            return;
446        }
447        if port == 1 {
448            return;
449        }
450        let register = self.regs.select;
451        if !r::valid_register(register) {
452            return;
453        }
454        let register = register as usize;
455        let msb = port == 3;
456        if register == r::VRW {
457            if !msb {
458                self.regs.write_latch = value;
459            } else {
460                if self.serve && self.bsy() {
461                    self.serve_wanted = true; // `data_access` would wait: the board serves it first
462                    return;
463                }
464                mclk = self.data_access(mclk);
465                let word = self.regs.write_latch as u16 | ((value as u16) << 8);
466                self.pending_write = Some((self.regs.value[r::MAWR], word));
467                self.regs.value[r::MAWR] =
468                    self.regs.value[r::MAWR].wrapping_add(self.regs.increment());
469                self.schedule_commit(mclk);
470            }
471            return;
472        }
473        self.regs.set_byte(register, value, msb);
474        if register == r::MARR && msb && self.serve && self.bsy() {
475            // `data_access` below would wait: the board serves it first (the access is made
476            // again after the wait and stores the same byte again)
477            self.serve_wanted = true;
478            return;
479        }
480        if register == r::MARR && msb {
481            // [hw: pcetech 5.1 $01] writing the MSB loads the read buffer from VRAM[MARR]
482            mclk = self.data_access(mclk);
483            self.pending_read = Some(self.regs.value[r::MARR]);
484            self.schedule_commit(mclk);
485        } else if register == r::BYR {
486            // [emu: Mednafen] set on both bytes: only changing on the MSB breaks a game
487            self.bg_y = (self.regs.value[r::BYR] & 0x1FF) as i64;
488        } else if register == r::SATB {
489            self.dma_arm_satb(); // [mfr] armed by a write; starts when the display period ends
490        } else if register == r::LENR && msb {
491            self.dma_start(mclk);
492        }
493    }
494
495    // -- VRAM access timing -----------------------------------------------------------------------
496
497    /// A second data-port access while one is pending holds the CPU until it commits; the
498    /// time at which the new access is accepted is returned.
499    ///
500    /// The hold is the /BUSY pin on the CPU's RDY [wiki: VDC pinout]: only the CPU stops. The
501    /// VDC's syncs come from the VCE, so the display keeps its lines while the CPU waits, and a
502    /// VRAM -> VRAM transfer the CPU waits on meets the display start like any other: paused
503    /// (C7, the default) or cancelled (`dma_resumes=false`, which serves the access there).
504    /// Issue 0004: the wait used to run this chip alone to the transfer's end, lines ahead of
505    /// the board's line clock, so the display never started during it.
506    fn data_access(&mut self, mclk: i64) -> i64 {
507        if !self.bsy() {
508            return mclk;
509        }
510        // With the board's wait wired the access stopped before this point (`serve_wanted`) and
511        // is made again once the board has served it, so nothing is pending here.
512        debug_assert!(!self.serve, "the board serves a wired VDC's wait");
513        self.wait_alone(mclk)
514    }
515
516    /// `data_access` for a VDC with no board: no line clock reaches it during the wait.
517    fn wait_alone(&mut self, mclk: i64) -> i64 {
518        let mut now = mclk;
519        while self.bsy() && self.dma.busy() {
520            // the pending access is stuck behind a transfer
521            let Some(due) = self.dma_next_event() else {
522                // paused behind the display: nothing to wait for but the end of it
523                self.dma_force_complete(now);
524                break;
525            };
526            if due > now {
527                self.hold(due - now);
528            }
529            self.catch_up(due);
530            now = now.max(due);
531        }
532        if self.bsy() {
533            let wait = self.commit_at - now;
534            if wait > 0 {
535                self.hold(wait);
536                now = self.commit_at;
537            }
538            self.commit_pending();
539        }
540        now
541    }
542
543    fn schedule_commit(&mut self, mclk: i64) {
544        if self.dma.busy() {
545            // waits for the transfer; its end commits (BSY meanwhile)
546            self.commit_at = 1 << 62;
547            return;
548        }
549        self.commit_at = self.slot_time(mclk);
550        if self.commit_at <= mclk {
551            self.commit_pending();
552        }
553    }
554
555    /// Earliest time at or after `mclk` that the CPU owns a VRAM slot (U1, provisional).
556    pub fn slot_time(&self, mclk: i64) -> i64 {
557        let seq = &self.seq;
558        if !(seq.active_display() && (seq.active_start..seq.active_end).contains(&mclk)) {
559            return mclk;
560        }
561        let div = seq.divider;
562        // first dot boundary at or after mclk
563        let mut dot = -py_floordiv(-(mclk - seq.active_start), div);
564        let slots = CPU_SLOTS[(self.regs.mwr() & 3) as usize];
565        if slots.is_empty() {
566            return seq.active_end;
567        }
568        loop {
569            let when = seq.active_start + dot * div;
570            if when >= seq.active_end {
571                return seq.active_end;
572            }
573            if slots.contains(&dot.rem_euclid(8)) {
574                return when;
575            }
576            dot += 1;
577        }
578    }
579
580    // -- display ----------------------------------------------------------------------------------
581
582    pub fn vphase(&self) -> VPhase {
583        self.seq.vphase
584    }
585
586    /// The fork: `pixel_row` without the copy, where the line was drawn at this width.
587    #[inline]
588    pub(crate) fn drawn_row(&self, dots: usize) -> Option<&[u16]> {
589        match &self.row {
590            Some(row) if row.len() == dots => Some(row),
591            _ => None,
592        }
593    }
594
595    /// The 9-bit VDC output for the line that just ran (drawn by `render_line`).
596    pub fn pixel_row(&self, dots: usize) -> Vec<u16> {
597        match &self.row {
598            Some(row) if row.len() == dots => row.clone(),
599            _ => vec![0x100; dots],
600        }
601    }
602}