# gameplay/crowd.md

`@ferret/crowd` puts hundreds or thousands of animated people (or animals, or anything skinned) in a scene for little, and shows each of them only
as richly as its size on the screen deserves. It works for any skinned character: a library character with its clip set, or any skinned glb
with its animation groups. Nothing in it knows a particular character. It is built on `@ferret/perspective`: every agent is an entity with a
ladder of rungs, and the perspective service picks the rung each frame by the agent's size in pixels.

## The rungs

| rung | what is drawn | cost |
|---|---|---|
| `full` | the character itself, its own animation group | what the model costs; a few at a time (`maxFull`) |
| `vat` | the same character skinned on the GPU from baked bone matrices, simplified to a few thousand triangles | one draw call per mesh of the model for all its agents |
| `impostor` | an animated picture of the model (all clips side by side in one atlas) | a quad |
| `point` | a dot of the model's mean colour and area | one pass for everything |
| `none` | nothing | nothing |

Every rung shows the same moment of the same clip: the full figure's animation group, the VAT instance (the frame is written per instance each
frame) and the impostor frame all follow from the agent's clip, phase, rate and the world's simulated time.

## Use

```ts
import { BabylonBackend, PerspectiveService } from '@ferret/perspective';
import { CrowdService, crowdModelFromLibrary, spawnCrowdAgent } from '@ferret/crowd';

const backend = new BabylonBackend(scene);
world.addService(new PerspectiveService({ backend, budget: { maxFull: 8 } }));
world.addService(new CrowdService(backend));

// one model per character: clip names of the agent -> clips of the library (cache: the persistent cache keeps the bakes and the ladder)
const people = await crowdModelFromLibrary(scene, lib, 'viking', { walk: 'cc-clips/Walk_Fwd', idle: 'cc-clips/Idle' }, { cache, maxFull: 8 });

for (let i = 0; i < 1000; i++) await spawnCrowdAgent(world, people, {
  position: [x, 0, z], heading, clip: 'walk', phase: Math.random(), rate: 0.9 + 0.2 * Math.random(),
  wander: { area: { x, z, halfX: 25, halfZ: 25 }, walk: 'walk', idle: 'idle', pause: [1, 6], seed: i },
});
```

A character that is not in the library: `CrowdModel.prepare(scene, { key, clips, mid: { root, groups }, full: () => loadAnother() })`, where `mid` is
a loaded instance (its lightest tier) and `full` makes one more full instance for the pool.

### What `prepare` does

1. Bakes the bone matrices of every frame of each clip (at most 48 frames a clip, 30 fps) into one float texture in the layout of Babylon's
   `BakedVertexAnimationManager`. Root motion is taken out and measured as the clip's speed; a clip made in place gets its speed from the stance
   of its feet. An agent walking at `speed * rate` has feet that do not slide.
2. Bakes the animated impostor over every clip (12 frames for a moving clip, 4 in place).
3. Makes the VAT rung from the `mid` instance: parts that ride a bone as child nodes (hats, weapons, strand hair) become one-bone skinned meshes;
   meshes of many loose pieces (strands, fur) lose whole pieces, the others are merged on a grid, down to `vatTriangles` (default 6000).
   Materials that are not PBR or standard (a custom shader) are replaced by a PBR material of the vertex colours.
4. Fills the pool of `maxFull` full instances.
5. Measures the ladder in the scene (`measureCrowdLadder`): each rung drawn alone into a render target at the same moment, from four sides, at a
   ladder of sizes; a cheaper rung takes over where its picture is within `tolerance` (default 0.05) of the richer one. Cached by key.

### Agents

`CrowdAgent` holds the clip, phase, rate and tint (simulation state, fixed step). `CrowdWander` (random goals in a region, pauses on the idle
clip) and `CrowdPath` (a loop of points) move the entity at the clip's foot speed; both are deterministic. A game can move the entity itself and
call `agent.play(name)`.

### Commands

`crowd.stats` (agents per rung, VAT instances and full instances per model), `crowd.list`, `crowd.spawn`, `crowd.play`; and the perspective's
`perspective.force` to hold agents at one rung (`?force=vat` in the sample).

## The detail chain of a crowd's figure

One rule orders the rungs of every figure, whatever the model: the **full** figure above the impostor's cell size in pixels, **impostors of the same model** beyond that, then a point.
There is no pool of different "reduced" figures between them (nothing that neighbours could differ in). `crowdChain` of `@ferret/perspective` builds the ladder; the full
figure's threshold is derived from the impostor's cell (`fullFigurePx(cell)`: 120 px for the default 128 px cell), so an impostor is never drawn bigger than its cell and a
full figure never smaller than the picture it replaces:

```ts
import { crowdChain, fullFigurePx, rangeForPx } from '@ferret/perspective';
entity.add(Perspective, { ladder: crowdChain({ cell: 128 }) });   // full >= 120 px, impostor down to 6 px, point below
```

`midPx` adds a GPU-skinned (VAT) rung between them for games that keep one; `rangeForPx(perMetreAt1m, size, px)` and `pxAtDistance` turn a threshold into a distance and back.

## Shipped bakes: no baking during the splash

The VAT bake (bone matrices of the person recipe's clips: stand, talk, sit, crouch, the walk, the posture blends, with the micro-motion in them) takes tens of seconds in a browser.
It is a build-time product: `tools/perspective/bake-vat.mjs` makes it by the same code the game would run and puts `vat/<id>.vat` into the figure's package, with the item's
`vat` entry (`recipe`, `clips`, `bones`, `signature`). A game asks `resolveVatBake` for it: the persistent cache first, then the shipped sources, then (the fallback) the bake in the browser.

```ts
import { resolveVatBake, libraryBakeSource, urlBakeSource } from '@ferret/crowd';
const vat = await resolveVatBake({ key, bones, cache, sources: [libraryBakeSource(lib, 'tommy-1'), urlBakeSource({ base: gameUrl, dir: 'assets/vat' })],
  compute: () => bakeInBrowser() });   // vat.from: 'cache' | the source's name | 'computed'
```

A shipped file is used only when it fits: the key's recipe, the rig's signature (bones and their hash) and the clips are those asked for, and the bytes unpack to that many bones;
otherwise the next source is tried. `bakePersonRig` and `personBakeKey` (the same module) are the recipe and its key. `tools/character/publish-character.sh --vat <spec>` ships the bake with a new character.

## Numbers (RTX 3050 laptop, 2026-11-11)

- 300 people of four library characters (man in jacket, business lady, viking, norna) at vsync from near to the horizon; VAT figures 3.8-4.9 k
  triangles; the whole scene 1.1-1.4 M triangles.
- 150 MetaHuman people with strand hair (girl, wizard, witch): 17-18 ms with four full figures near (the full figure's hair is ~0.7 M triangles).
- Measured thresholds of the library people: full above ~8 px, VAT above ~7 px, impostor above ~0.5 px.

## The sample

`examples/crowd` (`?ids=a,b,c&n=1000&size=300&force=vat`) and `node tools/crowd/check.mjs <outDir> [query]`, which serves the sample and the
library, opens it on the video card and shoots it from near to far with the stats of each view.

## Traps found on the way

- Babylon applies a thin instance's matrix *before* the mesh's world matrix, and glTF roots mirror z: the VAT set writes `W * A * W^-1`.
- WebGL has 16 vertex attributes: the VAT rung uses 4 bone influences and packs the fade and the tint into one attribute.
- The asset cache makes unskinned parts `InstancedMesh`es of one source: their geometry is read from `sourceMesh`.
- A decimated mesh must be a new mesh: the source's geometry is shared with other instances of the same file.
