Docs
API reference

@klorad/api/world

The World layer. Scenes, Scene Objects, space, time, packages, revisions, interaction and projections. Pure TypeScript.

import { createScene } from "@klorad/api/world";

Scene

ExportKindDescription
createScene(options)functionCreates an empty scene anchored on Earth. Throws without a coordinateSystem.
ScenetypeThe scene: the only way to change world state.
SceneOptionstypeOptions of createScene.
SceneEvent, SceneListenertypeThe ordered events every change becomes.
snapshotScene(scene), restoreScene(snapshot, options?)functionTo and from a version 1 SceneSnapshot. New code uses packages (below).
projectScene(source, admits, name?)functionA read model holding only the objects admits accepts, kept in step. Returns a Projection (scene, stop()).

Prop

Type

Scene methods

MethodReturnsDescription
add(spec)the object, typed by its specAdds a Scene Object. Throws on a duplicate id or an invalid spec.
update(id, patch)SceneObjectPatches name, position, orientation, scale, geometry, colour or properties (merged). Throws on an unknown id.
remove(id)booleanRemoves an object and its readings.
get(id)SceneObject | undefined
objects()readonly SceneObject[]In insertion order; the same array until something changes.
observe(input)ObserveResultOffers a reading: latest, late, duplicate or rejected.
latest(id, quantity)Observation | undefinedThe current reading.
readings(id)Record<string, Observation>The current reading of every quantity; the same object until one changes.
history(id, quantity)readonly Observation[]Ordered by observedAt, then seq.
isStale(id, quantity)booleanAgainst the scene's clock, now.
boundTo(source, entity)readonly SceneObject[]The shadows and twins bound to a source entity.
subscribe(listener)() => voidEvery event, in order. Returns an unsubscribe function.
version()numberThe seq of the last event.

Environment

How a scene looks, never what it holds: no object changes with it. See Light and arrange a scene.

