# Pipeline warm-up

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

Compile pipelines behind a loading screen, list each stage's bindings, and find the pipelines warm-up missed.

> `import { pipelines } from '@typegpu/kit'`: `pipelines.compile(from, options?)`, `pipelines.bindingsOf(pipeline, options?) → Bindings`. Compiles pipelines behind a loading screen, lists a pipeline's bindings per stage, and provides blend states. **kind** cpu. **constants** `blend`. **types** `Warmable`, `ShaderStage`, `BindingKind`, `Binding`, `Overflow`. `src/pipelines.ts`; afterimage, benthos, blockfall, censer, classroom, cloister, dominoes, ember-mirror, falling-sand, fireworks, fishtank, flow-field, forest, hex-isle, jellies, jelly-world, jump-flood, kinetic, lattice, night-market, ocean, platformer, quiver-trees, raymarch, robot-arm, skeletons, slime-mould, solar-system, sph-sculpt, spider, stampede, star-map, survey-model.
>
> `CompileOptions`, taken by `compile`:
> - `onProgress?: (fraction: number) => void` Receives the completed fraction whenever an item finishes compiling. Default none.
> - `budget?: number` Limits time spent starting compilations at a stretch, in milliseconds; starting an item resolves its WGSL on the calling thread. Default 8.
>
> `BindingsOptions`, taken by `bindingsOf`:
> - `limits?: Partial<Record<(typeof limitNames)[Overflow['kind']], number>>` Sets the per-stage limits to compare with, such as `root.device.limits`. Default the minimums WebGPU guarantees: 8 storage buffers, 12 uniform buffers, 16 textures, 16 samplers and 4 storage textures.
>
> `Bindings`, from `bindingsOf`:
> - `label: string` Names the pipeline by its label.
> - `bindings: readonly Binding[]` Lists every entry of every bind group layout the pipeline binds, in group and binding order.
> - `over: readonly Overflow[]` Lists each stage and kind over its limit.

A pipeline compiles at first use. That frame waits while TypeGPU resolves WGSL and the browser compiles it. Compile pipelines before rendering to avoid that stall.

Use `pipelines.compile` to warm up before the frame loop. It yields to the page between batches so a loading screen can keep drawing:

```ts
import { pipelines } from '@typegpu/kit';
const field = createField();
const final = createFinal();

await Promise.all([
  castle.ready, // the model's files
  pipelines.compile([field, final], {
    onProgress: (fraction) => (bar.value = fraction),
  }),
]);
```

## Compiling

