pub struct WebGpuRenderer { /* private fields */ }Expand description
A WebGPU rendering backend wrapping the GPU device, queue, and canvas context for GPU-accelerated rendering on the web.
Created asynchronously via WebGpuRenderer::init because adapter and
device acquisition returns JavaScript Promises that must be awaited.
Once initialized, the renderer provides methods to create GPU resources
(buffers, shader modules, command encoders) and execute render passes.
WebGPU types are stored as JsValue to avoid feature-gated import issues
with web_sys. Method calls are performed via Reflect and JsCast.
Implementations§
Source§impl WebGpuRenderer
Implements async initialization and GPU resource creation for WebGpuRenderer.
impl WebGpuRenderer
Implements async initialization and GPU resource creation for WebGpuRenderer.
Sourcepub fn is_available() -> bool
pub fn is_available() -> bool
Returns true if navigator.gpu is exposed on the current origin.
This is the synchronous half of the canonical WebGPU capability
probe used by Three.js (examples/jsm/capabilities/WebGPU.js): it
only checks that the browser surfaces the GPU interface at all.
It does not request an adapter — a present navigator.gpu
does not guarantee that a usable GPU adapter is reachable (Linux
software-rendered sessions, headless browsers, GPU-blacklisted
devices and sandboxed iframes all expose navigator.gpu while
requestAdapter() resolves to null or hangs forever).
Use this as the cheapest pre-flight check before showing a
“needs HTTPS or localhost” prompt. For a definitive answer use
Self::probe which also awaits requestAdapter().
§Returns
bool-truewhennavigator.gpuis a non-null, non-undefined object;falseotherwise (including the “nowindow” runtime case, whichweb_sys::window()returnsNonefor).
Sourcepub async fn probe() -> bool
pub async fn probe() -> bool
Probes whether a WebGPU adapter can actually be acquired.
Mirrors Three.js’ canonical capability probe exactly:
isAvailable = (navigator.gpu !== undefined)
if (isAvailable) {
isAvailable = Boolean(await navigator.gpu.requestAdapter())
}Wraps the adapter request in the same Promise.race timeout used
by Self::init so that browsers which leave the adapter promise
permanently pending (headless, sandboxed, device-lost) do not stall
the UI forever. The timeout itself uses the
INIT_PROMISE_TIMEOUT_MILLIS constant; on timeout, probe returns
false rather than an error so callers can treat it the same as
“no adapter”.
§Returns
bool-trueonly when bothnavigator.gpuis present andrequestAdapter()resolves to a non-null adapter within the timeout window.falsecovers every other case (nowindow, missingnavigator.gpu, reflect exception, adapter promise rejected or timed out, adapter resolved tonull/undefined).
Sourcepub async fn init(
config: &RenderConfig,
) -> Result<WebGpuRenderer, WebGpuInitError>
pub async fn init( config: &RenderConfig, ) -> Result<WebGpuRenderer, WebGpuInitError>
Asynchronously initializes a WebGPU renderer from the given render configuration.
Requests a GPU adapter and device, obtains the WebGPU canvas context,
and configures it with the preferred texture format. Returns Err if
WebGPU is not supported, the adapter/device request fails, the canvas
element is not found, or the adapter/device request hangs beyond
INIT_PROMISE_TIMEOUT_MILLIS (a defensive timeout for browser GPU
states that leave the WebGPU promises permanently pending).
The engine no longer logs diagnostic output internally; instead each
failure mode is returned as a distinct WebGpuInitError variant so
the caller can decide how to surface it (typically via Console::error
or by falling back to the Canvas 2D backend).
§Arguments
&RenderConfig- The rendering configuration.
§Returns
Result<WebGpuRenderer, WebGpuInitError>- The initialized renderer, or a typed error describing the specific failure.
Sourcepub fn resize(&mut self, physical_width: u32, physical_height: u32) -> bool
pub fn resize(&mut self, physical_width: u32, physical_height: u32) -> bool
Resizes the canvas backing store and reconfigures the swap chain.
WebGPU’s GpuCanvasContext.configure is sticky: it sets the texture
format and device once, but the swap chain tracks the canvas’s
width/height attributes. When the CSS layout size changes (a
window resize, a panel toggle, a DPR change) the canvas keeps its
old physical dimensions unless we explicitly update width/height
and call configure again. Without this, subsequent
getCurrentTexture() calls return a texture that no longer matches
the visible region and the frame either stretches or freezes.
Re-configureing with the same device + format is the
spec-defined way to swap in a fresh swap chain bound to the new
backing-store size.
§Arguments
u32- The new physical pixel width (already multiplied by DPR).u32- The new physical pixel height.
§Returns
bool-trueon success,falseif the swap chain or canvas handles were missing orconfigurefailed.
Sourcepub fn sync_to_current_canvas(&mut self) -> bool
pub fn sync_to_current_canvas(&mut self) -> bool
Resizes the canvas backing store to match the canvas element’s current CSS-rendered size in physical pixels (DPR applied).
This is the right entry point when the render loop does not know the desired logical size ahead of time and wants to follow the element’s actual layout box. It is also useful as a defensive recovery when the canvas was created while hidden (zero-sized parent) and is later shown at its real size.
Reads client_width / client_height from the canvas element,
multiplies by detect_dpr(), and forwards to Self::resize.
§Returns
bool-trueif the resize succeeded,falseif the canvas was zero-sized (nothing to render to), detached (CSS layout box collapses to 0), or the underlying resize rejected.
Sourcepub fn begin_render_pass_full(
&mut self,
encoder: &JsValue,
color: &mut RenderPassColorAttachment,
depth: Option<&RenderPassDepthStencilAttachment>,
) -> JsValue
pub fn begin_render_pass_full( &mut self, encoder: &JsValue, color: &mut RenderPassColorAttachment, depth: Option<&RenderPassDepthStencilAttachment>, ) -> JsValue
Begins a render pass with full control over attachments, load/store ops, MSAA resolve targets, and an optional depth-stencil attachment.
This is the “complete” render-pass API used by the rest of the
engine. All other render-pass entry points (including the
legacy begin_render_pass(clear_color) wrapper) funnel through
here.
The color attachment’s view is filled in lazily when None:
if antialias == true and the multisample intermediate is
available (or can be allocated), the pass draws into the MSAA
view and resolves into the swap chain; otherwise it draws
directly into the swap chain. The resolve_target is filled in
with the swap-chain view when MSAA is active and the caller
did not provide one.
§Arguments
encoder- TheGpuCommandEncoderto begin the pass on.color- The color attachment descriptor.color.viewandcolor.resolve_targetmay beNone; they are filled in with the renderer’s defaults.depth- An optional depth-stencil attachment.Some(...)adds adepthStencilAttachmentfield to the pass descriptor;Noneomits it entirely.
§Returns
JsValue- The activeGpuRenderPassEncoderas a JavaScript value, suitable for the existingset_pipeline/draw/end_render_passcalls.
Sourcepub fn create_render_pipeline<S>(&self, shader_code: S) -> JsValue
pub fn create_render_pipeline<S>(&self, shader_code: S) -> JsValue
Creates a simple render pipeline from a single WGSL shader source.
The shader must contain @vertex fn vs_main(...) and
@fragment fn fs_main(...) entry points. No vertex buffers are used;
vertex positions should be derived from @builtin(vertex_index) in
the shader. The pipeline uses auto-layout (layout: null), which works
when the shader has no bind groups.
This is the legacy “trivial” wrapper. For pipelines that need
vertex buffers, custom entry-point names, or a depth-stencil
state, use WebGpuRenderer::create_render_pipeline_full.
§Arguments
S: AsRef<str>- The WGSL shader source code.
§Returns
JsValue- The created render pipeline as a JavaScript value.
Sourcepub fn create_render_pipeline_full<S>(
&self,
shader_code: S,
vertex_buffer_layouts: &[VertexBufferLayout],
vertex_entry: &str,
fragment_entry: &str,
depth_format: Option<&str>,
) -> JsValue
pub fn create_render_pipeline_full<S>( &self, shader_code: S, vertex_buffer_layouts: &[VertexBufferLayout], vertex_entry: &str, fragment_entry: &str, depth_format: Option<&str>, ) -> JsValue
Creates a render pipeline with full control over vertex buffer layouts, shader entry-point names, and an optional depth-stencil state.
The vertex_buffer_layouts slice is forwarded as the
vertex.buffers array of the pipeline descriptor; the i-th
element matches setVertexBuffer(i, ...) calls. Pass &[] for
the legacy “use @builtin(vertex_index)” path.
The depth_format argument, when Some, sets
depthStencil.format on the descriptor; the rest of the depth
state (depthWriteEnabled, depthCompare) is left at the
WebGPU defaults (true / less). Callers that need different
depth state can pass the descriptor’s name string and rely on
the default depth-write/-compare behavior; for non-default
compare/write, prefer using RenderConfig and a custom shader
that performs the test explicitly.
§Arguments
shader_code- The WGSL shader source code.vertex_buffer_layouts- The list of vertex buffer layouts for the pipeline’s vertex state.vertex_entry- The vertex shader entry-point name (e.g."vs_main").fragment_entry- The fragment shader entry-point name (e.g."fs_main").depth_format- An optional depth-stencil format (e.g."depth24plus-stencil8").Noneomits thedepthStencilfield from the descriptor.
§Returns
JsValue- The created render pipeline as a JavaScript value.
Sourcepub fn create_uniform_buffer(&self, data: &[f32]) -> JsValue
pub fn create_uniform_buffer(&self, data: &[f32]) -> JsValue
Creates a GPU uniform buffer and initializes it with the given floats.
The buffer is created with UNIFORM | COPY_DST usage so it can be
bound in a bind group and refreshed per frame via
WebGpuRenderer::update_uniform_buffer. The allocation size is
rounded up to a multiple of 16 bytes because WebGPU requires uniform
buffer bindings to be 16-byte aligned in size (a bare vec2<f32>
uniform is only 8 bytes).
§Arguments
&[f32]- The initial uniform contents (e.g.[x, y]for avec2<f32>uniform).
§Returns
JsValue- The createdGpuBuffer.
Sourcepub fn update_uniform_buffer(&self, buffer: &JsValue, data: &[f32])
pub fn update_uniform_buffer(&self, buffer: &JsValue, data: &[f32])
Uploads float data into an existing uniform buffer via queue.writeBuffer.
§Arguments
&JsValue- TheGpuBufferpreviously created byWebGpuRenderer::create_uniform_buffer.&[f32]- The new uniform contents.
Sourcepub fn create_compute_pipeline<S>(
&self,
shader_code: S,
entry_point: &str,
) -> JsValue
pub fn create_compute_pipeline<S>( &self, shader_code: S, entry_point: &str, ) -> JsValue
Creates a compute pipeline from a WGSL shader.
The shader must contain exactly one @compute fn <name>(...)
entry point whose name matches entry_point. The pipeline uses
auto-layout, so any @group(N) binding it declares is wired
through getBindGroupLayout(N).
§Arguments
shader_code- The WGSL source code.entry_point- The compute entry-point name (e.g."cs_main").
§Returns
JsValue- The createdGpuComputePipeline, orJsValue::UNDEFINEDon failure.
Sourcepub fn begin_compute_pass(&self, encoder: &JsValue) -> JsValue
pub fn begin_compute_pass(&self, encoder: &JsValue) -> JsValue
Begins a compute pass on the given command encoder.
The returned JsValue is a GpuComputePassEncoder that supports
setPipeline / setBindGroup / dispatchWorkgroups /
dispatchWorkgroupsIndirect / end. The pass must be ended
(via end()) before the command encoder is finished.
§Arguments
encoder- TheGpuCommandEncoderto begin the pass on.
§Returns
JsValue- The activeGpuComputePassEncoder.
Sourcepub fn dispatch(&self, pass: &JsValue, x: u32, y: u32, z: u32)
pub fn dispatch(&self, pass: &JsValue, x: u32, y: u32, z: u32)
Issues a dispatchWorkgroups(x, y, z) on a compute pass encoder.
x/y/z are the workgroup counts in each dimension. WebGPU
limits each to 65535; callers that need larger grids must
split them across multiple dispatches or encode a loop inside
the shader.
§Arguments
pass- The activeGpuComputePassEncoder.x/y/z- Workgroup counts (each 1..=65535).
Sourcepub fn push_error_scope(&self, filter: &str)
pub fn push_error_scope(&self, filter: &str)
Pushes a GpuErrorScope with the given filter.
Pairs with WebGpuRenderer::pop_error_sync (or the JS
device.popErrorScope() promise). All create_* / write_*
operations issued while a scope is pushed accumulate their
validation errors into the most recent scope; pop to consume
them. The renderer does NOT auto-pop scopes; callers that
push a scope must pop it. The renderer pushes a
"validation" scope around create_bind_group; if you push
your own scope at the same time, the inner one is consumed
first.
filter is one of "validation", "out-of-memory", or
"internal" (use the WEBGPU_ERROR_FILTER_* constants).
§Arguments
filter- The WebGPU error filter name.
Sourcepub fn pop_error_sync(&self) -> Option<JsValue>
pub fn pop_error_sync(&self) -> Option<JsValue>
Pops the most recent error scope and asynchronously captures
the result into the renderer’s shared pending_error slot.
WebGPU’s popErrorScope() returns a Promise<GPUError?>;
because create_bind_group (and the rest of the renderer’s
hot path) cannot be async, we cannot .await the promise
in place. Instead this method:
- Calls
device.popErrorScope()to obtain the promise. - Spawns a local future that awaits the promise with
wasm_bindgen_futures::JsFutureand writes the resolved value (aGPUError?, orundefinedon success) intoself.pending_error. - Returns
Noneimmediately. The actual error becomes visible viaWebGpuRenderer::take_last_erroron a later call (typically the nextsubmittick).
Callers that want a synchronous error report should push
their own scope right before a create_* call, pop it right
after, and then poll take_last_error() from the next
frame’s render loop.
Returns None when the pop call itself failed (e.g. the
device is lost).
§Arguments
self- the renderer; the call borrows immutably because theRc<PendingErrorCell>slot lets the spawned future mutate the inner value without an exclusive borrow.
Sourcepub fn take_last_error(&self) -> Option<JsValue>
pub fn take_last_error(&self) -> Option<JsValue>
Drains the renderer’s pending error-scope slot, returning the most recent popped error, if any.
Call this on the render loop (after submit, before the
next create_* call) to surface validation errors that
were captured by WebGpuRenderer::pop_error_sync.
Returns None if no error was reported since the last
take_last_error call (or since the renderer was
constructed).
Sourcepub fn begin_render_pass_to_texture(
&mut self,
encoder: &JsValue,
color_view: &JsValue,
clear_color: Option<(f64, f64, f64, f64)>,
depth_view: Option<&JsValue>,
depth_clear: Option<f32>,
) -> JsValue
pub fn begin_render_pass_to_texture( &mut self, encoder: &JsValue, color_view: &JsValue, clear_color: Option<(f64, f64, f64, f64)>, depth_view: Option<&JsValue>, depth_clear: Option<f32>, ) -> JsValue
Begins a render pass that targets a user-supplied offscreen texture view instead of the swap chain.
This is the “render-to-texture” entry point used for post-processing chains, mipmap generation, shadow maps, and any time the pass should not appear on screen.
The view must be a GpuTextureView (not the texture itself);
the texture should have been created with
RENDER_ATTACHMENT usage.
§Arguments
encoder- TheGpuCommandEncoderto begin the pass on.color_view- The offscreen color attachment view.clear_color- The clear color (orNoneto"load").depth_view- An optional depth-stencil view to bind as the depth attachment. PassNoneto skip depth.depth_clear- An optional depth clear value. Ignored whendepth_viewisNone.
§Returns
JsValue- The activeGpuRenderPassEncoder.
Sourcepub fn copy_texture_to_buffer(
&self,
source: &JsValue,
destination: &JsValue,
bytes_per_row: u32,
width: u32,
height: u32,
)
pub fn copy_texture_to_buffer( &self, source: &JsValue, destination: &JsValue, bytes_per_row: u32, width: u32, height: u32, )
Copies a texture’s contents to a buffer for CPU readback.
The buffer must be created with
COPY_DST | MAP_READ usage. The bytes are not available to
the CPU until map_async is awaited and the mapped range
is read.
§Arguments
source- TheGpuTextureto copy from.destination- The destinationGpuBuffer.bytes_per_row- The number of bytes per row of the texture (i.e.width * bytes_per_pixel, padded to 256 for non-power-of-two widths).width/height- The texture subregion to copy.
Sourcepub fn create_offline_render_target(
&self,
width: u32,
height: u32,
format: &str,
) -> (JsValue, JsValue)
pub fn create_offline_render_target( &self, width: u32, height: u32, format: &str, ) -> (JsValue, JsValue)
Creates a standalone offscreen render target (texture + view) with the given size and format.
The returned tuple is (texture, view). The texture is
allocated with RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_SRC usage, which is the right baseline for “render
into it, then sample from it in a later pass”. Callers that
need STORAGE_BINDING or COPY_DST should use
WebGpuRenderer::create_texture_2d directly.
§Arguments
width/height- The texture dimensions in pixels.format- The WGSL texture format (e.g."rgba8unorm").
§Returns
(JsValue, JsValue)- The offscreen texture and its default view. Either may beUNDEFINEDon failure.
Sourcepub fn create_texture_view(&self, texture: &JsValue) -> JsValue
pub fn create_texture_view(&self, texture: &JsValue) -> JsValue
Creates a default-view for the given texture.
Used by WebGpuRenderer::create_offline_render_target; the
texture must have been created with the right usage flags.
Sourcepub fn on_device_lost(&mut self, callback: Function)
pub fn on_device_lost(&mut self, callback: Function)
Registers a closure to be invoked when the GPU device is lost.
The closure is called with a single JsValue argument
(the GPUDeviceLostInfo object) when the device is lost. The
renderer keeps a Closure alive for as long as the renderer
itself is alive; calling dispose() releases it.
The device.lost promise resolves with a reason of
"destroyed" when the user calls device.destroy(), or
"undefined" for any other GPU-level loss. The closure is
invoked from a JS microtask, so it should be cheap and
non-blocking.
§Arguments
callback- The function to invoke. The renderer wraps it in aClosureand forgets the wrapper.
Sourcepub fn create_buffer(&self, size: u64, usage: u32) -> JsValue
pub fn create_buffer(&self, size: u64, usage: u32) -> JsValue
Low-level buffer allocator. Creates a GpuBuffer with the given
size (in bytes) and usage bitmask (see WEBGPU_BUFFER_USAGE_*).
This is the foundation for the typed helpers
(WebGpuRenderer::create_vertex_buffer,
WebGpuRenderer::create_index_buffer,
WebGpuRenderer::create_uniform_buffer); prefer those unless
you need full control over the usage flags.
The returned value is JsValue::UNDEFINED (not an Err) when the
allocation fails, to match the convention used by the other
create_* helpers in this renderer. Callers should test for
JsValue::UNDEFINED before use.
§Arguments
size- The buffer size in bytes. Must be > 0.usage- The WebGPU buffer usage bitmask (e.g.WEBGPU_BUFFER_USAGE_VERTEX | WEBGPU_BUFFER_USAGE_COPY_DST).
§Returns
JsValue- The newGpuBuffer, orJsValue::UNDEFINEDon allocation failure.
Sourcepub fn create_vertex_buffer(&self, data: &[u8]) -> JsValue
pub fn create_vertex_buffer(&self, data: &[u8]) -> JsValue
Creates a vertex buffer pre-populated with the given bytes and
uploads the data via queue.writeBuffer in the same call.
The buffer is allocated with VERTEX | COPY_DST usage. The data
is uploaded at offset 0; for partial updates use
WebGpuRenderer::write_buffer after creation.
§Arguments
data- The raw bytes that will be interpreted as a packed vertex array by the pipeline’s vertex buffer layout.
§Returns
JsValue- The newGpuBuffer, orJsValue::UNDEFINEDon allocation failure.
Sourcepub fn create_index_buffer(&self, data: &[u8]) -> JsValue
pub fn create_index_buffer(&self, data: &[u8]) -> JsValue
Creates an index buffer pre-populated with the given bytes.
The buffer is allocated with INDEX | COPY_DST usage. The
format of the index data must be passed to the render pipeline
layout (indexFormat: "uint16" for 16-bit indices, "uint32"
for 32-bit).
§Arguments
data- The raw bytes of the index list (e.g.[0u8, 1u8, 2u8]for a single uint16 triangle, packed little-endian).
§Returns
JsValue- The newGpuBuffer, orJsValue::UNDEFINEDon allocation failure.
Sourcepub fn write_buffer(&self, buffer: &JsValue, offset: u64, data: &[u8])
pub fn write_buffer(&self, buffer: &JsValue, offset: u64, data: &[u8])
Uploads raw bytes into an existing buffer at the given offset
via queue.writeBuffer.
This is the byte-level counterpart to
WebGpuRenderer::update_uniform_buffer. It is a no-op when
data is empty; otherwise the GPU queue is invoked synchronously
(the call is non-blocking on the JS side; the actual upload is
ordered relative to the next submit).
§Arguments
buffer- TheGpuBufferto write into.offset- The byte offset into the buffer where the upload starts.data- The bytes to upload.
Sourcepub fn create_depth_texture(&mut self) -> Option<JsValue>
pub fn create_depth_texture(&mut self) -> Option<JsValue>
Creates a depth-stencil texture matching the canvas’s swap chain physical dimensions and caches it on the renderer.
The format defaults to "depth24plus-stencil8", which is
universally supported across browsers and matches what
WebGpuRenderer::create_render_pipeline expects when the
caller asks for depth testing. The texture is allocated with
RENDER_ATTACHMENT usage so it can be bound as the
depthStencilAttachment of a render pass.
If a depth texture already exists, this method is a no-op
(returns None and keeps the existing allocation). Callers that
need to force a re-allocation (e.g. after a resize) should call
self.set_depth_texture(None) first.
§Returns
Option<JsValue>- The depth texture’s defaultGpuTextureViewon success,Noneon allocation failure.
Sourcepub fn create_texture_2d(&self, descriptor: &Texture2DDescriptor) -> JsValue
pub fn create_texture_2d(&self, descriptor: &Texture2DDescriptor) -> JsValue
Creates a 2D texture from a Texture2DDescriptor.
The returned value is the GpuTexture itself; the caller is
expected to create views via texture.createView() (or use
the result as a RENDER_ATTACHMENT view in a render pass
descriptor).
§Arguments
descriptor- The texture descriptor.
§Returns
JsValue- The newGpuTexture, orJsValue::UNDEFINEDon allocation failure (includingwidth == 0orheight == 0).
Sourcepub fn create_sampler(&self, descriptor: &GpuSamplerDescriptor) -> JsValue
pub fn create_sampler(&self, descriptor: &GpuSamplerDescriptor) -> JsValue
Creates a GpuSampler from a GpuSamplerDescriptor.
The returned value is a sampler suitable for binding via
BindGroupEntry::Sampler (see
Self::create_bind_group).
§Arguments
descriptor- The sampler descriptor.
§Returns
JsValue- The newGpuSampler, orJsValue::UNDEFINEDon allocation failure.
Sourcepub fn create_uniform_bind_group(
&self,
pipeline: &JsValue,
buffer: &JsValue,
) -> JsValue
pub fn create_uniform_bind_group( &self, pipeline: &JsValue, buffer: &JsValue, ) -> JsValue
Creates a bind group for @group(0) of the given pipeline, binding the
given uniform buffer at @binding(0).
The pipeline must have been created with layout: "auto" (the default
for WebGpuRenderer::create_render_pipeline) and its WGSL shader must
Creates a bind group for a single uniform buffer at @group(0) @binding(0).
Thin convenience wrapper around
WebGpuRenderer::create_bind_group that takes the single
uniform buffer directly. For pipelines with multiple bindings
(uniform + texture + sampler, or several uniform slots) use
the slice form with explicit BindGroupEntry values.
§Arguments
&JsValue- The render or compute pipeline that owns the bind group layout.&JsValue- The uniformGpuBufferto bind.
§Returns
JsValue- The createdGpuBindGroup.
Sourcepub fn create_bind_group(
&self,
pipeline: &JsValue,
index: u32,
entries: &[BindGroupEntry],
) -> JsValue
pub fn create_bind_group( &self, pipeline: &JsValue, index: u32, entries: &[BindGroupEntry], ) -> JsValue
Creates a bind group from a list of BindGroupEntry values.
The index selects which auto-derived bind group layout to use
(matches @group(N) in the shader); the entries slice
describes every binding entry to populate. Each entry’s
binding slot is forwarded as-is, so the caller is responsible
for keeping them consistent with the shader’s @binding(...)
declarations.
The device.createBindGroup call is wrapped in a
pushErrorScope("validation") / popErrorScope() pair so
creation failures surface as Err(WebGpuError::CreateBindGroup)
instead of being silently lost. See
Self::pop_error_sync for the full pop semantics.
§Arguments
pipeline- The render/compute pipeline whose bind group layout to use.index- The bind group index (the@group(N)slot in the shader; typically0).entries- The list of bindings to attach. Pass an empty slice to allocate an empty bind group (rare, but legal).
§Returns
JsValue- The createdGpuBindGroup. The value isJsValue::UNDEFINEDwhen the device rejects the call; callers should compare againstUNDEFINEDbefore using it.
Sourcepub fn render_frame(
&mut self,
pipeline: &JsValue,
clear_color: (f64, f64, f64, f64),
vertex_count: u32,
)
pub fn render_frame( &mut self, pipeline: &JsValue, clear_color: (f64, f64, f64, f64), vertex_count: u32, )
Renders a complete frame with a pipeline and animated clear color.
This is a convenience method that creates a command encoder, begins a render pass with the given clear color, sets the pipeline, draws the specified number of vertices, ends the pass, finishes the encoder, and submits the command buffer.
§Arguments
&JsValue- The render pipeline to use.(f64, f64, f64, f64)- The clear color as (r, g, b, a) in 0.0–1.0 range.u32- The number of vertices to draw.
Sourcepub fn render_frame_with_bind_group(
&mut self,
pipeline: &JsValue,
bind_group: &JsValue,
clear_color: (f64, f64, f64, f64),
vertex_count: u32,
)
pub fn render_frame_with_bind_group( &mut self, pipeline: &JsValue, bind_group: &JsValue, clear_color: (f64, f64, f64, f64), vertex_count: u32, )
Renders a complete frame like WebGpuRenderer::render_frame, but
additionally binds a uniform bind group at @group(0) before drawing.
Used by shaders that read per-frame data (pointer position, rotation
angles, …) from a uniform buffer. The bind group should be created
once via WebGpuRenderer::create_uniform_bind_group and its buffer
refreshed each frame via WebGpuRenderer::update_uniform_buffer.
§Arguments
&JsValue- The render pipeline to use.&JsValue- The bind group for@group(0).(f64, f64, f64, f64)- The clear color as (r, g, b, a) in 0.0–1.0 range.u32- The number of vertices to draw.
Sourcepub fn dispose(&self)
pub fn dispose(&self)
Releases all GPU resources held by this renderer.
The teardown order matters per the WebGPU spec:
GpuCanvasContext.unconfigure()- releases the swap chain so the DOM canvas can be GCed.GpuDevice.destroy()- releases all child resources (buffers, textures, pipelines) and the device itself.
Callers should run this from a use_cleanup callback whenever the
host component is being torn down (e.g. on a match arm switch).
Without it the previous GPU device lingers until GC, and a fresh
init() may either reuse the dead device (silent black canvas) or
fail to acquire a new one until the old device is collected.
Reflect::get failures and JS exceptions are swallowed - this is a
best-effort cleanup path, and the engine must not panic during
teardown.
Sourcepub fn set_viewport(
&self,
pass: &JsValue,
x: f32,
y: f32,
width: f32,
height: f32,
min_depth: f32,
max_depth: f32,
)
pub fn set_viewport( &self, pass: &JsValue, x: f32, y: f32, width: f32, height: f32, min_depth: f32, max_depth: f32, )
Sets the viewport for all subsequent draw calls on the given render pass.
The viewport maps NDC [-1, 1] to the given pixel rectangle. min_depth
and max_depth (both in [0, 1]) clamp the depth range; the defaults
of 0.0 and 1.0 cover the whole depth buffer. This call must be
issued between beginRenderPass() and pass.end().
§Arguments
&JsValue- The activeGpuRenderPassEncoder.f32- X coordinate of the viewport’s top-left in pixels.f32- Y coordinate of the viewport’s top-left in pixels.f32- Viewport width in pixels.f32- Viewport height in pixels.f32- Minimum depth, clamped to[0, 1]. Pass0.0to disable.f32- Maximum depth, clamped to[0, 1]. Pass1.0to disable.
Sourcepub fn set_scissor_rect(
&self,
pass: &JsValue,
x: u32,
y: u32,
width: u32,
height: u32,
)
pub fn set_scissor_rect( &self, pass: &JsValue, x: u32, y: u32, width: u32, height: u32, )
Sets the scissor rectangle for all subsequent draw calls on the given render pass.
Fragments outside the rectangle are discarded. The scissor is applied
after the viewport, so coordinates are in the same pixel space as
WebGpuRenderer::set_viewport. A scissor that extends outside the
render target is clamped to the target bounds by the GPU.
§Arguments
&JsValue- The activeGpuRenderPassEncoder.u32- X coordinate of the scissor origin in pixels.u32- Y coordinate of the scissor origin in pixels.u32- Scissor width in pixels.u32- Scissor height in pixels.
Sourcepub fn set_blend_constant(&self, pass: &JsValue, r: f32, g: f32, b: f32, a: f32)
pub fn set_blend_constant(&self, pass: &JsValue, r: f32, g: f32, b: f32, a: f32)
Sets the blend constant used by "constant" / "one-minus-constant"
blend factors.
Affects all subsequent draw calls on the given render pass. The
constant is a linear-space RGBA color in [0, 1] per component.
§Arguments
&JsValue- The activeGpuRenderPassEncoder.f32- Red component.f32- Green component.f32- Blue component.f32- Alpha component.
Sourcepub fn set_stencil_reference(&self, pass: &JsValue, reference: u32)
pub fn set_stencil_reference(&self, pass: &JsValue, reference: u32)
Sets the stencil reference value used by stencil tests.
The reference is the value the GPU compares against when the shader
pipeline was built with a stencil state using "always", "less",
"equal", etc. compare ops. This call must be issued between
beginRenderPass() and pass.end().
§Arguments
&JsValue- The activeGpuRenderPassEncoder.u32- The stencil reference value (8-bit,[0, 255]).
Sourcepub fn set_bind_group_with_dynamic_offsets(
&self,
pass: &JsValue,
index: u32,
group: &JsValue,
dynamic_offsets: &[u32],
)
pub fn set_bind_group_with_dynamic_offsets( &self, pass: &JsValue, index: u32, group: &JsValue, dynamic_offsets: &[u32], )
Sets a bind group on a render pass with dynamic offsets.
Use this overload of set_bind_group when the bind-group layout was
built with hasDynamicOffset: true for one or more buffer bindings.
Each value in dynamic_offsets is added to the corresponding
@group(N) @binding(M) buffer’s base offset before the draw call.
For non-dynamic bind groups, prefer the simpler
set_bind_group (3-arg) overload exposed via the pub(crate) API.
§Arguments
&JsValue- The activeGpuRenderPassEncoder.u32- Bind-group slot index.&JsValue- TheGpuBindGroupto bind.&[u32]- Dynamic offsets, one per dynamic-offset binding.
Sourcepub fn set_bind_group_compute_with_dynamic_offsets(
&self,
pass: &JsValue,
index: u32,
group: &JsValue,
dynamic_offsets: &[u32],
)
pub fn set_bind_group_compute_with_dynamic_offsets( &self, pass: &JsValue, index: u32, group: &JsValue, dynamic_offsets: &[u32], )
Sets a bind group on a compute pass with optional dynamic offsets.
Same semantics as WebGpuRenderer::set_bind_group_with_dynamic_offsets
but on a GpuComputePassEncoder. The setBindGroup method name is
the same on both encoder types; this method wraps it for the compute
pass to give callers a typed entry point.
§Arguments
&JsValue- The activeGpuComputePassEncoder.u32- Bind-group slot index.&JsValue- TheGpuBindGroupto bind.&[u32]- Dynamic offsets for dynamic-offset bindings.
Sourcepub fn create_view(
&self,
texture: &JsValue,
descriptor: Option<&TextureViewDescriptor>,
) -> JsValue
pub fn create_view( &self, texture: &JsValue, descriptor: Option<&TextureViewDescriptor>, ) -> JsValue
Creates a GpuTextureView for the given texture with full descriptor control.
Pass None for a default view (full 2D, all mips, all aspects) — this
is the cheap view that is implicitly created by bind-group creation.
Pass Some(&descriptor) to sub-select mip levels, array slices, or
the depth-only aspect of a depth-stencil texture.
§Arguments
&JsValue- TheGpuTextureto view.Option<&TextureViewDescriptor>- Optional descriptor.
§Returns
JsValue- TheGpuTextureView. ReturnsJsValue::UNDEFINEDif the call fails (e.g. invalid mip range); check forundefinedbefore using the result.
Sourcepub fn generate_mipmaps(&self, texture: &JsValue)
pub fn generate_mipmaps(&self, texture: &JsValue)
Generates the full mipmap chain for the given texture.
Equivalent to repeatedly calling copyTextureToTexture from level
i to level i+1 with the appropriate mip dimensions, but in one
GPU command. The texture must have been created with RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_DST | COPY_SRC usage and mipLevelCount > 1.
Requires the mipmap WebGPU feature, or a GPU that supports it
unconditionally (most desktop GPUs do).
§Arguments
&JsValue- TheGpuTexturewhose mips will be generated.
Sourcepub fn write_texture(&self, descriptor: &TextureWriteDescriptor)
pub fn write_texture(&self, descriptor: &TextureWriteDescriptor)
Uploads CPU-side pixel data directly to a texture via queue.writeTexture.
Use this instead of create_buffer + write_buffer + copyBufferToTexture
for one-shot uploads (ImGui font atlases, sprite sheets, procedural
noise). The queue is acquired internally via the cached device.queue
handle, so this is the preferred path for textures that are written
once and sampled many times.
bytes_per_row must be a multiple of 256. The data layout must
match the texture’s format; the engine does not perform swizzling.
§Arguments
&TextureWriteDescriptor- The write descriptor.
Sourcepub fn create_shader_module_with_label(
&self,
wgsl_source: &str,
label: &str,
) -> JsValue
pub fn create_shader_module_with_label( &self, wgsl_source: &str, label: &str, ) -> JsValue
Creates a GpuShaderModule from a WGSL source string with a debug label.
Equivalent to the pub(crate) fn create_shader_module overload but
attaches a label to the module so it shows up under that name in
browser devtools (e.g. Chrome’s chrome://gpu-internals and the
WebGPU Inspector panel). The label has no runtime effect; it is
purely a developer-experience aid when many shader modules coexist.
§Arguments
&str- WGSL source.&str- Debug label shown in browser devtools.
§Returns
JsValue- TheGpuShaderModule, orJsValue::UNDEFINEDif the call fails.
Sourcepub async fn read_buffer(
&self,
buffer: &JsValue,
offset: u64,
size: u64,
) -> Option<Vec<u8>>
pub async fn read_buffer( &self, buffer: &JsValue, offset: u64, size: u64, ) -> Option<Vec<u8>>
Reads back the contents of a buffer via mapAsync + getMappedRange +
unmap.
This is an async fn, NOT a synchronous wrapper. It must be
await-ed by the caller. Use it from inside another
wasm_bindgen_futures future (e.g. a frame loop) — do not call
it from synchronous code, since the awaiter must be driven by
the executor. The buffer must have been created with MAP_READ
usage, and the read must be preceded by a GPU submission that
finished writing to the buffer (i.e. queue.submit([encoder.finish()])
followed by device.lost / a fence).
§Arguments
&JsValue- TheGpuBufferto read back.u64- Byte offset into the buffer.u64- Number of bytes to read.
§Returns
Option<Vec<u8>>- The bytes, orNoneif the readback failed.
Source§impl WebGpuRenderer
impl WebGpuRenderer
pub fn get_device(&self) -> &JsValue
pub fn get_mut_device(&mut self) -> &mut JsValue
pub fn set_device(&mut self, val: JsValue) -> &mut Self
pub fn get_queue(&self) -> &JsValue
pub fn get_mut_queue(&mut self) -> &mut JsValue
pub fn set_queue(&mut self, val: JsValue) -> &mut Self
pub fn get_context(&self) -> &JsValue
pub fn get_mut_context(&mut self) -> &mut JsValue
pub fn set_context(&mut self, val: JsValue) -> &mut Self
pub fn get_canvas(&self) -> &HtmlCanvasElement
pub fn get_mut_canvas(&mut self) -> &mut HtmlCanvasElement
pub fn set_canvas(&mut self, val: HtmlCanvasElement) -> &mut Self
pub fn get_format(&self) -> String
pub fn get_mut_format(&mut self) -> &mut String
pub fn set_format(&mut self, val: String) -> &mut Self
pub fn get_width(&self) -> u32
pub fn get_mut_width(&mut self) -> &mut u32
pub fn set_width(&mut self, val: u32) -> &mut Self
pub fn get_height(&self) -> u32
pub fn get_mut_height(&mut self) -> &mut u32
pub fn set_height(&mut self, val: u32) -> &mut Self
pub fn get_antialias(&self) -> bool
pub fn get_mut_antialias(&mut self) -> &mut bool
pub fn set_antialias(&mut self, val: bool) -> &mut Self
pub fn get_multisample_texture(&self) -> Option<JsValue>
pub fn try_get_multisample_texture(&self) -> Option<JsValue>
pub fn get_mut_multisample_texture(&mut self) -> &mut Option<JsValue>
pub fn set_multisample_texture(&mut self, val: Option<JsValue>) -> &mut Self
pub fn get_multisample_view(&self) -> Option<JsValue>
pub fn try_get_multisample_view(&self) -> Option<JsValue>
pub fn get_mut_multisample_view(&mut self) -> &mut Option<JsValue>
pub fn set_multisample_view(&mut self, val: Option<JsValue>) -> &mut Self
pub fn get_depth_texture(&self) -> Option<JsValue>
pub fn try_get_depth_texture(&self) -> Option<JsValue>
pub fn get_mut_depth_texture(&mut self) -> &mut Option<JsValue>
pub fn set_depth_texture(&mut self, val: Option<JsValue>) -> &mut Self
pub fn get_depth_view(&self) -> Option<JsValue>
pub fn try_get_depth_view(&self) -> Option<JsValue>
pub fn get_mut_depth_view(&mut self) -> &mut Option<JsValue>
pub fn set_depth_view(&mut self, val: Option<JsValue>) -> &mut Self
pub fn get_depth_format(&self) -> Option<String>
pub fn try_get_depth_format(&self) -> Option<String>
pub fn get_mut_depth_format(&mut self) -> &mut Option<String>
pub fn set_depth_format(&mut self, val: Option<String>) -> &mut Self
pub fn get_device_lost_callback(&self) -> Option<Function>
pub fn try_get_device_lost_callback(&self) -> Option<Function>
pub fn get_mut_device_lost_callback(&mut self) -> &mut Option<Function>
pub fn set_device_lost_callback(&mut self, val: Option<Function>) -> &mut Self
pub fn get_device_lost(&self) -> bool
pub fn get_mut_device_lost(&mut self) -> &mut bool
pub fn set_device_lost(&mut self, val: bool) -> &mut Self
pub fn get_pending_error(&self) -> &Rc<PendingErrorCell>
pub fn get_mut_pending_error(&mut self) -> &mut Rc<PendingErrorCell>
pub fn set_pending_error(&mut self, val: Rc<PendingErrorCell>) -> &mut Self
pub fn get_command_encoder(&self) -> Option<JsValue>
pub fn try_get_command_encoder(&self) -> Option<JsValue>
pub fn get_mut_command_encoder(&mut self) -> &mut Option<JsValue>
pub fn set_command_encoder(&mut self, val: Option<JsValue>) -> &mut Self
Trait Implementations§
Source§impl Clone for WebGpuRenderer
impl Clone for WebGpuRenderer
Source§fn clone(&self) -> WebGpuRenderer
fn clone(&self) -> WebGpuRenderer
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more