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            Cow::Owned(self.rows().flatten().copied().collect())
76        }
77    }
78}