Skip to content

compute.createStorageBuffer#write

Summary

compute.createStorageBuffer#write uploads CPU bytes into GPU storage. Use write for an array buffer or view, writeFromArrayBuffer for an explicit buffer range, or writeFromWasmMemory for bytes at a WebAssembly pointer.

Syntax

write(data: BufferSource, dstOffsetBytes?: number, srcOffsetBytes?: number, sizeBytes?: number): void
writeFromArrayBuffer(src: ArrayBuffer, srcOffsetBytes: number, sizeBytes: number, dstOffsetBytes?: number): void
writeFromWasmMemory(mem: WebAssembly.Memory, srcPtrBytes: number, sizeBytes: number, dstOffsetBytes?: number): void
storage.write(new Float32Array([1, 2]), 0);

Parameters

Name Type Required Description
data, src BufferSource, ArrayBuffer Yes Source used by write or writeFromArrayBuffer.
mem, srcPtrBytes WebAssembly.Memory, number Yes Memory and byte address used by writeFromWasmMemory.
dstOffsetBytes number No Offset relative to the storage wrapper, default 0.
srcOffsetBytes number Varies Offset relative to the source buffer or view. Defaults to 0 for write.
sizeBytes number Varies Bytes to upload. Defaults to the remaining source bytes for write. Required for the two other methods.

Returns

void - Schedules the upload on the compute queue.

Example

const wgpu = await WasmGPU.create(document.querySelector("canvas"));
const storage = wgpu.compute.createStorageBuffer({ byteLength: 8, copySrc: true });
storage.write(new Float32Array([2, 4]));
console.log(await storage.readAs(Float32Array));
storage.destroy();

Notes

Storage must be live and have COPY_DST usage. The destination offset and the source's offset within its backing buffer must be four-byte aligned. The requested ranges must fit. A write rounds the copy size up to four bytes and zero-fills the trailing bytes, so it can overwrite up to three bytes past the requested data. That rounded range must fit within the allocation for created storage or within the wrapper's byte range for wrapped storage.

See Also