-
Notifications
You must be signed in to change notification settings - Fork 65
/
scene.js
352 lines (294 loc) Β· 10.4 KB
/
scene.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
/*
* Things that handle all the 3D stuff
*/
import { EffectComposer, RenderPass } from "postprocessing";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { STLExporter } from "three/examples/jsm/exporters/STLExporter";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import {
ENVIRONMENT_ANIMATED_ASSET,
ENVIRONMENT_ASSET,
ENVIRONMENT_OBJECTS_ASSET,
FLOOR_HEIGHT,
GRASS_ASSET,
ROAD_TYPES,
TREES_SMALL,
} from "./constants";
// Global GLTF loader
const loader = new GLTFLoader();
export function createScene() {
// Create scene
const scene = new THREE.Scene();
const camera = createCamera();
const renderer = createRenderer(scene, camera);
setupLighting(scene);
const updateMixer = setupEnvironment(scene);
const controls = createControls(camera, renderer);
const composer = setupPostProcessing(scene, camera, renderer);
const clock = new THREE.Clock();
// Animation loop
function animate() {
const delta = clock.getDelta();
requestAnimationFrame(animate);
controls.update();
updateMixer(delta);
composer.render();
}
animate();
// Resize renderer when window size changes
window.onresize = () => {
resizeRenderer(renderer);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
};
return { scene, controls };
}
export function clearScene(scene) {
const toDelete = ["Building", "Road", "Grass", "Tree"];
for (let i = scene.children.length - 1; i >= 0; i--) {
if (toDelete.includes(scene.children[i].name))
scene.remove(scene.children[i]);
}
}
export function changeShadowPreset(scene, preset) {
for (const child of scene.children) {
if (child.type === "DirectionalLight") {
if (typeof preset === "string") preset = parseInt(preset);
if (preset === 1) {
child.shadow.mapSize.x = 768;
child.shadow.mapSize.y = 768;
child.shadow.map.dispose();
child.shadow.map = null;
} else if (preset === 2) {
child.shadow.mapSize.x = 2048;
child.shadow.mapSize.y = 2048;
child.shadow.map.dispose();
child.shadow.map = null;
}
}
}
}
// Set shadows on given object to given settings
function setShadow(obj, cast = false, receive = false) {
obj.castShadow = cast;
obj.receiveShadow = receive;
if (obj?.children != null) {
for (const child of obj.children) {
setShadow(child, cast, receive);
}
}
}
export function renderBuilding(x, y, z, building, scene) {
const height = Math.min(building.value, 35); // Cap height
for (let i = 0; i < height; i++) {
let assetToLoad = "";
if (i === 0)
assetToLoad = building.building.groundUrl; // Load ground tile
else if (i === height - 1)
assetToLoad = building.building.roofUrl; // Load roof tile
else assetToLoad = building.building.floorUrl; // Load floor tile
if (assetToLoad == null || assetToLoad === "") return;
loader.load(
`./assets/${assetToLoad}`,
function (gltf) {
const isLShaped = building.type === 2;
let extraShiftZ = 0;
let extraShiftX = 0;
if (isLShaped && building.dir === 1) {
extraShiftZ = 2;
extraShiftX = 2;
}
let extraAngle = 0;
setShadow(gltf.scene, true, false);
gltf.scene.name = "Building";
if (building.mirror) {
gltf.scene.scale.z *= -1; // mirror the object
extraAngle = 270; // add extra angle to compensate shift from mirroring
}
gltf.scene.position.y = y + i * FLOOR_HEIGHT * 2;
gltf.scene.position.x = x + extraShiftX;
gltf.scene.position.z = z + extraShiftZ;
gltf.scene.rotation.y = THREE.Math.degToRad(
-90 * (building.dir + (isLShaped ? 2 : 0)) - extraAngle,
);
scene.add(gltf.scene);
},
undefined,
function (error) {
console.error(error);
},
);
}
}
export function renderRoad(x, y, z, road, scene) {
let assetToLoad = "";
if (road.type === 0) assetToLoad = ROAD_TYPES[0]; // 2 way road
else if (road.type === 1) assetToLoad = ROAD_TYPES[1]; // 3 way road
else if (road.type === 2) assetToLoad = ROAD_TYPES[2]; // 4 way road
else if (road.type === 3) assetToLoad = ROAD_TYPES[3]; // 2 way turn
if (assetToLoad == null || assetToLoad === "") return;
loader.load(
`./assets/${assetToLoad}`,
function (gltf) {
gltf.scene.position.y = y;
gltf.scene.position.x = x;
gltf.scene.position.z = z;
gltf.scene.rotation.y = THREE.Math.degToRad(-90 * road.dir);
setShadow(gltf.scene, false, true);
gltf.scene.name = "Road";
scene.add(gltf.scene);
},
undefined,
function (error) {
console.error(error);
},
);
}
export function renderGrass(x, y, z, scene) {
const assetToLoad = GRASS_ASSET;
loader.load(
`./assets/${assetToLoad}`,
function (gltf) {
gltf.scene.position.y = y;
gltf.scene.position.x = x;
gltf.scene.position.z = z;
setShadow(gltf.scene, false, true);
gltf.scene.name = "Grass";
scene.add(gltf.scene);
},
undefined,
function (error) {
console.error(error);
},
);
// Create a tree somewhere on the tile
for (const i of [-0.7, 0.7]) {
loader.load(
`./assets/${
TREES_SMALL[Math.floor(TREES_SMALL.length * Math.random())]
}`,
function (gltf) {
gltf.scene.position.x = x + Math.random() * i;
gltf.scene.position.y = y;
gltf.scene.position.z = z + Math.random() * i;
setShadow(gltf.scene, true, false);
gltf.scene.name = "Tree";
scene.add(gltf.scene);
},
);
}
}
// Convert given scene into STL blob
export function convertSceneToStlBlob(scene) {
const exporter = new STLExporter();
const str = exporter.parse(scene);
return new Blob([str], { type: "text/plain" });
}
// Create and cofigure camera and return it
function createCamera() {
const camera = new THREE.PerspectiveCamera(
50,
window.innerWidth / window.innerHeight,
0.1,
400,
);
camera.position.set(0, 30, 51);
return camera;
}
// Create and configure renderer and return it
function createRenderer(scene, camera) {
const renderer = new THREE.WebGLRenderer({
powerPreference: "high-performance",
antialias: true,
depth: true,
canvas: document.querySelector("#bg"),
});
resizeRenderer(renderer);
renderer.render(scene, camera);
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
return renderer;
}
// Set's the renderers size to current window size
function resizeRenderer(renderer) {
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Create and configure controls and return it
function createControls(camera, renderer) {
const controls = new OrbitControls(camera, renderer.domElement);
controls.autoRotate = true;
controls.autoRotateSpeed = -1;
controls.enableDamping = true;
controls.dampingFactor = 0.1;
controls.enablePan = false;
controls.minDistance = 30;
controls.maxDistance = 150;
return controls;
}
// Configure postprocessing and return composer
function setupPostProcessing(scene, camera, renderer) {
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
return composer;
}
// Create and configure lighting in the scene
function setupLighting(scene) {
// Ambient lighting
const ambientLight = new THREE.AmbientLight(0x9ad0ec, 0.7);
// const ambientLight = new THREE.AmbientLight(0x9AD0EC, 1);
scene.add(ambientLight);
// Directional lighting and shadows
const directionLight = new THREE.DirectionalLight(0xe9b37c);
directionLight.position.set(-50, 50, -20);
directionLight.castShadow = true;
directionLight.shadow.mapSize.x = 768;
directionLight.shadow.mapSize.y = 768;
directionLight.shadow.camera.near = 15;
directionLight.shadow.camera.far = 150.0;
directionLight.shadow.camera.right = 75;
directionLight.shadow.camera.left = -75;
directionLight.shadow.camera.top = 75;
directionLight.shadow.camera.bottom = -75;
scene.add(directionLight);
}
// Create and setup anything environment-related
function setupEnvironment(scene) {
const sceneBackground = new THREE.Color(0x9ad0ec);
scene.background = sceneBackground;
const position = new THREE.Vector3(0, -4, 0);
// Render environment (ground)
loader.load(`./assets/${ENVIRONMENT_ASSET}`, function (gltf) {
const env = gltf.scene;
env.position.set(...position);
setShadow(gltf.scene, false, true);
scene.add(env);
});
// Render environment (objects and other stuff)
loader.load(`./assets/${ENVIRONMENT_OBJECTS_ASSET}`, function (gltf) {
const envObjects = gltf.scene;
envObjects.position.set(...position);
setShadow(gltf.scene, true, false);
scene.add(envObjects);
});
// Render and animate animated environment
let mixer;
const updateMixer = (delta) => {
if (mixer) mixer.update(delta);
};
loader.load(`./assets/${ENVIRONMENT_ANIMATED_ASSET}`, function (gltf) {
const envAnimated = gltf.scene;
envAnimated.position.set(...position);
setShadow(gltf.scene, true, false);
// Setup animation mixer and play all animations
mixer = new THREE.AnimationMixer(envAnimated);
const clips = gltf.animations;
clips.forEach(function (clip) {
mixer.clipAction(clip).play();
});
scene.add(envAnimated);
});
return updateMixer;
}