API REFERENCE · 2.2.0

wgpu-kit/observe

GPU timing, one-cycle device diagnostics, and canvas sizing helpers.

Auxiliary inputs, dispatch counts, managed batches and typed kernels are released in 2.1.0. The original API retains the published npm 2.0.0 declarations and implementation as its historical audit baseline; Additions in 2.1.0 and 2.2.0 are identified on affected APIs and cite src files, without claiming a fresh audit of the entire API. Only actual public exports of this entry point are listed.

Source reference: 1 ↗ 2 ↗ 3 ↗

timeGpufunction

Measure GPU timestamp elapsed time surrounding work submitted by a callback.

timeGpu(fn: (ctx: GpuContext) => void | Promise<void>): Promise<number>;

Parameters

NameTypeRequiredDefaultMeaning
fn(ctx: GpuContext) => void | Promise<void>Yes—Callback receiving the shared context. Submit the work to ctx.device.queue before the callback returns/resolves; encoding without submission is not measured.
fn.ctxGpuContextYes—Callback argument: the current shared GPU context, including its device.

Returns

Promise<number> GPU timestamp difference in milliseconds, including gaps and queue work between the two marker submissions.

Behavior & constraints

  • Uses three queue phases: submit a leading timestamp, await fn(ctx), then submit a trailing timestamp plus query readback. This is not isolated per-dispatch duration or display FPS.
  • The active device must have timestamp-query enabled. An externally adopted device must have requested the feature itself. Work on another device/queue is outside the markers.
  • Successful measurement destroys temporary query/readback resources. Version 2.0.0 has no finally cleanup if the callback or readback fails.

Errors & failure cases

  • Rejects UsageError with code ERR_TIMESTAMP_UNSUPPORTED when the device lacks timestamp-query. Context/device, callback, query, and mapping failures propagate.

Examples

Time a prepared kernel submission; kernel/resources are application-owned.
import { timeGpu } from 'wgpu-kit/observe';
// kernel and resources are created earlier.
await kernel.prepare();
const milliseconds = await timeGpu((ctx) => {
  const encoder = ctx.device.createCommandEncoder();
  kernel.encode(encoder, resources);
  ctx.device.queue.submit([encoder.finish()]);
  kernel.endSubmit();
});
console.log(milliseconds);

watchDevicefunction

Observe uncaptured errors and one device-loss/reacquisition cycle.

watchDevice(opts: {
  onError?: (message: string, recoverable: boolean) => void;
  onRebuild?: (ctx: GpuContext) => void;
}): void;

Parameters

NameTypeRequiredDefaultMeaning
opts{ onError?: (message: string, recoverable: boolean) => void; onRebuild?: (ctx: GpuContext) => void }Yes—Callback options; pass {} if no callbacks are needed.
opts.onError(message: string, recoverable: boolean) => voidNo—Called for uncapturederror with recoverable=true and for device loss with recoverable=false. These flags are library labels, not a guarantee of recovery.
opts.onError.messagestringYes—Error message, or GPU device lost: followed by the loss reason.
opts.onError.recoverablebooleanYes—True for uncaptured errors; false for device loss.
opts.onRebuild(ctx: GpuContext) => voidNo—Called after resetting the shared context and successfully acquiring a fresh device; rebuild your own resources here.
opts.onRebuild.ctxGpuContextYes—Freshly acquired context, not a repaired version of old buffers or pipelines.

Returns

void No return value.

Behavior & constraints

  • Returns immediately; setup runs asynchronously. No promise, unsubscribe function, or automatic recursive watcher registration is returned.
  • Only the originally acquired device is watched. Re-register for a new device if needed. Existing simulations, canvases, buffers, and pipelines must be recreated by the application.
  • Reacquisition failure is swallowed. Initial context acquisition has no catch; handle availability before registering. Repeated calls add repeated listeners.

Examples

Register diagnostics after verifying context availability.
import { GpuContext } from 'wgpu-kit';
import { watchDevice } from 'wgpu-kit/observe';
await GpuContext.get();
watchDevice({
  onError: (message, recoverable) => console.warn(message, recoverable),
  onRebuild: (ctx) => {
    console.log('Fresh GPU device:', ctx.device);
    // Recreate application buffers, kernels, and canvas bindings here.
  },
});

preferredCanvasFormatfunction

Return the browser preferred canvas texture format.

preferredCanvasFormat(): GPUTextureFormat;

Parameters

This call takes no arguments.

Returns

GPUTextureFormat Result of navigator.gpu.getPreferredCanvasFormat().

Behavior & constraints

  • Direct browser helper; it does not request a device, configure a canvas, or guard missing navigator.gpu.

Examples

Read the format before configuring a WebGPU canvas.
import { preferredCanvasFormat } from 'wgpu-kit/observe';
const format = preferredCanvasFormat();

resizeCanvasfunction

Update canvas backing dimensions from CSS client size and capped device pixel ratio.

resizeCanvas(canvas: HTMLCanvasElement, dprCap?: number): boolean;

Parameters

NameTypeRequiredDefaultMeaning
canvasHTMLCanvasElementYes—Canvas whose width and height backing attributes will be changed; CSS dimensions remain unchanged.
dprCapnumberNo2Maximum device pixel ratio; effective DPR is min(window.devicePixelRatio || 1, dprCap). Use a finite positive cap.

Returns

boolean True if width or height changed; false if both already match.

Behavior & constraints

  • Each dimension is max(1, floor(clientDimension × effectiveDPR)). No input validation, ResizeObserver, renderer resize, or texture reallocation is performed for you.

Examples

Call during application resize handling.
import { resizeCanvas } from 'wgpu-kit/observe';
const canvas = document.querySelector<HTMLCanvasElement>('#canvas')!;
if (resizeCanvas(canvas, 2)) {
  // Recreate size-dependent textures and update your camera if needed.
}

Search concepts, APIs, and examples