Skip to main content

mln_webgpu/
uniform_buffer.rs

1// Ports include/mln/webgpu/uniform_buffer.hpp and src/mln/webgpu/uniform_buffer.cpp
2//
3// `webgpu::UniformBufferArray` only overrides `bind` (a no-op: bind groups
4// are built per drawable in `Drawable::draw`) and `copy`, so the port uses
5// `gfx::UniformBufferArray` directly.
6
7use std::any::Any;
8use std::rc::Rc;
9
10use mln_gfx::uniform_buffer;
11
12use crate::context::Context;
13use crate::renderer_backend::BackendImpl;
14
15const UNIFORM_BUFFER_ALIGNMENT: usize = 256;
16
17const fn aligned_uniform_size(size: usize) -> usize {
18    if size == 0 {
19        return 0;
20    }
21    size.div_ceil(UNIFORM_BUFFER_ALIGNMENT) * UNIFORM_BUFFER_ALIGNMENT
22}
23
24pub struct UniformBuffer {
25    /// `gfx::UniformBuffer::size`: the 256-byte aligned size. (Quirk ported:
26    /// `UniformBufferArray::createOrUpdate` compares it to the unaligned data
27    /// size, so it recreates small UBOs instead of updating them.)
28    size: usize,
29    /// C++ keeps `Context&`; only device and queue are used. Holding the
30    /// backend state rather than `Rc<Context>` avoids an Rc cycle through the
31    /// context's global uniform buffer array.
32    backend: Rc<BackendImpl>,
33    buffer: Option<wgpu::Buffer>,
34}
35
36impl UniformBuffer {
37    /// `UniformBuffer(context, data, size)`; `data == None` is the C++ null
38    /// pointer.
39    pub fn new(context: &Context, data: Option<&[u8]>, size: usize) -> Self {
40        Self::with_backend(context.get_backend().clone(), data, size)
41    }
42
43    fn with_backend(backend: Rc<BackendImpl>, data: Option<&[u8]>, size: usize) -> Self {
44        let aligned_size = aligned_uniform_size(size);
45        let mut buffer = None;
46        if let Some(device) = backend.get_device()
47            && aligned_size > 0
48        {
49            // C++ creates the buffer mapped and copies the data (zero padded);
50            // a queue write of the padded data has the same effect for the
51            // next submission.
52            let b = device.create_buffer(&wgpu::BufferDescriptor {
53                label: Some("Uniform Buffer"),
54                size: aligned_size as u64,
55                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
56                mapped_at_creation: false,
57            });
58            if let Some(data) = data
59                && let Some(queue) = backend.get_queue()
60            {
61                let mut padded = vec![0u8; aligned_size];
62                padded[..size].copy_from_slice(&data[..size]);
63                queue.write_buffer(&b, 0, &padded);
64            }
65            buffer = Some(b);
66        }
67        UniformBuffer { size: aligned_size, backend, buffer }
68    }
69
70    /// `clone()`: a new buffer of the same size; contents are not copied
71    /// (C++: "We can't directly copy buffer contents in WebGPU without a
72    /// command encoder").
73    pub fn clone_buffer(&self) -> Self {
74        UniformBuffer::with_backend(self.backend.clone(), None, self.size)
75    }
76
77    pub fn get_buffer(&self) -> Option<&wgpu::Buffer> {
78        self.buffer.as_ref()
79    }
80}
81
82impl uniform_buffer::UniformBuffer for UniformBuffer {
83    fn update(&self, data: &[u8]) {
84        if !data.is_empty()
85            && let Some(buffer) = &self.buffer
86            && let Some(queue) = self.backend.get_queue()
87        {
88            queue.write_buffer(buffer, 0, data);
89        }
90    }
91
92    fn get_size(&self) -> usize {
93        self.size
94    }
95
96    fn as_any(&self) -> &dyn Any {
97        self
98    }
99}