Skip to main content

bhoo/
media.rs

1//! Bounded caller-owned RGBA images and object-fit geometry.
2use crate::Rect;
3use std::sync::{
4    Arc,
5    atomic::{AtomicU32, Ordering},
6};
7static NEXT_IMAGE_ID: AtomicU32 = AtomicU32::new(1);
8/// Immutable, shared RGBA8 pixels. Loading and decoding are the host application's responsibility.
9#[derive(Clone, Debug, PartialEq)]
10pub struct Image {
11    pub(crate) id: u32,
12    pub(crate) width: u32,
13    pub(crate) height: u32,
14    pub(crate) msdf_px_range: f32,
15    pub(crate) pixels: Arc<[u8]>,
16}
17impl Image {
18    /// Maximum width or height (in pixels) packed into the shared 2048×2048 GPU image atlas.
19    pub const ATLAS_MAX_DIMENSION: u32 = 1022;
20    /// Maximum width or height (in pixels) accepted for standalone RGBA images.
21    pub const MAX_DIMENSION: u32 = 4096;
22    const MAX_RGBA_BYTES: usize = 64 * 1024 * 1024;
23
24    /// Construct a bounded RGBA8 image (up to `4096×4096`, `<= 64 MiB`).
25    /// Images up to `1022×1022` pack into the shared atlas; larger images render via standalone GPU textures.
26    pub fn rgba(width: u32, height: u32, pixels: Vec<u8>) -> Option<Self> {
27        Self::new_inner(width, height, 0.0, Self::MAX_DIMENSION, pixels)
28    }
29    /// Construct a Multi-Channel Signed Distance Field (MSDF) RGBA8 image (`px_range > 0`)
30    /// for resolution-independent vector rendering in the GLES fragment shader.
31    pub fn msdf(width: u32, height: u32, px_range: f32, pixels: Vec<u8>) -> Option<Self> {
32        if !px_range.is_finite() || px_range <= 0.0 {
33            return None;
34        }
35        Self::new_inner(width, height, px_range, Self::ATLAS_MAX_DIMENSION, pixels)
36    }
37    fn new_inner(
38        width: u32,
39        height: u32,
40        msdf_px_range: f32,
41        max_dimension: u32,
42        pixels: Vec<u8>,
43    ) -> Option<Self> {
44        if width == 0 || height == 0 || width > max_dimension || height > max_dimension {
45            return None;
46        }
47        let length = (width as usize)
48            .checked_mul(height as usize)?
49            .checked_mul(4)?;
50        if length > Self::MAX_RGBA_BYTES || pixels.len() != length {
51            return None;
52        }
53        let id = NEXT_IMAGE_ID
54            .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
55            .ok()?;
56        Some(Self {
57            id,
58            width,
59            height,
60            msdf_px_range,
61            pixels: pixels.into(),
62        })
63    }
64    /// Whether this image fits in the shared 2048×2048 GPU image atlas (`<= 1022×1022`).
65    pub fn is_atlas_eligible(&self) -> bool {
66        self.width <= Self::ATLAS_MAX_DIMENSION && self.height <= Self::ATLAS_MAX_DIMENSION
67    }
68    pub fn msdf_px_range(&self) -> f32 {
69        self.msdf_px_range
70    }
71    pub fn width(&self) -> u32 {
72        self.width
73    }
74    pub fn height(&self) -> u32 {
75        self.height
76    }
77    pub fn pixels(&self) -> &[u8] {
78        &self.pixels
79    }
80    pub fn id(&self) -> u32 {
81        self.id
82    }
83}
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub enum ImageFit {
86    #[default]
87    Cover,
88    Contain,
89}
90/// Destination and normalized source coordinates for centered object-fit.
91pub fn fit_image(bounds: Rect, width: u32, height: u32, fit: ImageFit) -> Option<(Rect, [f32; 4])> {
92    if width == 0
93        || height == 0
94        || !bounds.width.is_finite()
95        || !bounds.height.is_finite()
96        || bounds.width <= 0.0
97        || bounds.height <= 0.0
98    {
99        return None;
100    }
101    let iw = width as f32;
102    let ih = height as f32;
103    match fit {
104        ImageFit::Contain => {
105            let scale = (bounds.width / iw).min(bounds.height / ih);
106            let w = iw * scale;
107            let h = ih * scale;
108            Some((
109                Rect {
110                    x: bounds.x + (bounds.width - w) / 2.0,
111                    y: bounds.y + (bounds.height - h) / 2.0,
112                    width: w,
113                    height: h,
114                },
115                [0.0, 0.0, 1.0, 1.0],
116            ))
117        }
118        ImageFit::Cover => {
119            let scale = (bounds.width / iw).max(bounds.height / ih);
120            let u = bounds.width / (iw * scale);
121            let v = bounds.height / (ih * scale);
122            Some((
123                bounds,
124                [
125                    (1.0 - u) / 2.0,
126                    (1.0 - v) / 2.0,
127                    (1.0 + u) / 2.0,
128                    (1.0 + v) / 2.0,
129                ],
130            ))
131        }
132    }
133}
134
135#[cfg(test)]
136#[path = "media.spec.rs"]
137mod tests;