FERRETGame engine over Babylon.js
Ferret

@ferret/morph

Geometric and colour morphing: banks of states from clip frames or hinged parts, objects blended by programs of the motion language, one-draw-call GPU batches, far colour morphs, retopology, morph.* commands.

87 exports · source in packages/morph/src

Classes

ConformError class

class ConformError extends Error
constructor(message: string, readonly report: ConformReport)

packages/morph/src/conform.ts:53

CpuMorphView class

class CpuMorphView

one object drawn by the CPU path

readonly mesh: BABYLON.Mesh
readonly material: BABYLON.ShaderMaterial
updates: numberhow many times the vertex arrays were rewritten (a morph that has arrived costs nothing: this stops growing)
look: MorphLook
constructor(readonly scene: BABYLON.Scene, readonly bank: MorphBank, readonly object: MorphObject, name = `morph:${object.name}`)
refresh(force = false): voidcall once per frame (the node is the mesh itself: parent it or move it)
arrays(): BlendOutthe blended arrays now (for tests and the comparison with the GPU path)
dispose(): void

packages/morph/src/view.ts:130

FarMorph class

class FarMorph
constructor(readonly object: MorphObject, readonly reps: ReadonlyMap<number, Representation>)
stand(i: number): numberthe baked state that stands in for state i
pair(): { a: number; b: number; mix: number }the two impostors to draw and the mix between them, from the object's blend now
apply(rung: RepState, rungMix: number): voidDraw the far rung. rung is the ladder's own state for this object (on, in, out, off) and rungMix its cross-fade with the neighbouring rung; the two cross-fades are laid over each other: state B shows with its share of the mix, state A with the rest.

packages/morph/src/far.ts:13

GpuMorphBatch class

class GpuMorphBatch

the objects of one bank drawn by the GPU path: one mesh, one draw call, thin instances

