// SPDX-License-Identifier: MIT //! The 32X VDP (315-5781): registers, palette, frame-buffer control, auto fill, the line //! timing its status bits and interrupts follow, and its own picture (milestone 3, //! docs/handoff-brief.md). Each row is the 32X's alone, 320 pixels wide whatever the Mega //! Drive's mode; `composite.rs` (milestone 4) lays it over the Mega Drive's line. //! //! **Where its time comes from.** The 32X VDP has no clock of its own: it takes the Mega //! Drive's EDCLK, HSYNC and VSYNC off the cartridge slot (service manual `A408a`, IC6 pins //! 64-69). Here that is socket 6: one `megadrive_rust::sockets::VideoLine` per Mega //! Drive line, each pixel's start in master clocks. From each record the VDP places, in //! dots of that line (so EDCLK's slow pixels around HSYNC count as one dot each, as the //! Manual's 100 dots = 860 MCLK does): //! //! ```text //! ======================== ============================================================== //! HBLANK rises 12 dots before the Mega Drive's HBlank flag sets (H40 H $15A), //! 23 before EDCLK's first slow dot (HSYNC): the one place where //! the Manual's four spans below come out in its own MCLK figures //! (``Quirks.hblank_phase``). In H32 the same 23 EDCLK dots before //! HSYNC: EDCLK keeps H40's dots there (``Quirks.edclk_h32``) //! PEN rises 3 dots after HBLANK (Manual 3.3, figure 3.17, A) //! FEN refresh pulse 40 Sclk from HBLANK (figure 3.17, B; ``Quirks.fen_refresh``) //! register latch 76 dots after HBLANK (figure 3.17, C) //! HBLANK falls, display 100 dots after HBLANK (figure 3.15, A = 100 dots, B = 320) //! VBLANK edges 27 dots after HBLANK, on the HBLANK that follows the last //! display line (rise) and on the one before line 0 (fall) //! (figure 3.15, C; ``Quirks.vblank_after_hblank``) //! ======================== ============================================================== //! ``` //! //! The HBLANK that precedes display row `n` lies in the Mega Drive line whose V counter is //! `n`: H40's V counter steps at H $14A, so H $15A comes 16 dots into that record, and the //! display it opens runs from H $01A to H $159. That window opens over the Mega Drive's own //! output pixel 0, as Sega's H/W Information says the two pictures lie, within half a dot //! (`Quirks.composite_alignment`). In H32 HBLANK rises 184 MCLK into the record (HSYNC at //! 368, provisional: `Quirks.edclk_h32`). //! //! Rows count from the Mega Drive's V counter; there are 224, or 240 with the 240 bit on a //! PAL console (Manual 3.3: blank periods of 38, 89 and 73 lines). //! //! **Events.** The status bits (VBLK, HBLK, PEN, FEN) are computed from the line records at //! the clock they are read. Everything that changes state is an event at its master clock, //! run in order with the SH-2s' instructions (`SH2Side.catch_up`) or up to a 68000 access //! (`Sega32X.catch_up`): HINT at HBLANK and the H counter's reload when it falls, the //! register latch, a row drawn when its display starts, VINT and the FS swap at VBLANK. //! //! **The picture.** Rows of 320 words: BGR555 with the through bit (bit 15), as the palette //! or the direct-colour pixel gives it, or None for a blank-mode row (Manual 3.3: "when the //! 32X designates blank ... [it] becomes transparent"). [`VDP32X::frame_rgb`] gives RGB888 //! for a PNG. Every choice a source does not fix is a `Quirk` (`machine.rs`). //! //! The reference's `vdp.py`. What Rust forced: //! - The reference's VDP keeps its device and reaches the device's `hen`, `hcount`, SH-2 //! side, composite and frame buffers through it. Here the device's fields it reaches are //! lent to each call that needs them as a [`Links`] (the device's other fields, which //! Rust lends beside the VDP); the frame buffers are the device's, lent the same way. //! - The event queue holds a copy of each line record; a record cancelled when its line //! is re-anchored has its queued copies marked too (the reference's events share the //! object). The queue orders by (clock, kind, sequence) as the reference's heap does. //! - `edclk_dots` is computed each time instead of cached (`functools.cache`): the same //! values. use std::cmp::Reverse; use std::collections::BinaryHeap; use megadrive_rust::sockets::VideoLine; use megadrive_rust::vdp::HName; use crate::composite::Composite; use crate::machine::Quirks; use crate::sh2side::SH2Side; /// Frame buffer: 1 Mbit, 64K words (Manual 2.1); the line table is its first 256 words. pub const WORDS: usize = 0x10000; pub const WIDTH: usize = 320; /// Event kinds, in the order two at the same clock run. pub const RISE: u8 = 0; pub const PEN_RISE: u8 = 1; pub const LATCH: u8 = 2; pub const FALL: u8 = 3; pub const VBLANK_ON: u8 = 4; pub const VBLANK_OFF: u8 = 5; pub const FAR: i64 = 1 << 62; /// EDCLK's 33 slow dots from HSYNC, in MCLK: four runs of 15 EDCLK cycles of 5 MCLK, one /// 8-MCLK dot apart, paired two cycles to a dot -- the H40 line's $1CD-$1ED as /// megadrive-python has them; in H32 taken the same (EDCLK is made outside the VDP: /// `Quirks.edclk_h32`). pub const SLOW_DOTS: [i64; 33] = [ 10, 10, 10, 10, 10, 10, 10, 9, 9, 10, 10, 10, 10, 10, 10, 10, 8, 10, 10, 10, 10, 10, 10, 10, 9, 9, 10, 10, 10, 10, 10, 10, 10, ]; /// The H40 HBlank flag ($166) lies this many dots before EDCLK's first slow dot ($1CD), so /// `Quirks.hblank_phase` (dots before the flag) + this = dots before the slow run. pub const FLAG_TO_SLOW: i64 = 11; /// EDCLK's dot starts over a line of `length` MCLK whose slow run starts `slow` MCLK in, /// 8 MCLK apart elsewhere (the first at or after 0), and the slow run's index. pub fn edclk_dots(slow: i64, length: i64) -> (Vec, i64) { let mut dots: Vec = (slow.rem_euclid(8)..slow).step_by(8).collect(); let first = dots.len() as i64; let mut t = slow; for width in SLOW_DOTS { dots.push(t); t += width; } dots.extend((t..length).step_by(8)); (dots, first) } /// One Mega Drive line as the 32X VDP sees it: its edges in master clocks. #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct LineTiming { pub cancelled: bool, pub end: i64, pub fall: i64, pub latch: i64, pub pal: bool, pub pen_rise: i64, pub published: i64, pub refresh_end: i64, pub rise: i64, pub start: i64, pub v: i64, pub vedge: i64, } impl LineTiming { pub fn new(line: &VideoLine, q: &Quirks) -> LineTiming { let start = line.start; let dots = q.hblank_phase.value; // dots before the H40 flag (negative: after) let owned; let (pixels, rise_dot): (&[i64], i64) = if line.hmode == HName::H40 { // The Mega Drive's HBlank flag sets at pixel k of the record ($166); socket 6's // H40 pixels are EDCLK's dots. let pixels = line.pixels; let offset = line.hblank_set - start; let mut k = 0usize; while k < pixels.len() && pixels[k] < offset { k += 1; } (pixels, k as i64 - dots) } else { // H32: the record's pixels are the Mega Drive's 10-MCLK dots, but EDCLK, which // the 32X counts, keeps H40's dots and slow run, from HSYNC (Quirks.edclk_h32). let slow; (owned, slow) = edclk_dots(q.edclk_h32.value, line.length); (&owned[..], slow - dots - FLAG_TO_SLOW) }; let last = pixels.len() as i64 - 1; let at = |dot: i64| -> i64 { if dot <= last { return start + pixels[dot as usize]; } start + line.length + (dot - last - 1) * 8 // past the record: 8 MCLK dots }; let timings = q.hblank_timing.value; let rise = at(rise_dot); LineTiming { start, end: start + line.length, v: line.v, pal: line.pal, published: line.published, cancelled: false, rise, pen_rise: at(rise_dot + timings.pen), latch: at(rise_dot + timings.latch), fall: at(rise_dot + timings.blank), vedge: at(rise_dot + q.vblank_after_hblank.value), refresh_end: rise + q.fen_refresh.value * 7 / 3, } } } /// An event of the queue: (clock, kind, sequence) and the line record it belongs to. #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Event { pub at: i64, pub kind: u8, pub seq: u64, pub timing: LineTiming, } impl PartialOrd for Event { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Event { fn cmp(&self, other: &Self) -> std::cmp::Ordering { (self.at, self.kind, self.seq).cmp(&(other.at, other.kind, other.seq)) } } /// A row of the 32X's picture: 320 words, or None for a blank-mode row. pub type Row = Option>; /// What the VDP reaches of its device (the reference's `self.device`): lent for a call. pub struct Links<'a> { pub hen: bool, pub hcount: u16, pub sh2: Option<&'a mut SH2Side>, pub composite: Option<&'a mut Composite>, pub framebuffers: &'a [Vec; 2], } /// The 32X VDP that both CPUs reach (`$A15180`/`$20004100`) and its picture. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct VDP32X { #[serde(skip, default)] pub quirks: Option, pub bitmap_writable: u16, // The registers as written (and read back: Manual 3.2.3 gives no read delay, and // the Mars Check Program's register tests poll until a written mode reads back). pub bitmap: u16, pub shift: u16, pub fill_length: u16, pub fill_start: u16, pub fill_data: u16, /// As the display circuit latched them, 76 dots after HBLANK (Manual 3.3). pub latched_mode: u16, pub latched_pri: u16, pub latched_shift: u16, pub latched_240: u16, /// FS: the frame buffer displayed; the CPUs reach the other one (Manual 3.1). pub fs: usize, pub fs_pending: Option, pub palette: Vec, pub ntsc: bool, /// The end of the auto fill under way (master clocks), for FEN. pub fill_end: i64, /// The H interrupt's internal counter and whether HBLANK's fall reloads it. pub hint_counter: i64, pub hint_reload: bool, pub vblank: bool, /// Line records still needed, oldest first; the event queue. pub timings: Vec, pub events: BinaryHeap>, pub seq: u64, pub next_event: i64, /// The first SH-2 state an event is due at (`SH2Side.catch_up`). pub next_state: i64, /// The frame being drawn, row by row, and the last finished one. pub rows: Vec, pub row_pri: Vec, pub picture: Option>, pub picture_pri: Vec, pub frames: u64, } impl VDP32X { pub fn new(quirks: &Quirks) -> VDP32X { let mut vdp = VDP32X { quirks: Some(*quirks), bitmap_writable: quirks.bitmap_bits.value as u16, bitmap: 0, shift: 0, fill_length: 0, fill_start: 0, fill_data: 0, latched_mode: 0, latched_pri: 0, latched_shift: 0, latched_240: 0, fs: 0, fs_pending: None, palette: vec![0; 256], ntsc: true, fill_end: -1, hint_counter: 0, hint_reload: false, vblank: true, timings: Vec::new(), events: BinaryHeap::new(), seq: 0, next_event: FAR, next_state: FAR, rows: vec![None; 240], row_pri: vec![0; 240], picture: None, picture_pri: Vec::new(), frames: 0, }; vdp.reset(); vdp } fn q(&self) -> &Quirks { self.quirks.as_ref().expect("the VDP's quirks") } pub fn reset(&mut self) { self.bitmap = 0; self.shift = 0; self.fill_length = 0; self.fill_start = 0; self.fill_data = 0; self.latched_mode = 0; self.latched_pri = 0; self.latched_shift = 0; self.latched_240 = 0; self.fs = 0; self.fs_pending = None; self.palette = vec![0; 256]; self.ntsc = true; self.fill_end = -1; self.hint_counter = 0; self.hint_reload = false; self.vblank = true; self.timings = Vec::new(); self.events = BinaryHeap::new(); self.seq = 0; self.next_event = FAR; self.next_state = FAR; self.rows = vec![None; 240]; self.row_pri = vec![0; 240]; self.picture = None; self.picture_pri = Vec::new(); self.frames = 0; } // -- socket 6 --------------------------------------------------------------------- /// A line record. With ADEN = 0 (`running` false) the VDP keeps only its timing: /// nothing can reach the registers then (testpico t_32x_init: the VDP hangs without /// ADEN), and no event is queued. pub fn video_line(&mut self, line: &VideoLine, running: bool) { let timing = LineTiming::new(line, self.q()); self.ntsc = !line.pal; let timings = &mut self.timings; if let Some(last) = timings.last_mut().filter(|last| last.start == timing.start && last.v == timing.v) { // Re-anchored at its HBlank by an H32/H40 change: the old record's events not // yet run are dropped, the new one's from its publication on are queued. let old = *last; *last = timing; self.cancel_queued(old); } else { timings.push(timing); if timings.len() > 512 { let cut = timings.len() - 256; timings.drain(..cut); } } if !running { if !self.events.is_empty() { self.events.clear(); self.next(); } let keep = self.timings.len().saturating_sub(4); self.timings.drain(..keep); return; } let after = timing.published; if timing.rise >= after { self.push(timing.rise, RISE, timing); } if timing.latch >= after { self.push(timing.latch, LATCH, timing); } if timing.fall >= after { self.push(timing.fall, FALL, timing); } if timing.vedge >= after { let active = self.active_rows(Some(&timing)); if timing.v == active { self.push(timing.vedge, VBLANK_ON, timing); } else if timing.v == 0 { self.push(timing.vedge, VBLANK_OFF, timing); } } } /// Mark the queued copies of a cancelled record (the reference's events share it). fn cancel_queued(&mut self, old: LineTiming) { if self.events.iter().any(|Reverse(e)| e.timing == old) { let events = std::mem::take(&mut self.events).into_vec(); self.events = events .into_iter() .map(|Reverse(mut e)| { if e.timing == old { e.timing.cancelled = true; } Reverse(e) }) .collect(); } } fn push(&mut self, at: i64, kind: u8, timing: LineTiming) { self.seq += 1; self.events.push(Reverse(Event { at, kind, seq: self.seq, timing })); if at < self.next_event { self.next_event = at; self.next_state = (at * 3 + 6).div_euclid(7); } } fn next(&mut self) { if let Some(Reverse(first)) = self.events.peek() { self.next_event = first.at; self.next_state = (self.next_event * 3 + 6).div_euclid(7); } else { self.next_event = FAR; self.next_state = FAR; } } /// Run every event due at or before `mclk`. pub fn advance(&mut self, mclk: i64, links: &mut Links) { while let Some(Reverse(first)) = self.events.peek() { if first.at > mclk { break; } let Reverse(event) = self.events.pop().expect("an event"); let timing = event.timing; if timing.cancelled { continue; } match event.kind { RISE => self.hblank_rise(&timing, links), LATCH => self.latch(), FALL => self.hblank_fall(&timing, links), VBLANK_ON => self.vblank_on(links), VBLANK_OFF => self.vblank_off(links), _ => {} } } self.next(); } /// Forget line records that end before `mclk` (no CPU is behind it), keeping two. pub fn prune(&mut self, mclk: i64) { let timings = &mut self.timings; let mut drop = 0; while drop + 2 < timings.len() && timings[drop].end <= mclk { drop += 1; } if drop != 0 { timings.drain(..drop); } } // -- the line's edges --------------------------------------------------------------- /// 224, or 240 with the 240 bit on a PAL console (Manual 3.2.3: "Valid only when /// PAL"; on NTSC the bit causes "operating errors", not modelled). pub fn active_rows(&self, timing: Option<&LineTiming>) -> i64 { let pal = match timing { Some(timing) => timing.pal, None => !self.ntsc, }; if pal && self.latched_240 != 0 { 240 } else { 224 } } /// HINT at HBLANK (Manual 3.2.2): the internal counter fires at 0 and is reloaded /// from the H count register when this HBLANK falls, else counts down; in VBLANK only /// with HEN, and without HEN it is reloaded at each fall (`Quirks.hint_counter`). fn hblank_rise(&mut self, timing: &LineTiming, links: &mut Links) { if self.vblank_at(timing, timing.rise) && !links.hen { self.hint_reload = true; return; } if self.hint_counter <= 0 { self.hint_reload = true; if let Some(sh2) = links.sh2.as_deref_mut() { if sh2.running { sh2.raise_hint(); } } } else { self.hint_counter -= 1; } } fn hblank_fall(&mut self, timing: &LineTiming, links: &mut Links) { if self.hint_reload { self.hint_counter = i64::from(links.hcount); self.hint_reload = false; } let row = timing.v; if row < self.active_rows(Some(timing)) && row < 240 { self.draw(row as usize, links.framebuffers); if let Some(composite) = links.composite.as_deref_mut() { composite.row_drawn(timing.start, self.rows[row as usize].as_deref(), self.row_pri[row as usize]); } } } /// The display circuit takes bitmap mode, PRI, 240 and shift for the next row /// (Manual 3.3, "VDP Register Latch Timing"); a swap waiting for blank mode happens /// now (`Quirks.fs_swap`). fn latch(&mut self) { let bitmap = self.bitmap; self.latched_mode = bitmap & 3; self.latched_pri = (bitmap >> 7) & 1; self.latched_240 = (bitmap >> 6) & 1; self.latched_shift = self.shift & 1; if self.latched_mode == 0 { if let Some(fs) = self.fs_pending.take() { self.fs = fs; } } } /// VBLANK: the frame is finished, a pending FS swaps (Manual 3.2.3: "swapping is /// done at the next V Blank"), VINT is raised (`Quirks.vint_at`). fn vblank_on(&mut self, links: &mut Links) { self.vblank = true; let active = self.active_rows(None) as usize; self.picture = Some(self.rows[..active].to_vec()); self.picture_pri = self.row_pri[..active].to_vec(); self.rows = vec![None; 240]; self.frames += 1; if let Some(fs) = self.fs_pending.take() { self.fs = fs; } if let Some(sh2) = links.sh2.as_deref_mut() { if sh2.running { sh2.raise_vint(true); } } } fn vblank_off(&mut self, links: &mut Links) { self.vblank = false; if let Some(sh2) = links.sh2.as_deref_mut() { if sh2.running { sh2.raise_vint(false); } } } // -- status at a clock ---------------------------------------------------------------- pub fn timing_at(&self, mclk: i64) -> Option<&LineTiming> { let timings = &self.timings; for timing in timings.iter().rev() { if timing.start <= mclk { return Some(timing); } } timings.first() } fn vblank_at(&self, timing: &LineTiming, mclk: i64) -> bool { let v = timing.v; if v == 0 { return mclk < timing.vedge; } let active = self.active_rows(Some(timing)); if v < active { return false; } if v == active { return mclk >= timing.vedge; } true } /// (VBLK, HBLK, PEN, FEN) at `mclk`. pub fn status(&self, mclk: i64) -> (bool, bool, bool, bool) { let Some(timing) = self.timing_at(mclk) else { return (true, true, true, mclk < self.fill_end); }; let (hblank, pen_on, refresh, vblank); if mclk >= timing.end { // Not yet published (the Mega Drive's VDP is lazy): the next line, predicted // with this one's geometry. let length = timing.end - timing.start; let offset = (mclk - timing.start).rem_euclid(length); hblank = timing.rise - timing.start <= offset && offset < timing.fall - timing.start; pen_on = timing.pen_rise - timing.start <= offset && offset < timing.fall - timing.start; refresh = timing.rise - timing.start <= offset && offset < timing.refresh_end - timing.start; vblank = self.vblank; } else { hblank = timing.rise <= mclk && mclk < timing.fall; pen_on = timing.pen_rise <= mclk && mclk < timing.fall; refresh = timing.rise <= mclk && mclk < timing.refresh_end; vblank = self.vblank_at(timing, mclk); } let pen = vblank || pen_on || self.latched_mode == 0 || self.latched_mode == 2; let fen = refresh || mclk < self.fill_end; (vblank, hblank, pen, fen) } /// Master clocks until PEN = 1 from `mclk` (0 if it is): "If accessing when PEN = /// 0, wait is held until PEN = 1" (Manual 3.3; `Quirks.palette_wait`). pub fn palette_wait(&self, mclk: i64) -> i64 { if self.status(mclk).2 { return 0; } let Some(timing) = self.timing_at(mclk) else { return 0; }; let length = timing.end - timing.start; let pen = timing.pen_rise - timing.start; let offset = (mclk - timing.start).rem_euclid(length); if offset < pen { pen - offset } else { length - offset + pen } } // -- registers -------------------------------------------------------------------------- /// A word of $A15180-$A1518F (`offset` 0-$E). pub fn read(&self, offset: u32, mclk: i64) -> u16 { match offset { 0x0 => (if self.ntsc { 0x8000 } else { 0 }) | self.bitmap, // PAL bit: 0 = PAL 0x2 => self.shift, 0x4 => self.fill_length, 0x6 => self.fill_start, 0x8 => self.fill_data, 0xA => { let (vblank, hblank, pen, fen) = self.status(mclk); (u16::from(vblank) << 15) | (u16::from(hblank) << 14) | (u16::from(pen) << 13) | (u16::from(fen) << 1) | self.fs as u16 } _ => 0, } } pub fn write(&mut self, offset: u32, value: u16, lanes: u16, mclk: i64, framebuffers: &mut [Vec; 2]) { let keep = !lanes; let value = value & lanes; match offset { 0x0 => self.bitmap = ((self.bitmap & keep) | value) & self.bitmap_writable, 0x2 => self.shift = ((self.shift & keep) | value) & 1, 0x4 => self.fill_length = ((self.fill_length & keep) | value) & 0xFF, 0x6 => self.fill_start = (self.fill_start & keep) | value, 0x8 => { self.fill_data = (self.fill_data & keep) | value; self.fill(mclk, framebuffers); } 0xA if lanes & 0x00FF != 0 => { let fs = usize::from(value & 1); if self.status(mclk).0 || self.bitmap & 3 == 0 { self.fs = fs; self.fs_pending = None; } else { self.fs_pending = Some(fs); // "swapping is done at the next V Blank" } } _ => {} } } /// Manual 3.2.3: length + 1 words of the data from the start address, A16-A9 fixed /// and A8-A1 counting (so it wraps in its 256-word page). The words are written at /// once; FEN reads 1 for the fill's 7 + 3 x length Sclk (Manual 3.3; `Quirks. /// auto_fill`). fn fill(&mut self, mclk: i64, framebuffers: &mut [Vec; 2]) { let buffer = &mut framebuffers[self.fs ^ 1]; let mut start = self.fill_start; let (high, low) = ((self.fill_data >> 8) as u8, self.fill_data as u8); let words = i64::from(self.fill_length) + 1; for _ in 0..words { let offset = usize::from(start) << 1; buffer[offset] = high; buffer[offset + 1] = low; start = (start & 0xFF00) | (start.wrapping_add(1) & 0xFF); } self.fill_start = start; let busy = (7 + 3 * words) * 7 / 3; self.fill_end = self.fill_end.max(mclk) + busy; } // -- the picture -------------------------------------------------------------------------- /// Row `row` from the displayed frame buffer, as latched for it (Manual 3.3, "Line /// Table Format": the row's word address, and 320 pixels' worth from there, running on /// through the address space, so into the overwrite image's alias of the same DRAM). fn draw(&mut self, row: usize, framebuffers: &[Vec; 2]) { self.row_pri[row] = self.latched_pri; let mode = self.latched_mode; if mode == 0 { self.rows[row] = None; return; } let fb = &framebuffers[self.fs]; let mut address = (usize::from(fb[row << 1]) << 8) | usize::from(fb[(row << 1) + 1]); let palette = &self.palette; if mode == 1 { // packed pixel: a palette index a byte, high byte first // DOC: Technical Bulletin #14, the shift is ignored on a line whose address's // low byte is $FF. OBSERVED (ares 9408cb4, M32X::VDP::scanlineMode1): the // shift moves packed pixels only (Quirks.screen_shift_modes, provisional). let shift = usize::from(self.latched_shift != 0 && (address & 0xFF) != 0xFF); let data = bytes_at(fb, (address << 1) + shift, WIDTH); self.rows[row] = Some(data.iter().map(|&index| palette[usize::from(index)]).collect()); } else if mode == 2 { // direct colour: a word a pixel let data = bytes_at(fb, address << 1, WIDTH * 2); self.rows[row] = Some(data.chunks(2).map(|w| u16::from(w[0]) << 8 | u16::from(w[1])).collect()); } else { // run length: (length - 1, index) a word, 1-256 pixels let mut out: Vec = Vec::with_capacity(WIDTH + 256); while out.len() < WIDTH { let offset = (address & 0xFFFF) << 1; let count = usize::from(fb[offset]) + 1; let colour = palette[usize::from(fb[offset + 1])]; address += 1; out.extend(std::iter::repeat(colour).take(count)); } out.truncate(WIDTH); self.rows[row] = Some(out); } } /// The last finished frame as rows of RGB888 (each 5-bit level as `v << 3 | /// v >> 2`: the RAMDAC's levels are unmeasured, docs/undocumented-behavior.md); a /// blank-mode row is `blank`. pub fn frame_rgb(&self, blank: u32) -> Vec> { let Some(picture) = &self.picture else { return vec![vec![blank; WIDTH]; 224]; }; let rgb = rgb_table(); picture .iter() .map(|row| match row { None => vec![blank; WIDTH], Some(row) => row.iter().map(|&word| rgb[usize::from(word & 0x7FFF)]).collect(), }) .collect() } } pub fn bytes_at(fb: &[u8], offset: usize, size: usize) -> Vec { let offset = offset & 0x1FFFF; let end = offset + size; if end <= 0x20000 { return fb[offset..end].to_vec(); } let mut out = fb[offset..].to_vec(); out.extend_from_slice(&fb[..end - 0x20000]); out } fn level(v: u32) -> u32 { (v << 3) | (v >> 2) } /// BGR555 -> RGB888 (R in bits 4-0, G 9-5, B 14-10: Manual 3.3, "Color Palette"). pub fn rgb_table() -> &'static [u32] { static TABLE: std::sync::OnceLock> = std::sync::OnceLock::new(); TABLE.get_or_init(|| { (0..0x8000u32).map(|c| (level(c & 31) << 16) | (level((c >> 5) & 31) << 8) | level((c >> 10) & 31)).collect() }) }