### Install WebXR Polyfill and Get XRSystem Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Startup_and_shutdown This function installs the WebXR polyfill if necessary and returns the XRSystem object. It assumes the polyfill is already included via a script tag. The global `webxrPolyfill` variable is used to keep a reference to the polyfill. ```javascript function getXR() { if (webxrPolyfill) { webxrPolyfill.install(); } return navigator.xr; } ``` -------------------------------- ### Getting an XRPose Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Spatial_tracking Demonstrates how to obtain an XRPose object using the getPose() method on an XRFrame, typically within a rendering loop. ```APIDOC ## POST /getPose ### Description Computes the position and orientation of a specified XRSpace relative to another XRSpace's origin, returning an XRPose object. ### Method POST ### Endpoint `XRFrame.getPose(space, baseSpace)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **space** (XRSpace) - Required - The XRSpace to get the pose for. - **baseSpace** (XRSpace) - Required - The XRSpace to use as the origin for the pose calculation. ### Request Example ```json { "space": "controllerGripSpace", "baseSpace": "worldRefSpace" } ``` ### Response #### Success Response (200) - **XRPose** (object) - An XRPose object representing the position and orientation. #### Response Example ```json { "transform": { "position": { "x": 0.1, "y": -0.2, "z": 0.5 }, "orientation": { "x": 0, "y": 0, "z": 0, "w": 1 } } } ``` ``` -------------------------------- ### Create Offset Reference Space (Meter) Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Spatial_tracking Creates a new reference space by applying an offset transform to an existing reference space. This example moves the reference space half a meter in each direction (X, Y, Z) while maintaining its original orientation. ```javascript const halfMeterTransform = new XRRigidTransform({ x: 0.5, y: 0.5, z: 0.5 }); aRefSpace = aRefSpace.getOffsetReferenceSpace(halfMeterTransform); ``` -------------------------------- ### Get Controller Grip Pose Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Spatial_tracking Demonstrates how to obtain the pose of a hand controller's grip space relative to the world's coordinate system. This pose can then be used to render a virtual representation of the controller. ```javascript const controlPose = frame.getPose(controller.gripSpace, worldRefSpace); ``` -------------------------------- ### Compute Perspective Projection Matrix with glMatrix Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Perspective This example shows how to compute a perspective projection matrix using the glMatrix library. It's useful when you need to manually define the viewing frustum, such as adjusting near and far clipping planes for performance. Ensure glMatrix is included in your project and the parameters (fov, aspect, near, far) are correctly determined. ```javascript const fov = 1.0; // Example field of view in radians const aspectRatio = 16 / 9; // Example aspect ratio const near = 0.1; // Example near clipping plane distance const far = 100.0; // Example far clipping plane distance const projectionMatrix = mat4.create(); mat4.perspective(projectionMatrix, fov, aspectRatio, near, far); // Now 'projectionMatrix' can be used with WebGL ``` -------------------------------- ### WebGLRenderingContext.makeXRCompatible() Method Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Performance Make a WebGL rendering context compatible with WebXR, preparing it for rendering XR content. ```APIDOC ## WebGLRenderingContext.makeXRCompatible() ### Description The `makeXRCompatible()` method of the `WebGLRenderingContext` interface makes the WebGL context compatible with WebXR. This is a necessary step before you can start an XR session that uses WebGL for rendering. ### Method `WebGLRenderingContext.makeXRCompatible()` ### Returns A `Promise` that resolves when the context is successfully made XR-compatible, or rejects if it fails. ### Example ```javascript const canvas = document.getElementById('my-canvas'); const gl = canvas.getContext('webgl2'); if (gl && gl.makeXRCompatible) { gl.makeXRCompatible().then(() => { console.log('WebGL context is now XR compatible.'); // Proceed to request an XR session }).catch((error) => { console.error('Failed to make WebGL context XR compatible:', error); }); } else { console.log('makeXRCompatible is not supported or WebGL 2 is not available.'); } ``` ``` -------------------------------- ### Getting an XRViewerPose Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Spatial_tracking Illustrates how to retrieve the XRViewerPose using the getViewerPose() method on an XRFrame, essential for rendering the scene from the user's perspective. ```APIDOC ## POST /getViewerPose ### Description Computes the viewer's pose (position and orientation) relative to a specified reference space, returning an XRViewerPose object. ### Method POST ### Endpoint `XRFrame.getViewerPose(viewerSpace)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **viewerSpace** (XRSpace) - Required - The XRSpace representing the viewer's reference frame (e.g., `session.preferredFrameOfReference`). ### Request Example ```json { "viewerSpace": "local-floor" } ``` ### Response #### Success Response (200) - **XRViewerPose** (object) - An XRViewerPose object representing the viewer's position and orientation. #### Response Example ```json { "views": [ { "projectionMatrix": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "viewMatrix": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "eye": {"x": 0, "y": 0, "z": 0} } ], "transform": { "position": {"x": 0, "y": 1.6, "z": 0}, "orientation": {"x": 0, "y": 0, "z": 0, "w": 1} } } ``` ``` -------------------------------- ### Primary Action Events Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Inputs Explains the sequence and purpose of `selectstart`, `select`, and `selectend` events triggered by user interaction with an input source's primary action. ```APIDOC ## Primary Action Events ### Description This section details the events associated with a primary action on an input source. A primary action is a user-initiated interaction (like a button press or gesture) that triggers a sequence of events. ### Events 1. **`selectstart`**: Sent when the user begins the primary action. 2. **`select`**: Sent when the primary action is completed successfully. 3. **`selectend`**: Sent after the `select` event or if the input source becomes unavailable. ### Usage - `selectstart` and `selectend` can be used to provide visual feedback to the user (e.g., highlighting a controller). - The `select` event is the primary indicator that the user has completed their intended action. - If only the completion of the action is needed, `selectstart` and `selectend` can be ignored. - The timing between these events can vary significantly and should not be presumed. ``` -------------------------------- ### Create an Inline WebXR Session with Local Reference Space Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Startup_and_shutdown This function attempts to create an inline WebXR session, prioritizing the 'local' reference space. If the 'local' reference space is not available, it falls back to the 'viewer' reference space, which is universally supported. ```javascript async function createInlineSession() { const xr = navigator.xr; const sessionInit = { requiredFeatures: ['local'], optionalFeatures: ['viewer'] }; try { const session = await xr.requestSession('inline', sessionInit); return session; } catch (error) { console.error('Failed to create inline session with local reference space:', error); // Fallback to viewer reference space if local fails sessionInit.requiredFeatures = ['viewer']; sessionInit.optionalFeatures = []; try { const session = await xr.requestSession('inline', sessionInit); return session; } catch (fallbackError) { throw new Error(`Failed to create inline session even with viewer reference space: ${fallbackError.message}`); } } } ``` -------------------------------- ### Draw Frame Callback with Viewer Pose Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Spatial_tracking The callback function executed for each animation frame. It retrieves the `XRFrame`, gets the `XRViewerPose` using `getViewerPose()`, and uses it for rendering the scene from the viewer's perspective. ```javascript function myDrawFrame(time, frame) { const session = frame.session; const viewerPose = frame.getViewerPose(viewerRefSpace); // Use viewerPose to render the scene } ``` -------------------------------- ### WebXR Device API Overview Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Performance This section provides an overview of the WebXR Device API, including its experimental nature and the various components it comprises. ```APIDOC ## WebXR Device API ### Description The WebXR Device API is an experimental API that provides access to immersive and augmented reality devices. It allows web applications to interact with VR and AR hardware, enabling users to experience web content in new and engaging ways. ### Experimental Status Many features of the WebXR Device API are marked as **Experimental**. This means that they are subject to change in future versions and may not be stable. Developers should be aware of this when implementing features that rely on experimental APIs. ### Key Components - **Guides**: Provides conceptual information and tutorials for using WebXR. - **Interfaces**: Defines the core objects and structures used by the WebXR API (e.g., `XRSystem`, `XRSession`, `XRInputSource`). - **Properties**: Exposes WebXR capabilities through properties on existing browser objects (e.g., `Navigator.xr`). - **Methods**: Provides functions to interact with XR devices (e.g., `WebGLRenderingContext.makeXRCompatible()`). - **Events**: Defines events that signal changes in the XR session or device state (e.g., `XRSession: end`, `XRReferenceSpace: reset`). ``` -------------------------------- ### Enumerating Input Sources Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Inputs This section details how to access and manage the list of available input sources within an XRSession. It explains the `inputSources` property and the `inputsourceschange` event for tracking additions and removals. ```APIDOC ## Enumerating Input Sources ### Description Accesses the `inputSources` property of an `XRSession` to get a live list of connected WebXR input devices. Explains how changes are handled via deletion and addition of source records, and how the `inputsourceschange` event notifies about these modifications. ### Event `inputsourceschange` ### Event Properties - `session` (XRSession) - The session for which input sources changed. - `added` (Array) - Input sources newly added. - `removed` (Array) - Input sources removed. ### Example Usage ```javascript // Assuming 'session' is a valid XRSession object session.addEventListener('inputsourceschange', (event) => { console.log('Input sources changed:', event); console.log('Added sources:', event.added); console.log('Removed sources:', event.removed); }); // Initial fetch of input sources console.log('Initial input sources:', session.inputSources); ``` ``` -------------------------------- ### Requesting Bounded or Local Floor Reference Space (JavaScript) Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Bounded_reference_spaces This code snippet demonstrates how to request a 'bounded-floor' reference space. If it fails, it falls back to requesting a 'local-floor' space. The successfully created reference space is then passed to `onRefSpaceCreated()`. If both fail, `handleError()` is called. ```javascript const spaceType = "bounded-floor"; myXRSession.requestReferenceSpace(spaceType).then(refSpace => { onRefSpaceCreated(refSpace); }).catch(error => { if (spaceType === "bounded-floor") { // Fallback to local-floor myXRSession.requestReferenceSpace("local-floor").then(refSpace => { onRefSpaceCreated(refSpace); }).catch(error => { handleError(error); }); } else { handleError(error); } }); function onRefSpaceCreated(refSpace) { // Setup the space for use console.log("Reference space created: " + refSpace.type); } function handleError(error) { console.error("Error creating reference space: " + error); } ```