// SPDX-License-Identifier: MIT //! The composite: the picture that leaves the console with a 32X attached (milestone 4, //! docs/handoff-brief.md; megadrive-rust socket 7, `sockets::Picture`). //! //! **What the hardware does** (service manual No. 012, `A406a`/`A408a`): the Mega Drive's //! finished analog RGB reaches the 32X by the A/V cable, the Mega Drive VDP's `-MYS` (YS), //! HSYNC, VSYNC and EDCLK cross the cartridge slot, and an analog switch (IC12) puts out, //! instant by instant, either the Mega Drive's RGB or the 32X RAMDAC's, driven by `YSO`, //! which the 32X VDP derives from YS, the 32X pixel's through bit, PRI and its mode. There is //! no capture of any of it (Aubrey's decision 6): every choice below is a `Quirk` resting on //! the Manual and on detectors, and docs/claims.md says so. //! //! **The rule** (`Quirks.composite_rule`): the 32X's pixel where the 32X row is not blank //! and either its through bit differs from PRI (Manual 3.3, "Priority", figure 3.9: with //! PRI = 0 the 32X is behind the Mega Drive and a through-bit pixel in front; with PRI = 1 //! the reverse) or the Mega Drive shows nothing there (YS; `Quirks.composite_md_transparent`); //! the Mega Drive's pixel otherwise. A blank-mode row is no 32X pixel at all, so the Mega //! Drive's line is handed back untouched (`Quirks.blank_row`). //! //! **Where the 32X's pixels fall** (`Quirks.composite_alignment`, `Quirks.composite_dot`): //! in master clocks. The Mega Drive's output pixel `i` starts at `display_at + (output_delay //! + i) * pixel_mclk` (socket 7); the 32X's pixel `x` at that line's output pixel 0 plus the //! mode's offset plus `x` 32X dots of 8 MCLK, H32 included. The line handed back is on the //! 32X's dot, from the Mega Drive's output pixel 0 (the left edge of every detector's frame) //! to the end of the 32X's last pixel: in H40, with offset 0, the two pictures one for one, 320 //! wide; in H32, 323 wide (3.25 of the 32X's dots on the left show only the Mega Drive, and the //! 32X's last pixels lie past the Mega Drive's 256, over its border). Each output pixel takes //! what lies under its centre from each side. Past the Mega Drive's active picture the Mega //! Drive shows its border, taken as YS (`Quirks.composite_border`). //! //! Only the pictures' relative place is used, never socket 7's clocks against the 32X VDP's: //! `display_at + output_delay x pixel_mclk` is where megadrive-python looks the colour up //! (its CRAM-write offset), not necessarily where the RGB pins show pixel 0. //! //! **When.** Socket 7 hands a line over when the Mega Drive VDP has finished it, which, the //! VDP being lazy, can be before or after the 32X VDP's event for the same line has run (the //! 32X runs in order with its SH-2s). The two meet by the line's start clock: whichever comes //! second composes, and a line handed over first is returned as a copy of the Mega Drive's //! own, filled in place with the composite when the 32X's row is drawn -- before the frame is //! read (`System::run_frame` runs every clocked device to the 68000's clock after each //! instruction). //! //! The reference's `composite.py`. What Rust forced: the dicts that keep insertion order //! are vectors of (key, value) in that order (the oldest is what `_KEEP` drops); the //! returned row is megadrive-rust's shared `PictureRow`, filled in place as the //! reference's list is; `picture_line` is told ADEN by the device (the reference reads its //! device's register). use std::sync::{Arc, Mutex}; use megadrive_rust::sockets::{PictureLine, PictureRow}; use megadrive_rust::vdp::HName; use crate::machine::Quirks; use crate::vdp::{rgb_table, WIDTH}; /// How many lines either side may run ahead of the other before an entry is forgotten. pub const KEEP: usize = 8; /// Socket 7's device: the 32X's row laid over the Mega Drive's line. pub struct Composite { pub alignment: crate::machine::CompositeAlignment, pub dot: i64, pub border_ys: bool, /// Rows the 32X drew whose Mega Drive line has not been handed over: line start -> /// (words or None, PRI). Lines handed over before their 32X row: start -> (line, /// the list returned for it). pub drawn: Vec<(i64, (Option>, u16))>, pub pending: Vec<(i64, (PictureLine, PictureRow))>, pub maps: Vec<((i64, usize, i64), Vec<(i64, i64)>)>, /// Lines composed (a 32X row laid over a Mega Drive line), for tests and reports. pub composed: u64, } impl Composite { pub fn new(q: &Quirks) -> Composite { Composite { alignment: q.composite_alignment.value, dot: q.composite_dot.value, border_ys: q.composite_border.value == "YS", drawn: Vec::new(), pending: Vec::new(), maps: Vec::new(), composed: 0, } } // -- socket 7 --------------------------------------------------------------------- pub fn picture_line(&mut self, line: PictureLine, aden: bool) -> Option { if !aden { return None; // ADEN = 0: the 32X shows nothing (Manual 3.5) } if let Some(index) = self.drawn.iter().position(|(start, _)| *start == line.start) { let (_, (words, pri)) = self.drawn.remove(index); return self.compose(&line, words.as_deref(), pri).map(|row| Arc::new(Mutex::new(row))); } let out: PictureRow = Arc::new(Mutex::new(line.rgb.clone())); let pending = &mut self.pending; if let Some(index) = pending.iter().position(|(start, _)| *start == line.start) { // A dict assignment to a key it holds keeps the key's place. pending[index].1 = (line, out.clone()); } else { pending.push((line.start, (line, out.clone()))); } if pending.len() > KEEP { pending.remove(0); } Some(out) } // -- from the 32X VDP --------------------------------------------------------------- /// The 32X VDP drew the row of the line that starts at `start` (its display began). pub fn row_drawn(&mut self, start: i64, words: Option<&[u16]>, pri: u16) { if let Some(index) = self.pending.iter().position(|(s, _)| *s == start) { let (_, (line, out)) = self.pending.remove(index); if let Some(composed) = self.compose(&line, words, pri) { *out.lock().expect("the composite's row") = composed; } return; } let drawn = &mut self.drawn; let entry = (words.map(|w| w.to_vec()), pri); if let Some(index) = drawn.iter().position(|(s, _)| *s == start) { drawn[index].1 = entry; } else { drawn.push((start, entry)); } if drawn.len() > KEEP { drawn.remove(0); } } // -- the switch ------------------------------------------------------------------------ /// For each output pixel, the Mega Drive output pixel and the 32X pixel under its /// centre (-1 where that side has none). fn map(&mut self, line: &PictureLine) -> Vec<(i64, i64)> { let offset = match line.hmode { HName::H40 => self.alignment.h40, HName::H32 => self.alignment.h32, }; let key = (line.pixel_mclk, line.width, offset); if let Some((_, cached)) = self.maps.iter().find(|(k, _)| *k == key) { return cached.clone(); } let (pixel_mclk, width, offset) = key; let dot = self.dot; let half = dot.div_euclid(2); let mut cached = Vec::new(); let count = (offset + WIDTH as i64 * dot - half - 1).div_euclid(dot) + 1; for x in 0..count { let centre = x * dot + half; let index = centre.div_euclid(pixel_mclk); let pixel = (centre - offset).div_euclid(dot); cached.push((if index < width as i64 { index } else { -1 }, if pixel >= 0 { pixel } else { -1 })); } self.maps.push((key, cached.clone())); cached } fn compose(&mut self, line: &PictureLine, words: Option<&[u16]>, pri: u16) -> Option> { let words = words?; // blank mode: transparent, the Mega Drive's own line self.composed += 1; let (rgb, ys) = (&line.rgb, &line.ys); let rgb32 = rgb_table(); let pri = pri << 15; let border_ys = self.border_ys; let mut out = Vec::new(); for (index, x) in self.map(line) { if x < 0 { // left of the 32X's first pixel out.push(rgb[index as usize]); continue; } let word = words[x as usize]; if index < 0 { if border_ys || (word ^ pri) & 0x8000 != 0 { out.push(rgb32[usize::from(word & 0x7FFF)]); } else { out.push(0); } } else if (word ^ pri) & 0x8000 != 0 || ys[index as usize] != 0 { out.push(rgb32[usize::from(word & 0x7FFF)]); } else { out.push(rgb[index as usize]); } } Some(out) } } /// A frame as a rectangle for a PNG: socket 7 hands back composite lines (320 wide, 323 /// in H32) where the 32X drew and the Mega Drive's own (256 in H32) where it did not, so a /// frame can mix them. A narrower row is laid on the 32X's dot as the composite lays the /// Mega Drive (`Quirks.composite_dot`), its border black. A frame of one width is /// returned as it is. pub fn rectangle(rows: Vec>, quirks: Option<&Quirks>) -> Vec> { let widest = rows.iter().map(Vec::len).max().unwrap_or(0); if rows.iter().all(|row| row.len() == widest) { return rows; } let dot = match quirks { Some(q) => q.composite_dot.value, None => Quirks::default().composite_dot.value, }; rows.iter() .map(|row| { let pixel_mclk = if row.len() == 256 { 10 } else { dot }; (0..widest as i64) .map(|x| { let index = ((x * dot + dot / 2) / pixel_mclk) as usize; if index < row.len() { row[index] } else { 0 } }) .collect() }) .collect() }