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
36/// Windows: the texture of a view's frame, shared with the backend's
37/// Direct3D 11 device (`ShaderView::surface`).
38#[cfg(windows)]
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct SharedTexture {
42    /// The view's textures and fence for one frame size, unique in the
43    /// process: handles of another set are other objects, even when equal.
44    pub set: u64,
45    /// The texture's NT handle (`ID3D11Device1::OpenSharedResource1`), valid
46    /// while the view keeps frames of this size.
47    pub texture: windows_sys::Win32::Foundation::HANDLE,
48    /// The NT handle of the view's fence (`ID3D11Device5::OpenSharedFence`),
49    /// valid while the view keeps frames of this size.
50    pub fence: windows_sys::Win32::Foundation::HANDLE,
51    /// What to signal on the fence once the frame that draws the texture is
52    /// submitted: until then the view renders into none of its others.
53    pub value: u64,
54    /// Width in pixels.
55    pub width: u32,
56    /// Height in pixels.
57    pub height: u32,
58}
59
60impl Frame {
61    /// The rows, without their padding.
62    pub fn rows(&self) -> impl Iterator<Item = &[u8]> {
63        let row = self.width as usize * 4;
64        self.pixels
65            .chunks(self.stride.max(1) as usize)
66            .take(self.height as usize)
67            .map(move |r| &r[..row.min(r.len())])
68    }
69
70    /// The pixels with no padding between rows (`width * 4` bytes apart).
71    pub fn tight(&self) -> Cow<'_, [u8]> {
72        if self.stride == self.width * 4 {
73            Cow::Borrowed(&self.pixels)
74        } else {
75            // Row by row: a backend takes this every frame of every shader
76            // view, megabytes each, so it copies whole rows into one
77            // allocation rather than collecting bytes into a growing one.
78            let mut tight = Vec::with_capacity(self.width as usize * 4 * self.height as usize);
79            for row in self.rows() {
80                tight.extend_from_slice(row);
81            }
82            Cow::Owned(tight)
83        }
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    #[test]
92    fn tight_drops_the_padding_between_rows() {
93        // 2×3 pixels, rows 12 bytes apart: 8 bytes of pixels, 4 of padding.
94        let pixels: Vec<u8> = (0..36).collect();
95        let frame = Frame {
96            pixels,
97            width: 2,
98            height: 3,
99            stride: 12,
100            serial: 1,
101        };
102        let tight = frame.tight();
103        assert!(matches!(tight, Cow::Owned(_)));
104        let want: Vec<u8> = [0..8, 12..20, 24..32].into_iter().flatten().collect();
105        assert_eq!(&*tight, &want[..]);
106    }
107
108    #[test]
109    fn tight_rows_are_borrowed() {
110        let frame = Frame {
111            pixels: (0..24).collect(),
112            width: 2,
113            height: 3,
114            stride: 8,
115            serial: 1,
116        };
117        assert!(matches!(frame.tight(), Cow::Borrowed(p) if p.len() == 24));
118    }
119}