Appearance
@bendyline/molen-kernel
Molen headless deterministic simulation kernel (no DOM, no three.js).
ts
import { /* … */ } from '@bendyline/molen-kernel';Classes
KernelHost
Wires a World + Scheduler to a message link (Worker, MessagePort, or test mock). Commands and control messages come in; keyframes/deltas/events/diag go out. Environment-agnostic: the actual Worker glue (self.onmessage) is a thin wrapper provided by the client/example.
Constructors
Constructor
ts
new KernelHost(
world,
link,
opts?
): KernelHost;Parameters
world
link
MessageLink
opts?
Returns
Methods
dispose()
ts
dispose(): void;Returns
void
pause()
ts
pause(): void;Returns
void
start()
ts
start(): void;Start or resume the scheduler. Initial state is announced by the constructor. Throws if a tick has faulted the world — a resume control message answers with a control-rejected diag rather than pretending to restart a dead simulation.
Returns
void
step()
ts
step(n?): void;Manually advance n ticks (used while paused, e.g. by a debugger).
Parameters
n?
number
Returns
void
Scheduler
Drives a world at its fixed timestep using a setTimeout accumulator. The world itself is clock-free; all real-time concerns live here. One implementation serves Worker and Node (setTimeout exists in both). Tests inject a clock to avoid flaky real timers.
Constructors
Constructor
ts
new Scheduler(world, opts?): Scheduler;Parameters
world
opts?
Returns
Accessors
state
Get Signature
ts
get state(): "running" | "paused";Returns
"running" | "paused"
Methods
pause()
ts
pause(): void;Returns
void
setRate()
ts
setRate(rate): void;Parameters
rate
number
Returns
void
start()
ts
start(): void;Start or resume. Refuses a faulted world: a tick that threw leaves the world unable to step (World.step throws on every call after a fault), so silently "resuming" would spin a dead loop. Recovery is explicit — rebuild the world, or restore a keyframe with applyKeyframeTo, which clears the fault — and then call start() again.
Returns
void
step()
ts
step(n?): void;Run n ticks synchronously (manual stepping while paused). A failing tick pauses the scheduler and reports through onError like a timer-driven one, then rethrows so the synchronous caller sees it too.
Parameters
n?
number
Returns
void
World
The ECS world: component-major storage, version-stamped query cache, deferred structural ops, and a fixed-timestep tick in four phases (commands → update → physics → late).
Snapshot/delta and command machinery attach via the internal accessors at the bottom; they live in sibling modules to keep this file focused on the ECS + tick.
Constructors
Constructor
ts
new World(opts?): World;Parameters
opts?
Returns
Properties
componentRegistry
ts
readonly componentRegistry: ComponentRegistry;content
ts
readonly content: Readonly<ContentIdentity>;Content this world was built from, by domain; empty when none was declared.
dt
ts
readonly dt: number;tickRate
ts
readonly tickRate: number;Accessors
faulted
Get Signature
ts
get faulted(): Error | undefined;The error that killed a tick, or undefined for a healthy world. A faulted world refuses to step again: hosts and schedulers check this to report the failure and to refuse a resume until the world is rebuilt or restored from a keyframe (applyKeyframeTo clears it).
Returns
Error | undefined
tick
Get Signature
ts
get tick(): number;Returns
number
Methods
addSystem()
ts
addSystem(system, opts?): void;Parameters
system
opts?
name?
string
phase?
priority?
number
Returns
void
commandTypes()
ts
commandTypes(): string[];Every declared command type (registration order).
Returns
string[]
declareCommand()
ts
declareCommand(type, opts?): void;Declare a command type (optionally with a payload validator) without attaching a handler. Scenes declare their commands this way at build time; scripts and setup modules attach handlers with onCommand/registerCommand.
Parameters
type
string
opts?
Returns
void
describeSystems()
ts
describeSystems(): SystemInfo[];Returns
destroy()
ts
destroy(id): void;Parameters
id
string
Returns
void
emit()
ts
emit(type, payload): void;Parameters
type
string
payload
Returns
void
exists()
ts
exists(id): boolean;Parameters
id
string
Returns
boolean
get()
ts
get<T>(id, c): Readonly<T> | undefined;Returns the stored object itself (frozen in dev). See the aliasing rule on WorldOptions.
Type Parameters
T
T extends JsonObject
Parameters
id
string
c
ComponentType<T>
Returns
Readonly<T> | undefined
has()
ts
has(id, c): boolean;Parameters
id
string
c
ComponentType<JsonObject>
Returns
boolean
hasCommand()
ts
hasCommand(type): boolean;Parameters
type
string
Returns
boolean
on()
ts
on(event, handler): Unsubscribe;Parameters
event
string
handler
Returns
onCommand()
ts
onCommand(type, handler): Unsubscribe;Attach a handler for a command type (declaring it if needed). Returns a remover.
Parameters
type
string
handler
CommandHandler<World>
Returns
patch()
ts
patch<T>(
id,
c,
partial
): void;Type Parameters
T
T extends JsonObject
Parameters
id
string
c
ComponentType<T>
partial
Partial<T>
Returns
void
query()
Call Signature
ts
query<A>(a): QueryResult<[A]>;Type Parameters
A
A extends JsonObject
Parameters
a
ComponentType<A>
Returns
QueryResult<[A]>
Call Signature
ts
query<A, B>(a, b): QueryResult<[A, B]>;Type Parameters
A
A extends JsonObject
B
B extends JsonObject
Parameters
a
ComponentType<A>
b
ComponentType<B>
Returns
QueryResult<[A, B]>
Call Signature
ts
query<A, B, C>(
a,
b,
c
): QueryResult<[A, B, C]>;Type Parameters
A
A extends JsonObject
B
B extends JsonObject
C
C extends JsonObject
Parameters
a
ComponentType<A>
b
ComponentType<B>
c
ComponentType<C>
Returns
QueryResult<[A, B, C]>
Call Signature
ts
query<A, B, C, D>(
a,
b,
c,
d
): QueryResult<[A, B, C, D]>;Type Parameters
A
A extends JsonObject
B
B extends JsonObject
C
C extends JsonObject
D
D extends JsonObject
Parameters
a
ComponentType<A>
b
ComponentType<B>
c
ComponentType<C>
d
ComponentType<D>
Returns
QueryResult<[A, B, C, D]>
registerCommand()
ts
registerCommand(
type,
handler,
opts?
): void;Register a handler (and optional payload validator) for a command type. A type may carry many handlers (setup module + scripts); they run in registration order.
Parameters
type
string
handler
CommandHandler<World>
opts?
Omit<CommandTypeDef<World>, "handler">
Returns
void
registerSnapshotProvider()
ts
registerSnapshotProvider(
name,
save,
load
): void;Register an opaque snapshot provider (e.g. a physics plugin). save is captured into keyframe.plugins[name]; load restores from it. Lets plugins persist state the legible ECS mirror can't (solver warm-start, sleeping flags) for bit-exact resume.
Parameters
name
string
save
() => JsonValue
load
(v) => void
Returns
void
remove()
ts
remove(id, c): void;Parameters
id
string
c
ComponentType<JsonObject>
Returns
void
removeSystem()
ts
removeSystem(name): boolean;Remove a registered system by name (a capability's dispose path). A removal during a tick takes effect from the next tick (the running tick iterates a snapshot). Returns whether a system was removed.
Parameters
name
string
Returns
boolean
set()
ts
set<T>(
id,
c,
data
): void;Type Parameters
T
T extends JsonObject
Parameters
id
string
c
ComponentType<T>
data
T
Returns
void
spawn()
ts
spawn(components, opts?): string;spawnRaw plus the two conveniences: component defaults (registered via defineComponent) deep-merged UNDER the authored data, and shape validation against the schema component registry (on by default in devFreeze worlds). Both apply per component PRESENT in the map — spawn never adds a component you did not ask for.
Parameters
components
ComponentMap
opts?
id?
string
validate?
boolean
Returns
string
spawnRaw()
ts
spawnRaw(components, id?): string;spawn without the conveniences: no component defaults, no shape validation. The hot path — snapshot restore and bulk spawners use it — and the terse one, so it is what most tests and scripts reach for. Prefer spawn when the components come from data you did not author, and see it for what the conveniences are. If id is omitted, a runtime id ("e"+seq) is allocated.
Parameters
components
ComponentMap
id?
string
Returns
string
step()
ts
step(): void;Advance exactly one tick, synchronously. Clock-free (no Date/performance access).
Returns
void
stepN()
ts
stepN(n): void;Parameters
n
number
Returns
void
submitCommand()
ts
submitCommand(command): SubmitResult;Validate and enqueue a command. Invalid commands never queue and surface a command-rejected event carrying (source, seq) and the formatted reason.
Parameters
command
Command
Returns
unregisterSnapshotProvider()
ts
unregisterSnapshotProvider(name): boolean;Remove a snapshot provider (a plugin's dispose path). Returns whether one was removed.
Parameters
name
string
Returns
boolean
Interfaces
ApplyKeyframeOptions
Properties
allowContentDrift?
ts
optional allowContentDrift?: boolean;Load even when the keyframe recorded different content than the world was built from (default false: that is an error naming the domain and both hashes).
AtmosphereSample
Properties
densityKgM3
ts
densityKgM3: number;pressurePa
ts
pressurePa: number;relativeHumidity
ts
relativeHumidity: number;temperatureK
ts
temperatureK: number;windVelocity
ts
windVelocity: [number, number, number];AudioMusicPayload
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
crossfadeS?
ts
optional crossfadeS?: number;playlist
ts
playlist: string[] | null;AudioPlayOptions
Properties
bus?
ts
optional bus?: string;entity?
ts
optional entity?: string;Play at (and follow) this entity's transform.
gain?
ts
optional gain?: number;loop?
ts
optional loop?: boolean;Loop until stop(handle); default the sound's own loop flag.
pitch?
ts
optional pitch?: number;position?
ts
optional position?: Vec3;Play at a fixed world position. Omit both for a non-positional sound.
AudioPlayPayload
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
bus?
ts
optional bus?: string;entity?
ts
optional entity?: string;gain?
ts
optional gain?: number;handle
ts
handle: string;loop?
ts
optional loop?: boolean;pitch?
ts
optional pitch?: number;position?
ts
optional position?: Vec3;sound
ts
sound: string;AudioScriptApi
Methods
music()
ts
music(playlist, opts?): void;Switch background music to a track or playlist; null stops it. Emits audio.music.
Parameters
playlist
string | string[] | null
opts?
crossfadeS?
number
Returns
void
play()
ts
play(sound, opts?): string;Play a sound-bank id; returns a handle for stop. Emits audio.play.
Parameters
sound
string
opts?
Returns
string
stop()
ts
stop(target, fadeS?): void;Stop by handle, or every voice matching an entity and/or sound. Emits audio.stop.
Parameters
target
| string | { entity?: string; sound?: string; }
fadeS?
number
Returns
void
AudioStopPayload
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
entity?
ts
optional entity?: string;fadeS?
ts
optional fadeS?: number;handle?
ts
optional handle?: string;sound?
ts
optional sound?: string;BuildWorldOptions
Extends
Extended by
Properties
capabilities?
ts
optional capabilities?: (world, manifest) => Record<string, object> | undefined[];Capability hooks (figures, vehicles, …), run in order after terrain and before setup. Same contract as physics: each may return script-api extension namespaces.
Parameters
world
manifest
SceneManifest
Returns
Record<string, object> | undefined
content?
ts
optional content?: ContentIdentity;Which content the world is built from (see ContentIdentity), e.g. a type library's hash. Recorded in keyframes and replays next to the state hash, never inside it.
defaults?
ts
optional defaults?: Readonly<Record<string, JsonObject>>;Inherited from
devFreeze?
ts
optional devFreeze?: boolean;gameplay?
ts
optional gameplay?: boolean;Inherited from
physics?
ts
optional physics?: (world, manifest) => Record<string, object> | undefined;Physics plugin hook (e.g. rapier), run after the data-declared systems and before setup. May return script-api extension namespaces ({ physics: rapierScriptApi(handle) }).
Parameters
world
manifest
SceneManifest
Returns
Record<string, object> | undefined
registry?
ts
optional registry?: ComponentRegistry;Inherited from
scriptExtensions?
ts
optional scriptExtensions?: Record<string, object>;Extra script-api namespaces merged with whatever the hooks return.
scripts?
ts
optional scripts?: boolean;Install resolved type scripts followed by the manifest's scripts (default true).
terrain?
ts
optional terrain?: (world, manifest) => Record<string, object> | undefined;Terrain ground field hook, run after physics and before setup. Same contract as physics: returns script-api extensions ({ terrain: terrainScriptApi(handle) }).
Parameters
world
manifest
SceneManifest
Returns
Record<string, object> | undefined
types?
ts
optional types?: ResolvedTypes;Flattened registry types; required when the scene references type ids.
Inherited from
validateSpawn?
ts
optional validateSpawn?: boolean;CommandTypeDef
Per-type declaration: an optional payload validator (runs after envelope validation).
Type Parameters
W
W
Properties
handler
ts
handler: CommandHandler<W>;validatePayload?
ts
optional validatePayload?: (payload) => PayloadCheck;Optional payload validator (a scene's declared JSON Schema, or hand-written).
Parameters
payload
Returns
ComponentType
A typed handle over a wire-string component name. Strings on the wire, types in code. defineComponent is metadata only — there is no class instantiation anywhere; components are pure JSON data (the shipped vocabulary is docs-src/schemas/components.md).
Type Parameters
T
T extends JsonObject
Properties
__type?
ts
readonly optional __type?: T;Phantom marker for the component's value type; never present at runtime.
defaults?
ts
readonly optional defaults?: () => T;Returns
T
name
ts
readonly name: string;DeclareCommandOptions
Properties
validatePayload?
ts
optional validatePayload?: (payload) => PayloadCheck;Parameters
payload
Returns
DMath
Properties
PI
ts
readonly PI: number;TAU
ts
readonly TAU: number;Methods
abs()
ts
abs(x): number;Parameters
x
number
Returns
number
acos()
ts
acos(x): number;Parameters
x
number
Returns
number
asin()
ts
asin(x): number;Parameters
x
number
Returns
number
atan()
ts
atan(x): number;Parameters
x
number
Returns
number
atan2()
ts
atan2(y, x): number;Parameters
y
number
x
number
Returns
number
cbrt()
ts
cbrt(x): number;Parameters
x
number
Returns
number
ceil()
ts
ceil(x): number;Parameters
x
number
Returns
number
clamp()
ts
clamp(
x,
lo,
hi
): number;Parameters
x
number
lo
number
hi
number
Returns
number
cos()
ts
cos(x): number;Parameters
x
number
Returns
number
exp()
ts
exp(x): number;Parameters
x
number
Returns
number
floor()
ts
floor(x): number;Parameters
x
number
Returns
number
frac()
ts
frac(x): number;Fractional part in [0, 1): x - floor(x).
Parameters
x
number
Returns
number
hypot()
ts
hypot(
x,
y,
z?
): number;Parameters
x
number
y
number
z?
number
Returns
number
lerp()
ts
lerp(
a,
b,
t
): number;a + (b - a) * t; t is not clamped.
Parameters
a
number
b
number
t
number
Returns
number
log()
ts
log(x): number;Parameters
x
number
Returns
number
log10()
ts
log10(x): number;Parameters
x
number
Returns
number
log2()
ts
log2(x): number;Parameters
x
number
Returns
number
max()
ts
max(a, b): number;Parameters
a
number
b
number
Returns
number
min()
ts
min(a, b): number;Parameters
a
number
b
number
Returns
number
pow()
ts
pow(x, y): number;Parameters
x
number
y
number
Returns
number
round()
ts
round(x): number;Parameters
x
number
Returns
number
sign()
ts
sign(x): number;Parameters
x
number
Returns
number
sin()
ts
sin(x): number;Parameters
x
number
Returns
number
smoothstep()
ts
smoothstep(x): number;Hermite smoothstep of x clamped to [0, 1].
Parameters
x
number
Returns
number
sqrt()
ts
sqrt(x): number;Parameters
x
number
Returns
number
tan()
ts
tan(x): number;Parameters
x
number
Returns
number
wrapAngle()
ts
wrapAngle(a): number;Wrap an angle (radians) into (-PI, PI].
Parameters
a
number
Returns
number
Experience
Properties
kind
ts
readonly kind: "molen-experience";setup
ts
readonly setup: WorldSetup;ExperienceDef
Properties
commands?
ts
optional commands?: Record<string,
| CommandHandler<World>
| CommandTypeDef<World>>;Command type -> handler (or handler + payload validator).
setup?
ts
optional setup?: WorldSetup;Imperative escape hatch; runs after commands/systems are registered.
systems?
ts
optional systems?: object[];fn
ts
fn: System;name?
ts
optional name?: string;phase?
ts
optional phase?: Phase;FsmData
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
state
ts
state: string;transitions
ts
transitions: FsmTransition[];FsmTransition
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
event
ts
event: string;from
ts
from: string;to
ts
to: string;GameplayOptions
Properties
fsm?
ts
optional fsm?: boolean;hierarchy?
ts
optional hierarchy?: boolean;lifetime?
ts
optional lifetime?: boolean;timers?
ts
optional timers?: boolean;tweens?
ts
optional tweens?: boolean;HardenScriptsOptions
Taming options for hardenScripts: the slice of SES's lockdown() options a kernel host has reason to choose. Anything omitted keeps SES's own default.
Properties
errorTaming?
ts
optional errorTaming?: "safe" | "unsafe" | "unsafe-debug";'safe' (SES's default) takes the error.stack accessor away from the whole process, host code included; 'unsafe' keeps stacks readable, which is usually what you want while debugging. Script failures carry the kernel's script "x" tick handler at tick n: … message either way — stacks only affect what the host can log around it.
overrideTaming?
ts
optional overrideTaming?: "moderate" | "min" | "severe";Override-by-assignment mitigation. 'severe' (our default) applies it to every property, the most forgiving setting for ordinary JS that assigns to an inherited property; SES's own default 'moderate' covers the well-known cases and starts faster. A compatibility knob, not a safety one.
stackFiltering?
ts
optional stackFiltering?: "concise" | "omit-frames" | "shorten-paths" | "verbose";How much of a stack tamed error reports keep.
InstallScriptingOptions
Properties
extensions?
ts
optional extensions?: Record<string, object>;Extra namespaces merged onto molen (deep-frozen for SES hygiene) — how capability packages reach a script without kernel coupling, e.g. { physics: rapierScriptApi(handle) }.
manifest?
ts
optional manifest?: SceneManifest;Manifest enabling molen.spawn(prefabName, components?).
types?
ts
optional types?: ResolvedTypes;validate?
ts
optional validate?: boolean;Validate component shapes on spawn/set against the registry (default true).
JsonObject
Extended by
CharacterDataMoveIntentDataPlatformBodyDataPlatformIntentDataPlatformSolidDataMountableDataMountedDataSeatDataVehicleInputDataVehicleStateDataAudioMusicPayloadAudioPlayPayloadAudioStopPayloadFsmDataFsmTransitionLifetimeDataParentDataTimerDataTimerEntryTransformDataTweenDataTweenEntryColliderDataKinematicBodyData
Indexable
ts
[key: string]: JsonValue | undefinedKernelHostOptions
Properties
clock?
ts
optional clock?: SchedulerClock;keyframeInterval?
ts
optional keyframeInterval?: number;Ticks between full keyframes (default from the scene's keyframeInterval, else 60).
rate?
ts
optional rate?: number;startPaused?
ts
optional startPaused?: boolean;Start paused; the client sends a resume control message to begin. Default false.
KernelWorker
Properties
host
ts
host: KernelHost;world
ts
world: World;LifetimeData
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
ticksLeft
ts
ticksLeft: number;LoadedProject
Properties
scene
ts
scene: SceneManifest;types?
ts
optional types?: ResolvedTypes;Present only when types documents were given; spreads straight into buildWorld.
LoadedScript
Properties
checkpoint?
ts
optional checkpoint?: "state";config?
ts
optional config?: JsonObject;id
ts
id: string;source
ts
source: string;LoadProjectOptions
Properties
scene
ts
scene: unknown;The scene document as imported JSON. Validated as molen/scene@3.
scripts?
ts
optional scripts?: Readonly<Record<string, string>>;Raw script sources, as a bundler's eager raw glob hands them over: module path to source text. Keys are matched to each script's path by suffix, so the glob's own prefix (../scenes/, ../, wherever the module sits) does not have to be stripped by hand.
types?
ts
optional types?: unknown;Entity type registry documents as imported JSON, one or several. Omit when the scene declares no type refs.
ParentData
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
id
ts
id: string;onParentDestroyed?
ts
optional onParentDestroyed?: "destroy" | "detach";QueryResult
Extends
Iterable<[EntityId,...T]>
Type Parameters
T
T extends JsonObject[]
Methods
count()
ts
count(): number;Returns
number
first()
ts
first(): [string, ...T[]] | undefined;Returns
[string, ...T[]] | undefined
ids()
ts
ids(): readonly string[];Returns
readonly string[]
without()
ts
without(...exclude): QueryResult<T>;The same query, excluding entities that carry ANY of the given components.
Parameters
exclude
...ComponentType<JsonObject>[]
Returns
QueryResult<T>
Rng
Methods
int()
ts
int(n): number;Next integer in [0, n) for integer n > 0.
Parameters
n
number
Returns
number
next()
ts
next(): number;Next float in [0, 1).
Returns
number
range()
ts
range(lo, hi): number;Float in [lo, hi).
Parameters
lo
number
hi
number
Returns
number
save()
ts
save(): RngState;Capture state for snapshots.
Returns
RngState
SceneResolveOptions
Extends
SceneResolveOptions
Extended by
Properties
defaults?
ts
optional defaults?: Readonly<Record<string, JsonObject>>;gameplay?
ts
optional gameplay?: boolean;registry?
ts
optional registry?: ComponentRegistry;types?
ts
optional types?: ResolvedTypes;Flattened registry types; required when the scene references type ids.
Inherited from
ts
SceneResolveOptions.typesSchedulerClock
Methods
clearTimer()
ts
clearTimer(h): void;Parameters
h
number
Returns
void
now()
ts
now(): number;Returns
number
setTimer()
ts
setTimer(cb, ms): number;Parameters
cb
() => void
ms
number
Returns
number
SchedulerOptions
Properties
clock?
ts
optional clock?: SchedulerClock;Injectable clock for deterministic tests; defaults to Date.now + setTimeout.
maxCatchUpTicks?
ts
optional maxCatchUpTicks?: number;Max ticks to catch up per wake before dropping debt (spiral-of-death guard).
onError?
ts
optional onError?: (error, tick) => void;Called when a tick (or its onTick callback) throws. The scheduler has already paused; the world is faulted and start() will refuse until it is restored. tick is the tick the world was on when it failed.
Parameters
error
Error
tick
number
Returns
void
onOverrun?
ts
optional onOverrun?: (droppedTicks) => void;Called when the catch-up cap is hit and ticks are dropped.
Parameters
droppedTicks
number
Returns
void
onTick?
ts
optional onTick?: (tick) => void;Called once per advanced tick (after world.step()).
Parameters
tick
number
Returns
void
rate?
ts
optional rate?: number;Playback rate multiplier; 1 = realtime. The sim tick rate is the world's tickRate.
ScriptAPI
The agent-facing verb set (string component names; scripts are text).
Properties
audio
ts
readonly audio: AudioScriptApi;Sound: play(sound, { entity | position, gain, pitch, bus, loop }) → handle, stop(handle | { entity, sound }, fadeS?), music(playlist | null). Each emits an audio.* event the client plays; nothing enters the state hash. See guide/audio.md.
dt
ts
readonly dt: number;math
ts
readonly math: DMath;state
ts
readonly state: Readonly<JsonObject>;Immutable script-owned JSON state, captured in checkpoints and preserved on reload.
tick
ts
readonly tick: number;Methods
after()
ts
after(
ticks,
event,
payload?
): string;Emit event after ticks ticks (snapshot-safe world timer). Returns the timer id.
Parameters
ticks
number
event
string
payload?
Returns
string
cancelTimer()
ts
cancelTimer(timerId, entity?): void;Parameters
timerId
string
entity?
string
Returns
void
cancelTween()
ts
cancelTween(entity, tweenId?): void;Parameters
entity
string
tweenId?
string
Returns
void
destroy()
ts
destroy(id): void;Parameters
id
string
Returns
void
emit()
ts
emit(type, payload): void;Parameters
type
string
payload
Returns
void
every()
ts
every(
ticks,
event,
payload?
): string;Emit event every ticks ticks. Returns the timer id.
Parameters
ticks
number
event
string
payload?
Returns
string
exists()
ts
exists(id): boolean;Parameters
id
string
Returns
boolean
get()
ts
get(id, component): JsonObject | undefined;Parameters
id
string
component
string
Returns
JsonObject | undefined
has()
ts
has(id, component): boolean;Parameters
id
string
component
string
Returns
boolean
on()
ts
on(event, handler): Unsubscribe;Parameters
event
string
handler
(payload, ctx) => void
Returns
onCommand()
ts
onCommand(type, handler): Unsubscribe;Handle a command type (player input, agent actions). The scene declares the type (and its payload schema) under commands; the queue rejects undeclared types and bad payloads before any handler runs. Handlers run in the commands phase, before every system.
Parameters
type
string
handler
(payload, ctx, command) => void
Returns
overlapCircle()
ts
overlapCircle(
center,
radius,
mask?
): string[];Parameters
center
radius
number
mask?
number
Returns
string[]
parent()
ts
parent(id, parentId): void;Parent an entity (keeps its current world pose); the hierarchy system takes over.
Parameters
id
string
parentId
string
Returns
void
patch()
ts
patch(
id,
component,
partial
): void;Parameters
id
string
component
string
partial
Returns
void
patchState()
ts
patchState(partial): void;Parameters
partial
Returns
void
query()
ts
query(...components): ScriptQuery;Entities having all named components. The result is iterable (yields [id, ...componentData] tuples) and also exposes .ids(), .count(), .first(), .without(...names).
Parameters
components
...string[]
Returns
raycast()
ts
raycast(
origin,
dir,
maxDist,
mask?
): RayHit | null;Parameters
origin
dir
maxDist
number
mask?
number
Returns
RayHit | null
remove()
ts
remove(id, component): void;Parameters
id
string
component
string
Returns
void
rng()
ts
rng(): number;Returns
number
set()
ts
set(
id,
component,
data
): void;Parameters
id
string
component
string
data
Returns
void
setState()
ts
setState(data): void;Parameters
data
Returns
void
spawn()
Call Signature
ts
spawn(components, id?): string;Spawn from a component map.
Parameters
components
Record<string, JsonObject>
id?
string
Returns
string
Call Signature
ts
spawn(
prefab,
components?,
id?
): string;Spawn from a manifest prefab by name, with optional components layered on top.
Parameters
prefab
string
components?
Record<string, JsonObject>
id?
string
Returns
string
spawnType()
ts
spawnType(
type,
components?,
id?
): string;Spawn a project-registry type with optional component overrides.
Parameters
type
string
components?
Record<string, JsonObject>
id?
string
Returns
string
tween()
ts
tween(entity, spec): void;Start a data-driven tween on an entity (component + path + to + ticks [+ easing/loop]).
Parameters
entity
string
spec
Returns
void
unparent()
ts
unparent(id): void;Parameters
id
string
Returns
void
ScriptHost
Properties
count
ts
readonly count: number;Number of registered scripts.
Methods
reload()
ts
reload(id, source): void;Re-evaluate a script's source in a fresh Compartment (world state survives).
Parameters
id
string
source
string
Returns
void
ScriptQuery
The string-named query result scripts get (adds string-based .without()).
Extends
Iterable<[EntityId,...JsonObject[]]>
Methods
count()
ts
count(): number;Returns
number
first()
ts
first(): [string, ...JsonObject[]] | undefined;Returns
[string, ...JsonObject[]] | undefined
ids()
ts
ids(): readonly string[];Returns
readonly string[]
without()
ts
without(...components): ScriptQuery;The same query, excluding entities carrying ANY of the named components.
Parameters
components
...string[]
Returns
StartKernelWorkerOptions
Extends
Properties
capabilities?
ts
optional capabilities?: (world, manifest) => Record<string, object> | undefined[];Capability hooks (figures, vehicles, …), run in order after terrain and before setup. Same contract as physics: each may return script-api extension namespaces.
Parameters
world
manifest
SceneManifest
Returns
Record<string, object> | undefined
Inherited from
BuildWorldOptions.capabilities
content?
ts
optional content?: ContentIdentity;Which content the world is built from (see ContentIdentity), e.g. a type library's hash. Recorded in keyframes and replays next to the state hash, never inside it.
Inherited from
defaults?
ts
optional defaults?: Readonly<Record<string, JsonObject>>;Inherited from
devFreeze?
ts
optional devFreeze?: boolean;Inherited from
gameplay?
ts
optional gameplay?: boolean;Inherited from
host?
ts
optional host?: KernelHostOptions;Host options. keyframeInterval defaults to the scene's own.
link?
ts
optional link?: MessageLink;Where to speak. Defaults to this worker's own global scope.
physics?
ts
optional physics?: (world, manifest) => Record<string, object> | undefined;Physics plugin hook (e.g. rapier), run after the data-declared systems and before setup. May return script-api extension namespaces ({ physics: rapierScriptApi(handle) }).
Parameters
world
manifest
SceneManifest
Returns
Record<string, object> | undefined
Inherited from
registry?
ts
optional registry?: ComponentRegistry;Inherited from
scene
ts
scene: SceneManifest;The manifest, scripts already inlined — loadProject returns one.
scriptExtensions?
ts
optional scriptExtensions?: Record<string, object>;Extra script-api namespaces merged with whatever the hooks return.
Inherited from
BuildWorldOptions.scriptExtensions
scripts?
ts
optional scripts?: boolean;Install resolved type scripts followed by the manifest's scripts (default true).
Inherited from
setup?
ts
optional setup?: WorldSetup;terrain?
ts
optional terrain?: (world, manifest) => Record<string, object> | undefined;Terrain ground field hook, run after physics and before setup. Same contract as physics: returns script-api extensions ({ terrain: terrainScriptApi(handle) }).
Parameters
world
manifest
SceneManifest
Returns
Record<string, object> | undefined
Inherited from
types?
ts
optional types?: ResolvedTypes;Flattened registry types; required when the scene references type ids.
Inherited from
validateSpawn?
ts
optional validateSpawn?: boolean;Inherited from
BuildWorldOptions.validateSpawn
SubmitResult
Properties
accepted
ts
accepted: boolean;reason?
ts
optional reason?: string;Set when rejected: human/agent-facing reason.
tickExecuted?
ts
optional tickExecuted?: number;Set when accepted: the tick the command will actually execute on.
SystemInfo
Properties
name
ts
name: string;order
ts
order: number;phase
ts
phase: Phase;TickContext
Properties
dt
ts
dt: number;rng
ts
rng: Rng;tick
ts
tick: number;TimerData
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
timers
ts
timers: TimerEntry[];TimerEntry
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
event
ts
event: string;id
ts
id: string;payload?
ts
optional payload?: JsonValue;repeatEvery?
ts
optional repeatEvery?: number;ticksLeft
ts
ticksLeft: number;TimerSpec
Properties
event
ts
event: string;id?
ts
optional id?: string;payload?
ts
optional payload?: JsonValue;repeatEvery?
ts
optional repeatEvery?: number;ticks
ts
ticks: number;TransformData
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
pos
ts
pos: [number, number, number];rot
ts
rot: [number, number, number, number];scale?
ts
optional scale?: [number, number, number];TransformLike
Properties
pos
ts
pos: Vec3;rot?
ts
optional rot?: Quat;scale?
ts
optional scale?: Vec3;TweenData
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
tweens
ts
tweens: TweenEntry[];TweenEntry
Extends
Indexable
ts
[key: string]: JsonValue | undefinedProperties
component
ts
component: string;easing?
ts
optional easing?: Easing;elapsed?
ts
optional elapsed?: number;Kernel-owned progress (snapshot-safe).
emitOnComplete?
ts
optional emitOnComplete?: string;from?
ts
optional from?: number | number[];id?
ts
optional id?: string;loop?
ts
optional loop?: "none" | "loop" | "pingpong";path
ts
path: string;Select-style value path within the component, e.g. "pos", "pos[1]", "primitive.size".
ticks
ts
ticks: number;to
ts
to: number | number[];TypeLibrary
Properties
hash
ts
readonly hash: string;Hash over every resolved type (components and scripts); the same for any document order.
types
ts
readonly types: ResolvedTypes;The resolved registry; pass it as types to buildWorld.
Methods
component()
ts
component<T>(id, name): T;One resolved component of a type, as a fresh copy; throws when the type lacks it.
Type Parameters
T
T
Parameters
id
string
name
string
Returns
T
components()
ts
components(id): ComponentMap;A type's resolved components (inherited ones included), as a fresh copy.
Parameters
id
string
Returns
ComponentMap
has()
ts
has(id): boolean;Parameters
id
string
Returns
boolean
ids()
ts
ids(): string[];Every type id, in document order.
Returns
string[]
idsWith()
ts
idsWith(name): string[];Ids of the types that have a component, in document order.
Parameters
name
string
Returns
string[]
TypeLibraryOptions
Properties
label?
ts
optional label?: string;Names the content in errors, e.g. "molen.entities@0.0.1".
scripts?
ts
optional scripts?: Readonly<Record<string, string>>;Script sources for types whose scripts use path refs, as a bundler's raw glob hands them over (matched by path suffix). Types without scripts, or with inline code, need none.
WorldOptions
Properties
content?
ts
optional content?: ContentIdentity;Which content the world is built from (see ContentIdentity). Recorded in keyframes next to the state hash, never in it; loading a keyframe with different content fails by name.
defaults?
ts
optional defaults?: Readonly<Record<string, JsonObject>>;World-local default values override package defaults for the named components.
devFreeze?
ts
optional devFreeze?: boolean;Dev mode deep-freezes component data ONCE when it enters the store (freeze-on-write), so reads hand back the stored object and accidental mutation throws. Default true.
Aliasing rule (both modes): get() and query rows return the live stored object, never a copy. Never mutate what you read — in dev worlds it throws; with devFreeze: false it silently corrupts state and deltas. set/patch/spawn always install a NEW object, so a reference you hold goes stale after the next write, never corrupted.
lateCommands?
ts
optional lateCommands?: LateCommandPolicy;Late-command policy (command.tick <= currentTick). Default 'rewrite'.
registry?
ts
optional registry?: ComponentRegistry;Isolated component vocabulary; defaults to a copy of package registrations.
seed?
ts
optional seed?: string | number;tickRate?
ts
optional tickRate?: number;Hz; dt = 1/tickRate. Immutable for the world's lifetime.
validateSpawn?
ts
optional validateSpawn?: boolean;Validate component shapes in spawn() against the schema registry. Default = devFreeze.
Type Aliases
CommandHandler
ts
type CommandHandler<W> = (world, command, ctx) => void;Type Parameters
W
W
Parameters
world
W
command
Command
ctx
Returns
void
Easing
ts
type Easing =
| "linear"
| "quadIn"
| "quadOut"
| "quadInOut"
| "cubicIn"
| "cubicOut"
| "cubicInOut";EventHandler
ts
type EventHandler = (event, ctx) => void;Parameters
event
EngineEvent
ctx
Returns
void
JsonPrimitive
ts
type JsonPrimitive = string | number | boolean | null;JsonValue
ts
type JsonValue =
| JsonPrimitive
| JsonValue[]
| JsonObject;LateCommandPolicy
ts
type LateCommandPolicy = "rewrite" | "reject";PayloadCheck
ts
type PayloadCheck =
| {
ok: true;
}
| {
message: string;
ok: false;
};Result of a payload validator: ok, or a formatted, agent-facing reason.
Phase
ts
type Phase = "commands" | "update" | "physics" | "late";Quat
ts
type Quat = [number, number, number, number];ResolvedTypes
ts
type ResolvedTypes = ReadonlyMap<string, ResolvedEntityType>;Pre-flattened project type registry.
System
ts
type System = (world, ctx) => void;Parameters
world
ctx
Returns
void
TimerHandle
ts
type TimerHandle = ReturnType<typeof setTimeout>;Unsubscribe
ts
type Unsubscribe = () => void;Returns
void
Vec3
ts
type Vec3 = [number, number, number];WorldSetup
ts
type WorldSetup = (world, manifest) => void;Convenience for tooling: a manifest plus a code setup step (systems + command handlers).
Parameters
world
manifest
SceneManifest
Returns
void
Variables
AUDIO_MUSIC
ts
const AUDIO_MUSIC: "audio.music";Event emitted by molen.audio.music.
AUDIO_PLAY
ts
const AUDIO_PLAY: "audio.play";Event emitted by molen.audio.play.
AUDIO_STOP
ts
const AUDIO_STOP: "audio.stop";Event emitted by molen.audio.stop.
AudioEnvironment
ts
const AudioEnvironment: ComponentType<AudioEnvironmentData>;AudioSource
ts
const AudioSource: ComponentType<AudioSourceData>;AudioZone
ts
const AudioZone: ComponentType<AudioZoneData>;CONTENT_KEY
ts
const CONTENT_KEY: "$content" = "$content";Keyframes record content identity under this reserved plugins key, beside $format.
dmath
ts
const dmath: DMath;ENGINE_VERSION
ts
const ENGINE_VERSION: "0.0.4" = "0.0.4";The kernel package's published version. Informational metadata only: it rides along in a keyframe so a save file says which build wrote it, and it is NOT compared on load and NOT hashed. Keep it in step with packages/kernel/package.json (a unit test pins the two together).
Fsm
ts
const Fsm: ComponentType<FsmData>;Lifetime
ts
const Lifetime: ComponentType<LifetimeData>;LocalTransform
ts
const LocalTransform: ComponentType<TransformData>;Parent
ts
const Parent: ComponentType<ParentData>;STATE_FORMAT
ts
const STATE_FORMAT: 1 = 1;The state-format generation: what actually has to match for a keyframe to be loadable and for two state hashes to be comparable. Bump it ONLY when simulation semantics or the snapshot layout change — never for a release, a docs edit, or a client-only change. Every release on the fixed version line used to invalidate every save file and every recorded *.replay.json because the package version was the gate; this constant is the gate now.
STATE_FORMAT_KEY
ts
const STATE_FORMAT_KEY: "$format" = "$format";Keyframes record their state format under this reserved key in plugins (the one extensible field of molen/keyframe@1; $scripts is the same kind of reserved name). A keyframe written before the key existed is read as format 1, the layout in use when it was introduced.
Timer
ts
const Timer: ComponentType<TimerData>;Transform
ts
const Transform: ComponentType<TransformData>;Tween
ts
const Tween: ComponentType<TweenData>;Weather
ts
const Weather: ComponentType<WeatherData>;Functions
applyDelta()
ts
function applyDelta(store, delta): Record<EntityId, ComponentMap>;Apply a delta to a passive entity-major store (the client mirror / replay scrubber). Mutates and returns the store. Shared by client interpolation and tests.
Parameters
store
Record<EntityId, ComponentMap>
delta
Delta
Returns
Record<EntityId, ComponentMap>
applyKeyframeTo()
ts
function applyKeyframeTo(
world,
keyframe,
options?
): void;Load a keyframe's state into an existing world in place (replacing entities, RNG, tick, and counter), keeping its registered systems/commands. The replay scrubber uses this to seek. Acceptance is gated on the STATE_FORMAT generation, never on the engine version, and on the content both sides recorded.
Parameters
world
keyframe
Keyframe
options?
Returns
void
approach()
ts
function approach(
value,
target,
amount
): number;Move value toward target by at most amount (amount ≥ 0).
Parameters
value
number
target
number
amount
number
Returns
number
audioEnvironmentOf()
ts
function audioEnvironmentOf(world): Readonly<AudioEnvironmentData> | undefined;First audioEnvironment entity in world order (the singleton), like weatherOf.
Parameters
world
Returns
Readonly<AudioEnvironmentData> | undefined
audioScriptApi()
ts
function audioScriptApi(world): AudioScriptApi;The molen.audio namespace: thin wrappers that emit audio.play|stop|music events. Handles are ${sound}@${tick}#${n} (n counts calls within the tick), so they are deterministic.
Parameters
world
Returns
buildWorld()
ts
function buildWorld(
manifest,
setup?,
opts?
): World;The one way every host builds a world from a scene — tooling ops, example workers, tests:
createWorldFromScene (gameplay → kinematics/character → commands → entities) → opts.physics?() → opts.terrain?() → opts.capabilities → setup?() → resolved type scripts → the manifest's scripts.
Scripts install last so they see every declared command and every capability extension. Type and manifest scripts must already be inline (code); resolve path refs first with inlineScriptSources (browser) or the tooling scene loader (Node).
Parameters
manifest
SceneManifest
setup?
opts?
Returns
cancelTimer()
ts
function cancelTimer(
world,
entity,
timerId
): void;Parameters
world
entity
string | null
timerId
string
Returns
void
cancelTween()
ts
function cancelTween(
world,
entity,
tweenId?
): void;Parameters
world
entity
string
tweenId?
string
Returns
void
canonicalBytes()
ts
function canonicalBytes(value): Uint8Array;Canonical byte serialization of a JSON value (sorted keys, IEEE-754 number bits).
Parameters
value
Returns
Uint8Array
cloneJson()
ts
function cloneJson<T>(value): T;Structured deep clone of pure-JSON data. Used so stored components never alias caller data.
Type Parameters
T
T extends JsonValue
Parameters
value
T
Returns
T
componentDefaults()
ts
function componentDefaults(name): (() => JsonObject) | undefined;The registered defaults factory for a component name (from any defineComponent call).
Parameters
name
string
Returns
(() => JsonObject) | undefined
componentHandle()
ts
function componentHandle(name): ComponentType<JsonObject>;A memoized bare handle for a wire-string component name (no defaults). The string-based surfaces (scripts, tweens, data-driven systems) use this so they never allocate a handle per call.
Parameters
name
string
Returns
ComponentType<JsonObject>
composeTransforms()
ts
function composeTransforms(parent, local): TransformLike;world = parent ∘ local (scale is component-wise; no shear).
Parameters
parent
local
Returns
contentDrift()
ts
function contentDrift(recorded, loaded): string[];Differences between recorded and loaded content, one message per domain present in both with a different hash. Domains only one side has are not compared: a replay recorded before a domain existed, or a host that loads extra content, is not a mismatch.
Parameters
recorded
ContentIdentity
loaded
ContentIdentity
Returns
string[]
createRng()
ts
function createRng(seed): Rng;Build an RNG from a world seed (string or number).
Parameters
seed
string | number
Returns
createTypeLibrary()
ts
function createTypeLibrary(docs, options?): TypeLibrary;Build a type library from molen/types@1 documents already in memory.
Parameters
docs
unknown
options?
Returns
createWorldFromScene()
ts
function createWorldFromScene(manifest, opts?): World;Build a World from a validated scene manifest: applies tickRate/seed/lateCommands, installs the data-declared systems (gameplay, kinematics + character when physics asks for them), declares the scene's commands (with their payload validators) and custom components, and instantiates entities (type/prefab/components) in manifest order, preserving authored ids.
Code setup (systems, command handlers) and the manifest's own scripts are NOT installed here; buildWorld layers those on top in the documented order.
Parameters
manifest
SceneManifest
opts?
object & SceneResolveOptions
Returns
deepFreeze()
ts
function deepFreeze<T>(value): T;Deep-freeze pure-JSON data (dev mode) so in-place mutation throws instead of corrupting deltas.
Type Parameters
T
T extends JsonValue
Parameters
value
T
Returns
T
defineComponent()
ts
function defineComponent<T>(name, opts?): ComponentType<T>;Type Parameters
T
T extends JsonObject
Parameters
name
string
opts?
defaults?
() => T
Returns
ComponentType<T>
defineExperience()
ts
function defineExperience(def): Experience;Define an experience: commands + systems + an optional imperative setup, composed into one WorldSetup. buildWorld(manifest, experience.setup) — or hand the whole object to tooling, whose setup loader accepts either form.
Parameters
def
Returns
hardenScripts()
ts
function hardenScripts(options?): boolean;Turn script evaluation into an actual isolation boundary by running SES lockdown() once for this process. Returns true if this call performed the lockdown, false if the realm was already hardened (calling it repeatedly is safe).
Without it, scripts are deterministic but not contained: they share the realm's mutable intrinsics and can reach the host global. After it, intrinsics are frozen and Function.prototype.constructor no longer builds a function in the host realm, so the usual escape fails.
Call it at host startup, before building a world, and only in a process whose job is running the kernel — a Worker or a dedicated Node host. lockdown() is process-global and irreversible: do not call it in a host that also runs bundlers, image or asset tooling, or a browser-automation stack, because frozen intrinsics break libraries that patch prototypes at runtime. The molen CLI and MCP server deliberately do not call it.
Determinism does not depend on this: the tamed Math/Date/Intl endowments already give that. Hardening only changes what a hostile script can reach.
Parameters
options?
Returns
boolean
hashBytes()
ts
function hashBytes(data): string;SHA-256 of raw bytes, prefixed "sha256:".
Parameters
data
Uint8Array
Returns
string
hashJson()
ts
function hashJson(value): string;Stable SHA-256 of a JSON value, prefixed "sha256:".
Parameters
value
Returns
string
identityQuat()
ts
function identityQuat(): Quat;A fresh identity quaternion [0, 0, 0, 1].
Returns
inlineScriptSources()
ts
function inlineScriptSources(manifest, sources): SceneManifest;Replace every path script ref with inline code from sources (keyed by the exact path string). Pure; returns a shallow copy of the manifest. Browsers use this with a bundler's raw imports; the Node tooling loader reads the files itself.
Parameters
manifest
SceneManifest
sources
Record<string, string>
Returns
SceneManifest
installFsm()
ts
function installFsm(world): void;Parameters
world
Returns
void
installGameplay()
ts
function installGameplay(world, opts?): void;Install the gameplay systems (all on by default). createWorldFromScene calls this.
Parameters
world
opts?
Returns
void
installHierarchy()
ts
function installHierarchy(world): void;Parameters
world
Returns
void
installLifetime()
ts
function installLifetime(world): void;Parameters
world
Returns
void
installSceneScripts()
ts
function installSceneScripts(
world,
manifest,
opts?
): ScriptHost;Install the scripts declared in a scene manifest's scripts field as scene data — no setup module required. Maps the wire field code to the host's source and threads the manifest so scripts can molen.spawn(prefabName, …). Returns a no-op host when the manifest has no scripts. Scripts still carrying an unresolved path (a file ref) throw — the kernel is fs-free; run the manifest through the tooling scene loader (which inlines path into code) first.
Parameters
world
manifest
SceneManifest
opts?
extensions?
Record<string, object>
types?
validate?
boolean
Returns
installScripting()
ts
function installScripting(
world,
scripts,
opts?
): ScriptHost;Install scripting on a world: evaluate each script in a Compartment, run tick handlers in a single update-phase system (registration order), and route world events to script handlers.
Scripts may author logic two ways: at the top level using the injected molen/config globals, or by exporting a setup(molen, config) function (defined as a top-level function setup in its Compartment). A script that registers no molen.on handlers is warned about — that is the classic silent no-op (a typo'd verb leaves the script doing nothing).
Parameters
world
scripts
opts?
Returns
installTimers()
ts
function installTimers(world): void;Parameters
world
Returns
void
installTweens()
ts
function installTweens(world): void;Parameters
world
Returns
void
inverseTransformPoint()
ts
function inverseTransformPoint(t, p): Vec3;A world point into the local frame of a transform (the inverse of transformPoint).
Parameters
t
p
Returns
isExperience()
ts
function isExperience(value): value is Experience;Is a value an Experience (vs a bare WorldSetup function)?
Parameters
value
unknown
Returns
value is Experience
keyframeContent()
ts
function keyframeContent(keyframe): ContentIdentity | undefined;The identity a keyframe recorded, or undefined for one written without content.
Parameters
keyframe
Keyframe
Returns
ContentIdentity | undefined
keyframeStateFormat()
ts
function keyframeStateFormat(keyframe): number;The state format a keyframe was written in. Keyframes from before the format key existed carry the layout it was introduced at (1), so they keep loading.
Parameters
keyframe
Keyframe
Returns
number
loadProject()
ts
function loadProject(options): LoadedProject;Validate a project's documents and hand back what a host needs: the scene manifest with its scripts inlined, and the resolved type registry. Throws with the validator's formatted error — the same text molen validate prints — so a bad document fails at load with a pinpointed message rather than somewhere inside the first tick.
Parameters
options
Returns
lookRotation()
ts
function lookRotation(forward, up?): Quat;The rotation whose +Z axis points along forward with +Y as close to up as possible. Returns identity for a zero-length forward or a forward parallel to up.
Parameters
forward
up?
Returns
patchJson()
ts
function patchJson<T>(base, partial): T;Shallow-merge a partial patch into a clone of base (whole-component semantics at top level). The result is a fresh null-prototype object, like every other stored component.
Type Parameters
T
T extends JsonObject
Parameters
base
T
partial
Partial<T>
Returns
T
quatConjugate()
ts
function quatConjugate(q): Quat;The inverse of a unit quaternion.
Parameters
q
Returns
quatDot()
ts
function quatDot(a, b): number;Parameters
a
b
Returns
number
quatFromAxisAngle()
ts
function quatFromAxisAngle(axis, angle): Quat;Rotation of angle radians about a unit axis.
Parameters
axis
angle
number
Returns
quatFromEuler()
ts
function quatFromEuler(
pitch,
yaw,
roll
): Quat;Intrinsic Y·X·Z Euler angles (yaw about +Y, then pitch about the rotated +X, then roll about the rotated +Z) — the natural order for characters and cameras.
Parameters
pitch
number
yaw
number
roll
number
Returns
quatFromTo()
ts
function quatFromTo(a, b): Quat;The shortest-arc rotation taking direction a to direction b (inputs need not be unit length). Identity for zero-length inputs; a half-turn about a perpendicular axis for opposite inputs.
Parameters
a
b
Returns
quatFromYaw()
ts
function quatFromYaw(yaw): Quat;Rotation of yaw radians about +Y (forward +Z turns toward +X for positive yaw).
Parameters
yaw
number
Returns
quatMul()
ts
function quatMul(a, b): Quat;Parameters
a
b
Returns
quatNormalize()
ts
function quatNormalize(q): Quat;Parameters
q
Returns
quatRotateVec3()
ts
function quatRotateVec3(q, v): Vec3;Parameters
q
v
Returns
quatSlerp()
ts
function quatSlerp(
a,
b,
t
): Quat;Spherical linear interpolation along the shortest arc; t is clamped to [0, 1]. Falls back to normalized linear interpolation when the inputs are nearly parallel.
Parameters
a
b
t
number
Returns
resolveEntityComponents()
ts
function resolveEntityComponents(
manifest,
entity,
opts?
): ComponentMap;Resolve a scene entity's final components (type <- prefab <- components).
Parameters
manifest
SceneManifest
entity
components?
ComponentMap
prefab?
string
type?
string
opts?
SceneResolveOptions
Returns
ComponentMap
resolvePrefab()
ts
function resolvePrefab(
manifest,
name,
opts?,
seen?
): ComponentMap;Resolve a prefab's components: registry type <- extends chain <- own components.
Parameters
manifest
SceneManifest
name
string
opts?
SceneResolveOptions
seen?
string[]
Returns
ComponentMap
restoreRng()
ts
function restoreRng(world, state): void;Restore RNG into a world (used by snapshot load).
Parameters
world
state
RngState
Returns
void
rngFromState()
ts
function rngFromState(state): Rng;Restore an RNG from a snapshotted state.
Parameters
state
RngState
Returns
sampleAtmosphere()
ts
function sampleAtmosphere(
data,
altitude?,
gravity?
): AtmosphereSample;Ideal-gas density and a simple isothermal hydrostatic pressure profile. Temperature, wind and humidity are uniform; no forecast, moist-air correction or automatic rain/snow switch. Altitude is absolute world Y in meters. Gravity and gas constant allow authored worlds.
Parameters
data
WeatherData
altitude?
number
gravity?
number
Returns
scheduleTimer()
ts
function scheduleTimer(
world,
entity,
spec
): string;Schedule a timer on an entity (null -> the kernel-owned $timers singleton). Returns its id.
Parameters
world
entity
string | null
spec
Returns
string
scriptsHardened()
ts
function scriptsHardened(): boolean;Whether this realm's intrinsics are frozen — by hardenScripts or by a host that called SES lockdown() itself.
Returns
boolean
seedToInt()
ts
function seedToInt(seed): number;Hash an arbitrary string/number seed into a 32-bit integer (FNV-1a for strings).
Parameters
seed
string | number
Returns
number
setParent()
ts
function setParent(
world,
id,
parentId
): void;Set a parent, initializing localTransform so the child keeps its current world pose.
Parameters
world
id
string
parentId
string
Returns
void
spawnFromData()
ts
function spawnFromData<T>(
world,
data,
template,
opts?
): string[];Bind a data array to entities (the visualization building block): spawn one entity per item via a template. With idPrefix, entities get stable ids (prefix0, prefix1, …) so later systems can update them by index.
Type Parameters
T
T
Parameters
world
data
readonly T[]
template
(item, index) => ComponentMap
opts?
idPrefix?
string
Returns
string[]
startKernelWorker()
ts
function startKernelWorker(options): KernelWorker;Build the world and serve it over the worker's message port: the whole body of a kernel worker entry. Returns both, so a host that wants to step manually or dispose still can.
keyframeInterval comes from the scene unless overridden, which is what makes a page's first frame arrive promptly instead of after a full keyframe period.
Parameters
options
Returns
startTween()
ts
function startTween(
world,
entity,
spec
): void;Start a tween on an entity (appends to its tween component).
Parameters
world
entity
string
spec
Returns
void
stateHash()
ts
function stateHash(world): string;Hash of serialized continuation state, including query order, commands, and plugin blobs. Equality assumes identical systems, script sources, and snapshot-safe host configuration. Mutable host/script closure state is outside this contract.
Parameters
world
Returns
string
takeDelta()
ts
function takeDelta(world, baseTick): Delta;Produce a delta capturing changes since the last takeDelta/keyframe boundary, then reset dirty tracking. Whole-component replacement granularity (docs-src/schemas/delta.md).
Parameters
world
baseTick
number
Returns
Delta
takeKeyframe()
ts
function takeKeyframe(world): Keyframe;Produce a complete keyframe of the world's current state (also the save-file format). A keyframe is a complete baseline, so it resets delta dirty-tracking: the next takeDelta reports only changes that happen after this keyframe.
Parameters
world
Returns
Keyframe
transformPoint()
ts
function transformPoint(t, p): Vec3;A local point through a transform: scale, rotate, then translate.
Parameters
t
p
Returns
unparent()
ts
function unparent(world, id): void;Parameters
world
id
string
Returns
void
weatherOf()
ts
function weatherOf(world): Readonly<WeatherData> | undefined;First weather entity in world order; absence preserves a consumer's existing atmosphere.
Parameters
world
Returns
Readonly<WeatherData> | undefined
worldFromKeyframe()
ts
function worldFromKeyframe(keyframe, opts?): World;Reconstruct a world from a keyframe. Restores entities, RNG, tick, and entity counter. Without opts.content, the world takes the content identity the keyframe recorded.
Parameters
keyframe
Keyframe
opts?
WorldOptions & ApplyKeyframeOptions
Returns
yawOf()
ts
function yawOf(q): number;Yaw (radians, about +Y) of the +Z forward direction of q. Zero when forward is +Z.
Parameters
q
Returns
number