pcengine_rust/vdc/
sprites.rs

1//! Sprites: the line scan of the sprite attribute table, and the drawing of the line's sprites
2//! (`vdc/sprites.py`).
3//!
4//! [hw: pcetech 5.3; mfr: Hudson HuC6270 manual] The 64-entry table (SAT, filled only by the VRAM ->
5//! SAT DMA) holds, per sprite: Y (10 bits, the first visible line is 64), X (10 bits, 32 is the
6//! display's left edge), pattern (bits 10-1; bit 0 is the CG bit), and flags: palette (3-0), priority
7//! (7), width 16/32 (8), flip X (11), height 16/32/64 (13-12), flip Y (15). A pattern is 16 x 16
8//! pixels = 64 words, four planes of 16 words. Larger sprites use neighbouring patterns: width 32
9//! clears pattern bit 0, height 32 clears bit 1, height 64 clears bits 2 and 1; flips act on the whole
10//! sprite.
11//!
12//! Per line the scan finds the sprites that cover the *next* line, in table order, up to 16 pattern
13//! entries (a 32-wide sprite is two entries); a 17th needed entry sets the overflow flag and ends the
14//! scan. The first opaque pixel in buffer order wins; a pixel is in front of the background if its
15//! priority bit is set or the background pixel is transparent; sprite 0 colliding with another
16//! sprite's opaque pixel sets the collision flag. When MWR's sprite access width is 1 the pattern
17//! is two bitplanes, picked by the CG bit (SP0/SP1 or SP2/SP3).
18//!
19//! Provisional (U3, tier 5): that the scan reads the pattern words when it finds the sprite (the
20//! line before it is drawn), as Mednafen does; the narrow-display budget below is Mesen2's.
21
22use serde::{Deserialize, Serialize};
23
24pub const HEIGHTS: [i64; 4] = [16, 32, 64, 64];
25pub const HEIGHT_MASKS: [u32; 4] = [!0, !2, !6, !6];
26/// [mfr: SM table; emu: Mesen2] dots of fetch time per entry
27pub const CLOCKS_PER_SPRITE: [i64; 4] = [4, 4, 8, 16];
28
29pub const SPRITE_LIMIT: usize = 16;
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
32pub struct Entry {
33    /// left pixel, in display columns (may be negative or past the width)
34    pub x: i64,
35    /// palette << 4
36    pub palette: u16,
37    pub priority: bool,
38    pub hflip: bool,
39    pub sprite0: bool,
40    pub planes: [u16; 4],
41}
42
43/// The entries of sprites covering `line` (counted from the first display line), and whether
44/// a 17th entry was needed (overflow).
45pub fn scan(
46    vram: &[u16],
47    size: usize,
48    sat: &[u16],
49    line: i64,
50    mwr: u16,
51    limit: usize,
52) -> (Vec<Entry>, bool) {
53    let mut entries: Vec<Entry> = Vec::new();
54    let cg_two_planes = ((mwr >> 2) & 3) == 1;
55    for i in 0..64 {
56        let (w0, w1, w2, w3) = (sat[4 * i], sat[4 * i + 1], sat[4 * i + 2], sat[4 * i + 3]);
57        let y = (w0 & 0x3FF) as i64 - 64;
58        let shape = ((w3 >> 12) & 3) as usize;
59        let height = HEIGHTS[shape];
60        if !(y..y + height).contains(&line) {
61            continue;
62        }
63        let wide = w3 & 0x100 != 0;
64        let hflip = w3 & 0x800 != 0;
65        let mut row = line - y;
66        if w3 & 0x8000 != 0 {
67            row = height - 1 - row;
68        }
69        let row = row as u32;
70        let mut pattern = ((w2 as u32 >> 1) & 0x3FF) & HEIGHT_MASKS[shape];
71        pattern |= (row & 0x30) >> 3;
72        if wide {
73            pattern &= !1;
74        }
75        let base_x = (w1 & 0x3FF) as i64 - 32;
76        for half in 0..(if wide { 2u32 } else { 1 }) {
77            if entries.len() == SPRITE_LIMIT {
78                // [mfr] "17 or more": the rest of the scan is dropped
79                entries.truncate(limit);
80                return (entries, true);
81            }
82            let cell = pattern | if wide { half ^ hflip as u32 } else { 0 };
83            let address = (cell * 64 + (row & 15)) as usize;
84            let planes = if address + 48 >= size {
85                // [emu: Mesen2] an empty sprite past the VRAM; U23
86                [0, 0, 0, 0]
87            } else if cg_two_planes {
88                let shift = if w2 & 1 != 0 { 32 } else { 0 };
89                [vram[address + shift], vram[address + shift + 16], 0, 0]
90            } else {
91                [
92                    vram[address],
93                    vram[address + 16],
94                    vram[address + 32],
95                    vram[address + 48],
96                ]
97            };
98            entries.push(Entry {
99                x: base_x + 16 * half as i64,
100                palette: (w3 & 0xF) << 4,
101                priority: w3 & 0x80 != 0,
102                hflip,
103                sprite0: i == 0,
104                planes,
105            });
106        }
107    }
108    entries.truncate(limit);
109    (entries, false)
110}
111
112/// Draw the entries over `row` (the line's 9-bit pixels; the display starts at index `first`).
113///
114/// Returns the display column of the first pixel where sprite 0 hit another sprite, or None.
115pub fn draw(entries: &[Entry], width: i64, row: &mut [u16], first: usize) -> Option<i64> {
116    let mut buffer = vec![0u16; width.max(0) as usize];
117    let mut hit: Option<i64> = None;
118    for entry in entries.iter().rev() {
119        let [p0, p1, p2, p3] = entry.planes;
120        for x in 0..16i64 {
121            let column = entry.x + x;
122            if !(0..width).contains(&column) {
123                continue;
124            }
125            let bit = if entry.hflip { x } else { 15 - x };
126            let raw = ((p0 >> bit) & 1)
127                | (((p1 >> bit) & 1) << 1)
128                | (((p2 >> bit) & 1) << 2)
129                | (((p3 >> bit) & 1) << 3);
130            if raw == 0 {
131                continue;
132            }
133            let slot = &mut buffer[column as usize];
134            if entry.sprite0 && *slot & 0x0F != 0 && hit.is_none_or(|h| column < h) {
135                hit = Some(column);
136            }
137            *slot = 0x100 | entry.palette | raw | if entry.priority { 0x200 } else { 0 };
138        }
139    }
140    for (column, &value) in buffer.iter().enumerate() {
141        if value & 0x0F != 0 {
142            let target = first + column;
143            if row[target] & 0x0F == 0 || value & 0x200 != 0 {
144                row[target] = value & 0x1FF;
145            }
146        }
147    }
148    hit
149}