# Scenery Scripting -- Guide, basics (v0.5.0) Concepts and how-to for scripting Scenery AR experiences: the basics every script needs. Sibling bundle (one guide per feature, from gestures to the camera): https://scenery.app/docs/scripting/guide/features/llms-full.txt Sibling bundles (complete API signatures): engine types https://scenery.app/docs/scripting/api/llms-full.txt, runtime types https://scenery.app/docs/scripting/api/runtime/llms-full.txt Heavier reference pages are fetchable directly: worked examples at https://scenery.app/docs/scripting/guide/examples.md, compute kernels at https://scenery.app/docs/scripting/guide/compute.md, changelog at https://scenery.app/docs/scripting/guide/changelog.md, migration at https://scenery.app/docs/scripting/guide/migration.md. 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. --- # Getting Started Scenery is a visual editor for spatial experiences. You design scenes, place objects, configure materials, and wire up behaviors - all without code. Scripts handle what the visual editor doesn't: state, logic, external data, real-time connections, procedural behavior. ## How scripts work Scripts attach to events. When something happens - a tap, an object appearing, a frame rendering - Scenery can run your code. To add a script: 1. Create an event (on an object or the scene) 2. Add a "Run Script" action 3. Write your code When the event fires, your script runs with event data in `scriptContext.sourceEvent`: ```javascript // Tap event - scale up the tapped object scriptContext.sourceEvent.objectEntity.animateTo( { scale: Vector3(1.2, 1.2, 1.2) }, 0.2 ); ``` Different events provide different data - position, deltaTime, distance, etc. Use `console.log(scriptContext.sourceEvent)` to inspect what data is available for any event. **Action order matters**: Actions run sequentially by default. If your script uses `scene.findEntity` to find an object, that object must already be in the scene - so place the "Add to Scene" action **before** "Run Script": **Add to Scene** (MyBox) → **Run Script** (finds MyBox) If the script runs first, the object won't exist yet and `findEntity` returns `null`. Alternatively, attach your script to the object's **On Will Appear** or **On Did Appear** event - then the object is guaranteed to be available. ## Example: Continuous rotation Attach to "On Render": ```javascript // Replace with your object's ID or use { name: "..." } var cube = scene.findEntity("YOUR_OBJECT_ID"); cube.representation.rotation = cube.representation.rotation.multiply( Rotation(0, scriptContext.sourceEvent.deltaTime, 0) ); ``` ## Finding objects ```javascript // By name (set in Identity panel) var box = scene.findEntity({ name: "MyBox" }); // By ID var box = scene.findEntity("ABC123"); // Access the representation (visual content). // position is an offset from where the object was placed in the editor: this lifts it 1 m. // worldPosition is where it is in the scene. box.representation.position = Vector3(0, 1, 0); box.representation.opacity = 0.5; ``` To get an ID: right-click an object or representation in the editor → **Copy Development ID**. **Entity vs Representation**: An **entity** is the top-level object (the anchor container you see in the scene list). A **representation** is the visual content inside it (model, shape, image, audio, etc.). Use `entity` for finding and referencing objects, use `entity.representation` for visual changes (position, rotation, scale, opacity). `scene.findEntity` finds top-level objects only - not nested representations. If your object contains multiple representations (e.g. a model and an audio source), find the parent entity first, then navigate: ```javascript var entity = scene.findEntity({ name: "MyObject" }); var audio = entity.findRepresentation({ name: "BGMusic" }); audio.isEnabled = true; ``` See [Examples → Entity hierarchy](/scripting/guide/examples#entity-hierarchy-and-lookup) for the full pattern. ## Rotations All rotation values are in **radians**. Use `Math.toRadians()` and `Math.toDegrees()` to convert: ```javascript Rotation(0, Math.PI / 2, 0); // 90° around Y axis Rotation(Math.toRadians(45), 0, 0); // 45° around X axis var degrees = Math.toDegrees(Math.PI); // 180 ``` Other math helpers: `Math.lerp(a, b, t)`, `Math.clamp(value, min, max)`, `Math.map(value, inMin, inMax, outMin, outMax)`, `Math.smoothstep(edge0, edge1, x)`. For working with directions, distances, dot/cross products, smooth motion, and converting between world and local space, see [Vectors & Transforms](/scripting/guide/vectors-transforms). ## Error handling Script errors are logged to the debug console but don't crash the scene - other scripts and actions continue to run. Use `try/catch` for operations that may fail: ```javascript try { var response = await http.get("https://api.example.com/data"); } catch (error) { console.error("Request failed: " + error); } ``` **Using await**: You can use `await` directly at the top level of your script - the runtime wraps async code for you, so there's no need for an `(async function(){...})()` wrapper or a helper function. ```javascript var box = await scene.createEntity(createBox(0.3, 0.3, 0.3)); ``` ## Configuring entities - use the descriptor builder `scene.createEntity(...)` takes **one** descriptor argument. Configure anchor, name, traits, and other settings via the descriptor's chainable builder methods, not as a second options argument. ```javascript // ✅ Correct - chain builder methods on the descriptor const box = createBox(0.3, 0.3, 0.3) .anchor(Anchor.position(0, 0, -1)) .name("hero-box"); const entity = await scene.createEntity(box); // ❌ Wrong - second argument throws at call time await scene.createEntity(box, { anchor: Anchor.position(0, 0, -1) }); ``` Same rule for `scene.runAction(action)` - single argument. Configure inside the action data, not via a second arg. The same builder also adjusts objects you already authored in the editor: `scene.getObjectDescriptor({ name: "..." })` returns an authored object's descriptor, so you can change its traits, material, or model - or add an interaction - *before* it's shown, then write it back with `scene.setObjectDescriptor(...)`. Where `findEntity` gives you the live object, `getObjectDescriptor` gives you its recipe. See [Examples → Adjust an authored object](/scripting/guide/examples#adjust-an-authored-object-before-it-appears). ## Debugging Tap the terminal button in the bottom-right corner to open the **debug console**. It shows `console.log` output and errors from your scripts. You can also type and run scripts directly in the console input field. ```javascript console.log("score:", experience.getVariable("score")); console.error("something went wrong"); ``` Scenery's own objects, such as a transform, a rotation or a vector, live in the app rather than in JavaScript. `JSON.stringify` prints `{}` for them and `Object.keys` returns `[]`, even when they hold values. Log them with `toString()` or read their properties by name: ```javascript console.log(entity.transform.rotation.toString()); console.log(entity.transform.rotation.eulerAngles.y); ``` ## Next steps - [Events](/scripting/guide/events) - Triggers, event data, the render loop - [API Reference](/scripting/api/) - Full documentation # The Console Everything a script logs with `console.log`, `console.warn` or `console.error` appears in the console, along with the engine's own notes about what the experience is doing. You can also type JavaScript into it and run it against the experience as it plays, which is the quickest way to try an idea before writing it into an action. The console is available while **editing** - in the editor's preview - and while **playing** a published experience. The playing case is the one worth knowing about, because it is how you debug on the device the experience will actually run on. ## Opening it | Where | How | |---|---| | Mac | Pause the experience and choose **Show Console**, or press **⌘⌥C** at any time | | iPad | Pause the experience and choose **Show Console** | | iPhone | Pause the experience and choose **Show Console** - it opens as a sheet you can drag to full height | | Apple Vision Pro | Tap the console button beside the pause button on your hand, or choose **Show Console** from the pause menu | On Mac the console starts as a panel over the bottom of the experience, and the **Open in Separate Window** button moves it into a window of its own, which you can put on a second display while the experience keeps running. **Put Back in the Experience** returns it. On Apple Vision Pro it is always a window, placed within reach and angled towards you. Closing the window closes the console, and the window closes with the experience. **Who sees it**: The console appears for the experience's **owner and their team**. Nobody else sees it, and a viewer who is not signed in to an account with access never knows it exists. ## Reading the log Each line carries the time it was logged. Lines from your scripts and lines from the engine are shown together, so you can see a `console.log` next to the state change that caused it. - **Search** - the magnifier opens a field that narrows the log to matching lines. - **Filter** - choose what to show: script output, engine output, errors and warnings only, or diagnostics. The button is tinted while any filter is away from its default, so a quiet console is never a mystery. - **Copy** - puts the whole log on the clipboard, formatted as it reads, which is what to attach to a bug report. - **Clear** - empties it. A cleared console says so, so a clear that worked does not look like one that did nothing. The console holds the most recent lines and drops the oldest as it fills, so a script that logs every frame will not grow it without limit. ## Running script Type into the field at the bottom and press **Return** to run. **Shift-Return** adds a line, so a multi-line snippet can be pasted or typed in one go. - **↑ / ↓** step back and forth through what you have run before, as long as the field holds a single line. Once it holds more, the arrows move the cursor instead. - **Paste** - the button inside the field puts the clipboard's text in without replacing what you have already typed. It is greyed when the clipboard holds no text. - Nothing runs on its own. Pasting fills the field; running is always a separate, deliberate press. Script you run here is evaluated against the live experience, in the same context as its own scripts - so an object your script created is reachable by the next thing you type. ```javascript // Try it: a box a metre in front of you. var box = await scene.createEntity( createBox(0.2, 0.2, 0.2).anchor(Anchor.currentPOV(0, 0, -1)) ); ``` `await` works directly, with no wrapper - see [Getting Started](/scripting/guide/getting-started). **While paused**: A paused experience completes no actions and never returns from `wait()`, so the input is disabled while playback is paused and the console says so. Resume, and it comes back. ## What it is not The console reads and writes the experience you are running, on your device. It does not reach other viewers, it is not a remote log, and nothing you type is saved into the experience. Close it and the session is gone. For logging that your scripts control, see [Events](/scripting/guide/events); for the API the input accepts, the whole [reference](/scripting/api/) applies. # Events Events trigger scripts. Scenery has two kinds: **object events** that fire for a specific object, and **scene events** that fire globally. ## Object events Attach to individual objects. The triggering object is available in `scriptContext.sourceEvent`. | Event | Fires when | |-------|------------| | On Will Appear | Object is about to be added to scene | | On Did Appear | Object has appeared | | On Removal | Object is removed from scene | | On Tap Gesture | Object is tapped | | On Gesture | Object is dragged, rotated, or resized (needs a gesture enabled) | | On Camera Collision | Camera enters/exits object bounds | | On Object Collision | Physics collision with another object | | Distance Field | Camera or target crosses distance threshold | | Look Direction | User looks at/away from object (or object looks at target) | | Media Playback | Video/audio begins, reaches timestamp, or ends | ```javascript // On Tap Gesture - scale up the tapped object scriptContext.sourceEvent.objectEntity.animateTo( { scale: Vector3(1.2, 1.2, 1.2) }, 0.2 ); ``` ## Scene events Fire regardless of which object is involved. | Event | Fires when | |-------|------------| | On Experience Start | Experience begins | | On Experience Load | Experience finishes loading | | On Screen Tap | User taps anywhere on screen | | On Render | Every frame | | On Schedule | After a delay or at specific time | | On Variable Change | A variable is modified | | On Language Change | The experience switches the language its texts show in | | On Audio Analysis | Audio levels update (ambient or microphone) | ```javascript // On Render - rotate every frame var cube = scene.findEntity("YOUR_OBJECT_ID"); cube.representation.rotation = cube.representation.rotation.multiply( Rotation(0, scriptContext.sourceEvent.deltaTime, 0) ); ``` Two scene events exist only in code: `snapshot` fires after the viewer takes a photo, and `recording` after a video recording ends. Both fire on iPhone and iPad; visionOS has no capture button. ```javascript scene.on('snapshot', function() { console.log('Photo taken'); }); ``` ## Subscribing in code You can also subscribe to events programmatically: ```javascript var cube = scene.findEntity("YOUR_OBJECT_ID"); // Object event cube.on('tap', function(e) { e.objectEntity.animateTo({ scale: Vector3(1.2, 1.2, 1.2) }, 0.2); }); // Scene event scene.on('render', function(e) { cube.representation.rotation = cube.representation.rotation.multiply( Rotation(0, e.deltaTime, 0) ); }); // One-time listener scene.once('start', function() { console.log('Experience started'); }); ``` ### Throttling For expensive operations, throttle the render loop: ```javascript scene.on('render', { throttle: 0.1 }, function(e) { // Runs every 100ms instead of every frame }); ``` ### Unsubscribing ```javascript var eventId = cube.on('tap', function() {}); // Later... cube.off(eventId); ``` **objectEntity vs representationEntity**: Tap and collision events give you both `objectEntity` (the top-level container) and `representationEntity` (the specific visual that was interacted with). Use `objectEntity` when you need to find sibling representations like audio sources. ## Gesture and screen events Beyond taps, you can react to live manipulation, multi-tap gestures, and raw screen gestures. ### Manipulating an object If an object has a gesture enabled (Drag, Rotate or Resize), `on('gesture')` fires continuously while the user manipulates it, so you can react to the movement itself. Read `e.phase` (`'began'` / `'changed'` / `'ended'`) and, by gesture kind, `e.translation` / `e.rotation` / `e.scale` (world-space): ```javascript box.on('gesture', function(e) { if (e.phase === 'ended') { console.log('let go'); } }); ``` `doubleTap` and `longPress` are discrete object gestures - these are available in code (not as editor triggers): ```javascript box.on('doubleTap', function() { /* ... */ }); box.on('longPress', { minimumDuration: 0.5 }, function() { /* ... */ }); ``` ### Screen gestures `pan`, `pinch` and `rotate` fire on any such gesture anywhere on screen, independent of scene objects - the raw input for mechanics like flick-to-launch. Read `e.position` (normalized) and, by kind, `translation` / `scale` / `rotation` plus `velocity`: ```javascript // Flick up in the bottom of the screen to launch the ball scene.on('pan', { area: [0, 0.6, 1, 0.4], phase: 'ended' }, function(e) { // e.velocity is in screen points/sec - scale it to a world-space push (tune to taste) var power = Math.max(0, -e.velocity.y) * 0.002; ball.applyImpulse(new Vector3(0, power, -power * 2), { space: 'world' }); }); ``` Outside AR (the desktop preview, the Mac app), a one-finger pan **also orbits the camera** by default. So if your handler reacts to a pan, that one gesture does two things at once - your mechanic runs *and* the camera swings. `consume` prevents that: return `true` from its predicate and the gesture is handled by your script alone, so the camera ignores it. The predicate runs as the gesture begins, so you can claim only the pans that start on your object and leave the rest for the camera: ```javascript // Claim the pan only when it starts on the ball; every other pan still orbits the camera scene.on('pan', { consume: function(e) { return e.hits(ball); } }, function(e) { /* ... */ }); ``` Omit `consume` for the smart default - a gesture is claimed automatically when it begins on a scene object. See [scene.on](/scripting/api/scene) for the full payload and `consume` options. **Screen gestures are for touch screens**: `pan`, `pinch` and `rotate` fire on iPhone, iPad and Mac. On Apple Vision Pro input is spatial (you look and pinch), so screen gestures aren't delivered - drive interaction from UI panels and buttons there instead. Gate a portable script with `environment.features.has('screenGestures')` and provide a fallback. ## Event data How you access event data depends on how your script runs: **Run Script action** - use `scriptContext.sourceEvent`: ```javascript var entity = scriptContext.sourceEvent.objectEntity; var dt = scriptContext.sourceEvent.deltaTime; ``` **Event subscriptions** - data is passed to your callback: ```javascript scene.on('render', function(e) { var dt = e.deltaTime; }); cube.on('tap', function(e) { var tapped = e.objectEntity; }); ``` **Properties by event type:** | Event | Properties | |-------|------------| | `render` | `deltaTime`, `time` | | `tap` | `objectEntity`, `representationEntity`, `screenPosition` | | `gesture` | `objectEntity`, `representationEntity`, `phase`, `translation`/`rotation`/`scale` | | `doubleTap`, `longPress` | `objectEntity`, `representationEntity` | | `pan`, `pinch`, `rotate` | `position`, `beganPosition`, `phase`, `translation`/`scale`/`rotation`, `velocity`; on `pan` also `beganOnDraggable` | | `view.on('pan' \| 'pinch' \| 'rotate' \| 'tap')` | `uiNodeId`, `uiInteractionKind`, `position`, `beganPosition`, `size`, `phase`, `translation`/`scale`/`rotation`, `velocity` (positions in points from the view's top-left) | | `screenTap` | `position` | | `distance` | `objectEntity`, `distance`, `crossed` | | `lookAt` | `objectEntity`, `isLooking` | | `cameraCollision` | `objectEntity`, `representationEntity` | | `physicsCollision` | `objectEntity`, `representationEntity`, `position`, `impulse` | | `variableChange` | `variableId`, `value` | | `languageChange` | `language` | | `mediaPlayback` | `objectEntity`, `status`, `time`, `duration` | | `audioAnalysis` | `kind`, `loudness`, `bass`, `lowMid`, `mid`, `upperMid`, `presence`, `brilliance`, `air`, `treble` | | `add`, `appear`, `remove` | `objectEntity`, `representationEntity` | | UI Interaction (editor trigger, via `scriptContext.sourceEvent`) | `uiNodeId`, `uiInteractionKind`, `uiValue` | Use `console.log(scriptContext.sourceEvent)` or `console.log(e)` to inspect all available properties. # Vectors & Transforms Positions, directions, and rotations are the raw material of anything spatial - aiming an object at the viewer, checking how far away something is, moving smoothly, turning a hand position into an object's own space. This page is a tour of the `Vector3`, `Rotation`, and `Transform` helpers, focused less on the maths and more on what each one is *for*. ## Points and directions A `Vector3` is just three numbers, but it plays two roles: - a **point** - a position in space (an object's `position`, a hand joint, a raycast hit) - a **direction** - which way something points, usually with a length of 1 The direction from one point to another is their difference: ```javascript var toTarget = target.subtract(myPosition); // points from me toward the target var distance = toTarget.length(); // how far away the target is var heading = toTarget.normalize(); // same direction, length 1 ``` `a.distanceTo(b)` is a shortcut for `b.subtract(a).length()` when you only need the distance. **What `normalize()` is for:** it scales a vector to length 1 while keeping its direction, so you're left with pure "which way" and no "how far". You want it whenever direction is what matters but magnitude shouldn't leak in - moving at a constant speed, aiming, or feeding a direction into a dot product (below), which only reads as an angle when its inputs are unit length. Normalize a direction before you use it to move or aim. A raw direction whose length happens to be, say, 3 would move an object 3× too fast - speed would depend on how far the target is, which is almost never what you want. Move an object a fixed speed toward a target each frame: ```javascript // Attach to: On Render var dt = scriptContext.sourceEvent.deltaTime; // seconds since last frame var step = target.subtract(obj.position).normalize().multiply(2.0 * dt); // 2 m/s obj.position = obj.position.add(step); ``` ## Dot product - how aligned are two directions? `a.dot(b)` measures how much two directions point the same way. For unit vectors it is the cosine of the angle between them: `1` means the same direction, `0` perpendicular, `-1` opposite. That makes it the go-to test for "is this in front of me?" and "is the viewer looking at it?": ```javascript // Attach to: On Render var cam = scene.cameraTransform; var forward = cam.transformVector(Vector3(0, 0, -1)); // where the camera looks var toObj = obj.representation.worldPosition.subtract(cam.position).normalize(); if (forward.dot(toObj) > 0.97) { // 0.97 ≈ within ~14° of dead-on; a smaller number = wider cone // the viewer is looking almost straight at the object } ``` Need the actual angle instead of a threshold? `a.angleTo(b)` returns it in radians. ## Cross product - give me a perpendicular `a.cross(b)` returns a vector at right angles to both `a` and `b`. You reach for it when you need an axis you don't already have: - a **surface normal** - the direction a surface faces - from two of its edges: `edge1.cross(edge2)`. Normals are what lighting uses to shade a surface, so this comes up when you build or deform a mesh. - a **"right" direction** from a forward and an up vector: `forward.cross(up)` - useful for placing something beside the viewer or moving sideways. This one is more advanced - if you're mostly moving and aiming objects, you may not need it yet. ## Smooth motion - lerp and slerp Snapping straight to a target reads as robotic; easing toward it feels alive. `lerp` blends between two values by a fraction `t` (0 = start, 1 = end): ```javascript // Attach to: On Render -- smooth follow obj.position = obj.position.lerp(target, 0.1); // moves 10% of the remaining distance each frame ``` - `Vector3.lerp` for positions, `Math.lerp(a, b, t)` for plain numbers. - Rotations use `rotation.slerp(other, t)` - the shortest smooth turn between two orientations. ## Rotations A `Rotation` orients something. Build one from angles (in **radians**), then combine, undo, or blend: ```javascript var quarterTurn = Rotation(0, Math.toRadians(90), 0); // 90° around the up (Y) axis var combined = rotA.multiply(rotB); // apply B, then A var undo = rot.inverse(); // the opposite rotation var eased = current.slerp(target, 0.2); // smooth turn toward another orientation ``` Use `Math.toRadians()` / `Math.toDegrees()` to convert. To turn an object to *face* a point (a "look-at"), see the billboard example in [Examples](/scripting/guide/examples). ## Coordinate spaces The same point can be described from different frames of reference, and mixing them up is a common source of "why is it in the wrong place" bugs: - **World space** - the one frame shared by everything, so any two things can be compared in it. The values you *read* are almost always world-space: hand joints (`scene.tracking.hands`), raycast hits, an object's `worldPosition`, the camera's position. - **Local space** - each object has its *own*, relative to its transform. A mesh's vertices, and an object's `position`, live in that object's local frame. (The camera has its own local frame too - "camera space".) So "local" isn't one place - it's per-object. Moving a point from one frame into another is exactly what a **Transform** does. ## Transforms A `Transform` bundles **position, rotation, and scale** - it is how one object sits in space, i.e. where its local frame lands in the world. Every entity has one: - `entity.transform` - relative to its parent (its **local** transform) - `entity.worldTransform` - its final place in the scene, with all parents applied Use it to move points and directions between the world and an object's local space: ```javascript var inv = Transform.inverse(entity.worldTransform); var local = Transform.transformPoint(inv, worldPoint); // world → this entity's local frame var world = entity.worldTransform.transformPoint(localPoint); // local → world ``` - **`transformPoint`** moves a position (translation included). - **`transformVector`** moves a direction (translation *ignored*, so it stays a direction) - this is why the dot-product example built the camera's forward with `transformVector`. - **`multiply`** chains two transforms; **`inverse`** reverses one. A hand joint feeding a mesh you built is the classic case: the joint is world-space, the mesh's vertices are the entity's local space - convert the joint into the entity's local frame first. In practice you rarely convert by hand, because entities hand you both frames directly: a representation's `position` is its **local** position, its `worldPosition` is the **world** one, and you can read *or set* either. Manual `transformPoint` conversion is for a loose point that isn't already an entity property - a hand joint, a raycast hit, a mesh vertex. An object at the scene's origin has local space equal to world space, so no conversion is needed. It starts to matter once the object - or the experience origin it sits under - is moved or rotated. # Materials A `Material` is what a surface looks like - color, texture, reflectivity, shader. Use the `Material` builder to construct one inline, reference an existing library material by id, or clone a library material and tweak it. ## Kinds Seven factories. Pick the one that matches the look you need. | Factory | Use for | |---------|---------| | `Material.unlit({...})` | Flat-shaded surfaces - UI, billboards, vertex-colored point clouds. Renders the same regardless of scene lighting. | | `Material.pbr({...})` | Realistic surfaces - metal, plastic, fabric. Responds to scene lighting. | | `Material.occlusion({...})` | Invisible itself but hides geometry behind it - holdouts, portals. | | `Material.customShader({...})` | Author-supplied Metal shader functions from a compiled `.metal` library. | | `Material.materialX({...})` | ShaderGraph material authored in Reality Composer Pro / `.usda`. | | `Material.video({...})` | Video texture playback. | | `Material.transmission({...})` | Glass, water or ice that refracts what is behind it. Settings go in `transmissionOptions({ ior, thickness, roughness, ... })`. Currently refracts on iPhone, iPad and Mac. | ## Inline construction Factory + options object reads naturally: ```javascript // Unlit - single flat color const red = Material.unlit({ color: '#FF0000' }); // PBR - color + metalness + roughness, no textures const gold = Material.pbr({ color: '#FFD700', metalness: 1.0, roughness: 0.2 }); // PBR - textured const brick = Material.pbr({ color: '#FFFFFF', // tints the texture map: 'brick-albedo.png', normalMap: 'brick-normal.png', roughnessMap: 'brick-rough.png' }); ``` Same chained, if you prefer: ```javascript const gold = new Material('pbr') .color('#FFD700') .metalness(1.0) .roughness(0.2); ``` ## Input shapes **Colors** - `color`, `emissive`, `sheenColor`, `specularColor`: - `'#RRGGBB'` or `'#RRGGBBAA'` - `{ r, g, b, a }` with values in 0..1 - `{ colorSpace: 'p3', hex: 'FF6600' }` **Textures** - `map`, `emissiveMap`, `normalMap`, etc.: - URL string: `'https://.../texture.png'` - Asset id string: `'libraryTextureId'` - With a scale: `{ texture: 'urlOrId', scale: 0.5 }` **Scalars** - `roughness`, `metalness`, `clearcoat`, `opacity`, `emissiveIntensity`: plain numbers. ## Library reference Materials authored in the experience editor are referenced by id directly - no inline construction needed: ```javascript // Apply a library material to a mesh await scene.createEntity(createMesh({ ..., materials: ['myLibraryMaterialId'] })); ``` Or fetch one with `scene.getMaterial(id)` to inspect: ```javascript const mat = scene.getMaterial('myLibraryMaterialId'); console.log(mat); // → Material(pbr 'My Material' id=..., color=#FFAA00, roughness=0.3) ``` ## Clone → tweak → apply To override a library material for a single entity (without mutating the library entry), clone it first: ```javascript const base = scene.getMaterial('redMatId'); const brighter = base.clone() .emissive('#FF0000') .emissiveIntensity(2); await entity.representation.setMaterial(brighter); ``` `.clone()` deep-copies the material with a fresh `id`. The original library material is untouched. ## ShaderGraph (MaterialX) parameters ShaderGraph materials authored in Reality Composer Pro expose promoted inputs. Set constant values via `setParameter(name, value, typeHint?)`: ```javascript const mat = scene.getMaterial('myShaderGraphMatId').clone() .setParameter('intensity', 0.6) .setParameter('tintColor', '#FF00FF', { type: 'color' }) .setParameter('offset', [0.1, 0.2, 0], { type: 'vector3' }); ``` The same `setParameter` works on `customShader` materials too - the Material auto-routes to the right options blob based on its kind. **Type hints** override inferred types: `{ type: "float" | "int" | "vector2" | "vector3" | "vector4" | "color" | "boolean" | "string" }` For runtime variable bindings (slider drives a parameter), use `entity.representation.bindMaterialParameter(parameterName, variableId)` - different path, lives on the entity, ties into the variable system. ## Shader textures A shader names its texture slots. Bind a texture to one with `shaderTexture(name, texture)`, on `customShader` and `materialX` materials. It takes a URL, an asset id or a texture handle. A dynamic texture keeps updating in the slot, so a video drives the shader frame by frame: ```javascript const clip = await Texture.video('clip.mp4', { loops: true }); await entity.representation.setMaterial( scene.getMaterial('glitchShaderMaterialId').clone() .shaderTexture('image', clip) .setParameter('amount', 0.4) ); ``` ## Runtime swap Replace an entity's material at runtime: ```javascript // Cycle materials every 2 seconds const palette = [ Material.unlit({ color: '#4287F5' }), Material.pbr({ color: '#42F578', metalness: 0.5, roughness: 0.3 }), Material.unlit({ color: '#F54242' }) ]; let i = 0; scene.on('schedule', { interval: 2 }, async function() { i = (i + 1) % palette.length; await entity.representation.setMaterial(palette[i]); }); ``` `setMaterial` accepts a `Material` instance, a library ref-id string, or `{ id, target? }`. `setMaterials([...])` for multiple at once. ## Introspection ```javascript console.log(material); // → Material(pbr id=..., color=#FF6600, roughness=0.3) console.log(JSON.stringify(material, null, 2)); // → full material JSON material.kind; // → 'pbr' material.id; // → 'AB12CD34' material.baseColor; // → { color: { colorSpace: 'p3', hex: 'FF6600' } } material.materialXOptions?.parameters; // → { intensity: { ... } } for materialX ``` For setter names that conflict with property names (`roughness`, `opacity`, `clearcoat`, `emissiveIntensity`), read via `material.data.` - e.g. `material.data.roughness?.scale`. ## Target By default a material applies to all models on an entity. Override for multi-model entities: ```javascript Material.pbr({ color: '#FF0000' }) .target({ type: 'firstModel' }); Material.pbr({ color: '#0000FF' }) .target({ type: 'selectedModels', models: ['windshield'], materialSlots: [0] }); ``` # Feature detection Not every Scenery feature is available on every platform or every runtime version. Compute shaders are gated behind a future runtime; hand tracking needs a visionOS device; SharePlay is stripped out of App Clip builds. Authors branch on capability through a single string-keyed registry on `environment.features`: ```javascript if (environment.features.has('compute')) { mesh.runCompute('advect', { uniforms }); } else { stepOnCPU(); } ``` Unknown feature names return `false` rather than throwing - this matches WebGPU's `Set.has` semantic and lets forward-looking scripts query features that may land in a future runtime version without crashing on today's runtime. ## Listing what's available ```javascript console.log(environment.features.list()); // → ['sharedActivities'] ``` `list()` returns every feature string the current runtime + device actually supports. Use it when debugging ("why isn't my branch firing?") or when reflecting capability state into telemetry. ## Current feature strings | Feature | Today | Notes | |---------|-------|-------| | `compute` | Apple-family 7+ devices on iOS 18 / visionOS 2 / macOS 15+ | GPU compute-kernel dispatch. `Kernel.fromSource(...)` / `Kernel.fromAsset(...)` compile a kernel; `mesh.runCompute(kernel, options)` dispatches it against `storage: "compute"` attribute buffers and / or compute textures. | | `sharedActivities` | platform-dependent | Multi-user / SharePlay support. `false` in App Clip and any build without the shared-activities trait. | | `background` | iPhone / iPad / Mac | The scene background as a texture (via `Texture.background()`). The camera image in AR on iPhone and iPad; on Mac, the scene's background, so a material sampling it at `context.backgroundUV` lines up with what is behind it. Not available on visionOS. | | `screenGestures` | iPhone / iPad / Mac | Screen-space `scene.on('pan'\|'pinch'\|'rotate')`, the `consume` camera claim, and `view.on('pan'\|'pinch'\|'rotate')` on views in screen panels. Not delivered on visionOS, where input is spatial (eyes + pinch) - use UI panels / buttons there instead. | | `instancing` | iOS 26 / visionOS 26 / macOS 26+ | GPU mesh instancing via `rep.setInstances(Instances.transforms([...]))` - render hundreds of copies of a mesh cheaply. Rendering-only (no physics, collision, or per-instance identity); use `entity.clone()` for objects the user interacts with. | | `ambientOcclusion` | iPhone / iPad / Mac | Shading in creases, corners and under objects via `scene.setAmbientOcclusion(...)`. Not available on visionOS. | | `splats` | iOS 27 / visionOS 27 / macOS 27, devices only | Gaussian splat captures via `createSplat(...)`. Neither simulator can render them. Check it before creating a splat, so a script can place something else instead. | | `gameController` | iPhone / iPad / Mac / Apple Vision Pro | Game controller input via [`scene.gameController`](/scripting/guide/game-controllers). Every Apple device has it; other players may not, so check it before relying on a controller. | | `cameraControls` | iPhone / iPad / Mac | Pointing the camera via [`scene.camera`](/scripting/guide/camera). `false` on Apple Vision Pro, where the wearer's head is the camera. On iPhone and iPad the camera follows only outside AR; read `scene.camera.kind` to tell. | | `accessoryTracking` | Apple Vision Pro | Tracked spatial controllers and styluses: `Anchor.accessory(...)` and the `aim` and `grip` poses in [`scene.gameController`](/scripting/guide/game-controllers). `false` everywhere else, where an object anchored to an accessory stays hidden. | Once a splat exists, the handle answers the same question for that object: `representation.splat` is `null` both on a representation that is not a capture and on a system that cannot render one: ```javascript var splat = entity.representation.splat; if (!splat) { return; } ``` More feature strings land here as their backends wire up. A name not in the table above always returns `false` from `has()` - never throws. ## Pattern Feature detection is the right tool for runtime branching across platforms and capability classes. Use it for: - Hardware capabilities the device may or may not have (compute, future: `handTracking`, `planeDetection`, `sceneReconstruction`). - Build-trait features that strip out of compact targets (`sharedActivities`, future: `gamification`). - Runtime-version features (anything reserved for a later API bump). For pure platform identity - "am I on visionOS?" - read `environment.hostingPlatform` directly: ```javascript if (environment.hostingPlatform === 'visionOS') { enableHandTrackingUI(); } ``` When you care about the **interaction model** rather than the exact OS, `environment.deviceCategory` is usually the cleaner branch - `'handheld'` (iPhone, iPad), `'spatial'` (Apple Vision Pro and other headsets), or `'desktop'` (Mac, desktop web). It collapses several hosts into the axis that actually drives your decision: ```javascript if (environment.deviceCategory === 'spatial') { showControlPanel(); // spatial input - use UI, not screen gestures } ``` Platform identity is single-valued (you're on exactly one host, in one category) and so stays a string property; capabilities form a set and live in the registry. Reach for a capability flag like `environment.features.has('screenGestures')` when you want the precise "does this specific API work here" answer rather than a form-factor guess.