Skip to content

compute.wrapStorageBuffer

Summary

compute.wrapStorageBuffer exposes a range of an existing GPU buffer to compute bindings and transfers. It creates a wrapper without allocating or copying GPU storage. Supply a buffer created on the compute device with GPUBufferUsage.STORAGE.

Syntax

wrapStorageBuffer(buffer: GPUBuffer, options?: WrapStorageBufferOptions): StorageBuffer
const storage = wgpu.compute.wrapStorageBuffer(buffer, { offsetBytes, byteLength: 16 });

Parameters

Name Type Required Description
buffer GPUBuffer Yes Live buffer from the same device, with storage usage.
options WrapStorageBufferOptions No Byte range, ownership and debug label for the wrapper.

Returns

StorageBuffer - A wrapper whose buffer is the original handle, usage is the original usage mask and byteLength is the logical size. Keep a borrowed buffer live for the lifetime of operations that use the wrapper.

Type Details

type WrapStorageBufferOptions = {
    offsetBytes?: number;
    byteLength?: number;
    ownBuffer?: boolean;
    label?: string;
};

offsetBytes defaults to 0 and must be a multiple of device.limits.minStorageBufferOffsetAlignment. byteLength defaults to buffer.size - offsetBytes. Both must be non-negative safe integers and the range must fit the buffer. ownBuffer defaults to false. Set it to true to have wrapper destruction destroy the original buffer too. label defaults to null on the wrapper.

Example

const wgpu = await WasmGPU.create(document.querySelector("canvas"));
const { device } = wgpu.compute;
const offsetBytes = device.limits.minStorageBufferOffsetAlignment;
const raw = device.createBuffer({
    size: offsetBytes + 16,
    usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC
});
const storage = wgpu.compute.wrapStorageBuffer(raw, { offsetBytes, byteLength: 16 });
storage.write(new Float32Array([1, 2, 3, 4]));
console.log(await storage.readAs(Float32Array));
storage.destroy();
raw.destroy();

Notes

Writes require COPY_DST and readback requires COPY_SRC on the original buffer. Wrapper-relative binding and transfer ranges must fit inside the view after any required alignment. Keep the original handle live until commands that use it have been submitted.

See Also