True spatial computing goes beyond stereoscopic rendering. It requires deep integration with the user's physical environment. The WebXR Device API exposes advanced capabilities like hit testing, lighting estimation, and depth sensing to achieve this.
Module 1: Real-world Hit Testing
Hit testing allows you to cast a ray into the real world and find intersections with physical geometry (floors, walls, tables).
hit-test.jsjavascript
const session = await navigator.xr.requestSession('immersive-ar', { requiredFeatures: ['hit-test'] });
const viewerSpace = await session.requestReferenceSpace('viewer');
const hitTestSource = await session.requestHitTestSource({ space: viewerSpace });
// Inside your render loop (requestAnimationFrame)
const hitTestResults = frame.getHitTestResults(hitTestSource);
if (hitTestResults.length > 0) {
const pose = hitTestResults[0].getPose(referenceSpace);
// Use pose.transform.matrix to position your reticle
}Module 2: Lighting Estimation
Lighting estimation reads camera feeds to calculate ambient lighting, spherical harmonics, and a primary directional light source. This makes virtual shadows match real shadows perfectly.
lighting.jsjavascript
const lightProbe = await session.requestLightProbe();
lightProbe.addEventListener('reflectionchange', () => {
const cubeMap = glBinding.getReflectionCubeMap(lightProbe);
// Apply cubeMap to environment texture for reflections
});