readonly mesh: BABYLON.Mesh
readonly material: BABYLON.ShaderMaterial
readonly texture: BABYLON.RawTexture
readonly layout: BankTexture
uploads: numberhow many times the per-instance weight buffers were rewritten
look: MorphLook
readonly lookup: VertexLookup
constructor(readonly scene: BABYLON.Scene, readonly bank: MorphBank, name = 'morph:batch', lookup?: VertexLookup)
add(object: MorphObject, node: BABYLON.TransformNode): void
remove(object: MorphObject): void
get count(): number
refresh(): voidevery frame (it is also hooked to the scene's before-render): matrices always, the weight vectors of an object only when its blend changed
dispose(): void

packages/morph/src/view.ts:171

MorphBank class

class MorphBank
readonly states: MorphState[]
source: stringwhere the bank came from (a clip and a model, with their versions): a bank is re-baked when this changes
constructor(readonly vertexCount: number, readonly indices: Uint32Array)
get count(): number
has(name: string): boolean
indexOf(name: string): number
names(): string[]
get(name: string): MorphState
add(state: MorphState): numberadd a state (a name already used is replaced); the arrays are checked against the vertex count
remove(name: string): void
hash(): stringthe content hash of every state and the index buffer
validate(): MorphIssue[]
toJson(): unknownthe bank as JSON: arrays become plain number lists, so a small bank can be read and diffed by eye
static fromJson(j: any): MorphBank
toBinary(): Uint8ArrayThe bank as one binary file (what a host loads and the GPU upload reads), little-endian: 'FMRB' u32 version=1 u32 vertexCount u32 indexCount u32 stateCount u32 sourceLength source (utf8, padded to 4) indices u32[indexCount] per state: u32 nameLength name (utf8, padded to 4) u32 flags (1 normals, 2 colors) f32 scale f32 pivot[3] f32 positions[3n] (f32 normals[3n]) (f32 colors[4n])
static fromBinary(bytes: Uint8Array): MorphBank

packages/morph/src/bank.ts:24

MorphHost class

class MorphHost implements Service
readonly name: "morph"
readonly service: MorphService
readonly rt: MotionRuntime
readonly bridge: MotionBridge
constructor(readonly opts: MorphHostOptions)
init(world: World): void
fixedUpdate(dt: number): voidthe world's fixed step: the programs first (they say what to do), then the objects advance

packages/morph/src/host.ts:22

MorphObject class

class MorphObject
time: number
version: numberbumped whenever the blend or the tint can have changed, so a view redraws only then
constructor(readonly name: string, readonly bank: MorphBank, initial?: string)
set(state: string): voidjump to a state at once
to(state: string, seconds: number, curve = 'smooth'): MorphWaitmove to state over seconds along the ease curve, from the blend as it is now. A move already running is replaced and its waiters end.
stop(): voidfreeze the move where it is
hold(state: string, w: number): voidlay state over the result with weight w (0..1) until release; a state held twice has the last weight
release(state: string): void
pin(a: string, b: string, w: number): voidhold the object at exactly a mixed with b by w (a hand on the slider) until unpin; moves are ignored meanwhile
unpin(): void
tintTo(color: Color3, seconds = 0, curve = 'smooth'): MorphWaitthe colour factor, now or over seconds
step(dt: number): void
progress(): numberprogress of the running move, eased, 0..1 (1 when none runs)
moving(): boolean
weights(): Weightsthe weights of the states now: at most four, summing to 1, the largest first
dominant(): stringthe name of the state with the largest weight
weightOf(state: string): numberthe weight of one state in the blend now
tint(): Color3
snapshot(): MorphSnapshot
restore(s: MorphSnapshot): void

packages/morph/src/sim.ts:25

MorphService class

class MorphService
addBank(name: string, bank: MorphBank): void
bank(name: string): MorphBank
bankNames(): string[]
addModel(name: string, model: SkinnedModel): voiddata the commands bake from: a skinned model, a clip, a mesh of another topology
addClip(name: string, clip: ClipJson): void
addMesh(name: string, mesh: MeshData): void
fromClip(bank: string, model: string, clip: string, opts: FromClipOptions = {}): MorphBanka bank from frames of a clip of a registered model (the clip path of fromclip.ts)
conform(bank: string, state: string, mesh: string, opts: ConformOptions = {}): unknowna state of a bank's topology that looks like a registered mesh
spawn(name: string, bank: string, initial?: string): MorphObjectmake an object that wears a bank's states
object(name: string): MorphObject
has(name: string): boolean
objectNames(): string[]
remove(name: string): void
step(dt: number): voidevery fixed step
describe(name: string): unknownstate of one object, as the commands answer it
register(reg: RegisterFn): void

packages/morph/src/service.ts:15

Functions

add3 function

function add3: (a: Vec3, b: Vec3) => Vec3

packages/morph/src/math.ts:10

appliedPositions function

function appliedPositions(state: MorphState): Float32Array

the positions of a state with its scale and pivot applied

packages/morph/src/blend.ts:17

averageColors function

async function averageColors(root: BABYLON.TransformNode): Promise<(m: BABYLON.AbstractMesh) => [number, number, number, number]>

The average colour of the base-colour texture of every material below root (a light figure has one colour per vertex, so a textured part takes the mean of its texture; a material without a texture keeps its colour factor). The answer is a function for modelArrays and bankFromGroups.

packages/morph/src/babylon.ts:28

bankBytes function

function bankBytes(bank: MorphBank): { texture: number; arrays: number }

bytes of the bank in the texture and in the arrays, for morph.state

packages/morph/src/budget.ts:36

bankFromClip function

function bankFromClip(model: SkinnedModel, clip: ClipJson, opts: FromClipOptions = {}): MorphBank

a bank of the frames of clip, one state per chosen time

packages/morph/src/fromclip.ts:77

bankFromGroups function

function bankFromGroups(root: BABYLON.TransformNode, groups: BABYLON.AnimationGroup[], opts: FromClipOptions = {}, colorOf?: (m: BABYLON.AbstractMesh) => [number, number, number, number]): { bank: MorphBank; arrays: ModelArrays }

The frames of animation groups of a model as a bank. The model must be in the scene at its rest pose. For every group and chosen time (see FromClipOptions) the group is put at that time, the bones are brought up to date and the vertices are skinned (rigid parts follow their node). The states are named ${group}@${seconds}.

packages/morph/src/babylon.ts:73

bankFromMesh function

function bankFromMesh(name: string, positions: ArrayLike<number>, indices: ArrayLike<number>, colors?: ArrayLike<number>): MorphBank

a bank from the arrays of one mesh: its first state is the mesh itself, named name

packages/morph/src/source.ts:112

bankIsCurrent function

function bankIsCurrent(bank: MorphBank, model: SkinnedModel, clip: ClipJson): boolean

is the bank still what the clip and the model would bake now? (if not, bake it again)

packages/morph/src/fromclip.ts:126

bankSource function

function bankSource(model: SkinnedModel, clip: ClipJson): string

names the clip and the model by their content

packages/morph/src/fromclip.ts:119

blendImages function

function blendImages(a: ArrayLike<number>, b: ArrayLike<number>, w: number, out?: Float32Array): Float32Array

the colour blend of two baked pictures, texel by texel (RGBA8 or float, the same size): the reference of the far rung, also used for the dots on the horizon

packages/morph/src/far.ts:53

blendInto function

function blendInto(bank: MorphBank, weights: Weights, out: BlendOut, tint: readonly [number, number, number] = [1, 1, 1]): BlendOut

mix weights (they are normalised here) into out; tint multiplies the colours

packages/morph/src/blend.ts:61

boneFrames function

function boneFrames(model: SkinnedModel, clip: ClipJson | null, t: number): Bone[]

the model-space frames of every bone of the model at a time of the clip

packages/morph/src/fromclip.ts:69

captureState function

function captureState(bank: MorphBank, name: string, positions: ArrayLike<number>, colors?: ArrayLike<number>, normals?: ArrayLike<number>): MorphState

copy the arrays of a mesh as a state (with normals computed from its triangles when none are given)

packages/morph/src/source.ts:12

chooseViews function

function chooseViews(objects: Candidate[], budget: MorphBudget = defaultBudget()): Map<string, ViewKind>

which view each object gets: the nearest moving objects take the CPU path while the budget lasts, the rest go to the GPU (or, with no GPU, all stay CPU and over-budget ones simply update less often)

packages/morph/src/budget.ts:25

clamp function

function clamp: (v: number, lo: number, hi: number) => number

packages/morph/src/math.ts:6

closestOnTriangle function

function closestOnTriangle(p: Vec3, a: Vec3, b: Vec3, c: Vec3): { point: Vec3; u: number; v: number; w: number }

closest point on triangle (a, b, c) to p, with its barycentric coordinates (Ericson, Real-Time Collision Detection)

packages/morph/src/conform.ts:64

colorState function

function colorState(bank: MorphBank, name: string, base: string, fn: (i: number, p: Vec3) => Color3 | [number, number, number, number]): MorphState

a state of the same shape as base with colours from a function of the vertex: fn(i, position) -> [r, g, b, a?]

packages/morph/src/source.ts:34

computeNormals function

function computeNormals(positions: ArrayLike<number>, indices: ArrayLike<number>, out?: Float32Array): Float32Array

area-weighted vertex normals of a triangle list

packages/morph/src/blend.ts:26

conform function

function conform(bank: MorphBank, name: string, target: MeshData, opts: ConformOptions = {}): ConformReport

Make a state called name in bank that looks like target. Returns the report; throws a ConformError when the result is not good enough (unless check: false), in which case no state is added.

packages/morph/src/conform.ts:118

cross3 function

function cross3: (a: Vec3, b: Vec3) => Vec3

packages/morph/src/math.ts:13

defaultBudget function

function defaultBudget: () => MorphBudget

packages/morph/src/budget.ts:20

defaultLook function

function defaultLook: () => MorphLook

packages/morph/src/view.ts:22

dot3 function

function dot3: (a: Vec3, b: Vec3) => number

packages/morph/src/math.ts:12

hashFloats function

function hashFloats(parts: ArrayLike<number>[]): string

32-bit FNV-1a of float data: the content hash of a bank (the same bytes give the same hash on every machine)

packages/morph/src/math.ts:18

installMorphOps function

function installMorphOps(service: MorphService, bridge: MorphBridgeLike): void

packages/morph/src/ops.ts:34

len3 function

function len3: (a: Vec3) => number

packages/morph/src/math.ts:14

lerp function

function lerp: (a: number, b: number, t: number) => number

packages/morph/src/math.ts:7

lerp3 function

function lerp3: (a: Vec3, b: Vec3, t: number) => Vec3

packages/morph/src/math.ts:8

materialColor function

function materialColor(m: BABYLON.Material | null): [number, number, number, number]

the colour of a material for a vertex colour: the PBR albedo, the standard diffuse, else white

packages/morph/src/babylon.ts:18

mergeBanks function

function mergeBanks(banks: MorphBank[]): MorphBank

the states of several banks of one topology in one bank (the first bank's index buffer; the topologies must agree)

packages/morph/src/source.ts:100

mirroredState function

function mirroredState(bank: MorphBank, name: string, base: string, partner: ArrayLike<number>, axis: 0 | 1 | 2 = 0): MorphState

a state mirrored across the plane axis = 0 (x by default), using a vertex pairing partner[i] = the vertex at the mirrored place

packages/morph/src/source.ts:49

mirrorPairs function

function mirrorPairs(positions: ArrayLike<number>, axis: 0 | 1 | 2 = 0, tolerance = 1e-4): Int32Array

pair each vertex with the vertex at its mirror image across axis = 0 (nearest within tolerance), or throw naming the first vertex without one

packages/morph/src/source.ts:62

modelArrays function

function modelArrays(root: BABYLON.TransformNode, colorOf: (m: BABYLON.AbstractMesh) => [number, number, number, number] = m => materialColor(m.material)): ModelArrays

every mesh below root as one mesh in the space of the scene (their world matrices applied), vertex colours from their materials (or from their own vertex colours)

packages/morph/src/babylon.ts:49

newBlendOut function

function newBlendOut(vertexCount: number): BlendOut

packages/morph/src/blend.ts:12

nodeHandle function

function nodeHandle(node: BABYLON.TransformNode, forward: [number, number, number] = [0, 0, 1]): NodeHandle

A scene node as the handle the language's node operations (move-along, turn-to) move. forward is the node's own axis that points where it faces (Ferret's is +z; a model made with its nose along +x says [1, 0, 0]); a placement turns the node so that axis points along the asked direction, with no roll (the upright aim of a vehicle or a person).

packages/morph/src/view.ts:245

norm3 function

function norm3: (a: Vec3) => Vec3

packages/morph/src/math.ts:15

packBank function

function packBank(bank: MorphBank, width = TEXTURE_WIDTH): BankTexture

packages/morph/src/layout.ts:22

partBounds function

function partBounds(bank: MorphBank, state: string, part: { first: number; count: number }): { min: Vec3; max: Vec3 }

the bounds of a part of a state: the corners of its box

packages/morph/src/source.ts:93

prepare function

function prepare(bank: MorphBank, i: number): Prepared

applied positions, normals (stored or computed) and colours of state i, cached until the state is replaced

packages/morph/src/blend.ts:47

proceduralState function

function proceduralState(bank: MorphBank, name: string, base: string, fn: (i: number, p: Vec3) => Vec3): MorphState

a state from a function of the vertex: fn(i, position of the base state) -> new position

packages/morph/src/source.ts:22

rotatedPartState function

function rotatedPartState(bank: MorphBank, name: string, base: string, part: { first: number; count: number }, point: Vec3, axis: Vec3, angle: number): MorphState

A state in which the vertices first .. first + count - 1 (one part of a model: a flap, a propeller, a door) are turned by angle radians about the line through point along axis, the rest of the model unchanged. This is how a part on a hinge takes a pose without a clip; hingeOf finds a hinge from the part's own bounds.

packages/morph/src/source.ts:79

scale3 function

function scale3: (a: Vec3, k: number) => Vec3

packages/morph/src/math.ts:11

selectKeyTimes function

function selectKeyTimes(candidates: number[], poseAt: (t: number) => Float32Array, count: number): number[]

The count most different times of candidates: the first, then each time whose pose is farthest (largest minimum vertex distance) from those chosen. Returned in time order.

packages/morph/src/fromclip.ts:104

shadeAll function

function shadeAll(t: BankTexture, idx: ArrayLike<number>, w: ArrayLike<number>, tint: readonly [number, number, number], out: BlendOut): BlendOut

the whole mesh through the shader's arithmetic

packages/morph/src/layout.ts:65

shadeVertex function

function shadeVertex(t: BankTexture, v: number, idx: ArrayLike<number>, w: ArrayLike<number>, tint: readonly [number, number, number]): { position: [number, number, number]; normal: [number, number, number]; color: [number, number, number, number] }

What the vertex shader computes for one vertex of one object: up to four states (idx) with their weights (w), normalised here as in the shader, and the tint. This is the function the GPU result is compared with in the tests (and the CPU path is its loop over all vertices).

packages/morph/src/layout.ts:50

skinVertices function

function skinVertices(model: SkinnedModel, bind: Bone[], pose: Bone[], out?: Float32Array): Float32Array

the vertices skinned by the bone frames pose (model space) against the rest frames bind

packages/morph/src/fromclip.ts:50

slots function

function slots(weights: ReadonlyArray<readonly [number, number]>): { idx: [number, number, number, number]; w: [number, number, number, number] }

the weights of an object as the four-slot vectors the per-instance buffers carry (unused slots: state 0, weight 0)

packages/morph/src/layout.ts:74

sub3 function

function sub3: (a: Vec3, b: Vec3) => Vec3

packages/morph/src/math.ts:9

texel function

function texel(t: BankTexture, state: number, kind: number, v: number): [number, number, number, number]

the texel of (state, kind, vertex) as the shader's texelFetch(tex, ivec2(col, row), 0) finds it

packages/morph/src/layout.ts:41

tintedState function

function tintedState(bank: MorphBank, name: string, base: string, color: Color3): MorphState

a flat colour over a whole state (a livery)

packages/morph/src/source.ts:46

vertexIndexChannel function

function vertexIndexChannel(vertexCount: number): Float32Array

the UV values of the baked vertex index: the vertex number as a float (exact below 2^24 vertices), one value per vertex, written by the content import for meshes without a vertex id

packages/morph/src/layout.ts:82

Interfaces

BankTexture interface

interface BankTexture
width: number
height: number
rowsPer: number
states: number
vertexCount: number
data: Float32ArrayRGBA32F, width height 4
hash: stringthe hash of the bank this texture was made from

packages/morph/src/layout.ts:14

BlendOut interface

interface BlendOut
positions: Float32Array
normals: Float32Array
colors: Float32Array

packages/morph/src/blend.ts:10

Candidate interface

interface Candidate
name: string
vertices: number
distance: number
moving: boolean

packages/morph/src/budget.ts:22

ConformOptions interface

interface ConformOptions
align?: 'bbox' | 'landmarks' | 'none'how B is put over A: 'bbox' (centres and the diagonal match; default), 'landmarks' (centroid and spread of the landmarks), 'none'
landmarks?: Landmark[]
collapse?: Array<{ a: number; to: Vec3 }>vertices of A that have no counterpart in B: each goes to a point (in B's own frame) and is held there
smooth?: number0..1, how far a vertex moves toward the mean offset of its neighbours per pass (default 0.5)
iterations?: numberpasses of smoothing (default 4)
normalWeight?: numberweight of the normal agreement in the choice of the closest point (default 0.5); 0 is the plain closest point
base?: stringthe state of A whose normals and edges are used (default: its first state)
maxResidual?: numberfail with a ConformError if the residual (max) is above this fraction of B's bounding diagonal (default 0.05) or any triangle folds (default 0 allowed)
maxFolds?: number
check?: booleando not fail, only report

packages/morph/src/conform.ts:21

ConformReport interface

interface ConformReport
meanResidual: numbermean and maximum distance of the result's vertices from B's surface, in the units of A and as a fraction of B's diagonal
maxResidual: number
relativeMax: number
folded: number[]triangles of A whose normal turned over or that became a point
unused: number[]vertices of A that no triangle uses, plus the collapsed ones
collapsed: number[]
alignment: { scale: number; centreA: Vec3; centreB: Vec3 }the alignment that was applied: B' = scale * (B - centreB) + centreA

packages/morph/src/conform.ts:42

FarSlot interface

interface FarSlot

The far rung of a morphing object. A baked impostor is a picture, so it cannot change shape; it morphs by colour. The impostors of the key states are baked (one Representation per state, from the perspective module's own bake) and the object shows the two states of largest weight, the one fading out while the other fades in with mix = the weight of the second: the same cross-fade the ladder uses between rungs, so state changes and rung changes run together and a program cannot tell which rung is drawn. A state with no baked impostor is replaced by the nearest baked one (by name order along the bank), so a bank can be baked at a few key states only.

state: number
rep: Representation

packages/morph/src/far.ts:11

FromClipOptions interface

interface FromClipOptions
times?: number[]the times (seconds) to pose at; or:
every?: numberevery n-th frame of the clip at its fps; or:
keyPoses?: numberthe n most different poses of the clip, found automatically (farthest-point choice over the skinned vertices, always including the first frame)
prefix?: stringname of the states: ${prefix}@${seconds}, default the clip's name
inPlace?: booleantake the root's travel out of every frame (default true)

packages/morph/src/fromclip.ts:27

Landmark interface

interface Landmark
a: numbera vertex of A
b: Vec3where it must land, in B's own frame (before the alignment is applied)

packages/morph/src/conform.ts:14

MeshData interface

interface MeshData

Retopology: a state of A's topology that looks like a mesh B of another topology. B is aligned to A, every vertex of A takes the closest point on B's surface (the normals of both break ties, so a vertex does not jump through a thin part to the far side), the field of offsets is smoothed so neighbours stay neighbours, colours are sampled at the same points, and the result is measured: the residual distance from B and the folded triangles. A failed conform is an error, not a silent result. Cost is O(vertices of A x triangles of B), which is small for light figures.

positions: ArrayLike<number>
indices: ArrayLike<number>
colors?: ArrayLike<number>

packages/morph/src/conform.ts:12

ModelArrays interface

interface ModelArrays extends MeshData

Reading models the engine holds: the arrays of a model's meshes as a mesh, and the frames of its animation groups as a bank. The skinning is the engine's own (the bone matrices Babylon computes, applied to the vertices on the CPU), so the states are what the engine would draw at those times. A model made of rigid parts (an aeroplane whose flap is a node) is the same case with one bone per part: its animation group moves the nodes and the part's vertices follow them.

positions: Float32Array
indices: Uint32Array
colors: Float32Array
parts: Array<{ name: string; first: number; count: number }>per mesh: first vertex, vertex count, name

packages/morph/src/babylon.ts:11

MorphBridgeLike interface

interface MorphBridgeLike
define(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => unknown): unknown
lasting(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => { done(): boolean; result?: unknown }): unknown
action(name: string, sig: { args: string[]; min?: number; rest?: string }, spec: { start(ctx: any, args: any[]): { step?(args: any[], ctx: any): void; stop?(): void } | void }): unknown

packages/morph/src/ops.ts:19

MorphBudget interface

interface MorphBudget
maxCpu: numberat most this many objects drawn by the CPU path (default 8)
cpuVertices: numbervertices the CPU path may blend in one frame over all its objects (default 200000)
gpu: booleanthe device has no vertex texture fetch (or GPU views are off): everything is CPU

packages/morph/src/budget.ts:11

MorphHostOptions interface

interface MorphHostOptions

The two modules in one service: the morph service and the motion language's runtime stepped together in the world's fixed step, with the morph operations and the node-moving operations (move-along, turn-to) registered on the same bridge, and the commands morph.* and morph.run. A program that morphs a plane and flies it is one program: (par (move-along route 80) (morph-to gear-up 4s) (tint-to #203040 20s)).

The host knows no engine: the game says how a node name becomes a NodeHandle (node), and the programs' target names both the morph object and the node.

seed?: number
node: (name: string) => NodeHandle | undefineda node of the scene by name, as the handle the node operations move
budget?: numberreductions a program may do per step (the language's budget)

packages/morph/src/host.ts:14

MorphIssue interface

interface MorphIssue
level: 'error' | 'warning'
path: string
message: string

packages/morph/src/bank.ts:22

MorphLook interface

interface MorphLook

Drawing the blend. Two views of the same MorphObject:

  `CpuMorphView`  one mesh whose vertex arrays are rewritten when the blend changes (and not otherwise): the reference, exact for any bank, for the few important objects;
  `GpuMorphBatch` one mesh and one draw call for all the objects of a bank: the states are in a float texture (see layout.ts), the vertex shader mixes up to four of them per
                  instance, and the CPU writes only a small vector per object per frame (four state numbers, four weights, a tint).

Both are lit by the same fragment shader (MorphLook), so a picture of one equals a picture of the other (the test of M4 compares them pixel by pixel).

sun: [number, number, number]the direction the sun shines along
sunColor: [number, number, number]
ambientUp: [number, number, number]
ambientDown: [number, number, number]

packages/morph/src/view.ts:15

MorphSnapshot interface

interface MorphSnapshot
v: 1
time: number
base: Array<[number, number]>
tr: { to: number; t0: number; dur: number; ease: string; id: number } | null
holds: Array<[number, number]>
pinned: { a: number; b: number; w: number } | null
nextId: number
activeId: number
tint: { from: Color3; to: Color3; t0: number; dur: number; ease: string }

packages/morph/src/sim.ts:15

MorphState interface

interface MorphState

The bank: the states of one topology. A state is a full set of per-vertex data (positions, optionally normals and colours) and a scale and pivot; the index buffer is held once. States are named. The bank is plain typed arrays and JSON/binary files, so the same bank is read by the browser and by the UE build.

name: string
positions: Float32Arrayxyz per vertex
normals?: Float32Arrayxyz per vertex, unit length; recomputed from the positions when absent
colors?: Float32Arrayrgba per vertex, 0..1; absent: white
scale?: numberone scale of the whole state (a folded wing is shorter than an open one)
pivot?: [number, number, number]the point the scale is about

packages/morph/src/bank.ts:8

MorphWait interface

interface MorphWait

a lasting move: the program waits on it; it is done when it has arrived or has been replaced by another move

readonly id: number
done(): boolean

packages/morph/src/sim.ts:23

SkinnedModel interface

interface SkinnedModel

States from the frames of a clip. A skinned model, posed at chosen times of a clip, is skinned on the CPU and the result is stored as a state of the model's topology. The model's vertices are in the rest pose of the skeleton the clip is made for (as a skinned mesh is bound). Root motion is taken out of every frame (the figure stays where it was at the first frame), as in the VAT bake. The bank carries a source that names the clip and the model by content, so a bank is re-baked when either changes (bankIsCurrent).

name: stringthe model's name, for the bank's source
positions: Float32Arrayxyz per vertex in the bind pose
indices: Uint32Array
joints: ArrayLike<number>four bone indices per vertex (into boneNames) and four weights
weights: ArrayLike<number>
boneNames: string[]
rest: Rest
colors?: Float32Arrayrgba per vertex, 0..1, kept in every state (optional)

packages/morph/src/fromclip.ts:12

Types

Color3 type

type Color3 = [number, number, number]

packages/morph/src/math.ts:4

RegisterFn type

type RegisterFn = (name: string, description: string, fn: (args: any) => unknown) => void

The morph service: the banks and the objects of a world, stepped once per fixed step, and the morph.* commands. It is host-agnostic: the game passes world.commands.register, a test passes a function that fills a Map. Everything the commands take and return is plain JSON.

packages/morph/src/service.ts:13

Vec3 type

type Vec3 = [number, number, number]

packages/morph/src/math.ts:3

VertexLookup type

type VertexLookup = 'vertex-id' | 'uv-index'

how the shader finds a vertex in the bank texture: by the vertex id the draw gives (vertex-id, WebGL2), or by the vertex's baked index in an attribute (uv-index)

packages/morph/src/view.ts:105

ViewKind type

type ViewKind = 'cpu' | 'gpu'

The choice between the CPU view and the GPU view, in the spirit of the perspective governor. A few objects near the camera may be drawn by the CPU path (any function can change the mesh, normals are exact); many, or any object whose blend changes every frame in a crowd, go to the GPU path (one draw call for all, cost per frame is the number of objects). Both read the same MorphObject, so an object can move from one to the other at any step.

packages/morph/src/budget.ts:9

Weights type

type Weights = ReadonlyArray<readonly [index: number, weight: number]>

The blend: up to four weighted states of one bank mixed into positions, normals and colours. A state's scale and pivot are applied first (appliedPositions), so the blend is a plain weighted sum and the GPU can read the same applied numbers from its texture.

packages/morph/src/blend.ts:8

Constants

KINDS const

const KINDS: 3

packages/morph/src/layout.ts:12

MAX_STATES const

const MAX_STATES: 4

The deterministic part: what blend one object is in, as a function of the fixed step and the commands it was given. Pure numbers, no engine; the same on every peer and every tier. The object holds up to four weighted states: a transition from the current blend to a state is base * (1 - u) + target * u with u the eased progress, a new transition starts from the blend as it is at that moment (never from a jump), and held weights (hold) are laid over the result.

packages/morph/src/sim.ts:12

TEXTURE_WIDTH const

const TEXTURE_WIDTH: 2048

The layout of a bank in a float texture and the reference of what the vertex shader does with it. The texture is RGBA32F, width texels wide; one row block of rowsPer = ceil(vertexCount / width) rows per (state, kind), the kinds being 0 position (xyz, w = 1), 1 normal (xyz), 2 colour (rgba). Vertex v of state s, kind k is at column v % width, row (s * 3 + k) * rowsPer + floor(v / width). A shader reads the same texture with the same arithmetic, by the vertex id or by the baked index of the vertex in an attribute (vertexIndexChannel), so both lookups give the same texel.

packages/morph/src/layout.ts:11