forked from Kitware/vtk-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
365 lines (320 loc) · 10.9 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
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
// For streamlined VR development install the WebXR emulator extension
// https://github.com/MozillaReality/WebXR-emulator-extension
import '@kitware/vtk.js/favicon';
// Load the rendering pieces we want to use (for both WebGL and WebGPU)
import '@kitware/vtk.js/Rendering/Profiles/Geometry';
import HttpDataAccessHelper from '@kitware/vtk.js/IO/Core/DataAccessHelper/HttpDataAccessHelper';
import macro from '@kitware/vtk.js/macros';
import vtkDeviceOrientationToCamera from '@kitware/vtk.js/Interaction/Misc/DeviceOrientationToCamera';
import vtkFullScreenRenderWindow from '@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow';
import vtkSkybox from '@kitware/vtk.js/Rendering/Core/Skybox';
import vtkSkyboxReader from '@kitware/vtk.js/IO/Misc/SkyboxReader';
import vtkURLExtract from '@kitware/vtk.js/Common/Core/URLExtract';
// import vtkMobileVR from '@kitware/vtk.js/Common/System/MobileVR';
// Force DataAccessHelper to have access to various data source
import '@kitware/vtk.js/IO/Core/DataAccessHelper/HtmlDataAccessHelper';
import '@kitware/vtk.js/IO/Core/DataAccessHelper/JSZipDataAccessHelper';
import vtkResourceLoader from '@kitware/vtk.js/IO/Core/ResourceLoader';
import style from './SkyboxViewer.module.css';
// Dynamically load WebXR polyfill from CDN for WebVR and Cardboard API backwards compatibility
if (navigator.xr === undefined) {
vtkResourceLoader
.loadScript(
'https://cdn.jsdelivr.net/npm/webxr-polyfill@latest/build/webxr-polyfill.js'
)
.then(() => {
// eslint-disable-next-line no-new, no-undef
new WebXRPolyfill();
});
}
// ----------------------------------------------
// Possible URL parameters to look for:
// - fileURL
// - position
// - direction
// - up
// - vr
// - eye
// - viewAngle
// - debug
// - autoIncrement
// - k1
// - k2
// - centerY
// ----------------------------------------------
const userParams = vtkURLExtract.extractURLParameters();
let autoInit = true;
const cameraFocalPoint = userParams.direction || [0, 0, -1];
const cameraViewUp = userParams.up || [0, 1, 0];
const cameraViewAngle = userParams.viewAngle || 100;
const eyeSpacing = userParams.eye || 0.0;
const grid = userParams.debug || false;
const autoIncrementTimer = userParams.timer || 0;
const body = document.querySelector('body');
let fullScreenMetod = null;
['requestFullscreen', 'msRequestFullscreen', 'webkitRequestFullscreen'].forEach(
(m) => {
if (body[m] && !fullScreenMetod) {
fullScreenMetod = m;
}
}
);
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
function createController(options) {
if (options.length === 1) {
return null;
}
const buffer = ['<select class="position">'];
buffer.push(options.join(''));
buffer.push('</select>');
return buffer.join('');
}
function drawLine(ctx, x, y, text, delta = 10) {
ctx.beginPath();
ctx.moveTo(x, y - delta);
ctx.lineTo(x, y + delta);
ctx.stroke();
ctx.fillText(text, x, y + delta + 10);
}
function createGrid(width, height) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.style.width = '100%';
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#FFFFFF';
ctx.fillStyle = '#FFFFFF';
ctx.textAlign = 'center';
const totalWidth = width;
const eyeCenter = width / 4;
const y = window.screen.height / 2;
ctx.clearRect(0, 0, width, height);
const nbTicks = 20;
for (let i = 0; i <= nbTicks; i++) {
const value = (i - nbTicks / 2) / (nbTicks / 2);
drawLine(
ctx,
eyeCenter + eyeCenter * (eyeSpacing + value),
y,
`${value}`,
value ? 20 : 100
);
drawLine(
ctx,
totalWidth - (eyeCenter + eyeCenter * (eyeSpacing + value)),
y,
`${value}`,
value ? 20 : 100
);
}
ctx.fillText(
`Current Offset ${eyeSpacing}`,
eyeCenter + eyeCenter * eyeSpacing,
y - 120
);
ctx.fillText(
`Current Offset ${eyeSpacing}`,
totalWidth - (eyeCenter + eyeCenter * eyeSpacing),
y - 120
);
canvas.style.zIndex = 1000;
canvas.style.position = 'fixed';
canvas.style.top = 0;
canvas.style.left = 0;
body.appendChild(canvas);
}
function createVisualization(container, mapReader) {
// Empty container
while (container.firstChild) {
container.removeChild(container.firstChild);
}
const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
rootContainer: container,
containerStyle: { height: '100%', width: '100%', position: 'absolute' },
});
const renderWindow = fullScreenRenderer.getRenderWindow();
const mainRenderer = fullScreenRenderer.getRenderer();
const interactor = fullScreenRenderer.getInteractor();
const actor = vtkSkybox.newInstance();
const camera = mainRenderer.getActiveCamera();
const updateCameraCallBack = mainRenderer.resetCameraClippingRange;
// Connect viz pipeline
actor.addTexture(mapReader.getOutputData());
// Update Camera configuration
const cameraConfiguration = {
focalPoint: cameraFocalPoint,
position: [0, 0, 0],
viewAngle: cameraViewAngle,
physicalViewNorth: cameraFocalPoint,
viewUp: cameraViewUp,
physicalViewUp: cameraViewUp,
};
function updateSkybox(position) {
const selector = document.querySelector('.position');
if (selector && selector.value !== position) {
selector.value = position;
}
actor.removeAllTextures();
mapReader.setPosition(`${position}`);
mapReader.update();
actor.addTexture(mapReader.getOutputData());
renderWindow.render();
}
function nextPosition() {
const currentPosition = mapReader.getPosition();
const allPositions = mapReader.getPositions();
const nextIdx =
(allPositions.indexOf(currentPosition) + 1) % allPositions.length;
updateSkybox(allPositions[nextIdx]);
}
camera.set(cameraConfiguration);
mainRenderer.addActor(actor);
// add vr option button if supported
if (
navigator.xr !== undefined &&
navigator.xr.isSessionSupported('immersive-vr')
) {
const button = document.createElement('button');
button.style.position = 'absolute';
button.style.left = '10px';
button.style.bottom = '10px';
button.style.zIndex = 10000;
button.textContent = 'Send To VR';
document.querySelector('body').appendChild(button);
button.addEventListener('click', () => {
if (button.textContent === 'Send To VR') {
fullScreenRenderer.getApiSpecificRenderWindow().startXR();
button.textContent = 'Return From VR';
} else {
fullScreenRenderer.getApiSpecificRenderWindow().stopXR();
button.textContent = 'Send To VR';
}
});
}
renderWindow.render();
// handle auto incrementing position
if (autoIncrementTimer !== 0) {
setInterval(nextPosition, autoIncrementTimer * 1000);
}
// Update camera control
if (vtkDeviceOrientationToCamera.isDeviceOrientationSupported()) {
vtkDeviceOrientationToCamera.addWindowListeners();
const cameraListenerId =
vtkDeviceOrientationToCamera.addCameraToSynchronize(
interactor,
camera,
updateCameraCallBack
);
interactor.requestAnimation('deviceOrientation');
// Test again after 100ms
setTimeout(() => {
if (!vtkDeviceOrientationToCamera.isDeviceOrientationSupported()) {
vtkDeviceOrientationToCamera.removeCameraToSynchronize(
cameraListenerId
);
vtkDeviceOrientationToCamera.removeWindowListeners();
interactor.cancelAnimation('deviceOrientation');
}
}, 100);
}
// Add Control UI
const controller = createController(
mapReader.getPositions().map((t) => `<option value="${t}">${t}</option>`)
);
if (controller) {
fullScreenRenderer.addController(controller);
document.querySelector('.position').addEventListener('change', (e) => {
updateSkybox(e.target.value);
});
}
// Apply url args to viz
if (userParams.position) {
updateSkybox(userParams.position);
}
if (grid) {
console.log(fullScreenRenderer.getOpenGLRenderWindow().getSize());
createGrid(...fullScreenRenderer.getOpenGLRenderWindow().getSize());
}
}
/* eslint-disable import/prefer-default-export */
/* eslint-disable import/no-extraneous-dependencies */
export function initLocalFileLoader(container) {
autoInit = false;
const exampleContainer = document.querySelector('.content');
const rootBody = document.querySelector('body');
const myContainer = container || exampleContainer || rootBody;
if (myContainer !== container) {
myContainer.classList.add(style.fullScreen);
rootBody.style.margin = '0';
rootBody.style.padding = '0';
} else {
rootBody.style.margin = '0';
rootBody.style.padding = '0';
}
const fileContainer = document.createElement('div');
fileContainer.innerHTML = `<div class="${style.bigFileDrop}"/><input type="file" accept=".skybox,.zip" style="display: none;"/>`;
myContainer.appendChild(fileContainer);
const fileInput = fileContainer.querySelector('input');
function handleFile(e) {
preventDefaults(e);
const dataTransfer = e.dataTransfer;
const files = e.target.files || dataTransfer.files;
if (files.length === 1) {
myContainer.removeChild(fileContainer);
const reader = vtkSkyboxReader.newInstance();
reader.parseAsArrayBuffer(files[0]);
reader.getReadyPromise().then(() => {
createVisualization(myContainer, reader);
});
}
}
fileInput.addEventListener('change', handleFile);
fileContainer.addEventListener('drop', handleFile);
fileContainer.addEventListener('click', (e) => fileInput.click());
fileContainer.addEventListener('dragover', preventDefaults);
}
// Look for data to download
if (userParams.fileURL) {
autoInit = false;
const exampleContainer = document.querySelector('.content');
const rootBody = document.querySelector('body');
const myContainer = exampleContainer || rootBody;
if (myContainer) {
myContainer.classList.add(style.fullScreen);
rootBody.style.margin = '0';
rootBody.style.padding = '0';
}
const progressContainer = document.createElement('div');
progressContainer.setAttribute('class', style.progress);
myContainer.appendChild(progressContainer);
const progressCallback = (progressEvent) => {
if (progressEvent.lengthComputable) {
const percent = Math.floor(
(100 * progressEvent.loaded) / progressEvent.total
);
progressContainer.innerHTML = `Loading ${percent}%`;
} else {
progressContainer.innerHTML = macro.formatBytesToProperUnit(
progressEvent.loaded
);
}
};
HttpDataAccessHelper.fetchBinary(userParams.fileURL, {
progressCallback,
}).then((arrayBuffer) => {
const reader = vtkSkyboxReader.newInstance();
reader.parseAsArrayBuffer(arrayBuffer);
reader.getReadyPromise().then(() => {
createVisualization(myContainer, reader);
});
});
}
// Auto setup if no method get called within 100ms
setTimeout(() => {
if (autoInit) {
initLocalFileLoader();
}
}, 100);