@ferret/crowd
Classes
CrowdAgent class
class CrowdAgent extends Component<CrowdAgentParams> implements ClipStateThe crowd state of an agent: which clip, where in its loop, how fast. It is simulation state (fixed step); the rungs read it to draw. A behaviour
(CrowdWander, CrowdPath, or the game's own) moves the entity and sets clip / rate.
clip: number | |
clipName: string | |
phase: number | 0..1, where in the loop the agent is at time 0 |
rate: number | playback rate (1: as baked) |
tint: [number, number, number] | |
clipNames: string[] | the clip names of the model (set by the model when the agent is spawned) |
clipSpeeds: number[] | travel speed of each clip at rate 1, m/s |
onAttach() | |
play(name: string): void | switch clip by name (the loop keeps its phase) |
get footSpeed(): number | the speed in m/s at which the current clip's feet do not slide |
packages/crowd/src/agent.ts:30
CrowdModel class
class CrowdModelEverything the rungs of a crowd need for one character, made once: the vertex-animation set (from mid), the animated impostor atlas (all
clips side by side, from mid too), the point colour and size, and a pool of full instances. Agents of the model share all of it.
readonly clips: CrowdClip[] | |
readonly impostorFrames: [number, number][] | frames of each clip in the impostor atlas: [start, frames] by clip index |
ladder: PerspectiveLevel[] | |
thresholds: CrowdThresholds | null | the measured thresholds the ladder was made from (null: the default ladder) |
time: number | the crowd time the rungs show (the world's simulated time; set by the crowd every frame) |
get key(): string | |
get clipNames(): string[] | |
get radius(): number | |
get centre(): [number, number, number] | |
get look(): { color: [number, number, number]; fill: number } | |
static async prepare(scene: BABYLON.Scene, o: CrowdModelOptions): Promise<CrowdModel> | |
vatRep(node: BABYLON.TransformNode, agent: ClipState & { tint?: [number, number, number] }): Representation | the vertex-animation representation of an agent |
vatLowRep(node: BABYLON.TransformNode, agent: ClipState & { tint?: [number, number, number] }): Representation | null | the coarser vertex-animation representation (null when the model has none) |
fullRep(node: BABYLON.TransformNode, agent: ClipState): Representation | the full-detail representation of an agent: takes a pooled instance while shown, gives it back when off |
impostorFrame(agent: ClipState): number | the impostor frame (index into the atlas) of an agent now |
get fullInUse(): number | for stats: full instances in use / ready |
get fullPool(): number | |
dispose(): void |
packages/crowd/src/model.ts:86
CrowdPath class
class CrowdPath extends Component<CrowdPathParams>Walks a closed path of points at the walk clip's foot speed.
heading: number | |
onAttach() | |
onFixedUpdate(dt: number) |
packages/crowd/src/agent.ts:127
CrowdRng class
class CrowdRngA seeded generator (the same seed gives the same crowd on every machine).
constructor(seed: number) | |
next(): number | |
range(a: number, b: number): number |
packages/crowd/src/agent.ts:6
CrowdService class
class CrowdService implements ServiceThe crowd service: the models, their agents, the time the rungs show. It owns nothing of the simulation (agents are entities with components that
move in the fixed step); in update it gives every model the world's simulated time, so every rung of every agent shows the same moment.
readonly name: "crowd" | |
readonly models: Map<string, CrowdModel> | |
readonly agents: Map<string, { entity: Entity; model: CrowdModel; }> | |
constructor(readonly backend: BabylonBackend) | |
init(world: World): void | |
addModel(model: CrowdModel): CrowdModel | |
update(): void | Called once per rendered frame. |
stats(): { agents: number; byRung: Record<string, number>; models: { key: string; agents: number; vat: number; full: string }[] } | agents per rung of the ladder, per model, and the draw cost of the shared rungs |
dispose(): void |
packages/crowd/src/crowd.ts:11
CrowdWander class
class CrowdWander extends Component<CrowdWanderParams>Walks between random points of a region at the walk clip's foot speed, turning smoothly, pausing (idle clip) at each goal. Deterministic: the goals come from the seed, the movement from the fixed step.
heading: number | |
onAttach() | |
onFixedUpdate(dt: number) |
packages/crowd/src/agent.ts:75
VatSet class
class VatSetEvery agent of one crowd model at the vertex-animation rung. template is an instance of the model's mid-detail source kept at the origin and hidden; its skinned meshes become the instanced meshes. Materials that are not PBR or standard (a custom shader) are replaced by fallback(mesh) (default a PBR material of the mesh's vertex colours), because the baked skinning lives in Babylon's own shaders.
readonly meshes: BABYLON.Mesh[] | |
readonly manager: BABYLON.BakedVertexAnimationManager | |
readonly texture: BABYLON.RawTexture | |
time: number | the crowd's time for the frames (set by the model each frame) |
readonly triangles: number | triangles of one instance after the decimation |
readonly cell: number | the grid cell the solid meshes were merged on, metres (0: not simplified): the geometric error of this rung |
static async create(scene: BABYLON.Scene, template: BABYLON.TransformNode, bake: VatBake, o: { fallback?: (m: BABYLON.Mesh) => BABYLON.Material; targetTriangles?: number; parts?: BABYLON.Mesh[]; share?: VatSet } = {}): Promise<VatSet> | a VAT set, its meshes simplified first (asynchronous: the simplifier works in steps) |
add(node: BABYLON.TransformNode, agent: ClipState & { tint?: [number, number, number] }): Representation | a representation of one agent at this rung |
get active(): number | |
dispose(): void |
packages/crowd/src/vat.ts:278
Functions
bakeVat function
function bakeVat(root: BABYLON.TransformNode, clips: VatClipSource[]): VatBakeBake the clips of a skinned model (an instance in the scene, at the origin). Root motion is taken out of every frame (the agent's node moves instead) and measured as the clip's speed; a clip made in place gets its speed from the stance of its feet.
packages/crowd/src/vat.ts:56
clipTime function
function clipTime(clip: CrowdClip, s: ClipState, t: number): numberSeconds into the agent's loop at time t (0 <= result < duration).
packages/crowd/src/clock.ts:31
crowdFrame function
function crowdFrame(clip: CrowdClip, s: ClipState, t: number): numberThe baked frame (fractional, within the clip: 0 <= f < frames) at time t.
packages/crowd/src/clock.ts:39
crowdModelFromLibrary function
async function crowdModelFromLibrary(scene: BABYLON.Scene, lib: AssetLibrary, id: string, clips: Record<string, string>, o: Partial<Omit<CrowdModelOptions, 'mid' | 'full' | 'clips'>> & { mid?: LibraryTier; full?: LibraryTier | false } = {}): Promise<CrowdModel>A crowd model of a library character: the vertex animation and the impostor from tier mid (default 'low'), full instances from full (default 'desktop').
packages/crowd/src/library.ts:24
crowdSourceFromLibrary function
async function crowdSourceFromLibrary(lib: AssetLibrary, id: string, clips: Record<string, string>, o: { tier?: LibraryTier; name?: string } = {}): Promise<CrowdSource>A crowd source from the asset library: an instance of character id at tier with its clips bound. clips maps the agent's clip names to the
library's clip ids ({ walk: 'cc-clips/Walk_Fwd', idle: 'cc-clips/Idle' }); the character's compatible clip sets are searched.
packages/crowd/src/library.ts:10
decimateForCrowd function
async function decimateForCrowd(meshes: BABYLON.Mesh[], target: number): Promise<{ meshes: BABYLON.Mesh[]; triangles: number; cell: number }>Fewer triangles for the middle rung, whatever the source: vertices are merged per cell of a grid (the first vertex of a cell stands for it, with its normal, uvs and skin weights), triangles that collapse are dropped. Every mesh of the model shares the cell size, chosen as the smallest that brings the whole model under target triangles. Returns the triangles after.
packages/crowd/src/vat.ts:110
defaultCrowdLadder function
function defaultCrowdLadder(o: { full?: boolean; impostor?: boolean; low?: boolean } = {}): PerspectiveLevel[]A default ladder for a person-sized model (projected size of the bounding sphere in pixels). Measure your own with tools/perspective/thresholds.mjs.
packages/crowd/src/model.ts:70
ladderOf function
function ladderOf(t: CrowdThresholds, has: { full: boolean; impostor: boolean; low?: boolean }): PerspectiveLevel[]The ladder from measured thresholds: full above mesh, the vertex animation above impostor, the impostor above point, the point above none; each rung a little below the one before.
packages/crowd/src/model.ts:56
measureCrowdLadder function
async function measureCrowdLadder(inp: CrowdMeasureInput): Promise<MeasuredThresholds & { vatLow?: number; curves?: Record<string, [number, number][]> }>packages/crowd/src/measure.ts:33
packVat function
function packVat(b: VatBake): Uint8Arraybytes of a bake, for a cache (version, bones, frames, clips json, floats)
packages/crowd/src/vat.ts:91
rigidAsSkinned function
function rigidAsSkinned(root: BABYLON.TransformNode, skeleton: BABYLON.Skeleton, skinned: BABYLON.Mesh): BABYLON.Mesh[]Parts that ride a bone as child nodes (a hat, a weapon in a socket, strand hair) become meshes skinned to that one bone, in the frame of the skinned meshes, so the baked animation moves them too. The model is put in its rest pose first.
packages/crowd/src/vat.ts:197
skinnedMeshes function
function skinnedMeshes(root: BABYLON.Node): { meshes: BABYLON.Mesh[]; skeleton: BABYLON.Skeleton }the skinned meshes of a model and their skeleton
packages/crowd/src/vat.ts:36
spawnCrowdAgent function
async function spawnCrowdAgent(world: World, model: CrowdModel, o: SpawnAgentOptions): Promise<Entity>An agent of model: an entity with a ladder of every rung the model has, the agent state and an optional behaviour.
packages/crowd/src/crowd.ts:66
unpackVat function
function unpackVat(bytes: Uint8Array): VatBake | nullpackages/crowd/src/vat.ts:97
vatParts function
function vatParts(template: BABYLON.TransformNode): BABYLON.Mesh[]the parts a VAT set is made of: the skinned meshes and the rigid parts on bones made skinned (made once per model, shared by its sets)
packages/crowd/src/vat.ts:231
vatSettings function
function vatSettings(clip: CrowdClip, s: ClipState, t: number): [number, number, number, number]The per-instance settings of Babylon's baked vertex animation for this agent at time t: (start frame, end frame, offset, speed). The speed is 0 and the offset is the frame itself, so the shader shows exactly start + floor(crowdFrame) (its own time formula skips frame 0 after the first loop); the crowd writes these every frame with the instance matrices, so every rung shows the same frame.
packages/crowd/src/clock.ts:48
vertexColourMaterial function
function vertexColourMaterial(scene: BABYLON.Scene, m: BABYLON.Mesh): BABYLON.PBRMateriala PBR material of the mesh's vertex colours (for meshes drawn by a custom shader, such as strand hair)
packages/crowd/src/vat.ts:375
Interfaces
ClipState interface
interface ClipStateThe part of an agent's state the clocks need.
clip: number | |
phase: number | 0..1, where in the loop the agent is at time 0 |
rate: number | playback rate (1: as baked) |
packages/crowd/src/clock.ts:22
CrowdAgentParams interface
interface CrowdAgentParamsclip?: string | the crowd model's name of the clip to play (index into its clips by name, resolved at attach) |
phase?: number | 0..1, where in the loop the agent starts |
rate?: number | playback rate (also scales the travel speed of a walking behaviour, so the feet keep their place) |
tint?: [number, number, number] | a colour multiplied into the model at every rung (linear rgb, default white) |
clips?: { name: string; speed: number }[] | the model's clips (names and foot speeds), given by spawnCrowdAgent |
packages/crowd/src/agent.ts:13
CrowdClip interface
interface CrowdClipOne clip as baked into a crowd model: where its frames start in the baked texture, how many, at what rate.
name: string | |
start: number | first baked frame (row of the vertex-animation texture) |
frames: number | baked frames of the loop |
duration: number | seconds of one loop at rate 1 |
speed: number | travel speed in m/s at rate 1 (0: in place); an agent moving at speed * rate has feet that do not slide |
packages/crowd/src/clock.ts:9
CrowdClipSpec interface
interface CrowdClipSpecname: string | |
fps?: number | baked frames per second of the vertex animation (default 30) |
impostorFrames?: number | frames of this clip in the animated impostor (default 12 for a moving clip, 4 in place) |
speed?: number | m/s at rate 1; default measured (see bakeVat) |
packages/crowd/src/model.ts:16
CrowdMeasureInput interface
interface CrowdMeasureInputThe thresholds of a crowd model's ladder, measured in the scene it lives in: one sample of each rung (the full figure, the
vertex-animation instance, the impostor, the point) drawn alone into a render target at the same moment of the first clip, from four sides,
at a ladder of sizes; a cheaper rung takes over at the smallest size where its picture is within tolerance of the richer one
(blurError, as @ferret/perspective measures its models). Runs before any agent exists, so nothing else is in the pictures.
scene: BABYLON.Scene | |
vat: VatSet | |
vatLow?: VatSet | null | the coarser VAT set (its threshold comes from its cell too) |
full: { root: BABYLON.TransformNode; meshes: BABYLON.AbstractMesh[]; rep: Representation; pose(frame01: number): void } | null | a full instance (posed by pose) or null when the model has no full rung |
atlas: Uint8Array | null | |
impostorFrame(frame01: number): number | atlas frame of the first clip's moment frame01 |
centre: [number, number, number] | |
radius: number | |
color: [number, number, number] | |
fill: number | |
tolerance?: number | |
maxPx?: number | |
errorPx?: number | pixels a merged cell of the VAT rungs may cover (default 1) |
packages/crowd/src/measure.ts:11
CrowdModelOptions interface
interface CrowdModelOptionskey: string | names the model and its content with a version (cache key of the bakes, and agents of one key share one atlas and one VAT) |
clips: (string | CrowdClipSpec)[] | |
mid: CrowdSource | the lighter instance the vertex animation and the impostor are made from (stays hidden at the origin) |
full?: () => Promise<CrowdSource> | makes one more full-detail instance for an agent near the camera (pooled: at most maxFull) |
maxFull?: number | full instances kept ready (the budget of the full rung; default 8) |
impostor?: ImpostorBakeOptions | false | impostor bake options (default flat, upper hemisphere, 8 views of 96 px); false: no impostor rung |
cache?: CacheBackend | the persistent cache for the bakes (@ferret/assets) |
vatTriangles?: number | triangles of the vertex-animation rung per agent (the mid source is simplified down to it; default 6000) |
vatLowTriangles?: number | triangles of the coarser vertex-animation rung (default 1200; 0: none) |
measure?: boolean | measure the ladder in the scene (default true; cached by key); false: defaultCrowdLadder |
tolerance?: number | the error a cheaper rung may have against the richer one (default 0.05) |
ladder?: PerspectiveLevel[] | the ladder of every agent of this model; given, nothing is measured |
packages/crowd/src/model.ts:26
CrowdPathParams interface
interface CrowdPathParamspoints: [number, number][] | points (x, z) walked in order, looping |
walk: string | |
from?: number | start at this point index |
turnRate?: number |
packages/crowd/src/agent.ts:117
CrowdSource interface
interface CrowdSourceA loaded instance of a character: its root (at the origin) and its animation groups by clip name, bound to that root.
root: BABYLON.TransformNode | |
groups: Record<string, BABYLON.AnimationGroup> | |
dispose?(): void | dispose the instance (the model calls it for pooled full instances it drops) |
packages/crowd/src/model.ts:9
CrowdWanderParams interface
interface CrowdWanderParamsarea: { x: number; z: number; halfX: number; halfZ: number } | the region: centre x, z and half sizes |
walk: string | clip names: walking and standing |
idle?: string | |
pause?: [number, number] | seconds of a pause at a goal (min, max); 0 never stops |
turnRate?: number | degrees per second the agent turns at most |
seed?: number |
packages/crowd/src/agent.ts:58
SpawnAgentOptions interface
interface SpawnAgentOptionsname?: string | |
position: [number, number, number] | |
heading?: number | radians about +Y; 0 faces +Z |
clip?: string | |
phase?: number | |
rate?: number | |
tint?: [number, number, number] | |
wander?: CrowdWanderParams | a built-in behaviour (or none: the game moves the entity and sets the agent's clip) |
path?: CrowdPathParams |
packages/crowd/src/crowd.ts:51
VatBake interface
interface VatBakebones: number | |
frames: number | total baked frames (rows) |
data: Float32Array | (bones + 1) * 16 floats per frame |
clips: CrowdClip[] |
packages/crowd/src/vat.ts:24
VatClipSource interface
interface VatClipSourceThe vertex-animation rung of a crowd. A skinned model's bone matrices are baked for every frame of the chosen clips into one float texture in the layout of Babylon's BakedVertexAnimationManager ((bones + 1) x 4 texels per frame row); the model's own meshes and materials then draw every agent as a thin instance, skinned on the GPU from the texture. One draw call per mesh of the model for all its agents; the CPU writes one matrix, one frame number, a fade and a tint per agent per frame.
name: string | |
group: BABYLON.AnimationGroup | |
fps?: number | baked frames per second (default 30) |
maxFrames?: number | at most this many frames of the loop (default 48): a long clip is sampled more sparsely |
speed?: number | travel speed in m/s at rate 1; default: measured from the clip's root motion, or from the feet when it is in place |
packages/crowd/src/vat.ts:13
Types
CrowdThresholds type
type CrowdThresholds = MeasuredThresholds & { vatLow?: number; curves?: Record<string, [number, number][]> }Measured thresholds of a crowd model: the perspective's, and vatLow (below it the coarser VAT rung is within the tolerance of the full figure).
packages/crowd/src/model.ts:53