Skip to content
Permalink
master
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time
<html>
<!-- Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<head>
<title>Show What Information is Being Sensed in the World</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script src="../libs/three/three.min.js"></script>
<link rel="stylesheet" href="../common.css"/>
</head>
<body>
<div id="description">
<h2>Show World Knowledge</h2>
<p>Render the anchors, including planes and face geometry, detected by the platform.</p>
</div>
<button type=button id=go-button>Go</button>
<script type=module>
/*
Reticle Example shows how to find surfaces or other features and place reticle relative to them.
In a production application, you would likely want to request world geometry, rather than only
using low level hit testing, and fall back to this method if the user declines to provide
real world geometry access.
*/
// some dependencies and utilities
import * as mat4 from '../libs/gl-matrix/mat4.js';
import * as vec3 from '../libs/gl-matrix/vec3.js';
import XREngine from '../XREngine.js';
let session = null;
let localReferenceSpace = null;
let viewerReferenceSpace = null;
let engine = null;
let hitTestSource = null;
let inputSource = null;
let isSelecting = false;
// worldMap: uid => {
// seen: bool,
// threeMesh: threejs mesh,
// node: node for mesh
// worldMesh: the XRMesh node
// }
// need to add timestamp, and use it to get rid of some updates!
const meshMap = new Map();
// temporary working variables
const workingMatrix = mat4.create();
const workingVec3 = vec3.create();
const reticleParent = new THREE.Object3D();
let reticle = null;
const reticleTrackedColor = new THREE.Color(0xDDFFDD);
const reticleNotTrackedColor = new THREE.Color(0xFF6666);
const reticleMaterial = new THREE.MeshStandardMaterial({color: reticleTrackedColor});
let ambientLight = null;
let directionalLight = null;
const goButton = document.getElementById('go-button');
const initXR = () => {
if (navigator.xr) {
navigator.xr.isSessionSupported('immersive-ar').then(supported => {
if (supported) {
goButton.disabled = false;
goButton.addEventListener('click', onButtonClick);
} else {
goButton.initText = 'No WebXR AR support';
}
});
} else {
goButton.initText = 'No WebXR support';
}
};
const onButtonClick = event => {
if (!session) {
navigator.xr.requestSession('immersive-ar', {requiredFeatures: ['hit-test', 'worldSensing']})
.then(xrSession => {
initSession(xrSession);
goButton.innerText = 'End';
}).catch(err => {
console.error('Session setup error', err);
});
} else {
session.end();
}
};
const initSession = async xrSession => {
session = xrSession;
session.addEventListener('end', onSessionEnd);
session.addEventListener('select', onSelect);
session.addEventListener('inputsourceschange', onInputSourcesChange);
localReferenceSpace = await session.requestReferenceSpace('local');
viewerReferenceSpace = await session.requestReferenceSpace('viewer');
// Create the context where we will render our 3D scene
const canvas = document.createElement('canvas');
const context = canvas.getContext('webgl', {
xrCompatible: true
});
if (!context) throw new Error('Could not create a webgl context');
// Set up the base layer
session.updateRenderState({baseLayer: new XRWebGLLayer(session, context)});
// Create a simple test scene and renderer
// The engine's scene is in the eye-level coordinate system
engine = new XREngine(canvas, context);
// get the location of the device, and use it to create an
// anchor with the identity orientation
session.requestAnimationFrame(async (t, frame) => {
mat4.copy(workingMatrix, frame.getPose(localReferenceSpace, viewerReferenceSpace).transform.matrix);
mat4.getTranslation(workingVec3, workingMatrix);
mat4.fromTranslation(workingMatrix, workingVec3);
const anchor = await frame.addAnchor(workingMatrix, localReferenceSpace);
engine.addAnchoredNode(anchor, engine.root);
// Kick off rendering
session.requestAnimationFrame(handleAnimationFrame);
});
// initialize hit test source at center
session.requestHitTestSource({space: viewerReferenceSpace}).then(xrHitTestSource => {
hitTestSource = xrHitTestSource;
});
// initialize world sensing
session.updateWorldSensingState({
illuminationDetectionState : {
enabled : true
},
meshDetectionState : {
enabled : true,
normals: true
}
});
// initialize scene
ambientLight = engine.addAmbientLight();
directionalLight = engine.addDirectionalLight();
// Add a box and axis at the origin of the eye-level coordinate system
// for debugging by uncommenting these lines
// engine.addBox([0, 0, 0], [0.025, 0.025, 0.025], 0x44ff44)
// engine.addAxesHelper([0,0,0], [0.2,0.2,0.2])
reticle = new THREE.Mesh(
new THREE.RingGeometry(0.04, 0.05, 36, 64),
reticleMaterial
);
reticle.geometry.applyMatrix(new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(-90)));
reticleParent.add(reticle);
reticleParent.matrixAutoUpdate = false;
reticleParent.visible = false;
engine.scene.add(reticleParent);
};
const onSessionEnd = event => {
clearHitTestSource();
session = null;
inputSource = null;
viewerReferenceSpace = null;
localReferenceSpace = null;
reticleParent.visible = false; // it starts invisible
goButton.innerText = 'Go';
};
const onInputSourcesChange = event => {
if (inputSource && event.removed.includes(inputSource)) {
inputSource = null;
}
if (!inputSource && event.added.length > 0) {
inputSource = event.added[0];
}
};
const onSelect = event => {
isSelecting = true;
};
const clearHitTestSource = () => {
if (hitTestSource) {
hitTestSource.cancel();
}
hitTestSource = null;
};
const updateScene = frame => {
frame.getGlobalLightEstimate().then(lightProbe => {
const ambientIntensity = lightProbe.indirectIrradiance; // @TODO: Fix me
ambientLight.intensity = ambientIntensity;
directionalLight.intensity = ambientIntensity * 0.5;
});
const worldInfo = frame.worldInformation;
if (worldInfo.meshes) {
meshMap.forEach(object => { object.seen = false });
worldInfo.meshes.forEach(worldMesh => {
let object = meshMap.get(worldMesh.uid);
if (object) {
handleUpdateNode(worldMesh, object);
} else {
handleNewNode(worldMesh);
}
});
meshMap.forEach(object => {
if (!object.seen) {
handleRemoveNode(object);
}
});
}
};
const handleUpdateNode = (worldMesh, object) => {
object.seen = true;
// we don't need to do anything if the timestamp isn't updated
if (worldMesh.timeStamp <= object.ts) {
return;
}
if (worldMesh.vertexCountChanged) {
const newMesh = newMeshNode(worldMesh);
object.threeMesh.geometry.dispose();
object.node.remove(object.threeMesh);
object.node.add(newMesh);
object.threeMesh = newMesh;
} else {
if (worldMesh.vertexPositionsChanged) {
const position = object.threeMesh.geometry.attributes.position;
if (position.array.length !== worldMesh.vertexPositions.length) {
console.error("position and vertex arrays are different sizes", position, worldMesh);
}
position.setArray(worldMesh.vertexPositions);
position.needsUpdate = true;
}
if (worldMesh.textureCoordinatesChanged) {
const uv = object.threeMesh.geometry.attributes.uv;
if (uv.array.length !== worldMesh.textureCoordinates.length) {
console.error("uv and vertex arrays are different sizes", uv, worldMesh);
}
uv.setArray(worldMesh.textureCoordinates);
uv.needsUpdate = true;
}
if (worldMesh.triangleIndicesChanged) {
const index = object.threeMesh.geometry.index;
if (index.array.length !== worldMesh.triangleIndices) {
console.error("uv and vertex arrays are different sizes", index, worldMesh);
}
index.setArray(worldMesh.triangleIndices);
index.needsUpdate = true;
}
if (worldMesh.vertexNormalsChanged && worldMesh.vertexNormals.length > 0) {
// normals are optional
const normals = object.threeMesh.geometry.attributes.normals;
if (normals.array.length != worldMesh.vertexNormals) {
console.error("uv and vertex arrays are different sizes", normals, worldMesh);
}
normals.setArray(worldMesh.vertexNormals);
normals.needsUpdate = true;
}
}
};
const handleRemoveNode = (object) => {
object.threeMesh.geometry.dispose();
engine.removeAnchoredNode(object.node);
meshMap.delete(object.worldMesh.uid);
};
const handleNewNode = (worldMesh) => {
const worldMeshGroup = new THREE.Group();
const mesh = newMeshNode(worldMesh);
worldMeshGroup.add(mesh);
const axesHelper = engine.createAxesHelper([0.1,0.1,0.1]);
worldMeshGroup.add(axesHelper);
//worldMesh.node = worldMeshGroup;
engine.addAnchoredNode(worldMesh, worldMeshGroup);
meshMap.set(worldMesh.uid, {
ts: worldMesh.timeStamp,
worldMesh: worldMesh,
node: worldMeshGroup,
seen: true,
threeMesh: mesh
});
};
const newMeshNode = worldMesh => {
let edgeColor, polyColor;
if (worldMesh instanceof XRFaceMesh) {
edgeColor = '#999999';
polyColor = '#999900';
} else {
edgeColor = '#11FF11';
polyColor = '#009900';
}
const mesh = new THREE.Group();
const geometry = new THREE.BufferGeometry();
const indices = new THREE.BufferAttribute(worldMesh.triangleIndices, 1);
indices.dynamic = true;
geometry.setIndex(indices);
const verticesBufferAttribute = new THREE.BufferAttribute(worldMesh.vertexPositions, 3);
verticesBufferAttribute.dynamic = true;
geometry.addAttribute('position', verticesBufferAttribute);
const uvBufferAttribute = new THREE.BufferAttribute(worldMesh.textureCoordinates, 2);
uvBufferAttribute.dynamic = true;
geometry.addAttribute('uv', uvBufferAttribute);
if (worldMesh.vertexNormals.length > 0) {
const normalsBufferAttribute = new THREE.BufferAttribute(worldMesh.vertexNormals, 3);
normalsBufferAttribute.dynamic = true;
geometry.addAttribute('normal', normalsBufferAttribute);
} else {
geometry.computeVertexNormals();
}
// transparent mesh
const wireMaterial = new THREE.MeshPhongMaterial({color: edgeColor, wireframe: true});
const material = new THREE.MeshPhongMaterial({color: polyColor, transparent: true, opacity: 0.25});
mesh.add(new THREE.Mesh(geometry, material));
mesh.add(new THREE.Mesh(geometry, wireMaterial));
mesh.geometry = geometry; // for later use
//worldMesh.mesh = mesh;
return mesh;
};
// Create offset ray for hit test from the relative transform
// between viewerPose and inputPose. There may be a room to optimize.
const createOffsetRay = (viewerPose, inputPose) => {
const offsetMatrix = mat4.multiply(mat4.create(), viewerPose.transform.matrix, inputPose.transform.matrix);
const direction = vec3.fromValues(0.0, 0.0, -0.2);
vec3.transformMat4(direction, direction, offsetMatrix);
vec3.normalize(direction, direction);
const offsetDirection = {
x: direction[0],
y: direction[1],
z: direction[2],
w: 0.0
};
const offsetOrigin = {x: 0, y: 0, z: 0, w: 1.0};
return new XRRay(offsetOrigin, offsetDirection);
};
// render loop
const handleAnimationFrame = (t, frame) => {
if (!session || session.ended) return;
session.requestAnimationFrame(handleAnimationFrame);
const viewerPose = frame.getViewerPose(localReferenceSpace);
if (!viewerPose) {
console.log('No viewer pose');
return;
}
// Create HitTest Source. Calculating offset ray from the relative transform
// between viewerPose and inputPose so we need to do in animation frame.
if (isSelecting && inputSource) {
const inputPose = frame.getPose(inputSource.targetRaySpace, localReferenceSpace);
const offsetRay = createOffsetRay(viewerPose, inputPose);
clearHitTestSource();
session.requestHitTestSource({space: viewerReferenceSpace, offsetRay: offsetRay}).then(xrHitTestSource => {
hitTestSource = xrHitTestSource;
});
isSelecting = false;
}
if (hitTestSource) {
const results = frame.getHitTestResults(hitTestSource);
if (results.length > 0) {
const result = results[0];
const pose = result.getPose(localReferenceSpace);
if (pose) {
reticleParent.matrix.fromArray(pose.transform.matrix);
reticleParent.visible = true; // it starts invisible
reticle.material.color = reticleTrackedColor;
reticleParent.updateMatrixWorld(true);
}
} else {
reticle.material.color = reticleNotTrackedColor;
}
}
updateScene(frame);
engine.startFrame();
for (const view of viewerPose.views) {
engine.preRender(
session.renderState.baseLayer.getViewport(view),
view.projectionMatrix,
view.transform.matrix
);
engine.render();
}
engine.endFrame();
};
initXR();
</script>
</body>
</html>