-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathviewer.js
More file actions
509 lines (450 loc) · 16.3 KB
/
Copy pathviewer.js
File metadata and controls
509 lines (450 loc) · 16.3 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import * as THREE from 'three';
import { GUI } from './three/libs/lil-gui.module.min.js';
import { OrbitControls } from './three/controls/OrbitControls.js';
import { TrackballControls } from './three/controls/TrackballControls.js';
import { LineMaterial } from './three/lines/LineMaterial.js';
import { Line2 } from './three/lines/Line2.js';
import { WireframeGeometry2 } from './three/lines/WireframeGeometry2.js';
import Stats from './three/libs/stats.module.js';
import * as BufferGeometryUtils from './three/utils/BufferGeometryUtils.js';
import * as utils from './utils.js';
// Largest on-screen point size (in pixels) when size attenuation is disabled.
// The point size slider is mapped onto [0, MAX_POINT_PIXEL_SIZE] in that mode.
const MAX_POINT_PIXEL_SIZE = 30;
// Rotation that brings the file's up axis to three.js' +Y. Each entry is a pure
// rotation, so handedness is preserved and no mirroring is introduced.
const UP_AXIS_ROTATIONS = {
'+X': new THREE.Euler(0, 0, Math.PI / 2),
'-X': new THREE.Euler(0, 0, -Math.PI / 2),
'+Y': new THREE.Euler(0, 0, 0),
'-Y': new THREE.Euler(Math.PI, 0, 0),
'+Z': new THREE.Euler(-Math.PI / 2, 0, 0),
'-Z': new THREE.Euler(Math.PI / 2, 0, 0),
};
class Viewer {
controls;
points;
mesh;
wireframe;
axis;
lastTime;
constructor() {
this.gui = null;
this.gridHelper = null;
this.axesHelper = null;
this.monochrome = false;
// Parameters
this.params = JSON.parse(
document.getElementById('vscode-3dviewer-data').getAttribute('data-settings')
);
this.params.gridHelper = {
size: 2000,
unit: 1,
};
// Three JS instances
this.renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: true,
});
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(this.renderer.domElement);
// Stats
this.stats = new Stats();
this.stats.showPanel(0);
document.body.appendChild(this.stats.dom);
// Scene
this.scene = new THREE.Scene();
this.scene.fog = new THREE.FogExp2(this.params.backgroundColor, this.params.fogDensity);
this.scene.background = new THREE.Color(this.params.backgroundColor);
const light = new THREE.HemisphereLight(0x888888, 0x333333, 1.0);
this.scene.add(light);
// All loaded objects (points, mesh, wireframe) live in this group, so that the
// file's coordinate system can be re-oriented by rotating the group alone.
// Camera and grid helper stay in world space.
this.model = new THREE.Group();
this.model.name = 'model';
this.scene.add(this.model);
// Camera
this.camera = new THREE.PerspectiveCamera(
45.0,
window.innerWidth / window.innerHeight,
0.1,
5000.0
);
// Key light attached to the camera, so that it follows the view direction and
// vertical surfaces stay shaded no matter how the model is rotated.
// Position is camera-local: slightly above and to the right of the viewpoint.
this.cameraLight = new THREE.DirectionalLight(0xffffff, this.params.lightIntensity);
this.cameraLight.position.set(0.5, 1.0, 1.0);
this.camera.add(this.cameraLight);
this.camera.add(this.cameraLight.target); // target at the camera origin
this.scene.add(this.camera);
// check extension
this.setMesh(this.params.fileToLoad);
}
mainloop() {
this.stats.begin();
requestAnimationFrame(this.mainloop.bind(this));
this.renderer.render(this.scene, this.camera);
this.controls.update();
this.stats.end();
}
// Bounding box of the loaded data in the file's own coordinate system.
localBBox() {
this.points.geometry.computeBoundingBox();
return this.points.geometry.boundingBox;
}
// Bounding box of the loaded data in world space, i.e. after the up-axis rotation.
worldBBox() {
this.model.updateMatrixWorld(true);
return new THREE.Box3().setFromObject(this.points);
}
// Rotate the model group so that the file's up axis points to +Y. The rotation is
// taken about the model's bounding-box centre, so the model stays where it is and
// only its orientation changes. The camera is intentionally left untouched.
applyUpAxis() {
const rotation = UP_AXIS_ROTATIONS[this.params.upAxis] || UP_AXIS_ROTATIONS['+Y'];
const center = utils.getBBoxCenter(this.localBBox());
this.model.rotation.copy(rotation);
this.model.position.copy(center).sub(center.clone().applyEuler(rotation));
this.model.updateMatrixWorld(true);
}
updateHelpers() {
// Remove current helpers
if (this.gridHelper !== null) {
this.scene.remove(this.gridHelper);
}
if (this.axesHelper !== null) {
this.model.remove(this.axesHelper);
}
// Grid helper: lives in world space so that it always reads as the floor,
// whatever up axis the file uses.
if (this.params.showGridHelper) {
const worldBox = this.worldBBox();
const center = utils.getBBoxCenter(worldBox);
const extent = utils.getBBoxMaxExtent(worldBox);
const size = this.params.gridHelper.size;
const unit = this.params.gridHelper.unit;
const divisions = size / unit;
if (
this.gridHelper === null ||
this.gridHelper.size !== size ||
this.gridHelper.divisions !== divisions
) {
const colorCenterLine = new THREE.Color('#888888');
const colorGrid = new THREE.Color('#888888');
this.gridHelper = new THREE.GridHelper(size, divisions, colorCenterLine, colorGrid);
this.gridHelper.material.linewidth = 10;
this.gridHelper.name = 'gridHelper';
}
this.gridHelper.position.set(
center.x - extent * 0.5,
center.y - extent * 0.5,
center.z - extent * 0.5
);
this.scene.add(this.gridHelper);
}
// Axes helper: child of the model group, so it shows the axes of the file's
// own coordinate system and follows the up-axis rotation.
if (this.params.showAxesHelper) {
const localBox = this.localBBox();
const center = utils.getBBoxCenter(localBox);
const extent = utils.getBBoxMaxExtent(localBox);
if (this.axesHelper === null) {
this.axesHelper = new THREE.AxesHelper(extent);
this.axesHelper.material.linewidth = 10;
this.axesHelper.name = 'axesHelper';
}
this.axesHelper.position.set(
center.x - extent * 0.5,
center.y - extent * 0.5,
center.z - extent * 0.5
);
this.model.add(this.axesHelper);
}
}
updateRender() {
// Fog
this.scene.fog = new THREE.FogExp2(this.params.backgroundColor, this.params.fogDensity);
this.scene.background = new THREE.Color(this.params.backgroundColor);
// Light
this.cameraLight.intensity = this.params.lightIntensity;
// Points
if (this.points.material.sizeAttenuation !== this.params.pointSizeAttenuation) {
// sizeAttenuation is a shader define, so the material must be recompiled.
this.points.material.sizeAttenuation = this.params.pointSizeAttenuation;
this.points.material.needsUpdate = true;
}
if (!this.params.showPoints) {
this.points.material.size = 0;
} else if (this.params.pointSizeAttenuation) {
// World-space size: points shrink with distance.
this.points.material.size = this.params.pointSize;
} else {
// Screen-space size: points stay visible at any distance.
this.points.material.size =
(this.params.pointSize / this.params.pointMaxSize) * MAX_POINT_PIXEL_SIZE;
}
if (this.monochrome) {
this.points.material.color = new THREE.Color(this.params.pointColor);
}
// Mesh
if (this.mesh) {
if (this.mesh.material.flatShading !== this.params.flatShading) {
// flatShading is a shader define, so the material must be recompiled.
this.mesh.material.flatShading = this.params.flatShading;
this.mesh.material.needsUpdate = true;
}
this.model.remove(this.mesh);
if (this.params.showMesh) {
this.model.add(this.mesh);
}
}
// Wireframe
if (this.wireframe) {
this.wireframe.material.color = new THREE.Color(this.params.wireframeColor);
this.wireframe.material.linewidth = this.params.wireframeWidth;
this.model.remove(this.wireframe);
if (this.params.showWireframe) {
this.model.add(this.wireframe);
}
}
}
onWindowResize() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
if (this.controls && typeof this.controls.handleResize === 'function') {
this.controls.handleResize();
}
}
setupControls() {
const target =
this.controls !== undefined
? this.controls.target.clone()
: utils.getBBoxCenter(this.worldBBox());
if (this.controls !== undefined) {
this.controls.dispose();
}
if (this.params.cameraControls === 'orbit') {
// OrbitControls keeps the camera upright and clamps the polar angle,
// so the model cannot be rotated over the poles.
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
} else {
// TrackballControls allows free rotation in any direction.
this.controls = new TrackballControls(this.camera, this.renderer.domElement);
this.controls.rotateSpeed = 2.0;
this.controls.zoomSpeed = 1.2;
this.controls.panSpeed = 0.8;
}
this.controls.target.copy(target);
this.controls.update();
}
setMesh(fileToLoad) {
const self = this;
const base = utils.basename(fileToLoad);
const loader = utils.createModelLoader(fileToLoad);
loader.load(fileToLoad, function (object) {
let geometry = null;
let computeIndices = false;
if (object.isGeometry || object.isBufferGeometry) {
// Geometry or BufferGeometry
console.log('The object is with type of "Geometry" or "BufferGeometry"');
geometry = object;
if (utils.extname(fileToLoad) === '.stl') {
computeIndices = true;
}
} else if (object.isGroup) {
// merge geometries
console.log('The object is with type of "THREE.Group"');
geometry = BufferGeometryUtils.mergeGeometries(
object.children.map((child) => {
const g = child.geometry.clone().applyMatrix4(child.matrix);
g.deleteAttribute('normal');
g.deleteAttribute('uv');
return g;
})
);
if (!object.children[0].isPoints) {
const tolerance = utils.getBBoxMaxExtent(geometry) * 1e-6;
geometry = BufferGeometryUtils.mergeVertices(geometry, tolerance);
}
} else {
// expect object is THREE.Mesh
console.log('The object is with type of "THREE.Mesh" or "THREE.Points"');
geometry = object.geometry;
}
// add indices to mesh object if not exist
if (computeIndices) {
const nVerts = geometry.getAttribute('position').count;
const indices = Array.from({ length: nVerts }, (_, k) => k);
geometry.setIndex(indices);
}
// mesh support
const meshSupport = geometry.index !== null;
self.params.showMesh = meshSupport;
self.params.showPoints = !meshSupport;
// add points
const sprite = new THREE.TextureLoader().load('three/textures/sprites/disc.png', () => {
const pointsMaterial = new THREE.PointsMaterial({
size: 35,
sizeAttenuation: true,
map: sprite,
alphaTest: 0.5,
transparent: true,
});
self.points = new THREE.Points(geometry, pointsMaterial);
self.points.name = base + '_points';
try {
if (geometry.getAttribute('color').count > 0) {
pointsMaterial.vertexColors = true;
}
} catch (e) {
console.warn(e);
self.monochrome = true;
}
self.model.add(self.points);
self.onMeshLoaded();
self.updateHelpers();
self.updateRender();
self.mainloop();
});
// add mesh
try {
geometry.computeVertexNormals();
// Mesh
var material = new THREE.MeshStandardMaterial({
color: 0xefefef,
roughness: 0.25,
flatShading: self.params.flatShading,
side: THREE.DoubleSide,
});
self.mesh = new THREE.Mesh(geometry, material);
self.mesh.castShadow = true;
self.mesh.receiveShadow = true;
self.mesh.name = base + '_mesh';
self.model.add(self.mesh);
// Wireframe
const wireMaterial = new LineMaterial({
color: self.params.wireframeColor,
linewidth: 1.0,
});
const edges = new WireframeGeometry2(geometry);
self.wireframe = new Line2(edges, wireMaterial);
self.wireframe.name = base + '_wireframe';
self.model.add(self.wireframe);
} catch (e) {
console.error(e);
}
});
}
onMeshLoaded() {
// Orient the model according to the configured up axis before placing the camera
this.applyUpAxis();
const worldBox = this.worldBBox();
// Camera setup
const camTarget = utils.getBBoxCenter(worldBox);
const camPos = utils.autoCameraPos(worldBox);
this.camera.position.copy(camPos);
this.camera.lookAt(camTarget);
this.setupControls();
window.addEventListener('resize', () => this.onWindowResize());
// GUI setup
const extent = utils.getBBoxMaxExtent(worldBox);
this.params.pointSize = extent / 100.0;
this.params.pointMaxSize = extent / 10.0;
this.params.gridHelper.unit = Math.pow(10, Math.floor(Math.log10(extent)));
this.params.gridHelper.size = this.params.gridHelper.unit * 1000;
this.gui = new GUI();
this.gui
.add(this.params, 'showPoints')
.name('Points')
.onChange(() => this.updateRender());
this.gui
.add(this.params, 'pointSize')
.min(0)
.max(this.params.pointMaxSize)
.name('Point size')
.onChange(() => this.updateRender());
this.gui
.addColor(this.params, 'pointColor')
.name('Point color')
.onChange(() => this.updateRender());
this.gui
.add(this.params, 'pointSizeAttenuation')
.name('Point size attenuation')
.onChange(() => this.updateRender());
this.gui
.add(this.params, 'showWireframe')
.name('Wireframe')
.onChange(() => this.updateRender());
this.gui
.add(this.params, 'wireframeWidth')
.min(0)
.max(1.0)
.name('Wireframe width')
.onChange(() => this.updateRender());
this.gui
.addColor(this.params, 'wireframeColor')
.name('Wireframe color')
.onChange(() => this.updateRender());
this.gui
.add(this.params, 'showMesh')
.name('Mesh')
.onChange(() => this.updateRender());
this.gui
.add(this.params, 'flatShading')
.name('Flat shading')
.onChange(() => this.updateRender());
this.gui
.addColor(this.params, 'backgroundColor')
.name('Background color')
.onChange(() => this.updateRender());
this.gui
.add(this.params, 'fogDensity')
.min(0)
.max(1)
.name('Fog')
.onChange(() => this.updateRender());
this.gui
.add(this.params, 'lightIntensity')
.min(0)
.max(5)
.name('Light intensity')
.onChange(() => this.updateRender());
this.gui
.add(this.params, 'cameraControls', { Trackball: 'trackball', Orbit: 'orbit' })
.name('Camera controls')
.onChange(() => this.setupControls());
this.gui
.add(this.params, 'upAxis', Object.keys(UP_AXIS_ROTATIONS))
.name('Up axis')
.onChange(() => {
this.applyUpAxis();
this.updateHelpers();
});
let folder = this.gui.addFolder('Grid Helper');
folder.open();
folder
.add(this.params, 'showAxesHelper')
.name('show axes helper')
.onChange(() => this.updateHelpers());
folder
.add(this.params, 'showGridHelper')
.name('show grid helper')
.onChange(() => this.updateHelpers());
folder
.add(this.params.gridHelper, 'size')
.name('size')
.onChange(() => this.updateHelpers());
folder
.add(this.params.gridHelper, 'unit')
.name('unit')
.onChange(() => this.updateHelpers());
if (this.params.hideControlsOnStart) {
this.gui.close();
}
}
}
const viewer = new Viewer();