# Idle people

# Idle people

`@ferret/micromotion` keeps the people of a scene alive when nothing is asked of them. A person who stands or sits by his place breathes, blinks, shifts his weight, looks at what
draws the eye, gestures while he talks, scratches, checks a watch, walks a few steps and comes back, and reacts when something happens near him (a blast, an impact, a fire, a shout).
It is built for the people of a scene that are *not* the player and not in a scripted animation: bystanders, a crowd that waits, someone who sits and watches, someone who holds a camera.

The module is a library of numbers and curves. It knows nothing of Babylon; the pose layer works on the arrays of the humans rig (`Rig` and `Pose` of `@ferret/humans`).

## The layers

| layer | file | what it does |
|---|---|---|
| profile | `profile.ts`, `profiles.ts` | a person's temperament, role, repertoire, props, anchors, interests and reactions as JSON, with a validator that names the path of a fault |
| sim | `sim.ts`, `gaze.ts`, `life.ts`, `speech.ts` | pure numbers in the fixed step: the activity scheduler, the gaze, blinks, breathing, walks about the anchor, sitting and standing, beats and nods on speech |
| react | `stimulus.ts` | what happens near a person: strength by distance, the delay of sound (343 m/s), sight only in the gaze cone and unoccluded, a reaction from the profile table 150-300 ms later, eyes first |
| ai | `ai.ts` | the person's own AI: habits that run beside the activities, a mode, orders, a walk to a place, settings changeable while he lives, and `explain` |
| link | `motion.ts` | the words of the motion language for the people of a session, and the events they send back |
| pose | `pose.ts`, `clips.ts` | the person's numbers onto the humans rig: breathing and sway, gaze (eyes, head, chest, body), gestures with hand IK, props in hand, the seat, fingers, the face as ARKit weights; clips as masked layers |
| lod | `lod.ts` | a level by size on the screen and a budget of people at the dear levels |
| service | `service.ts` | a `MicroSession` of people, the bus events it listens to, the `micro.*` commands and the manifest block |

Everything the sim decides comes from the person's seed, so every peer of a networked game and the Unreal build make the same choices. Only the seed, the profile name and the anchors need
to be replicated; the stimuli come from events that are already replicated.

## A first person

```ts
import { MicroSession, profile } from '@ferret/micromotion';

const micro = new MicroSession();
micro.spawn('guard', 'bystander', 42, { pos: [3, 0, 1], facing: Math.PI });   // a shipped profile, a seed, a place (his anchor)
micro.setTarget({ id: 'door', pos: [0, 1.5, 6], tags: ['action'], speed: 0 });  // something that can draw his eye
// in the fixed step:
micro.step(1 / 60);
// in the frame, for a person at the near level, on top of a clip pose (an idle or a walk):
import { applyMicro } from '@ferret/micromotion';
const report = applyMicro(rig, pose, micro.person('guard').out, micro.person('guard').profile, { time: micro.t, seed: 42, lod: 'near' });
// report.face: the ARKit weights for the face (blink, eyes, the face at rest and in reaction)
```

A person put at a place is anchored there: his home and the way he faces are the place given. A profile of your own is a JSON object (`validateProfile` tells what is wrong); `profile('name')`
returns a copy of a shipped one to edit.

## Profiles

A profile holds:

- `temperament` (energy, nervousness, expressiveness, mood) and `handedness`;
- `repertoire`: activities and their weights (`point`, `talk-gesture`, `check-watch`, `rub-beard`, `pace`, `sit-down`, `stand-up`, `megaphone-shout`, `follow-action` ...); the scheduler picks by weight, cool-down, recency, fatigue and what the scene is doing, and a person never stays still longer than `maxStill`;
- `props`: what he holds (a camera, a loudspeaker), with a rest and a use target for each hand;
- `anchors`: home, facing, radius he walks about, and a seat;
- `interests`: what draws his eye (tags on the gaze targets);
- `reactions`: for each stimulus kind, the reactions he may show with weights.

Shipped presets: `director` (sits and speaks through a loudspeaker prop), `cameraman` (holds a camera and follows the action), `posing-actor`, `bystander`, `crowd-waiting`. They are starting points.

## Stimuli

