# History

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

Write a shader function once and run it with this frame's values or last frame's, to find how far each point on screen has moved.

> `import { history } from '@typegpu/kit'`: `history.create(root, schema, options?) → History`, `history.create(root, schema, { usage, … }) → History`, `history.temporal(current, previous)`, `history.previously(callback)`. Keeps the previous frame's state for motion vectors and reprojection. **records** `record` frame: `record` once a frame, before the passes and kernels that read or move the state. **owns** 3 buffers: current state, previous state and pending writes. **lifecycle** `destroy()`, `[Symbol.dispose]`. **accessors** `epoch`. `src/history.ts`; classroom, jelly-world, lattice, ocean.
>
> `Options`, taken by `create`:
> - `usage?: U` Selects the buffer usage. Default `storage`.
> - `initial?: d.InferInput<T>` Sets the initial state for both the current and previous frame. Default zeros.
>
> `History`, from `create`:
> - `current: TgpuBuffer<T> & Flag<U>` Holds the current state, including pending writes applied by `record` and changes made by kernels.
> - `previous: TgpuBuffer<T> & Flag<U>` Holds the state from the previous frame, copied from `current` by the last `record`.
> - `reading: U extends 'uniform' ? TgpuAccessor.In<T> : TgpuAccessor.In<T> & TgpuMutableAccessor.In<T>` Fills an accessor with `current`, or `previous` in code compiled with `previously`.
> - `write(value)` Queues a copy of `value` for the next `record` to apply.
> - `record(frame)` Copies the current state to `previous`, then applies pending writes.
> - `destroy()` Destroys the buffers.

Motion vectors and reprojection need last frame's camera and object positions. Maintaining separate shader functions for current and previous state risks differences between them.

`history.previously(fn)` compiles `fn` a second time. In that copy, accessors filled with `history.temporal(current, previous)` read `previous`. `history.create` stores last frame's buffer state for that fill. The kit's [cameras](cameras.md#last-frames-view) store their own previous views, and a [table](table.md#last-frames-rows) or a set of [instances](instances.md#motion) created with `history: true` keeps its own rows. [Passes](passes.md) use `previously` to compute last frame's vertex for outputs such as motion.

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

const offsets = tgpu.accessor(d.arrayOf(d.vec3f, 64));
const placed = history.create(root, d.arrayOf(d.vec3f, 64));

const offsetOf = (i: number) => {
  'use gpu';
  return offsets.$[i];
};
const offsetBefore = history.previously(offsetOf); // last frame's

const moved = root.createMutable(d.arrayOf(d.f32, 64));
const measure = tgpu.computeFn({
  workgroupSize: [64],
  in: { gid: d.builtin.globalInvocationId },
})(({ gid }) => {
  'use gpu';
  if (gid.x >= 64) return;
  moved.$[gid.x] = std.distance(offsetOf(gid.x), offsetBefore(gid.x));
});
const measuring = root.with(offsets, placed.reading).createComputePipeline({ compute: measure });

placed.write(next); // lands at the next record
frames.animate(
  frames.create(root, (frame) => {
    placed.record(frame);
    const pass = frame.encoder.beginComputePass();
    pass.setPipeline(measuring);
    pass.dispatchWorkgroups(1);
    pass.end();
  }),
);
```

## Last frame's code

- `history.epoch` is a slot, `'current'` or `'previous'`, and `previously` resolves its function with `'previous'`. Call what it returns from any `'use gpu'` function, in any stage.
- `history.temporal(current, previous)` fills an accessor with any values it accepts. You can use two uniforms, two buffers, or a current constant and a previous uniform.
- Code that never calls a `previously` function binds `current` only.

## A buffer's history

`history.create(root, schema, options)` owns three buffers, for current state, previous state and the next write.

- The default storage `usage` binds `reading` read-only in render pipelines and read-write in compute pipelines, so it can fill a mutable accessor for kernels that update the state. `usage: 'uniform'` suits small state written by the CPU.
- Write through `write`, not straight into `current`. A queue write lands before everything the frame submits, so it would be copied aside as last frame's too.
- Call `record` once a frame, before what reads or moves the state. A write shows from the first `record` after it in a frame that submits, so a frame that throws leaves the write for the next.

## In a drawing

Store state that moves a drawing, such as the lattice's turn angle, in a history. Read it through a vertex-code accessor filled with `reading` by the [drawing](passes.md#drawings). Outputs that compute last frame's vertex then include the object's motion:

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

// How far the triangle has turned, now and last frame
const turn = tgpu.accessor(d.f32);
const turned = history.create(root, d.f32, { usage: 'uniform' });

const at = (vertexIndex: number, _instanceIndex: number) => {
  'use gpu';
  const angle = turn.$ + d.f32(vertexIndex) * 2.1;
  const world = d.vec3f(std.cos(angle), std.sin(angle), 0);
  return Corner({ position: cameras.toClip(world) });
};
const spinner = scene.add({
  Vertex: Corner,
  at,
  pixelOf,
  color: passes.shaded,
  inject: () => (cfg) => cfg.with(turn, turned.reading),
  draw: (pass) => pass.draw(3),
});

// Each frame, before the pass that draws it
turned.write(frame.time);
turned.record(frame);
```

Filled with a plain uniform, last frame's code reads this frame's turn, and the motion output sees only the camera move.

## Limits

- History stores only one previous frame.
- `record` copies the whole state every frame, and again in a frame with a write.
- A write that jumps the state, such as a teleport, reads as motion for a frame.