- **The list** `compile([field, final])` copies the list when you call it. It calls `initAsync()` on each item in that copy and resolves once all of them compile. An item is a TypeGPU pipeline, a pass description, or a module that compiles its own pipelines.
- **Budget** Each start resolves WGSL and creates a shader module on the main thread. The browser compiles in the background. `budget` limits how long `compile` keeps starting compiles before it yields to the event loop. Each stretch starts at least one item. The default is 8 ms, about half a 60 Hz frame. A larger budget can make frames late without increasing compiler throughput.
- **Progress** `onProgress(fraction)` runs as each item finishes; every item counts the same. If `onProgress` throws, `compile` stops calling it and waits for every item to finish. `compile` rejects with that error alone if all items compiled, or includes it with the compile errors in an `AggregateError`.
- **Failures** The promise rejects after every item finishes. Multiple failures produce an `AggregateError`. A missing `inject()` fails with an error that names the fill, and a stage over its binding limit with an error that [lists its bindings](#bindings-per-stage).
- **Before recording** Wait for the promise before recording. TypeGPU throws if a pipeline's `initAsync` is pending. If the frame loop starts earlier, return from its recorder until then. A [coroutine](coroutines.md) waits with `yield* coroutines.until(compiled)`.

> **Caution: WebKit compiles at the first draw**
>
> WebKit builds Metal state at the first draw or dispatch even after async compilation. WebKit compiles one pipeline at a time and presents nothing during compilation, so a budget can't keep its loading screen moving. Draw frames behind the loading screen until frame times settle.

## Bindings per stage

WebGPU guarantees each shader stage 8 storage buffers, 12 uniform buffers, 16 textures, 16 samplers and 4 storage textures. A binding counts in every stage its layout entry is visible to, whether or not that stage reads it. TypeGPU shows a resource in the automatic group only to the stages that read it. An entry of a `tgpu.bindGroupLayout`, such as a [shared layout](bindings.md)'s, is visible to every stage that can use it unless it sets `visibility`. A lit renderer adds up the camera, the lighting, its shadows and every lighting hook's resources.

When a pipeline in `compile` fails while a stage is over its limit, the error lists that kind's bindings by name, which TypeGPU takes from each resource's label:

```txt
The pipeline 'figure' binds more than WebGPU guarantees per stage:
- vertex: 13 uniform buffers, over 12
- fragment: 13 uniform buffers, over 12
Its uniform buffers:
  camera (group 0, binding 0; vertex, fragment)
  paint (group 0, binding 7; vertex, fragment)
  …
```

`pipelines.bindingsOf(pipeline)` reports the same bindings before and after compilation. Its `bindings` list each bind group layout entry with its group, binding, name, kind and the stages that count it. Its `over` lists each stage and resource kind over the limit. It counts entries the shader never reads, such as the other parts of a [shared layout](bindings.md). An external texture counts as 4 textures, a sampler and a uniform buffer. Pass `{ limits: root.device.limits }` to compare with the device's own limits.

To make room:

- Fill a lighting hook on just the renderers that need it, with `things.renderer().pipe((cfg) => cfg.with(shading.fog, fogged))`. A hook filled in `lighting.create` applies wherever a pipeline uses that lighting and reads the hook.
- Pack uniforms that change together into one struct.
- Keep per-object values in a buffer the pipeline already binds, such as an instance kind's host fields.

## Census

> `import { census } from '@typegpu/kit/debug'`: `census.create(root, options?) → Census`. Counts pipelines, their bindings per stage, and late compiles. **stability** unstable: may change in any way in a minor release. **kind** tool. **lifecycle** `destroy()`, `[Symbol.dispose]`. **types** `CensusEntry`. `src/debug/census.ts`.
>
> `Options`, taken by `create`:
> - `limits?: BindingsOptions['limits'] & { readonly maxBindGroups?: number }` Sets the limits to compare with, such as `root.device.limits`. Default the minimums WebGPU guarantees: 4 bind groups, 8 storage buffers, 12 uniform buffers, 16 textures, 16 samplers and 4 storage textures per stage.
>
> `Census`, from `create`:
> - `pipelines: readonly CensusEntry[]` Lists every pipeline created so far, in creation order.
> - `modules: number` Counts the shader modules created so far.
> - `wgslBytes: number` Sums the WGSL length of every shader module created so far, in characters.
> - `late: readonly CensusEntry[]` Lists pipelines created synchronously after `warm()`.
> - `overBudget: readonly CensusEntry[]` Lists pipelines with a stage over its limits, or more bind groups than allowed.
> - `warm()` Marks warm-up complete.
> - `destroy()` Restores the device's methods.

A census from `@typegpu/kit/debug` finds what warm-up missed. Create it right after the root, in development only, and call `warm()` once warm-up is done:

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

const counted = census.create(root); // before any compile
await pipelines.compile([field]);
counted.warm(); // a compile from now on is late
```

- It wraps the device's `createShaderModule`, `createBindGroupLayout`, `createPipelineLayout` and four pipeline methods. `destroy()`, or `using`, restores them.
- `late` lists the pipelines created synchronously after `warm()`. It can reveal compiles that happen during a frame. Play through the game to catch an effect or a menu that compiles on first use.
- Each entry of `pipelines` describes one pipeline. Its `bindings` list the layout entries, counted as `bindingsOf` counts them. `groups` counts its bind groups, including TypeGPU's automatic group, and `over` lists the stages over a limit.
- `overBudget` lists the pipelines with a stage over a limit or more bind groups than `maxBindGroups`. The limits default to the minimums WebGPU guarantees on every device.
- `modules` and `wgslBytes` count the shader modules and their WGSL.

## Blend states

`pipelines.blend.add` adds light, for sparks, glow and bloom. `pipelines.blend.over` lays premultiplied colour over what is there, for a fragment that returns `vec4f(rgb * a, a)`. `pipelines.blend.straight` lays straight colour, for one that returns `vec4f(rgb, a)`. Give any of them to a pipeline's target:

```ts
root.createRenderPipeline({ vertex, fragment, targets: { format, blend: pipelines.blend.add } });
```

## Limits

- The budget covers only compilation starts. Allow time for the rest of your frame. At 120 Hz a frame lasts about 8 ms, so use a smaller budget.
- Progress counts items, so a module of six pipelines moves the bar as much as one pipeline. Pass a module's pipelines one by one to count each.
- Started compiles can't be cancelled, so a typo in the first item is reported only after the slowest compile.
- Nothing warms a pipeline the first frames don't use, such as an effect that fires later. On WebKit it stalls the first time it draws.
- Only pipelines compiled through `compile`, directly or inside a module, fail with the binding list. A pipeline that compiles at its first draw reports the device's error.
