# gizlang/webgpu

gizlang/render's packets on this machine's GPU, through WebGPU's C interface (gizlang/sys/webgpu over wgpu-native, which draws with Vulkan, Metal, Direct3D 12 or OpenGL as the system has). It is the native twin of the browser's SurfaceDevice (app/components/src/surface.js): the same packet, the same WebGPU descriptors and pass methods, so one program draws in a page and in a window alike. The device draws straight into the window's surface (a gizlang/window surface: X11's xcb window, a Wayland surface or a Win32 window) and shows each frame at the display's refresh (FIFO): no frame is read back, and the wait for the display paces the program.

A descriptor is the JSON of WebGPU's JavaScript interface; Struct lays it out as webgpu.h's C struct, with natural alignment on a 64-bit machine. An enum's JavaScript name without its dashes is its C name in lower case ("one-minus-src-alpha" is OneMinusSrcAlpha), so one table per enum serves both.

```gizlang
import * as Webgpu from "gizlang/webgpu";
```

## Types

### `Device`

```gizlang
class Device { n: Native; instance: u64 = 0u; adapter: u64 = 0u; device: u64 = 0u; queue: u64 = 0u; budget: i64; bytes: i64 = 0; resources: Map<string, Entry> = new Map(); features: Vec<string> = []; maxBufferSize: i64 = 0; maxTextureDimension2D: i64 = 0; maxStorageBufferBindingSize: i64 = 0; surface: u64 = 0u; target: u64 = 0u; width: i64 = 0; height: i64 = 0; current: u64 = 0u; views: Vec<u64> = []; reply: u64; constructor(n: Native, budget: i64) { this.n = n; this.budget = budget; this.reply = replyBlock(n); } entry(handle: Handle): Entry throws string { const found = this.resources.get(key(handle)); if (found === undefined) { throw `Stale GPU resource ${key(handle) }`; } return found!; } object(value: Json): u64 throws string { const handle = handleOf(value.field("$gpu")); if (isSurface(handle)) { return this.current; } return this.entry(handle).object; } view(value: Json, s: Scratch): u64 throws string { const named = value.field("$view"); const handle = handleOf(named.kind === "null" ? value.field("$gpu"): named); const texture = isSurface(handle) ? this.current: this.entry(handle).object; if (texture === 0u) { throw "The surface texture is only valid inside a frame"; } const descriptor = value.field("descriptor"); let at: u64 = 0u; if (descriptor.kind === "object" && descriptor.keys().length> 0) { at = s.struct(new Struct().long(0u).long(s.text(descriptor.field("label"))) .int(enumOr(descriptor, "format", FORMATS, 0)).int(enumOr(descriptor, "dimension", VIEW_DIMENSIONS, 0)) .int(integerOr(descriptor.field("baseMipLevel"), 0)).int(integerOr(descriptor.field("mipLevelCount"), UNDEFINED_U32)) .int(integerOr(descriptor.field("baseArrayLayer"), 0)).int(integerOr(descriptor.field("arrayLayerCount"), UNDEFINED_U32)) .int(enumOr(descriptor, "aspect", ASPECTS, 0))); } const made = W.wgpuTextureCreateView(texture, at); this.views.push(made); return made; } layoutOf(value: Json): u64 throws string { const layout = value.field("$layout"); const pipeline = this.entry(handleOf(layout.field("pipeline"))); const index = u64(layout.field("index").integer()); return pipeline.kind === "renderPipeline" ? W.wgpuRenderPipelineGetBindGroupLayout(pipeline.object, index): W.wgpuComputePipelineGetBindGroupLayout(pipeline.object, index); } checked(what: string, action: () => void throws string): void throws string { W.wgpuDevicePushErrorScope(this.device, ERROR_FILTER_VALIDATION); let failure = ""; try { action(); } catch (why) { failure = why; } this.n.write(this.reply, new Array<u8>(24).fill(0u)); W.wgpuDevicePopErrorScope(this.device, errorAnswered, this.reply); const answer = answerAt(this.n, this.reply); if (failure !== "") { throw failure; } if (answer.status> 0) { throw `${what }:  ${ answer.message }`; } } create(resource: Json): void throws string { const handle = handleOf(resource.field("handle")); const kind = resource.field("kind").text(); if (handle.slot <1 || handle.generation <1) { throw "Invalid GPU slot"; } if (this.resources.has(key(handle))) { throw "Duplicate GPU resource"; } let dependencies: Vec<Handle> = []; for (const dependency of resource.field("dependencies").list()) { const h = handleOf(dependency); this.entry(h); dependencies.push(h); } const size = resource.field("bytes").integer(); if (size <0 || size> this.budget - this.bytes) { throw "GPU memory budget exceeded"; } const d = resource.field("descriptor"); let made: u64 = 0u; let s = new Scratch(this.n); try { this.checked(`GPU ${kind }`, (): void throws string => { made = this.make(kind, d, s); }); } finally { s.free(); } if (made === 0u) { throw `The GPU did not make the ${kind }`; } this.resources.set(key(handle), { object: made, kind, size, descriptor: d, dependencies }); this.bytes + = size; } make(kind: string, d: Json, s: Scratch): u64 throws string { const label = s.text(d.field("label")); if (kind === "buffer") { return W.wgpuDeviceCreateBuffer(this.device, s.struct(new Struct().long(0u).long(label).int(d.field("usage").integer()) .long(u64(d.field("size").integer())).int(d.field("mappedAtCreation").boolean() ? 1: 0))); } if (kind === "texture") { const extent = d.field("size"); return W.wgpuDeviceCreateTexture(this.device, s.struct(new Struct().long(0u).long(label).int(d.field("usage").integer()) .int(enumOr(d, "dimension", DIMENSIONS, 1)).inline(this.extent(extent)) .int(enumValue(FORMATS, d.field("format").text(), "format")) .int(integerOr(d.field("mipLevelCount"), 1)).int(integerOr(d.field("sampleCount"), 1)).long(0u).long(0u))); } if (kind === "sampler") { return W.wgpuDeviceCreateSampler(this.device, s.struct(new Struct().long(0u).long(label) .int(enumOr(d, "addressModeU", ADDRESS_MODES, 2)).int(enumOr(d, "addressModeV", ADDRESS_MODES, 2)) .int(enumOr(d, "addressModeW", ADDRESS_MODES, 2)).int(enumOr(d, "magFilter", FILTERS, 0)) .int(enumOr(d, "minFilter", FILTERS, 0)).int(enumOr(d, "mipmapFilter", FILTERS, 0)) .float(number(d.field("lodMinClamp"), 0.0)).float(number(d.field("lodMaxClamp"), 32.0)) .int(enumOr(d, "compare", COMPARES, 0)).half(integerOr(d.field("maxAnisotropy"), 1)))); } if (kind === "shader") { const wgsl = s.struct(new Struct().long(0u).int(STYPE_WGSL).long(s.text(d.field("code")))); return W.wgpuDeviceCreateShaderModule(this.device, s.struct(new Struct().long(wgsl).long(label).long(0u).long(0u))); } if (kind === "bindGroupLayout") { let entries: Vec<Struct> = []; for (const e of d.field("entries").list()) { entries.push(this.layoutEntry(e)); } return W.wgpuDeviceCreateBindGroupLayout(this.device, s.struct(new Struct().long(0u).long(label) .long(u64(entries.length)).long(s.array(entries)))); } if (kind === "pipelineLayout") { let layouts = b""; for (const l of d.field("bindGroupLayouts").list()) { writeU64LE(layouts, this.object(l)); } return W.wgpuDeviceCreatePipelineLayout(this.device, s.struct(new Struct().long(0u).long(label) .long(u64(layouts.length / 8)).long(s.put(layouts)))); } if (kind === "bindGroup") { const layout = d.field("layout"); const at = layout.field("$layout").kind !== "null" ? this.layoutOf(layout): this.object(layout); let entries: Vec<Struct> = []; for (const e of d.field("entries").list()) { entries.push(this.groupEntry(e, s)); } return W.wgpuDeviceCreateBindGroup(this.device, s.struct(new Struct().long(0u).long(label).long(at) .long(u64(entries.length)).long(s.array(entries)))); } if (kind === "renderPipeline") { return W.wgpuDeviceCreateRenderPipeline(this.device, s.struct(this.renderPipeline(d, label, s))); } if (kind === "computePipeline") { return W.wgpuDeviceCreateComputePipeline(this.device, s.struct(new Struct().long(0u).long(label) .long(this.pipelineLayout(d)).inline(this.stage(d.field("compute"), s)))); } if (kind === "querySet") { return W.wgpuDeviceCreateQuerySet(this.device, s.struct(new Struct().long(0u).long(label) .int(enumValue(QUERY_TYPES, d.field("type").text(), "query type")).int(d.field("count").integer()))); } throw `Unknown GPU resource kind ${kind }`; } pipelineLayout(d: Json): u64 throws string { const layout = d.field("layout"); return layout.kind === "object" ? this.object(layout): 0u; } extent(value: Json): Struct { if (value.kind === "array") { const items = value.list(); return new Struct().int(items[0].integer()).int(items.length> 1 ? items[1].integer(): 1).int(items.length> 2 ? items[2].integer(): 1); } return new Struct().int(value.field("width").integer()).int(integerOr(value.field("height"), 1)) .int(integerOr(value.field("depthOrArrayLayers"), 1)); } origin(value: Json): Struct { if (value.kind === "array") { const items = value.list(); return new Struct().int(items.length> 0 ? items[0].integer(): 0).int(items.length> 1 ? items[1].integer(): 0) .int(items.length> 2 ? items[2].integer(): 0); } return new Struct().int(integerOr(value.field("x"), 0)).int(integerOr(value.field("y"), 0)).int(integerOr(value.field("z"), 0)); } color(value: Json): Struct { if (value.kind === "array") { const items = value.list(); let out = new Struct(); for (const i of range(0, 4)) { out.double(i <items.length ? number(items[i], 0.0): 0.0); } return out; } return new Struct().double(number(value.field("r"), 0.0)).double(number(value.field("g"), 0.0)) .double(number(value.field("b"), 0.0)).double(number(value.field("a"), 0.0)); } layoutEntry(e: Json): Struct throws string { const buffer = e.field("buffer"); const sampler = e.field("sampler"); const texture = e.field("texture"); const storage = e.field("storageTexture"); let out = new Struct().long(0u).int(e.field("binding").integer()).int(e.field("visibility").integer()); out.inline(buffer.kind === "null" ? new Struct().long(0u).int(0).int(0).long(0u): new Struct().long(0u).int(enumOr(buffer, "type", BUFFER_BINDINGS, 1)).int(buffer.field("hasDynamicOffset").boolean() ? 1: 0) .long(u64(integerOr(buffer.field("minBindingSize"), 0)))); out.inline(new Struct().long(0u).int(sampler.kind === "null" ? 0: enumOr(sampler, "type", SAMPLER_BINDINGS, 1))); out.inline(texture.kind === "null" ? new Struct().long(0u).int(0).int(0).int(0): new Struct().long(0u).int(enumOr(texture, "sampleType", SAMPLE_TYPES, 1)).int(enumOr(texture, "viewDimension", VIEW_DIMENSIONS, 2)) .int(texture.field("multisampled").boolean() ? 1: 0)); out.inline(storage.kind === "null" ? new Struct().long(0u).int(0).int(0).int(0): new Struct().long(0u).int(enumOr(storage, "access", STORAGE_ACCESSES, 1)).int(enumValue(FORMATS, storage.field("format").text(), "format")) .int(enumOr(storage, "viewDimension", VIEW_DIMENSIONS, 2))); return out; } groupEntry(e: Json, s: Scratch): Struct throws string { const resource = e.field("resource"); let buffer: u64 = 0u; let offset: u64 = 0u; let size = WHOLE_SIZE; let sampler: u64 = 0u; let view: u64 = 0u; if (resource.field("buffer").kind !== "null") { buffer = this.object(resource.field("buffer")); offset = u64(integerOr(resource.field("offset"), 0)); if (resource.field("size").kind !== "null") { size = u64(resource.field("size").integer()); } } else if (resource.field("$view").kind !== "null") { view = this.view(resource, s); } else { const handle = handleOf(resource.field("$gpu")); const found = isSurface(handle) ? undefined: this.resources.get(key(handle)); if (found !== undefined && found!.kind === "sampler") { sampler = found!.object; } else if (found !== undefined && found!.kind === "buffer") { buffer = found!.object; } else { view = this.view(resource, s); } } return new Struct().long(0u).int(e.field("binding").integer()).long(buffer).long(offset).long(size).long(sampler).long(view); } constants(stage: Json, s: Scratch): Vec<u64> { const c = stage.field("constants"); let entries: Vec<Struct> = []; const keys = c.keys(); const values = c.values(); for (const i of range(0, keys.length)) { entries.push(new Struct().long(0u).long(s.put(utf8(keys[i]) + b"\u0000")).double(number(values[i], 0.0))); } return [u64(entries.length), s.array(entries)]; } stage(stage: Json, s: Scratch): Struct throws string { const c = this.constants(stage, s); return new Struct().long(0u).long(this.object(stage.field("module"))).long(s.text(stage.field("entryPoint"))).long(c[0]).long(c[1]); } renderPipeline(d: Json, label: u64, s: Scratch): Struct throws string { const vertex = d.field("vertex"); let buffers: Vec<Struct> = []; for (const b of vertex.field("buffers").list()) { let attributes: Vec<Struct> = []; for (const a of b.field("attributes").list()) { attributes.push(new Struct().int(enumValue(VERTEX_FORMATS, a.field("format").text(), "vertex format")) .long(u64(a.field("offset").integer())).int(a.field("shaderLocation").integer())); } buffers.push(new Struct().long(u64(b.field("arrayStride").integer())).int(enumOr(b, "stepMode", STEP_MODES, 0)) .long(u64(attributes.length)).long(s.array(attributes))); } const vc = this.constants(vertex, s); const vertexState = new Struct().long(0u).long(this.object(vertex.field("module"))).long(s.text(vertex.field("entryPoint"))) .long(vc[0]).long(vc[1]).long(u64(buffers.length)).long(s.array(buffers)); const p = d.field("primitive"); const primitive = new Struct().long(0u).int(enumOr(p, "topology", TOPOLOGIES, 3)).int(enumOr(p, "stripIndexFormat", INDEX_FORMATS, 0)) .int(enumOr(p, "frontFace", FRONT_FACES, 0)).int(enumOr(p, "cullMode", CULL_MODES, 0)); let depth: u64 = 0u; const ds = d.field("depthStencil"); if (ds.kind === "object") { const face = (f: Json): Struct throws string => new Struct().int(enumOr(f, "compare", COMPARES, 8)) .int(enumOr(f, "failOp", STENCIL_OPERATIONS, 0)).int(enumOr(f, "depthFailOp", STENCIL_OPERATIONS, 0)) .int(enumOr(f, "passOp", STENCIL_OPERATIONS, 0)); depth = s.struct(new Struct().long(0u).int(enumValue(FORMATS, ds.field("format").text(), "format")) .int(ds.field("depthWriteEnabled").boolean() ? 1: 0).int(enumOr(ds, "depthCompare", COMPARES, 0)) .inline(face(ds.field("stencilFront"))).inline(face(ds.field("stencilBack"))) .int(integerOr(ds.field("stencilReadMask"), UNDEFINED_U32)).int(integerOr(ds.field("stencilWriteMask"), UNDEFINED_U32)) .int(integerOr(ds.field("depthBias"), 0)).float(number(ds.field("depthBiasSlopeScale"), 0.0)) .float(number(ds.field("depthBiasClamp"), 0.0))); } const m = d.field("multisample"); const multisample = new Struct().long(0u).int(integerOr(m.field("count"), 1)).int(integerOr(m.field("mask"), UNDEFINED_U32)) .int(m.field("alphaToCoverageEnabled").boolean() ? 1: 0); let fragment: u64 = 0u; const f = d.field("fragment"); if (f.kind === "object") { let targets: Vec<Struct> = []; for (const t of f.field("targets").list()) { const blend = t.field("blend"); let blendAt: u64 = 0u; if (blend.kind === "object") { const component = (c: Json): Struct throws string => new Struct().int(enumOr(c, "operation", BLEND_OPERATIONS, 0)) .int(enumOr(c, "srcFactor", BLEND_FACTORS, 1)).int(enumOr(c, "dstFactor", BLEND_FACTORS, 0)); blendAt = s.struct(new Struct().inline(component(blend.field("color"))).inline(component(blend.field("alpha")))); } targets.push(new Struct().long(0u).int(this.format(t.field("format").text())).long(blendAt) .int(integerOr(t.field("writeMask"), 15))); } const fc = this.constants(f, s); fragment = s.struct(new Struct().long(0u).long(this.object(f.field("module"))).long(s.text(f.field("entryPoint"))) .long(fc[0]).long(fc[1]).long(u64(targets.length)).long(s.array(targets))); } return new Struct().long(0u).long(label).long(this.pipelineLayout(d)).inline(vertexState).inline(primitive).long(depth) .inline(multisample).long(fragment); } format(name: string): i64 throws string { return enumValue(FORMATS, name === "$surface-format" ? SURFACE_FORMAT: name, "format"); } configure(width: i64, height: i64): void throws string { if (width <1 || height <1 || width> this.maxTextureDimension2D || height> this.maxTextureDimension2D) { throw "Invalid surface size"; } if (width === this.width && height === this.height) { return; } let s = new Scratch(this.n); if (this.surface === 0u) { try { if (this.target !== 0u) { W.wgpuTextureDestroy(this.target); W.wgpuTextureRelease(this.target); this.target = 0u; } this.checked("GPU offscreen texture", (): void throws string => { this.target = W.wgpuDeviceCreateTexture(this.device, s.struct(new Struct().long(0u).long(0u) .int(USAGE_RENDER_ATTACHMENT | USAGE_COPY_SRC).int(1).inline(new Struct().int(width).int(height).int(1)) .int(this.format(SURFACE_FORMAT)).int(1).int(1).long(0u).long(0u))); }); } finally { s.free(); } if (this.target === 0u) { throw "The GPU did not make the offscreen texture"; } this.width = width; this.height = height; return; } try { this.checked("GPU surface", (): void throws string => { W.wgpuSurfaceConfigure(this.surface, s.struct(new Struct().long(0u).long(this.device).int(this.format(SURFACE_FORMAT)) .int(USAGE_RENDER_ATTACHMENT).long(0u).long(0u).int(0).int(width).int(height).int(PRESENT_FIFO))); }); } finally { s.free(); } this.width = width; this.height = height; } acquire(): u64 throws string { if (this.current !== 0u) { return this.current; } if (this.surface === 0u) { this.current = this.target; return this.target; } const at = this.n.allocate(16); this.n.write(at, new Array<u8>(16).fill(0u)); W.wgpuSurfaceGetCurrentTexture(this.surface, at); const got = this.n.read(at, 16); this.n.free(at); const texture = got.readU64LE(0); const status = i64(got.readU32LE(12)); if (status === TEXTURE_SUCCESS && got.readU32LE(8) === 0u) { this.current = texture; return texture; } if (texture !== 0u) { W.wgpuTextureRelease(texture); } if (status === TEXTURE_SUCCESS || status === TEXTURE_OUTDATED || status === TEXTURE_LOST) { const width = this.width; const height = this.height; this.width = 0; this.configure(width, height); throw SKIPPED; } if (status === TEXTURE_TIMEOUT) { throw SKIPPED; } throw `The window's GPU surface failed (${status })`; } submit(packet: bytes, width: i64, height: i64): bool throws string { if (packet.length <12 || string(packet.slice(0, 8)) !== "GIZGPU01") { throw "Unknown render packet"; } const length = i64(packet.readU32LE(8)); if (length> 16777216 || length> packet.length - 12) { throw "Invalid render packet length"; } const p = parseUnique(string(packet.slice(12, 12 + length)))!; if (p.field("version").integer() !== 1) { throw "Unknown render packet version"; } this.configure(width, height); for (const resource of p.field("resources").list()) { this.create(resource); } let releasing: Vec<Handle> = []; for (const r of p.field("releases").list()) { const h = handleOf(r); this.entry(h); releasing.push(h); } for (const [name, other] of this.resources) { if (!releasing.some(h => key(h) === name) && other.dependencies.some(d => releasing.some(h => key(h) === key(d)))) { throw "GPU resource still has live dependents"; } } const tail = packet.length - 12 - length; let s = new Scratch(this.n); const payload = s.put(packet.slice(12 + length, packet.length)); let shown = false; try { this.checked("GPU frame", (): void throws string => { this.run(p, payload, tail, s); }); if (this.current !== 0u) { if (this.surface !== 0u) { W.wgpuSurfacePresent(this.surface); } shown = true; } } catch (why) { if (why !== SKIPPED) { throw why; } } finally { s.free(); for (const v of this.views) { W.wgpuTextureViewRelease(v); } this.views = []; if (this.current !== 0u && this.surface !== 0u) { W.wgpuTextureRelease(this.current); } this.current = 0u; } for (const h of releasing) { const e = this.entry(h); this.resources.delete(key(h)); this.bytes - = e.size; release(e); } return shown; } run(p: Json, payload: u64, tail: i64, s: Scratch): void throws string { for (const u of p.field("uploads").list()) { const e = this.entry(handleOf(u.field("handle"))); const offset = u.field("offset").integer(); const size = u.field("size").integer(); const destination = u.field("destination").integer(); if (e.kind !== "buffer" || offset <0 || size <0 || offset + size> tail || destination <0 || size> e.size - destination || size % 4 !== 0 || destination % 4 !== 0) { throw "Invalid buffer upload"; } W.wgpuQueueWriteBuffer(this.queue, e.object, u64(destination), payload + u64(offset), u64(size)); } for (const image of p.field("images").list()) { const e = this.entry(handleOf(image.field("handle"))); const format = textureFormat(image.field("format").text()); if (e.kind !== "texture" || e.descriptor.field("format").text() !== image.field("format").text() || !format.upload) { throw "Texture upload format differs"; } const columns = (image.field("width").integer() + format.width - 1) / format.width; const rows = (image.field("height").integer() + format.height - 1) / format.height; const depth = image.field("depth").integer(); const size = columns * rows * depth * format.bytes; const offset = image.field("offset").integer(); if (image.field("size").integer() !== size || offset <0 || offset + size> tail) { throw "Invalid texture block upload"; } const destination = s.struct(new Struct().long(0u).long(e.object).int(image.field("mip").integer()) .inline(new Struct().int(image.field("x").integer()).int(image.field("y").integer()).int(image.field("z").integer())).int(0)); const layout = s.struct(new Struct().long(0u).long(0u).int(columns * format.bytes).int(rows)); const extent = s.struct(new Struct().int(columns * format.width).int(rows * format.height).int(depth)); W.wgpuQueueWriteTexture(this.queue, destination, payload + u64(offset), u64(size), layout, extent); } if (namesSurface(p.field("passes"))) { this.acquire(); } const encoder = W.wgpuDeviceCreateCommandEncoder(this.device, 0u); for (const pass of p.field("passes").list()) { this.pass(encoder, pass, s); } const commands = W.wgpuCommandEncoderFinish(encoder, 0u); let list = b""; writeU64LE(list, commands); W.wgpuQueueSubmit(this.queue, 1u, s.put(list)); W.wgpuCommandBufferRelease(commands); W.wgpuCommandEncoderRelease(encoder); } pass(encoder: u64, pass: Json, s: Scratch): void throws string { const kind = pass.field("kind").text(); const d = pass.field("descriptor"); if (kind === "render") { let colors: Vec<Struct> = []; for (const c of d.field("colorAttachments").list()) { const resolve = c.field("resolveTarget"); colors.push(new Struct().long(0u).long(this.view(c.field("view"), s)).int(integerOr(c.field("depthSlice"), UNDEFINED_U32)) .long(resolve.kind === "null" ? 0u: this.view(resolve, s)) .int(enumValue(LOAD_OPS, c.field("loadOp").text(), "load op")).int(enumValue(STORE_OPS, c.field("storeOp").text(), "store op")) .inline(this.color(c.field("clearValue")))); } let depth: u64 = 0u; const ds = d.field("depthStencilAttachment"); if (ds.kind === "object") { depth = s.struct(new Struct().long(this.view(ds.field("view"), s)).int(enumOr(ds, "depthLoadOp", LOAD_OPS, 0)) .int(enumOr(ds, "depthStoreOp", STORE_OPS, 0)).float(number(ds.field("depthClearValue"), 0.0)) .int(ds.field("depthReadOnly").boolean() ? 1: 0).int(enumOr(ds, "stencilLoadOp", LOAD_OPS, 0)) .int(enumOr(ds, "stencilStoreOp", STORE_OPS, 0)).int(integerOr(ds.field("stencilClearValue"), 0)) .int(ds.field("stencilReadOnly").boolean() ? 1: 0)); } const occlusion = d.field("occlusionQuerySet"); const encoderOf = W.wgpuCommandEncoderBeginRenderPass(encoder, s.struct(new Struct().long(0u).long(s.text(d.field("label"))) .long(u64(colors.length)).long(s.array(colors)).long(depth).long(occlusion.kind === "null" ? 0u: this.object(occlusion)) .long(this.timestamps(d.field("timestampWrites"), s)))); for (const c of pass.field("commands").list()) { this.renderCommand(encoderOf, c, s); } W.wgpuRenderPassEncoderEnd(encoderOf); W.wgpuRenderPassEncoderRelease(encoderOf); } else if (kind === "compute") { const encoderOf = W.wgpuCommandEncoderBeginComputePass(encoder, s.struct(new Struct().long(0u).long(s.text(d.field("label"))) .long(this.timestamps(d.field("timestampWrites"), s)))); for (const c of pass.field("commands").list()) { this.computeCommand(encoderOf, c, s); } W.wgpuComputePassEncoderEnd(encoderOf); W.wgpuComputePassEncoderRelease(encoderOf); } else if (kind === "copy") { for (const c of pass.field("commands").list()) { this.copyCommand(encoder, c, s); } } else { throw "Invalid GPU pass kind"; } } timestamps(t: Json, s: Scratch): u64 throws string { if (t.kind !== "object") { return 0u; } return s.struct(new Struct().long(this.object(t.field("querySet"))) .int(integerOr(t.field("beginningOfPassWriteIndex"), UNDEFINED_U32)).int(integerOr(t.field("endOfPassWriteIndex"), UNDEFINED_U32))); } offsets(value: Json, s: Scratch): Vec<u64> { let data = b""; for (const o of value.list()) { writeU32LE(data, u64(o.integer())); } return [u64(data.length / 4), s.put(data)]; } private renderCommand(pass: u64, c: Json, s: Scratch): void throws string { const method = c.field("method").text(); const a = c.field("args").list(); const at = (i: i64): Json => i <a.length ? a[i]: { kind: "null" }; const u = (i: i64, otherwise: i64): u64 => u64(integerOr(at(i), otherwise)); const size = (i: i64): u64 => at(i).kind === "null" ? WHOLE_SIZE: u64(at(i).integer()); if (method === "setPipeline") { W.wgpuRenderPassEncoderSetPipeline(pass, this.object(at(0))); } else if (method === "setBindGroup") { const o = this.offsets(at(2), s); W.wgpuRenderPassEncoderSetBindGroup(pass, u(0, 0), this.object(at(1)), o[0], o[1]); } else if (method === "setVertexBuffer") { W.wgpuRenderPassEncoderSetVertexBuffer(pass, u(0, 0), this.object(at(1)), u64(integerOr(at(2), 0)), size(3)); } else if (method === "setIndexBuffer") { W.wgpuRenderPassEncoderSetIndexBuffer(pass, this.object(at(0)), u64(enumValue(INDEX_FORMATS, at(1).text(), "index format")), u64(integerOr(at(2), 0)), size(3)); } else if (method === "setViewport") { W.wgpuRenderPassEncoderSetViewport(pass, number(at(0), 0.0), number(at(1), 0.0), number(at(2), 0.0), number(at(3), 0.0), number(at(4), 0.0), number(at(5), 1.0)); } else if (method === "setScissorRect") { W.wgpuRenderPassEncoderSetScissorRect(pass, u(0, 0), u(1, 0), u(2, 0), u(3, 0)); } else if (method === "setBlendConstant") { W.wgpuRenderPassEncoderSetBlendConstant(pass, s.struct(this.color(at(0)))); } else if (method === "setStencilReference") { W.wgpuRenderPassEncoderSetStencilReference(pass, u(0, 0)); } else if (method === "draw") { W.wgpuRenderPassEncoderDraw(pass, u(0, 0), u(1, 1), u(2, 0), u(3, 0)); } else if (method === "drawIndexed") { W.wgpuRenderPassEncoderDrawIndexed(pass, u(0, 0), u(1, 1), u(2, 0), integerOr(at(3), 0), u(4, 0)); } else if (method === "drawIndirect") { W.wgpuRenderPassEncoderDrawIndirect(pass, this.object(at(0)), u64(integerOr(at(1), 0))); } else if (method === "drawIndexedIndirect") { W.wgpuRenderPassEncoderDrawIndexedIndirect(pass, this.object(at(0)), u64(integerOr(at(1), 0))); } else { throw `Unsupported pass method ${method }`; } } private computeCommand(pass: u64, c: Json, s: Scratch): void throws string { const method = c.field("method").text(); const a = c.field("args").list(); const at = (i: i64): Json => i <a.length ? a[i]: { kind: "null" }; const u = (i: i64, otherwise: i64): u64 => u64(integerOr(at(i), otherwise)); if (method === "setPipeline") { W.wgpuComputePassEncoderSetPipeline(pass, this.object(at(0))); } else if (method === "setBindGroup") { const o = this.offsets(at(2), s); W.wgpuComputePassEncoderSetBindGroup(pass, u(0, 0), this.object(at(1)), o[0], o[1]); } else if (method === "dispatchWorkgroups") { W.wgpuComputePassEncoderDispatchWorkgroups(pass, u(0, 1), u(1, 1), u(2, 1)); } else if (method === "dispatchWorkgroupsIndirect") { W.wgpuComputePassEncoderDispatchWorkgroupsIndirect(pass, this.object(at(0)), u64(integerOr(at(1), 0))); } else { throw `Unsupported pass method ${method }`; } } copyBuffer(value: Json): Struct throws string { return new Struct().long(0u).inline(new Struct().long(0u).long(u64(integerOr(value.field("offset"), 0))) .int(integerOr(value.field("bytesPerRow"), UNDEFINED_U32)).int(integerOr(value.field("rowsPerImage"), UNDEFINED_U32))) .long(this.object(value.field("buffer"))); } copyTexture(value: Json): Struct throws string { return new Struct().long(0u).long(this.object(value.field("texture"))).int(integerOr(value.field("mipLevel"), 0)) .inline(this.origin(value.field("origin"))).int(enumOr(value, "aspect", ASPECTS, 0)); } private copyCommand(encoder: u64, c: Json, s: Scratch): void throws string { const method = c.field("method").text(); const a = c.field("args").list(); const at = (i: i64): Json => i <a.length ? a[i]: { kind: "null" }; const wide = (i: i64): u64 => u64(integerOr(at(i), 0)); if (method === "copyBufferToBuffer") { W.wgpuCommandEncoderCopyBufferToBuffer(encoder, this.object(at(0)), wide(1), this.object(at(2)), wide(3), wide(4)); } else if (method === "copyBufferToTexture") { W.wgpuCommandEncoderCopyBufferToTexture(encoder, s.struct(this.copyBuffer(at(0))), s.struct(this.copyTexture(at(1))), s.struct(this.extent(at(2)))); } else if (method === "copyTextureToBuffer") { W.wgpuCommandEncoderCopyTextureToBuffer(encoder, s.struct(this.copyTexture(at(0))), s.struct(this.copyBuffer(at(1))), s.struct(this.extent(at(2)))); } else if (method === "copyTextureToTexture") { W.wgpuCommandEncoderCopyTextureToTexture(encoder, s.struct(this.copyTexture(at(0))), s.struct(this.copyTexture(at(1))), s.struct(this.extent(at(2)))); } else if (method === "clearBuffer") { W.wgpuCommandEncoderClearBuffer(encoder, this.object(at(0)), wide(1), at(2).kind === "null" ? WHOLE_SIZE: wide(2)); } else if (method === "resolveQuerySet") { W.wgpuCommandEncoderResolveQuerySet(encoder, this.object(at(0)), u64(integerOr(at(1), 0)), u64(integerOr(at(2), 0)), this.object(at(3)), wide(4)); } else { throw `Unsupported pass method ${method }`; } } picture(): bytes throws string { if (this.surface !== 0u || this.target === 0u) { throw "Only an offscreen device keeps its frame"; } const row = (this.width * 4 + 255) / 256 * 256; const size = row * this.height; let s = new Scratch(this.n); let buffer: u64 = 0u; try { this.checked("GPU readback", (): void throws string => { buffer = W.wgpuDeviceCreateBuffer(this.device, s.struct(new Struct().long(0u).long(0u) .int(BUFFER_MAP_READ | USAGE_COPY_DST).long(u64(size)).int(0))); const encoder = W.wgpuDeviceCreateCommandEncoder(this.device, 0u); W.wgpuCommandEncoderCopyTextureToBuffer(encoder, s.struct(new Struct().long(0u).long(this.target).int(0).inline(new Struct().int(0).int(0).int(0)).int(0)), s.struct(new Struct().long(0u).inline(new Struct().long(0u).long(0u).int(row).int(this.height)).long(buffer)), s.struct(new Struct().int(this.width).int(this.height).int(1))); const commands = W.wgpuCommandEncoderFinish(encoder, 0u); let list = b""; writeU64LE(list, commands); W.wgpuQueueSubmit(this.queue, 1u, s.put(list)); W.wgpuCommandBufferRelease(commands); W.wgpuCommandEncoderRelease(encoder); }); this.n.write(this.reply, new Array<u8>(24).fill(0u)); W.wgpuBufferMapAsync(buffer, MAP_READ, 0u, u64(size), mapAnswered, this.reply); W.wgpuDevicePoll(this.device, 1u, 0u); const answer = answerAt(this.n, this.reply); if (!answer.answered || answer.status !== 0) { throw `The GPU did not map the frame (${answer.status })`; } const raw = this.n.read(W.wgpuBufferGetConstMappedRange(buffer, 0u, u64(size)), size); W.wgpuBufferUnmap(buffer); let out = b""; for (const y of range(0, this.height)) { for (const x of range(0, this.width)) { const from = y * row + x * 4; out.push(raw[from + 2]); out.push(raw[from + 1]); out.push(raw[from]); out.push(raw[from + 3]); } } return out; } finally { s.free(); if (buffer !== 0u) { W.wgpuBufferDestroy(buffer); W.wgpuBufferRelease(buffer); } } } close(): void { for (const [name, e] of this.resources) { release(e); } this.resources = new Map(); this.bytes = 0; if (this.target !== 0u) { W.wgpuTextureDestroy(this.target); W.wgpuTextureRelease(this.target); this.target = 0u; } if (this.surface !== 0u) { if (this.width> 0) { W.wgpuSurfaceUnconfigure(this.surface); } W.wgpuSurfaceRelease(this.surface); this.surface = 0u; } if (this.queue !== 0u) { W.wgpuQueueRelease(this.queue); } if (this.device !== 0u) { W.wgpuDeviceRelease(this.device); } if (this.adapter !== 0u) { W.wgpuAdapterRelease(this.adapter); } if (this.instance !== 0u) { W.wgpuInstanceRelease(this.instance); } if (this.reply !== 0u) { this.n.free(this.reply); this.reply = 0u; } this.queue = 0u; this.device = 0u; this.adapter = 0u; this.instance = 0u; } }
```

The device of the machine's GPU that runs one program's packets.

- `n`: `gizlang_native.Native`
- `instance`: `u64`
- `adapter`: `u64`
- `device`: `u64`
- `queue`: `u64`
- `budget`: `i64`
- `bytes`: `i64`
- `resources`: `_gizlang_sdk_collections.Map<string, gizlang_webgpu.Entry>`
- `features`: `Vec<string>` — The features the device took: each texture format's that the GPU has, and timestamp-query.
- `maxBufferSize`: `i64`
- `maxTextureDimension2D`: `i64`
- `maxStorageBufferBindingSize`: `i64`
- `surface`: `u64` — The window's surface, the size it is configured at (0: not yet), and its texture of the frame being drawn.
- `target`: `u64` — Without a window (offscreen), the texture each frame draws into in place of the surface's, which picture reads.
- `width`: `i64`
- `height`: `i64`
- `current`: `u64`
- `views`: `Vec<u64>` — Views made for one packet, released after it.
- `reply`: `u64` — The block the library's callbacks answer into (answerAt).

## Functions

### `constructor`

```gizlang
constructor(n: Native, budget: i64)
```

A device of no objects yet, through N, with BUDGET bytes of resources; open makes it.

Effects: fail, write, io, alloc.

### `open`

```gizlang
function open(surface: Surface, budget: i64 = 268435456): Device throws string
```

The machine's fastest GPU that can draw into the window's SURFACE, as a device for packets, with a budget of BUDGET
bytes of resources. Throws why there is none: no WebGPU library (wgpu-native) beside the program or on the system, a
surface it cannot draw into, or no adapter.

Effects: fail, read, write, io, alloc.

### `offscreen`

```gizlang
function offscreen(budget: i64 = 268435456): Device throws string
```

The machine's fastest GPU as a device with no window: each frame draws into a texture that picture reads (a frame
an agent or a test looks at).

Effects: fail, read, write, io, alloc.

## Methods

### `Device.entry`

```gizlang
entry(handle: Handle): Entry throws string
```

The resource HANDLE, or why it is not one.

Effects: fail, read, alloc.

### `Device.object`

```gizlang
object(value: Json): u64 throws string
```

The object a {"$gpu": handle} names; the surface texture for the surface handle.

Effects: fail, read, alloc.

### `Device.view`

```gizlang
view(value: Json, s: Scratch): u64 throws string
```

A texture view of VALUE: {"$view": handle, "descriptor"} or a texture's {"$gpu": handle}.

Effects: fail, read, write, io, alloc.

### `Device.layoutOf`

```gizlang
layoutOf(value: Json): u64 throws string
```

The bind group layout {"$layout": {pipeline, index}} names: the pipeline's "auto" layout of that group.

Effects: fail, read, io, alloc.

### `Device.checked`

```gizlang
checked(what: string, action: () => void throws string): void throws string
```

Runs ACTION inside a validation error scope; its error becomes a throw.

Effects: fail, read, write, console, io, alloc.

### `Device.create`

```gizlang
create(resource: Json): void throws string
```

One resource of a packet made on the device.

Effects: fail, read, write, console, io, alloc.

### `Device.make`

```gizlang
make(kind: string, d: Json, s: Scratch): u64 throws string
```

The device object of KIND from its WebGPU descriptor D.

Effects: fail, read, write, io, alloc.

### `Device.pipelineLayout`

```gizlang
pipelineLayout(d: Json): u64 throws string
```

A pipeline's layout: none for "auto".

Effects: fail, read, alloc.

### `Device.extent`

```gizlang
extent(value: Json): Struct
```

A WGPUExtent3D of an array [width, height, depth] or a dictionary.

Effects: fail, read, write, alloc.

### `Device.origin`

```gizlang
origin(value: Json): Struct
```

A WGPUOrigin3D of an array or a dictionary (zero where left out).

Effects: fail, read, write, alloc.

### `Device.color`

```gizlang
color(value: Json): Struct
```

A WGPUColor of an array [r, g, b, a] or a dictionary.

Effects: fail, read, write, alloc.

### `Device.layoutEntry`

```gizlang
layoutEntry(e: Json): Struct throws string
```

A WGPUBindGroupLayoutEntry: the one binding kind it names, the others left undefined (zero).

Effects: fail, read, write, alloc.

### `Device.groupEntry`

```gizlang
groupEntry(e: Json, s: Scratch): Struct throws string
```

A WGPUBindGroupEntry: a buffer binding {buffer, offset, size}, a texture view, or a sampler.

Effects: fail, read, write, io, alloc.

### `Device.constants`

```gizlang
constants(stage: Json, s: Scratch): Vec<u64>
```

The constants of a stage: their count and their array.

Effects: fail, read, write, io, alloc.

### `Device.stage`

```gizlang
stage(stage: Json, s: Scratch): Struct throws string
```

A WGPUProgrammableStageDescriptor.

Effects: fail, read, write, io, alloc.

### `Device.renderPipeline`

```gizlang
renderPipeline(d: Json, label: u64, s: Scratch): Struct throws string
```

A WGPURenderPipelineDescriptor.

Effects: fail, read, write, io, alloc.

### `Device.format`

```gizlang
format(name: string): i64 throws string
```

A texture format's C value; "$surface-format" is the surface texture's.

Effects: fail, alloc.

### `Device.configure`

```gizlang
configure(width: i64, height: i64): void throws string
```

Configures the surface for frames of WIDTH x HEIGHT, again when the window's size changed.

Effects: fail, read, write, console, io, alloc.

### `Device.acquire`

```gizlang
acquire(): u64 throws string
```

The surface's texture for this frame, taken at the first use of the surface handle; SKIPPED when the display has
none now (the window is hidden, or its surface changed and is configured again for the next frame).

Effects: fail, read, write, console, io, alloc.

### `Device.submit`

```gizlang
submit(packet: bytes, width: i64, height: i64): bool throws string
```

Runs one gizlang/render packet; a packet that draws to the surface shows its frame at the display's next refresh
(WIDTH x HEIGHT, the window's size). Whether a frame was shown: the wait for the display paced the caller.

Effects: fail, read, write, console, io, alloc.

### `Device.run`

```gizlang
run(p: Json, payload: u64, tail: i64, s: Scratch): void throws string
```

The uploads and passes of packet P, whose binary tail of TAIL bytes is at PAYLOAD.

Effects: fail, read, write, console, io, alloc.

### `Device.pass`

```gizlang
pass(encoder: u64, pass: Json, s: Scratch): void throws string
```

One render, compute or copy pass of the packet.

Effects: fail, read, write, io, alloc.

### `Device.timestamps`

```gizlang
timestamps(t: Json, s: Scratch): u64 throws string
```

A pass's timestampWrites, or 0 when it has none.

Effects: fail, read, write, io, alloc.

### `Device.offsets`

```gizlang
offsets(value: Json, s: Scratch): Vec<u64>
```

The dynamic offsets of a setBindGroup: their count and their array.

Effects: fail, read, write, io, alloc.

### `Device.copyBuffer`

```gizlang
copyBuffer(value: Json): Struct throws string
```

A WGPUImageCopyBuffer of {buffer, offset, bytesPerRow, rowsPerImage}.

Effects: fail, read, write, alloc.

### `Device.copyTexture`

```gizlang
copyTexture(value: Json): Struct throws string
```

A WGPUImageCopyTexture of {texture, mipLevel, origin, aspect}.

Effects: fail, read, write, alloc.

### `Device.picture`

```gizlang
picture(): bytes throws string
```

The last frame an offscreen device drew: WIDTH x HEIGHT pixels, RGBA, rows top first.

Effects: fail, read, write, console, io, alloc.

### `Device.close`

```gizlang
close(): void
```

Ends the device, its surface and every object it holds.

Effects: fail, read, write, io, alloc.

## Constants

### `SURFACE_FORMAT`

```gizlang
const SURFACE_FORMAT = "bgra8unorm"
```

The format of the surface texture, which every desktop's GPU presents (B, G, R, then alpha).

