Skip to main content

mln_engine/draw/
resources.rs

1//! What the renderer makes its buffers and textures with on its backend's
2//! `Gpu`, with the rendering stats that count them and the queue that they
3//! go to when they drop, and the handle a layer makes its meshes and
4//! targets with ([`Resources`]).
5
6use std::rc::Rc;
7
8use mln_gfx::cull_face_mode::CullFaceMode;
9use mln_gfx::gpu::{
10    BufferDesc, BufferUsage, Gpu, GpuError, ShaderKey, TextureDesc, TextureFormat, TextureId, TextureUsage,
11};
12use mln_gfx::rendering_stats::RenderingStats;
13use mln_gfx::types::TextureChannelDataType;
14use mln_gfx::{ColorMode, Rgba, Size};
15
16use crate::draw::buffer::{self, Buffer};
17use crate::draw::context::Context;
18use crate::draw::objects::{DrawGeometry, Mesh, Textures};
19use crate::draw::release::{Release, ReleaseQueue};
20use crate::draw::target::Target;
21use crate::log_target;
22
23/// The renderer's GPU resources, as a layer's hooks make and read them: the
24/// meshes it draws (`mesh`) and the targets its draws draw
25/// into ([`target`](Self::target)). What it makes stays while the layer
26/// keeps its handle.
27pub struct Resources<'a> {
28    pub gpu: &'a mut dyn Gpu,
29    pub context: &'a mut Context,
30}
31
32impl<'a> Resources<'a> {
33    pub(crate) fn new(gpu: &'a mut dyn Gpu, context: &'a mut Context) -> Self {
34        Resources { gpu, context }
35    }
36
37    /// The mesh of `geometry`, drawn with `shader` in `color_mode` and
38    /// `cull_face_mode`, binding `textures`.
39    #[must_use]
40    pub fn mesh(
41        &mut self,
42        shader: ShaderKey,
43        color_mode: ColorMode,
44        cull_face_mode: CullFaceMode,
45        geometry: DrawGeometry,
46        textures: Textures,
47    ) -> Mesh {
48        Mesh::new(self.context, shader, color_mode, cull_face_mode, geometry, textures)
49    }
50
51    /// A target of `size`, whose texture's channels are of `type_`, or of
52    /// the type the backend draws into for it, and which clears to `clear`
53    /// before its draws. Its texture is sampled linearly and clamped to its
54    /// edges.
55    #[must_use]
56    pub fn target(&mut self, size: Size, type_: TextureChannelDataType, clear: Rgba) -> Target {
57        Target::new(self.context, size, type_, clear)
58    }
59}
60
61/// A texture of the context's `Gpu`, which goes to the context's release
62/// queue when it drops, as a [`Buffer`] does.
63pub(crate) struct GpuTexture {
64    id: TextureId,
65    /// The bytes the rendering stats count it with, `None` where they don't.
66    counted: Option<usize>,
67    queue: Rc<ReleaseQueue>,
68}
69
70impl GpuTexture {
71    #[must_use]
72    pub(crate) fn id(&self) -> TextureId {
73        self.id
74    }
75}
76
77impl Drop for GpuTexture {
78    fn drop(&mut self) {
79        self.queue.push(match self.counted {
80            Some(bytes) => Release::Texture(self.id, bytes),
81            None => Release::Resource(self.id.into()),
82        });
83    }
84}
85
86/// A texture of the context's `Gpu` that draws share: a
87/// [`Texture2D`](crate::draw::texture2d::Texture2D)'s, which bindings made
88/// of it hold after the texture replaces it.
89pub(crate) type SharedGpuTexture = Rc<GpuTexture>;
90
91/// What the renderer makes its buffers and textures with: the rendering
92/// stats that count them, the queue that they go to when they drop, the
93/// epochs of its uniform buffer arrays, and what failed on the GPU in the
94/// frame being encoded.
95#[derive(Default)]
96pub(crate) struct Device {
97    pub(crate) stats: RenderingStats,
98    pub(crate) queue: Rc<ReleaseQueue>,
99    /// The last epoch a uniform buffer array took.
100    uniform_epoch: u64,
101    /// Why the first GPU failure since [`take_failure`](Self::take_failure)
102    /// failed.
103    failure: Option<String>,
104}
105
106impl Device {
107    /// Logs `message`, why something of the frame being encoded failed on
108    /// the GPU, and keeps it as the frame's failure unless one came first.
109    pub(crate) fn fail(&mut self, message: String) {
110        log::error!(target: log_target::RENDER, "{message}");
111        self.failure.get_or_insert(message);
112    }
113
114    /// Whether something failed since the last [`take_failure`](Self::take_failure).
115    pub(crate) fn failed(&self) -> bool {
116        self.failure.is_some()
117    }
118
119    /// Why the first GPU failure since the last call failed, if one did.
120    pub(crate) fn take_failure(&mut self) -> Option<String> {
121        self.failure.take()
122    }
123
124    /// An epoch for a uniform buffer array that changed, one that no array
125    /// of the device has had, and never 0.
126    pub(crate) fn next_uniform_epoch(&mut self) -> u64 {
127        self.uniform_epoch += 1;
128        self.uniform_epoch
129    }
130
131    /// A buffer of `gpu` of `usage` holding `data`.
132    pub(crate) fn buffer(&mut self, gpu: &mut dyn Gpu, usage: BufferUsage, data: &[u8]) -> Result<Buffer, GpuError> {
133        let buffer = self.allocate(gpu, usage, data.len())?;
134        write_bytes(gpu, &buffer, data)?;
135        buffer::count_write(&mut self.stats, usage, data.len(), false);
136        Ok(buffer)
137    }
138
139    /// A buffer of `usage` holding the bytes of `data`, written from the JS
140    /// array they're in.
141    #[cfg(target_family = "wasm")]
142    pub(crate) fn buffer_from_host(
143        &mut self,
144        gpu: &mut dyn Gpu,
145        usage: BufferUsage,
146        data: &mln_wire::host_bytes::HostBytes,
147    ) -> Result<Buffer, GpuError> {
148        let buffer = self.allocate(gpu, usage, data.len())?;
149        if !data.is_empty()
150            && let Some(array) = data.array()
151        {
152            gpu.write_buffer_from_host(buffer.id(), 0, &array)?;
153        }
154        Ok(buffer)
155    }
156
157    /// A buffer of `usage` that writes of up to `size` bytes fit in, which
158    /// the stats count until the context destroys it.
159    fn allocate(&mut self, gpu: &mut dyn Gpu, usage: BufferUsage, size: usize) -> Result<Buffer, GpuError> {
160        let allocated = buffer::allocated_size(usage, size);
161        let id = gpu.create_buffer(&BufferDesc { label: buffer::label(usage), usage, size: allocated as u64 })?;
162        buffer::count(&mut self.stats, usage, allocated, 1);
163        self.stats.total_buffers += 1;
164        self.stats.total_buffer_objs += 1;
165        Ok(Buffer::new(id, usage, size, &self.queue))
166    }
167
168    /// Writes `data` at the start of `buffer`, and counts the write. Fails
169    /// if `data` is longer than the buffer.
170    pub(crate) fn write(&mut self, gpu: &mut dyn Gpu, buffer: &Buffer, data: &[u8]) -> Result<(), GpuError> {
171        write_bytes(gpu, buffer, data)?;
172        buffer::count_write(&mut self.stats, buffer.usage(), data.len(), true);
173        Ok(())
174    }
175
176    /// Writes `data` to the uniform or, with `storage`, storage buffer in
177    /// `slot`, first making one if the slot has none or `data` doesn't fit
178    /// in it. Returns whether it made one in place of one the slot had,
179    /// whose bindings its owner then drops.
180    pub(crate) fn write_uniforms(
181        &mut self,
182        gpu: &mut dyn Gpu,
183        slot: &mut Option<Buffer>,
184        data: &[u8],
185        storage: bool,
186    ) -> bool {
187        let usage = if storage { BufferUsage::Storage } else { BufferUsage::Uniform };
188        if let Some(buffer) = slot.as_ref().filter(|buffer| buffer.usage() == usage && buffer.size() >= data.len()) {
189            if let Err(error) = self.write(gpu, buffer, data) {
190                self.fail(format!("Writing a buffer failed: {error}"));
191            }
192            return false;
193        }
194        let replaced = slot.is_some();
195        *slot = match self.buffer(gpu, usage, data) {
196            Ok(buffer) => Some(buffer),
197            Err(error) => {
198                self.fail(format!("Making a buffer failed: {error}"));
199                None
200            }
201        };
202        replaced
203    }
204
205    /// A texture of `gpu` of `desc`, which the stats count with `counted`
206    /// bytes, or not at all with `None`, until the context destroys it.
207    pub(crate) fn texture(
208        &mut self,
209        gpu: &mut dyn Gpu,
210        desc: &TextureDesc<'_>,
211        counted: Option<usize>,
212    ) -> Result<GpuTexture, GpuError> {
213        let id = gpu.create_texture(desc)?;
214        if let Some(bytes) = counted {
215            self.stats.num_created_textures += 1;
216            self.stats.num_active_textures += 1;
217            self.stats.mem_textures += bytes as i32;
218        }
219        Ok(GpuTexture { id, counted, queue: Rc::clone(&self.queue) })
220    }
221
222    /// A texture of `size` and `format` that passes draw into and nothing
223    /// samples, such as a target's depth and stencil. The stats don't count
224    /// it.
225    pub(crate) fn attachment(
226        &mut self,
227        gpu: &mut dyn Gpu,
228        label: &str,
229        size: Size,
230        format: TextureFormat,
231    ) -> Result<GpuTexture, GpuError> {
232        let usage = TextureUsage { render_target: true, ..TextureUsage::default() };
233        self.texture(gpu, &TextureDesc { label, size, format, usage, mipmapped: false }, None)
234    }
235}
236
237/// The bytes a texture of `size` and `format` that passes draw into takes,
238/// as [`RenderingStats`] counts it: a depth and stencil format at 4 bytes a
239/// texel, or 8 with a 32-bit depth and a stencil, though a backend may
240/// store it in more.
241pub(crate) fn attachment_bytes(size: Size, format: TextureFormat) -> u64 {
242    let texel = match format {
243        TextureFormat::Depth32Float | TextureFormat::Depth24PlusStencil8 => 4,
244        TextureFormat::Depth32FloatStencil8 => 8,
245        format => u64::from(format.bytes_per_texel().unwrap_or(4)),
246    };
247    u64::from(size.width) * u64::from(size.height) * texel
248}
249
250/// Writes `data` at the start of `buffer` through `gpu`. Fails if `data` is
251/// longer than the buffer.
252fn write_bytes(gpu: &mut dyn Gpu, buffer: &Buffer, data: &[u8]) -> Result<(), GpuError> {
253    if data.len() > buffer.size() {
254        return Err(GpuError::Invalid(format!("a write of {} bytes to a buffer of {}", data.len(), buffer.size())));
255    }
256    if data.is_empty() {
257        return Ok(());
258    }
259    // `Gpu::write_buffer` takes whole 4-byte words.
260    if data.len().is_multiple_of(4) {
261        gpu.write_buffer(buffer.id(), 0, data)
262    } else {
263        let mut padded = data.to_vec();
264        padded.resize(data.len().next_multiple_of(4), 0);
265        gpu.write_buffer(buffer.id(), 0, &padded)
266    }
267}