Feed the module through the bus (`session.attach(world.events)` listens to `explosion:blast`, `physics:impact`, `physics:break`, `vfx:ignite`, `vfx:out`, `combustion:out`, `take:start`, `take:cut`,
`scene:good`, `scene:bad` and `micro:stimulus`) or by command (`micro.stimulus`). A person who perceives a stimulus first glances toward it, then reacts from his profile's table
(flinch, duck, startle, stand up, cheer, despair, anger). A blast of 25 kg at 25 m is a startle after about 0.3-0.45 s; at 250-300 m it is a look; far past that it is not perceived.

## Speech

`say(person, { text, duration, shout })` places a beat gesture and a head nod on the line's stresses (from the text, or the `stresses` you give); a shouted line raises the loudspeaker prop for its whole length.
Lip-sync is not in this module.

## Clips

The module's gestures are curves made in code. A game or a library of captured or authored motion can bring clips for the same gesture ids: `new ClipBank().add(clip)` then `applyMicro(..., { clips })`.
A clip is played as a masked layer over the pose (the bones it names, blended in and out); the variant, speed and amplitude come from the person's seed; a clip made for one hand is mirrored for the other
(`mirrorPose`, `mirrorClip`, done on world rotations so it does not depend on how the rig's local axes lie).

## The person's own AI

Under the activity scheduler every person has **habits**: small things the body does without deciding to, each on its own clock and from its own stream of the seed (switching a habit off or tuning it never changes
which activities he chooses).

| habit | when | what |
|---|---|---|
| `leg-swing` | seated | a leg swings a little, the knee stays, the foot comes off the floor a few centimetres |
| `foot-tap` | any posture | the other foot taps |
| `head-turn` | any posture | the head turns a few degrees to one side and back, with a touch of tilt |
| `weight-shift` | standing | the weight goes from foot to foot: pelvis and shoulders tilt, each foot is eased off the floor in turn |
| `blink` | always | the eyelids, 10 to 20 times a minute |

How often and how wide comes from the **temperament** (a nervous person swings, taps and turns far more than a calm one; the energy sets the size) and grows up to 60 % as the time since anything else moved him nears
the profile's `maxStill`. A gap is jittered between half and one and a half of its mean, so "sometimes" is a promise: there is no minute without. Habits of one group (the legs, the head) do not overlap, none starts
while he walks, changes posture or reacts, and a gesture that already moves his weight or feet keeps those habits waiting.

A profile fixes any of it: `habits: { 'leg-swing': { perMin: 8 }, 'head-turn': { amp: 0.5 }, blink: { rate: 1.3 } }` (`perMin` sets the rate, `rate` and `amp` are factors, `enabled: false` switches it off) and
`mode`. All of it can be changed while he lives:

| control | does |
|---|---|
| `micro.mode {id, mode}` | `auto` (habits and activities), `habits` (habits only; activities wait for orders), `off` (nothing of his own; breathing, blink and reactions to what happens go on) |
| `micro.habit {id, habit, perMin?, rate?, amp?, enabled?}` | tune one habit; `perMin: null` goes back to the temperament's rate |
| `micro.temper {id, energy?, nervousness?, ...}` | change the character; the rates follow at once |
| `micro.do {id, name, dur?, now?}` | order an activity or a habit; it starts when he is free (`now` drops what he is doing); an order that does not fit his posture is refused and logged |
| `micro.goto {id, pos}` | walk to a place (he stands up first); the place becomes his home. The chair stays where it was, so he sits again only back at it |
| `micro.explain {id}` | the mode, each habit's rate, time to the next and what blocks it, the orders, and the chance of each activity he may choose next |

In code the same are `setMode`, `setHabit`, `setTemperament`, `order`, `walkTo` and `explainPerson`.

## With the motion language

`linkMotion(session, bridge)` (`motion.ts`) gives programs of `@ferret/motion` the words to order people and ask them things, and delivers what they do as events. It takes the bridge as a shape, so the module does not
depend on the language.

```lisp
(defmotion patrol (me a b)
  (loop (micro-walk me a 0 a) (wait 1)
        (micro-walk me b 0 b) (wait 2)))
(patrol self 1 4)
```

```ts
const rt = new MotionRuntime({ seed }), bridge = new MotionBridge(rt), micro = new MicroSession();
linkMotion(micro, bridge);                       // before the programs are loaded: the language checks names when it loads
bridge.load(patrolText);
runRoutine(bridge, 'guard', '(patrol self 1 4)');   // `self` is his id; or give a person a `routine` in the manifest and call startRoutines(bridge, manifest.people)
```

Words: `(micro-walk who x y z)` lasts until he is there (the value is `true`, or `false` if he is gone or could not go), `micro-do`, `micro-mode`, `micro-rate`, `micro-habit who habit on|off`, `micro-amp`, `micro-temper`,
`micro-say`, `micro-stimulus kind x y z [size]`, and `micro-posture`, `micro-activity`, `micro-moving`, `micro-habits`. Events for `wait-event` and `on`, the payload being the person's id: `micro:activity`,
`micro:reaction`, `micro:posture`, `micro:habit`, `micro:walk`, `micro:arrived`, `micro:refused`, `micro:removed`.

A lasting word is a statement (its value is the program's, not an argument's). Put something after the `wait` that ends a `seq` that holds an `on`, or the handler dies with the frame.

## Baked loops for the far planes

When a character is created its own behaviour is recorded: `bakePerson(rig, base, profile, seed)` runs the person at rest (habits, gestures, breathing, the gaze; no props, no walks) and keeps a seamless loop of the body's
pose for standing and, with a seat, for sitting. `poseOf(rig, pose, person, { lod, time, seed, baked })` is the one call for the frame: the **near level is always live** (a recording knows nothing of the
objects around the person and can cut through them or break the physics), the middle and far levels play the loop, each person at a phase of his seed. A person who reacts, speaks, walks, changes posture, holds a prop or has
an order waiting is live at every level (`loopFor` says when a loop may be used). Measured: the far pose is about 0.001 ms from a loop against about 0.04 ms live. In Unreal the loops become animation sequences.

## Levels of detail

`screenHeightPx` and `assignLods` give each person a level (`near`, `middle`, `far`, `crowd`, `off`) by his size on the screen, within a budget (`near` 6, near and middle 20 by default). The sim runs for everyone, whatever the level, so
a person who comes into view is where his numbers put him. `near` poses everything; `middle` leaves out fingers and face; `far` poses the body only, every third frame; `crowd` belongs to the crowd's baked clips; `off` is not posed.

Measured on the development machine (plain node, one core; the viewer renders on an NVIDIA RTX 3050): the sim costs about 1.3 microseconds per person per fixed step; the near pose about 0.09 ms per person; 20 people at the
budget's mix about 1.1 ms per frame.

## Commands and the viewer

`registerMicroCommands(host, session)` gives the `micro.*` commands: `profiles`, `profile`, `validate`, `spawn`, `remove`, `list`, `inspect`, `anchor`, `target`, `stimulus`, `event`, `take`, `say`, `step`, `activities`, `log`, and the AI: `habits`, `mode`, `habit`, `temper`, `do`, `goto`, `explain`.
A level's manifest may carry a `micro` block (`people`, `targets`, `take`), built with `sessionFromManifest`.

The viewer page `?micro` (build with `node tools/build.mjs viewer`) shows people of the humans module driven by a session and adds `micro.stage` (a sample set), `micro.add`, `micro.camera`, `micro.screenshot`,
`micro.capture` (frame-exact video on simulated time) and `micro.render`.

## Unreal

The sim, the AI, react, profiles and the session translate to C++ like the other logic modules; the pose layer, the clip player and the language link (which runs on the game's motion runtime) are given by the FerretRuntime plugin (anim nodes: layered blend per bone, LookAt, Two-Bone IK,
MetaHuman face curves). The same seed gives the same activity log in both.

## In a simulated crowd (Dunkirk)

`examples/dunkirk` gives each man a `PersonState` (`newPerson`, `stepPerson`) next to his simulation state; the crew of a ship uses `profile('bystander')` and a posture activity `'walk'` so they never sit or lie. Only the figures drawn in full (the near and middle rings) are posed: before each render the game resets the bones it touched last frame, then adds the person's offsets (`sampleRot`, `out.gestures`, `out.gaze`, the breath) on top of the playing clip. Offsets are written to bones through a small `fresh`/`done` mark so they never pile up from frame to frame.

Hands: the library's standing clip holds the arms out with the fingers spread, which looks like a scarecrow in a crowd. The game turns the upper arms a little inward (about 0.16 rad) and curls the fingers with `fingerCurl`; the signs of the rotations are found once per figure by probing the geometry (move the bone, see which way the hand goes), not assumed, because rigs differ.

Posture changes are cross-fades of the clip weights, never cuts. Keep a minimum linear rate under the exponential approach (`dt * 0.25`), or the old clip's long tail leaves a sliver that drops out in one frame. Note that the engine blends a clip at weight 0.99 differently from weight 1, so a lying body dips a few centimetres in the last third of a second; measure the head height per frame before trusting a blend.
