This repository was archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathindex.html
More file actions
390 lines (332 loc) · 11.7 KB
/
index.html
File metadata and controls
390 lines (332 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<html>
<!-- Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<head>
<title>ARKit face tracking example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link rel="stylesheet" href="../common.css"/>
<script src="../libs/three/three.js"></script>
<script src="../libs/three/loaders/GLTFLoader.js"></script>
<script src="../libs/dat.gui.min.js"></script>
<style>
.dg {
margin-top:30px !important;
}
</style>
</head>
<body>
<div id="description">
<h2>ARKit face tracking Example</h2>
<p>This detects and tracks your face using ARKit and places a 3D model on it.
(Glasses model by <a href="https://sketchfab.com/models/5c78f100eea749c895d69fe2ed728197#">person-x</a>)</p>
</div>
<button type="button" id="go-button">Go</button>
<script type="module">
// 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;
const meshMap = new Map();
// temporary working variables
const workingMatrix = mat4.create();
const workingVec3 = vec3.create();
let ambientLight = null;
let directionalLight = null;
// add dat.GUI to the left HUD. We hid it in stereo viewing, so we don't need to
// figure out how to duplicate it.
const params = {
face: 'occlusion',
ducky: false,
glasses: true
};
const gui = new dat.GUI({autoPlace: false});
gui.add(params, 'face', {'Occlusion Only': 'occlusion', 'Oclussion & Mesh': 'both', 'Transparent Mesh': 'transparent'});
gui.add(params, 'ducky');
gui.add(params, 'glasses');
gui.domElement.id = 'gui';
gui.open();
document.body.appendChild(gui.domElement);
let duckyCreated = false;
let glassesCreated = false;
let material = null;
let wireMaterial = null;
const ducky = new THREE.Group();
ducky.name = 'Duck group';
const loader = new THREE.GLTFLoader().setPath('./');
loader.load('DuckyMesh.glb',
gltf => {
const duckyNode = gltf.scene;
duckyNode.position.set(0, -0.25, -0.2);
duckyNode.scale.set(3,3,3);
ducky.add(duckyNode);
duckyCreated = true;
},
null, // progress callback
e => {
console.error('could not load gltf', e);
}
);
loader.setPath('./glasses/');
const glasses = new THREE.Group();
glasses.name = 'Glasses group';
loader.load('glasses.gltf',
gltf => {
let glassesNode = gltf.scene;
glassesNode.position.set(0, 0.01, 0.06);
glassesNode.scale.set(0.0005,0.0005,0.0005);
glasses.add(glassesNode);
glassesCreated = true;
},
null, // progress callback
e => {
console.error('could not load gltf', e);
}
);
const goButton = document.getElementById('go-button');
const initXR = () => {
if (navigator.xr) {
navigator.xr.isSessionSupported('immersive-ar', ['worldSensing']).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: ['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);
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');
session.updateWorldSensingState({
meshDetectionState: {
enabled: true
}
});
// 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
// Our custom engine class does hit testing at the end of each rAF
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 scene
ambientLight = engine.addAmbientLight();
directionalLight = engine.addDirectionalLight();
wireMaterial = new THREE.MeshPhongMaterial({color: '#999999', wireframe: true});
material = new THREE.MeshPhongMaterial({color: '#999900', transparent: true, opacity: 0.5});
};
const onSessionEnd = event => {
session = null;
viewerReferenceSpace = null;
localReferenceSpace = null;
goButton.innerText = 'Go';
};
// Called once per frame, before render, to give the app a chance to update this.scene
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 if (worldMesh instanceof XRFaceMesh) {
handleNewNode(worldMesh);
object = meshMap.get(worldMesh.uid);
}
if (object) {
if (params.ducky) {
if (ducky.parent != object.faceMesh) {
object.faceMesh.add(ducky);
}
} else {
object.faceMesh.remove(ducky);
}
if (params.glasses) {
if (glasses.parent != object.faceMesh) {
object.faceMesh.add(glasses);
}
} else {
object.faceMesh.remove(glasses);
}
}
});
if (material) {
if (params.face == "occlusion") {
material.colorWrite = false; // only update the depth
wireMaterial.colorWrite = false; // only update the depth
material.transparent = false;
} else if (params.face == "transparent") {
material.colorWrite = true; // only update the depth
wireMaterial.colorWrite = true; // only update the depth
material.transparent = true;
} else {
material.colorWrite = true; // only update the depth
wireMaterial.colorWrite = true; // only update the depth
material.transparent = false;
}
}
meshMap.forEach(object => {
if (!object.seen) {
handleRemoveNode(object);
}
});
}
};
const handleRemoveNode = object => {
object.geometry.dispose();
engine.removeAnchoredNode(object.faceMesh);
meshMap.delete(object.worldMesh.uid);
};
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;
}
let currentVertexIndex = 0;
if (worldMesh.vertexPositionsChanged) {
const position = object.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.vertexNormalsChanged && worldMap.vertexNormals.length > 0) {
// normals are optional
const normals = object.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;
}
/// these ones probably will not change while the face is tracked, but
/// for future changes to the underlying detector, keep them here
if (worldMesh.textureCoordinatesChanged) {
const uv = object.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.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;
}
}
const handleNewNode = worldMesh => {
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();
}
const transparentMesh = new THREE.Group();
let tm = new THREE.Mesh(geometry, material);
tm.renderOrder = -2;
transparentMesh.add(tm);
tm = new THREE.Mesh(geometry, wireMaterial);
tm.renderOrder = -2;
transparentMesh.add(tm);
const faceMesh = new THREE.Group();
faceMesh.add(transparentMesh);
engine.addAnchoredNode(worldMesh, faceMesh);
meshMap.set(worldMesh.uid, {
ts: worldMesh.timeStamp,
worldMesh: worldMesh,
seen: true,
geometry: geometry,
faceMesh: faceMesh,
transparentMesh: transparentMesh,
threeMesh: transparentMesh
});
};
////////////////
// render loop
const handleAnimationFrame = (t, frame) => {
if (!session || session.ended) return;
updateScene(frame);
session.requestAnimationFrame(handleAnimationFrame);
const pose = frame.getViewerPose(localReferenceSpace);
if (!pose) {
console.log('No pose');
return;
}
engine.startFrame();
for (const view of pose.views) {
engine.preRender(
session.renderState.baseLayer.getViewport(view),
view.projectionMatrix,
view.transform.matrix
);
engine.render();
}
engine.endFrame();
};
initXR();
</script>
</body>
</html>