Raw WebGPU example
Live: gpu-read is an annotated read of a pooled grid, and webgpu-smoke is the same contract with a fragment raymarch and no engine.
This samples a pooled grid along the x axis from a compute pass. It shows the whole contract, which the raymarching
demo (examples/src/demos/08-webgpu-smoke) repeats with a fragment shader:
- You own the device, created with
VDBGridPool.requiredLimits(adapter). - You generate one WGSL module and put it in front of your shader (
vdbModuleWgsl), and declare the pool binding in your own layout (vdbModuleEntries). - Each frame you record
pool.update(encoder)into your encoder, before the passes that read the pool. - You rebuild bind groups when
pool.versionchanges. - You call
pool.dispose()on teardown. The device stays yours.
import { vdbModuleEntries, vdbModuleWgsl } from '@pmndrs/vdb';
import type { VDBSlotModuleOptions } from '@pmndrs/vdb';
const options: VDBSlotModuleOptions = { slot: { group: 0, firstBinding: 0 }, types: ['float'], profile: 'sample' };
// The host's own half of the shader. The generated module declares `vdbPool` and the vdb* functions.
const code =
vdbModuleWgsl(options) +
/* wgsl */ `
@group(1) @binding(0) var<storage, read_write> result: array<f32>;
@group(1) @binding(1) var<uniform> grid: u32;
@compute @workgroup_size(8)
fn main(@builtin(global_invocation_id) id: vec3u) {
var acc = vdbAccessorInit(grid);
// World-space samples along x, through the grid's own transform.
let world = vec3f(f32(id.x) * 0.1, 0.0, 0.0);
result[id.x] = vdbSample(&acc, vdbWorldToIndex(grid, world));
}`;
const poolLayout = device.createBindGroupLayout({ entries: vdbModuleEntries(options.slot) });
const ownLayout = device.createBindGroupLayout({
entries: [
{ binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'storage' } },
{ binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform' } },
],
});
const pipeline = await device.createComputePipelineAsync({
layout: device.createPipelineLayout({ bindGroupLayouts: [poolLayout, ownLayout] }),
compute: { module: device.createShaderModule({ code }), entryPoint: 'main' },
});
const count = 8;
const result = device.createBuffer({ size: count * 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC });
const gridUniform = device.createBuffer({ size: 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
device.queue.writeBuffer(gridUniform, 0, new Uint32Array([gridId]));
const staging = device.createBuffer({ size: count * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
const encoder = device.createCommandEncoder();
pool.update(encoder); // before the bind group, and before the pass that reads the pool
const pass = encoder.beginComputePass();
pass.setPipeline(pipeline);
pass.setBindGroup(0, device.createBindGroup({ layout: poolLayout, entries: [pool.bindGroupEntry(options.slot)] }));
pass.setBindGroup(1, device.createBindGroup({ layout: ownLayout, entries: [{ binding: 0, resource: { buffer: result } }, { binding: 1, resource: { buffer: gridUniform } }] }));
pass.dispatchWorkgroups(1);
pass.end();
encoder.copyBufferToBuffer(result, 0, staging, 0, count * 4);
device.queue.submit([encoder.finish()]);
await staging.mapAsync(GPUMapMode.READ);
const values = new Float32Array(staging.getMappedRange().slice(0));
staging.unmap();
Several grids share the module by id: vdbAccessorInit(g) for grid g, and vdbWorldToIndex(g, p) reads the grid's
record, so instance transforms set with pool.setTransform are free. Voxel centres sit at integer index
coordinates.
Compute tools
The core also ships two compute tools that read a resident grid back. Each records into your encoder when you pass one, and otherwise submits its own.
import { vdbDecodeToAtlas, vdbGridStats } from '@pmndrs/vdb';
// The grid must be resident (an update() or flush() ran after its add()).
const stats = await vdbGridStats(device, pool, gridId, { histogramBins: 64 }).read();
console.log(stats.min, stats.max, stats.mean, stats.activeVoxelCount);
// Dense decode of the index box: x fastest, at most 128 voxels per axis, normalized to 0..255.
const atlas = await vdbDecodeToAtlas(device, pool, gridId, { maxDim: 128, format: 'uint8' }).read();
console.log(atlas.dims, atlas.data.length);
// To record into your own encoder instead: pass { encoder }, submit it, then `job.submitted().read()`.
vdbGridStats bins its histogram over the grid's root min and max statistics, so a grid without stats (or with stale
ones after a value transform) bins against whatever they hold. vdbDecodeToAtlas samples voxel centres: cell i of an axis with n cells over the index range [min, max] reads
index position min + (i + 0.5) * (max - min + 1) / n - 0.5, so at full resolution cell i is voxel min + i and the
last cell is voxel max. Treat the output as a texture over the voxel-centred box [min - 0.5, max + 0.5].
The CPU twins are vdbGridStatsCpu and vdbDecodeToAtlasCpu in @pmndrs/vdb/tools.