Skip to content

ModuleCore / Reading backConcept: Data on the GPU

Readback

Copy a buffer into your frame's encoder and read it on the CPU after submit without stalling.

import
import { readback } from '@typegpu/kit'
call
readback.create(root, source, { bytes, … }) → Readback
facts
recordsframelifecycledestroy()
On this page

The GPU executes commands after the CPU records them. A result such as the object under a cursor therefore reaches the CPU in a later . TypeGPU’s buffer.read() creates a , submit and promise per call. A readback reuses a ring of staging buffers, records copies in your frame’s encoder and maps them after submit.

Each copy reaches the CPU when its staging buffer maps

Try Drag map takes and the bars stretch into more staging buffers, then lower staging to see captures skipped while every buffer maps. read() waits for the next copy.
import {
import readback
readback
} from '@typegpu/kit';
const
const hits: TgpuBuffer<d.WgslArray<d.U32>> & StorageFlag
hits
=
const root: TgpuRoot
root
.
TgpuRoot.createBuffer<d.WgslArray<d.U32>>(typeSchema: d.WgslArray<d.U32>, initial?: ((buffer: TgpuBuffer<NoInfer<d.WgslArray<d.U32>>>) => void) | d.InferInput<NoInfer<d.WgslArray<d.U32>>> | undefined): TgpuBuffer<d.WgslArray<d.U32>> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader.

@remarks ― Typed wrapper around a GPUBuffer.

@param ― typeSchema The type of data that this buffer will hold.

@param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

createBuffer
(
import d
d
.
arrayOf<d.U32>(elementType: d.U32, elementCount: number): d.WgslArray<d.U32> (+2 overloads)
export arrayOf

@location ― . Wrap align/size in a struct instead, e.g. d.arrayOf(d.struct({ value: d.align(16, d.u32) }), n).

arrayOf
(
import d
d
.
const u32: d.U32
export u32

A schema that represents an unsigned 32-bit integer value. (equivalent to u32 in WGSL)

Can also be called to cast a value to an u32 in accordance with WGSL casting rules.

@example const value = u32(); // 0

@example const value = u32(7); // 7

@example const value = u32(3.14); // 3

@example const value = u32(-1); // 4294967295

@example const value = u32(-3.1); // 0

u32
, 4)).
TgpuBuffer<WgslArray<U32>>.$usage<["storage"]>(usages_0: "storage"): TgpuBuffer<d.WgslArray<d.U32>> & StorageFlag
$usage
('storage');
const
const probe: readback.Readback<number[]>
probe
=
import readback
readback
.
function create<d.WgslArray<d.U32>>(root: TgpuRoot, source: TgpuBuffer<d.WgslArray<d.U32>>, options?: readback.Options & {
readonly bytes?: false;
}): readback.Readback<number[]> (+3 overloads)

Copies a buffer, or a range of its bytes, to the CPU without stalling, using a ring of staging buffers. Records one copy per capture. Throws unless staging is an integer above 0, hz, when set, is finite and above 0, and offset and size are multiples of 4 that fit the buffer.

@owns ― 3 buffers: staging buffers mapped in turn, as many as staging, each the size of the copy

@records ― capture after the pass that writes the buffer; a second capture in a frame does nothing.

@param ― source the buffer it copies

@returns ― a reader you capture into and destroy

create
(
const root: TgpuRoot
root
,
const hits: TgpuBuffer<d.WgslArray<d.U32>> & StorageFlag
hits
, {
Options.hz?: number | undefined

Also captures for latest this many times per second on average, in the frame closest to each tick. Without a rate, only next() and request cause captures. Default none.

hz
: 30 });
import frames
frames
.
function create(root: TgpuRoot, record: Recorder): frames.Frames

Records a frame into one encoder and submits once, with a clock. Borrows the root. The synchronous recorder borrows each frame's encoder.

@submits ― always once a frame after your recorder returns, and again at each frame.submit()

@param ― record your frame, recorded into each frame's encoder

@returns ― a loop you run with each frame's time and destroy

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
// ... the pass that writes `hits`
const probe: readback.Readback<number[]>
probe
.
Readback<number[]>.capture(frame: frames.Frame): void

