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.
timeGpufunction
Measure GPU timestamp elapsed time surrounding work submitted by a callback.
timeGpu(fn: (ctx: GpuContext) => void | Promise<void>): Promise<number>;Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
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.ctx | GpuContext | Yes | — | 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
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) => void | No | — | 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.message | string | Yes | — | Error message, or GPU device lost: followed by the loss reason. |
opts.onError.recoverable | boolean | Yes | — | True for uncaptured errors; false for device loss. |
opts.onRebuild | (ctx: GpuContext) => void | No | — | Called after resetting the shared context and successfully acquiring a fresh device; rebuild your own resources here. |
opts.onRebuild.ctx | GpuContext | Yes | — | 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
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
canvas | HTMLCanvasElement | Yes | — | Canvas whose width and height backing attributes will be changed; CSS dimensions remain unchanged. |
dprCap | number | No | 2 | Maximum 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
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.
}GPU 计时、单次设备生命周期诊断和画布尺寸助手。
辅助输入、dispatch count、托管批次与类型化内核已随 2.1.0 发布。原 API 仍以 npm 2.0.0 声明与实现为历史核对基线;2.1.0 和 2.2.0 新增能力在对应 API 中注明并引用 src 文件,不代表整份 API 重新审计。只列出此入口实际导出的公开 API。
timeGpufunction
测量回调提交工作前后的 GPU 时间戳间隔。
timeGpu(fn: (ctx: GpuContext) => void | Promise<void>): Promise<number>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
fn | (ctx: GpuContext) => void | Promise<void> | 是 | — | 接收共享上下文的回调。回调返回或完成前应把工作提交至 ctx.device.queue;只编码而未提交的工作不会被计入。 |
fn.ctx | GpuContext | 是 | — | 回调参数:当前共享 GPU 上下文及其 device。 |
返回值
Promise<number> 两个标记提交之间的 GPU 时间戳差,单位毫秒,包含中间空隙和队列工作。
行为与约束
- 使用三阶段队列:提交前置时间戳,await fn(ctx),然后提交后置时间戳和查询读回。它不是单独 dispatch 的耗时,也不是显示帧率。
- 当前 device 必须已启用 timestamp-query;外部接入的 device 应自行请求该特性。其他设备/队列的工作不在标记范围内。
- 成功测量后会销毁临时查询/读回资源。2.0.0 在回调或读回失败时没有 finally 清理。
错误与失败情况
- device 不含 timestamp-query 时拒绝,错误为 UsageError,code 是 ERR_TIMESTAMP_UNSUPPORTED;上下文/设备、回调、查询和映射错误直接传播。
示例
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
监听未捕获错误,以及一次设备丢失/重新获取过程。
watchDevice(opts: {
onError?: (message: string, recoverable: boolean) => void;
onRebuild?: (ctx: GpuContext) => void;
}): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
opts | { onError?: (message: string, recoverable: boolean) => void; onRebuild?: (ctx: GpuContext) => void } | 是 | — | 回调选项,无需回调时传 {}。 |
opts.onError | (message: string, recoverable: boolean) => void | 否 | — | uncapturederror 时以 recoverable=true 调用,设备丢失时以 false 调用。这是库的分类标记,并不保证可恢复。 |
opts.onError.message | string | 是 | — | 错误消息;设备丢失时为 GPU device lost: 加丢失原因。 |
opts.onError.recoverable | boolean | 是 | — | 未捕获错误为 true;设备丢失为 false。 |
opts.onRebuild | (ctx: GpuContext) => void | 否 | — | 重置共享上下文并成功获取新设备后调用;在此重建应用自己的资源。 |
opts.onRebuild.ctx | GpuContext | 是 | — | 新获取的上下文;旧缓冲和管线不会因此自动修复。 |
返回值
void 无返回值。
行为与约束
- 立即返回,注册异步进行;不返回 Promise、取消订阅函数,也不会自动给后继设备重新注册监听。
- 仅监听最初获取的设备。需要时对新设备重新注册。已有模拟、画布、缓冲和管线均须由应用重新创建。
- 重新获取失败会被吞掉;初始上下文获取没有 catch,注册前应处理可用性。重复调用会重复添加监听器。
示例
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
返回浏览器推荐的画布纹理格式。
preferredCanvasFormat(): GPUTextureFormat;参数
此调用不接收参数。
返回值
GPUTextureFormat navigator.gpu.getPreferredCanvasFormat() 的结果。
行为与约束
- 直接调用浏览器接口,不申请设备、不配置画布,也不检查 navigator.gpu 是否存在。
示例
import { preferredCanvasFormat } from 'wgpu-kit/observe';
const format = preferredCanvasFormat();resizeCanvasfunction
根据 CSS 客户区尺寸和有上限的设备像素比更新画布像素尺寸。
resizeCanvas(canvas: HTMLCanvasElement, dprCap?: number): boolean;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
canvas | HTMLCanvasElement | 是 | — | 修改该画布的 width/height 像素属性,CSS 尺寸保持不变。 |
dprCap | number | 否 | 2 | 设备像素比上限;实际 DPR 为 min(window.devicePixelRatio || 1, dprCap)。应使用有限正数。 |
返回值
boolean 宽或高发生变化时为 true;两者都相同时为 false。
行为与约束
- 每个维度按 max(1, floor(clientDimension × effectiveDPR)) 计算。不执行输入校验,不自动创建 ResizeObserver,也不替你调整渲染器或重建纹理。
示例
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.
}