-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
313 lines (287 loc) · 7.3 KB
/
index.js
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { ARButton, RealityAccelerator } from 'ratk';
import {
BoxGeometry,
BufferGeometry,
DirectionalLight,
HemisphereLight,
Line,
Mesh,
MeshBasicMaterial,
PerspectiveCamera,
Scene,
SphereGeometry,
Vector3,
WebGLRenderer,
} from 'three';
import { Text } from 'troika-three-text';
import { XRControllerModelFactory } from 'three/examples/jsm/webxr/XRControllerModelFactory.js';
// Global variables for scene components
let camera, scene, renderer, controller;
let ratk; // Instance of Reality Accelerator
let pendingAnchorData = null;
// Initialize and animate the scene
init();
animate();
/**
* Initializes the scene, camera, renderer, lighting, and AR functionalities.
*/
function init() {
scene = new Scene();
setupCamera();
setupLighting();
setupRenderer();
setupARButton();
setupController();
window.addEventListener('resize', onWindowResize);
setupRATK();
}
/**
* Sets up the camera for the scene.
*/
function setupCamera() {
camera = new PerspectiveCamera(
50,
window.innerWidth / window.innerHeight,
0.1,
10,
);
camera.position.set(0, 1.6, 3);
}
/**
* Sets up the lighting for the scene.
*/
function setupLighting() {
scene.add(new HemisphereLight(0x606060, 0x404040));
const light = new DirectionalLight(0xffffff);
light.position.set(1, 1, 1).normalize();
scene.add(light);
}
/**
* Sets up the renderer for the scene.
*/
function setupRenderer() {
renderer = new WebGLRenderer({
alpha: true,
antialias: true,
multiviewStereo: true,
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.xr.enabled = true;
document.body.appendChild(renderer.domElement);
}
/**
* Sets up the AR button and web launch functionality.
*/
function setupARButton() {
const arButton = document.getElementById('ar-button');
const webLaunchButton = document.getElementById('web-launch-button');
webLaunchButton.onclick = () => {
window.open(
'https://www.oculus.com/open_url/?url=' +
encodeURIComponent(window.location.href),
);
};
ARButton.convertToARButton(arButton, renderer, {
requiredFeatures: [
'anchors',
'plane-detection',
'hit-test',
'mesh-detection',
'local-floor',
],
onUnsupported: () => {
arButton.style.display = 'none';
webLaunchButton.style.display = 'block';
},
});
}
/**
* Sets up the XR controller and its event listeners.
*/
function setupController() {
controller = renderer.xr.getController(0);
controller.addEventListener('connected', handleControllerConnected);
controller.addEventListener('disconnected', handleControllerDisconnected);
controller.addEventListener('selectstart', handleSelectStart);
controller.addEventListener('squeezestart', handleSqueezeStart);
scene.add(controller);
const controllerModelFactory = new XRControllerModelFactory();
const controllerGrip = renderer.xr.getControllerGrip(0);
controllerGrip.add(
controllerModelFactory.createControllerModel(controllerGrip),
);
scene.add(controllerGrip);
const geometry = new BufferGeometry().setFromPoints([
new Vector3(0, 0, 0),
new Vector3(0, 0, -1),
]);
const line = new Line(geometry);
renderer.xr.getController(0).add(line);
}
/**
* Handles controller connection events.
*/
function handleControllerConnected(event) {
ratk
.createHitTestTargetFromControllerSpace(event.data.handedness)
.then((hitTestTarget) => {
this.hitTestTarget = hitTestTarget;
const geometry = new SphereGeometry(0.05);
const material = new MeshBasicMaterial({
transparent: true,
opacity: 0.5,
});
const hitTestMarker = new Mesh(geometry, material);
this.hitTestTarget.add(hitTestMarker);
});
}
/**
* Handles controller disconnection events.
*/
function handleControllerDisconnected() {
ratk.deleteHitTestTarget(this.hitTestTarget);
this.hitTestTarget = null;
}
/**
* Handles 'selectstart' event for the controller.
*/
function handleSelectStart() {
if (this.hitTestTarget) {
pendingAnchorData = {
position: this.hitTestTarget.position.clone(),
quaternion: this.hitTestTarget.quaternion.clone(),
};
}
}
/**
* Handles 'squeezestart' event for the controller.
*/
function handleSqueezeStart() {
ratk.anchors.forEach((anchor) => {
console.log(anchor.anchorID);
ratk.deleteAnchor(anchor);
});
}
/**
* Sets up the Reality Accelerator instance and its event handlers.
*/
function setupRATK() {
ratk = new RealityAccelerator(renderer.xr);
ratk.onPlaneAdded = handlePlaneAdded;
ratk.onMeshAdded = handleMeshAdded;
scene.add(ratk.root);
renderer.xr.addEventListener('sessionstart', () => {
setTimeout(() => {
ratk.restorePersistentAnchors().then(() => {
ratk.anchors.forEach((anchor) => {
buildAnchorMarker(anchor, true);
});
});
}, 1000);
setTimeout(() => {
if (ratk.planes.size == 0) {
renderer.xr.getSession().initiateRoomCapture();
}
}, 5000);
});
}
/**
* Handles the addition of a new plane detected by RATK.
*/
function handlePlaneAdded(plane) {
const mesh = plane.planeMesh;
mesh.material = new MeshBasicMaterial({
wireframe: true,
color: Math.random() * 0xffffff,
});
}
/**
* Handles the addition of a new mesh detected by RATK.
*/
function handleMeshAdded(mesh) {
const meshMesh = mesh.meshMesh;
meshMesh.material = new MeshBasicMaterial({
wireframe: true,
color: Math.random() * 0xffffff,
});
meshMesh.geometry.computeBoundingBox();
const semanticLabel = new Text();
meshMesh.add(semanticLabel);
semanticLabel.text = mesh.semanticLabel;
semanticLabel.anchorX = 'center';
semanticLabel.anchorY = 'bottom';
semanticLabel.fontSize = 0.1;
semanticLabel.color = 0x000000;
semanticLabel.sync();
semanticLabel.position.y = meshMesh.geometry.boundingBox.max.y;
mesh.userData.semanticLabelMesh = semanticLabel;
}
/**
* Handles window resize events.
*/
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
/**
* Animation loop for the scene.
*/
function animate() {
renderer.setAnimationLoop(render);
}
/**
* Render loop for the scene, updating AR functionalities.
*/
function render() {
handlePendingAnchors();
ratk.update();
updateSemanticLabels();
renderer.render(scene, camera);
}
/**
* Handles the creation of anchors based on pending data.
*/
function handlePendingAnchors() {
if (pendingAnchorData) {
ratk
.createAnchor(
pendingAnchorData.position,
pendingAnchorData.quaternion,
true,
)
.then((anchor) => {
buildAnchorMarker(anchor, false);
});
pendingAnchorData = null;
}
}
function buildAnchorMarker(anchor, isRecovered) {
const geometry = new BoxGeometry(0.05, 0.05, 0.05);
const material = new MeshBasicMaterial({
color: isRecovered ? 0xff0000 : 0x00ff00,
});
const cube = new Mesh(geometry, material);
anchor.add(cube);
console.log(
`anchor created (id: ${anchor.anchorID}, isPersistent: ${anchor.isPersistent}, isRecovered: ${isRecovered})`,
);
}
/**
* Updates semantic labels for each mesh.
*/
function updateSemanticLabels() {
ratk.meshes.forEach((mesh) => {
const semanticLabel = mesh.userData.semanticLabelMesh;
if (semanticLabel) {
semanticLabel.lookAt(camera.position);
}
});
}