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
88impl Vdc {
89    /// The reference's defaults: `vblank_dots = Some(-8)`, `vertical_at_line_start = false`,
90    /// `dma_resumes = true`.
91    pub fn new(
92        power_on: Option<&mut PythonRandom>,
93        vblank_dots: Option<i64>,
94        vertical_at_line_start: bool,
95        dma_resumes: bool,
96    ) -> Vdc {
97        // U7: zeros by default, random on request.
98        let (vram, sat) = match power_on {
99            None => (vec![0; VRAM_WORDS], vec![0; 256]),
100            Some(rng) => {
101                let vram = (0..VRAM_WORDS)
102                    .map(|_| rng.getrandbits(16) as u16)
103                    .collect();
104                let sat = (0..256).map(|_| rng.getrandbits(16) as u16).collect();
105                (vram, sat)
106            }
107        };
108        Vdc {
109            regs: r::VdcRegisters::new(),
110            held: 0,
111            vram,
112            sat,
113            status: 0,
114            now: 0,
115            seq: Sequencer::new(vblank_dots, vertical_at_line_start),
116            dma: DmaEngine::new(dma_resumes),
117            bg_y: 0,
118            need_bg_y_step: false,
119            bg_y_offset: 0,
120            bg_x_offset: 0,
121            mwr_cache: 0,
122            row: None,
123            sprite_entries: Vec::new(),
124            pending_write: None,
125            pending_read: None,
126            commit_at: 0,
127            serve: false,
128            serve_wanted: false,
129        }
130    }
131
132    /// The master clocks the accesses since the last call asked the CPU to wait (the
133    /// reference's `hold` callable, summed).
134    pub fn take_hold(&mut self) -> i64 {
135        std::mem::take(&mut self.held)
136    }
137
138    fn hold(&mut self, clocks: i64) {
139        self.held += clocks;
140    }
141
142    // -- outputs --------------------------------------------------------------------------------
143
144    /// The /IRQ pin: held until the status port is read.
145    #[inline]
146    pub fn irq1(&self) -> bool {
147        self.status & r::IRQ_BITS != 0
148    }
149
150    #[inline]
151    pub fn bsy(&self) -> bool {
152        self.pending_write.is_some() || self.pending_read.is_some()
153    }
154
155    pub fn next_event(&self) -> Option<i64> {
156        [
157            self.seq_next_event(),
158            self.commit_event(),
159            self.dma_next_event(),
160        ]
161        .into_iter()
162        .flatten()
163        .min()
164    }
165
166    fn commit_event(&self) -> Option<i64> {
167        if self.bsy() {
168            Some(self.commit_at)
169        } else {
170            None
171        }
172    }
173
174    pub fn catch_up(&mut self, mclk: i64) {
175        loop {
176            let seq_t = self.seq_next_event();
177            let dma_t = self.dma_next_event();
178            let commit_t = self.commit_event();
179            let due = [seq_t, dma_t, commit_t]
180                .into_iter()
181                .flatten()
182                .filter(|&t| t <= mclk)
183                .min();
184            let Some(t) = due else {
185                self.dma_advance(mclk);
186                return;
187            };
188            if dma_t == Some(t) {
189                self.dma_advance(t);
190            } else if commit_t == Some(t) && seq_t.is_none_or(|seq_t| t <= seq_t) {
191                self.commit_pending();
192            } else {
193                self.dma_advance(t);
194                self.seq_run_to(t);
195            }
196        }
197    }
198
199    // -- the sync generator's calls (the VCE's line clock) ----------------------------------------
200
201    pub fn hsync(&mut self, mclk: i64, divider: i64) {
202        self.seq_hsync(mclk, divider);
203    }
204
205    pub fn vsync(&mut self) {
206        self.seq_vsync();
207        self.need_bg_y_step = false;
208        self.mwr_cache = self.regs.mwr();
209    }
210
211    // -- events from the sequencer ----------------------------------------------------------------
212
213    pub(crate) fn vblank_test(&mut self) {
214        if self.regs.cr() & r::CR_VBLANK_IRQ != 0 {
215            self.status |= r::VD;
216        }
217    }
218
219    pub(crate) fn raster_test(&mut self, count: i64) {
220        // [hw: pcetech 5.1] RCR is compared with the line counted from $40 at the first active
221        // line; values outside $40-$146 never match.
222        if count == self.regs.rcr() - 0x40 && self.regs.cr() & r::CR_RASTER_IRQ != 0 {
223            self.status |= r::RR;
224        }
225    }
226
227    pub(crate) fn latch_byr(&mut self) {
228        self.step_bg_y();
229        self.bg_y_offset = self.bg_y;
230    }
231
232    pub(crate) fn latch_bxr(&mut self) {
233        self.bg_x_offset = (self.regs.value[r::BXR] & 0x3FF) as i64;
234    }
235
236    fn step_bg_y(&mut self) {
237        if self.need_bg_y_step {
238            self.need_bg_y_step = false;
239            self.bg_y = if self.seq.rcr_count == 0 {
240                (self.regs.value[r::BYR] & 0x1FF) as i64
241            } else {
242                self.bg_y + 1
243            };
244        }
245    }
246
247    pub(crate) fn line_counter_step(&mut self, _count: i64) {
248        self.step_bg_y();
249        self.need_bg_y_step = true;
250    }
251
252    /// The scan for the next line's sprites, with the overflow flag and the narrow-display
253    /// budget (U3: Mesen2's: the VDC fetches 4, 4, 8 or 16 dots per entry between the end of
254    /// one line's display width and 16 dots before the next line's).
255    pub(crate) fn fetch_sprites(&mut self, line: i64) {
256        let seq = &self.seq;
257        let dots = 1365 / seq.divider;
258        let previous_end = py_floordiv(seq.active_end - seq.origin - HSYNC_CLOCKS, seq.divider);
259        let next_start = dots + 8 + (self.regs.hds() + 1) * 8 - 16;
260        let budget = 0.max(next_start - previous_end)
261            / sprites::CLOCKS_PER_SPRITE[((self.mwr_cache >> 2) & 3) as usize];
262        let (entries, overflow) = sprites::scan(
263            &self.vram,
264            VRAM_WORDS,
265            &self.sat,
266            line,
267            self.mwr_cache,
268            budget as usize,
269        );
270        self.sprite_entries = entries;
271        if overflow && self.regs.cr() & r::CR_OVERFLOW_IRQ != 0 {
272            self.status |= r::OR;
273        }
274    }
275
276    pub(crate) fn collision_hit(&mut self) {
277        if self.regs.cr() & r::CR_COLLISION_IRQ != 0 {
278            self.status |= r::CR_FLAG;
279        }
280    }
281
282    pub(crate) fn display_started(&mut self) {
283        self.dma_display_started(self.now);
284    }
285
286    pub(crate) fn display_ended(&mut self) {
287        self.dma_display_ended(self.now);
288    }
289
290    pub(crate) fn burst_began(&mut self) {
291        self.dma_advance(self.now);
292    }
293
294    /// The 9-bit pixels of this line, drawn as the display width begins. [hw: pcetech 5.2, 6]
295    /// Backdrop (background colour 0, $000) inside the width if either layer is on, overscan
296    /// (sprite colour 0, $100) otherwise and outside.
297    pub(crate) fn render_line(&mut self) {
298        let seq = &self.seq;
299        let dots = (1365 / seq.divider) as usize;
300        let mut row = vec![0x100u16; dots];
301        if !seq.display_line {
302            self.row = Some(row);
303            return;
304        }
305        let row_start = seq.origin + HSYNC_CLOCKS;
306        let first = py_floordiv(seq.active_start - row_start, seq.divider);
307        let width = py_floordiv(seq.active_end - seq.active_start, seq.divider);
308        let cr = seq.cr_cache;
309        let divider = seq.divider;
310        let end = (first + width).min(dots as i64);
311        if first >= end {
312            // Not reachable: a display start at or past the row's end is later than the next
313            // line's sync, which drops this line's events before `render_line` runs
314            // (sequencer.rs, `seq_leave_hsync`; the reference's comment cites issue 0004: the hdw
315            // event lands at most at the row's last dot). Kept so the slices below cannot panic.
316            self.row = Some(row);
317            return;
318        }
319        let pixels = if cr & 0x80 != 0 {
320            background::row(
321                &self.vram,
322                VRAM_WORDS,
323                self.mwr_cache,
324                self.bg_x_offset,
325                self.bg_y_offset,
326                width,
327            )
328        } else {
329            // sprites only, or neither layer inside a non-burst display period: the backdrop.
330            // [emu: Mednafen, Mesen2 and Beetle all show colour 0 of the background palette when
331            // both layers are off (Space Harrier's last 12 lines); pcetech 5.2 says overscan: C30]
332            vec![0x000; width as usize]
333        };
334        let (first_index, end_index) = (first as usize, end as usize);
335        row[first_index..end_index].copy_from_slice(&pixels[..end_index - first_index]);
336        let mut collision = None;
337        if cr & 0x40 != 0 && !self.sprite_entries.is_empty() {
338            let hit = sprites::draw(&self.sprite_entries, end - first, &mut row, first_index);
339            if let Some(hit) = hit {
340                if self.regs.cr() & r::CR_COLLISION_IRQ != 0 {
341                    // the flag rises when the beam reaches the pixel (Mesen2 runs the VDC per CPU cycle
342                    // for this; Mednafen raises it as the line is drawn): U3
343                    collision = Some(row_start + (first + hit) * divider);
344                }
345            }
346        }
347        self.row = Some(row);
348        if let Some(when) = collision {
349            self.seq_schedule(when.max(self.now), Event::Collision);
350        }
351    }
352
353    /// Commit a waiting CPU access unless a transfer holds the VRAM (Mednafen's
354    /// `CheckAndCommitPending`: nothing is committed while the SAT or VRAM DMA runs).
355    pub(crate) fn commit_unless_dma(&mut self) {
356        if !self.dma.busy() {
357            self.commit_pending();
358        }
359    }
360
361    pub(crate) fn commit_pending(&mut self) {
362        if let Some((address, word)) = self.pending_write.take() {
363            if (address as usize) < VRAM_WORDS {
364                // [hw] writes to the mirrored half are ignored
365                self.vram[address as usize] = word;
366            }
367        }
368        if let Some(address) = self.pending_read.take() {
369            // Mirrored reads "sometimes return corrupted data" [hw]; U23: this model reads 0.
370            self.regs.read_buffer = if (address as usize) < VRAM_WORDS {
371                self.vram[address as usize]
372            } else {
373                0
374            };
375        }
376    }
377
378    // -- the CPU's port ---------------------------------------------------------------------------
379
380    pub fn read(&mut self, offset: u32, mut mclk: i64) -> u8 {
381        self.catch_up(mclk);
382        let port = offset & 3;
383        if port == 0 {
384            let value = self.status | if self.bsy() { r::BSY } else { 0 };
385            self.status &= !r::IRQ_BITS;
386            return value;
387        }
388        if port == 1 {
389            return 0;
390        }
391        let msb = port == 3;
392        if self.serve
393            && (self.pending_read.is_some()
394                || (msb && self.regs.select as usize == r::VRW && self.bsy()))
395        {
396            // one of the two `data_access` calls below would wait: the board serves it first
397            self.serve_wanted = true;
398            return 0xFF;
399        }
400        if self.pending_read.is_some() {
401            // The word the last MARR write or VRR read asked for is not in the buffer yet (it
402            // waits for a CPU slot or a DMA): the CPU waits for it rather than reading the old
403            // word. The manual's read sequence and both Mednafen and Mesen2 ("D&D Order of the
404            // Griffon breaks without this") agree; the model's slot wait made the case possible.
405            mclk = self.data_access(mclk);
406        }
407        let value = if msb {
408            (self.regs.read_buffer >> 8) as u8
409        } else {
410            (self.regs.read_buffer & 0xFF) as u8
411        };
412        if msb && self.regs.select as usize == r::VRW {
413            // [hw: pcetech 5.1 $02] after the MSB read MARR advances and the next word is read
414            mclk = self.data_access(mclk);
415            self.regs.value[r::MARR] = self.regs.value[r::MARR].wrapping_add(self.regs.increment());
416            self.pending_read = Some(self.regs.value[r::MARR]);
417            self.schedule_commit(mclk);
418        }
419        value
420    }
421
422    pub fn write(&mut self, offset: u32, value: u8, mut mclk: i64) {
423        self.catch_up(mclk);
424        let port = offset & 3;
425        if port == 0 {
426            self.regs.select = value & 0x1F;
427            return;
428        }
429        if port == 1 {
430            return;
431        }
432        let register = self.regs.select;
433        if !r::valid_register(register) {
434            return;
435        }
436        let register = register as usize;
437        let msb = port == 3;
438        if register == r::VRW {
439            if !msb {
440                self.regs.write_latch = value;
441            } else {
442                if self.serve && self.bsy() {
443                    self.serve_wanted = true; // `data_access` would wait: the board serves it first
444                    return;
445                }
446                mclk = self.data_access(mclk);
447                let word = self.regs.write_latch as u16 | ((value as u16) << 8);
448                self.pending_write = Some((self.regs.value[r::MAWR], word));
449                self.regs.value[r::MAWR] =
450                    self.regs.value[r::MAWR].wrapping_add(self.regs.increment());
451                self.schedule_commit(mclk);
452            }
453            return;
454        }
455        self.regs.set_byte(register, value, msb);
456        if register == r::MARR && msb && self.serve && self.bsy() {
457            // `data_access` below would wait: the board serves it first (the access is made
458            // again after the wait and stores the same byte again)
459            self.serve_wanted = true;
460            return;
461        }
462        if register == r::MARR && msb {
463            // [hw: pcetech 5.1 $01] writing the MSB loads the read buffer from VRAM[MARR]
464            mclk = self.data_access(mclk);
465            self.pending_read = Some(self.regs.value[r::MARR]);
466            self.schedule_commit(mclk);
467        } else if register == r::BYR {
468            // [emu: Mednafen] set on both bytes: only changing on the MSB breaks a game
469            self.bg_y = (self.regs.value[r::BYR] & 0x1FF) as i64;
470        } else if register == r::SATB {
471            self.dma_arm_satb(); // [mfr] armed by a write; starts when the display period ends
472        } else if register == r::LENR && msb {
473            self.dma_start(mclk);
474        }
475    }
476
477    // -- VRAM access timing -----------------------------------------------------------------------
478
479    /// A second data-port access while one is pending holds the CPU until it commits; the
480    /// time at which the new access is accepted is returned.
481    ///
482    /// The hold is the /BUSY pin on the CPU's RDY [wiki: VDC pinout]: only the CPU stops. The
483    /// VDC's syncs come from the VCE, so the display keeps its lines while the CPU waits, and a
484    /// VRAM -> VRAM transfer the CPU waits on meets the display start like any other: paused
485    /// (C7, the default) or cancelled (`dma_resumes=false`, which serves the access there).
486    /// Issue 0004: the wait used to run this chip alone to the transfer's end, lines ahead of
487    /// the board's line clock, so the display never started during it.
488    fn data_access(&mut self, mclk: i64) -> i64 {
489        if !self.bsy() {
490            return mclk;
491        }
492        // With the board's wait wired the access stopped before this point (`serve_wanted`) and
493        // is made again once the board has served it, so nothing is pending here.
494        debug_assert!(!self.serve, "the board serves a wired VDC's wait");
495        self.wait_alone(mclk)
496    }
497
498    /// `data_access` for a VDC with no board: no line clock reaches it during the wait.
499    fn wait_alone(&mut self, mclk: i64) -> i64 {
500        let mut now = mclk;
501        while self.bsy() && self.dma.busy() {
502            // the pending access is stuck behind a transfer
503            let Some(due) = self.dma_next_event() else {
504                // paused behind the display: nothing to wait for but the end of it
505                self.dma_force_complete(now);
506                break;
507            };
508            if due > now {
509                self.hold(due - now);
510            }
511            self.catch_up(due);
512            now = now.max(due);
513        }
514        if self.bsy() {
515            let wait = self.commit_at - now;
516            if wait > 0 {
517                self.hold(wait);
518                now = self.commit_at;
519            }
520            self.commit_pending();
521        }
522        now
523    }
524
525    fn schedule_commit(&mut self, mclk: i64) {
526        if self.dma.busy() {
527            // waits for the transfer; its end commits (BSY meanwhile)
528            self.commit_at = 1 << 62;
529            return;
530        }
531        self.commit_at = self.slot_time(mclk);
532        if self.commit_at <= mclk {
533            self.commit_pending();
534        }
535    }
536
537    /// Earliest time at or after `mclk` that the CPU owns a VRAM slot (U1, provisional).
538    pub fn slot_time(&self, mclk: i64) -> i64 {
539        let seq = &self.seq;
540        if !(seq.active_display() && (seq.active_start..seq.active_end).contains(&mclk)) {
541            return mclk;
542        }
543        let div = seq.divider;
544        // first dot boundary at or after mclk
545        let mut dot = -py_floordiv(-(mclk - seq.active_start), div);
546        let slots = CPU_SLOTS[(self.regs.mwr() & 3) as usize];
547        if slots.is_empty() {
548            return seq.active_end;
549        }
550        loop {
551            let when = seq.active_start + dot * div;
552            if when >= seq.active_end {
553                return seq.active_end;
554            }
555            if slots.contains(&dot.rem_euclid(8)) {
556                return when;
557            }
558            dot += 1;
559        }
560    }
561
562    // -- display ----------------------------------------------------------------------------------
563
564    pub fn vphase(&self) -> VPhase {
565        self.seq.vphase
566    }
567
568    /// The 9-bit VDC output for the line that just ran (drawn by `render_line`).
569    pub fn pixel_row(&self, dots: usize) -> Vec<u16> {
570        match &self.row {
571            Some(row) if row.len() == dots => row.clone(),
572            _ => vec![0x100; dots],
573        }
574    }
575}