-
Notifications
You must be signed in to change notification settings - Fork 62
/
threeView.js
244 lines (200 loc) · 9.39 KB
/
threeView.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
/*global mainViewModel,ko*/
import * as THREE from '../node_modules/three/build/three.module.js';
import { GLTFLoader } from '../node_modules/three/examples/jsm/loaders/GLTFLoader.js';
import { RGBELoader } from '../node_modules/three/examples/jsm/loaders/RGBELoader.js';
import { KTX2Loader } from '../node_modules/three/examples/jsm/loaders/KTX2Loader.js';
import { DRACOLoader } from '../node_modules/three/examples/jsm/loaders/DRACOLoader.js';
import { OrbitControls } from '../node_modules/three/examples/jsm/controls/OrbitControls.js';
export class ThreeView {
constructor() {
// Tracks if this engine is currently the active engine.
this._enabled = false;
this._container = null;
this._camera = null;
this._clock = null;
this._scene = null;
this._renderer = null;
this._mixer = null;
this._orbitControls = null;
this._backgroundSubscription = undefined;
}
_subscribeToAnimUI(anim) {
anim.active.subscribe(function(newValue) {
mainViewModel.anyAnimChanged();
var action = anim.clipAction;
if (!newValue) {
action.stop();
} else {
action.play();
}
});
}
_initScene(rootPath, gltfContent) {
this._clock = new THREE.Clock();
this._container = document.getElementById('threeContainer');
var scene = this._scene = new THREE.Scene();
// Note: The near and far planes can be set this way due to the use of "logarithmicDepthBuffer" in the renderer below.
var camera = this._camera = new THREE.PerspectiveCamera(45, this._container.offsetWidth / this._container.offsetHeight, 1e-5, 1e10);
scene.add(camera);
// RENDERER
var renderer = this._renderer = new THREE.WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true });
renderer.setClearColor(0x222222);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputEncoding = THREE.sRGBEncoding;
this._container.appendChild(renderer.domElement);
var loader = new GLTFLoader();
var dracoLoaderPathAndFile = document.getElementById('dracoLoaderPath').textContent;
// Replace a slash followed by anything but a slash, to the end, with just a slash.
var dracoLoaderPath = dracoLoaderPathAndFile.replace(/\/[^\/]*$/, '/');
var dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath(dracoLoaderPath);
loader.setDRACOLoader( dracoLoader );
var extensionRootPath = document.getElementById('extensionRootPath').textContent;
var basisPath = extensionRootPath + '/node_modules/three/examples/js/libs/basis/';
loader.setKTX2Loader( new KTX2Loader().setTranscoderPath( basisPath ).detectSupport( renderer ) );
var cameraPos = new THREE.Vector3(-0.2, 0.4, 1.4);
var orbitControls = this._orbitControls = new OrbitControls(this._camera, renderer.domElement);
loader.parse(gltfContent, rootPath, data => {
var gltf = data;
var object = gltf.scene;
var defaultThreeReflection = document.getElementById('defaultThreeReflection').textContent.split('{face}');
var envMap;
var envPath = defaultThreeReflection[0];
if (defaultThreeReflection.length === 2) {
// Backwards compatibility for older, standard dynamic range backgrounds.
var envFormat = defaultThreeReflection[1];
envMap = new THREE.CubeTextureLoader().load([
envPath + 'posx' + envFormat, envPath + 'negx' + envFormat,
envPath + 'posy' + envFormat, envPath + 'negy' + envFormat,
envPath + 'posz' + envFormat, envPath + 'negz' + envFormat
]);
envMap.format = THREE.RGBFormat;
scene.environment = envMap;
} else {
// Recommended path: HDR environments have details revealed by bright and dark reflective surfaces on models.
var pmremGenerator = new THREE.PMREMGenerator( renderer );
pmremGenerator.compileEquirectangularShader();
new RGBELoader()
.setDataType(THREE.HalfFloatType)
.load(envPath, (texture) => {
envMap = pmremGenerator.fromEquirectangular(texture).texture;
pmremGenerator.dispose();
scene.environment = envMap;
applyBackground(mainViewModel.showBackground());
});
}
mainViewModel.hasBackground(true);
function applyBackground(showBackground) {
scene.background = showBackground ? envMap : null;
}
applyBackground(mainViewModel.showBackground());
this._backgroundSubscription = mainViewModel.showBackground.subscribe(applyBackground);
// Center the model on screen based on bounding box information.
object.updateMatrixWorld();
var boundingBox = new THREE.Box3().setFromObject(object);
var modelSizeVec3 = new THREE.Vector3();
boundingBox.getSize(modelSizeVec3);
var modelSize = modelSizeVec3.length();
var modelCenter = new THREE.Vector3();
boundingBox.getCenter(modelCenter);
// Set up mouse orbit controls.
orbitControls.reset();
orbitControls.maxDistance = modelSize * 50;
orbitControls.enableDamping = true;
orbitControls.dampingFactor = 0.07;
orbitControls.rotateSpeed = 1.25;
orbitControls.panSpeed = 1.25;
orbitControls.screenSpacePanning = true;
// Position the camera accordingly.
object.position.x = -modelCenter.x;
object.position.y = -modelCenter.y;
object.position.z = -modelCenter.z;
camera.position.copy(modelCenter);
camera.position.x += modelSize * cameraPos.x;
camera.position.y += modelSize * cameraPos.y;
camera.position.z += modelSize * cameraPos.z;
camera.near = modelSize / 100;
camera.far = modelSize * 100;
camera.updateProjectionMatrix();
camera.lookAt(modelCenter);
// Set up UI controls for any animations in the model.
var gltfAnimations = gltf.animations;
var koAnimations = [];
if (gltfAnimations && gltfAnimations.length) {
this._mixer = new THREE.AnimationMixer(object);
for (let i = 0; i < gltfAnimations.length; i++) {
var animation = gltfAnimations[i];
var clipAction = this._mixer.clipAction(animation);
var anim = {
index: i,
name: gltfAnimations[i].name || i,
active: ko.observable(false),
clipAction: clipAction
};
this._subscribeToAnimUI(anim);
koAnimations.push(anim);
}
mainViewModel.animations(koAnimations);
mainViewModel.anyAnimChanged();
}
scene.add(object);
this._onWindowResize();
mainViewModel.onReady();
}, function(error) {
console.error(error);
mainViewModel.showErrorMessage(error.stack);
});
}
_onWindowResize() {
if (!this._enabled) {
return;
}
this._camera.aspect = this._container.offsetWidth / this._container.offsetHeight;
this._camera.updateProjectionMatrix();
this._renderer.setSize(window.innerWidth, window.innerHeight);
}
_animate() {
if (!this._enabled) {
return;
}
requestAnimationFrame(() => this._animate());
if (this._mixer) {
this._mixer.update(this._clock.getDelta());
}
this._orbitControls.update();
this._renderer.render(this._scene, this._camera);
}
/**
* @function cleanup
* Perform any cleanup that needs to happen to stop rendering the current model.
* This is called right before the active engine for the preview window is switched.
*/
cleanup() {
if (this._backgroundSubscription) {
this._backgroundSubscription.dispose();
this._backgroundSubscription = undefined;
}
this._enabled = false;
if (this._container && this._renderer) {
this._container.removeChild(this._renderer.domElement);
}
this._camera = null;
mainViewModel.animations([]);
if (this._mixer) {
this._mixer.stopAllAction();
}
window.removeEventListener('resize', this._resizeHandler, false);
}
startPreview() {
var rev = document.getElementById('threeRevision');
rev.textContent = 'r' + THREE.REVISION;
var rootPath = document.getElementById('gltfRootPath').textContent;
var gltfContent = document.getElementById('gltf').textContent;
this._resizeHandler = () => this._onWindowResize();
this._enabled = true;
this._initScene(rootPath, gltfContent);
this._animate();
window.addEventListener('resize', this._resizeHandler, false);
}
}