Skip to main content

nsh_engine/
shader_frame.rs

1//! What the shader API (`crate::shader`) gives a backend, with or without the
2//! renderer (feature `shader`).
3
4use std::borrow::Cow;
5
6/// The largest side of a frame, in pixels.
7pub const MAX_SIDE: u32 = 4096;
8
9/// The pixels a backend shows: 8 bits per channel, premultiplied alpha.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum PixelFormat {
12    /// Red, green, blue, alpha (GDK's `R8G8B8A8_PREMULTIPLIED`, Core
13    /// Graphics' premultiplied last, Android's `ARGB_8888`).
14    #[default]
15    Rgba,
16    /// Blue, green, red, alpha (Direct2D's, GPUI's).
17    Bgra,
18}
19
20/// A rendered frame: `height` rows of `width` pixels, `stride` bytes apart.
21#[derive(Debug, Clone, Default)]
22#[non_exhaustive]
23pub struct Frame {
24    /// The pixels, row by row.
25    pub pixels: Vec<u8>,
26    /// Width in pixels.
27    pub width: u32,
28    /// Height in pixels.
29    pub height: u32,
30    /// Bytes from one row to the next (at least `width * 4`).
31    pub stride: u32,
32    /// Counts the frames shown: a new value is a new picture.
33    pub serial: u64,
34}
35
36impl Frame {
37    /// The rows, without their padding.
38    pub fn rows(&self) -> impl Iterator<Item = &[u8]> {
39        let row = self.width as usize * 4;
40        self.pixels
41            .chunks(self.stride.max(1) as usize)
42            .take(self.height as usize)
43            .map(move |r| &r[..row.min(r.len())])
44    }
45
46    /// The pixels with no padding between rows (`width * 4` bytes apart).
47    pub fn tight(&self) -> Cow<'_, [u8]> {
48        if self.stride == self.width * 4 {
49            Cow::Borrowed(&self.pixels)
50        } else {
51            Cow::Owned(self.rows().flatten().copied().collect())
52        }
53    }
54}