The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
// WebGPU (navigator.gpu) over threert-webgpu (wgpu). See webgpu/src/lib.rs for the
// design; the short version:
//
// * Native objects are integer ids (`_id`). Objects the page drops are released in batches
// (FinalizationRegistry → `N.release` at the next submit), never while a stream may use them.
// * GPUCommandEncoder and its pass encoders write 32-bit words into a pooled growable stream
// (opcodes below mirror webgpu/src/cmd.rs); `finish()` is the only native call of an
// encoder. Render bundles are streams spliced into the pass by `executeBundles`.
// * Creation dictionaries are passed as JSON with GPU objects replaced by their ids.
import { Event, EventTarget } from "../../runtime/js/core/events.ts";
import { surfaces, type CanvasHost } from "../../runtime/js/shared/surfaces.ts";
const g = globalThis as any;
let N: any;
// -------------------------------------------------------------------------------------- constants
export const GPUBufferUsage = Object.freeze({ MAP_READ: 1, MAP_WRITE: 2, COPY_SRC: 4, COPY_DST: 8, INDEX: 16, VERTEX: 32, UNIFORM: 64, STORAGE: 128, INDIRECT: 256, QUERY_RESOLVE: 512 });
export const GPUTextureUsage = Object.freeze({ COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, STORAGE_BINDING: 8, RENDER_ATTACHMENT: 16 });
export const GPUMapMode = Object.freeze({ READ: 1, WRITE: 2 });
export const GPUShaderStage = Object.freeze({ VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 });
export const GPUColorWrite = Object.freeze({ RED: 1, GREEN: 2, BLUE: 4, ALPHA: 8, ALL: 15 });
/** Command stream opcodes (crates/webgpu/src/cmd.rs `op`). */
const OP = {
BEGIN_RENDER_PASS: 1, BEGIN_COMPUTE_PASS: 2, END_PASS: 3, COPY_B2B: 4, COPY_B2T: 5, COPY_T2B: 6, COPY_T2T: 7, CLEAR_BUFFER: 8, RESOLVE_QUERY_SET: 9,
SET_PIPELINE: 16, SET_BIND_GROUP: 17, SET_VERTEX_BUFFER: 18, SET_INDEX_BUFFER: 19, DRAW: 20, DRAW_INDEXED: 21, DRAW_INDIRECT: 22, DRAW_INDEXED_INDIRECT: 23,
SET_VIEWPORT: 24, SET_SCISSOR: 25, SET_BLEND_CONSTANT: 26, SET_STENCIL_REF: 27, BEGIN_OCCLUSION: 28, END_OCCLUSION: 29, DISPATCH: 30, DISPATCH_INDIRECT: 31,
} as const;
const NONE = 0xffffffff;
// -------------------------------------------------------------------------------------- errors
function domError(message: string, name: string) {
const D = g.DOMException;
if (typeof D === "function") return new D(message, name);
const e = new Error(message); e.name = name; return e;
}
/** Native errors are "Kind: message"; map them to the WebGPU exception types. */
function rethrow(e: any): never {
const m = String(e?.message ?? e);
const k = /^(TypeError|RangeError|OperationError|InvalidStateError|AbortError): ?([\s\S]*)$/.exec(m);
if (!k) throw e;
if (k[1] === "TypeError") throw new TypeError(k[2]);
if (k[1] === "RangeError") throw new RangeError(k[2]);
throw domError(k[2], k[1]);
}
export class GPUError { message: string; constructor(message: string) { this.message = String(message ?? ""); } }
export class GPUValidationError extends GPUError {}
export class GPUOutOfMemoryError extends GPUError {}
export class GPUInternalError extends GPUError {}
const ERROR_KINDS = [GPUValidationError, GPUOutOfMemoryError, GPUInternalError];
export class GPUPipelineError extends Error {
reason: string;
constructor(message = "", options: { reason?: string } = {}) { super(message); this.name = "GPUPipelineError"; this.reason = options.reason ?? "validation"; }
}
export class GPUUncapturedErrorEvent extends Event {
error: GPUError;
constructor(type: string, init: { error: GPUError }) { super(type); this.error = init.error; }
}
export class GPUDeviceLostInfo { reason: string; message: string; constructor(reason: string, message: string) { this.reason = reason; this.message = message; } }
export class GPUCompilationMessage {
message: string; type: string; lineNum: number; linePos: number; offset: number; length: number;
constructor(m: any) { this.message = m.message; this.type = m.type; this.lineNum = m.lineNum; this.linePos = m.linePos; this.offset = m.offset; this.length = m.length; }
}
export class GPUCompilationInfo { messages: GPUCompilationMessage[]; constructor(m: GPUCompilationMessage[]) { this.messages = m; } }
const devices = new Set<GPUDevice>();
/** Deliver queued uncaptured errors to the devices' `uncapturederror` listeners. */
function drainErrors() {
const e = N.takeErrors();
if (!e) return;
for (let i = 0; i < e.length; i += 2) {
const error = new ERROR_KINDS[e[i]](e[i + 1]);
for (const d of devices) {
try { d.dispatchEvent(new GPUUncapturedErrorEvent("uncapturederror", { error })); } catch (x) { console.error(x); }
}
}
}
function validationError(msg: string) { N.reportError(0, msg); }
// -------------------------------------------------------------------------------------- object lifetime
const released: number[] = [];
const registry = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => { released.push(id); }) : null;
function flushReleased() {
if (released.length) { N.release(released, released.length); released.length = 0; }
}
/** Base of native-backed objects; JSON descriptors replace them with their id. */
export class GPUObjectBase {
/** @internal */ _id: number;
label: string;
/** @internal */ constructor(id: number, label?: string, track = true) {
this._id = id; this.label = label ?? "";
if (track && id && registry) registry.register(this, id);
}
}
const lower = (_k: string, v: any) => (v instanceof GPUObjectBase ? v._id : v);
const toJSON = (d: any) => JSON.stringify(d ?? {}, lower);
// -------------------------------------------------------------------------------------- async completion
const waiting = new Map<number, (status: number) => void>();
let polling = false;
function wait(token: number, cb: (status: number) => void) {
waiting.set(token, cb);
if (!polling) { polling = true; g.setTimeout(pollTick, 0); }
}
function pollTick() {
polling = false;
const ev = N.poll();
if (ev) {
for (let i = 0; i < ev.length; i += 2) {
const cb = waiting.get(ev[i]);
if (cb) { waiting.delete(ev[i]); try { cb(ev[i + 1]); } catch (e) { console.error(e); } }
}
}
drainErrors();
if (waiting.size) { polling = true; g.setTimeout(pollTick, 1); }
}
// -------------------------------------------------------------------------------------- command streams
class Stream {
u: Uint32Array; f: Float32Array; i: Int32Array; n = 0;
constructor(cap = 2048) { this.u = new Uint32Array(cap); this.f = new Float32Array(this.u.buffer); this.i = new Int32Array(this.u.buffer); }
grow(k: number) {
const u = new Uint32Array(Math.max(this.u.length * 2, this.n + k + 64));
u.set(this.u.subarray(0, this.n));
this.u = u; this.f = new Float32Array(u.buffer); this.i = new Int32Array(u.buffer);
}
/** append raw words (bundles) */
append(w: Uint32Array) { if (this.n + w.length > this.u.length) this.grow(w.length); this.u.set(w, this.n); this.n += w.length; }
}
const streamPool: Stream[] = [];
const takeStream = () => streamPool.pop() ?? new Stream();
function giveStream(s: Stream) { s.n = 0; if (streamPool.length < 8 && s.u.length <= 1 << 20) streamPool.push(s); }
const vu32 = (v: any) => (v === undefined ? NONE : v >>> 0);
function colorOf(c: any): [number, number, number, number] {
if (!c) return [0, 0, 0, 0];
if (Array.isArray(c) || ArrayBuffer.isView(c as any)) return [+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0];
return [+c.r || 0, +c.g || 0, +c.b || 0, +c.a || 0];
}
function originOf(o: any): [number, number, number] {
if (!o) return [0, 0, 0];
if (Array.isArray(o)) return [o[0] >>> 0, o[1] >>> 0, o[2] >>> 0];
return [o.x >>> 0, o.y >>> 0, o.z >>> 0];
}
function extentOf(e: any): [number, number, number] {
if (Array.isArray(e)) return [e[0] >>> 0, e[1] === undefined ? 1 : e[1] >>> 0, e[2] === undefined ? 1 : e[2] >>> 0];
return [e.width >>> 0, e.height === undefined ? 1 : e.height >>> 0, e.depthOrArrayLayers === undefined ? 1 : e.depthOrArrayLayers >>> 0];
}
const aspectCode = (a: any) => (a === "stencil-only" ? 1 : a === "depth-only" ? 2 : 0);
const viewId = (v: any) => (v instanceof GPUTexture ? v.createView()._id : v ? v._id : 0);
// -------------------------------------------------------------------------------------- pass encoders
/** Commands shared by render passes and render bundles. */
class RenderCommands {
/** @internal */ _s!: Stream;
/** @internal */ _ended = false;
label = "";
setPipeline(p: GPURenderPipeline) {
const s = this._s; if (s.n + 2 > s.u.length) s.grow(2);
const u = s.u, n = s.n; u[n] = OP.SET_PIPELINE; u[n + 1] = p._id; s.n = n + 2;
}
setBindGroup(index: number, bg: GPUBindGroup | null, offsets?: any, start?: number, length?: number) {
let k = 0;
if (offsets) { k = length !== undefined ? length >>> 0 : offsets.length - (start ?? 0); }
const s = this._s; if (s.n + 4 + k > s.u.length) s.grow(4 + k);
const u = s.u; let n = s.n;
u[n++] = OP.SET_BIND_GROUP; u[n++] = index >>> 0; u[n++] = bg ? bg._id : 0; u[n++] = k;
if (k) { const o = start ?? 0; for (let j = 0; j < k; j++) u[n++] = offsets[o + j] >>> 0; }
s.n = n;
}
setVertexBuffer(slot: number, b: GPUBuffer | null, offset = 0, size?: number) {
const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);
const u = s.u, n = s.n; u[n] = OP.SET_VERTEX_BUFFER; u[n + 1] = slot >>> 0; u[n + 2] = b ? b._id : 0; u[n + 3] = offset >>> 0; u[n + 4] = vu32(size); s.n = n + 5;
}
setIndexBuffer(b: GPUBuffer, format: string, offset = 0, size?: number) {
const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);
const u = s.u, n = s.n; u[n] = OP.SET_INDEX_BUFFER; u[n + 1] = b._id; u[n + 2] = format === "uint32" ? 1 : 0; u[n + 3] = offset >>> 0; u[n + 4] = vu32(size); s.n = n + 5;
}
draw(vertexCount: number, instanceCount = 1, firstVertex = 0, firstInstance = 0) {
const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);
const u = s.u, n = s.n; u[n] = OP.DRAW; u[n + 1] = vertexCount >>> 0; u[n + 2] = instanceCount >>> 0; u[n + 3] = firstVertex >>> 0; u[n + 4] = firstInstance >>> 0; s.n = n + 5;
}
drawIndexed(indexCount: number, instanceCount = 1, firstIndex = 0, baseVertex = 0, firstInstance = 0) {
const s = this._s; if (s.n + 6 > s.u.length) s.grow(6);
const u = s.u, n = s.n; u[n] = OP.DRAW_INDEXED; u[n + 1] = indexCount >>> 0; u[n + 2] = instanceCount >>> 0; u[n + 3] = firstIndex >>> 0; s.i[n + 4] = baseVertex | 0; u[n + 5] = firstInstance >>> 0; s.n = n + 6;
}
drawIndirect(b: GPUBuffer, offset: number) { this._op2(OP.DRAW_INDIRECT, b._id, offset >>> 0); }
drawIndexedIndirect(b: GPUBuffer, offset: number) { this._op2(OP.DRAW_INDEXED_INDIRECT, b._id, offset >>> 0); }
/** @internal */ _op2(op: number, a: number, b: number) {
const s = this._s; if (s.n + 3 > s.u.length) s.grow(3);
const u = s.u, n = s.n; u[n] = op; u[n + 1] = a; u[n + 2] = b; s.n = n + 3;
}
pushDebugGroup(_l: string) {}
popDebugGroup() {}
insertDebugMarker(_l: string) {}
}
export class GPURenderPassEncoder extends RenderCommands {
/** @internal */ _enc: GPUCommandEncoder;
/** @internal */ constructor(enc: GPUCommandEncoder) { super(); this._enc = enc; this._s = enc._s; }
setViewport(x: number, y: number, w: number, h: number, minDepth: number, maxDepth: number) {
const s = this._s; if (s.n + 7 > s.u.length) s.grow(7);
const f = s.f, n = s.n; s.u[n] = OP.SET_VIEWPORT; f[n + 1] = x; f[n + 2] = y; f[n + 3] = w; f[n + 4] = h; f[n + 5] = minDepth; f[n + 6] = maxDepth; s.n = n + 7;
}
setScissorRect(x: number, y: number, w: number, h: number) {
const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);
const u = s.u, n = s.n; u[n] = OP.SET_SCISSOR; u[n + 1] = x >>> 0; u[n + 2] = y >>> 0; u[n + 3] = w >>> 0; u[n + 4] = h >>> 0; s.n = n + 5;
}
setBlendConstant(color: any) {
const c = colorOf(color);
const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);
const f = s.f, n = s.n; s.u[n] = OP.SET_BLEND_CONSTANT; f[n + 1] = c[0]; f[n + 2] = c[1]; f[n + 3] = c[2]; f[n + 4] = c[3]; s.n = n + 5;
}
setStencilReference(ref: number) { const s = this._s; if (s.n + 2 > s.u.length) s.grow(2); s.u[s.n] = OP.SET_STENCIL_REF; s.u[s.n + 1] = ref >>> 0; s.n += 2; }
beginOcclusionQuery(index: number) { const s = this._s; if (s.n + 2 > s.u.length) s.grow(2); s.u[s.n] = OP.BEGIN_OCCLUSION; s.u[s.n + 1] = index >>> 0; s.n += 2; }
endOcclusionQuery() { const s = this._s; if (s.n + 1 > s.u.length) s.grow(1); s.u[s.n++] = OP.END_OCCLUSION; }
executeBundles(bundles: Iterable<GPURenderBundle>) {
for (const b of bundles) { this._s.append(b._words); this._enc._refs.push(b); }
}
end() {
if (this._ended) { validationError("GPURenderPassEncoder.end: the pass already ended"); return; }
this._ended = true;
const s = this._s; if (s.n + 1 > s.u.length) s.grow(1); s.u[s.n++] = OP.END_PASS;
this._enc._state = "open";
}
}
export class GPUComputePassEncoder {
/** @internal */ _enc: GPUCommandEncoder;
/** @internal */ _s: Stream;
/** @internal */ _ended = false;
label = "";
/** @internal */ constructor(enc: GPUCommandEncoder) { this._enc = enc; this._s = enc._s; }
setPipeline(p: GPUComputePipeline) { RenderCommands.prototype.setPipeline.call(this as any, p as any); }
setBindGroup(index: number, bg: GPUBindGroup | null, offsets?: any, start?: number, length?: number) { RenderCommands.prototype.setBindGroup.call(this as any, index, bg, offsets, start, length); }
dispatchWorkgroups(x: number, y = 1, z = 1) {
const s = this._s; if (s.n + 4 > s.u.length) s.grow(4);
const u = s.u, n = s.n; u[n] = OP.DISPATCH; u[n + 1] = x >>> 0; u[n + 2] = y >>> 0; u[n + 3] = z >>> 0; s.n = n + 4;
}
dispatchWorkgroupsIndirect(b: GPUBuffer, offset: number) { RenderCommands.prototype._op2.call(this as any, OP.DISPATCH_INDIRECT, b._id, offset >>> 0); }
pushDebugGroup(_l: string) {}
popDebugGroup() {}
insertDebugMarker(_l: string) {}
end() {
if (this._ended) { validationError("GPUComputePassEncoder.end: the pass already ended"); return; }
this._ended = true;
const s = this._s; if (s.n + 1 > s.u.length) s.grow(1); s.u[s.n++] = OP.END_PASS;
this._enc._state = "open";
}
}
export class GPURenderBundle { /** @internal */ _words: Uint32Array; /** @internal */ _refs: any[]; label = ""; /** @internal */ constructor(w: Uint32Array, refs: any[]) { this._words = w; this._refs = refs; } }
export class GPURenderBundleEncoder extends RenderCommands {
/** @internal */ _refs: any[] = [];
/** @internal */ constructor(desc: any) { super(); this._s = new Stream(256); this.label = desc?.label ?? ""; }
setPipeline(p: GPURenderPipeline) { this._refs.push(p); super.setPipeline(p); }
setBindGroup(index: number, bg: GPUBindGroup | null, offsets?: any, start?: number, length?: number) { this._refs.push(bg); super.setBindGroup(index, bg, offsets, start, length); }
setVertexBuffer(slot: number, b: GPUBuffer | null, offset = 0, size?: number) { this._refs.push(b); super.setVertexBuffer(slot, b, offset, size); }
setIndexBuffer(b: GPUBuffer, format: string, offset = 0, size?: number) { this._refs.push(b); super.setIndexBuffer(b, format, offset, size); }
drawIndirect(b: GPUBuffer, offset: number) { this._refs.push(b); super.drawIndirect(b, offset); }
drawIndexedIndirect(b: GPUBuffer, offset: number) { this._refs.push(b); super.drawIndexedIndirect(b, offset); }
finish(desc?: any) {
const b = new GPURenderBundle(this._s.u.slice(0, this._s.n), this._refs);
b.label = desc?.label ?? "";
this._refs = [];
this._s.n = 0;
return b;
}
}
// -------------------------------------------------------------------------------------- command encoder
export class GPUCommandBuffer extends GPUObjectBase {}
export class GPUCommandEncoder {
/** @internal */ _s: Stream;
/** @internal */ _state: "open" | "locked" | "ended" = "open";
/** @internal */ _refs: any[] = [];
label: string;
/** @internal */ constructor(desc: any) { this._s = takeStream(); this.label = desc?.label ?? ""; }
/** @internal */ _begin(what: string) {
if (this._state !== "open") { validationError(`GPUCommandEncoder.${what}: the encoder is ${this._state === "locked" ? "locked by an open pass" : "finished"}`); return false; }
return true;
}
beginRenderPass(desc: any) {
const ok = this._begin("beginRenderPass");
const pass = new GPURenderPassEncoder(this);
if (!ok) { pass._s = new Stream(64); pass._ended = true; return pass; }
this._state = "locked";
pass.label = desc?.label ?? "";
const ca = desc.colorAttachments ?? [];
const k = ca.length;
const s = this._s; if (s.n + 2 + k * 8 + 15 > s.u.length) s.grow(2 + k * 8 + 15);
const u = s.u, f = s.f; let n = s.n;
u[n++] = OP.BEGIN_RENDER_PASS; u[n++] = k;
for (let i = 0; i < k; i++) {
const a = ca[i];
if (!a) { for (let j = 0; j < 8; j++) u[n++] = 0; continue; }
u[n++] = viewId(a.view); u[n++] = viewId(a.resolveTarget);
u[n++] = a.loadOp === "clear" ? 1 : 0; u[n++] = a.storeOp === "discard" ? 1 : 0;
const c = colorOf(a.clearValue);
f[n++] = c[0]; f[n++] = c[1]; f[n++] = c[2]; f[n++] = c[3];
}
const ds = desc.depthStencilAttachment;
if (ds) {
u[n++] = 1; u[n++] = viewId(ds.view);
u[n++] = ds.depthLoadOp === "clear" ? 2 : ds.depthLoadOp === "load" ? 1 : 0;
u[n++] = ds.depthStoreOp === "discard" ? 2 : ds.depthStoreOp === "store" ? 1 : 0;
f[n++] = ds.depthClearValue ?? 0; u[n++] = ds.depthReadOnly ? 1 : 0;
u[n++] = ds.stencilLoadOp === "clear" ? 2 : ds.stencilLoadOp === "load" ? 1 : 0;
u[n++] = ds.stencilStoreOp === "discard" ? 2 : ds.stencilStoreOp === "store" ? 1 : 0;
u[n++] = (ds.stencilClearValue ?? 0) >>> 0; u[n++] = ds.stencilReadOnly ? 1 : 0;
} else u[n++] = 0;
u[n++] = desc.occlusionQuerySet ? desc.occlusionQuerySet._id : 0;
const tw = desc.timestampWrites;
u[n++] = tw?.querySet ? tw.querySet._id : 0; u[n++] = vu32(tw?.beginningOfPassWriteIndex); u[n++] = vu32(tw?.endOfPassWriteIndex);
s.n = n;
return pass;
}
beginComputePass(desc?: any) {
const ok = this._begin("beginComputePass");
const pass = new GPUComputePassEncoder(this);
if (!ok) { pass._s = new Stream(64); pass._ended = true; return pass; }
this._state = "locked";
const tw = desc?.timestampWrites;
this._w([OP.BEGIN_COMPUTE_PASS, tw?.querySet ? tw.querySet._id : 0, vu32(tw?.beginningOfPassWriteIndex), vu32(tw?.endOfPassWriteIndex)]);
return pass;
}
/** @internal */ _w(words: number[]) {
const s = this._s; if (s.n + words.length > s.u.length) s.grow(words.length);
for (let i = 0; i < words.length; i++) s.u[s.n + i] = words[i];
s.n += words.length;
}
copyBufferToBuffer(src: GPUBuffer, a: any, b?: any, c?: any, d?: any) {
if (!this._begin("copyBufferToBuffer")) return;
// (src, srcOffset, dst, dstOffset, size) or (src, dst, size?)
let so = 0, dst: GPUBuffer, dOff = 0, size: number;
if (a instanceof GPUBuffer) { dst = a; size = b === undefined ? src.size : b; }
else { so = a; dst = b; dOff = c; size = d === undefined ? src.size - so : d; }
this._w([OP.COPY_B2B, src._id, so >>> 0, dst._id, dOff >>> 0, size >>> 0]);
}
/** @internal */ _texInfo(t: any) { const o = originOf(t.origin); return [t.texture._id, (t.mipLevel ?? 0) >>> 0, o[0], o[1], o[2], aspectCode(t.aspect)]; }
/** @internal */ _bufInfo(b: any) { return [b.buffer._id, (b.offset ?? 0) >>> 0, vu32(b.bytesPerRow), vu32(b.rowsPerImage)]; }
copyBufferToTexture(src: any, dst: any, size: any) {
if (!this._begin("copyBufferToTexture")) return;
this._w([OP.COPY_B2T, ...this._bufInfo(src), ...this._texInfo(dst), ...extentOf(size)]);
}
copyTextureToBuffer(src: any, dst: any, size: any) {
if (!this._begin("copyTextureToBuffer")) return;
this._w([OP.COPY_T2B, ...this._texInfo(src), ...this._bufInfo(dst), ...extentOf(size)]);
}
copyTextureToTexture(src: any, dst: any, size: any) {
if (!this._begin("copyTextureToTexture")) return;
this._w([OP.COPY_T2T, ...this._texInfo(src), ...this._texInfo(dst), ...extentOf(size)]);
}
clearBuffer(b: GPUBuffer, offset = 0, size?: number) {
if (!this._begin("clearBuffer")) return;
this._w([OP.CLEAR_BUFFER, b._id, offset >>> 0, vu32(size)]);
}
resolveQuerySet(q: GPUQuerySet, first: number, count: number, dst: GPUBuffer, dstOffset: number) {
if (!this._begin("resolveQuerySet")) return;
this._w([OP.RESOLVE_QUERY_SET, q._id, first >>> 0, count >>> 0, dst._id, dstOffset >>> 0]);
}
writeTimestamp() { validationError("writeTimestamp is not supported (use timestampWrites)"); }
pushDebugGroup(_l: string) {}
popDebugGroup() {}
insertDebugMarker(_l: string) {}
finish(desc?: any) {
let id = 0;
if (this._state !== "open") validationError(`GPUCommandEncoder.finish: the encoder is ${this._state === "locked" ? "locked by an open pass" : "already finished"}`);
else id = N.finish(this._s.u, this._s.n);
if (this._state !== "ended") giveStream(this._s);
this._state = "ended";
this._refs = [];
return new GPUCommandBuffer(id, desc?.label, false);
}
}
// -------------------------------------------------------------------------------------- resources
type MapRange = { offset: number; size: number; ab: ArrayBuffer };
export class GPUBuffer extends GPUObjectBase {
readonly size: number;
readonly usage: number;
/** @internal */ _state: "unmapped" | "pending" | "mapped" = "unmapped";
/** @internal */ _mode = 0;
/** @internal */ _mapOff = 0;
/** @internal */ _mapEnd = 0;
/** @internal */ _ranges: MapRange[] = [];
/** @internal */ _pending: { token: number; reject: (e: any) => void } | null = null;
/** @internal */ _fresh = false;
/** @internal */ _destroyed = false;
/** @internal */ constructor(id: number, desc: any) {
super(id, desc.label);
this.size = desc.size; this.usage = desc.usage;
if (desc.mappedAtCreation) { this._state = "mapped"; this._mode = GPUMapMode.WRITE; this._mapOff = 0; this._mapEnd = desc.size; this._fresh = true; }
}
get mapState() { return this._state; }
mapAsync(mode: number, offset = 0, size?: number): Promise<undefined> {
if (this._state !== "unmapped") {
validationError("GPUBuffer.mapAsync: the buffer is already mapped or has a pending map");
return Promise.reject(domError("The buffer is already mapped or has a pending map", "OperationError"));
}
const token = N.mapAsync(this._id, mode, offset, size === undefined ? -1 : size);
if (!token) return Promise.reject(domError("mapAsync failed validation", "OperationError"));
this._state = "pending";
return new Promise((resolve, reject) => {
this._pending = { token, reject };
wait(token, (status) => {
if (this._pending?.token !== token) return; // unmapped meanwhile (already rejected)
this._pending = null;
if (status !== 0) { this._state = "unmapped"; reject(domError("mapAsync failed", "OperationError")); return; }
this._state = "mapped"; this._mode = mode; this._mapOff = offset; this._mapEnd = size === undefined ? this.size : offset + size;
this._fresh = false;
resolve(undefined);
});
});
}
getMappedRange(offset = 0, size?: number): ArrayBuffer {
if (this._state !== "mapped") throw domError("The buffer is not mapped", "OperationError");
const sz = size === undefined ? Math.max(0, this._mapEnd - offset) : size;
if (offset % 8 || sz % 4 || offset < this._mapOff || offset + sz > this._mapEnd) throw domError("getMappedRange: range is outside the mapped range or unaligned", "OperationError");
for (const r of this._ranges) if (offset < r.offset + r.size && r.offset < offset + sz) throw domError("getMappedRange: overlapping range", "OperationError");
// A JS-created buffer: native access pins an ArrayBuffer (JSObjectGetTypedArrayBytesPtr),
// and the page's buffer must stay detachable for unmap.
const ab = new ArrayBuffer(sz);
if (!this._fresh && sz) { try { new Uint8Array(ab).set(N.getMappedRange(this._id, offset, sz)); } catch (e) { rethrow(e); } }
this._ranges.push({ offset, size: sz, ab });
return ab;
}
unmap() {
if (this._state === "pending") {
const p = this._pending; this._pending = null;
p?.reject(domError("The buffer was unmapped before mapAsync completed", "AbortError"));
N.unmap(this._id, null);
} else if (this._state === "mapped") {
// Detach the page's buffers like a real unmap does; for write mappings their contents move
// (transfer) into the buffers handed to native.
const write = this._mode === GPUMapMode.WRITE;
const list: any[] = [];
for (const r of this._ranges) {
let moved: ArrayBuffer | null = null;
try { moved = (r.ab as any).transfer ? (r.ab as any).transfer() : r.ab.slice(0); } catch { /* already detached */ }
if (write && moved && moved.byteLength) list.push(r.offset, new Uint8Array(moved));
}
N.unmap(this._id, list.length ? list : null);
}
this._ranges = [];
this._state = "unmapped";
this._fresh = false;
}
destroy() {
if (this._destroyed) return;
if (this._state !== "unmapped") this.unmap();
this._destroyed = true;
N.bufferDestroy(this._id);
}
}
export class GPUTextureView extends GPUObjectBase {}
export class GPUTexture extends GPUObjectBase {
readonly width: number; readonly height: number; readonly depthOrArrayLayers: number;
readonly mipLevelCount: number; readonly sampleCount: number; readonly dimension: string;
readonly format: string; readonly usage: number;
/** @internal */ _view: GPUTextureView | null = null;
/** @internal */ constructor(id: number, desc: any, track = true) {
super(id, desc.label, track);
const [w, h, d] = extentOf(desc.size);
this.width = w; this.height = h; this.depthOrArrayLayers = d;
this.mipLevelCount = desc.mipLevelCount ?? 1; this.sampleCount = desc.sampleCount ?? 1;
this.dimension = desc.dimension ?? "2d"; this.format = desc.format; this.usage = desc.usage;
}
createView(desc?: any) {
const plain = !desc || (desc.format === undefined && desc.dimension === undefined && (desc.aspect ?? "all") === "all" && !desc.baseMipLevel && desc.mipLevelCount === undefined && !desc.baseArrayLayer && desc.arrayLayerCount === undefined && !desc.usage);
if (plain && this._view) return this._view;
const v = new GPUTextureView(N.createView(this._id, plain ? null : toJSON(desc)), desc?.label);
if (plain) this._view = v;
return v;
}
destroy() { N.textureDestroy(this._id); }
}
export class GPUSampler extends GPUObjectBase {}
export class GPUBindGroupLayout extends GPUObjectBase {}
export class GPUBindGroup extends GPUObjectBase {}
export class GPUPipelineLayout extends GPUObjectBase {}
export class GPUShaderModule extends GPUObjectBase {
getCompilationInfo() {
const msgs = JSON.parse(N.shaderInfo(this._id)).map((m: any) => new GPUCompilationMessage(m));
return Promise.resolve(new GPUCompilationInfo(msgs));
}
}
class PipelineBase extends GPUObjectBase {
getBindGroupLayout(index: number) { return new GPUBindGroupLayout(N.getBindGroupLayout(this._id, index >>> 0)); }
}
export class GPURenderPipeline extends PipelineBase {}
export class GPUComputePipeline extends PipelineBase {}
export class GPUQuerySet extends GPUObjectBase {
readonly type: string; readonly count: number;
/** @internal */ constructor(id: number, desc: any) { super(id, desc.label); this.type = desc.type; this.count = desc.count; }
destroy() { N.querySetDestroy(this._id); }
}
export class GPUExternalTexture {}
// -------------------------------------------------------------------------------------- queue
/** Pixels of an image source: [kind, source, width, height] (see crates/webgpu js.rs copyExternal). */
function imageSource(src: any): [number, any, number, number] | null {
if (!src) throw new TypeError("copyExternalImageToTexture: source is null");
if (src instanceof GPUCanvasContext) src = src.canvas;
if ("_imageId" in src) { // HTMLImageElement / ImageBitmap
const w = src.naturalWidth ?? src.width ?? 0, h = src.naturalHeight ?? src.height ?? 0;
return src._imageId ? [1, src._imageId, w, h] : null;
}
if (ArrayBuffer.isView(src.data) && typeof src.width === "number" && typeof src.getContext !== "function") return [2, src.data, src.width, src.height]; // ImageData
if (typeof src._surfaceId === "number") return [1, src._surfaceId, src.width, src.height];
const c = src._context;
if (c instanceof GPUCanvasContext) return [3, c._cid, src.width, src.height];
if (c && typeof c._surfaceId === "number") return [1, c._surfaceId, src.width >>> 0, src.height >>> 0];
if (c && typeof c._readPixelsForExport === "function") { const e = c._readPixelsForExport(); return e ? [2, e.data, e.width, e.height] : null; }
return null;
}
export class GPUQueue {
label = "";
submit(cbs: Iterable<GPUCommandBuffer>) {
const ids: number[] = [];
for (const cb of cbs) ids.push(cb._id);
N.submit(ids, ids.length);
flushReleased();
drainErrors();
}
writeBuffer(b: GPUBuffer, offset: number, data: any, dataOffset = 0, size?: number) {
const bpe = ArrayBuffer.isView(data) ? ((data as any).BYTES_PER_ELEMENT ?? 1) : 1;
try { N.writeBuffer(b._id, offset, data, dataOffset * bpe, size === undefined ? -1 : size * bpe); } catch (e) { rethrow(e); }
}
writeTexture(dst: any, data: any, layout: any, size: any) {
const o = originOf(dst.origin), e = extentOf(size);
try {
N.writeTexture(dst.texture._id, (dst.mipLevel ?? 0) >>> 0, o[0], o[1], o[2], aspectCode(dst.aspect), data, (layout.offset ?? 0), layout.bytesPerRow ?? -1, layout.rowsPerImage ?? -1, e[0], e[1], e[2]);
} catch (x) { rethrow(x); }
}
copyExternalImageToTexture(source: any, dst: any, size: any) {
const s = imageSource(source.source);
const so = Array.isArray(source.origin) ? source.origin : [source.origin?.x ?? 0, source.origin?.y ?? 0];
const o = originOf(dst.origin), e = extentOf(size);
if (!s) return; // blank source: nothing to copy
try {
N.copyExternal(s[0], s[1], s[2] >>> 0, s[3] >>> 0, so[0] >>> 0, so[1] >>> 0, !!source.flipY, dst.texture._id, (dst.mipLevel ?? 0) >>> 0, o[0], o[1], o[2], !!dst.premultipliedAlpha, e[0], e[1]);
} catch (x) { rethrow(x); }
}
onSubmittedWorkDone(): Promise<undefined> {
const token = N.workDone();
return new Promise((resolve) => wait(token, () => resolve(undefined)));
}
}
// -------------------------------------------------------------------------------------- device
class GPUSupportedFeatures extends Set<string> {}
class GPUSupportedLimits { [k: string]: number; constructor(l: Record<string, number>) { Object.assign(this, l); } }
class GPUAdapterInfo {
vendor: string; architecture: string; device: string; description: string; subgroupMinSize = 4; subgroupMaxSize = 128; isFallbackAdapter = false;
constructor(i: any) { this.vendor = i.vendor; this.architecture = i.architecture; this.device = i.device; this.description = i.description; }
}
export class GPUDevice extends EventTarget {
readonly features: GPUSupportedFeatures;
readonly limits: GPUSupportedLimits;
readonly adapterInfo: GPUAdapterInfo;
readonly queue = new GPUQueue();
readonly lost: Promise<GPUDeviceLostInfo>;
label = "";
/** @internal */ _lost!: (i: GPUDeviceLostInfo) => void;
/** @internal */ _onerror: any = null;
/** @internal */ constructor(features: GPUSupportedFeatures, limits: GPUSupportedLimits, info: GPUAdapterInfo) {
super();
this.features = features; this.limits = limits; this.adapterInfo = info;
this.lost = new Promise((r) => (this._lost = r));
devices.add(this);
}
get onuncapturederror() { return this._onerror; }
set onuncapturederror(f: any) {
if (this._onerror) this.removeEventListener("uncapturederror", this._onerror);
this._onerror = typeof f === "function" ? f : null;
if (this._onerror) this.addEventListener("uncapturederror", this._onerror);
}
destroy() {
if (!devices.has(this)) return;
devices.delete(this);
this._lost(new GPUDeviceLostInfo("destroyed", "device.destroy() was called"));
}
createBuffer(desc: any) {
const d = { size: Number(desc.size) || 0, usage: desc.usage >>> 0, mappedAtCreation: !!desc.mappedAtCreation, label: desc.label };
let id: number;
try { id = N.createBuffer(d.size, d.usage, d.mappedAtCreation, desc.label ?? null); } catch (e) { rethrow(e); }
return new GPUBuffer(id, d);
}
createTexture(desc: any) {
let id: number;
try { id = N.createTexture(toJSON(desc)); } catch (e) { throw new TypeError(String((e as any)?.message ?? e)); }
return new GPUTexture(id, desc);
}
createSampler(desc?: any) { return new GPUSampler(this._create("createSampler", desc), desc?.label); }
createBindGroupLayout(desc: any) { return new GPUBindGroupLayout(this._create("createBindGroupLayout", desc), desc.label); }
createPipelineLayout(desc: any) { return new GPUPipelineLayout(this._create("createPipelineLayout", desc), desc.label); }
createBindGroup(desc: any) { return new GPUBindGroup(this._create("createBindGroup", desc), desc.label); }
createShaderModule(desc: any) { return new GPUShaderModule(N.createShaderModule(String(desc.code ?? ""), desc.label ?? null), desc.label); }
createRenderPipeline(desc: any) { return new GPURenderPipeline(this._create("createRenderPipeline", desc), desc.label); }
createComputePipeline(desc: any) { return new GPUComputePipeline(this._create("createComputePipeline", desc), desc.label); }
createRenderPipelineAsync(desc: any) { return this._async("createRenderPipelineAsync", desc, GPURenderPipeline); }
createComputePipelineAsync(desc: any) { return this._async("createComputePipelineAsync", desc, GPUComputePipeline); }
createCommandEncoder(desc?: any) { return new GPUCommandEncoder(desc); }
createRenderBundleEncoder(desc: any) { return new GPURenderBundleEncoder(desc); }
createQuerySet(desc: any) {
let id: number;
try { id = N.createQuerySet(desc.type, desc.count >>> 0); } catch (e) { rethrow(e); }
return new GPUQuerySet(id, desc);
}
importExternalTexture(_d: any): any { throw domError("importExternalTexture is not supported", "NotSupportedError"); }
pushErrorScope(filter: string) { try { N.pushErrorScope(filter); } catch (e) { rethrow(e); } }
popErrorScope(): Promise<GPUError | null> {
let r: any;
try { r = N.popErrorScope(); } catch (e) { return Promise.reject(domError(String((e as any).message).replace(/^OperationError: /, ""), "OperationError")); }
return Promise.resolve(r ? new ERROR_KINDS[r[0]](r[1]) : null);
}
/** @internal */ _create(fn: string, desc: any): number {
try { return N[fn](toJSON(desc)); } catch (e) { throw new TypeError(String((e as any)?.message ?? e)); }
}
/** @internal */ _async(fn: string, desc: any, C: any) {
let r: any;
try { r = N[fn](toJSON(desc)); } catch (e) { return Promise.reject(new TypeError(String((e as any)?.message ?? e))); }
if (r[1] !== null) return Promise.reject(new GPUPipelineError(r[1], { reason: "validation" }));
return Promise.resolve(new C(r[0], desc.label));
}
}
export class GPUAdapter {
readonly features: GPUSupportedFeatures;
readonly limits: GPUSupportedLimits;
readonly info: GPUAdapterInfo;
readonly isFallbackAdapter = false;
/** @internal */ constructor(info: any) {
this.features = new GPUSupportedFeatures(info.features);
this.limits = new GPUSupportedLimits(info.limits);
this.info = new GPUAdapterInfo(info.info);
}
requestAdapterInfo() { return Promise.resolve(this.info); }
requestDevice(desc?: any): Promise<GPUDevice> {
for (const f of desc?.requiredFeatures ?? []) {
if (!this.features.has(f)) return Promise.reject(new TypeError(`requestDevice: feature '${f}' is not supported`));
}
const req = desc?.requiredLimits ?? {};
for (const k of Object.keys(req)) {
if (req[k] === undefined) continue;
if (!(k in this.limits)) return Promise.reject(domError(`requestDevice: unknown limit '${k}'`, "OperationError"));
const better = /^min/.test(k) ? req[k] >= this.limits[k] : req[k] <= this.limits[k];
if (!better) return Promise.reject(domError(`requestDevice: limit ${k}=${req[k]} exceeds the adapter's ${this.limits[k]}`, "OperationError"));
}
return Promise.resolve(new GPUDevice(this.features, this.limits, this.info));
}
}
export class GPU {
readonly wgslLanguageFeatures = new Set<string>();
requestAdapter(_opts?: any): Promise<GPUAdapter | null> {
const info = N.info();
return Promise.resolve(info ? new GPUAdapter(JSON.parse(info)) : null);
}
getPreferredCanvasFormat() { return N.preferredFormat(); }
}
// -------------------------------------------------------------------------------------- canvas
const canvasRegistry = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => { try { N.canvasRelease(id); } catch { /* */ } }) : null;
export class GPUCanvasContext {
readonly canvas: any;
/** @internal */ _cid: number;
/** @internal */ _config: any = null;
/** @internal */ _tex: GPUTexture | null = null;
/** @internal */ constructor(canvas: any, cid: number, track = true) {
this.canvas = canvas; this._cid = cid;
if (track && canvasRegistry) canvasRegistry.register(this, cid);
}
configure(config: any) {
if (!config?.device) throw new TypeError("configure: device is required");
const usage = config.usage ?? GPUTextureUsage.RENDER_ATTACHMENT;
try { N.canvasConfigure(this._cid, String(config.format), usage, config.alphaMode === "premultiplied", JSON.stringify(config.viewFormats ?? [])); } catch (e) { rethrow(e); }
this._config = { ...config, usage, alphaMode: config.alphaMode ?? "opaque", viewFormats: config.viewFormats ?? [] };
this._tex = null;
}
unconfigure() { N.canvasUnconfigure(this._cid); this._config = null; this._tex = null; }
getConfiguration() { return this._config ? { ...this._config } : null; }
getCurrentTexture(): GPUTexture {
if (!this._config) throw domError("getCurrentTexture: the context is not configured", "InvalidStateError");
let id: number;
try { id = N.canvasTexture(this._cid); } catch (e) { rethrow(e); }
if (this._tex && this._tex._id === id) return this._tex;
const c = this._config;
this._tex = new GPUTexture(id, { size: [this.canvas.width >>> 0, this.canvas.height >>> 0, 1], format: c.format, usage: c.usage, label: "canvas" }, false);
return this._tex;
}
/** @internal canvas.toDataURL / drawImage / texImage2D of this canvas */
_readPixelsForExport() {
const r = N.canvasRead(this._cid);
return r ? { width: r[0], height: r[1], data: r[2] } : null;
}
}
/** The window canvas: renders into the host's frame texture (webgpu `set_window_target`). */
export class WindowGpuCanvas {
style: Record<string, string> = {};
/** @internal */ _cid = 0;
/** @internal */ _w = -1;
/** @internal */ _h = -1;
/** @internal */ _ctx: GPUCanvasContext | null = null;
/** @internal */ _context: any = null;
/** @internal */ _id() {
if (!this._cid) this._cid = N.windowCanvas();
return this._cid;
}
/** @internal */ _init() {
if (this._w >= 0) return;
const i = N.windowInfo();
const dpr = g.devicePixelRatio || 1;
this._w = i[0] || Math.round((g.innerWidth || 300) * dpr);
this._h = i[1] || Math.round((g.innerHeight || 150) * dpr);
N.canvasResize(this._id(), this._w, this._h);
}
get width() { this._init(); return this._w; }
set width(v: number) { this._init(); this._w = Math.max(0, v >>> 0); N.canvasResize(this._id(), this._w, this._h); }
get height() { this._init(); return this._h; }
set height(v: number) { this._init(); this._h = Math.max(0, v >>> 0); N.canvasResize(this._id(), this._w, this._h); }
get clientWidth() { const i = N.windowInfo(); return i[2] || g.innerWidth || this.width / (g.devicePixelRatio || 1); }
get clientHeight() { const i = N.windowInfo(); return i[3] || g.innerHeight || this.height / (g.devicePixelRatio || 1); }
get offsetWidth() { return this.clientWidth; }
get offsetHeight() { return this.clientHeight; }
get isConnected() { return true; }
getBoundingClientRect() {
const w = this.clientWidth, h = this.clientHeight;
return { x: 0, y: 0, left: 0, top: 0, width: w, height: h, right: w, bottom: h, toJSON() { return this; } };
}
getContext(type: string) {
if (type !== "webgpu") return null;
if (!this._ctx) { this._init(); this._ctx = new GPUCanvasContext(this, this._id(), false); this._context = this._ctx; }
return this._ctx;
}
addEventListener() {}
removeEventListener() {}
dispatchEvent() { return true; }
setAttribute() {}
getAttribute() { return null; }
removeAttribute() {}
hasAttribute() { return false; }
focus() {}
setPointerCapture() {}
releasePointerCapture() {}
toDataURL(type?: string, quality?: number) { return surfaces.toDataURL ? surfaces.toDataURL(this as any, type, quality) : "data:,"; }
}
// -------------------------------------------------------------------------------------- installation
export function installWebGPU() {
N = g.__native?.gpu;
if (!N) return;
N.reportError ??= (_k: number, m: string) => console.warn("[webgpu]", m);
const gpu = new GPU();
Object.assign(g, {
GPU, GPUAdapter, GPUDevice, GPUQueue, GPUBuffer, GPUTexture, GPUTextureView, GPUSampler, GPUBindGroupLayout, GPUBindGroup,
GPUPipelineLayout, GPUShaderModule, GPURenderPipeline, GPUComputePipeline, GPUQuerySet, GPUCommandEncoder, GPUCommandBuffer,
GPURenderPassEncoder, GPUComputePassEncoder, GPURenderBundleEncoder, GPURenderBundle, GPUCanvasContext, GPUExternalTexture,
GPUError, GPUValidationError, GPUOutOfMemoryError, GPUInternalError, GPUPipelineError, GPUUncapturedErrorEvent, GPUDeviceLostInfo,
GPUCompilationInfo, GPUCompilationMessage, GPUSupportedFeatures, GPUSupportedLimits, GPUAdapterInfo,
GPUBufferUsage, GPUTextureUsage, GPUMapMode, GPUShaderStage, GPUColorWrite,
});
if (!g.navigator) g.navigator = {};
try { Object.defineProperty(g.navigator, "gpu", { value: gpu, configurable: true, enumerable: true }); } catch { g.navigator.gpu = gpu; }
surfaces.contextFactories.set("webgpu", (canvas: CanvasHost) => {
if (canvas._context instanceof GPUCanvasContext) return canvas._context;
const ctx = new GPUCanvasContext(canvas, N.canvasCreate(canvas.width >>> 0, canvas.height >>> 0));
canvas._onResize = (w, h) => N.canvasResize(ctx._cid, w >>> 0, h >>> 0);
return ctx;
});
// toDataURL of a WebGPU canvas goes through `_readPixelsForExport` (runtime/js/canvas2d.ts)
const windowCanvas = new WindowGpuCanvas();
g.__threertGpuCanvas = windowCanvas;
g.__pocketGpuCanvas = windowCanvas;
}