@ferret/core
World, fixed-step loop, entities and components, services, event bus, logging and the debug command channel.
Classes
CommandChannel class
class CommandChannelregister(name: string, description: string, fn: CommandFn): void | |
has(name: string): boolean | |
unregister(name: string, restore?: { fn: CommandFn; description: string }): boolean | Take a command back; the one it had replaced (a register of the same name overwrites) is given back with it. |
entry(name: string): { fn: CommandFn; description: string } | undefined | What is registered under the name now (to keep for unregister's restore). |
list(): CommandInfo[] | |
async execute(name: string, args: any = {}): Promise<unknown> |
packages/core/src/commands.ts:10
Component class
abstract class Component<P extends object = Record<string, any>>A component is a plain class attached to an entity. Parameters come from the manifest (params).
Hooks: onAttach (attached), onStart (first fixed step after attach), onFixedUpdate(dt) at the fixed rate,
onUpdate(dt) once per rendered frame, onDetach (removed or entity destroyed).
entity: Entity | |
started: boolean | |
enabled: boolean | |
constructor(public params: P = {} as P) | |
get world(): World | |
get scene(): BABYLON.Scene | |
get node(): BABYLON.TransformNode | |
onAttach?(): void | |
onStart?(): void | |
onFixedUpdate?(dt: number): void | |
onFixedUpdateAsync?(dt: number): Promise<() => void> | null | The same step for a component whose work can go to the workers: called instead of onFixedUpdate when the world steps asynchronously and wantsAsync is true.
It takes what it needs from the component at its place in the step and returns a promise of the function that puts the result back; the world calls those functions in
the order of the components when every component has had its turn, so a component after this one sees the result at the next step. It returns null to say that this
step cannot go (the component then runs onFixedUpdate in its place). |
wantsAsync?(): boolean | the component class has work for the workers now (cheap: the world asks every step); a component that registers itself in world.asyncComponents is asked |
onUpdate?(dt: number): void | |
onDetach?(): void | |
kernels?: KernelDecl[] | kernels this component declares: taken at its first fixed step, dropped when it is detached |
schedule?: ModuleDecl | a module's description: taken at its first fixed step like kernels |
packages/core/src/component.ts:11
Entity class
class EntityAn entity wraps a Babylon TransformNode and carries components.
readonly id: string | |
readonly components: Component[] | |
readonly tags: Set<string> | |
timeDilation: number | Per-entity time dilation (a game may slow its NPCs). 1 = normal. |
destroyed: boolean | |
data: Record<string, any> | |
constructor(readonly world: World, readonly node: BABYLON.TransformNode, id?: string) | |
get name(): string | |
get position(): BABYLON.Vector3 | |
add<C extends Component>(cls: ComponentClass<C> | string, params?: any): C | |
get<C extends Component>(cls: ComponentClass<C> | string): C | undefined | |
require<C extends Component>(cls: ComponentClass<C> | string): C | |
remove(c: Component): void | |
destroy(): void |
packages/core/src/entity.ts:8
EventBus class
class EventBusSmall event bus. emit calls handlers synchronously, in subscription order.
on<T = any>(name: string, fn: Handler<T>): () => void | |
once<T = any>(name: string, fn: Handler<T>): () => void | |
off(name: string, fn: Handler): void | |
emit<T = any>(name: string, payload?: T): void | |
clear(): void |
packages/core/src/events.ts:5
FramePacer class
class FramePacerk: number | refreshes per drawn frame |
period: number | the display's refresh period, ms (learnt) |
constructor(readonly o: { maxK?: number; minPeriod?: number } = {}) | |
tick(now: number, lastWork = 0): PacerTick | a display callback at now (ms); lastWork the ms the previous drawn frame's own work took (its callback) |
packages/core/src/frame-pacer.ts:16
FrameProfiler class
class FrameProfilerenabled: boolean | |
window: number | the window, in frames, over which the worst value is kept (the previous window's worst stays shown until the new one has one) |
external: boolean | true when the game calls endFrame itself (it runs its own loop); the world then leaves it alone |
frames: number | |
frameMs: number | the whole frame, ms (wall clock between two endFrame calls), as a moving average and the worst |
frameWorst: number | |
time<T>(name: string, fn: () => T): T | time fn into slot name |
own<T>(name: string, fn: () => T): T | time a function of the game's own into slot own:name: the report of what the game's code costs in the game's thread lists it with its share and what would take it off |
begin(): number | start a span: pass the result to end |
end(name: string, t0: number): void | |
add(name: string, ms: number): void | add a measured span (ms) to the slot's frame total |
probe(name: string, read: () => number): void | a number read at the end of every frame and kept like a span (a probe may return NaN to say "not available") |
endFrame(): void | close the frame: every slot's total goes into its average and worst, the probes are read, the totals reset |
bound(): FrameBound | which side holds the frame, from the moving averages (the GPU's frame time comes from the gpu:frame probe of instrumentScene) |
startTrace(seconds = 60, minMs = 1): void | Record every frame for seconds (turns the profiler on): its length and the slots of at least minMs in it, the browser's long tasks, and the
game's marks. For the start of a game: where the long frames come from. Read it with trace(). |
mark(name: string): void | a moment worth seeing in the trace (only while a trace runs) |
stopTrace(): void | |
trace(): PerfTrace | null | the trace so far (null when none was started) |
report(prefix?: string): PerfRow[] | the slots, the most expensive first (names starting with prefix only, when given) |
text(top = 24, prefix?: string): string | the report as aligned text, with the frame line first |
reset(): void |
packages/core/src/perf.ts:36
JobPool class
class JobPoolreadonly size: number | |
readonly shared_: Record<string, SharedArray> | |
stats: { parallel: number; serial: number; } | runs counted by how they ran, for the perf report |
constructor(private o: JobPoolOptions) | |
shared<T extends SharedArray>(name: string, ctor: Ctor<T>, length: number): T | make (or fetch) a shared array every job can read and write by name |
map(phase: string, n: number, args?: unknown): void | run phase over items 0..n-1; returns when every item is done |
async dispose(): Promise<void> |
packages/core/src/job-pool.ts:66
Logger class
class Loggerlevel: LogLevel | |
sinks: Array<(level: LogLevel, scope: string, msg: string) => void> | Sinks receive every line at or above level; the OS Beroun platform adds one that posts to the shell's log. |
constructor(readonly scope: string) | |
debug(m: string) | |
info(m: string) | |
warn(m: string) | |
error(m: string) |
packages/core/src/log.ts:5
QualityService class
class QualityService implements Servicereadonly name: "quality" | |
get auto(): boolean | the regulator is on (never true for a service made with never) |
set auto(v: boolean) | the regulator is on (never true for a service made with never) |
readonly never: boolean | this service never lowers quality (see QualityOptions.never) |
readonly log: QualityDecision[] | |
constructor(private o: QualityOptions = {}) | |
init(world: World): void | |
register(knob: QualityKnob): void | add a knob; a level remembered from an earlier run is put back at once |
unregister(id: string): void | |
scopedView(keep: (undo: () => void) => void): this | The service as a docked level sees it (Scope.view): the knobs the level registers are taken off with the level. |
has(id: string): boolean | |
level(id: string): number | |
hold(reason: string): void | nothing changes while a hold is on (assets loading, a level coming in); the frames meanwhile are not counted |
release(reason: string): void | |
preset(share: number): void | every knob at a share of its range (0 the richest, 1 the cheapest); the regulator goes on from there when it is on |
targetHz(): number | the frame rate being held now |
update(): void | Called once per rendered frame. |
report(): QualityReport | |
text(): string | one line for the ?perf overlay |
dispose(): void |
packages/core/src/quality.ts:94
Registry class
class Registry<T>A name -> constructor registry. A manifest names components and behaviours; games register the classes.
constructor(readonly kind: string) | |
register(name: string, item: T): this | |
unregister(name: string): boolean | Take a registration back (a docked level's scope does at its end). Returns whether there was one. |
get(name: string): T | |
has(name: string): boolean | |
names(): string[] |
packages/core/src/registry.ts:3
Replica class
class Replicathe objects of the last snapshot applied: plain objects with the spec's property paths, the same objects from frame to frame while their key lives
readonly codec: SnapshotCodec | |
readonly lists: Record<string, any[]> | each collection's objects in snapshot order (one array per name, kept and refilled) |
readonly byKey: Record<string, Map<number, any>> | each collection's objects by key |
readonly records: Record<string, any> | each record's object |
tick: number | |
time: number | |
readonly undeclared: Set<string> | the reads of undeclared properties seen while audit is on: "collection.path" |
constructor(spec: SnapshotSpec | SnapshotCodec, private hooks: ReplicaHooks = {}) | |
apply(cur: SnapshotView, prev?: SnapshotView | null, alpha = 1): void | Rebuild the objects from cur; with prev and alpha the interpolated fields are between the two (0 is prev, 1 is cur). |
packages/core/src/snapshot.ts:142
ResidentLost class
class ResidentLost extends Errora pinned task lost its worker (and the state the worker kept for its pin); the caller sets the state up again and asks again
constructor(readonly pin: string) |
packages/core/src/task-pool.ts:9
Roles class
class Roles implements ServiceThe roles of a parent game: a mechanism a game has at most once (the player's character, the camera, the input, the net room, the menu ...).
The parent provides what it holds; while a level is docked (dock), the engine's own entry points that make a role (spawnCharacter, CameraRig, a service of the
same name) ask takeOver first, so code written for a game of its own that makes "its" character or camera gets the parent's instead, unless the level brings that role itself (has).
With no parent and no dock nothing here changes anything: takeOver makes what it is asked to make.
readonly name: "roles" | |
provide(role: string, impl: unknown): () => void | The parent gives its implementation of a role (an instance). Returns the way to withdraw it. |
holds(role: string): boolean | |
get<T = unknown>(role: string): T | undefined | |
list(): string[] | |
dock(level: string, has: Iterable<string> = []): () => void | A level is docked: has are the roles it brings itself. Returns the way to end the dock. |
get docked(): string | undefined | the level docked now, if any |
get given(): string[] | The roles the docked code asked for and was given the parent's instance of (for the converter's run and the tests). |
parentAnswers(role: string): boolean | Is the parent's instance of the role the answer now: a level is docked, the parent holds the role and the level does not bring it. |
takeOver<T>(role: string, make: () => T): T | What an engine entry point calls to make a role: the parent's instance when it answers, else make(). |
packages/core/src/roles.ts:10
RowLayout class
class RowLayoutthe layout of one object's fields in a row of numbers (and the strings that go in the meta part)
readonly fields: Field[] | |
stride: number | |
metaCount: number | |
constructor(specs: readonly string[]) |
packages/core/src/snapshot.ts:29
SceneHost class
class SceneHost implements ServiceThe scene host: the place for a second World over a second Scene on the same Engine, so a game's
interlude can be an ordinary scene with its own lights, camera and behaviours while the target level loads in the main one.
Both scenes share the GL context, shaders and texture caches. Only the active world is rendered (rendering both cost 15x in
WebKit, S0). The main world always advances (its services - ui, net, input - keep running, and its paused flag still decides
whether the simulation steps); another world advances only while it is the active one.
readonly name: "host" | |
constructor(readonly engine: BABYLON.AbstractEngine) | |
init(world: World): void | |
get main(): World | The world the level service builds into and the game normally plays in. |
get active(): World | The world that is advanced and rendered now. |
worlds(): World[] | |
get(name: string): World | undefined | |
nameOf(w: World): string | undefined | |
create(name: string, opts: HostWorldOptions = {}): World | A new world over a new scene on the shared engine. It is not shown until show. The game owns what is in it. |
show(world: World): void | Show a world: from the next frame it is the one advanced and rendered. The one that was shown is not advanced any more. |
showMain(): void | Show the main world again (a travel does this when the player is let in, and when a transition fails). |
dispose(world?: World): void | Dispose a world the game created, with its scene (all of them with no argument: the service's own dispose). If it is shown, the main world is shown first. |
advance(realDt: number): void | One real frame: advance the main world, and the active one if it is another. |
async advanceAsync(realDt: number): Promise<void> | advance with the worlds' declared step kernels in the scheduler's workers (the same as advance when no world needs it) |
get pooled(): boolean | true when a world's step waits for kernels in workers: the loop then calls advanceAsync |
render(): void | Render the active world's scene. |
packages/core/src/host.ts:16
Scheduler class
class Schedulerstats: { runs: number; inWorkers: number; applied: number; lost: number; } | counts: kernel runs in all, in workers, and of frame kernels the answers applied |
constructor(private readonly world: World) | |
start(o: SchedulerStart): void | start the pools (a game does it in createGame); before it, and with no spawn, kernels run here |
startLike(o: Scheduler): void | start with the options another scheduler was started with (a second world of the same game) |
stop(): void | |
respawn(): void | drop the workers that run kernels and start new ones when a kernel next needs them (the spawn of the page changed: a docked level's kernels came or went); resident state is lost, as when a worker dies |
get threads(): number | workers that run kernels now (plain and Babylon) |
get pooled(): boolean | true when the step must be asynchronous: step kernels are declared and workers run them |
readonly MIN_PIECE_MS: 0.15 | a piece cheaper than this is not worth a message |
readonly PIECES_PER_WORKER: 4 | pieces per worker when a kernel is worth cutting: more pieces than workers, so a worker that is done takes the next (the pool's queue) |
pieces(name: string, n: number, threads: number): number | how many pieces a split kernel of n items is cut into: by its measured cost (one piece when the whole is cheap), the first time by the workers' number |
workerStats(): { cls: KernelWorker; threads: number; workers: { tasks: number; ms: number }[] }[] | per class of worker: how many workers and what each did (tasks finished, ms spent in them) |
costOf(name: string): number | undefined | the measured cost per item of a split kernel, ms (undefined before its first run) |
declare(d: KernelDecl, owner?: unknown): () => void | declare a kernel; owner lets dropOwner take all of an owner's kernels away. Returns the undeclare |
task<I, O>(spec: { name: string; gather(world: World, dt: number): I | null; apply(world: World, out: O): void; sync?: 'step' | 'frame'; each?: boolean; reads?: string[]; writes?: string[]; every?: number }, owner?: unknown): () => void | The author's short form: a task whose function is registered by defineTask(name, fn) in the game's src/kernels.ts. gather takes plain data out of the world (null: nothing
to do), apply puts the answer back. each says the data is a list of independent items (the answer a list of as many): it is cut over the cores and put together in order.
frame instead of step lets the page go on and applies the answer a step later. When the data is not plain (a node, a world, a function) the task runs in the game's thread and
Scheduler.stays() / scheduler.info say why. |
stays(): { task: string; why: string }[] | the tasks that stay in the game's thread, and why (in words an author can act on) |
dropOwner(owner: unknown): void | |
refresh(name: string): void | the resident state of a kernel is sent again before its next run (the world it holds changed) |
module(m: ModuleDecl, owner?: unknown): () => void | declare a module: all its parts, under the module's name; one undeclare for all |
modules(): { name: string; stays?: string; parts: { name: string; sync: string; reads: string[]; writes: string[]; split: boolean; resident: boolean }[] }[] | the declared modules: their parts (reads, writes, how each runs) and what stays in the game's thread |
list(): { name: string; sync: string; owner: string; module?: string; resident?: string }[] | the declared kernels |
main: Scheduler | undefined | the scheduler of the game's main world (the first one started, with workers or without): what views and loaders use when they are given none |
shared(key: string, init: { kernel: string; payload: () => unknown }, o: { replicas?: number } = {}): SharedState | A state kept in workers and asked by calls outside the step (a land to build chunks of, a collision world to sweep in): init is the kernel that sets it up
from payload(), update adds to it (every copy, also those made later, gets every update in order). Calls go to the least loaded worker, each of which
holds its own copy (at most replicas, default all), and to this thread when there are no workers. A copy lost with its worker is made again. |
spent(kernel: string): { calls: number; ms: number } | the worker time (ms) all finished calls of a kernel took so far, and how many calls: what a service measures its cost by |
call<O = unknown>(name: string, input: unknown, transfer: Transferable[] = [], pin?: string): Promise<O> | one call of a kernel outside the step (loading work): in a worker when there is one, here otherwise; never blocks the page |
stepHere(dt: number): void | the step kernels of this step, here, in waves (the synchronous step: tests, world.step, a world with no workers) |
async stepPooled(dt: number): Promise<void> | the step kernels of this step in the workers: each wave gathers, runs at the same time, applies in declaration order |
endStep(dt: number): void | the frame kernels at the end of a step: answers that came are applied (in declaration order), idle due ones are started.
With no workers they run here at once and are applied at the next step, so the answer is one step late either way |
dispose(): void |
packages/core/src/scheduler.ts:113
Scope class
class Scopereadonly entities: Set<Entity> | the entities spawned while the scope was open: those still alive are destroyed with it |
constructor(readonly world: World, readonly namespace: string) | |
get closed(): boolean | |
get size(): number | how many takings-back wait |
add(undo: Undo): Undo | Keep undo for the end of the scope (run at once when the scope is closed already). Returns a function that runs it now and forgets it. |
on<T = any>(event: string, fn: Handler<T>): Undo | An event handler on the world's bus. |
command(name: string, description: string, fn: CommandFn): Undo | A command; the one it replaced is given back. |
component(name: string, cls: ComponentClass): Undo | A component class under a name of the manifests. |
behaviour(name: string, cls: ComponentClass): Undo | A behaviour class under a name of the manifests. |
service<S extends Service>(s: S): S | A service; it is disposed and removed with the scope. A service the parent already has under that name is the parent's role: it is given back (seen through the scope, view) and left alone. |
view<S>(service: S): S | A service of the parent as the scope's code sees it: its scopedView when it has one (what the code adds to it is then taken back with the scope), else the service itself. |
observe<T, O>(obs: ObservableLike<T, O>, fn: (e: T) => void): O | An observer of a Babylon observable (scene.onBeforeRenderObservable); removed with the scope. |
listen(target: EventTarget, type: string, fn: EventListenerOrEventListenerObject, opts?: boolean | AddEventListenerOptions): Undo | A DOM listener; removed with the scope. |
interval(fn: () => void, ms: number): Undo | setInterval, stopped with the scope. |
async capture<R>(fn: () => R | Promise<R>): Promise<R> | Run fn and take back every DOM listener and interval that the code it runs adds meanwhile (EventTarget.prototype.addEventListener, setInterval): the code of an example
that was written for its own page reaches for window and document itself. Only for the span of the call (the promise it returns is awaited), so what the parent's own
code adds at the same time would be caught too: dock while the parent has nothing to add (under the transition video). A worker, a message port and a channel are their
maker's own and their listeners stay: the engine's pools make their workers the first time one is needed, which may be while a level installs, and they live on after it. |
dispose(): void | Take everything back, newest first; the entities that are left are destroyed. Safe to call twice. |
packages/core/src/scope.ts:19
SimHost class
class SimHostreadonly replica: Replica | |
readonly dt: number | |
readonly mode: 'worker' | 'thread' | |
readonly transport: 'ring' | 'transfer' | 'direct' | snapshot transport actually in use |
paused: boolean | |
tick: number | the most recent tick shown and the ticks that passed unseen (the render side was slower than the simulation) |
skipped: number | |
constructor(o: SimHostOptions) | |
ready(): Promise<void> | resolves when the program has initialised |
on(name: string, fn: (data: any) => void): () => void | |
command<T = unknown>(name: string, args?: unknown): Promise<T> | send a command; it is applied at the next step boundary, in the order sent. The promise gives the program's answer. |
pause(on = true) | worker mode: start or stop the free-running simulation. Thread mode: pumped by pump. |
start() | |
step(n = 1) | n steps by hand (a paused simulation, a test) |
pump(now: number): void | Call once a frame with the time in seconds. Thread mode steps the simulation by the time that passed (at most five steps); worker mode takes the snapshots that came. Then the replica is rebuilt, interpolated by how far into the step the render time is, and events are delivered. |
alpha(now: number): number | the renderer's alpha between the previous and the current snapshot at now |
async dispose(): Promise<void> |
packages/core/src/sim-host.ts:202
SnapshotCodec class
class SnapshotCodecreadonly layouts: Map<string, { layout: RowLayout; cap: number; record: boolean; }> | |
constructor(readonly spec: SnapshotSpec) | |
static size(cap: number, stride: number): number | numbers in the buffer of one collection of capacity cap and row width stride: the count, the keys, the rows |
sizes(): Record<string, number> | |
encode(src: SnapshotSource, tick: number, time: number, into?: (name: string, size: number) => Float64Array): SnapshotView | Pack the objects of src into buffers. into gives the buffer to write for a name (a slot of the shared ring: its length is the full capacity) or
nothing (a new array of exactly the rows is made). |
packages/core/src/snapshot.ts:70
StateBuffer class
class StateBuffer<T extends TypedArray = Float64Array>readonly id: number | |
readonly array: T | |
readonly shared: boolean | true: the array is in shared memory (slices are windows); false: slices are copies |
constructor(ctor: new (n: number) => T, length: number, mode: 'auto' | 'shared' | 'copy' = 'auto') | |
slice(from = 0, to = this.array.length, access: Access = 'rw'): StateSlice | the range [from, to) for a kernel: access says whether the kernel reads it, writes it or both (a copy is made only for what is read) |
write(from: number, data: TypedArray): void | the answer's writes arrive here (copy mode) |
dispose(): void |
packages/core/src/state-buffer.ts:24
TaskPool class
class TaskPoolreadonly threads: number | |
done: number | tasks finished, in total, and how many ran in a worker |
inWorkers: number | |
readonly worked: { tasks: number; ms: number }[] | per worker: tasks it finished and the time it spent in them (ms, as the worker measured) |
constructor(private readonly o: TaskPoolOptions) | |
get capacity(): number | |
get pending(): number | |
spentOn(task: string): { calls: number; ms: number } | the worker time (ms) all finished calls of a task took so far, and how many calls |
alive(): { at: number; load: number }[] | the workers that run (their indices) and the tasks each has in hand |
pinTo(pin: string, at: number): void | tie a pin to one worker (-1: this thread) before its first task; a pin already tied keeps its worker |
pinGeneration(pin: string): number | the generation of a pin: it changes when the worker that kept the pin's state is gone (0 before the pin's first task) |
run<T = unknown>(task: string, payload: unknown, transfer: Transferable[] = [], pin?: string): Promise<T> | run a task; transfer hands buffers of the payload over to the worker (they are empty here after). Tasks with the same pin run in one worker, in order,
and share a state object there (the second argument of the task); if that worker dies they reject with ResidentLost and the pin moves on |
dispose(): void |
packages/core/src/task-pool.ts:52
World class
class WorldThe World owns the Babylon scene, the fixed-step simulation loop (decoupled from rendering), the clock with time dilation, the event bus, the services and the entities.
readonly events: EventBus | |
readonly components: Registry<ComponentClass> | |
readonly behaviours: Registry<ComponentClass> | |
readonly commands: CommandChannel | |
readonly entities: Entity[] | |
readonly fixedStep: number | |
readonly perf: FrameProfiler | where the time of a frame goes (off until perf.enabled; see perf.ts) |
readonly scheduler: Scheduler | the system scheduler: declared kernels of services and components, run in the workers it was started with (scheduler.start), here otherwise |
readonly maxFrame: number | |
timeScale: number | Global time scale (slow motion < 1). |
time: number | Simulated seconds since the world was created (affected by timeScale, not by entity dilation). |
tickCount: number | Number of fixed steps run. |
paused: boolean | |
constructor(readonly scene: BABYLON.Scene, opts: WorldOptions = {}) | |
addService<S extends Service>(s: S): S | |
service<S extends Service = Service>(name: string): S | |
hasService(name: string): boolean | |
removeService(name: string): boolean | Take a service out of the world: its scheduled work is dropped and it is disposed (a docked level's scope does it at its end). Returns whether there was one. |
forEachService(fn: (s: Service) => void): void | every service, in the order they were added |
get alpha(): number | How far the render frame is between the last two fixed steps (0..1), for interpolating what the camera follows. |
spawn(name: string, opts: { node?: BABYLON.TransformNode; position?: BABYLON.Vector3; id?: string; tags?: string[] } = {}): Entity | Make an entity over a new TransformNode (or over an existing node of the scene). |
removeEntity(e: Entity): void | |
expose(name: string, get: () => unknown): () => void | Show a named value of the game to tests and tools: world.expose('rpm', () => car.rpm). Returns the function that takes it back. |
exposed(name: string): unknown | The current value of an exposed name; throws with the names there are when the game does not expose it. |
exposedNames(): string[] | The names the game exposes. |
entity(id: string): Entity | undefined | |
findByName(name: string): Entity | undefined | |
findByTag(tag: string): Entity[] | |
entitiesWith<C extends Component>(cls: ComponentClass<C>): Entity[] | |
advance(realDt: number): number | Advance by a real frame time: runs as many fixed steps as fit, then the per-frame updates. |
async advanceAsync(realDt: number): Promise<number> | advance with the declared step kernels run in the scheduler's workers (the step waits for them without blocking the page); the same as advance when there are none |
step(): void | Exactly one fixed step (also the way tests drive the world); declared step kernels run here, with the same result as in workers. |
get stepsAsync(): boolean | true when the step has work in workers that it must wait for: declared step kernels, or a service whose asynchronous step wants to run |
readonly asyncComponents: Set<Component<Record<string, any>>> | components that may step in the workers (they add themselves when attached and take themselves out when detached) |
run(seconds: number): void | Run the world headless for seconds of simulated time. |
dispose(): void |
packages/core/src/world.ts:42
Functions
addPackageWorkers function
function addPackageWorkers(urls: Record<string, string>): () => voida docked level's workers: added to the game's own while the level is current; the returned function takes them away
packages/core/src/web-workers.ts:26
buildKernelSpawn function
async function buildKernelSpawn(kernels: { path: string; text: string }[]): Promise<{ spawn: ((cls: KernelWorker) => WorkerLike) | null; urls: string[] }>The kernel workers of a game (or a docked level) played from a package: module workers that load the release's kernel module (kernels/plain.js, or after
Babylon kernels/babylon.js), then the game's own kernels from its package (entry.kernels, their @ferret/* imports pointed at that module, so they register
where the worker runs them), then run. Messages that come while it loads wait. Without the release folder (FERRET_LIB) the page's own scripts stay.
packages/core/src/web-workers.ts:69
callWithSlices function
function callWithSlices(fn: (input: any, st: Record<string, unknown>) => unknown, input: unknown, st: Record<string, unknown>): unknownRuns a kernel function with the slices of its input turned into typed arrays (the input's own properties, one level deep). With no slices it is a plain call.
With copies, the arrays asked for writing come back in the answer (finishWrites on the game's side puts them into their StateBuffers).
packages/core/src/state-buffer.ts:65
defaultPoolSize function
function defaultPoolSize: () => numberpackages/core/src/job-pool.ts:60
defineTask function
function defineTask<I, O>(name: string, run: (input: I) => O): voidthe function of a task: plain data in, plain data out. Put it in the game's src/kernels.ts (the build puts that file in the workers too)
packages/core/src/task.ts:8
ensureBabylon function
function ensureBabylon(...parts: string[]): Promise<void>Make sure the named parts of Babylon are loaded (core, gltf with the PBR materials, shadows, particles, pipeline, video, debug; tools/babylon/parts.mjs): fetched from
globalThis.FERRET_BABYLON (the folder of the parts, set by the player or the page) and imported once. Resolves at once when they are there.
packages/core/src/babylon.ts:23
finishWrites function
function finishWrites(out: unknown): unknownthe game's side of a kernel's answer: the writes of copies go into their buffers, the kernel's own result comes out
packages/core/src/state-buffer.ts:80
frameWork function
function frameWork(engine: { onBeginFrameObservable: { add(f: () => void): unknown; remove(o: unknown): void }; onEndFrameObservable: { add(f: () => void): unknown; remove(o: unknown): void } }): { read: () => number; stop: () => void }The CPU work of a frame from a Babylon engine: the time from the start of the frame to the end of its rendering (what the frame's JavaScript cost, without the wait for the next frame). Returns the reader and the function that stops it.
packages/core/src/quality.ts:364
gameWorker function
function gameWorker(name: string): WorkerLikeStarts one of the game's own workers by its script name (gameWorker('sim-worker.js')): from the game's package when the player runs it, else the script of
that name beside the page (a sample's own page, where tools/build.mjs puts it next to main.js).
packages/core/src/web-workers.ts:37
gpuTimer function
async function gpuTimer(engine: BABYLON.AbstractEngine): Promise<{ read: () => number; stop: () => void }>The GPU time of the last frame (ms), from the browser's timer query (EXT_disjoint_timer_query); NaN where there is none. For the quality
regulator, without the whole scene instrumentation. Resolves to the reader and the function that stops it.
packages/core/src/perf.ts:180
guardFrame function
function guardFrame(fn: () => void, o: GuardOptions = {}): () => voidwrap a frame callback: an exception is reported (once per kind, then every 100th time with the count) and the loop goes on
packages/core/src/frame-guard.ts:49
hangWatcherSource function
function hangWatcherSource(base: string, hangMs: number): stringThe watcher's code (it runs in a Web Worker, as a string). Messages in: { v } the page's visibility (a hidden page has no frames and runs its timers
rarely: not a hang; a change starts both clocks again), { a: 1 } the main thread's timer, { b: 1 } a finished frame (also proof that the thread runs).
Each second: no answer from the main thread for hangMs is a stuck thread; an answering thread with no frame for hangMs after the first frame is a
frame waiting forever. The first goes to the server's log at once (the main thread cannot send it), and when the stall ends its length goes back to the
page (postMessage). Exported for the unit test, which runs it with a fake clock.
packages/core/src/frame-guard.ts:89
hasBabylonPart function
function hasBabylonPart(part: string): booleanIs part available now: the full build, or a part already loaded?
packages/core/src/babylon.ts:14
hasKernel function
function hasKernel(name: string): booleanpackages/core/src/scheduler.ts:30
instrumentScene function
async function instrumentScene(profiler: FrameProfiler, scene: BABYLON.Scene, engine?: BABYLON.AbstractEngine): Promise<() => void>Babylon's own phases as probes (ms of the last frame): the evaluation of the active meshes, the render targets, the scene render, the animations, the
particles, the sprites, plus the draw calls and the GPU frame time where the browser has the timer query (gpu is then NaN-free, else it is left out).
Loads the Babylon part instrumentation on a host that serves Babylon in parts. Resolves to the function that stops the instrumentation.
packages/core/src/perf.ts:153
isSlice function
function isSlice: (v: unknown) => v is StateSlicepackages/core/src/state-buffer.ts:18
kernelNames function
function kernelNames(): { name: string; worker: KernelWorker; resident: boolean }[]the registered kernels (names and worker classes)
packages/core/src/scheduler.ts:29
kernelWorkerSpawn function
function kernelWorkerSpawn(): typeof kernelSpawnthe kernel worker spawn now in force (or null: the page's own scripts)
packages/core/src/web-workers.ts:32
nodePort function
function nodePort(): WorkerPortthe worker end, inside a Node worker script
packages/core/src/node-workers.ts:23
nodeWorker function
function nodeWorker(script: string | URL): WorkerLikethe page end of a Node worker started from a script file
packages/core/src/node-workers.ts:13
notPlain function
function notPlain(v: unknown): string | nullwhat in v is not plain data (so it cannot go to a worker), as a path and a reason; null when it is all plain. Looks at most at a few thousand values
packages/core/src/task.ts:23
ownReport function
function ownReport(perf: FrameProfiler, scheduler: Scheduler, extra: (slot: string) => string | undefined = () => undefined): { frameMs: number; rows: OwnRow[] }the rows of a profiler that are at least 2% of the frame (and 0.3 ms), with what takes each off the game's thread. Needs perf.enabled and a few frames
packages/core/src/perf-advice.ts:23
perfOverlay function
function perfOverlay(profiler: FrameProfiler, opts: { top?: number; parent?: HTMLElement; extra?: () => string } = {}): () => voidA text panel in the corner of the page with the report, refreshed four times a second (a game starts it with ?perf). Returns the stop function.
Without a DOM it does nothing.
packages/core/src/perf.ts:194
pointImports function
function pointImports(text: string, to: (name: string) => string): string@ferret/* imports of a packaged script pointed at to(name) (a worker has no import map)
packages/core/src/web-workers.ts:60
registerKernels function
function registerKernels(kernels: Record<string, KernelFn | { run: KernelFn; init?: KernelEntry['init'] }>, o: { worker?: KernelWorker } = {}): voidregister kernels by name (a package's src/kernels.ts does it at its top level; the page and the worker bundle both import that file)
packages/core/src/scheduler.ts:21
registerSnapshotCommands function
function registerSnapshotCommands(world: { commands: { register(name: string, description: string, fn: (a?: any) => unknown): void } }, replica: Replica): voidthe report of the render side's reads of undeclared fields, for edit.validate (snapshot.audit), and the spec's own check: declared fields that no object had
packages/core/src/snapshot.ts:232
reportLine function
function reportLine(line: string, o: GuardOptions = {}): voidrecord one report line (console, __ferretErrors, local storage, the server's log)
packages/core/src/frame-guard.ts:36
rolesOf function
function rolesOf(world: World): Roles | undefinedThe roles service of a world, if the parent made one (a world with no dock has none).
packages/core/src/roles.ts:54
runJobWorker function
function runJobWorker(jobs: Record<string, JobFn>, port: WorkerPort): voidthe worker's end: call in the job worker's entry with the same jobs the pool was made with
packages/core/src/job-pool.ts:33
runKernelWorker function
function runKernelWorker(port: WorkerPortLike): voidthe worker bundle's entry: runKernelWorker(webPort()) after importing every kernels.ts
packages/core/src/scheduler.ts:45
runSimWorker function
function runSimWorker(make: () => SimProgram | Promise<SimProgram>, port: WorkerPort): voidpackages/core/src/sim-host.ts:138
runTaskWorker function
function runTaskWorker(tasks: Record<string, TaskFn>, port: WorkerPortLike): voidthe worker's script: runTaskWorker({ analyseTree }, webPort())
packages/core/src/task-pool.ts:19
scopedGame function
function scopedGame<G extends { world: World; scene: object; input?: any }>(game: G, scope: Scope, _roles?: Roles): Ggame seen by the code of a docked level: its world, scene and input are the scoped views; anything else is the parent's own
packages/core/src/scoped-view.ts:94
scopedInput function
function scopedInput<I extends { dispose(): void; attach(canvas: any, o?: any): void; setPointerLock?(on: boolean): void; pointerLock?: boolean }>(input: I, scope: Scope): Ithe input as a docked level sees it: the parent's service, which the level may not dispose; attach changes only what the level asks (the pointer lock) and is undone with the scope
packages/core/src/scoped-view.ts:78
scopedScene function
function scopedScene<S extends object>(scene: S, scope: Scope): Sscene seen by the code of a docked level: its observables (onBeforeRenderObservable ...) record the observers they get
packages/core/src/scoped-view.ts:51
scopedWorld function
function scopedWorld<W extends World>(world: W, scope: Scope): Wworld seen by the code of a docked level
packages/core/src/scoped-view.ts:14
setKernelWorkerSpawn function
function setKernelWorkerSpawn(spawn: ((cls: 'plain' | 'babylon') => WorkerLike) | null): voidThe player: how this page starts the kernel workers instead of ferret-worker.js beside it (a game played from a package has none there): the engine's
kernel module of the release with the game's own kernels from its package. null gives the page's own scripts back.
packages/core/src/web-workers.ts:47
setPackageWorkers function
function setPackageWorkers(urls: Record<string, string> | Map<string, string>): voidthe player: the game's packaged workers, by their script name (sim-worker.js), each a URL a module worker starts from
packages/core/src/web-workers.ts:21
watchHangs function
function watchHangs(o: GuardOptions & { hangMs?: number; onEndFrame?: { add(f: () => void): unknown; remove(x: unknown): void } } = {}): { beat: () => void; stop: () => void }Watch for a stuck main thread from a Web Worker. beat is called after every finished frame (pass the engine's end-of-frame observable, or call the
returned beat yourself). Returns the stop function. Without Web Workers (a test, OS Beroun) it does nothing.
packages/core/src/frame-guard.ts:64
webKernelWorker function
function webKernelWorker(cls: 'plain' | 'babylon'): WorkerLikethe engine's kernel workers of a page: ferret-worker.js, or ferret-worker-babylon.js for kernels that need Babylon, beside the page; for world.scheduler.start
packages/core/src/web-workers.ts:50
webPort function
function webPort: () => WorkerPortpackages/core/src/sim-host.ts:135
webWorker function
function webWorker(url: string | URL, name?: string, type?: 'classic' | 'module'): WorkerLikethe page's end of a Web Worker started from a script URL (relative to the page): the same shape as nodeWorker, for SimHost and JobPool; type 'module' for an ES module script
packages/core/src/web-workers.ts:6
withSlices function
function withSlices(tasks: Record<string, TaskFn>): Record<string, TaskFn>wrap a registry's tasks so slices in their input work (the worker bundle and the page's fallback use it)
packages/core/src/state-buffer.ts:87
workersParam function
function workersParam(): number | undefinedthe page's ?workers=N (0: every kernel here), or undefined
packages/core/src/web-workers.ts:55
Interfaces
CollectionSpec interface
interface CollectionSpecThe snapshot contract: what a simulation shows to whoever draws it, as flat typed arrays, and the replica that rebuilds objects from them.
A snapshot spec says which fields of which objects the render side may read. The simulation side packs them (SnapshotEncoder), the render side unpacks
them into plain objects with the same property paths (Replica), so code that reads craft.plane.pos[0] or ship.vessel.q goes on reading it; nothing
else of the simulation is visible across the boundary. Values that move are interpolated between two snapshots by alpha, as World.alpha does for the
fixed step.
Fields (a path from the object, then a suffix):
`x` a number `plane.pos:3` a vector of 3 numbers (any length)
`plane.pos:3~` interpolated linearly `plane.q:4~q` a quaternion (interpolated by normalised lerp) `heading~a` an angle in radians (by the short way round)
`gone?` a boolean `state@idle|walk|board` one of the listed words (stored as its index)
`kind$` a string `dmg{}` any JSON value (a string or JSON field that the source gives as `undefined` is left as it was)
A collection is many objects with the same fields, each with a unique integer key, up to capacity; a record is one object.
fields: string[] | |
capacity: number |
packages/core/src/snapshot.ts:18
CommandInfo interface
interface CommandInfoname: string | |
description: string |
packages/core/src/commands.ts:8
FrameBound interface
interface FrameBoundwhich side holds the frame: the GPU when its frame time is most of the frame, else the CPU ('?' without the GPU timer)
by: 'cpu' | 'gpu' | '?' | |
frameMs: number | |
gpuMs: number |
packages/core/src/perf.ts:17
Gathered interface
interface Gathered<I>what a gather gives: the input, and the buffers to hand over (they are not used here after)
input: I | |
transfer: Transferable[] |
packages/core/src/scheduler.ts:48
GuardOptions interface
interface GuardOptionsgame?: string | the game's name in the reports |
report?: (line: string) => void | where a report line goes besides the console and local storage (default: the server's log on https) |
packages/core/src/frame-guard.ts:18
HostWorldOptions interface
interface HostWorldOptions extends WorldOptionsclearColor?: [number, number, number] |
packages/core/src/host.ts:5
JobContext interface
interface JobContextshared: Record<string, SharedArray> | |
args: any |
packages/core/src/job-pool.ts:18
JobPoolOptions interface
interface JobPoolOptionsjobs: Record<string, JobFn> | the jobs by phase name (the same registry the worker entry gets) |
spawn?: () => WorkerLike | makes one job worker; without it, or with size 0, every phase runs serially |
size?: number | number of workers (default: hardware threads - 2, between 0 and 8) |
minItems?: number | a phase with fewer items than this runs serially (the call overhead is more than the work) |
packages/core/src/job-pool.ts:49
KernelDecl interface
interface KernelDecl<I = any, O = any>name: string | the kernel's name in the registry |
inline?: boolean | a part its service runs itself at its place in the step (a kernel's step between a service's own phases): listed in the module, left out of the waves |
module?: string | the module this part belongs to (set by Scheduler.module) |
sync: 'step' | 'frame' | step: the step waits for it (gameplay, physics; deterministic); frame: the page does not wait, the answer is applied at a later step (the view) |
reads?: string[] | names of the resources it reads and writes: kernels that do not touch the same resources (one writing what the other reads or writes) run at the same time |
writes?: string[] | |
every?: number | run it every n-th step (default 1) |
resident?: { key: string; init(world: World): unknown | Gathered<unknown> } | a state the kernel keeps in its worker (a collision world, a surface): sent by init once, again when the worker is lost or refresh asks |
split?: { count(input: I): number; slice(input: I, from: number, to: number): I; merge(outs: O[], input: I): O } | independent items: cut into one range per worker, each range a kernel call, the answers merged in index order (the result is the same for any number of workers) |
author?: boolean | set by the author's short form (Scheduler.task): what it is given is looked at, and when it is not plain data the task runs in the game's thread and the engine says why |
gather(world: World, dt: number): I | Gathered<I> | null | take the input out of the world here (null: nothing to do at this step) |
apply(world: World, out: O): void | write the answer back here |
packages/core/src/scheduler.ts:50
KernelEntry interface
interface KernelEntryrun: KernelFn | |
init?: (payload: any, state: Record<string, unknown>) => void | |
worker: KernelWorker |
packages/core/src/scheduler.ts:16
ModuleDecl interface
interface ModuleDeclA module's description, written once by the engine's developers: its parts (kernels with what each reads and writes, step or frame,
and how its data splits), and in words what stays in the game's thread. The step of 9.2 follows from it: parts that touch nothing in common run at the same
time, a part that reads what another writes waits, a split part runs as many pieces as there are workers, the step ends at a barrier.
name: string | |
parts: KernelDecl[] | |
stays?: string |
packages/core/src/scheduler.ts:103
ObservableLike interface
interface ObservableLike<T = unknown, O = unknown>a Babylon Observable, as far as the scope needs it
add(fn: (e: T) => void, ...rest: any[]): O | |
remove(o: O): unknown |
packages/core/src/scope.ts:17
OwnRow interface
interface OwnRowname: string | the slot: own:name (a function of the game, timed by its author), component:Class.onFixedUpdate, fixed:service, update:service |
ms: number | ms in the game's thread per frame, and its share of the frame |
share: number | |
kind: 'own' | 'engine' | 'code' | own: the author's function; engine: a module of the engine that is declared to the scheduler; code: a component or service no module is declared for |
say: string | what the engine says about this row: where it runs and why it is the narrow place |
packages/core/src/perf-advice.ts:9
PacerTick interface
interface PacerTickEven frame pacing. A frame that takes a little more than one refresh of the display is shown after two, the next after one, then two: the pictures come at uneven intervals and the motion jerks although the average rate is fair. The pacer draws every k-th refresh instead, k the smallest that the frames keep without being late, and gives the world exactly k refreshes of time a frame, so things move the same distance every picture.
- the refresh period is learnt from the callbacks that come after one that drew nothing (60 Hz until there are some, less if callbacks come faster); - a drawn frame that comes later than its slot by more than half a refresh is a miss; misses in more than 4% of the last two seconds of frames raise k at once; - after four seconds without a miss, k is lowered by one if the frame's own work fits the shorter step with a third to spare; when that brings misses back
within ten seconds, the shorter step is not tried again for half a minute (the work a frame gives the GPU is not in its own work);
- the time given to the world is k periods while on schedule; a frame really late gets the time that really passed (the world never falls behind the clock).
Pure: no Babylon. tick(now, work) is called on every display callback; it says whether to draw and with how much time.
draw: boolean | |
dt: number |
packages/core/src/frame-pacer.ts:14
PerfRow interface
interface PerfRowname: string | |
avgMs: number | |
worstMs: number | |
lastMs: number | |
callsPerFrame: number |
packages/core/src/perf.ts:14
PerfTrace interface
interface PerfTraceframes: TraceFrame[] | the frames, in order |
longTasks: { t: number; ms: number }[] | the main thread's long tasks (over 50 ms) the browser reported, inside frames or between them |
marks: { t: number; name: string }[] | what the game marked (an asset loaded, a level shown) |
done: boolean | the trace has run its time |
packages/core/src/perf.ts:21
QualityDecision interface
interface QualityDecisiont: number | |
id: string | |
from: number | |
to: number | |
why: string |
packages/core/src/quality.ts:73
QualityKnob interface
interface QualityKnobreadonly id: string | unique id, module.what ('render.scale', 'perspective.distance', 'crowd.near') |
readonly load: QualityLoad | which side of the frame a step down relieves |
readonly steps: number | number of steps, 0 the richest, steps - 1 the cheapest |
visibility?: number | ((level: number) => number) | how visible it is to be at level (the step about to be taken): the least visible is given up first. Default: 1 for every step |
apply(level: number): void | put the knob at level |
ready?(): boolean | may the knob change now (a framebuffer change only behind a fade, say); default yes |
active?(): boolean | is the knob in play now (a headset knob only during a session); default yes |
label?: string |
packages/core/src/quality.ts:25
QualityOptions interface
interface QualityOptionstargetHz?: number | (() => number) | the frame rate to hold on a flat screen (default 60). A function is read every decision |
xrHz?: () => number | the headset's display rate while a session runs (the XR service sets it); a positive value wins over targetHz |
floorHz?: number | a flat screen may settle at this lower steady rate when every knob is spent (never a headset); default none |
gpuMs?: () => number | GPU time of the last frame in ms, NaN when unknown (see gpuTimer) |
workMs?: () => number | CPU work of the last frame in ms (see frameWork); without it the wall time stands for it |
every?: number | seconds between decisions (0.5), the window measured (1 s), the wait after a change (2 s), the comfort time before a step back (4 s) |
window?: number | |
settle?: number | |
upAfter?: number | |
late?: number | a frame is late above this share of the budget (1.08), comfortable below comfort (0.7) |
comfort?: number | |
remember?: { load(): unknown; save(v: unknown): void } | false | remember the levels between runs: load gives what save was given; default: the browser's local storage under key |
key?: string | the name the levels are remembered under (a game name and a device class are good: 'dunkirk:desktop') |
auto?: boolean | start regulating at once (default true); quality.auto switches it |
never?: boolean | Never lower quality (a game that holds its picture before its frame rate): the regulator is off and cannot be switched on, the levels remembered from earlier runs are not
loaded and nothing is saved, every knob stays at its richest (level 0). The commands quality.set and quality.preset still work by hand. |
busy?: () => boolean | something loads now (besides the services' own qualityBusy() and the scene's waiting items): the frames are not judged meanwhile |
packages/core/src/quality.ts:43
QualityReport interface
interface QualityReportauto: boolean | |
targetHz: number | |
budgetMs: number | |
xr: boolean | |
frameP95: number | |
workP95: number | |
gpuP95: number | |
by: 'cpu' | 'gpu' | '?' | |
holds: string[] | |
knobs: { id: string; load: QualityLoad; level: number; steps: number; pinned: boolean; active: boolean }[] | |
log: QualityDecision[] |
packages/core/src/quality.ts:74
ReplicaHooks interface
interface ReplicaHooksaudit?: boolean | dev check: every read of a property the spec does not declare is recorded in Replica.undeclared (the objects are proxies); off by default |
make?(collection: string, key: number): any | an object for a key that is new (default {}): a game can give it methods or a class |
remove?(collection: string, key: number, obj: any): void | an object whose key is no longer in the snapshots |
packages/core/src/snapshot.ts:131
SchedulerStart interface
interface SchedulerStartspawn?: (cls: KernelWorker) => WorkerLike | starts a worker of a class (webKernelWorker on a page); without it every kernel runs here |
threads?: number | plain workers (default: the cores less two, 1 to 7) |
babylonThreads?: number | Babylon workers, started when a kernel needs one (default 1) |
packages/core/src/scheduler.ts:76
Service interface
interface ServiceA world-wide singleton (the rough equivalent of a UE subsystem): input, levels, zones, physics, ui ...
readonly name: string | |
init?(world: World): void | |
fixedUpdate?(dt: number): void | Called before the components' fixed update, at the fixed rate. |
update?(dt: number): void | Called once per rendered frame. |
dispose?(): void | |
readonly kernels?: KernelDecl[] | kernels this service declares: taken when the service is added |
readonly schedule?: ModuleDecl | a module's description: its parts, what splits, what stays in the game's thread; taken when the service is added |
fixedUpdateAsync?(dt: number): Promise<void> | the same step, asynchronous, for a service whose work goes to workers at its place in the step: used by advanceAsync when wantsAsync says yes |
wantsAsync?(): boolean | |
whyHere?(): string | undefined | why its work stays in the game's thread right now (in words), or undefined when it goes to the cores: what perf.report tells the author |
packages/core/src/world.ts:12
SimEmitter interface
interface SimEmitteremit(name: string, data?: unknown): void |
packages/core/src/sim-host.ts:15
SimHostOptions interface
interface SimHostOptionsmode?: 'worker' | 'thread' | where the simulation runs; default: in a worker when spawn is given and the platform has workers, else in this thread (program needed) |
spawn?: () => WorkerLike | worker mode: makes the worker (the entry calls runSimWorker) |
program?: () => SimProgram | thread mode: the program itself |
spec: SnapshotSpec | |
dt?: number | |
opts?: unknown | options for SimProgram.init |
shared?: boolean | share the ring by SharedArrayBuffer (needs cross-origin isolation); default: when the environment has it |
catchUp?: { maxFrame?: number; maxSteps?: number; drop?: number } | Thread mode: how the simulation catches up after a long frame. At most maxFrame seconds of a frame count, at most maxSteps steps are taken in
one pump, and when more than drop seconds are owed they are dropped (the machine cannot keep up: slow motion, not a spiral).
Default: 0.1 s, 0.15 s worth of steps, 0.25 s. |
reuse?: boolean | thread mode: reuse the snapshot buffers (default true) |
interpDelay?: number | Worker mode: the drawing runs this many seconds behind the newest snapshot (default 0.05, never less than 2.5 snapshot spacings), on a clock of its own that is steered gently toward that point (at most 10 % faster or slower) and never goes back; the picture is interpolated between the two snapshots round the clock, so snapshots that arrive unevenly (a slow frame, the worker's own jitter) do not show as jerks. |
hooks?: ReplicaHooks | |
paused?: boolean | Created paused: game time does not run until start() (thread mode: pump does not step; worker mode: the worker does not free-run). A game made so that nothing
happens before Ready creates its host paused and starts it when the splash leaves. Default false (thread mode steps from the first pump). |
packages/core/src/sim-host.ts:161
SimProgram interface
interface SimProgramreadonly spec: SnapshotSpec | |
init(opts: unknown, out: SimEmitter): void | Promise<void> | called once with the options the host was given, before the first step |
command(name: string, args: unknown): unknown | a command from the render side, applied at a step boundary; its result goes back to the caller |
step(dt: number): void | one fixed step |
source(): SnapshotSource | the objects to show now |
readonly time: number | simulation seconds so far |
snapshotDue?(): boolean | Is the state worth a snapshot after this step? A program whose world changes only on some steps (a 20 Hz world in 60 Hz steps) says no on the others, so the drawing interpolates between real changes and not between equal snapshots. Default: every step. |
dispose?(): void |
packages/core/src/sim-host.ts:17
SnapshotSource interface
interface SnapshotSourcewhat the simulation hands the encoder: where the objects of each collection are, and each object's key
collections?: Record<string, { items: Iterable<any>; key: (item: any) => number }> | |
records?: Record<string, any> |
packages/core/src/snapshot.ts:57
SnapshotSpec interface
interface SnapshotSpeccollections: Record<string, CollectionSpec> | |
records?: Record<string, string[]> | single objects: name -> fields |
packages/core/src/snapshot.ts:19
SnapshotView interface
interface SnapshotViewone snapshot: the time of the simulation it shows, one Float64Array per collection or record ([count, keys..., rows...]) and the rest as JSON
tick: number | |
time: number | |
data: Record<string, Float64Array> | |
meta: Record<string, unknown[][]> | per collection or record: the rows' strings and JSON values, aligned with the rows |
packages/core/src/snapshot.ts:63
StateSlice interface
interface StateSlicewhat travels in a kernel's input in place of a typed array
$slice: 1 | |
id: number | |
ctor: string | |
from: number | |
to: number | |
access: Access | |
buffer?: SharedArrayBuffer | |
byteOffset?: number | |
data?: TypedArray |
packages/core/src/state-buffer.ts:14
TaskPoolOptions interface
interface TaskPoolOptionsspawn?: () => WorkerLike | starts a worker (() => webWorker(new URL('task-worker.js', document.baseURI))); without it, or with threads 0, tasks run in this thread, one per turn of the event loop |
threads?: number | how many workers (default: the cores less two, 1 to 4) |
tasks: Record<string, TaskFn> | the same functions the worker's script has: the fallback in this thread |
packages/core/src/task-pool.ts:43
TraceFrame interface
interface TraceFrameone frame of a trace: when it ended (ms, page clock), how long it was, and the slots that took at least minMs in it
t: number | |
dt: number | |
slots: Record<string, number> |
packages/core/src/perf.ts:20
WorkerLike interface
interface WorkerLikewhat a worker and the page's end of it share: the two ends of a Web Worker or a Node worker
postMessage(msg: unknown, transfer?: Transferable[]): void | |
on(event: 'message', fn: (msg: any) => void): void | |
terminate(): void | Promise<unknown> |
packages/core/src/sim-host.ts:38
WorkerPort interface
interface WorkerPortThe worker's side: call this in the worker's entry with a function that makes the program. port is the worker's end (self of a Web Worker, or
parentPort of a Node worker; use nodePort/webPort below).
post(msg: unknown, transfer?: Transferable[]): void | |
onMessage(fn: (msg: any) => void): void | |
close(): void |
packages/core/src/sim-host.ts:134
WorkerPortLike interface
interface WorkerPortLikepost(msg: unknown, transfer?: Transferable[]): void | |
onMessage(fn: (msg: any) => void): void | |
close(): void |
packages/core/src/task-pool.ts:10
WorldOptions interface
interface WorldOptionsfixedStep?: number | Fixed simulation step in seconds (default 1/60). |
maxFrame?: number | Longest real frame time that is simulated, in seconds; a stall is not a jump (default 0.1). |
packages/core/src/world.ts:31
Types
Access type
type Access = 'r' | 'w' | 'rw'packages/core/src/state-buffer.ts:12
CommandFn type
type CommandFn = (args: any) => unknown | Promise<unknown>The debug command channel: named commands that a tool (the inspector, the model viewer, an AI agent over MCP) calls to look at and change a running world. Commands are plain JSON in, plain JSON out.
packages/core/src/commands.ts:6
ComponentClass type
type ComponentClass<C extends Component = Component> = new (params?: any) => Cpackages/core/src/component.ts:41
Handler type
type Handler<T = any> = (payload: T) => voidpackages/core/src/events.ts:2
JobFn type
type JobFn = (from: number, to: number, ctx: JobContext) => voidpackages/core/src/job-pool.ts:19
KernelFn type
type KernelFn<I = any, O = any> = (input: I, state: Record<string, unknown>) => O | { result: O; transfer: Transferable[] }a kernel: pure, on plain data (typed arrays, numbers, strings, plain objects); state is the resident state of its pin in the worker that runs it
packages/core/src/scheduler.ts:13
KernelWorker type
type KernelWorker = 'plain' | 'babylon'the class of worker a kernel needs: plain (no Babylon), or one that loads Babylon first (ferret-worker-babylon.js)
packages/core/src/scheduler.ts:15
LogLevel type
type LogLevel = 'debug' | 'info' | 'warn' | 'error'packages/core/src/log.ts:2
QualityLoad type
type QualityLoad = 'cpu' | 'gpu' | 'both'packages/core/src/quality.ts:23
TaskFn type
type TaskFn = (payload: any, state: Record<string, unknown>) => unknown | { result: unknown; transfer: Transferable[] }a task: the result, or { result, transfer } to hand typed arrays' buffers back without a copy
packages/core/src/task-pool.ts:7
TypedArray type
type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Arraypackages/core/src/state-buffer.ts:8
Undo type
type Undo = () => voidScoped registration: a view of the world that records what a docked level adds and takes all of it back when the level goes.
Commands, components, behaviours, services, event handlers, entities, Babylon observers, DOM listeners and intervals made through the scope are undone by dispose,
newest first. A game that is not docked never makes one, so nothing changes for it. A name clash with the parent is the level's own error and is thrown as it is
without a scope (Registry.register); a command of the same name replaces the parent's for the time of the level and is given back after it.
packages/core/src/scope.ts:14
Constants
BABYLON_VERSION const
const BABYLON_VERSION: "9.33.1"the Babylon version this engine was built and tested with
packages/core/src/version.ts:11
FERRET_BUILD const
const FERRET_BUILD: stringthe build stamp yyyymmddHHMM in the LOCAL time of the build machine, never UTC; dev when the code runs unbuilt (tests, the repository)
packages/core/src/version.ts:13
FERRET_VERSION const
const FERRET_VERSION: "0.1.0"the engine's version (semver); every module of a release shares it
packages/core/src/version.ts:9
FERRET_VERSION_FULL const
const FERRET_VERSION_FULL: stringwhat to show a person: 0.1.0+202611051430
packages/core/src/version.ts:15