ExportKindDescription
SoundSourcetypeA sound at a place (ADR-0059): id, name, asset (the id of an audio asset), east and north in metres of the scene's frame, up (1.5 m, SOUND_HEIGHT, when absent), volume (0 to 1) and reach, the metres at which it can no longer be heard (2 to 500). checkSoundSource and checkSounds list its problems; SOUND_LIMITS holds the bounds, at most 50 sounds. A PublicPresentation and a package's manifest carry them as sounds.
SceneEnvironmenttypesky (a colour like #9cc3e4), sun (azimuth and elevation in degrees, intensity, color), ambient (0 to 2), fog (read, not drawn since ADR-0105), ground (whether the ground sheet is drawn), exposure (0.2 to 3), floor (a colour the objects cast their shadows on), shadows (how they are kept: "off", "on-change", the default, or "realtime"), reveal (read, not drawn), time (the time of day, 0 up to 1), sound (the id of an audio asset played as its ambience where it is shown), map (a SceneMap), look ("normal", the default, or "operational": what is connected to a source stands out and the rest is faint, ADR-0109), and the preset it started from, if any.
TIME_OF_DAY, lightAt, phaseOf, onCycle, timeOfvalue, functionsThe time of day (ADR-0105): a phase of one cycle, dawn 0, day 0.25, dusk 0.5, night 0.75. lightAt(time, studio) is the light there, blended between the four; phaseOf the nearest named one; timeOf(environment) a look's own time or its preset's. A control of appearance, not a sun: no date, clock or place is used.
inStudio, drawnLook, STUDIO_FLOORfunctions, valueWhether a look's 3D scene is the Studio (SceneMap.studio, or a floor for a look stored before it), and what a 3D reader draws for a look: the Studio on its floor, or the land with no floor, at a time of day.
SceneMaptypeThe map a scene is drawn on, where a reader draws one (ADR-0104): basemap (a name in lower case letters, digits and hyphens; none when absent), terrain (off when absent) and labels (place names; shown when absent). It names what is drawn; the app that shows the scene maps the name to a source.
ShadowMode, SHADOW_MODEStype, value"off", "on-change", "realtime": how an environment's shadows are kept (ADR-0076). A device may draw less, never more.
EnvironmentPreset, ENVIRONMENT_PRESETStype, value"dawn", "day", "dusk", "night", "studio"; "morning" and "evening" are deprecated names of dawn and dusk.
environmentOf(preset)functionThe environment of a preset: a starting point to adjust by making a new value.
checkEnvironment(value)functionEvery problem of an environment; empty when a renderer may draw it.

Scene Objects

ExportKindDescription
SceneObjecttypeDigitalObject | DigitalShadow | DigitalTwin, discriminated by correspondence.
SceneObjectSpec, DigitalObjectSpec, DigitalShadowSpec, DigitalTwinSpectypeWhat add takes.
SceneObjectPatchtypeWhat update takes.
Correspondencetype"object" | "shadow" | "twin".
SourceBindingtype{ source, entity }.
GeometrytypeHow an object is drawn: one of the eleven kinds below.
PlanPointtype[east, north]: a point of a footprint or a path, in metres from the object's position.
Orientationtypeheading, pitch, roll in degrees.
isObservable(object)functionNarrows to a shadow or a twin.
Relationtype{ kind, to }: an edge from an object to another, by id.

Every object may also carry class (Klorad's classification), classifications (other schemes, by name: { ifc: "IfcPump" }), layer (a layer id of the package), relations and navigation (Navigation, one of NAVIGATION: "walkable", "blocks" or "ignore", how a person moves about it; absent, a renderer decides by its shape and IFC class, ADR-0066). An update replaces the relations it is given; navigation: null gives the choice back to the shape.

Geometry

Sizes are metres. The first four kinds are shapes; model and splat are drawn from files; the next three are the shapes of a map, given around the object's position, so the object itself stays one position on Earth. feature is a part of another object's model, and group is a whole made of other objects.

kindFieldsDraws
"box"width, depth, heightA box standing on its position: width runs east, depth north.
"cylinder"radius, heightAn upright cylinder.
"sphere"radiusA sphere resting on its position.
"marker"noneA pin whose tip is the position.
"model"uri, format?, part?A model file; format: "3d-tiles" (TILESET_FORMAT) names a 3D Tiles 1.1 tileset, streamed. A glTF or GLB file, in metres, with its origin at the object's position. At heading 0 its minus z axis points north.
"splat"uri, format?, capturedAt?A Gaussian splat: SPZ when format is absent, or PLY. Picked by the box of its points, never walked on. Readers that cannot draw it show a symbol. See Show a Gaussian splat.
"extrusion"footprint, heightA footprint raised to a height: a building block.
"polygon"footprintA flat area: a square, a zone, water.
"polyline"path, widthA line with a width: a road, a pipe, a route.
"feature"of, feature, footprint?, height?One element of another object's model: of names that object, feature the element's id in its model (the globalId of a 3D Tiles feature, or a node's name in a GLB). Drawn by that model; footprint and height give its box around its position, for framing and the plan. See Show a building as BIM.
"group"noneNothing of its own: a compound object drawn by the objects that name it as their whole. See Group objects into a compound.

A footprint is one ring of at least three PlanPoints that encloses an area, in either winding, without holes; it may repeat its first point at the end, as GeoJSON does. A path has at least two points. The scene checks, copies and freezes them, and throws a RangeError on a size that is not a positive number or a point that is not finite. See Draw a place from a map.

Packages

A scene as klorad.scene version 2: a manifest and its chunks. See Save, load and edit a scene.

ExportKindDescription
packScene(scene, meta?, options?)async functionA PackedScene: objects in chunks of chunkSize metres (default 250), each with bounds and a SHA-256; includeState (default true) adds the latest readings; revision records a store's revision.
unpackScene(manifest, load, options?)async functionA scene from a manifest, loading through load only the chunks that overlap bounds, keeping only layers. Refuses a chunk whose hash does not match. Returns scene, meta, revision, loaded.
chunksFrom(chunks)functionA chunk loader over chunks in memory.
readPackedScene(value)async functionAny scene document Klorad wrote, a version 1 snapshot upgraded in memory.
validatePackage(value), assertPackage(value)functionEvery problem of a manifest, or a throw listing them.
ScenePackage, SceneChunk, PackedScene, ChunkRef, BoundstypeThe manifest, its chunks and their references.
SceneMeta, Layer, NamedView, AssetRef, ExternalSpace, Provenance, CoordinateReference, EMPTY_METAtype, valueWhat a package carries besides objects.
TourtypeAn ordered walk through some of the scene's views: id, name, text?, stops (view ids, in order).
PropertyField, PropertyFieldTypetypeWhat a property of the scene's objects means: its key, label, type ("text", "number", "period", "url" or "choice") and the choices of a choice.
AttachmenttypeA file that belongs to an object without drawing it: id, object, title, asset (one of the scene's assets, by id), mediaType, and role ("media", or "alternate" for another model of the same object).
CitedSourcetypeWhere an object's description came from, as a reader may see it (ADR-0124): id, object, the caption its editor approved, and a url only for an outside, https source. It never names a file, and it is not an attachment: nothing of it can be downloaded.

A SceneMeta may also carry its presentation: an environment, tours, fields, attachments and cited sources, and a NamedView its text, what a reader is told when they stand there. A reader that does not know them ignores them. | objectBounds(object), intersects(a, b) | function | The box an object occupies; whether two boxes overlap in plan. | | hashJson(value), sha256Hex(bytes), canonicalJson(value) | function | The content hashes a package uses. |

Queries and partial loading

ExportKindDescription
queryScene(scene, query?)functionThe objects that match every part of a SceneQuery: bounds, layers (null for objects without one), ids, classes, correspondence, related ({ to, kind?, direction? }). In scene order.
relationsOf(scene, id, direction?)functionThe Edges that leave (out), reach (in) or touch (both, default) an object.
pickFields(objects, fields)functionOnly the named fields of each object, id always included.
createChunkedScene(manifest, load, options?)functionA scene that holds only the chunks of a package its views overlap. Each view opens a viewer(name, { admits? }): its own scene holds only the objects admits allows (from an Access policy), whatever the shared scene loaded for other views, so chunks are shared for memory and permissions are not. setBounds(bounds) says what the view shows; release() closes it, stops its scene and lets go of chunks only it held. A chunk that arrives after every view needing it has moved on is dropped. Chunks beyond a margin of every view (default half its width) are let go. A chunked scene is a reader's cache: edits go to the scene's store.
PlanBounds, SceneQuery, Edge, ChunkedScene, ChunkViewer, ViewerOptions, ChunkChangetype

Readers

ExportKindDescription
ReaderCapabilitiestypeWhat a reader draws: dimensions, each geometry kind as drawn, symbol or none, streams, readings. Every renderer exports its own.
unsupportedBy(capabilities, objects)functionThe objects a reader draws only as a symbol or not at all, with why.

The projection for agents

Read only: an agent changes nothing through it. See For agents.

ExportKindDescription
describeScene(scene, options?)functionAn AgentView: each object (by query) with class, correspondence, layer, position in metres, readings with their age and freshness, relations, and with interaction and actor the Action ids that actor may perform.
agentText(view)functionThe view as compact text for a model's context: one line per object and the schematic plan.
planText(scene, objects?, options?)functionA schematic plan as characters, north up, one letter per object, with its legend and metres per character.
distanceBetween(scene, a, b), nearest(scene, id, options?)functionMetric answers in metres: the distance between two objects; the nearest ones, optionally within a radius and among a query.

Revisions

ExportKindDescription
SceneCommand, CommandBatchtypeadd, update or remove, sent with the base revision its author read.
findConflicts(batch, versionOf)functionEvery field the batch touches that changed after its base. Empty means it may be applied.
planCommands(commands, current, cs)functionThe objects a batch produces, without changing anything; throws on an invalid batch.
stampVersion(command, revision, previous)functionAn object's field revisions after a command.
ObjectVersion, Conflict, PlannedChangetypeWhat a store remembers and what it answers.
fieldsOf(command), commandTarget(command)functionThe fields a command writes and the object it names.

Space

ExportKindDescription
createCoordinateSystem({ origin })functionAn East, North, Up frame in metres at a WGS84 origin: toLocal, toGeo, resolve.
Position, GeoPosition, LocalPosition, GeoPoint, LocalPointtypeA position on Earth (lat, lon, height) or in metres (east, north, up).
isLocalPosition(p)functionTrue for the local form.
geoPoint, geodeticToEcef, ecefToGeodetic, toRadians, toDegreesfunctionGeodesy helpers on WGS84.

Time

ExportKindDescription
Clock, Instanttypenow() in epoch milliseconds.
systemClockvalueThe default clock.
createManualClock(start)functionA clock you advance(ms) or set(instant), for tests.
Observation, ObservationInput, ObservationValue, ObservationQuality, ObserveResulttypeA reading: objectId, quantity, value, unit, observedAt, receivedAt, source, quality, seq.
compareObservations(a, b)functionThe Time Spectrum order: observedAt, then seq.
isValidObservationInput(input)functionA finite value of a known type, a time, a quantity and a source.
ValuePolicy, resolveValue(policy, readings)type, functionWhich source's reading is the operational value: latest-observed, latest-received or precedence.

Interaction

ExportKindDescription
createInteraction(scene, options)functionRuns Action, Entitlement, Behaviour, Animation. Returns an Interaction.
Interactiontypeavailable(objectId, actor, world?) and perform(request).
ActionDefinition, BehaviourDefinition, BehaviourContext, AnimationRequesttypeWhat you define.
ActionRequest, ActionResult, ActionOutcome, ActionParams, ParamValue, ActortypeWhat you ask and what you get back.
Entitlement, DecisiontypeThe port Access implements.
Actuator, Command, CommandReceipttypeThe port toward devices, for Digital Twins.

The options of createInteraction:

Prop

Type

Operations

ExportKindDescription
OperationDefinition, EffectClass, ParamSchema, ParamValues, AppliesTo, PropertySource, OperationReftypeA versioned operation: effect class, parameter schema, the properties an edit sets, the command an actuation sends, its timeout and compensation.
ProcedureDefinitiontypeA linear procedure of pinned operation versions.
CommandStatetypeaccepted, dispatched, acknowledged, failed, unknown.
createRegistry(operations, procedures?)functionDescribes operations and procedures; refuses a malformed definition. Never authorises.
OperationRegistrytypeget(id, version?), procedure(id), forObject(object, effects), all(), procedures().
checkOperation(op), checkProcedure(p, find)functionThe problems of a definition; empty when it may be registered.
operationApplies(op, object), validateParams(op, params)functionWhether it applies, and the first problem of the parameters.
editPatch(op, params), inversePatch(before, patch)functionWhat a model edit changes, and the patch that puts it back.
canTransition(from, to), isFinal(state)functionThe command life cycle's rules.

Publication

ExportKindDescription
PublicationFiltertypeWhich objects, properties, readings and alarms are public; nothing else is.
publicPackage(packed, filter, name?, views?, presentation?)functionThe sanitised projection a public World shows: no source or device id, nothing the filter does not name; views replace the scene's own. A presentation is applied over it.
PublicPresentation, ObjectPresentationtypeHow a public World is presented: views (which win over the fourth argument), tours, environment, fields, attachments, cited sources (kept only for public objects, and only when they carry a caption or an https address), and per object id a name, east, north, up, heading, scale, the values of described properties and hidden. It hides and arranges public objects and adds only the properties fields describes, never what the filter keeps out.
checkPresentation(presentation), MAX_PRESENTEDfunction, constantEvery problem of a presentation, and how many tours (20), fields (40), attachments (500), sources (500) and objects (2000) it may hold.
isPublic(filter, object), checkPublicationFilter(filter)functionWhether an object is public, and the problems of a filter.
checkPublicViews(views), MAX_PUBLIC_VIEWSfunction, constantThe problems of the views a World is published with, and how many it may have (50).

Something wrong or unclear? Tell us.