Records a copy when a next() is waiting, a request is pending or the capture rate is due. Maps the copy after submission. Call after the pass that writes the buffer. A second call in the same frame does nothing.

capture
(
frame: frames.Frame
frame
); // after it
const scheduler: coroutines.Coroutines
scheduler
.
Coroutines.run(frame: frames.Frame): void

Resumes every coroutine whose wait is complete. Call while a frame is recording. Coroutine and wait errors go to the coroutine's yield* or to onError, rather than escaping run.

run
(
frame: frames.Frame
frame
);
const
const polled: number[] | undefined
polled
=
const probe: readback.Readback<number[]>
probe
.
Readback<number[]>.take(): number[] | undefined

Returns latest once per completed copy, then undefined until the next copy completes. Each value goes to one caller. Callers sharing a readback split the values between them.

take
(); // polled: each new value once, or undefined
if (
const polled: number[] | undefined
polled
)
function onHits(count: number): void
onHits
(
const polled: number[]
polled
[0]);
});
function*
function react(): Generator<coroutines.Wait<unknown>, void, unknown>
react
() {
const
const counts: number[]
counts
= yield*
import coroutines
coroutines
.
function until<number[]>(promise: PromiseLike<number[]>): coroutines.Wait<number[]>

Waits for a promise, such as a readback's next() or pipelines.compile. Resumes at the first run after it settles, with its value or its error.

@param ― promise the promise to wait for

@returns ― a wait to yield*

until
(
const probe: readback.Readback<number[]>
probe
.
Readback<number[]>.next(): Promise<number[]>

Returns a promise for the value from the next capture, and requests that capture. Promises asked for before one capture share its copy. Rejects if mapping fails or the reader is destroyed first. Waits indefinitely without a capture. In a coroutine, wait with yield* coroutines.until(probe.next()).

next
()); // or waited on: the next capture
function onHits(count: number): void
onHits
(
const counts: number[]
counts
[0]);
}

capture(frame) copies the buffer, or its range, at that point in the command order. Place it after the pass that fills a counter, or before the passes when a picker must read the frame already on screen.

  • Busy buffers While every staging buffer is mapping, it is skipped and tried again next frame.
  • Cadence Record the pass that fills the buffer every frame and let hz pick the frames that copy; a pass that counts costs microseconds. Gating that pass with a clock of your own makes two that disagree, so a copy can land in a frame the pass skipped.
  • Once a frame A frame captures once; a second call does nothing.
  • Unsubmitted frames A frame that is never submitted hands its reads to the next capture.
  • Reads return the buffer’s value transformed by decode, if supplied. If decode throws, reads waiting on that copy fail with its error.
  • Two callers of take() split the values. If both need every value, have each read latest and track latestFrame.
  • In a coroutine, wait for next() with yield* coroutines.until(probe.next()).
  • A picker’s pick calls request() for its own copy.
  • For counters that only increase, compare each read with the last value to handle late or repeated reads. Counters does that for named counters.

Reads decode the whole schema into JavaScript values, one object per struct, so a large array of structs allocates thousands of objects per read. Pass bytes: true to skip decoding. decode then receives the copied bytes, which follow the schema’s WGSL layout with its padding. They are valid only during the call, so read them into arrays of your own. Without decode, reads return a copy as an ArrayBuffer, so a result of any other type needs a decode that makes it.

const
const Cell: d.WgslStruct<{
level: d.F32;
source: d.U32;
}>
Cell
=
import d
d
.
struct<{
level: d.F32;
source: d.U32;
}>(props: {
level: d.F32;
source: d.U32;
}): d.WgslStruct<{
level: d.F32;
source: d.U32;
}>
export struct

Creates a struct schema that can be used to construct GPU buffers. Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema). The order of members matches the passed in properties object.

@example const CircleStruct = d.struct({ radius: d.f32, pos: d.vec3f });

@param ― props Record with string keys and TgpuData values, each entry describing one struct member.

