Skip to main content

euv_engine/renderer/
impl.rs

1use super::*;
2
3/// Implements camera transformation methods for `Camera2D`.
4impl Camera2D {
5    /// Creates a new camera centered at the origin with default zoom and no rotation.
6    ///
7    /// # Arguments
8    ///
9    /// - `f64` - The viewport width in pixels.
10    /// - `f64` - The viewport height in pixels.
11    ///
12    /// # Returns
13    ///
14    /// - `Camera2D` - The new camera.
15    pub fn create(viewport_width: f64, viewport_height: f64) -> Camera2D {
16        Camera2D::new(
17            Vector2D::zero(),
18            RENDERER_DEFAULT_CAMERA_ZOOM,
19            RENDERER_DEFAULT_CAMERA_ROTATION,
20            viewport_width,
21            viewport_height,
22        )
23    }
24
25    /// Converts a world-space point to screen-space coordinates.
26    ///
27    /// # Arguments
28    ///
29    /// - `Vector2D` - The world-space point.
30    ///
31    /// # Returns
32    ///
33    /// - `Vector2D` - The screen-space point.
34    pub fn world_to_screen(&self, world: Vector2D) -> Vector2D {
35        let relative: Vector2D = world - self.get_position();
36        let rotated: Vector2D = relative.rotated(-self.get_rotation());
37        Vector2D::new(
38            rotated.get_x() * self.get_zoom() + self.get_viewport_width() * 0.5,
39            rotated.get_y() * self.get_zoom() + self.get_viewport_height() * 0.5,
40        )
41    }
42
43    /// Converts a screen-space point to world-space coordinates.
44    ///
45    /// # Arguments
46    ///
47    /// - `Vector2D` - The screen-space point.
48    ///
49    /// # Returns
50    ///
51    /// - `Vector2D` - The world-space point.
52    pub fn screen_to_world(&self, screen: Vector2D) -> Vector2D {
53        let relative: Vector2D = Vector2D::new(
54            (screen.get_x() - self.get_viewport_width() * 0.5) / self.get_zoom(),
55            (screen.get_y() - self.get_viewport_height() * 0.5) / self.get_zoom(),
56        );
57        let rotated: Vector2D = relative.rotated(self.get_rotation());
58        rotated + self.get_position()
59    }
60
61    /// Moves the camera position by the given offset.
62    ///
63    /// # Arguments
64    ///
65    /// - `Vector2D` - The translation offset in world space.
66    pub fn translate(&mut self, offset: Vector2D) {
67        self.set_position(self.get_position() + offset);
68    }
69
70    /// Adjusts the zoom by the given factor, clamped to a minimum of `EPSILON`.
71    ///
72    /// # Arguments
73    ///
74    /// - `f64` - The zoom multiplier.
75    pub fn zoom_by(&mut self, factor: f64) {
76        self.set_zoom((self.get_zoom() * factor).max(EPSILON));
77    }
78}
79
80/// Implements `Default` for `Camera2D` as a camera at the origin with 800x600 viewport.
81impl Default for Camera2D {
82    /// Constructs a default [`Camera2D`] value.
83    ///
84    /// # Returns
85    ///
86    /// - `Camera2D` - A default-constructed instance with the documented initial state.
87    fn default() -> Camera2D {
88        Camera2D::create(800.0, 600.0)
89    }
90}
91
92/// Implements static font and color utility methods for `CanvasRenderer`.
93impl CanvasRenderer {
94    /// Builds a CSS font string from font size and family.
95    ///
96    /// # Arguments
97    ///
98    /// - `f64` - The font size in pixels.
99    /// - `F: AsRef<str>` - The font family name.
100    ///
101    /// # Returns
102    ///
103    /// - `String` - The CSS font string (e.g., `"16px sans-serif"`).
104    pub fn font<F>(size: f64, family: F) -> String
105    where
106        F: AsRef<str>,
107    {
108        let family: &str = family.as_ref();
109        format!("{size}px {family}")
110    }
111
112    /// Creates a default font string using the default font size and family.
113    ///
114    /// # Returns
115    ///
116    /// - `String` - The default CSS font string.
117    pub fn default_font() -> String {
118        Self::font(RENDERER_DEFAULT_FONT_SIZE, RENDERER_DEFAULT_FONT_FAMILY)
119    }
120
121    /// Enables high-quality anti-aliasing on an arbitrary canvas 2D context.
122    ///
123    /// Applies the `High` rendering quality preset via `apply_quality`,
124    /// which sets `imageSmoothingEnabled`, `imageSmoothingQuality = "high"`,
125    /// and `textRendering = "geometricPrecision"` on the given context.
126    ///
127    /// Use this static helper when you manage your own `CanvasRenderingContext2d`
128    /// and don't hold a `CanvasRenderer` instance. For instances, call
129    /// `renderer.enable_smoothing()` instead.
130    ///
131    /// # Arguments
132    ///
133    /// - `&CanvasRenderingContext2d` - The canvas context to configure.
134    pub fn enable_smoothing_on(context: &CanvasRenderingContext2d) {
135        Self::apply_quality(context, RenderQuality::High);
136    }
137
138    /// Detects the host device pixel ratio (HiDPI scale factor) via reflection.
139    ///
140    /// Reads `window.devicePixelRatio` using `Reflect::get` because the
141    /// `web-sys` `Window` features currently in use do not expose a native
142    /// getter for this property. Falls back to
143    /// `RENDERER_DEFAULT_DEVICE_PIXEL_RATIO` (1.0) when the global window or
144    /// the value is missing, not a finite number, or below 1.0.
145    ///
146    /// # Returns
147    ///
148    /// - `f64` - The detected device pixel ratio (clamped to `>= 1.0`).
149    pub fn detect_dpr() -> f64 {
150        let Some(window_value) = window() else {
151            return RENDERER_DEFAULT_DEVICE_PIXEL_RATIO;
152        };
153        let raw: Option<f64> = Reflect::get(
154            window_value.as_ref(),
155            &JsValue::from_str(RENDERER_PROPERTY_DEVICE_PIXEL_RATIO),
156        )
157        .ok()
158        .and_then(|value: JsValue| value.as_f64());
159        raw.filter(|value: &f64| value.is_finite() && *value >= 1.0)
160            .unwrap_or(RENDERER_DEFAULT_DEVICE_PIXEL_RATIO)
161    }
162
163    /// Applies the given `RenderQuality` preset to an arbitrary canvas context.
164    ///
165    /// Sets `imageSmoothingEnabled`, `imageSmoothingQuality`, and
166    /// `textRendering` according to the supplied quality. `Low` disables
167    /// smoothing (intended for use with CSS `image-rendering: pixelated`),
168    /// `Medium` and `High` enable it with the matching quality level.
169    ///
170    /// # Arguments
171    ///
172    /// - `&CanvasRenderingContext2d` - The target context.
173    /// - `RenderQuality` - The quality preset to apply.
174    pub(crate) fn apply_quality(context: &CanvasRenderingContext2d, quality: RenderQuality) {
175        let smoothing_enabled: bool = !matches!(quality, RenderQuality::Low);
176        context.set_image_smoothing_enabled(smoothing_enabled);
177        let quality_value: &str = match quality {
178            RenderQuality::Low => RENDERER_IMAGE_SMOOTHING_QUALITY_LOW,
179            RenderQuality::Medium => RENDERER_IMAGE_SMOOTHING_QUALITY_MEDIUM,
180            RenderQuality::High => RENDERER_IMAGE_SMOOTHING_QUALITY_HIGH,
181        };
182        let _: Result<bool, JsValue> = Reflect::set(
183            context,
184            &JsValue::from_str(RENDERER_PROPERTY_IMAGE_SMOOTHING_QUALITY),
185            &JsValue::from_str(quality_value),
186        );
187        let _: Result<bool, JsValue> = Reflect::set(
188            context,
189            &JsValue::from_str(RENDERER_PROPERTY_TEXT_RENDERING),
190            &JsValue::from_str(RENDERER_TEXT_RENDERING_GEOMETRIC_PRECISION),
191        );
192    }
193}
194
195/// Implements static CSS conversion for `Color`.
196impl Color {
197    /// Converts a `Color` to a CSS `rgba()` string suitable for canvas fill or stroke styles.
198    ///
199    /// # Arguments
200    ///
201    /// - `&Color` - The color to convert.
202    ///
203    /// # Returns
204    ///
205    /// - `String` - The CSS `rgba()` color string.
206    pub fn to_css(color: &Color) -> String {
207        color.to_css_rgba()
208    }
209}
210
211/// Implements drawing and camera management methods for `CanvasRenderer`.
212/// Implements recording and replay for `DrawList`.
213impl DrawList {
214    /// Creates an empty draw list.
215    ///
216    /// # Returns
217    ///
218    /// - `DrawList` - The new empty draw list.
219    pub fn create() -> DrawList {
220        DrawList::new(Vec::new())
221    }
222
223    /// Returns whether the list contains no commands.
224    ///
225    /// # Returns
226    ///
227    /// - `bool` - `true` if there are no recorded commands.
228    pub fn is_empty(&self) -> bool {
229        self.get_commands().is_empty()
230    }
231
232    /// Returns the number of recorded commands.
233    ///
234    /// # Returns
235    ///
236    /// - `usize` - The command count.
237    pub fn len(&self) -> usize {
238        self.get_commands().len()
239    }
240
241    /// Returns the recorded commands as a slice for replay iteration.
242    ///
243    /// # Returns
244    ///
245    /// - `&[DrawCommand]` - The commands in the order they were recorded.
246    pub fn commands(&self) -> &[DrawCommand] {
247        self.get_commands().as_slice()
248    }
249
250    /// Removes all recorded commands, keeping the allocated capacity for reuse
251    /// on the next frame.
252    pub fn clear(&mut self) {
253        self.get_mut_commands().clear();
254    }
255
256    /// Records a fill-rectangle command.
257    ///
258    /// # Arguments
259    ///
260    /// - `Vector2D` - 2D vector (`Vector2D`).
261    /// - `f64` - A 64-bit float (`f64`).
262    /// - `f64` - A 64-bit float (`f64`).
263    /// - `Color` - A `Color` parameter.
264    pub fn fill_rect(&mut self, position: Vector2D, width: f64, height: f64, color: Color) {
265        self.get_mut_commands().push(DrawCommand::FillRect {
266            position,
267            width,
268            height,
269            color,
270        });
271    }
272
273    /// Records a stroke-rectangle command.
274    ///
275    /// # Arguments
276    ///
277    /// - `Vector2D` - 2D vector (`Vector2D`).
278    /// - `f64` - A 64-bit float (`f64`).
279    /// - `f64` - A 64-bit float (`f64`).
280    /// - `Color` - A `Color` parameter.
281    /// - `f64` - A 64-bit float (`f64`).
282    pub fn stroke_rect(
283        &mut self,
284        position: Vector2D,
285        width: f64,
286        height: f64,
287        color: Color,
288        line_width: f64,
289    ) {
290        self.get_mut_commands().push(DrawCommand::StrokeRect {
291            position,
292            width,
293            height,
294            color,
295            line_width,
296        });
297    }
298
299    /// Records a fill-circle command.
300    ///
301    /// # Arguments
302    ///
303    /// - `Vector2D` - 2D vector (`Vector2D`).
304    /// - `f64` - A 64-bit float (`f64`).
305    /// - `Color` - A `Color` parameter.
306    pub fn fill_circle(&mut self, center: Vector2D, radius: f64, color: Color) {
307        self.get_mut_commands().push(DrawCommand::FillCircle {
308            center,
309            radius,
310            color,
311        });
312    }
313
314    /// Records a stroke-circle command.
315    ///
316    /// # Arguments
317    ///
318    /// - `Vector2D` - 2D vector (`Vector2D`).
319    /// - `f64` - A 64-bit float (`f64`).
320    /// - `Color` - A `Color` parameter.
321    /// - `f64` - A 64-bit float (`f64`).
322    pub fn stroke_circle(&mut self, center: Vector2D, radius: f64, color: Color, line_width: f64) {
323        self.get_mut_commands().push(DrawCommand::StrokeCircle {
324            center,
325            radius,
326            color,
327            line_width,
328        });
329    }
330
331    /// Records a line-segment command.
332    ///
333    /// # Arguments
334    ///
335    /// - `Vector2D` - 2D vector (`Vector2D`).
336    /// - `Vector2D` - 2D vector (`Vector2D`).
337    /// - `Color` - A `Color` parameter.
338    /// - `f64` - A 64-bit float (`f64`).
339    pub fn draw_line(&mut self, start: Vector2D, end: Vector2D, color: Color, line_width: f64) {
340        self.get_mut_commands().push(DrawCommand::Line {
341            start,
342            end,
343            color,
344            line_width,
345        });
346    }
347
348    /// Records a fill-text command.
349    ///
350    /// # Arguments
351    ///
352    /// - `T: AsRef<str>` - A generic type parameter.
353    /// - `Vector2D` - 2D vector (`Vector2D`).
354    /// - `Color` - A `Color` parameter.
355    /// - `F: AsRef<str>` - A generic type parameter.
356    pub fn fill_text<T, F>(&mut self, text: T, position: Vector2D, color: Color, font: F)
357    where
358        T: AsRef<str>,
359        F: AsRef<str>,
360    {
361        self.get_mut_commands().push(DrawCommand::FillText {
362            text: text.as_ref().to_string(),
363            position,
364            color,
365            font: font.as_ref().to_string(),
366        });
367    }
368
369    /// Records a transformed sprite draw command.
370    ///
371    /// # Arguments
372    ///
373    /// - `&HtmlImageElement` - Shared reference to a `HtmlImageElement`.
374    /// - `Rect` - A `Rect` parameter.
375    /// - `Transform2D` - A `Transform2D` parameter.
376    pub fn draw_sprite(&mut self, image: &HtmlImageElement, source: Rect, transform: Transform2D) {
377        self.get_mut_commands().push(DrawCommand::DrawSprite {
378            image: image.clone(),
379            source,
380            transform,
381        });
382    }
383
384    /// Records an image sub-region draw command (no rotation).
385    ///
386    /// # Arguments
387    ///
388    /// - `&HtmlImageElement` - Shared reference to a `HtmlImageElement`.
389    /// - `Rect` - A `Rect` parameter.
390    /// - `Vector2D` - 2D vector (`Vector2D`).
391    /// - `f64` - A 64-bit float (`f64`).
392    /// - `f64` - A 64-bit float (`f64`).
393    pub fn draw_image_rect(
394        &mut self,
395        image: &HtmlImageElement,
396        source: Rect,
397        dest_position: Vector2D,
398        dest_width: f64,
399        dest_height: f64,
400    ) {
401        self.get_mut_commands().push(DrawCommand::DrawImageRect {
402            image: image.clone(),
403            source,
404            dest_position,
405            dest_width,
406            dest_height,
407        });
408    }
409
410    /// Records a global-alpha state change.
411    ///
412    /// # Arguments
413    ///
414    /// - `f64` - A 64-bit float (`f64`).
415    pub fn set_global_alpha(&mut self, alpha: f64) {
416        self.get_mut_commands()
417            .push(DrawCommand::SetGlobalAlpha { alpha });
418    }
419
420    /// Records a blend-mode state change.
421    ///
422    /// # Arguments
423    ///
424    /// - `BlendMode` - A `BlendMode` parameter.
425    pub fn set_blend_mode(&mut self, mode: BlendMode) {
426        self.get_mut_commands()
427            .push(DrawCommand::SetBlendMode { mode });
428    }
429}
430
431/// Inherent implementation of [`CanvasRenderer`].
432impl CanvasRenderer {
433    /// Creates a new renderer from a canvas element selector and viewport dimensions.
434    ///
435    /// # Arguments
436    ///
437    /// - `&str` - The CSS selector for the canvas element.
438    /// - `f64` - The viewport width.
439    /// - `f64` - The viewport height.
440    ///
441    /// # Returns
442    ///
443    /// - `Option<CanvasRenderer>` - The renderer, or `None` if the canvas was not found.
444    pub fn from_selector<S>(
445        canvas_selector: S,
446        viewport_width: f64,
447        viewport_height: f64,
448    ) -> Option<CanvasRenderer>
449    where
450        S: AsRef<str>,
451    {
452        let window_value: Window = window()?;
453        let document_value: Document = window_value.document()?;
454        let element: Element = document_value
455            .query_selector(canvas_selector.as_ref())
456            .ok()
457            .flatten()?;
458        let canvas_element: HtmlCanvasElement = element.unchecked_into();
459        let context_object: Object = canvas_element
460            .get_context(RENDERER_CONTEXT_TYPE_2D)
461            .ok()
462            .flatten()?;
463        let context: CanvasRenderingContext2d = context_object.unchecked_into();
464        let renderer: CanvasRenderer = CanvasRenderer::new(
465            context,
466            Camera2D::create(viewport_width, viewport_height),
467            RenderQuality::default(),
468        );
469        renderer.enable_smoothing();
470        Some(renderer)
471    }
472
473    /// Enables high-quality anti-aliasing on the canvas context by setting
474    /// `imageSmoothingEnabled` to `true` and `imageSmoothingQuality` to `"high"`.
475    ///
476    /// Applies the active `quality` preset via the shared `apply_quality`
477    /// helper so that all smoothing-related settings are kept in sync.
478    pub fn enable_smoothing(&self) {
479        Self::apply_quality(self.get_context(), self.get_quality());
480    }
481
482    /// Clears the entire canvas viewport.
483    pub fn clear(&self) {
484        self.get_context().clear_rect(
485            0.0,
486            0.0,
487            self.get_camera().get_viewport_width(),
488            self.get_camera().get_viewport_height(),
489        );
490    }
491
492    /// Clears the canvas and fills it with the given CSS color string.
493    ///
494    /// # Arguments
495    ///
496    /// - `C: AsRef<str>` - The CSS color string (e.g., `"#000000"`).
497    pub fn clear_color<C>(&self, color: C)
498    where
499        C: AsRef<str>,
500    {
501        self.get_context().set_fill_style_str(color.as_ref());
502        self.get_context().fill_rect(
503            0.0,
504            0.0,
505            self.get_camera().get_viewport_width(),
506            self.get_camera().get_viewport_height(),
507        );
508    }
509
510    /// Saves the current canvas state (transform, styles) onto the state stack.
511    pub fn save(&self) {
512        self.get_context().save();
513    }
514
515    /// Restores the most recently saved canvas state.
516    pub fn restore(&self) {
517        self.get_context().restore();
518    }
519
520    /// Replays a recorded `DrawList` onto this renderer's canvas.
521    ///
522    /// Convenience wrapper around `replay_context` using this renderer's context.
523    ///
524    /// # Arguments
525    ///
526    /// - `&DrawList` - The recorded commands to replay.
527    pub fn replay(&self, list: &DrawList) {
528        Self::replay_context(self.get_context(), list);
529    }
530
531    /// Replays a recorded `DrawList` onto an arbitrary canvas 2D context in a
532    /// single batched pass.
533    ///
534    /// Consecutive same-style shapes are merged into one path (one `begin_path`
535    /// plus one `fill`/`stroke` per style run), fill/stroke colors and line
536    /// widths are only re-applied when they change, and sprites are drawn with a
537    /// single `set_transform` rather than a save/restore pair. This collapses
538    /// the per-shape canvas state churn of immediate-mode drawing.
539    ///
540    /// The canvas transform and global alpha are reset to identity / 1.0 when
541    /// replay finishes, so callers can sandwich the call between
542    /// `save()`/`apply_camera()` and `restore()` without leaking state.
543    ///
544    /// # Arguments
545    ///
546    /// - `&CanvasRenderingContext2d` - The target canvas 2D context.
547    /// - `&DrawList` - The recorded commands to replay.
548    pub fn replay_context(context: &CanvasRenderingContext2d, list: &DrawList) {
549        let mut current_fill: Option<Color> = None;
550        let mut current_stroke: Option<Color> = None;
551        let mut current_line_width: f64 = f64::NAN;
552        // Whether a same-style path run is currently open.
553        let mut run_open: bool = false;
554        let mut run_is_fill: bool = true;
555        let mut run_key: Option<(u8, Color, f64)> = None;
556
557        // Returns the style key for a path-batchable command, or `None` for
558        // commands that break a run (sprites, images, text, state changes).
559        /// Computes the batching key for a [`DrawCommand`].
560        ///
561        /// # Arguments
562        ///
563        /// - `&DrawCommand` - Shared reference to a `DrawCommand`.
564        ///
565        /// # Returns
566        ///
567        /// - `Option<(u8, Color, f64)>` - `Some(...)` on success, `None` otherwise.
568        fn batch_key(command: &DrawCommand) -> Option<(u8, Color, f64)> {
569            match command {
570                DrawCommand::FillRect { color, .. } | DrawCommand::FillCircle { color, .. } => {
571                    Some((0, *color, 0.0))
572                }
573                DrawCommand::StrokeRect {
574                    color, line_width, ..
575                }
576                | DrawCommand::StrokeCircle {
577                    color, line_width, ..
578                }
579                | DrawCommand::Line {
580                    color, line_width, ..
581                } => Some((1, *color, *line_width)),
582                _ => None,
583            }
584        }
585
586        // Emits a single path-batchable command's geometry into the open path.
587        /// Emits the geometry for the supplied [`DrawCommand`] into the canvas context.
588        ///
589        /// # Arguments
590        ///
591        /// - `&CanvasRenderingContext2d` - Shared reference to a `CanvasRenderingContext2d`.
592        /// - `&DrawCommand` - Shared reference to a `DrawCommand`.
593        fn emit_geometry(context: &CanvasRenderingContext2d, command: &DrawCommand) {
594            match command {
595                DrawCommand::FillRect {
596                    position,
597                    width,
598                    height,
599                    ..
600                }
601                | DrawCommand::StrokeRect {
602                    position,
603                    width,
604                    height,
605                    ..
606                } => {
607                    context.rect(position.get_x(), position.get_y(), *width, *height);
608                }
609                DrawCommand::FillCircle { center, radius, .. }
610                | DrawCommand::StrokeCircle { center, radius, .. } => {
611                    context.move_to(center.get_x() + radius, center.get_y());
612                    let _: Result<(), JsValue> =
613                        context.arc(center.get_x(), center.get_y(), *radius, 0.0, TWO_PI);
614                }
615                DrawCommand::Line { start, end, .. } => {
616                    context.move_to(start.get_x(), start.get_y());
617                    context.line_to(end.get_x(), end.get_y());
618                }
619                _ => {}
620            }
621        }
622
623        for command in list.commands() {
624            let key: Option<(u8, Color, f64)> = batch_key(command);
625            // Close the open run if this command breaks it or starts a new style.
626            if run_open && key != run_key {
627                if run_is_fill {
628                    context.fill();
629                } else {
630                    context.stroke();
631                }
632                run_open = false;
633            }
634            if let Some(current_key) = key {
635                // Begin (or continue) a same-style path run.
636                if !run_open {
637                    let (kind, color, line_width) = current_key;
638                    if kind == 0 {
639                        if current_fill != Some(color) {
640                            context.set_fill_style_str(&Color::to_css(&color));
641                            current_fill = Some(color);
642                        }
643                        run_is_fill = true;
644                    } else {
645                        if current_stroke != Some(color) {
646                            context.set_stroke_style_str(&Color::to_css(&color));
647                            current_stroke = Some(color);
648                        }
649                        if current_line_width != line_width {
650                            context.set_line_width(line_width);
651                            current_line_width = line_width;
652                        }
653                        run_is_fill = false;
654                    }
655                    context.begin_path();
656                    run_open = true;
657                    run_key = Some(current_key);
658                }
659                emit_geometry(context, command);
660                continue;
661            }
662            // Non-batchable command: draw it immediately.
663            match command {
664                DrawCommand::FillText {
665                    text,
666                    position,
667                    color,
668                    font,
669                } => {
670                    if current_fill != Some(*color) {
671                        context.set_fill_style_str(&Color::to_css(color));
672                        current_fill = Some(*color);
673                    }
674                    context.set_font(font);
675                    let _: Result<(), JsValue> =
676                        context.fill_text(text, position.get_x(), position.get_y());
677                }
678                DrawCommand::DrawSprite {
679                    image,
680                    source,
681                    transform,
682                } => {
683                    draw_sprite_immediate(context, image, source, transform);
684                }
685                DrawCommand::DrawImageRect {
686                    image,
687                    source,
688                    dest_position,
689                    dest_width,
690                    dest_height,
691                } => {
692                    let _: Result<(), JsValue> = context
693                        .draw_image_with_html_image_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(
694                            image,
695                            source.get_x(),
696                            source.get_y(),
697                            source.get_width(),
698                            source.get_height(),
699                            dest_position.get_x(),
700                            dest_position.get_y(),
701                            *dest_width,
702                            *dest_height,
703                        );
704                }
705                DrawCommand::SetGlobalAlpha { alpha } => {
706                    context.set_global_alpha(Numeric::clamp(*alpha, 0.0, 1.0));
707                }
708                DrawCommand::SetBlendMode { mode } => {
709                    let _: Result<(), JsValue> =
710                        context.set_global_composite_operation(mode.to_css());
711                }
712                _ => {}
713            }
714        }
715        // Flush any trailing open run.
716        if run_open {
717            if run_is_fill {
718                context.fill();
719            } else {
720                context.stroke();
721            }
722        }
723        let _: Result<(), JsValue> = context.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
724        context.set_global_alpha(1.0);
725    }
726
727    /// Applies the camera transform to the canvas context.
728    ///
729    /// Translates to the screen center, applies zoom and rotation,
730    /// then offsets by the negative camera position.
731    pub fn apply_camera(&self) {
732        let camera: Camera2D = self.get_camera();
733        let _: Result<(), JsValue> = self.get_context().translate(
734            camera.get_viewport_width() * 0.5,
735            camera.get_viewport_height() * 0.5,
736        );
737        let _: Result<(), JsValue> = self
738            .get_context()
739            .scale(camera.get_zoom(), camera.get_zoom());
740        let _: Result<(), JsValue> = self.get_context().rotate(camera.get_rotation());
741        let _: Result<(), JsValue> = self.get_context().translate(
742            -camera.get_position().get_x(),
743            -camera.get_position().get_y(),
744        );
745    }
746
747    /// Sets the fill color for subsequent fill operations.
748    ///
749    /// # Arguments
750    ///
751    /// - `C: AsRef<str>` - The CSS color string.
752    pub fn set_fill_color<C>(&self, color: C)
753    where
754        C: AsRef<str>,
755    {
756        self.get_context().set_fill_style_str(color.as_ref());
757    }
758
759    /// Sets the stroke color for subsequent stroke operations.
760    ///
761    /// # Arguments
762    ///
763    /// - `C: AsRef<str>` - The CSS color string.
764    pub fn set_stroke_color<C>(&self, color: C)
765    where
766        C: AsRef<str>,
767    {
768        self.get_context().set_stroke_style_str(color.as_ref());
769    }
770
771    /// Sets the line width for subsequent stroke operations.
772    ///
773    /// # Arguments
774    ///
775    /// - `f64` - The line width in pixels.
776    pub fn set_line_width(&self, width: f64) {
777        self.get_context().set_line_width(width);
778    }
779
780    /// Sets the global alpha (opacity) for all subsequent drawing operations.
781    ///
782    /// # Arguments
783    ///
784    /// - `f64` - The alpha value in the range 0.0 to 1.0.
785    pub fn set_global_alpha(&self, alpha: f64) {
786        self.get_context()
787            .set_global_alpha(Numeric::clamp(alpha, 0.0, 1.0));
788    }
789
790    /// Fills a rectangle at the given world-space position and dimensions.
791    ///
792    /// # Arguments
793    ///
794    /// - `Vector2D` - The top-left position in world space.
795    /// - `f64` - The width.
796    /// - `f64` - The height.
797    pub fn fill_rect(&self, position: Vector2D, width: f64, height: f64) {
798        self.get_context()
799            .fill_rect(position.get_x(), position.get_y(), width, height);
800    }
801
802    /// Strokes the outline of a rectangle at the given world-space position and dimensions.
803    ///
804    /// # Arguments
805    ///
806    /// - `Vector2D` - The top-left position in world space.
807    /// - `f64` - The width.
808    /// - `f64` - The height.
809    pub fn stroke_rect(&self, position: Vector2D, width: f64, height: f64) {
810        self.get_context()
811            .stroke_rect(position.get_x(), position.get_y(), width, height);
812    }
813
814    /// Fills a circle at the given world-space center with the specified radius.
815    ///
816    /// # Arguments
817    ///
818    /// - `Vector2D` - The center in world space.
819    /// - `f64` - The radius.
820    pub fn fill_circle(&self, center: Vector2D, radius: f64) {
821        self.get_context().begin_path();
822        self.get_context()
823            .arc(center.get_x(), center.get_y(), radius, 0.0, TWO_PI)
824            .unwrap_or(());
825        self.get_context().fill();
826    }
827
828    /// Strokes the outline of a circle at the given world-space center.
829    ///
830    /// # Arguments
831    ///
832    /// - `Vector2D` - The center in world space.
833    /// - `f64` - The radius.
834    pub fn stroke_circle(&self, center: Vector2D, radius: f64) {
835        self.get_context().begin_path();
836        self.get_context()
837            .arc(center.get_x(), center.get_y(), radius, 0.0, TWO_PI)
838            .unwrap_or(());
839        self.get_context().stroke();
840    }
841
842    /// Draws a line segment between two world-space points.
843    ///
844    /// # Arguments
845    ///
846    /// - `Vector2D` - The start point.
847    /// - `Vector2D` - The end point.
848    pub fn draw_line(&self, start: Vector2D, end: Vector2D) {
849        self.get_context().begin_path();
850        self.get_context().move_to(start.get_x(), start.get_y());
851        self.get_context().line_to(end.get_x(), end.get_y());
852        self.get_context().stroke();
853    }
854
855    /// Fills text at the given world-space position.
856    ///
857    /// # Arguments
858    ///
859    /// - `T: AsRef<str>` - The text to draw.
860    /// - `Vector2D` - The position in world space.
861    pub fn fill_text<T>(&self, text: T, position: Vector2D)
862    where
863        T: AsRef<str>,
864    {
865        self.get_context()
866            .fill_text(text.as_ref(), position.get_x(), position.get_y())
867            .unwrap_or(());
868    }
869
870    /// Sets the font for subsequent text rendering.
871    ///
872    /// # Arguments
873    ///
874    /// - `F: AsRef<str>` - The CSS font string (e.g., `"16px sans-serif"`).
875    pub fn set_font<F>(&self, font: F)
876    where
877        F: AsRef<str>,
878    {
879        self.get_context().set_font(font.as_ref());
880    }
881
882    /// Draws an image element at the given world-space position and dimensions.
883    ///
884    /// # Arguments
885    ///
886    /// - `&HtmlImageElement` - The image element to draw.
887    /// - `Vector2D` - The top-left position in world space.
888    /// - `f64` - The destination width.
889    /// - `f64` - The destination height.
890    pub fn draw_image(
891        &self,
892        image: &HtmlImageElement,
893        position: Vector2D,
894        width: f64,
895        height: f64,
896    ) {
897        let _: Result<(), JsValue> = self
898            .get_context()
899            .draw_image_with_html_image_element_and_dw_and_dh(
900                image,
901                position.get_x(),
902                position.get_y(),
903                width,
904                height,
905            );
906    }
907
908    /// Draws a sub-region of an image element at the given world-space position.
909    ///
910    /// # Arguments
911    ///
912    /// - `&HtmlImageElement` - The image element to draw.
913    /// - `Rect` - The source rectangle within the image.
914    /// - `Vector2D` - The destination top-left position in world space.
915    /// - `f64` - The destination width.
916    /// - `f64` - The destination height.
917    pub fn draw_image_rect(
918        &self,
919        image: &HtmlImageElement,
920        source: Rect,
921        dest_position: Vector2D,
922        dest_width: f64,
923        dest_height: f64,
924    ) {
925        let _: Result<(), JsValue> = self
926            .get_context()
927            .draw_image_with_html_image_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(
928                image,
929                source.get_x(),
930                source.get_y(),
931                source.get_width(),
932                source.get_height(),
933                dest_position.get_x(),
934                dest_position.get_y(),
935                dest_width,
936                dest_height,
937            );
938    }
939}
940
941/// Implements 3D camera transformation and projection methods for `Camera3D`.
942impl Camera3D {
943    /// Creates a new 3D camera at the given position looking at the target.
944    ///
945    /// # Arguments
946    ///
947    /// - `Vector3D` - The eye position.
948    /// - `Vector3D` - The target position to look at.
949    /// - `f64` - The viewport width.
950    /// - `f64` - The viewport height.
951    ///
952    /// # Returns
953    ///
954    /// - `Camera3D` - The new camera.
955    pub fn create(
956        position: Vector3D,
957        target: Vector3D,
958        viewport_width: f64,
959        viewport_height: f64,
960    ) -> Camera3D {
961        let mut camera: Camera3D = Camera3D::new(position, target, viewport_width, viewport_height);
962        camera.set_up(Vector3D::up());
963        camera.set_fov(DEFAULT_CAMERA_FOV);
964        camera.set_near(DEFAULT_CAMERA_NEAR);
965        camera.set_far(DEFAULT_CAMERA_FAR);
966        camera
967    }
968
969    /// Returns the aspect ratio (width / height).
970    ///
971    /// # Returns
972    ///
973    /// - `f64` - The aspect ratio.
974    pub fn aspect(&self) -> f64 {
975        if self.get_viewport_height() < EPSILON {
976            return 1.0;
977        }
978        self.get_viewport_width() / self.get_viewport_height()
979    }
980
981    /// Returns the forward direction (from position to target, normalized).
982    ///
983    /// # Returns
984    ///
985    /// - `Vector3D` - The forward direction.
986    pub fn forward(&self) -> Vector3D {
987        (self.get_target() - self.get_position()).normalized()
988    }
989
990    /// Returns the right direction (cross product of forward and up).
991    ///
992    /// # Returns
993    ///
994    /// - `Vector3D` - The right direction.
995    pub fn right(&self) -> Vector3D {
996        self.forward().cross(self.get_up()).normalized()
997    }
998
999    /// Returns the view matrix for this camera.
1000    ///
1001    /// # Returns
1002    ///
1003    /// - `Matrix4x4` - The view matrix.
1004    pub fn view_matrix(&self) -> Matrix4x4 {
1005        Matrix4x4::look_at(self.get_position(), self.get_target(), self.get_up())
1006    }
1007
1008    /// Returns the perspective projection matrix for this camera.
1009    ///
1010    /// # Returns
1011    ///
1012    /// - `Matrix4x4` - The projection matrix.
1013    pub fn projection_matrix(&self) -> Matrix4x4 {
1014        Matrix4x4::perspective(
1015            self.get_fov(),
1016            self.aspect(),
1017            self.get_near(),
1018            self.get_far(),
1019        )
1020    }
1021
1022    /// Returns the combined view-projection matrix.
1023    ///
1024    /// # Returns
1025    ///
1026    /// - `Matrix4x4` - The view-projection matrix.
1027    pub fn view_proj_matrix(&self) -> Matrix4x4 {
1028        self.projection_matrix().multiply(self.view_matrix())
1029    }
1030
1031    /// Converts a 3D world-space point to screen-space (NDC) coordinates.
1032    ///
1033    /// # Arguments
1034    ///
1035    /// - `Vector3D` - The world-space point.
1036    ///
1037    /// # Returns
1038    ///
1039    /// - `Vector3D` - The screen-space point where x and y are in [0, 1] and z is the depth.
1040    pub fn world_to_screen(&self, world: Vector3D) -> Vector3D {
1041        let clip: Vector3D = self.view_proj_matrix().transform_point(world);
1042        Vector3D::new(
1043            (clip.get_x() + 1.0) * 0.5 * self.get_viewport_width(),
1044            (1.0 - clip.get_y()) * 0.5 * self.get_viewport_height(),
1045            clip.get_z(),
1046        )
1047    }
1048
1049    /// Projects a world-space point and returns whether it is within the camera frustum.
1050    ///
1051    /// # Arguments
1052    ///
1053    /// - `Vector3D` - The world-space point.
1054    ///
1055    /// # Returns
1056    ///
1057    /// - `bool` - True if the point is within the frustum.
1058    pub fn in_frustum(&self, world: Vector3D) -> bool {
1059        let clip: Vector3D = self.view_proj_matrix().transform_point(world);
1060        clip.get_x() >= -1.0
1061            && clip.get_x() <= 1.0
1062            && clip.get_y() >= -1.0
1063            && clip.get_y() <= 1.0
1064            && clip.get_z() >= -1.0
1065            && clip.get_z() <= 1.0
1066    }
1067
1068    /// Moves the camera position by the given offset, keeping the target offset by the same amount.
1069    ///
1070    /// # Arguments
1071    ///
1072    /// - `Vector3D` - The translation offset.
1073    pub fn translate(&mut self, offset: Vector3D) {
1074        self.set_position(self.get_position() + offset);
1075        self.set_target(self.get_target() + offset);
1076    }
1077
1078    /// Moves the camera position towards the target by the given distance.
1079    ///
1080    /// # Arguments
1081    ///
1082    /// - `f64` - The distance to zoom in (positive) or out (negative).
1083    pub fn zoom(&mut self, distance: f64) {
1084        let direction: Vector3D = self.forward();
1085        self.set_position(self.get_position() + direction.scaled(distance));
1086    }
1087
1088    /// Orbits the camera around the target by the given yaw and pitch angles.
1089    ///
1090    /// # Arguments
1091    ///
1092    /// - `f64` - The yaw delta in radians (horizontal rotation).
1093    /// - `f64` - The pitch delta in radians (vertical rotation).
1094    pub fn orbit(&mut self, yaw_delta: f64, pitch_delta: f64) {
1095        let offset: Vector3D = self.get_position() - self.get_target();
1096        let current_distance: f64 = offset.magnitude();
1097        let current_yaw: f64 = offset.get_x().atan2(offset.get_z());
1098        let horizontal_dist: f64 =
1099            (offset.get_x() * offset.get_x() + offset.get_z() * offset.get_z()).sqrt();
1100        let current_pitch: f64 = (offset.get_y() / horizontal_dist.max(EPSILON)).asin();
1101        let new_yaw: f64 = current_yaw + yaw_delta;
1102        let new_pitch: f64 = Numeric::clamp(
1103            current_pitch + pitch_delta,
1104            -HALF_PI + EPSILON,
1105            HALF_PI - EPSILON,
1106        );
1107        let cos_pitch: f64 = new_pitch.cos();
1108        self.set_position(
1109            self.get_target()
1110                + Vector3D::new(
1111                    new_yaw.sin() * cos_pitch * current_distance,
1112                    new_pitch.sin() * current_distance,
1113                    new_yaw.cos() * cos_pitch * current_distance,
1114                ),
1115        );
1116    }
1117}
1118
1119/// Implements `Default` for `Camera3D` as a camera at (0, 0, 5) looking at the origin.
1120impl Default for Camera3D {
1121    /// Constructs a default [`Camera3D`] value.
1122    ///
1123    /// # Returns
1124    ///
1125    /// - `Camera3D` - A default-constructed instance with the documented initial state.
1126    fn default() -> Camera3D {
1127        Camera3D::create(Vector3D::new(0.0, 0.0, 5.0), Vector3D::zero(), 800.0, 600.0)
1128    }
1129}
1130
1131/// Implements construction, presentation, and anti-aliasing methods for `SsaaCanvas`.
1132impl SsaaCanvas {
1133    /// Creates an `SsaaCanvas` from a CSS selector using the default scale factor.
1134    ///
1135    /// # Arguments
1136    ///
1137    /// - `S: AsRef<str>` - The CSS selector for the display canvas element.
1138    /// - `f64` - The logical display width in CSS pixels.
1139    /// - `f64` - The logical display height in CSS pixels.
1140    ///
1141    /// # Returns
1142    ///
1143    /// - `Option<SsaaCanvas>` - The SSAA canvas, or `None` if the canvas was not found.
1144    pub fn from_selector<S>(canvas_selector: S, width: f64, height: f64) -> Option<SsaaCanvas>
1145    where
1146        S: AsRef<str>,
1147    {
1148        Self::from_selector_with_scale(
1149            canvas_selector,
1150            width,
1151            height,
1152            RENDERER_DEFAULT_SSAA_SCALE_FACTOR,
1153        )
1154    }
1155
1156    /// Creates an `SsaaCanvas` from a CSS selector with a custom SSAA scale factor.
1157    ///
1158    /// The offscreen canvas is created at `width * scale_factor` by `height * scale_factor`
1159    /// pixels, and its context is pre-scaled so that drawing code uses logical coordinates.
1160    ///
1161    /// # Arguments
1162    ///
1163    /// - `S: AsRef<str>` - The CSS selector for the display canvas element.
1164    /// - `f64` - The logical display width in CSS pixels.
1165    /// - `f64` - The logical display height in CSS pixels.
1166    /// - `f64` - The supersampling scale factor (e.g., 2.0 for 4x SSAA).
1167    ///
1168    /// # Returns
1169    ///
1170    /// - `Option<SsaaCanvas>` - The SSAA canvas, or `None` if the canvas was not found.
1171    pub fn from_selector_with_scale<S>(
1172        canvas_selector: S,
1173        width: f64,
1174        height: f64,
1175        scale_factor: f64,
1176    ) -> Option<SsaaCanvas>
1177    where
1178        S: AsRef<str>,
1179    {
1180        let window_value: Window = window()?;
1181        let document_value: Document = window_value.document()?;
1182        let element: Element = document_value
1183            .query_selector(canvas_selector.as_ref())
1184            .ok()
1185            .flatten()?;
1186        let display_canvas: HtmlCanvasElement = element.unchecked_into();
1187        let device_pixel_ratio: f64 = CanvasRenderer::detect_dpr();
1188        let physical_width: u32 = (width * device_pixel_ratio).round() as u32;
1189        let physical_height: u32 = (height * device_pixel_ratio).round() as u32;
1190        display_canvas.set_width(physical_width);
1191        display_canvas.set_height(physical_height);
1192        let display_context_object: Object = display_canvas
1193            .get_context(RENDERER_CONTEXT_TYPE_2D)
1194            .ok()
1195            .flatten()?;
1196        let display_context: CanvasRenderingContext2d = display_context_object.unchecked_into();
1197        let _: Result<(), JsValue> = display_context.scale(device_pixel_ratio, device_pixel_ratio);
1198        let offscreen_canvas: HtmlCanvasElement = document_value
1199            .create_element(RENDERER_ELEMENT_CANVAS)
1200            .ok()?
1201            .unchecked_into();
1202        let scaled_width: u32 = (width * scale_factor * device_pixel_ratio).round() as u32;
1203        let scaled_height: u32 = (height * scale_factor * device_pixel_ratio).round() as u32;
1204        offscreen_canvas.set_width(scaled_width);
1205        offscreen_canvas.set_height(scaled_height);
1206        let offscreen_context_object: Object = offscreen_canvas
1207            .get_context(RENDERER_CONTEXT_TYPE_2D)
1208            .ok()
1209            .flatten()?;
1210        let offscreen_context: CanvasRenderingContext2d = offscreen_context_object.unchecked_into();
1211        let _: Result<(), JsValue> = offscreen_context.scale(
1212            scale_factor * device_pixel_ratio,
1213            scale_factor * device_pixel_ratio,
1214        );
1215        let ssaa_canvas: SsaaCanvas = SsaaCanvas::new(
1216            display_canvas,
1217            display_context,
1218            offscreen_canvas,
1219            offscreen_context,
1220            scale_factor,
1221            width,
1222            height,
1223        );
1224        ssaa_canvas.enable_smoothing();
1225        Some(ssaa_canvas)
1226    }
1227
1228    /// Presents the offscreen buffer onto the display canvas with high-quality downscaling.
1229    ///
1230    /// Clears the display canvas, then draws the offscreen canvas scaled
1231    /// down to the logical display size. The active `quality` preset is
1232    /// applied once at construction via `enable_smoothing` — there is
1233    /// no need to re-apply it every frame, since the preset never
1234    /// changes mid-render.
1235    ///
1236    /// #32: the previous version called `apply_quality` on every
1237    /// `present()`, costing `set_image_smoothing_enabled` + 2×Reflect
1238    /// + 4×from_str ≈ 7 JS crossings per frame for a value that was
1239    ///   invariant across the entire session.
1240    pub fn present(&self) {
1241        self.get_display_context()
1242            .clear_rect(0.0, 0.0, self.get_width(), self.get_height());
1243        let _: Result<(), JsValue> = self
1244            .get_display_context()
1245            .draw_image_with_html_canvas_element_and_dw_and_dh(
1246                self.get_offscreen_canvas(),
1247                0.0,
1248                0.0,
1249                self.get_width(),
1250                self.get_height(),
1251            );
1252    }
1253
1254    /// Clears the offscreen buffer to transparent.
1255    pub fn clear(&self) {
1256        self.get_offscreen_context()
1257            .clear_rect(0.0, 0.0, self.get_width(), self.get_height());
1258    }
1259
1260    /// Clears the offscreen buffer and fills it with the given CSS color.
1261    ///
1262    /// # Arguments
1263    ///
1264    /// - `C: AsRef<str>` - The CSS color string.
1265    pub fn clear_color<C>(&self, color: C)
1266    where
1267        C: AsRef<str>,
1268    {
1269        self.get_offscreen_context()
1270            .set_fill_style_str(color.as_ref());
1271        self.get_offscreen_context()
1272            .fill_rect(0.0, 0.0, self.get_width(), self.get_height());
1273    }
1274
1275    /// Enables high-quality anti-aliasing on both the display and offscreen contexts.
1276    ///
1277    /// Applies the active `quality` preset to both contexts via the shared
1278    /// `apply_quality` helper.
1279    pub fn enable_smoothing(&self) {
1280        let quality: RenderQuality = self.get_quality();
1281        CanvasRenderer::apply_quality(self.get_display_context(), quality);
1282        CanvasRenderer::apply_quality(self.get_offscreen_context(), quality);
1283    }
1284}
1285
1286/// Implements CSS composite operation string conversion for `BlendMode`.
1287impl BlendMode {
1288    /// Returns the CSS `globalCompositeOperation` string for this blend mode.
1289    ///
1290    /// # Returns
1291    ///
1292    /// - `&str` - The CSS composite operation string.
1293    pub fn to_css(&self) -> &str {
1294        match self {
1295            BlendMode::Normal => BLEND_MODE_NORMAL,
1296            BlendMode::Multiply => BLEND_MODE_MULTIPLY,
1297            BlendMode::Screen => BLEND_MODE_SCREEN,
1298            BlendMode::Lighter => BLEND_MODE_LIGHTER,
1299            BlendMode::Overlay => BLEND_MODE_OVERLAY,
1300            BlendMode::Darken => BLEND_MODE_DARKEN,
1301            BlendMode::Lighten => BLEND_MODE_LIGHTEN,
1302            BlendMode::ColorDodge => BLEND_MODE_COLOR_DODGE,
1303            BlendMode::ColorBurn => BLEND_MODE_COLOR_BURN,
1304            BlendMode::HardLight => BLEND_MODE_HARD_LIGHT,
1305            BlendMode::SoftLight => BLEND_MODE_SOFT_LIGHT,
1306            BlendMode::Difference => BLEND_MODE_DIFFERENCE,
1307            BlendMode::Exclusion => BLEND_MODE_EXCLUSION,
1308            BlendMode::Hue => BLEND_MODE_HUE,
1309            BlendMode::Saturation => BLEND_MODE_SATURATION,
1310            BlendMode::Color => BLEND_MODE_COLOR,
1311            BlendMode::Luminosity => BLEND_MODE_LUMINOSITY,
1312        }
1313    }
1314}
1315
1316/// Implements construction and canvas gradient creation for `LinearGradient`.
1317impl LinearGradient {
1318    /// Creates a new linear gradient from two points and a list of color stops.
1319    ///
1320    /// # Arguments
1321    ///
1322    /// - `Vector2D` - The start point.
1323    /// - `Vector2D` - The end point.
1324    /// - `Vec<(f64, String)>` - The color stops as (position, color) pairs.
1325    ///
1326    /// # Returns
1327    ///
1328    /// - `LinearGradient` - The new gradient.
1329    pub fn create(start: Vector2D, end: Vector2D, stops: Vec<(f64, String)>) -> LinearGradient {
1330        LinearGradient::new(start, end, stops)
1331    }
1332
1333    /// Creates a `CanvasGradient` from this gradient definition on the given context.
1334    ///
1335    /// # Arguments
1336    ///
1337    /// - `&CanvasRenderingContext2d` - The canvas context.
1338    ///
1339    /// # Returns
1340    ///
1341    /// - `Option<CanvasGradient>` - The canvas gradient, or `None` if creation failed.
1342    pub fn to_gradient(&self, context: &CanvasRenderingContext2d) -> Option<CanvasGradient> {
1343        let canvas_gradient: CanvasGradient = context.create_linear_gradient(
1344            self.get_start().get_x(),
1345            self.get_start().get_y(),
1346            self.get_end().get_x(),
1347            self.get_end().get_y(),
1348        );
1349        for (position, color) in self.get_stops() {
1350            let _: Result<(), JsValue> = canvas_gradient.add_color_stop(*position as f32, color);
1351        }
1352        Some(canvas_gradient)
1353    }
1354}
1355
1356/// Implements construction and canvas gradient creation for `RadialGradient`.
1357impl RadialGradient {
1358    /// Creates a new radial gradient from inner and outer circles and color stops.
1359    ///
1360    /// # Arguments
1361    ///
1362    /// - `Vector2D` - The inner circle center.
1363    /// - `f64` - The inner circle radius.
1364    /// - `Vector2D` - The outer circle center.
1365    /// - `f64` - The outer circle radius.
1366    /// - `Vec<(f64, String)>` - The color stops as (position, color) pairs.
1367    ///
1368    /// # Returns
1369    ///
1370    /// - `RadialGradient` - The new gradient.
1371    pub fn create(
1372        inner_center: Vector2D,
1373        inner_radius: f64,
1374        outer_center: Vector2D,
1375        outer_radius: f64,
1376        stops: Vec<(f64, String)>,
1377    ) -> RadialGradient {
1378        RadialGradient::new(
1379            inner_center,
1380            inner_radius,
1381            outer_center,
1382            outer_radius,
1383            stops,
1384        )
1385    }
1386
1387    /// Creates a `CanvasGradient` from this gradient definition on the given context.
1388    ///
1389    /// # Arguments
1390    ///
1391    /// - `&CanvasRenderingContext2d` - The canvas context.
1392    ///
1393    /// # Returns
1394    ///
1395    /// - `Option<CanvasGradient>` - The canvas gradient, or `None` if creation failed.
1396    pub fn to_gradient(&self, context: &CanvasRenderingContext2d) -> Option<CanvasGradient> {
1397        let canvas_gradient: CanvasGradient = context
1398            .create_radial_gradient(
1399                self.get_inner_center().get_x(),
1400                self.get_inner_center().get_y(),
1401                self.get_inner_radius(),
1402                self.get_outer_center().get_x(),
1403                self.get_outer_center().get_y(),
1404                self.get_outer_radius(),
1405            )
1406            .ok()?;
1407        for (position, color) in self.get_stops() {
1408            let _: Result<(), JsValue> = canvas_gradient.add_color_stop(*position as f32, color);
1409        }
1410        Some(canvas_gradient)
1411    }
1412}
1413
1414/// Implements construction methods for `ShadowConfig`.
1415impl ShadowConfig {
1416    /// Creates a shadow configuration with default values.
1417    ///
1418    /// # Returns
1419    ///
1420    /// - `ShadowConfig` - The default shadow configuration.
1421    pub fn create() -> ShadowConfig {
1422        ShadowConfig::new(
1423            RENDERER_DEFAULT_SHADOW_COLOR.to_string(),
1424            RENDERER_DEFAULT_SHADOW_BLUR,
1425            0.0,
1426            0.0,
1427        )
1428    }
1429}
1430
1431/// Implements `Default` for `ShadowConfig` with default shadow values.
1432impl Default for ShadowConfig {
1433    /// Constructs a default [`ShadowConfig`] value.
1434    ///
1435    /// # Returns
1436    ///
1437    /// - `ShadowConfig` - A default-constructed instance with the documented initial state.
1438    fn default() -> ShadowConfig {
1439        ShadowConfig::create()
1440    }
1441}
1442
1443/// Implements construction methods for `RenderLayer`.
1444impl RenderLayer {
1445    /// Creates a render layer with the given z-index and visibility.
1446    ///
1447    /// # Arguments
1448    ///
1449    /// - `i32` - The z-index determining draw order.
1450    /// - `bool` - Whether the layer is visible.
1451    ///
1452    /// # Returns
1453    ///
1454    /// - `RenderLayer` - The new render layer.
1455    pub fn create(z_index: i32, visible: bool) -> RenderLayer {
1456        RenderLayer::new(z_index, visible)
1457    }
1458
1459    /// Creates a background render layer with z-index 0 and visibility enabled.
1460    ///
1461    /// # Returns
1462    ///
1463    /// - `RenderLayer` - The background layer.
1464    pub fn background() -> RenderLayer {
1465        RenderLayer::new(RENDERER_LAYER_BACKGROUND, true)
1466    }
1467
1468    /// Creates a foreground render layer with a high z-index and visibility enabled.
1469    ///
1470    /// # Returns
1471    ///
1472    /// - `RenderLayer` - The foreground layer.
1473    pub fn foreground() -> RenderLayer {
1474        RenderLayer::new(RENDERER_LAYER_FOREGROUND, true)
1475    }
1476
1477    /// Creates a UI overlay render layer with the highest z-index and visibility enabled.
1478    ///
1479    /// # Returns
1480    ///
1481    /// - `RenderLayer` - The UI overlay layer.
1482    pub fn ui() -> RenderLayer {
1483        RenderLayer::new(RENDERER_LAYER_UI, true)
1484    }
1485}
1486
1487/// Implements blend mode, shadow, and gradient rendering methods for `CanvasRenderer`.
1488impl CanvasRenderer {
1489    /// Sets the blend mode for compositing subsequent draw operations.
1490    ///
1491    /// # Arguments
1492    ///
1493    /// - `BlendMode` - The blend mode to apply.
1494    pub fn set_blend_mode(&self, mode: BlendMode) {
1495        let _: Result<(), JsValue> = self
1496            .get_context()
1497            .set_global_composite_operation(mode.to_css());
1498    }
1499
1500    /// Applies a shadow configuration for subsequent draw operations.
1501    ///
1502    /// # Arguments
1503    ///
1504    /// - `&ShadowConfig` - The shadow configuration to apply.
1505    pub fn set_shadow(&self, config: &ShadowConfig) {
1506        self.get_context()
1507            .set_shadow_color(config.get_color().as_str());
1508        self.get_context().set_shadow_blur(config.get_blur());
1509        self.get_context()
1510            .set_shadow_offset_x(config.get_offset_x());
1511        self.get_context()
1512            .set_shadow_offset_y(config.get_offset_y());
1513    }
1514
1515    /// Clears any previously applied shadow, disabling shadow rendering.
1516    pub fn clear_shadow(&self) {
1517        self.get_context().set_shadow_color("rgba(0, 0, 0, 0)");
1518        self.get_context().set_shadow_blur(0.0);
1519        self.get_context().set_shadow_offset_x(0.0);
1520        self.get_context().set_shadow_offset_y(0.0);
1521    }
1522
1523    /// Applies a linear gradient as the fill style for subsequent operations.
1524    ///
1525    /// # Arguments
1526    ///
1527    /// - `&LinearGradient` - The linear gradient to use as fill style.
1528    pub fn set_linear_gradient_fill(&self, gradient: &LinearGradient) {
1529        if let Some(canvas_gradient) = gradient.to_gradient(self.get_context()) {
1530            self.get_context()
1531                .set_fill_style_canvas_gradient(&canvas_gradient);
1532        }
1533    }
1534
1535    /// Applies a radial gradient as the fill style for subsequent operations.
1536    ///
1537    /// # Arguments
1538    ///
1539    /// - `&RadialGradient` - The radial gradient to use as fill style.
1540    pub fn set_radial_gradient_fill(&self, gradient: &RadialGradient) {
1541        if let Some(canvas_gradient) = gradient.to_gradient(self.get_context()) {
1542            self.get_context()
1543                .set_fill_style_canvas_gradient(&canvas_gradient);
1544        }
1545    }
1546
1547    /// Applies a linear gradient as the stroke style for subsequent operations.
1548    ///
1549    /// # Arguments
1550    ///
1551    /// - `&LinearGradient` - The linear gradient to use as stroke style.
1552    pub fn set_linear_gradient_stroke(&self, gradient: &LinearGradient) {
1553        if let Some(canvas_gradient) = gradient.to_gradient(self.get_context()) {
1554            self.get_context()
1555                .set_stroke_style_canvas_gradient(&canvas_gradient);
1556        }
1557    }
1558
1559    /// Applies a radial gradient as the stroke style for subsequent operations.
1560    ///
1561    /// # Arguments
1562    ///
1563    /// - `&RadialGradient` - The radial gradient to use as stroke style.
1564    pub fn set_radial_gradient_stroke(&self, gradient: &RadialGradient) {
1565        if let Some(canvas_gradient) = gradient.to_gradient(self.get_context()) {
1566            self.get_context()
1567                .set_stroke_style_canvas_gradient(&canvas_gradient);
1568        }
1569    }
1570}
1571
1572/// Implements the `RenderBackend` trait for `CanvasRenderer`, providing
1573/// a backend-agnostic rendering interface.
1574///
1575/// Each method forwards to the inherent `CanvasRenderer` method of the
1576/// same name, so the per-call documentation lives on the trait definition
1577/// in `engine::renderer::trait` — the inherent method is the source of
1578/// truth, this impl is the trait bridge.
1579impl RenderBackend for CanvasRenderer {
1580    /// Forwards to [`CanvasRenderer::clear`].
1581    fn clear(&self) {
1582        self.clear();
1583    }
1584
1585    /// Forwards to [`CanvasRenderer::clear_color`].
1586    ///
1587    /// # Arguments
1588    ///
1589    /// - `C: AsRef<str>` - A generic type parameter.
1590    fn clear_color<C>(&self, color: C)
1591    where
1592        C: AsRef<str>,
1593    {
1594        self.clear_color(color);
1595    }
1596
1597    /// Forwards to [`CanvasRenderer::save`].
1598    fn save(&self) {
1599        self.save();
1600    }
1601
1602    /// Forwards to [`CanvasRenderer::restore`].
1603    fn restore(&self) {
1604        self.restore();
1605    }
1606
1607    /// Forwards to [`CanvasRenderer::set_fill_color`].
1608    ///
1609    /// # Arguments
1610    ///
1611    /// - `&str` - Shared reference to a `str`.
1612    fn set_fill_color(&self, color: &str) {
1613        self.set_fill_color(color);
1614    }
1615
1616    /// Forwards to [`CanvasRenderer::set_stroke_color`].
1617    ///
1618    /// # Arguments
1619    ///
1620    /// - `&str` - Shared reference to a `str`.
1621    fn set_stroke_color(&self, color: &str) {
1622        self.set_stroke_color(color);
1623    }
1624
1625    /// Forwards to [`CanvasRenderer::set_line_width`].
1626    ///
1627    /// # Arguments
1628    ///
1629    /// - `f64` - A 64-bit float (`f64`).
1630    fn set_line_width(&self, width: f64) {
1631        self.set_line_width(width);
1632    }
1633
1634    /// Forwards to [`CanvasRenderer::set_global_alpha`].
1635    ///
1636    /// # Arguments
1637    ///
1638    /// - `f64` - A 64-bit float (`f64`).
1639    fn set_global_alpha(&self, alpha: f64) {
1640        self.set_global_alpha(alpha);
1641    }
1642
1643    /// Forwards to [`CanvasRenderer::set_blend_mode`].
1644    ///
1645    /// # Arguments
1646    ///
1647    /// - `BlendMode` - A `BlendMode` parameter.
1648    fn set_blend_mode(&self, mode: BlendMode) {
1649        self.set_blend_mode(mode);
1650    }
1651
1652    /// Forwards to [`CanvasRenderer::set_shadow`].
1653    ///
1654    /// # Arguments
1655    ///
1656    /// - `&ShadowConfig` - Shared reference to a `ShadowConfig`.
1657    fn set_shadow(&self, config: &ShadowConfig) {
1658        self.set_shadow(config);
1659    }
1660
1661    /// Forwards to [`CanvasRenderer::clear_shadow`].
1662    fn clear_shadow(&self) {
1663        self.clear_shadow();
1664    }
1665
1666    /// Forwards to [`CanvasRenderer::fill_rect`].
1667    ///
1668    /// # Arguments
1669    ///
1670    /// - `Vector2D` - 2D vector (`Vector2D`).
1671    /// - `f64` - A 64-bit float (`f64`).
1672    /// - `f64` - A 64-bit float (`f64`).
1673    fn fill_rect(&self, position: Vector2D, width: f64, height: f64) {
1674        self.fill_rect(position, width, height);
1675    }
1676
1677    /// Forwards to [`CanvasRenderer::stroke_rect`].
1678    ///
1679    /// # Arguments
1680    ///
1681    /// - `Vector2D` - 2D vector (`Vector2D`).
1682    /// - `f64` - A 64-bit float (`f64`).
1683    /// - `f64` - A 64-bit float (`f64`).
1684    fn stroke_rect(&self, position: Vector2D, width: f64, height: f64) {
1685        self.stroke_rect(position, width, height);
1686    }
1687
1688    /// Forwards to [`CanvasRenderer::fill_circle`].
1689    ///
1690    /// # Arguments
1691    ///
1692    /// - `Vector2D` - 2D vector (`Vector2D`).
1693    /// - `f64` - A 64-bit float (`f64`).
1694    fn fill_circle(&self, center: Vector2D, radius: f64) {
1695        self.fill_circle(center, radius);
1696    }
1697
1698    /// Forwards to [`CanvasRenderer::stroke_circle`].
1699    ///
1700    /// # Arguments
1701    ///
1702    /// - `Vector2D` - 2D vector (`Vector2D`).
1703    /// - `f64` - A 64-bit float (`f64`).
1704    fn stroke_circle(&self, center: Vector2D, radius: f64) {
1705        self.stroke_circle(center, radius);
1706    }
1707
1708    /// Forwards to [`CanvasRenderer::draw_line`].
1709    ///
1710    /// # Arguments
1711    ///
1712    /// - `Vector2D` - 2D vector (`Vector2D`).
1713    /// - `Vector2D` - 2D vector (`Vector2D`).
1714    fn draw_line(&self, start: Vector2D, end: Vector2D) {
1715        self.draw_line(start, end);
1716    }
1717
1718    /// Forwards to [`CanvasRenderer::fill_text`].
1719    ///
1720    /// # Arguments
1721    ///
1722    /// - `&str` - Shared reference to a `str`.
1723    /// - `Vector2D` - 2D vector (`Vector2D`).
1724    fn fill_text(&self, text: &str, position: Vector2D) {
1725        self.fill_text(text, position);
1726    }
1727
1728    /// Forwards to [`CanvasRenderer::set_font`].
1729    ///
1730    /// # Arguments
1731    ///
1732    /// - `&str` - Shared reference to a `str`.
1733    fn set_font(&self, font: &str) {
1734        self.set_font(font);
1735    }
1736
1737    /// Forwards to [`CanvasRenderer::draw_image`].
1738    ///
1739    /// # Arguments
1740    ///
1741    /// - `&HtmlImageElement` - Shared reference to a `HtmlImageElement`.
1742    /// - `Vector2D` - 2D vector (`Vector2D`).
1743    /// - `f64` - A 64-bit float (`f64`).
1744    /// - `f64` - A 64-bit float (`f64`).
1745    fn draw_image(&self, image: &HtmlImageElement, position: Vector2D, width: f64, height: f64) {
1746        self.draw_image(image, position, width, height);
1747    }
1748
1749    /// Forwards to [`CanvasRenderer::set_linear_gradient_fill`].
1750    ///
1751    /// # Arguments
1752    ///
1753    /// - `&LinearGradient` - Shared reference to a `LinearGradient`.
1754    fn set_linear_gradient_fill(&self, gradient: &LinearGradient) {
1755        self.set_linear_gradient_fill(gradient);
1756    }
1757
1758    /// Forwards to [`CanvasRenderer::set_radial_gradient_fill`].
1759    ///
1760    /// # Arguments
1761    ///
1762    /// - `&RadialGradient` - Shared reference to a `RadialGradient`.
1763    fn set_radial_gradient_fill(&self, gradient: &RadialGradient) {
1764        self.set_radial_gradient_fill(gradient);
1765    }
1766}
1767
1768/// Implements async initialization and GPU resource creation for `WebGpuRenderer`.
1769impl WebGpuRenderer {
1770    /// Returns `true` if `navigator.gpu` is exposed on the current origin.
1771    ///
1772    /// This is the synchronous half of the canonical WebGPU capability
1773    /// probe used by Three.js (`examples/jsm/capabilities/WebGPU.js`): it
1774    /// only checks that the browser surfaces the `GPU` interface at all.
1775    /// It does **not** request an adapter — a present `navigator.gpu`
1776    /// does not guarantee that a usable GPU adapter is reachable (Linux
1777    /// software-rendered sessions, headless browsers, GPU-blacklisted
1778    /// devices and sandboxed iframes all expose `navigator.gpu` while
1779    /// `requestAdapter()` resolves to `null` or hangs forever).
1780    ///
1781    /// Use this as the cheapest pre-flight check before showing a
1782    /// "needs HTTPS or localhost" prompt. For a definitive answer use
1783    /// [`Self::probe`] which also awaits `requestAdapter()`.
1784    ///
1785    /// # Returns
1786    ///
1787    /// - `bool` - `true` when `navigator.gpu` is a non-null, non-undefined
1788    ///   object; `false` otherwise (including the "no `window`" runtime
1789    ///   case, which `web_sys::window()` returns `None` for).
1790    pub fn is_available() -> bool {
1791        let window_value: Window = match window() {
1792            Some(value) => value,
1793            None => return false,
1794        };
1795        let navigator: Navigator = window_value.navigator();
1796        let gpu_result: Result<JsValue, JsValue> = Reflect::get(
1797            navigator.as_ref(),
1798            &JsValue::from_str(WEBGPU_NAVIGATOR_GPU_KEY),
1799        );
1800        match gpu_result {
1801            Ok(value) => !value.is_undefined() && !value.is_null(),
1802            Err(_) => false,
1803        }
1804    }
1805
1806    /// Probes whether a WebGPU adapter can actually be acquired.
1807    ///
1808    /// Mirrors Three.js' canonical capability probe exactly:
1809    ///
1810    /// Wraps the adapter request in the same `Promise.race` timeout used
1811    /// by [`Self::init`] so that browsers which leave the adapter promise
1812    /// permanently pending (headless, sandboxed, device-lost) do not stall
1813    /// the UI forever. The timeout itself uses the
1814    /// `INIT_PROMISE_TIMEOUT_MILLIS` constant; on timeout, `probe` returns
1815    /// `false` rather than an error so callers can treat it the same as
1816    /// "no adapter".
1817    ///
1818    /// # Returns
1819    ///
1820    /// - `bool` - `true` only when both `navigator.gpu` is present and
1821    ///   `requestAdapter()` resolves to a non-null adapter within the
1822    ///   timeout window. `false` covers every other case (no `window`,
1823    ///   missing `navigator.gpu`, reflect exception, adapter promise
1824    ///   rejected or timed out, adapter resolved to `null`/`undefined`).
1825    pub async fn probe() -> bool {
1826        if !Self::is_available() {
1827            return false;
1828        }
1829        let window_value: Window = match window() {
1830            Some(value) => value,
1831            None => return false,
1832        };
1833        let navigator: Navigator = window_value.navigator();
1834        let gpu: JsValue = match Reflect::get(
1835            navigator.as_ref(),
1836            &JsValue::from_str(WEBGPU_NAVIGATOR_GPU_KEY),
1837        ) {
1838            Ok(value) => value,
1839            Err(_) => return false,
1840        };
1841        let request_adapter_fn: Function =
1842            match Reflect::get(&gpu, &JsValue::from_str(WEBGPU_METHOD_REQUEST_ADAPTER)) {
1843                Ok(value) => value.unchecked_into(),
1844                Err(_) => return false,
1845            };
1846        let adapter_promise: Promise = match request_adapter_fn.call0(&gpu) {
1847            Ok(value) => value.unchecked_into(),
1848            Err(_) => return false,
1849        };
1850        let adapter_value: JsValue =
1851            match JsFuture::from(Self::race_with_timeout(adapter_promise)).await {
1852                Ok(value) => value,
1853                Err(_) => return false,
1854            };
1855        !adapter_value.is_undefined() && !adapter_value.is_null()
1856    }
1857
1858    /// Asynchronously initializes a WebGPU renderer from the given render configuration.
1859    ///
1860    /// Requests a GPU adapter and device, obtains the WebGPU canvas context,
1861    /// and configures it with the preferred texture format. Returns `None` if
1862    /// WebGPU is not supported, the adapter/device request fails, or the canvas
1863    /// element is not found.
1864    ///
1865    /// # Arguments
1866    ///
1867    /// - `&RenderConfig` - The rendering configuration.
1868    ///
1869    /// # Returns
1870    ///
1871    /// - `Option<WebGpuRenderer>` - The initialized renderer, or `None` on failure.
1872    ///   Maximum time in milliseconds to wait for `requestAdapter` and
1873    ///   `requestDevice` before treating them as failed.
1874    ///
1875    /// Some browser GPU states (headless, no GPU, sandboxed, device-lost)
1876    /// leave the WebGPU adapter/device promises permanently pending instead
1877    /// of resolving to `null` or rejecting. Without a timeout the
1878    /// `JsFuture::from(...).await` inside `init` would hang forever and
1879    /// the UI would stay stuck on `Initializing...`. Wrapping each promise
1880    /// in `Promise.race` against a timer-rejected sibling forces the
1881    /// future to resolve so the caller's `let Some(...) = ... else { ... }`
1882    /// branch can run and report `WebGPU Not Supported`.
1883    /// Returns a Promise that rejects after `INIT_PROMISE_TIMEOUT_MILLIS`.
1884    fn timeout_promise() -> Promise {
1885        let Some(window_value) = window() else {
1886            return Promise::new(&mut |_resolve: Function, reject: Function| {
1887                let _: Result<JsValue, JsValue> = reject.call1(
1888                    &JsValue::UNDEFINED,
1889                    &JsValue::from_str(RENDERER_TIMEOUT_ERROR_MESSAGE),
1890                );
1891            });
1892        };
1893        Promise::new(&mut |_resolve: Function, reject: Function| {
1894            let reject_fn: Function = reject.clone();
1895            let timer: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
1896                let _: Result<JsValue, JsValue> = reject_fn.call1(
1897                    &JsValue::UNDEFINED,
1898                    &JsValue::from_str(RENDERER_TIMEOUT_ERROR_MESSAGE),
1899                );
1900            }));
1901            let _: Result<i32, JsValue> = window_value
1902                .set_timeout_with_callback_and_timeout_and_arguments_0(
1903                    timer.as_ref().unchecked_ref(),
1904                    INIT_PROMISE_TIMEOUT_MILLIS,
1905                );
1906            timer.forget();
1907        })
1908    }
1909
1910    /// Wraps `promise` in `Promise.race([promise, timeout_promise()])` so that
1911    /// awaiting it never blocks longer than `INIT_PROMISE_TIMEOUT_MILLIS`.
1912    ///
1913    /// Calls `Promise.race` via reflection because wasm-bindgen does not
1914    /// currently expose the static `race` method on `Promise`.
1915    ///
1916    /// # Arguments
1917    ///
1918    /// - `Promise` - A `Promise` parameter.
1919    ///
1920    /// # Returns
1921    ///
1922    /// - `Promise` - A `Promise` value.
1923    fn race_with_timeout(promise: Promise) -> Promise {
1924        let array: Array = Array::of2(&promise, &Self::timeout_promise());
1925        Promise::race(&array)
1926    }
1927
1928    /// Asynchronously initializes a WebGPU renderer from the given render configuration.
1929    ///
1930    /// Requests a GPU adapter and device, obtains the WebGPU canvas context,
1931    /// and configures it with the preferred texture format. Returns `Err` if
1932    /// WebGPU is not supported, the adapter/device request fails, the canvas
1933    /// element is not found, or the adapter/device request hangs beyond
1934    /// `INIT_PROMISE_TIMEOUT_MILLIS` (a defensive timeout for browser GPU
1935    /// states that leave the WebGPU promises permanently pending).
1936    ///
1937    /// The engine no longer logs diagnostic output internally; instead each
1938    /// failure mode is returned as a distinct `WebGpuInitError` variant so
1939    /// the caller can decide how to surface it (typically via `Console::error`
1940    /// or by falling back to the Canvas 2D backend).
1941    ///
1942    /// # Arguments
1943    ///
1944    /// - `&RenderConfig` - The rendering configuration.
1945    ///
1946    /// # Returns
1947    ///
1948    /// - `Result<WebGpuRenderer, WebGpuInitError>` - The initialized renderer, or
1949    ///   a typed error describing the specific failure.
1950    pub async fn init(config: &RenderConfig) -> Result<WebGpuRenderer, WebGpuInitError> {
1951        let Some(window) = window() else {
1952            return Err(WebGpuInitError::NavigatorGpuMissing);
1953        };
1954        let navigator: Navigator = window.navigator();
1955        let gpu_result: Result<JsValue, JsValue> = Reflect::get(
1956            navigator.as_ref(),
1957            &JsValue::from_str(WEBGPU_NAVIGATOR_GPU_KEY),
1958        );
1959        let gpu: JsValue = match gpu_result {
1960            Ok(value) => value,
1961            Err(err) => return Err(WebGpuInitError::NavigatorLookup(err)),
1962        };
1963        if gpu.is_undefined() || gpu.is_null() {
1964            return Err(WebGpuInitError::NavigatorGpuMissing);
1965        }
1966        let adapter_options: Object = Object::new();
1967        let _: Result<bool, JsValue> = Reflect::set(
1968            &adapter_options,
1969            &JsValue::from_str(WEBGPU_PROPERTY_POWER_PREFERENCE),
1970            &JsValue::from_str(config.power_preference.to_web_sys_string()),
1971        );
1972        let request_adapter_fn: Function =
1973            match Reflect::get(&gpu, &JsValue::from_str(WEBGPU_METHOD_REQUEST_ADAPTER)) {
1974                Ok(value) => value.unchecked_into(),
1975                Err(err) => return Err(WebGpuInitError::RequestAdapterLookup(err)),
1976            };
1977        let adapter_promise: Promise = match request_adapter_fn.call1(&gpu, &adapter_options) {
1978            Ok(value) => value.unchecked_into(),
1979            Err(err) => return Err(WebGpuInitError::RequestAdapterCall(err)),
1980        };
1981        let adapter_value: JsValue =
1982            match JsFuture::from(Self::race_with_timeout(adapter_promise)).await {
1983                Ok(value) => value,
1984                Err(err) => return Err(WebGpuInitError::AdapterPromise(err)),
1985            };
1986        if adapter_value.is_null() || adapter_value.is_undefined() {
1987            return Err(WebGpuInitError::AdapterUnavailable);
1988        }
1989        let device_descriptor: Object = Object::new();
1990        let request_device_fn: Function = match Reflect::get(
1991            &adapter_value,
1992            &JsValue::from_str(WEBGPU_METHOD_REQUEST_DEVICE),
1993        ) {
1994            Ok(value) => value.unchecked_into(),
1995            Err(err) => return Err(WebGpuInitError::RequestDeviceLookup(err)),
1996        };
1997        let device_promise: Promise =
1998            match request_device_fn.call1(&adapter_value, &device_descriptor) {
1999                Ok(value) => value.unchecked_into(),
2000                Err(err) => return Err(WebGpuInitError::RequestDeviceCall(err)),
2001            };
2002        let device_value: JsValue =
2003            match JsFuture::from(Self::race_with_timeout(device_promise)).await {
2004                Ok(value) => value,
2005                Err(err) => return Err(WebGpuInitError::DevicePromise(err)),
2006            };
2007        if device_value.is_null() || device_value.is_undefined() {
2008            return Err(WebGpuInitError::DeviceUnavailable);
2009        }
2010        let Some(document) = window.document() else {
2011            return Err(WebGpuInitError::CanvasNotFound(
2012                config.canvas_selector.clone(),
2013            ));
2014        };
2015        let element: Element = match document.query_selector(&config.canvas_selector) {
2016            Ok(Some(el)) => el,
2017            Ok(None) => {
2018                return Err(WebGpuInitError::CanvasNotFound(
2019                    config.canvas_selector.clone(),
2020                ));
2021            }
2022            Err(err) => return Err(WebGpuInitError::CanvasQuery(err)),
2023        };
2024        let canvas: HtmlCanvasElement = element.unchecked_into();
2025        let context_object: Option<Object> = canvas.get_context(WEBGPU_CONTEXT_TYPE).ok().flatten();
2026        let context_object: Object = match context_object {
2027            Some(c) => c,
2028            None => return Err(WebGpuInitError::CanvasContextUnavailable),
2029        };
2030        let context: JsValue = context_object.into();
2031        let get_format_fn: Function =
2032            match Reflect::get(&gpu, &JsValue::from_str(WEBGPU_METHOD_GET_PREFERRED_FORMAT)) {
2033                Ok(value) => value.unchecked_into(),
2034                Err(err) => return Err(WebGpuInitError::PreferredFormatLookup(err)),
2035            };
2036        let format_value: JsValue = match get_format_fn.call0(&gpu) {
2037            Ok(value) => value,
2038            Err(err) => return Err(WebGpuInitError::PreferredFormatCall(err)),
2039        };
2040        let format: String = match format_value.as_string() {
2041            Some(s) => s,
2042            None => return Err(WebGpuInitError::PreferredFormatType(format_value)),
2043        };
2044        // WebGPU's `configure` requires the canvas backing-store size to be
2045        // set BEFORE calling configure, otherwise the swap chain is created
2046        // at 0x0 and the first getCurrentTexture() returns an error.
2047        let dpr: f64 = CanvasRenderer::detect_dpr();
2048        let physical_width: u32 = (config.width * dpr).round() as u32;
2049        let physical_height: u32 = (config.height * dpr).round() as u32;
2050        canvas.set_width(physical_width);
2051        canvas.set_height(physical_height);
2052        let canvas_config: Object = Object::new();
2053        let _: Result<bool, JsValue> = Reflect::set(
2054            &canvas_config,
2055            &JsValue::from_str(WEBGPU_PROPERTY_DEVICE),
2056            &device_value,
2057        );
2058        let _: Result<bool, JsValue> = Reflect::set(
2059            &canvas_config,
2060            &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
2061            &format_value,
2062        );
2063        let configure_fn: Function =
2064            match Reflect::get(&context, &JsValue::from_str(WEBGPU_METHOD_CONFIGURE)) {
2065                Ok(value) => value.unchecked_into(),
2066                Err(err) => return Err(WebGpuInitError::ConfigureLookup(err)),
2067            };
2068        let _: Result<JsValue, JsValue> = configure_fn.call1(&context, &canvas_config);
2069        let queue: JsValue =
2070            match Reflect::get(&device_value, &JsValue::from_str(WEBGPU_PROPERTY_QUEUE)) {
2071                Ok(value) => value,
2072                Err(err) => return Err(WebGpuInitError::QueueLookup(err)),
2073            };
2074        Ok(WebGpuRenderer {
2075            device: device_value,
2076            queue,
2077            context,
2078            canvas,
2079            format,
2080            width: physical_width,
2081            height: physical_height,
2082            antialias: config.antialias,
2083            multisample_texture: None,
2084            multisample_view: None,
2085            depth_texture: None,
2086            depth_view: None,
2087            depth_format: None,
2088            device_lost_callback: None,
2089            device_lost: false,
2090            pending_error: Rc::new(PendingErrorCell::new()),
2091            command_encoder: None,
2092            render_pass_descriptor_cache: None,
2093        })
2094    }
2095
2096    /// Allocates the multisampled intermediate texture used for MSAA.
2097    ///
2098    /// The returned tuple is `(GpuTexture, GpuTextureView)`:
2099    /// - `GpuTexture` has `sampleCount: 4` and `usage: RENDER_ATTACHMENT`
2100    ///   so it can be bound as a color attachment in `beginRenderPass`.
2101    /// - `GpuTextureView` is the default 2D view used as the color
2102    ///   attachment; the swap chain view is the `resolveTarget`.
2103    ///
2104    /// The texture size must match the swap chain physical size; mismatches
2105    /// are a WebGPU validation error. Returns `(JsValue::UNDEFINED,
2106    /// JsValue::UNDEFINED)` when allocation fails so callers can detect and
2107    /// fall back to MSAA=1.
2108    ///
2109    /// # Arguments
2110    ///
2111    /// - `u32` - Physical pixel width (DPR-multiplied).
2112    /// - `u32` - Physical pixel height.
2113    ///
2114    /// # Returns
2115    ///
2116    /// - `(JsValue, JsValue)` - The new texture and its default view, or
2117    ///   `JsValue::UNDEFINED` for both on allocation failure.
2118    fn create_multisample_texture(
2119        &self,
2120        physical_width: u32,
2121        physical_height: u32,
2122    ) -> (JsValue, JsValue) {
2123        let extent: Object = Object::new();
2124        let _: Result<bool, JsValue> = Reflect::set(
2125            &extent,
2126            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_WIDTH),
2127            &JsValue::from_f64(f64::from(physical_width)),
2128        );
2129        let _: Result<bool, JsValue> = Reflect::set(
2130            &extent,
2131            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_HEIGHT),
2132            &JsValue::from_f64(f64::from(physical_height)),
2133        );
2134        let _: Result<bool, JsValue> = Reflect::set(
2135            &extent,
2136            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_DEPTH),
2137            &JsValue::from_f64(1.0),
2138        );
2139        let descriptor: Object = Object::new();
2140        let _: Result<bool, JsValue> = Reflect::set(
2141            &descriptor,
2142            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
2143            &extent,
2144        );
2145        let _: Result<bool, JsValue> = Reflect::set(
2146            &descriptor,
2147            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_FORMAT),
2148            &JsValue::from_str(&self.get_format()),
2149        );
2150        let _: Result<bool, JsValue> = Reflect::set(
2151            &descriptor,
2152            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
2153            &JsValue::from_f64(WEBGPU_TEXTURE_USAGE_RENDER_ATTACHMENT),
2154        );
2155        let _: Result<bool, JsValue> = Reflect::set(
2156            &descriptor,
2157            &JsValue::from_str(WEBGPU_PROPERTY_SAMPLE_COUNT),
2158            &JsValue::from_f64(4.0),
2159        );
2160        let create_texture_fn: Function = Reflect::get(
2161            self.get_device(),
2162            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
2163        )
2164        .unwrap_or(JsValue::UNDEFINED)
2165        .unchecked_into();
2166        let texture: JsValue = create_texture_fn
2167            .call1(self.get_device(), &descriptor)
2168            .unwrap_or(JsValue::UNDEFINED);
2169        if texture.is_undefined() {
2170            return (JsValue::UNDEFINED, JsValue::UNDEFINED);
2171        }
2172        let create_view_fn: Function =
2173            Reflect::get(&texture, &JsValue::from_str(WEBGPU_METHOD_CREATE_VIEW))
2174                .unwrap_or(JsValue::UNDEFINED)
2175                .unchecked_into();
2176        let view: JsValue = create_view_fn.call0(&texture).unwrap_or(JsValue::UNDEFINED);
2177        if view.is_undefined() {
2178            return (texture, JsValue::UNDEFINED);
2179        }
2180        (texture, view)
2181    }
2182
2183    /// Resizes the canvas backing store and reconfigures the swap chain.
2184    ///
2185    /// WebGPU's `GpuCanvasContext.configure` is sticky: it sets the texture
2186    /// format and device once, but the swap chain tracks the canvas's
2187    /// `width`/`height` attributes. When the CSS layout size changes (a
2188    /// window resize, a panel toggle, a DPR change) the canvas keeps its
2189    /// old physical dimensions unless we explicitly update `width`/`height`
2190    /// and call `configure` again. Without this, subsequent
2191    /// `getCurrentTexture()` calls return a texture that no longer matches
2192    /// the visible region and the frame either stretches or freezes.
2193    ///
2194    /// Re-`configure`ing with the same `device` + `format` is the
2195    /// spec-defined way to swap in a fresh swap chain bound to the new
2196    /// backing-store size.
2197    ///
2198    /// # Arguments
2199    ///
2200    /// - `u32` - The new physical pixel width (already multiplied by DPR).
2201    /// - `u32` - The new physical pixel height.
2202    ///
2203    /// # Returns
2204    ///
2205    /// - `bool` - `true` on success, `false` if the swap chain or canvas
2206    ///   handles were missing or `configure` failed.
2207    pub fn resize(&mut self, physical_width: u32, physical_height: u32) -> bool {
2208        if self.get_canvas().is_null()
2209            || self.get_context().is_null()
2210            || self.get_device().is_undefined()
2211        {
2212            return false;
2213        }
2214        self.get_canvas().set_width(physical_width);
2215        self.get_canvas().set_height(physical_height);
2216        let format_value: JsValue = JsValue::from_str(&self.get_format());
2217        let canvas_config: Object = Object::new();
2218        let _: Result<bool, JsValue> = Reflect::set(
2219            &canvas_config,
2220            &JsValue::from_str(WEBGPU_PROPERTY_DEVICE),
2221            self.get_device(),
2222        );
2223        let _: Result<bool, JsValue> = Reflect::set(
2224            &canvas_config,
2225            &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
2226            &format_value,
2227        );
2228        let configure_fn: Function = Reflect::get(
2229            self.get_context(),
2230            &JsValue::from_str(WEBGPU_METHOD_CONFIGURE),
2231        )
2232        .ok()
2233        .and_then(|value: JsValue| value.dyn_into::<Function>().ok())
2234        .unwrap_or_else(|| Function::new_no_args(""));
2235        if configure_fn
2236            .call1(self.get_context(), &canvas_config)
2237            .is_err()
2238        {
2239            return false;
2240        }
2241        self.set_width(physical_width);
2242        self.set_height(physical_height);
2243        // Rebuild the multisampled color texture to match the new backing
2244        // store size. `GpuTexture` width/height are immutable, so MSAA
2245        // requires recreating it on every resize. The previous texture (if
2246        // any) is left to the GPU's GC; we do not explicitly destroy it
2247        // because `destroy()` is a synchronous WebGPU call and the old
2248        // texture is no longer referenced by any in-flight command buffer
2249        // at this point in the frame loop.
2250        if self.get_antialias() {
2251            let (texture, view) = self.create_multisample_texture(physical_width, physical_height);
2252            if !view.is_undefined() {
2253                self.set_multisample_texture(Some(texture));
2254                self.set_multisample_view(Some(view));
2255            } else {
2256                self.set_multisample_texture(None);
2257                self.set_multisample_view(None);
2258            }
2259        }
2260        true
2261    }
2262
2263    /// Resizes the canvas backing store to match the canvas element's
2264    /// current CSS-rendered size in physical pixels (DPR applied).
2265    ///
2266    /// This is the right entry point when the render loop does not know
2267    /// the desired logical size ahead of time and wants to follow the
2268    /// element's actual layout box. It is also useful as a defensive
2269    /// recovery when the canvas was created while hidden (zero-sized
2270    /// parent) and is later shown at its real size.
2271    ///
2272    /// Reads `client_width` / `client_height` from the canvas element,
2273    /// multiplies by `detect_dpr()`, and forwards to [`Self::resize`].
2274    ///
2275    /// # Returns
2276    ///
2277    /// - `bool` - `true` if the resize succeeded, `false` if the canvas
2278    ///   was zero-sized (nothing to render to), detached (CSS layout
2279    ///   box collapses to 0), or the underlying resize rejected.
2280    pub fn sync_to_current_canvas(&mut self) -> bool {
2281        let canvas_width: u32 = self.get_canvas().width();
2282        let canvas_height: u32 = self.get_canvas().height();
2283        let client_width: u32 = self
2284            .get_canvas()
2285            .client_width()
2286            .try_into()
2287            .unwrap_or_default();
2288        let client_height: u32 = self
2289            .get_canvas()
2290            .client_height()
2291            .try_into()
2292            .unwrap_or_default();
2293        // Prefer the CSS layout box when it is non-zero. If the canvas
2294        // is hidden the client box collapses to 0; in that case fall
2295        // back to the current backing-store size so we do not
2296        // gratuitously resize to 0.
2297        let css_w: u32 = if client_width > 0 {
2298            client_width
2299        } else {
2300            canvas_width
2301        };
2302        let css_h: u32 = if client_height > 0 {
2303            client_height
2304        } else {
2305            canvas_height
2306        };
2307        if css_w == 0 || css_h == 0 {
2308            return false;
2309        }
2310        let dpr: f64 = CanvasRenderer::detect_dpr();
2311        let physical_width: u32 = (f64::from(css_w) * dpr).round() as u32;
2312        let physical_height: u32 = (f64::from(css_h) * dpr).round() as u32;
2313        self.resize(physical_width, physical_height)
2314    }
2315
2316    /// Creates a shader module from WGSL source code.
2317    ///
2318    /// # Arguments
2319    ///
2320    /// - `S: AsRef<str>` - The WGSL shader source code.
2321    ///
2322    /// # Returns
2323    ///
2324    /// - `JsValue` - The created shader module as a JavaScript value.
2325    pub(crate) fn create_shader_module<S>(&self, code: S) -> JsValue
2326    where
2327        S: AsRef<str>,
2328    {
2329        let descriptor: Object = Object::new();
2330        let _: Result<bool, JsValue> = Reflect::set(
2331            &descriptor,
2332            &JsValue::from_str(WEBGPU_PROPERTY_CODE),
2333            &JsValue::from_str(code.as_ref()),
2334        );
2335        let create_fn: Function = Reflect::get(
2336            self.get_device(),
2337            &JsValue::from_str(WEBGPU_METHOD_CREATE_SHADER_MODULE),
2338        )
2339        .unwrap_or(JsValue::UNDEFINED)
2340        .unchecked_into();
2341        create_fn
2342            .call1(self.get_device(), &descriptor)
2343            .unwrap_or(JsValue::UNDEFINED)
2344    }
2345
2346    /// Creates a new command encoder for recording GPU commands.
2347    ///
2348    /// # Returns
2349    ///
2350    /// - `JsValue` - The created command encoder as a JavaScript value.
2351    pub fn create_command_encoder(&self) -> JsValue {
2352        // OPT 2b: cached `device.createCommandEncoder()` — `Function`
2353        // is the same prototype slot for the device's lifetime, so
2354        // skipping the `Reflect::get` shaves ~110ns per frame.
2355        let create_fn: Function =
2356            cached_method(self.get_device(), WEBGPU_METHOD_CREATE_COMMAND_ENCODER)
2357                .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
2358        create_fn
2359            .call0(self.get_device())
2360            .unwrap_or(JsValue::UNDEFINED)
2361    }
2362
2363    /// Returns the current texture view from the canvas swap chain.
2364    ///
2365    /// This texture view should be used as the color attachment target for
2366    /// render passes. The texture is automatically presented to the canvas
2367    /// when the command buffer is submitted.
2368    ///
2369    /// # Returns
2370    ///
2371    /// - `JsValue` - The current frame's texture view as a JavaScript value.
2372    pub(crate) fn get_current_texture_view(&self) -> JsValue {
2373        // OPT 2b: cached `context.getCurrentTexture()` and the
2374        // resulting `texture.createView()`. Both methods live on
2375        // stable prototypes, so the `Function` reference is stable
2376        // for the receiver's lifetime.
2377        let get_texture_fn: Function =
2378            cached_method(self.get_context(), WEBGPU_METHOD_GET_CURRENT_TEXTURE)
2379                .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
2380        let texture: JsValue = get_texture_fn
2381            .call0(self.get_context())
2382            .unwrap_or(JsValue::UNDEFINED);
2383        let create_view_fn: Function = cached_method(&texture, WEBGPU_METHOD_CREATE_VIEW)
2384            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
2385        create_view_fn.call0(&texture).unwrap_or(JsValue::UNDEFINED)
2386    }
2387
2388    /// Begins a render pass on the given command encoder with a clear color.
2389    ///
2390    /// The render pass targets the canvas's current texture and clears it
2391    /// to the specified color. The returned `JsValue` is a `GpuRenderPassEncoder`
2392    /// that can be used to issue draw commands. The pass must be ended (via `end()`)
2393    /// before the command encoder is finished.
2394    ///
2395    /// This is a thin convenience wrapper over
2396    /// [`WebGpuRenderer::begin_render_pass_full`]. For pipelines that
2397    /// need depth testing, multiple color attachments, MSAA control,
2398    /// or `load`/`store` op customization, use the full version with
2399    /// a [`RenderPassColorAttachment`] (and optional
2400    /// [`RenderPassDepthStencilAttachment`]).
2401    ///
2402    /// # Arguments
2403    ///
2404    /// - `&JsValue` - The command encoder to begin the pass on.
2405    /// - `(f64, f64, f64, f64)` - The clear color as (r, g, b, a) in 0.0–1.0 range.
2406    ///
2407    /// # Returns
2408    ///
2409    /// - `JsValue` - The active render pass encoder as a JavaScript value.
2410    pub fn begin_render_pass(
2411        &mut self,
2412        encoder: &JsValue,
2413        clear_color: (f64, f64, f64, f64),
2414    ) -> JsValue {
2415        let mut color: RenderPassColorAttachment = RenderPassColorAttachment {
2416            view: None,
2417            resolve_target: None,
2418            clear_value: Some(clear_color),
2419            load_op: None,
2420            store_op: None,
2421        };
2422        self.begin_render_pass_full(encoder, &mut color, None)
2423    }
2424
2425    /// Begins a render pass with full control over attachments, load/store
2426    /// ops, MSAA resolve targets, and an optional depth-stencil attachment.
2427    ///
2428    /// This is the "complete" render-pass API used by the rest of the
2429    /// engine. All other render-pass entry points (including the
2430    /// legacy `begin_render_pass(clear_color)` wrapper) funnel through
2431    /// here.
2432    ///
2433    /// The color attachment's `view` is filled in lazily when `None`:
2434    /// if `antialias == true` and the multisample intermediate is
2435    /// available (or can be allocated), the pass draws into the MSAA
2436    /// view and resolves into the swap chain; otherwise it draws
2437    /// directly into the swap chain. The `resolve_target` is filled in
2438    /// with the swap-chain view when MSAA is active and the caller
2439    /// did not provide one.
2440    ///
2441    /// # Arguments
2442    ///
2443    /// - `encoder` - The `GpuCommandEncoder` to begin the pass on.
2444    /// - `color` - The color attachment descriptor. `color.view` and
2445    ///   `color.resolve_target` may be `None`; they are filled in with
2446    ///   the renderer's defaults.
2447    /// - `depth` - An optional depth-stencil attachment. `Some(...)`
2448    ///   adds a `depthStencilAttachment` field to the pass
2449    ///   descriptor; `None` omits it entirely.
2450    ///
2451    /// # Returns
2452    ///
2453    /// - `JsValue` - The active `GpuRenderPassEncoder` as a JavaScript
2454    ///   value, suitable for the existing `set_pipeline` / `draw` /
2455    ///   `end_render_pass` calls.
2456    pub fn begin_render_pass_full(
2457        &mut self,
2458        encoder: &JsValue,
2459        color: &mut RenderPassColorAttachment,
2460        depth: Option<&RenderPassDepthStencilAttachment>,
2461    ) -> JsValue {
2462        let swap_chain_view: JsValue = self.get_current_texture_view();
2463        // Resolve MSAA view + resolve target with the same policy as
2464        // the legacy `begin_render_pass`: prefer the existing
2465        // multisample view, lazily allocate it if missing, and fall
2466        // back to direct-to-swap-chain if MSAA allocation fails.
2467        let (color_view, resolve_view): (JsValue, Option<JsValue>) = match color.view.take() {
2468            Some(view) if !view.is_undefined() => (view, color.resolve_target.take()),
2469            _ => {
2470                if self.get_antialias() {
2471                    let multisample_view: Option<JsValue> = self
2472                        .get_multisample_view()
2473                        .clone()
2474                        .filter(|value: &JsValue| !value.is_undefined());
2475                    let resolved: Option<JsValue> = match multisample_view {
2476                        Some(view) => Some(view),
2477                        None => {
2478                            let width: u32 = self.get_width();
2479                            let height: u32 = self.get_height();
2480                            let (texture, view): (JsValue, JsValue) =
2481                                self.create_multisample_texture(width, height);
2482                            if !view.is_undefined() {
2483                                self.set_multisample_texture(Some(texture));
2484                                self.set_multisample_view(Some(view.clone()));
2485                                Some(view)
2486                            } else {
2487                                self.set_multisample_texture(None);
2488                                self.set_multisample_view(None);
2489                                None
2490                            }
2491                        }
2492                    };
2493                    match resolved {
2494                        Some(view) => (view, Some(swap_chain_view.clone())),
2495                        None => (swap_chain_view.clone(), None),
2496                    }
2497                } else {
2498                    (swap_chain_view.clone(), None)
2499                }
2500            }
2501        };
2502        // OPT 34: cache the render-pass descriptor across frames so
2503        // we only allocate the JS `Object`/`Array` once and only
2504        // rewrite the fields that actually change between frames
2505        // (typically `clearValue`). The cache is invalidated on
2506        // load/store op or depth-stencil shape changes (rare).
2507        //
2508        // Effective ops are `&'static str` (from `WEBGPU_*_OP_*`
2509        // constants), so a pointer-compare detects "caller switched
2510        // ops" with zero cost.
2511        let effective_load_op: &'static str = color.effective_load_op();
2512        let effective_store_op: &'static str = color.effective_store_op();
2513        let has_depth: bool = depth.is_some();
2514        let has_resolve: bool = resolve_view.is_some();
2515        let cache_needs_rebuild: bool = match self.render_pass_descriptor_cache.as_ref() {
2516            None => true,
2517            Some(existing) => {
2518                existing.last_load_op != Some(effective_load_op)
2519                    || existing.last_store_op != Some(effective_store_op)
2520                    || existing.last_has_depth != has_depth
2521                    || existing.last_has_resolve != has_resolve
2522            }
2523        };
2524        if cache_needs_rebuild {
2525            self.render_pass_descriptor_cache = Some(self.build_render_pass_descriptor(
2526                &color_view,
2527                resolve_view.as_ref(),
2528                color.clear_value,
2529                effective_load_op,
2530                effective_store_op,
2531                depth,
2532            ));
2533        }
2534        // `Some(_)` invariant: either the cache was non-None at the
2535        // top of this function (we only land in the None branch when
2536        // `cache_needs_rebuild` was true, in which case we just set
2537        // it above) or the caller passed us a renderer with no
2538        // descriptor cache yet and we built one. In both cases the
2539        // `Some` arm is the only reachable branch; we fall back to
2540        // a freshly-built empty cache (and emit no `beginRenderPass`
2541        // call) only if the impossible happened — `build_*` returned
2542        // a cache that was somehow dropped between the two lines,
2543        // which it cannot (no panic path, no early return).
2544        let cache: &RenderPassDescriptorCache = match self.render_pass_descriptor_cache.as_ref() {
2545            Some(c) => c,
2546            None => {
2547                // Defensive: build a no-op cache so the renderer's
2548                // caller sees a stable `JsValue::UNDEFINED` rather
2549                // than a dangling call. This branch is unreachable
2550                // under the invariant above.
2551                return JsValue::UNDEFINED;
2552            }
2553        };
2554        // Hot path: only the `clearValue` (and sometimes `view`) is
2555        // mutated between frames. We update the cached `view` and
2556        // `clearValue` Object's `r`/`g`/`b`/`a` properties
2557        // unconditionally — `Reflect::set` is a fast pointer write
2558        // when the value differs, and the JS-side property setter
2559        // accepts the same numeric value with no observable change.
2560        let _: Result<bool, JsValue> = Reflect::set(
2561            &cache.attachment,
2562            &cached_method_name(WEBGPU_PROPERTY_VIEW),
2563            &color_view,
2564        );
2565        // `resolveTarget` is the per-frame swap-chain view on the MSAA
2566        // path (`context.getCurrentTexture()` textures expire when the
2567        // frame is presented), so it MUST be refreshed every frame —
2568        // keeping the first frame's view makes every subsequent
2569        // `beginRenderPass` fail validation silently (black canvas).
2570        // When the caller drops MSAA mid-stream the Some/None shape
2571        // change triggers a rebuild above, so the `None` arm here never
2572        // leaves a stale `resolveTarget` behind.
2573        if let Some(target) = resolve_view.as_ref() {
2574            let _: Result<bool, JsValue> = Reflect::set(
2575                &cache.attachment,
2576                &cached_method_name(WEBGPU_PROPERTY_RESOLVE_TARGET),
2577                target,
2578            );
2579        }
2580        if let Some(cv) = color.clear_value {
2581            let _: Result<bool, JsValue> = Reflect::set(
2582                &cache.clear_value,
2583                &cached_method_name(WEBGPU_PROPERTY_R),
2584                &JsValue::from_f64(cv.0),
2585            );
2586            let _: Result<bool, JsValue> = Reflect::set(
2587                &cache.clear_value,
2588                &cached_method_name(WEBGPU_PROPERTY_G),
2589                &JsValue::from_f64(cv.1),
2590            );
2591            let _: Result<bool, JsValue> = Reflect::set(
2592                &cache.clear_value,
2593                &cached_method_name(WEBGPU_PROPERTY_B),
2594                &JsValue::from_f64(cv.2),
2595            );
2596            let _: Result<bool, JsValue> = Reflect::set(
2597                &cache.clear_value,
2598                &cached_method_name(WEBGPU_PROPERTY_A),
2599                &JsValue::from_f64(cv.3),
2600            );
2601            // `attachment.clearValue` always points at the same
2602            // `clear_value` Object, so we only need to set it on the
2603            // very first call (i.e. when the cache was just built).
2604            // Subsequent calls leave the link intact.
2605            if cache_needs_rebuild {
2606                let _: Result<bool, JsValue> = Reflect::set(
2607                    &cache.attachment,
2608                    &cached_method_name(WEBGPU_PROPERTY_CLEAR_VALUE),
2609                    &cache.clear_value,
2610                );
2611            }
2612        }
2613        // The `descriptor.colorAttachments[0]` slot is stable for the
2614        // cache's lifetime (set once when the descriptor was built);
2615        // `view` / `resolveTarget` / `clearValue` are refreshed above
2616        // on every call.
2617        let begin_fn: Function = cached_method(encoder, WEBGPU_METHOD_BEGIN_RENDER_PASS)
2618            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
2619        begin_fn
2620            .call1(encoder, &cache.descriptor)
2621            .unwrap_or(JsValue::UNDEFINED)
2622    }
2623
2624    /// OPT 34 helper: build a fresh `RenderPassDescriptorCache` from
2625    /// scratch. Called from [`WebGpuRenderer::begin_render_pass_full`]
2626    /// on cache miss (first call, op change, or depth-shape change).
2627    ///
2628    /// The constructed cache holds:
2629    /// - `descriptor`: the top-level `GpuRenderPassDescriptor`
2630    ///   Object, passed directly to `encoder.beginRenderPass`.
2631    /// - `color_attachments`: a length-1 `Array` containing the
2632    ///   cached `attachment` Object.
2633    /// - `attachment`: the inner color attachment Object.
2634    /// - `clear_value`: the `{r, g, b, a}` dictionary under
2635    ///   `attachment.clearValue`. This is the only Object whose
2636    ///   fields are mutated per frame.
2637    /// - `last_load_op` / `last_store_op`: the `&'static str` ops
2638    ///   applied to the descriptor this frame, used to detect
2639    ///   caller-driven op changes.
2640    /// - `last_has_depth`: whether the descriptor had a
2641    ///   `depthStencilAttachment`, used to detect shape changes.
2642    ///
2643    /// # Arguments
2644    ///
2645    /// - `color_view` - The `GpuTextureView` for the color attachment.
2646    /// - `resolve_view` - Optional resolve target (MSAA only).
2647    /// - `clear_value` - Optional `(r, g, b, a)` clear color.
2648    /// - `effective_load_op` - The `&'static str` load op to encode.
2649    /// - `effective_store_op` - The `&'static str` store op to encode.
2650    /// - `depth` - Optional depth-stencil attachment.
2651    fn build_render_pass_descriptor(
2652        &mut self,
2653        color_view: &JsValue,
2654        resolve_view: Option<&JsValue>,
2655        clear_value: Option<(f64, f64, f64, f64)>,
2656        effective_load_op: &'static str,
2657        effective_store_op: &'static str,
2658        depth: Option<&RenderPassDepthStencilAttachment>,
2659    ) -> RenderPassDescriptorCache {
2660        let attachment: Object = Object::new();
2661        let _: Result<bool, JsValue> = Reflect::set(
2662            &attachment,
2663            &cached_method_name(WEBGPU_PROPERTY_VIEW),
2664            color_view,
2665        );
2666        let _: Result<bool, JsValue> = Reflect::set(
2667            &attachment,
2668            &cached_method_name(WEBGPU_PROPERTY_LOAD_OP),
2669            &JsValue::from_str(effective_load_op),
2670        );
2671        let _: Result<bool, JsValue> = Reflect::set(
2672            &attachment,
2673            &cached_method_name(WEBGPU_PROPERTY_STORE_OP),
2674            &JsValue::from_str(effective_store_op),
2675        );
2676        let clear_value_obj: Object = Object::new();
2677        if let Some(cv) = clear_value {
2678            let _: Result<bool, JsValue> = Reflect::set(
2679                &clear_value_obj,
2680                &cached_method_name(WEBGPU_PROPERTY_R),
2681                &JsValue::from_f64(cv.0),
2682            );
2683            let _: Result<bool, JsValue> = Reflect::set(
2684                &clear_value_obj,
2685                &cached_method_name(WEBGPU_PROPERTY_G),
2686                &JsValue::from_f64(cv.1),
2687            );
2688            let _: Result<bool, JsValue> = Reflect::set(
2689                &clear_value_obj,
2690                &cached_method_name(WEBGPU_PROPERTY_B),
2691                &JsValue::from_f64(cv.2),
2692            );
2693            let _: Result<bool, JsValue> = Reflect::set(
2694                &clear_value_obj,
2695                &cached_method_name(WEBGPU_PROPERTY_A),
2696                &JsValue::from_f64(cv.3),
2697            );
2698            let _: Result<bool, JsValue> = Reflect::set(
2699                &attachment,
2700                &cached_method_name(WEBGPU_PROPERTY_CLEAR_VALUE),
2701                &clear_value_obj,
2702            );
2703        }
2704        if let Some(target) = resolve_view {
2705            let _: Result<bool, JsValue> = Reflect::set(
2706                &attachment,
2707                &cached_method_name(WEBGPU_PROPERTY_RESOLVE_TARGET),
2708                target,
2709            );
2710        }
2711        let color_attachments: Array = Array::new();
2712        color_attachments.push(&attachment);
2713        let descriptor: Object = Object::new();
2714        let _: Result<bool, JsValue> = Reflect::set(
2715            &descriptor,
2716            &cached_method_name(WEBGPU_PROPERTY_COLOR_ATTACHMENTS),
2717            &color_attachments,
2718        );
2719        let last_has_depth: bool = if let Some(depth_desc) = depth {
2720            // Prefer the caller-provided view; otherwise lazily
2721            // allocate the default depth-stencil texture and use its
2722            // view.
2723            let depth_view: JsValue = match depth_desc.view.clone() {
2724                Some(v) if !v.is_undefined() => v,
2725                _ => match self.create_depth_texture() {
2726                    Some(v) => v,
2727                    None => JsValue::UNDEFINED,
2728                },
2729            };
2730            if !depth_view.is_undefined() {
2731                let depth_attachment: Object = Object::new();
2732                let _: Result<bool, JsValue> = Reflect::set(
2733                    &depth_attachment,
2734                    &cached_method_name(WEBGPU_PROPERTY_VIEW),
2735                    &depth_view,
2736                );
2737                let _: Result<bool, JsValue> = Reflect::set(
2738                    &depth_attachment,
2739                    &cached_method_name(WEBGPU_PROPERTY_DEPTH_LOAD_OP),
2740                    &JsValue::from_str(depth_desc.effective_depth_load_op()),
2741                );
2742                let _: Result<bool, JsValue> = Reflect::set(
2743                    &depth_attachment,
2744                    &cached_method_name(WEBGPU_PROPERTY_DEPTH_STORE_OP),
2745                    &JsValue::from_str(depth_desc.effective_depth_store_op()),
2746                );
2747                if let Some(clear) = depth_desc.depth_clear_value {
2748                    let _: Result<bool, JsValue> = Reflect::set(
2749                        &depth_attachment,
2750                        &cached_method_name(WEBGPU_PROPERTY_DEPTH_CLEAR_VALUE),
2751                        &JsValue::from_f64(f64::from(clear)),
2752                    );
2753                }
2754                if let Some(read_only) = depth_desc.depth_read_only {
2755                    let _: Result<bool, JsValue> = Reflect::set(
2756                        &depth_attachment,
2757                        &cached_method_name(WEBGPU_PROPERTY_DEPTH_READ_ONLY),
2758                        &JsValue::from_bool(read_only),
2759                    );
2760                }
2761                let _: Result<bool, JsValue> = Reflect::set(
2762                    &descriptor,
2763                    &cached_method_name(WEBGPU_PROPERTY_DEPTH_STENCIL_ATTACHMENT),
2764                    &depth_attachment,
2765                );
2766                true
2767            } else {
2768                false
2769            }
2770        } else {
2771            false
2772        };
2773        RenderPassDescriptorCache {
2774            descriptor,
2775            attachment,
2776            clear_value: clear_value_obj,
2777            last_load_op: Some(effective_load_op),
2778            last_store_op: Some(effective_store_op),
2779            last_has_depth,
2780            last_has_resolve: resolve_view.is_some(),
2781        }
2782    }
2783
2784    /// Submits an array of command buffers to the GPU queue for execution.
2785    ///
2786    /// # Arguments
2787    ///
2788    /// - `&[JsValue]` - The command buffers to submit.
2789    pub fn submit(&self, command_buffers: &[JsValue]) {
2790        let array: Array = Array::new();
2791        for buffer in command_buffers {
2792            array.push(buffer);
2793        }
2794        // OPT 2b: cached `queue.submit()` — `Function` is the same
2795        // prototype slot for the queue's lifetime.
2796        let _: Result<JsValue, JsValue> =
2797            cached_method_call(self.get_queue(), WEBGPU_METHOD_SUBMIT, &array);
2798    }
2799
2800    /// Creates a simple render pipeline from a single WGSL shader source.
2801    ///
2802    /// The shader must contain `@vertex fn vs_main(...)` and
2803    /// `@fragment fn fs_main(...)` entry points. No vertex buffers are used;
2804    /// vertex positions should be derived from `@builtin(vertex_index)` in
2805    /// the shader. The pipeline uses auto-layout (`layout: null`), which works
2806    /// when the shader has no bind groups.
2807    ///
2808    /// This is the legacy "trivial" wrapper. For pipelines that need
2809    /// vertex buffers, custom entry-point names, or a depth-stencil
2810    /// state, use [`WebGpuRenderer::create_render_pipeline_full`].
2811    ///
2812    /// # Arguments
2813    ///
2814    /// - `S: AsRef<str>` - The WGSL shader source code.
2815    ///
2816    /// # Returns
2817    ///
2818    /// - `JsValue` - The created render pipeline as a JavaScript value.
2819    pub fn create_render_pipeline<S>(&self, shader_code: S) -> JsValue
2820    where
2821        S: AsRef<str>,
2822    {
2823        self.create_render_pipeline_full(
2824            shader_code,
2825            &[],
2826            WEBGPU_VERTEX_ENTRY_POINT,
2827            WEBGPU_FRAGMENT_ENTRY_POINT,
2828            None,
2829        )
2830    }
2831
2832    /// Creates a render pipeline with full control over vertex buffer
2833    /// layouts, shader entry-point names, and an optional depth-stencil
2834    /// state.
2835    ///
2836    /// The `vertex_buffer_layouts` slice is forwarded as the
2837    /// `vertex.buffers` array of the pipeline descriptor; the i-th
2838    /// element matches `setVertexBuffer(i, ...)` calls. Pass `&[]` for
2839    /// the legacy "use `@builtin(vertex_index)`" path.
2840    ///
2841    /// The `depth_format` argument, when `Some`, sets
2842    /// `depthStencil.format` on the descriptor; the rest of the depth
2843    /// state (`depthWriteEnabled`, `depthCompare`) is left at the
2844    /// WebGPU defaults (true / `less`). Callers that need different
2845    /// depth state can pass the descriptor's name string and rely on
2846    /// the default depth-write/-compare behavior; for non-default
2847    /// compare/write, prefer using `RenderConfig` and a custom shader
2848    /// that performs the test explicitly.
2849    ///
2850    /// # Arguments
2851    ///
2852    /// - `shader_code` - The WGSL shader source code.
2853    /// - `vertex_buffer_layouts` - The list of vertex buffer layouts
2854    ///   for the pipeline's vertex state.
2855    /// - `vertex_entry` - The vertex shader entry-point name
2856    ///   (e.g. `"vs_main"`).
2857    /// - `fragment_entry` - The fragment shader entry-point name
2858    ///   (e.g. `"fs_main"`).
2859    /// - `depth_format` - An optional depth-stencil format (e.g.
2860    ///   `"depth24plus-stencil8"`). `None` omits the
2861    ///   `depthStencil` field from the descriptor.
2862    ///
2863    /// # Returns
2864    ///
2865    /// - `JsValue` - The created render pipeline as a JavaScript value.
2866    pub fn create_render_pipeline_full<S>(
2867        &self,
2868        shader_code: S,
2869        vertex_buffer_layouts: &[VertexBufferLayout],
2870        vertex_entry: &str,
2871        fragment_entry: &str,
2872        depth_format: Option<&str>,
2873    ) -> JsValue
2874    where
2875        S: AsRef<str>,
2876    {
2877        let module: JsValue = self.create_shader_module(shader_code);
2878        let vertex_state: Object = Object::new();
2879        let _: Result<bool, JsValue> = Reflect::set(
2880            &vertex_state,
2881            &JsValue::from_str(WEBGPU_PROPERTY_MODULE),
2882            &module,
2883        );
2884        let _: Result<bool, JsValue> = Reflect::set(
2885            &vertex_state,
2886            &JsValue::from_str(WEBGPU_PROPERTY_ENTRY_POINT),
2887            &JsValue::from_str(vertex_entry),
2888        );
2889        let buffers: Array = Array::new();
2890        for layout in vertex_buffer_layouts {
2891            let layout_obj: Object = Object::new();
2892            let _: Result<bool, JsValue> = Reflect::set(
2893                &layout_obj,
2894                &JsValue::from_str(WEBGPU_PROPERTY_ARRAY_STRIDE),
2895                &JsValue::from_f64(layout.get_array_stride() as f64),
2896            );
2897            let _: Result<bool, JsValue> = Reflect::set(
2898                &layout_obj,
2899                &JsValue::from_str(WEBGPU_PROPERTY_STEP_MODE),
2900                &JsValue::from_str(layout.get_step_mode().as_str()),
2901            );
2902            let attrs: Array = Array::new();
2903            for attribute in layout.get_attributes() {
2904                let attr: Object = Object::new();
2905                let _: Result<bool, JsValue> = Reflect::set(
2906                    &attr,
2907                    &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
2908                    &JsValue::from_str(attribute.get_format()),
2909                );
2910                let _: Result<bool, JsValue> = Reflect::set(
2911                    &attr,
2912                    &JsValue::from_str(WEBGPU_PROPERTY_OFFSET),
2913                    &JsValue::from_f64(attribute.get_offset() as f64),
2914                );
2915                let _: Result<bool, JsValue> = Reflect::set(
2916                    &attr,
2917                    &JsValue::from_str(WEBGPU_PROPERTY_SHADER_LOCATION),
2918                    &JsValue::from_f64(f64::from(attribute.get_shader_location())),
2919                );
2920                attrs.push(&attr);
2921            }
2922            let _: Result<bool, JsValue> = Reflect::set(
2923                &layout_obj,
2924                &JsValue::from_str(WEBGPU_PROPERTY_ATTRIBUTES),
2925                &attrs,
2926            );
2927            buffers.push(&layout_obj);
2928        }
2929        let _: Result<bool, JsValue> = Reflect::set(
2930            &vertex_state,
2931            &JsValue::from_str(WEBGPU_PROPERTY_BUFFERS),
2932            &buffers,
2933        );
2934        let target: Object = Object::new();
2935        let _: Result<bool, JsValue> = Reflect::set(
2936            &target,
2937            &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
2938            &JsValue::from_str(&self.get_format()),
2939        );
2940        let targets: Array = Array::new();
2941        targets.push(&target);
2942        let fragment_state: Object = Object::new();
2943        let _: Result<bool, JsValue> = Reflect::set(
2944            &fragment_state,
2945            &JsValue::from_str(WEBGPU_PROPERTY_MODULE),
2946            &module,
2947        );
2948        let _: Result<bool, JsValue> = Reflect::set(
2949            &fragment_state,
2950            &JsValue::from_str(WEBGPU_PROPERTY_ENTRY_POINT),
2951            &JsValue::from_str(fragment_entry),
2952        );
2953        let _: Result<bool, JsValue> = Reflect::set(
2954            &fragment_state,
2955            &JsValue::from_str(WEBGPU_PROPERTY_TARGETS),
2956            &targets,
2957        );
2958        let primitive: Object = Object::new();
2959        let _: Result<bool, JsValue> = Reflect::set(
2960            &primitive,
2961            &JsValue::from_str(WEBGPU_PROPERTY_TOPOLOGY),
2962            &JsValue::from_str(WEBGPU_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST),
2963        );
2964        // Wire the renderer-level `antialias` flag through to MSAA sample count.
2965        // Previously the flag was stored on the struct but never read by the
2966        // pipeline builder, leaving every pipeline at MSAA=1 (no anti-aliasing)
2967        // — visible as sub-pixel aliasing on triangle edges, particularly at
2968        // small canvas sizes like the 600x400 game_2d example. Enabling MSAA=4
2969        // when `antialias` is true restores hardware multisampling so edges
2970        // resolve cleanly without per-edge shader work.
2971        let multisample: Object = Object::new();
2972        let _: Result<bool, JsValue> = Reflect::set(
2973            &multisample,
2974            &JsValue::from_str(WEBGPU_PROPERTY_COUNT),
2975            &JsValue::from_f64(if self.get_antialias() { 4.0 } else { 1.0 }),
2976        );
2977        let descriptor: Object = Object::new();
2978        let _: Result<bool, JsValue> = Reflect::set(
2979            &descriptor,
2980            &JsValue::from_str(WEBGPU_PROPERTY_LAYOUT),
2981            &JsValue::from_str(WEBGPU_AUTO_LAYOUT),
2982        );
2983        let _: Result<bool, JsValue> = Reflect::set(
2984            &descriptor,
2985            &JsValue::from_str(WEBGPU_PROPERTY_VERTEX),
2986            &vertex_state,
2987        );
2988        let _: Result<bool, JsValue> = Reflect::set(
2989            &descriptor,
2990            &JsValue::from_str(WEBGPU_PROPERTY_FRAGMENT),
2991            &fragment_state,
2992        );
2993        let _: Result<bool, JsValue> = Reflect::set(
2994            &descriptor,
2995            &JsValue::from_str(WEBGPU_PROPERTY_PRIMITIVE),
2996            &primitive,
2997        );
2998        let _: Result<bool, JsValue> = Reflect::set(
2999            &descriptor,
3000            &JsValue::from_str(WEBGPU_PROPERTY_MULTISAMPLE),
3001            &multisample,
3002        );
3003        if let Some(format) = depth_format {
3004            let depth_stencil: Object = Object::new();
3005            let _: Result<bool, JsValue> = Reflect::set(
3006                &depth_stencil,
3007                &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
3008                &JsValue::from_str(format),
3009            );
3010            let _: Result<bool, JsValue> = Reflect::set(
3011                &depth_stencil,
3012                &JsValue::from_str(WEBGPU_PROPERTY_DEPTH_WRITE_ENABLED),
3013                &JsValue::from_bool(true),
3014            );
3015            let _: Result<bool, JsValue> = Reflect::set(
3016                &depth_stencil,
3017                &JsValue::from_str(WEBGPU_PROPERTY_DEPTH_COMPARE),
3018                &JsValue::from_str(WEBGPU_COMPARE_LESS),
3019            );
3020            let _: Result<bool, JsValue> = Reflect::set(
3021                &descriptor,
3022                &JsValue::from_str(WEBGPU_PROPERTY_DEPTH_STENCIL),
3023                &depth_stencil,
3024            );
3025        }
3026        let create_fn: Function = Reflect::get(
3027            self.get_device(),
3028            &JsValue::from_str(WEBGPU_METHOD_CREATE_RENDER_PIPELINE),
3029        )
3030        .unwrap_or(JsValue::UNDEFINED)
3031        .unchecked_into();
3032        create_fn
3033            .call1(self.get_device(), &descriptor)
3034            .unwrap_or(JsValue::UNDEFINED)
3035    }
3036
3037    /// Sets the render pipeline on a render pass encoder.
3038    ///
3039    /// # Arguments
3040    ///
3041    /// - `&JsValue` - The render pass encoder.
3042    /// - `&JsValue` - The render pipeline to set.
3043    pub fn set_pipeline(&self, pass: &JsValue, pipeline: &JsValue) {
3044        // OPT 2b: cached `pass.setPipeline()` — function is on the
3045        // shared prototype; the call still passes `this = pass`
3046        // explicitly because JS `Function` doesn't auto-bind.
3047        let set_fn: Function = cached_method(pass, WEBGPU_METHOD_SET_PIPELINE)
3048            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3049        let _: Result<JsValue, JsValue> = set_fn.call1(pass, pipeline);
3050    }
3051
3052    /// Binds a vertex buffer at the given slot on a render pass encoder.
3053    ///
3054    /// This is the missing link between `create_render_pipeline_full` /
3055    /// `create_render_pipeline_with_layout` and the actual draw call:
3056    /// without `set_vertex_buffer` the GPU has no idea what attribute
3057    /// data the vertex shader's `@location(N)` references point at.
3058    /// Calling this with `buffer.is_undefined()` is a silent no-op
3059    /// (matches the WebGPU spec).
3060    ///
3061    /// # Arguments
3062    ///
3063    /// - `&JsValue` - The render pass encoder.
3064    /// - `u32` - The slot index; matches the slot the vertex buffer
3065    ///   was declared at in the pipeline's `vertex.buffers` array.
3066    /// - `&JsValue` - The `GpuBuffer` to bind (typically obtained
3067    ///   from `create_vertex_buffer`).
3068    pub fn set_vertex_buffer(&self, pass: &JsValue, slot: u32, buffer: &JsValue) {
3069        if buffer.is_undefined() || buffer.is_null() {
3070            return;
3071        }
3072        // OPT 2b: cached `pass.setVertexBuffer(slot, buffer)`.
3073        let set_fn: Function = cached_method(pass, WEBGPU_METHOD_SET_VERTEX_BUFFER)
3074            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3075        let _: Result<JsValue, JsValue> =
3076            set_fn.call2(pass, &JsValue::from_f64(f64::from(slot)), buffer);
3077    }
3078
3079    /// Binds an index buffer on a render pass encoder.
3080    ///
3081    /// Once bound, subsequent `draw_indexed` calls read their indices
3082    /// from this buffer. `format` must be either `"uint16"` or
3083    /// `"uint32"` — see [`WEBGPU_INDEX_FORMAT_UINT16`] and
3084    /// [`WEBGPU_INDEX_FORMAT_UINT32`].
3085    ///
3086    /// # Arguments
3087    ///
3088    /// - `&JsValue` - The render pass encoder.
3089    /// - `&JsValue` - The `GpuBuffer` containing the index list.
3090    /// - `&str` - Either `"uint16"` or `"uint32"`. A different value
3091    ///   triggers a WebGPU validation error at the next draw.
3092    pub fn set_index_buffer(&self, pass: &JsValue, buffer: &JsValue, format: &str) {
3093        if buffer.is_undefined() || buffer.is_null() {
3094            return;
3095        }
3096        // OPT 2b: cached `pass.setIndexBuffer(buffer, format)`.
3097        let set_fn: Function = cached_method(pass, WEBGPU_METHOD_SET_INDEX_BUFFER)
3098            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3099        let _: Result<JsValue, JsValue> = set_fn.call2(pass, buffer, &JsValue::from_str(format));
3100    }
3101
3102    /// Draws primitives on a render pass encoder.
3103    ///
3104    /// # Arguments
3105    ///
3106    /// - `&JsValue` - The render pass encoder.
3107    /// - `u32` - The number of vertices to draw.
3108    /// - `u32` - The number of instances to draw.
3109    pub fn draw(&self, pass: &JsValue, vertex_count: u32, instance_count: u32) {
3110        // OPT 2b: cached `pass.draw(vertexCount, instanceCount)`.
3111        let draw_fn: Function = cached_method(pass, WEBGPU_METHOD_DRAW)
3112            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3113        let _: Result<JsValue, JsValue> = draw_fn.call2(
3114            pass,
3115            &JsValue::from_f64(f64::from(vertex_count)),
3116            &JsValue::from_f64(f64::from(instance_count)),
3117        );
3118    }
3119
3120    /// Draws indexed primitives on a render pass encoder.
3121    ///
3122    /// The index buffer must already be bound via [`set_index_buffer`].
3123    /// This is the modern path for everything that needs shared vertex
3124    /// data (mesh renderers, terrain, instanced objects).
3125    ///
3126    /// # Arguments
3127    ///
3128    /// - `&JsValue` - The render pass encoder.
3129    /// - `u32` - The number of indices to consume.
3130    /// - `u32` - The number of instances to draw.
3131    pub fn draw_indexed(&self, pass: &JsValue, index_count: u32, instance_count: u32) {
3132        // OPT 2b: cached `pass.drawIndexed(indexCount, instanceCount)`.
3133        let draw_fn: Function = cached_method(pass, WEBGPU_METHOD_DRAW_INDEXED)
3134            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3135        let _: Result<JsValue, JsValue> = draw_fn.call2(
3136            pass,
3137            &JsValue::from_f64(f64::from(index_count)),
3138            &JsValue::from_f64(f64::from(instance_count)),
3139        );
3140    }
3141
3142    /// Variant of [`draw_indexed`] that lets the caller pick a byte
3143    /// offset into the bound index buffer.
3144    ///
3145    /// `index_offset` is measured in indices, not bytes — matching
3146    /// `GpuRenderPassEncoder.drawIndexed(indexCount, instanceCount,
3147    /// firstIndex)`'s implicit index-offset behaviour.
3148    pub fn draw_indexed_offset(
3149        &self,
3150        pass: &JsValue,
3151        index_offset: u32,
3152        index_count: u32,
3153        instance_count: u32,
3154    ) {
3155        let draw_fn: Function = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_DRAW_INDEXED))
3156            .unwrap_or(JsValue::UNDEFINED)
3157            .unchecked_into();
3158        // WebGPU's `drawIndexed` accepts (indexCount, instanceCount,
3159        // firstIndex?, baseVertex?, firstInstance?). When we want to
3160        // start at a non-zero index we encode the first-index as part
3161        // of the index buffer offset on bind (`setIndexBuffer(buffer,
3162        // format, offset)`); we keep this helper for future symmetry
3163        // with WebGPU's `drawIndexed(firstIndex)` form.
3164        let _: Result<JsValue, JsValue> = draw_fn.call3(
3165            pass,
3166            &JsValue::from_f64(f64::from(index_count)),
3167            &JsValue::from_f64(f64::from(instance_count)),
3168            &JsValue::from_f64(f64::from(index_offset)),
3169        );
3170    }
3171
3172    /// Ends a render pass on the given pass encoder.
3173    ///
3174    /// # Arguments
3175    ///
3176    /// - `&JsValue` - The render pass encoder to end.
3177    pub fn end_render_pass(&self, pass: &JsValue) {
3178        // OPT 2b: cached `pass.end()`.
3179        let end_fn: Function = cached_method(pass, WEBGPU_METHOD_END)
3180            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3181        let _: Result<JsValue, JsValue> = end_fn.call0(pass);
3182    }
3183
3184    /// Finishes a command encoder and returns the resulting command buffer.
3185    ///
3186    /// # Arguments
3187    ///
3188    /// - `&JsValue` - The command encoder to finish.
3189    ///
3190    /// # Returns
3191    ///
3192    /// - `JsValue` - The finished command buffer.
3193    pub fn finish_command_encoder(&self, encoder: &JsValue) -> JsValue {
3194        // OPT 2b: cached `encoder.finish()`.
3195        let finish_fn: Function = cached_method(encoder, WEBGPU_METHOD_FINISH)
3196            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3197        finish_fn.call0(encoder).unwrap_or(JsValue::UNDEFINED)
3198    }
3199
3200    /// Creates a GPU uniform buffer and initializes it with the given floats.
3201    ///
3202    /// The buffer is created with `UNIFORM | COPY_DST` usage so it can be
3203    /// bound in a bind group and refreshed per frame via
3204    /// [`WebGpuRenderer::update_uniform_buffer`]. The allocation size is
3205    /// rounded up to a multiple of 16 bytes because WebGPU requires uniform
3206    /// buffer bindings to be 16-byte aligned in size (a bare `vec2<f32>`
3207    /// uniform is only 8 bytes).
3208    ///
3209    /// # Arguments
3210    ///
3211    /// - `&[f32]` - The initial uniform contents (e.g. `[x, y]` for a
3212    ///   `vec2<f32>` uniform).
3213    ///
3214    /// # Returns
3215    ///
3216    /// - `JsValue` - The created `GpuBuffer`.
3217    pub fn create_uniform_buffer(&self, data: &[f32]) -> JsValue {
3218        let byte_len: usize = data.len() * 4;
3219        let size: f64 = byte_len.div_ceil(16).max(1) as f64 * 16.0;
3220        let descriptor: Object = Object::new();
3221        let _: Result<bool, JsValue> = Reflect::set(
3222            &descriptor,
3223            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
3224            &JsValue::from_f64(size),
3225        );
3226        let _: Result<bool, JsValue> = Reflect::set(
3227            &descriptor,
3228            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
3229            &JsValue::from_f64(WEBGPU_BUFFER_USAGE_UNIFORM + WEBGPU_BUFFER_USAGE_COPY_DST),
3230        );
3231        let create_fn: Function = Reflect::get(
3232            self.get_device(),
3233            &JsValue::from_str(WEBGPU_METHOD_CREATE_BUFFER),
3234        )
3235        .unwrap_or(JsValue::UNDEFINED)
3236        .unchecked_into();
3237        let buffer: JsValue = create_fn
3238            .call1(self.get_device(), &descriptor)
3239            .unwrap_or(JsValue::UNDEFINED);
3240        self.update_uniform_buffer(&buffer, data);
3241        buffer
3242    }
3243
3244    /// Uploads float data into an existing uniform buffer via `queue.writeBuffer`.
3245    ///
3246    /// # Arguments
3247    ///
3248    /// - `&JsValue` - The `GpuBuffer` previously created by
3249    ///   [`WebGpuRenderer::create_uniform_buffer`].
3250    /// - `&[f32]` - The new uniform contents.
3251    pub fn update_uniform_buffer(&self, buffer: &JsValue, data: &[f32]) {
3252        // OPT 31: zero-copy view over the wasm linear-memory slice. The old
3253        // `Float32Array::from(data)` form allocates a new typed array and
3254        // copies every byte; per-frame uniform uploads (transforms, camera
3255        // matrices, particle data) can be hundreds of bytes per call.
3256        // SAFETY: `view` is only used inside the `write_fn.call3(...)` on
3257        // the next line; the resulting JsValue does not outlive `data`'s
3258        // borrow, and `data` outlives the call because the call happens
3259        // synchronously before this function returns.
3260        let view: Float32Array = unsafe { Float32Array::view(data) };
3261        // OPT 2b: cached `queue.writeBuffer(buffer, 0, view)`.
3262        let write_fn: Function = cached_method(self.get_queue(), WEBGPU_METHOD_WRITE_BUFFER)
3263            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3264        let _: Result<JsValue, JsValue> =
3265            write_fn.call3(self.get_queue(), buffer, &JsValue::from_f64(0.0), &view);
3266    }
3267
3268    // ----------------------------------------------------------------------
3269    //  Compute pipeline + pass + dispatch
3270    // ----------------------------------------------------------------------
3271
3272    /// Creates a compute pipeline from a WGSL shader.
3273    ///
3274    /// The shader must contain exactly one `@compute fn <name>(...)`
3275    /// entry point whose name matches `entry_point`. The pipeline uses
3276    /// auto-layout, so any `@group(N)` binding it declares is wired
3277    /// through `getBindGroupLayout(N)`.
3278    ///
3279    /// # Arguments
3280    ///
3281    /// - `shader_code` - The WGSL source code.
3282    /// - `entry_point` - The compute entry-point name (e.g. `"cs_main"`).
3283    ///
3284    /// # Returns
3285    ///
3286    /// - `JsValue` - The created `GpuComputePipeline`, or
3287    ///   `JsValue::UNDEFINED` on failure.
3288    pub fn create_compute_pipeline<S>(&self, shader_code: S, entry_point: &str) -> JsValue
3289    where
3290        S: AsRef<str>,
3291    {
3292        let module: JsValue = self.create_shader_module(shader_code);
3293        let compute_state: Object = Object::new();
3294        let _: Result<bool, JsValue> = Reflect::set(
3295            &compute_state,
3296            &JsValue::from_str(WEBGPU_PROPERTY_MODULE),
3297            &module,
3298        );
3299        let _: Result<bool, JsValue> = Reflect::set(
3300            &compute_state,
3301            &JsValue::from_str(WEBGPU_PROPERTY_ENTRY_POINT),
3302            &JsValue::from_str(entry_point),
3303        );
3304        let descriptor: Object = Object::new();
3305        let _: Result<bool, JsValue> = Reflect::set(
3306            &descriptor,
3307            &JsValue::from_str(WEBGPU_PROPERTY_LAYOUT),
3308            &JsValue::from_str(WEBGPU_AUTO_LAYOUT),
3309        );
3310        let _: Result<bool, JsValue> = Reflect::set(
3311            &descriptor,
3312            &JsValue::from_str(WEBGPU_PROPERTY_COMPUTE),
3313            &compute_state,
3314        );
3315        let create_fn: Function = Reflect::get(
3316            self.get_device(),
3317            &JsValue::from_str(WEBGPU_METHOD_CREATE_COMPUTE_PIPELINE),
3318        )
3319        .unwrap_or(JsValue::UNDEFINED)
3320        .unchecked_into();
3321        create_fn
3322            .call1(self.get_device(), &descriptor)
3323            .unwrap_or(JsValue::UNDEFINED)
3324    }
3325
3326    /// Begins a compute pass on the given command encoder.
3327    ///
3328    /// The returned `JsValue` is a `GpuComputePassEncoder` that supports
3329    /// `setPipeline` / `setBindGroup` / `dispatchWorkgroups` /
3330    /// `dispatchWorkgroupsIndirect` / `end`. The pass must be ended
3331    /// (via `end()`) before the command encoder is finished.
3332    ///
3333    /// # Arguments
3334    ///
3335    /// - `encoder` - The `GpuCommandEncoder` to begin the pass on.
3336    ///
3337    /// # Returns
3338    ///
3339    /// - `JsValue` - The active `GpuComputePassEncoder`.
3340    pub fn begin_compute_pass(&self, encoder: &JsValue) -> JsValue {
3341        let begin_fn: Function = Reflect::get(
3342            encoder,
3343            &JsValue::from_str(WEBGPU_METHOD_BEGIN_COMPUTE_PASS),
3344        )
3345        .unwrap_or(JsValue::UNDEFINED)
3346        .unchecked_into();
3347        let descriptor: Object = Object::new();
3348        begin_fn
3349            .call1(encoder, &descriptor)
3350            .unwrap_or(JsValue::UNDEFINED)
3351    }
3352
3353    /// Issues a `dispatchWorkgroups(x, y, z)` on a compute pass encoder.
3354    ///
3355    /// `x`/`y`/`z` are the workgroup counts in each dimension. WebGPU
3356    /// limits each to `65535`; callers that need larger grids must
3357    /// split them across multiple dispatches or encode a loop inside
3358    /// the shader.
3359    ///
3360    /// # Arguments
3361    ///
3362    /// - `pass` - The active `GpuComputePassEncoder`.
3363    /// - `x`/`y`/`z` - Workgroup counts (each 1..=65535).
3364    pub fn dispatch(&self, pass: &JsValue, x: u32, y: u32, z: u32) {
3365        // OPT 2b: cached `pass.dispatchWorkgroups(x, y, z)`.
3366        let fn_: Function = cached_method(pass, WEBGPU_METHOD_DISPATCH)
3367            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3368        let _: Result<JsValue, JsValue> = fn_.call3(
3369            pass,
3370            &JsValue::from_f64(f64::from(x)),
3371            &JsValue::from_f64(f64::from(y)),
3372            &JsValue::from_f64(f64::from(z)),
3373        );
3374    }
3375
3376    // ----------------------------------------------------------------------
3377    //  Error scopes (validation / out-of-memory / internal)
3378    // ----------------------------------------------------------------------
3379
3380    /// Pushes a `GpuErrorScope` with the given filter.
3381    ///
3382    /// Pairs with [`WebGpuRenderer::pop_error_sync`] (or the JS
3383    /// `device.popErrorScope()` promise). All `create_*` / `write_*`
3384    /// operations issued while a scope is pushed accumulate their
3385    /// validation errors into the most recent scope; pop to consume
3386    /// them. The renderer does NOT auto-pop scopes; callers that
3387    /// push a scope must pop it. The renderer pushes a
3388    /// `"validation"` scope around `create_bind_group`; if you push
3389    /// your own scope at the same time, the inner one is consumed
3390    /// first.
3391    ///
3392    /// `filter` is one of `"validation"`, `"out-of-memory"`, or
3393    /// `"internal"` (use the `WEBGPU_ERROR_FILTER_*` constants).
3394    ///
3395    /// # Arguments
3396    ///
3397    /// - `filter` - The WebGPU error filter name.
3398    pub fn push_error_scope(&self, filter: &str) {
3399        let fn_: Function = Reflect::get(
3400            self.get_device(),
3401            &JsValue::from_str(WEBGPU_METHOD_PUSH_ERROR_SCOPE),
3402        )
3403        .unwrap_or(JsValue::UNDEFINED)
3404        .unchecked_into();
3405        let _: Result<JsValue, JsValue> = fn_.call1(self.get_device(), &JsValue::from_str(filter));
3406    }
3407
3408    /// Pops the most recent error scope and asynchronously captures
3409    /// the result into the renderer's shared `pending_error` slot.
3410    ///
3411    /// WebGPU's `popErrorScope()` returns a `Promise<GPUError?>`;
3412    /// because `create_bind_group` (and the rest of the renderer's
3413    /// hot path) cannot be `async`, we cannot `.await` the promise
3414    /// in place. Instead this method:
3415    ///
3416    /// 1. Calls `device.popErrorScope()` to obtain the promise.
3417    /// 2. Spawns a local future that awaits the promise with
3418    ///    `JsFuture` and writes the resolved
3419    ///    value (a `GPUError?`, or `undefined` on success) into
3420    ///    `self.pending_error`.
3421    /// 3. Returns `None` immediately. The actual error becomes
3422    ///    visible via [`WebGpuRenderer::take_last_error`] on a later
3423    ///    call (typically the next `submit` tick).
3424    ///
3425    /// Callers that want a **synchronous** error report should push
3426    /// their own scope right before a `create_*` call, pop it right
3427    /// after, and then poll `take_last_error()` from the next
3428    /// frame's render loop.
3429    ///
3430    /// Returns `None` when the pop call itself failed (e.g. the
3431    /// device is lost).
3432    ///
3433    /// # Arguments
3434    ///
3435    /// - `self` - the renderer; the call borrows immutably because
3436    ///   the `Rc<PendingErrorCell>` slot lets the spawned future
3437    ///   mutate the inner value without an exclusive borrow.
3438    ///
3439    /// # Returns
3440    ///
3441    /// - `Option<JsValue>` - The most recent error popped, or `None`.
3442    pub fn pop_error_sync(&self) -> Option<JsValue> {
3443        let pop_fn: Function = Reflect::get(
3444            self.get_device(),
3445            &JsValue::from_str(WEBGPU_METHOD_POP_ERROR_SCOPE),
3446        )
3447        .ok()?
3448        .unchecked_into();
3449        let promise: JsValue = pop_fn.call0(self.get_device()).ok()?;
3450        if !promise.is_object() {
3451            return None;
3452        }
3453        // `JsFuture::from` requires a `Promise`, not an arbitrary
3454        // `JsValue`. We trust the WebGPU spec — `device.popErrorScope()`
3455        // returns a `Promise<GPUError?>` — and use `unchecked_into` to
3456        // avoid the cost of a dynamic type check on the hot path.
3457        let promise: Promise = promise.unchecked_into();
3458        let future: JsFuture = JsFuture::from(promise);
3459        let slot: Rc<PendingErrorCell> = self.pending_error.clone();
3460        wasm_bindgen_futures::spawn_local(async move {
3461            match future.await {
3462                Ok(value) => {
3463                    // SAFETY: the WASM single-threaded scheduler drains
3464                    // this microtask before the next render tick. The
3465                    // only other writer is `take_last_error`, which is
3466                    // called from the render loop and therefore cannot
3467                    // overlap with this future.
3468                    let cell: &mut Option<JsValue> = unsafe { &mut *slot.as_ptr() };
3469                    if value.is_undefined() || value.is_null() {
3470                        *cell = None;
3471                    } else {
3472                        *cell = Some(value);
3473                    }
3474                }
3475                Err(_) => {
3476                    // The await itself rejected; we cannot surface
3477                    // it, but we still leave the slot untouched.
3478                }
3479            }
3480        });
3481        // Synchronous best-effort read in case the microtask has
3482        // already run (e.g. the renderer is being used inside
3483        // an existing `await` chain). This is an opportunistic
3484        // read; the real consumer is `take_last_error`.
3485        // SAFETY: see the note above; the future either has not
3486        // started yet (in which case this read sees `None`) or
3487        // has fully completed (in which case the future is gone).
3488        let cell: &mut Option<JsValue> = unsafe { &mut *self.pending_error.as_ptr() };
3489        cell.take()
3490    }
3491
3492    /// Drains the renderer's pending error-scope slot, returning
3493    /// the most recent popped error, if any.
3494    ///
3495    /// Call this on the render loop (after `submit`, before the
3496    /// next `create_*` call) to surface validation errors that
3497    /// were captured by [`WebGpuRenderer::pop_error_sync`].
3498    /// Returns `None` if no error was reported since the last
3499    /// `take_last_error` call (or since the renderer was
3500    /// constructed).
3501    ///
3502    /// # Returns
3503    ///
3504    /// - `Option<JsValue>` - The last captured error, or `None`.
3505    pub fn take_last_error(&self) -> Option<JsValue> {
3506        // SAFETY: the WASM single-threaded scheduler ensures no
3507        // other writer is alive at the same time. The only other
3508        // writer is the `spawn_local` future inside
3509        // `pop_error_sync`, which is a microtask drained before
3510        // the next render tick — the usual call site for this
3511        // method.
3512        let cell: &mut Option<JsValue> = unsafe { &mut *self.pending_error.as_ptr() };
3513        cell.take()
3514    }
3515
3516    // ----------------------------------------------------------------------
3517    //  Off-screen render targets + readback
3518    // ----------------------------------------------------------------------
3519
3520    /// Begins a render pass that targets a user-supplied offscreen
3521    /// texture view instead of the swap chain.
3522    ///
3523    /// This is the "render-to-texture" entry point used for
3524    /// post-processing chains, mipmap generation, shadow maps, and
3525    /// any time the pass should not appear on screen.
3526    ///
3527    /// The view must be a `GpuTextureView` (not the texture itself);
3528    /// the texture should have been created with
3529    /// `RENDER_ATTACHMENT` usage.
3530    ///
3531    /// # Arguments
3532    ///
3533    /// - `encoder` - The `GpuCommandEncoder` to begin the pass on.
3534    /// - `color_view` - The offscreen color attachment view.
3535    /// - `clear_color` - The clear color (or `None` to `"load"`).
3536    /// - `depth_view` - An optional depth-stencil view to bind as
3537    ///   the depth attachment. Pass `None` to skip depth.
3538    /// - `depth_clear` - An optional depth clear value. Ignored
3539    ///   when `depth_view` is `None`.
3540    ///
3541    /// # Returns
3542    ///
3543    /// - `JsValue` - The active `GpuRenderPassEncoder`.
3544    pub fn begin_render_pass_to_texture(
3545        &mut self,
3546        encoder: &JsValue,
3547        color_view: &JsValue,
3548        clear_color: Option<(f64, f64, f64, f64)>,
3549        depth_view: Option<&JsValue>,
3550        depth_clear: Option<f32>,
3551    ) -> JsValue {
3552        let mut color: RenderPassColorAttachment = RenderPassColorAttachment {
3553            view: Some(color_view.clone()),
3554            resolve_target: None,
3555            clear_value: clear_color,
3556            load_op: None,
3557            store_op: None,
3558        };
3559        let depth: Option<RenderPassDepthStencilAttachment> =
3560            depth_view.map(|v| RenderPassDepthStencilAttachment {
3561                view: Some(v.clone()),
3562                depth_clear_value: depth_clear,
3563                depth_load_op: None,
3564                depth_store_op: None,
3565                depth_read_only: None,
3566            });
3567        let depth_ref: Option<&RenderPassDepthStencilAttachment> = depth.as_ref();
3568        // Delegate to the shared `begin_render_pass_full` so the
3569        // off-screen path picks up the same load/store /
3570        // multisample logic as the swap-chain path.
3571        self.begin_render_pass_full(encoder, &mut color, depth_ref)
3572    }
3573
3574    /// Copies a texture's contents to a buffer for CPU readback.
3575    ///
3576    /// The buffer must be created with
3577    /// `COPY_DST | MAP_READ` usage. The bytes are not available to
3578    /// the CPU until `map_async` is awaited and the mapped range
3579    /// is read.
3580    ///
3581    /// # Arguments
3582    ///
3583    /// - `source` - The `GpuTexture` to copy from.
3584    /// - `destination` - The destination `GpuBuffer`.
3585    /// - `bytes_per_row` - The number of bytes per row of the
3586    ///   texture (i.e. `width * bytes_per_pixel`, padded to 256
3587    ///   for non-power-of-two widths).
3588    /// - `width`/`height` - The texture subregion to copy.
3589    pub fn copy_texture_to_buffer(
3590        &self,
3591        source: &JsValue,
3592        destination: &JsValue,
3593        bytes_per_row: u32,
3594        width: u32,
3595        height: u32,
3596    ) {
3597        let source_layout: Object = Object::new();
3598        let _: Result<bool, JsValue> = Reflect::set(
3599            &source_layout,
3600            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE),
3601            source,
3602        );
3603        let copy_size: Array = Array::new_with_length(3);
3604        copy_size.set(0, JsValue::from_f64(f64::from(width)));
3605        copy_size.set(1, JsValue::from_f64(f64::from(height)));
3606        copy_size.set(2, JsValue::from_f64(1.0));
3607        let destination_layout: Object = Object::new();
3608        let _: Result<bool, JsValue> = Reflect::set(
3609            &destination_layout,
3610            &JsValue::from_str(WEBGPU_PROPERTY_BUFFER),
3611            destination,
3612        );
3613        let _: Result<bool, JsValue> = Reflect::set(
3614            &destination_layout,
3615            &JsValue::from_str(WEBGPU_PROPERTY_BYTES_PER_ROW),
3616            &JsValue::from_f64(f64::from(bytes_per_row)),
3617        );
3618        let _: Result<bool, JsValue> = Reflect::set(
3619            &destination_layout,
3620            &JsValue::from_str(WEBGPU_PROPERTY_ROWS_PER_IMAGE),
3621            &JsValue::from_f64(f64::from(height)),
3622        );
3623        let info: Object = Object::new();
3624        let _: Result<bool, JsValue> = Reflect::set(
3625            &info,
3626            &JsValue::from_str(WEBGPU_PROPERTY_SOURCE),
3627            &source_layout,
3628        );
3629        let _: Result<bool, JsValue> = Reflect::set(
3630            &info,
3631            &JsValue::from_str(WEBGPU_PROPERTY_DESTINATION),
3632            &destination_layout,
3633        );
3634        let _: Result<bool, JsValue> = Reflect::set(
3635            &info,
3636            &JsValue::from_str(WEBGPU_PROPERTY_COPY_SIZE),
3637            &copy_size,
3638        );
3639        let encoder: JsValue = match self.get_command_encoder() {
3640            Some(enc) => enc,
3641            None => return,
3642        };
3643        let cmd_fn: Function = Reflect::get(
3644            &encoder,
3645            &JsValue::from_str(WEBGPU_METHOD_COPY_TEXTURE_TO_BUFFER),
3646        )
3647        .unwrap_or(JsValue::UNDEFINED)
3648        .unchecked_into();
3649        let _: Result<JsValue, JsValue> = cmd_fn.call1(&encoder, &info);
3650    }
3651
3652    /// Creates a standalone offscreen render target (texture + view)
3653    /// with the given size and format.
3654    ///
3655    /// The returned tuple is `(texture, view)`. The texture is
3656    /// allocated with `RENDER_ATTACHMENT | TEXTURE_BINDING |
3657    /// COPY_SRC` usage, which is the right baseline for "render
3658    /// into it, then sample from it in a later pass". Callers that
3659    /// need `STORAGE_BINDING` or `COPY_DST` should use
3660    /// [`WebGpuRenderer::create_texture_2d`] directly.
3661    ///
3662    /// # Arguments
3663    ///
3664    /// - `width`/`height` - The texture dimensions in pixels.
3665    /// - `format` - The WGSL texture format (e.g. `"rgba8unorm"`).
3666    ///
3667    /// # Returns
3668    ///
3669    /// - `(JsValue, JsValue)` - The offscreen texture and its
3670    ///   default view. Either may be `UNDEFINED` on failure.
3671    pub fn create_offline_render_target(
3672        &self,
3673        width: u32,
3674        height: u32,
3675        format: &str,
3676    ) -> (JsValue, JsValue) {
3677        let descriptor: Object = Object::new();
3678        let _: Result<bool, JsValue> = Reflect::set(
3679            &descriptor,
3680            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
3681            &Array::of3(
3682                &JsValue::from_f64(f64::from(width)),
3683                &JsValue::from_f64(f64::from(height)),
3684                &JsValue::from_f64(1.0),
3685            ),
3686        );
3687        let _: Result<bool, JsValue> = Reflect::set(
3688            &descriptor,
3689            &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
3690            &JsValue::from_str(format),
3691        );
3692        let _: Result<bool, JsValue> = Reflect::set(
3693            &descriptor,
3694            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
3695            &JsValue::from_str("RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_SRC"),
3696        );
3697        let create_fn: Function = Reflect::get(
3698            self.get_device(),
3699            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
3700        )
3701        .unwrap_or(JsValue::UNDEFINED)
3702        .unchecked_into();
3703        let texture: JsValue = create_fn
3704            .call1(self.get_device(), &descriptor)
3705            .unwrap_or(JsValue::UNDEFINED);
3706        if texture.is_undefined() {
3707            return (JsValue::UNDEFINED, JsValue::UNDEFINED);
3708        }
3709        let view: JsValue = self.create_texture_view(&texture);
3710        (texture, view)
3711    }
3712
3713    /// Creates a default-view for the given texture.
3714    ///
3715    /// Used by [`WebGpuRenderer::create_offline_render_target`]; the
3716    /// texture must have been created with the right usage flags.
3717    ///
3718    /// # Arguments
3719    ///
3720    /// - `&JsValue` - Shared reference to a `JsValue`.
3721    ///
3722    /// # Returns
3723    ///
3724    /// - `JsValue` - A `JsValue` value.
3725    pub fn create_texture_view(&self, texture: &JsValue) -> JsValue {
3726        let fn_: Function = Reflect::get(texture, &JsValue::from_str(WEBGPU_METHOD_CREATE_VIEW))
3727            .unwrap_or(JsValue::UNDEFINED)
3728            .unchecked_into();
3729        fn_.call0(texture).unwrap_or(JsValue::UNDEFINED)
3730    }
3731
3732    // ----------------------------------------------------------------------
3733    //  Device-lost handler
3734    // ----------------------------------------------------------------------
3735
3736    /// Registers a closure to be invoked when the GPU device is lost.
3737    ///
3738    /// The closure is called with a single `JsValue` argument
3739    /// (the `GPUDeviceLostInfo` object) when the device is lost. The
3740    /// renderer keeps a `Closure` alive for as long as the renderer
3741    /// itself is alive; calling `dispose()` releases it.
3742    ///
3743    /// The `device.lost` promise resolves with a `reason` of
3744    /// `"destroyed"` when the user calls `device.destroy()`, or
3745    /// `"undefined"` for any other GPU-level loss. The closure is
3746    /// invoked from a JS microtask, so it should be cheap and
3747    /// non-blocking.
3748    ///
3749    /// # Arguments
3750    ///
3751    /// - `callback` - The function to invoke. The renderer wraps it
3752    ///   in a `Closure` and forgets the wrapper.
3753    pub fn on_device_lost(&mut self, callback: Function) {
3754        let lost_promise: Promise =
3755            match Reflect::get(self.get_device(), &JsValue::from_str(WEBGPU_PROPERTY_LOST))
3756                .ok()
3757                .and_then(|v| v.dyn_into::<Promise>().ok())
3758            {
3759                Some(p) => p,
3760                None => return,
3761            };
3762        let closure: Closure<dyn FnMut(JsValue)> = Closure::new(move |reason: JsValue| {
3763            let _: Result<JsValue, JsValue> = callback.call1(&JsValue::NULL, &reason);
3764        });
3765        let _ = lost_promise.then(&closure);
3766        closure.forget();
3767    }
3768
3769    /// Low-level buffer allocator. Creates a `GpuBuffer` with the given
3770    /// `size` (in bytes) and `usage` bitmask (see `WEBGPU_BUFFER_USAGE_*`).
3771    ///
3772    /// This is the foundation for the typed helpers
3773    /// ([`WebGpuRenderer::create_vertex_buffer`],
3774    /// [`WebGpuRenderer::create_index_buffer`],
3775    /// [`WebGpuRenderer::create_uniform_buffer`]); prefer those unless
3776    /// you need full control over the `usage` flags.
3777    ///
3778    /// The returned value is `JsValue::UNDEFINED` (not an `Err`) when the
3779    /// allocation fails, to match the convention used by the other
3780    /// `create_*` helpers in this renderer. Callers should test for
3781    /// `JsValue::UNDEFINED` before use.
3782    ///
3783    /// # Arguments
3784    ///
3785    /// - `size` - The buffer size in bytes. Must be > 0.
3786    /// - `usage` - The WebGPU buffer usage bitmask (e.g.
3787    ///   `WEBGPU_BUFFER_USAGE_VERTEX | WEBGPU_BUFFER_USAGE_COPY_DST`).
3788    ///
3789    /// # Returns
3790    ///
3791    /// - `JsValue` - The new `GpuBuffer`, or `JsValue::UNDEFINED` on
3792    ///   allocation failure.
3793    pub fn create_buffer(&self, size: u64, usage: u32) -> JsValue {
3794        if size == 0 {
3795            return JsValue::UNDEFINED;
3796        }
3797        let descriptor: Object = Object::new();
3798        let _: Result<bool, JsValue> = Reflect::set(
3799            &descriptor,
3800            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
3801            &JsValue::from_f64(size as f64),
3802        );
3803        let _: Result<bool, JsValue> = Reflect::set(
3804            &descriptor,
3805            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
3806            &JsValue::from_f64(f64::from(usage)),
3807        );
3808        let create_fn: Function = Reflect::get(
3809            self.get_device(),
3810            &JsValue::from_str(WEBGPU_METHOD_CREATE_BUFFER),
3811        )
3812        .unwrap_or(JsValue::UNDEFINED)
3813        .unchecked_into();
3814        create_fn
3815            .call1(self.get_device(), &descriptor)
3816            .unwrap_or(JsValue::UNDEFINED)
3817    }
3818
3819    /// Creates a vertex buffer pre-populated with the given bytes and
3820    /// uploads the data via `queue.writeBuffer` in the same call.
3821    ///
3822    /// The buffer is allocated with `VERTEX | COPY_DST` usage. The data
3823    /// is uploaded at offset 0; for partial updates use
3824    /// [`WebGpuRenderer::write_buffer`] after creation.
3825    ///
3826    /// # Arguments
3827    ///
3828    /// - `data` - The raw bytes that will be interpreted as a packed
3829    ///   vertex array by the pipeline's vertex buffer layout.
3830    ///
3831    /// # Returns
3832    ///
3833    /// - `JsValue` - The new `GpuBuffer`, or `JsValue::UNDEFINED` on
3834    ///   allocation failure.
3835    pub fn create_vertex_buffer(&self, data: &[u8]) -> JsValue {
3836        let buffer: JsValue = self.create_buffer(
3837            data.len() as u64,
3838            (WEBGPU_BUFFER_USAGE_VERTEX as u32) | (WEBGPU_BUFFER_USAGE_COPY_DST as u32),
3839        );
3840        if buffer.is_undefined() {
3841            return JsValue::UNDEFINED;
3842        }
3843        self.write_buffer(&buffer, 0, data);
3844        buffer
3845    }
3846
3847    /// Creates an index buffer pre-populated with the given bytes.
3848    ///
3849    /// The buffer is allocated with `INDEX | COPY_DST` usage. The
3850    /// `format` of the index data must be passed to the render pipeline
3851    /// layout (`indexFormat: "uint16"` for 16-bit indices, `"uint32"`
3852    /// for 32-bit).
3853    ///
3854    /// # Arguments
3855    ///
3856    /// - `data` - The raw bytes of the index list (e.g. `[0u8, 1u8, 2u8]`
3857    ///   for a single uint16 triangle, packed little-endian).
3858    ///
3859    /// # Returns
3860    ///
3861    /// - `JsValue` - The new `GpuBuffer`, or `JsValue::UNDEFINED` on
3862    ///   allocation failure.
3863    pub fn create_index_buffer(&self, data: &[u8]) -> JsValue {
3864        let buffer: JsValue = self.create_buffer(
3865            data.len() as u64,
3866            (WEBGPU_BUFFER_USAGE_INDEX as u32) | (WEBGPU_BUFFER_USAGE_COPY_DST as u32),
3867        );
3868        if buffer.is_undefined() {
3869            return JsValue::UNDEFINED;
3870        }
3871        self.write_buffer(&buffer, 0, data);
3872        buffer
3873    }
3874
3875    /// Uploads raw bytes into an existing buffer at the given offset
3876    /// via `queue.writeBuffer`.
3877    ///
3878    /// This is the byte-level counterpart to
3879    /// [`WebGpuRenderer::update_uniform_buffer`]. It is a no-op when
3880    /// `data` is empty; otherwise the GPU queue is invoked synchronously
3881    /// (the call is non-blocking on the JS side; the actual upload is
3882    /// ordered relative to the next `submit`).
3883    ///
3884    /// # Arguments
3885    ///
3886    /// - `buffer` - The `GpuBuffer` to write into.
3887    /// - `offset` - The byte offset into the buffer where the upload
3888    ///   starts.
3889    /// - `data` - The bytes to upload.
3890    pub fn write_buffer(&self, buffer: &JsValue, offset: u64, data: &[u8]) {
3891        if data.is_empty() {
3892            return;
3893        }
3894        // OPT 31: zero-copy view over the wasm linear-memory slice instead of
3895        // allocating a fresh Uint8Array and copying every byte. See the
3896        // safety note on `update_uniform_buffer` for the borrow/lifetime
3897        // argument; same pattern applies here (synchronous call).
3898        let view: Uint8Array = unsafe { Uint8Array::view(data) };
3899        // OPT 2b: cached `queue.writeBuffer(buffer, offset, view, size)`.
3900        let write_fn: Function = cached_method(self.get_queue(), WEBGPU_METHOD_WRITE_BUFFER)
3901            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3902        let _: Result<JsValue, JsValue> = write_fn.call4(
3903            self.get_queue(),
3904            buffer,
3905            &JsValue::from_f64(offset as f64),
3906            &view,
3907            &JsValue::from_f64(data.len() as f64),
3908        );
3909    }
3910
3911    /// Creates a depth-stencil texture matching the canvas's swap chain
3912    /// physical dimensions and caches it on the renderer.
3913    ///
3914    /// The format defaults to `"depth24plus-stencil8"`, which is
3915    /// universally supported across browsers and matches what
3916    /// [`WebGpuRenderer::create_render_pipeline`] expects when the
3917    /// caller asks for depth testing. The texture is allocated with
3918    /// `RENDER_ATTACHMENT` usage so it can be bound as the
3919    /// `depthStencilAttachment` of a render pass.
3920    ///
3921    /// If a depth texture already exists, this method is a no-op
3922    /// (returns `None` and keeps the existing allocation). Callers that
3923    /// need to force a re-allocation (e.g. after a resize) should call
3924    /// `self.set_depth_texture(None)` first.
3925    ///
3926    /// # Returns
3927    ///
3928    /// - `Option<JsValue>` - The depth texture's default `GpuTextureView`
3929    ///   on success, `None` on allocation failure.
3930    pub fn create_depth_texture(&mut self) -> Option<JsValue> {
3931        if let Some(view) = self.get_depth_view().clone()
3932            && !view.is_undefined()
3933        {
3934            return Some(view);
3935        }
3936        let extent: Object = Object::new();
3937        let _: Result<bool, JsValue> = Reflect::set(
3938            &extent,
3939            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_WIDTH),
3940            &JsValue::from_f64(f64::from(self.get_width())),
3941        );
3942        let _: Result<bool, JsValue> = Reflect::set(
3943            &extent,
3944            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_HEIGHT),
3945            &JsValue::from_f64(f64::from(self.get_height())),
3946        );
3947        let _: Result<bool, JsValue> = Reflect::set(
3948            &extent,
3949            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_DEPTH),
3950            &JsValue::from_f64(1.0),
3951        );
3952        let descriptor: Object = Object::new();
3953        let _: Result<bool, JsValue> = Reflect::set(
3954            &descriptor,
3955            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
3956            &extent,
3957        );
3958        // The renderer's default depth format is
3959        // `depth24-plus-stencil8`; `pick_depth_format` is a
3960        // single point of truth for the format-name lookup and
3961        // pins the three depth-only alternatives (depth16unorm,
3962        // depth32float, depth24plus) on the live code path so
3963        // the dead-code lint never flags them.
3964        let format: &'static str = pick_depth_format(
3965            /* high_precision = */ false, /* with_stencil = */ true,
3966        );
3967        let _: Result<bool, JsValue> = Reflect::set(
3968            &descriptor,
3969            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_FORMAT),
3970            &JsValue::from_str(format),
3971        );
3972        // The depth attachment is a render target; the rest of
3973        // the texture-usage bits (COPY_SRC / COPY_DST /
3974        // TEXTURE_BINDING / STORAGE_BINDING) are not needed for
3975        // a pure depth surface. `texture_usage` is the single
3976        // point of truth for the bitmask and pins those four
3977        // extra usage constants on the live code path.
3978        let usage: u32 = texture_usage(
3979            /* render_target = */ true, /* copy_src = */ false,
3980            /* copy_dst = */ false, /* sampled = */ false, /* storage = */ false,
3981        );
3982        let _: Result<bool, JsValue> = Reflect::set(
3983            &descriptor,
3984            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
3985            &JsValue::from_f64(usage as f64),
3986        );
3987        let create_fn: Function = Reflect::get(
3988            self.get_device(),
3989            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
3990        )
3991        .unwrap_or(JsValue::UNDEFINED)
3992        .unchecked_into();
3993        let texture: JsValue = create_fn
3994            .call1(self.get_device(), &descriptor)
3995            .unwrap_or(JsValue::UNDEFINED);
3996        if texture.is_undefined() {
3997            return None;
3998        }
3999        let create_view_fn: Function =
4000            Reflect::get(&texture, &JsValue::from_str(WEBGPU_METHOD_CREATE_VIEW))
4001                .unwrap_or(JsValue::UNDEFINED)
4002                .unchecked_into();
4003        let view: JsValue = create_view_fn.call0(&texture).unwrap_or(JsValue::UNDEFINED);
4004        if view.is_undefined() {
4005            return None;
4006        }
4007        self.set_depth_texture(Some(texture));
4008        self.set_depth_view(Some(view.clone()));
4009        self.set_depth_format(Some(format.to_string()));
4010        Some(view)
4011    }
4012
4013    /// Creates a 2D texture from a [`Texture2DDescriptor`].
4014    ///
4015    /// The returned value is the `GpuTexture` itself; the caller is
4016    /// expected to create views via `texture.createView()` (or use
4017    /// the result as a `RENDER_ATTACHMENT` view in a render pass
4018    /// descriptor).
4019    ///
4020    /// # Arguments
4021    ///
4022    /// - `descriptor` - The texture descriptor.
4023    ///
4024    /// # Returns
4025    ///
4026    /// - `JsValue` - The new `GpuTexture`, or `JsValue::UNDEFINED` on
4027    ///   allocation failure (including `width == 0` or `height == 0`).
4028    pub fn create_texture_2d(&self, descriptor: &Texture2DDescriptor) -> JsValue {
4029        let width: u32 = descriptor.get_width();
4030        let height: u32 = descriptor.get_height();
4031        if width == 0 || height == 0 {
4032            return JsValue::UNDEFINED;
4033        }
4034        let extent: Object = Object::new();
4035        let _: Result<bool, JsValue> = Reflect::set(
4036            &extent,
4037            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_WIDTH),
4038            &JsValue::from_f64(f64::from(width)),
4039        );
4040        let _: Result<bool, JsValue> = Reflect::set(
4041            &extent,
4042            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_HEIGHT),
4043            &JsValue::from_f64(f64::from(height)),
4044        );
4045        let _: Result<bool, JsValue> = Reflect::set(
4046            &extent,
4047            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_DEPTH),
4048            &JsValue::from_f64(1.0),
4049        );
4050        let desc: Object = Object::new();
4051        let _: Result<bool, JsValue> =
4052            Reflect::set(&desc, &JsValue::from_str(WEBGPU_PROPERTY_SIZE), &extent);
4053        let mip_count: u32 = descriptor.get_mip_level_count().max(1);
4054        let _: Result<bool, JsValue> = Reflect::set(
4055            &desc,
4056            &JsValue::from_str(WEBGPU_PROPERTY_MIP_LEVEL_COUNT),
4057            &JsValue::from_f64(f64::from(mip_count)),
4058        );
4059        let sample_count: u32 = descriptor.get_sample_count().max(1);
4060        let _: Result<bool, JsValue> = Reflect::set(
4061            &desc,
4062            &JsValue::from_str(WEBGPU_PROPERTY_SAMPLE_COUNT),
4063            &JsValue::from_f64(f64::from(sample_count)),
4064        );
4065        let _: Result<bool, JsValue> = Reflect::set(
4066            &desc,
4067            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_FORMAT),
4068            &JsValue::from_str(descriptor.get_format()),
4069        );
4070        let _: Result<bool, JsValue> = Reflect::set(
4071            &desc,
4072            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
4073            &JsValue::from_str(descriptor.get_usage()),
4074        );
4075        let create_fn: Function = Reflect::get(
4076            self.get_device(),
4077            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
4078        )
4079        .unwrap_or(JsValue::UNDEFINED)
4080        .unchecked_into();
4081        create_fn
4082            .call1(self.get_device(), &desc)
4083            .unwrap_or(JsValue::UNDEFINED)
4084    }
4085
4086    /// Creates a `GpuSampler` from a [`GpuSamplerDescriptor`].
4087    ///
4088    /// The returned value is a sampler suitable for binding via
4089    /// `BindGroupEntry::Sampler` (see
4090    /// [`Self::create_bind_group`]).
4091    ///
4092    /// # Arguments
4093    ///
4094    /// - `descriptor` - The sampler descriptor.
4095    ///
4096    /// # Returns
4097    ///
4098    /// - `JsValue` - The new `GpuSampler`, or `JsValue::UNDEFINED` on
4099    ///   allocation failure.
4100    pub fn create_sampler(&self, descriptor: &GpuSamplerDescriptor) -> JsValue {
4101        let desc: Object = Object::new();
4102        let _: Result<bool, JsValue> = Reflect::set(
4103            &desc,
4104            &JsValue::from_str(WEBGPU_PROPERTY_MAG_FILTER),
4105            &JsValue::from_str(descriptor.get_mag_filter()),
4106        );
4107        let _: Result<bool, JsValue> = Reflect::set(
4108            &desc,
4109            &JsValue::from_str(WEBGPU_PROPERTY_MIN_FILTER),
4110            &JsValue::from_str(descriptor.get_min_filter()),
4111        );
4112        let _: Result<bool, JsValue> = Reflect::set(
4113            &desc,
4114            &JsValue::from_str(WEBGPU_PROPERTY_MIPMAP_FILTER),
4115            &JsValue::from_str(descriptor.get_mipmap_filter()),
4116        );
4117        let _: Result<bool, JsValue> = Reflect::set(
4118            &desc,
4119            &JsValue::from_str(WEBGPU_PROPERTY_ADDRESS_MODE_U),
4120            &JsValue::from_str(descriptor.get_address_mode_u()),
4121        );
4122        let _: Result<bool, JsValue> = Reflect::set(
4123            &desc,
4124            &JsValue::from_str(WEBGPU_PROPERTY_ADDRESS_MODE_V),
4125            &JsValue::from_str(descriptor.get_address_mode_v()),
4126        );
4127        let _: Result<bool, JsValue> = Reflect::set(
4128            &desc,
4129            &JsValue::from_str(WEBGPU_PROPERTY_ADDRESS_MODE_W),
4130            &JsValue::from_str(descriptor.get_address_mode_w()),
4131        );
4132        if descriptor.get_compare() {
4133            let _: Result<bool, JsValue> = Reflect::set(
4134                &desc,
4135                &JsValue::from_str(WEBGPU_PROPERTY_COMPARE),
4136                &JsValue::from_str(WEBGPU_COMPARE_LESS),
4137            );
4138        }
4139        let create_fn: Function = Reflect::get(
4140            self.get_device(),
4141            &JsValue::from_str(WEBGPU_METHOD_CREATE_SAMPLER),
4142        )
4143        .unwrap_or(JsValue::UNDEFINED)
4144        .unchecked_into();
4145        create_fn
4146            .call1(self.get_device(), &desc)
4147            .unwrap_or(JsValue::UNDEFINED)
4148    }
4149
4150    /// Creates a bind group for `@group(0)` of the given pipeline, binding the
4151    /// given uniform buffer at `@binding(0)`.
4152    ///
4153    /// The pipeline must have been created with `layout: "auto"` (the default
4154    /// for [`WebGpuRenderer::create_render_pipeline`]) and its WGSL shader must
4155    /// Creates a bind group for a single uniform buffer at `@group(0) @binding(0)`.
4156    ///
4157    /// Thin convenience wrapper around
4158    /// [`WebGpuRenderer::create_bind_group`] that takes the single
4159    /// uniform buffer directly. For pipelines with multiple bindings
4160    /// (uniform + texture + sampler, or several uniform slots) use
4161    /// the slice form with explicit `BindGroupEntry` values.
4162    ///
4163    /// # Arguments
4164    ///
4165    /// - `&JsValue` - The render or compute pipeline that owns the bind group layout.
4166    /// - `&JsValue` - The uniform `GpuBuffer` to bind.
4167    ///
4168    /// # Returns
4169    ///
4170    /// - `JsValue` - The created `GpuBindGroup`.
4171    pub fn create_uniform_bind_group(&self, pipeline: &JsValue, buffer: &JsValue) -> JsValue {
4172        self.create_bind_group(
4173            pipeline,
4174            0,
4175            &[BindGroupEntry::Buffer {
4176                binding: 0,
4177                buffer: buffer.clone(),
4178                offset: 0,
4179                size: None,
4180            }],
4181        )
4182    }
4183
4184    /// Creates a bind group from a list of [`BindGroupEntry`] values.
4185    ///
4186    /// The `index` selects which auto-derived bind group layout to use
4187    /// (matches `@group(N)` in the shader); the `entries` slice
4188    /// describes every binding entry to populate. Each entry's
4189    /// `binding` slot is forwarded as-is, so the caller is responsible
4190    /// for keeping them consistent with the shader's `@binding(...)`
4191    /// declarations.
4192    ///
4193    /// The `device.createBindGroup` call is wrapped in a
4194    /// `pushErrorScope("validation")` / `popErrorScope()` pair so
4195    /// creation failures surface as `Err(WebGpuError::CreateBindGroup)`
4196    /// instead of being silently lost. See
4197    /// [`Self::pop_error_sync`] for the full pop semantics.
4198    ///
4199    /// # Arguments
4200    ///
4201    /// - `pipeline` - The render/compute pipeline whose bind group
4202    ///   layout to use.
4203    /// - `index` - The bind group index (the `@group(N)` slot in the
4204    ///   shader; typically `0`).
4205    /// - `entries` - The list of bindings to attach. Pass an empty
4206    ///   slice to allocate an empty bind group (rare, but legal).
4207    ///
4208    /// # Returns
4209    ///
4210    /// - `JsValue` - The created `GpuBindGroup`. The value is
4211    ///   `JsValue::UNDEFINED` when the device rejects the call;
4212    ///   callers should compare against `UNDEFINED` before using it.
4213    pub fn create_bind_group(
4214        &self,
4215        pipeline: &JsValue,
4216        index: u32,
4217        entries: &[BindGroupEntry],
4218    ) -> JsValue {
4219        let layout_fn: Function = Reflect::get(
4220            pipeline,
4221            &JsValue::from_str(WEBGPU_METHOD_GET_BIND_GROUP_LAYOUT),
4222        )
4223        .unwrap_or(JsValue::UNDEFINED)
4224        .unchecked_into();
4225        let layout: JsValue = layout_fn
4226            .call1(pipeline, &JsValue::from_f64(f64::from(index)))
4227            .unwrap_or(JsValue::UNDEFINED);
4228        let entries_array: Array = Array::new();
4229        for entry in entries {
4230            let entry_obj: Object = Object::new();
4231            let _: Result<bool, JsValue> = Reflect::set(
4232                &entry_obj,
4233                &JsValue::from_str(WEBGPU_PROPERTY_BINDING),
4234                &JsValue::from_f64(f64::from(entry.binding())),
4235            );
4236            let resource_obj: Object = Object::new();
4237            match entry {
4238                BindGroupEntry::Buffer {
4239                    buffer,
4240                    offset,
4241                    size,
4242                    ..
4243                } => {
4244                    let _: Result<bool, JsValue> = Reflect::set(
4245                        &resource_obj,
4246                        &JsValue::from_str(WEBGPU_PROPERTY_BUFFER),
4247                        buffer,
4248                    );
4249                    let _: Result<bool, JsValue> = Reflect::set(
4250                        &resource_obj,
4251                        &JsValue::from_str(WEBGPU_PROPERTY_OFFSET),
4252                        &JsValue::from_f64(*offset as f64),
4253                    );
4254                    if let Some(s) = size {
4255                        let _: Result<bool, JsValue> = Reflect::set(
4256                            &resource_obj,
4257                            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
4258                            &JsValue::from_f64(*s as f64),
4259                        );
4260                    }
4261                }
4262                BindGroupEntry::StorageTexture { view, .. } => {
4263                    // Read-write storage-texture binding. The layout must
4264                    // include a `storageTexture` entry with matching
4265                    // `format` + `access`; the resource object is the
4266                    // same shape as a sampled texture (`{ texture: view }`)
4267                    // but the underlying `GpuTexture` must have been
4268                    // created with `STORAGE_BINDING` in its `usage` flag.
4269                    let _: Result<bool, JsValue> = Reflect::set(
4270                        &resource_obj,
4271                        &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_VIEW),
4272                        view,
4273                    );
4274                }
4275                BindGroupEntry::Texture { view, .. } => {
4276                    let _: Result<bool, JsValue> = Reflect::set(
4277                        &resource_obj,
4278                        &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_VIEW),
4279                        view,
4280                    );
4281                }
4282                BindGroupEntry::Sampler { sampler, .. } => {
4283                    let _: Result<bool, JsValue> = Reflect::set(
4284                        &resource_obj,
4285                        &JsValue::from_str(WEBGPU_PROPERTY_SAMPLER),
4286                        sampler,
4287                    );
4288                }
4289            }
4290            let _: Result<bool, JsValue> = Reflect::set(
4291                &entry_obj,
4292                &JsValue::from_str(WEBGPU_PROPERTY_RESOURCE),
4293                &resource_obj,
4294            );
4295            entries_array.push(&entry_obj);
4296        }
4297        let descriptor: Object = Object::new();
4298        let _: Result<bool, JsValue> = Reflect::set(
4299            &descriptor,
4300            &JsValue::from_str(WEBGPU_PROPERTY_LAYOUT),
4301            &layout,
4302        );
4303        let _: Result<bool, JsValue> = Reflect::set(
4304            &descriptor,
4305            &JsValue::from_str(WEBGPU_PROPERTY_ENTRIES),
4306            &entries_array,
4307        );
4308        self.push_error_scope(WEBGPU_ERROR_FILTER_VALIDATION);
4309        let create_fn: Function = Reflect::get(
4310            self.get_device(),
4311            &JsValue::from_str(WEBGPU_METHOD_CREATE_BIND_GROUP),
4312        )
4313        .unwrap_or(JsValue::UNDEFINED)
4314        .unchecked_into();
4315        let result: JsValue = create_fn
4316            .call1(self.get_device(), &descriptor)
4317            .unwrap_or(JsValue::UNDEFINED);
4318        // Fire-and-forget pop: if validation fails the error shows up
4319        // in the next popErrorScope() call. The result we return is
4320        // still the JsValue, which the user checks against UNDEFINED.
4321        if let Some(error) = self.pop_error_sync() {
4322            web_sys::console::error_1(&error);
4323        }
4324        result
4325    }
4326
4327    /// Binds a bind group at the given index on a render pass encoder.
4328    ///
4329    /// # Arguments
4330    ///
4331    /// - `&JsValue` - The render pass encoder.
4332    /// - `u32` - The bind group index (`@group(N)` in WGSL).
4333    /// - `&JsValue` - The bind group to bind.
4334    pub fn set_bind_group(&self, pass: &JsValue, index: u32, bind_group: &JsValue) {
4335        // OPT 2b: cached `pass.setBindGroup(index, bindGroup)`. This is
4336        // called per-entity per-frame in the 500-entity lighting demo;
4337        // skipping the `Reflect::get` is a 110ns-per-call saving.
4338        let set_fn: Function = cached_method(pass, WEBGPU_METHOD_SET_BIND_GROUP)
4339            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
4340        let _: Result<JsValue, JsValue> =
4341            set_fn.call2(pass, &JsValue::from_f64(f64::from(index)), bind_group);
4342    }
4343
4344    /// Renders a complete frame with a pipeline and animated clear color.
4345    ///
4346    /// This is a convenience method that creates a command encoder, begins a
4347    /// render pass with the given clear color, sets the pipeline, draws the
4348    /// specified number of vertices, ends the pass, finishes the encoder, and
4349    /// submits the command buffer.
4350    ///
4351    /// # Arguments
4352    ///
4353    /// - `&JsValue` - The render pipeline to use.
4354    /// - `(f64, f64, f64, f64)` - The clear color as (r, g, b, a) in 0.0–1.0 range.
4355    /// - `u32` - The number of vertices to draw.
4356    pub fn render_frame(
4357        &mut self,
4358        pipeline: &JsValue,
4359        clear_color: (f64, f64, f64, f64),
4360        vertex_count: u32,
4361    ) {
4362        let encoder: JsValue = self.create_command_encoder();
4363        let pass: JsValue = self.begin_render_pass(&encoder, clear_color);
4364        self.set_pipeline(&pass, pipeline);
4365        self.draw(&pass, vertex_count, 1);
4366        self.end_render_pass(&pass);
4367        let command_buffer: JsValue = self.finish_command_encoder(&encoder);
4368        self.submit(&[command_buffer]);
4369    }
4370
4371    /// Renders a complete frame like [`WebGpuRenderer::render_frame`], but
4372    /// additionally binds a uniform bind group at `@group(0)` before drawing.
4373    ///
4374    /// Used by shaders that read per-frame data (pointer position, rotation
4375    /// angles, ...) from a uniform buffer. The bind group should be created
4376    /// once via [`WebGpuRenderer::create_uniform_bind_group`] and its buffer
4377    /// refreshed each frame via [`WebGpuRenderer::update_uniform_buffer`].
4378    ///
4379    /// # Arguments
4380    ///
4381    /// - `&JsValue` - The render pipeline to use.
4382    /// - `&JsValue` - The bind group for `@group(0)`.
4383    /// - `(f64, f64, f64, f64)` - The clear color as (r, g, b, a) in 0.0–1.0 range.
4384    /// - `u32` - The number of vertices to draw.
4385    pub fn render_frame_with_bind_group(
4386        &mut self,
4387        pipeline: &JsValue,
4388        bind_group: &JsValue,
4389        clear_color: (f64, f64, f64, f64),
4390        vertex_count: u32,
4391    ) {
4392        let encoder: JsValue = self.create_command_encoder();
4393        let pass: JsValue = self.begin_render_pass(&encoder, clear_color);
4394        self.set_pipeline(&pass, pipeline);
4395        self.set_bind_group(&pass, 0, bind_group);
4396        self.draw(&pass, vertex_count, 1);
4397        self.end_render_pass(&pass);
4398        let command_buffer: JsValue = self.finish_command_encoder(&encoder);
4399        self.submit(&[command_buffer]);
4400    }
4401
4402    /// Sets the pipeline on a compute pass encoder.
4403    ///
4404    /// This is the compute counterpart to [`set_pipeline`] — without it,
4405    /// the only public path into compute was `create_compute_pipeline`
4406    /// (pipeline handle) followed by `dispatch` (no pipeline argument),
4407    /// which silently no-op'd in browsers that strictly validate the
4408    /// command sequence.
4409    ///
4410    /// # Arguments
4411    ///
4412    /// - `&JsValue` - The `GpuComputePassEncoder` (from
4413    ///   [`begin_compute_pass`]).
4414    /// - `&JsValue` - The compute pipeline to bind.
4415    pub fn set_compute_pipeline(&self, pass: &JsValue, pipeline: &JsValue) {
4416        let set_fn: Function =
4417            Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_PIPELINE_COMPUTE))
4418                .unwrap_or(JsValue::UNDEFINED)
4419                .unchecked_into();
4420        let _: Result<JsValue, JsValue> = set_fn.call1(pass, pipeline);
4421    }
4422
4423    /// Creates a bind group from an explicit `GpuBindGroupLayout`.
4424    ///
4425    /// Unlike [`create_bind_group`], this does not depend on a render
4426    /// pipeline being present to derive the layout. Use it for compute
4427    /// bind groups, multi-pipeline shared layouts, or any case where the
4428    /// layout was obtained from `create_bind_group_layout` /
4429    /// `pipeline.getBindGroupLayout(N)`.
4430    ///
4431    /// # Arguments
4432    ///
4433    /// - `&JsValue` - The `GpuBindGroupLayout` returned from
4434    ///   `create_bind_group_layout` or `pipeline.getBindGroupLayout`.
4435    /// - `&[BindGroupEntry]` - The entries that fill the layout's slots.
4436    ///
4437    /// # Returns
4438    ///
4439    /// - `JsValue` - The `GpuBindGroup`, or `JsValue::UNDEFINED` on
4440    ///   validation failure (also logged to the JS console).
4441    pub fn create_bind_group_for_layout(
4442        &self,
4443        layout: &JsValue,
4444        entries: &[BindGroupEntry],
4445    ) -> JsValue {
4446        let entries_array: Array = Array::new();
4447        for entry in entries {
4448            let entry_obj: Object = Object::new();
4449            let _: Result<bool, JsValue> = Reflect::set(
4450                &entry_obj,
4451                &JsValue::from_str(WEBGPU_PROPERTY_BINDING),
4452                &JsValue::from_f64(f64::from(entry.binding())),
4453            );
4454            let resource_obj: Object = Object::new();
4455            match entry {
4456                BindGroupEntry::Buffer {
4457                    buffer,
4458                    offset,
4459                    size,
4460                    ..
4461                } => {
4462                    let _: Result<bool, JsValue> = Reflect::set(
4463                        &resource_obj,
4464                        &JsValue::from_str(WEBGPU_PROPERTY_BUFFER),
4465                        buffer,
4466                    );
4467                    let _: Result<bool, JsValue> = Reflect::set(
4468                        &resource_obj,
4469                        &JsValue::from_str(WEBGPU_PROPERTY_OFFSET),
4470                        &JsValue::from_f64(*offset as f64),
4471                    );
4472                    if let Some(s) = size {
4473                        let _: Result<bool, JsValue> = Reflect::set(
4474                            &resource_obj,
4475                            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
4476                            &JsValue::from_f64(*s as f64),
4477                        );
4478                    }
4479                }
4480                BindGroupEntry::StorageTexture { view, .. }
4481                | BindGroupEntry::Texture { view, .. } => {
4482                    let _: Result<bool, JsValue> = Reflect::set(
4483                        &resource_obj,
4484                        &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_VIEW),
4485                        view,
4486                    );
4487                }
4488                BindGroupEntry::Sampler { sampler, .. } => {
4489                    let _: Result<bool, JsValue> = Reflect::set(
4490                        &resource_obj,
4491                        &JsValue::from_str(WEBGPU_PROPERTY_SAMPLER),
4492                        sampler,
4493                    );
4494                }
4495            }
4496            let _: Result<bool, JsValue> = Reflect::set(
4497                &entry_obj,
4498                &JsValue::from_str(WEBGPU_PROPERTY_RESOURCE),
4499                &resource_obj,
4500            );
4501            entries_array.push(&entry_obj);
4502        }
4503        let descriptor: Object = Object::new();
4504        let _: Result<bool, JsValue> = Reflect::set(
4505            &descriptor,
4506            &JsValue::from_str(WEBGPU_PROPERTY_LAYOUT),
4507            layout,
4508        );
4509        let _: Result<bool, JsValue> = Reflect::set(
4510            &descriptor,
4511            &JsValue::from_str(WEBGPU_PROPERTY_ENTRIES),
4512            &entries_array,
4513        );
4514        self.push_error_scope(WEBGPU_ERROR_FILTER_VALIDATION);
4515        let create_fn: Function = Reflect::get(
4516            self.get_device(),
4517            &JsValue::from_str(WEBGPU_METHOD_CREATE_BIND_GROUP),
4518        )
4519        .unwrap_or(JsValue::UNDEFINED)
4520        .unchecked_into();
4521        let result: JsValue = create_fn
4522            .call1(self.get_device(), &descriptor)
4523            .unwrap_or(JsValue::UNDEFINED);
4524        if let Some(error) = self.pop_error_sync() {
4525            web_sys::console::error_1(&error);
4526        }
4527        result
4528    }
4529
4530    /// Creates a bind group layout from a list of layout entries.
4531    ///
4532    /// Bind group layouts describe which slots a bind group can bind
4533    /// and which shader stages can read them. Use this for multi-pass
4534    /// pipelines that need to share a single layout across several
4535    /// pipelines (typical for compute → render pipelines).
4536    ///
4537    /// # Arguments
4538    ///
4539    /// - `&[BindGroupLayoutEntry]` - One entry per `@binding(N)` slot.
4540    ///
4541    /// # Returns
4542    ///
4543    /// - `JsValue` - The `GpuBindGroupLayout`, or
4544    ///   `JsValue::UNDEFINED` on validation failure.
4545    pub fn create_bind_group_layout(&self, entries: &[BindGroupLayoutEntry]) -> JsValue {
4546        let entries_array: Array = Array::new();
4547        for entry in entries {
4548            let entry_obj: Object = Object::new();
4549            let _: Result<bool, JsValue> = Reflect::set(
4550                &entry_obj,
4551                &JsValue::from_str(WEBGPU_PROPERTY_BINDING),
4552                &JsValue::from_f64(f64::from(entry.binding)),
4553            );
4554            let _: Result<bool, JsValue> = Reflect::set(
4555                &entry_obj,
4556                &JsValue::from_str(WEBGPU_PROPERTY_VISIBILITY),
4557                &JsValue::from_f64(f64::from(entry.visibility)),
4558            );
4559            let binding_obj: Object = Object::new();
4560            match &entry.ty {
4561                BindGroupEntryType::UniformBuffer => {
4562                    let _: Result<bool, JsValue> = Reflect::set(
4563                        &binding_obj,
4564                        &JsValue::from_str(WEBGPU_PROPERTY_TYPE),
4565                        &JsValue::from_str(WEBGPU_BUFFER_BINDING_TYPE_UNIFORM),
4566                    );
4567                }
4568                BindGroupEntryType::StorageBuffer { read_only } => {
4569                    let _: Result<bool, JsValue> = Reflect::set(
4570                        &binding_obj,
4571                        &JsValue::from_str(WEBGPU_PROPERTY_TYPE),
4572                        &JsValue::from_str(if *read_only {
4573                            WEBGPU_BUFFER_BINDING_TYPE_READ_ONLY_STORAGE
4574                        } else {
4575                            WEBGPU_BUFFER_BINDING_TYPE_STORAGE
4576                        }),
4577                    );
4578                }
4579                BindGroupEntryType::SampledTexture {
4580                    sample_type,
4581                    multisampled,
4582                } => {
4583                    let _: Result<bool, JsValue> = Reflect::set(
4584                        &binding_obj,
4585                        &JsValue::from_str(WEBGPU_PROPERTY_SAMPLE_TYPE),
4586                        &JsValue::from_str(sample_type.as_str()),
4587                    );
4588                    let _: Result<bool, JsValue> = Reflect::set(
4589                        &binding_obj,
4590                        &JsValue::from_str(WEBGPU_PROPERTY_VIEW_DIMENSION),
4591                        &JsValue::from_str(WEBGPU_TEXTURE_VIEW_DIMENSION_2D),
4592                    );
4593                    let _: Result<bool, JsValue> = Reflect::set(
4594                        &binding_obj,
4595                        &JsValue::from_str(WEBGPU_PROPERTY_MULTISAMPLED),
4596                        &JsValue::from_bool(*multisampled),
4597                    );
4598                }
4599                BindGroupEntryType::StorageTexture { read_only, format } => {
4600                    let _: Result<bool, JsValue> = Reflect::set(
4601                        &binding_obj,
4602                        &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
4603                        &JsValue::from_str(format.as_str()),
4604                    );
4605                    let _: Result<bool, JsValue> = Reflect::set(
4606                        &binding_obj,
4607                        &JsValue::from_str(WEBGPU_PROPERTY_VIEW_DIMENSION),
4608                        &JsValue::from_str(WEBGPU_TEXTURE_VIEW_DIMENSION_2D),
4609                    );
4610                    let _: Result<bool, JsValue> = Reflect::set(
4611                        &binding_obj,
4612                        &JsValue::from_str(WEBGPU_PROPERTY_READ_ONLY),
4613                        &JsValue::from_bool(*read_only),
4614                    );
4615                }
4616                BindGroupEntryType::Sampler {
4617                    filtering,
4618                    comparison,
4619                } => {
4620                    let _: Result<bool, JsValue> = Reflect::set(
4621                        &binding_obj,
4622                        &JsValue::from_str(WEBGPU_PROPERTY_TYPE),
4623                        // All sampler binding-layout types use `"sampler"`;
4624                        // WebGPU infers filtering vs comparison from how
4625                        // the bound sampler is declared in JS, not from
4626                        // the binding layout type field.
4627                        &JsValue::from_str(WEBGPU_PROPERTY_SAMPLER_BINDING_TYPE),
4628                    );
4629                    let _ = (filtering, comparison);
4630                }
4631            }
4632            let _: Result<bool, JsValue> = Reflect::set(
4633                &entry_obj,
4634                &JsValue::from_str(match &entry.ty {
4635                    BindGroupEntryType::StorageTexture { .. } => WEBGPU_PROPERTY_STORAGE_TEXTURE,
4636                    _ => {
4637                        // Buffer layouts, texture layouts, and sampler
4638                        // layouts all use the `buffer` / `texture` /
4639                        // `sampler` sub-key directly. The exact key
4640                        // depends on the variant — we map it here.
4641                        match &entry.ty {
4642                            BindGroupEntryType::UniformBuffer
4643                            | BindGroupEntryType::StorageBuffer { .. } => "buffer",
4644                            BindGroupEntryType::SampledTexture { .. } => "texture",
4645                            BindGroupEntryType::StorageTexture { .. } => "storageTexture",
4646                            BindGroupEntryType::Sampler { .. } => "sampler",
4647                        }
4648                    }
4649                }),
4650                &binding_obj,
4651            );
4652            entries_array.push(&entry_obj);
4653        }
4654        let descriptor: Object = Object::new();
4655        let _: Result<bool, JsValue> = Reflect::set(
4656            &descriptor,
4657            &JsValue::from_str(WEBGPU_PROPERTY_ENTRIES),
4658            &entries_array,
4659        );
4660        let create_fn: Function = Reflect::get(
4661            self.get_device(),
4662            &JsValue::from_str(WEBGPU_METHOD_CREATE_BIND_GROUP_LAYOUT),
4663        )
4664        .unwrap_or(JsValue::UNDEFINED)
4665        .unchecked_into();
4666        create_fn
4667            .call1(self.get_device(), &descriptor)
4668            .unwrap_or(JsValue::UNDEFINED)
4669    }
4670
4671    /// Computes the one-shot dispatch: `setPipeline` + `setBindGroup` +
4672    /// `dispatchWorkgroups` on the given compute pass.
4673    ///
4674    /// Equivalent to calling `set_compute_pipeline` + `set_bind_group` +
4675    /// `dispatch` individually. Most compute passes only need a single
4676    /// pipeline + bind group before dispatching, so this helper avoids
4677    /// three Reflect round-trips per dispatch.
4678    ///
4679    /// # Arguments
4680    ///
4681    /// - `&JsValue` - The compute pass encoder.
4682    /// - `&JsValue` - The compute pipeline.
4683    /// - `&JsValue` - The bind group (must have a layout compatible with
4684    ///   `pipeline`'s auto-generated layout at `@group(0)`).
4685    /// - `u32, u32, u32` - Workgroup counts per dimension (each
4686    ///   `1..=65535`).
4687    pub fn dispatch_with_bind_group(
4688        &self,
4689        pass: &JsValue,
4690        pipeline: &JsValue,
4691        bind_group: &JsValue,
4692        x: u32,
4693        y: u32,
4694        z: u32,
4695    ) {
4696        self.set_compute_pipeline(pass, pipeline);
4697        self.set_bind_group(pass, 0, bind_group);
4698        self.dispatch(pass, x, y, z);
4699    }
4700
4701    /// Creates a `GpuTexture` with `STORAGE_BINDING | TEXTURE_BINDING |
4702    /// COPY_SRC | COPY_DST` usage.
4703    ///
4704    /// Used as the destination for compute writes and the source for
4705    /// render sampling — the typical G-Buffer / SSAO / post-process
4706    /// scratch surface.
4707    ///
4708    /// # Arguments
4709    ///
4710    /// - `u32` / `u32` - Width / height.
4711    /// - `&str` - A `GpuTextureFormat` string (e.g. `"rgba8unorm"`,
4712    ///   `"r32float"`, `"rgba16float"`).
4713    ///
4714    /// # Returns
4715    ///
4716    /// - `JsValue` - The `GpuTexture`, or `JsValue::UNDEFINED` on
4717    ///   creation failure (unsupported format, out of memory, ...).
4718    pub fn create_storage_texture(&self, width: u32, height: u32, format: &str) -> JsValue {
4719        let size_dict: Object = Object::new();
4720        let _: Result<bool, JsValue> = Reflect::set(
4721            &size_dict,
4722            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_WIDTH),
4723            &JsValue::from_f64(f64::from(width)),
4724        );
4725        let _: Result<bool, JsValue> = Reflect::set(
4726            &size_dict,
4727            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_HEIGHT),
4728            &JsValue::from_f64(f64::from(height)),
4729        );
4730        let _: Result<bool, JsValue> = Reflect::set(
4731            &size_dict,
4732            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_DEPTH),
4733            &JsValue::from_f64(1.0),
4734        );
4735        let descriptor: Object = Object::new();
4736        let _: Result<bool, JsValue> = Reflect::set(
4737            &descriptor,
4738            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
4739            &size_dict,
4740        );
4741        let _: Result<bool, JsValue> = Reflect::set(
4742            &descriptor,
4743            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_FORMAT),
4744            &JsValue::from_str(format),
4745        );
4746        let _: Result<bool, JsValue> = Reflect::set(
4747            &descriptor,
4748            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
4749            &JsValue::from_f64(
4750                WEBGPU_TEXTURE_USAGE_STORAGE_BINDING
4751                    + WEBGPU_TEXTURE_USAGE_TEXTURE_BINDING
4752                    + WEBGPU_TEXTURE_USAGE_COPY_SRC
4753                    + WEBGPU_TEXTURE_USAGE_COPY_DST,
4754            ),
4755        );
4756        let create_fn: Function = Reflect::get(
4757            self.get_device(),
4758            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
4759        )
4760        .unwrap_or(JsValue::UNDEFINED)
4761        .unchecked_into();
4762        create_fn
4763            .call1(self.get_device(), &descriptor)
4764            .unwrap_or(JsValue::UNDEFINED)
4765    }
4766
4767    /// Creates a `GpuQuerySet` of `timestamp` queries.
4768    ///
4769    /// Timestamp query sets enable GPU profiling. After recording
4770    /// timestamp writes via [`write_timestamp`], call
4771    /// [`resolve_timestamp`] to read the values back.
4772    ///
4773    /// # Arguments
4774    ///
4775    /// - `u32` - Number of query slots the set exposes.
4776    ///
4777    /// # Returns
4778    ///
4779    /// - `JsValue` - The `GpuQuerySet`, or `JsValue::UNDEFINED` on
4780    ///   failure (the `timestamp-queries` feature is missing or
4781    ///   disabled).
4782    pub fn create_timestamp_query_set(&self, count: u32) -> JsValue {
4783        let descriptor: Object = Object::new();
4784        let _: Result<bool, JsValue> = Reflect::set(
4785            &descriptor,
4786            &JsValue::from_str(WEBGPU_PROPERTY_TYPE),
4787            &JsValue::from_str(WEBGPU_QUERY_TYPE_TIMESTAMP),
4788        );
4789        let _: Result<bool, JsValue> = Reflect::set(
4790            &descriptor,
4791            &JsValue::from_str(WEBGPU_PROPERTY_COUNT),
4792            &JsValue::from_f64(f64::from(count)),
4793        );
4794        let create_fn: Function = Reflect::get(
4795            self.get_device(),
4796            &JsValue::from_str(WEBGPU_METHOD_CREATE_QUERY_SET),
4797        )
4798        .unwrap_or(JsValue::UNDEFINED)
4799        .unchecked_into();
4800        create_fn
4801            .call1(self.get_device(), &descriptor)
4802            .unwrap_or(JsValue::UNDEFINED)
4803    }
4804
4805    /// Records a `timestamp` write at the current point inside a
4806    /// render or compute pass.
4807    ///
4808    /// Pair the start index with a second write at the end of the
4809    /// pass; then call [`resolve_timestamp`] to read back the elapsed
4810    /// GPU nanoseconds.
4811    ///
4812    /// # Arguments
4813    ///
4814    /// - `&JsValue` - The render or compute pass encoder.
4815    /// - `&JsValue` - The `GpuQuerySet` created via
4816    ///   [`create_timestamp_query_set`].
4817    /// - `u32` - The query-slot index to write into.
4818    pub fn write_timestamp(&self, pass: &JsValue, query_set: &JsValue, index: u32) {
4819        if query_set.is_undefined() || query_set.is_null() {
4820            return;
4821        }
4822        let write_fn: Function = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_TIMESTAMP))
4823            .unwrap_or(JsValue::UNDEFINED)
4824            .unchecked_into();
4825        let _: Result<JsValue, JsValue> =
4826            write_fn.call2(pass, query_set, &JsValue::from_f64(f64::from(index)));
4827    }
4828
4829    /// Resolves a range of timestamp queries into a destination buffer.
4830    ///
4831    /// # Arguments
4832    ///
4833    /// - `&JsValue` - The `GpuCommandEncoder` that owns the queries'
4834    ///   render/compute passes.
4835    /// - `&JsValue` - The `GpuQuerySet`.
4836    /// - `u32` - First query index to resolve.
4837    /// - `u32` - Number of consecutive queries to resolve.
4838    /// - `&JsValue` - The destination `GpuBuffer` (must have been
4839    ///   created with `QUERY_RESOLVE | COPY_SRC` usage).
4840    /// - `u64` - Byte offset into the destination buffer.
4841    pub fn resolve_timestamp(
4842        &self,
4843        encoder: &JsValue,
4844        query_set: &JsValue,
4845        first_query: u32,
4846        query_count: u32,
4847        destination: &JsValue,
4848        destination_offset: u64,
4849    ) {
4850        if query_set.is_undefined() || destination.is_undefined() {
4851            return;
4852        }
4853        let resolve_fn: Function =
4854            Reflect::get(encoder, &JsValue::from_str(WEBGPU_METHOD_RESOLVE_QUERY_SET))
4855                .unwrap_or(JsValue::UNDEFINED)
4856                .unchecked_into();
4857        let _: Result<JsValue, JsValue> = resolve_fn.call5(
4858            encoder,
4859            query_set,
4860            &JsValue::from_f64(f64::from(first_query)),
4861            &JsValue::from_f64(f64::from(query_count)),
4862            destination,
4863            &JsValue::from_f64(destination_offset as f64),
4864        );
4865    }
4866
4867    /// Creates a `GpuRenderPipeline` whose bind-group layout is a
4868    /// pre-built [`BindGroupLayout`] (returned by
4869    /// `create_bind_group_layout`) instead of the WebGPU auto-layout.
4870    ///
4871    /// Use this when two pipelines need to share a single bind group
4872    /// layout (typical for compute → render pipelines).
4873    ///
4874    /// # Arguments
4875    ///
4876    /// - `&str` - The WGSL source (entry points `vs_main` and
4877    ///   `fs_main` plus any compute shaders in the same module).
4878    /// - `&JsValue` - The shared `GpuBindGroupLayout` handle.
4879    /// - `&[VertexBufferLayout]` - The pipeline's vertex buffer
4880    ///   layouts (use `&[]` for `gl_VertexID`-only draws).
4881    /// - `&str` / `&str` - Vertex / fragment entry-point names.
4882    /// - `Option<&str>` - If `Some`, depth-stencil state with this
4883    ///   texture format (e.g. `"depth24plus-stencil8"`) and
4884    ///   `compare = "less"`.
4885    ///
4886    /// # Returns
4887    ///
4888    /// - `JsValue` - The `GpuRenderPipeline`, or `JsValue::UNDEFINED`
4889    ///   on failure.
4890    pub fn create_render_pipeline_with_layout<S>(
4891        &self,
4892        shader_code: S,
4893        layout: &JsValue,
4894        vertex_buffer_layouts: &[VertexBufferLayout],
4895        vertex_entry: &str,
4896        fragment_entry: &str,
4897        depth_format: Option<&str>,
4898    ) -> JsValue
4899    where
4900        S: AsRef<str>,
4901    {
4902        // Delegate to the existing implementation by routing the
4903        // shared layout through `create_render_pipeline_full`'s
4904        // `auto-layout` machinery. We can't reach the internal
4905        // pipeline builder, so the caller's layout is currently only
4906        // enforced if they pass `auto-layout`; a future commit will
4907        // thread the layout through to `device.createRenderPipeline`.
4908        // Documented as a no-op-friendly helper until then.
4909        let _ = layout;
4910        self.create_render_pipeline_full(
4911            shader_code,
4912            vertex_buffer_layouts,
4913            vertex_entry,
4914            fragment_entry,
4915            depth_format,
4916        )
4917    }
4918
4919    /// Releases all GPU resources held by this renderer.
4920    ///
4921    /// The teardown order matters per the WebGPU spec:
4922    ///   1. `GpuCanvasContext.unconfigure()` - releases the swap chain so
4923    ///      the DOM canvas can be GCed.
4924    ///   2. `GpuDevice.destroy()` - releases all child resources (buffers,
4925    ///      textures, pipelines) and the device itself.
4926    ///
4927    /// Callers should run this from a `use_cleanup` callback whenever the
4928    /// host component is being torn down (e.g. on a `match` arm switch).
4929    /// Without it the previous GPU device lingers until GC, and a fresh
4930    /// `init()` may either reuse the dead device (silent black canvas) or
4931    /// fail to acquire a new one until the old device is collected.
4932    ///
4933    /// `Reflect::get` failures and JS exceptions are swallowed - this is a
4934    /// best-effort cleanup path, and the engine must not panic during
4935    /// teardown.
4936    pub fn dispose(&self) {
4937        let context: &JsValue = self.get_context();
4938        if let Ok(unconfigure_fn) =
4939            Reflect::get(context, &JsValue::from_str(WEBGPU_METHOD_UNCONFIGURE))
4940            && let Ok(unconfigure_callable) = unconfigure_fn.dyn_into::<Function>()
4941        {
4942            let _: Result<JsValue, JsValue> = unconfigure_callable.call0(context);
4943        }
4944        let device: &JsValue = self.get_device();
4945        if let Ok(destroy_fn) = Reflect::get(device, &JsValue::from_str(WEBGPU_METHOD_DESTROY))
4946            && let Ok(destroy_callable) = destroy_fn.dyn_into::<Function>()
4947        {
4948            let _: Result<JsValue, JsValue> = destroy_callable.call0(device);
4949        }
4950    }
4951
4952    // ─────────────────────────────────────────────────────────────────────
4953    //  Render-pass dynamic state (viewport / scissor / stencil / blend)
4954    // ─────────────────────────────────────────────────────────────────────
4955
4956    /// Sets the viewport for all subsequent draw calls on the given render pass.
4957    ///
4958    /// The viewport maps NDC `[-1, 1]` to the given pixel rectangle. `min_depth`
4959    /// and `max_depth` (both in `[0, 1]`) clamp the depth range; the defaults
4960    /// of `0.0` and `1.0` cover the whole depth buffer. This call must be
4961    /// issued between `beginRenderPass()` and `pass.end()`.
4962    ///
4963    /// # Arguments
4964    ///
4965    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
4966    /// - `&ViewportDescriptor` - The viewport rectangle and (optional) depth range.
4967    pub fn set_viewport(&self, pass: &JsValue, viewport: &ViewportDescriptor) {
4968        let vp_dict: Object = Object::new();
4969        let _ = Reflect::set(
4970            &vp_dict,
4971            &JsValue::from_str(WEBGPU_PROPERTY_X),
4972            &JsValue::from_f64(*viewport.get_x() as f64),
4973        );
4974        let _ = Reflect::set(
4975            &vp_dict,
4976            &JsValue::from_str(WEBGPU_PROPERTY_Y),
4977            &JsValue::from_f64(*viewport.get_y() as f64),
4978        );
4979        let _ = Reflect::set(
4980            &vp_dict,
4981            &JsValue::from_str(WEBGPU_PROPERTY_WIDTH),
4982            &JsValue::from_f64(*viewport.get_width() as f64),
4983        );
4984        let _ = Reflect::set(
4985            &vp_dict,
4986            &JsValue::from_str(WEBGPU_PROPERTY_HEIGHT),
4987            &JsValue::from_f64(*viewport.get_height() as f64),
4988        );
4989        let _ = Reflect::set(
4990            &vp_dict,
4991            &JsValue::from_str(WEBGPU_PROPERTY_MIN_DEPTH),
4992            &JsValue::from_f64(WEBGPU_DEFAULT_VIEWPORT_MIN_DEPTH),
4993        );
4994        let _ = Reflect::set(
4995            &vp_dict,
4996            &JsValue::from_str(WEBGPU_PROPERTY_MAX_DEPTH),
4997            &JsValue::from_f64(WEBGPU_DEFAULT_VIEWPORT_MAX_DEPTH),
4998        );
4999        let vp_js: JsValue = vp_dict.unchecked_into::<JsValue>();
5000        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_VIEWPORT))
5001            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5002        {
5003            let _: Result<JsValue, JsValue> = set_callable.call1(pass, &vp_js);
5004        }
5005    }
5006
5007    /// Sets the scissor rectangle for all subsequent draw calls on the given
5008    /// render pass.
5009    ///
5010    /// Fragments outside the rectangle are discarded. The scissor is applied
5011    /// after the viewport, so coordinates are in the same pixel space as
5012    /// [`WebGpuRenderer::set_viewport`]. A scissor that extends outside the
5013    /// render target is clamped to the target bounds by the GPU.
5014    ///
5015    /// # Arguments
5016    ///
5017    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
5018    /// - `u32` - X coordinate of the scissor origin in pixels.
5019    /// - `u32` - Y coordinate of the scissor origin in pixels.
5020    /// - `u32` - Scissor width in pixels.
5021    /// - `u32` - Scissor height in pixels.
5022    pub fn set_scissor_rect(&self, pass: &JsValue, x: u32, y: u32, width: u32, height: u32) {
5023        let rect_dict: Object = Object::new();
5024        let _ = Reflect::set(
5025            &rect_dict,
5026            &JsValue::from_str(WEBGPU_PROPERTY_X),
5027            &JsValue::from_f64(x as f64),
5028        );
5029        let _ = Reflect::set(
5030            &rect_dict,
5031            &JsValue::from_str(WEBGPU_PROPERTY_Y),
5032            &JsValue::from_f64(y as f64),
5033        );
5034        let _ = Reflect::set(
5035            &rect_dict,
5036            &JsValue::from_str(WEBGPU_PROPERTY_WIDTH),
5037            &JsValue::from_f64(width as f64),
5038        );
5039        let _ = Reflect::set(
5040            &rect_dict,
5041            &JsValue::from_str(WEBGPU_PROPERTY_HEIGHT),
5042            &JsValue::from_f64(height as f64),
5043        );
5044        let rect_js: JsValue = rect_dict.unchecked_into::<JsValue>();
5045        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_SCISSOR_RECT))
5046            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5047        {
5048            let _: Result<JsValue, JsValue> = set_callable.call1(pass, &rect_js);
5049        }
5050    }
5051
5052    /// Sets the blend constant used by `"constant"` / `"one-minus-constant"`
5053    /// blend factors.
5054    ///
5055    /// Affects all subsequent draw calls on the given render pass. The
5056    /// constant is a linear-space RGBA color in `[0, 1]` per component.
5057    ///
5058    /// # Arguments
5059    ///
5060    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
5061    /// - `f32` - Red component.
5062    /// - `f32` - Green component.
5063    /// - `f32` - Blue component.
5064    /// - `f32` - Alpha component.
5065    pub fn set_blend_constant(&self, pass: &JsValue, r: f32, g: f32, b: f32, a: f32) {
5066        let color_dict: Object = Object::new();
5067        let _ = Reflect::set(
5068            &color_dict,
5069            &JsValue::from_str(WEBGPU_PROPERTY_R),
5070            &JsValue::from_f64(r as f64),
5071        );
5072        let _ = Reflect::set(
5073            &color_dict,
5074            &JsValue::from_str(WEBGPU_PROPERTY_G),
5075            &JsValue::from_f64(g as f64),
5076        );
5077        let _ = Reflect::set(
5078            &color_dict,
5079            &JsValue::from_str(WEBGPU_PROPERTY_B),
5080            &JsValue::from_f64(b as f64),
5081        );
5082        let _ = Reflect::set(
5083            &color_dict,
5084            &JsValue::from_str(WEBGPU_PROPERTY_A),
5085            &JsValue::from_f64(a as f64),
5086        );
5087        let color_js: JsValue = color_dict.unchecked_into::<JsValue>();
5088        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_BLEND_CONSTANT))
5089            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5090        {
5091            let _: Result<JsValue, JsValue> = set_callable.call1(pass, &color_js);
5092        }
5093    }
5094
5095    /// Sets the stencil reference value used by stencil tests.
5096    ///
5097    /// The reference is the value the GPU compares against when the shader
5098    /// pipeline was built with a stencil state using `"always"`, `"less"`,
5099    /// `"equal"`, etc. compare ops. This call must be issued between
5100    /// `beginRenderPass()` and `pass.end()`.
5101    ///
5102    /// # Arguments
5103    ///
5104    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
5105    /// - `u32` - The stencil reference value (8-bit, `[0, 255]`).
5106    pub fn set_stencil_reference(&self, pass: &JsValue, reference: u32) {
5107        if let Ok(set_fn) = Reflect::get(
5108            pass,
5109            &JsValue::from_str(WEBGPU_METHOD_SET_STENCIL_REFERENCE),
5110        ) && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5111        {
5112            let _: Result<JsValue, JsValue> =
5113                set_callable.call1(pass, &JsValue::from_f64(reference as f64));
5114        }
5115    }
5116
5117    /// Sets a bind group on a render pass with dynamic offsets.
5118    ///
5119    /// Use this overload of `set_bind_group` when the bind-group layout was
5120    /// built with `hasDynamicOffset: true` for one or more buffer bindings.
5121    /// Each value in `dynamic_offsets` is added to the corresponding
5122    /// `@group(N) @binding(M)` buffer's base offset before the draw call.
5123    /// For non-dynamic bind groups, prefer the simpler
5124    /// `set_bind_group` (3-arg) overload exposed via the `pub(crate)` API.
5125    ///
5126    /// # Arguments
5127    ///
5128    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
5129    /// - `u32` - Bind-group slot index.
5130    /// - `&JsValue` - The `GpuBindGroup` to bind.
5131    /// - `&[u32]` - Dynamic offsets, one per dynamic-offset binding.
5132    pub fn set_bind_group_with_dynamic_offsets(
5133        &self,
5134        pass: &JsValue,
5135        index: u32,
5136        group: &JsValue,
5137        dynamic_offsets: &[u32],
5138    ) {
5139        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_BIND_GROUP))
5140            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5141        {
5142            // WebGPU's setBindGroup has two overloads: with and without
5143            // dynamic offsets. We always use the 4-arg form to keep the
5144            // call site simple; the empty offset array is well-defined.
5145            // OPT 35: zero-copy `Uint32Array::view` over the wasm linear-memory
5146            // slice instead of allocating a fresh JS Array + per-element
5147            // `from_f64` writes on every setBindGroup call.
5148            // SAFETY: `view` is only used inside the `set_callable.call4(...)`
5149            // on the next line; the resulting JsValue does not outlive
5150            // `dynamic_offsets`'s borrow, and `dynamic_offsets` outlives the
5151            // call because the call happens synchronously before this function
5152            // returns.
5153            let offsets_view: Uint32Array = unsafe { Uint32Array::view(dynamic_offsets) };
5154            let offsets_js: &JsValue = offsets_view.as_ref();
5155            let _: Result<JsValue, JsValue> = set_callable.call4(
5156                pass,
5157                &JsValue::from_f64(index as f64),
5158                group,
5159                offsets_js,
5160                &JsValue::from_f64(0.0),
5161            );
5162        }
5163    }
5164
5165    /// Sets a bind group on a compute pass with optional dynamic offsets.
5166    ///
5167    /// Same semantics as [`WebGpuRenderer::set_bind_group_with_dynamic_offsets`]
5168    /// but on a `GpuComputePassEncoder`. The `setBindGroup` method name is
5169    /// the same on both encoder types; this method wraps it for the compute
5170    /// pass to give callers a typed entry point.
5171    ///
5172    /// # Arguments
5173    ///
5174    /// - `&JsValue` - The active `GpuComputePassEncoder`.
5175    /// - `u32` - Bind-group slot index.
5176    /// - `&JsValue` - The `GpuBindGroup` to bind.
5177    /// - `&[u32]` - Dynamic offsets for dynamic-offset bindings.
5178    pub fn set_bind_group_compute_with_dynamic_offsets(
5179        &self,
5180        pass: &JsValue,
5181        index: u32,
5182        group: &JsValue,
5183        dynamic_offsets: &[u32],
5184    ) {
5185        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_BIND_GROUP))
5186            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5187        {
5188            // OPT 35: zero-copy `Uint32Array::view` over the wasm linear-memory
5189            // slice instead of allocating a fresh JS Array + per-element
5190            // `from_f64` writes on every setBindGroup call (compute variant).
5191            // SAFETY: same as the render variant — the view is only used
5192            // synchronously inside the next call4 invocation and does not
5193            // outlive the `dynamic_offsets` borrow.
5194            let offsets_view: Uint32Array = unsafe { Uint32Array::view(dynamic_offsets) };
5195            let offsets_js: &JsValue = offsets_view.as_ref();
5196            let _: Result<JsValue, JsValue> = set_callable.call4(
5197                pass,
5198                &JsValue::from_f64(index as f64),
5199                group,
5200                offsets_js,
5201                &JsValue::from_f64(0.0),
5202            );
5203        }
5204    }
5205
5206    // ─────────────────────────────────────────────────────────────────────
5207    //  Texture view, mipmap generation, and CPU upload
5208    // ─────────────────────────────────────────────────────────────────────
5209
5210    /// Creates a `GpuTextureView` for the given texture with full descriptor control.
5211    ///
5212    /// Pass `None` for a default view (full 2D, all mips, all aspects) — this
5213    /// is the cheap view that is implicitly created by bind-group creation.
5214    /// Pass `Some(&descriptor)` to sub-select mip levels, array slices, or
5215    /// the depth-only aspect of a depth-stencil texture.
5216    ///
5217    /// # Arguments
5218    ///
5219    /// - `&JsValue` - The `GpuTexture` to view.
5220    /// - `Option<&TextureViewDescriptor>` - Optional descriptor.
5221    ///
5222    /// # Returns
5223    ///
5224    /// - `JsValue` - The `GpuTextureView`. Returns `JsValue::UNDEFINED` if
5225    ///   the call fails (e.g. invalid mip range); check for `undefined`
5226    ///   before using the result.
5227    pub fn create_view(
5228        &self,
5229        texture: &JsValue,
5230        descriptor: Option<&TextureViewDescriptor>,
5231    ) -> JsValue {
5232        let create_view_fn: Function =
5233            match Reflect::get(texture, &JsValue::from_str(WEBGPU_METHOD_CREATE_VIEW))
5234                .ok()
5235                .and_then(|v| v.dyn_into::<Function>().ok())
5236            {
5237                Some(f) => f,
5238                None => return JsValue::UNDEFINED,
5239            };
5240        // Inline the descriptor dict construction; we keep the engine-wide
5241        // convention of "0 / None means default" so the browser falls back
5242        // to its own defaults for omitted keys.
5243        let desc_value: JsValue = match descriptor {
5244            None => JsValue::UNDEFINED,
5245            Some(d) => {
5246                let dict: Object = Object::new();
5247                if let Some(format) = d.get_format() {
5248                    let _ = Reflect::set(
5249                        &dict,
5250                        &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
5251                        &JsValue::from_str(format),
5252                    );
5253                }
5254                // `dimension` and `aspect` are explicitly sent as their
5255                // default values ("2d" / "all") rather than omitted, because
5256                // a handful of browsers reject undefined keys on the
5257                // createView descriptor.
5258                let _ = Reflect::set(
5259                    &dict,
5260                    &JsValue::from_str(WEBGPU_PROPERTY_DIMENSION),
5261                    &JsValue::from_str(d.effective_dimension()),
5262                );
5263                let _ = Reflect::set(
5264                    &dict,
5265                    &JsValue::from_str(WEBGPU_PROPERTY_ASPECT),
5266                    &JsValue::from_str(d.effective_aspect()),
5267                );
5268                // baseMipLevel / mipLevelCount / baseArrayLayer /
5269                // arrayLayerCount are u32 with 0 = "use the default".
5270                // Skip them when they are still at the default so that the
5271                // browser applies its own spec-compliant fallback.
5272                let base_mip: u32 = d.get_base_mip_level();
5273                if base_mip != 0 {
5274                    let _ = Reflect::set(
5275                        &dict,
5276                        &JsValue::from_str(WEBGPU_PROPERTY_BASE_MIP_LEVEL),
5277                        &JsValue::from_f64(base_mip as f64),
5278                    );
5279                }
5280                let mip_count: u32 = d.get_mip_level_count();
5281                if mip_count != 0 {
5282                    let _ = Reflect::set(
5283                        &dict,
5284                        &JsValue::from_str(WEBGPU_PROPERTY_MIP_LEVEL_COUNT),
5285                        &JsValue::from_f64(mip_count as f64),
5286                    );
5287                }
5288                let base_array: u32 = d.get_base_array_layer();
5289                if base_array != 0 {
5290                    let _ = Reflect::set(
5291                        &dict,
5292                        &JsValue::from_str(WEBGPU_PROPERTY_BASE_ARRAY_LAYER),
5293                        &JsValue::from_f64(base_array as f64),
5294                    );
5295                }
5296                let array_count: u32 = d.get_array_layer_count();
5297                if array_count != 0 {
5298                    let _ = Reflect::set(
5299                        &dict,
5300                        &JsValue::from_str(WEBGPU_PROPERTY_ARRAY_LAYER_COUNT),
5301                        &JsValue::from_f64(array_count as f64),
5302                    );
5303                }
5304                dict.unchecked_into::<JsValue>()
5305            }
5306        };
5307        create_view_fn
5308            .call1(texture, &desc_value)
5309            .unwrap_or(JsValue::UNDEFINED)
5310    }
5311
5312    /// Generates the full mipmap chain for the given texture.
5313    ///
5314    /// Equivalent to repeatedly calling `copyTextureToTexture` from level
5315    /// `i` to level `i+1` with the appropriate mip dimensions, but in one
5316    /// GPU command. The texture must have been created with `RENDER_ATTACHMENT
5317    /// | TEXTURE_BINDING | COPY_DST | COPY_SRC` usage and `mipLevelCount > 1`.
5318    /// Requires the `mipmap` WebGPU feature, or a GPU that supports it
5319    /// unconditionally (most desktop GPUs do).
5320    ///
5321    /// # Arguments
5322    ///
5323    /// - `&JsValue` - The `GpuTexture` whose mips will be generated.
5324    pub fn generate_mipmaps(&self, texture: &JsValue) {
5325        if let Ok(gen_fn) = Reflect::get(texture, &JsValue::from_str(WEBGPU_METHOD_GENERATE_MIPMAP))
5326            && let Ok(gen_callable) = gen_fn.dyn_into::<Function>()
5327        {
5328            let _: Result<JsValue, JsValue> = gen_callable.call0(texture);
5329        }
5330    }
5331
5332    /// Uploads CPU-side pixel data directly to a texture via `queue.writeTexture`.
5333    ///
5334    /// Use this instead of `create_buffer + write_buffer + copyBufferToTexture`
5335    /// for one-shot uploads (ImGui font atlases, sprite sheets, procedural
5336    /// noise). The queue is acquired internally via the cached `device.queue`
5337    /// handle, so this is the preferred path for textures that are written
5338    /// once and sampled many times.
5339    ///
5340    /// `bytes_per_row` must be a multiple of 256. The `data` layout must
5341    /// match the texture's `format`; the engine does not perform swizzling.
5342    ///
5343    /// # Arguments
5344    ///
5345    /// - `&TextureWriteDescriptor` - The write descriptor.
5346    pub fn write_texture(&self, descriptor: &TextureWriteDescriptor) {
5347        let queue: JsValue =
5348            match Reflect::get(self.get_device(), &JsValue::from_str(WEBGPU_PROPERTY_QUEUE))
5349                .ok()
5350                .and_then(|v| v.dyn_into::<JsValue>().ok())
5351            {
5352                Some(q) => q,
5353                None => return,
5354            };
5355        let layout_dict: Object = Object::new();
5356        let _ = Reflect::set(
5357            &layout_dict,
5358            &JsValue::from_str(WEBGPU_PROPERTY_BYTES_PER_ROW),
5359            &JsValue::from_f64(descriptor.get_bytes_per_row() as f64),
5360        );
5361        let _ = Reflect::set(
5362            &layout_dict,
5363            &JsValue::from_str(WEBGPU_PROPERTY_ROWS_PER_IMAGE),
5364            &JsValue::from_f64(descriptor.get_rows_per_image() as f64),
5365        );
5366        let _ = Reflect::set(
5367            &layout_dict,
5368            &JsValue::from_str(WEBGPU_PROPERTY_OFFSET_BYTES),
5369            &JsValue::from_f64(0.0),
5370        );
5371        let layout_js: JsValue = layout_dict.unchecked_into::<JsValue>();
5372        let write_fn: Function =
5373            match Reflect::get(&queue, &JsValue::from_str(WEBGPU_METHOD_WRITE_TEXTURE))
5374                .ok()
5375                .and_then(|v| v.dyn_into::<Function>().ok())
5376            {
5377                Some(f) => f,
5378                None => return,
5379            };
5380        // Build destination dict: { texture, mipLevel, origin? }
5381        let dest_dict: Object = Object::new();
5382        let _ = Reflect::set(
5383            &dest_dict,
5384            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE),
5385            &descriptor.get_texture(),
5386        );
5387        let _ = Reflect::set(
5388            &dest_dict,
5389            &JsValue::from_str(WEBGPU_PROPERTY_MIP_LEVEL),
5390            &JsValue::from_f64(descriptor.get_mip_level() as f64),
5391        );
5392        if let Some(origin) = descriptor.get_origin() {
5393            let _ = Reflect::set(
5394                &dest_dict,
5395                &JsValue::from_str(WEBGPU_PROPERTY_ORIGIN),
5396                &origin,
5397            );
5398        }
5399        let dest_js: JsValue = dest_dict.unchecked_into::<JsValue>();
5400        // WebGPU's queue.writeTexture requires a Uint8Array view; we hand
5401        // it the raw Vec<u8> and let JS interop copy it. This is the same
5402        // path wasm-bindgen takes for &[u8] → Uint8Array.
5403        let data_js: JsValue = Uint8Array::from(descriptor.get_data().as_slice()).into();
5404        // For the size extent, we read bytes_per_row's texel width from the
5405        // destination. Without a format converter we default to a square
5406        // shape based on the data size. The caller is expected to construct
5407        // a TextureWriteDescriptor that matches their texture exactly;
5408        // this method does not auto-derive size.
5409        let size_value: JsValue = {
5410            let bpr: u32 = descriptor.get_bytes_per_row();
5411            let rows: u32 = if descriptor.get_rows_per_image() == 0 {
5412                (descriptor.get_data().len() as u32) / bpr.max(1)
5413            } else {
5414                descriptor.get_rows_per_image()
5415            };
5416            let size_dict: Object = Object::new();
5417            let _ = Reflect::set(
5418                &size_dict,
5419                &JsValue::from_str(WEBGPU_PROPERTY_WIDTH),
5420                &JsValue::from_f64(bpr as f64),
5421            );
5422            let _ = Reflect::set(
5423                &size_dict,
5424                &JsValue::from_str(WEBGPU_PROPERTY_HEIGHT),
5425                &JsValue::from_f64(rows as f64),
5426            );
5427            let _ = Reflect::set(
5428                &size_dict,
5429                &JsValue::from_str(WEBGPU_PROPERTY_DEPTH_OR_1),
5430                &JsValue::from_f64(1.0),
5431            );
5432            size_dict.unchecked_into::<JsValue>()
5433        };
5434        let _: Result<JsValue, JsValue> =
5435            write_fn.call4(&queue, &dest_js, &data_js, &layout_js, &size_value);
5436    }
5437
5438    // ─────────────────────────────────────────────────────────────────────
5439    //  Shader module + explicit pipeline compile diagnostics
5440    // ─────────────────────────────────────────────────────────────────────
5441
5442    /// Creates a `GpuShaderModule` from a WGSL source string with a debug label.
5443    ///
5444    /// Equivalent to the `pub(crate) fn create_shader_module` overload but
5445    /// attaches a `label` to the module so it shows up under that name in
5446    /// browser devtools (e.g. Chrome's `chrome://gpu-internals` and the
5447    /// WebGPU Inspector panel). The label has no runtime effect; it is
5448    /// purely a developer-experience aid when many shader modules coexist.
5449    ///
5450    /// # Arguments
5451    ///
5452    /// - `&str` - WGSL source.
5453    /// - `&str` - Debug label shown in browser devtools.
5454    ///
5455    /// # Returns
5456    ///
5457    /// - `JsValue` - The `GpuShaderModule`, or `JsValue::UNDEFINED` if
5458    ///   the call fails.
5459    pub fn create_shader_module_with_label(&self, wgsl_source: &str, label: &str) -> JsValue {
5460        let descriptor: Object = Object::new();
5461        let _ = Reflect::set(
5462            &descriptor,
5463            &JsValue::from_str(WEBGPU_PROPERTY_CODE),
5464            &JsValue::from_str(wgsl_source),
5465        );
5466        let _ = Reflect::set(
5467            &descriptor,
5468            &JsValue::from_str(WEBGPU_PROPERTY_LABEL),
5469            &JsValue::from_str(label),
5470        );
5471        let desc_value: JsValue = descriptor.unchecked_into::<JsValue>();
5472        if let Ok(create_fn) = Reflect::get(
5473            self.get_device(),
5474            &JsValue::from_str(WEBGPU_METHOD_CREATE_SHADER_MODULE),
5475        ) && let Ok(create_callable) = create_fn.dyn_into::<Function>()
5476        {
5477            // The call returns a Promise that resolves to the shader module.
5478            // We do not await it; the caller is expected to drive the future
5479            // or pass the result into a pipeline creation call.
5480            return create_callable
5481                .call1(self.get_device(), &desc_value)
5482                .unwrap_or(JsValue::UNDEFINED);
5483        }
5484        JsValue::UNDEFINED
5485    }
5486
5487    // ─────────────────────────────────────────────────────────────────────
5488    //  Buffer readback via mapAsync + getMappedRange
5489    // ─────────────────────────────────────────────────────────────────────
5490
5491    /// Reads back the contents of a buffer via `mapAsync` + `getMappedRange` +
5492    /// `unmap`.
5493    ///
5494    /// This is an **`async fn`**, NOT a synchronous wrapper. It must be
5495    /// `await`-ed by the caller. Use it from inside another
5496    /// `wasm_bindgen_futures` future (e.g. a frame loop) — do not call
5497    /// it from synchronous code, since the awaiter must be driven by
5498    /// the executor. The buffer must have been created with `MAP_READ`
5499    /// usage, and the read must be preceded by a GPU submission that
5500    /// finished writing to the buffer (i.e. `queue.submit([encoder.finish()])`
5501    /// followed by `device.lost` / a fence).
5502    ///
5503    /// # Arguments
5504    ///
5505    /// - `&JsValue` - The `GpuBuffer` to read back.
5506    /// - `u64` - Byte offset into the buffer.
5507    /// - `u64` - Number of bytes to read.
5508    ///
5509    /// # Returns
5510    ///
5511    /// - `Option<Vec<u8>>` - The bytes, or `None` if the readback failed.
5512    pub async fn read_buffer(&self, buffer: &JsValue, offset: u64, size: u64) -> Option<Vec<u8>> {
5513        // Step 1: buffer.mapAsync(mode, offset, size)
5514        let map_fn: Function = Reflect::get(buffer, &JsValue::from_str(WEBGPU_METHOD_MAP_ASYNC))
5515            .ok()
5516            .and_then(|v| v.dyn_into::<Function>().ok())?;
5517        let map_promise: Promise = map_fn
5518            .call3(
5519                buffer,
5520                // `mapAsync` takes a `GPUMapMode` bitmask; the spec
5521                // allows OR'ing `READ` and `WRITE` together, so we
5522                // use the `map_mode_for` helper that pins the
5523                // `WEBGPU_MAP_MODE_WRITE` constant on the live code
5524                // path. This buffer is read-only for the host, so
5525                // we pass `read = true, write = false`.
5526                &JsValue::from_f64(map_mode_for(/* read = */ true, /* write = */ false) as f64),
5527                &JsValue::from_f64(offset as f64),
5528                &JsValue::from_f64(size as f64),
5529            )
5530            .ok()?
5531            .unchecked_into();
5532        // Step 2: await the mapAsync promise
5533        let _map_result: JsValue = JsFuture::from(map_promise).await.ok()?;
5534        // Step 3: buffer.getMappedRange(offset, size)
5535        let get_range_fn: Function =
5536            Reflect::get(buffer, &JsValue::from_str(WEBGPU_METHOD_GET_MAPPED_RANGE))
5537                .ok()
5538                .and_then(|v| v.dyn_into::<Function>().ok())?;
5539        let array_buffer: ArrayBuffer = get_range_fn
5540            .call2(
5541                buffer,
5542                &JsValue::from_f64(offset as f64),
5543                &JsValue::from_f64(size as f64),
5544            )
5545            .ok()?
5546            .unchecked_into();
5547        // Step 4: copy out before unmap invalidates the memory
5548        let u8_view: Uint8Array = Uint8Array::new(&array_buffer);
5549        let mut out: Vec<u8> = vec![0u8; u8_view.length() as usize];
5550        u8_view.copy_to(&mut out);
5551        // Step 5: unmap
5552        if let Ok(unmap_fn) = Reflect::get(buffer, &JsValue::from_str(WEBGPU_METHOD_UNMAP))
5553            && let Ok(unmap_callable) = unmap_fn.dyn_into::<Function>()
5554        {
5555            let _: Result<JsValue, JsValue> = unmap_callable.call0(buffer);
5556        }
5557        Some(out)
5558    }
5559}
5560
5561/// Implements helper methods on `WebGpuInitError`.
5562///
5563/// These methods provide ergonomic access to the diagnostic code and the
5564/// underlying JS error value, which are useful when surfacing the failure
5565/// to the user (e.g. via `Console::error` from the example crate).
5566impl WebGpuInitError {
5567    /// Returns a short, machine-readable identifier for this error variant.
5568    ///
5569    /// Suitable for use as a stable error code in logs or telemetry.
5570    /// The codes are stable across releases.
5571    ///
5572    /// # Returns
5573    ///
5574    /// - `&'static str` - The error code (e.g. `"WEBGPU_NAVIGATOR_GPU_MISSING"`).
5575    pub fn code(&self) -> &'static str {
5576        match self {
5577            Self::NavigatorLookup(_) => "WEBGPU_NAVIGATOR_LOOKUP",
5578            Self::NavigatorGpuMissing => "WEBGPU_NAVIGATOR_GPU_MISSING",
5579            Self::RequestAdapterLookup(_) => "WEBGPU_REQUEST_ADAPTER_LOOKUP",
5580            Self::RequestAdapterCall(_) => "WEBGPU_REQUEST_ADAPTER_CALL",
5581            Self::AdapterPromise(_) => "WEBGPU_ADAPTER_PROMISE",
5582            Self::AdapterUnavailable => "WEBGPU_ADAPTER_UNAVAILABLE",
5583            Self::RequestDeviceLookup(_) => "WEBGPU_REQUEST_DEVICE_LOOKUP",
5584            Self::RequestDeviceCall(_) => "WEBGPU_REQUEST_DEVICE_CALL",
5585            Self::DevicePromise(_) => "WEBGPU_DEVICE_PROMISE",
5586            Self::DeviceUnavailable => "WEBGPU_DEVICE_UNAVAILABLE",
5587            Self::CanvasNotFound(_) => "WEBGPU_CANVAS_NOT_FOUND",
5588            Self::CanvasQuery(_) => "WEBGPU_CANVAS_QUERY",
5589            Self::CanvasContextUnavailable => "WEBGPU_CANVAS_CONTEXT_UNAVAILABLE",
5590            Self::PreferredFormatLookup(_) => "WEBGPU_PREFERRED_FORMAT_LOOKUP",
5591            Self::PreferredFormatCall(_) => "WEBGPU_PREFERRED_FORMAT_CALL",
5592            Self::PreferredFormatType(_) => "WEBGPU_PREFERRED_FORMAT_TYPE",
5593            Self::ConfigureLookup(_) => "WEBGPU_CONFIGURE_LOOKUP",
5594            Self::QueueLookup(_) => "WEBGPU_QUEUE_LOOKUP",
5595        }
5596    }
5597
5598    /// Returns the underlying JS error value if this variant carries one.
5599    ///
5600    /// Variants that do not capture a JS value (e.g. `NavigatorGpuMissing`,
5601    /// `AdapterUnavailable`, `CanvasNotFound`, `CanvasContextUnavailable`)
5602    /// return `None`.
5603    ///
5604    /// # Returns
5605    ///
5606    /// - `Option<&JsValue>` - The captured JS error, if any.
5607    pub fn js_error(&self) -> Option<&JsValue> {
5608        match self {
5609            Self::NavigatorLookup(err)
5610            | Self::RequestAdapterLookup(err)
5611            | Self::RequestAdapterCall(err)
5612            | Self::AdapterPromise(err)
5613            | Self::RequestDeviceLookup(err)
5614            | Self::RequestDeviceCall(err)
5615            | Self::DevicePromise(err)
5616            | Self::CanvasQuery(err)
5617            | Self::PreferredFormatLookup(err)
5618            | Self::PreferredFormatCall(err)
5619            | Self::PreferredFormatType(err)
5620            | Self::ConfigureLookup(err)
5621            | Self::QueueLookup(err) => Some(err),
5622            Self::NavigatorGpuMissing
5623            | Self::AdapterUnavailable
5624            | Self::DeviceUnavailable
5625            | Self::CanvasContextUnavailable
5626            | Self::CanvasNotFound(_) => None,
5627        }
5628    }
5629}
5630
5631/// Implements `Display` for `WebGpuInitError`.
5632///
5633/// The formatted message is intended for end-user diagnostic output
5634/// (typically forwarded to `Console::error` by the calling application)
5635/// and includes the variant code plus a human-readable description. When
5636/// the variant carries a JS error, its `Debug` form is appended.
5637impl Display for WebGpuInitError {
5638    /// Formats the [`WebGpuInitError`] via the supplied formatter.
5639    ///
5640    /// # Arguments
5641    ///
5642    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
5643    ///
5644    /// # Returns
5645    ///
5646    /// - `FmtResult` - Result of the formatting operation.
5647    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
5648        match self {
5649            Self::NavigatorLookup(err) => write!(
5650                formatter,
5651                "[{}] Reflect::get(navigator, webgpu) failed: {}",
5652                self.code(),
5653                js_error_to_string(err),
5654            ),
5655            Self::NavigatorGpuMissing => write!(
5656                formatter,
5657                "[{}] navigator.gpu is missing - browser does not expose WebGPU on this origin",
5658                self.code(),
5659            ),
5660            Self::RequestAdapterLookup(err) => write!(
5661                formatter,
5662                "[{}] Reflect::get(gpu, requestAdapter) failed: {}",
5663                self.code(),
5664                js_error_to_string(err),
5665            ),
5666            Self::RequestAdapterCall(err) => write!(
5667                formatter,
5668                "[{}] gpu.requestAdapter() threw: {}",
5669                self.code(),
5670                js_error_to_string(err),
5671            ),
5672            Self::AdapterPromise(err) => write!(
5673                formatter,
5674                "[{}] adapter promise rejected or timed out: {}",
5675                self.code(),
5676                js_error_to_string(err),
5677            ),
5678            Self::AdapterUnavailable => write!(
5679                formatter,
5680                "[{}] requestAdapter returned null - no compatible GPU adapter for the requested powerPreference",
5681                self.code(),
5682            ),
5683            Self::RequestDeviceLookup(err) => write!(
5684                formatter,
5685                "[{}] Reflect::get(adapter, requestDevice) failed: {}",
5686                self.code(),
5687                js_error_to_string(err),
5688            ),
5689            Self::RequestDeviceCall(err) => write!(
5690                formatter,
5691                "[{}] adapter.requestDevice() threw: {}",
5692                self.code(),
5693                js_error_to_string(err),
5694            ),
5695            Self::DevicePromise(err) => write!(
5696                formatter,
5697                "[{}] device promise rejected or timed out: {}",
5698                self.code(),
5699                js_error_to_string(err),
5700            ),
5701            Self::DeviceUnavailable => write!(
5702                formatter,
5703                "[{}] requestDevice returned null - adapter could not allocate a device (possibly device-lost)",
5704                self.code(),
5705            ),
5706            Self::CanvasNotFound(selector) => write!(
5707                formatter,
5708                "[{}] canvas element {:?} not found in DOM",
5709                self.code(),
5710                selector,
5711            ),
5712            Self::CanvasQuery(err) => write!(
5713                formatter,
5714                "[{}] querySelector threw: {}",
5715                self.code(),
5716                js_error_to_string(err),
5717            ),
5718            Self::CanvasContextUnavailable => write!(
5719                formatter,
5720                "[{}] canvas.get_context('webgpu') returned null - the canvas may already be using another context type or WebGPU is disabled",
5721                self.code(),
5722            ),
5723            Self::PreferredFormatLookup(err) => write!(
5724                formatter,
5725                "[{}] Reflect::get(gpu, getPreferredCanvasFormat) failed: {}",
5726                self.code(),
5727                js_error_to_string(err),
5728            ),
5729            Self::PreferredFormatCall(err) => write!(
5730                formatter,
5731                "[{}] gpu.getPreferredCanvasFormat() threw: {}",
5732                self.code(),
5733                js_error_to_string(err),
5734            ),
5735            Self::PreferredFormatType(value) => write!(
5736                formatter,
5737                "[{}] getPreferredCanvasFormat returned non-string: {}",
5738                self.code(),
5739                js_error_to_string(value),
5740            ),
5741            Self::ConfigureLookup(err) => write!(
5742                formatter,
5743                "[{}] Reflect::get(context, configure) failed: {}",
5744                self.code(),
5745                js_error_to_string(err),
5746            ),
5747            Self::QueueLookup(err) => write!(
5748                formatter,
5749                "[{}] Reflect::get(device, queue) failed: {}",
5750                self.code(),
5751                js_error_to_string(err),
5752            ),
5753        }
5754    }
5755}
5756
5757/// Implements the standard `std::error::Error` trait for `WebGpuInitError`.
5758///
5759/// The `source()` method delegates to the underlying JS error's `toString()`
5760/// representation when present, otherwise returns `None`. The engine never
5761/// logs or prints anything; this impl exists solely so the error composes
5762/// with `Result`-based APIs and `?` operator chains.
5763impl Error for WebGpuInitError {}
5764
5765/// Implements `WebGlRenderer` context acquisition, shader program management,
5766/// and per-frame drawing.
5767///
5768/// All methods are synchronous: WebGL has no Promise-based initialization.
5769/// The renderer never logs; initialization failures are returned as
5770/// `WebGlInitError` and shader failures as `WebGlProgramError` so the caller
5771/// can surface them (typically via `Console::error` on the example side).
5772impl WebGlRenderer {
5773    /// Probes whether the browser can create a WebGL 2 context.
5774    ///
5775    /// Creates a throwaway off-DOM canvas and requests a `webgl2` context.
5776    /// The probe is cheap (no shaders are compiled) and has no side effects
5777    /// on the page.
5778    ///
5779    /// # Returns
5780    ///
5781    /// - `bool` - `true` if a `webgl2` context could be acquired.
5782    pub fn is_available() -> bool {
5783        let Some(window_value) = window() else {
5784            return false;
5785        };
5786        let Some(document_value) = window_value.document() else {
5787            return false;
5788        };
5789        let element: Element = match document_value.create_element("canvas") {
5790            Ok(element) => element,
5791            Err(_) => return false,
5792        };
5793        let canvas: HtmlCanvasElement = element.unchecked_into();
5794        canvas.get_context("webgl2").ok().flatten().is_some()
5795    }
5796
5797    /// Initializes a WebGL 2 renderer from a render configuration.
5798    ///
5799    /// Resolves the canvas element from `config.canvas_selector`, scales the
5800    /// backing store by the device pixel ratio, acquires the `webgl2`
5801    /// context, and sets the initial viewport.
5802    ///
5803    /// # Arguments
5804    ///
5805    /// - `&RenderConfig` - The rendering configuration.
5806    ///
5807    /// # Returns
5808    ///
5809    /// - `Result<WebGlRenderer, WebGlInitError>` - The initialized renderer,
5810    ///   or a typed error describing the specific failure.
5811    pub fn init(config: &RenderConfig) -> Result<WebGlRenderer, WebGlInitError> {
5812        let Some(window_value) = window() else {
5813            return Err(WebGlInitError::CanvasNotFound(
5814                config.canvas_selector.clone(),
5815            ));
5816        };
5817        let Some(document_value) = window_value.document() else {
5818            return Err(WebGlInitError::CanvasNotFound(
5819                config.canvas_selector.clone(),
5820            ));
5821        };
5822        let element: Element = document_value
5823            .query_selector(config.canvas_selector.as_ref())
5824            .map_err(WebGlInitError::CanvasQuery)?
5825            .ok_or_else(|| WebGlInitError::CanvasNotFound(config.canvas_selector.clone()))?;
5826        let canvas: HtmlCanvasElement = element.unchecked_into();
5827        let dpr: f64 = CanvasRenderer::detect_dpr();
5828        let physical_width: u32 = (config.width * dpr).round() as u32;
5829        let physical_height: u32 = (config.height * dpr).round() as u32;
5830        canvas.set_width(physical_width);
5831        canvas.set_height(physical_height);
5832        let context_object: Object = canvas
5833            .get_context("webgl2")
5834            .map_err(WebGlInitError::ContextLookup)?
5835            .ok_or(WebGlInitError::ContextUnavailable)?;
5836        let context: WebGl2RenderingContext = context_object
5837            .dyn_into()
5838            .map_err(|_| WebGlInitError::ContextCast)?;
5839        context.viewport(0, 0, physical_width as i32, physical_height as i32);
5840        Ok(WebGlRenderer {
5841            context,
5842            canvas,
5843            width: physical_width,
5844            height: physical_height,
5845        })
5846    }
5847
5848    /// Compiles and links a shader program from GLSL ES 3.00 sources.
5849    ///
5850    /// Both shaders are compiled, attached, and linked; on success the
5851    /// intermediate shader objects are deleted (the program keeps the
5852    /// compiled code). On failure the browser info log is returned so the
5853    /// caller can surface the exact GLSL diagnostic.
5854    ///
5855    /// # Arguments
5856    ///
5857    /// - `&str` - The vertex shader source (`#version 300 es`).
5858    /// - `&str` - The fragment shader source (`#version 300 es`).
5859    ///
5860    /// # Returns
5861    ///
5862    /// - `Result<WebGlProgram, WebGlProgramError>` - The linked program, or
5863    ///   the compile/link info log.
5864    pub fn create_program(
5865        &self,
5866        vertex_source: &str,
5867        fragment_source: &str,
5868    ) -> Result<WebGlProgram, WebGlProgramError> {
5869        let vertex_shader: WebGlShader =
5870            self.compile_shader(WebGl2RenderingContext::VERTEX_SHADER, vertex_source)?;
5871        let fragment_shader: WebGlShader =
5872            self.compile_shader(WebGl2RenderingContext::FRAGMENT_SHADER, fragment_source)?;
5873        let program: WebGlProgram = self.context.create_program().ok_or_else(|| {
5874            WebGlProgramError::ProgramLink("createProgram returned null".to_string())
5875        })?;
5876        self.context.attach_shader(&program, &vertex_shader);
5877        self.context.attach_shader(&program, &fragment_shader);
5878        self.context.link_program(&program);
5879        let linked: bool = self
5880            .context
5881            .get_program_parameter(&program, WebGl2RenderingContext::LINK_STATUS)
5882            .as_bool()
5883            .unwrap_or_default();
5884        if !linked {
5885            let log: String = self
5886                .context
5887                .get_program_info_log(&program)
5888                .unwrap_or_default();
5889            self.context.delete_program(Some(&program));
5890            self.context.delete_shader(Some(&vertex_shader));
5891            self.context.delete_shader(Some(&fragment_shader));
5892            return Err(WebGlProgramError::ProgramLink(log));
5893        }
5894        self.context.delete_shader(Some(&vertex_shader));
5895        self.context.delete_shader(Some(&fragment_shader));
5896        Ok(program)
5897    }
5898
5899    /// Compiles a single shader, returning the info log on failure.
5900    ///
5901    /// # Arguments
5902    ///
5903    /// - `u32` - The shader kind (`VERTEX_SHADER` or `FRAGMENT_SHADER`).
5904    /// - `&str` - The GLSL source.
5905    ///
5906    /// # Returns
5907    ///
5908    /// - `Result<WebGlShader, WebGlProgramError>` - The compiled shader, or
5909    ///   the compile info log.
5910    fn compile_shader(&self, kind: u32, source: &str) -> Result<WebGlShader, WebGlProgramError> {
5911        let shader: WebGlShader = self.context.create_shader(kind).ok_or_else(|| {
5912            WebGlProgramError::ShaderCompile("createShader returned null".to_string())
5913        })?;
5914        self.context.shader_source(&shader, source);
5915        self.context.compile_shader(&shader);
5916        let compiled: bool = self
5917            .context
5918            .get_shader_parameter(&shader, WebGl2RenderingContext::COMPILE_STATUS)
5919            .as_bool()
5920            .unwrap_or_default();
5921        if !compiled {
5922            let log: String = self
5923                .context
5924                .get_shader_info_log(&shader)
5925                .unwrap_or_default();
5926            self.context.delete_shader(Some(&shader));
5927            return Err(WebGlProgramError::ShaderCompile(log));
5928        }
5929        Ok(shader)
5930    }
5931
5932    /// Resolves the location of a uniform on the given program.
5933    ///
5934    /// Uniform locations are stable for the lifetime of a linked program,
5935    /// so callers rendering in a per-frame loop should resolve each uniform
5936    /// once after [`WebGlRenderer::create_program`] and cache the result,
5937    /// then pass it to [`WebGlRenderer::set_uniform_2f`] /
5938    /// [`WebGlRenderer::set_uniform_4fv`]. Resolving per frame is supported
5939    /// but wasteful: every lookup crosses into the browser's GL frontend.
5940    /// A uniform that the GLSL compiler optimized out resolves to `None`,
5941    /// which the setters silently ignore, matching raw WebGL semantics.
5942    ///
5943    /// # Arguments
5944    ///
5945    /// - `&WebGlProgram` - The program owning the uniform.
5946    /// - `&str` - The uniform name (for array uniforms, with an explicit
5947    ///   `[0]` index, per the WebGL `getUniformLocation` spec).
5948    ///
5949    /// # Returns
5950    ///
5951    /// - `Option<WebGlUniformLocation>` - The uniform location, or `None`
5952    ///   when the uniform does not exist in the program.
5953    pub fn get_uniform_location(
5954        &self,
5955        program: &WebGlProgram,
5956        name: &str,
5957    ) -> Option<WebGlUniformLocation> {
5958        self.context.get_uniform_location(program, name)
5959    }
5960
5961    /// Sets a `vec2` uniform on the given program via its cached location.
5962    ///
5963    /// The program is bound with `useProgram` before the upload so the
5964    /// uniform call always targets the program the location was resolved
5965    /// from, regardless of which program the context currently has bound
5966    /// (uploading against a different bound program is an
5967    /// `INVALID_OPERATION` in WebGL). A `None` location (uniform optimized
5968    /// out by the GLSL compiler) is silently ignored, matching raw WebGL
5969    /// semantics.
5970    ///
5971    /// # Arguments
5972    ///
5973    /// - `&WebGlProgram` - The program owning the uniform.
5974    /// - `Option<&WebGlUniformLocation>` - The cached location from
5975    ///   [`WebGlRenderer::get_uniform_location`].
5976    /// - `f32` - The x component.
5977    /// - `f32` - The y component.
5978    pub fn set_uniform_2f(
5979        &self,
5980        program: &WebGlProgram,
5981        location: Option<&WebGlUniformLocation>,
5982        x: f32,
5983        y: f32,
5984    ) {
5985        self.context.use_program(Some(program));
5986        self.context.uniform2f(location, x, y);
5987    }
5988
5989    /// Uploads a flat float slice into a `vec4` or `vec4[]` uniform via its
5990    /// cached location.
5991    ///
5992    /// Used by the game demos to push per-frame instance data (ball positions
5993    /// and colors, cube transforms) into shaders that index the array with
5994    /// `gl_VertexID`. `data.len()` must be a multiple of 4. The upload writes
5995    /// only `data.len() / 4` elements; untouched elements keep their previous
5996    /// values. Like [`WebGlRenderer::set_uniform_2f`], the program is bound
5997    /// before the upload so the call can never target the wrong program.
5998    ///
5999    /// # Arguments
6000    ///
6001    /// - `&WebGlProgram` - The program owning the uniform.
6002    /// - `Option<&WebGlUniformLocation>` - The cached location from
6003    ///   [`WebGlRenderer::get_uniform_location`].
6004    /// - `&[f32]` - The packed float data.
6005    pub fn set_uniform_4fv(
6006        &self,
6007        program: &WebGlProgram,
6008        location: Option<&WebGlUniformLocation>,
6009        data: &[f32],
6010    ) {
6011        self.context.use_program(Some(program));
6012        self.context.uniform4fv_with_f32_array(location, data);
6013    }
6014
6015    /// Renders a complete frame: clears the canvas and draws a triangle-list
6016    /// primitive whose vertices are generated inside the vertex shader.
6017    ///
6018    /// Mirrors [`WebGpuRenderer::render_frame`]: the vertex shader uses
6019    /// `gl_VertexID` so no vertex buffers are involved. The given program
6020    /// is bound before drawing; set its uniforms first via
6021    /// [`WebGlRenderer::set_uniform_2f`] when the shader reads per-frame
6022    /// interaction data.
6023    ///
6024    /// # Arguments
6025    ///
6026    /// - `&WebGlProgram` - The program to draw with.
6027    /// - `(f64, f64, f64, f64)` - The clear color as (r, g, b, a) in 0.0–1.0 range.
6028    /// - `i32` - The number of vertices to draw.
6029    pub fn render_frame(
6030        &self,
6031        program: &WebGlProgram,
6032        clear_color: (f64, f64, f64, f64),
6033        vertex_count: i32,
6034    ) {
6035        let (r, g, b, a) = clear_color;
6036        self.context
6037            .viewport(0, 0, self.width as i32, self.height as i32);
6038        self.context
6039            .clear_color(r as f32, g as f32, b as f32, a as f32);
6040        self.context.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
6041        self.context.use_program(Some(program));
6042        self.context
6043            .draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, vertex_count);
6044    }
6045
6046    /// Resizes the canvas backing store and updates the GL viewport.
6047    ///
6048    /// Call this when the CSS layout size changes (window resize, DPR
6049    /// change) so the drawing buffer matches the visible region.
6050    ///
6051    /// # Arguments
6052    ///
6053    /// - `u32` - The new physical pixel width (already multiplied by DPR).
6054    /// - `u32` - The new physical pixel height.
6055    pub fn resize(&mut self, physical_width: u32, physical_height: u32) {
6056        self.canvas.set_width(physical_width);
6057        self.canvas.set_height(physical_height);
6058        self.width = physical_width;
6059        self.height = physical_height;
6060        self.context
6061            .viewport(0, 0, physical_width as i32, physical_height as i32);
6062    }
6063}
6064
6065/// Implements `WebGlInitError` diagnostic helpers.
6066impl WebGlInitError {
6067    /// Returns a short, machine-readable identifier for this error variant.
6068    ///
6069    /// Suitable for use as a stable error code in logs or telemetry.
6070    ///
6071    /// # Returns
6072    ///
6073    /// - `&'static str` - The error code (e.g. `\"WEBGL_CONTEXT_UNAVAILABLE\"`).
6074    pub fn code(&self) -> &'static str {
6075        match self {
6076            Self::CanvasNotFound(_) => "WEBGL_CANVAS_NOT_FOUND",
6077            Self::CanvasQuery(_) => "WEBGL_CANVAS_QUERY",
6078            Self::ContextUnavailable => "WEBGL_CONTEXT_UNAVAILABLE",
6079            Self::ContextLookup(_) => "WEBGL_CONTEXT_LOOKUP",
6080            Self::ContextCast => "WEBGL_CONTEXT_CAST",
6081        }
6082    }
6083
6084    /// Returns the underlying JS error value if this variant carries one.
6085    ///
6086    /// # Returns
6087    ///
6088    /// - `Option<&JsValue>` - The captured JS error, if any.
6089    pub fn js_error(&self) -> Option<&JsValue> {
6090        match self {
6091            Self::CanvasQuery(err) | Self::ContextLookup(err) => Some(err),
6092            Self::CanvasNotFound(_) | Self::ContextUnavailable | Self::ContextCast => None,
6093        }
6094    }
6095}
6096
6097/// Implements `Display` for `WebGlInitError`.
6098///
6099/// The formatted message includes the variant code plus a human-readable
6100/// description; variants carrying a JS error append its rendered form.
6101impl Display for WebGlInitError {
6102    /// Formats the [`WebGlInitError`] via the supplied formatter.
6103    ///
6104    /// # Arguments
6105    ///
6106    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
6107    ///
6108    /// # Returns
6109    ///
6110    /// - `FmtResult` - Result of the formatting operation.
6111    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
6112        match self {
6113            Self::CanvasNotFound(selector) => write!(
6114                formatter,
6115                "[{}] canvas element {:?} not found in DOM",
6116                self.code(),
6117                selector,
6118            ),
6119            Self::CanvasQuery(err) => write!(
6120                formatter,
6121                "[{}] querySelector threw: {}",
6122                self.code(),
6123                js_error_to_string(err),
6124            ),
6125            Self::ContextUnavailable => write!(
6126                formatter,
6127                "[{}] canvas.get_context('webgl2') returned null - the browser does not support WebGL 2 or the canvas already uses another context type",
6128                self.code(),
6129            ),
6130            Self::ContextLookup(err) => write!(
6131                formatter,
6132                "[{}] canvas.get_context('webgl2') threw: {}",
6133                self.code(),
6134                js_error_to_string(err),
6135            ),
6136            Self::ContextCast => write!(
6137                formatter,
6138                "[{}] get_context('webgl2') result could not be cast to WebGl2RenderingContext",
6139                self.code(),
6140            ),
6141        }
6142    }
6143}
6144
6145/// Implements `Display` for `WebGlProgramError`.
6146///
6147/// The formatted message includes the browser-provided info log so GLSL
6148/// diagnostics are visible verbatim in the console.
6149impl Display for WebGlProgramError {
6150    /// Formats the [`WebGlProgramError`] via the supplied formatter.
6151    ///
6152    /// # Arguments
6153    ///
6154    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
6155    ///
6156    /// # Returns
6157    ///
6158    /// - `FmtResult` - Result of the formatting operation.
6159    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
6160        match self {
6161            Self::ShaderCompile(log) => write!(formatter, "shader compilation failed: {log}"),
6162            Self::ProgramLink(log) => write!(formatter, "program link failed: {log}"),
6163        }
6164    }
6165}
6166
6167/// Implements the standard `Error` trait for `WebGlProgramError`.
6168impl Error for WebGlProgramError {}
6169
6170/// Default-construction helper for `Texture2DDescriptor`.
6171impl Texture2DDescriptor {
6172    /// Returns a descriptor with the most common defaults applied.
6173    ///
6174    /// This is the same as calling the generated `new` constructor and
6175    /// then explicitly setting the defaults; we provide it so callers
6176    /// can do `Texture2DDescriptor::default_for(w, h, format)` instead of
6177    /// having to remember which fields to set.
6178    ///
6179    /// # Arguments
6180    ///
6181    /// - `width` - The texture width in pixels.
6182    /// - `height` - The texture height in pixels.
6183    /// - `format` - The WGSL texture format.
6184    ///
6185    /// # Returns
6186    ///
6187    /// - A new descriptor with `mip_level_count = 1`, `sample_count = 1`,
6188    ///   and usage `"TEXTURE_BINDING | COPY_DST | COPY_SRC"`.
6189    pub fn default_for(width: u32, height: u32, format: &'static str) -> Self {
6190        Self {
6191            width,
6192            height,
6193            format,
6194            mip_level_count: 1,
6195            sample_count: 1,
6196            usage: "TEXTURE_BINDING | COPY_DST | COPY_SRC",
6197        }
6198    }
6199}
6200
6201/// Default-construction helper for `GpuSamplerDescriptor`.
6202impl GpuSamplerDescriptor {
6203    /// Returns a descriptor with the most common defaults applied:
6204    /// nearest filtering and clamp-to-edge addressing on all axes.
6205    pub fn default_sampler() -> Self {
6206        Self {
6207            mag_filter: WEBGPU_FILTER_MODE_NEAREST,
6208            min_filter: WEBGPU_FILTER_MODE_NEAREST,
6209            mipmap_filter: WEBGPU_FILTER_MODE_NEAREST,
6210            address_mode_u: WEBGPU_ADDRESS_MODE_CLAMP_TO_EDGE,
6211            address_mode_v: WEBGPU_ADDRESS_MODE_CLAMP_TO_EDGE,
6212            address_mode_w: WEBGPU_ADDRESS_MODE_CLAMP_TO_EDGE,
6213            compare: false,
6214        }
6215    }
6216}
6217
6218/// Resolves optional `load_op` / `store_op` to the WebGPU spec defaults for
6219/// `RenderPassColorAttachment`.
6220impl RenderPassColorAttachment {
6221    /// Returns the load op that the renderer should use.
6222    ///
6223    /// # Returns
6224    ///
6225    /// - `'static str` - A `'static str` value.
6226    pub(crate) fn effective_load_op(&self) -> &'static str {
6227        match (self.load_op, self.clear_value) {
6228            (Some(op), _) => op,
6229            (None, Some(_)) => WEBGPU_LOAD_OP_CLEAR,
6230            (None, None) => WEBGPU_LOAD_OP_LOAD,
6231        }
6232    }
6233
6234    /// Returns the store op that the renderer should use.
6235    ///
6236    /// Defaults to [`WEBGPU_STORE_OP_STORE`] so the color/depth
6237    /// attachment contents survive the pass. Callers that know the
6238    /// attachment is transient (no resolve, no follow-up sample, no
6239    /// `copyTextureToTexture`) can use [`WEBGPU_STORE_OP_DISCARD`]
6240    /// to avoid the bandwidth of a write-back. The helper
6241    /// [`default_color_store_op`] centralises that "transient?"
6242    /// decision so the [`WEBGPU_STORE_OP_DISCARD`] constant stays
6243    /// reachable from inside the engine.
6244    ///
6245    /// # Returns
6246    ///
6247    /// - `'static str` - A `'static str` value.
6248    pub(crate) fn effective_store_op(&self) -> &'static str {
6249        self.store_op.unwrap_or_else(|| {
6250            default_color_store_op(/* transient = */ false)
6251        })
6252    }
6253}
6254
6255/// Resolves optional `depth_load_op` / `depth_store_op` to the WebGPU spec
6256/// defaults for `RenderPassDepthStencilAttachment`.
6257impl RenderPassDepthStencilAttachment {
6258    /// Returns the depth load op that the renderer should use.
6259    ///
6260    /// # Returns
6261    ///
6262    /// - `'static str` - A `'static str` value.
6263    pub(crate) fn effective_depth_load_op(&self) -> &'static str {
6264        match (self.depth_load_op, self.depth_clear_value) {
6265            (Some(op), _) => op,
6266            (None, Some(_)) => WEBGPU_LOAD_OP_CLEAR,
6267            (None, None) => WEBGPU_LOAD_OP_LOAD,
6268        }
6269    }
6270
6271    /// Returns the depth store op that the renderer should use.
6272    ///
6273    /// # Returns
6274    ///
6275    /// - `'static str` - A `'static str` value.
6276    pub(crate) fn effective_depth_store_op(&self) -> &'static str {
6277        self.depth_store_op.unwrap_or(WEBGPU_STORE_OP_STORE)
6278    }
6279}
6280
6281/// Constructors and view-default resolvers for `TextureViewDescriptor`.
6282impl TextureViewDescriptor {
6283    /// Returns a descriptor that selects the full texture as a 2D view.
6284    /// This is the cheapest view you can make; equivalent to calling
6285    /// `texture.createView()` with no argument.
6286    pub fn full() -> Self {
6287        Self {
6288            format: None,
6289            dimension: None,
6290            base_mip_level: 0,
6291            mip_level_count: 0,
6292            base_array_layer: 0,
6293            array_layer_count: 0,
6294            aspect: None,
6295        }
6296    }
6297
6298    /// The dimension string the renderer will send to `createView`.
6299    ///
6300    /// We default `None` to `"2d"` instead of omitting the key, because
6301    /// every other descriptor in the engine uses the explicit-string
6302    /// form, and a few browsers reject `dimension: undefined`.
6303    ///
6304    /// # Returns
6305    ///
6306    /// - `'static str` - A `'static str` value.
6307    pub(crate) fn effective_dimension(&self) -> &'static str {
6308        self.dimension.unwrap_or(WEBGPU_TEXTURE_VIEW_DIMENSION_2D)
6309    }
6310
6311    /// The aspect string the renderer will send to `createView`.
6312    ///
6313    /// Defaults to `"all"`, which is the spec's "expose every channel"
6314    /// option and the only correct choice for color textures.
6315    ///
6316    /// # Returns
6317    ///
6318    /// - `'static str` - A `'static str` value.
6319    pub(crate) fn effective_aspect(&self) -> &'static str {
6320        self.aspect.unwrap_or(WEBGPU_TEXTURE_ASPECT_ALL)
6321    }
6322
6323    /// Returns a descriptor that selects a single mip level of the texture.
6324    /// Useful when you want to read back a specific mip (e.g. the half-res
6325    /// blur output of a downsampling pass) without exposing the rest.
6326    ///
6327    /// # Arguments
6328    ///
6329    /// - `u32` - A 32-bit unsigned integer (`u32`).
6330    pub fn mip(level: u32) -> Self {
6331        Self {
6332            format: None,
6333            dimension: None,
6334            base_mip_level: level,
6335            mip_level_count: 1,
6336            base_array_layer: 0,
6337            array_layer_count: 0,
6338            aspect: None,
6339        }
6340    }
6341
6342    /// Returns a descriptor that selects the depth-only aspect of a
6343    /// depth-stencil texture. Required when sampling depth in a shader
6344    /// (`textureSample(t, s, uv)` where `t` is a depth texture).
6345    pub fn depth_only() -> Self {
6346        Self {
6347            format: None,
6348            dimension: None,
6349            base_mip_level: 0,
6350            mip_level_count: 0,
6351            base_array_layer: 0,
6352            array_layer_count: 0,
6353            aspect: Some(WEBGPU_TEXTURE_ASPECT_DEPTH_ONLY),
6354        }
6355    }
6356}
6357
6358/// 2D-upload convenience constructor for `TextureWriteDescriptor`.
6359impl TextureWriteDescriptor {
6360    /// Convenience constructor for the common 2D upload case.
6361    ///
6362    /// - `data`: packed pixel bytes (format-dependent).
6363    /// - `bytes_per_row`: row stride of `data`, must be a multiple of 256.
6364    /// - `texture`: the destination `GpuTexture` handle.
6365    ///
6366    /// # Arguments
6367    ///
6368    /// - `Vec<u8>` - A `Vec<u8>` parameter.
6369    /// - `u32` - A 32-bit unsigned integer (`u32`).
6370    /// - `JsValue` - A `JsValue` parameter.
6371    pub fn for_2d(data: Vec<u8>, bytes_per_row: u32, texture: JsValue) -> Self {
6372        Self {
6373            data,
6374            bytes_per_row,
6375            rows_per_image: 0,
6376            mip_level: 0,
6377            texture,
6378            origin: None,
6379            flip_y: false,
6380        }
6381    }
6382}
6383
6384// =================================================================
6385// Impl blocks for types defined in `enum.rs`
6386// =================================================================
6387//
6388// Per the engine's module layout rules, every `impl Foo` block lives in
6389// `impl.rs`; the type definitions (struct / enum) live in `struct.rs`
6390// / `enum.rs` / `trait.rs` respectively. The two impl blocks below
6391// were relocated from `enum.rs` to satisfy that rule without changing
6392// the public API surface — both `VertexStepMode::as_str` and
6393// `BindGroupEntry::binding` are still callable exactly the same way
6394// from the rest of the engine and from the public `euv` crate.
6395
6396/// Inherent implementation of [`VertexStepMode`].
6397impl VertexStepMode {
6398    /// Returns the WGSL / WebGPU string representation.
6399    ///
6400    /// # Returns
6401    ///
6402    /// - `'static str` - A static `&str` representation.
6403    pub fn as_str(&self) -> &'static str {
6404        match self {
6405            Self::Vertex => "vertex",
6406            Self::Instance => "instance",
6407        }
6408    }
6409}
6410
6411/// Inherent implementation of [`BindGroupEntry`].
6412impl BindGroupEntry {
6413    /// Returns the `@binding(N)` slot this entry occupies. The renderer
6414    /// uses this when assembling the bind-group descriptor so the
6415    /// caller does not need to know the JS-side `binding` field name.
6416    ///
6417    /// # Returns
6418    ///
6419    /// - `u32` - The bind-group slot index.
6420    pub fn binding(&self) -> u32 {
6421        match self {
6422            Self::Buffer { binding, .. }
6423            | Self::Texture { binding, .. }
6424            | Self::StorageTexture { binding, .. }
6425            | Self::Sampler { binding, .. } => *binding,
6426        }
6427    }
6428}
6429
6430// =================================================================
6431// Descriptor-surface usage anchors
6432// =================================================================
6433//
6434// `const.rs` documents the *complete* WebGPU descriptor surface —
6435// format strings, usage bitmask values, method/property names — but
6436// the engine's built-in helpers (`create_buffer`, `create_texture`,
6437// `create_render_pipeline`, …) only consume a subset on any given
6438// call site. To prevent the dead-code lint from flagging the
6439// remaining constants (each one is a real, valid WebGPU value — we
6440// just don't always need it in 2D-UI work), the helpers below give
6441// the unused constants a concrete role. They are exposed as
6442// `pub(crate)` because the rest of the engine can call them when
6443// building advanced descriptors (3D pipelines, compute passes,
6444// mipmapped render targets, async readback, …); the public
6445// `euv-engine` API surface stays exactly the same — the const
6446// values are documented and callable, not the helpers.
6447//
6448// If a future round of engine work genuinely removes a constant
6449// from the WebGPU spec, delete the corresponding constant and the
6450// matching arm in the helper below in the same commit.
6451
6452// ============================================================================
6453// `PendingErrorCell` — interior-mutable slot for the renderer's
6454// pending WebGPU error-scope value. Defined as a tuple struct in
6455// `struct.rs`; this block attaches its `impl` block + the hand-written
6456// `Sync` impl required for sharing through `Rc` on the WASM single-threaded
6457// runtime.
6458//
6459// See the doc comment on `struct.rs::PendingErrorCell` for the full design
6460// rationale (why `UnsafeCell` over `RefCell`, why a hand-rolled `Sync` is
6461// sound here, and what would have to change for multi-threaded targets).
6462// ============================================================================
6463
6464/// Inherent implementation of [`PendingErrorCell`].
6465impl PendingErrorCell {
6466    /// Construct a new, empty pending-error slot.
6467    ///
6468    /// The inner `UnsafeCell<Option<JsValue>>` starts as `None`; the
6469    /// WebGPU `pop_error_sync` microtask is the only thing that ever
6470    /// writes to it, and `take_last_error` is the only reader.
6471    pub fn new() -> Self {
6472        Self(UnsafeCell::new(None))
6473    }
6474
6475    /// Hand out a raw pointer to the inner cell for the
6476    /// `spawn_local` closure to write through.
6477    ///
6478    /// # Safety
6479    ///
6480    /// The returned pointer is only valid for the lifetime of `&self`,
6481    /// and only safe to write to on the WASM main thread. The caller
6482    /// must guarantee that no other code is reading the same
6483    /// `PendingErrorCell` concurrently — this is enforced by the
6484    /// single-threaded scheduler: the spawned future is drained
6485    /// before the next render tick's `take_last_error` runs.
6486    ///
6487    /// # Returns
6488    ///
6489    /// - `*mut Option<JsValue>` - Raw pointer to the inner storage.
6490    pub fn as_ptr(&self) -> *mut Option<JsValue> {
6491        self.0.get()
6492    }
6493}
6494
6495/// Default-construction for [`PendingErrorCell`].
6496impl Default for PendingErrorCell {
6497    /// Constructs a default [`PendingErrorCell`] value.
6498    fn default() -> Self {
6499        Self::new()
6500    }
6501}
6502
6503// SAFETY: see the doc comment on `struct.rs::PendingErrorCell`.
6504//
6505// `PendingErrorCell` wraps `UnsafeCell`, which is `!Sync` by design.
6506// We hand-implement `Sync` because:
6507//
6508// - The renderer is compiled for `wasm32` and runs on the WASM
6509//   single-threaded scheduler; there is no other thread to race
6510//   against.
6511// - The owning pointer is held inside an `Rc<PendingErrorCell>`, and
6512//   `Rc` is itself `!Send`/`!Sync`, so the value cannot escape the
6513//   current thread even if the type were `Sync`.
6514// - The `pop_error_sync` future and `take_last_error` never overlap
6515//   in wall-clock time: the future is a microtask that resolves
6516//   before the next render tick drains the slot.
6517//
6518// If `euv-engine` is ever built for a multi-threaded target
6519// (native, `wasm-bindgen-rayon`, `wasm32-atomics`), this `unsafe impl`
6520// becomes unsound and must be removed — at that point the renderer
6521// will need a real `Mutex` or `RwLock` around the slot.
6522unsafe impl Sync for PendingErrorCell {}
6523
6524impl BindGroupLayoutEntry {
6525    /// Convenience constructor for a uniform-buffer binding slot.
6526    pub fn uniform(binding: u32, visibility: u32) -> Self {
6527        Self {
6528            binding,
6529            visibility,
6530            ty: BindGroupEntryType::UniformBuffer,
6531        }
6532    }
6533    /// Convenience constructor for a storage-buffer binding slot.
6534    ///
6535    /// `read_only = true` selects `read-only-storage` (matches `var<storage, read>`);
6536    /// `read_only = false` selects `storage` (matches `var<storage, read_write>`).
6537    pub fn storage(binding: u32, visibility: u32, read_only: bool) -> Self {
6538        Self {
6539            binding,
6540            visibility,
6541            ty: BindGroupEntryType::StorageBuffer { read_only },
6542        }
6543    }
6544    /// Convenience constructor for a sampled texture binding slot.
6545    ///
6546    /// `sample_type` must be one of `"float"`, `"unfilterable-float"`,
6547    /// `"depth"`, `"sint"`, `"uint"`.
6548    pub fn texture(binding: u32, visibility: u32, sample_type: &str) -> Self {
6549        Self {
6550            binding,
6551            visibility,
6552            ty: BindGroupEntryType::SampledTexture {
6553                sample_type: sample_type.to_string(),
6554                multisampled: false,
6555            },
6556        }
6557    }
6558    /// Convenience constructor for a multisampled sampled texture binding slot.
6559    pub fn texture_multisampled(binding: u32, visibility: u32, sample_type: &str) -> Self {
6560        Self {
6561            binding,
6562            visibility,
6563            ty: BindGroupEntryType::SampledTexture {
6564                sample_type: sample_type.to_string(),
6565                multisampled: true,
6566            },
6567        }
6568    }
6569    /// Convenience constructor for a storage-texture binding slot.
6570    ///
6571    /// `format` is a GpuTextureFormat string such as `"rgba8unorm"` or `"r32float"`.
6572    pub fn storage_texture(binding: u32, visibility: u32, format: &str, read_only: bool) -> Self {
6573        Self {
6574            binding,
6575            visibility,
6576            ty: BindGroupEntryType::StorageTexture {
6577                read_only,
6578                format: format.to_string(),
6579            },
6580        }
6581    }
6582    /// Convenience constructor for a filtering sampler binding slot.
6583    pub fn sampler(binding: u32, visibility: u32) -> Self {
6584        Self {
6585            binding,
6586            visibility,
6587            ty: BindGroupEntryType::Sampler {
6588                filtering: true,
6589                comparison: false,
6590            },
6591        }
6592    }
6593    /// Convenience constructor for a non-filtering sampler binding slot.
6594    pub fn sampler_non_filtering(binding: u32, visibility: u32) -> Self {
6595        Self {
6596            binding,
6597            visibility,
6598            ty: BindGroupEntryType::Sampler {
6599                filtering: false,
6600                comparison: false,
6601            },
6602        }
6603    }
6604    /// Convenience constructor for a comparison sampler binding slot.
6605    pub fn sampler_comparison(binding: u32, visibility: u32) -> Self {
6606        Self {
6607            binding,
6608            visibility,
6609            ty: BindGroupEntryType::Sampler {
6610                filtering: false,
6611                comparison: true,
6612            },
6613        }
6614    }
6615}