Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_vram/
lib.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Typed VRAM primitives.
3//!
4//! PS1 VRAM is a 1024×512 halfword frame, and getting a sprite
5//! on screen is three interlocking decisions: *where* the texel
6//! bytes live, *where* the CLUT lives, and *what* format you're
7//! in. PsyQ leaves those as `short` variables you pass around by
8//! convention. This crate promotes them to types.
9//!
10//! ## What's here
11//!
12//! - [`Color555`] -- a 15bpp BGR pixel. Constructed via
13//!   [`Color555::rgb8`] (`u8` RGB → 5-bit truncation), or
14//!   [`Color555::rgb5`] (already 5-bit), or the `const` raw
15//!   constructor [`Color555::raw`].
16//! - [`VramRect`] -- an `(x, y, w, h)` in VRAM pixels with const
17//!   validation of the bounds. Can't construct one that would
18//!   overflow VRAM.
19//! - [`TexturePage`] -- a texture-page handle. Const constructor
20//!   enforces the PSX alignment rules (`x % 64 == 0`, `y ∈ {0, 256}`),
21//!   knows its bit-depth, and emits the GP0(E1h) draw-mode word
22//!   or the 16-bit tpage field embedded in textured-rect UV words.
23//! - [`Clut`] -- a CLUT handle. `x % 16 == 0`, `y ∈ 0..512`. Emits
24//!   the 16-bit clut field for UV words. 4bpp and 8bpp CLUTs are
25//!   the same underlying type -- the calling primitive's tpage
26//!   picks which entry count it uses.
27//! - [`upload_16bpp`] -- safe upload wrapper: checks `pixels.len()`
28//!   matches `rect.w * rect.h`, packs to GP0 0xA0 + word stream.
29//!
30//! ## What's NOT here (yet)
31//!
32//! - Compile-time tpage-overlap detection. A later pass can wrap
33//!   allocations in a const-generic `Layout<...>` that enforces
34//!   non-overlap across a fixed set of TexturePage/Clut declarations;
35//!   kept out for now because the rules around the 16-pixel CLUT
36//!   stride + tpage-row sharing get messy to express in bare
37//!   Rust const generics, and a build-time allocator tool is a
38//!   cleaner path when we're ready.
39//! - TIM parsing. Runtime / proc-macro loading lives in
40//!   `psx-asset` when it lands.
41//! - 4bpp / 8bpp upload helpers. PsyQ packs those as 16-bit
42//!   halfwords too (4 / 2 texels per halfword); the same
43//!   `upload_16bpp` works once the caller has pre-packed the
44//!   indices. A typed `upload_4bpp(rect, &[u8], clut)` would be
45//!   nicer; it's one of the first obvious follow-ups.
46//!
47//! ## Why these types over PsyQ's shorts
48//!
49//! Every field has rules PsyQ leaves to the programmer. TexturePage X
50//! must be a multiple of 64; Y must be 0 or 256. CLUT X must be
51//! a multiple of 16. Upload sizes are clamped on hardware but
52//! wrap (wrap, not truncate) on the real DMA controller if you
53//! oversize them. Getting any of these wrong in PsyQ silently
54//! corrupts VRAM. Const-validating them at construction means
55//! the bug can't compile -- which is the whole point of writing
56//! a Rust SDK instead of a C one.
57
58#![no_std]
59#![deny(unsafe_op_in_unsafe_fn)]
60#![warn(missing_docs)]
61
62use psx_hw::gpu::{gp0, gp1, pack_xy};
63use psx_io::dma::{self, Channel};
64use psx_io::gpu::{pause_recording, wait_command_ready, write_command, write_display_control};
65use psx_io::periph::GpuDma;
66
67/// VRAM framebuffer width in pixels.
68pub const VRAM_WIDTH: u16 = 1024;
69/// VRAM framebuffer height in pixels.
70pub const VRAM_HEIGHT: u16 = 512;
71
72// ======================================================================
73// Color
74// ======================================================================
75
76/// A 15-bit BGR pixel as stored in VRAM.
77///
78/// PSX VRAM stores every halfword in BGR-555-with-mask-bit layout:
79///
80/// ```text
81///   bit  15   14..10   9..5   4..0
82///        m    B       G      R
83/// ```
84///
85/// The mask bit is bit 15; [`Color555::rgb8`] constructs with the
86/// mask bit clear (most common). The "transparency" that games rely
87/// on for CLUT sprites is `Color555::raw(0)` -- PSX treats an
88/// all-zero texel as transparent in direct-color mode.
89#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
90#[repr(transparent)]
91pub struct Color555(u16);
92
93impl Color555 {
94    /// Fully-transparent texel (value 0). PSX treats this as "skip"
95    /// when sampling a textured primitive, regardless of mode.
96    pub const TRANSPARENT: Self = Self(0);
97    /// Opaque black with mask bit clear.
98    pub const BLACK: Self = Self(0);
99    /// Opaque white -- all five bits set in each channel.
100    pub const WHITE: Self = Self(0x7fff);
101
102    /// Build a color from 8-bit channels, truncating the low 3 bits
103    /// of each. `rgb8(255, 255, 255) == WHITE`.
104    ///
105    /// Matches PsyQ's `getTPage(0, r, g, b)` and
106    /// `setRGB0(prim, r, g, b)` convention where the caller writes
107    /// 8-bit values; hardware sees 5 bits per channel.
108    pub const fn rgb8(r: u8, g: u8, b: u8) -> Self {
109        let r = (r as u16) >> 3;
110        let g = (g as u16) >> 3;
111        let b = (b as u16) >> 3;
112        Self(r | (g << 5) | (b << 10))
113    }
114
115    /// Build a color from already-5-bit channels. Asserts each
116    /// fits in 5 bits. `rgb5(31, 31, 31) == WHITE`.
117    pub const fn rgb5(r: u8, g: u8, b: u8) -> Self {
118        assert!(r < 32, "rgb5: red must be < 32");
119        assert!(g < 32, "rgb5: green must be < 32");
120        assert!(b < 32, "rgb5: blue must be < 32");
121        Self((r as u16) | ((g as u16) << 5) | ((b as u16) << 10))
122    }
123
124    /// Construct from the raw VRAM halfword. Useful when decoding
125    /// CLUT bytes or loading pre-packed asset data.
126    pub const fn raw(value: u16) -> Self {
127        Self(value)
128    }
129
130    /// Underlying VRAM halfword.
131    pub const fn as_u16(self) -> u16 {
132        self.0
133    }
134
135    /// Set the mask bit (bit 15). Matters when `GP0 0xE6` has
136    /// "check mask on draw" enabled -- writes are skipped where
137    /// existing mask is set. Games use this for UI overlays.
138    ///
139    /// In a **CLUT entry** bit 15 means something else entirely: see
140    /// [`Self::with_semi_transparency`].
141    pub const fn with_mask_bit(self) -> Self {
142        Self(self.0 | 0x8000)
143    }
144
145    /// Set the semi-transparency bit (STP, bit 15) for use in a **CLUT entry**.
146    ///
147    /// This is the same bit as [`Self::with_mask_bit`], but when the halfword
148    /// is a palette entry rather than a framebuffer pixel the GPU reads it as
149    /// "blend this texel". Selecting a blend mode on a textured primitive is
150    /// not enough on its own: the mode says *how* to blend, STP says *which
151    /// texels* blend. A palette without it draws fully opaque whatever blend
152    /// mode the primitive carries, and nothing reports it -- a silent failure
153    /// that reads like a brightness bug rather than a blending one.
154    ///
155    /// Set it on every entry of an additive or translucent palette, leaving
156    /// the fully transparent index (usually 0) at [`Self::TRANSPARENT`].
157    #[doc(alias = "STP")]
158    pub const fn with_semi_transparency(self) -> Self {
159        Self(self.0 | 0x8000)
160    }
161
162    /// Whether bit 15 is set (the mask bit, or STP in a CLUT entry).
163    #[doc(alias = "STP")]
164    pub const fn is_semi_transparent(self) -> bool {
165        self.0 & 0x8000 != 0
166    }
167}
168
169// ======================================================================
170// Rect
171// ======================================================================
172
173/// An `(x, y, w, h)` rectangle in VRAM coordinates.
174///
175/// Construction asserts the rect fits in VRAM. Subsequent code can
176/// pass `VramRect` around without re-checking -- it's by-construction
177/// safe.
178#[derive(Copy, Clone, Debug, PartialEq, Eq)]
179pub struct VramRect {
180    /// Top-left X in VRAM pixels (0..VRAM_WIDTH).
181    pub x: u16,
182    /// Top-left Y in VRAM pixels (0..VRAM_HEIGHT).
183    pub y: u16,
184    /// Width in pixels. `x + w <= VRAM_WIDTH`.
185    pub w: u16,
186    /// Height in pixels. `y + h <= VRAM_HEIGHT`.
187    pub h: u16,
188}
189
190impl VramRect {
191    /// Build a rect, asserting it fits in VRAM.
192    pub const fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
193        assert!(w > 0, "VramRect: width must be > 0");
194        assert!(h > 0, "VramRect: height must be > 0");
195        assert!(x <= VRAM_WIDTH, "VramRect: x past VRAM right edge");
196        assert!(y <= VRAM_HEIGHT, "VramRect: y past VRAM bottom edge");
197        assert!(
198            (x as u32) + (w as u32) <= VRAM_WIDTH as u32,
199            "VramRect: (x + w) overflows VRAM width",
200        );
201        assert!(
202            (y as u32) + (h as u32) <= VRAM_HEIGHT as u32,
203            "VramRect: (y + h) overflows VRAM height",
204        );
205        Self { x, y, w, h }
206    }
207
208    /// Total pixel count. `w * h`.
209    pub const fn pixel_count(self) -> u32 {
210        (self.w as u32) * (self.h as u32)
211    }
212
213    /// Do these two rectangles share a pixel?
214    ///
215    /// Const so a game can prove its fixed VRAM layout at compile time. See
216    /// [`first_vram_overlap`].
217    pub const fn overlaps(self, other: Self) -> bool {
218        self.x < other.x + other.w
219            && other.x < self.x + self.w
220            && self.y < other.y + other.h
221            && other.y < self.y + self.h
222    }
223}
224
225/// Index of the first pair of rectangles in `rects` that share a pixel.
226///
227/// This exists because VRAM is the one PS1 resource with no allocator between
228/// the writer and the hardware: a picture uploaded to the wrong row silently
229/// reinterprets whatever was there, and the symptom is a wrong-looking texture
230/// somewhere else entirely, often only on the map that fills VRAM deepest.
231///
232/// A game that hardcodes its layout should list every fixed rectangle it owns
233/// (framebuffers, texture-page bands, CLUT rows, HUD and font strips) and pin
234/// the list at compile time, which costs no image bytes:
235///
236/// ```
237/// use psx_vram::{first_vram_overlap, VramRect};
238///
239/// const LAYOUT: [VramRect; 3] = [
240///     VramRect::new(0, 0, 320, 240),     // framebuffer A
241///     VramRect::new(0, 240, 320, 240),   // framebuffer B
242///     VramRect::new(0, 480, 320, 32),    // CLUT block
243/// ];
244/// const _: () = assert!(
245///     matches!(first_vram_overlap(&LAYOUT), None),
246///     "VRAM layout overlaps",
247/// );
248/// ```
249///
250/// A dynamic allocator's reachable output is a rectangle too. Bound it and
251/// list that bound, so a later change to the bound, the band or the row count
252/// fails the build rather than corrupting VRAM on one map.
253pub const fn first_vram_overlap(rects: &[VramRect]) -> Option<(usize, usize)> {
254    let mut i = 0;
255    while i < rects.len() {
256        let mut j = i + 1;
257        while j < rects.len() {
258            if rects[i].overlaps(rects[j]) {
259                return Some((i, j));
260            }
261            j += 1;
262        }
263        i += 1;
264    }
265    None
266}
267
268/// True when no two rectangles in `rects` share a pixel. See
269/// [`first_vram_overlap`] for the pattern and why it is worth pinning.
270pub const fn vram_layout_is_disjoint(rects: &[VramRect]) -> bool {
271    first_vram_overlap(rects).is_none()
272}
273
274// ======================================================================
275// Texture-window atlas allocation
276// ======================================================================
277
278/// Texture-window granularity in texels.
279///
280/// GP0(E2) stores texture-window masks and offsets in 8-texel units,
281/// so small atlas placements only need an 8-texel occupancy grid.
282pub const TEXTURE_WINDOW_UNIT_TEXELS: u16 = 8;
283
284/// Texture-page width and height in texels.
285pub const TEXTURE_PAGE_TEXELS: u16 = 256;
286
287const TEXTURE_PAGE_UNITS: usize = (TEXTURE_PAGE_TEXELS / TEXTURE_WINDOW_UNIT_TEXELS) as usize;
288
289/// Placement returned by [`TextureWindowAtlas::allocate`].
290#[derive(Copy, Clone, Debug, PartialEq, Eq)]
291pub struct TextureWindowPlacement {
292    page_index: u16,
293    origin_u: u8,
294    origin_v: u8,
295    width: u8,
296    height: u8,
297}
298
299impl TextureWindowPlacement {
300    /// Zero-based page index within the caller-owned atlas page band.
301    pub const fn page_index(self) -> u16 {
302        self.page_index
303    }
304
305    /// U origin in texels within the selected texture page.
306    pub const fn origin_u(self) -> u8 {
307        self.origin_u
308    }
309
310    /// V origin in texels within the selected texture page.
311    pub const fn origin_v(self) -> u8 {
312        self.origin_v
313    }
314
315    /// Allocated width in texels.
316    pub const fn width(self) -> u8 {
317        self.width
318    }
319
320    /// Allocated height in texels.
321    pub const fn height(self) -> u8 {
322        self.height
323    }
324}
325
326/// Tiny no-alloc atlas for PS1 texture-window-sized subtextures.
327///
328/// Each 256x256 texture page is tracked as a 32x32 bit grid where one
329/// bit represents an 8x8 texel block. Allocations are power-of-two
330/// rectangles that fit GP0(E2) texture-window constraints and are
331/// placed on their own width/height grid.
332#[derive(Copy, Clone, Debug, PartialEq, Eq)]
333pub struct TextureWindowAtlas<const PAGE_COUNT: usize> {
334    rows: [[u32; TEXTURE_PAGE_UNITS]; PAGE_COUNT],
335}
336
337impl<const PAGE_COUNT: usize> TextureWindowAtlas<PAGE_COUNT> {
338    /// Build an empty atlas.
339    pub const fn new() -> Self {
340        Self {
341            rows: [[0; TEXTURE_PAGE_UNITS]; PAGE_COUNT],
342        }
343    }
344
345    /// Clear every occupied bit.
346    pub fn clear(&mut self) {
347        for page in &mut self.rows {
348            page.fill(0);
349        }
350    }
351
352    /// Allocate a power-of-two texture-window rectangle.
353    ///
354    /// Dimensions are texels. They must be 8-texel aligned,
355    /// power-of-two, and no larger than 128 texels, matching the
356    /// hardware texture-window range.
357    pub fn allocate(&mut self, width: u16, height: u16) -> Option<TextureWindowPlacement> {
358        self.allocate_with_usable_rows(width, height, 256)
359    }
360
361    /// Allocate within the first `usable_rows` texel rows of each page.
362    ///
363    /// The row bound must be a multiple of 8 in `8..=256`. Dimensions and
364    /// placement alignment follow [`Self::allocate`]. Invalid bounds or a
365    /// rectangle taller than the bound return `None` without changing the atlas.
366    /// This per-call bound does not reserve excluded rows: callers sharing a
367    /// page band must consistently apply their ownership limit.
368    pub fn allocate_with_usable_rows(
369        &mut self,
370        width: u16,
371        height: u16,
372        usable_rows: u16,
373    ) -> Option<TextureWindowPlacement> {
374        if usable_rows == 0
375            || usable_rows > 256
376            || !usable_rows.is_multiple_of(TEXTURE_WINDOW_UNIT_TEXELS)
377        {
378            return None;
379        }
380        let width_units = texture_window_units(width)?;
381        let height_units = texture_window_units(height)?;
382        let row_units = (usable_rows / TEXTURE_WINDOW_UNIT_TEXELS) as usize;
383        let max_y = row_units.checked_sub(height_units)?;
384        let max_x = TEXTURE_PAGE_UNITS.checked_sub(width_units)?;
385
386        for page_index in 0..PAGE_COUNT {
387            let mut y = 0usize;
388            while y <= max_y {
389                let mut x = 0usize;
390                while x <= max_x {
391                    if texture_region_free(&self.rows[page_index], x, y, width_units, height_units)
392                    {
393                        texture_region_mark(
394                            &mut self.rows[page_index],
395                            x,
396                            y,
397                            width_units,
398                            height_units,
399                        );
400                        return Some(TextureWindowPlacement {
401                            page_index: u16::try_from(page_index).ok()?,
402                            origin_u: u8::try_from(x * TEXTURE_WINDOW_UNIT_TEXELS as usize).ok()?,
403                            origin_v: u8::try_from(y * TEXTURE_WINDOW_UNIT_TEXELS as usize).ok()?,
404                            width: u8::try_from(width).ok()?,
405                            height: u8::try_from(height).ok()?,
406                        });
407                    }
408                    x += width_units;
409                }
410                y += height_units;
411            }
412        }
413        None
414    }
415
416    /// Reserve one completely empty texture page and return its page index.
417    ///
418    /// This is for assets that use a whole page without GP0(E2) texture
419    /// windows, such as large UI/background strips. It shares the atlas
420    /// bookkeeping so later windowed material allocations cannot overlap the
421    /// reserved page.
422    pub fn reserve_empty_page(&mut self) -> Option<usize> {
423        for page_index in 0..PAGE_COUNT {
424            if self.rows[page_index].iter().all(|row| *row == 0) {
425                self.rows[page_index].fill(u32::MAX);
426                return Some(page_index);
427            }
428        }
429        None
430    }
431
432    /// Release a placement previously returned by [`allocate`](Self::allocate),
433    /// clearing its occupancy bits so the space can be reused. The
434    /// `width`/`height` are the texel dimensions the placement was allocated
435    /// with (the placement records them).
436    pub fn release(&mut self, placement: TextureWindowPlacement) {
437        let page = placement.page_index() as usize;
438        let (Some(width_units), Some(height_units)) = (
439            texture_window_units(placement.width() as u16),
440            texture_window_units(placement.height() as u16),
441        ) else {
442            return;
443        };
444        let x = (placement.origin_u() / TEXTURE_WINDOW_UNIT_TEXELS as u8) as usize;
445        let y = (placement.origin_v() / TEXTURE_WINDOW_UNIT_TEXELS as u8) as usize;
446        if page >= PAGE_COUNT {
447            return;
448        }
449        let mask = texture_region_mask(x, width_units);
450        for row in &mut self.rows[page][y..y + height_units] {
451            *row &= !mask;
452        }
453    }
454
455    /// Release a whole page previously taken by
456    /// [`reserve_empty_page`](Self::reserve_empty_page).
457    pub fn release_page(&mut self, page_index: usize) {
458        if page_index < PAGE_COUNT {
459            self.rows[page_index].fill(0);
460        }
461    }
462
463    /// Whether a logical atlas page contains no live window or full-page
464    /// reservation. Used by the physical allocator to return lazy backing at
465    /// scene boundaries.
466    pub fn is_page_empty(&self, page_index: usize) -> bool {
467        self.rows
468            .get(page_index)
469            .is_some_and(|rows| rows.iter().all(|row| *row == 0))
470    }
471}
472
473impl<const PAGE_COUNT: usize> Default for TextureWindowAtlas<PAGE_COUNT> {
474    fn default() -> Self {
475        Self::new()
476    }
477}
478
479fn texture_window_units(size: u16) -> Option<usize> {
480    if !(TEXTURE_WINDOW_UNIT_TEXELS..=128).contains(&size)
481        || !size.is_power_of_two()
482        || !size.is_multiple_of(TEXTURE_WINDOW_UNIT_TEXELS)
483    {
484        return None;
485    }
486    Some((size / TEXTURE_WINDOW_UNIT_TEXELS) as usize)
487}
488
489fn texture_region_mask(x: usize, width: usize) -> u32 {
490    ((1u32 << width) - 1) << x
491}
492
493fn texture_region_free(
494    rows: &[u32; TEXTURE_PAGE_UNITS],
495    x: usize,
496    y: usize,
497    width: usize,
498    height: usize,
499) -> bool {
500    let mask = texture_region_mask(x, width);
501    for row in &rows[y..y + height] {
502        if row & mask != 0 {
503            return false;
504        }
505    }
506    true
507}
508
509fn texture_region_mark(
510    rows: &mut [u32; TEXTURE_PAGE_UNITS],
511    x: usize,
512    y: usize,
513    width: usize,
514    height: usize,
515) {
516    let mask = texture_region_mask(x, width);
517    for row in &mut rows[y..y + height] {
518        *row |= mask;
519    }
520}
521
522// ======================================================================
523// TexturePage + Clut
524// ======================================================================
525
526/// Texture color depth -- the last field of GP0(E1h) and bits 7..8
527/// of a primitive's tpage word.
528#[derive(Copy, Clone, Debug, PartialEq, Eq)]
529#[repr(u8)]
530pub enum TextureDepth {
531    /// 4-bit CLUT-indexed. 4 texels per 16-bit halfword.
532    Bit4 = 0,
533    /// 8-bit CLUT-indexed. 2 texels per halfword.
534    Bit8 = 1,
535    /// 15-bit direct color. 1 texel per halfword.
536    Bit15 = 2,
537}
538
539impl TextureDepth {
540    const fn as_u16(self) -> u16 {
541        self as u16
542    }
543
544    /// Texels per 16-bit halfword at this depth. 4 for 4bpp,
545    /// 2 for 8bpp, 1 for 15bpp.
546    pub const fn texels_per_halfword(self) -> u16 {
547        match self {
548            TextureDepth::Bit4 => 4,
549            TextureDepth::Bit8 => 2,
550            TextureDepth::Bit15 => 1,
551        }
552    }
553}
554
555/// A texture page: a 256×256 region at a specific VRAM origin,
556/// plus a depth.
557///
558/// Hardware constraints (PSX-SPX "GP0 0xE1"):
559/// - `x` is multiples of 64 pixels → one of 0, 64, 128, …, 960.
560/// - `y` is either 0 or 256.
561/// - The effective page width shrinks with depth: 64 pixels for
562///   4bpp, 128 for 8bpp, 256 for 15bpp. (Because the texel-fetch
563///   address is `tpage_x + u / texels_per_halfword`, so smaller
564///   texels pack into fewer halfwords and hence a narrower span.)
565///
566/// The const constructor catches misaligned X/Y at compile time.
567/// A const check across multiple TexturePage consts (to enforce non-
568/// overlap) needs const generics that are noisy to express here;
569/// runtime collision tooling lives in a follow-up.
570#[derive(Copy, Clone, Debug, PartialEq, Eq)]
571pub struct TexturePage {
572    x: u16,
573    y: u16,
574    depth: TextureDepth,
575}
576
577impl TexturePage {
578    /// Build a TexturePage. Compile-time assertion that `x` is a
579    /// multiple of 64 and `y` is 0 or 256.
580    #[allow(clippy::manual_is_multiple_of)]
581    pub const fn new(x: u16, y: u16, depth: TextureDepth) -> Self {
582        assert!(x % 64 == 0, "TexturePage: x must be a multiple of 64");
583        assert!(x < VRAM_WIDTH, "TexturePage: x past VRAM");
584        assert!(y == 0 || y == 256, "TexturePage: y must be 0 or 256");
585        Self { x, y, depth }
586    }
587
588    /// VRAM X origin (0, 64, …, 960).
589    pub const fn x(self) -> u16 {
590        self.x
591    }
592    /// VRAM Y origin (0 or 256).
593    pub const fn y(self) -> u16 {
594        self.y
595    }
596    /// Color depth.
597    pub const fn depth(self) -> TextureDepth {
598        self.depth
599    }
600
601    /// VRAM rect this tpage would actually cover at its depth.
602    /// Useful for sanity-checking that uploaded texture data fits.
603    pub const fn covering_rect(self) -> VramRect {
604        let w = match self.depth {
605            TextureDepth::Bit4 => 64,
606            TextureDepth::Bit8 => 128,
607            TextureDepth::Bit15 => 256,
608        };
609        // covering_rect is for upload sizing; height is always the
610        // 256-row page height. The assert in VramRect::new guards
611        // the actual bound at compile time.
612        VramRect::new(self.x, self.y, w, 256)
613    }
614
615    /// Encode as the low-16-bits of a textured-primitive UV word
616    /// (the "tpage" embedded field). Same byte layout as GP0(E1h)'s
617    /// low 10 bits minus display-disable / dither bits, which we
618    /// leave to the draw-mode setter. Bits:
619    ///
620    /// ```text
621    ///   bits 0..3   : tpage X / 64
622    ///   bit  4      : tpage Y / 256
623    ///   bits 5..6   : semi-transparency mode (0 = half + half)
624    ///   bits 7..8   : depth (0=4bpp, 1=8bpp, 2=15bpp)
625    /// ```
626    ///
627    /// `semi_trans` picks the GPU blend mode when a texel's mask
628    /// bit is set. 0 is "0.5·bg + 0.5·fg" -- the most common.
629    #[doc(alias = "getTPage")]
630    pub const fn uv_word(self, semi_trans: u8) -> u16 {
631        assert!(semi_trans < 4, "semi_trans must be 0..4");
632        let tpx = (self.x / 64) & 0xf;
633        let tpy = if self.y == 256 { 1 } else { 0 };
634        let depth = self.depth.as_u16();
635        tpx | (tpy << 4) | ((semi_trans as u16) << 5) | (depth << 7)
636    }
637
638    /// The full GP0(E1h) draw-mode word. Use this to set the
639    /// "current" tpage for sprite / rect primitives that don't
640    /// embed a tpage of their own.
641    pub fn apply_as_draw_mode(self) {
642        wait_command_ready();
643        write_command(gp0::draw_mode(
644            (self.x / 64) as u32,
645            if self.y == 256 { 1 } else { 0 },
646            0,
647            self.depth as u32,
648            false,
649            true,
650        ));
651        // Plain tpage application means "sample the page directly".
652        // Material-aware helpers re-apply their own texture window after
653        // setting draw mode.
654        wait_command_ready();
655        write_command(gp0::tex_window(0, 0, 0, 0));
656    }
657}
658
659/// A CLUT slot -- 16 consecutive halfwords at `(x, y)` for 4bpp, or
660/// 256 consecutive halfwords for 8bpp. Const constructor asserts
661/// the 16-pixel X alignment hardware requires.
662#[derive(Copy, Clone, Debug, PartialEq, Eq)]
663pub struct Clut {
664    x: u16,
665    y: u16,
666}
667
668impl Clut {
669    /// Build a CLUT. `x` must be a multiple of 16; `y` is any row.
670    #[allow(clippy::manual_is_multiple_of)]
671    pub const fn new(x: u16, y: u16) -> Self {
672        assert!(x % 16 == 0, "Clut: x must be a multiple of 16");
673        assert!(x < VRAM_WIDTH, "Clut: x past VRAM");
674        assert!(y < VRAM_HEIGHT, "Clut: y past VRAM");
675        Self { x, y }
676    }
677
678    /// VRAM X origin (0, 16, 32, …).
679    pub const fn x(self) -> u16 {
680        self.x
681    }
682    /// VRAM Y origin (0..512).
683    pub const fn y(self) -> u16 {
684        self.y
685    }
686
687    /// Encode as the high-16-bits of a textured-primitive's first
688    /// UV word. Bits:
689    ///
690    /// ```text
691    ///   bits 0..5   : CLUT X / 16
692    ///   bits 6..14  : CLUT Y
693    /// ```
694    #[doc(alias = "getClut")]
695    pub const fn uv_word(self) -> u16 {
696        let cx = (self.x / 16) & 0x3f;
697        let cy = self.y & 0x1ff;
698        cx | (cy << 6)
699    }
700}
701
702// ======================================================================
703// Unified VRAM allocator
704// ======================================================================
705
706/// Coarse VRAM occupancy cell width in pixels (one texture-page column).
707const ALLOC_COL_W: u16 = 64;
708/// Coarse VRAM occupancy cell height in pixels.
709const ALLOC_ROW_H: u16 = 16;
710/// Number of 64-pixel columns across VRAM (16).
711pub const VRAM_ALLOC_COLS: usize = (VRAM_WIDTH / ALLOC_COL_W) as usize;
712/// Number of 16-pixel rows down VRAM (32).
713pub const VRAM_ALLOC_ROWS: usize = (VRAM_HEIGHT / ALLOC_ROW_H) as usize;
714/// Page height in coarse rows (a texture page is 256 px tall).
715const ALLOC_PAGE_ROWS: usize = (TEXTURE_PAGE_TEXELS / ALLOC_ROW_H) as usize;
716/// CLUT slots per VRAM row (1024 px / 16 px).
717const CLUT_SLOTS_PER_ROW: u16 = VRAM_WIDTH / 16;
718
719/// A freeable handle to a VRAM reservation handed out by [`VramAllocator`].
720///
721/// Returned alongside the hardware [`TexturePage`] / [`Clut`] so a caller can both
722/// use the reservation immediately and release it later via
723/// [`VramAllocator::free`]. `Copy` so it can sit in fixed slot tables.
724#[derive(Copy, Clone, Debug, PartialEq, Eq)]
725pub enum VramHandle {
726    /// No reservation (allocation failed, or a default slot).
727    Empty,
728    /// A coarse-grid rectangle: texture pages, model strips, the framebuffer.
729    Rect(VramRect),
730    /// A room-material window inside the composed [`TextureWindowAtlas`].
731    Window(TextureWindowPlacement),
732    /// A whole reserved room-material page (its page index).
733    RoomPage(u16),
734    /// A CLUT-row sub-allocation: `entries` palette slots at `(x, y)`.
735    Clut {
736        /// VRAM X (multiple of 16).
737        x: u16,
738        /// VRAM Y.
739        y: u16,
740        /// Palette entry count (16 or 256).
741        entries: u16,
742    },
743}
744
745/// Source of VRAM regions for crates that should not depend on the whole
746/// [`VramAllocator`] type (e.g. `psx-font`). [`VramAllocator`] implements it.
747pub trait VramRegionSource {
748    /// Reserve `count` contiguous texture pages at page row `page_y`
749    /// (0 or 256), returning the base [`TexturePage`] and a free handle.
750    fn alloc_page_run(
751        &mut self,
752        count: u16,
753        depth: TextureDepth,
754        page_y: u16,
755    ) -> Option<(TexturePage, VramHandle)>;
756
757    /// Reserve a CLUT of `entries` palette slots (16 for 4bpp, 256 for 8bpp).
758    fn alloc_clut(&mut self, entries: u16) -> Option<(Clut, VramHandle)>;
759}
760
761/// CLUT-row sub-allocator over a reserved band of `ROWS` VRAM rows.
762///
763/// Each row holds up to [`CLUT_SLOTS_PER_ROW`] 16-pixel slots tracked as a
764/// `u64` bitmap, so a 4bpp (16-entry) CLUT takes 1 slot and an 8bpp
765/// (256-entry) CLUT takes 16 contiguous slots. [`ClutRowAllocator::new`] spans
766/// the whole 1024-pixel row; [`ClutRowAllocator::with_width`] narrows the band
767/// to its first `width` pixels, which is what lets a layout keep the band
768/// clear of every texture page (see [`VramAllocator::with_clut_band`]).
769#[derive(Copy, Clone, Debug)]
770pub struct ClutRowAllocator<const ROWS: usize> {
771    base_y: u16,
772    slots_per_row: u16,
773    // psx-numeric-allow-next-line: 64-slot occupancy bitmask is a u64 by definition
774    rows: [u64; ROWS],
775}
776
777impl<const ROWS: usize> ClutRowAllocator<ROWS> {
778    /// Build an allocator over rows `[base_y, base_y + ROWS)`, full VRAM width.
779    pub const fn new(base_y: u16) -> Self {
780        Self {
781            base_y,
782            slots_per_row: CLUT_SLOTS_PER_ROW,
783            rows: [0; ROWS],
784        }
785    }
786
787    /// Build an allocator over rows `[base_y, base_y + ROWS)` limited to the
788    /// first `width` pixels of each row (a multiple of 16, at most the VRAM
789    /// width).
790    #[allow(clippy::manual_is_multiple_of)]
791    pub const fn with_width(base_y: u16, width: u16) -> Self {
792        assert!(
793            width >= 16 && width % 16 == 0 && width <= VRAM_WIDTH,
794            "ClutRowAllocator: width must be a multiple of 16 within VRAM"
795        );
796        assert!(
797            (base_y as usize) + ROWS <= VRAM_HEIGHT as usize,
798            "ClutRowAllocator: band runs past VRAM"
799        );
800        Self {
801            base_y,
802            slots_per_row: width / 16,
803            rows: [0; ROWS],
804        }
805    }
806
807    /// The rectangle every CLUT this allocator can hand out lies inside.
808    pub const fn bounds(&self) -> VramRect {
809        VramRect::new(0, self.base_y, self.slots_per_row * 16, ROWS as u16)
810    }
811
812    fn slot_count(entries: u16) -> usize {
813        (entries.max(1) as usize).div_ceil(16)
814    }
815
816    /// Allocate a CLUT of `entries` (16 or 256) palette slots.
817    pub fn alloc(&mut self, entries: u16) -> Option<Clut> {
818        let slots = Self::slot_count(entries);
819        let cap = self.slots_per_row as usize;
820        if slots == 0 || slots > cap.min(64) {
821            return None;
822        }
823        // psx-numeric-allow-next-line: 64-slot occupancy bitmask is a u64 by definition
824        let want: u64 = if slots == 64 {
825            // psx-numeric-allow-next-line: 64-slot occupancy bitmask is a u64 by definition
826            u64::MAX
827        } else {
828            (1u64 << slots) - 1
829        };
830        for (r, row) in self.rows.iter_mut().enumerate() {
831            let mut s = 0usize;
832            while s + slots <= cap.min(64) {
833                let mask = want << s;
834                if *row & mask == 0 {
835                    *row |= mask;
836                    return Some(Clut::new((s as u16) * 16, self.base_y + r as u16));
837                }
838                s += 1;
839            }
840        }
841        None
842    }
843
844    /// Release a CLUT previously returned by [`alloc`](Self::alloc).
845    pub fn free(&mut self, clut: Clut, entries: u16) {
846        let slots = Self::slot_count(entries);
847        let r = clut.y().saturating_sub(self.base_y) as usize;
848        let s = (clut.x() / 16) as usize;
849        if r >= ROWS || s + slots > self.slots_per_row as usize {
850            return;
851        }
852        // psx-numeric-allow-next-line: 64-slot occupancy bitmask is a u64 by definition
853        let mask: u64 = if slots == 64 {
854            // psx-numeric-allow-next-line: 64-slot occupancy bitmask is a u64 by definition
855            u64::MAX
856        } else {
857            (1u64 << slots) - 1
858        } << s;
859        self.rows[r] &= !mask;
860    }
861}
862
863/// One owner for all of VRAM: texture pages, room-material windows, model
864/// strips and CLUT rows, with `free`. A coarse 64×16-pixel occupancy grid
865/// keeps page/strip/framebuffer reservations from overlapping; a composed
866/// [`TextureWindowAtlas`] sub-allocates room-material windows inside a
867/// reserved band; a [`ClutRowAllocator`] hands out CLUT rows.
868#[derive(Copy, Clone, Debug)]
869pub struct VramAllocator<const ROOM_PAGES: usize, const CLUT_ROWS: usize> {
870    grid: [u16; VRAM_ALLOC_ROWS],
871    clut: ClutRowAllocator<CLUT_ROWS>,
872    room: TextureWindowAtlas<ROOM_PAGES>,
873    /// Physical backing selected lazily for each logical room-atlas page.
874    /// Unused capacity therefore consumes no VRAM, and a page is returned when
875    /// its final window (or full-page image) is released at a scene boundary.
876    room_pages: [Option<TexturePage>; ROOM_PAGES],
877    room_page_handles: [VramHandle; ROOM_PAGES],
878    room_base_x: u16,
879    room_base_y: u16,
880    clut_band_reserved: bool,
881}
882
883impl<const ROOM_PAGES: usize, const CLUT_ROWS: usize> VramAllocator<ROOM_PAGES, CLUT_ROWS> {
884    /// Build an empty allocator. `clut_base_y` is the first CLUT-band row.
885    ///
886    /// The band spans the whole 1024-pixel row and is *not* reserved in the
887    /// page grid, so a texture page placed at page row 256 runs through it. Use
888    /// [`with_clut_band`](Self::with_clut_band) to keep the two apart.
889    pub const fn new(clut_base_y: u16) -> Self {
890        Self {
891            grid: [0; VRAM_ALLOC_ROWS],
892            clut: ClutRowAllocator::new(clut_base_y),
893            room: TextureWindowAtlas::new(),
894            room_pages: [None; ROOM_PAGES],
895            room_page_handles: [VramHandle::Empty; ROOM_PAGES],
896            room_base_x: 0,
897            room_base_y: 0,
898            clut_band_reserved: false,
899        }
900    }
901
902    /// Build an empty allocator whose CLUTs all lie in `band`, with `band`
903    /// reserved in the page grid so no texture page, model strip or room page
904    /// can overlap it.
905    ///
906    /// A texture page is 256 rows tall, so every page at page row 256 reaches
907    /// VRAM row 511; a CLUT band that shares rows with such a page also shares
908    /// its pixels, and a sampler that runs a texel past the bottom of its
909    /// window reads palette words as texture. The only VRAM that no page covers
910    /// is the strip under a 320 x 480 framebuffer, so `band` is expected to be
911    /// that strip, e.g. `VramRect::new(0, 480, 320, 32)` with `CLUT_ROWS == 32`.
912    ///
913    /// `band` must start at x 0, be `CLUT_ROWS` rows tall, and align to the
914    /// 64 x 16 pixel occupancy cells.
915    #[allow(clippy::manual_is_multiple_of)]
916    pub const fn with_clut_band(band: VramRect) -> Self {
917        assert!(band.x == 0, "with_clut_band: CLUT slots start at x 0");
918        assert!(
919            band.h as usize == CLUT_ROWS,
920            "with_clut_band: band height must equal CLUT_ROWS"
921        );
922        assert!(
923            band.w % ALLOC_COL_W == 0 && band.y % ALLOC_ROW_H == 0 && band.h % ALLOC_ROW_H == 0,
924            "with_clut_band: band must align to the 64 x 16 occupancy cells"
925        );
926        let mut grid = [0u16; VRAM_ALLOC_ROWS];
927        let c1 = (band.w / ALLOC_COL_W) as usize;
928        let r0 = (band.y / ALLOC_ROW_H) as usize;
929        let r1 = ((band.y + band.h) / ALLOC_ROW_H) as usize;
930        let mut r = r0;
931        while r < r1 {
932            let mut c = 0;
933            while c < c1 {
934                grid[r] |= 1 << c;
935                c += 1;
936            }
937            r += 1;
938        }
939        Self {
940            grid,
941            clut: ClutRowAllocator::with_width(band.y, band.w),
942            room: TextureWindowAtlas::new(),
943            room_pages: [None; ROOM_PAGES],
944            room_page_handles: [VramHandle::Empty; ROOM_PAGES],
945            room_base_x: 0,
946            room_base_y: 0,
947            clut_band_reserved: true,
948        }
949    }
950
951    /// The rectangle every CLUT this allocator hands out lies inside.
952    pub const fn clut_bounds(&self) -> VramRect {
953        self.clut.bounds()
954    }
955
956    /// Whether the CLUT band is reserved in the page grid, which makes it
957    /// disjoint from every texture rectangle by construction.
958    pub const fn clut_band_is_reserved(&self) -> bool {
959        self.clut_band_reserved
960    }
961
962    fn span(x: u16, y: u16, w: u16, h: u16) -> (usize, usize, usize, usize) {
963        let c0 = (x / ALLOC_COL_W) as usize;
964        let c1 = ((x as usize + w as usize).div_ceil(ALLOC_COL_W as usize)).min(VRAM_ALLOC_COLS);
965        let r0 = (y / ALLOC_ROW_H) as usize;
966        let r1 = ((y as usize + h as usize).div_ceil(ALLOC_ROW_H as usize)).min(VRAM_ALLOC_ROWS);
967        (c0, c1, r0, r1)
968    }
969
970    #[allow(dead_code)] // used by later stages for overlap assertions
971    fn rect_free(&self, x: u16, y: u16, w: u16, h: u16) -> bool {
972        let (c0, c1, r0, r1) = Self::span(x, y, w, h);
973        for r in r0..r1 {
974            for c in c0..c1 {
975                if self.grid[r] & (1 << c) != 0 {
976                    return false;
977                }
978            }
979        }
980        true
981    }
982
983    fn set_rect(&mut self, x: u16, y: u16, w: u16, h: u16, occupied: bool) {
984        let (c0, c1, r0, r1) = Self::span(x, y, w, h);
985        for r in r0..r1 {
986            for c in c0..c1 {
987                if occupied {
988                    self.grid[r] |= 1 << c;
989                } else {
990                    self.grid[r] &= !(1 << c);
991                }
992            }
993        }
994    }
995
996    /// Reserve a fixed rectangle (e.g. the double-buffered framebuffer, or a
997    /// region still owned by legacy hardcoded uploads). Returns a handle that
998    /// can be `free`d but is normally permanent.
999    pub fn reserve_rect(&mut self, rect: VramRect) -> VramHandle {
1000        assert!(
1001            !self.clut_band_reserved || !rect.overlaps(self.clut.bounds()),
1002            "reserve_rect: rectangle overlaps the reserved CLUT band"
1003        );
1004        self.set_rect(rect.x, rect.y, rect.w, rect.h, true);
1005        VramHandle::Rect(rect)
1006    }
1007
1008    /// Select the preferred room-material page band. Physical pages are
1009    /// reserved lazily as the logical atlas first touches them, so a six-page
1010    /// capacity no longer pins six pages for a scene that uses only one.
1011    pub fn reserve_room_band(&mut self, base_x: u16, base_y: u16) {
1012        self.room_base_x = base_x;
1013        self.room_base_y = base_y;
1014    }
1015
1016    fn ensure_room_page(&mut self, page_index: usize) -> Option<TexturePage> {
1017        if let Some(tpage) = self.room_pages.get(page_index).copied().flatten() {
1018            return Some(tpage);
1019        }
1020        if page_index >= ROOM_PAGES {
1021            return None;
1022        }
1023        let preferred_x = self
1024            .room_base_x
1025            .checked_add((page_index as u16).checked_mul(ALLOC_COL_W)?)?;
1026        let x = if preferred_x + ALLOC_COL_W <= VRAM_WIDTH
1027            && self.rect_free(
1028                preferred_x,
1029                self.room_base_y,
1030                ALLOC_COL_W,
1031                TEXTURE_PAGE_TEXELS,
1032            ) {
1033            preferred_x
1034        } else {
1035            self.find_page_run(1, self.room_base_y)?
1036        };
1037        self.set_rect(x, self.room_base_y, ALLOC_COL_W, TEXTURE_PAGE_TEXELS, true);
1038        let tpage = TexturePage::new(x, self.room_base_y, TextureDepth::Bit4);
1039        self.room_pages[page_index] = Some(tpage);
1040        self.room_page_handles[page_index] = VramHandle::Rect(VramRect::new(
1041            x,
1042            self.room_base_y,
1043            ALLOC_COL_W,
1044            TEXTURE_PAGE_TEXELS,
1045        ));
1046        Some(tpage)
1047    }
1048
1049    fn release_room_page_if_empty(&mut self, page_index: usize) {
1050        if page_index >= ROOM_PAGES || !self.room.is_page_empty(page_index) {
1051            return;
1052        }
1053        let handle = core::mem::replace(&mut self.room_page_handles[page_index], VramHandle::Empty);
1054        if let VramHandle::Rect(rect) = handle {
1055            self.set_rect(rect.x, rect.y, rect.w, rect.h, false);
1056        }
1057        self.room_pages[page_index] = None;
1058    }
1059
1060    fn find_page_run(&self, count: u16, page_y: u16) -> Option<u16> {
1061        let r0 = (page_y / ALLOC_ROW_H) as usize;
1062        let r1 = r0 + ALLOC_PAGE_ROWS;
1063        if r1 > VRAM_ALLOC_ROWS || count == 0 {
1064            return None;
1065        }
1066        let n = count as usize;
1067        let mut c = 0usize;
1068        while c + n <= VRAM_ALLOC_COLS {
1069            let cols_free = (c..c + n).all(|col| (r0..r1).all(|r| self.grid[r] & (1 << col) == 0));
1070            if cols_free {
1071                return Some((c as u16) * ALLOC_COL_W);
1072            }
1073            c += 1;
1074        }
1075        None
1076    }
1077
1078    /// Allocate a room-material window (delegates to the composed
1079    /// [`TextureWindowAtlas`]; the band must be reserved first).
1080    pub fn alloc_window(
1081        &mut self,
1082        width_texels: u16,
1083        height_texels: u16,
1084    ) -> Option<(TexturePage, TextureWindowPlacement, VramHandle)> {
1085        let placement = self.room.allocate(width_texels, height_texels)?;
1086        let page_index = placement.page_index() as usize;
1087        let Some(tpage) = self.ensure_room_page(page_index) else {
1088            self.room.release(placement);
1089            return None;
1090        };
1091        Some((tpage, placement, VramHandle::Window(placement)))
1092    }
1093
1094    /// Reserve a whole room-material page (large UI / background textures use a
1095    /// full page without a GP0(E2) window). The room band must be reserved
1096    /// first via [`reserve_room_band`](Self::reserve_room_band).
1097    pub fn alloc_room_page(&mut self) -> Option<(TexturePage, VramHandle)> {
1098        let page_index = self.room.reserve_empty_page()?;
1099        let Some(tpage) = self.ensure_room_page(page_index) else {
1100            self.room.release_page(page_index);
1101            return None;
1102        };
1103        Some((tpage, VramHandle::RoomPage(page_index as u16)))
1104    }
1105
1106    /// Allocate an indexed model-atlas strip `halfwords_per_row` wide (rounded
1107    /// up to whole 64-halfword tpage bases) at page row 256.
1108    ///
1109    /// Placement is measured in physical VRAM halfwords, so the same allocator
1110    /// works for 4bpp and 8bpp atlases. `depth` controls how the GPU interprets
1111    /// those halfwords when the returned tpage word is emitted.
1112    pub fn alloc_model_slot(
1113        &mut self,
1114        halfwords_per_row: u16,
1115        depth: TextureDepth,
1116    ) -> Option<(TexturePage, VramHandle)> {
1117        if !matches!(depth, TextureDepth::Bit4 | TextureDepth::Bit8) {
1118            return None;
1119        }
1120        let pages = halfwords_per_row.div_ceil(ALLOC_COL_W).max(1);
1121        let x = self.find_page_run(pages, 256)?;
1122        self.set_rect(x, 256, pages * ALLOC_COL_W, TEXTURE_PAGE_TEXELS, true);
1123        Some((
1124            TexturePage::new(x, 256, depth),
1125            VramHandle::Rect(VramRect::new(
1126                x,
1127                256,
1128                pages * ALLOC_COL_W,
1129                TEXTURE_PAGE_TEXELS,
1130            )),
1131        ))
1132    }
1133
1134    /// Release a reservation.
1135    pub fn free(&mut self, handle: VramHandle) {
1136        match handle {
1137            VramHandle::Empty => {}
1138            VramHandle::Rect(rect) => self.set_rect(rect.x, rect.y, rect.w, rect.h, false),
1139            VramHandle::Window(placement) => {
1140                let page = placement.page_index() as usize;
1141                self.room.release(placement);
1142                self.release_room_page_if_empty(page);
1143            }
1144            VramHandle::RoomPage(page) => {
1145                let page = page as usize;
1146                self.room.release_page(page);
1147                self.release_room_page_if_empty(page);
1148            }
1149            VramHandle::Clut { x, y, entries } => self.clut.free(Clut::new(x, y), entries),
1150        }
1151    }
1152}
1153
1154impl<const ROOM_PAGES: usize, const CLUT_ROWS: usize> VramRegionSource
1155    for VramAllocator<ROOM_PAGES, CLUT_ROWS>
1156{
1157    fn alloc_page_run(
1158        &mut self,
1159        count: u16,
1160        depth: TextureDepth,
1161        page_y: u16,
1162    ) -> Option<(TexturePage, VramHandle)> {
1163        let x = self.find_page_run(count, page_y)?;
1164        self.set_rect(x, page_y, count * ALLOC_COL_W, TEXTURE_PAGE_TEXELS, true);
1165        Some((
1166            TexturePage::new(x, page_y, depth),
1167            VramHandle::Rect(VramRect::new(
1168                x,
1169                page_y,
1170                count * ALLOC_COL_W,
1171                TEXTURE_PAGE_TEXELS,
1172            )),
1173        ))
1174    }
1175
1176    fn alloc_clut(&mut self, entries: u16) -> Option<(Clut, VramHandle)> {
1177        let clut = self.clut.alloc(entries)?;
1178        Some((
1179            clut,
1180            VramHandle::Clut {
1181                x: clut.x(),
1182                y: clut.y(),
1183                entries,
1184            },
1185        ))
1186    }
1187}
1188
1189// ======================================================================
1190// Uploads
1191// ======================================================================
1192
1193/// Upload raw 16bpp halfwords into a VRAM rect via GP0 0xA0 + word
1194/// stream. Checks that `pixels.len() * 2 == rect.w * rect.h` -- one
1195/// halfword per pixel, and the FIFO ships 32-bit words containing
1196/// two halfwords each. Odd pixel counts (which round up on
1197/// hardware) panic because they're rarely what the caller wanted.
1198///
1199/// For a 15bpp direct-color upload, each halfword is a
1200/// [`Color555`]. For pre-packed 4bpp / 8bpp index data, each
1201/// halfword packs 4 or 2 indices respectively.
1202pub fn upload_16bpp(rect: VramRect, pixels: &[u16]) {
1203    let expected = rect.pixel_count();
1204    // Literal messages: formatting the counts links core::fmt (about 4 KB)
1205    // into any program where this function is not inlined.
1206    assert!(
1207        pixels.len() as u32 == expected,
1208        "upload_16bpp: pixels.len() != rect.w * rect.h"
1209    );
1210    assert!(
1211        expected.is_multiple_of(2),
1212        "upload_16bpp: odd pixel count not supported; round the rect up"
1213    );
1214
1215    // FIFO path by default: the CL2 silicon probes showed this console's
1216    // DMA controller can latch a channel busy-forever while moving
1217    // nothing, and an upload that wedges freezes boot with no diagnostic
1218    // (the unbounded busy-wait in the DMA path). The FIFO loop is a
1219    // boot-time cost nobody measures; callers that trust their DMA can
1220    // opt in via `dma_copy_to_vram`.
1221    // Two halfwords per 32-bit word, low half first.
1222    // During GP0(0xA0) image transfer the GPU is waiting for data,
1223    // not normal commands; DuckStation clears READY_CMD in this
1224    // state, so stream payload words without polling command-ready.
1225    // An image upload cannot be recorded, so it always reaches the port.
1226    let _pause = pause_recording();
1227    copy_to_vram_header(rect);
1228    let mut i = 0;
1229    while i + 1 < pixels.len() {
1230        let lo = pixels[i] as u32;
1231        let hi = pixels[i + 1] as u32;
1232        psx_io::gpu::write_command_unguarded(lo | (hi << 16));
1233        i += 2;
1234    }
1235}
1236
1237/// Upload raw byte-stream pixel data, interpreted as halfwords in
1238/// little-endian order. Same semantics as [`upload_16bpp`] but
1239/// accepts a `&[u8]` -- useful when the data comes from
1240/// `include_bytes!` of a cooked asset blob, where the returned
1241/// byte array has alignment 1 and a direct `&[u16]` reinterpret
1242/// would be undefined behaviour.
1243///
1244/// `rect.w` still measures *halfwords* (the VRAM native unit).
1245/// The byte length must be exactly `2 × rect.w × rect.h`.
1246pub fn upload_bytes(rect: VramRect, bytes: &[u8]) {
1247    let expected = (rect.pixel_count() as usize) * 2;
1248    assert_eq!(
1249        bytes.len(),
1250        expected,
1251        "upload_bytes: bytes.len() ({}) != 2 × rect.w × rect.h ({})",
1252        bytes.len(),
1253        expected,
1254    );
1255    assert!(
1256        bytes.len() >= 2 && bytes.len().is_multiple_of(2),
1257        "upload_bytes: byte count must be a positive multiple of 2"
1258    );
1259
1260    // FIFO path by default; see upload_16bpp for the silicon rationale.
1261    // Two halfwords per word, low half first -- matches upload_16bpp's
1262    // packing convention. GP0 image copies with an odd halfword count still
1263    // consume one complete final word; its unused high halfword is ignored by
1264    // the GPU, so zero-pad it. See upload_16bpp: image payload writes must not
1265    // wait on the normal command-ready bit.
1266    let _pause = pause_recording();
1267    copy_to_vram_header(rect);
1268    let mut i = 0;
1269    while i < bytes.len() {
1270        psx_io::gpu::write_command_unguarded(packed_upload_word(bytes, i));
1271        i += 4;
1272    }
1273}
1274
1275#[inline]
1276fn packed_upload_word(bytes: &[u8], offset: usize) -> u32 {
1277    u32::from_le_bytes([
1278        bytes[offset],
1279        bytes[offset + 1],
1280        bytes.get(offset + 2).copied().unwrap_or(0),
1281        bytes.get(offset + 3).copied().unwrap_or(0),
1282    ])
1283}
1284
1285/// Upload bytes using aligned word loads when possible. Unaligned and odd
1286/// halfword counts retain [`upload_bytes`]'s zero-padded final-word behavior.
1287pub fn upload_bytes_aligned(rect: VramRect, bytes: &[u8]) {
1288    if cfg!(target_endian = "little")
1289        && bytes.as_ptr().align_offset(4) == 0
1290        && bytes.len().is_multiple_of(4)
1291    {
1292        let words =
1293            // SAFETY: every u32 bit pattern is valid; alignment, extent and
1294            // lifetime are checked above and the input stays immutably borrowed.
1295            unsafe { core::slice::from_raw_parts(bytes.as_ptr().cast::<u32>(), bytes.len() / 4) };
1296        upload_words(rect, words);
1297    } else {
1298        upload_bytes(rect, bytes);
1299    }
1300}
1301
1302/// Upload an already packed little-endian stream of two 16-bit VRAM pixels
1303/// per word.
1304///
1305/// This is the aligned counterpart to [`upload_bytes`]. Runtime-generated
1306/// textures commonly live in a `u32` staging arena already, so accepting the
1307/// packed words directly avoids reconstructing every word from four byte
1308/// loads while retaining the silicon-safe FIFO transfer path.
1309#[doc(alias = "LoadImage")]
1310pub fn upload_words(rect: VramRect, words: &[u32]) {
1311    let expected_words = rect.pixel_count() as usize / 2;
1312    assert!(
1313        rect.pixel_count().is_multiple_of(2),
1314        "upload_words: odd pixel count is not supported"
1315    );
1316    assert_eq!(
1317        words.len(),
1318        expected_words,
1319        "upload_words: words.len() ({}) != rect.w*rect.h/2 ({})",
1320        words.len(),
1321        expected_words,
1322    );
1323    assert!(!words.is_empty(), "upload_words: empty upload");
1324
1325    let _pause = pause_recording();
1326    copy_to_vram_header(rect);
1327    for &word in words {
1328        psx_io::gpu::write_command_unguarded(word);
1329    }
1330}
1331
1332/// Emit the GP0(0xA0) "copy CPU→VRAM" header (destination, halfword extent). Its writes run
1333/// any armed present-queue guard and callers hold a recording pause, so the FIFO payload that
1334/// follows skips the flag test (`write_command_unguarded`); block DMA follows otherwise.
1335#[inline]
1336fn copy_to_vram_header(rect: VramRect) {
1337    // An asynchronously kicked ordering-table walk may still be feeding
1338    // GP0 over this same channel when streaming code uploads from a
1339    // fixed update. Interleaving header words (or reprogramming the
1340    // channel for the block-DMA path) mid-walk corrupts the command
1341    // stream, so drain the channel first. Bounded: a wedged walk must
1342    // not take the upload (or the boot that needs it) down with it.
1343    if !dma::wait_done(Channel::Gpu, dma::DEFAULT_SPINS) {
1344        dma::abort(Channel::Gpu);
1345    }
1346    wait_command_ready();
1347    write_command(gp0::COPY_CPU_TO_VRAM);
1348    write_command(pack_xy(rect.x, rect.y));
1349    write_command(pack_xy(rect.w, rect.h));
1350}
1351
1352/// Upload `words` to `rect` over block-mode DMA (channel 2) instead of
1353/// word-at-a-time FIFO writes, and wait for it. This mirrors PsyQ's
1354/// `LoadImage`: `BS = words-per-row`, `BA = rows`.
1355///
1356/// `words` holds the pixels as little-endian 32-bit words, two 16-bit
1357/// halfwords each, row after row: `(rect.w / 2) * rect.h` words, and only
1358/// that many are sent. Returns `false`, leaving the GPU untouched, when the
1359/// transfer cannot be expressed this way: an odd or zero width, a zero
1360/// height, a row wider than the GPU's 16-word FIFO, or a slice shorter than
1361/// the rectangle. Use [`upload_16bpp`] (the FIFO path) for those.
1362///
1363/// Opt-in: on real hardware the DMA controller can latch a channel
1364/// busy-forever (CL2 probe, 2026-07-31). The completion wait is bounded,
1365/// so a wedge costs a `false` and a partial upload rather than a hang.
1366#[doc(alias = "LoadImage")]
1367pub fn dma_copy_to_vram(_dma: &mut GpuDma, rect: VramRect, words: &[u32]) -> bool {
1368    if words.len() < copy_words(rect) {
1369        return false;
1370    }
1371    // SAFETY: the check above proved `words` holds the whole rectangle, and
1372    // it stays borrowed until this function returns; the wait below, or the
1373    // abort on a wedge, ends the transfer before then.
1374    if !unsafe { kick_copy_to_vram(rect, words.as_ptr()) } {
1375        return false;
1376    }
1377    // On a wedge the GP0(A0) header is already out and the payload did not
1378    // land, so VRAM holds a partial upload either way; report it.
1379    dma::wait_or_abort(Channel::Gpu, dma::DEFAULT_SPINS)
1380}
1381
1382/// [`dma_copy_to_vram`] without the completion wait: send the copy header,
1383/// kick the block DMA and return, so the CPU keeps working while channel 2
1384/// feeds the GPU. Poll [`dma_copy_to_vram_done`]; abort channel 2
1385/// (`psx_io::dma::abort`) if it never finishes. Returns `false`, having
1386/// touched nothing, for a transfer the DMA cannot express (see
1387/// [`dma_copy_to_vram`]).
1388///
1389/// `words` points at the `(rect.w / 2) * rect.h` pixel words, as the slice
1390/// of [`dma_copy_to_vram`] would.
1391///
1392/// # Safety
1393/// `words` must point at that many readable words, alive and unmodified
1394/// until [`dma_copy_to_vram_done`] returns `true` or channel 2 is aborted.
1395/// Until then nothing else may write GP0 or program channel 2, so no
1396/// drawing, other upload or frame submission; the `&mut GpuDma` borrow only
1397/// covers the call itself.
1398#[doc(alias = "LoadImage")]
1399pub unsafe fn dma_copy_to_vram_start(_dma: &mut GpuDma, rect: VramRect, words: *const u32) -> bool {
1400    // SAFETY: the caller upholds this function's contract.
1401    unsafe { kick_copy_to_vram(rect, words) }
1402}
1403
1404/// True once the transfer [`dma_copy_to_vram_start`] kicked has finished.
1405#[inline]
1406pub fn dma_copy_to_vram_done() -> bool {
1407    !dma::is_busy(Channel::Gpu)
1408}
1409
1410/// Words one block-DMA upload of `rect` sends.
1411fn copy_words(rect: VramRect) -> usize {
1412    (rect.w / 2) as usize * rect.h as usize
1413}
1414
1415/// The GP0(A0) header, then a block DMA of the rectangle's words from
1416/// `src`, with no wait. `false` (nothing touched) when the DMA cannot send
1417/// the rectangle whole: an odd or zero width, a zero height, or a row wider
1418/// than the GPU's 16-word FIFO.
1419///
1420/// # Safety
1421/// `src` must point at [`copy_words`] readable words that stay unmodified
1422/// until channel 2 finishes or is aborted.
1423unsafe fn kick_copy_to_vram(rect: VramRect, src: *const u32) -> bool {
1424    if !rect.w.is_multiple_of(2) || rect.w == 0 || rect.h == 0 {
1425        return false;
1426    }
1427    let words_per_row = rect.w / 2;
1428    // GPU block-mode DMA's BCR block size must fit the GPU's 16-word
1429    // FIFO. Wider rows, such as the combined UI font atlas, can appear to
1430    // work in emulators but wedge real hardware; use the GP0 FIFO path
1431    // instead of starting an invalid DMA.
1432    if words_per_row > 16 {
1433        return false;
1434    }
1435    let _pause = pause_recording();
1436    copy_to_vram_header(rect);
1437    // GP1(04h) = 2: route DMA words CPU→GP0. `psx-gpu::init` sets this,
1438    // but a VRAM readback could have flipped it to GPUREAD→CPU.
1439    write_display_control(gp1::dma_direction(2));
1440    dma::enable_channel(Channel::Gpu);
1441    // SAFETY: the channel was drained by `copy_to_vram_header`. The transfer
1442    // reads `words_per_row * rect.h` words from `src`, which the caller
1443    // keeps readable and unmodified until it completes or is aborted.
1444    unsafe {
1445        dma::start(
1446            Channel::Gpu,
1447            dma::Transfer {
1448                address: src as u32,
1449                size: dma::size_blocks(words_per_row, rect.h),
1450                control: psx_hw::dma::CHCR_TO_DEVICE
1451                    | psx_hw::dma::CHCR_SYNC_BLOCK
1452                    | psx_hw::dma::CHCR_START,
1453            },
1454        )
1455    };
1456    true
1457}
1458
1459/// Upload typed [`Color555`] pixels -- sugar over [`upload_16bpp`]
1460/// for direct-color textures.
1461pub fn upload_15bpp(rect: VramRect, pixels: &[Color555]) {
1462    let as_u16: &[u16] = unsafe {
1463        // SAFETY: Color555 is `#[repr(transparent)] u16`, so the
1464        // slice cast is layout-safe.
1465        core::slice::from_raw_parts(pixels.as_ptr() as *const u16, pixels.len())
1466    };
1467    upload_16bpp(rect, as_u16);
1468}
1469
1470/// Upload a CLUT -- a row of [`Color555`]s at `clut`. The caller
1471/// picks the width: 16 entries for 4bpp, 256 for 8bpp. Asserts
1472/// the CLUT fits in VRAM width and the slice length matches.
1473pub fn upload_clut(clut: Clut, entries: &[Color555]) {
1474    let rect = VramRect::new(clut.x(), clut.y(), entries.len() as u16, 1);
1475    upload_15bpp(rect, entries);
1476}
1477
1478// ======================================================================
1479// Tests
1480// ======================================================================
1481
1482/// Renamed to [`TexturePage`].
1483#[deprecated(note = "renamed to `TexturePage`")]
1484pub type Tpage = TexturePage;
1485
1486/// Renamed to [`TextureDepth`].
1487#[deprecated(note = "renamed to `TextureDepth`")]
1488pub type TexDepth = TextureDepth;
1489
1490impl TexturePage {
1491    /// Renamed to [`TexturePage::uv_word`].
1492    #[deprecated(note = "renamed to `uv_word`")]
1493    #[inline(always)]
1494    pub const fn uv_tpage_word(self, semi_trans: u8) -> u16 {
1495        self.uv_word(semi_trans)
1496    }
1497}
1498
1499impl Clut {
1500    /// Renamed to [`Clut::uv_word`].
1501    #[deprecated(note = "renamed to `uv_word`")]
1502    #[inline(always)]
1503    pub const fn uv_clut_word(self) -> u16 {
1504        self.uv_word()
1505    }
1506}
1507
1508#[cfg(test)]
1509mod tests {
1510    use super::*;
1511
1512    #[test]
1513    fn dma_copy_to_vram_refuses_what_it_cannot_send_whole() {
1514        // Every case returns before touching the GPU, so this runs on the host.
1515        // SAFETY: the only token in this test.
1516        let mut dma = unsafe { GpuDma::steal() };
1517        let words = [0u32; 8];
1518        // Four words per row, two rows: the slice is one word short.
1519        assert!(!dma_copy_to_vram(
1520            &mut dma,
1521            VramRect::new(0, 0, 8, 2),
1522            &words[..7]
1523        ));
1524        // Odd, zero or FIFO-overflowing widths, and a zero height.
1525        assert!(!dma_copy_to_vram(
1526            &mut dma,
1527            VramRect::new(0, 0, 3, 1),
1528            &words
1529        ));
1530        assert!(!dma_copy_to_vram(
1531            &mut dma,
1532            VramRect {
1533                x: 0,
1534                y: 0,
1535                w: 0,
1536                h: 1
1537            },
1538            &words
1539        ));
1540        assert!(!dma_copy_to_vram(
1541            &mut dma,
1542            VramRect::new(0, 0, 34, 1),
1543            &[0; 17]
1544        ));
1545        assert!(!dma_copy_to_vram(
1546            &mut dma,
1547            VramRect {
1548                x: 0,
1549                y: 0,
1550                w: 2,
1551                h: 0
1552            },
1553            &words
1554        ));
1555    }
1556
1557    #[test]
1558    fn byte_upload_word_zero_pads_an_odd_final_halfword() {
1559        assert_eq!(
1560            packed_upload_word(&[0x11, 0x22, 0x33, 0x44], 0),
1561            0x4433_2211
1562        );
1563        assert_eq!(packed_upload_word(&[0x55, 0x66], 0), 0x0000_6655);
1564    }
1565
1566    #[test]
1567    fn stp_is_the_mask_bit_named_for_its_palette_meaning() {
1568        let opaque = Color555::rgb8(255, 255, 255);
1569        assert!(!opaque.is_semi_transparent());
1570        assert_eq!(
1571            opaque.with_semi_transparency().as_u16(),
1572            opaque.with_mask_bit().as_u16()
1573        );
1574        assert!(opaque.with_semi_transparency().is_semi_transparent());
1575        // The fully transparent slot must stay 0x0000: setting STP there would
1576        // make the GPU blend the texel instead of skipping it.
1577        assert_eq!(Color555::TRANSPARENT.as_u16(), 0);
1578        assert!(!Color555::TRANSPARENT.is_semi_transparent());
1579    }
1580
1581    #[test]
1582    fn color_rgb8_truncates_low_bits() {
1583        assert_eq!(Color555::rgb8(0, 0, 0).as_u16(), 0);
1584        assert_eq!(Color555::rgb8(255, 255, 255).as_u16(), 0x7fff);
1585        // 0x18 = 24 → 24 >> 3 = 3.
1586        assert_eq!(Color555::rgb8(24, 0, 0).as_u16(), 3);
1587    }
1588
1589    #[test]
1590    fn color_rgb5_rejects_out_of_range_via_panic() {
1591        // Compile-time assert check happens in `const fn`; the panic
1592        // path at runtime is the same.
1593        assert_eq!(Color555::rgb5(31, 0, 0).as_u16(), 31);
1594        assert_eq!(Color555::rgb5(0, 31, 0).as_u16(), 31 << 5);
1595        assert_eq!(Color555::rgb5(0, 0, 31).as_u16(), 31 << 10);
1596    }
1597
1598    #[test]
1599    #[should_panic = "red must be < 32"]
1600    fn color_rgb5_panics_on_32() {
1601        let _ = Color555::rgb5(32, 0, 0);
1602    }
1603
1604    #[test]
1605    fn vram_rect_new_accepts_valid_positions() {
1606        let _ = VramRect::new(0, 0, 64, 64);
1607        let _ = VramRect::new(VRAM_WIDTH - 1, 0, 1, 1);
1608        let _ = VramRect::new(0, VRAM_HEIGHT - 1, 1, 1);
1609    }
1610
1611    #[test]
1612    #[should_panic = "overflows VRAM width"]
1613    fn vram_rect_new_rejects_horizontal_overflow() {
1614        let _ = VramRect::new(1000, 0, 100, 10);
1615    }
1616
1617    #[test]
1618    fn texture_window_row_bound_preserves_scan_order_and_palette_rows() {
1619        let mut atlas = TextureWindowAtlas::<2>::new();
1620        for index in 0..24 {
1621            let placement = atlas.allocate_with_usable_rows(64, 64, 224).unwrap();
1622            assert_eq!(placement.page_index(), index / 12);
1623            assert_eq!(u16::from(placement.origin_u()), (index % 4) * 64);
1624            assert_eq!(u16::from(placement.origin_v()), ((index % 12) / 4) * 64);
1625            assert!(u16::from(placement.origin_v()) + u16::from(placement.height()) <= 224);
1626        }
1627        assert!(atlas.allocate_with_usable_rows(64, 64, 224).is_none());
1628        // The remaining aligned 32-high strip still fits below the limit.
1629        let strip = atlas.allocate_with_usable_rows(32, 32, 224).unwrap();
1630        assert_eq!(
1631            (strip.page_index(), strip.origin_u(), strip.origin_v()),
1632            (0, 0, 192)
1633        );
1634        assert_eq!(core::mem::size_of_val(&atlas), 2 * 32 * 4);
1635    }
1636
1637    #[test]
1638    fn texture_window_row_bound_rejects_invalid_input_without_mutation() {
1639        let mut atlas = TextureWindowAtlas::<1>::new();
1640        atlas.allocate(32, 32).unwrap();
1641        let before = atlas;
1642        for rows in [0, 1, 7, 9, 223, 255, 257, 264, u16::MAX] {
1643            assert!(atlas.allocate_with_usable_rows(8, 8, rows).is_none());
1644            assert_eq!(atlas, before);
1645        }
1646        assert!(atlas.allocate_with_usable_rows(64, 64, 56).is_none());
1647        assert_eq!(atlas, before);
1648        assert!(atlas.allocate_with_usable_rows(48, 32, 224).is_none());
1649        assert_eq!(atlas, before);
1650        let edge = atlas.allocate_with_usable_rows(8, 8, 8).unwrap();
1651        assert_eq!((edge.origin_u(), edge.origin_v()), (32, 0));
1652    }
1653
1654    #[test]
1655    fn texture_window_full_row_bound_matches_default_allocator() {
1656        let mut default = TextureWindowAtlas::<2>::new();
1657        let mut bounded = default;
1658        for index in 0..160 {
1659            let (width, height) = [(32, 32), (64, 16), (8, 128), (128, 8)][index % 4];
1660            assert_eq!(
1661                default.allocate(width, height),
1662                bounded.allocate_with_usable_rows(width, height, 256)
1663            );
1664            assert_eq!(default, bounded);
1665        }
1666    }
1667
1668    #[test]
1669    fn texture_window_atlas_packs_32x32_textures_inside_one_page() {
1670        let mut atlas = TextureWindowAtlas::<1>::new();
1671
1672        let first = atlas.allocate(32, 32).expect("first texture fits");
1673        let second = atlas.allocate(32, 32).expect("second texture fits");
1674        let eighth = {
1675            let mut placement = second;
1676            for _ in 2..8 {
1677                placement = atlas.allocate(32, 32).expect("top row texture fits");
1678            }
1679            placement
1680        };
1681        let ninth = atlas.allocate(32, 32).expect("second row texture fits");
1682
1683        assert_eq!(first.page_index(), 0);
1684        assert_eq!((first.origin_u(), first.origin_v()), (0, 0));
1685        assert_eq!((second.origin_u(), second.origin_v()), (32, 0));
1686        assert_eq!((eighth.origin_u(), eighth.origin_v()), (224, 0));
1687        assert_eq!((ninth.origin_u(), ninth.origin_v()), (0, 32));
1688    }
1689
1690    #[test]
1691    fn texture_window_atlas_moves_to_next_page_when_current_page_is_full() {
1692        let mut atlas = TextureWindowAtlas::<2>::new();
1693
1694        for _ in 0..16 {
1695            atlas
1696                .allocate(64, 64)
1697                .expect("64x64 slot fits in first page");
1698        }
1699        let next = atlas.allocate(64, 64).expect("second page has space");
1700
1701        assert_eq!(next.page_index(), 1);
1702        assert_eq!((next.origin_u(), next.origin_v()), (0, 0));
1703    }
1704
1705    #[test]
1706    fn texture_window_atlas_reserves_empty_page_for_unwindowed_texture() {
1707        let mut atlas = TextureWindowAtlas::<2>::new();
1708
1709        let page = atlas.reserve_empty_page().expect("page reserved");
1710        assert_eq!(page, 0);
1711        let next = atlas.allocate(64, 64).expect("second page still free");
1712
1713        assert_eq!(next.page_index(), 1);
1714        assert_eq!((next.origin_u(), next.origin_v()), (0, 0));
1715    }
1716
1717    #[test]
1718    fn texture_window_atlas_aligns_each_allocation_to_its_own_size() {
1719        let mut atlas = TextureWindowAtlas::<1>::new();
1720
1721        atlas.allocate(32, 32).expect("small texture fits");
1722        let large = atlas.allocate(64, 64).expect("large texture fits");
1723
1724        assert_eq!((large.origin_u(), large.origin_v()), (64, 0));
1725    }
1726
1727    #[test]
1728    fn texture_window_atlas_rejects_non_texture_window_dimensions() {
1729        let mut atlas = TextureWindowAtlas::<1>::new();
1730
1731        assert!(atlas.allocate(48, 32).is_none());
1732        assert!(atlas.allocate(4, 32).is_none());
1733        assert!(atlas.allocate(256, 32).is_none());
1734    }
1735
1736    #[test]
1737    fn tpage_encodes_uv_word_correctly() {
1738        let tp = TexturePage::new(640, 0, TextureDepth::Bit15);
1739        // x=640 → tpx=10, y=0 → tpy=0, depth=15bpp → 2.
1740        let word = tp.uv_word(0);
1741        assert_eq!(word & 0xf, 10, "tpx");
1742        assert_eq!((word >> 4) & 1, 0, "tpy");
1743        assert_eq!((word >> 5) & 3, 0, "semi_trans");
1744        assert_eq!((word >> 7) & 3, 2, "depth");
1745    }
1746
1747    #[test]
1748    #[should_panic = "x must be a multiple of 64"]
1749    fn tpage_rejects_misaligned_x() {
1750        let _ = TexturePage::new(32, 0, TextureDepth::Bit8);
1751    }
1752
1753    #[test]
1754    #[should_panic = "y must be 0 or 256"]
1755    fn tpage_rejects_bad_y() {
1756        let _ = TexturePage::new(0, 128, TextureDepth::Bit4);
1757    }
1758
1759    #[test]
1760    fn clut_encodes_uv_word_correctly() {
1761        let cl = Clut::new(640, 240);
1762        // x=640 → cx=40, y=240 → cy=240.
1763        let word = cl.uv_word();
1764        assert_eq!(word & 0x3f, 40, "cx");
1765        assert_eq!((word >> 6) & 0x1ff, 240, "cy");
1766    }
1767
1768    #[test]
1769    #[should_panic = "x must be a multiple of 16"]
1770    fn clut_rejects_misaligned_x() {
1771        let _ = Clut::new(8, 0);
1772    }
1773
1774    #[test]
1775    fn tex_depth_texels_per_halfword() {
1776        assert_eq!(TextureDepth::Bit4.texels_per_halfword(), 4);
1777        assert_eq!(TextureDepth::Bit8.texels_per_halfword(), 2);
1778        assert_eq!(TextureDepth::Bit15.texels_per_halfword(), 1);
1779    }
1780
1781    #[test]
1782    fn vram_alloc_reserves_framebuffer_then_packs_pages_past_it() {
1783        let mut a = VramAllocator::<6, 16>::new(480);
1784        a.reserve_rect(VramRect::new(0, 0, 320, 480));
1785        let (tp, _h) = a
1786            .alloc_page_run(3, TextureDepth::Bit4, 0)
1787            .expect("3 contiguous pages");
1788        assert_eq!(tp.x() % 64, 0, "page X is 64-aligned");
1789        assert!(tp.x() >= 320, "page must not overlap the framebuffer");
1790        assert_eq!(tp.y(), 0);
1791    }
1792
1793    #[test]
1794    fn vram_alloc_free_round_trips_a_page() {
1795        let mut a = VramAllocator::<6, 16>::new(480);
1796        let (tp1, h1) = a.alloc_page_run(1, TextureDepth::Bit4, 0).unwrap();
1797        let (tp2, _h2) = a.alloc_page_run(1, TextureDepth::Bit4, 0).unwrap();
1798        assert_ne!(tp1.x(), tp2.x());
1799        a.free(h1);
1800        let (tp3, _h3) = a.alloc_page_run(1, TextureDepth::Bit4, 0).unwrap();
1801        assert_eq!(tp3.x(), tp1.x(), "freed page is reused");
1802    }
1803
1804    #[test]
1805    fn vram_alloc_window_lands_in_reserved_room_band() {
1806        let mut a = VramAllocator::<2, 16>::new(480);
1807        a.reserve_room_band(640, 0);
1808        let (tp, pl, _h) = a.alloc_window(32, 32).expect("window fits");
1809        assert_eq!(tp.x(), 640, "first window is at room band base");
1810        assert_eq!((pl.origin_u(), pl.origin_v()), (0, 0));
1811    }
1812
1813    #[test]
1814    fn lazy_room_page_returns_physical_backing_after_last_window() {
1815        let mut a = VramAllocator::<6, 16>::new(480);
1816        a.reserve_rect(VramRect::new(0, 0, 320, 480));
1817        a.reserve_room_band(640, 0);
1818        let (_, _, window) = a.alloc_window(64, 64).expect("room window");
1819        assert!(
1820            a.alloc_page_run(6, TextureDepth::Bit4, 0).is_none(),
1821            "live preferred room page interrupts the six-page top run"
1822        );
1823        a.free(window);
1824        assert!(
1825            a.alloc_page_run(6, TextureDepth::Bit4, 0).is_some(),
1826            "last-window release must return the physical room page"
1827        );
1828    }
1829
1830    #[test]
1831    fn model_slots_preserve_indexed_texture_depth() {
1832        let mut a = VramAllocator::<2, 16>::new(480);
1833        let (bit4, _h4) = a.alloc_model_slot(32, TextureDepth::Bit4).unwrap();
1834        let (bit8, _h8) = a.alloc_model_slot(64, TextureDepth::Bit8).unwrap();
1835
1836        assert_eq!(bit4.depth(), TextureDepth::Bit4);
1837        assert_eq!(bit8.depth(), TextureDepth::Bit8);
1838        assert_ne!(bit4.x(), bit8.x());
1839        assert!(a.alloc_model_slot(64, TextureDepth::Bit15).is_none());
1840    }
1841
1842    #[test]
1843    fn clut_row_allocator_packs_and_reuses_slots() {
1844        let mut c = ClutRowAllocator::<4>::new(480);
1845        let a = c.alloc(16).unwrap();
1846        let b = c.alloc(16).unwrap();
1847        assert_eq!((a.x(), a.y()), (0, 480));
1848        assert_eq!((b.x(), b.y()), (16, 480));
1849        let big = c.alloc(256).unwrap(); // 16 contiguous slots
1850        assert_eq!((big.x(), big.y()), (32, 480));
1851        c.free(a, 16);
1852        let reused = c.alloc(16).unwrap();
1853        assert_eq!((reused.x(), reused.y()), (0, 480), "freed slot reused");
1854    }
1855
1856    #[test]
1857    fn clut_row_allocator_width_limits_each_row() {
1858        let mut c = ClutRowAllocator::<2>::with_width(480, 320);
1859        assert_eq!(c.bounds(), VramRect::new(0, 480, 320, 2));
1860        // 20 four-bit CLUTs fill row 480; the 21st goes to row 481.
1861        for slot in 0..20u16 {
1862            let clut = c.alloc(16).unwrap();
1863            assert_eq!((clut.x(), clut.y()), (slot * 16, 480));
1864        }
1865        let next = c.alloc(16).unwrap();
1866        assert_eq!((next.x(), next.y()), (0, 481));
1867        // A 256-entry CLUT is 16 slots and fits a 20-slot row once.
1868        let mut c = ClutRowAllocator::<2>::with_width(480, 320);
1869        assert!(c.alloc(256).is_some());
1870        assert_eq!(c.alloc(256).unwrap().y(), 481);
1871        assert!(c.alloc(256).is_none());
1872        // Freeing outside the band is ignored rather than corrupting a row.
1873        c.free(Clut::new(320, 480), 16);
1874    }
1875
1876    /// Every rectangle the allocator can hand out, with the CLUT band reserved
1877    /// beside the framebuffer, is disjoint from every CLUT it can hand out.
1878    #[test]
1879    fn reserved_clut_band_is_disjoint_from_every_texture_rectangle() {
1880        const BAND: VramRect = VramRect::new(0, 480, 320, 32);
1881        let inside = |r: VramRect, outer: VramRect| {
1882            r.x >= outer.x
1883                && r.y >= outer.y
1884                && r.x + r.w <= outer.x + outer.w
1885                && r.y + r.h <= outer.y + outer.h
1886        };
1887        let mut a = VramAllocator::<6, 32>::with_clut_band(BAND);
1888        assert!(a.clut_band_is_reserved());
1889        assert_eq!(a.clut_bounds(), BAND);
1890        let framebuffer = VramRect::new(0, 0, 320, 480);
1891        a.reserve_rect(framebuffer);
1892        a.reserve_room_band(640, 0);
1893
1894        let mut rects: [Option<VramRect>; 64] = [None; 64];
1895        let mut count = 0;
1896        let mut keep = |handle: VramHandle, rects: &mut [Option<VramRect>; 64]| {
1897            if let VramHandle::Rect(r) = handle {
1898                rects[count] = Some(r);
1899                count += 1;
1900            }
1901        };
1902        // Pages at both page rows, until the allocator refuses.
1903        for page_y in [0u16, 256] {
1904            while let Some((_, h)) = a.alloc_page_run(1, TextureDepth::Bit4, page_y) {
1905                keep(h, &mut rects);
1906            }
1907        }
1908        // Model strips and room pages ask the same grid.
1909        assert!(a.alloc_model_slot(64, TextureDepth::Bit4).is_none());
1910        let first_room_page = a.alloc_window(64, 64);
1911        assert!(
1912            first_room_page.is_none(),
1913            "no page is left to back a room window"
1914        );
1915
1916        // CLUTs: fill the band with 4-bit and 8-bit palettes.
1917        let mut cluts: [Option<VramRect>; 640] = [None; 640];
1918        let mut n = 0;
1919        while let Some((clut, _)) = a.alloc_clut(16) {
1920            cluts[n] = Some(VramRect::new(clut.x(), clut.y(), 16, 1));
1921            n += 1;
1922        }
1923        assert_eq!(
1924            n,
1925            20 * 32,
1926            "the band holds 20 four-bit CLUTs on each of 32 rows"
1927        );
1928        let mut a8 = VramAllocator::<6, 32>::with_clut_band(BAND);
1929        let mut eight = 0;
1930        while let Some((clut, _)) = a8.alloc_clut(256) {
1931            assert!(inside(VramRect::new(clut.x(), clut.y(), 256, 1), BAND));
1932            eight += 1;
1933        }
1934        assert_eq!(eight, 32);
1935
1936        for clut in cluts[..n].iter().flatten() {
1937            assert!(inside(*clut, BAND), "CLUT inside the band");
1938            assert!(!clut.overlaps(framebuffer));
1939            for page in rects[..count].iter().flatten() {
1940                assert!(!clut.overlaps(*page), "CLUT overlaps a texture page");
1941            }
1942        }
1943        assert!(count > 0);
1944    }
1945
1946    #[test]
1947    fn the_unreserved_full_width_band_overlaps_a_lower_page() {
1948        // The layout this replaces: pages at page row 256 run through the CLUT
1949        // band under the framebuffer, and nothing in the allocator notices.
1950        let mut a = VramAllocator::<6, 16>::new(480);
1951        assert!(!a.clut_band_is_reserved());
1952        let (_, handle) = a.alloc_page_run(1, TextureDepth::Bit4, 256).unwrap();
1953        let VramHandle::Rect(page) = handle else {
1954            panic!("page handle");
1955        };
1956        assert!(page.overlaps(a.clut_bounds()));
1957    }
1958
1959    #[test]
1960    #[should_panic = "overlaps the reserved CLUT band"]
1961    fn reserving_a_rectangle_over_the_clut_band_is_refused() {
1962        let mut a = VramAllocator::<6, 32>::with_clut_band(VramRect::new(0, 480, 320, 32));
1963        a.reserve_rect(VramRect::new(0, 256, 320, 256));
1964    }
1965
1966    #[test]
1967    fn texture_window_atlas_release_frees_for_reuse() {
1968        let mut atlas = TextureWindowAtlas::<1>::new();
1969        let first = atlas.allocate(32, 32).unwrap();
1970        let _second = atlas.allocate(32, 32).unwrap();
1971        atlas.release(first);
1972        let reused = atlas.allocate(32, 32).unwrap();
1973        assert_eq!(
1974            (reused.origin_u(), reused.origin_v()),
1975            (first.origin_u(), first.origin_v()),
1976            "released slot is reused"
1977        );
1978    }
1979
1980    #[test]
1981    fn overlapping_layout_rectangles_are_found_in_listed_order() {
1982        // Disjoint: the two framebuffers and the block under them.
1983        let clean = [
1984            VramRect::new(0, 0, 320, 240),
1985            VramRect::new(0, 240, 320, 240),
1986            VramRect::new(0, 480, 320, 32),
1987        ];
1988        assert_eq!(first_vram_overlap(&clean), None);
1989        assert!(vram_layout_is_disjoint(&clean));
1990
1991        // The hl-psx bug in miniature: CLUT rows at Y=480..503 that run past
1992        // X=320 sit inside a texture page banded at Y=256.
1993        let clashing = [
1994            VramRect::new(0, 0, 320, 240),
1995            VramRect::new(320, 256, 64, 256),
1996            VramRect::new(0, 480, 640, 24),
1997        ];
1998        assert_eq!(first_vram_overlap(&clashing), Some((1, 2)));
1999        assert!(!vram_layout_is_disjoint(&clashing));
2000
2001        // Touching edges are not an overlap.
2002        let touching = [
2003            VramRect::new(0, 0, 320, 240),
2004            VramRect::new(320, 0, 64, 240),
2005        ];
2006        assert_eq!(first_vram_overlap(&touching), None);
2007        let stacked = [VramRect::new(0, 0, 320, 240), VramRect::new(0, 240, 320, 8)];
2008        assert_eq!(first_vram_overlap(&stacked), None);
2009
2010        // A single rect, and none at all, are trivially disjoint.
2011        assert!(vram_layout_is_disjoint(&[VramRect::new(0, 0, 1, 1)]));
2012        assert!(vram_layout_is_disjoint(&[]));
2013    }
2014}