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