struct
({
level: d.F32
level
:
import d
d
.
const f32: d.F32
export f32

A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)

Can also be called to cast a value to an f32.

@example const value = f32(); // 0

@example const value = f32(1.23); // 1.23

@example const value = f32(true); // 1

f32
,
source: d.U32
source
:
import d
d
.
const u32: d.U32
export u32

A schema that represents an unsigned 32-bit integer value. (equivalent to u32 in WGSL)

Can also be called to cast a value to an u32 in accordance with WGSL casting rules.

@example const value = u32(); // 0

@example const value = u32(7); // 7

@example const value = u32(3.14); // 3

@example const value = u32(-1); // 4294967295

@example const value = u32(-3.1); // 0

u32
}); // 8 bytes a cell
const
const cells: TgpuBuffer<d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>> & StorageFlag
cells
=
const root: TgpuRoot
root
.
TgpuRoot.createBuffer<d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>>(typeSchema: d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>, initial?: ((buffer: TgpuBuffer<NoInfer<d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>>>) => void) | d.InferInput<NoInfer<d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>>> | undefined): TgpuBuffer<d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader.

@remarks ― Typed wrapper around a GPUBuffer.

@param ― typeSchema The type of data that this buffer will hold.

@param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

createBuffer
(
import d
d
.
arrayOf<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>(elementType: d.WgslStruct<{
level: d.F32;
source: d.U32;
}>, elementCount: number): d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>> (+2 overloads)
export arrayOf

@location ― . Wrap align/size in a struct instead, e.g. d.arrayOf(d.struct({ value: d.align(16, d.u32) }), n).

arrayOf
(
const Cell: d.WgslStruct<{
level: d.F32;
source: d.U32;
}>
Cell
, 12288)).
TgpuBuffer<WgslArray<WgslStruct<{ level: F32; source: U32; }>>>.$usage<["storage"]>(usages_0: "storage"): TgpuBuffer<d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>> & StorageFlag
$usage
('storage');
const
const levels: Float32Array<ArrayBuffer>
levels
= new
var Float32Array: Float32ArrayConstructor
new (length: number) => Float32Array<ArrayBuffer> (+6 overloads)
Float32Array
(12288);
const
const field: readback.Readback<Float32Array<ArrayBuffer>>
field
=
import readback
readback
.
function create<d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>, Float32Array<ArrayBuffer>>(root: TgpuRoot, source: TgpuBuffer<d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>>, options: readback.BytesOptions<Float32Array<ArrayBuffer>> & {
readonly decode: (bytes: ArrayBuffer) => Float32Array<ArrayBuffer>;
}): readback.Readback<Float32Array<ArrayBuffer>> (+3 overloads)

Copies a buffer, or a range of its bytes, to the CPU without stalling, using a ring of staging buffers. Records one copy per capture. Throws unless staging is an integer above 0, hz, when set, is finite and above 0, and offset and size are multiples of 4 that fit the buffer.

@owns ― 3 buffers: staging buffers mapped in turn, as many as staging, each the size of the copy

@records ― capture after the pass that writes the buffer; a second capture in a frame does nothing.

@param ― source the buffer it copies

@returns ― a reader you capture into and destroy

create
(
const root: TgpuRoot
root
,
const cells: TgpuBuffer<d.WgslArray<d.WgslStruct<{
level: d.F32;
source: d.U32;
}>>> & StorageFlag
cells
, {
BytesOptions<T = ArrayBuffer>.bytes: true

Reads the copied bytes without decoding them through the buffer's schema.

bytes
: true,
decode: ((bytes: ArrayBuffer) => Float32Array<ArrayBuffer>) & ((bytes: ArrayBuffer) => Float32Array<ArrayBuffer>)

Converts the copied bytes to the value returned by next and latest, such as typed arrays of your own. The bytes are valid only during the call, so copy what you keep. If it throws, reads for that copy fail with the error. Required for a result other than an ArrayBuffer. Default a copy of the bytes.

@cpu

decode
: (
bytes: ArrayBuffer
bytes
) => {
const
const words: Float32Array<ArrayBuffer>
words
= new
var Float32Array: Float32ArrayConstructor
new <ArrayBuffer>(buffer: ArrayBuffer, byteOffset?: number, length?: number) => Float32Array<ArrayBuffer> (+6 overloads)
Float32Array
(
bytes: ArrayBuffer
bytes
);
for (let
let i: number
i
= 0;
let i: number
i
<
const levels: Float32Array<ArrayBuffer>
levels
.
Float32Array<ArrayBuffer>.length: number

The length of the array.

length
;
let i: number
i
++)
const levels: Float32Array<ArrayBuffer>
levels
[
let i: number
i
] =
const words: Float32Array<ArrayBuffer>
words
[
let i: number
i
* 2];
return
const levels: Float32Array<ArrayBuffer>
levels
;
},
});

