FERRETGame engine over Babylon.js
Ferret

@ferret/ai

NavMesh queries, crowd agents, steering and the small behaviours and trees NPCs run.

48 exports · source in packages/ai/src

Classes

Attention class

class Attention extends Component<AttentionParams>

Stops and turns to face a target that comes near (the player), resumes when it leaves; startTalk / endTalk hold the character in place regardless of distance. Roam is paused while attending. Emits ai:attend and ai:resume.

attending: boolean
talking: boolean
onAttach()
startTalk()
endTalk()
onFixedUpdate()

packages/ai/src/behaviours.ts:62

AutoWalk class

class AutoWalk

Walks a character along a NavMesh path to a point, on the fixed step, through the same movement code a person uses. It fails when the capsule falls through the ground, sticks in a wall or does not get there in time. This is the regression test of a level's collision.

constructor(private world: World, private character: () => Walker | null)
get active()
buildNav(o: { agentRadius?: number; agentHeight?: number; maxClimb?: number; maxSlope?: number; cellSize?: number }): NavServiceA NavMesh of the whole level for walking (the level's own may cover only the volume of its NavMeshBoundsVolume).
go(nav: NavService, goal: BABYLON.Vector3, timeout = 60): Promise<WalkResult>

packages/ai/src/autowalk.ts:16

BehaviorTree class

class BehaviorTree
readonly bb: Blackboard
lastStatus: Status
constructor(readonly root: BTNode, bb: Blackboard = {})
update(dt: number): Status
reset()

packages/ai/src/tree.ts:108

BTNode class

abstract class BTNode
abstract tick(ctx: TreeContext): Status
reset(): voidcalled when a running node is interrupted by a higher-priority branch

packages/ai/src/tree.ts:12

Follow class

class Follow extends Component<FollowParams>

Walk after an entity and stop distance short of it.

onAttach()
onFixedUpdate()

packages/ai/src/behaviours.ts:116

Roam class

class Roam extends Component<RoamParams>

Walk to random points within a radius of home, wait a while at each, repeat. Needs a NavAgent.

home: Vector3
active: booleana game or another behaviour may switch roaming off (talking, a cutscene)
onAttach()
onFixedUpdate(dt: number)

packages/ai/src/behaviours.ts:15

Functions

clipFor function

function clipFor(s: PostureState, id: number, table: Record<Posture, string[]> = CC_CLIPS): ClipChoice

the clip for a person: id picks among the variants of a posture, the same person always the same.

packages/ai/src/posture.ts:192

clipToBounds function

function clipToBounds(g: { positions: Float32Array; indices: Uint32Array }, bounds?: NavBuildOptions['bounds'])

cut the geometry to the box bounds: triangles are clipped against its six planes (a ground made of two big triangles is cut too)

packages/ai/src/nav-geometry.ts:111

collectGeometry function

function collectGeometry(meshes: BABYLON.AbstractMesh[]): { positions: Float32Array; indices: Uint32Array }

World-space triangles of the meshes, in the flat arrays recast takes.

packages/ai/src/nav-geometry.ts:30

cutBoxes function

function cutBoxes(g: { positions: Float32Array; indices: Uint32Array }, boxes?: NavExcludeBox[])

remove the parts of the geometry inside each box: a triangle is split by the box's six planes and the pieces outside are kept

packages/ai/src/nav-geometry.ts:67

fireActuator function

function fireActuator(world: World, actuator: string): BTNode

Run an actuator from the start: one impulse or one cycle (a stroke).

packages/ai/src/actuate.ts:20

goPosture function

function goPosture(s: PostureState, p: Posture)

order him into a posture now (a worker who bends to a task and rises from it): the change takes the time of the posture chain and goes on from the pose the body shows

packages/ai/src/posture.ts:167

initNavigation function

function initNavigation(opts: NavigationInit = {}): Promise<void>

Load the WebAssembly of recast-navigation (once). Await it before new NavService().

packages/ai/src/nav.ts:25

newPosture function

function newPosture(seed: number, posture: Posture = 'stand'): PostureState

packages/ai/src/posture.ts:50

poseKeys function

function poseKeys(s: PostureState): Array<{ posture: Posture; weight: number }>

what the body shows now as a blend of key poses: the weights (summing to 1) of the postures to draw. A change of posture is a chain of poses the body passes through (stand, crouch, sit, lie), two neighbours in the chain blended by a smooth step, so a man lowers and rises instead of one picture dissolving into another.

packages/ai/src/posture.ts:150

poseOf function

function poseOf(s: PostureState): { posture: Posture; amount: number }

what the body shows now: a posture and how far into it (0 standing, 1 all the way down), through the change under way. A change between two low postures goes up out of the first and down into the second. The game draws posture at amount (a pose blended with standing by it).

packages/ai/src/posture.ts:131

setCommand function

function setCommand(world: World, actuator: string, value: number | ((bb: Blackboard) => number)): BTNode

Set an actuator's command (a throttle, a lever); the value may be read from the blackboard.

packages/ai/src/actuate.ts:15

standUp function

function standUp(s: PostureState)

order him up (before he walks)

packages/ai/src/posture.ts:169

stepPosture function

function stepPosture(s: PostureState, dt: number, activity: Activity, o: { crowded?: number } = {}): PostureResult

Advance one person by dt seconds in the given activity. crowded: 0..1 how close the neighbours are (a sitting man in a crowd is unlikely, a lying one more so).

packages/ai/src/posture.ts:70

switchActuator function

function switchActuator(world: World, actuator: string, on: boolean): BTNode

Switch an actuator on or off.

packages/ai/src/actuate.ts:25

worldPos function

function worldPos(n: BABYLON.TransformNode): BABYLON.Vector3

The world position of a node, up to date even when nothing has rendered since it moved (Babylon caches the matrix per render id).

packages/ai/src/agent.ts:8

Interfaces

AttentionParams interface

interface AttentionParams
target?: stringthe entity to look at: found by name or tag (default tag "player")
radius?: numbercloser than this the character stops and turns to the target
leaveRadius?: numberstays interested until the target is this far (hysteresis; default radius * 1.3)
visible?: (from: BABYLON.Vector3, to: BABYLON.Vector3) => booleanwhether the character can see the target from here (smoke, fog, walls); a target that cannot be seen is not attended to. Default: always

packages/ai/src/behaviours.ts:47

ClipChoice interface

interface ClipChoice
clip: string
from: numberplay only this part of the clip, as fractions of its length (a lying man holds the end of Death_Backward and stirs within it)
to: number
pingPong: booleanplay back and forth over the part instead of looping it
loop: boolean

packages/ai/src/posture.ts:183

FollowParams interface

interface FollowParams
target?: string
distance?: numberkeep this far from the target
tolerance?: numberre-plan when the target moved more than this

packages/ai/src/behaviours.ts:107

PostureResult interface

interface PostureResult
canWalk: booleanthe person can walk now (standing, not changing); a walking order should wait for this and call standUp
wantsStep: booleana few steps about the spot would be natural now (a standing waiter shifting position): the game picks the point

packages/ai/src/posture.ts:62

PostureState interface

interface PostureState
posture: Posture
to: Posture | nullthe posture he is changing to (null when settled) and the time left in the change, s
change: number
changeTotal: numberthe whole time of the change under way, s
hold: numberseconds left in the current posture
fidget: numbera small happening now: weight shift, glance, stir; 0 when none, its time left in s
fidgetKind: 'none' | 'shift' | 'look' | 'stir' | 'scratch'
nextFidget: numbertime to the next fidget
rs: numberthe person's seed state

packages/ai/src/posture.ts:32

RoamParams interface

interface RoamParams
radius?: numberroam within this distance of the home point (default: where the entity starts)
home?: [number, number, number]
pause?: [number, number]seconds to wait at each stop: [min, max]

packages/ai/src/behaviours.ts:6

TreeContext interface

interface TreeContext
bb: Blackboard
dt: number

packages/ai/src/tree.ts:10

Walker interface

interface Walker

What the walk drives: a character's mesh (position), its yaw and its move input (CharacterMovement fits).

mesh: BABYLON.AbstractMesh
yaw: number
setMoveInput(dir: BABYLON.Vector3, run: boolean): void

packages/ai/src/autowalk.ts:6

WalkResult interface

interface WalkResult
goal: number[]
reached: boolean
reason: 'reached' | 'stuck' | 'fell' | 'no path' | 'timeout'
seconds: number
position: number[]
distanceLeft: number

packages/ai/src/autowalk.ts:10

Types

Activity type

type Activity = 'wait' | 'queue' | 'cover' | 'walk' | 'aboard'

packages/ai/src/posture.ts:11

Blackboard type

type Blackboard = Record<string, any>

packages/ai/src/tree.ts:8

Posture type

type Posture = 'stand' | 'talk' | 'sit' | 'crouch' | 'lie'

Posture AI for crowds: what a person who is not going anywhere does with his body. Each person is in one posture (stand, talk, sit, crouch, lie) for a while, then changes to another by a weight table that depends on what he is doing (waiting, queueing, taking cover), with the small happenings of real waiting in between: shifting weight, looking round, a few steps, a stir (a lying man turns over, lifts his head), getting up before he walks. Pure numbers (no engine): a seeded generator per person, a timer, the posture and the "doing" flags; the game maps posture and fidget to animation clips (clipFor) or to a vertex-animation pose, and moves the person when wantsStep gives a point. Deterministic from the seed, so the same crowd waits the same way on every peer.

packages/ai/src/posture.ts:10

Status type

type Status = 'success' | 'failure' | 'running'

A small behaviour tree runner (the equivalent of UE's Behavior Tree + Blackboard): composites, decorators and leaves tick every update and answer success, failure or running. A running leaf is resumed where it was. The blackboard is a plain object shared by the nodes. Pure logic, no Babylon.

packages/ai/src/tree.ts:7

Vec3 type

type Vec3 = { x: number; y: number; z: number }

packages/ai/src/nav-geometry.ts:27

Constants

bt const

const bt: { action: (fn: (ctx: TreeContext) => boolean | void | Status) => BTNode; condition: (fn: (bb: Blackboard) => boolean) => BTNode; sequence: (...kids: BTNode[]) => BTNode; selector: (...kids: BTNode[]) => BTNode; wait: (seconds: number | ((bb: Blackboard) => number)) => BTNode; not: (kid: BTNode) => BTNode; succeed: (kid: BTNode) => BTNode; guard: (cond: (bb: Blackboard) => boolean, kid: BTNode) =>  …

packages/ai/src/tree.ts:83

CC_CLIPS const

const CC_CLIPS: Record<Posture, string[]>

the clips of the Character Customizer set (cc-clips) for each posture; a game with other clips passes its own table

packages/ai/src/posture.ts:176

POSTURE_DOWN const

const POSTURE_DOWN: Record<Posture, number>

the time it takes to get from standing into a posture or back up out of it, s (a man sits down in two or three seconds, lies down in four; a change between two low postures goes up through standing and down again, taking both)

packages/ai/src/posture.ts:29

POSTURE_HOLD const

const POSTURE_HOLD: Record<Posture, [number, number]>

how long (s) a posture is held before he thinks again: [min, max]

packages/ai/src/posture.ts:26

POSTURE_WEIGHTS const

const POSTURE_WEIGHTS: Record<Activity, Partial<Record<Posture, number>>>

weights of the next posture by activity; a missing posture has weight 0

packages/ai/src/posture.ts:14