FERRETGame engine over Babylon.js
Ferret

@ferret/editor

Level editing as commands and patches, for people and for AI agents; sessions and packages.

21 exports · source in packages/editor/src

Classes

EditError class

class EditError extends Error
constructor(message: string, readonly issues: ManifestIssue[] = [])

packages/editor/src/session.ts:10

EditSession class

class EditSession

An editing session over one level's manifest.json: every change is a patch checked against the manifest schema (and the behaviours' parameter schemas) before it stays, with undo and redo. scene.glb is never touched, so a re-export from Unreal keeps all of it: the manifest refers to nodes by name.

draft: LevelManifest
constructor(manifest: LevelManifest, readonly opts: SessionOptions = {})
get canUndo(): boolean
get canRedo(): boolean
get dirty(): boolean
history(): string[]
check(): ManifestIssue[]Everything wrong with the draft: the manifest schema, then each entity's parameters against its behaviour's schema.
apply(label: string, ops: Op[]): voidApply a patch. If the result is not valid nothing changes and the problems come back in the error.
undo(): string | null
redo(): string | null
get navBuildChanged(): booleanDid the NavMesh settings change since the last save? Then navmesh.bin has to be built again.
setNavBuild(patch: Record<string, number | null>)Set the NavMesh build settings (merged into the current ones; null removes one). The file name defaults to navmesh.bin.
changes(): Op[]What differs from the saved state.
markSaved()
text(): string
entity(id: string): ManifestEntity | undefined
addEntity(e: ManifestEntity)
removeEntity(id: string)
setEntity(id: string, patch: Partial<Omit<ManifestEntity, 'id'>> & { params?: Record<string, unknown>; transform?: ManifestEntity['transform'] })Change an entity: transform parts and params are merged key by key (null removes one), the rest replaced.
duplicateEntity(id: string, newId: string, offset: [number, number, number] = [1, 0, 0])
addSpawn(s: ManifestSpawn)
removeSpawn(id: string)
setSpawn(id: string, patch: Partial<Omit<ManifestSpawn, 'id'>>)
addZone(z: Record<string, unknown> & { name: string })
removeZone(name: string)
setZone(name: string, patch: Record<string, unknown>)
physics(): Record<string, unknown>
setMaterial(name: string, values: PhysicsMaterial)Add or replace a material of the level (its values are those of a PhysicsMaterial).
removeMaterial(name: string)
setConstraint(k: LevelConstraint)Add a link between two bodies (by the names of their nodes), or replace the one with the same id.
removeConstraint(id: string)
setFracture(f: LevelFracture)Say that a body (by its node) breaks into authored pieces (nodes).
removeFracture(node: string)
chemistry(): Record<string, any>
setChemistryOption(key: 'sets' | 'aqueous' | 'standard' | 'phases', value: unknown)Standard species sets, aqueous, standard and phases of the level's chemistry block (null removes).
setChemistrySpecies(name: string, def: Record<string, unknown>)Add or replace a species of the level: { formula?, phase?, Hf, S?, cp, ... }.
removeChemistrySpecies(name: string)
setChemistryReaction(name: string, def: Record<string, unknown>)Add or replace a reaction of the level: { equation, A, Ea, ... } or { reactants, products, A, Ea, ... }.
removeChemistryReaction(name: string)
setPhysics(key: string, value: unknown)Set a top-level key of the block (capabilities, gravity, a capability's values, combine, pairs); null removes it.
materialLooks(): MaterialLooks
lookOf(scope: LookScope, uid: string, material: string): Record<string, unknown> | undefinedthe look in the draft for that scope, uid and material name (undefined: none)
setMaterialLook(scope: LookScope, uid: string, material: string, values: Record<string, unknown>)Change the look of the material material of the type or the instance uid: the values are merged into what is there, a value of null takes that one off; nothing left removes the entry.
removeMaterialLook(scope: LookScope, uid: string, material?: string)Take a look off: one material of the uid, or (no material) everything the uid has. What is left empty goes with it.
setStreaming(block: StreamingBlock | null)Replace the whole streaming block (null removes it, and the entities' needs with it being refused by the check if any remain).
setStreamField(key: string, value: unknown)Change one setting of the block (loadRadius, unloadRadius, lodRadius, cell, texturesProgressive); null removes an optional one.
setStreamCell(id: string, cell: StreamCellDef | null)Add or replace a cell (a cut made elsewhere); null removes it.
setTags(tags: string[] | null)
setLevelData(key: string, value: unknown)Set a key of the level's free data (null removes it).
graph(name: string): GraphDef
setGraph(name: string, def: GraphDef)
removeGraph(name: string)
setState(graph: string, state: string, def: StateDef)
removeState(graph: string, state: string, withTransitions = false)Remove a state. The transitions that start or end in it must go too (withTransitions), or the edit is refused.
setInitial(graph: string, state: string)
addTransition(graph: string, t: TransitionDef, index?: number)Add a transition at the end, or at index (the first transition whose conditions hold wins, so the order matters).
setTransition(graph: string, index: number, patch: Partial<TransitionDef> & Record<string, unknown>)Change fields of a transition (merged; null removes one): its target, conditions, cross-fade duration.
removeTransition(graph: string, index: number)
setGraphParam(graph: string, name: string, kind: 'float' | 'bool' | 'trigger' | null)Declare a parameter (float, bool or trigger), or drop it with null.
setCollider(node: string, collide: boolean)Make a node solid or walk-through whatever the export says.
removeCollider(node: string)

packages/editor/src/session.ts:31

FmdlEditError class

class FmdlEditError extends Error
constructor(message: string, readonly issues: PackageIssue[] = [])

packages/editor/src/fmdl.ts:27

FmdlSession class

class FmdlSession
static async open(files: Files, opts: FmdlSessionOptions, fresh = false): Promise<FmdlSession>open a model folder; throws when it is not a good model
get id(): string
get version(): string
get model(): ModelJson
get manifest(): PackageManifest
get description(): ModelDescriptionthe author's description.json (the packer fills the rest)
get canUndo(): boolean
get canRedo(): boolean
get dirty(): boolean
history(): string[]
changedFiles(): string[]the paths of the files that differ from what the session was opened with
files(): Filesa copy of the folder as it is now
read(path: string): Uint8Array | undefined
async check(files: Files = this.draft): Promise<PackageIssue[]>everything wrong with the draft: the folder as ferret fmdl check sees it, and the chain and the included models resolved with it
async snapshot(): Promise<DraftModel>the resolved model of the draft (the parents merged, the includes resolved): what a game would place, with the reader of the files of all the models it is made of
async resolved(): Promise<ResolvedModel>
async edit(label: string, change: (m: { model: any; description: any; manifest: any; files: Files }) => void): Promise<this>Run a change on a copy; keep it only when the copy is a good model. change edits the parsed files (model, description, manifest) and may write or remove other files.
undo(): string | undefined
redo(): string | undefined
setDescription(fields: Partial<Record<keyof ModelDescription, unknown>>): Promise<this>the description's own fields (summary, kind, tags, purpose, text ...); null removes one; objects (parts, docks ...) merge by key
setName(name: string, version?: string): Promise<this>
setParent(parent: { id: string; version: string } | null): Promise<this>the parent: extends; its package becomes a dependency. null makes the model a root again (it must then say everything itself)
addInclude(name: string, inc: ModelInclude): Promise<this>an include (SPEC 6.2): at is a placement or a list of them ({ name, dock?, to?, node?, position?, rotation?, scale?, overrides? })
setInclude(name: string, patch: Partial<ModelInclude>): Promise<this>
removeInclude(name: string): Promise<this>takes an include away; in a child, an include of the parent is removed by null (SPEC 8.3)
setDock(name: string, dock: ModelDock): Promise<this>
removeDock(name: string): Promise<this>
setPart(name: string, part: ModelPart): Promise<this>
removePart(name: string): Promise<this>
setMaterial(name: string, material: ModelMaterial): Promise<this>
removeMaterial(name: string): Promise<this>
setMovingPart(name: string, part: ModelMovingPart): Promise<this>
removeMovingPart(name: string): Promise<this>
setPhysics(patch: Record<string, unknown>): Promise<this>the physics block merged by key (null removes a key): { mass: 3 }, { collision: { body: {...} } }, { modules: { atom: { nuclide: "H-2" } } }
setMotion(name: string, motion: Omit<ModelMotion, 'file'> & { file?: string }, program?: string): Promise<this>a motion: its entry in motions and, when program is given, the file it names (default motions/<name>.fm). Every form the program uses must be in requires.forms, and of the model.
removeMotion(name: string): Promise<this>
patch(ops: Op[], label = 'patch'): Promise<this>anything else: JSON-pointer operations on model.json (add, replace, remove)
async makeChild(id: string, o: { name?: string; version?: string; summary?: string; kind?: string } = {}): Promise<FmdlSession>A new model that extends this one. Nothing is copied: the child holds only what it changes, and the parent's levels, parts, docks, motions and includes are its own by inheritance (SPEC 8). The parent's version range is ^<version>. Give it what makes it a different thing (summary, kind come from the parent unless set).
async prepare()the folder prepared as ferret fmdl pack does (levels measured, mass and charge computed, the description written): the files the packer would write
async pack(o: { sign?: { privateKey: string }; encrypt?: { password: string } } = {}): Promise<{ bytes: Uint8Array; manifest: PackageManifest }>the .fmdl bytes; the folder of the session gets what the packer wrote (model.json, the description) as one change

packages/editor/src/fmdl.ts:53

Functions

applyOps function

function applyOps(root: any, ops: Op[]): Op[]

Apply operations in order to root (changed in place) and return the operations that undo them.

packages/editor/src/patch.ts:39

diff function

function diff(a: unknown, b: unknown, path = ''): Op[]

The operations that turn a into b (objects by key, lists by position). For showing what an edit session changed.

packages/editor/src/patch.ts:83

escapePointer function

function escapePointer: (s: string) => string

packages/editor/src/patch.ts:12

get function

function get(root: unknown, path: string): unknown

packages/editor/src/patch.ts:32

installClipEditor function

function installClipEditor(ctx: ClipEditorContext): { editor(): ClipEditor | null; clip(): ClipJson | null }

packages/editor/src/clip.ts:25

installEditor function

function installEditor(ctx: EditorContext): { session(): EditSession | null }

The editing commands (V2) on top of the inspector's: open a level's manifest, change entities, spawns, zones and collision overrides with undo and redo, validate against the schemas and the loaded scene, and save manifest.json. Every command is JSON in and out, so a person's panel and an AI agent (over MCP) edit the same way. After each change the level is reloaded from the draft, so what you see is what the game will load.

Commands: edit.open, edit.close, edit.get, edit.entity.add / set / remove / duplicate, edit.spawn.add / set / remove, edit.zone.add / set / remove, edit.navmesh.rebuild / info, edit.anim.graph / set / remove, edit.anim.state.set / remove, edit.anim.initial, edit.anim.transition.add / set / remove, edit.anim.param, edit.collider.set / remove, edit.colliders.missing, edit.physics.get / set / material.set / material.remove / constraint.set / constraint.remove / fracture.set / fracture.remove, edit.material.list / get / set / remove (the look of the glTF materials, live), edit.chemistry.get / option / species.set / species.remove / reaction.set / reaction.remove, edit.patch, edit.undo, edit.redo, edit.history, edit.validate, edit.diff, edit.save, edit.reload.

packages/editor/src/commands.ts:42

packageEditing function

function packageEditing(mount: PackageMount, o: { persist?: (pkgId: string) => Promise<unknown> } = {}): Pick<EditorContext, 'fetch' | 'save' | 'saveFile'>

Editing a level that lives in a .ferret package (PLAN.md 4.9): the editor reads the level through the mount and its saves go into the package's draft, so the level reloads with them and pkg.pack / pkg.save write the result. Give the result to installEditor({ ..., ...packageEditing(mount) }); persist runs after each save (write the changed files, pack again).

packages/editor/src/package.ts:10

registerFmdlEditCommands function

function registerFmdlEditCommands(register: RegisterFn, host: FmdlEditHost): { sessions: Map<string, FmdlSession> }

packages/editor/src/fmdl.ts:285

Interfaces

ClipEditorContext interface

interface ClipEditorContext

Clip editing (plans/demo_fight.md, D2) on top of the engine's command registry: the commands a person's panel and an agent over MCP share. One clip is open at a time; every change goes through ClipEditor (checked, with undo), and a preview, when the host gives one, shows the clip on a body.

edit.clip.new / open / get / save / close, edit.clip.undo / redo / history, edit.clip.key.set / remove / copy, edit.clip.mirror, edit.clip.notify.set / remove, edit.clip.retime, edit.clip.info, edit.clip.validate, edit.clip.preview.

world: World
rest(skeleton: string): Promise<Rest> | Restthe rest pose of a skeleton (read from a body of the library: restOf(bonesOf(model.root)) of @ferret/animation)
load?(id: string): Promise<ClipJson | undefined> | ClipJson | undefineda saved or library clip by id (edit.clip.open, and base of edit.clip.new)
save?(clip: ClipJson): Promise<void> | voidwrite the clip (edit.clip.save); without it the command only returns the JSON
preview?(clip: ClipJson, a: { body?: string; time?: number; play?: boolean; loop?: boolean }): Promise<unknown> | unknownshow the clip on a body: a pose at time (seconds), or play it; the host owns the bodies
positionBones?: (bone: string) => boolean

packages/editor/src/clip.ts:12

DraftModel interface

interface DraftModel
resolved: ResolvedModel
read: (qualified: string) => Promise<Uint8Array>

packages/editor/src/fmdl.ts:32

EditorContext interface

interface EditorContext
world: World
levels: LevelService
loader: PackageLoaderOptionsthe options given to installPackageLoader: the editor hooks its draft in so a reload shows the edit
load?: (def: LevelDef) => Promise<LevelManifest>read a level's manifest (default: fetch <url>/manifest.json)
save?: (def: LevelDef, text: string) => Promise<void>write a level's manifest.json; without it edit.save only returns the text
saveFile?: (def: LevelDef, name: string, data: Uint8Array) => Promise<void>write a binary file of the level's folder (navmesh.bin after a rebuild); without it a rebuilt NavMesh is not saved
fetch?: (url: string) => Promise<{ ok: boolean; json(): Promise<any> }>replace fetch for the default loader

packages/editor/src/commands.ts:8

FmdlEditHost interface

interface FmdlEditHost
folder(id: string): Promise<Files> | Filesthe files of a model by id (a folder, or the files of an open package), to open it for editing
loader: ModelLoader
run?(draft: DraftModel, motion: string, args: Record<string, unknown>): Promise<unknown> | unknownrun a motion of a model: the viewer, or a world with a stage, gives this; the editor only asks
save?(id: string, files: Files, bytes?: Uint8Array): Promise<unknown> | unknownwhere a packed model goes (a file, the library)

packages/editor/src/fmdl.ts:275

FmdlSessionOptions interface

interface FmdlSessionOptions
loader: ModelLoaderwhere a parent or an included model is found: the packages open in the world, a folder, a catalog
onChange?: (label: string) => void

packages/editor/src/fmdl.ts:47

SessionOptions interface

interface SessionOptions
schema?: (behaviour: string) => ParamSchema | undefinedthe parameter schema of a behaviour, if it has one
known?: (name: string) => booleanis the behaviour or component registered? (unknown ones are reported, not refused: the game may add them later)
onChange?: (label: string) => void

packages/editor/src/session.ts:14

Types

Op type

type Op = | { op: 'add'; path: string; value: unknown } | { op: 'replace'; path: string; value: unknown } | { op: 'remove'; path: string }

JSON-pointer patches, the one way the editor changes a manifest: each edit is a list of operations, and applying it gives back the list that undoes it. Paths are RFC 6901 pointers ("/entities/2/params/angle"); "-" appends to a list.

packages/editor/src/patch.ts:6

ParamSchema type

type ParamSchema = Record<string, { type: 'number' | 'string' | 'boolean' | 'array' | 'object'; min?: number; max?: number; enum?: unknown[]; required?: boolean }>

What a behaviour's parameters may be: a component class can describe them with static schema.

packages/editor/src/session.ts:8

RegisterFn type

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

packages/editor/src/fmdl.ts:273