# Scenery Scripting -- API Reference, engine types (v0.5.0) Types the engine bridges into JavaScript: entities, the scene, meshes, materials, GPU buffers and kernels. Every type, method, and signature. Sibling bundle (runtime types -- object creation, animation, anchors, helpers): https://scenery.app/docs/scripting/api/runtime/llms-full.txt Sibling bundle (concepts, how-to, worked examples): https://scenery.app/docs/scripting/guide/llms-full.txt Global instances available in every script without declaration: - `experience` -- `Experience` - `scene` -- `Scene` - `environment` -- `Environment` - `http` -- `HTTP client (promisified). Methods: get(url, options?), post(url, body, options?), request(url, options). All return Promise<{status, data}>` - `websocket` -- `WebSocket client. Methods: connect(url, options?) returns WebSocket` - `secrets` -- `Secrets. Methods: mint(name, params?) returns Promise<{value, expiresAt, provider}>. For ordinary REST use `http.request(url, { secret })` instead, which never puts a credential on the device` - `httpClient` -- `HTTPClient (low-level, callback-based -- prefer `http` instead)` - `secretsClient` -- `SecretsClient (low-level, callback-based -- prefer `secrets` instead)` - `webSocketManager` -- `WebSocketManager (low-level -- prefer `websocket` instead)` Any docs page is also available as raw markdown by appending `.md` -- e.g. https://scenery.app/docs/scripting/api/mesh.md, https://scenery.app/docs/scripting/guide/examples.md. Authoritative for runtime v0.5.0. If an API is not listed here or in the sibling bundles, it does not exist in this version -- do not invent signatures. --- ## Swift JSExport APIs ### `ARRaycastResult` Result from scene.raycastAR() when ray intersects real-world surfaces **Properties:** - `worldTransform`: `Transform` (read-only) - World transform matrix at hit location - `target`: `string` (read-only) - Type of target that was hit: "existingPlaneGeometry", "existingPlaneInfinite", "estimatedPlane" - `targetAlignment`: `string` (read-only) - Surface alignment: "horizontal", "vertical", "any" - `anchor`: `AnchorData` (read-only) - Associated plane anchor if hit was on a tracked plane (nil for estimated surfaces) ### `Accessibility` The accessibility settings a script can adapt to, exposed as `environment.accessibility`. **Properties:** - `reduceMotion`: `boolean` (read-only) - `true` while the person has asked for less motion: Reduce Motion on Apple devices, `prefers-reduced-motion` on the web. Replace loops, shakes and fly-ins with fades or stills. **Methods:** **Runtime Extensions:** - `on(event: string, callback: function)` → `any` - Subscribe to changes of the accessibility settings. Supported: 'change' → callback(), fired when the person turns Reduce Motion on or off while the experience runs. Read the new value from `environment.accessibility`. ### `Action` **Properties:** - `id`: `string` (read-only) - `kind`: `string` (read-only) **Methods:** ### `AnchorData` **Properties:** - `id`: `string` (read-only) - Unique identifier for this anchor - `kind`: `string` (read-only) - Anchor type: "plane", "hand", "face", "image", "world", "geo", "mesh" - `name`: `string` (read-only) - Optional name for this anchor - `worldTransform`: `Transform` (read-only) - World-space transform matrix for anchor position and orientation - `isTracked`: `boolean` (read-only) - Whether this anchor is currently being tracked (image, face, hand anchors) - `alignment`: `string` (read-only) - Plane alignment: "horizontal" or "vertical" (plane anchors only) - `classification`: `string` (read-only) - Plane classification: "floor", "ceiling", "wall", "table", "seat", "window", "door" (plane anchors only) - `width`: `number` (read-only) - Plane width in meters (plane anchors only) - `height`: `number` (read-only) - Plane height in meters (plane anchors only) - `referenceImageName`: `string` (read-only) - Reference image name from ARReferenceImage (image anchors only) - `estimatedScaleFactor`: `number` (read-only) - Estimated scale factor of detected image (image anchors only) - `chirality`: `string` (read-only) - Hand chirality: "left" or "right" (hand anchors only, visionOS) - `joints`: `Array` (read-only) - Hand joint transforms by name - `orderedJointTransforms`: `Array` (read-only) - Ordered joint transforms for skeletal animation (hand anchors only) - `blendShapes`: `Array` (read-only) - Blend shape coefficients for facial expressions - `leftEyeTransform`: `Transform` (read-only) - Left eye transform in face coordinate space (face anchors only) - `rightEyeTransform`: `Transform` (read-only) - Right eye transform in face coordinate space (face anchors only) - `lookAtPoint`: `Vector3` (read-only) - Estimated gaze direction point in face coordinate space (face anchors only) - `latitude`: `number` (read-only) - Geographic latitude in degrees (geo anchors only, iOS) - `longitude`: `number` (read-only) - Geographic longitude in degrees (geo anchors only, iOS) - `altitude`: `number` (read-only) - Altitude in meters (geo anchors only, iOS) ### `AudioStream` Streaming audio player for real-time audio playback Used for continuous audio streams like OpenAI Realtime API **Properties:** - `isDrained`: `boolean` (read-only) - Whether the audio buffer has finished playing Use this to wait for playback to complete before resuming microphone **Methods:** - `append(base64: string)` → `void` - Append base64-encoded audio data to the stream buffer - `stop()` → `void` - Stop playback and release resources ### `BoundingBox` Axis-aligned bounding box for collision and visibility testing **Properties:** - `min`: `Vector3` - Minimum corner of the box - `max`: `Vector3` - Maximum corner of the box - `center`: `Vector3` (read-only) - Center point of the box - `extents`: `Vector3` (read-only) - Size of the box along each axis (max minus min), in metres - `boundingRadius`: `number` (read-only) - Radius of bounding sphere - `isEmpty`: `boolean` (read-only) - Whether the box has zero volume **Methods:** - `create(min: Vector3, max: Vector3)` → `BoundingBox` - Create a bounding box from min/max corners - `createEmpty()` → `BoundingBox` - Create an empty bounding box - `contains(box: BoundingBox, point: Vector3)` → `boolean` - Check if a point is inside the box - `containsBox(box1: BoundingBox, box2: BoundingBox)` → `boolean` - Check if one box fully contains another - `intersects(box1: BoundingBox, box2: BoundingBox)` → `boolean` - Check if two boxes intersect **Runtime Extensions:** - `contains(point: Vector3)` → `boolean` - Check if point is inside bounding box - `containsBox(other: BoundingBox)` → `boolean` - Check if another bounding box is fully contained - `intersects(other: BoundingBox)` → `boolean` - Check if bounding boxes intersect ### `CollisionCastHit` Result from scene.raycast() when ray intersects an entity or scene mesh **Properties:** - `type`: `string` (read-only) - Hit type - "representation" or "sceneMesh" - `representation`: `RepresentationEntity` (read-only) - The entity that was hit (nil for scene mesh hits) - `position`: `Vector3` (read-only) - World-space position where ray hit the entity - `normal`: `Vector3` (read-only) - Surface normal at hit point - `distance`: `number` (read-only) - Distance from ray origin to hit point - `shapeIndex`: `number | null` (read-only) - Index of the shape within the entity that was hit (iOS 18+) - `faceIndex`: `number | null` (read-only) - Index of the triangle face that was hit (iOS 18+, mesh collisions only) - `uv`: `Vector2` (read-only) - Barycentric UV coordinate on the triangle (iOS 18+, mesh collisions only) ### `Color` RGBA color with components in 0-1 range **Properties:** - `r`: `number` - Red component (0-1) - `g`: `number` - Green component (0-1) - `b`: `number` - Blue component (0-1) - `a`: `number` - Alpha component (0-1) **Methods:** - `create(r: number, g: number, b: number, a: number)` → `Color` - Create a color from RGBA values - `lerp(c1: Color, c2: Color, t: number)` → `Color` - Linearly interpolate between two colors **Runtime Extensions:** - `lerp(other: Color, t: number)` → `Color` - Linearly interpolate to another color ### `Buffer` Raw GPU buffer wrapping a typed scratch region for compute kernels. Use for things meshes + textures don't model: atomic counters, lookup tables (e.g. marching cubes' triangle / edge tables), per-particle state, scratch arrays between kernel passes. **Properties:** - `id`: `string` (read-only) - Stable handle id assigned at construction. Surfaces in the scripting manager's live-set; used by `destroy()` to release the experience-lifetime retention. - `elementType`: `string` (read-only) - Element type as a scripting string (`"float32"`, `"uint32"`, `"uint8"`, `"atomic_uint"`). - `length`: `number` (read-only) - Number of elements (not bytes). - `byteLength`: `number` (read-only) - Total byte length -- `length * elementSize`. **Methods:** - `readSync()` → `any` - Read the buffer contents back to JS as a TypedArray. Blocks until any compute dispatch still in flight has finished, so the values are the ones the kernel wrote -- use sparingly (typical pattern: read atomic counters after dispatch to size a downstream draw call). - `writeSync(data: any)` → `void` - Write a TypedArray's contents into the buffer (CPU → GPU). Useful for seeding lookup tables, atomic counter resets, particle initial state. Length must match the buffer's declared element count; shorter writes leave the tail untouched. Blocks until any compute dispatch still in flight has finished, so a reset between passes cannot land under a running kernel. - `destroy()` → `void` - Release the underlying GPU buffer immediately. ### `Kernel` Opaque handle to a compiled GPU compute kernel. Returned by `Kernel.fromSource(...)` / `Kernel.fromAsset(...)`. Two dispatch entry points: `kernel.run({...})` for standalone compute (texture / buffer I/O, no mesh involvement) and `mesh.runCompute(kernel, options)` when the kernel writes mesh-attribute buffers. **Properties:** - `id`: `string` (read-only) - Stable handle id assigned at construction. Surfaces in the scripting manager's live-set; used by `destroy()` to release the experience-lifetime retention. - `functionName`: `string` (read-only) - Display name of the kernel's entry-point function. **Methods:** - `destroy()` → `void` - Release the kernel's GPU resources (compiled library + pipeline state) immediately. Use in hot loops where JSC's non-deterministic GC would otherwise stretch the lifetime. Normal scripts don't need to call this -- ARC handles cleanup when the kernel goes out of scope. Calling `mesh.runCompute(...)` or `kernel.run(...)` against a destroyed kernel warns and aborts the dispatch. - `run(options: any)` → `void` - Dispatch the kernel against textures and / or `Buffer` handles -- no mesh involvement. Use for compute passes that don't write mesh attribute buffers (texture generation, particle simulation pre-pass, any "pure compute" kernel that doesn't displace geometry). ### `Mesh` Scriptable dynamic mesh with CPU-driven vertex and index updates. **Properties:** - `vertexCapacity`: `number` (read-only) - Maximum vertex count the mesh was allocated for. Read-only -- the underlying buffer is sized at creation. To grow, create a new mesh. - `indexCapacity`: `number` (read-only) - Maximum index count the mesh was allocated for. - `partCount`: `number` (read-only) - Number of parts (draw ranges) on the mesh. - `drawCount`: `number` - Convenience getter/setter for single-part meshes. - `attributes`: `any` (read-only) - Read-only summary of the mesh's attribute layout: an object keyed by attribute name with `{ semantic, format, storage }` fields. Useful for introspection ("does this mesh have a 'speed' attribute?") and for cross-engine devs who reach for `geometry.attributes` reflexively. **Methods:** - `writeVertices(name: string, vertexOffset: number, data: any)` → `void` - Write packed elements of a single named attribute. - `writeIndices(indexOffset: number, data: any)` → `void` - Write indices starting at slot `indexOffset`. - `updatePart(partIndex: number, options: any)` → `void` - Update a part's metadata. - `replaceParts(parts: any)` → `void` - Replace the entire parts list. Use for dynamic-part-count meshes where each frame's GPU dispatch produces a variable triangle count (marching cubes, fluid surface, voxel terrain). Pair with an atomic counter in `outputBuffers` to size the part: - `setBounds(bounds: any)` → `void` - Update the bounds of part 0. - `recomputeBounds(partIndex: number)` → `any` - Recompute and apply min/max bounds for a part from its written vertex positions. - `runCompute(kernel: any, options: any)` → `void` - Dispatch a compute kernel against this mesh's `storage: compute` attribute buffers, optionally the index buffer, plus arbitrary input / output buffers and textures. The renderer waits on the dispatch's command buffer before sampling the mesh. - `setShader(kernel: any, options: any)` → `void` - Runs a compute shader's update on this mesh every frame, or once, in place of its Shader slot, until the object next loads. Pass `null` to stop it. With `recalculateNormals: true` the normals are recomputed from the triangles after each run, as the Shader slot's Recalculate Normals does. - `recalculateNormals()` → `void` - Recomputes the normals once from the triangles, after `runCompute` or `writeVertices` moved the points. Points and lines are left as they are. - `setParameter(name: string, value: any, typeHint: any)` → `Mesh` - Sets a parameter of the shader running on this mesh, the Shader slot's or one set with `setShader`, until the object next loads. An unknown name is reported in the console. ### `TextureBinding` Marker token returned by `texture.read` / `texture.write`. Carries the backing texture and the role so dispatch knows whether to bind the texture as a kernel read source or write target. **Methods:** ### `Texture` A GPU texture created and managed at runtime. Construct one from an image or video source (`Texture.image(...)`, `Texture.video(...)`), the live camera feed (`Texture.cameraFeed()`), or a compute kernel that writes its pixels (`Texture.compute(...)`). **Properties:** - `id`: `string` (read-only) - Texture id -- matches `dynamicTexture.id`. Stable for the lifetime of the texture; surfaces in material `TextureReference.dynamic` references. - `width`: `number` (read-only) - `height`: `number` (read-only) - `depth`: `number` (read-only) - Depth (slices) for 3D textures, layer count for arrays. `1` for flat 2D / cubemap-face textures. - `textureType`: `string` (read-only) - Texture dimensionality: `"2d"`, `"3d"`, `"cube"`, `"2dArray"`, `"cubeArray"`. - `pixelFormat`: `string` (read-only) - Engine-agnostic pixel format name (e.g. `"rgba32Float"`). - `read`: `TextureBinding` (read-only) - Token tagged as "read into kernel" -- pass to a kernel's `inputTextures` map. - `write`: `TextureBinding` (read-only) - Token tagged as "write from kernel" -- pass to a kernel's `outputTextures` map. **Methods:** - `generateMipmaps()` → `void` - Generate the mipmap chain. Runs a synchronous GPU mipmap-generation pass against the texture's command queue. Requires the texture was allocated with `mipmapLevelCount > 1`. No-op on textures without a mip chain. - `setParameter(name: string, value: any, typeHint: any)` → `Texture` - Sets a setting of the shader that draws a Library texture, on the running copy only: the texture in Library > Textures keeps its value. Converts the value as `Material.setParameter` does, and replaces a setting bound to a variable. A texture whose shader runs once runs once more with the new value. - `destroy()` → `void` - Release the texture's GPU memory immediately. ### `ObjectEntity` Entity in the scene **Properties:** - `id`: `string` (read-only) - Unique entity identifier - `representation`: `RepresentationEntity` (read-only) - Primary representation (visual/model) - `position`: `Vector3` - Offset from the placement authored in the editor, in metres, in the object's authored frame. Reads zero until a script, physics or a gesture moves the object; `worldPosition` is where the object is. - `rotation`: `Rotation` - Rotation on top of the authored rotation, as a quaternion; identity until something turns the object, and `worldRotation` is its orientation in the scene. Assign a whole `Rotation`; per-component quaternion mutation is not meaningful, so use `rotation`/`eulerAngles` assignment or animateTo. - `eulerAngles`: `Vector3` - Rotation on top of the authored rotation, as euler angles in radians. - `scale`: `Vector3` - Scale on top of the authored scale; one until something scales the object, and `worldScale` is its scale in the scene. - `transform`: `Transform` - Position, rotation and scale on top of the authored placement, combined. - `worldPosition`: `Vector3` - World-space position - `worldRotation`: `Rotation` - World-space rotation as quaternion - `worldEulerAngles`: `Vector3` - World-space rotation as euler angles (radians) - `worldScale`: `Vector3` - World-space scale - `worldTransform`: `Transform` - World-space transform - `boundingBox`: `BoundingBox` (read-only) - Local bounding box - `worldBoundingBox`: `BoundingBox` (read-only) - World-space bounding box - `opacity`: `number` - Opacity (0-1) - `isEnabled`: `boolean` - Whether this representation is enabled/visible - `instances`: `Object | null` (read-only) - The instance transform buffer, for handing to a compute kernel. Proxies to the primary representation. `null` until `setInstances(...)` has run, and on any OS below the instancing requirement. **Methods:** - `findRepresentation(query: any)` → `RepresentationEntity` - Find a representation by ID or name **Runtime Extensions:** - `on(type: string, options: Object | function, listener: function)` → `string` - Register an entity event listener - `off(eventId: string)` → `void` - Remove an entity event listener - `once(type: string, options: Object | function, listener: function)` → `string` - Register a one-time entity event listener - `playAudio(source: string, options: Object, options.gain: number, options.loops: boolean, options.inputMode: string)` → `Promise` - Play audio asset on this entity - `playAudioBuffer(base64: string, options: Object, options.sampleRate: number, options.channels: number, options.format: string, options.gain: number)` → `Promise` - Play audio buffer on this entity - `stopAudio()` → `Promise` - Stop audio playback on this entity - `setMaterials(materials: Array)` → `Promise` - Set materials on this entity's representation - `setMaterial(options: Object)` → `Promise` - Set material on this entity's representation - `createAudioStream(options: Object)` → `AudioStream` - Create a streaming audio player on this entity - `waitUntilReady()` → `Promise` - Wait until this entity's primary representation has finished loading. Convenience that proxies to `entity.representation.waitUntilReady()`. Resolves immediately if there's no primary representation. - `remove()` → `Promise` - Remove this entity from the scene - `clone(options: Object, options.position: Vector3, options.rotation: Rotation, options.scale: Vector3, options.anchor: Object, options.enabled: boolean, options.id: string)` → `Promise` - Deep-copy this object and add the copy to the scene. The copy carries fresh ids, so it behaves like any other object -- attach events, move it, remove it independently. Pose overrides merge into the copy's transform, so an omitted field keeps this object's value. If this object was authored "disabled by default" (a common template pattern), the copy is added hidden with its physics body off until you `toggle(true)` it -- so a batch can be revealed together on one frame. Cloning rejects past 512 live copies of one source object. That ceiling exists only to stop a runaway loop (`while (true) clone()`) from exhausting memory -- reaching it means a bug, not a budget. Remove copies you no longer need with `entity.remove()`. - `toggle(enabled: boolean)` → `Promise` - Enable or disable this entity's representation - `play(animation: Animation)` → `Promise` - Play an animation on this entity's representation - `followPath(path: Path, options: Object, options.repeat: boolean | number)` → `void` - Move this entity along a path from scene.createPath(...). - `toggleAnimations(options: Object, options.play: boolean, options.animationIds: Array)` → `Promise` - Toggle (pause/resume) animations on this entity's representation - `stopAnimations(options: Object, options.transitionDuration: number)` → `Promise` - Stop and remove animations from this entity's representation - `animateTo(properties: Object, properties.position: Vector3, properties.rotation: Rotation, properties.scale: Vector3, properties.transform: Transform, properties.opacity: number, duration: number, options: Object, options.timingFunction: string | Object, options.delay: number, options.repeatCount: number, options.repeatMode: string)` → `Promise` - Animate this entity's representation to target properties - `animateFromTo(fromProperties: Object, toProperties: Object, duration: number, options: Object)` → `Promise` - Animate this entity's representation from starting to target properties - `animateBy(properties: Object, duration: number, options: Object)` → `Promise` - Animate this entity's representation by relative values (additive animation) - `applyImpulse(impulse: Vector3, options: Object)` → `Promise` - Push this object with a one-off force. Proxies to the primary representation. - `applyAngularImpulse(impulse: Vector3, options: Object)` → `Promise` - Spin this object with a one-off rotational force. Proxies to the primary representation. - `setPhysicsMode(mode: string)` → `void` - Set the physics body mode at runtime. Proxies to the primary representation. - `setVelocity(velocity: Vector3)` → `void` - Set the world-space linear velocity of this object's physics body. Proxies to the primary representation. - `setAngularVelocity(angularVelocity: Vector3)` → `void` - Set the world-space angular velocity of this object's physics body (axis-angle, radians per second). Proxies to the primary representation. - `setInstances(transforms: Object | Array)` → `void` - GPU-instance this object's mesh -- draw one copy per transform. Proxies to the primary representation. Pass `Instances.transforms([...])` or a bare array of `Transform` / `Vector3`. Rendering-only; gate with `environment.features.has('instancing')`. - `clearInstances()` → `void` - Remove instancing from this object, reverting to the single base mesh. Proxies to the primary representation. ### `RepresentationEntity` Visual representation of an entity (model, shape, etc.) **Properties:** - `id`: `string` (read-only) - Unique representation identifier - `entity`: `ObjectEntity` (read-only) - Parent entity - `opacity`: `number` - Opacity (0-1) - `isEnabled`: `boolean` - Whether this representation is enabled/visible - `position`: `Vector3` - Offset from the placement authored in the editor, in metres, in the object's authored frame. Reads zero until a script, physics or a gesture moves the object; `worldPosition` is where the object is. - `rotation`: `Rotation` - Rotation on top of the authored rotation, as a quaternion; identity until something turns the object, and `worldRotation` is its orientation in the scene. Assign a whole `Rotation`; per-component quaternion mutation is not meaningful, so use `rotation`/`eulerAngles` assignment or animateTo. - `eulerAngles`: `Vector3` - Rotation on top of the authored rotation, as euler angles in radians. - `scale`: `Vector3` - Scale on top of the authored scale; one until something scales the object, and `worldScale` is its scale in the scene. - `transform`: `Transform` - Position, rotation and scale on top of the authored placement, combined. - `worldPosition`: `Vector3` - World-space position - `worldRotation`: `Rotation` - World-space rotation as quaternion - `worldEulerAngles`: `Vector3` - World-space rotation as euler angles (radians) - `worldScale`: `Vector3` - World-space scale - `worldTransform`: `Transform` - World-space transform - `boundingBox`: `BoundingBox` (read-only) - Local bounding box - `worldBoundingBox`: `BoundingBox` (read-only) - World-space bounding box - `rootView`: `UIView` (read-only) - Root view of the panel content. Nil unless this representation's kind is `.userInterface`. - `mesh`: `Mesh` (read-only) - Dynamic mesh handle for this representation. Nil unless the kind is `.dynamicMesh`. Use this to write vertex/index buffers and update per-part bounds from a script. Bulk-copy semantics -- one call moves many vertices, no per-element overhead. - `light`: `Light` (read-only) - Light handle for this representation. Nil unless the kind is `.light`. Reads and writes go to the running scene, not the saved experience. - `particles`: `Particles` (read-only) - Particle emitter handle for this representation. Nil unless the kind is a particle system. `burst()` and `isEmitting` work on every particle representation; the other properties need an emitter built in the editor. Writes go to the running scene, not the saved experience. - `splat`: `Splat` (read-only) - Gaussian splat handle for this representation. Nil unless the kind is `.gaussianSplat`. Vends `count` and a read / write token per GPU attribute, for compute kernels. - `instances`: `InstanceData` (read-only) - The instance transform buffer, for handing to a compute kernel. **Methods:** - `findRepresentation(query: any)` → `RepresentationEntity` - Find a child representation by ID or name - `findChild(name: string, recursive: any)` → `Entity` - Find a nested entity by name within the model hierarchy - `getChildNames()` → `Array` - List all nested entity names (for discovery) - `toggleWithAnimation(enable: boolean)` → `void` - Toggle visibility with fade animation - `guideTo(target: any, options: any)` → `void` - Points the direction indicator at a part of this object, or at the whole object, on iPhone, iPad and Mac. - `findView(query: any)` → `UIView` - Find a view in this representation's UI tree by ID or name - `bindMaterialParameter(parameterName: string, variableId: string, options: any)` → `void` - Bind a material parameter to a variable for automatic updates - `unbindMaterialParameter(parameterName: string, options: any)` → `void` - Remove a variable binding from a material parameter - `setPhysicsMode(mode: string)` → `void` - Set the physics body mode at runtime: `"static"`, `"kinematic"`, or `"dynamic"`. - `setVelocity(velocity: Vector3)` → `void` - Set the world-space linear velocity of this representation's physics body. - `setAngularVelocity(angularVelocity: Vector3)` → `void` - Set the world-space angular velocity of this representation's physics body (axis-angle, radians per second). The linear velocity is preserved. The rotational counterpart of `setVelocity` -- e.g. give a thrown object spin. - `setInstances(transforms: any)` → `void` - GPU-instance this representation's mesh -- draw one copy per transform, at a fraction of the cost of real entities. Pass `Instances.transforms([...])` (or a bare array of `Transform` / `Vector3`, where a `Vector3` places a copy at that position). Applies to every mesh in the representation. - `followPath(path: Path, options: any)` → `void` - Move this entity along a path (from `scene.createPath`). - `clearInstances()` → `void` - Remove instancing from this representation, reverting to the single base mesh. **Runtime Extensions:** - `on(type: string, options: Object | function, listener: function)` → `string` - Register an event listener on this representation - `off(eventId: string)` → `void` - Remove an event listener from this representation - `once(type: string, options: Object | function, listener: function)` → `string` - Register a one-time event listener on this representation - `playAudio(source: string, options: Object, options.gain: number, options.loops: boolean, options.inputMode: string)` → `Promise` - Play audio asset on this representation - `stopAudio()` → `Promise` - Stop audio playback on this representation - `playAudioBuffer(base64: string, options: Object, options.sampleRate: number, options.channels: number, options.format: string, options.gain: number)` → `Promise` - Play audio buffer spatially on this representation - `createAudioStream(options: Object, options.sampleRate: number, options.channels: number, options.format: string)` → `AudioStream` - Create a streaming audio player on this representation - `waitUntilReady()` → `Promise` - Wait until this representation's model assets have finished loading and been attached to the scene. Many setup calls -- `bindMaterialParameter`, transform reads, animation triggers -- depend on the model being present. On `onWillAppear` the representation proxy exists but the model itself usually hasn't been attached yet, and calling those methods too early silently no-ops. Await this before any model-dependent setup. - `toggle(enabled: boolean)` → `Promise` - Enable or disable this representation - `play(animation: Animation)` → `Promise` - Play an animation on this representation - `toggleAnimations(options: Object, options.play: boolean, options.animationIds: Array)` → `Promise` - Toggle (pause/resume) animations on this representation - `stopAnimations(options: Object, options.transitionDuration: number)` → `Promise` - Stop and remove animations from this representation - `animateTo(properties: Object, duration: number, options: Object)` → `Promise` - Animate this representation to target properties - `animateFromTo(fromProperties: Object, toProperties: Object, duration: number, options: Object)` → `Promise` - Animate this representation from starting to target properties - `animateBy(properties: Object, duration: number, options: Object)` → `Promise` - Animate this representation by relative values - `setBlendShapeWeights(weights: Object | number, options: Object, options.modelName: string, options.weightSetIndex: number, options.weightSetId: string)` → `void` - Update blend shape weights on this representation (for models with morph targets/blend shapes) - `resetBlendShapeWeights(options: Object)` → `void` - Reset all blend shape weights to zero - `setMaterials(materials: Array, materials[].id: string, materials[].target: Object, materials[].target.type: string, materials[].target.models: Array, materials[].target.materialSlots: Array)` → `Promise` - Set materials on this representation - `setMaterial(options: Object, options.id: string, options.target: Object, options.target.type: string, options.target.models: Array, options.target.materialSlots: Array)` → `Promise` - Set material on this representation - `applyImpulse(impulse: Vector3, options: Object, options.space: string | Object, options.at: Vector3 | string)` → `Promise` - Push this representation with a one-off force. The object needs a dynamic physics body -- see `t.physics({ mode: 'dynamic' })`. - `applyAngularImpulse(impulse: Vector3, options: Object, options.space: string | Object)` → `Promise` - Spin this representation with a one-off rotational force. The rotational counterpart of `applyImpulse`. There is no application point -- an angular impulse acts on the body as a whole. ### `EngineBufferBinding` Marker token for a GPU buffer the engine owns and renders from, as opposed to the scratch regions a script's own `Buffer` allocates. Mirrors `TextureBinding`: a role plus a way back to the memory, resolved at dispatch. **Methods:** ### `Entity` Generic entity within a model hierarchy (bones, groups, nested models) **Properties:** - `name`: `string` (read-only) - Entity name - `isEnabled`: `boolean` - Whether this entity is enabled/visible - `opacity`: `number` - Opacity (0-1) - `position`: `Vector3` - Local position relative to parent - `rotation`: `Rotation` - Local rotation as quaternion - `scale`: `Vector3` - Local scale - `transform`: `Transform` - Local transform (position, rotation, scale combined) - `worldPosition`: `Vector3` - World-space position - `worldRotation`: `Rotation` - World-space rotation - `worldTransform`: `Transform` - World-space transform - `boundingBox`: `BoundingBox` (read-only) - Bounding box of this entity and its descendants, relative to its parent - `worldBoundingBox`: `BoundingBox` (read-only) - World-space bounding box of this entity and its descendants - `jointNames`: `Array` (read-only) - Joint names for skeletal animation (empty if not a skeletal model) - `jointTransforms`: `Array` - Joint transforms array (parallel to jointNames) - `children`: `Array` (read-only) - Direct child entities - `instances`: `InstanceData` (read-only) - The instance transform buffer, for handing to a compute kernel. `null` until `setInstances(...)` has run, and on any OS below the instancing requirement. **Methods:** - `findChild(name: string, recursive: any)` → `Entity` - Find a child entity by name - `setInstances(transforms: any)` → `void` - GPU-instance this node's mesh -- draw one copy per transform. Pass `Instances.transforms([...])` (or a bare array of `Transform` / `Vector3`). Rendering-only (no physics / collision / identity). Gate with `environment.features.has('instancing')` (iOS 26 / visionOS 26 / macOS 26+). - `clearInstances()` → `void` - Remove instancing from this node, reverting to the single base mesh. ### `EnvironmentFeatures` Capability registry exposed at `environment.features`. **Methods:** - `has(name: string)` → `boolean` - Whether the named feature is supported on the current platform and runtime version. Unknown names return `false` (WebGPU `Set.has` semantic). - `list()` → `Array` - Every feature string currently supported on this device/runtime. Useful for debugging ("why isn't my branch firing?") and for reflecting the capability set into telemetry. ### `Environment` **Properties:** - `hostingPlatform`: `string` (read-only) - The platform running the experience: "iOS", "macOS", "visionOS", or "web" - `deviceCategory`: `string` (read-only) - The device form factor: "handheld" (iPhone, iPad), "spatial" (Apple Vision Pro and other headsets), or "desktop" (Mac, desktop web). Prefer this over `hostingPlatform` when branching on the *interaction model* rather than the exact OS -- e.g. screen gestures exist on handheld and desktop but not spatial, where input is the user's eyes and hands. - `systemOSVersion`: `string` (read-only) - Operating system version string, e.g. "18.0" or "2.0" - `locale`: `string` (read-only) - User's locale in BCP 47 format, e.g. "en-US", "de-DE" - `isEditing`: `boolean` (read-only) - `true` when the experience is running inside the Scenery editor's scene preview, `false` during normal playback. Lets scripts gate debug overlays, skip intros, or auto-fill placeholder state while the author is iterating. - `features`: `EnvironmentFeatures` (read-only) - Runtime + device capability registry. Authors query by string -- `environment.features.has('compute')` -- to branch on whether the current platform supports a given feature. Mirrors WebGPU's `adapter.features.has(...)` shape so portable scripts read the same on both backends. - `location`: `Location` (read-only) - The user's device location. Coarse reads ride the base grant; the precise tier is opted into explicitly. See `Location`. - `accessibility`: `Accessibility` (read-only) - The accessibility settings a script can adapt to, such as Reduce Motion. See `Accessibility`. **Methods:** ### `Experience` **Properties:** - `currentScene`: `Scene` (read-only) - The current scene - `environment`: `Environment` (read-only) - Environment information (platform, OS version, locale) - `sharedActivity`: `SharedActivity` (read-only) - Shared activity state (SharePlay, WebSocket, or other shared session protocols) - `language`: `any` - The language the experience's texts show in, as a BCP 47 code such as `"de"`, or `undefined` when the experience has no translations. **Methods:** - `setVariable(id: string, value: any, options: any)` → `void` - Set an experience-scoped variable (persists across scene transitions) - `getVariable(id: string)` → `any` - Get an experience-scoped variable - `transitionToScene(id: string)` → `void` - Transition to another scene - `localize(key: string, values: any)` → `string` - Returns a shared text in the experience's language, with each `${name}` replaced by `values.name`. **Runtime Extensions:** - `openScreen(name: string)` → `Promise` - Show one of the experience's screens, made in the editor's Screens section, as Open Screen does. The screen appears with its own Reveal Animation, on top of anything already showing. Opening a screen that is already open does nothing and resolves with it. - `closeScreen(name: string)` → `Promise` - Close one of the experience's screens, as Close Screen does. The screen leaves with its own Removal Animation. Without a name, closes the screen whose event ran this script. ### `HTTPClient` HTTP client for making network requests Supports GET, POST, and custom requests with authentication **Methods:** - `get(url: string, callback: any)` → `void` - Make a GET request and parse the response as JSON. For text or binary, use `request()` with `responseType`. - `post(url: string, body: string, callback: any)` → `void` - Make a POST request - `request(url: string, options: Array, callback: any)` → `void` - Make a custom HTTP request ### `InstanceData` The GPU buffer behind an entity's mesh instances, for handing to a compute kernel. **Properties:** - `count`: `number` (read-only) - How many instances the entity draws. Size a dispatch from this, and guard on it in the kernel: a thread past the end writes into memory the renderer is using. - `read`: `EngineBufferBinding` (read-only) - Token tagged as "read into kernel". Returns the transforms as the renderer last saw them. - `write`: `EngineBufferBinding` (read-only) - Token tagged as "write from kernel". The buffer arrives uninitialised, so the kernel has to write every element it is dispatched over. One `float4x4` per instance, column-major, so column 3 is the translation, in the instanced mesh's own space rather than the space `rep.setInstances(...)` accepts. - `meshToLocal`: `Array` (read-only) - Converts a distance or position from the buffer's units into metres, as 16 numbers in column-major order, ready to hand a kernel as uniforms. Its scale, element 0, is the conversion factor on its own. - `localToMesh`: `Array` (read-only) - Converts a distance or position from metres into the buffer's units. Multiply an offset in metres by its scale, element 0, before adding it to an instance's translation. The inverse of `meshToLocal`, same 16-number column-major layout. **Methods:** ### `Light` A light in the running scene. **Properties:** - `type`: `string` (read-only) - Which light this is: `"spot"`, `"point"` or `"directional"`. Read-only -- the three types take different parameters, so switching one for another is creating a different light. - `intensity`: `number` - Brightness. Lumens for a spot or point light, lux for a directional one, so the same number means different things across the three. - `color`: `Color` - The colour the light emits. White leaves surfaces their own colour. - `innerAngle`: `number` - The cone that receives the light's full intensity, in degrees. Spot only; reading it on another type returns 0 and writing is ignored with a warning. Clamped to the outer angle, which is what the renderer requires. - `outerAngle`: `number` - The cone at which the light has fallen to nothing, in degrees. Between the two angles it fades. Spot only. - `attenuationRadius`: `number` - The distance in metres at which the light's contribution reaches zero. Spot and point only -- a directional light shines from infinitely far away. - `falloffExponent`: `number` - How quickly the light fades with distance. 2 is physically correct; lower carries further. Spot and point only. - `projectedTextureRotation`: `number` - Rotation of the projected texture within the cone, in radians. Spot only, and only where `environment.features.has('projectedLightTexture')` is true. - `projectedTextureOffset`: `Vector2` - Shifts the projected texture within the cone. Spot only, and only where `environment.features.has('projectedLightTexture')` is true. - `projectedTextureScale`: `Vector2` - Tiles the projected texture within the cone, `1, 1` being the authored size. Spot only, and only where `environment.features.has('projectedLightTexture')` is true. **Methods:** ### `Location` The user's device location, exposed to scripting as `environment.location`. Coarse reads ride the base grant; precise accuracy is an explicit opt-in. **Properties:** - `authorizationStatus`: `string` (read-only) - Current authorization: "notDetermined" | "denied" | "restricted" | "granted". - `accuracyAuthorization`: `string` (read-only) - Current accuracy authorization: "full" | "reduced" | "unknown". **Methods:** **Runtime Extensions:** - `requestAccess()` → `Promise` - Request base location access. Prompts once if undetermined; resolves the resulting authorization status. Reads never prompt on their own. - `current(options: Object)` → `Promise` - Read the current location once. - `requestPreciseAccess(options: Object)` → `Promise` - Request precise (full) accuracy. Shows a confirmation carrying `options.reason` (once per run), then the OS accuracy prompt. Resolves whether precise is now active. - `watch(onPosition: any, options: Object)` → `any` - Observe location continuously. `onPosition` receives a GeoCoordinate. - `on(event: string, callback: function)` → `any` - Subscribe to a location event. Supported: 'authorizationchange' → callback(status). ### `Microphone` Microphone audio streaming Access via `scene.microphone` **Properties:** - `onData`: `any` - Callback for audio data chunks (base64-encoded PCM16) - `onError`: `any` - Callback for errors (permission denied, etc.) - `isStreaming`: `boolean` (read-only) - Whether the microphone is currently streaming **Methods:** - `start()` → `void` - Start capturing audio - `stop()` → `void` - Stop capturing audio - `configure(options: Array)` → `void` - Configure microphone settings ### `Particles` A particle emitter in the running scene. **Properties:** - `birthRate`: `number | null` - Particles born per second while the emitter emits. - `speed`: `number | null` - How fast a particle leaves the emitter, in metres per second. - `size`: `number | null` - A particle's size when it is born, in metres. - `lifeSpan`: `number | null` - How long a particle lives, in seconds. - `color`: `Color` - The colour particles are born with. Where the authored colour changes over a particle's life, writing this replaces the start colour and keeps the end colour. A random pair is replaced by the single colour written. - `endColor`: `Color` - The colour particles fade to by the end of their life, or `null` when the colour does not change. Writing it to an emitter with one colour makes the colour change over a particle's life. - `acceleration`: `Vector3` - The force on each particle, in metres per second squared. Use a negative `y` for gravity. - `isEmitting`: `boolean` - Whether the emitter releases new particles. Turning it off lets the particles already born finish their life. **Methods:** - `burst()` → `void` - Releases one burst of particles at once, as many as the emitter's burst count. ### `Path` Runtime path handle returned by `scene.createPath(...)`. Read-only spline queries; consumed by `entity.followPath(...)`. Not persisted (v1). **Properties:** - `length`: `number` (read-only) - Total arc length of the path, in meters. **Methods:** - `point(t: number)` → `Vector3` - Position at parameter `t` (0...1 across the whole path). - `pointAtDistance(d: number)` → `Vector3` - Position at arc-length distance `d` (0...`length`) -- constant-speed spacing. - `tangent(t: number)` → `Vector3` - Unit tangent (direction of travel) at parameter `t`. ### `Effect` A post-processing effect of the experience, as a script changes it while it runs. Get one with `scene.getEffect(id)`. Changes apply to the running effect only, never to the stored one, and they last while the experience runs, also when a scene change or an action shows the effect again. **Properties:** - `id`: `string` (read-only) - The effect's id in the experience. **Methods:** - `setParameter(name: string, value: any, typeHint: any)` → `Effect` - Sets a parameter of the effect's shader. Converts the value as `Material.setParameter` does, and replaces a parameter bound to a variable. A name the shader does not have is reported in the console. - `shaderTexture(name: string, texture: any)` → `Effect` - Binds a texture to one of the effect shader's named texture slots. Takes what `Material.shaderTexture` takes: a URL, an asset id or a texture handle, and a texture handle keeps updating in the slot. A slot the shader does not have, a texture of another kind than the slot reads, or one that fails to load is reported in the console. ### `Ray` A ray with origin and direction, useful for raycasting **Properties:** - `origin`: `Vector3` (read-only) - Ray starting point in world space - `direction`: `Vector3` (read-only) - Normalized ray direction ### `Rotation` Rotation represented as a quaternion **Properties:** - `quaternion`: `Vector4` - Quaternion components (x, y, z, w) - `eulerAngles`: `Vector3` - Euler angles in radians (x, y, z) **Methods:** - `create()` → `Rotation` - Create identity rotation (no rotation) - `slerp(r1: Rotation, r2: Rotation, t: number)` → `Rotation` - Spherically interpolate between two rotations - `multiply(r1: Rotation, r2: Rotation)` → `Rotation` - Multiply two rotations (compose) - `inverse(r: Rotation)` → `Rotation` - Get the inverse (conjugate) of a rotation **Runtime Extensions:** - `slerp(other: Rotation, t: number)` → `Rotation` - Spherically interpolate to another rotation - `multiply(other: Rotation)` → `Rotation` - Multiply (compose) with another rotation - `inverse()` → `Rotation` - Get the inverse of this rotation ### `Scene` **Properties:** - `id`: `string` (read-only) - Scene identifier - `time`: `number` (read-only) - Time elapsed since scene started (seconds) - `microphone`: `Microphone` (read-only) - Microphone audio streaming - `cameraTransform`: `Transform` (read-only) - Current camera transform in world space - `viewportSize`: `Vector2` (read-only) - Viewport size in points (iOS only) **Methods:** - `setVariable(id: string, value: any, options: any)` → `void` - Set a scene-scoped variable (cleared on scene transition) - `getVariable(id: string)` → `any` - Get a scene-scoped variable - `setBloom(options: any)` → `void` - Make bright pixels glow. Pass `null` to switch it off. - `setAmbientOcclusion(options: any)` → `void` - Darken creases, corners and the ground under objects. Pass `null` to switch it off. - `setToneMapping(options: any)` → `void` - Set the scene's tone curve -- how brightness is mapped onto the display. Pass `null` to return to the platform default. - `getEffect(id: string)` → `Effect` - Fetch a shader effect of the experience by id, to change its settings and textures while it runs. Changes reach the running effect only; the stored effect keeps its values. - `findEntity(query: any)` → `ObjectEntity` - Find an entity by ID or name - `triggerCustomEvent(query: any)` → `void` - Trigger one or more custom-trigger events. - `cancelNamedActions(name: string)` → `void` - Stops every running Group and Sequence action with this name, including one the calling script runs inside. - `getCustomEvents()` → `Array` - List custom-trigger scene events on the current segment. Useful for debug panels that enumerate triggerable events at runtime. Each entry has the event's `id`, optional `name` (omitted when unset), and `isEnabled` flag. System events (tap, render, screenTap, schedule, etc.) are not included -- those are handled by the engine, not scripted. - `getAnchors(kind: string)` → `Array` - Get detected AR anchors - `projectToScreen(worldPosition: Vector3)` → `Vector2` - Convert world position to normalized screen coordinates (iOS only) - `screenToRay(normalizedPosition: Vector2)` → `Ray` - Convert normalized screen coordinates to a ray for raycasting (iOS only) - `raycast(origin: Vector3, direction: Vector3)` → `Array` - Cast ray through scene entities and scene mesh - `raycastAR(origin: Vector3, direction: Vector3, target: string, alignment: string)` → `Array` - Cast ray against AR planes (iOS only) - `createPath(options: any)` → `Path` - Create a catmull-rom path from control points. - `createAudioStream(options: Array)` → `AudioStream` - Create a streaming audio player **Runtime Extensions:** - `getMaterial(id: string)` → `Material` - Fetch a material from the experience's material library by id, hydrated into a live `Material` you can inspect, `.clone()`, and edit. Use the get → `.clone()` → tweak → apply pattern to override a library material on a single object without mutating the library entry. - `getObjectDescriptor(nameOrId: string | Object)` → `ObjectDescriptor | null` - Read an authored object's descriptor so a script can adjust it before it is displayed. Returns an editable ObjectDescriptor (the recipe) -- distinct from `findEntity`, which returns the live entity once it's in the scene. Edit it with the usual chainable methods (`.material`, `.gestures`, `.asset`, `.representation`, ...), then either `scene.setObjectDescriptor(...)` to update it in place, or `.clone()` + `scene.createEntity(...)` to spawn a variant. Ordering: run the edit + set BEFORE the object's Display Element action, in the same event (top level or a Sequence -- not inside a Group, which runs concurrently), and keep the set synchronous (no `await` before it). - `setObjectDescriptor(descriptor: ObjectDescriptor)` → `boolean` - Write an edited descriptor back into the current scene, keyed by its id. Takes effect the next time the object is displayed (edit before its first Display Element for the clean path). If the object is already displayed, the change lands but `displayElement` won't re-apply it -- remove and re-display to see it. - `on(type: string, options: Object | function, listener: function)` → `string` - Register a scene event listener - `off(eventId: string)` → `void` - Remove a scene event listener - `preload(sources: string | Array, options: Object, options.type: string)` → `Promise` - Warm one or more assets so their first use doesn't hitch -- the decode / GPU upload happens now (e.g. during scene setup) instead of on the frame you first play or show them. - `once(type: string, options: Object | function, listener: function)` → `string` - Register a one-time scene event listener - `createEntity(descriptor: ObjectDescriptor)` → `Promise` - Create an object in the scene. - `runAction(action: Action)` → `Promise` - Run an action and wait for completion. - `playAudioBuffer(base64: string, options: Object, options.sampleRate: number, options.channels: number, options.format: string, options.gain: number, options.elementId: string, options.representationId: string)` → `Promise` - Play audio from PCM buffer data - `toggle(entities: Array, isEnabled: boolean)` → `Promise` - Reveal or hide a batch of objects in a single frame. Calling `entity.toggle(true)` in a loop enables each object on its own frame -- so physics bodies start at different times and a stack settles against its half-built self. This runs one grouped action instead, so every object reveals and every physics body starts together. Pairs with cloning a disabled template: clone the batch (each copy stays hidden, physics off), then `scene.toggle(copies, true)` to bring them all up at once. - `playAnimation(objectOrId: string | ObjectEntity, animation: Object, representationId: string)` → `Promise` - Play animation on object - `animateTo(objectOrId: string | ObjectEntity, properties: Object, duration: number, options: Object)` → `Promise` - Animate object to target properties - `animateFromTo(objectOrId: string | ObjectEntity, fromProperties: Object, toProperties: Object, duration: number, options: Object)` → `Promise` - Animate object from starting to target properties - `animateBy(objectOrId: string | ObjectEntity, properties: Object, duration: number, options: Object)` → `Promise` - Animate object by relative values - `emitHaptic(feedback: string | Object)` → `Promise` - Play haptic feedback on the viewer's device. Haptics are device-level rather than positional -- they play on the device no matter which object triggered them -- so this lives on the scene rather than on an entity. Devices without a haptic engine ignore it. - `createSurfaceInput(options: Object, options.target: RepresentationEntity, options.project: string, options.plane: Object, options.plane.axis: string, options.plane.offset: number, options.maxDistance: number)` → `any` - Platform-adaptive surface interaction. Returns a live input source that yields interaction points on a surface, in that surface's LOCAL frame, using whatever input the platform offers -- fingertips on Apple Vision Pro (hand tracking), screen taps / drags on iPhone / iPad / Mac. Your logic reads the same points either way and never branches on platform. Read `input.points` once per frame inside `scene.on('render', ...)`, and call `input.stop()` when done (it tears down the gesture subscriptions). ### `SecretsClient` Mints short-lived credentials for the vendors that issue them. **Methods:** - `mint(name: string, params: Array, callback: any)` → `void` - Mint a credential for one of this experience's secrets. ### `SharedActivity` Shared activity state for multi-user sessions (SharePlay, WebSocket, etc.) **Properties:** - `isActive`: `boolean` (read-only) - Whether a shared activity session is currently active - `isOwner`: `boolean` (read-only) - Whether the local participant is the session owner (presenter) - `participantCount`: `number` (read-only) - Number of remote participants (excludes local participant) - `onMessage`: `any` - Called when a script message is received from another participant - `onOwnershipChanged`: `any` - Called when session ownership changes (session start, transfer, owner leaves, session end) **Methods:** - `send(data: any)` → `boolean` - Send data to all participants (reliable delivery). - `sendFrequent(data: any)` → `boolean` - Send data to all participants (unreliable delivery, suitable for high-frequency updates). ### `SplatAttribute` One attribute's GPU buffer, as a pair of kernel bindings. **Properties:** - `itemSize`: `number` (read-only) - Floats per splat. Buffer length is `splat.count * itemSize`, which is what a kernel's bounds guard and thread count are sized from. Named after three.js `BufferAttribute`. - `read`: `EngineBufferBinding` (read-only) - Token tagged as "read into kernel". Returns the contents as the renderer last saw them. - `write`: `EngineBufferBinding` (read-only) - Token tagged as "write from kernel". The buffer arrives uninitialised, so the kernel has to write every element it is dispatched over. Written values then persist with no further dispatches, so a one-shot effect can stop when it finishes. **Methods:** ### `Splat` The GPU buffers behind a Gaussian splat, for handing to a compute kernel. **Properties:** - `count`: `number` (read-only) - How many splats the capture holds. Size a dispatch from this, and guard on it in the kernel: a thread that runs past the end writes into memory the renderer is using. - `boundingBox`: `BoundingBox` (read-only) - The box around the capture, in the same space as the values in `position`. - `position`: `SplatAttribute` (read-only) - Centre of each splat, 3 floats per splat, read in a kernel as `packed_float3`. - `scale`: `SplatAttribute` (read-only) - Per-axis size of each splat, 3 floats per splat, in log space and read in a kernel as `packed_float3`. Halving a splat means subtracting `log(2)`, not multiplying by 0.5. - `rotation`: `SplatAttribute` (read-only) - Orientation of each splat as a quaternion, 4 floats per splat, stored **w first** as `(w, x, y, z)`. Identity is `(1, 0, 0, 0)`; an `xyzw` identity is a half turn. - `opacity`: `SplatAttribute` (read-only) - Opacity of each splat, 1 float per splat, stored pre-sigmoid so 0 is half opaque rather than invisible. Fade the alpha and convert back rather than interpolating the stored value. - `sphericalHarmonics`: `SplatAttribute` (read-only) - View-dependent colour: the DC triplet first, then one triplet per higher-order coefficient, so `itemSize` is `3 * (bands + 1)` and a splat's base colour is the first three floats of its block. Read in a kernel as `float`, indexed by that stride. - `sphericalHarmonicDegree`: `number` (read-only) - Spherical harmonic degree of the capture, 0 through 3. **Methods:** - `setShader(kernel: any, options: any)` → `void` - Runs a compute shader's update on this splat every frame, or once, in place of its Shader slot, until the object next loads. Element fields bind by attribute name. Pass `null` to stop it. - `setParameter(name: string, value: any, typeHint: any)` → `Splat` - Sets a parameter of the shader running on this splat, the Shader slot's or one set with `setShader`, until the object next loads. An unknown name is reported in the console. ### `Transform` 4x4 transformation matrix representing position, rotation, and scale **Properties:** - `position`: `Vector3` - Position vector - `rotation`: `Rotation` - Rotation; read its components through `.quaternion` or `.eulerAngles` - `scale`: `Vector3` - Scale vector **Methods:** - `create()` → `Transform` - Create identity transform (position: 0,0,0, rotation: identity, scale: 1,1,1) - `createWith(position: Vector3, rotation: Rotation, scale: Vector3)` → `Transform` - Create transform with specific values - `transformPoint(transform: Transform, point: Vector3)` → `Vector3` - Transform a point by this matrix - `transformVector(transform: Transform, vector: Vector3)` → `Vector3` - Transform a direction vector (ignores position) - `multiply(t1: Transform, t2: Transform)` → `Transform` - Multiply two transforms (combine transformations) - `inverse(transform: Transform)` → `Transform` - Get inverse transform **Runtime Extensions:** - `transformPoint(point: Vector3)` → `Vector3` - Transform a point - `transformVector(vector: Vector3)` → `Vector3` - Transform a vector - `multiply(other: Transform)` → `Transform` - Multiply with another transform - `inverse()` → `Transform` - Get inverse transform ### `UIView` A view node inside a UI panel. **Properties:** - `id`: `string` (read-only) - Stable view ID set in the experience model. - `name`: `string` (read-only) - Optional human-readable name (mirrors `representation.name`). - `kind`: `string` (read-only) - View kind as a string: "label", "button", "slider", "toggle", "textField", "stepper", "segmentedControl", "progressView", "image", "divider", "shape", "hStack", "vStack", "zStack", "spacer", "webView", "carousel", "annotation". - `text`: `string` - Text content. Applies to: `label`, `textField`. - `title`: `string` - Button title. Applies to: `button`. - `value`: `number` - Numeric value. Applies to: `slider`, `stepper`, `progressView`, `segmentedControl`. - `isOn`: `boolean` - On/off state. Applies to: `toggle`. - `isExpanded`: `boolean` - Whether the card is open. Applies to: `annotation`. - `progress`: `number` - Fill progress, 0-1. Applies to: `progressView`. - `selectedIndex`: `number` - Index of the selected segment or child. Setting it on a carousel scrolls that child to the middle. Applies to: `segmentedControl`, `carousel`. - `placeholder`: `string` - Placeholder text. Applies to: `textField`. - `image`: `string` - The SF Symbol an image shows, such as `'bolt.fill'`, in the image's colour and size; `null` when it shows a photo. Applies to: `image`. - `isHidden`: `boolean` - Visibility flag. Applies to: any kind. - `isEnabled`: `boolean` - Interactive flag. Applies to: any kind. - `opacity`: `number` - View opacity, 0-1. Applies to: any kind. - `scale`: `number` - Size about the view's centre, 1 by default. The layout keeps the view's own size. Applies to: any kind. - `rotation`: `number` - Turn about the view's centre in radians, clockwise, 0 by default. Applies to: any kind. - `offsetX`: `number` - Points the view moves right, on top of its authored offset, 0 by default. Applies to: any kind. - `offsetY`: `number` - Points the view moves down, on top of its authored offset, 0 by default. Applies to: any kind. - `background`: `JSUIView[]` - The views drawn behind this one, back to front. They never change its size or move its neighbours. Setting a list keeps the views it names that are already there, takes out the others and adds the new ones made with `UI.*`, for as long as the experience runs. Applies to: any kind. - `overlay`: `JSUIView[]` - The views drawn in front of this one, back to front. Set like `background`. Applies to: any kind. **Methods:** - `getProperty(name: string)` → `any` - Read a property by key - `setProperty(name: string, value: any)` → `void` - Write a property by key. Live-updates the rendered view; for input controls bound via `.reference`, also writes back to the bound variable so observers see the change. No view tree rebuild. - `bindProperty(propertyName: string, variableName: string, options: any)` → `void` - Bind a property to an experience variable at runtime. Variable changes flow into the live view; for input controls, user input flows back into the variable. Calling `bindProperty` again on the same property replaces the existing binding. Does not mutate the saved model -- bindings last as long as the panel, until `unbindProperty` or a panel rebuild removes them. - `unbindProperty(propertyName: string)` → `void` - Remove a runtime binding installed via `bindProperty`. The property keeps its current displayed value but no longer reacts to the variable; user input on the property no longer writes back. No-op if no binding exists for `propertyName`. - `scrollTransition(effect: any)` → `void` - Shrinks, fades, turns or moves carousel children by their distance from the middle. On a carousel it applies to every child; on a view inside a child it applies to that view, which gives parallax. Values are what a child one step from the middle gets (its own length plus the spacing); the middle child gets none, children in between blend. - `findView(query: any)` → `UIView` - Find a view inside this one by ID or name, this view included. **Runtime Extensions:** - `bind(propertyName: string, variableName: string, options: Object)` → `JSUIView` - Bind a property to an experience variable. Sugar for bindProperty. - `unbind(propertyName: string)` → `JSUIView` - Remove a runtime binding installed via bind(). - `animateTo(properties: Object, duration: number, options: Object, options.timingFunction: string, options.spring: Object, options.spring.duration: number, options.spring.bounce: number, options.velocity: Object, options.repeatCount: number, options.repeatMode: string)` → `Promise` - Animate one or more numeric view properties to target values. - `stopAnimations()` → `void` - Stop the animations `animateTo` started on this view. The view keeps the values it has now. - `add(view: Object, options: Object, options.to: string, options.at: number)` → `JSUIView | null` - Add a view made with `UI.label(...)`, `UI.shape(...)` and the rest to this one while the experience runs. The panel keeps every other view as it is, with its state and animations. - `remove()` → `void` - Take this view and every view inside it out of the panel while the experience runs, stopping their animations. - `copy()` → `Object | null` - A copy of this view and every view inside it as authored in the editor, ready for `add`. A script's changes to the original, such as a new text, are not in the copy. Every copy gets new ids and keeps the names and the translations, so find views inside it with `row.findView(...)`. Use it to build a list from one sample cell authored in the editor: add a copy per item, fill it in, then hide the sample. - `enablePinchZoom(options: Object, options.minScale: number, options.maxScale: number, options.releaseBehavior: string)` → `any` - Let two fingers zoom this view, about the point between them, and move it while zoomed. Built on `on('pinch')` and the `scale`, `offsetX` and `offsetY` properties, so it works where those do: panels on the screen on iPhone, iPad and Mac. A new pinch catches the view where a running spring has it. - `scrollWith(e: Object)` → `void` - Scroll this carousel with a pan that began somewhere else, as a swipe on the carousel itself would: it follows the finger, stretches past the first and last child, coasts after a flick and snaps to a child. Pass every event of a `scene.on('pan')` or `view.on('pan')` listener. A scene pan that began on an object the viewer can drag, or on a panel placed in 3D, moves that instead and doesn't scroll the carousel. Taps on the scene keep working, since a tap is no pan. - `fadeIn(duration: number)` → `Promise` - Fade view to fully opaque. - `fadeOut(duration: number)` → `Promise` - Fade view to fully transparent. - `on(type: string, listener: function)` → `string` - Subscribe to a UI interaction on this view. Supported types per kind: - 'tap' → any kind. On a button it fires in every panel; on other kinds in panels on the screen. - 'valueChanged' → slider, segmentedControl, carousel (`uiValue` is the selected child's index, sent when a scroll or tap settles) - 'scroll' → carousel (`uiValue` is the position in the middle as a child index, fractional between two children, sent on every scroll step) - 'toggled' → toggle, annotation - 'textChanged' → textField - 'pinch', 'pan', 'rotate' → any kind, in panels on the screen on iPhone, iPad and Mac. A panel placed in 3D and Apple Vision Pro don't deliver them; check `environment.features.has('screenGestures')`. A view inside a carousel takes 'pinch' and 'rotate' but not 'pan', since the carousel scrolls. The listener receives `{ uiNodeId, uiInteractionKind, uiValue? }`, matching the payload authored UI-interaction events emit. Gestures add, like the scene's own `pan`, `pinch` and `rotate` events: - `phase`: 'began', 'changed' or 'ended' (not on 'tap') - `position`, `beganPosition` (Vector2): points from where the view's top-left corner sits untransformed, so the view's own scale or offset doesn't change them - `size` (Vector2): the view's size in points, untransformed - 'pinch': `scale` since the pinch began and `velocity`, per second - 'rotate': `rotation` in radians since it began and `velocity`, radians per second - 'pan': `translation` (Vector2) in points since it began and `velocity` (Vector2), points per second - `off(subscriptionId: string)` → `void` - Remove an interaction listener by subscription id. - `once(type: string, listener: function)` → `string` - Subscribe to a single UI interaction; auto-unsubscribes after first fire. ### `ValueAnimation` Value animations with spring and curve timing **Properties:** - `isPlaying`: `boolean` (read-only) - Whether the animation is currently playing **Methods:** - `start()` → `void` - Start or resume the animation - `stop()` → `void` - Pause the animation (can be resumed with start()) - `destroy()` → `void` - Stop and clean up the animation permanently ### `Vector2` 2D vector for screen coordinates, UV mapping, and 2D math **Properties:** - `x`: `number` - X component - `y`: `number` - Y component **Methods:** - `create(x: number, y: number)` → `Vector2` - Create a Vector2 - `zero()` → `Vector2` - Zero vector (0, 0) - `one()` → `Vector2` - One vector (1, 1) - `lerp(v1: Vector2, v2: Vector2, t: number)` → `Vector2` - Linearly interpolate between two vectors - `distance(v1: Vector2, v2: Vector2)` → `number` - Distance between two vectors - `dot(v1: Vector2, v2: Vector2)` → `number` - Dot product of two vectors - `normalize(v: Vector2)` → `Vector2` - Normalize a vector (unit length) - `length(v: Vector2)` → `number` - Length of a vector ### `Vector3` 3D vector for positions, directions, and scales **Properties:** - `x`: `number` - X component - `y`: `number` - Y component - `z`: `number` - Z component **Methods:** - `create(x: number, y: number, z: number)` → `Vector3` - Create a Vector3 - `zero()` → `Vector3` - Zero vector (0, 0, 0) - `one()` → `Vector3` - One vector (1, 1, 1) - `lerp(v1: Vector3, v2: Vector3, t: number)` → `Vector3` - Linearly interpolate between two vectors - `distance(v1: Vector3, v2: Vector3)` → `number` - Distance between two vectors - `dot(v1: Vector3, v2: Vector3)` → `number` - Dot product of two vectors - `cross(v1: Vector3, v2: Vector3)` → `Vector3` - Cross product of two vectors - `normalize(v: Vector3)` → `Vector3` - Normalize a vector (unit length) - `length(v: Vector3)` → `number` - Length of a vector - `angleBetween(v1: Vector3, v2: Vector3)` → `number` - Angle between two vectors in radians **Runtime Extensions:** - `add(other: Vector3)` → `Vector3` - Add two vectors - `subtract(other: Vector3)` → `Vector3` - Subtract a vector from this vector - `multiply(scalar: number)` → `Vector3` - Multiply vector by scalar - `divide(scalar: number)` → `Vector3` - Divide vector by scalar - `dot(other: Vector3)` → `number` - Calculate dot product with another vector - `cross(other: Vector3)` → `Vector3` - Calculate cross product with another vector - `length()` → `number` - Get length of vector - `normalize()` → `Vector3` - Get normalized vector - `distanceTo(other: Vector3)` → `number` - Calculate distance to another vector - `lerp(other: Vector3, t: number)` → `Vector3` - Linearly interpolate to another vector - `angleTo(other: Vector3)` → `number` - Calculate angle to another vector ### `Vector4` 4D vector for quaternions, colors, and homogeneous coordinates **Properties:** - `x`: `number` - X component - `y`: `number` - Y component - `z`: `number` - Z component - `w`: `number` - W component **Methods:** - `create(x: number, y: number, z: number, w: number)` → `Vector4` - Create a Vector4 ### `WebSocket` WebSocket connection for real-time communication **Properties:** - `onOpen`: `any` - Called when connection opens - `onClose`: `any` - Called when connection closes - `onMessage`: `any` - Called when message received (event.data contains the message) - `onError`: `any` - Called on error (event.error contains the Error) **Methods:** - `send(message: string)` → `void` - Send a message - `close()` → `void` - Close the connection ### `WebSocketManager` WebSocket connection manager Access via `websocket.connect()` **Methods:** - `connect(url: string, options: Array)` → `WebSocket` - Create a new WebSocket connection