With bytes: true, offset and size copy only that range of the buffer, such as one level of a packed map or a run of . Both count bytes and are multiples of 4; size defaults to the rest of the buffer. Each staging buffer holds only the range, and decode receives only its bytes. A range needs bytes: true, since part of a buffer is not a value of its schema.

const
const heights: TgpuBuffer<d.WgslArray<d.F32>> & StorageFlag
heights
=
const root: TgpuRoot
root
.
TgpuRoot.createBuffer<d.WgslArray<d.F32>>(typeSchema: d.WgslArray<d.F32>, initial?: ((buffer: TgpuBuffer<NoInfer<d.WgslArray<d.F32>>>) => void) | d.InferInput<NoInfer<d.WgslArray<d.F32>>> | undefined): TgpuBuffer<d.WgslArray<d.F32>> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader.

@remarks ― Typed wrapper around a GPUBuffer.

@param ― typeSchema The type of data that this buffer will hold.

@param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

createBuffer
(
import d
d
.
arrayOf<d.F32>(elementType: d.F32, elementCount: number): d.WgslArray<d.F32> (+2 overloads)
export arrayOf

@location ― . Wrap align/size in a struct instead, e.g. d.arrayOf(d.struct({ value: d.align(16, d.u32) }), n).

arrayOf
(
import d
d
.
const f32: d.F32
export f32

A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)

Can also be called to cast a value to an f32.

@example const value = f32(); // 0

@example const value = f32(1.23); // 1.23

@example const value = f32(true); // 1

f32
, 256 * 256 + 128 * 128)).
TgpuBuffer<WgslArray<F32>>.$usage<["storage"]>(usages_0: "storage"): TgpuBuffer<d.WgslArray<d.F32>> & StorageFlag
$usage
('storage');
// The second level, after the first level's 256 × 256 floats
const
const coarse: readback.Readback<ArrayBuffer>
coarse
=
import readback
readback
.
function create<d.WgslArray<d.F32>>(root: TgpuRoot, source: TgpuBuffer<d.WgslArray<d.F32>>, options: readback.BytesOptions): readback.Readback<ArrayBuffer> (+3 overloads)

Copies a buffer, or a range of its bytes, to the CPU without stalling, using a ring of staging buffers. Records one copy per capture. Throws unless staging is an integer above 0, hz, when set, is finite and above 0, and offset and size are multiples of 4 that fit the buffer.

@owns ― 3 buffers: staging buffers mapped in turn, as many as staging, each the size of the copy

@records ― capture after the pass that writes the buffer; a second capture in a frame does nothing.

@param ― source the buffer it copies

@returns ― a reader you capture into and destroy

create
(
const root: TgpuRoot
root
,
const heights: TgpuBuffer<d.WgslArray<d.F32>> & StorageFlag
heights
, {
BytesOptions<ArrayBuffer>.bytes: true

Reads the copied bytes without decoding them through the buffer's schema.

bytes
: true,
BytesOptions<ArrayBuffer>.offset?: number | undefined

Copies from this many bytes into the buffer, a multiple of 4. Default 0.

offset
: 256 * 256 * 4 });
const
const level: Float32Array<ArrayBuffer>
level
= new
var Float32Array: Float32ArrayConstructor
new <ArrayBuffer>(buffer: ArrayBuffer, byteOffset?: number, length?: number) => Float32Array<ArrayBuffer> (+6 overloads)
Float32Array
(await
const coarse: readback.Readback<ArrayBuffer>
coarse
.
Readback<ArrayBuffer>.next(): Promise<ArrayBuffer>

Returns a promise for the value from the next capture, and requests that capture. Promises asked for before one capture share its copy. Rejects if mapping fails or the reader is destroyed first. Waits indefinitely without a capture. In a coroutine, wait with yield* coroutines.until(probe.next()).

next
());

