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. A row the reference's slice assignment would
23//! leave with a length other than the line's (a display start past the row's end) is left as
24//! the overscan row `pixel_row` returns for it there.
25
26use serde::{Deserialize, Serialize};
27
28use crate::machine::{py_floordiv, HSYNC_CLOCKS};
29use crate::mt::PythonRandom;
30use crate::vdc::dma::DmaEngine;
31use crate::vdc::regs as r;
32use crate::vdc::sequencer::{Event, Sequencer, VPhase};
33use crate::vdc::{background, sprites};
34
35/// [hw: pcetech 5] 64 KiB; the upper half of the 128 KiB space mirrors it
36pub const VRAM_WORDS: usize = 0x8000;
37
38/// [hw: pcetech 5.1 register $09] CPU slots within the 8-dot cycle, by VRAM access mode
39/// (MWR D1-D0): mode 0 "CPU BAT CPU ??? CPU CG0 CPU CG1", modes 1 and 2 "BAT CPU CG0 CG1" over
40/// two dots each, mode 3 none for the CPU (four-dot accesses, BAT then CG).
41pub const CPU_SLOTS: [&[i64]; 4] = [&[0, 2, 4, 6], &[2], &[2], &[]];
42
43#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
44pub struct Vdc {
45    pub regs: r::VdcRegisters,
46    held: i64,
47    pub vram: Vec<u16>,
48    pub sat: Vec<u16>,
49    pub status: u8,
50    /// master-clock time of the sequencer event being handled
51    pub now: i64,
52    pub seq: Sequencer,
53    pub dma: DmaEngine,
54    // [emu: Mednafen BG_YMoo, BG_YOffset, BG_XOffset] the scroll as the line latched it
55    pub(crate) bg_y: i64,
56    pub(crate) need_bg_y_step: bool,
57    pub(crate) bg_y_offset: i64,
58    pub(crate) bg_x_offset: i64,
59    /// MWR as the vertical sync latched it
60    pub(crate) mwr_cache: u16,
61    pub(crate) row: Option<Vec<u16>>,
62    pub(crate) sprite_entries: Vec<sprites::Entry>,
63    /// A pending CPU VRAM write: (address, word)
64    pub(crate) pending_write: Option<(u16, u16)>,
65    pub(crate) pending_read: Option<u16>,
66    pub(crate) commit_at: i64,
67}
68
69impl Vdc {
70    /// The reference's defaults: `vblank_dots = Some(-8)`, `vertical_at_line_start = false`,
71    /// `dma_resumes = true`.
72    pub fn new(
73        power_on: Option<&mut PythonRandom>,
74        vblank_dots: Option<i64>,
75        vertical_at_line_start: bool,
76        dma_resumes: bool,
77    ) -> Vdc {
78        // U7: zeros by default, random on request.
79        let (vram, sat) = match power_on {
80            None => (vec![0; VRAM_WORDS], vec![0; 256]),
81            Some(rng) => {
82                let vram = (0..VRAM_WORDS)
83                    .map(|_| rng.getrandbits(16) as u16)
84                    .collect();
85                let sat = (0..256).map(|_| rng.getrandbits(16) as u16).collect();
86                (vram, sat)
87            }
88        };
89        Vdc {
90            regs: r::VdcRegisters::new(),
91            held: 0,
92            vram,
93            sat,
94            status: 0,
95            now: 0,
96            seq: Sequencer::new(vblank_dots, vertical_at_line_start),
97            dma: DmaEngine::new(dma_resumes),
98            bg_y: 0,
99            need_bg_y_step: false,
100            bg_y_offset: 0,
101            bg_x_offset: 0,
102            mwr_cache: 0,
103            row: None,
104            sprite_entries: Vec::new(),
105            pending_write: None,
106            pending_read: None,
107            commit_at: 0,
108        }
109    }
110
111    /// The master clocks the accesses since the last call asked the CPU to wait (the
112    /// reference's `hold` callable, summed).
113    pub fn take_hold(&mut self) -> i64 {
114        std::mem::take(&mut self.held)
115    }
116
117    fn hold(&mut self, clocks: i64) {
118        self.held += clocks;
119    }
120
121    // -- outputs --------------------------------------------------------------------------------
122
123    /// The /IRQ pin: held until the status port is read.
124    #[inline]
125    pub fn irq1(&self) -> bool {
126        self.status & r::IRQ_BITS != 0
127    }
128
129    #[inline]
130    pub fn bsy(&self) -> bool {
131        self.pending_write.is_some() || self.pending_read.is_some()
132    }
133
134    pub fn next_event(&self) -> Option<i64> {
135        [
136            self.seq_next_event(),
137            self.commit_event(),
138            self.dma_next_event(),
139        ]
140        .into_iter()
141        .flatten()
142        .min()
143    }
144
145    fn commit_event(&self) -> Option<i64> {
146        if self.bsy() {
147            Some(self.commit_at)
148        } else {
149            None
150        }
151    }
152
153    pub fn catch_up(&mut self, mclk: i64) {
154        loop {
155            let seq_t = self.seq_next_event();
156            let dma_t = self.dma_next_event();
157            let commit_t = self.commit_event();
158            let due = [seq_t, dma_t, commit_t]
159                .into_iter()
160                .flatten()
161                .filter(|&t| t <= mclk)
162                .min();
163            let Some(t) = due else {
164                self.dma_advance(mclk);
165                return;
166            };
167            if dma_t == Some(t) {
168                self.dma_advance(t);
169            } else if commit_t == Some(t) && seq_t.is_none_or(|seq_t| t <= seq_t) {
170                self.commit_pending();
171            } else {
172                self.dma_advance(t);
173                self.seq_run_to(t);
174            }
175        }
176    }
177
178    // -- the sync generator's calls (the VCE's line clock) ----------------------------------------
179
180    pub fn hsync(&mut self, mclk: i64, divider: i64) {
181        self.seq_hsync(mclk, divider);
182    }
183
184    pub fn vsync(&mut self) {
185        self.seq_vsync();
186        self.need_bg_y_step = false;
187        self.mwr_cache = self.regs.mwr();
188    }
189
190    // -- events from the sequencer ----------------------------------------------------------------
191
192    pub(crate) fn vblank_test(&mut self) {
193        if self.regs.cr() & r::CR_VBLANK_IRQ != 0 {
194            self.status |= r::VD;
195        }
196    }
197
198    pub(crate) fn raster_test(&mut self, count: i64) {
199        // [hw: pcetech 5.1] RCR is compared with the line counted from $40 at the first active
200        // line; values outside $40-$146 never match.
201        if count == self.regs.rcr() - 0x40 && self.regs.cr() & r::CR_RASTER_IRQ != 0 {
202            self.status |= r::RR;
203        }
204    }
205
206    pub(crate) fn latch_byr(&mut self) {
207        self.step_bg_y();
208        self.bg_y_offset = self.bg_y;
209    }
210
211    pub(crate) fn latch_bxr(&mut self) {
212        self.bg_x_offset = (self.regs.value[r::BXR] & 0x3FF) as i64;
213    }
214
215    fn step_bg_y(&mut self) {
216        if self.need_bg_y_step {
217            self.need_bg_y_step = false;
218            self.bg_y = if self.seq.rcr_count == 0 {
219                (self.regs.value[r::BYR] & 0x1FF) as i64
220            } else {
221                self.bg_y + 1
222            };
223        }
224    }
225
226    pub(crate) fn line_counter_step(&mut self, _count: i64) {
227        self.step_bg_y();
228        self.need_bg_y_step = true;
229    }
230
231    /// The scan for the next line's sprites, with the overflow flag and the narrow-display
232    /// budget (U3: Mesen2's: the VDC fetches 4, 4, 8 or 16 dots per entry between the end of
233    /// one line's display width and 16 dots before the next line's).
234    pub(crate) fn fetch_sprites(&mut self, line: i64) {
235        let seq = &self.seq;
236        let dots = 1365 / seq.divider;
237        let previous_end = py_floordiv(seq.active_end - seq.origin - HSYNC_CLOCKS, seq.divider);
238        let next_start = dots + 8 + (self.regs.hds() + 1) * 8 - 16;
239        let budget = 0.max(next_start - previous_end)
240            / sprites::CLOCKS_PER_SPRITE[((self.mwr_cache >> 2) & 3) as usize];
241        let (entries, overflow) = sprites::scan(
242            &self.vram,
243            VRAM_WORDS,
244            &self.sat,
245            line,
246            self.mwr_cache,
247            budget as usize,
248        );
249        self.sprite_entries = entries;
250        if overflow && self.regs.cr() & r::CR_OVERFLOW_IRQ != 0 {
251            self.status |= r::OR;
252        }
253    }
254
255    pub(crate) fn collision_hit(&mut self) {
256        if self.regs.cr() & r::CR_COLLISION_IRQ != 0 {
257            self.status |= r::CR_FLAG;
258        }
259    }
260
261    pub(crate) fn display_started(&mut self) {
262        self.dma_display_started(self.now);
263    }
264
265    pub(crate) fn display_ended(&mut self) {
266        self.dma_display_ended(self.now);
267    }
268
269    pub(crate) fn burst_began(&mut self) {
270        self.dma_advance(self.now);
271    }
272
273    /// The 9-bit pixels of this line, drawn as the display width begins. [hw: pcetech 5.2, 6]
274    /// Backdrop (background colour 0, $000) inside the width if either layer is on, overscan
275    /// (sprite colour 0, $100) otherwise and outside.
276    pub(crate) fn render_line(&mut self) {
277        let seq = &self.seq;
278        let dots = (1365 / seq.divider) as usize;
279        let mut row = vec![0x100u16; dots];
280        if !seq.display_line {
281            self.row = Some(row);
282            return;
283        }
284        let row_start = seq.origin + HSYNC_CLOCKS;
285        let first = py_floordiv(seq.active_start - row_start, seq.divider);
286        let width = py_floordiv(seq.active_end - seq.active_start, seq.divider);
287        let cr = seq.cr_cache;
288        let divider = seq.divider;
289        let end = (first + width).min(dots as i64);
290        if first >= end {
291            // The display starts at or past the end of the row: nothing of it shows. (The
292            // reference's slice assignment may leave a row of another length here, which
293            // `pixel_row` answers with the overscan row; no sprite pixel can land either.)
294            self.row = Some(row);
295            return;
296        }
297        let pixels = if cr & 0x80 != 0 {
298            background::row(
299                &self.vram,
300                VRAM_WORDS,
301                self.mwr_cache,
302                self.bg_x_offset,
303                self.bg_y_offset,
304                width,
305            )
306        } else {
307            // sprites only, or neither layer inside a non-burst display period: the backdrop.
308            // [emu: Mednafen, Mesen2 and Beetle all show colour 0 of the background palette when
309            // both layers are off (Space Harrier's last 12 lines); pcetech 5.2 says overscan: C30]
310            vec![0x000; width as usize]
311        };
312        let (first_index, end_index) = (first as usize, end as usize);
313        row[first_index..end_index].copy_from_slice(&pixels[..end_index - first_index]);
314        let mut collision = None;
315        if cr & 0x40 != 0 && !self.sprite_entries.is_empty() {
316            let hit = sprites::draw(&self.sprite_entries, end - first, &mut row, first_index);
317            if let Some(hit) = hit {
318                if self.regs.cr() & r::CR_COLLISION_IRQ != 0 {
319                    // the flag rises when the beam reaches the pixel (Mesen2 runs the VDC per CPU cycle
320                    // for this; Mednafen raises it as the line is drawn): U3
321                    collision = Some(row_start + (first + hit) * divider);
322                }
323            }
324        }
325        self.row = Some(row);
326        if let Some(when) = collision {
327            self.seq_schedule(when.max(self.now), Event::Collision);
328        }
329    }
330
331    /// Commit a waiting CPU access unless a transfer holds the VRAM (Mednafen's
332    /// `CheckAndCommitPending`: nothing is committed while the SAT or VRAM DMA runs).
333    pub(crate) fn commit_unless_dma(&mut self) {
334        if !self.dma.busy() {
335            self.commit_pending();
336        }
337    }
338
339    pub(crate) fn commit_pending(&mut self) {
340        if let Some((address, word)) = self.pending_write.take() {
341            if (address as usize) < VRAM_WORDS {
342                // [hw] writes to the mirrored half are ignored
343                self.vram[address as usize] = word;
344            }
345        }
346        if let Some(address) = self.pending_read.take() {
347            // Mirrored reads "sometimes return corrupted data" [hw]; U23: this model reads 0.
348            self.regs.read_buffer = if (address as usize) < VRAM_WORDS {
349                self.vram[address as usize]
350            } else {
351                0
352            };
353        }
354    }
355
356    // -- the CPU's port ---------------------------------------------------------------------------
357
358    pub fn read(&mut self, offset: u32, mclk: i64) -> u8 {
359        self.catch_up(mclk);
360        let port = offset & 3;
361        if port == 0 {
362            let value = self.status | if self.bsy() { r::BSY } else { 0 };
363            self.status &= !r::IRQ_BITS;
364            return value;
365        }
366        if port == 1 {
367            return 0;
368        }
369        let msb = port == 3;
370        if self.pending_read.is_some() {
371            // The word the last MARR write or VRR read asked for is not in the buffer yet (it
372            // waits for a CPU slot or a DMA): the CPU waits for it rather than reading the old
373            // word. The manual's read sequence and both Mednafen and Mesen2 ("D&D Order of the
374            // Griffon breaks without this") agree; the model's slot wait made the case possible.
375            self.data_access(mclk);
376        }
377        let value = if msb {
378            (self.regs.read_buffer >> 8) as u8
379        } else {
380            (self.regs.read_buffer & 0xFF) as u8
381        };
382        if msb && self.regs.select as usize == r::VRW {
383            // [hw: pcetech 5.1 $02] after the MSB read MARR advances and the next word is read
384            self.data_access(mclk);
385            self.regs.value[r::MARR] = self.regs.value[r::MARR].wrapping_add(self.regs.increment());
386            self.pending_read = Some(self.regs.value[r::MARR]);
387            self.schedule_commit(mclk);
388        }
389        value
390    }
391
392    pub fn write(&mut self, offset: u32, value: u8, mclk: i64) {
393        self.catch_up(mclk);
394        let port = offset & 3;
395        if port == 0 {
396            self.regs.select = value & 0x1F;
397            return;
398        }
399        if port == 1 {
400            return;
401        }
402        let register = self.regs.select;
403        if !r::valid_register(register) {
404            return;
405        }
406        let register = register as usize;
407        let msb = port == 3;
408        if register == r::VRW {
409            if !msb {
410                self.regs.write_latch = value;
411            } else {
412                self.data_access(mclk);
413                let word = self.regs.write_latch as u16 | ((value as u16) << 8);
414                self.pending_write = Some((self.regs.value[r::MAWR], word));
415                self.regs.value[r::MAWR] =
416                    self.regs.value[r::MAWR].wrapping_add(self.regs.increment());
417                self.schedule_commit(mclk);
418            }
419            return;
420        }
421        self.regs.set_byte(register, value, msb);
422        if register == r::MARR && msb {
423            // [hw: pcetech 5.1 $01] writing the MSB loads the read buffer from VRAM[MARR]
424            self.data_access(mclk);
425            self.pending_read = Some(self.regs.value[r::MARR]);
426            self.schedule_commit(mclk);
427        } else if register == r::BYR {
428            // [emu: Mednafen] set on both bytes: only changing on the MSB breaks a game
429            self.bg_y = (self.regs.value[r::BYR] & 0x1FF) as i64;
430        } else if register == r::SATB {
431            self.dma_arm_satb(); // [mfr] armed by a write; starts when the display period ends
432        } else if register == r::LENR && msb {
433            self.dma_start(mclk);
434        }
435    }
436
437    // -- VRAM access timing -----------------------------------------------------------------------
438
439    /// A second data-port access while one is pending holds the CPU until it commits.
440    fn data_access(&mut self, mclk: i64) {
441        let mut now = mclk;
442        while self.bsy() && self.dma.busy() {
443            // the pending access is stuck behind a transfer
444            let Some(due) = self.dma_next_event() else {
445                // paused behind the display: nothing to wait for but the end of it
446                self.dma_force_complete(now);
447                break;
448            };
449            if due > now {
450                self.hold(due - now);
451            }
452            self.catch_up(due);
453            now = now.max(due);
454        }
455        if self.bsy() {
456            let wait = self.commit_at - now;
457            if wait > 0 {
458                self.hold(wait);
459            }
460            self.commit_pending();
461        }
462    }
463
464    fn schedule_commit(&mut self, mclk: i64) {
465        if self.dma.busy() {
466            // waits for the transfer; its end commits (BSY meanwhile)
467            self.commit_at = 1 << 62;
468            return;
469        }
470        self.commit_at = self.slot_time(mclk);
471        if self.commit_at <= mclk {
472            self.commit_pending();
473        }
474    }
475
476    /// Earliest time at or after `mclk` that the CPU owns a VRAM slot (U1, provisional).
477    pub fn slot_time(&self, mclk: i64) -> i64 {
478        let seq = &self.seq;
479        if !(seq.active_display() && (seq.active_start..seq.active_end).contains(&mclk)) {
480            return mclk;
481        }
482        let div = seq.divider;
483        // first dot boundary at or after mclk
484        let mut dot = -py_floordiv(-(mclk - seq.active_start), div);
485        let slots = CPU_SLOTS[(self.regs.mwr() & 3) as usize];
486        if slots.is_empty() {
487            return seq.active_end;
488        }
489        loop {
490            let when = seq.active_start + dot * div;
491            if when >= seq.active_end {
492                return seq.active_end;
493            }
494            if slots.contains(&dot.rem_euclid(8)) {
495                return when;
496            }
497            dot += 1;
498        }
499    }
500
501    // -- display ----------------------------------------------------------------------------------
502
503    pub fn vphase(&self) -> VPhase {
504        self.seq.vphase
505    }
506
507    /// The 9-bit VDC output for the line that just ran (drawn by `render_line`).
508    pub fn pixel_row(&self, dots: usize) -> Vec<u16> {
509        match &self.row {
510            Some(row) if row.len() == dots => row.clone(),
511            _ => vec![0x100; dots],
512        }
513    }
514}