Skip to main content

mln_webgpu/
renderable_resource.rs

1// Ports include/mln/webgpu/renderable_resource.hpp
2//
3// `gfx::Renderable` stores its resource as `Rc<dyn gfx::RenderableResource>`.
4// The WebGPU resources are wrapped in `RenderableResourceBox`, the one
5// concrete type the backend downcasts to (`as_webgpu`), standing in for the
6// C++ `getResource<webgpu::RenderableResource>()` static_cast.
7//
8// `getBackend()`, `getCommandEncoder()` and `getRenderPassEncoder()` return
9// dummies in every C++ implementation; they are not ported.
10
11use std::any::Any;
12use std::rc::Rc;
13
14use mln_gfx::renderable;
15
16pub trait RenderableResource {
17    /// WebGPU binding happens at the command encoder level; a no-op.
18    fn bind(&self) {}
19
20    /// Renderable resources that require a swap function to be called
21    /// explicitly can override this method.
22    fn swap(&self) {}
23
24    /// The color attachment view for render passes targeting this resource,
25    /// or `None` if the backend supplies it (swapchain).
26    fn get_color_texture_view(&self) -> Option<wgpu::TextureView> {
27        None
28    }
29    fn get_color_texture_format(&self) -> Option<wgpu::TextureFormat> {
30        None
31    }
32    /// The depth/stencil view, if the resource manages one.
33    fn get_depth_stencil_texture_view(&self) -> Option<wgpu::TextureView> {
34        None
35    }
36    fn get_depth_stencil_texture_format(&self) -> Option<wgpu::TextureFormat> {
37        None
38    }
39
40    fn as_any(&self) -> &dyn Any;
41}
42
43/// The `gfx::RenderableResource` of every WebGPU renderable.
44pub struct RenderableResourceBox(pub Box<dyn RenderableResource>);
45
46impl renderable::RenderableResource for RenderableResourceBox {
47    fn bind(&self) {
48        self.0.bind();
49    }
50    fn as_any(&self) -> &dyn Any {
51        self
52    }
53}
54
55impl RenderableResourceBox {
56    pub fn new_rc(resource: impl RenderableResource + 'static) -> Rc<dyn renderable::RenderableResource> {
57        Rc::new(RenderableResourceBox(Box::new(resource)))
58    }
59}
60
61/// `renderable.getResource<webgpu::RenderableResource>()`
62pub fn as_webgpu(resource: &dyn renderable::RenderableResource) -> Option<&dyn RenderableResource> {
63    resource.as_any().downcast_ref::<RenderableResourceBox>().map(|b| b.0.as_ref())
64}
65
66/// `renderable.getResource<T>()` for a concrete WebGPU resource type.
67pub fn downcast_resource<T: 'static>(resource: &dyn renderable::RenderableResource) -> Option<&T> {
68    as_webgpu(resource)?.as_any().downcast_ref::<T>()
69}