Skip to main content

euv_engine/renderer/
struct.rs

1use super::*;
2
3/// A 2D camera that defines the viewport into the game world.
4#[derive(Clone, Copy, Data, Debug, New, PartialEq, PartialOrd)]
5pub struct Camera2D {
6    /// The world-space position of the camera center.
7    #[get(type(copy))]
8    pub(crate) position: Vector2D,
9    /// The zoom factor (1.0 = no zoom, 2.0 = 2x magnification).
10    #[get(type(copy))]
11    pub(crate) zoom: f64,
12    /// The rotation angle in radians.
13    #[get(type(copy))]
14    pub(crate) rotation: f64,
15    /// The viewport width in screen pixels.
16    #[get(type(copy))]
17    pub(crate) viewport_width: f64,
18    /// The viewport height in screen pixels.
19    #[get(type(copy))]
20    pub(crate) viewport_height: f64,
21}
22
23/// A 3D camera that defines the viewport into a 3D world using perspective
24/// or orthographic projection.
25#[derive(Clone, Copy, Data, Debug, New, PartialEq, PartialOrd)]
26pub struct Camera3D {
27    /// The world-space position of the camera (eye).
28    #[get(type(copy))]
29    pub(crate) position: Vector3D,
30    /// The point the camera is looking at (target).
31    #[get(type(copy))]
32    pub(crate) target: Vector3D,
33    /// The up direction for the camera.
34    #[get(type(copy))]
35    #[new(skip)]
36    pub(crate) up: Vector3D,
37    /// The vertical field of view in radians.
38    #[get(type(copy))]
39    #[new(skip)]
40    pub(crate) fov: f64,
41    /// The near clipping plane distance.
42    #[get(type(copy))]
43    #[new(skip)]
44    pub(crate) near: f64,
45    /// The far clipping plane distance.
46    #[get(type(copy))]
47    #[new(skip)]
48    pub(crate) far: f64,
49    /// The viewport width in pixels.
50    #[get(type(copy))]
51    pub(crate) viewport_width: f64,
52    /// The viewport height in pixels.
53    #[get(type(copy))]
54    pub(crate) viewport_height: f64,
55}
56
57/// A wrapper around `CanvasRenderingContext2d` providing convenience
58/// drawing methods and camera management for the game engine.
59#[derive(Clone, Data, New)]
60pub struct CanvasRenderer {
61    /// The underlying canvas 2D rendering context.
62    pub(crate) context: CanvasRenderingContext2d,
63    /// The active camera controlling the viewport.
64    #[get(type(copy))]
65    pub(crate) camera: Camera2D,
66    /// The active rendering quality preset.
67    ///
68    /// Controls `imageSmoothingEnabled`, `imageSmoothingQuality`, and
69    /// `textRendering` on the underlying context. Defaults to `Medium`.
70    #[get(type(copy))]
71    pub(crate) quality: RenderQuality,
72}
73
74/// A linear gradient defined by two endpoints and a list of color stops.
75///
76/// Used to create smooth color transitions along a straight line
77/// for fill or stroke operations on the canvas.
78#[derive(Clone, Data, Debug, New, PartialEq)]
79pub struct LinearGradient {
80    /// The starting point of the gradient in world space.
81    #[get(type(copy))]
82    pub(crate) start: Vector2D,
83    /// The ending point of the gradient in world space.
84    #[get(type(copy))]
85    pub(crate) end: Vector2D,
86    /// The ordered list of color stops, each containing a position (0.0 to 1.0) and a CSS color string.
87    pub(crate) stops: Vec<(f64, String)>,
88}
89
90/// A radial gradient defined by inner and outer circles and a list of color stops.
91///
92/// Used to create smooth color transitions radiating outward from a center point
93/// for fill or stroke operations on the canvas.
94#[derive(Clone, Data, Debug, New, PartialEq)]
95pub struct RadialGradient {
96    /// The center of the inner circle of the gradient.
97    #[get(type(copy))]
98    pub(crate) inner_center: Vector2D,
99    /// The radius of the inner circle.
100    #[get(type(copy))]
101    pub(crate) inner_radius: f64,
102    /// The center of the outer circle of the gradient.
103    #[get(type(copy))]
104    pub(crate) outer_center: Vector2D,
105    /// The radius of the outer circle.
106    #[get(type(copy))]
107    pub(crate) outer_radius: f64,
108    /// The ordered list of color stops, each containing a position (0.0 to 1.0) and a CSS color string.
109    pub(crate) stops: Vec<(f64, String)>,
110}
111
112/// Shadow rendering configuration for drop shadow effects on canvas primitives.
113///
114/// When applied, all subsequent fill, stroke, and draw operations will cast
115/// a shadow with the specified color, blur radius, and offset.
116#[derive(Clone, Data, Debug, New, PartialEq, PartialOrd)]
117pub struct ShadowConfig {
118    /// The CSS color string of the shadow (e.g., `"rgba(0,0,0,0.5)"`).
119    #[get(type(clone))]
120    pub(crate) color: String,
121    /// The blur radius of the shadow in pixels.
122    #[get(type(copy))]
123    pub(crate) blur: f64,
124    /// The horizontal offset of the shadow in pixels.
125    #[get(type(copy))]
126    pub(crate) offset_x: f64,
127    /// The vertical offset of the shadow in pixels.
128    #[get(type(copy))]
129    pub(crate) offset_y: f64,
130}
131
132/// Represents the rendering priority layer for draw call ordering.
133///
134/// Higher z-index values are drawn on top of lower values,
135/// enabling correct visual layering of game objects.
136#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, New, Ord, PartialEq, PartialOrd)]
137pub struct RenderLayer {
138    /// The z-index determining draw order. Higher values draw later (on top).
139    #[get(type(copy))]
140    pub(crate) z_index: i32,
141    /// Whether objects in this layer should be rendered.
142    #[get(type(copy))]
143    pub(crate) visible: bool,
144}
145
146/// An ordered buffer of deferred draw commands recorded during a frame.
147///
148/// Scenes and components push `DrawCommand`s into the list during `on_render`
149/// instead of drawing immediately. The engine then replays the whole list once
150/// per frame via `CanvasRenderer::replay`, which batches consecutive same-style
151/// shapes into a single path and skips redundant canvas state changes. The
152/// backing `Vec` is reused across frames via `clear()` to avoid reallocation.
153#[derive(Clone, Data, Debug, Default, New)]
154pub struct DrawList {
155    /// The recorded draw commands for the current frame.
156    #[get(pub(crate))]
157    #[get_mut(pub(crate))]
158    #[set(pub(crate))]
159    pub(crate) commands: Vec<DrawCommand>,
160}
161
162/// A supersampling anti-aliasing (SSAA) canvas wrapper that renders at a higher
163/// resolution on an offscreen canvas and downscales to the display canvas for
164/// smoother polygon edges in software-rendered 3D scenes.
165///
166/// The offscreen context is scaled by `scale_factor` so that all drawing
167/// code can use logical pixel coordinates without modification. After
168/// rendering, call `present()` to draw the high-resolution buffer onto the
169/// visible canvas with high-quality image smoothing.
170#[derive(Clone, Data, New)]
171pub struct SsaaCanvas {
172    /// The display canvas element visible to the user.
173    pub(crate) display_canvas: HtmlCanvasElement,
174    /// The 2D rendering context of the display canvas used for final presentation.
175    pub(crate) display_context: CanvasRenderingContext2d,
176    /// The offscreen canvas used for high-resolution rendering.
177    pub(crate) offscreen_canvas: HtmlCanvasElement,
178    /// The 2D rendering context of the offscreen canvas, pre-scaled by `scale_factor`.
179    pub(crate) offscreen_context: CanvasRenderingContext2d,
180    /// The supersampling scale factor (e.g., 2.0 means 4x SSAA).
181    #[get(type(copy))]
182    pub(crate) scale_factor: f64,
183    /// The rendering quality preset for the downscaling present step.
184    ///
185    /// Controls the smoothing strategy when the offscreen buffer is
186    /// downscaled onto the display canvas. Defaults to `Medium`.
187    #[new(skip)]
188    #[get(type(copy))]
189    pub(crate) quality: RenderQuality,
190    /// The logical display width in CSS pixels.
191    #[get(type(copy))]
192    pub(crate) width: f64,
193    /// The logical display height in CSS pixels.
194    #[get(type(copy))]
195    pub(crate) height: f64,
196}
197
198/// A WebGPU rendering backend wrapping the GPU device, queue, and canvas context
199/// for GPU-accelerated rendering on the web.
200///
201/// Created asynchronously via `WebGpuRenderer::init` because adapter and
202/// device acquisition returns JavaScript Promises that must be awaited.
203/// Once initialized, the renderer provides methods to create GPU resources
204/// (buffers, shader modules, command encoders) and execute render passes.
205///
206/// WebGPU types are stored as `JsValue` to avoid feature-gated import issues
207/// with `web_sys`. Method calls are performed via `Reflect` and `JsCast`.
208#[derive(Clone, Data)]
209pub struct WebGpuRenderer {
210    /// The WebGPU device (`GpuDevice`) used to create GPU resources.
211    pub(crate) device: JsValue,
212    /// The device's command queue (`GpuQueue`) for submitting command buffers.
213    pub(crate) queue: JsValue,
214    /// The WebGPU canvas rendering context (`GpuCanvasContext`).
215    pub(crate) context: JsValue,
216    /// The HTML canvas element backing the WebGPU context.
217    pub(crate) canvas: HtmlCanvasElement,
218    /// The texture format string used by the canvas's swap chain (e.g., `"bgra8unorm"`).
219    #[get(type(clone))]
220    pub(crate) format: String,
221    /// The physical pixel width of the canvas backing store.
222    #[get(type(copy))]
223    pub(crate) width: u32,
224    /// The physical pixel height of the canvas backing store.
225    #[get(type(copy))]
226    pub(crate) height: u32,
227    /// Whether MSAA anti-aliasing is enabled for render pipelines.
228    ///
229    /// When `true`, the renderer allocates a multisampled intermediate texture
230    /// (`sampleCount: 4`) and resolves into the swap chain each frame; when
231    /// `false`, render passes attach directly to the swap chain view at
232    /// `sampleCount: 1`.
233    #[get(type(copy))]
234    pub(crate) antialias: bool,
235    /// The multisampled color texture used when `antialias` is `true`.
236    ///
237    /// `None` when MSAA is disabled. Rebuilt on every resize because the
238    /// `width`/`height` are immutable for a given `GpuTexture`.
239    #[get(type(clone))]
240    pub(crate) multisample_texture: Option<JsValue>,
241    /// The default `GpuTextureView` into `multisample_texture`.
242    ///
243    /// Cached at texture-create time so `begin_render_pass` does not have to
244    /// recreate the view each frame. `None` when MSAA is disabled.
245    #[get(type(clone))]
246    pub(crate) multisample_view: Option<JsValue>,
247    /// The depth-stencil texture used for depth-tested passes.
248    ///
249    /// Created lazily on the first call to [`WebGpuRenderer::begin_render_pass`]
250    /// that includes a `depthStencil` attachment. Rebuilt on every resize
251    /// because the dimensions are immutable for a given `GpuTexture`. The
252    /// matching default view is cached in `depth_view`.
253    ///
254    /// `None` until the first depth-tested render pass is opened.
255    #[get(type(clone))]
256    pub(crate) depth_texture: Option<JsValue>,
257    /// The default `GpuTextureView` into `depth_texture`.
258    ///
259    /// `None` when no depth texture has been allocated.
260    #[get(type(clone))]
261    pub(crate) depth_view: Option<JsValue>,
262    /// The depth-stencil format used for `depth_texture`.
263    ///
264    /// Stored so subsequent render-pass openers can pass the same format
265    /// to the pipeline layout without having to remember it externally.
266    /// `None` until the first depth texture is allocated.
267    #[get(type(clone))]
268    pub(crate) depth_format: Option<String>,
269    /// User-supplied closure fired when the underlying `GpuDevice` enters
270    /// the `lost` state (browser-initiated context loss, OS driver crash,
271    /// `device.destroy()`, ...).
272    ///
273    /// `None` until the caller calls [`WebGpuRenderer::on_device_lost`].
274    /// The renderer also stores a separate `device_lost_handle` that
275    /// forwards the `GPUDeviceLostInfo` JS value into this callback.
276    #[get(type(clone))]
277    pub(crate) device_lost_callback: Option<js_sys::Function>,
278    /// Whether the device is currently in the `lost` state.
279    ///
280    /// Once flipped to `true`, every GPU operation returns
281    /// `Err(WebGpuError::RendererDisposed)` until the caller destroys the
282    /// renderer and creates a new one (WebGPU has no "recover from lost
283    /// device" API).
284    #[get(type(copy))]
285    pub(crate) device_lost: bool,
286    /// Shared slot for the most recent popped error-scope value.
287    ///
288    /// `device.popErrorScope()` returns a `Promise<GPUError?>`; we
289    /// cannot `.await` it from a sync call site. Instead, every
290    /// `push_error_scope` + `pop_error_scope` pair registers a
291    /// microtask via `wasm_bindgen_futures::spawn_local` that stores
292    /// the resolved value here. Callers that want the error
293    /// synchronously call [`WebGpuRenderer::take_last_error`] to
294    /// drain the slot.
295    ///
296    /// Holding a `Rc<PendingErrorCell>` lets the spawn_local future
297    /// own its own handle independently of `&self`, so the
298    /// renderer's borrow checker stays happy. The slot is empty
299    /// (`None`) by default and after each successful take.
300    ///
301    /// The cell is intentionally `PendingErrorCell` (a `Sync`
302    /// `UnsafeCell` newtype, see [`crate::renderer::static`]) rather
303    /// than `Rc<RefCell<...>>`: the WASM single-threaded scheduler
304    /// makes the runtime borrow check `RefCell` provides unreachable
305    /// in practice, so we trade it for a raw `UnsafeCell` deref
306    /// confined to two call sites. This mirrors how euv-core
307    /// implements its global registries
308    /// (`core/src/renderer/registry/struct.rs:62`).
309    pub(crate) pending_error: Rc<PendingErrorCell>,
310    /// The currently-open `GpuCommandEncoder`, if any.
311    ///
312    /// WebGPU expects the application to encode all work for a
313    /// frame (clear, render passes, compute passes, copy ops) into
314    /// a single command encoder, then call `encoder.finish()` to
315    /// produce a `GpuCommandBuffer` and submit it to the queue.
316    /// The encoder is `None` after `submit()` finishes and must
317    /// be re-acquired via `device.createCommandEncoder()` before
318    /// the next frame.
319    #[get(type(clone))]
320    pub(crate) command_encoder: Option<JsValue>,
321}
322
323/// Describes a 2D viewport rectangle plus optional depth range, in the same
324/// pixel space as the destination render target.
325///
326/// Used by [`WebGpuRenderer::set_viewport`] (and any future caller that needs
327/// to push a `GpuViewport`-shaped JS object through `Reflect::set`). The
328/// depth-range fields are omitted from the `::new` constructor via
329/// `#[new(skip)]`; they default to zero-initialised `f32` and are typically
330/// overwritten by [`WebGpuRenderer::set_viewport`] to the WebGPU spec
331/// defaults of `0.0` / `1.0`.
332#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
333pub struct ViewportDescriptor {
334    /// X coordinate of the viewport's top-left in pixels.
335    pub(crate) x: f32,
336    /// Y coordinate of the viewport's top-left in pixels.
337    pub(crate) y: f32,
338    /// Viewport width in pixels.
339    pub(crate) width: f32,
340    /// Viewport height in pixels.
341    pub(crate) height: f32,
342    /// Minimum depth, clamped to `[0, 1]`. Set to `0.0` to disable.
343    #[new(skip)]
344    pub(crate) min_depth: f32,
345    /// Maximum depth, clamped to `[0, 1]`. Set to `1.0` to disable.
346    #[new(skip)]
347    pub(crate) max_depth: f32,
348}
349
350/// A WebGL 2 rendering backend wrapping the `WebGl2RenderingContext`.
351///
352/// Unlike `WebGpuRenderer`, which stores all GPU handles as opaque `JsValue`s,
353/// WebGL exposes concrete `web_sys` types, so the context and canvas are kept
354/// as strongly typed values. Shader programs created via
355/// [`WebGlRenderer::create_program`] are managed by the caller.
356///
357/// Construct via [`WebGlRenderer::init`], which resolves the canvas from the
358/// [`RenderConfig`], applies device-pixel-ratio scaling to the backing store,
359/// and acquires the `webgl2` context.
360#[derive(Clone, Data)]
361pub struct WebGlRenderer {
362    /// The WebGL 2 rendering context used for all GL calls.
363    pub(crate) context: WebGl2RenderingContext,
364    /// The HTML canvas element backing the WebGL context.
365    pub(crate) canvas: HtmlCanvasElement,
366    /// The physical pixel width of the canvas backing store.
367    #[get(type(copy))]
368    pub(crate) width: u32,
369    /// The physical pixel height of the canvas backing store.
370    #[get(type(copy))]
371    pub(crate) height: u32,
372}
373
374// =====================================================================
375// WebGPU: descriptor & data structs (consumed by the WebGpuRenderer API)
376// =====================================================================
377
378/// A single vertex attribute within a vertex buffer layout.
379///
380/// Mirrors the fields of `GPUVertexAttribute` exactly. The shader location
381/// is the `@location(N)` qualifier in the WGSL source. The offset is in
382/// bytes from the start of the vertex, and `format` is one of the
383/// WGSL vertex format strings (e.g. `"float32x4"`, `"unorm8x4"`).
384#[derive(Clone, Copy, Debug, Eq, Getter, Hash, New, PartialEq)]
385pub struct VertexAttribute {
386    /// The shader location the attribute maps to.
387    #[get(type(copy))]
388    pub(crate) shader_location: u32,
389    /// The byte offset from the start of the vertex.
390    #[get(type(copy))]
391    pub(crate) offset: u64,
392    /// The WGSL vertex format (e.g. `"float32x4"`).
393    #[get(type(clone))]
394    pub(crate) format: &'static str,
395}
396
397/// The layout of a single vertex buffer, expressed as an array stride plus
398/// a list of attributes.
399///
400/// Mirrors `GPUVertexBufferLayout` from the WebGPU spec. The renderer
401/// passes the assembled descriptor straight to `createRenderPipeline` via
402/// `Reflect`.
403#[derive(Clone, Debug, Getter, New)]
404pub struct VertexBufferLayout {
405    /// The byte stride of one vertex in the buffer.
406    #[get(type(copy))]
407    pub(crate) array_stride: u64,
408    /// Whether the buffer should be advanced per-instance (`true`) or
409    /// per-vertex (`false`).
410    #[get(type(copy))]
411    pub(crate) step_mode: VertexStepMode,
412    /// The attributes that describe how to interpret the bytes of one
413    /// vertex.
414    pub(crate) attributes: Vec<VertexAttribute>,
415}
416
417/// A 2D texture descriptor for `create_texture_2d`.
418///
419/// Defaults produce a 1x1 RGBA8 texture with `TEXTURE_BINDING | COPY_DST
420/// | COPY_SRC` usage, which is the right baseline for a sampled color
421/// texture that is uploaded to via `queue.writeTexture`. Override fields
422/// after constructing to set `mip_level_count`, `sample_count`, or
423/// different `usage` flags.
424#[derive(Clone, Debug, Getter, New)]
425pub struct Texture2DDescriptor {
426    /// The texture width in pixels. Must be > 0.
427    #[get(type(copy))]
428    pub(crate) width: u32,
429    /// The texture height in pixels. Must be > 0.
430    #[get(type(copy))]
431    pub(crate) height: u32,
432    /// The WGSL texture format (e.g. `"rgba8unorm"`, `"bgra8unorm"`,
433    /// `"rgba16float"`, `"depth24plus-stencil8"`).
434    #[get(type(clone))]
435    pub(crate) format: &'static str,
436    /// The number of mip levels. `0` is treated as `1`.
437    #[get(type(copy))]
438    #[new(skip)]
439    pub(crate) mip_level_count: u32,
440    /// The number of samples per texel (`1` for non-MSAA, `4` for MSAA).
441    #[get(type(copy))]
442    #[new(skip)]
443    pub(crate) sample_count: u32,
444    /// The WGSL usage flags (e.g. `"RENDER_ATTACHMENT | TEXTURE_BINDING |
445    /// COPY_DST | COPY_SRC"`).
446    #[get(type(clone))]
447    #[new(skip)]
448    pub(crate) usage: &'static str,
449}
450
451/// A sampler descriptor for `create_sampler`.
452///
453/// Defaults produce a non-filtering clamp-to-edge sampler. Override
454/// fields after constructing to enable linear filtering, repeat
455/// addressing, or depth comparison.
456#[derive(Clone, Debug, Getter, New)]
457pub struct GpuSamplerDescriptor {
458    /// Minification filter.
459    #[get(type(clone))]
460    #[new(skip)]
461    pub(crate) mag_filter: &'static str,
462    /// Magnification filter.
463    #[get(type(clone))]
464    #[new(skip)]
465    pub(crate) min_filter: &'static str,
466    /// Mipmap filter.
467    #[get(type(clone))]
468    #[new(skip)]
469    pub(crate) mipmap_filter: &'static str,
470    /// U address mode.
471    #[get(type(clone))]
472    #[new(skip)]
473    pub(crate) address_mode_u: &'static str,
474    /// V address mode.
475    #[get(type(clone))]
476    #[new(skip)]
477    pub(crate) address_mode_v: &'static str,
478    /// W address mode.
479    #[get(type(clone))]
480    #[new(skip)]
481    pub(crate) address_mode_w: &'static str,
482    /// Whether the sampler is a comparison sampler.
483    #[get(type(copy))]
484    #[new(skip)]
485    pub(crate) compare: bool,
486}
487
488/// The descriptor for a single (color or depth-stencil) render pass
489/// attachment, used as input to `begin_render_pass` / `begin_render_pass_to_texture`.
490#[derive(Clone, Debug)]
491pub struct RenderPassColorAttachment {
492    /// The texture view to draw into.
493    ///
494    /// When `None`, the renderer uses the swap-chain view (or the MSAA
495    /// intermediate view if `antialias == true`).
496    pub(crate) view: Option<JsValue>,
497    /// An optional resolve target for MSAA.
498    ///
499    /// `None` when MSAA is disabled. The renderer fills in the default
500    /// resolve target (the swap-chain view) when MSAA is enabled and the
501    /// caller leaves this as `None`.
502    pub(crate) resolve_target: Option<JsValue>,
503    /// The clear color as `(r, g, b, a)` in `0.0..=1.0`. `None` means
504    /// `"load"` (keep the previous contents).
505    pub(crate) clear_value: Option<(f64, f64, f64, f64)>,
506    /// The load operation. `None` → `"clear"` when `clear_value` is
507    /// `Some`, otherwise `"load"`.
508    pub(crate) load_op: Option<&'static str>,
509    /// The store operation. `None` → `"store"`.
510    pub(crate) store_op: Option<&'static str>,
511}
512
513/// The depth-stencil portion of a `RenderPassDescriptor`, used as input to
514/// `begin_render_pass` / `begin_render_pass_to_texture`.
515#[derive(Clone, Debug)]
516pub struct RenderPassDepthStencilAttachment {
517    /// The depth-stencil texture view to use.
518    ///
519    /// When `None`, the renderer uses the default view into its
520    /// `depth_texture` field, allocating the depth texture lazily if
521    /// needed.
522    pub(crate) view: Option<JsValue>,
523    /// The depth clear value in `0.0..=1.0`. `None` means
524    /// `"load"` (keep previous depth).
525    pub(crate) depth_clear_value: Option<f32>,
526    /// The depth load op. `None` → `"clear"` when
527    /// `depth_clear_value` is `Some`, otherwise `"load"`.
528    pub(crate) depth_load_op: Option<&'static str>,
529    /// The depth store op. `None` → `"store"`.
530    pub(crate) depth_store_op: Option<&'static str>,
531    /// Whether depth reads should be enabled. `None` → `false`.
532    pub(crate) depth_read_only: Option<bool>,
533}
534
535/// Descriptor for `GpuTexture.createView(descriptor)`.
536///
537/// Sub-selects a single cube face / mip / array slice / depth-aspect of a
538/// texture. When you need the full texture as a 2D view (the common case),
539/// just call `create_view` without a descriptor; the new method accepts an
540/// `Option<&TextureViewDescriptor>` for callers that need the full
541/// flexibility of the WebGPU spec.
542#[derive(Clone, Debug, Getter, New)]
543pub struct TextureViewDescriptor {
544    /// View format override, or `None` to use the texture's own format.
545    #[get(type(clone))]
546    #[new(value = "None")]
547    pub(crate) format: Option<&'static str>,
548    /// View dimension (`"2d"`, `"2d-array"`, `"cube"`, `"cube-array"`, ...).
549    /// `None` means the dimension is inferred from the texture.
550    #[get(type(clone))]
551    #[new(value = "None")]
552    pub(crate) dimension: Option<&'static str>,
553    /// Most significant mip level (inclusive). `None` → `0`.
554    #[get(type(copy))]
555    #[new(value = "0")]
556    pub(crate) base_mip_level: u32,
557    /// Number of mip levels in the view. `0` → all the way to the top.
558    #[get(type(copy))]
559    #[new(value = "0")]
560    pub(crate) mip_level_count: u32,
561    /// First array layer (inclusive). `None` → `0`. Only meaningful for
562    /// `2d-array` / `cube` / `cube-array` views.
563    #[get(type(copy))]
564    #[new(value = "0")]
565    pub(crate) base_array_layer: u32,
566    /// Number of array layers. `0` → all remaining layers.
567    #[get(type(copy))]
568    #[new(value = "0")]
569    pub(crate) array_layer_count: u32,
570    /// Which aspect of the texture to expose. One of:
571    /// `"all"`, `"depth-only"`, `"stencil-only"`. `None` → `"all"`.
572    #[get(type(clone))]
573    #[new(value = "None")]
574    pub(crate) aspect: Option<&'static str>,
575}
576
577/// Descriptor for `queue.writeTexture(destination, data, dataLayout, size)`.
578///
579/// WebGPU's `writeTexture` lets you upload CPU-side pixel data directly to a
580/// texture without staging through a buffer. Use it for: ImGui font atlases,
581/// procedural noise textures, sprite sheets, `ImageBitmap` pixels, etc.
582#[derive(Clone, Debug, Getter, New)]
583pub struct TextureWriteDescriptor {
584    /// The pixel data to upload. Bytes are laid out according to
585    /// `bytes_per_row` / `rows_per_image`.
586    #[get(type(clone))]
587    pub(crate) data: Vec<u8>,
588    /// Bytes per row of the source data. Must be a multiple of 256.
589    #[get(type(copy))]
590    pub(crate) bytes_per_row: u32,
591    /// Number of rows per image. `0` for 2D textures without mip chains.
592    #[get(type(copy))]
593    pub(crate) rows_per_image: u32,
594    /// Destination mip level to write into.
595    #[get(type(copy))]
596    pub(crate) mip_level: u32,
597    /// Destination texture to write into.
598    #[get(type(clone))]
599    pub(crate) texture: JsValue,
600    /// Origin within the destination texture. `None` → `(0, 0, 0)`.
601    #[get(type(clone))]
602    #[new(value = "None")]
603    pub(crate) origin: Option<JsValue>,
604    /// Whether to flip the source data vertically before writing.
605    /// `true` is essential when uploading from `<img>` / `<canvas>` whose
606    /// rows are top-to-bottom but WebGPU textures are bottom-to-top.
607    #[get(type(copy))]
608    #[new(value = "false")]
609    pub(crate) flip_y: bool,
610}
611
612/// Interior-mutable slot for the renderer's pending error-scope value.
613///
614/// This is the `euv-engine` analog of euv-core's `HandlerRegistryCell`
615/// (`core/src/renderer/registry/struct.rs:62`): a single-element
616/// `Sync` wrapper that holds an `Option<JsValue>` behind an
617/// `UnsafeCell`.
618///
619/// # Why this type exists
620///
621/// `WebGpuRenderer::pending_error` needs interior mutability
622/// because:
623///
624/// 1. `pop_error_sync` takes `&self` (the WebGPU hot path cannot
625///    be `async`), but the spawned `wasm_bindgen_futures::spawn_local`
626///    future must mutate the slot to store the resolved
627///    `Promise<GPUError?>` value.
628/// 2. `take_last_error` also takes `&self` and drains the slot
629///    on the next render tick.
630///
631/// The first implementation used `Rc<RefCell<Option<JsValue>>>`,
632/// which works but pays for:
633///
634/// - a `RefCell::borrow_mut` runtime borrow check on every
635///   write (the panic path is unreachable in practice — only
636///   the spawn_local future and `take_last_error` ever touch
637///   the slot, and they never overlap because the future is
638///   a microtask drained before the next render tick).
639/// - a heap allocation for the `RefCell`'s borrow state.
640///
641/// The newtype keeps the interior-mutability primitive (`Rc`),
642/// because the spawn_local future needs its own owning handle,
643/// but swaps the inner cell from `RefCell` to `UnsafeCell`:
644///
645/// - zero runtime borrow check (the WASM single-threaded
646///   scheduler makes the borrow impossible to violate).
647/// - zero allocation (the cell is just a `*mut Option<JsValue>`
648///   sitting inside the `Rc`-managed box).
649///
650/// # Sync safety
651///
652/// `PendingErrorCell` is **not** `Sync` by default (`UnsafeCell`
653/// explicitly opts out). We hand-implement `Sync` for it because
654/// the renderer is only ever used in the WASM single-threaded
655/// runtime; the `Rc` ensures the same instance is never shared
656/// across threads (it is not `Send`/`Sync` either), and the
657/// WASM main thread is the only place that ever touches the
658/// slot. This matches euv-core's pattern
659/// (`unsafe impl Sync for HandlerRegistryCell {}`).
660///
661/// If the engine is ever compiled for a multi-threaded target
662/// (native, `wasm-bindgen-rayon`), this `unsafe impl Sync` is
663/// unsound and must be removed.
664pub struct PendingErrorCell(
665    /// Interior-mutable storage for the optional `JsValue`.
666    ///
667    /// Marked `pub(crate)` (not just `pub`) because the field is
668    /// only meant to be touched from inside the renderer module —
669    /// specifically from the `impl PendingErrorCell` block in
670    /// `impl.rs`. The struct itself stays `pub` so external code
671    /// can name the type, but the raw `UnsafeCell` is an
672    /// implementation detail.
673    pub(crate) UnsafeCell<Option<JsValue>>,
674);