Appearance
@bendyline/molen-client
Molen rendering client: three.js wrapper, snapshot sync, interpolation.
ts
import { /* … */ } from '@bendyline/molen-client';Classes
AdaptiveQualityController
Rendering-only feedback controller; does not change simulation state or depend on a browser. Lower quickly, recover slowly, and probe with backoff instead of oscillating between tiers. Hosts should apply a change atomically to resolution, screen-space error, and residency.
Constructors
Constructor
ts
new AdaptiveQualityController(options?): AdaptiveQualityController;Parameters
options?
Returns
Methods
getStats()
ts
getStats(): AdaptiveQualityStats;Returns
sample()
ts
sample(frameMs, sample?): AdaptiveQualityChange | undefined;No allocation in the usual per-frame path. A change object is returned only on a step.
Parameters
frameMs
number
sample?
Returns
AdaptiveQualityChange | undefined
setBounds()
ts
setBounds(minLevel, maxLevel): AdaptiveQualityChange | undefined;Change a user/device ceiling and floor; an out-of-bounds current level is clamped.
Parameters
minLevel
number
maxLevel
number
Returns
AdaptiveQualityChange | undefined
setLevel()
ts
setLevel(level): AdaptiveQualityChange | undefined;Set a manual tier or restart automatic adaptation without carrying stale timing samples.
Parameters
level
number
Returns
AdaptiveQualityChange | undefined
AssetCache
Parse each glTF ref once; hand out per-entity instances (SkeletonUtils.clone so skinned meshes work while geometry/textures stay shared). whenIdle() resolves when no loads are pending — the capture path awaits it before its single deterministic frame.
Constructors
Constructor
ts
new AssetCache(provider, loader): AssetCache;Parameters
provider
loader
GLTFLoader
Returns
Methods
clear()
ts
clear(): void;Returns
void
dispose()
ts
dispose(): void;Returns
void
instance()
ts
instance(ref, node?): Promise<LoadedGltf>;A fresh instance of the (sub-)scene for one entity.
Parameters
ref
string
node?
string
Returns
Promise<LoadedGltf>
track()
ts
track<T>(p): Promise<T>;Register an external async task (e.g. a material bake) so whenIdle() waits for it.
Type Parameters
T
T
Parameters
p
Promise<T>
Returns
Promise<T>
whenIdle()
ts
whenIdle(): Promise<void>;Resolves once every load kicked off so far has settled.
Returns
Promise<void>
FrameAdmissionQueue
Implements
Constructors
Constructor
ts
new FrameAdmissionQueue(options?): FrameAdmissionQueue;Parameters
options?
Returns
Accessors
pending
Get Signature
ts
get pending(): number;Jobs waiting, where the queue can say, so optional work can hold off behind a backlog.
Returns
number
Jobs waiting, where the queue can say, so optional work can hold off behind a backlog.
Implementation of
Methods
dispose()
ts
dispose(): void;Returns
void
flush()
ts
flush(): void;One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests.
A job cannot be split, so one can take several frames' budget by itself, and a queue of them would hold every frame at that length however small the budget. A frame that overruns repays the excess from the frames after it, so the budget holds on average: a 20 ms shader build every third frame, rather than every frame at half the frame rate, for the same throughput.
The budget is a share of a frame at 60 a second. A frame that comes later than that repays the same share of its own length: under software rendering a frame takes 200 ms or more, and a job that waits on the GPU once is charged for a whole such frame, so repaying 2 ms a frame left the queue idle for minutes. At 60 frames a second and faster nothing changes. Sustained frames that slow also run that share of themselves (see SLOW_FRAME_MS).
Returns
void
promote()
ts
promote(promise, options?): void;Move a still-queued background job to the normal lane, behind the jobs already there, or with front ahead of them: for work a frame is waiting on, such as a material an object holds off switching to until it is prepared.
Parameters
promise
Promise<unknown>
options?
front?
boolean
Returns
void
run()
ts
run<T>(task, options?): Promise<T>;Type Parameters
T
T
Parameters
task
() => T
options?
Returns
Promise<T>
Implementation of
setLimits()
ts
setLimits(limits): void;Change the per-frame budget from the next frame on; omitted limits keep their values. A host can admit more when frames have time to spare (an adaptive quality tier, say). backlog is replaced when the key is present: undefined takes the backlog budget away.
Parameters
limits
Pick<FrameAdmissionOptions, "maxMilliseconds" | "maxBytes" | "maxJobs" | "backlog">
Returns
void
setPaused()
ts
setPaused(paused): void;Hold queued uploads/preparation while the view is inactive; keep resources for resume.
Parameters
paused
boolean
Returns
void
InputMap
Keyboard/mouse + browser controllers mapped to numeric named actions. Call update() each frame (applyInputRules does this on its poller). Profiles are complete replacements.
Constructors
Constructor
ts
new InputMap(opts): InputMap;Parameters
opts
Returns
Accessors
activeProfile
Get Signature
ts
get activeProfile(): string | undefined;Returns
string | undefined
gamepadStatus
Get Signature
ts
get gamepadStatus(): "available" | "unavailable" | "blocked";Returns
"available" | "unavailable" | "blocked"
Methods
activeActions()
ts
activeActions(): Set<string>;Returns
Set<string>
clearVirtual()
ts
clearVirtual(source?): void;Release every action a software control drives (all controls when source is omitted).
Parameters
source?
string
Returns
void
defineProfile()
ts
defineProfile(name, profile): void;Atomically validate and replace bindings; no held button becomes a new action.
Parameters
name
string | undefined
profile
InputProfile
Returns
void
devices()
ts
devices(): InputGamepad[];Snapshot of all detected devices and raw values, suitable for an axis/button inspector.
Returns
dispose()
ts
dispose(): void;Returns
void
getProfile()
ts
getProfile(...selection): InputProfile;Detached, serializable copy for custom editors and host-managed persistence.
Parameters
selection
...[string]
Returns
InputProfile
hasAxis()
ts
hasAxis(action): boolean;Whether an enabled, connected axis supplies this action, including a zero reading.
Parameters
action
string
Returns
boolean
isActive()
ts
isActive(action): boolean;Parameters
action
string
Returns
boolean
onChange()
ts
onChange(handler): Unsubscribe;Action values changed (including neutralization on reset/profile switch).
Parameters
handler
() => void
Returns
Unsubscribe
onPress()
ts
onPress(action, handler): Unsubscribe;Parameters
action
string
handler
(action) => void
Returns
Unsubscribe
onProfilesChanged()
ts
onProfilesChanged(handler): Unsubscribe;Profile selection or definitions changed.
Parameters
handler
() => void
Returns
Unsubscribe
onRelease()
ts
onRelease(action, handler): Unsubscribe;Parameters
action
string
handler
(action) => void
Returns
Unsubscribe
onReset()
ts
onReset(handler): Unsubscribe;Explicit neutralization on reset, focus loss, suspension or profile replacement.
Parameters
handler
() => void
Returns
Unsubscribe
press()
ts
press(code): void;Parameters
code
string
Returns
void
profileNames()
ts
profileNames(): string[];Returns
string[]
release()
ts
release(code): void;Parameters
code
string
Returns
void
reset()
ts
reset(): void;Release actions immediately; suppress held physical buttons until released.
Returns
void
setEnabled()
ts
setEnabled(enabled): void;Suspend while editing a form/menu; device discovery continues during update().
Parameters
enabled
boolean
Returns
void
setProfile()
ts
setProfile(name): void;Undefined selects the root bindings. Held keys/buttons must be released before reuse.
Parameters
name
string | undefined
Returns
void
setVirtual()
ts
setVirtual(
source,
action,
value
): void;Drive an action from a software control such as a touch joystick or an on-screen button. source names the control so several can feed one action; like every device, the strongest contribution wins. A value persists until changed, clearVirtual, or a reset (focus loss, suspension, profile switch), and is ignored while input is not accepted.
Parameters
source
string
action
string
value
number
Returns
void
suspend()
ts
suspend(): Unsubscribe;Temporarily suppress gameplay while a remapping UI is open; returned release is idempotent.
Returns
Unsubscribe
update()
ts
update(): void;Poll fresh browser objects; unplugging or losing permission releases affected controls.
Returns
void
value()
ts
value(action): number;Numeric action value; strongest absolute contribution wins, keyboard wins ties.
Parameters
action
string
Returns
number
InstanceBatch
An InstancedMesh whose instances live in a geometry of its own, so WebGPU builds its shaders once for every batch of the same material and model layout instead of once per batch.
Three's WebGPU renderer keys an instanced mesh's node build by the mesh, since its instance matrices are a node bound to that mesh's buffer: every batch streamed in paid a build of its own, about 10 ms of main thread each, which was most of a flight's streaming work. A batch instead carries its matrices and colors as instanced vertex attributes of an InstancedBufferGeometry that shares the model geometry's buffers, and the WebGPU driver reads them by name, the way it reads position: one build serves every batch, and each draw binds its own batch's vertex buffers, which a recorded render bundle replays as recorded. WebGL draws it as the InstancedMesh it is, with no setup, through three's own instancing.
It keeps InstancedMesh's API: count, setMatrixAt, setColorAt, bounds, raycasting and dispose. Assigning geometry selects the model it draws (a level of detail can swap it each frame without a new build, as long as the models share an attribute layout); geometry then reads back as the batch's own geometry and sourceGeometry as the model. Set colors before the first draw: a batch drawn without colors keeps its build. Models with morph targets are not supported.
Extends
InstancedMesh<THREE.BufferGeometry,TMaterial>
Type Parameters
TMaterial
TMaterial extends THREE.Material | THREE.Material[] = THREE.Material | THREE.Material[]
Constructors
Constructor
ts
new InstanceBatch<TMaterial>(
geometry,
material,
count
): InstanceBatch<TMaterial>;Parameters
geometry
BufferGeometry
material
TMaterial
count
number
Returns
InstanceBatch<TMaterial>
Overrides
ts
THREE.InstancedMesh<THREE.BufferGeometry, TMaterial>.constructorProperties
isInstanceBatch
ts
readonly isInstanceBatch: true;Accessors
sourceGeometry
Get Signature
ts
get sourceGeometry(): BufferGeometry;The model geometry this batch draws (what geometry was last set to).
Returns
BufferGeometry
Methods
batchGeometries()
ts
batchGeometries(): BufferGeometry<NormalBufferAttributes, BufferGeometryEventMap>[];Every geometry of this batch's own, one per model it has drawn.
Returns
BufferGeometry<NormalBufferAttributes, BufferGeometryEventMap>[]
copy()
ts
copy(source, recursive?): this;Copies the given object into this object.
Parameters
source
InstanceBatch<TMaterial>
recursive?
boolean
If set to true, descendants of the object are copied next to the existing ones. If set to false, descendants are left unchanged. Default is true.
Returns
this
Remarks
Event listeners and user-defined callbacks (.onAfterRender and .onBeforeRender) are not copied.
Overrides
ts
THREE.InstancedMesh.copydispose()
ts
dispose(): this;Release the batch's buffers. Its own geometries are released with it, but not the model geometry's buffers, which other batches share: a disposed batch is not drawn again.
Returns
this
Overrides
ts
THREE.InstancedMesh.disposesetInstanceMatrices()
ts
setInstanceMatrices(matrices): this;Draw the instances in matrices, sixteen floats each as Matrix4.elements lays them out. The batch takes the array over; set count to match.
Parameters
matrices
Float32Array
Returns
this
InstanceMatrixAttribute
A batch's instance matrices: one interleaved buffer that WebGL reads as a mat4 attribute and WebGPU as four vec4 columns, so either backend uploads it once. It keeps the version and usage an InstancedBufferAttribute reports, which its buffer holds.
Extends
InterleavedBufferAttribute
Constructors
Constructor
ts
new InstanceMatrixAttribute(buffer): InstanceMatrixAttribute;Parameters
buffer
InstancedInterleavedBuffer
Returns
Overrides
ts
THREE.InterleavedBufferAttribute.constructorProperties
isInstanceMatrixAttribute
ts
readonly isInstanceMatrixAttribute: true = true;Accessors
updateRanges
Get Signature
ts
get updateRanges(): object[];Returns
object[]
usage
Get Signature
ts
get usage(): Usage;Returns
Usage
version
Get Signature
ts
get version(): number;Returns
number
Methods
addUpdateRange()
ts
addUpdateRange(start, count): void;Parameters
start
number
count
number
Returns
void
clearUpdateRanges()
ts
clearUpdateRanges(): void;Returns
void
setUsage()
ts
setUsage(usage): this;Parameters
usage
Usage
Returns
this
InterpolationBuffer
Holds a small ring of recent per-tick transform snapshots and samples interpolated transforms ~delayTicks behind the latest tick. Never extrapolates: clamps to the latest known transform when ahead of the buffer.
Constructors
Constructor
ts
new InterpolationBuffer(tickRate, opts?): InterpolationBuffer;Parameters
tickRate
number
opts?
capacity?
number
delayTicks?
number
Returns
Properties
delayTicks
ts
readonly delayTicks: number;tickRate
ts
readonly tickRate: number;Accessors
lastSampleVisited
Get Signature
ts
get lastSampleVisited(): number;Returns
number
latestTick
Get Signature
ts
get latestTick(): number | undefined;Returns
number | undefined
size
Get Signature
ts
get size(): number;Number of snapshots currently held (≤ capacity).
Returns
number
Methods
activate()
ts
activate(id): void;Reapply a static pose after a render/light binding changes without a transform delta.
Parameters
id
string
Returns
void
clear()
ts
clear(): void;Returns
void
estimateRenderTick()
ts
estimateRenderTick(nowMs): number | undefined;Estimate the render tick for a wall-clock time from the smoothed clock, minus the delay. Never runs ahead of the newest tick held (sampling clamps there anyway) and never steps backwards between calls, so a late delta cannot reverse motion mid-flight.
Parameters
nowMs
number
Returns
number | undefined
latestIds()
ts
latestIds(): string[];Ids present in the most recent snapshot.
Returns
string[]
push()
ts
push(
tick,
transforms,
recvMs
): void;Record the transforms present at a kernel tick. recvMs is the local receive time.
Parameters
tick
number
transforms
Map<string, InterpTransform>
recvMs
number
Returns
void
pushDelta()
ts
pushDelta(
tick,
changes,
recvMs
): void;Record a contiguous sparse update. Unmentioned entities keep their previous transform.
Parameters
tick
number
changes
Map<string, InterpTransform | undefined>
recvMs
number
Returns
void
resumeClock()
ts
resumeClock(nowMs): void;Resume wall-clock playback after an intentional pause, retaining poses and the render floor.
Parameters
nowMs
number
Returns
void
sample()
ts
sample(nowMs, id): InterpTransform | undefined;Sample for a wall-clock time using the estimated render tick.
Parameters
nowMs
number
id
string
Returns
InterpTransform | undefined
sampleActive()
ts
sampleActive(nowMs, apply): void;Visit only changed/interpolating entities; send the final pose once before retiring it.
Parameters
nowMs
number
apply
(id, transform) => void
Returns
void
sampleAt()
ts
sampleAt(renderTick, id): InterpTransform | undefined;Sample an entity's interpolated transform at an explicit render tick (the tested core).
Parameters
renderTick
number
id
string
Returns
InterpTransform | undefined
MaterialResolver
Resolves materialRef strings to three.js materials. Sync for palette:; doc-backed refs (matgraph:/pixelgrid:) load + bake asynchronously. Every ref string maps to ONE cached material shared by all entities using it; acquire*/release refcount those so a material (and its textures) is disposed exactly when its last user lets go.
Constructors
Constructor
ts
new MaterialResolver(provider?, baker?): MaterialResolver;An optional caller-owned worker baker keeps procedural rasterization off the UI thread.
Parameters
provider?
baker?
MaterialBaker
Returns
Methods
acquire()
ts
acquire(materialRef): Promise<Material<MaterialEventMap>>;resolve plus one reference; pair with release.
Parameters
materialRef
string
Returns
Promise<Material<MaterialEventMap>>
acquireSync()
ts
acquireSync(materialRef): Material;resolveSync plus one reference; pair with release.
Parameters
materialRef
string | undefined
Returns
Material
dispose()
ts
dispose(): void;Returns
void
isAsync()
ts
isAsync(materialRef): boolean;Is this a doc-backed ref that resolves asynchronously?
Parameters
materialRef
string | undefined
Returns
boolean
release()
ts
release(material): void;Drop one reference; at zero the material (and its textures) is disposed and evicted from the cache. Materials not handed out by acquire* are ignored.
Parameters
material
Material
Returns
void
resolve()
ts
resolve(materialRef): Promise<Material<MaterialEventMap>>;Async resolution for doc-backed refs; falls back to grey (with one warning) when the doc is missing/invalid so a bad ref never blanks the scene.
Parameters
materialRef
string
Returns
Promise<Material<MaterialEventMap>>
resolveSync()
ts
resolveSync(materialRef): Material;Sync resolution: palette refs (and the shared grey fallback for unknown/absent refs).
Parameters
materialRef
string | undefined
Returns
Material
Renderer
Thin wrapper over the three.js renderer + scene + camera. The engine owns the single construction path so capture settings (pixel ratio, AA, tone mapping) are deterministic. The backend option selects WebGPU or WebGL — see docs-src/guide/rendering-backends.md.
Constructors
Constructor
ts
new Renderer(opts?, initialized?): Renderer;Parameters
opts?
initialized?
InitializedRenderer
Returns
Properties
admission
ts
readonly admission: FrameAdmissionQueue;backend
ts
readonly backend: RendererBackend;camera
ts
camera: PerspectiveCamera | OrthographicCamera;defaultClearColor
ts
readonly defaultClearColor: Color;scene
ts
readonly scene: Scene;three
ts
readonly three: ThreeRenderer;worldRoot
ts
readonly worldRoot: Group;World-space objects live here so the renderer can rebase them near the camera.
Accessors
cloudQuality
Get Signature
ts
get cloudQuality(): CloudQuality;Returns
deviceLost
Get Signature
ts
get deviceLost(): string | undefined;The WebGPU device-loss reason once the device is gone (undefined while it is live). Every later render() throws, so a frame loop stops here instead of failing once per frame.
Returns
string | undefined
fallbackReason
Get Signature
ts
get fallbackReason(): string | undefined;Returns
string | undefined
farShadowInfo
Get Signature
ts
get farShadowInfo(): FarShadowInfo | undefined;The far shadow map as last drawn, or undefined while there is none.
Returns
FarShadowInfo | undefined
shadowTexelSize
Get Signature
ts
get shadowTexelSize(): number | undefined;Meters one texel of the sun's shadow map covers as of the last frame, or undefined while sun shadows are off or parked. A focus over a wide view coarsens it: hosts use it to keep a subject the map cannot resolve out of the shadow pass (AircraftVisual.updateShadows).
Returns
number | undefined
sky
Get Signature
ts
get sky(): SkyVisual | undefined;Active clear-sky visual and sampled ephemeris, when environment.sky is configured.
Returns
SkyVisual | undefined
softwareRasterizer
Get Signature
ts
get softwareRasterizer(): boolean;Whether this device draws through a software rasterizer: SwiftShader (headless and blocklisted-GPU Chromium), Mesa's llvmpipe or lavapipe, Windows' Basic Render Driver, or a WebGPU fallback adapter. Every pixel and vertex then costs CPU time, so a host that sizes its work to the device starts at its lowest tier. Read once, from the WebGL context's unmasked renderer string (false where the browser hides it) or the WebGPU adapter's fallback flag.
Returns
boolean
weather
Get Signature
ts
get weather(): WeatherVisual | undefined;Active weather effects; physical weather data is also available in the simulation component.
Returns
WeatherVisual | undefined
Methods
createGpuTimer()
ts
createGpuTimer(options?): GpuFrameTimer | undefined;Optional backend-specific GPU timing with the same nonblocking polling interface.
Parameters
options?
Returns
GpuFrameTimer | undefined
createRenderGroup()
ts
createRenderGroup(): Group;Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. WebGL leaves a group out of the scene walks it cannot be seen in, once its owner states its bounds in userData.renderBounds (see RENDER_BOUNDS) and keeps them true as its content changes (expandRenderBounds, markRenderBoundsChanged): see cullRenderGroups.
Returns
Group
dispose()
ts
dispose(): void;Returns
void
getViewportSize()
ts
getViewportSize(): [number, number];Drawing size in CSS pixels as last passed to setSize (before the pixel ratio).
Returns
[number, number]
getWorldOrigin()
ts
getWorldOrigin(): Vec3;Returns
Vec3
prepareMaterialChange()
ts
prepareMaterialChange(current, next): Promise<void>;Build next's shaders for every kind of prepared mesh that draws current, before the caller copies next into current: a progressive material upgrading its placeholder in place once a texture bake lands. Three shares a program between materials built alike, so the upgraded placeholder draws with it at once. Otherwise every mesh showing the placeholder built its new shaders in the next frame, together: seconds of frozen flight shortly after loading. The work runs in the background lane. Keep next alive while current uses the shared program.
Parameters
current
Material
next
Material
Returns
Promise<void>
prepareObject()
ts
prepareObject(
root,
signal?,
parent?
): Promise<void>;Prepare shared resources once; all dependants await the same admission jobs.
With parent (the object this root will be added to), LODs are evaluated for the current camera as if attached: the levels they select are prepared before this resolves, and the other levels afterwards in the background, so publication waits only for what can be seen. Queued work is cancelled once every caller waiting for it has aborted, and background work once its mesh or geometry is disposed.
root.userData.admissionPriority admits the root's own work as 'urgent' (ahead of normal work) or 'background' (only in budget normal work leaves: content nobody waits on yet). root.userData.admissionOrder supplies live normal-lane order (lower first).
Parameters
root
Object3D
signal?
AbortSignal
parent?
Object3D<Object3DEventMap>
Returns
Promise<void>
render()
ts
render(): void;Returns
void
setAmbientOcclusion()
ts
setAmbientOcclusion(enabled, options?): void;Screen-space ambient occlusion on the WebGPU backend (a no-op on WebGL): creases, corners and the ground around buildings and trees darken a little, as indirect light cannot reach them. The frame then renders through a node pipeline; frames draw directly while it compiles.
Parameters
enabled
boolean
options?
AmbientOcclusionOptions
Returns
void
setCamera()
ts
setCamera(pose): void;Pose the perspective camera (leaving top-down ortho mode if it was active).
Parameters
pose
Returns
void
setCameraClip()
ts
setCameraClip(near, far): void;Parameters
near
number
far
number
Returns
void
setCloudQuality()
ts
setCloudQuality(quality): void;Per-pixel cloud work, default 'medium': ray-march steps and light samples, erosion detail from 'high', and from 'high' also cloud shadows on every lit surface. Takes effect on the next frame without rebuilding any shader, so adaptive quality tiers may change it freely.
Parameters
quality
Returns
void
setEnvironmentTime()
ts
setEnvironmentTime(seconds): void;Absolute simulation seconds, shared by live playback, paused snapshots and captures.
Parameters
seconds
number
Returns
void
setEnvironmentTimeOverride()
ts
setEnvironmentTimeOverride(seconds): void;Preview a sky at absolute simulation seconds without seeking the world; undefined resumes its clock.
Parameters
seconds
number | undefined
Returns
void
setFarShadowCasters()
ts
setFarShadowCasters(root): void;The scenery that does not move (a terrain stream's object: ground, buildings, trees), for the sun's far shadow map. With it and a focus that names a far square, surfaces past the focused map are shadowed from a second, wider map instead of ending in sunlight: over a city the focused map ends a few hundred meters out, and buildings gained their shadows as it reached them. Only what is under root casts into it, and it is redrawn when the camera has left its middle, when the sun has moved and about once a second for scenery that has arrived, so a moving caster would leave its shadow behind. WebGL; undefined turns it off.
Parameters
root
Object3D<Object3DEventMap> | undefined
Returns
void
setFov()
ts
setFov(fovDeg): void;Vertical field of view in degrees (perspective camera only; a no-op for ortho).
Parameters
fovDeg
number
Returns
void
setPixelRatio()
ts
setPixelRatio(ratio): void;Update the device pixel ratio after a display change. Three applies the ratio on the next setSize, so callers pair the two (the mount's resize handler does).
Parameters
ratio
number
Returns
void
setShadowFocus()
ts
setShadowFocus(focus): void;Aim the sun's shadow at a focus (absolute world coordinates) covering at least ±radius meters, or undefined for the environment's own fixed box. Call whenever what the camera frames moves: an orbit target, a walker, a car. Shadows must be on (setShadowQuality).
Parameters
focus
ShadowFocus | undefined
Returns
void
setShadowQuality()
ts
setShadowQuality(quality): void;Turn sun shadows on at a map resolution, or off, without rebuilding the environment. Once a light has cast shadows, 'off' stops redrawing its map and fades it out, so every lit shader keeps the shadow inputs it was built with: a host that turns shadows on once before its first frame can then switch them freely (adaptive quality tiers do) without rebuilding a shader.
Parameters
quality
Returns
void
setSize()
ts
setSize(width, height): void;Parameters
width
number
height
number
Returns
void
setStarCatalog()
ts
setStarCatalog(stars): void;Stars for every sky this renderer shows, e.g. decodeStarCatalog of a content pack's molen/stars@1 file. Applies to the current sky at once and survives sky changes; undefined removes the stars.
Parameters
stars
readonly SkyStar[] | undefined
Returns
void
setTopDownOrtho()
ts
setTopDownOrtho(opts): void;Switch to a top-down orthographic camera looking straight down at a world point.
Parameters
opts
Returns
void
setWeather()
ts
setWeather(data): void;Apply the singleton weather component without rebuilding the sky or moving the camera.
Parameters
data
WeatherData | undefined
Returns
void
setWeatherTimeOverride()
ts
setWeatherTimeOverride(seconds): void;Standalone weather preview clock. Undefined follows simulation time, independently of sky seeks.
Parameters
seconds
number | undefined
Returns
void
setWorldOrigin()
ts
setWorldOrigin(origin): void;Shift all engine-owned world objects near the local origin without changing world poses.
Parameters
origin
Vec3
Returns
void
stats()
ts
stats(): object;Last completed visible frame, excluding offscreen resource preparation.
Returns
object
drawCalls
ts
drawCalls: number;triangles
ts
triangles: number;suspendAmbientOcclusion()
ts
suspendAmbientOcclusion(suspended): void;Skip the occlusion computation while keeping ambient occlusion set up: the frame still draws into its target, and the image is copied out unshaded. Each object's shaders are built for one draw target, so turning occlusion off and on again (setAmbientOcclusion) built every object in view again, mid-frame, when the target changed; suspending changes nothing there.
Parameters
suspended
boolean
Returns
void
create()
ts
static create(opts?): Promise<Renderer>;Prefer WebGPU when available; explicit webgpu is strict and never silently falls back.
Parameters
opts?
Returns
Promise<Renderer>
SceneMirror
Maintains a client-side mirror of kernel entities and reconciles renderable bindings against a SceneBackend (create / updateRenderable / destroy). Pure aside from the backend calls, so it is unit-testable with a mock backend.
Reconciliation is incremental: a delta marks the ids it touched dirty and reconcile visits only those (a keyframe forces a full pass), so a 1000-entity scene with one moving entity serializes one renderable per message, not a thousand.
Constructors
Constructor
ts
new SceneMirror(): SceneMirror;Returns
Accessors
lastReconcileVisited
Get Signature
ts
get lastReconcileVisited(): number;How many entity ids the last reconcile examined (all of them after a keyframe).
Returns
number
tick
Get Signature
ts
get tick(): number | undefined;Returns
number | undefined
Methods
applyDelta()
ts
applyDelta(delta): boolean;Apply only a contiguous delta; false means the caller must request a fresh keyframe.
Parameters
delta
Delta
Returns
boolean
applyKeyframe()
ts
applyKeyframe(keyframe): void;Parameters
keyframe
Keyframe
Returns
void
boundIds()
ts
boundIds(): string[];Returns
string[]
components()
ts
components(id): string[];The component names an entity currently carries.
Parameters
id
string
Returns
string[]
entities()
ts
entities(): string[];Every mirrored entity id, in creation order.
Returns
string[]
get()
ts
get(id, component): JsonObject | undefined;A detached copy of one component of a mirrored entity (undefined when absent).
Parameters
id
string
component
string
Returns
JsonObject | undefined
has()
ts
has(id): boolean;Parameters
id
string
Returns
boolean
peek()
ts
peek(id, component): JsonObject | undefined;The stored component object (no copy) for renderers that sample every frame: treat it as frozen. Its identity changes exactly when a delta or keyframe replaced it.
Parameters
id
string
component
string
Returns
JsonObject | undefined
reconcile()
ts
reconcile(backend): void;Create/update/destroy backend objects so they match the mirror's renderables.
Parameters
backend
Returns
void
transformChanges()
ts
transformChanges(delta): Map<string, InterpTransform | undefined>;Extract only transform changes (including removals), before reconciliation clears dirty ids.
Parameters
delta
Delta
Returns
Map<string, InterpTransform | undefined>
transforms()
ts
transforms(): Map<string, InterpTransform>;Extract the transforms present in the mirror (for the interpolation buffer).
Returns
Map<string, InterpTransform>
SkyReflections
One small half-float panorama and filtered target per viewer; no model-specific textures or network fetches. Quantization suppresses imperceptible ephemeris changes and camera motion never invalidates the map. Explicit host-assigned scene.environment textures take priority.
Constructors
Constructor
ts
new SkyReflections(scene, filter): SkyReflections;Parameters
scene
Scene
filter
Returns
Properties
texture
ts
readonly texture: DataTexture;Accessors
active
Get Signature
ts
get active(): boolean;False when a host has replaced the scene environment with its own texture.
Returns
boolean
Methods
dispose()
ts
dispose(): void;Returns
void
update()
ts
update(state): boolean;Parameters
state
Returns
boolean
SkyVisual
Generic clear-sky dome, celestial spheres, batched stars and lighting, using standard materials on WebGL and WebGPU. A separate background scene avoids far-plane, reverse-depth, logarithmic-depth and floating-origin coupling. No textures, shaders or network requests.
Constructors
Constructor
ts
new SkyVisual(data, options?): SkyVisual;Parameters
data
options?
Returns
Properties
ambientLight
ts
readonly ambientLight: HemisphereLight;camera
ts
readonly camera: PerspectiveCamera;data
ts
readonly data: SkyData;lights
ts
readonly lights: Group;moonLight
ts
readonly moonLight: DirectionalLight;scene
ts
readonly scene: Scene;sunLight
ts
readonly sunLight: DirectionalLight;Accessors
frame
Get Signature
ts
get frame(): SkyFrame;Returns
reflectionState
Get Signature
ts
get reflectionState(): SkyReflectionState;Sky radiance for the viewer's shared PBR environment, sampled with the celestial frame.
Returns
Methods
dispose()
ts
dispose(): void;Returns
void
prepareCamera()
ts
prepareCamera(camera): void;Copy view orientation/projection only; celestial bodies never translate with the camera.
Parameters
camera
Camera
Returns
void
setCloudAttenuation()
ts
setCloudAttenuation(value, direct?): void;Diffuse cloud lighting; actual celestial occlusion comes from the cloud layer geometry. direct dims the sun and moon (default value); with spatial cloud shadows it is 0, since the shadows themselves take light away where clouds cover the sun.
Parameters
value
number
direct?
number
Returns
void
setObserver()
ts
setObserver(observer): void;Move an Earth observer without rebuilding the dome, bodies or star catalog.
Parameters
observer
Returns
void
setStars()
ts
setStars(stars): void;Replace the star catalog, e.g. once a catalog loaded from a content pack arrives. undefined removes the stars. Takes effect on the next update.
Parameters
stars
readonly SkyStar[] | undefined
Returns
void
update()
ts
update(simulationSeconds): SkyFrame;Seek in simulation seconds. Earth render samples use a stable one-second UTC grid.
Parameters
simulationSeconds
number
Returns
ThreeSceneBackend
three.js implementation of the SceneBackend: primitives + async glTF instances + lights.
Implements
Constructors
Constructor
ts
new ThreeSceneBackend(
scene,
assets?,
renderer?,
materials?,
optimization?
): ThreeSceneBackend;Parameters
scene
Object3D
assets?
renderer?
materials?
optimization?
Returns
Accessors
threeScene
Get Signature
ts
get threeScene(): Object3D;The three.js world root this backend writes into (escape hatch for custom objects/lights).
Returns
Object3D
Methods
bindMirror()
ts
bindMirror(reader): void;Give custom kinds read access to the mirrored components (no per-frame cloning).
Parameters
reader
Returns
void
count()
ts
count(): number;Returns
number
create()
ts
create(id, renderable): void;Parameters
id
string
renderable
Returns
void
Implementation of
createLight()
ts
createLight(id, data): void;Per-entity light components (directional/spot aim at the origin by default).
Parameters
id
string
data
Returns
void
Implementation of
destroy()
ts
destroy(id): void;Parameters
id
string
Returns
void
Implementation of
destroyLight()
ts
destroyLight(id): void;Parameters
id
string
Returns
void
Implementation of
dispose()
ts
dispose(): void;Returns
void
entityForIntersection()
ts
entityForIntersection(hit): string | undefined;Parameters
hit
Intersection
Returns
string | undefined
getObject()
ts
getObject(id): Object3D<Object3DEventMap> | undefined;Escape hatch: the raw three.js object for an entity (undefined if not created), for advanced effects the wrapper doesn't cover. Unstable — you own whatever you mutate, and the backend may recreate the object when the renderable changes.
Parameters
id
string
Returns
Object3D<Object3DEventMap> | undefined
prepareFrame()
ts
prepareFrame(): void;Flush static membership only when bindings change; world-origin shifts move the common root.
Returns
void
registerKind()
ts
registerKind(kind): void;Register a custom renderable kind (capability client halves). Core kinds cannot be replaced.
Parameters
kind
Returns
void
setAnimationTick()
ts
setAnimationTick(tick, tickRate): void;Live and capture poses use the same simulation tick and no wall-clock accumulation.
Parameters
tick
number
tickRate
number
Returns
void
setEnvironment()
ts
setEnvironment(env): void;The singleton environment component; undefined restores the default rig.
Parameters
env
Record<string, unknown> | undefined
Returns
void
Implementation of
setGlass()
ts
setGlass(
id,
data,
state
): void;Parameters
id
string
data
GlassData | undefined
state
GlassStateData | undefined
Returns
void
Implementation of
setLivery()
ts
setLivery(id, data): void;Latest mirrored values are retained while the model loads. No simulation state is changed.
Parameters
id
string
data
LiveryData | undefined
Returns
void
Implementation of
setModelSignals()
ts
setModelSignals(
id,
spec,
signals
): void;Latest mirrored values are retained while the model loads. No simulation state is changed.
Parameters
id
string
spec
ModelSignalSpec | undefined
signals
Returns
void
Implementation of
setTransform()
ts
setTransform(id, t): void;Parameters
id
string
t
Returns
void
Implementation of
setWeather()
ts
setWeather(weather): void;Physical and visual weather singleton; independent of environment/sky configuration.
Parameters
weather
Record<string, unknown> | undefined
Returns
void
Implementation of
tickAnimations()
ts
tickAnimations(dtSec): void;Standalone preview clock; connected clients use setAnimationTick with the kernel clock.
Parameters
dtSec
number
Returns
void
updateLight()
ts
updateLight(id, data): void;Parameters
id
string
data
Returns
void
Implementation of
updateLiveAnimations()
ts
updateLiveAnimations(
tick,
tickRate,
camera
): void;Exact tick-derived poses on return to view; invisible shadow casters are never skipped.
Parameters
tick
number
tickRate
number
camera
Camera
Returns
void
updateRenderable()
ts
updateRenderable(id, renderable): void;Parameters
id
string
renderable
Returns
void
Implementation of
whenReady()
ts
whenReady(): Promise<void>;Returns
Promise<void>
WeatherVisual
Volumetric clouds, a high cirrus layer and local precipitation on both graphics backends. Patterns are seeded and sampled at absolute simulation time, not integrated frames. Cloud layers use absolute world altitudes; particles are visual and do not accumulate or collide.
Constructors
Constructor
ts
new WeatherVisual(data, options?): WeatherVisual;Parameters
data
options?
Returns
Properties
fog
ts
readonly fog: Fog;object
ts
readonly object: Group;Accessors
cloudAttenuation
Get Signature
ts
get cloudAttenuation(): number;Returns
number
cloudQuality
Get Signature
ts
get cloudQuality(): CloudQuality;Returns
data
Get Signature
ts
get data(): ResolvedWeather;Resolved copy; editing it does not change the visual.
Returns
shadowsActive
Get Signature
ts
get shadowsActive(): boolean;Whether lit surfaces get spatial cloud shadows this frame: from 'high' quality, once the clouds have appeared. While they do, direct light needs no uniform cloud dimming.
Returns
boolean
stats
Get Signature
ts
get stats(): object;Cloud layers drawn (the volumetric layer and cirrus) and precipitation particles.
Returns
object
cloudLayers
ts
cloudLayers: number;particles
ts
particles: number;Methods
dispose()
ts
dispose(): void;Returns
void
fogFor()
ts
fogFor(base, sky?): Fog | FogExp2;Combine weather visibility with an authored/streaming fog limit without mutating it. The clouds are fogged with the result (see CloudUniforms.setFog).
Parameters
base
Fog | FogExp2 | null
sky?
Returns
Fog | FogExp2
setCloudQuality()
ts
setCloudQuality(quality): void;Per-pixel cloud work. Uniform-driven: changing it rebuilds nothing.
Parameters
quality
Returns
void
setData()
ts
setData(data): void;Replace weather while retaining geometry, particles and cached noise.
Parameters
data
Returns
void
update()
ts
update(
seconds,
camera,
origin,
sky?
): void;Update camera-relative geometry using the renderer's absolute floating origin.
Parameters
seconds
number
camera
Camera
origin
Vec3
sky?
Returns
void
writeShadows()
ts
writeShadows(uniforms, active?): void;Write this frame's cloud shadow into a renderer's lit-shader uniforms.
Parameters
uniforms
CloudShadowUniforms
active?
boolean
Returns
void
Interfaces
AdaptiveQualityChange
Properties
level
ts
level: number;previousLevel
ts
previousLevel: number;reason
ts
reason: AdaptiveQualityReason;AdaptiveQualityOptions
Properties
cooldownMs?
ts
optional cooldownMs?: number;decreaseDelayMs?
ts
optional decreaseDelayMs?: number;Sustained overload before stepping down; memory pressure bypasses this delay.
evaluationIntervalMs?
ts
optional evaluationIntervalMs?: number;Measurements are evaluated in windows; frame samples alone never change quality.
increaseDelayMs?
ts
optional increaseDelayMs?: number;Stable headroom before probing one higher level. Failed probes increase this delay.
initialLevel?
ts
optional initialLevel?: number;maxLevel?
ts
optional maxLevel?: number;minLevel?
ts
optional minLevel?: number;Integer detail levels increase with quality. The host maps them to its own budgets.
pauseFrameMs?
ts
optional pauseFrameMs?: number;An isolated longer interval is treated as a pause; repeated ones remain overload.
pauseRepeatMs?
ts
optional pauseRepeatMs?: number;A second isolated pause within this much measured time of the last one is a stall, not a tab resume, and lowers detail (default 60 s). The first is still ignored.
strainDelayMs?
ts
optional strainDelayMs?: number;Sustained strained samples before stepping down (default 10 s).
targetFrameMs?
ts
optional targetFrameMs?: number;upgradeWorkFraction?
ts
optional upgradeWorkFraction?: number;Measured frame work must stay under this share of the target before detail goes up (default 0.9). A step up costs more than the level it leaves, so a host whose levels differ a lot in cost sets it lower: at 0.9 a frame using 15 of its 16.7 ms counted as headroom.
warmupMs?
ts
optional warmupMs?: number;AdaptiveQualitySample
Properties
active?
ts
optional active?: boolean;False while hidden, suspended, or deliberately not rendering. Resets measurement history.
cpuFrameMs?
ts
optional cpuFrameMs?: number;Optional measured work, excluding waiting for the next animation frame.
gpuFrameMs?
ts
optional gpuFrameMs?: number;Supply only a completed, valid asynchronous GPU timing query.
loading?
ts
optional loading?: boolean;Loading alone never authorizes an upgrade. Sustained on-target frames with both CPU and GPU headroom can recover during continuous streaming. Measured loading stalls do not lower detail unless rendering itself is heavy.
memoryPressure?
ts
optional memoryPressure?: number;Estimated resident working set / memory budget. Values above one lower detail.
settling?
ts
optional settling?: boolean;The host's view is still arriving (a first mount, a jump to a new place): slow frames and stalls are that arrival, not the level's cost. A step now would rebuild what is half loaded at another level and start the wait again, so frame time neither lowers nor raises detail while it is set; memory pressure, and measured GPU time over twice the frame budget, still lower it. Hosts clear it once the view has loaded, or after a bound of their own, so a device that cannot afford the level still steps down afterwards.
strained?
ts
optional strained?: boolean;The level asks for more than streaming can hold or deliver, by the host's own measure: tiles rebuilt after eviction, a view that crowds its cache. Frame times do not show this (the work runs outside the frame), so a level can look affordable while it never finishes loading. Blocks upgrades at once and lowers detail when sustained (strainDelayMs). Report only strain the level causes: a slow network strains every level alike, and stepping down would not help.
AdaptiveQualityStats
Properties
changes
ts
changes: number;level
ts
level: number;p90FrameMs
ts
p90FrameMs: number | undefined;reason
ts
reason: AdaptiveQualityReason | undefined;recoveryDelayMs
ts
recoveryDelayMs: number;samples
ts
samples: number;Valid samples in the most recently completed measurement window.
slowFrameRatio
ts
slowFrameRatio: number;smoothedFrameMs
ts
smoothedFrameMs: number | undefined;Exponentially smoothed, trimmed frame time; undefined before the first complete window.
targetFrameMs
ts
targetFrameMs: number;AdmissionBacklog
A larger frame budget for work that is backing up. Once the oldest waiting job (not a background one) has waited afterMs, the frame's time and byte budgets grow with its wait and reach these at twice that; a limit left out, or below the ordinary one, stays as it is. A fixed small budget protects the frame rate of a view that keeps up and starves one that does not: a city streaming in under an aircraft asked for more than twice the work 2 ms a frame could publish, each job waited 3 s (21 s at worst) for each of the several turns a tile's layer takes, and the ground ahead stayed bare while the queue used a twentieth of the main thread.
Properties
afterMs
ts
afterMs: number;maxBytes?
ts
optional maxBytes?: number;maxMilliseconds?
ts
optional maxMilliseconds?: number;AdmissionOptions
Shared main-thread work queue. A job is indivisible; oversize jobs run alone and are reported.
Properties
bytes?
ts
optional bytes?: number;label?
ts
optional label?: string;order?
ts
optional order?: () => number;Live order within normal work, lower first. Unordered work still receives regular service.
Returns
number
priority?
ts
optional priority?: "normal" | "urgent" | "background";Background jobs run in frame budget that no normal job is waiting for, and once one has waited backgroundWaitMs it takes a turn after every backgroundShare other jobs. Urgent jobs run before normal ones, in their own order: small work the view is visibly waiting on, such as terrain ground. Sustained urgent traffic shares service with waiting normal work.
signal?
ts
optional signal?: AbortSignal;AdmissionSample
Properties
background
ts
background: boolean;Ran from the background lane, so its queue time was deliberately deferred.
bytes
ts
bytes: number;label
ts
label: string;overBudget
ts
overBudget: boolean;queueMs
ts
queueMs: number;workMs
ts
workMs: number;AssetOptions
Properties
baseUrl?
ts
optional baseUrl?: string;Base URL asset refs resolve against (default: the page origin).
index?
ts
optional index?: Record<string, string>;Asset id -> served URL index (from the project manifest); ids without an entry use the assets/<id>/model.glb convention.
provider?
ts
optional provider?: AssetProvider;Bring-your-own provider (overrides baseUrl/index).
variant?
ts
optional variant?: string;Packed runtime variant to prefer for convention-resolved ids (e.g. "ktx2"); pair it with decoders.ktx2TranscoderPath. Falls back to model.glb per asset when the variant is missing.
AssetProvider
Resolves asset refs to bytes. Refs are project asset ids ("crate"); refs containing "/" or starting with "./" / "http(s):" pass through as URLs, so manifest-less demos stay trivial.
Methods
load()
ts
load(ref, options?): Promise<ArrayBuffer>;Parameters
ref
string
options?
signal?
AbortSignal
Returns
Promise<ArrayBuffer>
loadText()
ts
loadText(ref, options?): Promise<string>;Parameters
ref
string
options?
signal?
AbortSignal
Returns
Promise<string>
AutoWorldOriginOptions
Properties
gridSize?
ts
optional gridSize?: number;Snap the new origin to this grid size; omitted means use the exact camera position.
includeY?
ts
optional includeY?: boolean;Include vertical movement in the threshold and new origin. Defaults to horizontal XZ only.
threshold
ts
threshold: number;Rebase after the camera moves farther than this world-space distance from the current origin.
CameraPose
Properties
lookAt?
ts
optional lookAt?: Vec3;Either a look-at target or an explicit rotation quaternion.
position
ts
position: Vec3;rotation?
ts
optional rotation?: Quat;CameraTarget
The renderer surface applySceneCamera needs (satisfied by Renderer).
Methods
setCamera()
ts
setCamera(pose): void;Parameters
pose
Returns
void
setFov()
ts
setFov(fovDeg): void;Parameters
fovDeg
number
Returns
void
setTopDownOrtho()
ts
setTopDownOrtho(opts): void;Parameters
opts
Returns
void
CelestialPosition
Properties
altitudeDeg
ts
altitudeDeg: number;Geometric topocentric altitude; no atmospheric refraction.
angularDiameterDeg
ts
angularDiameterDeg: number;azimuthDeg
ts
azimuthDeg: number;Clockwise from geographic north, before northOffsetDeg.
direction
ts
direction: Vec3;Unit vector toward the body; Y-up, default +X east / -Z north.
distanceKm
ts
distanceKm: number;ClientCore
Properties
buffer
ts
readonly buffer: InterpolationBuffer | undefined;The interpolation buffer, once the first keyframe/ready message fixed the tick rate.
mirror
ts
readonly mirror: SceneMirror;tick
ts
readonly tick: number | undefined;The latest kernel tick applied to the mirror.
Methods
command()
ts
command(type, payload?): void;Send a command by type + payload; the envelope is filled (seq, source: 'local').
Parameters
type
string
payload?
JsonValue
Returns
void
control()
ts
control(action): void;Drive the kernel's scheduler: pause, resume, step a fixed number of ticks, set-rate, or request-keyframe. Pairs with the host's startPaused option — a page that boots paused resumes once its assets are in, so nothing simulates behind a loading screen.
Parameters
action
ControlAction
Returns
void
dispose()
ts
dispose(): void;Unhook the link and clear the buffer.
Returns
void
entities()
ts
entities(): string[];Every mirrored entity id (creation order).
Returns
string[]
get()
ts
get(id, component): JsonObject | undefined;Read a component of a mirrored entity (a detached copy).
Parameters
id
string
component
string
Returns
JsonObject | undefined
onDiag()
ts
onDiag(cb): Unsubscribe;Subscribe to kernel diagnostics (tick overruns, rejected commands, protocol errors). Codes the client does not know are delivered as they arrive rather than dropped, so a newer kernel's diagnostics reach an older page.
Parameters
cb
(diag) => void
Returns
onError()
ts
onError(cb): Unsubscribe;Subscribe to client-side failures: a dead or throwing kernel link, and frame-loop exceptions. Without this a crashed Worker is invisible — the page keeps rendering its last pose while every command() posts into nothing.
Parameters
cb
(error) => void
Returns
onEvent()
ts
onEvent(type, cb): Unsubscribe;Subscribe to kernel events by type, or '*' for all. Exact-type handlers run first.
Parameters
type
string
cb
(event, tick) => void
Returns
reportError()
ts
reportError(error): void;Push a failure through the error + diag channels (the frame loop and custom backends use it).
Parameters
error
Returns
void
sampleTransforms()
ts
sampleTransforms(nowMs, apply): void;Sample every interpolated transform for nowMs into the backend (or any consumer).
Parameters
nowMs
number
apply
(id, t) => void
Returns
void
sendCommand()
ts
sendCommand(command): void;Parameters
command
Command
Returns
void
ClientCoreOptions
Properties
backend
ts
backend: SceneBackend;interpolationDelayTicks?
ts
optional interpolationDelayTicks?: number;link
ts
link: MessageLink;now?
ts
optional now?: () => number;Wall clock in ms (default performance.now / Date.now); injectable for tests.
Returns
number
ClientError
A failure the page has to see. link is the kernel side going away or misbehaving (an uncaught throw in the Worker, a script that fails to load, an undeserializable message); frame is an exception out of the client's own render frame. Both also reach onDiag as a ClientDiagCode diagnostic, so a page that only wired diagnostics still learns its kernel is dead.
Properties
cause?
ts
optional cause?: unknown;The ErrorEvent/MessageEvent or thrown value behind it, when there was one.
message
ts
message: string;Human-readable summary, already including the underlying message where one was available.
source
ts
source: "link" | "frame";ClientOptions
Extends
Extended by
Properties
admission?
ts
optional admission?: FrameAdmissionOptions;Inherited from
antialias?
ts
optional antialias?: boolean;Inherited from
assets?
ts
optional assets?: AssetOptions;Enable gltf renderables: where asset refs load from.
autoWorldOrigin?
ts
optional autoWorldOrigin?: AutoWorldOriginOptions;Optional automatic large-world origin rebasing driven by camera movement.
Inherited from
RendererOptions.autoWorldOrigin
backend?
ts
optional backend?: RendererBackendPreference;Which graphics backend to use. Defaults to 'auto': probe WebGPU, fall back to WebGL. 'webgl' skips the probe entirely — pin it when the pixels must be reproducible. 'webgpu' is strict and never silently falls back.
Inherited from
backendProbeTimeoutMs?
ts
optional backendProbeTimeoutMs?: number;How long the WebGPU probe may take before 'auto' gives up and uses WebGL (default 5000ms; 0 or Infinity waits forever). A context can advertise navigator.gpu and then never settle its initialization — headless software rendering does exactly this — and without a bound the page hangs with no error rather than falling back. 'webgpu' rejects on timeout instead.
Inherited from
RendererOptions.backendProbeTimeoutMs
cameraFar?
ts
optional cameraFar?: number;Inherited from
cameraNear?
ts
optional cameraNear?: number;Inherited from
canvas?
ts
optional canvas?: HTMLCanvasElement | OffscreenCanvas;Inherited from
clearColor?
ts
optional clearColor?: string;Background clear color, default a mid grey.
Inherited from
cullRenderGroups?
ts
optional cullRenderGroups?: boolean;WebGL: leave render groups that state their bounds (see createRenderGroup) out of each scene walk they cannot be seen in, and out of each shadow map they cannot cast into. Default true; false walks every group every frame, for comparison.
Inherited from
RendererOptions.cullRenderGroups
decoders?
ts
optional decoders?: DecoderConfig;Optional Draco/KTX2 decoder hosting (canonical imported assets need neither).
frameLoop?
ts
optional frameLoop?: "manual" | "auto";height?
ts
optional height?: number;Inherited from
interpolationDelayTicks?
ts
optional interpolationDelayTicks?: number;kinds?
ts
optional kinds?: RenderableKind[];Custom renderable kinds from capability client halves (e.g. figures).
logarithmicDepthBuffer?
ts
optional logarithmicDepthBuffer?: boolean;Compatibility fallback for large view ranges; costs early-fragment performance.
Inherited from
RendererOptions.logarithmicDepthBuffer
materialBaker?
ts
optional materialBaker?: MaterialBaker;Optional caller-owned worker pool for procedural textures.
onDeviceLost?
ts
optional onDeviceLost?: (reason) => void;Device loss requires a new viewer/canvas. Auto fallback applies during initialization.
Parameters
reason
string
Returns
void
Inherited from
optimizeWebGpu?
ts
optional optimizeWebGpu?: boolean;Persistent instance buffers and managed tile command caches. Defaults to true on WebGPU.
Inherited from
RendererOptions.optimizeWebGpu
pauseWhenInactive?
ts
optional pauseWhenInactive?: boolean;Pause the worker and automatic rendering on blur/hidden. Default true for automatic loops.
pixelRatio?
ts
optional pixelRatio?: number;Inherited from
powerPreference?
ts
optional powerPreference?: "default" | "high-performance" | "low-power";Inherited from
RendererOptions.powerPreference
preserveDrawingBuffer?
ts
optional preserveDrawingBuffer?: boolean;WebGL only. WebGPU presentation does not preserve the drawing buffer between frames.
Inherited from
RendererOptions.preserveDrawingBuffer
reflections?
ts
optional reflections?: boolean;Shared procedural sky/ground reflections for PBR materials. Default false; Earth viewers enable it.
Inherited from
releaseContextOnDispose?
ts
optional releaseContextOnDispose?: boolean;WebGL only: dispose() also releases the GL context (forceContextLoss). Browsers cap live contexts per page (Chromium keeps 16), so a single-page host that mounts and unmounts viewers should enable this; each mount then needs a fresh canvas, because a lost context stays attached to its canvas. Default false keeps a canvas reusable after dispose.
Inherited from
RendererOptions.releaseContextOnDispose
reverseDepthBuffer?
ts
optional reverseDepthBuffer?: boolean;Better depth precision for large view ranges; WebGL uses logarithmic depth if EXT_clip_control is unavailable.
Inherited from
RendererOptions.reverseDepthBuffer
sceneCamera?
ts
optional sceneCamera?: SceneCamera;Declarative camera; follow targets use the same interpolation as rendered entities.
sceneOptimization?
ts
optional sceneOptimization?: SceneOptimizationOptions;signal?
ts
optional signal?: AbortSignal;Cancels a mount in flight (createClient, createSnapshotViewer, createViewer, mountExperience): if it aborts while the GPU is initializing the factory rejects with an AbortError and nothing is left running. A host that unmounts mid-mount (React StrictMode's double-invoked effect) otherwise leaks a live client on the same canvas. Every factory is asynchronous, so every mount can be cancelled.
stars?
ts
optional stars?: readonly SkyStar[];Stars for every sky, e.g. decodeStarCatalog of the molen.sky content pack's stars.bin. Without a catalog, skies show no stars; setStarCatalog supplies one later.
Inherited from
width?
ts
optional width?: number;Inherited from
CustomSkyData
Extends
Properties
dome?
ts
optional dome?: object;brightness?
ts
optional brightness?: number;Inherited from
lighting?
ts
optional lighting?: object;castShadow?
ts
optional castShadow?: boolean;dayAmbient?
ts
optional dayAmbient?: number;moonIntensity?
ts
optional moonIntensity?: number;nightAmbient?
ts
optional nightAmbient?: number;referenceElevation?
ts
optional referenceElevation?: number;skyLightSaturation?
ts
optional skyLightSaturation?: number;sunIntensity?
ts
optional sunIntensity?: number;Inherited from
mode
ts
mode: "custom";moon?
ts
optional moon?: object;earthshine?
ts
optional earthshine?: number;size?
ts
optional size?: number;visible?
ts
optional visible?: boolean;Inherited from
moonBody?
ts
optional moonBody?: SkyBodyData;palette?
ts
optional palette?: SkyPalette;Inherited from
starRotationDeg?
ts
optional starRotationDeg?: [number, number, number];stars?
ts
optional stars?: object;enabled?
ts
optional enabled?: boolean;intensity?
ts
optional intensity?: number;magnitudeLimit?
ts
optional magnitudeLimit?: number;size?
ts
optional size?: number;Inherited from
sun?
ts
optional sun?: object;size?
ts
optional size?: number;visible?
ts
optional visible?: boolean;Inherited from
sunBody
ts
sunBody: SkyBodyData;DecoderConfig
Properties
dracoDecoderPath?
ts
optional dracoDecoderPath?: string;Hosted Draco decoder dir (e.g. "/decoders/draco/"); omit if assets are meshopt-canonical.
ktx2TranscoderPath?
ts
optional ktx2TranscoderPath?: string;Hosted Basis transcoder dir for KTX2 textures; omit when not using KTX2.
EarthObserver
Properties
elevation?
ts
optional elevation?: number;latitude
ts
latitude: number;longitude
ts
longitude: number;northOffsetDeg?
ts
optional northOffsetDeg?: number;EarthSkyData
Extends
Properties
dome?
ts
optional dome?: object;brightness?
ts
optional brightness?: number;Inherited from
lighting?
ts
optional lighting?: object;castShadow?
ts
optional castShadow?: boolean;dayAmbient?
ts
optional dayAmbient?: number;moonIntensity?
ts
optional moonIntensity?: number;nightAmbient?
ts
optional nightAmbient?: number;referenceElevation?
ts
optional referenceElevation?: number;skyLightSaturation?
ts
optional skyLightSaturation?: number;sunIntensity?
ts
optional sunIntensity?: number;Inherited from
mode
ts
mode: "earth";moon?
ts
optional moon?: object;earthshine?
ts
optional earthshine?: number;size?
ts
optional size?: number;visible?
ts
optional visible?: boolean;Inherited from
observer
ts
observer: EarthObserver;palette?
ts
optional palette?: SkyPalette;Inherited from
stars?
ts
optional stars?: object;enabled?
ts
optional enabled?: boolean;intensity?
ts
optional intensity?: number;magnitudeLimit?
ts
optional magnitudeLimit?: number;size?
ts
optional size?: number;Inherited from
sun?
ts
optional sun?: object;size?
ts
optional size?: number;visible?
ts
optional visible?: boolean;Inherited from
time
ts
time: SkyTime;EarthSkyState
Properties
julianDate
ts
julianDate: number;moon
ts
moon: CelestialPosition & object;Type Declaration
illuminatedFraction
ts
illuminatedFraction: number;phase
ts
phase: number;starBasis
ts
starBasis: [Vec3, Vec3, Vec3];Columns transforming J2000 equatorial Cartesian coordinates into the local world.
sun
ts
sun: CelestialPosition;utcMs
ts
utcMs: number;EnvironmentData
Mirrors the schema environment component (loose; all fields optional).
Properties
ambient?
ts
optional ambient?: object;ground?
ts
optional ground?: string;intensity?
ts
optional intensity?: number;sky?
ts
optional sky?: string;background?
ts
optional background?: string;exposure?
ts
optional exposure?: number;fog?
ts
optional fog?: object;color
ts
color: string;far?
ts
optional far?: number;near?
ts
optional near?: number;shadows?
ts
optional shadows?: "off" | "low" | "medium" | "high";sky?
ts
optional sky?: SkyData;Earth or authored clear sky. Owns ambient/sun/moon lights when present.
sun?
ts
optional sun?: object;castShadow?
ts
optional castShadow?: boolean;color?
ts
optional color?: string;direction?
ts
optional direction?: [number, number, number];intensity?
ts
optional intensity?: number;toneMapping?
ts
optional toneMapping?: "none" | "aces" | "agx" | "neutral";FarShadowInfo
Properties
draws
ts
draws: number;Times the map has been drawn.
lastDrawMs
ts
lastDrawMs: number;Main-thread time of its last drawing, ms.
radius
ts
radius: number;Half-width of the map as drawn, meters.
FrameAdmissionOptions
Properties
backgroundShare?
ts
optional backgroundShare?: number;backgroundWaitMs?
ts
optional backgroundWaitMs?: number;How long a background job waits (ms, default 750) before the lane takes turns with the others, and how many other jobs run between its turns (default 8). In flight normal work never runs out, and what waited behind it (texture upgrades, the levels an object is not showing yet) arrived seconds late: a second on average over a town, five at worst.
backlog?
ts
optional backlog?: AdmissionBacklog;See AdmissionBacklog; none by default.
maxBytes?
ts
optional maxBytes?: number;maxJobs?
ts
optional maxJobs?: number;maxMilliseconds?
ts
optional maxMilliseconds?: number;now?
ts
optional now?: () => number;Returns
number
onSample?
ts
optional onSample?: (sample) => void;Parameters
sample
Returns
void
schedule?
ts
optional schedule?: (callback) => void;Parameters
callback
() => void
Returns
void
GpuFrameTimer
Methods
begin()
ts
begin(): boolean;Returns false when unsupported, busy, suspended, or this frame is not sampled.
Returns
boolean
dispose()
ts
dispose(): void;Returns
void
end()
ts
end(): void;Finish the measurement started by begin(); safe when begin() returned false.
Returns
void
poll()
ts
poll(): number | undefined;Poll once per animation frame. Returns the latest completed valid duration in milliseconds.
Returns
number | undefined
GpuFrameTimerOptions
Properties
maxPendingQueries?
ts
optional maxPendingQueries?: number;Maximum outstanding queries, including an active measurement. Default 4.
sampleEveryFrames?
ts
optional sampleEveryFrames?: number;Sample one frame out of this many to limit instrumentation overhead. Default 4.
InputBindings
Properties
bindings
ts
bindings: Record<string, string>;InputGamepad
Structural Gamepad API snapshot; also usable by custom device adapters and tests.
Properties
axes
ts
axes: readonly number[];buttons
ts
buttons: readonly object[];connected
ts
connected: boolean;id
ts
id: string;index
ts
index: number;mapping
ts
mapping: string;InputMapOptions
Extends
InputProfile
Properties
axes?
ts
optional axes?: GamepadAxisBinding[];Inherited from
ts
InputProfile.axesbindings
ts
bindings: Record<string, string>;KeyboardEvent.code or Mouse<button> -> named action.
Inherited from
ts
InputProfile.bindingsbuttons?
ts
optional buttons?: GamepadButtonBinding[];Inherited from
ts
InputProfile.buttonsgetGamepads?
ts
optional getGamepads?: () => readonly (InputGamepad | null)[];Defaults to navigator.getGamepads. Inject an adapter for other browser facilities.
Returns
readonly (InputGamepad | null)[]
profile?
ts
optional profile?: string;profiles?
ts
optional profiles?: Record<string, InputProfile>;target?
ts
optional target?: EventTargetLike;Event source (usually window); injectable for tests.
InputRuleOptions
Properties
pollMs?
ts
optional pollMs?: number;How often controllers and numeric rules are polled (ms). Default 50.
timer?
ts
optional timer?: object;Injectable timer (setInterval/clearInterval shape) for tests.
clear()
ts
clear(handle): void;Parameters
handle
unknown
Returns
void
set()
ts
set(fn, ms): unknown;Parameters
fn
() => void
ms
number
Returns
unknown
InterpTransform
Properties
pos
ts
pos: Vec3;rot
ts
rot: Quat;scale?
ts
optional scale?: Vec3;teleport?
ts
optional teleport?: boolean;When true, the renderer snaps to this transform instead of interpolating into it.
KindContext
Properties
assets
ts
readonly assets: AssetCache | undefined;materials
ts
readonly materials: MaterialResolver;mirror
ts
readonly mirror: MirrorReader | undefined;Mirrored components (bound once the client connects; undefined in bare viewers).
renderer
ts
readonly renderer: Renderer | undefined;scene
ts
readonly scene: Object3D;The world root the entity object lives under (floating origin included).
Methods
track()
ts
track<T>(promise): Promise<T>;Register async work the capture barrier (client.ready()) must wait for.
Type Parameters
T
T
Parameters
promise
Promise<T>
Returns
Promise<T>
warn()
ts
warn(message): void;Parameters
message
string
Returns
void
KindHandle
Properties
object
ts
readonly object: Object3D;The entity's root object; the backend names it, adds it to the scene and drives its transform.
Methods
dispose()
ts
dispose(): void;Returns
void
setTick()?
ts
optional setTick(
tick,
tickRate,
view
): void;Sample the entity's pose at a simulation tick (fractional on the live path). view is undefined on the capture path: exact tick, full detail, no throttling.
Parameters
tick
number
tickRate
number
view
KindView | undefined
Returns
void
update()
ts
update(renderable): void;The renderable changed without changing identity.
Parameters
renderable
Returns
void
KindView
What the live frame loop knows about an entity when it samples its pose.
Properties
distance
ts
distance: number;Distance from the camera to the entity origin, meters.
distantDistance
ts
distantDistance: number;The configured near/far animation distance.
inView
ts
inView: boolean;shadows
ts
shadows: boolean;Whether any mesh of the entity casts shadows (never throttled).
LightData
A light source component at the entity transform (mirrors the schema light component).
Properties
angleDeg?
ts
optional angleDeg?: number;castShadow?
ts
optional castShadow?: boolean;color?
ts
optional color?: string;intensity?
ts
optional intensity?: number;penumbra?
ts
optional penumbra?: number;range?
ts
optional range?: number;type
ts
type: "directional" | "point" | "spot";LiveryVisual
Properties
warnings
ts
readonly warnings: readonly string[];Methods
dispose()
ts
dispose(): void;Restore originals and release only the resources owned by this livery.
Returns
void
LoadedGltf
Properties
clips
ts
clips: AnimationClip[];scene
ts
scene: Group;MirrorReader
Read-only view of the client's mirrored components, without per-frame cloning.
Properties
tick
ts
readonly tick: number | undefined;Methods
peek()
ts
peek(id, component): JsonObject | undefined;The stored component object, not a copy: treat it as frozen. Its identity changes exactly when a delta or keyframe replaced it, so peek(...) !== last is a free change test.
Parameters
id
string
component
string
Returns
JsonObject | undefined
ModelSignalVisual
Properties
missingNodes
ts
readonly missingNodes: readonly string[];missingSignals
ts
readonly missingSignals: readonly string[];Unavailable binding sources on the most recent update (including invalid formulas).
Methods
reset()
ts
reset(): void;Restore authored transforms before removing or replacing bindings.
Returns
void
update()
ts
update(signals, timeSeconds?): void;Absolute simulation time enables responseSeconds; omission applies readings immediately.
Parameters
signals
timeSeconds?
number
Returns
void
MolenClient
Properties
backend
ts
readonly backend: ThreeSceneBackend;The three.js scene backend driving this client (escape hatch: getObject, threeScene, registerKind). Unstable, like everything else you reach through it.
renderer
ts
readonly renderer: Renderer;tick
ts
readonly tick: number | undefined;The latest kernel tick applied (undefined before the first keyframe).
Methods
command()
ts
command(type, payload?): void;Send a command by type + payload; the client fills the envelope (seq auto-increments, source: 'local', tick: 0 — the kernel rewrites late ticks to the next tick).
Parameters
type
string
payload?
JsonValue
Returns
void
control()
ts
control(action): void;Drive the kernel's scheduler: {action: 'resume'} after a startPaused host, 'pause', 'step' a fixed number of ticks, 'set-rate', or 'request-keyframe'. A page that boots its worker paused and resumes on ready() never simulates behind its own loading screen, and a test that steps instead of waiting is independent of wall-clock speed. No-op on a snapshot viewer, which has no kernel.
Parameters
action
ControlAction
Returns
void
dispose()
ts
dispose(): void;Returns
void
entities()
ts
entities(): string[];Every mirrored entity id.
Returns
string[]
entityForIntersection()
ts
entityForIntersection(hit): string | undefined;Resolve a Three ray hit to its entity, including static instanced meshes.
Parameters
hit
Intersection
Returns
string | undefined
get()
ts
get(id, component): JsonObject | undefined;Read a component of a mirrored entity — a HUD's data source (a detached copy).
Parameters
id
string
component
string
Returns
JsonObject | undefined
getObject()
ts
getObject(id): Object3D<Object3DEventMap> | undefined;Escape hatch: the raw three.js object for an entity (undefined when it has none yet). Taking it un-batches the entity from any static batch and marks it escaped, so edits you make stay visible — renderer.worldRoot.getObjectByName(id) skips that and hands back a hidden original.
Parameters
id
string
Returns
Object3D<Object3DEventMap> | undefined
objectCount()
ts
objectCount(): number;Number of bound scene objects (for stats/tests).
Returns
number
onDiag()
ts
onDiag(cb): Unsubscribe;Subscribe to kernel diagnostics (tick overruns, rejected commands, protocol errors).
Parameters
cb
(diag) => void
Returns
onError()
ts
onError(cb): Unsubscribe;Subscribe to client-side failures the kernel cannot report: the link died (source: 'link' — the Worker threw, failed to load, or sent an undeserializable message) or a render frame threw (source: 'frame'). Each also arrives on onDiag as link-error / frame-error.
Parameters
cb
(error) => void
Returns
onEvent()
ts
onEvent(type, cb): Unsubscribe;Subscribe to kernel events by type, or '*' for all (gameplay feedback: hits, pickups, win/lose, command-rejected). Handlers get the event and the tick it happened on.
Parameters
type
string
cb
(event, tick) => void
Returns
ready()
ts
ready(): Promise<void>;Resolves when all pending asset loads have settled (capture/testing barrier).
Returns
Promise<void>
renderFrame()
ts
renderFrame(nowMs?): void;Parameters
nowMs?
number
Returns
void
sendCommand()
ts
sendCommand(command): void;Parameters
command
Command
Returns
void
setCamera()
ts
setCamera(pose): void;Override the declarative camera, disabling automatic follow tracking.
Parameters
pose
Returns
void
MountedExperience
Properties
client
ts
client: MolenClient;input
ts
input: InputMap | undefined;The InputMap driving the scene's emit rules (undefined when the scene has no input block).
Methods
dispose()
ts
dispose(): void;Returns
void
MountExperienceOptions
Extends
Properties
admission?
ts
optional admission?: FrameAdmissionOptions;Inherited from
antialias?
ts
optional antialias?: boolean;Inherited from
assets?
ts
optional assets?: AssetOptions;Enable gltf renderables: where asset refs load from.
Inherited from
autoResize?
ts
optional autoResize?: boolean;Follow the canvas's client size on window resize (default true when window exists).
autoWorldOrigin?
ts
optional autoWorldOrigin?: AutoWorldOriginOptions;Optional automatic large-world origin rebasing driven by camera movement.
Inherited from
backend?
ts
optional backend?: RendererBackendPreference;Which graphics backend to use. Defaults to 'auto': probe WebGPU, fall back to WebGL. 'webgl' skips the probe entirely — pin it when the pixels must be reproducible. 'webgpu' is strict and never silently falls back.
Inherited from
backendProbeTimeoutMs?
ts
optional backendProbeTimeoutMs?: number;How long the WebGPU probe may take before 'auto' gives up and uses WebGL (default 5000ms; 0 or Infinity waits forever). A context can advertise navigator.gpu and then never settle its initialization — headless software rendering does exactly this — and without a bound the page hangs with no error rather than falling back. 'webgpu' rejects on timeout instead.
Inherited from
ClientOptions.backendProbeTimeoutMs
cameraFar?
ts
optional cameraFar?: number;Inherited from
cameraNear?
ts
optional cameraNear?: number;Inherited from
canvas
ts
canvas: HTMLCanvasElement;Overrides
clearColor?
ts
optional clearColor?: string;Background clear color, default a mid grey.
Inherited from
cullRenderGroups?
ts
optional cullRenderGroups?: boolean;WebGL: leave render groups that state their bounds (see createRenderGroup) out of each scene walk they cannot be seen in, and out of each shadow map they cannot cast into. Default true; false walks every group every frame, for comparison.
Inherited from
ClientOptions.cullRenderGroups
decoders?
ts
optional decoders?: DecoderConfig;Optional Draco/KTX2 decoder hosting (canonical imported assets need neither).
Inherited from
frameLoop?
ts
optional frameLoop?: "manual" | "auto";Inherited from
height?
ts
optional height?: number;Inherited from
inputTarget?
ts
optional inputTarget?: EventTargetLike;Where key/mouse events come from (default: window).
interpolationDelayTicks?
ts
optional interpolationDelayTicks?: number;Inherited from
ClientOptions.interpolationDelayTicks
kinds?
ts
optional kinds?: RenderableKind[];Custom renderable kinds from capability client halves (e.g. figures).
Inherited from
link
ts
link: MessageLink;The kernel link (a Worker running KernelHost, or a MessagePort). Built by the host.
logarithmicDepthBuffer?
ts
optional logarithmicDepthBuffer?: boolean;Compatibility fallback for large view ranges; costs early-fragment performance.
Inherited from
ClientOptions.logarithmicDepthBuffer
materialBaker?
ts
optional materialBaker?: MaterialBaker;Optional caller-owned worker pool for procedural textures.
Inherited from
onDeviceLost?
ts
optional onDeviceLost?: (reason) => void;Device loss requires a new viewer/canvas. Auto fallback applies during initialization.
Parameters
reason
string
Returns
void
Inherited from
optimizeWebGpu?
ts
optional optimizeWebGpu?: boolean;Persistent instance buffers and managed tile command caches. Defaults to true on WebGPU.
Inherited from
pauseWhenInactive?
ts
optional pauseWhenInactive?: boolean;Pause the worker and automatic rendering on blur/hidden. Default true for automatic loops.
Inherited from
ClientOptions.pauseWhenInactive
pixelRatio?
ts
optional pixelRatio?: number;Inherited from
pollMs?
ts
optional pollMs?: number;Controller/numeric input poll interval in ms (default 50).
powerPreference?
ts
optional powerPreference?: "default" | "high-performance" | "low-power";Inherited from
preserveDrawingBuffer?
ts
optional preserveDrawingBuffer?: boolean;WebGL only. WebGPU presentation does not preserve the drawing buffer between frames.
Inherited from
ClientOptions.preserveDrawingBuffer
reflections?
ts
optional reflections?: boolean;Shared procedural sky/ground reflections for PBR materials. Default false; Earth viewers enable it.
Inherited from
releaseContextOnDispose?
ts
optional releaseContextOnDispose?: boolean;WebGL only: dispose() also releases the GL context (forceContextLoss). Browsers cap live contexts per page (Chromium keeps 16), so a single-page host that mounts and unmounts viewers should enable this; each mount then needs a fresh canvas, because a lost context stays attached to its canvas. Default false keeps a canvas reusable after dispose.
Inherited from
ClientOptions.releaseContextOnDispose
reverseDepthBuffer?
ts
optional reverseDepthBuffer?: boolean;Better depth precision for large view ranges; WebGL uses logarithmic depth if EXT_clip_control is unavailable.
Inherited from
ClientOptions.reverseDepthBuffer
scene
ts
scene: SceneManifest;The validated scene manifest; its camera and input blocks are applied.
sceneCamera?
ts
optional sceneCamera?: SceneCamera;Declarative camera; follow targets use the same interpolation as rendered entities.
Inherited from
sceneOptimization?
ts
optional sceneOptimization?: SceneOptimizationOptions;Inherited from
ClientOptions.sceneOptimization
signal?
ts
optional signal?: AbortSignal;Cancels a mount in flight (createClient, createSnapshotViewer, createViewer, mountExperience): if it aborts while the GPU is initializing the factory rejects with an AbortError and nothing is left running. A host that unmounts mid-mount (React StrictMode's double-invoked effect) otherwise leaks a live client on the same canvas. Every factory is asynchronous, so every mount can be cancelled.
Inherited from
stars?
ts
optional stars?: readonly SkyStar[];Stars for every sky, e.g. decodeStarCatalog of the molen.sky content pack's stars.bin. Without a catalog, skies show no stars; setStarCatalog supplies one later.
Inherited from
width?
ts
optional width?: number;Inherited from
Renderable
The render contract component (docs-src/schemas/components.md, renderable).
Properties
animation?
ts
optional animation?: object;gltf clip playback; clip time derives deterministically from startTick in captures.
clip
ts
clip: string;loop?
ts
optional loop?: "repeat" | "once" | "pingpong";paused?
ts
optional paused?: boolean;pausedAtTick?
ts
optional pausedAtTick?: number;speed?
ts
optional speed?: number;startTick?
ts
optional startTick?: number;kind
ts
kind: "primitive" | "gltf" | string & object;materialRef?
ts
optional materialRef?: string;node?
ts
optional node?: string;gltf: named sub-node to instance (default: the whole scene).
primitive?
ts
optional primitive?: object;size?
ts
optional size?: Vec3;ref
ts
ref: string;shadows?
ts
optional shadows?: object;cast?
ts
optional cast?: boolean;receive?
ts
optional receive?: boolean;visible?
ts
optional visible?: boolean;RenderableKind
Properties
kind
ts
readonly kind: string;Methods
create()
ts
create(
id,
renderable,
ctx
): KindHandle;Parameters
id
string
renderable
ctx
Returns
dispose()?
ts
optional dispose(): void;Release kind-level shared resources (geometry caches, materials).
Returns
void
identity()
ts
identity(renderable): string;The identity part of a renderable: a change rebuilds the object, otherwise update runs.
Parameters
renderable
Returns
string
RendererOptions
Extended by
Properties
admission?
ts
optional admission?: FrameAdmissionOptions;antialias?
ts
optional antialias?: boolean;autoWorldOrigin?
ts
optional autoWorldOrigin?: AutoWorldOriginOptions;Optional automatic large-world origin rebasing driven by camera movement.
backend?
ts
optional backend?: RendererBackendPreference;Which graphics backend to use. Defaults to 'auto': probe WebGPU, fall back to WebGL. 'webgl' skips the probe entirely — pin it when the pixels must be reproducible. 'webgpu' is strict and never silently falls back.
backendProbeTimeoutMs?
ts
optional backendProbeTimeoutMs?: number;How long the WebGPU probe may take before 'auto' gives up and uses WebGL (default 5000ms; 0 or Infinity waits forever). A context can advertise navigator.gpu and then never settle its initialization — headless software rendering does exactly this — and without a bound the page hangs with no error rather than falling back. 'webgpu' rejects on timeout instead.
cameraFar?
ts
optional cameraFar?: number;cameraNear?
ts
optional cameraNear?: number;canvas?
ts
optional canvas?: HTMLCanvasElement | OffscreenCanvas;clearColor?
ts
optional clearColor?: string;Background clear color, default a mid grey.
cullRenderGroups?
ts
optional cullRenderGroups?: boolean;WebGL: leave render groups that state their bounds (see createRenderGroup) out of each scene walk they cannot be seen in, and out of each shadow map they cannot cast into. Default true; false walks every group every frame, for comparison.
height?
ts
optional height?: number;logarithmicDepthBuffer?
ts
optional logarithmicDepthBuffer?: boolean;Compatibility fallback for large view ranges; costs early-fragment performance.
onDeviceLost?
ts
optional onDeviceLost?: (reason) => void;Device loss requires a new viewer/canvas. Auto fallback applies during initialization.
Parameters
reason
string
Returns
void
optimizeWebGpu?
ts
optional optimizeWebGpu?: boolean;Persistent instance buffers and managed tile command caches. Defaults to true on WebGPU.
pixelRatio?
ts
optional pixelRatio?: number;powerPreference?
ts
optional powerPreference?: "default" | "high-performance" | "low-power";preserveDrawingBuffer?
ts
optional preserveDrawingBuffer?: boolean;WebGL only. WebGPU presentation does not preserve the drawing buffer between frames.
reflections?
ts
optional reflections?: boolean;Shared procedural sky/ground reflections for PBR materials. Default false; Earth viewers enable it.
releaseContextOnDispose?
ts
optional releaseContextOnDispose?: boolean;WebGL only: dispose() also releases the GL context (forceContextLoss). Browsers cap live contexts per page (Chromium keeps 16), so a single-page host that mounts and unmounts viewers should enable this; each mount then needs a fresh canvas, because a lost context stays attached to its canvas. Default false keeps a canvas reusable after dispose.
reverseDepthBuffer?
ts
optional reverseDepthBuffer?: boolean;Better depth precision for large view ranges; WebGL uses logarithmic depth if EXT_clip_control is unavailable.
stars?
ts
optional stars?: readonly SkyStar[];Stars for every sky, e.g. decodeStarCatalog of the molen.sky content pack's stars.bin. Without a catalog, skies show no stars; setStarCatalog supplies one later.
width?
ts
optional width?: number;SceneAdmission
Properties
pending?
ts
readonly optional pending?: number;Jobs waiting, where the queue can say, so optional work can hold off behind a backlog.
Methods
run()
ts
run<T>(task, options?): Promise<T>;Type Parameters
T
T
Parameters
task
() => T
options?
Returns
Promise<T>
SceneBackend
A backend that owns actual scene-graph objects (three.js, or a mock in tests).
Methods
create()
ts
create(id, renderable): void;Parameters
id
string
renderable
Returns
void
createLight()?
ts
optional createLight(id, light): void;Optional light surface (per-entity light components).
Parameters
id
string
light
Returns
void
destroy()
ts
destroy(id): void;Parameters
id
string
Returns
void
destroyLight()?
ts
optional destroyLight(id): void;Parameters
id
string
Returns
void
setEnvironment()?
ts
optional setEnvironment(env): void;Optional environment surface (the singleton environment component, or undefined).
Parameters
env
Record<string, unknown> | undefined
Returns
void
setGlass()?
ts
optional setGlass(
id,
data,
state
): void;Parameters
id
string
data
GlassData | undefined
state
GlassStateData | undefined
Returns
void
setLivery()?
ts
optional setLivery(id, data): void;Parameters
id
string
data
LiveryData | undefined
Returns
void
setModelSignals()?
ts
optional setModelSignals(
id,
spec,
signals
): void;Parameters
id
string
spec
ModelSignalSpec | undefined
signals
Returns
void
setTransform()
ts
setTransform(id, transform): void;Parameters
id
string
transform
Returns
void
setWeather()?
ts
optional setWeather(weather): void;Physical and visual weather singleton; independent of environment/sky configuration.
Parameters
weather
Record<string, unknown> | undefined
Returns
void
updateLight()?
ts
optional updateLight(id, light): void;Parameters
id
string
light
Returns
void
updateRenderable()
ts
updateRenderable(id, renderable): void;Parameters
id
string
renderable
Returns
void
SceneOptimizationOptions
Properties
animation?
ts
optional animation?:
| false
| {
distantDistance?: number;
distantHz?: number;
hiddenHz?: number;
};Live-only pose throttling. Captures continue to sample exact simulation ticks.
maxLocalLights?
ts
optional maxLocalLights?: number;Local lights beyond this count are ranked by influence; unlimited by default.
shaderWarmup?
ts
optional shaderWarmup?: boolean;staticInstancing?
ts
optional staticInstancing?: boolean | StaticBatchOptions;ShadowFocus
Properties
center
ts
center: readonly [number, number, number];Focus point in absolute world coordinates (before any floating-origin rebase).
far?
ts
optional far?: object;A second, wider map around center (absolute world coordinates) covering at least ±radius meters, for the scenery named by Renderer.setFarShadowCasters: surfaces past the focused map read it instead of ending in sunlight. WebGL.
center
ts
center: readonly [number, number, number];radius
ts
radius: number;radius
ts
radius: number;Minimum half-width of the shadowed square, meters. Rounded up for a stable texel grid.
SkyAppearance
Extended by
Properties
dome?
ts
optional dome?: object;brightness?
ts
optional brightness?: number;lighting?
ts
optional lighting?: object;castShadow?
ts
optional castShadow?: boolean;dayAmbient?
ts
optional dayAmbient?: number;moonIntensity?
ts
optional moonIntensity?: number;nightAmbient?
ts
optional nightAmbient?: number;referenceElevation?
ts
optional referenceElevation?: number;skyLightSaturation?
ts
optional skyLightSaturation?: number;sunIntensity?
ts
optional sunIntensity?: number;moon?
ts
optional moon?: object;earthshine?
ts
optional earthshine?: number;size?
ts
optional size?: number;visible?
ts
optional visible?: boolean;palette?
ts
optional palette?: SkyPalette;stars?
ts
optional stars?: object;enabled?
ts
optional enabled?: boolean;intensity?
ts
optional intensity?: number;magnitudeLimit?
ts
optional magnitudeLimit?: number;size?
ts
optional size?: number;sun?
ts
optional sun?: object;size?
ts
optional size?: number;visible?
ts
optional visible?: boolean;SkyBodyData
Properties
angularDiameterDeg?
ts
optional angularDiameterDeg?: number;direction
ts
direction: [number, number, number];SkyFrame
Properties
daylight
ts
daylight: number;earth?
ts
optional earth?: EarthSkyState;moonDiameterDeg
ts
moonDiameterDeg: number;moonDirection?
ts
optional moonDirection?: Vec3;moonIllumination
ts
moonIllumination: number;starVisibility
ts
starVisibility: number;sunDiameterDeg
ts
sunDiameterDeg: number;sunDirection
ts
sunDirection: Vec3;SkyPalette
Properties
dayHorizon?
ts
optional dayHorizon?: string;dayZenith?
ts
optional dayZenith?: string;ground?
ts
optional ground?: string;moon?
ts
optional moon?: string;nightHorizon?
ts
optional nightHorizon?: string;nightZenith?
ts
optional nightZenith?: string;sun?
ts
optional sun?: string;twilight?
ts
optional twilight?: string;SkyReflectionFilter
A backend owns one PMREM generator and reuses its render target across lighting changes.
Methods
dispose()
ts
dispose(): void;Returns
void
update()
ts
update(texture): Texture;Parameters
texture
DataTexture
Returns
Texture
SkyReflectionState
Scene-linear radiance, independent of camera position and floating world origin.
Properties
clouds
ts
clouds: number;ground
ts
ground: RGB;horizon
ts
horizon: RGB;sunColor
ts
sunColor: RGB;sunDirection
ts
sunDirection: RGB;sunGlow
ts
sunGlow: number;twilight
ts
twilight: RGB;twilightStrength
ts
twilightStrength: number;zenith
ts
zenith: RGB;SkyStar
Properties
color?
ts
optional color?: string;direction
ts
direction: Vec3;Unit direction in the unrotated star sphere. Earth skies use J2000 equatorial XYZ.
magnitude
ts
magnitude: number;SkyTime
Properties
epochMs
ts
epochMs: number;UTC Unix milliseconds at simulation second zero.
scale?
ts
optional scale?: number;Sky seconds per simulation second, default 1.
SkyVisualOptions
Properties
shadows?
ts
optional shadows?: "off" | "low" | "medium" | "high";stars?
ts
optional stars?: readonly SkyStar[];The star catalog: decodeStarCatalog of the molen.sky pack for Earth, or an authored world's own. Without one the sky has no stars.
StaticBatchOptions
Properties
cellSize?
ts
optional cellSize?: number;minInstances?
ts
optional minInstances?: number;TopDownOrtho
The framing for the orthographic top-down camera: where it looks and how much it covers.
Properties
cameraHeight?
ts
optional cameraHeight?: number;Camera height above the ground (for depth ordering).
center
ts
center: [number, number];World XZ the camera centers on.
rotationDeg?
ts
optional rotationDeg?: number;viewHeight
ts
viewHeight: number;Vertical world extent the viewport covers.
UrlAssetProviderOptions
Properties
variant?
ts
optional variant?: string;Packed runtime variant to prefer for convention-resolved ids (e.g. "ktx2" from molen asset pack): assets/<id>/model.<variant>.glb is tried first and model.glb is the fallback when the variant is not served. Index-mapped and URL-ish refs are used as given.
WeatherVisualOptions
Properties
backend?
ts
optional backend?: "webgl" | "webgpu";The renderer's backend, which decides how the sky veil matches its fog (three fogs WebGL materials after tone mapping, WebGPU's before). Default 'webgl'.
createCloudMaterial?
ts
optional createCloudMaterial?: (uniforms, textures) => Material;The cloud deck's material for the renderer's backend; the WebGL material by default.
Parameters
uniforms
CloudUniforms
textures
CloudTextures
Returns
Material
noiseBudgetMs?
ts
optional noiseBudgetMs?: number;Milliseconds of cloud noise generation per update until it is complete (default 3); the clouds appear once it is. Infinity builds it all in the first update. Built once per page.
quality?
ts
optional quality?: CloudQuality;Per-pixel cloud work; default 'medium'. See setCloudQuality.
textures?
ts
optional textures?: CloudTextures;Cloud textures to draw with. A renderer passes its own; by default the visual makes some.
Type Aliases
AdaptiveQualityReason
ts
type AdaptiveQualityReason = "frame-time" | "memory-pressure" | "streaming" | "headroom" | "manual";ClientDiagCode
ts
type ClientDiagCode = "link-error" | "frame-error";Diag codes the client synthesizes for failures the kernel cannot report (it is the casualty).
CloudQuality
ts
type CloudQuality = "low" | "medium" | "high" | "ultra";How much work the cloud renderer does per pixel: ray-march steps, light samples, erosion detail and, from 'high', cloud shadows on lit surfaces. Changing it never rebuilds a shader.
CloudType
ts
type CloudType = "cumulus" | "stratocumulus" | "stratus" | "cumulonimbus";Cloud genera the renderer draws: separate fair-weather heaps, a lumpy closed layer, a flat grey sheet, and towering storm cells with anvil tops.
ModelSignals
ts
type ModelSignals = Readonly<Record<string, number | undefined>>;RendererBackend
ts
type RendererBackend = "webgl" | "webgpu";RendererBackendPreference
ts
type RendererBackendPreference = "auto" | RendererBackend;ResolvedWeather
ts
type ResolvedWeather = object;Properties
atmosphere
ts
atmosphere: Required<NonNullable<WeatherData["atmosphere"]>>;clouds
ts
clouds: Required<NonNullable<WeatherData["clouds"]>>;precipitation
ts
precipitation: Required<NonNullable<WeatherData["precipitation"]>>;seed
ts
seed: number;snowCover?
ts
optional snowCover?: ResolvedSnowCover;visibility
ts
visibility: number;wind
ts
wind: Required<NonNullable<WeatherData["wind"]>>;ShadowQuality
ts
type ShadowQuality = "off" | "low" | "medium" | "high";SkyData
ts
type SkyData = EarthSkyData | CustomSkyData;StarCatalogRow
ts
type StarCatalogRow = readonly [number, number, number, number];One catalog row: J2000 right ascension and declination in degrees, magnitude, B-V.
ThreeRenderer
ts
type ThreeRenderer = THREE.WebGLRenderer | WebGPURenderer;Unsubscribe
ts
type Unsubscribe = () => void;Returns
void
WeatherData
ts
type WeatherData = object;Independent atmospheric, cloud and precipitation parameters, in SI units.
Properties
atmosphere?
ts
optional atmosphere?: object;gasConstant?
ts
optional gasConstant?: number;model?
ts
optional model?: "standard" | "isothermal";moistAir?
ts
optional moistAir?: boolean;pressurePa?
ts
optional pressurePa?: number;referenceAltitude?
ts
optional referenceAltitude?: number;relativeHumidity?
ts
optional relativeHumidity?: number;temperatureK?
ts
optional temperatureK?: number;windVelocity?
ts
optional windVelocity?: [number, number, number];clouds?
ts
optional clouds?: object;baseAltitude?
ts
optional baseAltitude?: number;cirrus?
ts
optional cirrus?: number;cirrusAltitude?
ts
optional cirrusAltitude?: number;coverage?
ts
optional coverage?: number;density?
ts
optional density?: number;scale?
ts
optional scale?: number;thickness?
ts
optional thickness?: number;type?
ts
optional type?: CloudType;precipitation?
ts
optional precipitation?: object;intensity?
ts
optional intensity?: number;kind?
ts
optional kind?: "none" | "rain" | "snow";seed?
ts
optional seed?: number;snowCover?
ts
optional snowCover?: object;depth?
ts
optional depth?: number;depthGain?
ts
optional depthGain?: number;level
ts
level: number;maxDepth?
ts
optional maxDepth?: number;transition?
ts
optional transition?: number;visibility?
ts
optional visibility?: number;wind?
ts
optional wind?: object;gusts?
ts
optional gusts?: number;referenceHeight?
ts
optional referenceHeight?: number;shear?
ts
optional shear?: number;terrain?
ts
optional terrain?: number;turbulence?
ts
optional turbulence?: number;WeatherProfile
ts
type WeatherProfile = "sunny" | "partly-cloudy" | "overcast" | "rain" | "storm" | "snow" | "fog";Variables
defaultEnvironment
ts
const defaultEnvironment: EnvironmentData;Exactly the rig the renderer always shipped — existing scenes render byte-identical.
defaultSkyPalette
ts
const defaultSkyPalette: Required<SkyPalette>;INSTANCE_BATCH_COLOR
ts
const INSTANCE_BATCH_COLOR: "instanceColor" = "instanceColor";The geometry attribute a batch's instance colors are read through, when it has colors.
INSTANCE_BATCH_MATRIX_COLUMNS
ts
const INSTANCE_BATCH_MATRIX_COLUMNS: readonly string[];The geometry attributes a batch's instance matrices are read through, one matrix column each.
RENDER_BOUNDS
ts
const RENDER_BOUNDS: "renderBounds";userData key of a render group's bounds: a THREE.Box3 in the frame of the group's parent that contains everything the group draws, now and as its parts move. A group without one is never left out.
RENDER_BOUNDS_STALE
ts
const RENDER_BOUNDS_STALE: "renderBoundsStale";userData flag asking a group's owner to work its bounds out again (see markRenderBoundsChanged).
RENDER_MATRICES_STALE
ts
const RENDER_MATRICES_STALE: "renderMatricesStale";userData flag an owner sets on its render group when it adds content to it: that content has no world matrices until a walk reaches it, and the renderer may be leaving the group out of the scene's walk. Before a shadow map draws a group it left out, the renderer brings a flagged group's matrices up to date and clears the flag; an owner whose group skips walks while hidden clears it in the walk it does make.
Functions
applyEnvironment()
ts
function applyEnvironment(renderer, env): void;Apply an environment onto the renderer + scene: replaces the ambient/sun rig, background, fog, tone mapping, exposure, and the shadow quality tier. Passing defaultEnvironment restores the stock rig; omitted fields fall back to it.
Parameters
renderer
env
Returns
void
applyInputRules()
ts
function applyInputRules(
input,
inputMap,
emit,
opts?
): Unsubscribe$1;Run a scene's input.emit rules against an InputMap: press/release rules emit on action edges; numeric rules share one controller poller that emits a scalar or [x, y] vector only when its value changes. Returns a disposer.
Parameters
input
SceneInput
inputMap
emit
(type, payload) => void
opts?
Returns
Unsubscribe$1
applyLivery()
ts
function applyLivery(model, data): LiveryVisual;Apply to an instance, never a cache template. Does not mutate shared materials or geometry.
Parameters
model
Object3D
data
LiveryData
Returns
applySceneCamera()
ts
function applySceneCamera(
camera,
renderer,
target?
): void;Apply a scene's camera block. fixed and free-fly pose the perspective camera (free-fly applies its initial pose only; movement controls are the host's); top-down-ortho switches to the orthographic framing. Re-run after a resize to keep ortho framing (the Renderer already refits on setSize; callers with their own renderer may call this again).
Parameters
camera
SceneCamera
renderer
target?
Returns
void
boxOutsideView()
ts
function boxOutsideView(
matrix,
min,
max,
depth?
): boolean;Whether a world-space box lies wholly outside a camera's view: every corner beyond the same side of it, or all of them behind a perspective camera. Without depth the near and far planes are not tested (ground a camera's far plane cuts is still wanted, and the test then holds for either depth convention). With it, a box wholly nearer than near or beyond far along the camera's axis is outside too, read in view space: an orthographic shadow map is a box, and ground far along the light's direction lines up with it without being in it. A box across a corner of the view can read as inside when it is not, which only costs the walk it would have saved.
Parameters
matrix
Matrix4
min
Vector3
max
Vector3
depth?
ViewDepth
Returns
boolean
computeClipTime()
ts
function computeClipTime(
anim,
tick,
tickRate,
durationSec
): number;Deterministic clip time from kernel tick (the capture path's animation contract).
Parameters
anim
clip
string
loop?
"repeat" | "once" | "pingpong"
paused?
boolean
pausedAtTick?
number
speed?
number
startTick?
number
tick
number
tickRate
number
durationSec
number
Returns
number
createClient()
ts
function createClient(link, opts?): Promise<MolenClient>;Create a client bound to a kernel message link (Worker/MessagePort). The renderer-free core (createClientCore) applies keyframes/deltas into a scene mirror + interpolation buffer and dispatches events; this wraps it with the three.js backend and a frame loop.
Asynchronous because selecting a graphics backend is: backend defaults to 'auto', which probes WebGPU and falls back to WebGL. Pass backend: 'webgl' to skip the probe — capture and golden paths do, because a pinned backend is what makes a frame byte-stable.
Parameters
link
MessageLink
opts?
Returns
Promise<MolenClient>
createClientCore()
ts
function createClientCore(opts): ClientCore;Parameters
opts
Returns
createGltfLoader()
ts
function createGltfLoader(renderer?, config?): GLTFLoader;A GLTFLoader with the meshopt decoder always attached (its WASM is inlined — zero hosting), plus optional Draco/KTX2 support when decoder paths are configured. Canonical GLBs from molen asset import are quantize+meshopt only, so most apps never configure paths.
Parameters
renderer?
WebGLRenderer | WebGPURenderer
config?
Returns
GLTFLoader
createGpuFrameTimer()
ts
function createGpuFrameTimer(context, options?): GpuFrameTimer | undefined;Optional WebGL2 timing. Reads a result only after QUERY_RESULT_AVAILABLE; never waits, flushes, finishes, or schedules polling. Unavailable extensions return undefined. Context restoration reacquires the extension and starts with fresh query objects.
Parameters
context
WebGLRenderingContext | WebGL2RenderingContext
options?
Returns
GpuFrameTimer | undefined
createIndexedDbMaterialStore()
ts
function createIndexedDbMaterialStore(name?): BakedMaterialStore | undefined;Baked materials kept in IndexedDB across visits; pair with withBakedMaterialStore from @bendyline/molen-materials. Undefined where IndexedDB is unavailable. Every failure (quota, private browsing, a blocked upgrade) resolves as a miss, so baking simply runs as before.
Parameters
name?
string
Returns
BakedMaterialStore | undefined
createModelSignalVisual()
ts
function createModelSignalVisual(model, spec): ModelSignalVisual;Model-agnostic; moves existing geometry without creating a cockpit or changing physics.
Parameters
model
Object3D
spec
ModelSignalSpec
Returns
createSnapshotViewer()
ts
function createSnapshotViewer(keyframe, opts?): Promise<MolenClient>;Boot a client directly from a serialized keyframe with no live kernel — the capture page and replay viewer use this (docs-src/guide/three-surface.md). With gltf renderables, await ready() before the deterministic frame; clip poses derive from the keyframe tick.
Like createClient, backend defaults to 'auto'; pin 'webgl' for a byte-stable frame.
Parameters
keyframe
Keyframe
opts?
Returns
Promise<MolenClient>
createUrlAssetProvider()
ts
function createUrlAssetProvider(
baseUrl,
index?,
options?
): AssetProvider;URL-backed provider: asset ids resolve through an id -> URL index (from the project manifest's assets record, mapped to served model URLs); URL-ish refs resolve against baseUrl.
Parameters
baseUrl
string
index?
Record<string, string>
options?
Returns
createViewer()
ts
function createViewer(opts?): Promise<MolenClient>;Create a viewer with no kernel and no snapshot — just a renderer + camera over an empty scene. For client-side capabilities (terrain, custom three.js objects via renderer.scene).
Parameters
opts?
Returns
Promise<MolenClient>
createWebGlSkyReflectionFilter()
ts
function createWebGlSkyReflectionFilter(renderer): SkyReflectionFilter;Parameters
renderer
WebGLRenderer
Returns
decodeStarCatalog()
ts
function decodeStarCatalog(input): SkyStar[];Decode a molen/stars@1 catalog into sky stars (J2000 equatorial directions, the same frame the bundled catalog uses) for SkyVisual.setStars or Renderer.setStarCatalog.
Parameters
input
ArrayBuffer | Uint8Array<ArrayBufferLike>
Returns
SkyStar[]
decodeStarCatalogRows()
ts
function decodeStarCatalogRows(input): StarCatalogRow[];Decode molen/stars@1 bytes to catalog rows.
Parameters
input
ArrayBuffer | Uint8Array<ArrayBufferLike>
Returns
encodeStarCatalog()
ts
function encodeStarCatalog(rows): Uint8Array;Encode catalog rows as molen/stars@1 bytes.
Parameters
rows
readonly StarCatalogRow[]
Returns
Uint8Array
evaluateEarthSky()
ts
function evaluateEarthSky(utcMs, observer): EarthSkyState;Compact Earth ephemeris: Keplerian Sun + Moon with the major lunar perturbations, ellipsoidal observer parallax, sidereal rotation and stellar precession. Formula reference: https://www.stjarnhimlen.se/comp/ppcomp.html (Paul Schlyter). Intended for visual skies, not navigation: no refraction, nutation, eclipses, or light time.
Parameters
utcMs
number
observer
Returns
expandRenderBounds()
ts
function expandRenderBounds(
bounds,
object,
frame,
padding?
): Box3;Grow bounds (in frame's own coordinates) to hold everything object draws: each mesh's bounding box where it has one already (an instanced mesh's own, over its instances), and otherwise the box round its bounding sphere, which three works out for its own culling anyway. Nothing is measured from vertices that three would not measure too: a box computed here for every building's geometry was a pass over a dense tile's half a million vertices, 5 ms of the job that published it. An object marked userData.dynamicTransform may turn about its own origin, so it and what is under it count as the sphere they can sweep there; one that travels needs its owner to state bounds for the whole of its way. Local matrices are read as they stand (static content has them frozen), so the object need not have been drawn or even attached. padding is added round each part.
Parameters
bounds
Box3
object
Object3D
frame
Object3D
padding?
number
Returns
Box3
followCameraPose()
ts
function followCameraPose(camera, target): CameraPose;Pure camera composition shared by live interpolation and deterministic snapshot viewers.
Parameters
camera
entity
string
fov?
number
lookOffset
Vec3
mode
"follow"
offset
Vec3
space?
"world" | "local"
target
Returns
isInstanceBatch()
ts
function isInstanceBatch(object): object is InstanceBatch<Material<MaterialEventMap> | Material<MaterialEventMap>[]>;Whether object is an InstanceBatch.
Parameters
object
unknown
Returns
object is InstanceBatch<Material<MaterialEventMap> | Material<MaterialEventMap>[]>
isInstanceBatchGeometry()
ts
function isInstanceBatchGeometry(geometry): boolean;Whether geometry is one of an InstanceBatch's own geometries.
Parameters
geometry
BufferGeometry
Returns
boolean
lerp3()
ts
function lerp3(
a,
b,
t
): Vec3;Parameters
a
Vec3
b
Vec3
t
number
Returns
Vec3
liveryGraphicTexture()
ts
function liveryGraphicTexture(graphic, size?): DataTexture;Flat vector artwork, including outlined text; no browser fonts or image downloads.
Parameters
graphic
LiveryGraphic
size?
number
Returns
DataTexture
localCommand()
ts
function localCommand(
seq,
type,
payload
): Command;The envelope command() fills: local source, kernel re-stamps tick 0 to next tick.
Parameters
seq
number
type
string
payload
JsonValue
Returns
Command
markRenderBoundsChanged()
ts
function markRenderBoundsChanged(object): void;Tell the render group above object that what it draws has changed size: call it after adding or replacing geometry inside streamed content once that content is on show (a landmark's next level of detail arriving, say). The group's owner works its bounds out again before the next frame. Does nothing for an object outside any group with bounds.
Parameters
object
Object3D
Returns
void
materialFromBaked()
ts
function materialFromBaked(baked): MeshStandardMaterial;Upload a BakedMaterial's slots onto a MeshStandardMaterial.
Parameters
baked
BakedMaterial
Returns
MeshStandardMaterial
mountExperience()
ts
function mountExperience(opts): Promise<MountedExperience>;The one-call browser mount: create the client on the link, apply the scene's camera, wire its input bindings + emit rules to client.command, and keep the renderer sized to the canvas. The kernel side is the host's KernelHost in a Worker built with buildWorld (which installs the same scene's scripts). Returns the client plus a disposer.
This is the one entry point a page needs. It is asynchronous because backend defaults to 'auto', which probes WebGPU and falls back to WebGL; pass backend: 'webgl' to skip the probe.
Parameters
opts
Returns
Promise<MountedExperience>
nextWorldOrigin()
ts
function nextWorldOrigin(
current,
cameraPosition,
options
): Vec3 | undefined;Pure automatic-origin policy, exported so hosts can predict and test rebases without WebGL.
Parameters
current
Vec3
cameraPosition
Vec3
options
Returns
Vec3 | undefined
nlerp4()
ts
function nlerp4(
a,
b,
t
): Quat;Normalized linear quaternion interpolation along the shorter arc. Not a slerp: the angular rate is not constant across t, which is the right trade for interpolating between two consecutive simulation ticks (cheap, always returns a unit quaternion, no trig). A rotation large enough for the difference to read would have to turn most of the way around inside one tick.
Parameters
a
Quat
b
Quat
t
number
Returns
Quat
normalizeInputAxis()
ts
function normalizeInputAxis(raw, binding): number;Calibrate and shape a raw axis. Invalid/non-finite hardware readings are neutral.
Parameters
raw
number
binding
GamepadAxisBinding
Returns
number
observePageActivity()
ts
function observePageActivity(onChange): () => void;Observe whether the page is both visible and focused; reports the initial state immediately.
Parameters
onChange
(active) => void
Returns
() => void
orthoFrustum()
ts
function orthoFrustum(viewHeight, aspect): object;Orthographic half-extents for a vertical view extent at an aspect ratio (pure; testable).
Parameters
viewHeight
number
aspect
number
Returns
object
halfH
ts
halfH: number;halfW
ts
halfW: number;readModelSignals()
ts
function readModelSignals(sources, readComponent): ModelSignals;Read data only: no expressions, evaluation, prototype traversal, or simulation writes.
Parameters
sources
Readonly<Record<string, ModelSignalSource>> | undefined
readComponent
(name) => unknown
Returns
reflectionStateFromLights()
ts
function reflectionStateFromLights(
ambient,
sun,
background,
clouds
): SkyReflectionState;Fallback for authored/static light rigs without a celestial SkyVisual.
Parameters
ambient
HemisphereLight | undefined
sun
DirectionalLight | undefined
background
Color
clouds
number
Returns
resolveAction()
ts
function resolveAction(bindings, code): string | undefined;Resolve a key or Mouse<button> code to its bound action.
Parameters
bindings
Record<string, string>
code
string
Returns
string | undefined
resolveWeather()
ts
function resolveWeather(data?): ResolvedWeather;Expand validated weather data without changing or retaining its mutable nested values.
Parameters
data?
Returns
skyTimeMs()
ts
function skyTimeMs(time, simulationSeconds?): number;Explicit, seekable simulation clock; no implicit Date.now or browser timezone.
Parameters
time
simulationSeconds?
number
Returns
number
starDirection()
ts
function starDirection(
rightAscensionDeg,
declinationDeg,
state
): Vec3;Map a catalog J2000 position (degrees) through a sampled Earth's star basis.
Parameters
rightAscensionDeg
number
declinationDeg
number
state
Returns
Vec3
viewProjection()
ts
function viewProjection(camera, target): Matrix4;A camera's view volume as the matrix from world to clip space, for boxOutsideView.
Parameters
camera
Camera
target
Matrix4
Returns
Matrix4
weatherProfile()
ts
function weatherProfile(profile): WeatherData;Presets are starting points, not a mutually exclusive weather model. Returns fresh data.