hz schedules captures at that rate and updates latest without a waiting read. It uses a cadence, so the first capture is immediate.

  • Call reset() after clearing a buffer or reloading a scene to discard earlier copies.
  • To restart counters, clear the buffer in the frame, before the passes that count, and reset(). Otherwise a copy made before the clear can land after it, and counters that take differences run backwards.
  • A late map never replaces a newer latest.
  • A promise that already resolved keeps its value, even if its coroutine resumes after a reset. Compare a held result with latest.
  • A ’s changes reach the GPU at the first submit after its flush. Compare latestFrame with that frame’s index when a value must be newer than a change.

Device loss rejects every map. Promises waiting on a copy reject with the map’s error, later captures also fail, and latest keeps its last value. Create the again on another root to recover.

  • A capture placed before the pass that fills the buffer reads the previous frame’s value, and nothing catches that.
  • A reads a fixed buffer. A varying list read once, on demand, needs code of its own.
frameA frame is one turn of the loop, and the object your function gets for it, which holds the encoder, the time and the time since the last frame.You own the frame →
staging bufferA staging buffer is a buffer the CPU can map, which a result is copied into so that it can be read after the frame.Words →
cadenceA cadence tells you on which frames work that runs less often than every frame is due.Cadences →
rowA row is one object's values in a buffer, such as one enemy, one particle or one light.Objects are rows in buffers →
tableA table is a buffer of rows with named fields, some written by the CPU and the others by kernels.Rows →
moduleA module is one piece of GPU work, made by a factory that borrows your root and returns resources, shader functions and methods that record into your frame.A module borrows →
readbackA readback copies a buffer during a frame and hands it to the CPU a frame or two later, without making the frame wait.Results back →

Reference

kit.readback

moduleHow to read this card

Callsborrows, never destroystakesreturns

readback.create(root, source, { bytes, … }) → Readback

root
the root
source
the buffer it copies
Readback
a reader you capture into and destroy
takes

BytesOptions

6 fields
bytes

true

Reads the copied bytes without decoding them through the buffer's schema.

offset?

number

Copies from this many bytes into the buffer, a multiple of 4.Default 0.

size?

number

Copies this many bytes, a multiple of 4.Default the rest of the buffer after offset.

decode?

(bytes: ArrayBuffer) => T

Converts the copied bytes to the value returned by next and latest, such as typed arrays of your own.Default a copy of the bytes.

staging?

number

Sets the number of staging buffers.Default 3.

hz?

number

Also captures for latest this many times per second on average, in the frame closest to each tick.Default none.

takes

DecodeOptions

3 fields
decode

(value: d.Infer<S>) => T

Converts the source buffer value, read by its schema, to the value returned by next and latest, such as a candidate index or null.

staging?

number

Sets the number of staging buffers.Default 3.

hz?

number

Also captures for latest this many times per second on average, in the frame closest to each tick.Default none.

takes

Options

2 fields
staging?

number

Sets the number of staging buffers.Default 3.

hz?

number

Also captures for latest this many times per second on average, in the frame closest to each tick.Default none.

returns

Readback

8 members
latest

T | undefined

Reports the latest value read, or undefined before the first read and after reset.

latestFrame

number

Identifies the frame copied for latest, or -1 if there is no value.

take()

Returns latest once per completed copy, then undefined until the next copy completes.

next()

Returns a promise for the value from the next capture, and requests that capture.

request()

Requests a copy at the next capture for latest and take(), without a promise.

capture(frame)

Records a copy when a next() is waiting, a request is pending or the capture rate is due.

reset()

Clears latest and discards results from copies already recorded, such as after resetting the source buffer.

destroy()

Destroys the staging buffers and rejects the reads still waiting.

readback.create(root, source, { bytes, decode, … }) → Readback

root
the root
source
the buffer it copies
Readback
a reader you capture into and destroy

readback.create(root, source, { decode, … }) → Readback

root
the root
source
the buffer it copies
Readback
a reader you capture into and destroy

readback.create(root, source, options?) → Readback

root
the root
source
the buffer it copies
Readback
a reader you capture into and destroy

In a frame

records

capture after the pass that writes the buffer; a second capture in a frame does nothing.

Holds

owns

3 buffers

Staging buffers mapped in turn, as many as staging, each the size of the copy.

lifecycle

destroy()[Symbol.dispose]

used byFireworksFish tankSPH sculptStampede