@gameable/wasm-host
Classes
Editor
The editor. Make one with createEditor; the host loop attaches it.
Example
ts
import { editorOf } from 'gameable/host';
const editor = editorOf();
await editor?.enter();
const door = editor?.actors().find((a) => a.class === 'Door');
if (door) editor?.select(door.id);Constructors
Constructor
ts
new Editor(): Editor;Returns
Accessors
active
Get Signature
ts
get active(): boolean;Whether edit mode is on.
Returns
boolean
selected
Get Signature
ts
get selected(): number | null;The selected actor's id, or null.
Returns
number | null
transformMode
Get Signature
ts
get transformMode(): EditorTransformMode;The gizmo's mode.
Returns
Methods
actors()
ts
actors(): EditorActor[];Every actor the guest has, with where the page draws it.
Returns
The actors, in spawn order.
attach()
ts
attach(host): void;Take the host. The host loop calls this in its init.
Parameters
| Parameter | Type | Description |
|---|---|---|
host | EditorHost | The engine, the adapter and the rest. |
Returns
void
classes()
ts
classes(): string[];The class names the running game's actors have.
Returns
string[]
Unique names, in first-seen order.
detach()
ts
detach(): void;Leave edit mode if on, and forget the host. The host loop calls this on dispose.
Returns
void
enter()
ts
enter(): Promise<void>;Pause the game and put the gizmo and the orbit on the page. Nothing moves until Editor.exit.
Returns
Promise<void>
Once the controls are up.
Throws
When no host loop has attached the editor, or the page has no renderer.
exit()
ts
exit(): void;Put every moved thing back, restore the camera, take the controls off the page and let time run again. Nothing is kept: a layout is kept by saving the level file and reloading the game. A body the editor moved is put back as a teleport, so one that was moving when the game paused is at rest afterwards. Called while Editor.enter is still loading the controls, it cancels that enter.
Returns
void
groundPoint()
ts
groundPoint(ndcX, ndcY): [number, number, number] | null;The surface under a point of the canvas: where a new thing goes.
Parameters
| Parameter | Type | Description |
|---|---|---|
ndcX | number | 1 (left) to 1 (right). |
ndcY | number | 1 (bottom) to 1 (top). |
Returns
[number, number, number] | null
The point, or null when the ray meets nothing.
holdCamera()
ts
holdCamera(): void;Remember the orbit's camera pose. The host loop calls this once per frame before the adapter, which writes the camera from its own transform slot every frame and would otherwise undo the orbit.
Returns
void
levels()
ts
levels(): EditorLevels;The levels the game declares and the one loaded.
Returns
Names, the current one and its place.
loadLevel()
ts
loadLevel(name): void;Ask for another level. The editor does not load it: the page's driver does, by reloading the game with {"level": name} in its options.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | The level's name. |
Returns
void
on()
ts
on(listener): () => void;Listen.
Parameters
| Parameter | Type | Description |
|---|---|---|
listener | (event) => void | The listener. |
Returns
A function that stops listening.
() => void
pick()
ts
pick(ndcX, ndcY): EditorActor | null;The actor drawn under a point of the canvas.
Parameters
| Parameter | Type | Description |
|---|---|---|
ndcX | number | 1 (left) to 1 (right). |
ndcY | number | 1 (bottom) to 1 (top). |
Returns
EditorActor | null
The actor, or null.
refresh()
ts
refresh(): void;Read the guest's actors again: after a prop changed, say.
Returns
void
select()
ts
select(id): void;Select an actor: the gizmo attaches to it when a level placed it. It holds the editor's handle, stood where the actor's root is, since a root may be an empty component with nothing drawn for it.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | number | null | The actor's id, or null for none. |
Returns
void
setTransform()
ts
setTransform(id, transform): void;Move, turn or scale an actor from numbers (an inspector's fields), the way the gizmo would.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | number | The actor's id. |
transform | EditorTransform | What to change. |
Returns
void
setTransformMode()
ts
setTransformMode(mode): void;Switch the gizmo between moving, turning and scaling.
Parameters
| Parameter | Type | Description |
|---|---|---|
mode | EditorTransformMode | The mode. |
Returns
void
showColliders()
ts
showColliders(on): void;Draw every body's shape as a wireframe, so a collider that does not match its mesh shows.
Parameters
| Parameter | Type | Description |
|---|---|---|
on | boolean | Whether to draw them. |
Returns
void
snap()
ts
snap(on): void;Snap moves to a quarter metre, turns to 15 degrees and scales to a tenth.
Parameters
| Parameter | Type | Description |
|---|---|---|
on | boolean | Whether to snap. |
Returns
void
update()
ts
update(dt?): void;Put the orbit's camera pose back, fly it by the keys held down and advance the orbit. The host loop calls this once per frame, after interpolation.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
dt | number | 0 | Seconds since the last frame, for the fly keys. |
Returns
void
abstract GuestLoop
The game module: one fixed step is one guest tick.
A step runs GuestLoop.beginStep, GuestLoop.readInput, GuestLoop.beforeEncode, then reads contacts, drains events, reads GuestLoop.readPlayers, encodes, steps and applies. The first failure latches: a trapped guest is not retried, the frame it returned is not applied, and GuestLoop.onDead runs once.
Example
ts
class MyLoop extends GuestLoop<HeadlessEngine, ServerAdapter> {
protected initGuest(ctx: HostContext): void { this.sandbox.init(config); }
protected beginStep(): void { this.adapter.beginTick(); }
protected readInput(): void { aliasInputState(input, this.args.inputState); }
protected entityOfBody(body: number): number { return this.adapter.world.entityOfBody(body); }
protected onDead(error: Error | null): void { console.error(error); }
}Type Parameters
| Type Parameter | Default type |
|---|---|
E extends LoopEngine | - |
A extends LoopAdapter | - |
S extends Sandbox | null | Sandbox |
Implements
Constructors
Constructor
ts
new GuestLoop<E, A, S>(
engine,
sandbox,
adapter,
options
): GuestLoop<E, A, S>;Parameters
| Parameter | Type | Description |
|---|---|---|
engine | E | The booted engine, page or headless. |
sandbox | S | The guest, or null for a loop that runs none. |
adapter | A | Where the guest's output is applied. |
options | GuestLoopOptions | Capacity and module order. |
Returns
GuestLoop<E, A, S>
Properties
adapter
ts
protected readonly adapter: A;Where the guest's output is applied.
args
ts
protected readonly args: EncodeArgs;The encoder's arguments, one object rewritten every tick.
bodies
ts
protected readonly bodies: BodyRows;Post-step body rows, reused; grows by doubling when the world does.
dead
ts
protected dead: boolean = false;True once the guest has died; latches.
elapsed
ts
protected elapsed: number = 0;Simulated seconds ticked so far.
encoder
ts
protected readonly encoder: InputEncoder;The frame-input builder; reuses one record.
engine
ts
protected readonly engine: E;The booted engine, page or headless.
frame
ts
protected frame: number = 0;Fixed steps ticked so far.
id
ts
readonly id: "game" = 'game';The module id; the slot it fills is registered under the same one.
Implementation of
order
ts
readonly order: number;The module order.
Implementation of
physics
ts
protected physics: PhysicsService | null = null;The physics service, looked up in init; null without one.
sandbox
ts
protected readonly sandbox: S;The guest, or null for a loop that runs none.
tap
ts
protected tap: StepTap | null = null;Sees each step's input and output: the page's playtest. Null for none.
Methods
beforeEncode()?
ts
protected optional beforeEncode(): void;Queue anything else onto adapter.events before they are drained.
Returns
void
beginStep()
ts
abstract protected beginStep(): void;Open the step on the adapter (beginFixedStep, beginTick).
Returns
void
dispose()
ts
dispose(): void;Unsubscribe, shut the guest down (when there is one) and dispose the adapter.
Returns
void
Implementation of
entityOfBody()
ts
abstract protected entityOfBody(body): number;Parameters
| Parameter | Type | Description |
|---|---|---|
body | number | A body id from a contact. |
Returns
number
The entity it drives.
fixedUpdate()
ts
fixedUpdate(dt): void;Tick the guest once and apply what it sent.
Parameters
| Parameter | Type | Description |
|---|---|---|
dt | number | The fixed step, in seconds. |
Returns
void
Implementation of
init()
ts
init(ctx): void;Look physics up, subscribe to physics:stepped, then the subclass's own set-up.
Parameters
| Parameter | Type | Description |
|---|---|---|
ctx | HostContext | The engine context. |
Returns
void
Implementation of
initGuest()
ts
abstract protected initGuest(ctx): void;The subclass's part of init: its own services, and sandbox.init.
Parameters
| Parameter | Type | Description |
|---|---|---|
ctx | HostContext | The engine context. |
Returns
void
onDead()
ts
abstract protected onDead(error): void;Report the guest's death. Runs once.
Parameters
| Parameter | Type | Description |
|---|---|---|
error | Error | null | Why the sandbox died. |
Returns
void
readInput()
ts
abstract protected readInput(): void;Fill this.args.inputState with this step's input.
Returns
void
readPlayers()
ts
protected readPlayers(): readonly PlayerInput[];This step's frame-input.players. Read once per step, after GuestLoop.readInput; must not allocate.
Returns
readonly PlayerInput[]
Every player in the room, ascending by id. Empty by default: a page is one player, and its input is frame-input.input.
runSeed()
ts
protected static runSeed(seed): bigint;Parameters
| Parameter | Type | Description |
|---|---|---|
seed | number | bigint | undefined | The caller's seed, if any. |
Returns
bigint
The run seed game.init takes; 0x5eed1234 when none was given.
step()
ts
protected step(input): FrameOutput | null;Run one step of the guest. Defaults to sandbox.tick, and to nothing without a sandbox.
Parameters
| Parameter | Type | Description |
|---|---|---|
input | HostFrameInput | This step's encoded frame-input. |
Returns
FrameOutput | null
The frame to apply, or null for nothing to apply (the dead check and applyOutput are skipped).
PlaytestController
The playtest controller.
Example
ts
import { createPlaytest } from 'gameable/host';
const playtest = createPlaytest();
// The host loop attaches it and calls `input` and `stepped` each step.
playtest.record();
// ... a person plays ...
const trace = playtest.stop();
await playtest.train();
const { summary } = await playtest.run({ episodes: 3 });Constructors
Constructor
ts
new PlaytestController(meta?): PlaytestController;Parameters
| Parameter | Type | Description |
|---|---|---|
meta | Record<string, string> | What every trace says about the game (its name, the engine commit). |
Returns
Accessors
mode
Get Signature
ts
get mode(): PlaytestMode;Returns
What the controller is doing.
obsVersion
Get Signature
ts
get obsVersion(): number;Returns
number
The observation layout this engine records and plays: a trace or policy of another is refused.
policy
Get Signature
ts
get policy(): Policy | null;Returns
Policy | null
The policy the agent plays with, or null.
traces
Get Signature
ts
get traces(): readonly Trace[];Returns
readonly Trace[]
Traces kept this session, oldest first.
Methods
assess()
ts
assess(runs): Assessment;Assess the game from runs summed up by who played them: can it be finished, how hard is each level, what in its pacing tends to spoil the fun (assess.ts).
Parameters
| Parameter | Type | Description |
|---|---|---|
runs | readonly PlayedRun[] | Summaries, each with who played: pilot, agent or human. |
Returns
The assessment.
Example
ts
const pilot = await playtest.pilot({ episodes: 8, speed: 4 });
const { possible, levels, fun } = playtest.assess([{ player: 'pilot', summary: pilot.summary }]);attach()
ts
attach(host): void;Called by the host loop once, when the guest starts.
Parameters
| Parameter | Type | Description |
|---|---|---|
host | PlaytestHost | What the loop gives. |
Returns
void
describe()
ts
describe(meta): void;Add to what every trace says about the game.
Parameters
| Parameter | Type | Description |
|---|---|---|
meta | Record<string, string> | Keys and values. |
Returns
void
detach()
ts
detach(): void;Stop listening and forget the host.
Returns
void
exportTrace()
ts
exportTrace(trace): Promise<Uint8Array<ArrayBufferLike>>;A trace as gzipped bytes, for an upload.
Parameters
| Parameter | Type | Description |
|---|---|---|
trace | Trace | The trace. |
Returns
Promise<Uint8Array<ArrayBufferLike>>
Its bytes, gzipped.
importTrace()
ts
importTrace(bytes): Promise<Trace>;Bytes from PlaytestController.exportTrace (or not gzipped) back into a trace.
Parameters
| Parameter | Type | Description |
|---|---|---|
bytes | Uint8Array | The bytes. |
Returns
Promise<Trace>
The trace.
input()
ts
input(input): void;The host loop's first call each step, after input is read: the agent or a replay writes its input here, and a person's is folded into an action.
Parameters
| Parameter | Type | Description |
|---|---|---|
input | PlaytestInput | The input block the guest is about to receive. |
Returns
void
jumps()
ts
jumps(): PlannedJump[];The jumps on the route from where the run began to the goal, each with what the player's measured movement makes of it: whether a walk or a run reaches it, how much reach is left over, and the jump speed or gap that would leave a 30 % margin, to tune a level to what the player can do. Empty before the level is scanned (a kept run with a footing and a goal).
Returns
PlannedJump[]
The jumps, in order.
Example
ts
for (const j of playtest.jumps()) console.log(j.across, j.rise, j.needs, j.margin);keep()
ts
keep(trace): void;Keep a trace from elsewhere (an upload, another session) to train on.
Parameters
| Parameter | Type | Description |
|---|---|---|
trace | Trace | The trace. |
Returns
void
movement()
ts
movement(): Movement;Returns
Movement
How the player has been seen to move: walk and run speed, jump speed, gravity.
observation()
ts
observation(): Float32Array;What the agent sees this step (schema.ts says what each float is). The array is reused: copy it to keep it.
Returns
Float32Array
The observation built on the last step.
Example
ts
const obs = playtestOf()?.observation();
console.log('goal ahead?', obs?.[OBS.goalBearing + 1]);on()
ts
on(listener): () => void;Listen to events, mode changes, training and episodes.
Parameters
| Parameter | Type | Description |
|---|---|---|
listener | (notice) => void | The listener. |
Returns
A function that stops listening.
() => void
pilot()
ts
pilot(options?): Promise<RunResult>;Let the route pilot play a number of lives and sum them up: a player that follows the route to the goal (pilot.ts), with no recording and no policy. Its runs are kept, as kind pilot, and are what PlaytestController.train learns from when no person has recorded a run. The route needs the game to have said where the goal is.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | RunOptions | Lives, their length, the speed (policy and temperature are not used). |
Returns
Promise<RunResult>
What the run found.
Example
ts
const { summary } = await playtestOf()!.pilot({ episodes: 5, speed: 4 });
console.log(summary.findings);play()
ts
play(options?): void;Let the agent play until PlaytestController.stop.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | AgentOptions | The policy and how freely it explores. |
Returns
void
Throws
When there is no policy.
practice()
ts
practice(options?): Promise<PracticeResult>;Let the agent practise: rounds of playing with room to explore, each followed by learning from its own steps, weighted by how well they went (see practice.ts). The person's runs are learned alongside. Every round begins where the first began. The best policy any round played with becomes the agent's, a practised one only when it scored clearly better than the one practice began with. Practice runs are not kept as traces.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | PracticeOptions | Rounds, lives, speed. |
Returns
Promise<PracticeResult>
Every round, and the best policy.
Throws
When there is no policy.
record()
ts
record(meta?): void;Start recording a person playing. Recording already going on is finished first.
Parameters
| Parameter | Type | Description |
|---|---|---|
meta | Record<string, string> | What this trace says about itself, on top of the game's. |
Returns
void
replay()
ts
replay(trace): Promise<void>;Play a trace's input back from here. For the same run again, reload the page with the trace's seed first.
Parameters
| Parameter | Type | Description |
|---|---|---|
trace | Trace | The trace. |
Returns
Promise<void>
Resolves when it has played out (or was stopped).
run()
ts
run(options?): Promise<RunResult>;Let the agent play a number of lives and sum them up.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | RunOptions | Lives, their length, the policy. |
Returns
Promise<RunResult>
What the run found.
setPolicy()
ts
setPolicy(policy): void;Use a saved policy.
Parameters
| Parameter | Type | Description |
|---|---|---|
policy | PolicyJson | Policy | The policy, or its JSON. |
Returns
void
status()
ts
status(): PlaytestStatus;Returns
The status, for a page to show.
stepped()
ts
stepped(
bodies,
bodyCount,
out,
dt
): void;The host loop's second call each step, with what the guest sent back and the bodies it saw.
Parameters
| Parameter | Type | Description |
|---|---|---|
bodies | ArrayLike<number> | Stride-15 body rows the guest received this step. |
bodyCount | number | Rows. |
out | FrameOutput | The guest's output. |
dt | number | The step, seconds. |
Returns
void
stop()
ts
stop(): Trace | null;Stop recording, the agent or a replay, and go back to watching.
Returns
Trace | null
The trace of what stopped, or null when nothing was being kept.
summary()
ts
summary(traces?): PlaytestSummary;Sum up the session so far, or some traces.
Parameters
| Parameter | Type | Description |
|---|---|---|
traces? | readonly Trace[] | Traces to sum up; the whole session's events when omitted. |
Returns
The summary.
train()
ts
train(traces?, options?): Promise<TrainResult>;Teach the agent from traces: this session's people's runs by default, or the route pilot's when there are none. The game is paused while it learns.
Parameters
| Parameter | Type | Description |
|---|---|---|
traces? | readonly Trace[] | What to learn from. |
options? | TrainOptions | How to train. |
Returns
Promise<TrainResult>
The policy, now the agent's, and how well it learned.
Policy
The policy network.
Example
ts
const policy = Policy.create(96, 1);
const action = new Uint8Array(6);
policy.act(observation, action, 0.5, new Rng(1));Constructors
Constructor
ts
new Policy(sizes, params?): Policy;Parameters
| Parameter | Type | Description |
|---|---|---|
sizes | readonly number[] | Layer widths, input to output. |
params? | Float32Array<ArrayBufferLike> | Weights and biases, or none for zeros. |
Returns
Properties
layout
ts
readonly layout: object[];Offsets of each layer's weights and biases in params.
b
ts
b: number;inputs
ts
inputs: number;outputs
ts
outputs: number;w
ts
w: number;mean
ts
readonly mean: Float32Array;Per-feature mean.
meta
ts
meta: Record<string, string | number> = {};What it was trained on.
params
ts
readonly params: Float32Array;Every weight and bias.
sizes
ts
readonly sizes: readonly number[];Layer widths, input to output.
std
ts
readonly std: Float32Array;Per-feature spread.
Methods
act()
ts
act(
obs,
action,
temperature,
rng
): void;Choose an action for one observation.
Parameters
| Parameter | Type | Description |
|---|---|---|
obs | Float32Array | The observation. |
action | Uint8Array | Where the classes go, one per head. |
temperature | number | 0 picks each head's likeliest class; above 0 samples, more freely the higher. |
rng | Rng | The sampler's generator. |
Returns
void
clone()
ts
clone(): Policy;Returns
A copy that trains apart from this one.
create()
ts
static create(hidden?, seed?): Policy;A fresh policy with He-initialised weights.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
hidden | number | 96 | Units in each of the two hidden layers. |
seed | number | 1 | The initialisation seed. |
Returns
The policy.
forward()
ts
forward(obs): Float32Array;Run the network on one observation.
Parameters
| Parameter | Type | Description |
|---|---|---|
obs | Float32Array | The observation. |
Returns
Float32Array
The logits, a view of scratch that the next call overwrites.
fromJSON()
ts
static fromJSON(json): Policy;Parameters
| Parameter | Type | Description |
|---|---|---|
json | PolicyJson | What Policy.toJSON made. |
Returns
The policy.
Throws
When it was trained on another observation layout.
toJSON()
ts
toJSON(): PolicyJson;Returns
The policy as JSON.
Interfaces
AdapterCall
One recorded EngineAdapter call.
Properties
args
ts
args: readonly unknown[];Arguments, by reference — they may be pooled and reused by the guest.
method
ts
method: AdapterMethod;Method name.
AgentOptions
Options for the agent.
Extended by
Properties
policy?
ts
optional policy?: Policy;The policy; the last trained or loaded one by default.
record?
ts
optional record?: boolean;Keep the agent's run as a trace. Default true.
temperature?
ts
optional temperature?: number;0 always picks the likeliest action; higher explores. Default 0.6.
Assessment
What the playtests say about a game.
Properties
findings
ts
findings: string[];What to look at first.
fun
ts
fun: string[];Signals about fun, each a short sentence that says what it is a proxy for.
levels
ts
levels: LevelAssessment[];Each level in order.
possible
ts
possible: "unknown" | "yes" | "no";Can it be finished: every level reached by someone.
why
ts
why: string;Why, in a sentence.
CharacterClipEnd
A pooled character animation or motion event.
Example
ts
import type { CharacterClipEnd } from 'gameable/host';
const event: CharacterClipEnd = { entity: 1, clip: 'idle', name: 'loop', time: 0 };
console.log(event.clip);Properties
clip
ts
clip: string;The clip's runtime name; ragdoll for the physics body's own events; left-foot or right-foot for a footstep; motion for what the movement system says (an action's moments among them: see CharacterClipEnd.motion).
entity
ts
entity: number;The character.
motion?
ts
optional motion?: CharacterMotionSaid;What the movement system says (the clip is then motion): absent on every other record. The record is reused: copy what you keep. The host loop sends it to the game as a motion-event.
name
ts
name: "ended" | "hit" | "step" | "loop" | "fell" | "recovered";'ended' (a once-only clip finished) or 'loop' (a looping clip wrapped); on the clip ragdoll: 'hit' (a blow landed), 'fell' (the body came to rest on the floor) or 'recovered' (back in the animation); on left-foot / right-foot: 'step' (the foot came down; only with locomotion.footPlant). On the clip motion it says nothing: what happened is motion.kind.
time
ts
time: number;The clip's local time at the report, seconds; the seconds since the hit for ragdoll; the seconds since the character's last footstep for a step (0 for its first).
CharacterLoadProgress
How far one character's package has come.
Properties
copy
ts
readonly copy: "full" | "light";'light' for a lighter copy drawn first, 'full' for the whole package.
entity
ts
readonly entity: number;The entity the character belongs to.
files
ts
files: number;filesDone
ts
filesDone: number;Files finished, and files in all (0 until the descriptor is read).
id
ts
readonly id: string;The character's manifest id.
loaded
ts
loaded: number;Bytes that have come.
readyAt
ts
readyAt: number;startedAt
ts
startedAt: number;When the first request went out and when the character stood, performance.now().
state
ts
state: "failed" | "ready" | "loading" | "waiting";Where it is: waiting its turn, downloading, built and drawn, or given up.
stillAt
ts
stillAt: number;When the character's points were first drawn still, before it stood (stillFirst), performance.now(); 0 until then, and 0 for a character drawn posed at once.
total
ts
total: number;Bytes in all, as the descriptor names them, or 0 until it is read.
CharacterMotionRequest
Host motion controls for one character.
Example
ts
import type { CharacterMotionRequest } from 'gameable/host';
const motion: CharacterMotionRequest = { on: true, stop: 'hard' };
console.log(motion.stop);Properties
carry?
ts
optional carry?: boolean;Whether the take carries the walker.
naturalness?
ts
optional naturalness?: number;on?
ts
optional on?: boolean;Whether the movement system moves the character at all.
responsiveness?
ts
optional responsiveness?: number;0 to 1; below 0 keeps what it has.
set?
ts
optional set?: string;The set, by name: 'own', 'shared' or a name in the bridge's motion.sets.
stop?
ts
optional stop?: StopStyle;Which kind of stop the character makes when it runs and is asked to stand (the stick let go, a walk to a spot given up): 'gradual' (the default: it slows and stands upright) or 'hard' (it brakes). Read on a run's stops, where its set has stops of both kinds; a walk's stop and a sprint's stop are the same under both on the shared set. Left out, it keeps the kind it has.
CharacterMotionSaid
A pooled host motion report.
Example
ts
import type { CharacterMotionSaid } from 'gameable/host';
function report(event: CharacterMotionSaid): void { console.log(event.kind, event.name); }
console.log(typeof report);Properties
amount
ts
amount: number;'arrived': how far from the spot asked it stands, metres ('face': from the facing asked, radians). 'limited': the speed it is given, metres a second. 'started' and 'done' named 'stop': the metres it is from the spot. 'contact' of a move played from the seat with a target: how far the wrist or ankle is from the target, metres.
facing
ts
facing: number;The way the character faces there, radians about +Y: where a walk to a spot left it.
kind
ts
kind:
| "limited"
| "failed"
| "ready"
| "arrived"
| "started"
| "contact"
| "release"
| "landed"
| "done";'ready' (the character's motion set has the body: from here it moves by its takes), 'arrived' (a walk to a spot got there), an action's 'started', 'contact', 'release', 'landed', 'done', or 'failed'. Of a walk to a spot, named 'stop': 'started' (its stop begins) and 'done' (it no longer travels; 'arrived' follows when it has settled). Of a move played from the seat (seatedMove), named by the move: 'started', 'contact', 'release', 'done', 'failed'.
limb
ts
limb: number;The limb (0 left hand, 1 right hand, 2 left foot, 3 right foot), or -1.
name
ts
name: string;The action's name; the set's name for 'ready'; 'walk' for a walk to a spot, 'face' for a turn on the spot; the gait for 'limited' (the speed asked is not one the set covers): 'walk', 'run', or 'sprint' on a set that carries a sprint part.
object
ts
object: number;The object's number as the game gave it, or -1.
point
ts
point: [number, number, number];Where, world metres, and how fast that point moves, metres a second: the hand or the foot at a 'contact', the hand at a 'release' (the thing let go is given this speed), the limb that clipped. For 'landed': where the body landed, at the height of the floor it landed on (a game whose action ends on another floor moves its walker to that height). Otherwise: where the character stands.
reason
ts
reason: string;Why, for 'failed'; empty otherwise. Of an action: hit (the body was hit), clipped (a limb met the object: the action goes on, the physics body flinches), no-floor (nothing under the landing: the body falls), too-close, not-lined-up, wrong-foot (no way in was found), cancelled; of a request refused at once: not-available, unknown-action, needs-object, too-high, too-low, busy, seated (the character sits on something: see seat). Of a move played from the seat: replaced, cancelled, unseated; and on its 'contact': out-of-range (a target was given and lay outside the take's reach).
velocity
ts
velocity: [number, number, number];CutsceneBridge
The bridge.
Properties
player
ts
readonly player: CutscenePlayer;The core player underneath, for a page that plays a clip of its own.
Methods
dispose()
ts
dispose(): void;Drop the player and its preloaded clips.
Returns
void
handle()
ts
handle(command): void;The engine adapter's cutscene option: hand the game's commands here.
Parameters
| Parameter | Type |
|---|---|
command | CutsceneCmd |
Returns
void
CutsceneBridgeOptions
Options for createCutsceneBridge.
Properties
duckSeconds?
ts
readonly optional duckSeconds?: number;Seconds the duck takes to settle, each way. Default 0.25.
engine
ts
readonly engine: Engine;The engine: the manifest's URLs and the time scale.
events
ts
readonly events: GameEvent[];Where the game's events go (adapter.events of the engine adapter).
mixer?
ts
readonly optional mixer?: CutsceneMixer;The mixer to duck under a clip. Nothing is ducked without one.
player?
ts
readonly optional player?: Omit<CutscenePlayerOptions, "onPause" | "onDuck">;Passed to the core player (the container, the stacking order, the words).
warn?
ts
readonly optional warn?: (message) => void;Where warnings go. Defaults to console.warn.
Parameters
| Parameter | Type |
|---|---|
message | string |
Returns
void
CutsceneMixer
What the bridge needs of a mixer: the master bus and the clock. The audio module's engine fits.
Properties
buses
ts
readonly buses: object;master
ts
readonly master: object;master.gain
ts
readonly gain: AudioParam;context
ts
readonly context: object;currentTime
ts
readonly currentTime: number;DirectSandboxOptions
Run the game's TypeScript directly, in the host realm.
Properties
game
ts
game: GameDefinition;The game's defineGame result.
host
ts
host: HostApi;Host services the guest imports.
mode
ts
mode: "direct";DomHudOptions
Options accepted by createDomHud.
Properties
className?
ts
optional className?: string;Class name given to the root element. Defaults to aos-hud.
container?
ts
optional container?: HudElement;Where the overlay is appended. Defaults to document.body.
document?
ts
optional document?: HudDocument;Document used to create elements. Defaults to the global document.
EditorActor
An actor as the editor lists it.
Properties
class
ts
class: string;Its class name.
editable
ts
editable: boolean;True when a level file placed it: it can be moved and written back.
entity
ts
entity: number;Its root entity: the object the page draws.
id
ts
id: number;The actor's runtime id.
name
ts
name: string;Its name: the level entry's, the automatic one, or '' from code.
position
ts
position: [number, number, number];World position, as drawn.
props
ts
props: Record<string, unknown>;Its props, as the guest holds them.
rotation
ts
rotation: [number, number, number, number];World rotation xyzw, as drawn.
scale
ts
scale: [number, number, number];Scale, as drawn.
source?
ts
optional source?: ActorSource;The level entry that placed it, when one did.
tags
ts
tags: string[];Its tags.
yaw
ts
yaw: number;Degrees about +Y, zero facing +Z, from the rotation.
EditorAdapter
The subset of the adapter the editor writes through.
Properties
transforms
ts
readonly transforms: TransformStore;The page's transform store: where an entity is drawn.
Methods
bodyOfEntity()
ts
bodyOfEntity(entity): number | undefined;Parameters
| Parameter | Type | Description |
|---|---|---|
entity | number | An entity. |
Returns
number | undefined
The body driving it, if any.
entityOfBody()
ts
entityOfBody(body): number;Parameters
| Parameter | Type | Description |
|---|---|---|
body | number | A body id. |
Returns
number
The entity it drives, or 0.
setBodyTransform()
ts
setBodyTransform(
body,
position,
rotation,
teleport
): void;Put a body somewhere.
Parameters
| Parameter | Type | Description |
|---|---|---|
body | number | The body. |
position | { x: number; y: number; z: number; } | Where. |
position.x | number | - |
position.y | number | - |
position.z | number | - |
rotation | { w: number; x: number; y: number; z: number; } | Facing. |
rotation.w | number | - |
rotation.x | number | - |
rotation.y | number | - |
rotation.z | number | - |
teleport | boolean | Snap rather than interpolate. |
Returns
void
setTransformFromHost()
ts
setTransformFromHost(
entity,
flags,
position,
rotation,
scale
): void;Write a transform the host authored.
Parameters
| Parameter | Type | Description |
|---|---|---|
entity | number | The entity. |
flags | number | TRANSFORM_FLAGS bits. |
position | ArrayLike<number> | xyz. |
rotation | ArrayLike<number> | xyzw. |
scale | ArrayLike<number> | xyz. |
Returns
void
EditorControls
The gizmo and the orbit, as three's controls or a test's stand-ins.
Properties
gizmo
ts
gizmo: object;The transform gizmo.
axis
ts
readonly axis: string | null;dragging
ts
readonly dragging: boolean;object
ts
readonly object: Object3D<Object3DEventMap> | undefined;addEventListener()
ts
addEventListener(type, listener): void;Parameters
| Parameter | Type |
|---|---|
type | "objectChange" | "dragging-changed" |
listener | (event) => void |
Returns
void
attach()
ts
attach(object): unknown;Parameters
| Parameter | Type |
|---|---|
object | Object3D |
Returns
unknown
detach()
ts
detach(): unknown;Returns
unknown
dispose()
ts
dispose(): void;Returns
void
getHelper()
ts
getHelper(): Object3D;Returns
Object3D
setMode()
ts
setMode(mode): void;Parameters
| Parameter | Type |
|---|---|
mode | "scale" | "translate" | "rotate" |
Returns
void
setRotationSnap()
ts
setRotationSnap(snap): void;Parameters
| Parameter | Type |
|---|---|
snap | number | null |
Returns
void
setScaleSnap()
ts
setScaleSnap(snap): void;Parameters
| Parameter | Type |
|---|---|
snap | number | null |
Returns
void
setTranslationSnap()
ts
setTranslationSnap(snap): void;Parameters
| Parameter | Type |
|---|---|
snap | number | null |
Returns
void
orbit
ts
orbit: object;The orbit camera.
enabled
ts
enabled: boolean;target
ts
target: Vector3;dispose()
ts
dispose(): void;Returns
void
update()
ts
update(): unknown;Returns
unknown
EditorHost
What the host loop gives the editor.
Properties
adapter
ts
adapter: EditorAdapter;The adapter, for the transform store and the bodies.
controls?
ts
optional controls?: (engine) => Promise<EditorControls>;Make the controls. Defaults to three's OrbitControls and TransformControls.
Parameters
| Parameter | Type | Description |
|---|---|---|
engine | Engine | The engine the controls drive. |
Returns
Promise<EditorControls>
The controls.
engine
ts
engine: Engine;The engine: its scene, camera, renderer and graph.
input
ts
input: InputService | null;The input service, or null without one.
pause
ts
pause: object;Shared pause ownership for the page.
pop()
ts
pop(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
push()
ts
push(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
physics
ts
physics: PhysicsService | null;The physics world, or null without one.
Methods
snapshot()
ts
snapshot(): Uint8Array;Returns
Uint8Array
The guest's state, for its actor rows.
EditorLevels
What the guest says about its levels, from the snapshot's levels part.
Properties
current
ts
current: string | null;The loaded one, or null.
names
ts
names: string[];Every declared level, in declaration order.
place
ts
place: string | null;The loaded level's place, or null.
EditorTransform
A transform, or part of one, for Editor.setTransform.
Properties
position?
ts
optional position?: readonly [number, number, number];rotation?
ts
optional rotation?: readonly [number, number, number, number];scale?
ts
optional scale?: readonly [number, number, number];yaw?
ts
optional yaw?: number;Degrees about +Y; ignored when rotation is given.
EncodeArgs
Everything an encoder needs for one fixed step.
Properties
bodies
ts
bodies: Float32Array;Packed body rows, stride 15, sorted ascending by body id.
Handed to the guest as a view of this very buffer, so the caller may grow it whenever it likes — the encoder notices the new identity and drops the views it memoised over the old one.
bodyCount
ts
bodyCount: number;Live body count; bodies may be longer.
contacts?
ts
optional contacts?: readonly Contact[];Reported contacts.
dt
ts
dt: number;Fixed timestep in seconds.
elapsed
ts
elapsed: number;Simulated seconds since init.
events?
ts
optional events?: readonly GameEvent[];Host-side events since the previous tick.
frame
ts
frame: number;Fixed-step counter.
inputState
ts
inputState: InputSnapshot;Host input state.
players?
ts
optional players?: readonly PlayerInput[];Every player's input in a room, ascending by id. Absent or empty for one player.
vehicles?
ts
optional vehicles?: Float32Array<ArrayBufferLike>;Post-step versioned vehicle readback, captured with bodies.
EngineAdapter
Everything the host can be asked to do, one method per command.
Extended by
Properties
appliesLocal
ts
readonly appliesLocal: boolean;True when frame-output.local-commands are applied here, after commands: the page's own adapter and the authority's server adapter. A replica's adapter says false; the replicator never forwards them.
Methods
addBody()
ts
addBody(args): void;Create a rigid body or character controller.
Parameters
| Parameter | Type |
|---|---|
args | AddBodyCmd |
Returns
void
addJoint()
ts
addJoint(args): void;Create a joint; invalid body references are dropped.
Parameters
| Parameter | Type |
|---|---|
args | AddJointCmd |
Returns
void
addVehicle()
ts
addVehicle(command): void;Attach arcade handling to a dynamic body.
Parameters
| Parameter | Type |
|---|---|
command | AddVehicleCmd |
Returns
void
applyImpulse()
ts
applyImpulse(
body,
impulse,
atPoint
): void;Apply a one-shot impulse.
Parameters
| Parameter | Type |
|---|---|
body | number |
impulse | Vec3 |
atPoint | Vec3 | undefined |
Returns
void
applyTransforms()
ts
applyTransforms(transforms, count): void;Apply packed entity transforms.
Parameters
| Parameter | Type | Description |
|---|---|---|
transforms | Float32Array | Stride 12: entity, flags, position, rotation, scale. |
count | number | Number of rows. The buffer may be longer. |
Returns
void
cancelCharacterAction()
ts
cancelCharacterAction(entity): void;Take an action's request back.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
conversation()
ts
conversation(command): void;Forward structural controls to an optional conversation module.
Parameters
| Parameter | Type |
|---|---|
command | ConversationCmd |
Returns
void
cutscene()
ts
cutscene(command): void;A cutscene: preload, play over the stage, or skip (the optional cutscene bridge).
Parameters
| Parameter | Type |
|---|---|
command | CutsceneCmd |
Returns
void
despawn()
ts
despawn(entity): void;Destroy an entity and everything attached to it.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
doCharacterAction()
ts
doCharacterAction(command): void;Ask a character to do an action of its motion set.
Parameters
| Parameter | Type |
|---|---|
command | DoCharacterActionCmd |
Returns
void
effect()
ts
effect(command): void;Apply a particle command; payload is borrowed.
Parameters
| Parameter | Type |
|---|---|
command | EffectCmd |
Returns
void
exchange()
ts
exchange(command): void;Trade between two players' documents. The command is pooled: read it, never keep it.
Parameters
| Parameter | Type |
|---|---|
command | ExchangeCmd |
Returns
void
faceCharacter()
ts
faceCharacter(
entity,
facing,
quick
): void;Turn a character on the spot to face a way.
Parameters
| Parameter | Type |
|---|---|
entity | number |
facing | number |
quick | boolean |
Returns
void
fightCamera()
ts
fightCamera(command): void;The fight camera, run on the host.
Parameters
| Parameter | Type |
|---|---|
command | FightCameraCmd |
Returns
void
fightFall()
ts
fightFall(command): void;A fighter thrown into the fight kit's rag-doll.
Parameters
| Parameter | Type |
|---|---|
command | FightFallCmd |
Returns
void
fightGetUp()
ts
fightGetUp(command): void;A fighter up off the floor.
Parameters
| Parameter | Type |
|---|---|
command | FightGetUpCmd |
Returns
void
fightHit()
ts
fightHit(command): void;A blow on a fighter on the fight kit's door.
Parameters
| Parameter | Type |
|---|---|
command | FightHitCmd |
Returns
void
fightState()
ts
fightState(command): void;The fight kit's script door: what a fighter's body is doing this step.
Parameters
| Parameter | Type |
|---|---|
command | FightStateCmd |
Returns
void
hitCharacter()
ts
hitCharacter(
entity,
at,
direction,
strength
): void;A blow on a character's physics body.
Parameters
| Parameter | Type |
|---|---|
entity | number |
at | Vec3 |
direction | Vec3 |
strength | HitStrength |
Returns
void
loadAsset()
ts
loadAsset(asset, priority): void;Start loading an asset.
Parameters
| Parameter | Type |
|---|---|
asset | number |
priority | number |
Returns
void
localScope()?
ts
optional localScope(on): void;Optional: told when applyOutput starts (true) and ends (false) applying frame-output.local-commands. The server adapter uses it to keep what a local command does out of the replicated world record.
Parameters
| Parameter | Type |
|---|---|
on | boolean |
Returns
void
lookAt()
ts
lookAt(
entity,
target,
weight
): void;Aim a character's head and eyes.
Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Vec3 | undefined |
weight | number |
Returns
void
moveCharacter()
ts
moveCharacter(
body,
desiredVelocity,
jump,
crouch,
maxSlopeDeg
): void;Drive a character body for one step.
Parameters
| Parameter | Type |
|---|---|
body | number |
desiredVelocity | Vec3 |
jump | boolean |
crouch | boolean |
maxSlopeDeg | number |
Returns
void
pausePop()
ts
pausePop(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
pausePush()
ts
pausePush(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
playMusic()
ts
playMusic(command): void;Apply play-music.
Parameters
| Parameter | Type |
|---|---|
command | PlayMusicCmd |
Returns
void
playSound()
ts
playSound(
sound,
asset,
entity,
position,
volume,
pitch,
looping,
bus
): void;Start a sound.
Parameters
| Parameter | Type |
|---|---|
sound | number |
asset | number |
entity | number | undefined |
position | Vec3 | undefined |
volume | number |
pitch | number |
looping | boolean |
bus | AudioBus |
Returns
void
playSoundOnBeat()
ts
playSoundOnBeat(command): void;Apply play-sound-on-beat.
Parameters
| Parameter | Type |
|---|---|
command | PlaySoundOnBeatCmd |
Returns
void
playtest()
ts
playtest(command): void;A playtest mark. It changes nothing in the game: the page's playtest tap reads the marks off the frame itself, so an adapter ignores them. The command is pooled: read it, never keep it.
Parameters
| Parameter | Type |
|---|---|
command | PlaytestCmd |
Returns
void
recoverCharacter()
ts
recoverCharacter(entity): void;A character that is down blends back into its animation.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
removeBody()
ts
removeBody(body): void;Destroy a body.
Parameters
| Parameter | Type |
|---|---|
body | number |
Returns
void
removeJoint()
ts
removeJoint(joint): void;Destroy a joint.
Parameters
| Parameter | Type |
|---|---|
joint | number |
Returns
void
removeVehicle()
ts
removeVehicle(body): void;Release handling, leaving the chassis.
Parameters
| Parameter | Type |
|---|---|
body | number |
Returns
void
resetVehicle()
ts
resetVehicle(command): void;Teleport and reset handling history.
Parameters
| Parameter | Type |
|---|---|
command | ResetVehicleCmd |
Returns
void
saveGameData()
ts
saveGameData(data): void;Persist the room's game-wide document (JSON).
Parameters
| Parameter | Type |
|---|---|
data | string |
Returns
void
savePlayerData()
ts
savePlayerData(player, data): void;Persist one player's document (JSON).
Parameters
| Parameter | Type |
|---|---|
player | number |
data | string |
Returns
void
say()
ts
say(
entity,
text,
audio,
visemes
): void;Speak a line.
Parameters
| Parameter | Type |
|---|---|
entity | number |
text | string |
audio | number | undefined |
visemes | string | undefined |
Returns
void
send()
ts
send(
to,
name,
payload,
reliable
): void;Send a game message; to undefined is every player (or the authority, from a client).
Parameters
| Parameter | Type |
|---|---|
to | number | undefined |
name | string |
payload | string |
reliable | boolean |
Returns
void
setAnim()
ts
setAnim(
entity,
clip,
looping,
speed,
fadeMs,
weight
): void;Play or cross-fade an animation clip.
Parameters
| Parameter | Type |
|---|---|
entity | number |
clip | string |
looping | boolean |
speed | number |
fadeMs | number |
weight | number |
Returns
void
setAsset()
ts
setAsset(entity, asset): void;Attach or detach a renderable.
Parameters
| Parameter | Type |
|---|---|
entity | number |
asset | number | undefined |
Returns
void
setBodyEnabled()
ts
setBodyEnabled(body, enabled): void;Enable or disable a body in the broad phase.
Parameters
| Parameter | Type |
|---|---|
body | number |
enabled | boolean |
Returns
void
setBodyTransform()
ts
setBodyTransform(
body,
position,
rotation,
teleport
): void;Move a body directly.
Parameters
| Parameter | Type |
|---|---|
body | number |
position | Vec3 |
rotation | Quat |
teleport | boolean |
Returns
void
setBodyVelocity()
ts
setBodyVelocity(
body,
linear,
angular
): void;Overwrite a body's velocities; undefined leaves one untouched.
Parameters
| Parameter | Type |
|---|---|
body | number |
linear | Vec3 | undefined |
angular | Vec3 | undefined |
Returns
void
setBusFx()
ts
setBusFx(command): void;Apply set-bus-fx.
Parameters
| Parameter | Type |
|---|---|
command | SetBusFxCmd |
Returns
void
setCamera()
ts
setCamera(camera): void;Apply the camera the guest asked for.
Parameters
| Parameter | Type |
|---|---|
camera | CameraState |
Returns
void
setCharacterMotion()
ts
setCharacterMotion(command): void;How the movement system moves a character.
Parameters
| Parameter | Type |
|---|---|
command | SetCharacterMotionCmd |
Returns
void
setCharacterState()
ts
setCharacterState(
entity,
state,
velocity,
grounded,
facing?
): void;Drive a character's locomotion state machine.
Parameters
| Parameter | Type |
|---|---|
entity | number |
state | string |
velocity | Vec3 |
grounded | boolean |
facing? | number |
Returns
void
setClipWeights()
ts
setClipWeights(
entity,
clips,
weights,
timeScale
): void;Set explicit per-clip weights.
Parameters
| Parameter | Type |
|---|---|
entity | number |
clips | readonly string[] |
weights | ArrayLike<number> |
timeScale | number |
Returns
void
setExpression()
ts
setExpression(
entity,
space,
weights
): void;Set facial expression coefficients.
Parameters
| Parameter | Type |
|---|---|
entity | number |
space | ExpressionSpace |
weights | ArrayLike<number> |
Returns
void
setHud()
ts
setHud(json): void;Apply the HUD model, or leave the previous one when undefined.
Parameters
| Parameter | Type |
|---|---|
json | string | undefined |
Returns
void
setJointMotor()
ts
setJointMotor(args): void;Set a joint motor in radians/metres.
Parameters
| Parameter | Type |
|---|---|
args | SetJointMotorCmd |
Returns
void
setListener()
ts
setListener(
position,
rotation,
velocity
): void;Place the audio listener.
Parameters
| Parameter | Type |
|---|---|
position | Vec3 |
rotation | Quat |
velocity | Vec3 |
Returns
void
setMaterialParam()
ts
setMaterialParam(
entity,
name,
value
): void;Set one material uniform.
Parameters
| Parameter | Type |
|---|---|
entity | number |
name | string |
value | MaterialValue |
Returns
void
setMusicLayer()
ts
setMusicLayer(command): void;Apply set-music-layer.
Parameters
| Parameter | Type |
|---|---|
command | SetMusicLayerCmd |
Returns
void
setParent()
ts
setParent(
entity,
parent,
keepWorldTransform
): void;Reparent an entity.
Parameters
| Parameter | Type |
|---|---|
entity | number |
parent | number | undefined |
keepWorldTransform | boolean |
Returns
void
setPlayerCamera()
ts
setPlayerCamera(player, camera): void;The camera one player renders from.
Parameters
| Parameter | Type |
|---|---|
player | number |
camera | CameraState |
Returns
void
setPlayerEntity()
ts
setPlayerEntity(
player,
entity,
spawn?
): void;Which entity a player controls (0 for none). The authority keeps the mapping for relevancy and each player's "your entity"; a page ignores it.
Parameters
| Parameter | Type |
|---|---|
player | number |
entity | number |
spawn? | number |
Returns
void
setPlayerHud()
ts
setPlayerHud(player, hud): void;One player's HUD model as JSON.
Parameters
| Parameter | Type |
|---|---|
player | number |
hud | string |
Returns
void
setPointerLock()
ts
setPointerLock(locked): void;Request or release pointer lock.
Parameters
| Parameter | Type |
|---|---|
locked | boolean |
Returns
void
setPost()
ts
setPost(command): void;Apply partial post settings; payload is borrowed.
Parameters
| Parameter | Type |
|---|---|
command | PostCmd |
Returns
void
setSoundOcclusion()
ts
setSoundOcclusion(command): void;Apply set-sound-occlusion.
Parameters
| Parameter | Type |
|---|---|
command | SetSoundOcclusionCmd |
Returns
void
setSpotLight()?
ts
optional setSpotLight(command): void;Create or update an entity-owned spotlight; optional for headless adapters.
Parameters
| Parameter | Type |
|---|---|
command | SpotLightCmd |
Returns
void
setTimeScale()
ts
setTimeScale(scale): void;Scale simulated time.
Parameters
| Parameter | Type |
|---|---|
scale | number |
Returns
void
setUi()
ts
setUi(json): void;Apply the page UI model, or keep it when undefined.
Parameters
| Parameter | Type |
|---|---|
json | string | undefined |
Returns
void
setVehicleInput()
ts
setVehicleInput(command): void;Set one step of vehicle controls.
Parameters
| Parameter | Type |
|---|---|
command | SetVehicleInputCmd |
Returns
void
spawn()
ts
spawn(
entity,
asset,
position,
rotation,
scale,
flags
): void;Create an entity in the scene.
Parameters
| Parameter | Type |
|---|---|
entity | number |
asset | number | undefined |
position | Vec3 |
rotation | Quat |
scale | Vec3 |
flags | { name?: string; parent?: number; visible: boolean; } |
flags.name? | string |
flags.parent? | number |
flags.visible | boolean |
Returns
void
spawnCharacter()
ts
spawnCharacter(
entity,
bundle,
position,
rotation
): void;Instantiate a splat character bundle.
Parameters
| Parameter | Type |
|---|---|
entity | number |
bundle | number |
position | Vec3 |
rotation | Quat |
Returns
void
stopCharacterWalk()
ts
stopCharacterWalk(entity): void;Give up a walk to a spot.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
stopMusic()
ts
stopMusic(command): void;Apply stop-music.
Parameters
| Parameter | Type |
|---|---|
command | number |
Returns
void
stopSound()
ts
stopSound(sound, fadeMs): void;Stop a playing sound.
Parameters
| Parameter | Type |
|---|---|
sound | number |
fadeMs | number |
Returns
void
thing()
ts
thing(command): void;Something asked of a loose thing in a made world (the optional world bridge).
Parameters
| Parameter | Type |
|---|---|
command | ThingCmd |
Returns
void
walkCharacterTo()
ts
walkCharacterTo(
entity,
target,
facing,
pace,
quick,
stop?,
start?
): void;Walk a character to a spot. stop is the kind of stop this one walk ends with ('gradual', it slows and stands upright; 'hard', it brakes); left out: the character's own. start says how it is begun ('moving': the game says the body is under way already); left out: as the character's takes have the body.
Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Vec3 |
facing | number | undefined |
pace | number |
quick | boolean |
stop? | StopStyle |
start? | "moving" |
Returns
void
EngineAdapterHandle
The engine-backed adapter, plus the hooks the host loop drives.
Extends
Properties
appliesLocal
ts
readonly appliesLocal: boolean;True when frame-output.local-commands are applied here, after commands: the page's own adapter and the authority's server adapter. A replica's adapter says false; the replicator never forwards them.
Inherited from
clipEnds
ts
readonly clipEnds: CharacterClipEnd[] | null;The character bridge's clips' ends since the loop last drained them (CharacterBridge.clipEnds), or null without a bridge.
events
ts
readonly events: GameEvent[];Host-side occurrences since the loop last drained them.
hud
ts
readonly hud: HudRenderer | null;The HUD renderer, or null when hud: false.
hudModel
ts
readonly hudModel: unknown;The HUD model currently on screen, whether or not a renderer is attached.
musicEventsEnabled
ts
readonly musicEventsEnabled: boolean;A bpm-enabled music request has started.
musicTracks
ts
readonly musicTracks: readonly number[];Handles in the current music source order.
savesReady?
ts
readonly optional savesReady?: Promise<void>;Solo documents have finished loading before gameplay begins.
transforms
ts
readonly transforms: TransformStore;Previous/current transforms, slot 0 being the camera.
ui
ts
readonly ui: UiRenderer | null;The page UI renderer, or null when disabled.
uiModel
ts
readonly uiModel: unknown;The UI model currently on screen.
usesCharacterPhysics?
ts
readonly optional usesCharacterPhysics?: boolean;True when the page owns the character rig and its physics.
Methods
addBody()
ts
addBody(args): void;Create a rigid body or character controller.
Parameters
| Parameter | Type |
|---|---|
args | AddBodyCmd |
Returns
void
Inherited from
addJoint()
ts
addJoint(args): void;Create a joint; invalid body references are dropped.
Parameters
| Parameter | Type |
|---|---|
args | AddJointCmd |
Returns
void
Inherited from
addVehicle()
ts
addVehicle(command): void;Attach arcade handling to a dynamic body.
Parameters
| Parameter | Type |
|---|---|
command | AddVehicleCmd |
Returns
void
Inherited from
animationOf()
ts
animationOf(entity): CharacterAnimationState | null;What the guest last asked an entity's animation to do.
Parameters
| Parameter | Type | Description |
|---|---|---|
entity | number | The entity. |
Returns
CharacterAnimationState | null
The recorded intent, or null when the entity has never been the subject of a spawn-character, set-anim or set-character-state.
applyBodyRows()
ts
applyBodyRows(rows, count): void;Write post-step body rows straight onto the entities they drive.
The host half of "physics owns body transforms": the physics module hands these rows over the moment it has stepped, and each one becomes the driven entity's current position and rotation in the transform store. The entity's scale is left alone — a body has none, and the guest's is the only opinion there is.
Nothing crosses the wasm boundary here. The guest still receives the same rows as frame-input.bodies on its next tick and still keeps Transform and Velocity up to date for gameplay; it simply no longer has to send twelve floats per body back for the host to apply a second time.
Parameters
| Parameter | Type | Description |
|---|---|---|
rows | Float32Array | Stride-15 rows, as PhysicsWorld.readBodies writes them. |
count | number | Rows to read; rows may be longer. |
Returns
void
Nothing.
applyImpulse()
ts
applyImpulse(
body,
impulse,
atPoint
): void;Apply a one-shot impulse.
Parameters
| Parameter | Type |
|---|---|
body | number |
impulse | Vec3 |
atPoint | Vec3 | undefined |
Returns
void
Inherited from
applyTransforms()
ts
applyTransforms(transforms, count): void;Apply packed entity transforms.
Parameters
| Parameter | Type | Description |
|---|---|---|
transforms | Float32Array | Stride 12: entity, flags, position, rotation, scale. |
count | number | Number of rows. The buffer may be longer. |
Returns
void
Inherited from
beginFixedStep()
ts
beginFixedStep(): void;Roll current transforms into previous ones.
Call once per fixed step, before applying that step's output.
Returns
void
Nothing.
bodyOfEntity()
ts
bodyOfEntity(entity): number | undefined;Root body currently driving an entity.
Parameters
| Parameter | Type | Description |
|---|---|---|
entity | number | Entity id. |
Returns
number | undefined
Body id, or undefined when absent.
Example
ts
const body = adapter.bodyOfEntity(player);cancelCharacterAction()
ts
cancelCharacterAction(entity): void;Take an action's request back.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
EngineAdapter.cancelCharacterAction
conversation()
ts
conversation(command): void;Forward structural controls to an optional conversation module.
Parameters
| Parameter | Type |
|---|---|
command | ConversationCmd |
Returns
void
Inherited from
cutscene()
ts
cutscene(command): void;A cutscene: preload, play over the stage, or skip (the optional cutscene bridge).
Parameters
| Parameter | Type |
|---|---|
command | CutsceneCmd |
Returns
void
Inherited from
despawn()
ts
despawn(entity): void;Destroy an entity and everything attached to it.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
dispose()
ts
dispose(): void;Release the HUD and every object this adapter put in the scene.
Returns
void
doCharacterAction()
ts
doCharacterAction(command): void;Ask a character to do an action of its motion set.
Parameters
| Parameter | Type |
|---|---|
command | DoCharacterActionCmd |
Returns
void
Inherited from
EngineAdapter.doCharacterAction
effect()
ts
effect(command): void;Apply a particle command; payload is borrowed.
Parameters
| Parameter | Type |
|---|---|
command | EffectCmd |
Returns
void
Inherited from
entityOfBody()
ts
entityOfBody(body): number;The entity a body id drives.
Parameters
| Parameter | Type | Description |
|---|---|---|
body | number | Body id minted by the guest. |
Returns
number
The entity, or 0 when the body is unknown.
exchange()
ts
exchange(command): void;Trade between two players' documents. The command is pooled: read it, never keep it.
Parameters
| Parameter | Type |
|---|---|
command | ExchangeCmd |
Returns
void
Inherited from
faceCharacter()
ts
faceCharacter(
entity,
facing,
quick
): void;Turn a character on the spot to face a way.
Parameters
| Parameter | Type |
|---|---|
entity | number |
facing | number |
quick | boolean |
Returns
void
Inherited from
fightCamera()
ts
fightCamera(command): void;The fight camera, run on the host.
Parameters
| Parameter | Type |
|---|---|
command | FightCameraCmd |
Returns
void
Inherited from
fightFall()
ts
fightFall(command): void;A fighter thrown into the fight kit's rag-doll.
Parameters
| Parameter | Type |
|---|---|
command | FightFallCmd |
Returns
void
Inherited from
fightGetUp()
ts
fightGetUp(command): void;A fighter up off the floor.
Parameters
| Parameter | Type |
|---|---|
command | FightGetUpCmd |
Returns
void
Inherited from
fightHit()
ts
fightHit(command): void;A blow on a fighter on the fight kit's door.
Parameters
| Parameter | Type |
|---|---|
command | FightHitCmd |
Returns
void
Inherited from
fightState()
ts
fightState(command): void;The fight kit's script door: what a fighter's body is doing this step.
Parameters
| Parameter | Type |
|---|---|
command | FightStateCmd |
Returns
void
Inherited from
hitCharacter()
ts
hitCharacter(
entity,
at,
direction,
strength
): void;A blow on a character's physics body.
Parameters
| Parameter | Type |
|---|---|
entity | number |
at | Vec3 |
direction | Vec3 |
strength | HitStrength |
Returns
void
Inherited from
interpolate()
ts
interpolate(alpha): void;Write the blend of the previous and current transforms onto the scene.
Parameters
| Parameter | Type | Description |
|---|---|---|
alpha | number | Interpolation factor in [0, 1), from the engine loop. |
Returns
void
Nothing.
loadAsset()
ts
loadAsset(asset, priority): void;Start loading an asset.
Parameters
| Parameter | Type |
|---|---|
asset | number |
priority | number |
Returns
void
Inherited from
localScope()?
ts
optional localScope(on): void;Optional: told when applyOutput starts (true) and ends (false) applying frame-output.local-commands. The server adapter uses it to keep what a local command does out of the replicated world record.
Parameters
| Parameter | Type |
|---|---|
on | boolean |
Returns
void
Inherited from
lookAt()
ts
lookAt(
entity,
target,
weight
): void;Aim a character's head and eyes.
Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Vec3 | undefined |
weight | number |
Returns
void
Inherited from
moveCharacter()
ts
moveCharacter(
body,
desiredVelocity,
jump,
crouch,
maxSlopeDeg
): void;Drive a character body for one step.
Parameters
| Parameter | Type |
|---|---|
body | number |
desiredVelocity | Vec3 |
jump | boolean |
crouch | boolean |
maxSlopeDeg | number |
Returns
void
Inherited from
pausePop()
ts
pausePop(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
Inherited from
pausePush()
ts
pausePush(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
Inherited from
playMusic()
ts
playMusic(command): void;Apply play-music.
Parameters
| Parameter | Type |
|---|---|
command | PlayMusicCmd |
Returns
void
Inherited from
playSound()
ts
playSound(
sound,
asset,
entity,
position,
volume,
pitch,
looping,
bus
): void;Start a sound.
Parameters
| Parameter | Type |
|---|---|
sound | number |
asset | number |
entity | number | undefined |
position | Vec3 | undefined |
volume | number |
pitch | number |
looping | boolean |
bus | AudioBus |
Returns
void
Inherited from
playSoundOnBeat()
ts
playSoundOnBeat(command): void;Apply play-sound-on-beat.
Parameters
| Parameter | Type |
|---|---|
command | PlaySoundOnBeatCmd |
Returns
void
Inherited from
playtest()
ts
playtest(command): void;A playtest mark. It changes nothing in the game: the page's playtest tap reads the marks off the frame itself, so an adapter ignores them. The command is pooled: read it, never keep it.
Parameters
| Parameter | Type |
|---|---|
command | PlaytestCmd |
Returns
void
Inherited from
recoverCharacter()
ts
recoverCharacter(entity): void;A character that is down blends back into its animation.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
EngineAdapter.recoverCharacter
removeBody()
ts
removeBody(body): void;Destroy a body.
Parameters
| Parameter | Type |
|---|---|
body | number |
Returns
void
Inherited from
removeJoint()
ts
removeJoint(joint): void;Destroy a joint.
Parameters
| Parameter | Type |
|---|---|
joint | number |
Returns
void
Inherited from
removeVehicle()
ts
removeVehicle(body): void;Release handling, leaving the chassis.
Parameters
| Parameter | Type |
|---|---|
body | number |
Returns
void
Inherited from
resetVehicle()
ts
resetVehicle(command): void;Teleport and reset handling history.
Parameters
| Parameter | Type |
|---|---|
command | ResetVehicleCmd |
Returns
void
Inherited from
saveGameData()
ts
saveGameData(data): void;Persist the room's game-wide document (JSON).
Parameters
| Parameter | Type |
|---|---|
data | string |
Returns
void
Inherited from
savePlayerData()
ts
savePlayerData(player, data): void;Persist one player's document (JSON).
Parameters
| Parameter | Type |
|---|---|
player | number |
data | string |
Returns
void
Inherited from
say()
ts
say(
entity,
text,
audio,
visemes
): void;Speak a line.
Parameters
| Parameter | Type |
|---|---|
entity | number |
text | string |
audio | number | undefined |
visemes | string | undefined |
Returns
void
Inherited from
send()
ts
send(
to,
name,
payload,
reliable
): void;Send a game message; to undefined is every player (or the authority, from a client).
Parameters
| Parameter | Type |
|---|---|
to | number | undefined |
name | string |
payload | string |
reliable | boolean |
Returns
void
Inherited from
setAnim()
ts
setAnim(
entity,
clip,
looping,
speed,
fadeMs,
weight
): void;Play or cross-fade an animation clip.
Parameters
| Parameter | Type |
|---|---|
entity | number |
clip | string |
looping | boolean |
speed | number |
fadeMs | number |
weight | number |
Returns
void
Inherited from
setAsset()
ts
setAsset(entity, asset): void;Attach or detach a renderable.
Parameters
| Parameter | Type |
|---|---|
entity | number |
asset | number | undefined |
Returns
void
Inherited from
setBodyEnabled()
ts
setBodyEnabled(body, enabled): void;Enable or disable a body in the broad phase.
Parameters
| Parameter | Type |
|---|---|
body | number |
enabled | boolean |
Returns
void
Inherited from
setBodyTransform()
ts
setBodyTransform(
body,
position,
rotation,
teleport
): void;Move a body directly.
Parameters
| Parameter | Type |
|---|---|
body | number |
position | Vec3 |
rotation | Quat |
teleport | boolean |
Returns
void
Inherited from
EngineAdapter.setBodyTransform
setBodyVelocity()
ts
setBodyVelocity(
body,
linear,
angular
): void;Overwrite a body's velocities; undefined leaves one untouched.
Parameters
| Parameter | Type |
|---|---|
body | number |
linear | Vec3 | undefined |
angular | Vec3 | undefined |
Returns
void
Inherited from
setBusFx()
ts
setBusFx(command): void;Apply set-bus-fx.
Parameters
| Parameter | Type |
|---|---|
command | SetBusFxCmd |
Returns
void
Inherited from
setCamera()
ts
setCamera(camera): void;Apply the camera the guest asked for.
Parameters
| Parameter | Type |
|---|---|
camera | CameraState |
Returns
void
Inherited from
setCharacterMotion()
ts
setCharacterMotion(command): void;How the movement system moves a character.
Parameters
| Parameter | Type |
|---|---|
command | SetCharacterMotionCmd |
Returns
void
Inherited from
EngineAdapter.setCharacterMotion
setCharacterState()
ts
setCharacterState(
entity,
state,
velocity,
grounded,
facing?
): void;Drive a character's locomotion state machine.
Parameters
| Parameter | Type |
|---|---|
entity | number |
state | string |
velocity | Vec3 |
grounded | boolean |
facing? | number |
Returns
void
Inherited from
EngineAdapter.setCharacterState
setClipWeights()
ts
setClipWeights(
entity,
clips,
weights,
timeScale
): void;Set explicit per-clip weights.
Parameters
| Parameter | Type |
|---|---|
entity | number |
clips | readonly string[] |
weights | ArrayLike<number> |
timeScale | number |
Returns
void
Inherited from
setExpression()
ts
setExpression(
entity,
space,
weights
): void;Set facial expression coefficients.
Parameters
| Parameter | Type |
|---|---|
entity | number |
space | ExpressionSpace |
weights | ArrayLike<number> |
Returns
void
Inherited from
setHud()
ts
setHud(json): void;Apply the HUD model, or leave the previous one when undefined.
Parameters
| Parameter | Type |
|---|---|
json | string | undefined |
Returns
void
Inherited from
setJointMotor()
ts
setJointMotor(args): void;Set a joint motor in radians/metres.
Parameters
| Parameter | Type |
|---|---|
args | SetJointMotorCmd |
Returns
void
Inherited from
setListener()
ts
setListener(
position,
rotation,
velocity
): void;Place the audio listener.
Parameters
| Parameter | Type |
|---|---|
position | Vec3 |
rotation | Quat |
velocity | Vec3 |
Returns
void
Inherited from
setMaterialParam()
ts
setMaterialParam(
entity,
name,
value
): void;Set one material uniform.
Parameters
| Parameter | Type |
|---|---|
entity | number |
name | string |
value | MaterialValue |
Returns
void
Inherited from
EngineAdapter.setMaterialParam
setMusicLayer()
ts
setMusicLayer(command): void;Apply set-music-layer.
Parameters
| Parameter | Type |
|---|---|
command | SetMusicLayerCmd |
Returns
void
Inherited from
setParent()
ts
setParent(
entity,
parent,
keepWorldTransform
): void;Reparent an entity.
Parameters
| Parameter | Type |
|---|---|
entity | number |
parent | number | undefined |
keepWorldTransform | boolean |
Returns
void
Inherited from
setPlayerCamera()
ts
setPlayerCamera(player, camera): void;The camera one player renders from.
Parameters
| Parameter | Type |
|---|---|
player | number |
camera | CameraState |
Returns
void
Inherited from
setPlayerEntity()
ts
setPlayerEntity(
player,
entity,
spawn?
): void;Which entity a player controls (0 for none). The authority keeps the mapping for relevancy and each player's "your entity"; a page ignores it.
Parameters
| Parameter | Type |
|---|---|
player | number |
entity | number |
spawn? | number |
Returns
void
Inherited from
setPlayerHud()
ts
setPlayerHud(player, hud): void;One player's HUD model as JSON.
Parameters
| Parameter | Type |
|---|---|
player | number |
hud | string |
Returns
void
Inherited from
setPointerLock()
ts
setPointerLock(locked): void;Request or release pointer lock.
Parameters
| Parameter | Type |
|---|---|
locked | boolean |
Returns
void
Inherited from
setPost()
ts
setPost(command): void;Apply partial post settings; payload is borrowed.
Parameters
| Parameter | Type |
|---|---|
command | PostCmd |
Returns
void
Inherited from
setSoundOcclusion()
ts
setSoundOcclusion(command): void;Apply set-sound-occlusion.
Parameters
| Parameter | Type |
|---|---|
command | SetSoundOcclusionCmd |
Returns
void
Inherited from
EngineAdapter.setSoundOcclusion
setSpotLight()?
ts
optional setSpotLight(command): void;Create or update an entity-owned spotlight; optional for headless adapters.
Parameters
| Parameter | Type |
|---|---|
command | SpotLightCmd |
Returns
void
Inherited from
setTimeScale()
ts
setTimeScale(scale): void;Scale simulated time.
Parameters
| Parameter | Type |
|---|---|
scale | number |
Returns
void
Inherited from
setTransformFromHost()
ts
setTransformFromHost(
entity,
flags,
position,
rotation,
scale
): void;Write one transform the host, not the guest, authored: a multiplayer client's replicated row from the authority.
Only the lanes flags names are written (TRANSFORM_FLAGS.POSITION, ROTATION, SCALE); the others keep their current values. TELEPORT snaps instead of interpolating, and VISIBLE shows an entity that was hidden at spawn. Unlike applyTransforms, a rotation written here is not guest intent, so it never outranks a later physics row. An unknown entity is ignored.
Parameters
| Parameter | Type | Description |
|---|---|---|
entity | number | The entity. |
flags | number | TRANSFORM_FLAGS bits; the multiplayer RowFlag bits are the same values. |
position | ArrayLike<number> | Position xyz, read when POSITION is set. |
rotation | ArrayLike<number> | Quaternion xyzw, read when ROTATION is set. |
scale | ArrayLike<number> | Scale xyz, read when SCALE is set. |
Returns
void
Nothing.
setUi()
ts
setUi(json): void;Apply the page UI model, or keep it when undefined.
Parameters
| Parameter | Type |
|---|---|
json | string | undefined |
Returns
void
Inherited from
setVehicleInput()
ts
setVehicleInput(command): void;Set one step of vehicle controls.
Parameters
| Parameter | Type |
|---|---|
command | SetVehicleInputCmd |
Returns
void
Inherited from
spawn()
ts
spawn(
entity,
asset,
position,
rotation,
scale,
flags
): void;Create an entity in the scene.
Parameters
| Parameter | Type |
|---|---|
entity | number |
asset | number | undefined |
position | Vec3 |
rotation | Quat |
scale | Vec3 |
flags | { name?: string; parent?: number; visible: boolean; } |
flags.name? | string |
flags.parent? | number |
flags.visible | boolean |
Returns
void
Inherited from
spawnCharacter()
ts
spawnCharacter(
entity,
bundle,
position,
rotation
): void;Instantiate a splat character bundle.
Parameters
| Parameter | Type |
|---|---|
entity | number |
bundle | number |
position | Vec3 |
rotation | Quat |
Returns
void
Inherited from
stopCharacterWalk()
ts
stopCharacterWalk(entity): void;Give up a walk to a spot.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
EngineAdapter.stopCharacterWalk
stopMusic()
ts
stopMusic(command): void;Apply stop-music.
Parameters
| Parameter | Type |
|---|---|
command | number |
Returns
void
Inherited from
stopSound()
ts
stopSound(sound, fadeMs): void;Stop a playing sound.
Parameters
| Parameter | Type |
|---|---|
sound | number |
fadeMs | number |
Returns
void
Inherited from
thing()
ts
thing(command): void;Something asked of a loose thing in a made world (the optional world bridge).
Parameters
| Parameter | Type |
|---|---|
command | ThingCmd |
Returns
void
Inherited from
update()
ts
update(dt, alpha): void;One rendered frame's worth of adapter work: interpolate, then the character bridge's animators and rigs.
The two are separate because interpolation is pure transform maths and characters are not: a rig runs a compute pass and wants wall-clock seconds, not an interpolation factor.
Parameters
| Parameter | Type | Description |
|---|---|---|
dt | number | Clamped wall-clock seconds since the previous frame. |
alpha | number | Interpolation factor in [0, 1), from the engine loop. |
Returns
void
Nothing.
walkCharacterTo()
ts
walkCharacterTo(
entity,
target,
facing,
pace,
quick,
stop?,
start?
): void;Walk a character to a spot. stop is the kind of stop this one walk ends with ('gradual', it slows and stands upright; 'hard', it brakes); left out: the character's own. start says how it is begun ('moving': the game says the body is under way already); left out: as the character's takes have the body.
Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Vec3 |
facing | number | undefined |
pace | number |
quick | boolean |
stop? | StopStyle |
start? | "moving" |
Returns
void
Inherited from
EngineAdapterOptions
Options accepted by createEngineAdapter; localPlayer and send are on the base.
Extends
PlayerCommandOptions
Properties
capacity?
ts
optional capacity?: number;Entity slots reserved up front. Defaults to 512.
characters?
ts
optional characters?: HostCharacters<Object3D<Object3DEventMap>>;Renders the spawn-character family for real.
Build one with createCharacterBridge from gameable/host/characters — the optional module, so a game with no characters never downloads the rig stack. Leave it out and the six character commands are recorded on EngineAdapterHandle.animationOf and warn once, which is what shipped before this existed.
conversation?
ts
optional conversation?: (command) => void;Optional structural interview command sink. No integration is loaded by default.
Forward structural controls to an optional conversation module.
Parameters
| Parameter | Type |
|---|---|
command | ConversationCmd |
Returns
void
cutscene?
ts
optional cutscene?: (command) => void;Optional cutscene sink: createCutsceneBridge(...).handle from gameable/host/cutscenes. Without it a cutscene command warns once and does nothing (a cutscene is an option a game asks for, never a default).
A cutscene: preload, play over the stage, or skip (the optional cutscene bridge).
Parameters
| Parameter | Type |
|---|---|
command | CutsceneCmd |
Returns
void
gameId?
ts
optional gameId?: string;Stable solo save identity; defaults to the play URL game parameter, then pathname.
Inherited from
ts
PlayerCommandOptions.gameIdhud?
ts
optional hud?: false | HudRenderer;HUD renderer. Defaults to createDomHud over document.body; pass your own to restyle it, or false to render no HUD at all and read adapter.hudModel yourself.
hudContainer?
ts
optional hudContainer?: HudElement;Container for the default HUD. Defaults to document.body.
localPlayer?
ts
optional localPlayer?: number | (() => number);The player this page shows. Defaults to 0, the single-player player. A room page's seat is not known until the room assigns it, so pass a function (e.g. () => net.localPlayer) to read it fresh each call instead of a number fixed at construction.
Inherited from
ts
PlayerCommandOptions.localPlayermaxBodies?
ts
optional maxBodies?: number;Body-id slots reserved for the body-to-entity table. Defaults to 4096.
The table is a Uint32Array indexed by body id, so EngineAdapterHandle.entityOfBody is an array read rather than a Map lookup — it runs once per contact and once per raycast hit. Guest body ids are minted in order and never reused, so a long session walks past any fixed ceiling; the table doubles when it has to and warns once, naming this option.
modules?
ts
optional modules?: readonly EngineModule[];The module instances handed to createEngine.
Services are normally reached through engine.get(id), but the audio decoder is only on the module object: decodeAsset, which turns a play-sound asset handle into an AudioBuffer, and the optional decodedAsset, which answers synchronously for a buffer that is already decoded and so lets a sound start on the frame it was asked for. Pass the same array you passed to createEngine and both are found automatically.
placeholders?
ts
optional placeholders?: "bodies" | "always" | "never";When to draw a placeholder mesh in place of a real asset.
bodies(the default) — an entity with no renderable gets a mesh the shape and size of its physics body, and a spawn whose asset is unknown or not yet resident gets a unit box until the bytes arrive.always— additionally, an entity with neither an asset nor a body gets a unit box. The right choice for a sketch, where nothing has an asset yet and an empty scene is indistinguishable from a broken one.never— draw only what the manifest provides. The right choice once the game has real content, because then a missing mesh is a bug and should look like one.
send?
ts
optional send?: (to, name, payload, reliable) => void;Where the guest's send commands go: the client transport. Without one they are dropped. Called during applyOutput; copy what you keep.
Parameters
| Parameter | Type | Description |
|---|---|---|
to | number | undefined | The addressee, or undefined for the authority / everyone. |
name | string | Message name. |
payload | string | JSON payload. |
reliable | boolean | Whether it must arrive. |
Returns
void
Inherited from
ts
PlayerCommandOptions.sendsoloSaves?
ts
optional soloSaves?: boolean;Disable page persistence when a room owns documents.
Inherited from
ts
PlayerCommandOptions.soloSavesthing?
ts
optional thing?: (command) => void;Optional sink for a made world's things: createWorldBridge(...).handle from gameable/world. Without it a thing command warns once and does nothing.
Something asked of a loose thing in a made world (the optional world bridge).
Parameters
| Parameter | Type |
|---|---|
command | ThingCmd |
Returns
void
ui?
ts
optional ui?: false | UiRenderer;Page UI renderer; false disables it. Defaults to createDomUi above the HUD when there is a document.
uiContainer?
ts
optional uiContainer?: UiElement;Container for the default UI. Defaults to the HUD container.
vfx?
ts
optional vfx?: VfxSink;Optional vfx feature sink; copies any pooled payloads it retains.
warn?
ts
optional warn?: (message) => void;Where warnings go. Defaults to console.warn, once per distinct message.
Parameters
| Parameter | Type | Description |
|---|---|---|
message | string | What went wrong. |
Returns
void
GameSlot
A registered place in the module order, filled in once the engine exists.
Properties
module
ts
readonly module: EngineModule;Register this with createEngine({ modules }).
Methods
attach()
ts
attach(loop, ctx): Promise<void>;Bind the real loop and initialise it.
Parameters
| Parameter | Type | Description |
|---|---|---|
loop | EngineModule | The module from createHostLoop. |
ctx | HostContext | The engine context, normally engine.ctx. |
Returns
Promise<void>
Resolves once the loop's own init has run.
GuestLoopOptions
Options every loop takes.
Example
ts
const options: GuestLoopOptions = { maxBodies: 2048, order: -50 };Properties
maxBodies?
ts
optional maxBodies?: number;Body rows the input encoder reserves before it grows. Defaults to 1024.
order?
ts
optional order?: number;Module order. Defaults to -50: after input, before physics.
GuestNamespace
The game namespace the component exports.
Methods
init()
ts
init(config): void;Parameters
| Parameter | Type |
|---|---|
config | HostGameConfig |
Returns
void
restore()
ts
restore(state): void;Parameters
| Parameter | Type |
|---|---|
state | Uint8Array |
Returns
void
shutdown()
ts
shutdown(): void;Returns
void
snapshot()
ts
snapshot(): Uint8Array;Returns
Uint8Array
tick()
ts
tick(input): FrameOutput;Parameters
| Parameter | Type |
|---|---|
input | HostFrameInput |
Returns
Head
One action head: a name and how many classes it chooses between.
Properties
classes
ts
readonly classes: number;How many classes.
name
ts
readonly name: string;The head's name.
HostBindings
The gameable:engine half of a jco import object.
Properties
gameable:engine/assets
ts
gameable:engine/assets: object;describe
ts
describe: (id) => AssetDesc | undefined;Parameters
| Parameter | Type |
|---|---|
id | number |
Returns
AssetDesc | undefined
resolveId
ts
resolveId: (name) => number | undefined;Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
number | undefined
gameable:engine/env
ts
gameable:engine/env: object;log
ts
log: (level, msg) => void;Parameters
| Parameter | Type |
|---|---|
level | string |
msg | string |
Returns
void
nowMs
ts
nowMs: () => number;Returns
number
seed
ts
seed: () => bigint;Returns
bigint
gameable:engine/physics-query
ts
gameable:engine/physics-query: object;jointValue
ts
jointValue: (joint, axis) => number | undefined;Parameters
| Parameter | Type |
|---|---|
joint | number |
axis | number |
Returns
number | undefined
overlapShape
ts
overlapShape: (shape, position, rotation, filter, maxResults) => OverlapHit[];Parameters
| Parameter | Type |
|---|---|
shape | QueryShape |
position | Vec3 |
rotation | Quat |
filter | QueryFilter |
maxResults | number |
Returns
overlapSphere
ts
overlapSphere: (center, radius, filter, maxResults) => OverlapHit[];Parameters
| Parameter | Type |
|---|---|
center | Vec3 |
radius | number |
filter | QueryFilter |
maxResults | number |
Returns
raycast
ts
raycast: (origin, direction, maxDistance, filter) => RayHit | undefined;Parameters
| Parameter | Type |
|---|---|
origin | Vec3 |
direction | Vec3 |
maxDistance | number |
filter | QueryFilter |
Returns
RayHit | undefined
raycastBatch
ts
raycastBatch: (rays) => (RayHit | undefined)[];Parameters
| Parameter | Type |
|---|---|
rays | RayQuery[] |
Returns
(RayHit | undefined)[]
shapeCast
ts
shapeCast: (shape, position, rotation, direction, maxDistance, filter) => RayHit | undefined;Parameters
| Parameter | Type |
|---|---|
shape | QueryShape |
position | Vec3 |
rotation | Quat |
direction | Vec3 |
maxDistance | number |
filter | QueryFilter |
Returns
RayHit | undefined
HostCharacters
The character operations used by a generic frame adapter, without a rendering runtime.
Example
ts
import type { HostCharacters } from 'gameable/host';
function clear(provider: HostCharacters): void { provider.dispose(); }
console.log(typeof clear);Type Parameters
| Type Parameter | Default type |
|---|---|
Parent | unknown |
Properties
clipEnds
ts
readonly clipEnds: CharacterClipEnd[];Methods
cancelAction()?
ts
optional cancelAction(entity): boolean;Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
boolean
carriedVelocity()?
ts
optional carriedVelocity(entity, out): boolean;Parameters
| Parameter | Type |
|---|---|
entity | number |
out | [number, number] |
Returns
boolean
despawn()
ts
despawn(entity): void;Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
dispose()
ts
dispose(): void;Returns
void
doAction()?
ts
optional doAction(
entity,
name,
target?,
options?
):
| Readonly<{
ok: boolean;
reason: string;
}>
| null;Parameters
| Parameter | Type |
|---|---|
entity | number |
name | string |
target? | | Readonly<{ depth: number; height: number; id: number; width: number; x: number; y: number; yaw: number; z: number; }> | null |
options? | { plain?: boolean; } |
options.plain? | boolean |
Returns
| Readonly<{ ok: boolean; reason: string; }> | null
entryOf()
ts
entryOf(entity):
| {
ragdoll: unknown;
}
| null;Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
| { ragdoll: unknown; } | null
faceTo()?
ts
optional faceTo(
entity,
facing,
quick?
): boolean;Parameters
| Parameter | Type |
|---|---|
entity | number |
facing | number |
quick? | boolean |
Returns
boolean
fightCamera()?
ts
optional fightCamera(
shot,
dt,
aspect,
out
): boolean;The fight camera, one step: the shot asked, the step's seconds, the picture's aspect; the eye in out.
Parameters
| Parameter | Type |
|---|---|
shot | HostFightShot |
dt | number |
aspect | number |
out | HostFightCameraOut |
Returns
boolean
fightContact()?
ts
optional fightContact(
attacker,
target,
out
): boolean;Whether one fighter's strike meets the other's body this step; the part struck, the point and the nearer leg in out.
Parameters
| Parameter | Type |
|---|---|
attacker | number |
target | number |
out | HostFightContact |
Returns
boolean
fightFall()?
ts
optional fightFall(
entity,
velocity,
spin,
turn,
kick
): boolean;A fighter thrown into the rag-doll; kick: a blow blended into a body already thrown.
Parameters
| Parameter | Type |
|---|---|
entity | number |
velocity | Vec3 |
spin | number |
turn | number |
kick | boolean |
Returns
boolean
fightGetUp()?
ts
optional fightGetUp(entity, quick):
| {
clip: string;
facing: number;
frames: number;
}
| null;A fighter up off the floor; null when it is not down.
Parameters
| Parameter | Type |
|---|---|
entity | number |
quick | boolean |
Returns
| { clip: string; facing: number; frames: number; } | null
fightHit()?
ts
optional fightHit(entity, hit): boolean;A blow on a fighter: the push, the stagger, the reaction take.
Parameters
| Parameter | Type |
|---|---|
entity | number |
hit | HostFightHit |
Returns
boolean
fightOf()?
ts
optional fightOf(entity): HostFightState | null;What the fight camera reads of a fighter.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
HostFightState | null
fightSet()?
ts
optional fightSet():
| {
json: string;
name: string;
}
| null;The fight set once read: the pack's name and its fight block as the pack carries it (JSON text); null before.
Returns
| { json: string; name: string; } | null
hit()
ts
hit(entity, request): string | null;Parameters
| Parameter | Type |
|---|---|
entity | number |
request | { at: readonly [number, number, number]; direction?: readonly [number, number, number]; strength?: number | "small" | "big" | "shot" | "big-shot"; } |
request.at | readonly [number, number, number] |
request.direction? | readonly [number, number, number] |
request.strength? | number | "small" | "big" | "shot" | "big-shot" |
Returns
string | null
lookAt()
ts
lookAt(
entity,
target,
weight
): void;Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Vec3 | undefined |
weight | number |
Returns
void
motionFailed()?
ts
optional motionFailed(
entity,
name,
reason
): void;Parameters
| Parameter | Type |
|---|---|
entity | number |
name | string |
reason | string |
Returns
void
motionRefusal()?
ts
optional motionRefusal(entity): string | null;Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
string | null
recover()
ts
recover(entity): void;Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
say()
ts
say(
entity,
text,
audio?,
visemes?
): void;Parameters
| Parameter | Type |
|---|---|
entity | number |
text | string |
audio? | number |
visemes? | string |
Returns
void
setClipWeights()
ts
setClipWeights(
entity,
clips,
weights,
timeScale
): void;Parameters
| Parameter | Type |
|---|---|
entity | number |
clips | readonly string[] |
weights | ArrayLike<number> |
timeScale | number |
Returns
void
setExpression()
ts
setExpression(
entity,
space,
weights
): void;Parameters
| Parameter | Type |
|---|---|
entity | number |
space | ExpressionSpace |
weights | ArrayLike<number> |
Returns
void
setFight()?
ts
optional setFight(entity, request): boolean;The fight kit's script door: what a fighter's body is doing this step; null ends it. False until the set and the rig are in.
Parameters
| Parameter | Type |
|---|---|
entity | number |
request | HostFightRequest | null |
Returns
boolean
setMaterialParam()?
ts
optional setMaterialParam(
entity,
name,
value
): boolean;Parameters
| Parameter | Type |
|---|---|
entity | number |
name | string |
value | MaterialValue |
Returns
boolean
setMotion()?
ts
optional setMotion(entity, how): boolean;Parameters
| Parameter | Type |
|---|---|
entity | number |
how | Readonly<CharacterMotionRequest> |
Returns
boolean
setState()
ts
setState(
entity,
state,
velocity,
grounded,
facing?
): void;Parameters
| Parameter | Type |
|---|---|
entity | number |
state | string |
velocity | Vec3 |
grounded | boolean |
facing? | number |
Returns
void
spawn()
ts
spawn(request): void;Parameters
| Parameter | Type |
|---|---|
request | HostCharacterSpawn<Parent> |
Returns
void
stepWalks()?
ts
optional stepWalks(dt, moved): void;Parameters
| Parameter | Type |
|---|---|
dt | number |
moved | (entity, x, z, yaw) => void |
Returns
void
stopWalk()?
ts
optional stopWalk(entity): boolean;Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
boolean
update()
ts
update(dt, alpha?): void;Parameters
| Parameter | Type |
|---|---|
dt | number |
alpha? | number |
Returns
void
walkTo()?
ts
optional walkTo(
entity,
target,
facing,
pace,
quick?,
stop?,
start?
): boolean;Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Readonly<Vec3> |
facing | number | undefined |
pace | number |
quick? | boolean |
stop? | StopStyle |
start? | "moving" |
Returns
boolean
HostCharacterSpawn
Spawn data; the host chooses the type of scene parent.
Example
ts
import type { HostCharacterSpawn } from 'gameable/host';
const spawn: HostCharacterSpawn = { entity: 1, bundle: 1, position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 } };
console.log(spawn.entity);Type Parameters
| Type Parameter | Default type |
|---|---|
Parent | unknown |
Properties
bundle
ts
bundle: number;entity
ts
entity: number;groundOffset?
ts
optional groundOffset?: number;onAttached?
ts
optional onAttached?: () => void;Returns
void
ownsBody?
ts
optional ownsBody?: (body) => boolean;Whether a query body belongs to this entity; read live as bodies change.
Parameters
| Parameter | Type |
|---|---|
body | number |
Returns
boolean
parent?
ts
optional parent?: Parent;position
ts
position: Vec3;rotation
ts
rotation: Quat;HostFightBase
The take under a fighter's state, as the bridge takes it (the fight kit's script door).
Properties
fade?
ts
optional fade?: number;frames?
ts
optional frames?: number;from?
ts
optional from?: number;hold?
ts
optional hold?: number;loop?
ts
optional loop?: boolean;name
ts
name: string;rate?
ts
optional rate?: number;to?
ts
optional to?: number;upper?
ts
optional upper?: string;HostFightCameraOut
Where the fight camera put the eye: its place, its turn (x, y, z, w) and its field of view (degrees).
Properties
fov
ts
fov: number;position
ts
position: [number, number, number];rotation
ts
rotation: [number, number, number, number];HostFightContact
Where one fighter's strike met the other's body, as the bridge says it.
Properties
leg
ts
leg: number;+1 the struck body's left leg is the nearer to the striker, -1 its right
x
ts
x: number;the point, world
y
ts
y: number;z
ts
z: number;zone
ts
zone: number;the part struck: 0 the head, 1 the body, 2 the legs
HostFightHit
A blow on a fighter, as the bridge takes it.
Properties
blocked
ts
blocked: boolean;taken on the guard: the block's push and the legs' give, nothing else
dir
ts
dir: number;the way the blow came along the floor (+1 / -1: the striker's facing) and the striker's line's turn
k
ts
k: number;leg
ts
leg: number;reaction
ts
reaction:
| {
amount: number;
clip: string;
frames: number;
}
| null;rising
ts
rising: boolean;side
ts
side: number;stagger
ts
stagger:
| {
side: number;
up: number;
}
| null;throws
ts
throws: boolean;the blow throws the body (a fall follows): the push on the joints only
turn
ts
turn: number;zone
ts
zone: number;HostFightRequest
What a fighter's body is doing this step, as the bridge takes it.
Properties
anchor
ts
anchor: number;the base take's root held (1 where it started, 2 in place); a turn laid on the pose, radians
arc
ts
arc: number;a jump with no strike in it: its arc (0 to 1; below 0 none), its way, a somersault
base
ts
base: HostFightBase | null;blend
ts
blend: number;frames to blend from the pose as it was, on the step the state changes (0 none; -1 the driver's own)
bounce
ts
bounce: number;bulk
ts
bulk: number;how thick the body is to a blow, 1 as built
crouch
ts
crouch: boolean;facing
ts
facing: number;fists
ts
fists: string;the take whose hands make the fists in the guard (the fighter's idle); '' for the base's own hands
flip
ts
flip: boolean;frozen
ts
frozen: boolean;grounded
ts
grounded: boolean;guard
ts
guard: number;guardUp
ts
guardUp: boolean;held
ts
held: boolean;the impact freeze held at the start of the step (the physics and the reaction stand still)
jumpDir
ts
jumpDir: number;look
ts
look:
| {
x: number;
y: number;
z: number;
}
| null;lookWeight
ts
lookWeight: number;mirrored
ts
mirrored: boolean;pitch
ts
pitch: number;posture
ts
posture: boolean;reach
ts
reach: number;the fighter's real reach, metres (0: the figure's own)
recoil
ts
recoil: number;reset
ts
reset: boolean;a round starts again: the blows' push, the stagger, the springs and the rag-doll cleared
squash
ts
squash: number;nudges on the springs this step, the legs' give cleared, the striker's recoil
squashReset
ts
squashReset: boolean;stance
ts
stance: "crouch" | "stand";strike
ts
strike: HostFightStrike | null;target
ts
target: number;the other fighter (an entity; 0 none): the strike is aimed at its body and met against it
turning
ts
turning: number;turnTo
ts
turnTo: number;x
ts
x: number;where the fighter stands (world: along, up, across) and the yaw its object is turned by
y
ts
y: number;yaw
ts
yaw: number;z
ts
z: number;HostFightShot
The fight camera's request.
Properties
a
ts
a: number;b
ts
b: number;closeUp
ts
closeUp: number;half
ts
half: number;hero
ts
hero: number;on
ts
on: boolean;openFloor
ts
openFloor: boolean;ropeLine
ts
ropeLine: number;shake
ts
shake: number;sides
ts
sides: number;wideFor
ts
wideFor: number;HostFightState
What the fight camera and the game read of a fighter.
Properties
airborne
ts
readonly airborne: boolean;thrown and still in the air; lying face up
depth
ts
readonly depth: number;down
ts
readonly down: boolean;faceUp
ts
readonly faceUp: boolean;facing
ts
readonly facing: number;headY
ts
readonly headY: number;lift
ts
readonly lift: number;pose
ts
readonly pose: object;the pose this step (a recording's, a test's): every joint's turn in its parent, and the hips' place
hips
ts
readonly hips: object;hips.x
ts
readonly x: number;hips.y
ts
readonly y: number;hips.z
ts
readonly z: number;local
ts
readonly local: readonly object[];ragdolled
ts
readonly ragdolled: boolean;rising
ts
readonly rising: boolean;scale
ts
readonly scale: number;x
ts
readonly x: number;y
ts
readonly y: number;HostFightStrike
A strike under way, as the bridge takes it.
Properties
aim
ts
aim:
| {
x: number;
y: number;
z: number;
}
| null;aimWeight
ts
aimWeight: number;extra
ts
extra: number;frame
ts
frame: number;id
ts
id: string;speed
ts
speed: number;HostLoopOptions
Options accepted by createHostLoop.
Properties
devMode?
ts
optional devMode?: boolean;Value of game-config.dev-mode. Defaults to true.
editor?
ts
optional editor?: false | Editor;The page's editor: the game paused, its actors listed, picked and moved with a gizmo, for a person laying a level out by hand. One is made and published as window.__gameable.editor by default; pass your own, or false for none.
guestWorker?
ts
optional guestWorker?: boolean;Opt in to a supervised guest and Jolt worker. Defaults to false.
init?
ts
optional init?: boolean;Call sandbox.init during module init. Defaults to true.
maxBodies?
ts
optional maxBodies?: number;Body rows the input encoder reserves. Defaults to 1024.
onDead?
ts
optional onDead?: (error) => void;Shown when the guest dies. Defaults to a red overlay on document.body.
Parameters
| Parameter | Type | Description |
|---|---|---|
error | Error | null | Why the sandbox died. |
Returns
void
options?
ts
optional options?: string;Extra options string handed to game.init.
order?
ts
optional order?: number;Module order. Defaults to -50: after input, before physics.
That is what removes a fixed step of input latency — see createHostLoop. Moving it after physics puts the latency back.
playtest?
ts
optional playtest?: false | PlaytestController;The page's playtest: it records a person playing, lets an agent play, and notices where players die and get stuck. One is made and published as window.__gameable.playtest by default; pass your own to configure it, or false for none.
seed?
ts
optional seed?: number | bigint;Deterministic run seed handed to game.init. Defaults to 0x5eed1234.
Fix it and a run replays; vary it and each run differs.
workerPhysics?
ts
optional workerPhysics?: PhysicsOptions;Physics settings for the worker; use the same settings as the page.
Hotspot
One place where something kept happening.
Properties
count
ts
count: number;How many times.
notes
ts
notes: string[];The causes or notes seen there, most common first.
x
ts
x: number;Where, the middle of the cell's events.
y
ts
y: number;Where.
z
ts
z: number;Where.
HudDocument
The slice of Document the renderer uses.
Methods
createElement()
ts
createElement(tag): HudElement;Create an element.
Parameters
| Parameter | Type | Description |
|---|---|---|
tag | string | Tag name, always 'div' here. |
Returns
The new element.
HudElement
The slice of HTMLElement the renderer uses.
Properties
className
ts
className: string;Class name, set once per element at creation.
style
ts
readonly style: object;Inline style, written through setProperty so a fake needs one method.
setProperty()
ts
setProperty(name, value): void;Parameters
| Parameter | Type |
|---|---|
name | string |
value | string |
Returns
void
textContent
ts
textContent: string | null;Text content; the renderer only ever writes it.
Methods
append()
ts
append(...nodes): void;Append children.
The parameter is unknown rather than HudElement on purpose: the real HTMLElement.append takes (string | Node)[], and only a parameter type that a Node is assignable to makes a real element satisfy this interface under method bivariance.
Parameters
| Parameter | Type | Description |
|---|---|---|
...nodes | unknown[] | Children to append; always HudElements here. |
Returns
void
remove()
ts
remove(): void;Detach from the parent, if any.
Returns
void
HudModel
The HUD model the default renderer understands.
Properties
bars?
ts
optional bars?: Record<string, {
max: number;
value: number;
}>;Label to { value, max } meters, drawn bottom-left in declaration order.
crosshair?
ts
optional crosshair?: boolean;Draw the centre crosshair.
message?
ts
optional message?: string;A single centred line, for "You win" and friends. Empty or absent hides it.
text?
ts
optional text?: Record<string, string | number>;Label to value rows, drawn top-left in declaration order.
HudRenderer
What createDomHud returns, and what the adapter drives.
Properties
element
ts
readonly element: HudElement;The overlay root, for tests and for callers that want to restyle it.
model
ts
readonly model: HudModel | null;The model currently on screen, or null before the first payload.
Methods
clear()
ts
clear(): void;Hide everything and forget the model.
Returns
void
dispose()
ts
dispose(): void;Detach the overlay from its container.
Returns
void
set()
ts
set(json): boolean;Apply one frame-output.hud value.
Parameters
| Parameter | Type | Description |
|---|---|---|
json | string | undefined | The JSON the guest sent, or undefined when nothing changed. |
Returns
boolean
True when the DOM was touched.
InputEncoder
A reusable frame-input builder.
Methods
encode()
ts
encode(args): HostFrameInput;Build the next frame input. The returned object is reused.
Parameters
| Parameter | Type |
|---|---|
args | EncodeArgs |
Returns
InputSnapshot
The shape the engine's input module hands over each frame.
Properties
control?
ts
optional control?: object;moveX
ts
moveX: number;moveY
ts
moveY: number;pitch
ts
pitch: number;spawn
ts
spawn: number;yaw
ts
yaw: number;down
ts
down: Uint32Array;Keys held, KEY_WORDS words. Aliased into the frame input, not copied: the array must stay alive and must not be recycled mid-tick.
focused
ts
focused: boolean;gamepads?
ts
optional gamepads?: readonly GamepadState[];mods
ts
mods: InputMods;mouse
ts
mouse: MouseState;pressed
ts
pressed: Uint32Array;Keys that went down this step, aliased like InputSnapshot.down.
released
ts
released: Uint32Array;Keys that came up this step, aliased like InputSnapshot.down.
LoadOrder
The loading order.
Properties
fetch
ts
readonly fetch: (input, init?) => Promise<Response>;The fetch to load a package through: it waits its turn and counts its bytes.
Parameters
| Parameter | Type |
|---|---|
input | URL | RequestInfo |
init? | RequestInit |
Returns
Promise<Response>
progress
ts
readonly progress: LoadProgress;Everything's progress, the same object every time.
Methods
begin()
ts
begin(
entity,
id,
descriptorUrl,
copy?
): LoadTicket;A character's load begins: its files, under directory, take their turn by the order.
Parameters
| Parameter | Type | Description |
|---|---|---|
entity | number | The character's entity. |
id | string | Its manifest id. |
descriptorUrl | string | Its character.json, whose folder holds its files. |
copy? | "full" | "light" | Which copy this is. |
Returns
The ticket; ready() or failed() when the load ends.
dispose()
ts
dispose(): void;Release every waiter (a shutdown).
Returns
void
onProgress()
ts
onProgress(listener): () => void;Hear every step.
Parameters
| Parameter | Type | Description |
|---|---|---|
listener | (progress) => void | What to tell. |
Returns
A function that stops telling it.
() => void
placeTurn()
ts
placeTurn(): Promise<void>;The place's turn: resolves once the first character stands (or has failed), at once when the option says 'first' or nothing is loading.
Returns
Promise<void>
Resolves when the place may load.
setOrder()
ts
setOrder(ids): void;The game's order, first first. May be given before or after the spawns; a request already waiting is re-sorted.
Parameters
| Parameter | Type | Description |
|---|---|---|
ids | readonly string[] | Manifest ids. |
Returns
void
LoadOrderOptions
Options for createLoadOrder.
Properties
cache?
ts
optional cache?: boolean;Whether the files go through the page's asset cache (core's pageAssetCache) over that fetch, so a reload takes a package's files from the browser instead of the line. Default true; the page turns the cache off for everything with globalThis.__gameableAssetCache = false.
fetch?
ts
optional fetch?: (input, init?) => Promise<Response>;The fetch the requests go out through; the global one by default.
Parameters
| Parameter | Type |
|---|---|
input | URL | RequestInfo |
init? | RequestInit |
Returns
Promise<Response>
now?
ts
optional now?: () => number;The clock, performance.now() by default.
Returns
number
onProgress?
ts
optional onProgress?: (progress) => void;Told on every step; progress holds the same.
Parameters
| Parameter | Type |
|---|---|
progress | LoadProgress |
Returns
void
order?
ts
optional order?: readonly string[];The characters' order by manifest id, the first first. A character not named comes after the named ones, in the order it was spawned.
place?
ts
optional place?: "first" | "after-first";When the place may load: after the first character stands (the default), at once ('first'), or never held ('any', the same as 'first').
reportEveryMs?
ts
optional reportEveryMs?: number;Milliseconds between two progress reports while bytes stream. Default 100.
LoadProgress
How far everything has come.
Properties
characters
ts
readonly characters: readonly CharacterLoadProgress[];Each character's own count, in the order they load.
files
ts
readonly files: number;filesDone
ts
readonly filesDone: number;Files finished and files in all.
loaded
ts
readonly loaded: number;Bytes that have come, over every character.
total
ts
readonly total: number;Bytes in all, over every character whose descriptor has been read.
LoadTicket
One character's place in the order, as the bridge holds it while the character loads.
Properties
progress
ts
readonly progress: CharacterLoadProgress;The character's own progress.
Methods
failed()
ts
failed(): void;The load ended without the character (failed, or despawned).
Returns
void
ready()
ts
ready(): void;The character stood: its files are done as far as the order is concerned.
Returns
void
still()
ts
still(): void;The character's points are drawn still: on screen, its other parts still coming.
Returns
void
LoopAdapter
What a loop needs of its adapter beyond the EngineAdapter commands.
Example
ts
const adapter: LoopAdapter = createServerAdapter(engine.modules.get('physics'));Extends
Properties
appliesLocal
ts
readonly appliesLocal: boolean;True when frame-output.local-commands are applied here, after commands: the page's own adapter and the authority's server adapter. A replica's adapter says false; the replicator never forwards them.
Inherited from
events
ts
readonly events: GameEvent[];The host event queue; drained into each tick's frame-input.events.
Methods
addBody()
ts
addBody(args): void;Create a rigid body or character controller.
Parameters
| Parameter | Type |
|---|---|
args | AddBodyCmd |
Returns
void
Inherited from
addJoint()
ts
addJoint(args): void;Create a joint; invalid body references are dropped.
Parameters
| Parameter | Type |
|---|---|
args | AddJointCmd |
Returns
void
Inherited from
addVehicle()
ts
addVehicle(command): void;Attach arcade handling to a dynamic body.
Parameters
| Parameter | Type |
|---|---|
command | AddVehicleCmd |
Returns
void
Inherited from
applyBodyRows()
ts
applyBodyRows(rows, count): void;Write the post-step body rows onto the entities they drive.
Parameters
| Parameter | Type |
|---|---|
rows | Float32Array |
count | number |
Returns
void
applyImpulse()
ts
applyImpulse(
body,
impulse,
atPoint
): void;Apply a one-shot impulse.
Parameters
| Parameter | Type |
|---|---|
body | number |
impulse | Vec3 |
atPoint | Vec3 | undefined |
Returns
void
Inherited from
applyTransforms()
ts
applyTransforms(transforms, count): void;Apply packed entity transforms.
Parameters
| Parameter | Type | Description |
|---|---|---|
transforms | Float32Array | Stride 12: entity, flags, position, rotation, scale. |
count | number | Number of rows. The buffer may be longer. |
Returns
void
Inherited from
cancelCharacterAction()
ts
cancelCharacterAction(entity): void;Take an action's request back.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
EngineAdapter.cancelCharacterAction
conversation()
ts
conversation(command): void;Forward structural controls to an optional conversation module.
Parameters
| Parameter | Type |
|---|---|
command | ConversationCmd |
Returns
void
Inherited from
cutscene()
ts
cutscene(command): void;A cutscene: preload, play over the stage, or skip (the optional cutscene bridge).
Parameters
| Parameter | Type |
|---|---|
command | CutsceneCmd |
Returns
void
Inherited from
despawn()
ts
despawn(entity): void;Destroy an entity and everything attached to it.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
dispose()
ts
dispose(): void;Release the adapter.
Returns
void
doCharacterAction()
ts
doCharacterAction(command): void;Ask a character to do an action of its motion set.
Parameters
| Parameter | Type |
|---|---|
command | DoCharacterActionCmd |
Returns
void
Inherited from
EngineAdapter.doCharacterAction
effect()
ts
effect(command): void;Apply a particle command; payload is borrowed.
Parameters
| Parameter | Type |
|---|---|
command | EffectCmd |
Returns
void
Inherited from
exchange()
ts
exchange(command): void;Trade between two players' documents. The command is pooled: read it, never keep it.
Parameters
| Parameter | Type |
|---|---|
command | ExchangeCmd |
Returns
void
Inherited from
faceCharacter()
ts
faceCharacter(
entity,
facing,
quick
): void;Turn a character on the spot to face a way.
Parameters
| Parameter | Type |
|---|---|
entity | number |
facing | number |
quick | boolean |
Returns
void
Inherited from
fightCamera()
ts
fightCamera(command): void;The fight camera, run on the host.
Parameters
| Parameter | Type |
|---|---|
command | FightCameraCmd |
Returns
void
Inherited from
fightFall()
ts
fightFall(command): void;A fighter thrown into the fight kit's rag-doll.
Parameters
| Parameter | Type |
|---|---|
command | FightFallCmd |
Returns
void
Inherited from
fightGetUp()
ts
fightGetUp(command): void;A fighter up off the floor.
Parameters
| Parameter | Type |
|---|---|
command | FightGetUpCmd |
Returns
void
Inherited from
fightHit()
ts
fightHit(command): void;A blow on a fighter on the fight kit's door.
Parameters
| Parameter | Type |
|---|---|
command | FightHitCmd |
Returns
void
Inherited from
fightState()
ts
fightState(command): void;The fight kit's script door: what a fighter's body is doing this step.
Parameters
| Parameter | Type |
|---|---|
command | FightStateCmd |
Returns
void
Inherited from
hitCharacter()
ts
hitCharacter(
entity,
at,
direction,
strength
): void;A blow on a character's physics body.
Parameters
| Parameter | Type |
|---|---|
entity | number |
at | Vec3 |
direction | Vec3 |
strength | HitStrength |
Returns
void
Inherited from
loadAsset()
ts
loadAsset(asset, priority): void;Start loading an asset.
Parameters
| Parameter | Type |
|---|---|
asset | number |
priority | number |
Returns
void
Inherited from
localScope()?
ts
optional localScope(on): void;Optional: told when applyOutput starts (true) and ends (false) applying frame-output.local-commands. The server adapter uses it to keep what a local command does out of the replicated world record.
Parameters
| Parameter | Type |
|---|---|
on | boolean |
Returns
void
Inherited from
lookAt()
ts
lookAt(
entity,
target,
weight
): void;Aim a character's head and eyes.
Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Vec3 | undefined |
weight | number |
Returns
void
Inherited from
moveCharacter()
ts
moveCharacter(
body,
desiredVelocity,
jump,
crouch,
maxSlopeDeg
): void;Drive a character body for one step.
Parameters
| Parameter | Type |
|---|---|
body | number |
desiredVelocity | Vec3 |
jump | boolean |
crouch | boolean |
maxSlopeDeg | number |
Returns
void
Inherited from
pausePop()
ts
pausePop(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
Inherited from
pausePush()
ts
pausePush(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
Inherited from
playMusic()
ts
playMusic(command): void;Apply play-music.
Parameters
| Parameter | Type |
|---|---|
command | PlayMusicCmd |
Returns
void
Inherited from
playSound()
ts
playSound(
sound,
asset,
entity,
position,
volume,
pitch,
looping,
bus
): void;Start a sound.
Parameters
| Parameter | Type |
|---|---|
sound | number |
asset | number |
entity | number | undefined |
position | Vec3 | undefined |
volume | number |
pitch | number |
looping | boolean |
bus | AudioBus |
Returns
void
Inherited from
playSoundOnBeat()
ts
playSoundOnBeat(command): void;Apply play-sound-on-beat.
Parameters
| Parameter | Type |
|---|---|
command | PlaySoundOnBeatCmd |
Returns
void
Inherited from
playtest()
ts
playtest(command): void;A playtest mark. It changes nothing in the game: the page's playtest tap reads the marks off the frame itself, so an adapter ignores them. The command is pooled: read it, never keep it.
Parameters
| Parameter | Type |
|---|---|
command | PlaytestCmd |
Returns
void
Inherited from
recoverCharacter()
ts
recoverCharacter(entity): void;A character that is down blends back into its animation.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
EngineAdapter.recoverCharacter
removeBody()
ts
removeBody(body): void;Destroy a body.
Parameters
| Parameter | Type |
|---|---|
body | number |
Returns
void
Inherited from
removeJoint()
ts
removeJoint(joint): void;Destroy a joint.
Parameters
| Parameter | Type |
|---|---|
joint | number |
Returns
void
Inherited from
removeVehicle()
ts
removeVehicle(body): void;Release handling, leaving the chassis.
Parameters
| Parameter | Type |
|---|---|
body | number |
Returns
void
Inherited from
resetVehicle()
ts
resetVehicle(command): void;Teleport and reset handling history.
Parameters
| Parameter | Type |
|---|---|
command | ResetVehicleCmd |
Returns
void
Inherited from
saveGameData()
ts
saveGameData(data): void;Persist the room's game-wide document (JSON).
Parameters
| Parameter | Type |
|---|---|
data | string |
Returns
void
Inherited from
savePlayerData()
ts
savePlayerData(player, data): void;Persist one player's document (JSON).
Parameters
| Parameter | Type |
|---|---|
player | number |
data | string |
Returns
void
Inherited from
say()
ts
say(
entity,
text,
audio,
visemes
): void;Speak a line.
Parameters
| Parameter | Type |
|---|---|
entity | number |
text | string |
audio | number | undefined |
visemes | string | undefined |
Returns
void
Inherited from
send()
ts
send(
to,
name,
payload,
reliable
): void;Send a game message; to undefined is every player (or the authority, from a client).
Parameters
| Parameter | Type |
|---|---|
to | number | undefined |
name | string |
payload | string |
reliable | boolean |
Returns
void
Inherited from
setAnim()
ts
setAnim(
entity,
clip,
looping,
speed,
fadeMs,
weight
): void;Play or cross-fade an animation clip.
Parameters
| Parameter | Type |
|---|---|
entity | number |
clip | string |
looping | boolean |
speed | number |
fadeMs | number |
weight | number |
Returns
void
Inherited from
setAsset()
ts
setAsset(entity, asset): void;Attach or detach a renderable.
Parameters
| Parameter | Type |
|---|---|
entity | number |
asset | number | undefined |
Returns
void
Inherited from
setBodyEnabled()
ts
setBodyEnabled(body, enabled): void;Enable or disable a body in the broad phase.
Parameters
| Parameter | Type |
|---|---|
body | number |
enabled | boolean |
Returns
void
Inherited from
setBodyTransform()
ts
setBodyTransform(
body,
position,
rotation,
teleport
): void;Move a body directly.
Parameters
| Parameter | Type |
|---|---|
body | number |
position | Vec3 |
rotation | Quat |
teleport | boolean |
Returns
void
Inherited from
EngineAdapter.setBodyTransform
setBodyVelocity()
ts
setBodyVelocity(
body,
linear,
angular
): void;Overwrite a body's velocities; undefined leaves one untouched.
Parameters
| Parameter | Type |
|---|---|
body | number |
linear | Vec3 | undefined |
angular | Vec3 | undefined |
Returns
void
Inherited from
setBusFx()
ts
setBusFx(command): void;Apply set-bus-fx.
Parameters
| Parameter | Type |
|---|---|
command | SetBusFxCmd |
Returns
void
Inherited from
setCamera()
ts
setCamera(camera): void;Apply the camera the guest asked for.
Parameters
| Parameter | Type |
|---|---|
camera | CameraState |
Returns
void
Inherited from
setCharacterMotion()
ts
setCharacterMotion(command): void;How the movement system moves a character.
Parameters
| Parameter | Type |
|---|---|
command | SetCharacterMotionCmd |
Returns
void
Inherited from
EngineAdapter.setCharacterMotion
setCharacterState()
ts
setCharacterState(
entity,
state,
velocity,
grounded,
facing?
): void;Drive a character's locomotion state machine.
Parameters
| Parameter | Type |
|---|---|
entity | number |
state | string |
velocity | Vec3 |
grounded | boolean |
facing? | number |
Returns
void
Inherited from
EngineAdapter.setCharacterState
setClipWeights()
ts
setClipWeights(
entity,
clips,
weights,
timeScale
): void;Set explicit per-clip weights.
Parameters
| Parameter | Type |
|---|---|
entity | number |
clips | readonly string[] |
weights | ArrayLike<number> |
timeScale | number |
Returns
void
Inherited from
setExpression()
ts
setExpression(
entity,
space,
weights
): void;Set facial expression coefficients.
Parameters
| Parameter | Type |
|---|---|
entity | number |
space | ExpressionSpace |
weights | ArrayLike<number> |
Returns
void
Inherited from
setHud()
ts
setHud(json): void;Apply the HUD model, or leave the previous one when undefined.
Parameters
| Parameter | Type |
|---|---|
json | string | undefined |
Returns
void
Inherited from
setJointMotor()
ts
setJointMotor(args): void;Set a joint motor in radians/metres.
Parameters
| Parameter | Type |
|---|---|
args | SetJointMotorCmd |
Returns
void
Inherited from
setListener()
ts
setListener(
position,
rotation,
velocity
): void;Place the audio listener.
Parameters
| Parameter | Type |
|---|---|
position | Vec3 |
rotation | Quat |
velocity | Vec3 |
Returns
void
Inherited from
setMaterialParam()
ts
setMaterialParam(
entity,
name,
value
): void;Set one material uniform.
Parameters
| Parameter | Type |
|---|---|
entity | number |
name | string |
value | MaterialValue |
Returns
void
Inherited from
EngineAdapter.setMaterialParam
setMusicLayer()
ts
setMusicLayer(command): void;Apply set-music-layer.
Parameters
| Parameter | Type |
|---|---|
command | SetMusicLayerCmd |
Returns
void
Inherited from
setParent()
ts
setParent(
entity,
parent,
keepWorldTransform
): void;Reparent an entity.
Parameters
| Parameter | Type |
|---|---|
entity | number |
parent | number | undefined |
keepWorldTransform | boolean |
Returns
void
Inherited from
setPlayerCamera()
ts
setPlayerCamera(player, camera): void;The camera one player renders from.
Parameters
| Parameter | Type |
|---|---|
player | number |
camera | CameraState |
Returns
void
Inherited from
setPlayerEntity()
ts
setPlayerEntity(
player,
entity,
spawn?
): void;Which entity a player controls (0 for none). The authority keeps the mapping for relevancy and each player's "your entity"; a page ignores it.
Parameters
| Parameter | Type |
|---|---|
player | number |
entity | number |
spawn? | number |
Returns
void
Inherited from
setPlayerHud()
ts
setPlayerHud(player, hud): void;One player's HUD model as JSON.
Parameters
| Parameter | Type |
|---|---|
player | number |
hud | string |
Returns
void
Inherited from
setPointerLock()
ts
setPointerLock(locked): void;Request or release pointer lock.
Parameters
| Parameter | Type |
|---|---|
locked | boolean |
Returns
void
Inherited from
setPost()
ts
setPost(command): void;Apply partial post settings; payload is borrowed.
Parameters
| Parameter | Type |
|---|---|
command | PostCmd |
Returns
void
Inherited from
setSoundOcclusion()
ts
setSoundOcclusion(command): void;Apply set-sound-occlusion.
Parameters
| Parameter | Type |
|---|---|
command | SetSoundOcclusionCmd |
Returns
void
Inherited from
EngineAdapter.setSoundOcclusion
setSpotLight()?
ts
optional setSpotLight(command): void;Create or update an entity-owned spotlight; optional for headless adapters.
Parameters
| Parameter | Type |
|---|---|
command | SpotLightCmd |
Returns
void
Inherited from
setTimeScale()
ts
setTimeScale(scale): void;Scale simulated time.
Parameters
| Parameter | Type |
|---|---|
scale | number |
Returns
void
Inherited from
setUi()
ts
setUi(json): void;Apply the page UI model, or keep it when undefined.
Parameters
| Parameter | Type |
|---|---|
json | string | undefined |
Returns
void
Inherited from
setVehicleInput()
ts
setVehicleInput(command): void;Set one step of vehicle controls.
Parameters
| Parameter | Type |
|---|---|
command | SetVehicleInputCmd |
Returns
void
Inherited from
spawn()
ts
spawn(
entity,
asset,
position,
rotation,
scale,
flags
): void;Create an entity in the scene.
Parameters
| Parameter | Type |
|---|---|
entity | number |
asset | number | undefined |
position | Vec3 |
rotation | Quat |
scale | Vec3 |
flags | { name?: string; parent?: number; visible: boolean; } |
flags.name? | string |
flags.parent? | number |
flags.visible | boolean |
Returns
void
Inherited from
spawnCharacter()
ts
spawnCharacter(
entity,
bundle,
position,
rotation
): void;Instantiate a splat character bundle.
Parameters
| Parameter | Type |
|---|---|
entity | number |
bundle | number |
position | Vec3 |
rotation | Quat |
Returns
void
Inherited from
stopCharacterWalk()
ts
stopCharacterWalk(entity): void;Give up a walk to a spot.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
EngineAdapter.stopCharacterWalk
stopMusic()
ts
stopMusic(command): void;Apply stop-music.
Parameters
| Parameter | Type |
|---|---|
command | number |
Returns
void
Inherited from
stopSound()
ts
stopSound(sound, fadeMs): void;Stop a playing sound.
Parameters
| Parameter | Type |
|---|---|
sound | number |
fadeMs | number |
Returns
void
Inherited from
thing()
ts
thing(command): void;Something asked of a loose thing in a made world (the optional world bridge).
Parameters
| Parameter | Type |
|---|---|
command | ThingCmd |
Returns
void
Inherited from
walkCharacterTo()
ts
walkCharacterTo(
entity,
target,
facing,
pace,
quick,
stop?,
start?
): void;Walk a character to a spot. stop is the kind of stop this one walk ends with ('gradual', it slows and stands upright; 'hard', it brakes); left out: the character's own. start says how it is begun ('moving': the game says the body is under way already); left out: as the character's takes have the body.
Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Vec3 |
facing | number | undefined |
pace | number |
quick | boolean |
stop? | StopStyle |
start? | "moving" |
Returns
void
Inherited from
LoopEngine
The two parts of an engine a loop uses: the module registry and the event bus.
Both the page's Engine and a HeadlessEngine have them.
Example
ts
const engine: LoopEngine = await createHeadlessEngine({ manifest, modules });Properties
events
ts
readonly events: Events<EngineEventMap>;Where physics:stepped is announced.
modules
ts
readonly modules: ModuleRegistry;Where the physics service is looked up.
MinimalWasiOptions
Options for minimalWasi.
Properties
monotonicNs?
ts
optional monotonicNs?: () => bigint;Monotonic nanoseconds. Default: performance.now().
Returns
bigint
stderr?
ts
optional stderr?: StderrSink;Where the guest's stderr goes. Default: console.error.
NullAdapter
An adapter that records instead of rendering.
Extends
Properties
appliesLocal
ts
appliesLocal: boolean;Whether applyOutput applies localCommands here. True unless the options say otherwise.
Overrides
calls
ts
readonly calls: AdapterCall[];Every call, in order.
lastTransformCount
ts
readonly lastTransformCount: number;Rows handed to the most recent applyTransforms.
Methods
addBody()
ts
addBody(args): void;Create a rigid body or character controller.
Parameters
| Parameter | Type |
|---|---|
args | AddBodyCmd |
Returns
void
Inherited from
addJoint()
ts
addJoint(args): void;Create a joint; invalid body references are dropped.
Parameters
| Parameter | Type |
|---|---|
args | AddJointCmd |
Returns
void
Inherited from
addVehicle()
ts
addVehicle(command): void;Attach arcade handling to a dynamic body.
Parameters
| Parameter | Type |
|---|---|
command | AddVehicleCmd |
Returns
void
Inherited from
applyImpulse()
ts
applyImpulse(
body,
impulse,
atPoint
): void;Apply a one-shot impulse.
Parameters
| Parameter | Type |
|---|---|
body | number |
impulse | Vec3 |
atPoint | Vec3 | undefined |
Returns
void
Inherited from
applyTransforms()
ts
applyTransforms(transforms, count): void;Apply packed entity transforms.
Parameters
| Parameter | Type | Description |
|---|---|---|
transforms | Float32Array | Stride 12: entity, flags, position, rotation, scale. |
count | number | Number of rows. The buffer may be longer. |
Returns
void
Inherited from
by()
ts
by(method): AdapterCall[];Calls with a given method name.
Parameters
| Parameter | Type |
|---|---|
method | AdapterMethod |
Returns
cancelCharacterAction()
ts
cancelCharacterAction(entity): void;Take an action's request back.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
EngineAdapter.cancelCharacterAction
conversation()
ts
conversation(command): void;Forward structural controls to an optional conversation module.
Parameters
| Parameter | Type |
|---|---|
command | ConversationCmd |
Returns
void
Inherited from
cutscene()
ts
cutscene(command): void;A cutscene: preload, play over the stage, or skip (the optional cutscene bridge).
Parameters
| Parameter | Type |
|---|---|
command | CutsceneCmd |
Returns
void
Inherited from
despawn()
ts
despawn(entity): void;Destroy an entity and everything attached to it.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
doCharacterAction()
ts
doCharacterAction(command): void;Ask a character to do an action of its motion set.
Parameters
| Parameter | Type |
|---|---|
command | DoCharacterActionCmd |
Returns
void
Inherited from
EngineAdapter.doCharacterAction
effect()
ts
effect(command): void;Apply a particle command; payload is borrowed.
Parameters
| Parameter | Type |
|---|---|
command | EffectCmd |
Returns
void
Inherited from
exchange()
ts
exchange(command): void;Trade between two players' documents. The command is pooled: read it, never keep it.
Parameters
| Parameter | Type |
|---|---|
command | ExchangeCmd |
Returns
void
Inherited from
faceCharacter()
ts
faceCharacter(
entity,
facing,
quick
): void;Turn a character on the spot to face a way.
Parameters
| Parameter | Type |
|---|---|
entity | number |
facing | number |
quick | boolean |
Returns
void
Inherited from
fightCamera()
ts
fightCamera(command): void;The fight camera, run on the host.
Parameters
| Parameter | Type |
|---|---|
command | FightCameraCmd |
Returns
void
Inherited from
fightFall()
ts
fightFall(command): void;A fighter thrown into the fight kit's rag-doll.
Parameters
| Parameter | Type |
|---|---|
command | FightFallCmd |
Returns
void
Inherited from
fightGetUp()
ts
fightGetUp(command): void;A fighter up off the floor.
Parameters
| Parameter | Type |
|---|---|
command | FightGetUpCmd |
Returns
void
Inherited from
fightHit()
ts
fightHit(command): void;A blow on a fighter on the fight kit's door.
Parameters
| Parameter | Type |
|---|---|
command | FightHitCmd |
Returns
void
Inherited from
fightState()
ts
fightState(command): void;The fight kit's script door: what a fighter's body is doing this step.
Parameters
| Parameter | Type |
|---|---|
command | FightStateCmd |
Returns
void
Inherited from
hitCharacter()
ts
hitCharacter(
entity,
at,
direction,
strength
): void;A blow on a character's physics body.
Parameters
| Parameter | Type |
|---|---|
entity | number |
at | Vec3 |
direction | Vec3 |
strength | HitStrength |
Returns
void
Inherited from
loadAsset()
ts
loadAsset(asset, priority): void;Start loading an asset.
Parameters
| Parameter | Type |
|---|---|
asset | number |
priority | number |
Returns
void
Inherited from
localScope()?
ts
optional localScope(on): void;Optional: told when applyOutput starts (true) and ends (false) applying frame-output.local-commands. The server adapter uses it to keep what a local command does out of the replicated world record.
Parameters
| Parameter | Type |
|---|---|
on | boolean |
Returns
void
Inherited from
lookAt()
ts
lookAt(
entity,
target,
weight
): void;Aim a character's head and eyes.
Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Vec3 | undefined |
weight | number |
Returns
void
Inherited from
moveCharacter()
ts
moveCharacter(
body,
desiredVelocity,
jump,
crouch,
maxSlopeDeg
): void;Drive a character body for one step.
Parameters
| Parameter | Type |
|---|---|
body | number |
desiredVelocity | Vec3 |
jump | boolean |
crouch | boolean |
maxSlopeDeg | number |
Returns
void
Inherited from
pausePop()
ts
pausePop(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
Inherited from
pausePush()
ts
pausePush(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
Inherited from
playMusic()
ts
playMusic(command): void;Apply play-music.
Parameters
| Parameter | Type |
|---|---|
command | PlayMusicCmd |
Returns
void
Inherited from
playSound()
ts
playSound(
sound,
asset,
entity,
position,
volume,
pitch,
looping,
bus
): void;Start a sound.
Parameters
| Parameter | Type |
|---|---|
sound | number |
asset | number |
entity | number | undefined |
position | Vec3 | undefined |
volume | number |
pitch | number |
looping | boolean |
bus | AudioBus |
Returns
void
Inherited from
playSoundOnBeat()
ts
playSoundOnBeat(command): void;Apply play-sound-on-beat.
Parameters
| Parameter | Type |
|---|---|
command | PlaySoundOnBeatCmd |
Returns
void
Inherited from
playtest()
ts
playtest(command): void;A playtest mark. It changes nothing in the game: the page's playtest tap reads the marks off the frame itself, so an adapter ignores them. The command is pooled: read it, never keep it.
Parameters
| Parameter | Type |
|---|---|
command | PlaytestCmd |
Returns
void
Inherited from
recoverCharacter()
ts
recoverCharacter(entity): void;A character that is down blends back into its animation.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
EngineAdapter.recoverCharacter
removeBody()
ts
removeBody(body): void;Destroy a body.
Parameters
| Parameter | Type |
|---|---|
body | number |
Returns
void
Inherited from
removeJoint()
ts
removeJoint(joint): void;Destroy a joint.
Parameters
| Parameter | Type |
|---|---|
joint | number |
Returns
void
Inherited from
removeVehicle()
ts
removeVehicle(body): void;Release handling, leaving the chassis.
Parameters
| Parameter | Type |
|---|---|
body | number |
Returns
void
Inherited from
reset()
ts
reset(): void;Forget every recorded call.
Returns
void
resetVehicle()
ts
resetVehicle(command): void;Teleport and reset handling history.
Parameters
| Parameter | Type |
|---|---|
command | ResetVehicleCmd |
Returns
void
Inherited from
saveGameData()
ts
saveGameData(data): void;Persist the room's game-wide document (JSON).
Parameters
| Parameter | Type |
|---|---|
data | string |
Returns
void
Inherited from
savePlayerData()
ts
savePlayerData(player, data): void;Persist one player's document (JSON).
Parameters
| Parameter | Type |
|---|---|
player | number |
data | string |
Returns
void
Inherited from
say()
ts
say(
entity,
text,
audio,
visemes
): void;Speak a line.
Parameters
| Parameter | Type |
|---|---|
entity | number |
text | string |
audio | number | undefined |
visemes | string | undefined |
Returns
void
Inherited from
send()
ts
send(
to,
name,
payload,
reliable
): void;Send a game message; to undefined is every player (or the authority, from a client).
Parameters
| Parameter | Type |
|---|---|
to | number | undefined |
name | string |
payload | string |
reliable | boolean |
Returns
void
Inherited from
setAnim()
ts
setAnim(
entity,
clip,
looping,
speed,
fadeMs,
weight
): void;Play or cross-fade an animation clip.
Parameters
| Parameter | Type |
|---|---|
entity | number |
clip | string |
looping | boolean |
speed | number |
fadeMs | number |
weight | number |
Returns
void
Inherited from
setAsset()
ts
setAsset(entity, asset): void;Attach or detach a renderable.
Parameters
| Parameter | Type |
|---|---|
entity | number |
asset | number | undefined |
Returns
void
Inherited from
setBodyEnabled()
ts
setBodyEnabled(body, enabled): void;Enable or disable a body in the broad phase.
Parameters
| Parameter | Type |
|---|---|
body | number |
enabled | boolean |
Returns
void
Inherited from
setBodyTransform()
ts
setBodyTransform(
body,
position,
rotation,
teleport
): void;Move a body directly.
Parameters
| Parameter | Type |
|---|---|
body | number |
position | Vec3 |
rotation | Quat |
teleport | boolean |
Returns
void
Inherited from
EngineAdapter.setBodyTransform
setBodyVelocity()
ts
setBodyVelocity(
body,
linear,
angular
): void;Overwrite a body's velocities; undefined leaves one untouched.
Parameters
| Parameter | Type |
|---|---|
body | number |
linear | Vec3 | undefined |
angular | Vec3 | undefined |
Returns
void
Inherited from
setBusFx()
ts
setBusFx(command): void;Apply set-bus-fx.
Parameters
| Parameter | Type |
|---|---|
command | SetBusFxCmd |
Returns
void
Inherited from
setCamera()
ts
setCamera(camera): void;Apply the camera the guest asked for.
Parameters
| Parameter | Type |
|---|---|
camera | CameraState |
Returns
void
Inherited from
setCharacterMotion()
ts
setCharacterMotion(command): void;How the movement system moves a character.
Parameters
| Parameter | Type |
|---|---|
command | SetCharacterMotionCmd |
Returns
void
Inherited from
EngineAdapter.setCharacterMotion
setCharacterState()
ts
setCharacterState(
entity,
state,
velocity,
grounded,
facing?
): void;Drive a character's locomotion state machine.
Parameters
| Parameter | Type |
|---|---|
entity | number |
state | string |
velocity | Vec3 |
grounded | boolean |
facing? | number |
Returns
void
Inherited from
EngineAdapter.setCharacterState
setClipWeights()
ts
setClipWeights(
entity,
clips,
weights,
timeScale
): void;Set explicit per-clip weights.
Parameters
| Parameter | Type |
|---|---|
entity | number |
clips | readonly string[] |
weights | ArrayLike<number> |
timeScale | number |
Returns
void
Inherited from
setExpression()
ts
setExpression(
entity,
space,
weights
): void;Set facial expression coefficients.
Parameters
| Parameter | Type |
|---|---|
entity | number |
space | ExpressionSpace |
weights | ArrayLike<number> |
Returns
void
Inherited from
setHud()
ts
setHud(json): void;Apply the HUD model, or leave the previous one when undefined.
Parameters
| Parameter | Type |
|---|---|
json | string | undefined |
Returns
void
Inherited from
setJointMotor()
ts
setJointMotor(args): void;Set a joint motor in radians/metres.
Parameters
| Parameter | Type |
|---|---|
args | SetJointMotorCmd |
Returns
void
Inherited from
setListener()
ts
setListener(
position,
rotation,
velocity
): void;Place the audio listener.
Parameters
| Parameter | Type |
|---|---|
position | Vec3 |
rotation | Quat |
velocity | Vec3 |
Returns
void
Inherited from
setMaterialParam()
ts
setMaterialParam(
entity,
name,
value
): void;Set one material uniform.
Parameters
| Parameter | Type |
|---|---|
entity | number |
name | string |
value | MaterialValue |
Returns
void
Inherited from
EngineAdapter.setMaterialParam
setMusicLayer()
ts
setMusicLayer(command): void;Apply set-music-layer.
Parameters
| Parameter | Type |
|---|---|
command | SetMusicLayerCmd |
Returns
void
Inherited from
setParent()
ts
setParent(
entity,
parent,
keepWorldTransform
): void;Reparent an entity.
Parameters
| Parameter | Type |
|---|---|
entity | number |
parent | number | undefined |
keepWorldTransform | boolean |
Returns
void
Inherited from
setPlayerCamera()
ts
setPlayerCamera(player, camera): void;The camera one player renders from.
Parameters
| Parameter | Type |
|---|---|
player | number |
camera | CameraState |
Returns
void
Inherited from
setPlayerEntity()
ts
setPlayerEntity(
player,
entity,
spawn?
): void;Which entity a player controls (0 for none). The authority keeps the mapping for relevancy and each player's "your entity"; a page ignores it.
Parameters
| Parameter | Type |
|---|---|
player | number |
entity | number |
spawn? | number |
Returns
void
Inherited from
setPlayerHud()
ts
setPlayerHud(player, hud): void;One player's HUD model as JSON.
Parameters
| Parameter | Type |
|---|---|
player | number |
hud | string |
Returns
void
Inherited from
setPointerLock()
ts
setPointerLock(locked): void;Request or release pointer lock.
Parameters
| Parameter | Type |
|---|---|
locked | boolean |
Returns
void
Inherited from
setPost()
ts
setPost(command): void;Apply partial post settings; payload is borrowed.
Parameters
| Parameter | Type |
|---|---|
command | PostCmd |
Returns
void
Inherited from
setSoundOcclusion()
ts
setSoundOcclusion(command): void;Apply set-sound-occlusion.
Parameters
| Parameter | Type |
|---|---|
command | SetSoundOcclusionCmd |
Returns
void
Inherited from
EngineAdapter.setSoundOcclusion
setSpotLight()?
ts
optional setSpotLight(command): void;Create or update an entity-owned spotlight; optional for headless adapters.
Parameters
| Parameter | Type |
|---|---|
command | SpotLightCmd |
Returns
void
Inherited from
setTimeScale()
ts
setTimeScale(scale): void;Scale simulated time.
Parameters
| Parameter | Type |
|---|---|
scale | number |
Returns
void
Inherited from
setUi()
ts
setUi(json): void;Apply the page UI model, or keep it when undefined.
Parameters
| Parameter | Type |
|---|---|
json | string | undefined |
Returns
void
Inherited from
setVehicleInput()
ts
setVehicleInput(command): void;Set one step of vehicle controls.
Parameters
| Parameter | Type |
|---|---|
command | SetVehicleInputCmd |
Returns
void
Inherited from
spawn()
ts
spawn(
entity,
asset,
position,
rotation,
scale,
flags
): void;Create an entity in the scene.
Parameters
| Parameter | Type |
|---|---|
entity | number |
asset | number | undefined |
position | Vec3 |
rotation | Quat |
scale | Vec3 |
flags | { name?: string; parent?: number; visible: boolean; } |
flags.name? | string |
flags.parent? | number |
flags.visible | boolean |
Returns
void
Inherited from
spawnCharacter()
ts
spawnCharacter(
entity,
bundle,
position,
rotation
): void;Instantiate a splat character bundle.
Parameters
| Parameter | Type |
|---|---|
entity | number |
bundle | number |
position | Vec3 |
rotation | Quat |
Returns
void
Inherited from
stopCharacterWalk()
ts
stopCharacterWalk(entity): void;Give up a walk to a spot.
Parameters
| Parameter | Type |
|---|---|
entity | number |
Returns
void
Inherited from
EngineAdapter.stopCharacterWalk
stopMusic()
ts
stopMusic(command): void;Apply stop-music.
Parameters
| Parameter | Type |
|---|---|
command | number |
Returns
void
Inherited from
stopSound()
ts
stopSound(sound, fadeMs): void;Stop a playing sound.
Parameters
| Parameter | Type |
|---|---|
sound | number |
fadeMs | number |
Returns
void
Inherited from
thing()
ts
thing(command): void;Something asked of a loose thing in a made world (the optional world bridge).
Parameters
| Parameter | Type |
|---|---|
command | ThingCmd |
Returns
void
Inherited from
walkCharacterTo()
ts
walkCharacterTo(
entity,
target,
facing,
pace,
quick,
stop?,
start?
): void;Walk a character to a spot. stop is the kind of stop this one walk ends with ('gradual', it slows and stands upright; 'hard', it brakes); left out: the character's own. start says how it is begun ('moving': the game says the body is under way already); left out: as the character's takes have the body.
Parameters
| Parameter | Type |
|---|---|
entity | number |
target | Vec3 |
facing | number | undefined |
pace | number |
quick | boolean |
stop? | StopStyle |
start? | "moving" |
Returns
void
Inherited from
PlaytestEvent
One thing that happened.
Properties
game
ts
game: boolean;True when the game said it, false when the engine noticed it.
kind
ts
kind: string;What: a game mark's kind, or one the engine noticed.
note
ts
note: string;Why, in a few words.
step
ts
step: number;Fixed step it happened at, counted from the start of the run.
value
ts
value: number;How much, or 0.
x
ts
x: number;Where the player was (or where the game said).
y
ts
y: number;Where.
z
ts
z: number;Where.
PlaytestHost
What the host loop gives the controller.
Properties
hz
ts
hz: number;Fixed steps a second.
pause?
ts
optional pause?: object;Shared ownership when the page pauses playtesting.
pop()
ts
pop(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
push()
ts
push(reason): void;Parameters
| Parameter | Type |
|---|---|
reason | string |
Returns
void
physics
ts
physics: RayWorld | null;The physics queries, or null without a physics world.
seed
ts
seed: number;The run's seed.
Methods
entityOfBody()
ts
entityOfBody(body): number;Parameters
| Parameter | Type | Description |
|---|---|---|
body | number | A body id. |
Returns
number
The entity it drives, or 0.
placePlayer()?
ts
optional placePlayer(
body,
position,
rotation
): void;Put the player's body somewhere, as a teleport: the agent starts its next life at the run's start or the last checkpoint. Without it a life that ends leaves the player where it ended.
Parameters
| Parameter | Type | Description |
|---|---|---|
body | number | The player's body id. |
position | Vec3 | Where. |
rotation | Quat | Facing. |
Returns
void
setTimeScale()?
ts
optional setTimeScale(scale): void;Scale simulated time: 0 pauses the game while the agent trains.
Parameters
| Parameter | Type | Description |
|---|---|---|
scale | number | The scale; 1 is real time. |
Returns
void
PlaytestInput
The input block, as the page's host loop hands it to the guest. Only the parts the playtest reads or writes are named.
Properties
control?
ts
optional control?: object;The page-decided move axes of a room's client, when there are any.
moveX
ts
moveX: number;moveY
ts
moveY: number;down
ts
down: Uint32Array;Keys held.
focused
ts
focused: boolean;Whether the page has focus.
gamepads?
ts
optional gamepads?: readonly object[];Gamepads, the touch pad among them.
mods
ts
mods: object;Modifier keys.
shift
ts
shift: boolean;mouse
ts
mouse: object;The mouse.
buttons
ts
buttons: number;dx
ts
dx: number;dy
ts
dy: number;locked
ts
locked: boolean;pressed
ts
pressed: number;released
ts
released: number;wheel
ts
wheel: number;pressed
ts
pressed: Uint32Array;Keys that went down this step.
released
ts
released: Uint32Array;Keys that came up this step.
PlaytestStatus
The status the page shows.
Properties
mode
ts
mode: PlaytestMode;What the controller is doing.
playerFound
ts
playerFound: boolean;True when a player body is being followed.
policy
ts
policy: Record<string, string | number> | null;The policy's training record, or null when there is none.
route
ts
route:
| {
cells: number;
reachable: boolean;
}
| null;The route to the goal, or null before a scan: cells the goal can be reached from, and whether the run's start is one.
steps
ts
steps: number;Steps in the current recording, agent run or replay.
traces
ts
traces: number;Traces kept this session.
training
ts
training: boolean;True while training.
PlaytestSummary
One run, summed up.
Properties
attempts
ts
attempts: number;Tries: lives started.
checkpoints
ts
checkpoints: number;Checkpoints reached.
damage
ts
damage: number;Damage taken, summed.
deathCauses
ts
deathCauses: Record<string, number>;Deaths by cause.
deaths
ts
deaths: number;Deaths of every kind (the game's, falls, respawns with no death said).
deathSpots
ts
deathSpots: Hotspot[];Where players died, most deaths first.
findings
ts
findings: string[];Plain-language findings, the most useful first.
firstWinSeconds
ts
firstWinSeconds: number | null;Seconds to the first win, or null.
gameDeaths
ts
gameDeaths: number;Deaths the game said (playtest.death), whatever their cause; the rest the engine noticed.
goals
ts
goals: GoalStretch[];The play toward each goal the game said, in order: a level each, in a game that says one per level.
goalsReached
ts
goalsReached: number;Times the player got to the goal the game said (a level done counts, with a win or without).
hadGoal
ts
hadGoal: boolean;True when the game said where the goal is, at least once.
jumpsInAir
ts
jumpsInAir: number;Jump presses with nothing underfoot (a player wishing for a double jump).
kind
ts
kind: string;Who played.
marks
ts
marks: Record<string, number>;The game's own marks by kind.
missedJumps
ts
missedJumps: Hotspot[];Where jumps were missed, with how far they carried and the gap.
noRoute
ts
noRoute: string | null;Where the route to the goal breaks, when the planner found none: what it saw.
pace
ts
pace: Pace;What a player met per minute.
respawnDeaths
ts
respawnDeaths: Hotspot[];Where players died again within seconds of coming back to life: an unsafe respawn point.
reward
ts
reward: number;Rewards, summed.
seconds
ts
seconds: number;Seconds played.
stuckSpots
ts
stuckSpots: Hotspot[];Where players got stuck.
wins
ts
wins: number;Wins.
PolicyJson
A policy as JSON: what is saved and uploaded.
Properties
mean
ts
mean: number[];Per-feature mean, for normalising.
meta
ts
meta: Record<string, string | number>;What it was trained on.
obsVersion
ts
obsVersion: number;The observation layout it was trained on.
params
ts
params: string;Every weight and bias, little-endian f32, base64.
sizes
ts
sizes: number[];Layer widths, input to output.
std
ts
std: number[];Per-feature spread, for normalising.
version
ts
version: number;Format version: 1.
PracticeOptions
Options for PlaytestController.practice.
Properties
anchor?
ts
optional anchor?: number;How much the person's runs count against the agent's, in all. Default 0.5.
balanceClasses?
ts
optional balanceClasses?: boolean;Weigh rare choices up, as behaviour cloning does (TrainOptions.balanceClasses). Default false.
episodes?
ts
optional episodes?: number;Lives a round. Default 12: a game whose lives last seconds gives little to learn from in a few.
epochs?
ts
optional epochs?: number;Passes over a round's steps. Default 4.
learningRate?
ts
optional learningRate?: number;Adam's step size. Default 0.0005.
maxSeconds?
ts
optional maxSeconds?: number;Seconds a life may last. Default 30.
rounds?
ts
optional rounds?: number;Rounds of play-then-learn. Default 6, at most 20.
signal?
ts
optional signal?: AbortSignal;Stops after the round under way; the best policy so far is kept.
speed?
ts
optional speed?: number;How much faster than real time the game runs, 1 to 4. Default 4.
temperature?
ts
optional temperature?: number;How freely the agent explores while it practises. Default 1.
traces?
ts
optional traces?: readonly Trace[];The person's runs, taught alongside so the agent keeps what it copied; this session's human runs by default.
PracticeResult
What practice did.
Properties
before
ts
before: number;The first round's score per life.
best
ts
best: number;The best round's score per life.
policy
ts
policy: Policy;The best policy it played with, now the agent's.
rounds
ts
rounds: PracticeRound[];Every round, the first played with the policy practice started from.
PracticeRound
One round of practice.
Properties
lives
ts
lives: number;Lives played.
meanReturn
ts
meanReturn: number;The round's score per life.
outcomes
ts
outcomes: string[];How each life ended.
round
ts
round: number;From 1.
wins
ts
wins: number;Lives won.
RunEvents
What a summary reads: a trace header, or any run's events.
Properties
events
ts
events: readonly PlaytestEvent[];What happened.
hz
ts
hz: number;Steps a second.
kind
ts
kind: string;Who played: human, agent, replay, session.
steps
ts
steps: number;Steps played.
RunOptions
Options for PlaytestController.run.
Extends
Properties
episodes?
ts
optional episodes?: number;Lives to play. Default 5.
maxSeconds?
ts
optional maxSeconds?: number;Seconds a life may last before it counts as timed out. Default 60.
policy?
ts
optional policy?: Policy;The policy; the last trained or loaded one by default.
Inherited from
record?
ts
optional record?: boolean;Keep the agent's run as a trace. Default true.
Inherited from
speed?
ts
optional speed?: number;How much faster than real time the game runs while the agent plays, 1 to 4. Default 1.
temperature?
ts
optional temperature?: number;0 always picks the likeliest action; higher explores. Default 0.6.
Inherited from
RunResult
What a run of the agent found.
Properties
outcomes
ts
outcomes: string[];How each life ended: win, death, fell, respawn, timeout.
route
ts
route: Float32Array;Route metres to the goal at each step of the trace; NaN where there was no route.
summary
ts
summary: PlaytestSummary;The summary.
trace
ts
trace: Trace;The run, step by step.
Sandbox
One loaded game module.
Properties
dead
ts
readonly dead: boolean;True once the guest has trapped or failed. A dead sandbox returns a safe empty frame forever; rebuild it.
devReload?
ts
optional devReload?: (apply) => void;Dev-only: publish reload services once the initial host output has been applied.
Parameters
| Parameter | Type |
|---|---|
apply | (output) => void |
Returns
void
error
ts
readonly error: Error | null;Why the sandbox died, when it did.
mode
ts
readonly mode: "direct" | "wasm";How this sandbox runs its guest.
Methods
init()
ts
init(config): void;Call once, before the first tick.
Parameters
| Parameter | Type |
|---|---|
config | HostGameConfig |
Returns
void
restore()
ts
restore(state): void;Restore a state produced by snapshot from the same build.
Parameters
| Parameter | Type |
|---|---|
state | Uint8Array |
Returns
void
shutdown()
ts
shutdown(): void;Release guest-side resources. No further calls follow.
Returns
void
snapshot()
ts
snapshot(): Uint8Array;Serialise the whole guest state.
Returns
Uint8Array
tick()
ts
tick(input): FrameOutput;One fixed simulation step.
Parameters
| Parameter | Type |
|---|---|
input | HostFrameInput |
Returns
StartOptions
Why play begins. Capture callbacks must leave pointer lock and gated audio optional.
Properties
reason?
ts
optional reason?: "player" | "capture" | "playtest";Defaults to player.
StepTap
Something that sees every step a loop takes: the page's playtest (record a person, let an agent play). Both calls run inside the fixed step and must not allocate.
Example
ts
const tap: StepTap = {
input(input) { input.mouse.dx = 0; },
stepped(bodies, count, out) { if (out.hud !== undefined) console.log(out.hud); },
};Methods
input()
ts
input(input): void;After the step's input is read, before it is encoded: it may rewrite it.
Parameters
| Parameter | Type | Description |
|---|---|---|
input | InputSnapshot | The input the guest is about to receive. |
Returns
void
stepped()
ts
stepped(
bodies,
bodyCount,
out,
dt
): void;After the guest stepped, before its output is applied.
Parameters
| Parameter | Type | Description |
|---|---|---|
bodies | Float32Array | The body rows the guest received, stride 15. |
bodyCount | number | Rows. |
out | FrameOutput | What the guest sent back. Pooled: read it, never keep it. |
dt | number | The step, seconds. |
Returns
void
Trace
A trace in memory.
Properties
actions
ts
actions: Uint8Array;steps × ACTION_SIZE.
buttons
ts
buttons: Uint8Array;steps: mouse buttons.
header
ts
header: TraceHeader;What it says about itself.
keys
ts
keys: Uint32Array;steps × KEY_WORDS.
mouse
ts
mouse: Float32Array;steps × 2: mouse dx, dy.
obs
ts
obs: Float32Array;steps × obsSize.
TraceHeader
What a trace says about itself.
Properties
events
ts
events: PlaytestEvent[];What happened.
hz
ts
hz: number;Steps a second.
kind
ts
kind: TraceKind;Who played.
meta
ts
meta: Record<string, string>;Whatever the page adds: the game, the engine commit, the template.
obsSize
ts
obsSize: number;Floats per observation.
obsVersion
ts
obsVersion: number;The observation layout's version.
seed
ts
seed: number;The run's seed, when the page knows it.
startedAt
ts
startedAt: string;When it started, ISO time.
steps
ts
steps: number;Steps recorded.
version
ts
version: number;Format version: 1.
TrainOptions
How to train.
Properties
balanceClasses?
ts
optional balanceClasses?: boolean;Weigh rare choices up (a jump is a few steps in a hundred). Default true; off when the examples' own weights already say what matters, as in practice.
batch?
ts
optional batch?: number;Examples per update. Default 64.
epochs?
ts
optional epochs?: number;Passes over the data. Default 20.
from?
ts
optional from?: Policy;Start from this policy instead of a fresh one (it must have the same shape).
hidden?
ts
optional hidden?: number;Hidden units per layer. Default 96.
learningRate?
ts
optional learningRate?: number;Adam's step size. Default 0.001.
mirror?
ts
optional mirror?: boolean;Mirror every example left to right. Default true.
onProgress?
ts
optional onProgress?: (progress) => void;Told after every epoch.
Parameters
| Parameter | Type |
|---|---|
progress | TrainProgress |
Returns
void
seed?
ts
optional seed?: number;Seed for the initial weights and the shuffle. Default 1.
signal?
ts
optional signal?: AbortSignal;Stops training early; what has been learned so far is returned.
sliceMs?
ts
optional sliceMs?: number;Milliseconds of work between yields. Default 12.
yieldTo?
ts
optional yieldTo?: () => Promise<void>;Waits between slices. Defaults to a macrotask.
Returns
Promise<void>
TrainProgress
How training is going.
Properties
epoch
ts
epoch: number;Epochs done.
epochs
ts
epochs: number;Epochs in all.
jumpAccuracy
ts
jumpAccuracy: number;Held-out accuracy of the jump head, 0..1.
loss
ts
loss: number;Mean loss over the last epoch.
moveAccuracy
ts
moveAccuracy: number;Held-out accuracy of the move head, 0..1.
TrainResult
What training made.
Properties
examples
ts
examples: number;Examples trained on (mirrored ones included).
policy
ts
policy: Policy;The policy.
progress
ts
progress: TrainProgress;The last epoch's progress.
UiDocument
The structural slice of a document used by the UI renderer.
Methods
createElement()
ts
createElement(tag): UiElement;Parameters
| Parameter | Type |
|---|---|
tag | string |
Returns
UiElement
The structural slice of an element used by the UI renderer.
Properties
className
ts
className: string;style
ts
readonly style: object;setProperty()
ts
setProperty(name, value): void;Parameters
| Parameter | Type |
|---|---|
name | string |
value | string |
Returns
void
textContent
ts
textContent: string | null;value?
ts
optional value?: string;Only read or written on input elements.
Methods
addEventListener()
ts
addEventListener(type, listener): void;Parameters
| Parameter | Type |
|---|---|
type | string |
listener | EventListener |
Returns
void
append()
ts
append(...nodes): void;Parameters
| Parameter | Type |
|---|---|
...nodes | unknown[] |
Returns
void
focus()
ts
focus(options?): void;Parameters
| Parameter | Type |
|---|---|
options? | { preventScroll?: boolean; } |
options.preventScroll? | boolean |
Returns
void
getBoundingClientRect()
ts
getBoundingClientRect(): object;Returns
object
bottom
ts
bottom: number;left
ts
left: number;right
ts
right: number;top
ts
top: number;insertBefore()
ts
insertBefore(node, child): unknown;Parameters
| Parameter | Type |
|---|---|
node | unknown |
child | unknown |
Returns
unknown
releasePointerCapture()
ts
releasePointerCapture(pointerId): void;Parameters
| Parameter | Type |
|---|---|
pointerId | number |
Returns
void
remove()
ts
remove(): void;Returns
void
removeAttribute()
ts
removeAttribute(name): void;Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
void
removeEventListener()
ts
removeEventListener(type, listener): void;Parameters
| Parameter | Type |
|---|---|
type | string |
listener | EventListener |
Returns
void
setAttribute()
ts
setAttribute(name, value): void;Parameters
| Parameter | Type |
|---|---|
name | string |
value | string |
Returns
void
setPointerCapture()
ts
setPointerCapture(pointerId): void;Parameters
| Parameter | Type |
|---|---|
pointerId | number |
Returns
void
UiRenderer
A retained DOM overlay, driven by frame payloads and camera placement.
Example
ts
import { createDomUi, type UiRenderer } from 'gameable/host';
const ui: UiRenderer = createDomUi({ onEvent: console.log });
ui.set(JSON.stringify({ nodes: [{ type: 'text', text: 'Hello' }] }));
ui.dispose();Properties
element
ts
readonly element: UiElement;The overlay root, attached at creation.
model
ts
readonly model: UiModel | null;The most recently applied model, or null after clearing.
Methods
clear()
ts
clear(): void;Remove nodes, release captures and forget the payload.
Returns
void
dispose()
ts
dispose(): void;Release nodes and listeners and detach the overlay.
Returns
void
place()
ts
place(project): void;Place world anchors once per rendered frame using caller-supplied projection.
Parameters
| Parameter | Type |
|---|---|
project | (anchor, out) => boolean |
Returns
void
set()
ts
set(json): boolean;Apply changed JSON; return false for unchanged or malformed payloads.
Parameters
| Parameter | Type |
|---|---|
json | string | undefined |
Returns
boolean
VfxSink
Optional particle and post command sink. Payloads and their vectors are pooled and reused by the guest: a sink must copy anything it keeps after the call.
Example
ts
import type { VfxSink } from 'gameable/host';
const sink: VfxSink = {
effect(command) { console.log(command.action, command.preset); },
setPost(command) { console.log(command.exposure); },
};Methods
effect()
ts
effect(command): void;Read a borrowed particle command.
Parameters
| Parameter | Type |
|---|---|
command | EffectCmd |
Returns
void
setPost()
ts
setPost(command): void;Read borrowed partial post settings.
Parameters
| Parameter | Type |
|---|---|
command | PostCmd |
Returns
void
WasmSandboxOptions
Load a jco transpiled component.
Properties
getCoreBytes?
ts
optional getCoreBytes?: (path) => Promise<Uint8Array<ArrayBuffer>>;Raw core loader; required when memoryLimitBytes is set explicitly, so the cap is clamped before compilation.
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
Promise<Uint8Array<ArrayBuffer>>
getCoreModule
ts
getCoreModule: (path) => Promise<Module>;Compile one of the nine core wasm files by its relative path.
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
Promise<Module>
guestModuleUrl?
ts
optional guestModuleUrl?: string | URL;URL of the transpiled game.js; also locates lazy source maps when instantiate is given. Dynamically imported, so bundlers see a runtime specifier.
host
ts
host: HostApi;Host services the guest imports.
instantiate?
ts
optional instantiate?: Instantiate;The transpiled module's instantiate, when it is already imported. Pass jco's own function, not a wrapper round it: what the game was compiled with is read from its text (guest-kinds.ts), and a game whose lists cannot be read is handed only the kinds of event and of asset the contract first had.
memoryLimitBytes?
ts
optional memoryLimitBytes?: number | null;Maximum total linear memory in bytes. Default 512 MiB. Null disables the cap for trusted guests; allocator failures are still checked after every call.
mode
ts
mode: "wasm";wasi?
ts
optional wasi?: MinimalWasiOptions;WASI stub overrides.
Type Aliases
EditorEvent
ts
type EditorEvent =
| {
type: "entered";
}
| {
type: "exited";
}
| {
id: number | null;
type: "selected";
}
| {
id: number;
position: [number, number, number];
rotation: [number, number, number, number];
scale: [number, number, number];
type: "changed";
what: EditorTransformPart[];
yaw: number;
}
| {
ground: [number, number, number] | null;
id: number | null;
type: "contextmenu";
x: number;
y: number;
}
| {
entity: number;
type: "missed";
x: number;
y: number;
}
| {
name: string;
type: "levelRequested";
};What the editor tells a listener.
Union Members
Type Literal
ts
{
type: "entered";
}Type Literal
ts
{
type: "exited";
}Type Literal
ts
{
id: number | null;
type: "selected";
}Type Literal
ts
{
id: number;
position: [number, number, number];
rotation: [number, number, number, number];
scale: [number, number, number];
type: "changed";
what: EditorTransformPart[];
yaw: number;
}id
ts
id: number;position
ts
position: [number, number, number];rotation
ts
rotation: [number, number, number, number];scale
ts
scale: [number, number, number];type
ts
type: "changed";what
ts
what: EditorTransformPart[];The parts the edit moved: a yaw from an inspector is ['rotation'], the rest is as it was.
yaw
ts
yaw: number;Type Literal
ts
{
ground: [number, number, number] | null;
id: number | null;
type: "contextmenu";
x: number;
y: number;
}ground
ts
ground: [number, number, number] | null;The surface under the pointer, or null.
id
ts
id: number | null;The actor under the pointer, or null.
type
ts
type: "contextmenu";x
ts
x: number;Pointer position in the page's CSS pixels.
y
ts
y: number;Type Literal
ts
{
entity: number;
type: "missed";
x: number;
y: number;
}entity
ts
entity: number;The guest entity it belongs to, or 0 for the page's own (the world, a splat).
type
ts
type: "missed";A click on something that is no actor: scenery the game spawned from code, or the page's own objects.
x
ts
x: number;Pointer position in the page's CSS pixels.
y
ts
y: number;Type Literal
ts
{
name: string;
type: "levelRequested";
}EditorTransformMode
ts
type EditorTransformMode = "translate" | "rotate" | "scale";The transform gizmo's modes.
EditorTransformPart
ts
type EditorTransformPart = "position" | "rotation" | "scale";A part of a transform, as a changed event names what an edit moved.
EngineHostOptions
ts
type EngineHostOptions = HostQueriesOptions;Options accepted by createEngineHost: seed, log sink and query capacity.
Instantiate
ts
type Instantiate = (getCoreModule, imports, instantiateCore) => Promise<Record<string, unknown>>;The instantiate a jco transpile --instantiation async module exports.
It resolves to the component's exports by name; the host reads only the versioned gameable:engine/game@0.2.0 one (see gameNamespace).
Parameters
| Parameter | Type |
|---|---|
getCoreModule | (path) => Promise<WebAssembly.Module> |
imports | Record<string, unknown> |
instantiateCore | typeof WebAssembly.instantiate |
Returns
Promise<Record<string, unknown>>
LoadKind
ts
type LoadKind =
| "descriptor"
| "splat"
| "bindings"
| "head"
| "mesh"
| "clips"
| "mouth"
| "other";The file kinds, each a lane of its own.
PlaytestMode
ts
type PlaytestMode = "play" | "record" | "agent" | "replay";What the controller is doing.
PlaytestNotice
ts
type PlaytestNotice =
| {
event: PlaytestEvent;
type: "event";
}
| {
mode: PlaytestMode;
type: "mode";
}
| {
progress: TrainProgress;
type: "train";
}
| {
episode: number;
outcome: string;
steps: number;
type: "episode";
}
| {
best: number;
round: PracticeRound;
rounds: number;
type: "practice";
};Something the controller tells a listener.
SandboxOptions
ts
type SandboxOptions =
| DirectSandboxOptions
| WasmSandboxOptions;Either kind of sandbox.
StderrSink
ts
type StderrSink = (bytes) => void;Where stub stderr goes. Replaced by minimalWasi({ stderr }).
Parameters
| Parameter | Type |
|---|---|
bytes | Uint8Array |
Returns
void
TraceKind
ts
type TraceKind = "human" | "agent" | "pilot" | "replay";Who played a trace.
Variables
HEADS
ts
const HEADS: readonly Head[];The action heads, in order.
move: nine classes,(x + 1) * 3 + (y + 1)for x right and y forward in-1..1.turn: five classes, the camera turned hard left, left, not at all, right, hard right.jump,primary,sprint,use: held or not.useisE, the templates' interact key.
OBS_SIZE
ts
const OBS_SIZE: number;Floats in one observation.
OBS_VERSION
ts
const OBS_VERSION: 3 = 3;The observation layout's version, stored in every trace and policy.
PACKAGE
ts
const PACKAGE: "@gameable/wasm-host";Package identity marker.
Example
ts
import { PACKAGE } from 'gameable/host';
console.log(PACKAGE); // 'gameable/host'Functions
applyCommand()
ts
function applyCommand(adapter, command): void;Dispatch one command to the adapter.
The switch is exhaustive over Command['tag']; adding a case to the WIT variant without adding one here is a compile error, which is exactly what should happen.
Parameters
| Parameter | Type | Description |
|---|---|---|
adapter | EngineAdapter | The engine. |
command | Command | The command. |
Returns
void
Nothing.
Example
ts
import { applyCommand } from 'gameable/host';
for (const command of out.commands) applyCommand(adapter, command);applyOutput()
ts
function applyOutput(adapter, out): void;Apply a whole frame-output.
Parameters
| Parameter | Type | Description |
|---|---|---|
adapter | EngineAdapter | The engine. |
out | FrameOutput | The guest's output for this frame. |
Returns
void
Nothing.
Example
ts
import { applyOutput } from 'gameable/host';
applyOutput(adapter, sandbox.tick(input));copyInputState()
ts
function copyInputState(state, snapshot): void;Copy the input module's state into the encoder's shape.
The two differ in exactly two places: the key bitsets are named keysDown / keysPressed / keysReleased rather than down / pressed / released, and mods is a bitfield rather than a record.
Parameters
| Parameter | Type | Description |
|---|---|---|
state | InputState | The input module's published state. |
snapshot | InputSnapshot | The snapshot to rewrite. |
Returns
void
Nothing.
createCutsceneBridge()
ts
function createCutsceneBridge(options): CutsceneBridge;Make the bridge.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CutsceneBridgeOptions | See CutsceneBridgeOptions. |
Returns
The bridge; pass bridge.handle as the adapter's cutscene option.
Example
ts
import { createCutsceneBridge } from 'gameable/host';
const cutscenes = createCutsceneBridge({ engine, events: adapter.events, mixer: engine.get('audio') });
// createEngineAdapter({ ..., cutscene: cutscenes.handle })
cutscenes.handle({ action: 'preload', asset: engine.assets.resolve('kael-falls'), fadeInMs: 0, fadeOutMs: 0, skippable: true, pause: true });createDirectSandbox()
ts
function createDirectSandbox(options): Sandbox;Build a direct-mode sandbox, synchronously.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | DirectSandboxOptions | The game definition and host services. |
Returns
A sandbox running the SDK runtime in this realm.
Example
ts
import { createDirectSandbox } from 'gameable/host';
const sandbox = createDirectSandbox({ mode: 'direct', game, host });createDomHud()
ts
function createDomHud(options?): HudRenderer;Create the default DOM HUD.
The renderer is deliberately dumb: it knows four keys and draws them the same way for every game. A game that wants its own look passes its own renderer to createEngineAdapter({ hud }), or turns this one off with { hud: false } and reads adapter.hudModel itself.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | DomHudOptions | Container, document and root class name. |
Returns
A renderer, already attached to its container.
Example
ts
import { createDomHud } from 'gameable/host';
const hud = createDomHud();
hud.set(JSON.stringify({ text: { ammo: 12 }, crosshair: true }));createDomUi()
ts
function createDomUi(options): UiRenderer;Create a retained, themed DOM UI with pointer-based drag and drop.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | { className?: string; container?: UiElement; document?: UiDocument; onEvent: (event) => void; } | DOM overrides and the event sink. |
options.className? | string | Root class, defaulting to aos-ui. |
options.container? | UiElement | Parent for the overlay, defaulting to document.body. |
options.document? | UiDocument | Element factory, defaulting to the browser document. |
options.onEvent | (event) => void | Sink for player interactions. |
Returns
An attached renderer.
Example
ts
import { createDomUi } from 'gameable/host';
const ui = createDomUi({ onEvent: console.log });
ui.set(JSON.stringify({ nodes: [{ type: 'button', id: 'play', text: 'Play' }] }));createEditor()
ts
function createEditor(): Editor;Make an editor. The host loop does this and publishes it.
Returns
The editor, not yet attached.
Example
ts
import { createEditor, publishEditor } from 'gameable/host';
publishEditor(createEditor());createEngineAdapter()
ts
function createEngineAdapter(engine, options?): EngineAdapterHandle;Parameters
| Parameter | Type |
|---|---|
engine | Engine |
options | EngineAdapterOptions |
Returns
createEngineHost()
ts
function createEngineHost(
engine,
adapter,
options?
): HostApi;Build the HostApi a browser sandbox imports.
These are the only synchronous calls the guest may make during tick: three physics queries and two init-time manifest lookups. Everything else the guest wants is a command, applied after it returns. The queries themselves are HostQueries, shared with the server's createServerHost; this wrapper only says where the page's physics, bodies and assets come from.
Physics is looked up lazily, on the first query that finds it registered, so the host can be built before the engine boots.
Parameters
| Parameter | Type | Description |
|---|---|---|
engine | Engine | The booted engine. |
adapter | EngineAdapterHandle | The adapter, for the body-to-entity mapping queries report. |
options | HostQueriesOptions | Seed, log sink and query capacity. |
Returns
A HostApi to hand to createSandbox.
Example
ts
import { createEngineAdapter, createEngineHost, createSandbox } from 'gameable/host';
const adapter = createEngineAdapter(engine, { modules });
const host = createEngineHost(engine, adapter, { seed: 1 });
const sandbox = await createSandbox({ mode: 'direct', game, host });createGameSlot()
ts
function createGameSlot(order?): GameSlot;Reserve the game module's place in the module order.
createEngine wants its module list up front, and the game module wants the booted engine — the adapter needs engine.graph, the host bindings need engine.assets. Rather than make every application shell invent a way round that, the slot registers a module that does nothing until GameSlot.attach hands it the real one.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
order | number | -50 | Module order. Defaults to -50: after input, before physics, matching createHostLoop. The slot's order is the one that counts — the engine sorts the placeholder, not the loop attached to it. |
Returns
The slot.
Example
ts
import { createGameSlot, createHostLoop } from 'gameable/host';
const slot = createGameSlot();
const engine = await createEngine({ canvas, manifest, modules: [...modules, slot.module] });
await slot.attach(createHostLoop(engine, sandbox, adapter), engine.ctx);createHostLoop()
ts
function createHostLoop(
engine,
sandbox,
adapter,
options?
): EngineModule & object;The game module: one fixed step is one guest tick.
Order -50: after input, before physics. The guest therefore ticks on the freshest input there is, and the move-character, apply-impulse and set-body-velocity commands it emits are simulated by the physics step in the same fixed step rather than the next one. That is one whole step of input latency gone — the difference between a jump landing on the frame the key went down and a frame later.
The bodies the guest reads are still post-step rows, one step old: exactly the state it reacted to when it emitted those commands. They arrive on the physics:stepped event, which this module subscribes to in init — the same handler writes each row onto the entity it drives through EngineAdapterHandle.applyBodyRows, so a physics-driven object gets to the screen without its transform ever crossing the wasm boundary.
Its update hands the interpolation factor to the adapter, which is what makes a 60 Hz simulation look smooth on a 144 Hz display.
The first failure latches: a dead sandbox is not retried, because a trapped component instance stays poisoned. The overlay says so.
With guestWorker: true, pass wasm sandbox options instead of an already instantiated sandbox. The guest and Jolt then boot in a supervised worker; the page keeps input and presentation. A character bridge retains the page loop and reports GAMEABLE_GUEST_WORKER_UNSUPPORTED once.
Parameters
| Parameter | Type | Description |
|---|---|---|
engine | Engine | The booted engine. |
sandbox | Sandbox | WasmSandboxOptions | The guest from createSandbox, or deferred wasm options for worker boot. |
adapter | EngineAdapterHandle | The adapter from createEngineAdapter. |
options | HostLoopOptions | Seed, capacity and the death handler. |
Returns
EngineModule & object
A module to register with createEngine.
Example
ts
import { createHostLoop } from 'gameable/host';
const game = createHostLoop(engine, sandbox, adapter, { seed: 1n });
engine.modules.register(game); // or pass it in createEngine({ modules })createInputEncoder()
ts
function createInputEncoder(maxBodies?): InputEncoder;Create a reusable frame-input builder.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
maxBodies | number | 4096 | Initial hint for the memoised view table — not a ceiling. A frame with more rows than this still reaches the guest whole; the hint only decides how many subarray views are preallocated, and the table grows with the game. |
Returns
An encoder that reuses one frame-input record.
Example
ts
import { createInputEncoder } from 'gameable/host';
const encoder = createInputEncoder(2048);
const input = encoder.encode({ frame, dt, elapsed, inputState, bodies, bodyCount });createInputSnapshot()
ts
function createInputSnapshot(): InputSnapshot;A zeroed snapshot, the one a host loop rewrites every fixed step.
Returns
A fresh snapshot.
createLoadOrder()
ts
function createLoadOrder(options?): LoadOrder;Create the loading order.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | LoadOrderOptions | See LoadOrderOptions. |
Returns
The order; hand order.fetch to whatever loads packages.
Example
ts
import { createLoadOrder } from 'gameable/host';
const order = createLoadOrder({ order: ['char.hero', 'char.player'] });
const ticket = order.begin(1, 'char.hero', 'characters/hero/character.json');
console.log(ticket.progress.state, order.progress.characters.length); // 'waiting' 1createPlaytest()
ts
function createPlaytest(meta?): PlaytestController;Make a playtest controller. The page's host loop makes one for itself; make your own only to hand it to createHostLoop({ playtest }).
Parameters
| Parameter | Type | Description |
|---|---|---|
meta | Record<string, string> | What every trace says about the game. |
Returns
The controller.
Example
ts
import { createPlaytest } from 'gameable/host';
const playtest = createPlaytest({ game: 'stomp-to-the-top' });
playtest.on((notice) => {
if (notice.type === 'event') console.log(notice.event.kind, notice.event.note);
});createSandbox()
ts
function createSandbox(options): Promise<Sandbox>;Build a sandbox in either mode.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | SandboxOptions | Direct or wasm configuration. |
Returns
Promise<Sandbox>
The sandbox, once the component (if any) is instantiated.
Example
ts
import { createSandbox } from 'gameable/host';
const sandbox = await createSandbox({
mode: 'wasm',
guestModuleUrl: new URL('./guest/game.js', import.meta.url),
getCoreModule: (p) => fetch(new URL(p, base)).then((r) => WebAssembly.compileStreaming(r)),
getCoreBytes: (p) => fetch(new URL(p, base)).then(async (r) => new Uint8Array(await r.arrayBuffer())),
host,
});decodeTrace()
ts
function decodeTrace(bytes): Trace;Bytes back into a trace.
Parameters
| Parameter | Type | Description |
|---|---|---|
bytes | Uint8Array | What encodeTrace made. |
Returns
The trace.
Throws
When the bytes are not a trace, or of another observation layout.
editorOf()
ts
function editorOf(): Editor | null;The page's editor, when a game is running.
Returns
Editor | null
The editor, or null.
Example
ts
import { editorOf } from 'gameable/host';
await editorOf()?.enter();encodeTrace()
ts
function encodeTrace(trace): Uint8Array;A trace as bytes.
Parameters
| Parameter | Type | Description |
|---|---|---|
trace | Trace | The trace. |
Returns
Uint8Array
Its bytes.
Example
ts
const bytes = encodeTrace(trace);
const again = decodeTrace(bytes);gunzip()
ts
function gunzip(bytes): Promise<Uint8Array<ArrayBufferLike>>;Gunzip bytes in the page (DecompressionStream).
Parameters
| Parameter | Type | Description |
|---|---|---|
bytes | Uint8Array | Gzipped bytes. |
Returns
Promise<Uint8Array<ArrayBufferLike>>
The bytes.
gzip()
ts
function gzip(bytes): Promise<Uint8Array<ArrayBufferLike>>;Gzip bytes in the page (CompressionStream).
Parameters
| Parameter | Type | Description |
|---|---|---|
bytes | Uint8Array | The bytes. |
Returns
Promise<Uint8Array<ArrayBufferLike>>
The gzipped bytes.
hostBindings()
ts
function hostBindings(host): HostBindings;Adapt a HostApi to the import object instantiate expects.
Parameters
| Parameter | Type | Description |
|---|---|---|
host | HostApi | The host services. |
Returns
The gameable:engine/* import object, with unversioned keys.
Example
ts
import { hostBindings, minimalWasi } from 'gameable/host';
const root = await instantiate(getCoreModule, {
...minimalWasi(),
...hostBindings(host),
});loadKindOf()
ts
function loadKindOf(url): LoadKind;The file kind of a package file, by its name.
Parameters
| Parameter | Type | Description |
|---|---|---|
url | string | The file's URL. |
Returns
Its lane.
minimalWasi()
ts
function minimalWasi(options?): Record<string, unknown>;Build the wasi:* half of the import object.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | MinimalWasiOptions | Stderr sink and clock overrides. |
Returns
Record<string, unknown>
An object keyed by unversioned WASI interface name.
Example
ts
import { minimalWasi } from 'gameable/host';
const imports = { ...minimalWasi(), ...hostBindings(host) };NullEngineAdapter()
ts
function NullEngineAdapter(options?): NullAdapter;An adapter that records every call and does nothing else.
The node-side stand-in for the real engine: boundary tests assert on calls, and deepCopy is deliberately absent, because the whole point is that the guest reuses its command objects.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | { appliesLocal?: boolean; } | What the adapter says about itself. |
options.appliesLocal? | boolean | False to stand in for a replica, which skips localCommands. Defaults to true. |
Returns
A recording adapter.
Example
ts
import { NullEngineAdapter } from 'gameable/host';
const adapter = NullEngineAdapter();
applyOutput(adapter, out);
console.log(adapter.by('spawn').length);onStart()
ts
function onStart(fn): () => void;Register what the page's Play does. Handlers run once in registration order. The first handler runs synchronously, preserving a player's browser gesture.
Parameters
| Parameter | Type | Description |
|---|---|---|
fn | StartHandler | Hide the title and optionally unlock audio or pointer lock for a player. |
Returns
Unregister the handler when the page is disposed.
() => void
Example
ts
import { onStart, startGame } from 'gameable/host';
onStart(({ reason }) => {
document.querySelector('#title')?.remove();
if (reason === 'player') document.querySelector('canvas')?.requestPointerLock();
});
document.querySelector('#play')?.addEventListener('click', () => { void startGame(); });playtestOf()
ts
function playtestOf(): PlaytestController | null;The page's playtest, when a game is running.
Returns
PlaytestController | null
The controller, or null.
Example
ts
import { playtestOf } from 'gameable/host';
playtestOf()?.record();projectToScreen()
ts
function projectToScreen(
viewProjection,
x,
y,
z,
width,
height,
out
): boolean;Project a world point through a column-major view-projection matrix into CSS pixels. Writes into the caller's scratch object; points behind the camera leave it unchanged.
Parameters
| Parameter | Type | Description |
|---|---|---|
viewProjection | ArrayLike<number> | Column-major 4x4 view-projection matrix. |
x | number | World x. |
y | number | World y. |
z | number | World z. |
width | number | View width in CSS pixels. |
height | number | View height in CSS pixels. |
out | { x: number; y: number; } | Reusable output point. |
out.x | number | Receives the horizontal coordinate in CSS pixels. |
out.y | number | Receives the vertical coordinate in CSS pixels. |
Returns
boolean
False when clip w is nonpositive, otherwise true.
Example
ts
import { projectToScreen } from 'gameable/host';
const matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
const point = { x: 0, y: 0 };
projectToScreen(matrix, 0, 0, 0, 800, 600, point);
console.log(point); // { x: 400, y: 300 }publishEditor()
ts
function publishEditor(editor): void;Publish an editor as the page's. The host loop does this.
Parameters
| Parameter | Type | Description |
|---|---|---|
editor | Editor | The editor. |
Returns
void
Example
ts
import { createEditor, publishEditor } from 'gameable/host';
publishEditor(createEditor());publishPlaytest()
ts
function publishPlaytest(controller): void;Publish a controller as the page's playtest. The host loop does this.
Parameters
| Parameter | Type | Description |
|---|---|---|
controller | PlaytestController | The controller. |
Returns
void
Example
ts
import { createPlaytest, publishPlaytest } from 'gameable/host';
publishPlaytest(createPlaytest());quantizeInput()
ts
function quantizeInput(input): HostFrameInput;Round every f32 field of a frame-input in place.
bodies is already a Float32Array, so it needs nothing. frame is a u64 and focused a bool; only the timing, mouse, gamepad, event and contact floats can differ.
Parameters
| Parameter | Type | Description |
|---|---|---|
input | HostFrameInput | The frame input to normalise. Mutated in place where it can be, which is every field the host encoder owns. |
Returns
The same object.
Example
ts
import { quantizeInput } from 'gameable/host';
sandbox.tick(quantizeInput(encoder.encode(args)));quantizeSeed()
ts
function quantizeSeed(seed): bigint;Round a game-config's floats. There are none today, but the seed must be a bigint and the counts integers; this is the hook if the record grows.
Parameters
| Parameter | Type | Description |
|---|---|---|
seed | number | bigint | The seed as the host holds it. |
Returns
bigint
The same value, as a bigint.
Example
ts
import { quantizeSeed } from 'gameable/host';
const seed = quantizeSeed(0x5eed1234n);startGame()
ts
function startGame(opts?): Promise<void>;Run Play once, queue the guest's start event, then wait for two rendered frames. Repeated calls resolve immediately, including while the first call is pending. With no handlers the guest still starts. Handler failures reject the first call; later calls still resolve immediately.
Parameters
| Parameter | Type | Description |
|---|---|---|
opts | StartOptions | The reason, available to each page handler. |
Returns
Promise<void>
Completion of Play and two subsequent rendered frames.
Example
ts
import { startGame } from 'gameable/host';
await startGame({ reason: 'capture' });summarise()
ts
function summarise(header): PlaytestSummary;Sum a run up.
Parameters
| Parameter | Type | Description |
|---|---|---|
header | RunEvents | The trace's header (its events, steps and rate). |
Returns
The summary.
Example
ts
const summary = summarise(trace.header);
console.log(summary.findings.join('\n'));summariseAll()
ts
function summariseAll(headers): PlaytestSummary;Several runs' summaries as one: the counts added, the spots merged.
Parameters
| Parameter | Type | Description |
|---|---|---|
headers | readonly RunEvents[] | The runs. |
Returns
One summary.
trainBehaviourCloning()
ts
function trainBehaviourCloning(traces, options?): Promise<TrainResult>;Teach a policy the examples in some traces.
Parameters
| Parameter | Type | Description |
|---|---|---|
traces | readonly Trace[] | What people (or the agent) did. |
options | TrainOptions | How to train. |
Returns
Promise<TrainResult>
The policy, and how well it learned.
Throws
When there is nothing to learn from.
Example
ts
const { policy, progress } = await trainBehaviourCloning(traces, { epochs: 15 });
console.log(progress.moveAccuracy);