# Readback

> `@typegpu/kit` 0.1.0. If it is installed, read `node_modules/@typegpu/kit/docs/` instead.

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

> `import { readback } from '@typegpu/kit'`: `readback.create(root, source, { bytes, … }) → Readback`, `readback.create(root, source, { bytes, decode, … }) → Readback`, `readback.create(root, source, { decode, … }) → Readback`, `readback.create(root, source, options?) → Readback`. Copies a buffer, or a range of its bytes, to the CPU without stalling, using a ring of staging buffers. **records** `capture` frame: `capture` after the pass that writes the buffer; a second capture in a frame does nothing. **owns** 3 buffers: staging buffers mapped in turn, as many as `staging`, each the size of the copy. **lifecycle** `destroy()`, `[Symbol.dispose]`. `src/readback.ts`; fireworks, fishtank, sph-sculpt, stampede.
>
> `BytesOptions`, taken by `create`:
> - `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.
>
> `DecodeOptions`, taken by `create`:
> - `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.
>
> `Options`, taken by `create`:
> - `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.
>
> `Readback`, from `create`:
> - `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.

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 frame. TypeGPU's `buffer.read()` creates a staging buffer, 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.

```ts
import { readback } from '@typegpu/kit';

const hits = root.createBuffer(d.arrayOf(d.u32, 4)).$usage('storage');
const probe = readback.create(root, hits, { hz: 30 });

frames.create(root, (frame) => {
  // ... the pass that writes `hits`
  probe.capture(frame); // after it
  scheduler.run(frame);

  const polled = probe.take(); // polled: each new value once, or undefined
  if (polled) onHits(polled[0]);
});

function* react() {
  const counts = yield* coroutines.until(probe.next()); // or waited on: the next capture
  onHits(counts[0]);
}
```

## Placing the capture

`capture(frame)` copies the buffer, or its [range](#reading-a-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 cadences 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.

## Reading

- 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](coroutines.md), wait for `next()` with `yield* coroutines.until(probe.next())`.
- A [picker](picker.md)'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](counters.md) does that for named counters.

## Reading bytes

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.

```ts
const Cell = d.struct({ level: d.f32, source: d.u32 }); // 8 bytes a cell
const cells = root.createBuffer(d.arrayOf(Cell, 12288)).$usage('storage');

const levels = new Float32Array(12288);
const field = readback.create(root, cells, {
  bytes: true,
  decode: (bytes) => {
    const words = new Float32Array(bytes);
    for (let i = 0; i < levels.length; i++) levels[i] = words[i * 2];
    return levels;
  },
});
```

### Reading a range

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 rows. 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.

```ts
const heights = root.createBuffer(d.arrayOf(d.f32, 256 * 256 + 128 * 128)).$usage('storage');

// The second level, after the first level's 256 × 256 floats
const coarse = readback.create(root, heights, { bytes: true, offset: 256 * 256 * 4 });
const level = new Float32Array(await coarse.next());
```

## Rate

`hz` schedules captures at that rate and updates `latest` without a waiting read. It uses a [cadence](clock.md#cadences), so the first capture is immediate.

## Staleness

- 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 table'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 modules again on another root to recover.

## Limits

- A capture placed before the pass that fills the buffer reads the previous frame's value, and nothing catches that.
- A readback reads a fixed buffer. A varying list read once, on demand, needs code of its own.
