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