Skip to main content

euv_engine/renderer/webgpu/
struct.rs

1use super::*;
2
3/// A WebGPU rendering backend wrapping the GPU device, queue, and canvas context
4/// for GPU-accelerated rendering on the web.
5///
6/// Created asynchronously via `WebGpuRenderer::init` because adapter and
7/// device acquisition returns JavaScript Promises that must be awaited.
8/// Once initialized, the renderer provides methods to create GPU resources
9/// (buffers, shader modules, command encoders) and execute render passes.
10///
11/// WebGPU types are stored as `JsValue` to avoid feature-gated import issues
12/// with `web_sys`. Method calls are performed via `Reflect` and `JsCast`.
13#[derive(Clone, Data)]
14pub struct WebGpuRenderer {
15    /// The WebGPU device (`GpuDevice`) used to create GPU resources.
16    pub(crate) device: JsValue,
17    /// The device's command queue (`GpuQueue`) for submitting command buffers.
18    pub(crate) queue: JsValue,
19    /// The WebGPU canvas rendering context (`GpuCanvasContext`).
20    pub(crate) context: JsValue,
21    /// The HTML canvas element backing the WebGPU context.
22    pub(crate) canvas: HtmlCanvasElement,
23    /// The texture format string used by the canvas's swap chain (e.g., `"bgra8unorm"`).
24    #[get(type(clone))]
25    pub(crate) format: String,
26    /// The physical pixel width of the canvas backing store.
27    #[get(type(copy))]
28    pub(crate) width: u32,
29    /// The physical pixel height of the canvas backing store.
30    #[get(type(copy))]
31    pub(crate) height: u32,
32    /// Whether MSAA anti-aliasing is enabled for render pipelines.
33    ///
34    /// When `true`, the renderer allocates a multisampled intermediate texture
35    /// (`sampleCount: 4`) and resolves into the swap chain each frame; when
36    /// `false`, render passes attach directly to the swap chain view at
37    /// `sampleCount: 1`.
38    #[get(type(copy))]
39    pub(crate) antialias: bool,
40    /// The multisampled color texture used when `antialias` is `true`.
41    ///
42    /// `None` when MSAA is disabled. Rebuilt on every resize because the
43    /// `width`/`height` are immutable for a given `GpuTexture`.
44    #[get(type(clone))]
45    pub(crate) multisample_texture: Option<JsValue>,
46    /// The default `GpuTextureView` into `multisample_texture`.
47    ///
48    /// Cached at texture-create time so `begin_render_pass` does not have to
49    /// recreate the view each frame. `None` when MSAA is disabled.
50    #[get(type(clone))]
51    pub(crate) multisample_view: Option<JsValue>,
52    /// The depth-stencil texture used for depth-tested passes.
53    ///
54    /// Created lazily on the first call to [`WebGpuRenderer::begin_render_pass`]
55    /// that includes a `depthStencil` attachment. Rebuilt on every resize
56    /// because the dimensions are immutable for a given `GpuTexture`. The
57    /// matching default view is cached in `depth_view`.
58    ///
59    /// `None` until the first depth-tested render pass is opened.
60    #[get(type(clone))]
61    pub(crate) depth_texture: Option<JsValue>,
62    /// The default `GpuTextureView` into `depth_texture`.
63    ///
64    /// `None` when no depth texture has been allocated.
65    #[get(type(clone))]
66    pub(crate) depth_view: Option<JsValue>,
67    /// The depth-stencil format used for `depth_texture`.
68    ///
69    /// Stored so subsequent render-pass openers can pass the same format
70    /// to the pipeline layout without having to remember it externally.
71    /// `None` until the first depth texture is allocated.
72    #[get(type(clone))]
73    pub(crate) depth_format: Option<String>,
74    /// User-supplied closure fired when the underlying `GpuDevice` enters
75    /// the `lost` state (browser-initiated context loss, OS driver crash,
76    /// `device.destroy()`, ...).
77    ///
78    /// `None` until the caller calls [`WebGpuRenderer::on_device_lost`].
79    /// The renderer also stores a separate `device_lost_handle` that
80    /// forwards the `GPUDeviceLostInfo` JS value into this callback.
81    #[get(type(clone))]
82    pub(crate) device_lost_callback: Option<js_sys::Function>,
83    /// Whether the device is currently in the `lost` state.
84    ///
85    /// Once flipped to `true`, every GPU operation returns
86    /// `Err(WebGpuError::RendererDisposed)` until the caller destroys the
87    /// renderer and creates a new one (WebGPU has no "recover from lost
88    /// device" API).
89    #[get(type(copy))]
90    pub(crate) device_lost: bool,
91    /// Shared slot for the most recent popped error-scope value.
92    ///
93    /// `device.popErrorScope()` returns a `Promise<GPUError?>`; we
94    /// cannot `.await` it from a sync call site. Instead, every
95    /// `push_error_scope` + `pop_error_scope` pair registers a
96    /// microtask via `wasm_bindgen_futures::spawn_local` that stores
97    /// the resolved value here. Callers that want the error
98    /// synchronously call [`WebGpuRenderer::take_last_error`] to
99    /// drain the slot.
100    ///
101    /// Holding a `Rc<PendingErrorCell>` lets the spawn_local future
102    /// own its own handle independently of `&self`, so the
103    /// renderer's borrow checker stays happy. The slot is empty
104    /// (`None`) by default and after each successful take.
105    ///
106    /// The cell is intentionally `PendingErrorCell` (a `Sync`
107    /// `UnsafeCell` newtype, see [`crate::renderer::static`]) rather
108    /// than `Rc<RefCell<...>>` - the WASM single-threaded scheduler
109    /// makes the runtime borrow check `RefCell` provides unreachable
110    /// in practice, so we trade it for a raw `UnsafeCell` deref
111    /// confined to two call sites. This mirrors how euv-core
112    /// implements its global registries
113    /// (`core/src/renderer/registry/struct.rs:62`).
114    pub(crate) pending_error: Rc<PendingErrorCell>,
115    /// The currently-open `GpuCommandEncoder`, if any.
116    ///
117    /// WebGPU expects the application to encode all work for a
118    /// frame (clear, render passes, compute passes, copy ops) into
119    /// a single command encoder, then call `encoder.finish()` to
120    /// produce a `GpuCommandBuffer` and submit it to the queue.
121    /// The encoder is `None` after `submit()` finishes and must
122    /// be re-acquired via `device.createCommandEncoder()` before
123    /// the next frame.
124    #[get(type(clone))]
125    pub(crate) command_encoder: Option<JsValue>,
126    /// OPT 34: cached render-pass descriptor, allocated lazily on the
127    /// first call to [`WebGpuRenderer::begin_render_pass_full`].
128    ///
129    /// The pre-WebGPU-audit path allocated a fresh `Object` +
130    /// `Array` + 8-15 `Reflect::set` calls every frame. We keep the
131    /// descriptor Object alive for the renderer's lifetime, refreshing
132    /// the per-frame fields (`view`, `resolveTarget`, `clearValue`) in
133    /// place on every call. The cache invalidates itself automatically
134    /// when `load_op` / `store_op`, the depth-stencil shape, or the
135    /// resolve-target shape changes.
136    ///
137    /// `None` until the first `begin_render_pass_full` call; `Some(_)`
138    /// afterwards and persists for the lifetime of the renderer.
139    #[get(type(clone))]
140    pub(crate) render_pass_descriptor_cache: Option<RenderPassDescriptorCache>,
141}
142
143/// OPT 34: persistent render-pass descriptor and its inner
144/// attachments, reused across `begin_render_pass_full` calls.
145///
146/// # Why
147///
148/// `begin_render_pass_full` historically allocated a fresh descriptor
149/// `Object`, a `colorAttachments` `Array`, and one inner
150/// `color_attachment` `Object` (plus an optional `clearValue` `Object`)
151/// on every frame, then ran 8-15 `Reflect::set` calls to populate
152/// them. WebGPU re-validates the descriptor each call, but the JS-side
153/// `Object` / `Array` allocations and the per-property `Reflect::set`
154/// crossings are pure overhead — only the `clearValue` and (rarely)
155/// `view` / `loadOp` / `storeOp` fields change between frames.
156///
157/// # What we cache
158///
159/// - The top-level descriptor `Object` (the one passed to
160///   `beginRenderPass`).
161/// - The `colorAttachments` `Array` (always exactly one element —
162///   we keep the same `Array` reference and mutate its slot 0 in
163///   place).
164/// - The inner color attachment `Object` (slot 0 of
165///   `colorAttachments`).
166/// - The `clearValue` `Object` (the `{r, g, b, a}` dictionary that
167///   is the actual per-frame mutating field).
168/// - Last-applied `loadOp` / `storeOp` string slices, to detect when
169///   the caller switched ops and the cached descriptor must be
170///   rebuilt (rare; WebGPU does not hot-swap ops every frame).
171/// - Last-applied depth-stencil shape (present / absent), to detect
172///   when the depth-stencil shape changes.
173///
174/// # Invalidation
175///
176/// The cache is invalidated (rebuilt from scratch) when any of:
177/// - `load_op` changes between calls,
178/// - `store_op` changes between calls,
179/// - the depth-stencil shape changes (None → Some / Some → None),
180/// - the resolve-target shape changes (MSAA on/off).
181///
182/// `view` / `resolveTarget` / `clearValue` are refreshed on every call
183/// (the swap-chain view expires after each presented frame, so caching
184/// it across frames silently invalidates every subsequent render pass).
185///
186/// These are all `&'static str` (they come from `WEBGPU_*_OP_*`
187/// constants), so invalidation is a pointer-compare.
188///
189/// `Clone` is derived so the parent `WebGpuRenderer`'s `Data` derive
190/// (which adds a `Clone` bound on every field) keeps compiling;
191/// `js_sys::Object` and `js_sys::Array` both derive `Clone`, so the
192/// derived `Clone` impl just clones the inner JS-side references
193/// (cheap, no JS allocation).
194#[derive(Clone, Debug)]
195pub struct RenderPassDescriptorCache {
196    /// The cached top-level `GpuRenderPassDescriptor` Object.
197    /// Pass directly to `encoder.beginRenderPass(descriptor)`.
198    pub(crate) descriptor: Object,
199    /// The cached inner color attachment Object.
200    /// `descriptor.colorAttachments[0]` in JS terms.
201    pub(crate) attachment: Object,
202    /// The cached `clearValue` Object (the `{r, g, b, a}` dictionary
203    /// under `attachment.clearValue`). The hot-path field — only
204    /// this is mutated on most frames.
205    pub(crate) clear_value: Object,
206    /// Last applied `loadOp` (as a `&'static str`). Used to detect
207    /// op changes that invalidate the descriptor.
208    pub(crate) last_load_op: Option<&'static str>,
209    /// Last applied `storeOp` (as a `&'static str`). Used to detect
210    /// op changes that invalidate the descriptor.
211    pub(crate) last_store_op: Option<&'static str>,
212    /// Whether the last applied descriptor had a depth-stencil
213    /// attachment (`true`) or not (`false`). Used to detect shape
214    /// changes that invalidate the descriptor.
215    pub(crate) last_has_depth: bool,
216    /// Whether the last applied descriptor had a `resolveTarget`
217    /// (`true`, MSAA path) or not (`false`). Used to detect shape
218    /// changes that invalidate the descriptor, so a stale
219    /// `resolveTarget` never survives an MSAA -> non-MSAA switch.
220    pub(crate) last_has_resolve: bool,
221}
222
223/// Interior-mutable slot for the renderer's pending error-scope value.
224///
225/// This is the `euv-engine` analog of euv-core's `HandlerRegistryCell`
226/// (`core/src/renderer/registry/struct.rs:62`): a single-element
227/// `Sync` wrapper that holds an `Option<JsValue>` behind an
228/// `UnsafeCell`.
229///
230/// # Why this type exists
231///
232/// `WebGpuRenderer::pending_error` needs interior mutability
233/// because:
234///
235/// 1. `pop_error_sync` takes `&self` (the WebGPU hot path cannot
236///    be `async`), but the spawned `wasm_bindgen_futures::spawn_local`
237///    future must mutate the slot to store the resolved
238///    `Promise<GPUError?>` value.
239/// 2. `take_last_error` also takes `&self` and drains the slot
240///    on the next render tick.
241///
242/// The first implementation used `Rc<RefCell<Option<JsValue>>>`,
243/// which works but pays for:
244///
245/// - a `RefCell::borrow_mut` runtime borrow check on every
246///   write (the panic path is unreachable in practice — only
247///   the spawn_local future and `take_last_error` ever touch
248///   the slot, and they never overlap because the future is
249///   a microtask drained before the next render tick).
250/// - a heap allocation for the `RefCell`'s borrow state.
251///
252/// The newtype keeps the interior-mutability primitive (`Rc`),
253/// because the spawn_local future needs its own owning handle,
254/// but swaps the inner cell from `RefCell` to `UnsafeCell`:
255///
256/// - zero runtime borrow check (the WASM single-threaded
257///   scheduler makes the borrow impossible to violate).
258/// - zero allocation (the cell is just a `*mut Option<JsValue>`
259///   sitting inside the `Rc`-managed box).
260///
261/// # Sync safety
262///
263/// `PendingErrorCell` is **not** `Sync` by default (`UnsafeCell`
264/// explicitly opts out). We hand-implement `Sync` for it because
265/// the renderer is only ever used in the WASM single-threaded
266/// runtime; the `Rc` ensures the same instance is never shared
267/// across threads (it is not `Send`/`Sync` either), and the
268/// WASM main thread is the only place that ever touches the
269/// slot. This matches euv-core's pattern
270/// (`unsafe impl Sync for HandlerRegistryCell {}`).
271///
272/// If the engine is ever compiled for a multi-threaded target
273/// (native, `wasm-bindgen-rayon`), this `unsafe impl Sync` is
274/// unsound and must be removed.
275pub struct PendingErrorCell(
276    /// Interior-mutable storage for the optional `JsValue`.
277    ///
278    /// Marked `pub(crate)` (not just `pub`) because the field is
279    /// only meant to be touched from inside the renderer module —
280    /// specifically from the `impl PendingErrorCell` block in
281    /// `impl.rs`. The struct itself stays `pub` so external code
282    /// can name the type, but the raw `UnsafeCell` is an
283    /// implementation detail.
284    pub(crate) UnsafeCell<Option<JsValue>>,
285);