@margoengine/xr 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,592 +1,843 @@
1
- # @margoengine/xr
2
-
3
- Import `margoengine/xr` from the `margoengine` package, or `@margoengine/xr` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
-
5
- Optional WebGPU WebXR session negotiation, input poses and instanced stereo PBR rendering. XR owns a compatible GPU device and attaches through the existing core extension interface. Core and the stage facade remain frozen.
6
-
7
- ```ts
8
- import {Engine,box} from 'margoengine/core';
9
- import {XR} from 'margoengine/xr';
10
-
11
- const canvas=document.createElement('canvas');document.body.append(canvas);
12
- const engine=await Engine.create(canvas,{backend:'webgpu'});
13
- const cube=engine.createMesh().setGeometry(box());
14
- if(await XR.isSupported('immersive-vr')) {
15
- const xr=await XR.create(engine); // prepare before the user gesture
16
- const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
17
- enter.onclick=()=>{void xr.requestSession('immersive-vr',{
18
- onFrame({delta,inputs}) {
19
- cube.rotation.y+=delta;
20
- // inputs expose native sources/gamepads plus targetRay and optional grip poses.
21
- }
22
- }).then(session=>session.addEventListener('end',()=>engine.start(),{once:true})).catch(engine.onError);};
23
- // await xr.end() exits; xr.dispose() detaches and releases GPU resources.
24
- }
25
- engine.start();
26
- ```
27
-
28
- `layers` (an option of `XR.create` and `XR.attach`, and a property you can change at any time) is the render layer mask both eyes draw, on either route, as `RenderView.layers` is for a desktop view; unset draws every layer. A mesh whose mask (`setRenderLayers` from `margoengine/cameras/layers`) shares no bit with it is drawn in neither eye. This is how a first-person avatar hides its own head in the headset (`addVRMFirstPerson` from `margoengine/rigging/vrm-first-person`):
29
-
30
- ```ts
31
- import {Engine,box} from 'margoengine/core';
32
- import {setRenderLayers} from 'margoengine/cameras/layers';
33
- import {XR} from 'margoengine/xr';
34
-
35
- const canvas=document.createElement('canvas');document.body.append(canvas);
36
- const engine=await Engine.create(canvas,{backend:'webgpu'});
37
- engine.createMesh().setGeometry(box()).setPosition([0,1.5,-2]); // layer 0: seen in the headset
38
- const hidden=engine.createMesh().setGeometry(box()).setPosition([0,1.6,0]);
39
- setRenderLayers(hidden,1<<30); // on layer 30 only
40
- if(await XR.isSupported('immersive-vr')) {
41
- const xr=await XR.create(engine,{layers:~(1<<30)>>>0}); // every layer but 30
42
- const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
43
- enter.onclick=()=>void xr.requestSession('immersive-vr').catch(engine.onError);
44
- // xr.layers=undefined draws every layer again; a mask outside 0 to 0xffffffff throws a RangeError.
45
- }
46
- engine.start();
47
- ```
48
-
49
- `XRManager` is an alias for `XR`. `useXRSession(manager, mode, options)` is a framework-neutral request helper; prepare the manager before the user gesture and dispose it with the owning engine. It adds no React dependency.
50
-
51
- `requestSession` supports `immersive-vr`, `immersive-ar`, and `inline`. Immersive sessions require native `XRGPUBinding`, require `webgpu`, and default to `local` space. On the WebGL2 compatibility layer the layer's `installXR()` takes the binding's place and the session runs on an `XRWebGLLayer` instead, without `webgpu` ([its README](../webgl2-compat/README.md#xr-margoenginewebgl2-compatxr)). Inline sessions use `viewer` space and track poses/inputs while the desktop canvas continues rendering. The [WebGPU XR draft](https://immersive-web.github.io/webxr-webgpu-binding/#feature-descriptor) prohibits WebGPU inline layers and mixing `XRWebGLLayer` with WebGPU sessions. Missing immersive bindings leave desktop rendering active. Reference-space and feature options are forwarded. AR clears transparently. Failed initialization closes the session and frees its layer. Engine disposal ends XR and frees buffers/device. Device loss ends the session; recreate the manager to recover.
52
-
53
- Use HTTPS or localhost and call `requestSession` from a user gesture. `isSupported` checks APIs and session mode; adapter compatibility, permissions and feature support are established during creation/negotiation. Support follows browser capabilities without headset brand detection. Vision Pro VR support does not imply AR support. See the [binding draft](https://immersive-web.github.io/webxr-webgpu-binding/) and [WebKit announcement](https://webkit.org/blog/17640/webkit-features-for-safari-26-2/).
54
-
55
- Immersive XR stops the engine RAF after entry and automatically restarts it on exit/disconnection. Update animation in XR `onFrame`; engine `onFrame` and React `useFrame` belong to the window RAF. Core plugin `onPreUpdate` runs once per immersive XR frame. Inline tracking leaves the window RAF active.
56
-
57
- Core geometry/materials use the shared base shader, per-eye uniforms, native [0,1] projections, viewports and texture-array descriptors. Loader-owned PBR models are discovered through the optional triangle registry and use their PBR shader in both eyes. The canvas mirror and XR buffers use separate devices; each eye owns independent PBR resources and deformation kernels, sharing current CPU pose data without advancing playback twice. Late animation attachment/removal and extension replacements synchronize before drawing. Glass (`KHR_materials_transmission`) on a display-encoded layer adds its light to the light behind it in linear values, as on the canvas: when a drawn model has glass, the eye pass keeps its samples and gltf/pbr's snapshot hook resolves them before each glass surface (one extra resolve pass and one reopened eye pass per surface); scenes without glass draw one pass per eye as before. Caller-owned material extension texture views require recreation for the XR device and report an explicit error. That separate route draws no package passes or post effects; an engine from `createXREngine` draws them all (below).
58
-
59
- `XRController` reuses target-ray/grip matrices, 32 button triplets (value/pressed/touched), 16 axes, and 25 hand joint matrices/tracking flags when granted. Controllers change on `inputsourceschange`. Frame state, input arrays and existing controller buffers retain identity; copy to retain a past frame. Browser-owned poses and GPU descriptors may allocate; this is not a whole-runtime zero-GC guarantee.
60
-
61
- Run `npx vite --host 127.0.0.1` at the root and open `/examples/webxr-orbit/`. Peer ranges accept core 0.1.x and 1.x.
62
-
63
- `npm test` checks negotiation, inputs, eye buffers, reference-space failure, device loss and disposal races. Root `npm run modern:test:xr:browser` checks actual stereo pixels, GPU validation and teardown using simulated sessions with real WebGPU. Physical Meta Quest and Apple Vision Pro sessions remain untested. No Apple hardware is required for these checks.
64
-
65
- Build with root `npm run build:packages` or local `npm run build`. Apache-2.0 licensed.
66
-
67
- ## AR hit testing
68
-
69
- `HitTest` uses the WebXR Hit Test Module in an `immersive-ar` session started with the `'hit-test'` feature. Its ray
70
- starts at the viewer (the centre of the view, for a placement reticle), at an input source's target ray, or at transient
71
- inputs such as screen taps (`{profile: 'generic-touchscreen'}`). `hits.results(frame)` gives this frame's hits nearest
72
- first, each with a column-major `matrix`, `position` and `orientation` in the session's reference space;
73
- `hits.anchor(hit)` anchors one (WebXR Anchors Module, feature `'anchors'`). The source is cancelled with `cancel()` or
74
- when the session ends. Not yet tried on an AR headset or phone; tested against the specification's interfaces.
75
-
76
- ```ts
77
- import { Engine, box } from 'margoengine/core';
78
- import { XR, HitTest } from 'margoengine/xr';
79
-
80
- const canvas = document.querySelector('canvas')!;
81
- const engine = await Engine.create(canvas, { backend: 'webgpu' });
82
- const reticle = engine.createMesh().setGeometry(box(0.2, 0.01, 0.2));
83
- const xr = await XR.create(engine);
84
- let hits: HitTest | undefined;
85
- await xr.requestSession('immersive-ar', {
86
- requiredFeatures: ['hit-test'],
87
- onFrame({ frame }) {
88
- const hit = hits?.first(frame);
89
- reticle.visible = !!hit;
90
- if (hit) reticle.setPosition(hit.position).setQuaternion(hit.orientation);
91
- },
92
- });
93
- hits = await HitTest.create(xr, { from: 'viewer' });
94
- ```
95
-
96
- ## Body tracking
97
-
98
- `BodyTracking` from `@margoengine/xr/body` reads the W3C WebXR Body Tracking Module: all 83 `XRBodyJoint` poses (hips,
99
- spine, arms, hands, legs) in the session's reference space, every frame. Ask for the `'body-tracking'` feature as an
100
- optional feature; few devices have it. Without it, `BodyTracking.create` does not throw: `available` is `false` and
101
- `read` returns `null`. Pass `{ required: true }` for a MargoError `'unsupported'` instead. `read(frame)` also returns
102
- `null` while tracking is lost, as the spec reports every joint or none. `humanoidPose(pose)` maps the joints to the
103
- humanoid bone names of `@margoengine/rigging` (`hips`, `leftUpperArm`, `rightHand`, ...) for retargeting. Not yet tried on
104
- a device; tested against the specification's interfaces.
105
-
106
- ```ts
107
- import { Engine } from 'margoengine/core';
108
- import { XR } from 'margoengine/xr';
109
- import { BodyTracking, humanoidPose } from 'margoengine/xr/body';
110
-
111
- const canvas = document.querySelector('canvas')!;
112
- const engine = await Engine.create(canvas, { backend: 'webgpu' });
113
- const xr = await XR.create(engine);
114
- let body: BodyTracking | undefined;
115
- await xr.requestSession('immersive-vr', {
116
- optionalFeatures: ['body-tracking'],
117
- onFrame({ frame }) {
118
- const pose = body?.read(frame);
119
- if (pose) console.log('head', pose.position('head'), 'bones', humanoidPose(pose).size);
120
- },
121
- });
122
- body = BodyTracking.create(xr);
123
- if (!body.available) console.log('This device has no body tracking');
124
- ```
125
-
126
- ## Device runs
127
-
128
- `runDeviceCheck` from `@margoengine/xr/device-check` runs one session and gives back what happened: frames, poses, views, frame times, inputs, granted features and failures. `examples/xr-device-check` is the page to open on a headset or phone; [docs/xr-device-runs](../../docs/xr-device-runs/README.md) keeps the records, and `npm run check:xr-runs` prints which routes a real device has proven. No real device has run yet: all four routes read NOT RUN. A run whose `navigator.xr` is a JavaScript stand-in has `native: false` and proves nothing.
129
-
130
- ```ts
131
- import { Engine } from 'margoengine/core';
132
- import { XR } from 'margoengine/xr';
133
- import { runDeviceCheck } from 'margoengine/xr/device-check';
134
-
135
- const canvas = document.querySelector('canvas')!;
136
- const engine = await Engine.create(canvas, { backend: 'webgpu' });
137
- const xr = await XR.create(engine);
138
- document.querySelector('button')!.onclick = async () => {
139
- const run = await runDeviceCheck(xr, { mode: 'immersive-vr', seconds: 20 });
140
- console.log(run.tracked, 'tracked frames at', run.frameMs.median, 'ms');
141
- };
142
- ```
143
-
144
- ## Package passes and post effects in XR
145
-
146
- Create the engine with `createXREngine` instead of `Engine.create` and XR draws through the engine's own frame graph on its own GPU device: lines, point clouds, terrain, shadows, sky and post effects appear in both eyes as they do on the desktop. `xr.route` is `'engine'`. An engine from `Engine.create` keeps the older `'separate'` route, which draws core meshes and glTF PBR models only.
147
-
148
- ```ts
149
- import {box} from 'margoengine/core';
150
- import {XR,createXREngine} from 'margoengine/xr';
151
-
152
- const canvas=document.createElement('canvas');document.body.append(canvas);
153
- const engine=await createXREngine(canvas);
154
- engine.createMesh().setGeometry(box()).setPosition([0,1.5,-2]);
155
- const xr=await XR.create(engine);
156
- console.log(xr.route); // 'engine'
157
- const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
158
- enter.onclick=()=>void xr.requestSession('immersive-vr').catch(engine.onError);
159
- engine.start();
160
- ```
161
-
162
- Each eye is a view of `engine.render({views})` drawn into a texture, then copied into the session's layer, with the scene's depth written to the layer's depth so the compositor can reproject. In AR the real world shows where the scene draws neither depth nor light. A stage gets the same route with `new Stage(await createXREngine(canvas))`. On the WebGL2 compatibility layer, call `installXR()` from `@margoengine/webgl2-compat/xr` first and `createXREngine` takes the same route there.
163
-
164
- ## Controller and hand models
165
-
166
- `XRModels` from `@margoengine/xr/models` draws every input source the session has: a controller at its grip, whose trigger swings, squeeze sinks and thumbstick leans as they are used and turn blue while pressed (on a gamepad with the `xr-standard` mapping; other mappings leave the parts at rest), and each tracked hand as a sphere per joint (sized by the joint radius WebXR reports) and a cylinder per bone. The models are core meshes and need no files. A source whose `skipRendering` is true (the system draws it) is hidden. The models are made in the scene the XR is in, whichever scene is active when a frame arrives, and are disposed with that scene.
167
-
168
- ```ts
169
- import {Engine} from 'margoengine/core';
170
- import {XR} from 'margoengine/xr';
171
- import {XRModels} from 'margoengine/xr/models';
172
-
173
- const canvas=document.createElement('canvas');document.body.append(canvas);
174
- const engine=await Engine.create(canvas,{backend:'webgpu'});
175
- const xr=await XR.create(engine);
176
- const models=XRModels.attach(xr,engine,{handColor:'#d8b49a'});
177
- const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
178
- enter.onclick=()=>void xr.requestSession('immersive-vr',{optionalFeatures:['hand-tracking']}).catch(engine.onError);
179
- // models.dispose() removes the meshes.
180
- ```
181
-
182
- For a device's own model, serve the [WebXR input profile assets](https://github.com/immersive-web/webxr-input-profiles) and call `fetchProfile(source, baseUrl)`: it picks the most specific listed profile and gives its layout and model URL. `componentStates(layout, controller)` and `responseWeight(response, state)` give each node's weight for the layout's visual responses each frame. `xr.onFrame(callback)` runs a function every XR frame, before the session's own `onFrame`.
183
-
184
- ## AR planes, depth and light
185
-
186
- `@margoengine/xr/ar` reads what an AR device knows about the room, each in the session's reference space. Ask for the features when the session starts; `init` passes module options such as `depthSensing` through to `navigator.xr.requestSession`.
187
-
188
- - `ARPlanes.create(xr, { onAdd, onChange, onRemove, show })` follows `frame.detectedPlanes`: each plane's pose (its y axis is the normal), outline, orientation and label, and with `show` a flat mesh per plane.
189
- - `ARDepth.create(xr)` reads CPU depth: `depthAt(frame, view, x, y)` in metres at a point of the view (0 to 1 from the top left) and `pointAt(...)` the real-world point there.
190
- - `await ARLight.create(xr, { lighting: engine.lighting })` turns the room's light estimate into `estimate` (spherical harmonics in `@margoengine/math` SH3 order, the brightest light's direction and colour) and points the engine's sun at the room's brightest light, with the ambient set to the room's average light.
191
-
192
- ```ts
193
- import {Engine,PbrMaterial} from 'margoengine/core';
194
- import {XR} from 'margoengine/xr';
195
- import {ARDepth,ARLight,ARPlanes,DEPTH_SENSING} from 'margoengine/xr/ar';
196
-
197
- const canvas=document.createElement('canvas');document.body.append(canvas);
198
- const engine=await Engine.create(canvas,{backend:'webgpu'});
199
- const xr=await XR.create(engine);
200
- const enter=document.createElement('button');enter.textContent='Enter AR';document.body.append(enter);
201
- enter.onclick=async()=>{
202
- await xr.requestSession('immersive-ar',{optionalFeatures:['plane-detection','depth-sensing','light-estimation'],init:{depthSensing:DEPTH_SENSING}});
203
- const planes=ARPlanes.create(xr,{show:{engine,material:new PbrMaterial({color:'#4f9be8'})},onAdd:(plane)=>console.log('plane',plane.label)});
204
- const light=await ARLight.create(xr,{lighting:engine.lighting});
205
- const depth=ARDepth.create(xr);
206
- xr.onFrame(({frame,viewer})=>{const view=viewer?.views[0];if(view)console.log(depth.depthAt(frame,view,0.5,0.5));});
207
- // planes.dispose() and light.dispose() stop them.
208
- };
209
- ```
210
-
211
- Each `create` throws a coded error naming the feature to ask for when the session lacks it.
212
-
213
- ## AR occlusion by real depth
214
-
215
- `@margoengine/xr/occlusion` hides the scene where the real world is in front of it, so a virtual box behind a real chair disappears behind the chair. It reads the session's depth sensing each frame and runs one full-screen pass per eye after the scene draws, on both XR routes and on the WebGL2 layer.
216
-
217
- - CPU-optimized depth (`DEPTH_SENSING`, `float32`, `unsigned-short` or `luminance-alpha`) is uploaded to a small texture each frame; GPU-optimized depth (`usagePreference: ['gpu-optimized']`, `float32` or `unsigned-short`) is read where the browser leaves it, with no copy.
218
- - Each drawn sample of the eye's depth becomes a point, carried into the depth sensor's own view (its pose and projection when they differ from the eye's), and compared with the real depth there. Pixels with no depth (0, invalid) hide nothing.
219
- - `feather` (metres, default `0.05`) fades a surface from shown to hidden around equal depth, which hides the sensor's noise along the contact line; `0` gives a hard edge. `enabled = false` skips the pass.
220
- - Content that writes no depth has nothing to compare and is kept: a `Line` needs `depthWrite: true` to be hidden. A pixel with colour but no depth sample of its own (the antialiased fringe of a line or an edge) takes its neighbours' verdict.
221
-
222
- ```ts
223
- import {Engine,PbrMaterial,box} from 'margoengine/core';
224
- import {XR} from 'margoengine/xr';
225
- import {DEPTH_SENSING} from 'margoengine/xr/ar';
226
- import {AROcclusion} from 'margoengine/xr/occlusion';
227
-
228
- const canvas=document.createElement('canvas');document.body.append(canvas);
229
- const engine=await Engine.create(canvas,{backend:'webgpu'});
230
- engine.createMesh().setGeometry(box(0.3,0.3,0.3)).setMaterial(new PbrMaterial({color:'#e8a04f'})).setPosition([0,0,-1.5]);
231
- const xr=await XR.create(engine);
232
- const enter=document.createElement('button');enter.textContent='Enter AR';document.body.append(enter);
233
- enter.onclick=async()=>{
234
- await xr.requestSession('immersive-ar',{requiredFeatures:['depth-sensing'],init:{depthSensing:DEPTH_SENSING}});
235
- const occlusion=AROcclusion.create(xr,{feather:0.05});
236
- // occlusion.enabled=false shows the scene over everything again; occlusion.dispose() stops it.
237
- };
238
- ```
239
-
240
- `AROcclusion.create` throws `state` without a session and `unsupported` when the session has no depth sensing, or has GPU depth in `luminance-alpha`, which WebGPU cannot read. Tested with stand-in sessions on real GPUs (`npm run test:gpu:occlusion`); not yet run on an AR device.
241
-
242
- ## AR reflections from the room's light
243
-
244
- `@margoengine/xr/reflection` turns the room's light estimate into a cube texture, which an `Environment` from `@margoengine/environment` filters into the scene's specular reflections and diffuse harmonics, so a shiny virtual object reflects the room it sits in. Start the session with `light-estimation`.
245
-
246
- - `ARReflection.create(xr, { device })` follows the browser's light probe. Where the WebGPU binding gives the probe's reflection cube map (`getReflectionCubeMap`, the `reflectionchange` event of the WebXR Lighting Estimation API), that texture is copied into the cube; everywhere else the cube is painted from the probe's nine spherical harmonics, a soft room of bands 0 to 2 (Ramamoorthi and Hanrahan, 2001).
247
- - Options and defaults: `size` 32 (power of two, 8 to 256; the harmonics path), `reflectionFormat` `'rgba16f'`, `interval` 500 ms between harmonics repaints, `forceSH` false, `light` (an `ARLight` to share; one is made otherwise).
248
- - `await reflection.ready` gives the cube texture after the first estimate; make the `Environment` from it and `reflection.attach(environment)` so it is refreshed after each repaint.
249
-
250
- ```ts
251
- import {Engine} from 'margoengine/core';
252
- import {Environment} from 'margoengine/environment';
253
- import {XR} from 'margoengine/xr';
254
- import {ARReflection} from 'margoengine/xr/reflection';
255
-
256
- const canvas=document.createElement('canvas');document.body.append(canvas);
257
- const engine=await Engine.create(canvas,{backend:'webgpu'});
258
- const xr=await XR.create(engine);
259
- const enter=document.createElement('button');enter.textContent='Enter AR';document.body.append(enter);
260
- enter.onclick=async()=>{
261
- await xr.requestSession('immersive-ar',{requiredFeatures:['light-estimation']});
262
- const reflection=await ARReflection.create(xr,{device:engine.gpu!,size:32});
263
- const cube=await reflection.ready;
264
- const environment=await Environment.create(engine,{texture:cube},{size:cube.width});
265
- engine.use(environment);
266
- reflection.attach(environment);
267
- // reflection.dispose() stops it.
268
- };
269
- ```
270
-
271
- Tested with stand-in sessions on real GPUs (`npm run test:gpu:reflection`); not yet run on an AR device.
272
-
273
- ## AR where WebXR is absent: Quick Look and Scene Viewer
274
-
275
- `@margoengine/xr/launch` opens a model in the phone's own AR viewer when the browser has no `immersive-ar` session. iOS Safari has none, so a USDZ opens in AR Quick Look through an anchor with `rel="ar"` and an image inside; Android Chrome without WebXR opens Google's Scene Viewer through an intent URL. The USDZ comes from `exportUSDZ` (`@margoengine/exporters/usdz`), the GLB from `exportGLB`.
276
-
277
- - `chooseARRoute({webxr})` returns `'webxr'` (start an `XR` session instead), `'quick-look'` (the browser answers `relList.supports('ar')`), `'scene-viewer'` (an Android user agent) or `'none'`. Every field of the platform argument defaults to the browser's own value.
278
- - `launchAR({usdz, glb, ...})` does the opening and returns the route. Call it from a tap. `usdz` is a URL or the bytes (made into a blob URL for a minute); `glb` must be one Scene Viewer can fetch itself (no blob). `fallback(route)` runs where neither viewer exists; a route that needs a model you left out throws code `state`.
279
- - `quickLookURL(url, {allowsContentScaling, canonicalWebPageURL})` and `sceneViewerURL(url, {mode, title, link, sound, resizable, verticalPlacement, fallbackUrl})` build the two links alone. URLs are checked before they reach a link or intent: each is resolved against `document.baseURI` and only `https:` and `http:` pass (`blob:` too for the USDZ), so `javascript:`, `data:`, `vbscript:` and `file:` throw code `unsupported`; every value is percent-encoded, the `#Intent;...;end;` part is a fixed template, and `mode` must be `ar_preferred`, `3d_preferred` or `3d_only` (else `RangeError`). Defaults: scaling on, `mode` `'ar_preferred'`, `resizable` true, vertical placement off, fallback the current page, `title` cut to 60 characters.
280
-
281
- ```ts
282
- import {chooseARRoute, launchAR, quickLookURL, sceneViewerURL} from 'margoengine/xr/launch';
283
-
284
- console.log(chooseARRoute({webxr: false, quickLook: true}));
285
- console.log(quickLookURL('https://example.com/chair.usdz', {allowsContentScaling: false}));
286
- console.log(sceneViewerURL('https://example.com/chair.glb', {title: 'Chair', fallbackUrl: 'https://example.com/chair'}));
287
- const button = document.createElement('button');
288
- button.textContent = 'View in your room';
289
- button.onclick = () => launchAR({usdz: 'https://example.com/chair.usdz', glb: 'https://example.com/chair.glb', fallback: () => alert('AR is not available here')});
290
- document.body.append(button);
291
- ```
292
-
293
- Tested with stand-in pages and links in Node; not yet run on an iPhone or an Android phone.
294
-
295
- ## Layers, haptics, video and locomotion
296
-
297
- `@margoengine/xr/layers` adds WebXR composition layers, controller vibration and teleport movement. Layers are drawn by the headset's compositor at their own resolution, so text and video stay sharp. Ask for `optionalFeatures: ['layers']`.
298
-
299
- - `XRLayers.attach(xr)` then `quad`, `cylinder`, `equirect`, `cube` or `video(element)`: each takes `pixels`, a placement and `content` (an image, a `{left, right}` pair, six cube faces, or a function that draws into each eye's texture). Quads, cylinders and video sit above the scene, equirect and cube skies below it; `isStatic: true` draws once until `redraw()` or the compositor asks. A video or `VideoFrame` as `content` in a browser that takes no video as a copy source (Firefox) is drawn on a canvas each frame and copied from there.
300
- - Every layer also takes `quality` (`'default'`, `'text-optimized'` or `'graphics-optimized'`, what the compositor favours when it resamples), `blendTextureSourceAlpha` (default true), `chromaticAberrationCorrection` and `mipLevels` (default 1); each is left to the browser when you do not pass it. Use `quality: 'text-optimized'` for menus and captions.
301
- - `pulse(controller, intensity, milliseconds)` vibrates a controller and resolves false when it has no actuator.
302
- - `teleportArc(origin, direction, options)` samples the parabola a teleport pointer draws and where it lands; `Locomotion.attach(xr)` moves the player there with `teleport(point, yaw)` and turns with `turn(yaw)`, by offsetting the reference space.
303
-
304
- ```ts
305
- import {Engine} from 'margoengine/core';
306
- import {XR} from 'margoengine/xr';
307
- import {Locomotion,XRLayers,pulse,teleportArc} from 'margoengine/xr/layers';
308
-
309
- const canvas=document.createElement('canvas');document.body.append(canvas);
310
- const engine=await Engine.create(canvas,{backend:'webgpu'});
311
- const xr=await XR.create(engine);
312
- const menu=new OffscreenCanvas(512,256);const pen=menu.getContext('2d')!;pen.fillStyle='#223';pen.fillRect(0,0,512,256);pen.fillStyle='#fff';pen.font='48px sans-serif';pen.fillText('Hello',40,140);
313
- const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
314
- enter.onclick=async()=>{
315
- await xr.requestSession('immersive-vr',{optionalFeatures:['layers']});
316
- const layers=XRLayers.attach(xr);
317
- layers.quad({pixels:[512,256],size:[1,0.5],position:[0,1.5,-1.5],content:menu,isStatic:true});
318
- const move=Locomotion.attach(xr);
319
- xr.onFrame(({inputs})=>{
320
- const c=xr.controllers[0],ray=c?.targetRay;if(!ray)return;
321
- const p=ray.transform.position,m=c.targetRayMatrix;
322
- const arc=teleportArc([p.x,p.y,p.z],[-m[8],-m[9],-m[10]]);
323
- if(arc.hit&&c.buttons[1]){move.teleport(arc.hit);void pulse(c,0.6,40);}
324
- });
325
- };
326
- ```
327
-
328
- Without the browser's layer support `XRLayers.attach` and each layer throw a coded error that names the feature to ask for.
329
-
330
- ## Session state: blend mode, frame rate, visibility and play area
331
-
332
- `@margoengine/xr/session` reads and follows what the WebXR session says about the display and the room, with no rendering of its own.
333
-
334
- - `XRSessionState.attach(xr, { signal })` gives `environmentBlendMode` (`'opaque'`, `'additive'` or `'alpha-blend'`), `interactionMode`, `visibility` (`'visible'`, `'visible-blurred'` while a system menu is up, `'hidden'`) with `onVisibilityChange(callback)`, and `frameRate`.
335
- - `supportedFrameRates` lists the rates the device accepts and `await setFrameRate(rate)` asks for one; a rate not in the list throws a `RangeError`, and a browser without frame rate control rejects with an `unsupported` error.
336
- - `bounds` is the play area of a `referenceSpace: 'bounded-floor'` session as x and z metres per corner (null otherwise), and `onReset(callback)` runs when the space resets, so you can read `bounds` again.
337
-
338
- ```ts
339
- import {Engine} from 'margoengine/core';
340
- import {XR} from 'margoengine/xr';
341
- import {XRSessionState} from 'margoengine/xr/session';
342
-
343
- const canvas=document.createElement('canvas');document.body.append(canvas);
344
- const engine=await Engine.create(canvas,{backend:'webgpu'});
345
- const xr=await XR.create(engine);
346
- const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
347
- enter.onclick=async()=>{
348
- await xr.requestSession('immersive-vr',{referenceSpace:'bounded-floor',optionalFeatures:['bounded-floor']});
349
- const state=XRSessionState.attach(xr);
350
- const fastest=state.supportedFrameRates.at(-1);
351
- if(fastest&&fastest!==state.frameRate)await state.setFrameRate(fastest);
352
- state.onVisibilityChange((visibility)=>console.log('session is',visibility));
353
- console.log(state.environmentBlendMode,state.frameRate,state.bounds);
354
- // state.dispose() stops it.
355
- };
356
- ```
357
-
358
- Tested with stand-in sessions; not yet run on a headset.
359
-
360
- ## Smooth movement, skinned hands, AR extras and performance
361
-
362
- Four more entries are separate imports, so a page that does not use them does not load them. Each attaches to a running session and stops when the session ends or its `AbortSignal` aborts.
363
-
364
- - `@margoengine/xr/locomotion` adds `SmoothLocomotion.attach(xr, options)`: thumbstick walking and smooth turning next to the teleport and snap turn of `Locomotion`, with a vignette that fades in while you move (`vignette: false` turns it off; `comfort` reads its strength). Options and defaults: `speed` 2 (metres per second), `turnSpeed` `Math.PI / 2` (radians per second), `moveHand` `'left'`, `turnHand` `'right'`, `direction` `'head'`, `deadZone` 0.15, `axes` `[2, 3]`, `fieldOfView` `Math.PI / 2`, `feather` 0.2 and `fade` 0.15. Set `enabled = false` to pause it.
365
- - `@margoengine/xr/hands` adds `SkinnedHands.create(xr, {left, right}, options)`, which drives your own skinned glTF hand models from the 25 tracked joints (`HAND_JOINT_NAMES` lists them). It keeps each asset's inverse binds and weights and loads `@margoengine/animation` when you call it. `jointNames` maps WebXR joint names to your node names when they differ from the generic-hand profile names. Pass at least one model, and not the same model for both hands.
366
- - `@margoengine/xr/ar-extra` adds `DOMOverlay` (with `domOverlaySessionOptions(root)` for the session request), `ImageTracking` (with `imageTrackingSessionOptions(images)`), `MeshDetection` for the room's triangle meshes, which can draw them as Margo meshes through its `show` option, and `PersistentAnchors`, whose handles belong to the browser and the origin until you delete them. Each needs its WebXR feature in the session and rejects with an `unsupported` error naming what is missing.
367
- - `@margoengine/xr/performance` adds `performanceSessionOptions({framebufferScale, cameraAccess})` for the session request and `XRPerformance.attach(xr, {fixedFoveation, signal})` for a live foveation setting (0 to 1) that is restored when the session ends or the signal aborts. Camera images are a borrowed WebGL texture, valid only inside their XR frame; native WebGPU raw camera access rejects with the capability reason.
368
-
369
- ## Interaction toolkit
370
-
371
- `Interaction.attach(xr, { grabbables, sockets, panels })` from `@margoengine/xr/interaction` handles the usual hand and controller interactions. Squeeze (or pinch, on a tracked hand) near an object or with the ray on it to pick it up; it follows the grip as you hold it. Let go over a socket that fits and it snaps in; otherwise `onRelease` gets its speed for a throw. Point the ray at a panel and press the trigger (or pinch) for `down` and `up`, with `u` and `v` from the panel's top left. The arrays stay live: push or remove items at any time.
372
-
373
- ```ts
374
- import {Engine,PbrMaterial,box as boxGeometry} from 'margoengine/core';
375
- import {Quaternion} from 'margoengine/math/quaternion';
376
- import {Vector3} from 'margoengine/math/vector3';
377
- import {XR} from 'margoengine/xr';
378
- import {Interaction,grabbable} from 'margoengine/xr/interaction';
379
-
380
- const canvas=document.createElement('canvas');document.body.append(canvas);
381
- const engine=await Engine.create(canvas,{backend:'webgpu'});
382
- const xr=await XR.create(engine);
383
- const box=engine.createMesh().setGeometry(boxGeometry()).setMaterial(new PbrMaterial({color:'#e8a33d'})).setScale([0.1,0.1,0.1]).setPosition([0,1,-0.5]);
384
- const cube=grabbable(box,{radius:0.08});
385
- const shelf={position:new Vector3(0.3,1,-0.5),orientation:new Quaternion(),radius:0.1,held:null};
386
- const button={position:new Vector3(0,1.4,-1),orientation:new Quaternion(),size:[0.3,0.1] as const,onPointer:(e:{type:string})=>{if(e.type==='up')console.log('clicked');}};
387
- const ui=Interaction.attach(xr,{grabbables:[cube],sockets:[shelf],panels:[button]});
388
- const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
389
- enter.onclick=()=>void xr.requestSession('immersive-vr',{optionalFeatures:['hand-tracking']}).catch(engine.onError);
390
- // ui.rays[i] tells where each ray points, for drawing a pointer; ui.dispose() lets go of everything.
391
- ```
392
-
393
- ## Near interaction
394
-
395
- `@margoengine/xr/near` holds the hand-and-controller behaviours for UI you reach out to. Each one attaches to the `XR` (any `{controllers, onFrame}` host), moves objects you pass in (`{position, orientation}`, plus `scale` where it scales), has `dispose()` and `Symbol.dispose`, and checks its options with a `RangeError` that names the fix. Units are metres in the reference space.
396
-
397
- | Behaviour | What it does |
398
- | --- | --- |
399
- | `HandConstraint` | Carries a menu on the palm. It shows while a tracked hand's palm faces you (`showAngle` 45 degrees) and hides past `hideAngle` (60), so it does not flicker; `offset` is in the wrist joint's frame, default 10 cm off the palm. |
400
- | `FollowInView` | Tag-along: a panel stays put while it is inside a cone around your gaze (`maxViewDegrees` 25) and between `minDistance` 0.4 and `maxDistance` 1.2; outside, it eases to the cone's edge. `enabled = false` pins it, `snap()` puts it `distance` in front, `billboard` turns it to face you. |
401
- | `SurfaceMagnetism` | Sticks an object to the surface the gaze or a controller ray points at (planes, for example AR hit tests through `surfaceFromHit(hit)`), aligned to the normal: `normalAxis` 'y' stands it up, 'z' hangs a panel. `snapToSurface` snaps an object that something else moved. |
402
- | `Manipulator` | Six-DoF drag and multi-pointer scale: a pinch or squeeze on an object, or along the ray, picks it up; it keeps its pose in your hand's frame. A second pointer on the same object scales it by the distance between the pointers and turns it by the line between them; lifting one returns to the one-point drag with no jump. `rotate` ('follow', 'yaw', 'none'), `lock`, `translate` and `scaleLimits` constrain it. |
403
- | `AppBar` | A row of buttons under an object (default `remove` and `adjust`) that shows when a hand is within `showDistance` (0.6 m). |
404
- | `NearMenu` | A grid of buttons in front of you that tags along until its pin button pins it. |
405
- | `Slate` | A holographic 2D panel: drag its title bar to move it, its corner to resize it (within `minSize` and `maxSize`), its content to pan it (`contentOffset`, `zoomBy`); taps and the close button call back. |
406
-
407
- `AppBar`, `NearMenu` and `Slate` are `RayPanel`s: add them to `Interaction.panels` and rays and pinches press them. `AppBar` and `NearMenu` are also pressed by a fingertip: the index tip hovers a button within 6 cm of the panel, presses within 1.2 cm and clicks on release (`poke` sets the distances, `false` turns it off). They expose `layout()`, each button's centre, size and state in metres from the panel's centre, for drawing; Margo draws nothing here, so the look is yours.
408
-
409
- ```ts
410
- import {Engine,PbrMaterial,box as boxGeometry} from 'margoengine/core';
411
- import {Quaternion} from 'margoengine/math/quaternion';
412
- import {Vector3} from 'margoengine/math/vector3';
413
- import {XR} from 'margoengine/xr';
414
- import {Interaction} from 'margoengine/xr/interaction';
415
- import {AppBar,FollowInView,HandConstraint,Manipulator,NearMenu,Slate,SurfaceMagnetism,nearTarget} from 'margoengine/xr/near';
416
-
417
- const canvas=document.createElement('canvas');document.body.append(canvas);
418
- const engine=await Engine.create(canvas,{backend:'webgpu'});
419
- const xr=await XR.create(engine);
420
- const box=engine.createMesh().setGeometry(boxGeometry()).setMaterial(new PbrMaterial({color:'#e8a33d'})).setScale([0.2,0.2,0.2]).setPosition([0,1,-0.6]);
421
- const cube=nearTarget(box,{radius:0.15,scale:[0.2,0.2,0.2]});
422
- // Pinch or squeeze the cube to move it; two hands scale it (x scale between 0.05 and 0.6).
423
- const drag=Manipulator.attach(xr,{draggables:[cube],scaleLimits:[0.05,0.6]});
424
- // Its app bar appears when a hand comes near.
425
- const bar=AppBar.attach(xr,{target:cube,extent:[1,1],onSelect:(id)=>{if(id==='remove')cube.enabled=false;}});
426
- // A menu on the left palm, a tag-along menu and a slate.
427
- const wrist={position:new Vector3(),orientation:new Quaternion()};
428
- const palm=HandConstraint.attach(xr,{target:wrist,hand:'left'});
429
- const menu=NearMenu.attach(xr,{buttons:[{id:'a',label:'A'},{id:'b',label:'B'}],onSelect:(id)=>console.log('menu',id)});
430
- const slate=new Slate({title:'Notes',onClose:()=>{slate.enabled=false;},onContent:(e)=>console.log('tap',e.x,e.y)});
431
- const rays=Interaction.attach(xr,{panels:[bar,menu,slate]});
432
- // Hang a label on the wall the gaze meets (planes such as AR hit tests give; see surfaceFromHit), and keep it in view.
433
- const label={position:new Vector3(),orientation:new Quaternion()};
434
- const wall=SurfaceMagnetism.attach(xr,{target:label,surfaces:[{point:[0,0,-3],normal:[0,0,1]}],normalAxis:'z'});
435
- const tag=FollowInView.attach(xr,{target:label,billboard:'none',snapOnStart:false});
436
- const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
437
- enter.onclick=()=>void xr.requestSession('immersive-vr',{optionalFeatures:['hand-tracking']}).catch(engine.onError);
438
- // Draw bar.layout(), menu.layout() and the slate with your own meshes; menu.pinned = true stops it following you.
439
- void [drag,palm,rays,wall,tag];
440
- ```
441
-
442
- Hands report no buttons, so `Manipulator` picks up with a pinch (thumb tip to index tip within `pinch`, default 2 cm) and controllers with the squeeze button. Joint frames follow WebXR Hand Input: -Z toward the fingertips and -Y out of the palm.
443
-
444
- ## Transform gizmo by controller ray
445
-
446
- `@margoengine/xr/gizmo` drives the transform gizmo of `@margoengine/controls/transform` from the controllers' target rays instead of a mouse. Point a controller at a handle and it lights; hold the trigger and the handle follows the ray under the gizmo's own constraints: arrows and scale cubes slide along their axis, plane handles over their plane, rings turn by the angle the ray sweeps on the ring's plane. Press the other controller's trigger during a grab and the two hands scale everything attached by the ratio of their separation. Snapping, modes, spaces, pivots, several objects and the gizmo's events are the gizmo's own, so they match the desktop.
447
-
448
- | Option | Default | What it does |
449
- | --- | --- | --- |
450
- | `button` | `'select'` | The action that grabs: `'select'` (trigger, or a hand's pinch) or `'squeeze'` (grip). |
451
- | `hands` | `['left', 'right', 'none']` | Which input sources drive the gizmo, by handedness. |
452
- | `twoHandScale` | `true` | A second hand's press during a grab starts a two-hand scale. The one-hand drag ends where it is. |
453
- | `minSeparation` | `0.02` | Hands closer than this, in metres, at the second press do not start a scale. |
454
- | `onHover`, `onGrab`, `onRelease` | none | Called with `{controller, handle}`: the handle's name, `'scale'` for a two-hand scale, null when a hover ends. |
455
- | `signal` | none | Aborting disposes the driver. |
456
-
457
- ```ts
458
- import {Engine,PbrMaterial,box as boxGeometry} from 'margoengine/core';
459
- import {TransformControls} from 'margoengine/controls/transform';
460
- import {XR} from 'margoengine/xr';
461
- import {XRGizmo} from 'margoengine/xr/gizmo';
462
- import {pulse} from 'margoengine/xr/layers';
463
-
464
- const canvas=document.createElement('canvas');document.body.append(canvas);
465
- const engine=await Engine.create(canvas,{backend:'webgpu'});
466
- const xr=await XR.create(engine);
467
- const box=engine.createMesh().setGeometry(boxGeometry()).setMaterial(new PbrMaterial({color:'#e8a33d'})).setScale([0.3,0.3,0.3]).setPosition([0,1.2,-1]);
468
- // A gizmo 25 cm long in the room (fixed: false), with arrows, rings and scale cubes; moves snap to 5 cm, turns to 15 degrees.
469
- const gizmo=new TransformControls(engine,{mode:'all',fixed:false,size:0.25,translationSnap:0.05,rotationSnap:Math.PI/12});
470
- gizmo.attach(box);
471
- // Point at a handle and hold the trigger to drag it; press the other trigger as well to scale with two hands.
472
- const drive=XRGizmo.attach(xr,gizmo,{
473
- onGrab:({controller,handle})=>{console.log(controller.source.handedness,'holds',handle);void pulse(controller,0.4,30);},
474
- onRelease:()=>console.log('now at',box.position.x,box.position.y,box.position.z,'scale',box.scale.x),
475
- });
476
- const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
477
- enter.onclick=()=>void xr.requestSession('immersive-vr').catch(engine.onError);
478
- addEventListener('pagehide',()=>{drive.dispose();gizmo.dispose();},{once:true});
479
- ```
480
-
481
- `XRGizmo.attach(xr, gizmo, options)` takes the `XR` (any `{session, controllers, onFrame}` host) and a `TransformControls` (any gizmo with its pointer methods and ray hook: `frame`, `pick`, `setAxis`, `pointerDown`, `pointerMove`, `begin`, `endDrag` and `aim`). `drive.grabbing` is the controller holding a handle, `drive.scaling` is true during a two-hand scale, and `dispose()` or `using` lets go and removes every listener. A bad host, gizmo or option throws a `RangeError` that names the fix. Poses are read in the XR reference space and taken as world space. A ray within 2.5 degrees of the arrow it drags has no steady nearest point on it, so there the arrow follows the hand's own travel along the axis and does not jump. A controller that leaves the session, or a session that ends, lets go. After a two-hand scale a hand that is still pressing presses again to grab. Not run on a headset: it is tested with simulated input sources and poses.
482
-
483
- ### Any world ray: `GizmoRayDriver`
484
-
485
- `XRGizmo` works through `GizmoRayDriver`, which the entry also exports for rays that are not XR controllers (a tracked stylus, a second camera, a test). `new GizmoRayDriver(gizmo)` wraps a `TransformControls`; a ray is an origin and a direction in world space, and the direction need not be unit. The ray code lives in this entry, so `@margoengine/controls/transform` on a desktop page does not carry it.
486
-
487
- | Method | What it does |
488
- | --- | --- |
489
- | `rayHover(origin, direction)` | Lights the handle the ray points at and returns its name, or null. During a drag it returns the dragged handle and changes nothing. The pick radius is 1.5 degrees about the ray. |
490
- | `rayDown(origin, direction)` | Grabs the handle the ray points at and starts a drag. False when it points at none or a drag is under way. |
491
- | `rayMove(origin, direction)` | Continues the drag. An arrow or scale cube follows the point of its axis nearest the ray; a plane handle follows the ray over its plane; a ring turns by the angle the ray sweeps on its plane; the view ring, the free turn and the centre scale handle read the ray's travel across a plane facing the ray at the grab. |
492
- | `rayUp()` | Ends a `rayDown` or `scaleDown` drag; with no drag, puts out the hover light. A pointer drag is left alone. |
493
- | `scaleDown()` | Starts a two-point scale in any mode. False when nothing is attached or a drag is under way. |
494
- | `scaleTo(factor)` | Sizes everything attached about the gizmo: 1 is the size at `scaleDown`, and the scale snap applies. |
495
- | `dragging`, `gizmo` | True while a handle is dragged; the gizmo driven. |
496
-
497
- A ray that is not finite or has a zero direction, and a `scaleTo` factor that is not above 0, throw a `RangeError`. A disabled gizmo or one with nothing attached takes no ray. Modes, spaces, pivots, several objects, snapping, `cancelDrag()`, `reset()` and the events work as with a pointer.
498
-
499
- ```ts
500
- import {Engine, box} from 'margoengine/core';
501
- import {TransformControls} from 'margoengine/controls/transform';
502
- import {GizmoRayDriver} from 'margoengine/xr/gizmo';
503
-
504
- const engine = await Engine.create(document.querySelector('canvas')!);
505
- const crate = engine.createMesh().setGeometry(box());
506
- const gizmo = TransformControls.attach(engine, {translationSnap: 0.25});
507
- gizmo.attach(crate);
508
- engine.render();
509
- const rays = new GizmoRayDriver(gizmo);
510
- // A ray from a hand at [0.5, 2, 3] down to the X arrow, then swung to meet the axis one unit further along.
511
- const hand = [0.5, 2, 3], reach = 0.6 * gizmo.frame()!.size;
512
- const toward = (x: number) => [x - hand[0], -hand[1], -hand[2]];
513
- if (rays.rayDown(hand, toward(reach))) {
514
- rays.rayMove(hand, toward(reach + 1));
515
- rays.rayUp();
516
- }
517
- console.log(crate.position.x); // 1
518
- ```
519
-
520
- Sources: WebXR Device API, W3C (input sources, `targetRaySpace`, select and squeeze events), https://www.w3.org/TR/webxr/; C. Ericson, Real-Time Collision Detection, 2005, section 5.1.8 (closest points of two lines), https://realtimecollisiondetection.net/; M. Mine, F. Brooks and C. Sequin, Moving Objects in Space: Exploiting Proprioception in Virtual-Environment Interaction, SIGGRAPH 1997 (two-handed scaling), https://doi.org/10.1145/258734.258747; D. Bowman and L. Hodges, An Evaluation of Techniques for Grabbing and Manipulating Remote Objects in Immersive Virtual Environments, I3D 1997 (ray-casting and HOMER), https://doi.org/10.1145/253284.253301; D. Mendes, F. Caputo, A. Giachetti, A. Ferreira and J. Jorge, A Survey on 3D Virtual Object Manipulation: From the Desktop to Immersive Virtual Environments, Computer Graphics Forum 2019 (widgets that separate degrees of freedom), https://doi.org/10.1111/cgf.13390.
521
-
522
- ## Preview tier refusal
523
-
524
- `XR.create` and `XR.attach` reject the small WebGL2 preview with linked `MargoError` code `unsupported`, so an awaited call inside `autoEngine` setup can trigger `loadCompat`. After installing the full layer, WebXR also needs its `/xr` route and browser session support as documented above. An already attached or disposed engine remains a state error.
525
-
526
- ## Mesh pointer events
527
-
528
- `XRPointerEvents` from `@margoengine/xr/pointer` sends `pointerover`, `pointerout`,
529
- `pointermove`, `pointerdown`, `pointerup`, `pointercancel` and `click` to selection
530
- hits on any supported mesh or glTF primitive. `SpatialPicking` from
531
- `@margoengine/selection/spatial` supplies GPU ray picking and exact triangle
532
- proximity. A source has one stable pointer id. Touch wins over grab, then ray;
533
- `types` can change that order or disable modes. Capture keeps the selected target
534
- through a miss. Session end, source removal, tracking loss and disposal cancel a
535
- press. Pending picks retain pose snapshots and press/release ordering; moves
536
- coalesce. Native select/squeeze events support sources without gamepads.
537
-
538
- Copy `packages/exporters/tests/fixtures/Box.glb` to your app's
539
- `public/xr-pointer-box.glb` before running this example. The README gate serves
540
- that exact licensed fixture at the same URL.
541
-
542
- ```ts
543
- import { Engine } from '@margoengine/core';
544
- import { loadGLTF } from '@margoengine/gltf/pbr';
545
- import { Picking } from '@margoengine/selection';
546
- import { SpatialPicking } from '@margoengine/selection/spatial';
547
- import { XR } from '@margoengine/xr';
548
- import { XRPointerEvents } from '@margoengine/xr/pointer';
549
-
550
- const canvas = document.createElement('canvas'); document.body.append(canvas);
551
- const engine = await Engine.create(canvas, { backend: 'webgpu', camera: { position: [0, 0, 4] } });
552
- await loadGLTF(engine, '/xr-pointer-box.glb');
553
- const picking = Picking.attach(engine);
554
- const spatial = new SpatialPicking(engine, picking);
555
- const xr = await XR.create(engine);
556
- const pointers = XRPointerEvents.attach(xr, spatial, {
557
- onEvent(event) { if (event.type === 'click') console.log(event.target, event.pointerType); },
558
- onError: engine.onError,
559
- });
560
- const enter = document.createElement('button'); enter.textContent = 'Enter VR'; document.body.append(enter);
561
- enter.onclick = () => void xr.requestSession('immersive-vr', { optionalFeatures: ['hand-tracking'] }).catch(engine.onError);
562
- engine.start();
563
- // On teardown: pointers.dispose(); spatial.dispose(); picking.dispose(); xr.dispose(); engine.dispose();
564
- ```
565
-
566
- The sample model is Cesium's Khronos Box, CC BY 4.0; see
567
- [its fixture notice](../exporters/tests/fixtures/NOTICE.md). Serve this repository
568
- or copy that standard asset to your application's public folder.
569
-
570
- Distances are metres: `touchRadius` defaults to 0.01 in addition to the reported
571
- fingertip radius, `grabRadius` to 0.08, `near` to 0.0001 and `far` to 1000. Pinch
572
- uses a 0.025 metre thumb/index-tip threshold. Controller trigger selects; squeeze
573
- grabs. Touch presses on surface contact and releases/clicks on leaving it. A
574
- held pointer keeps its mode through release. `signal` aborts the attachment;
575
- `dispose()` and `Symbol.dispose` detach it. `onError` is required. `onEvent` may
576
- call `stopPropagation` and `setPointerCapture(target?)`, `releasePointerCapture`
577
- or `hasPointerCapture`; the optional target lets a parent capture a child hit.
578
- A custom picker can implement the exported `XRPointerPicker` interface.
579
-
580
- React apps mount `XRPointerEvents` from `@margoengine/react/xr-pointer` inside
581
- `Canvas` and `XR`; existing mesh handlers receive the events with the source and
582
- selection hit at `event.xr`. See that package's example. These deterministic and
583
- browser checks do not replace the still-missing physical device runs.
584
-
585
- `npm run test:gpu:pointers --workspace @margoengine/xr` is registered in the GPU
586
- package plan and check:merge, with a 3 minute hard limit. Pass `-- --compat` for
587
- the WebGL2 implementation. The dedicated compatibility XR bridge suite remains
588
- packages/webgl2-compat/test/xr-browser.mjs.
589
-
590
- ### Attaching from a second scene
591
-
592
- `XR.create` remembers the scene that is active when you call it, before its first await, and joins that scene when it finishes. Start it inside a second scene's plugin `setup` and the plugin belongs to that scene; start it anywhere else and it belongs to the default scene. An abort or a failure leaves nothing in either scene.
1
+ # @margoengine/xr
2
+
3
+ Import `margoengine/xr` from the `margoengine` package, or `@margoengine/xr` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Optional WebGPU WebXR session negotiation, input poses and instanced stereo PBR rendering. XR owns a compatible GPU device and attaches through the existing core extension interface. Core and the stage facade remain frozen.
6
+
7
+ ```ts
8
+ import {Engine,box} from 'margoengine/core';
9
+ import {XR} from 'margoengine/xr';
10
+
11
+ const canvas=document.createElement('canvas');document.body.append(canvas);
12
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
13
+ const cube=engine.createMesh().setGeometry(box());
14
+ if(await XR.isSupported('immersive-vr')) {
15
+ const xr=await XR.create(engine); // prepare before the user gesture
16
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
17
+ enter.onclick=()=>{void xr.requestSession('immersive-vr',{
18
+ onFrame({delta,inputs}) {
19
+ cube.rotation.y+=delta;
20
+ // inputs expose native sources/gamepads plus targetRay and optional grip poses.
21
+ }
22
+ }).then(session=>session.addEventListener('end',()=>engine.start(),{once:true})).catch(engine.onError);};
23
+ // await xr.end() exits; xr.dispose() detaches and releases GPU resources.
24
+ }
25
+ engine.start();
26
+ ```
27
+
28
+ `layers` (an option of `XR.create` and `XR.attach`, and a property you can change at any time) is the render layer mask both eyes draw, on either route, as `RenderView.layers` is for a desktop view; unset draws every layer. A mesh whose mask (`setRenderLayers` from `margoengine/cameras/layers`) shares no bit with it is drawn in neither eye. This is how a first-person avatar hides its own head in the headset (`addVRMFirstPerson` from `margoengine/rigging/vrm-first-person`):
29
+
30
+ ```ts
31
+ import {Engine,box} from 'margoengine/core';
32
+ import {setRenderLayers} from 'margoengine/cameras/layers';
33
+ import {XR} from 'margoengine/xr';
34
+
35
+ const canvas=document.createElement('canvas');document.body.append(canvas);
36
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
37
+ engine.createMesh().setGeometry(box()).setPosition([0,1.5,-2]); // layer 0: seen in the headset
38
+ const hidden=engine.createMesh().setGeometry(box()).setPosition([0,1.6,0]);
39
+ setRenderLayers(hidden,1<<30); // on layer 30 only
40
+ if(await XR.isSupported('immersive-vr')) {
41
+ const xr=await XR.create(engine,{layers:~(1<<30)>>>0}); // every layer but 30
42
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
43
+ enter.onclick=()=>void xr.requestSession('immersive-vr').catch(engine.onError);
44
+ // xr.layers=undefined draws every layer again; a mask outside 0 to 0xffffffff throws a RangeError.
45
+ }
46
+ engine.start();
47
+ ```
48
+
49
+ `XRManager` is an alias for `XR`. `useXRSession(manager, mode, options)` is a framework-neutral request helper; prepare the manager before the user gesture and dispose it with the owning engine. It adds no React dependency.
50
+
51
+ `requestSession` supports `immersive-vr`, `immersive-ar`, and `inline`. Immersive sessions require native `XRGPUBinding`, require `webgpu`, and default to `local` space. On the WebGL2 compatibility layer the layer's `installXR()` takes the binding's place and the session runs on an `XRWebGLLayer` instead, without `webgpu` ([its README](../webgl2-compat/README.md#xr-margoenginewebgl2-compatxr)). Inline sessions use `viewer` space and track poses/inputs while the desktop canvas continues rendering. The [WebGPU XR draft](https://immersive-web.github.io/webxr-webgpu-binding/#feature-descriptor) prohibits WebGPU inline layers and mixing `XRWebGLLayer` with WebGPU sessions. Missing immersive bindings leave desktop rendering active. Reference-space and feature options are forwarded. AR clears transparently. An AR eye is opaque where the scene wrote depth, under post effects too, and content drawn after the main pass without depth (a `Line` with its default `depthWrite: false`) takes its own alpha as coverage; during an AR session the engine is marked premultiplied, as on a `TransparentCanvas`, so TAA and display transforms keep that alpha. Transparent meshes that write no depth take their brightest colour channel. Failed initialization closes the session and frees its layer. Engine disposal ends XR and frees buffers/device. Device loss ends the session; recreate the manager to recover.
52
+
53
+ Use HTTPS or localhost and call `requestSession` from a user gesture. `isSupported` checks APIs and session mode; adapter compatibility, permissions and feature support are established during creation/negotiation. Support follows browser capabilities without headset brand detection. Vision Pro VR support does not imply AR support. See the [binding draft](https://immersive-web.github.io/webxr-webgpu-binding/) and [WebKit announcement](https://webkit.org/blog/17640/webkit-features-for-safari-26-2/).
54
+
55
+ Immersive XR stops the engine RAF after entry and automatically restarts it on exit/disconnection. Update animation in XR `onFrame`; engine `onFrame` and React `useFrame` belong to the window RAF. Core plugin `onPreUpdate` runs once per immersive XR frame. Inline tracking leaves the window RAF active.
56
+
57
+ Core geometry/materials use the shared base shader, per-eye uniforms, native [0,1] projections, viewports and texture-array descriptors. Loader-owned PBR models are discovered through the optional triangle registry and use their PBR shader in both eyes. The canvas mirror and XR buffers use separate devices; each eye owns independent PBR resources and deformation kernels, sharing current CPU pose data without advancing playback twice. Late animation attachment/removal and extension replacements synchronize before drawing. Glass (`KHR_materials_transmission`) on a display-encoded layer adds its light to the light behind it in linear values, as on the canvas: when a drawn model has glass, the eye pass keeps its samples and gltf/pbr's snapshot hook resolves them before each glass surface (one extra resolve pass and one reopened eye pass per surface); scenes without glass draw one pass per eye as before. Caller-owned material extension texture views require recreation for the XR device and report an explicit error. That separate route draws no package passes or post effects; an engine from `createXREngine` draws them all (below).
58
+
59
+ `XRController` reuses target-ray/grip matrices, 32 button triplets (value/pressed/touched), 16 axes, and 25 hand joint matrices/tracking flags when granted. Controllers change on `inputsourceschange`. Frame state, input arrays and existing controller buffers retain identity; copy to retain a past frame. Browser-owned poses and GPU descriptors may allocate; this is not a whole-runtime zero-GC guarantee.
60
+
61
+ Run `npx vite --host 127.0.0.1` at the root and open `/examples/webxr-orbit/`. Peer ranges accept core 0.1.x and 1.x.
62
+
63
+ `npm test` checks negotiation, inputs, eye buffers, reference-space failure, device loss and disposal races. Root `npm run modern:test:xr:browser` checks actual stereo pixels, GPU validation and teardown using simulated sessions with real WebGPU. Physical Meta Quest and Apple Vision Pro sessions remain untested. No Apple hardware is required for these checks.
64
+
65
+ Build with root `npm run build:packages` or local `npm run build`. Apache-2.0 licensed.
66
+
67
+ ## AR hit testing
68
+
69
+ `HitTest` uses the WebXR Hit Test Module in an `immersive-ar` session started with the `'hit-test'` feature. Its ray
70
+ starts at the viewer (the centre of the view, for a placement reticle), at an input source's target ray, or at transient
71
+ inputs such as screen taps (`{profile: 'generic-touchscreen'}`). `hits.results(frame)` gives this frame's hits nearest
72
+ first, each with a column-major `matrix`, `position` and `orientation` in the session's reference space;
73
+ `hits.anchor(hit)` anchors one (WebXR Anchors Module, feature `'anchors'`). The source is cancelled with `cancel()` or
74
+ when the session ends. Not yet tried on an AR headset or phone; tested against the specification's interfaces.
75
+
76
+ ```ts
77
+ import { Engine, box } from 'margoengine/core';
78
+ import { XR, HitTest } from 'margoengine/xr';
79
+
80
+ const canvas = document.querySelector('canvas')!;
81
+ const engine = await Engine.create(canvas, { backend: 'webgpu' });
82
+ const reticle = engine.createMesh().setGeometry(box(0.2, 0.01, 0.2));
83
+ const xr = await XR.create(engine);
84
+ let hits: HitTest | undefined;
85
+ await xr.requestSession('immersive-ar', {
86
+ requiredFeatures: ['hit-test'],
87
+ onFrame({ frame }) {
88
+ const hit = hits?.first(frame);
89
+ reticle.visible = !!hit;
90
+ if (hit) reticle.setPosition(hit.position).setQuaternion(hit.orientation);
91
+ },
92
+ });
93
+ hits = await HitTest.create(xr, { from: 'viewer' });
94
+ ```
95
+
96
+ ## Body tracking
97
+
98
+ `BodyTracking` from `@margoengine/xr/body` reads the W3C WebXR Body Tracking Module: all 83 `XRBodyJoint` poses (hips,
99
+ spine, arms, hands, legs) in the session's reference space, every frame. Ask for the `'body-tracking'` feature as an
100
+ optional feature; few devices have it. Without it, `BodyTracking.create` does not throw: `available` is `false` and
101
+ `read` returns `null`. Pass `{ required: true }` for a MargoError `'unsupported'` instead. `read(frame)` also returns
102
+ `null` while tracking is lost, as the spec reports every joint or none. `humanoidPose(pose)` maps the joints to the
103
+ humanoid bone names of `@margoengine/rigging` (`hips`, `leftUpperArm`, `rightHand`, ...) for retargeting. Not yet tried on
104
+ a device; tested against the specification's interfaces.
105
+
106
+ ```ts
107
+ import { Engine } from 'margoengine/core';
108
+ import { XR } from 'margoengine/xr';
109
+ import { BodyTracking, humanoidPose } from 'margoengine/xr/body';
110
+
111
+ const canvas = document.querySelector('canvas')!;
112
+ const engine = await Engine.create(canvas, { backend: 'webgpu' });
113
+ const xr = await XR.create(engine);
114
+ let body: BodyTracking | undefined;
115
+ await xr.requestSession('immersive-vr', {
116
+ optionalFeatures: ['body-tracking'],
117
+ onFrame({ frame }) {
118
+ const pose = body?.read(frame);
119
+ if (pose) console.log('head', pose.position('head'), 'bones', humanoidPose(pose).size);
120
+ },
121
+ });
122
+ body = BodyTracking.create(xr);
123
+ if (!body.available) console.log('This device has no body tracking');
124
+ ```
125
+
126
+ ## Device runs
127
+
128
+ `runDeviceCheck` from `@margoengine/xr/device-check` runs one session and gives back what happened: frames, poses, views, frame times, inputs, granted features and failures. `examples/xr-device-check` is the page to open on a headset or phone; [docs/xr-device-runs](../../docs/xr-device-runs/README.md) keeps the records, and `npm run check:xr-runs` prints which routes a real device has proven. No real device has run yet: all four routes read NOT RUN. A run whose `navigator.xr` is a JavaScript stand-in has `native: false` and proves nothing.
129
+
130
+ ```ts
131
+ import { Engine } from 'margoengine/core';
132
+ import { XR } from 'margoengine/xr';
133
+ import { runDeviceCheck } from 'margoengine/xr/device-check';
134
+
135
+ const canvas = document.querySelector('canvas')!;
136
+ const engine = await Engine.create(canvas, { backend: 'webgpu' });
137
+ const xr = await XR.create(engine);
138
+ document.querySelector('button')!.onclick = async () => {
139
+ const run = await runDeviceCheck(xr, { mode: 'immersive-vr', seconds: 20 });
140
+ console.log(run.tracked, 'tracked frames at', run.frameMs.median, 'ms');
141
+ };
142
+ ```
143
+
144
+ ## Package passes and post effects in XR
145
+
146
+ Create the engine with `createXREngine` instead of `Engine.create` and XR draws through the engine's own frame graph on its own GPU device: lines, point clouds, terrain, shadows, sky and post effects appear in both eyes as they do on the desktop. `xr.route` is `'engine'`. An engine from `Engine.create` keeps the older `'separate'` route, which draws core meshes and glTF PBR models only.
147
+
148
+ ```ts
149
+ import {box} from 'margoengine/core';
150
+ import {XR,createXREngine} from 'margoengine/xr';
151
+
152
+ const canvas=document.createElement('canvas');document.body.append(canvas);
153
+ const engine=await createXREngine(canvas);
154
+ engine.createMesh().setGeometry(box()).setPosition([0,1.5,-2]);
155
+ const xr=await XR.create(engine);
156
+ console.log(xr.route); // 'engine'
157
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
158
+ enter.onclick=()=>void xr.requestSession('immersive-vr').catch(engine.onError);
159
+ engine.start();
160
+ ```
161
+
162
+ Each eye is a view of `engine.render({views})` drawn into a texture, then copied into the session's layer, with the scene's depth written to the layer's depth so the compositor can reproject. In AR the real world shows where the scene draws neither depth nor light. A stage gets the same route with `new Stage(await createXREngine(canvas))`. On the WebGL2 compatibility layer, call `installXR()` from `@margoengine/webgl2-compat/xr` first and `createXREngine` takes the same route there.
163
+
164
+ ## Controller and hand models
165
+
166
+ `XRModels` from `@margoengine/xr/models` draws every input source the session has: a controller at its grip, whose trigger swings, squeeze sinks and thumbstick leans as they are used and turn blue while pressed (on a gamepad with the `xr-standard` mapping; other mappings leave the parts at rest), and each tracked hand as a sphere per joint (sized by the joint radius WebXR reports) and a cylinder per bone. The models are core meshes and need no files. A source whose `skipRendering` is true (the system draws it) is hidden. The models are made in the scene the XR is in, whichever scene is active when a frame arrives, and are disposed with that scene.
167
+
168
+ ```ts
169
+ import {Engine} from 'margoengine/core';
170
+ import {XR} from 'margoengine/xr';
171
+ import {XRModels} from 'margoengine/xr/models';
172
+
173
+ const canvas=document.createElement('canvas');document.body.append(canvas);
174
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
175
+ const xr=await XR.create(engine);
176
+ const models=XRModels.attach(xr,engine,{handColor:'#d8b49a'});
177
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
178
+ enter.onclick=()=>void xr.requestSession('immersive-vr',{optionalFeatures:['hand-tracking']}).catch(engine.onError);
179
+ // models.dispose() removes the meshes.
180
+ ```
181
+
182
+ For a device's own model, serve the [WebXR input profile assets](https://github.com/immersive-web/webxr-input-profiles) and call `fetchProfile(source, baseUrl)`: it picks the most specific listed profile and gives its layout and model URL. `componentStates(layout, controller)` and `responseWeight(response, state)` give each node's weight for the layout's visual responses each frame. `xr.onFrame(callback)` runs a function every XR frame, before the session's own `onFrame`.
183
+
184
+ ## AR planes, depth and light
185
+
186
+ `@margoengine/xr/ar` reads what an AR device knows about the room, each in the session's reference space. Ask for the features when the session starts; `init` passes module options such as `depthSensing` through to `navigator.xr.requestSession`.
187
+
188
+ - `ARPlanes.create(xr, { onAdd, onChange, onRemove, show })` follows `frame.detectedPlanes`: each plane's pose (its y axis is the normal), outline, orientation and label, and with `show` a flat mesh per plane.
189
+ - `ARDepth.create(xr)` reads CPU depth: `depthAt(frame, view, x, y)` in metres at a point of the view (0 to 1 from the top left) and `pointAt(...)` the real-world point there.
190
+ - `await ARLight.create(xr, { lighting: engine.lighting })` turns the room's light estimate into `estimate` (spherical harmonics in `@margoengine/math` SH3 order, the brightest light's direction and colour) and points the engine's sun at the room's brightest light, with the ambient set to the room's average light.
191
+
192
+ ```ts
193
+ import {Engine,PbrMaterial} from 'margoengine/core';
194
+ import {XR} from 'margoengine/xr';
195
+ import {ARDepth,ARLight,ARPlanes,DEPTH_SENSING} from 'margoengine/xr/ar';
196
+
197
+ const canvas=document.createElement('canvas');document.body.append(canvas);
198
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
199
+ const xr=await XR.create(engine);
200
+ const enter=document.createElement('button');enter.textContent='Enter AR';document.body.append(enter);
201
+ enter.onclick=async()=>{
202
+ await xr.requestSession('immersive-ar',{optionalFeatures:['plane-detection','depth-sensing','light-estimation'],init:{depthSensing:DEPTH_SENSING}});
203
+ const planes=ARPlanes.create(xr,{show:{engine,material:new PbrMaterial({color:'#4f9be8'})},onAdd:(plane)=>console.log('plane',plane.label)});
204
+ const light=await ARLight.create(xr,{lighting:engine.lighting});
205
+ const depth=ARDepth.create(xr);
206
+ xr.onFrame(({frame,viewer})=>{const view=viewer?.views[0];if(view)console.log(depth.depthAt(frame,view,0.5,0.5));});
207
+ // planes.dispose() and light.dispose() stop them.
208
+ };
209
+ ```
210
+
211
+ Each `create` throws a coded error naming the feature to ask for when the session lacks it.
212
+
213
+ ## AR occlusion by real depth
214
+
215
+ `@margoengine/xr/occlusion` hides the scene where the real world is in front of it, so a virtual box behind a real chair disappears behind the chair. It reads the session's depth sensing each frame and runs one full-screen pass per eye after the scene draws, on both XR routes and on the WebGL2 layer.
216
+
217
+ - CPU-optimized depth (`DEPTH_SENSING`, `float32`, `unsigned-short` or `luminance-alpha`) is uploaded to a small texture each frame; GPU-optimized depth (`usagePreference: ['gpu-optimized']`, `float32` or `unsigned-short`) is read where the browser leaves it, with no copy.
218
+ - Each drawn sample of the eye's depth becomes a point, carried into the depth sensor's own view (its pose and projection when they differ from the eye's), and compared with the real depth there. Pixels with no depth (0, invalid) hide nothing.
219
+ - `feather` (metres, default `0.05`) fades a surface from shown to hidden around equal depth, which hides the sensor's noise along the contact line; `0` gives a hard edge. `enabled = false` skips the pass.
220
+ - Content that writes no depth has nothing to compare and is kept: a `Line` needs `depthWrite: true` to be hidden. A pixel with colour but no depth sample of its own (the antialiased fringe of a line or an edge) takes its neighbours' verdict.
221
+
222
+ ```ts
223
+ import {Engine,PbrMaterial,box} from 'margoengine/core';
224
+ import {XR} from 'margoengine/xr';
225
+ import {DEPTH_SENSING} from 'margoengine/xr/ar';
226
+ import {AROcclusion} from 'margoengine/xr/occlusion';
227
+
228
+ const canvas=document.createElement('canvas');document.body.append(canvas);
229
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
230
+ engine.createMesh().setGeometry(box(0.3,0.3,0.3)).setMaterial(new PbrMaterial({color:'#e8a04f'})).setPosition([0,0,-1.5]);
231
+ const xr=await XR.create(engine);
232
+ const enter=document.createElement('button');enter.textContent='Enter AR';document.body.append(enter);
233
+ enter.onclick=async()=>{
234
+ await xr.requestSession('immersive-ar',{requiredFeatures:['depth-sensing'],init:{depthSensing:DEPTH_SENSING}});
235
+ const occlusion=AROcclusion.create(xr,{feather:0.05});
236
+ // occlusion.enabled=false shows the scene over everything again; occlusion.dispose() stops it.
237
+ };
238
+ ```
239
+
240
+ `AROcclusion.create` throws `state` without a session and `unsupported` when the session has no depth sensing, or has GPU depth in `luminance-alpha`, which WebGPU cannot read. Tested with stand-in sessions on real GPUs (`npm run test:gpu:occlusion`); not yet run on an AR device.
241
+
242
+ ## AR reflections from the room's light
243
+
244
+ `@margoengine/xr/reflection` turns the room's light estimate into a cube texture, which an `Environment` from `@margoengine/environment` filters into the scene's specular reflections and diffuse harmonics, so a shiny virtual object reflects the room it sits in. Start the session with `light-estimation`.
245
+
246
+ - `ARReflection.create(xr, { device })` follows the browser's light probe. Where the WebGPU binding gives the probe's reflection cube map (`getReflectionCubeMap`, the `reflectionchange` event of the WebXR Lighting Estimation API), that texture is copied into the cube; everywhere else the cube is painted from the probe's nine spherical harmonics, a soft room of bands 0 to 2 (Ramamoorthi and Hanrahan, 2001).
247
+ - Options and defaults: `size` 32 (power of two, 8 to 256; the harmonics path), `reflectionFormat` `'rgba16f'`, `interval` 500 ms between harmonics repaints, `forceSH` false, `light` (an `ARLight` to share; one is made otherwise).
248
+ - `await reflection.ready` gives the cube texture after the first estimate; make the `Environment` from it and `reflection.attach(environment)` so it is refreshed after each repaint.
249
+
250
+ ```ts
251
+ import {Engine} from 'margoengine/core';
252
+ import {Environment} from 'margoengine/environment';
253
+ import {XR} from 'margoengine/xr';
254
+ import {ARReflection} from 'margoengine/xr/reflection';
255
+
256
+ const canvas=document.createElement('canvas');document.body.append(canvas);
257
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
258
+ const xr=await XR.create(engine);
259
+ const enter=document.createElement('button');enter.textContent='Enter AR';document.body.append(enter);
260
+ enter.onclick=async()=>{
261
+ await xr.requestSession('immersive-ar',{requiredFeatures:['light-estimation']});
262
+ const reflection=await ARReflection.create(xr,{device:engine.gpu!,size:32});
263
+ const cube=await reflection.ready;
264
+ const environment=await Environment.create(engine,{texture:cube},{size:cube.width});
265
+ engine.use(environment);
266
+ reflection.attach(environment);
267
+ // reflection.dispose() stops it.
268
+ };
269
+ ```
270
+
271
+ Tested with stand-in sessions on real GPUs (`npm run test:gpu:reflection`); not yet run on an AR device.
272
+
273
+ ## AR where WebXR is absent: Quick Look and Scene Viewer
274
+
275
+ `@margoengine/xr/launch` opens a model in the phone's own AR viewer when the browser has no `immersive-ar` session. iOS Safari has none, so a USDZ opens in AR Quick Look through an anchor with `rel="ar"` and an image inside; Android Chrome without WebXR opens Google's Scene Viewer through an intent URL. The USDZ comes from `exportUSDZ` (`@margoengine/exporters/usdz`), the GLB from `exportGLB`.
276
+
277
+ - `chooseARRoute({webxr})` returns `'webxr'` (start an `XR` session instead), `'quick-look'` (the browser answers `relList.supports('ar')`), `'scene-viewer'` (an Android user agent) or `'none'`. Every field of the platform argument defaults to the browser's own value.
278
+ - `launchAR({usdz, glb, ...})` does the opening and returns the route. Call it from a tap. `usdz` is a URL or the bytes (made into a blob URL for a minute); `glb` must be one Scene Viewer can fetch itself (no blob). `fallback(route)` runs where neither viewer exists; a route that needs a model you left out throws code `state`.
279
+ - `quickLookURL(url, {allowsContentScaling, canonicalWebPageURL})` and `sceneViewerURL(url, {mode, title, link, sound, resizable, verticalPlacement, fallbackUrl})` build the two links alone. URLs are checked before they reach a link or intent: each is resolved against `document.baseURI` and only `https:` and `http:` pass (`blob:` too for the USDZ), so `javascript:`, `data:`, `vbscript:` and `file:` throw code `unsupported`; every value is percent-encoded, the `#Intent;...;end;` part is a fixed template, and `mode` must be `ar_preferred`, `3d_preferred` or `3d_only` (else `RangeError`). Defaults: scaling on, `mode` `'ar_preferred'`, `resizable` true, vertical placement off, fallback the current page, `title` cut to 60 characters.
280
+
281
+ ```ts
282
+ import {chooseARRoute, launchAR, quickLookURL, sceneViewerURL} from 'margoengine/xr/launch';
283
+
284
+ console.log(chooseARRoute({webxr: false, quickLook: true}));
285
+ console.log(quickLookURL('https://example.com/chair.usdz', {allowsContentScaling: false}));
286
+ console.log(sceneViewerURL('https://example.com/chair.glb', {title: 'Chair', fallbackUrl: 'https://example.com/chair'}));
287
+ const button = document.createElement('button');
288
+ button.textContent = 'View in your room';
289
+ button.onclick = () => launchAR({usdz: 'https://example.com/chair.usdz', glb: 'https://example.com/chair.glb', fallback: () => alert('AR is not available here')});
290
+ document.body.append(button);
291
+ ```
292
+
293
+ Tested with stand-in pages and links in Node; not yet run on an iPhone or an Android phone.
294
+
295
+ ## Layers, haptics, video and locomotion
296
+
297
+ `@margoengine/xr/layers` adds WebXR composition layers, controller vibration and teleport movement. Layers are drawn by the headset's compositor at their own resolution, so text and video stay sharp. Ask for `optionalFeatures: ['layers']`.
298
+
299
+ - `XRLayers.attach(xr)` then `quad`, `cylinder`, `equirect`, `cube` or `video(element)`: each takes `pixels`, a placement and `content` (an image, a `{left, right}` pair, six cube faces, or a function that draws into each eye's texture). Quads, cylinders and video sit above the scene, equirect and cube skies below it; `isStatic: true` draws once until `redraw()` or the compositor asks. A video or `VideoFrame` as `content` in a browser that takes no video as a copy source (Firefox) is drawn on a canvas each frame and copied from there.
300
+ - Every layer also takes `quality` (`'default'`, `'text-optimized'` or `'graphics-optimized'`, what the compositor favours when it resamples), `blendTextureSourceAlpha` (default true), `chromaticAberrationCorrection` and `mipLevels` (default 1); each is left to the browser when you do not pass it. Use `quality: 'text-optimized'` for menus and captions.
301
+ - `pulse(controller, intensity, milliseconds)` vibrates a controller and resolves false when it has no actuator.
302
+ - `teleportArc(origin, direction, options)` samples the parabola a teleport pointer draws and where it lands; `Locomotion.attach(xr)` moves the player there with `teleport(point, yaw)` and turns with `turn(yaw)`, by offsetting the reference space.
303
+
304
+ ```ts
305
+ import {Engine} from 'margoengine/core';
306
+ import {XR} from 'margoengine/xr';
307
+ import {Locomotion,XRLayers,pulse,teleportArc} from 'margoengine/xr/layers';
308
+
309
+ const canvas=document.createElement('canvas');document.body.append(canvas);
310
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
311
+ const xr=await XR.create(engine);
312
+ const menu=new OffscreenCanvas(512,256);const pen=menu.getContext('2d')!;pen.fillStyle='#223';pen.fillRect(0,0,512,256);pen.fillStyle='#fff';pen.font='48px sans-serif';pen.fillText('Hello',40,140);
313
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
314
+ enter.onclick=async()=>{
315
+ await xr.requestSession('immersive-vr',{optionalFeatures:['layers']});
316
+ const layers=XRLayers.attach(xr);
317
+ layers.quad({pixels:[512,256],size:[1,0.5],position:[0,1.5,-1.5],content:menu,isStatic:true});
318
+ const move=Locomotion.attach(xr);
319
+ xr.onFrame(({inputs})=>{
320
+ const c=xr.controllers[0],ray=c?.targetRay;if(!ray)return;
321
+ const p=ray.transform.position,m=c.targetRayMatrix;
322
+ const arc=teleportArc([p.x,p.y,p.z],[-m[8],-m[9],-m[10]]);
323
+ if(arc.hit&&c.buttons[1]){move.teleport(arc.hit);void pulse(c,0.6,40);}
324
+ });
325
+ };
326
+ ```
327
+
328
+ Without the browser's layer support `XRLayers.attach` and each layer throw a coded error that names the feature to ask for.
329
+
330
+ ## Session state: blend mode, frame rate, visibility and play area
331
+
332
+ `@margoengine/xr/session` reads and follows what the WebXR session says about the display and the room, with no rendering of its own.
333
+
334
+ - `XRSessionState.attach(xr, { signal })` gives `environmentBlendMode` (`'opaque'`, `'additive'` or `'alpha-blend'`), `interactionMode`, `visibility` (`'visible'`, `'visible-blurred'` while a system menu is up, `'hidden'`) with `onVisibilityChange(callback)`, and `frameRate`.
335
+ - `supportedFrameRates` lists the rates the device accepts and `await setFrameRate(rate)` asks for one; a rate not in the list throws a `RangeError`, and a browser without frame rate control rejects with an `unsupported` error.
336
+ - `bounds` is the play area of a `referenceSpace: 'bounded-floor'` session as x and z metres per corner (null otherwise), and `onReset(callback)` runs when the space resets, so you can read `bounds` again.
337
+
338
+ ```ts
339
+ import {Engine} from 'margoengine/core';
340
+ import {XR} from 'margoengine/xr';
341
+ import {XRSessionState} from 'margoengine/xr/session';
342
+
343
+ const canvas=document.createElement('canvas');document.body.append(canvas);
344
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
345
+ const xr=await XR.create(engine);
346
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
347
+ enter.onclick=async()=>{
348
+ await xr.requestSession('immersive-vr',{referenceSpace:'bounded-floor',optionalFeatures:['bounded-floor']});
349
+ const state=XRSessionState.attach(xr);
350
+ const fastest=state.supportedFrameRates.at(-1);
351
+ if(fastest&&fastest!==state.frameRate)await state.setFrameRate(fastest);
352
+ state.onVisibilityChange((visibility)=>console.log('session is',visibility));
353
+ console.log(state.environmentBlendMode,state.frameRate,state.bounds);
354
+ // state.dispose() stops it.
355
+ };
356
+ ```
357
+
358
+ Tested with stand-in sessions; not yet run on a headset.
359
+
360
+ ## Smooth movement, skinned hands, AR extras and performance
361
+
362
+ Four more entries are separate imports, so a page that does not use them does not load them. Each attaches to a running session and stops when the session ends or its `AbortSignal` aborts.
363
+
364
+ - `@margoengine/xr/locomotion` adds `SmoothLocomotion.attach(xr, options)`: thumbstick walking and smooth turning next to the teleport and snap turn of `Locomotion`, with a vignette that fades in while you move (`vignette: false` turns it off; `comfort` reads its strength). Options and defaults: `speed` 2 (metres per second), `turnSpeed` `Math.PI / 2` (radians per second), `moveHand` `'left'`, `turnHand` `'right'`, `direction` `'head'`, `deadZone` 0.15, `axes` `[2, 3]`, `fieldOfView` `Math.PI / 2`, `feather` 0.2 and `fade` 0.15. Set `enabled = false` to pause it.
365
+ - `@margoengine/xr/hands` adds `SkinnedHands.create(xr, {left, right}, options)`, which drives your own skinned glTF hand models from the 25 tracked joints (`HAND_JOINT_NAMES` lists them). It keeps each asset's inverse binds and weights and loads `@margoengine/animation` when you call it. `jointNames` maps WebXR joint names to your node names when they differ from the generic-hand profile names. Pass at least one model, and not the same model for both hands.
366
+ - `@margoengine/xr/ar-extra` adds `DOMOverlay` (with `domOverlaySessionOptions(root)` for the session request), `ImageTracking` (with `imageTrackingSessionOptions(images)`), `MarkerTracking` for QR codes the browser finds itself (with `markerTrackingSessionOptions()`), `MeshDetection` for the room's triangle meshes, which can draw them as Margo meshes through its `show` option, and `PersistentAnchors`, whose handles belong to the browser and the origin until you delete them. Each needs its WebXR feature in the session and rejects with an `unsupported` error naming what is missing.
367
+ - `@margoengine/xr/performance` adds `performanceSessionOptions({framebufferScale, cameraAccess})` for the session request and `XRPerformance.attach(xr, {fixedFoveation, signal})` for a live foveation setting (0 to 1) that is restored when the session ends or the signal aborts. Camera images are a borrowed WebGL texture, valid only inside their XR frame; native WebGPU raw camera access rejects with the capability reason.
368
+
369
+ ### Thumbstick walking and turning (`@margoengine/xr/locomotion`)
370
+
371
+ ```ts
372
+ import {Engine} from 'margoengine/core';
373
+ import {XR} from 'margoengine/xr';
374
+ import {SmoothLocomotion} from 'margoengine/xr/locomotion';
375
+ import {teleportArc} from 'margoengine/xr/layers';
376
+
377
+ const canvas=document.createElement('canvas');document.body.append(canvas);
378
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
379
+ const xr=await XR.create(engine);
380
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
381
+ enter.onclick=async()=>{
382
+ await xr.requestSession('immersive-vr'); // attach only once the session is running
383
+ const walk=SmoothLocomotion.attach(xr,{speed:1.5,turnSpeed:Math.PI/3}); // left stick walks, right stick turns
384
+ xr.onFrame(()=>{
385
+ const c=xr.controllers[0],ray=c?.targetRay;if(!ray)return;
386
+ const p=ray.transform.position,m=c.targetRayMatrix;
387
+ const arc=teleportArc([p.x,p.y,p.z],[-m[8],-m[9],-m[10]]);
388
+ if(arc.hit&&c.buttons[1])walk.teleport(arc.hit); // teleport still works beside smooth movement
389
+ if(c.buttons[4])walk.turn(Math.PI/4); // and a 45 degree snap turn
390
+ });
391
+ };
392
+ ```
393
+
394
+ - **When to attach.** After `await xr.requestSession(...)`: with no session running `attach` throws a MargoError
395
+ `state`. The controller belongs to that session; when the session ends it disposes itself, so attach a new one in
396
+ the next session. `teleport` or `turn` on a controller from an earlier session throws `state`.
397
+ - **Sticks.** `moveHand` (default `'left'`) walks and `turnHand` (default `'right'`) turns, reading the gamepad's
398
+ `axes` (default `[2, 3]`, the xr-standard thumbstick; `[0, 1]` for a touchpad). Inside the `deadZone` (default 0.15
399
+ of full travel, radial for walking) nothing happens; past it the speed rises from 0 to full at the stick's edge.
400
+ `speed` is metres per second at full tilt (default 2), `turnSpeed` radians per second (default `Math.PI / 2`).
401
+ `direction: 'head'` (default) walks where you look, flattened to the floor; `'controller'` walks where the moving
402
+ hand points. Movement stays on the floor height of the last teleport (0 until then). A frame gap is capped at
403
+ 0.1 s, so a hitch does not throw you across the room.
404
+ - **Teleport and snap turn.** `teleport(point, yaw)` and `turn(yaw)` are those of `Locomotion` and work at any time;
405
+ `enabled = false` pauses the sticks only.
406
+ - **Comfort vignette.** While you move or turn, both eyes get a soft dark ring that narrows the view to
407
+ `fieldOfView` (default `Math.PI / 2`) at full stick, with a `feather` edge (default 0.2 radians), fading in and out
408
+ over `fade` seconds (default 0.15). It is drawn through `xr.onEye` into each eye's view, so both eyes see it. `comfort` reads its current strength, 0 to 1; `vignette: false` turns it off.
409
+ - **Errors.** A negative or non-finite speed or time, a `deadZone` outside 0 to just under 1, the same axis twice or
410
+ an XR without `onEye` and `onFrame` throws (`RangeError` or `TypeError`) before anything is attached.
411
+ - **Disposal.** `dispose()`, `using`, the session's end or the `signal` option's abort removes the frame and eye
412
+ hooks and the vignette's GPU buffers; it is idempotent, and the reference-space offset reached stays.
413
+
414
+ Tested with stand-in sessions (`tests/locomotion.test.js`, and `tests/locomotion.browser.mjs` in a real browser);
415
+ not yet run on a headset.
416
+
417
+ ### Skinned hand models (`@margoengine/xr/hands`)
418
+
419
+ ```ts
420
+ import {Engine} from 'margoengine/core';
421
+ import {loadGLTF} from 'margoengine/gltf/pbr';
422
+ import {XR} from 'margoengine/xr';
423
+ import {SkinnedHands} from 'margoengine/xr/hands';
424
+
425
+ const canvas=document.createElement('canvas');document.body.append(canvas);
426
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
427
+ const xr=await XR.create(engine);
428
+ // Your own copies of the WebXR input profiles' generic-hand models (left.glb, right.glb), or any rigged hands.
429
+ const [left,right]=await Promise.all([loadGLTF(engine,'/hands/left.glb'),loadGLTF(engine,'/hands/right.glb')]);
430
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
431
+ enter.onclick=async()=>{
432
+ await xr.requestSession('immersive-vr',{optionalFeatures:['hand-tracking']});
433
+ using hands=await SkinnedHands.create(xr,{left,right}); // models stay yours; dispose puts them back
434
+ await new Promise((done)=>xr.session!.addEventListener('end',done,{once:true}));
435
+ };
436
+ ```
437
+
438
+ - **Models.** Pass at least one of `left` and `right`, already loaded, and two different models: one asset cannot be
439
+ both hands (a mirrored hand is a separate asset). Each needs one skin holding all 25 WebXR joints
440
+ (`HAND_JOINT_NAMES`), each name on exactly one node; the asset's inverse bind matrices and weights are used as
441
+ authored. Nothing is downloaded for you: load the profile assets (`generic-hand/left.glb` and `right.glb` of the
442
+ WebXR input profiles) or your own hands from wherever you serve them.
443
+ - **`jointNames`** maps a WebXR joint name to your node name, such as `{wrist: 'Hand_L', 'thumb-tip': 'Thumb_04_L'}`,
444
+ for rigs exported with other names. A joint missing from the map keeps its WebXR name.
445
+ - **Session.** Ask for `'hand-tracking'` in the session request (`optionalFeatures`, or `requiredFeatures` to refuse
446
+ a session without it). Each hand shows only while its input source is a tracked hand with all 25 joints posed this
447
+ frame and the browser does not ask to skip drawing it; holding a controller hides it. On the session's end the
448
+ hands hide; `SkinnedHands` keeps listening and works in the next session too.
449
+ - **Loading.** `create` loads `@margoengine/animation` for skinning the first time, so a page without hands never
450
+ downloads it. It is async and takes `signal`.
451
+ - **Errors.** No model, the same model twice, a missing or repeated joint name, or a joint outside the skin throws a
452
+ `TypeError` that says how to fix the asset; a disposed model throws code `disposed`. Nothing stays attached after a
453
+ refusal.
454
+ - **Ownership and cleanup.** The models are borrowed. `dispose()` (or `using`, the `signal`'s abort, or disposing the
455
+ scene) stops tracking, removes the skinning player and restores every node's local transform and each root's
456
+ visibility as they were before `create`. Disposing the models themselves stays your job.
457
+
458
+ ### DOM overlay, image targets, room meshes and saved anchors (`@margoengine/xr/ar-extra`)
459
+
460
+ ```ts
461
+ import {Engine,PbrMaterial} from 'margoengine/core';
462
+ import {XR,HitTest} from 'margoengine/xr';
463
+ import {DOMOverlay,ImageTracking,MeshDetection,PersistentAnchors,domOverlaySessionOptions,imageTrackingSessionOptions,type XRPersistentAnchor} from 'margoengine/xr/ar-extra';
464
+
465
+ const canvas=document.createElement('canvas');document.body.append(canvas);
466
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
467
+ const xr=await XR.create(engine);
468
+ const hud=document.createElement('div');hud.textContent='Tap to place';document.body.append(hud);
469
+ const enter=document.createElement('button');enter.textContent='Enter AR';document.body.append(enter);
470
+ enter.onclick=async()=>{
471
+ const poster=await createImageBitmap(await (await fetch('/targets/poster.jpg')).blob()); // printed 30 cm wide
472
+ let options=domOverlaySessionOptions(hud,{requiredFeatures:['hit-test','anchors','mesh-detection']});
473
+ options=imageTrackingSessionOptions([{image:poster,widthInMeters:0.3}],{},options);
474
+ await xr.requestSession('immersive-ar',options); // attach the extras once the session runs
475
+ const overlay=DOMOverlay.attach(xr,hud); // taps on the HUD do not also select in the world
476
+ const images=ImageTracking.attach(xr,{onUpdate:(seen)=>{hud.textContent=seen.length?`poster ${seen[0].trackingState}`:'Tap to place';}});
477
+ console.log(overlay.type,await images.trackability()); // e.g. 'screen' ['trackable']
478
+ const room=await MeshDetection.create(xr,{show:{engine,material:new PbrMaterial({color:'#88aacc'})},onAdd:(m)=>console.log('mesh',m.label)});
479
+ const anchors=PersistentAnchors.attach(xr);
480
+ for(const handle of anchors.handles)await anchors.restore(handle); // last visit's anchors
481
+ const hits=await HitTest.create(xr,{from:'viewer'});
482
+ let tapped=false;xr.session!.addEventListener('select',()=>{tapped=true;});
483
+ xr.onFrame(({frame})=>{
484
+ const hit=tapped?hits.first(frame):null;tapped=false;
485
+ if(hit)hits.anchor(hit).then((anchor)=>anchors.save(anchor as XRPersistentAnchor)).then((handle)=>console.log('saved',handle));
486
+ });
487
+ // room.dispose(), images.dispose(), overlay.dispose() and anchors.dispose() stop them early.
488
+ };
489
+ ```
490
+
491
+ - **Session request.** Each helper returns a new options object for `xr.requestSession` and keeps what you pass as
492
+ its last argument, so they chain. `domOverlaySessionOptions(root)` adds the `'dom-overlay'` feature and
493
+ `init.domOverlay.root`; `imageTrackingSessionOptions(images, {legacy})` adds `init.trackedImages` and the
494
+ `'marker-tracking'` feature of the WebXR image tracking draft, or with `legacy: true` the `'image-tracking'` feature
495
+ Chrome ships behind its flag today. A missing or non-element root throws `TypeError`; an empty target list
496
+ `TypeError`; a target without a bitmap or with a `widthInMeters` that is not a positive finite number `RangeError`.
497
+ Targets are copied, so changing your array afterwards changes nothing; the bitmaps stay yours.
498
+ - **Attach after the session starts.** Each tracker binds to the session running at the time and ends itself when
499
+ that session ends or its `signal` aborts. With no session, `attach` and `create` throw MargoError `'state'`; a
500
+ session without the feature throws `'unsupported'` naming the feature to request.
501
+ - **DOM overlay.** The browser shows your `root` over the camera view. `DOMOverlay` cancels `beforexrselect` on it,
502
+ so a tap on a button there does not also fire a world `select`; `preventWorldSelect: false` lets both happen.
503
+ `type` is the browser's `domOverlayState.type` (`'screen'`, `'floating'` or `'head-locked'`), or `null`. The element
504
+ stays yours: `dispose` only removes the listeners.
505
+ - **Image targets.** Each frame, `images` holds a copy of what the browser reports, keyed by the target's index in
506
+ the list you passed: `trackingState` (`'tracked'`, or `'emulated'` while the pose is guessed from the last
507
+ sighting), `measuredWidthInMeters` and a column-major `matrix` in `xr.referenceSpace`, or `null` while no pose is
508
+ known. Untracked targets are absent. Copies stay valid after the frame. `onUpdate` gets the same list once a frame.
509
+ `trackability(signal)` resolves `'trackable'` or `'untrackable'` per target, through the draft's
510
+ `getImageTrackability` or Chrome's `getTrackedImageScores`; `dispose`, the session's end or `signal` rejects it.
511
+ - **Room meshes.** `meshes` maps each browser mesh to a frozen copy of its `vertices`, `indices`, `label` (the
512
+ semantic label, or `''`), `lastChangedTime` and current `matrix`. Vertices are copied again only when the browser
513
+ changes the mesh or its label, which is when `onChange` fires; a pose change alone moves the drawn mesh without a
514
+ callback. `onRemove` fires when the browser drops a mesh and for every mesh still held at `dispose`. With `show`,
515
+ each mesh is drawn in `show.scene` (default `engine.scene`) with your material (default a grey `PbrMaterial`) and
516
+ normals from `@margoengine/geometry`, which `create` loads only when `show` is set; the drawn meshes are disposed
517
+ with the tracker, or with the scene.
518
+ - **Saved anchors.** `save(anchor)` asks the browser for a persistent handle; `restore(handle)` tracks it again in a
519
+ later session; `handles` lists this origin's saved handles; `delete(handle)` forgets one. Handles belong to the
520
+ browser and the origin, not to the tracker: `dispose` and the session's end keep them, and only `delete` removes
521
+ one. Two `save` calls for one anchor, or two `restore` calls for one handle, share one browser request. If every
522
+ caller aborts before the browser answers, the result is thrown away: a handle made by that save is deleted, and an
523
+ anchor restored by that restore stops tracking, while the saved handle stays. A tracker from an ended session
524
+ throws `'state'`; after `dispose`, `'disposed'`.
525
+
526
+ Tested with stand-in sessions (`tests/ar-extra.test.js`, and `tests/ar-extra.browser.mjs` in a real browser); not
527
+ yet run on an AR phone or headset.
528
+
529
+ #### Markers the browser finds (the marker tracking module)
530
+
531
+ The WebXR marker tracking module finds QR codes during the session by itself, with no targets given up front.
532
+ `markerTrackingSessionOptions()` requests it; `MarkerTracking` copies what it finds each frame.
533
+
534
+ ```ts
535
+ import {XR} from 'margoengine/xr';
536
+ import {MarkerTracking, markerTrackingSessionOptions} from 'margoengine/xr/ar-extra';
537
+ declare const xr: XR;
538
+ declare const hud: HTMLElement;
539
+ const start = async () => { // from a button's click handler
540
+ await xr.requestSession('immersive-ar', markerTrackingSessionOptions({optionalFeatures: ['hit-test']}));
541
+ const markers = MarkerTracking.attach(xr, {
542
+ onUpdate: (found) => {
543
+ const code = found.find((m) => m.payload !== null);
544
+ hud.textContent = code ? `${code.payload} (${code.extent?.widthInMeters ?? '?'} m)` : 'Point at a QR code';
545
+ },
546
+ });
547
+ document.querySelector('#save-power')?.addEventListener('click', () => {
548
+ if (markers.active) markers.pause();
549
+ else markers.resume();
550
+ });
551
+ };
552
+ ```
553
+
554
+ - **Observations.** `markers` is a frozen list, in the browser's order and replaced every frame, of copies:
555
+ `trackingState` (`'tracked'`, or `'emulated'` while the browser holds a marker it cannot see), `payload` (the
556
+ code's text, or `null` until decoded), `extent` (`widthInMeters` and `heightInMeters`, or `null`) and a
557
+ column-major `matrix` of the marker centre in `xr.referenceSpace`, its x-y plane on the marker face, or `null`.
558
+ `id` stays the same while the browser keeps the marker, so use it as a map key; a marker lost or paused may come back
559
+ under a new one, and `payload` is the code's text, not its identity.
560
+ - **Pause and resume.** `pause()` and `resume()` ask the session's `pauseMarkerTracking` and
561
+ `resumeMarkerTracking` to save power. The draft takes those calls only inside an animation frame, so the tracker
562
+ makes them as the next frame begins and a button may call them; `active` reads `markerTrackingActive`, or the
563
+ request still waiting. A session without them throws `'unsupported'`; after `dispose`, `'disposed'`. `dispose`
564
+ leaves tracking as it is.
565
+ - **Which module.** Both modules can be granted under the name `'marker-tracking'`. `trackingModule(xr.session)`
566
+ says `'markers'` (the session has `markerTrackingActive` or `pauseMarkerTracking`), `'images'` (it reports image
567
+ trackability, or was granted `'image-tracking'`) or `null`. `ImageTracking` refuses a marker session and
568
+ `MarkerTracking` an image one, each naming the tracker to use.
569
+
570
+ Sources: M. Al Kalbani and A. Cooper (editors), *WebXR Marker Tracking Module, Level 1*, W3C Immersive Web Community
571
+ Group draft (https://github.com/immersive-web/marker-tracking, `index.bs` and `explainer.md`), for every name above;
572
+ ISO/IEC 18004:2015, *QR Code bar code symbology specification*, the one marker symbology the draft reports. Tested
573
+ with stand-in sessions only; no browser ships the module yet.
574
+
575
+ ### Render scale, foveation and camera images (`@margoengine/xr/performance`)
576
+
577
+ ```ts
578
+ import {Engine} from 'margoengine/core';
579
+ import {XR} from 'margoengine/xr';
580
+ import {XRPerformance,performanceSessionOptions} from 'margoengine/xr/performance';
581
+
582
+ const canvas=document.createElement('canvas');document.body.append(canvas);
583
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
584
+ const xr=await XR.create(engine);
585
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
586
+ enter.onclick=async()=>{
587
+ await xr.requestSession('immersive-vr',performanceSessionOptions({framebufferScale:0.8})); // 80% of the headset's size
588
+ const perf=XRPerformance.attach(xr,{fixedFoveation:0.5}); // throws 'unsupported' where the layer has no foveation
589
+ console.log(perf.fixedFoveation); // what the runtime actually set, such as 0.5 or a nearby step
590
+ // perf.fixedFoveation=1 when frames run late; perf.dispose() puts the browser's value back.
591
+ };
592
+ ```
593
+
594
+ - **Render scale.** `framebufferScale` sizes the projection layer against the runtime's recommendation (1); below 1
595
+ draws fewer pixels, the first thing to lower on a weak device. It is fixed for the session, so it goes in the
596
+ request: `performanceSessionOptions({framebufferScale})` or `xr.requestSession(mode, {framebufferScale})`, which
597
+ passes it as the layer's `scaleFactor`. Unset keeps the browser's size, or on the WebGL2 compatibility route
598
+ `installXR`'s `framebufferScale`; a session's own value wins over `installXR`'s for that session. A value that is
599
+ not finite and positive (checked as float32) throws `RangeError`.
600
+ - **Camera access.** `cameraAccess: 'required'` puts `'camera-access'` in `requiredFeatures` (and takes it out of
601
+ `optionalFeatures`), so the session fails without camera permission; `'optional'` asks for it without failing.
602
+ Default `false` adds nothing. Your other features and options are copied, never changed.
603
+ - **Foveation.** `XRPerformance.attach(xr, {fixedFoveation, signal})` binds to the running session (MargoError
604
+ `'state'` without one). `fixedFoveation` from 0 (off) to 1 (strongest) lowers resolution at the edges of each eye;
605
+ reading it gives the runtime's value after its rounding, or `null` where the layer has none, where setting it throws
606
+ `'unsupported'`. A value outside 0 to 1 throws `RangeError`. Unset keeps the browser's setting.
607
+ - **Camera images.** `perf.cameraImage(view)`, inside a frame, returns `{camera, texture, context}`: the Raw Camera
608
+ Access image for that view as a WebGL texture with its width and height, or `null` when the view has no camera
609
+ this frame. The texture belongs to the browser and is valid only during that frame; never delete it. The module
610
+ gives WebGL textures only, so it works on the WebGL2 compatibility route (`margoengine/webgl2-compat/xr`) and throws
611
+ `'unsupported'` on native WebGPU, as it does without the `'camera-access'` feature.
612
+ - **Cleanup.** `dispose()`, `using` or the `signal`'s abort puts foveation back as it was at `attach` and removes the
613
+ listeners; the session's end does the same without touching the ended layer. After that, every member throws
614
+ `'disposed'`, and on a newer session `'state'`.
615
+
616
+ ## Interaction toolkit
617
+
618
+ `Interaction.attach(xr, { grabbables, sockets, panels })` from `@margoengine/xr/interaction` handles the usual hand and controller interactions. Squeeze (or pinch, on a tracked hand) near an object or with the ray on it to pick it up; it follows the grip as you hold it. Let go over a socket that fits and it snaps in; otherwise `onRelease` gets its speed for a throw. Point the ray at a panel and press the trigger (or pinch) for `down` and `up`, with `u` and `v` from the panel's top left. The arrays stay live: push or remove items at any time.
619
+
620
+ ```ts
621
+ import {Engine,PbrMaterial,box as boxGeometry} from 'margoengine/core';
622
+ import {Quaternion} from 'margoengine/math/quaternion';
623
+ import {Vector3} from 'margoengine/math/vector3';
624
+ import {XR} from 'margoengine/xr';
625
+ import {Interaction,grabbable} from 'margoengine/xr/interaction';
626
+
627
+ const canvas=document.createElement('canvas');document.body.append(canvas);
628
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
629
+ const xr=await XR.create(engine);
630
+ const box=engine.createMesh().setGeometry(boxGeometry()).setMaterial(new PbrMaterial({color:'#e8a33d'})).setScale([0.1,0.1,0.1]).setPosition([0,1,-0.5]);
631
+ const cube=grabbable(box,{radius:0.08});
632
+ const shelf={position:new Vector3(0.3,1,-0.5),orientation:new Quaternion(),radius:0.1,held:null};
633
+ const button={position:new Vector3(0,1.4,-1),orientation:new Quaternion(),size:[0.3,0.1] as const,onPointer:(e:{type:string})=>{if(e.type==='up')console.log('clicked');}};
634
+ const ui=Interaction.attach(xr,{grabbables:[cube],sockets:[shelf],panels:[button]});
635
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
636
+ enter.onclick=()=>void xr.requestSession('immersive-vr',{optionalFeatures:['hand-tracking']}).catch(engine.onError);
637
+ // ui.rays[i] tells where each ray points, for drawing a pointer; ui.dispose() lets go of everything.
638
+ ```
639
+
640
+ ## Near interaction
641
+
642
+ `@margoengine/xr/near` holds the hand-and-controller behaviours for UI you reach out to. Each one attaches to the `XR` (any `{controllers, onFrame}` host), moves objects you pass in (`{position, orientation}`, plus `scale` where it scales), has `dispose()` and `Symbol.dispose`, and checks its options with a `RangeError` that names the fix. Units are metres in the reference space.
643
+
644
+ | Behaviour | What it does |
645
+ | --- | --- |
646
+ | `HandConstraint` | Carries a menu on the palm. It shows while a tracked hand's palm faces you (`showAngle` 45 degrees) and hides past `hideAngle` (60), so it does not flicker; `offset` is in the wrist joint's frame, default 10 cm off the palm. |
647
+ | `FollowInView` | Tag-along: a panel stays put while it is inside a cone around your gaze (`maxViewDegrees` 25) and between `minDistance` 0.4 and `maxDistance` 1.2; outside, it eases to the cone's edge. `enabled = false` pins it, `snap()` puts it `distance` in front, `billboard` turns it to face you. |
648
+ | `SurfaceMagnetism` | Sticks an object to the surface the gaze or a controller ray points at (planes, for example AR hit tests through `surfaceFromHit(hit)`), aligned to the normal: `normalAxis` 'y' stands it up, 'z' hangs a panel. `snapToSurface` snaps an object that something else moved. |
649
+ | `Manipulator` | Six-DoF drag and multi-pointer scale: a pinch or squeeze on an object, or along the ray, picks it up; it keeps its pose in your hand's frame. A second pointer on the same object scales it by the distance between the pointers and turns it by the line between them; lifting one returns to the one-point drag with no jump. `rotate` ('follow', 'yaw', 'none'), `lock`, `translate` and `scaleLimits` constrain it. |
650
+ | `AppBar` | A row of buttons under an object (default `remove` and `adjust`) that shows when a hand is within `showDistance` (0.6 m). |
651
+ | `NearMenu` | A grid of buttons in front of you that tags along until its pin button pins it. |
652
+ | `Slate` | A holographic 2D panel: drag its title bar to move it, its corner to resize it (within `minSize` and `maxSize`), its content to pan it (`contentOffset`, `zoomBy`); taps and the close button call back. |
653
+
654
+ `AppBar`, `NearMenu` and `Slate` are `RayPanel`s: add them to `Interaction.panels` and rays and pinches press them. `AppBar` and `NearMenu` are also pressed by a fingertip: the index tip hovers a button within 6 cm of the panel, presses within 1.2 cm and clicks on release (`poke` sets the distances, `false` turns it off). They expose `layout()`, each button's centre, size and state in metres from the panel's centre, for drawing; Margo draws nothing here, so the look is yours.
655
+
656
+ ```ts
657
+ import {Engine,PbrMaterial,box as boxGeometry} from 'margoengine/core';
658
+ import {Quaternion} from 'margoengine/math/quaternion';
659
+ import {Vector3} from 'margoengine/math/vector3';
660
+ import {XR} from 'margoengine/xr';
661
+ import {Interaction} from 'margoengine/xr/interaction';
662
+ import {AppBar,FollowInView,HandConstraint,Manipulator,NearMenu,Slate,SurfaceMagnetism,nearTarget} from 'margoengine/xr/near';
663
+
664
+ const canvas=document.createElement('canvas');document.body.append(canvas);
665
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
666
+ const xr=await XR.create(engine);
667
+ const box=engine.createMesh().setGeometry(boxGeometry()).setMaterial(new PbrMaterial({color:'#e8a33d'})).setScale([0.2,0.2,0.2]).setPosition([0,1,-0.6]);
668
+ const cube=nearTarget(box,{radius:0.15,scale:[0.2,0.2,0.2]});
669
+ // Pinch or squeeze the cube to move it; two hands scale it (x scale between 0.05 and 0.6).
670
+ const drag=Manipulator.attach(xr,{draggables:[cube],scaleLimits:[0.05,0.6]});
671
+ // Its app bar appears when a hand comes near.
672
+ const bar=AppBar.attach(xr,{target:cube,extent:[1,1],onSelect:(id)=>{if(id==='remove')cube.enabled=false;}});
673
+ // A menu on the left palm, a tag-along menu and a slate.
674
+ const wrist={position:new Vector3(),orientation:new Quaternion()};
675
+ const palm=HandConstraint.attach(xr,{target:wrist,hand:'left'});
676
+ const menu=NearMenu.attach(xr,{buttons:[{id:'a',label:'A'},{id:'b',label:'B'}],onSelect:(id)=>console.log('menu',id)});
677
+ const slate=new Slate({title:'Notes',onClose:()=>{slate.enabled=false;},onContent:(e)=>console.log('tap',e.x,e.y)});
678
+ const rays=Interaction.attach(xr,{panels:[bar,menu,slate]});
679
+ // Hang a label on the wall the gaze meets (planes such as AR hit tests give; see surfaceFromHit), and keep it in view.
680
+ const label={position:new Vector3(),orientation:new Quaternion()};
681
+ const wall=SurfaceMagnetism.attach(xr,{target:label,surfaces:[{point:[0,0,-3],normal:[0,0,1]}],normalAxis:'z'});
682
+ const tag=FollowInView.attach(xr,{target:label,billboard:'none',snapOnStart:false});
683
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
684
+ enter.onclick=()=>void xr.requestSession('immersive-vr',{optionalFeatures:['hand-tracking']}).catch(engine.onError);
685
+ // Draw bar.layout(), menu.layout() and the slate with your own meshes; menu.pinned = true stops it following you.
686
+ void [drag,palm,rays,wall,tag];
687
+ ```
688
+
689
+ Hands report no buttons, so `Manipulator` picks up with a pinch (thumb tip to index tip within `pinch`, default 2 cm) and controllers with the squeeze button. Joint frames follow WebXR Hand Input: -Z toward the fingertips and -Y out of the palm.
690
+
691
+ ## Transform gizmo by controller ray
692
+
693
+ `@margoengine/xr/gizmo` drives the transform gizmo of `@margoengine/controls/transform` from the controllers' target rays instead of a mouse. Point a controller at a handle and it lights; hold the trigger and the handle follows the ray under the gizmo's own constraints: arrows and scale cubes slide along their axis, plane handles over their plane, rings turn by the angle the ray sweeps on the ring's plane. Press the other controller's trigger during a grab and the two hands scale everything attached by the ratio of their separation. Snapping, modes, spaces, pivots, several objects and the gizmo's events are the gizmo's own, so they match the desktop.
694
+
695
+ | Option | Default | What it does |
696
+ | --- | --- | --- |
697
+ | `button` | `'select'` | The action that grabs: `'select'` (trigger, or a hand's pinch) or `'squeeze'` (grip). |
698
+ | `hands` | `['left', 'right', 'none']` | Which input sources drive the gizmo, by handedness. |
699
+ | `twoHandScale` | `true` | A second hand's press during a grab starts a two-hand scale. The one-hand drag ends where it is. |
700
+ | `minSeparation` | `0.02` | Hands closer than this, in metres, at the second press do not start a scale. |
701
+ | `onHover`, `onGrab`, `onRelease` | none | Called with `{controller, handle}`: the handle's name, `'scale'` for a two-hand scale, null when a hover ends. |
702
+ | `signal` | none | Aborting disposes the driver. |
703
+
704
+ ```ts
705
+ import {Engine,PbrMaterial,box as boxGeometry} from 'margoengine/core';
706
+ import {TransformControls} from 'margoengine/controls/transform';
707
+ import {XR} from 'margoengine/xr';
708
+ import {XRGizmo} from 'margoengine/xr/gizmo';
709
+ import {pulse} from 'margoengine/xr/layers';
710
+
711
+ const canvas=document.createElement('canvas');document.body.append(canvas);
712
+ const engine=await Engine.create(canvas,{backend:'webgpu'});
713
+ const xr=await XR.create(engine);
714
+ const box=engine.createMesh().setGeometry(boxGeometry()).setMaterial(new PbrMaterial({color:'#e8a33d'})).setScale([0.3,0.3,0.3]).setPosition([0,1.2,-1]);
715
+ // A gizmo 25 cm long in the room (fixed: false), with arrows, rings and scale cubes; moves snap to 5 cm, turns to 15 degrees.
716
+ const gizmo=new TransformControls(engine,{mode:'all',fixed:false,size:0.25,translationSnap:0.05,rotationSnap:Math.PI/12});
717
+ gizmo.attach(box);
718
+ // Point at a handle and hold the trigger to drag it; press the other trigger as well to scale with two hands.
719
+ const drive=XRGizmo.attach(xr,gizmo,{
720
+ onGrab:({controller,handle})=>{console.log(controller.source.handedness,'holds',handle);void pulse(controller,0.4,30);},
721
+ onRelease:()=>console.log('now at',box.position.x,box.position.y,box.position.z,'scale',box.scale.x),
722
+ });
723
+ const enter=document.createElement('button');enter.textContent='Enter VR';document.body.append(enter);
724
+ enter.onclick=()=>void xr.requestSession('immersive-vr').catch(engine.onError);
725
+ addEventListener('pagehide',()=>{drive.dispose();gizmo.dispose();},{once:true});
726
+ ```
727
+
728
+ `XRGizmo.attach(xr, gizmo, options)` takes the `XR` (any `{session, controllers, onFrame}` host) and a `TransformControls` (any gizmo with its pointer methods and ray hook: `frame`, `pick`, `setAxis`, `pointerDown`, `pointerMove`, `begin`, `endDrag` and `aim`). `drive.grabbing` is the controller holding a handle, `drive.scaling` is true during a two-hand scale, and `dispose()` or `using` lets go and removes every listener. A bad host, gizmo or option throws a `RangeError` that names the fix. Poses are read in the XR reference space and taken as world space. A ray within 2.5 degrees of the arrow it drags has no steady nearest point on it, so there the arrow follows the hand's own travel along the axis and does not jump. A controller that leaves the session, or a session that ends, lets go. After a two-hand scale a hand that is still pressing presses again to grab. Not run on a headset: it is tested with simulated input sources and poses.
729
+
730
+ ### Any world ray: `GizmoRayDriver`
731
+
732
+ `XRGizmo` works through `GizmoRayDriver`, which the entry also exports for rays that are not XR controllers (a tracked stylus, a second camera, a test). `new GizmoRayDriver(gizmo)` wraps a `TransformControls`; a ray is an origin and a direction in world space, and the direction need not be unit. The ray code lives in this entry, so `@margoengine/controls/transform` on a desktop page does not carry it.
733
+
734
+ | Method | What it does |
735
+ | --- | --- |
736
+ | `rayHover(origin, direction)` | Lights the handle the ray points at and returns its name, or null. During a drag it returns the dragged handle and changes nothing. The pick radius is 1.5 degrees about the ray. |
737
+ | `rayDown(origin, direction)` | Grabs the handle the ray points at and starts a drag. False when it points at none or a drag is under way. |
738
+ | `rayMove(origin, direction)` | Continues the drag. An arrow or scale cube follows the point of its axis nearest the ray; a plane handle follows the ray over its plane; a ring turns by the angle the ray sweeps on its plane; the view ring, the free turn and the centre scale handle read the ray's travel across a plane facing the ray at the grab. |
739
+ | `rayUp()` | Ends a `rayDown` or `scaleDown` drag; with no drag, puts out the hover light. A pointer drag is left alone. |
740
+ | `scaleDown()` | Starts a two-point scale in any mode. False when nothing is attached or a drag is under way. |
741
+ | `scaleTo(factor)` | Sizes everything attached about the gizmo: 1 is the size at `scaleDown`, and the scale snap applies. |
742
+ | `dragging`, `gizmo` | True while a handle is dragged; the gizmo driven. |
743
+
744
+ A ray that is not finite or has a zero direction, and a `scaleTo` factor that is not above 0, throw a `RangeError`. A disabled gizmo or one with nothing attached takes no ray. Modes, spaces, pivots, several objects, snapping, `cancelDrag()`, `reset()` and the events work as with a pointer.
745
+
746
+ ```ts
747
+ import {Engine, box} from 'margoengine/core';
748
+ import {TransformControls} from 'margoengine/controls/transform';
749
+ import {GizmoRayDriver} from 'margoengine/xr/gizmo';
750
+
751
+ const engine = await Engine.create(document.querySelector('canvas')!);
752
+ const crate = engine.createMesh().setGeometry(box());
753
+ const gizmo = TransformControls.attach(engine, {translationSnap: 0.25});
754
+ gizmo.attach(crate);
755
+ engine.render();
756
+ const rays = new GizmoRayDriver(gizmo);
757
+ // A ray from a hand at [0.5, 2, 3] down to the X arrow, then swung to meet the axis one unit further along.
758
+ const hand = [0.5, 2, 3], reach = 0.6 * gizmo.frame()!.size;
759
+ const toward = (x: number) => [x - hand[0], -hand[1], -hand[2]];
760
+ if (rays.rayDown(hand, toward(reach))) {
761
+ rays.rayMove(hand, toward(reach + 1));
762
+ rays.rayUp();
763
+ }
764
+ console.log(crate.position.x); // 1
765
+ ```
766
+
767
+ Sources: WebXR Device API, W3C (input sources, `targetRaySpace`, select and squeeze events), https://www.w3.org/TR/webxr/; C. Ericson, Real-Time Collision Detection, 2005, section 5.1.8 (closest points of two lines), https://realtimecollisiondetection.net/; M. Mine, F. Brooks and C. Sequin, Moving Objects in Space: Exploiting Proprioception in Virtual-Environment Interaction, SIGGRAPH 1997 (two-handed scaling), https://doi.org/10.1145/258734.258747; D. Bowman and L. Hodges, An Evaluation of Techniques for Grabbing and Manipulating Remote Objects in Immersive Virtual Environments, I3D 1997 (ray-casting and HOMER), https://doi.org/10.1145/253284.253301; D. Mendes, F. Caputo, A. Giachetti, A. Ferreira and J. Jorge, A Survey on 3D Virtual Object Manipulation: From the Desktop to Immersive Virtual Environments, Computer Graphics Forum 2019 (widgets that separate degrees of freedom), https://doi.org/10.1111/cgf.13390.
768
+
769
+ ## Preview tier refusal
770
+
771
+ `XR.create` and `XR.attach` reject the small WebGL2 preview with linked `MargoError` code `unsupported`, so an awaited call inside `autoEngine` setup can trigger `loadCompat`. After installing the full layer, WebXR also needs its `/xr` route and browser session support as documented above. An already attached or disposed engine remains a state error.
772
+
773
+ ## Mesh pointer events
774
+
775
+ `XRPointerEvents` from `@margoengine/xr/pointer` sends `pointerover`, `pointerout`,
776
+ `pointermove`, `pointerdown`, `pointerup`, `pointercancel` and `click` to selection
777
+ hits on any supported mesh or glTF primitive. `SpatialPicking` from
778
+ `@margoengine/selection/spatial` supplies GPU ray picking and exact triangle
779
+ proximity. A source has one stable pointer id. Touch wins over grab, then ray;
780
+ `types` can change that order or disable modes. Capture keeps the selected target
781
+ through a miss. Session end, source removal, tracking loss and disposal cancel a
782
+ press. Pending picks retain pose snapshots and press/release ordering; moves
783
+ coalesce. Native select/squeeze events support sources without gamepads.
784
+
785
+ Copy `packages/exporters/tests/fixtures/Box.glb` to your app's
786
+ `public/xr-pointer-box.glb` before running this example. The README gate serves
787
+ that exact licensed fixture at the same URL.
788
+
789
+ ```ts
790
+ import { Engine } from '@margoengine/core';
791
+ import { loadGLTF } from '@margoengine/gltf/pbr';
792
+ import { Picking } from '@margoengine/selection';
793
+ import { SpatialPicking } from '@margoengine/selection/spatial';
794
+ import { XR } from '@margoengine/xr';
795
+ import { XRPointerEvents } from '@margoengine/xr/pointer';
796
+
797
+ const canvas = document.createElement('canvas'); document.body.append(canvas);
798
+ const engine = await Engine.create(canvas, { backend: 'webgpu', camera: { position: [0, 0, 4] } });
799
+ await loadGLTF(engine, '/xr-pointer-box.glb');
800
+ const picking = Picking.attach(engine);
801
+ const spatial = new SpatialPicking(engine, picking);
802
+ const xr = await XR.create(engine);
803
+ const pointers = XRPointerEvents.attach(xr, spatial, {
804
+ onEvent(event) { if (event.type === 'click') console.log(event.target, event.pointerType); },
805
+ onError: engine.onError,
806
+ });
807
+ const enter = document.createElement('button'); enter.textContent = 'Enter VR'; document.body.append(enter);
808
+ enter.onclick = () => void xr.requestSession('immersive-vr', { optionalFeatures: ['hand-tracking'] }).catch(engine.onError);
809
+ engine.start();
810
+ // On teardown: pointers.dispose(); spatial.dispose(); picking.dispose(); xr.dispose(); engine.dispose();
811
+ ```
812
+
813
+ The sample model is Cesium's Khronos Box, CC BY 4.0; see
814
+ [its fixture notice](../exporters/tests/fixtures/NOTICE.md). Serve this repository
815
+ or copy that standard asset to your application's public folder.
816
+
817
+ Distances are metres: `touchRadius` defaults to 0.01 in addition to the reported
818
+ fingertip radius, `grabRadius` to 0.08, `near` to 0.0001 and `far` to 1000. Pinch
819
+ uses a 0.025 metre thumb/index-tip threshold. Controller trigger selects; squeeze
820
+ grabs. Touch presses on surface contact and releases/clicks on leaving it. A
821
+ held pointer keeps its mode through release. `signal` aborts the attachment;
822
+ `dispose()` and `Symbol.dispose` detach it. `onError` is required. `onEvent` may
823
+ call `stopPropagation` and `setPointerCapture(target?)`, `releasePointerCapture`
824
+ or `hasPointerCapture`; the optional target lets a parent capture a child hit.
825
+ A custom picker can implement the exported `XRPointerPicker` interface.
826
+
827
+ React apps mount `XRPointerEvents` from `@margoengine/react/xr-pointer` inside
828
+ `Canvas` and `XR`; existing mesh handlers receive the events with the source and
829
+ selection hit at `event.xr`. See that package's example. These deterministic and
830
+ browser checks do not replace the still-missing physical device runs.
831
+
832
+ `npm run test:gpu:pointers --workspace @margoengine/xr` is registered in the GPU
833
+ package plan and check:merge, with a 3 minute hard limit. Pass `-- --compat` for
834
+ the WebGL2 implementation. The dedicated compatibility XR bridge suite remains
835
+ packages/webgl2-compat/test/xr-browser.mjs.
836
+
837
+ ### Attaching from a second scene
838
+
839
+ `XR.create` remembers the scene that is active when you call it, before its first await, and joins that scene when it finishes. Start it inside a second scene's plugin `setup` and the plugin belongs to that scene; start it anywhere else and it belongs to the default scene. An abort or a failure leaves nothing in either scene.
840
+
841
+ ## Core compatibility at engine boundaries
842
+
843
+ Each engine-bound entry (`.`, `/models`, `/session`, `/layers`, `/interaction`, `/pointer`, `/locomotion`, `/hands`, `/ar-extra`, `/performance`, `/near`, `/gizmo`) carries the core version its build was made for, stamped into its plugins, `attach` methods and `engineRuntime` calls, and checks the engine's core when it attaches or its plugin is set up, before it reads or changes the engine. A mismatched core version, or a second core module in the page (two installs, or one bundled twice), throws MargoError `'version'` naming both cores and the package, with the help link https://margoengine.com/errors#version. The cure is one core: dedupe or rebuild the packages against the same core build (`npm ls @margoengine/core` lists the copies); do not catch the error and go on. The check keeps no global state, and importing an entry registers nothing and attaches nothing. Details: [One core per engine](../core/README.md#one-core-per-engine-version-checks-extension) in the core README. The other entries (`/device-check`, `/ar`, `/occlusion`, `/launch`, `/reflection`, `/body`) carry no check of their own: the build found no plugin, `attach` or `engineRuntime` call in them, and anything they hand to an engine is checked by the entry that attaches it.