Skip to main content

mln_webgpu/
renderer_backend.rs

1// Ports include/mln/webgpu/renderer_backend.hpp and src/mln/webgpu/renderer_backend.cpp
2//
3// The C++ backend stores raw `WGPUDevice`/`WGPUQueue`/instance handles in its
4// `Impl` and every resource reaches them through `Context& -> getBackend()`.
5// Here the `Impl` is shared (`Rc<BackendImpl>`) by the backend and the
6// context, and resources hold an `Rc<Context>`.
7//
8// `getDefaultRenderable()` is pure virtual and implemented by the platform
9// backends (HeadlessBackend), which embed this struct.
10//
11// TODO(port): `setSurface` (window surfaces) and the `getCurrentTextureView`
12// / `getDepthStencilView` / `getFramebufferSize` virtuals used as render pass
13// fallbacks when a renderable has no views of its own; the headless
14// renderable always provides them.
15
16use std::cell::{Cell, RefCell};
17use std::rc::Rc;
18
19use mln_gfx::renderer_backend::{ContextMode, RendererBackendBase};
20use mln_gfx::shader_registry::ShaderRegistry;
21use mln_gfx::shaders::program_parameters::ProgramParameters;
22use mln_gfx::shaders::shader_source::BuiltIn;
23
24use crate::context::Context;
25use crate::shaders::shader_group::ShaderGroup;
26use crate::shaders::shader_source::shader_source;
27
28/// `RendererBackend::Impl`
29#[derive(Default)]
30pub struct BackendImpl {
31    instance: RefCell<Option<wgpu::Instance>>,
32    adapter: RefCell<Option<wgpu::Adapter>>,
33    device: RefCell<Option<wgpu::Device>>,
34    queue: RefCell<Option<wgpu::Queue>>,
35    /// `wgpu::TextureFormat::Undefined` is `None`.
36    depth_stencil_format: Cell<Option<wgpu::TextureFormat>>,
37    color_format: Cell<Option<wgpu::TextureFormat>>,
38}
39
40impl BackendImpl {
41    pub fn set_instance(&self, instance: Option<wgpu::Instance>) {
42        *self.instance.borrow_mut() = instance;
43    }
44    pub fn set_adapter(&self, adapter: Option<wgpu::Adapter>) {
45        *self.adapter.borrow_mut() = adapter;
46    }
47    pub fn set_device(&self, device: Option<wgpu::Device>) {
48        *self.device.borrow_mut() = device;
49    }
50    pub fn set_queue(&self, queue: Option<wgpu::Queue>) {
51        *self.queue.borrow_mut() = queue;
52    }
53    pub fn get_instance(&self) -> Option<wgpu::Instance> {
54        self.instance.borrow().clone()
55    }
56    pub fn get_adapter(&self) -> Option<wgpu::Adapter> {
57        self.adapter.borrow().clone()
58    }
59    pub fn get_device(&self) -> Option<wgpu::Device> {
60        self.device.borrow().clone()
61    }
62    pub fn get_queue(&self) -> Option<wgpu::Queue> {
63        self.queue.borrow().clone()
64    }
65    pub fn set_depth_stencil_format(&self, format: Option<wgpu::TextureFormat>) {
66        self.depth_stencil_format.set(format);
67    }
68    pub fn get_depth_stencil_format(&self) -> Option<wgpu::TextureFormat> {
69        self.depth_stencil_format.get()
70    }
71    pub fn set_color_format(&self, format: Option<wgpu::TextureFormat>) {
72        self.color_format.set(format);
73    }
74    pub fn get_color_format(&self) -> Option<wgpu::TextureFormat> {
75        self.color_format.get()
76    }
77}
78
79/// `webgpu::RendererBackend`: embedded by the platform backends, which
80/// implement `gfx::RendererBackend` by delegating to it.
81pub struct RendererBackend {
82    pub base: RendererBackendBase,
83    impl_: Rc<BackendImpl>,
84}
85
86/// The shader types registered by `initShaders`, in the C++ order.
87const REGISTERED_SHADERS: &[BuiltIn] = &[
88    BuiltIn::BackgroundShader,
89    BuiltIn::BackgroundPatternShader,
90    BuiltIn::CircleShader,
91    BuiltIn::ClippingMaskProgram,
92    BuiltIn::CollisionBoxShader,
93    BuiltIn::CollisionCircleShader,
94    BuiltIn::DebugShader,
95    BuiltIn::FillShader,
96    BuiltIn::FillOutlineShader,
97    BuiltIn::FillPatternShader,
98    BuiltIn::FillOutlinePatternShader,
99    BuiltIn::FillOutlineTriangulatedShader,
100    BuiltIn::FillExtrusionShader,
101    BuiltIn::FillExtrusionPatternShader,
102    BuiltIn::HeatmapShader,
103    BuiltIn::HeatmapTextureShader,
104    BuiltIn::HillshadeShader,
105    BuiltIn::HillshadePrepareShader,
106    BuiltIn::ColorReliefShader,
107    BuiltIn::LineShader,
108    BuiltIn::LineGradientShader,
109    BuiltIn::LinePatternShader,
110    BuiltIn::LineSDFShader,
111    BuiltIn::LineGradientSDFShader,
112    BuiltIn::LocationIndicatorShader,
113    BuiltIn::LocationIndicatorTexturedShader,
114    BuiltIn::RasterShader,
115    BuiltIn::SymbolIconShader,
116    BuiltIn::SymbolSDFShader,
117    BuiltIn::SymbolTextAndIconShader,
118    BuiltIn::WideVectorShader,
119];
120
121impl RendererBackend {
122    pub fn new(context_mode: ContextMode) -> Self {
123        RendererBackend { base: RendererBackendBase::new(context_mode), impl_: Rc::new(BackendImpl::default()) }
124    }
125
126    pub fn backend_impl(&self) -> &Rc<BackendImpl> {
127        &self.impl_
128    }
129
130    /// `context.reset()`, which also releases the buffers the context caches
131    /// (`Context::release_cached_buffers`).
132    pub(crate) fn reset_context(&mut self) {
133        if let Some(context) = self.base.reset_context()
134            && let Some(context) = context.as_any().downcast_ref::<Context>()
135        {
136            context.release_cached_buffers();
137        }
138    }
139
140    /// `createContext()`
141    pub fn create_context(&self) -> Rc<Context> {
142        Context::new(self.impl_.clone())
143    }
144
145    /// `activate()` / `deactivate()`: activation logic if needed (none).
146    pub fn activate(&self) {}
147    pub fn deactivate(&self) {}
148
149    /// `initShaders`: register one `webgpu::ShaderGroup` per built-in shader.
150    ///
151    /// C++ registers all 31 types; a type whose WGSL is not part of this
152    /// build is skipped (TODO(port): all sources once the
153    /// `@maplibre//:webgpu-shader-headers` filegroup feeds the extractor).
154    /// A duplicate registration is an error, as in C++ (which throws).
155    pub fn init_shaders(&self, registry: &ShaderRegistry, program_parameters: &ProgramParameters) {
156        for &shader_id in REGISTERED_SHADERS {
157            let Some(source) = shader_source(shader_id) else {
158                continue;
159            };
160            let group = Rc::new(ShaderGroup::new(shader_id, program_parameters.clone()));
161            if !registry.register_shader_group(group, source.name) {
162                panic!("Failed to register {} with shader registry!", source.name);
163            }
164        }
165    }
166
167    pub fn set_instance(&self, instance: Option<wgpu::Instance>) {
168        self.impl_.set_instance(instance);
169    }
170    pub fn set_device(&self, device: Option<wgpu::Device>) {
171        self.impl_.set_device(device);
172    }
173    pub fn set_queue(&self, queue: Option<wgpu::Queue>) {
174        self.impl_.set_queue(queue);
175    }
176    pub fn get_instance(&self) -> Option<wgpu::Instance> {
177        self.impl_.get_instance()
178    }
179    pub fn get_device(&self) -> Option<wgpu::Device> {
180        self.impl_.get_device()
181    }
182    pub fn get_queue(&self) -> Option<wgpu::Queue> {
183        self.impl_.get_queue()
184    }
185    pub fn set_depth_stencil_format(&self, format: Option<wgpu::TextureFormat>) {
186        self.impl_.set_depth_stencil_format(format);
187    }
188    pub fn get_depth_stencil_format(&self) -> Option<wgpu::TextureFormat> {
189        self.impl_.get_depth_stencil_format()
190    }
191    pub fn set_color_format(&self, format: Option<wgpu::TextureFormat>) {
192        self.impl_.set_color_format(format);
193    }
194    pub fn get_color_format(&self) -> Option<wgpu::TextureFormat> {
195        self.impl_.get_color_format()
196    }
197}
198
199impl Drop for RendererBackend {
200    fn drop(&mut self) {
201        self.reset_context();
202    }
203}