-
Notifications
You must be signed in to change notification settings - Fork 0
/
GrWorld.js
721 lines (654 loc) · 24.8 KB
/
GrWorld.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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
/*jshint esversion: 11 */
// @ts-check
/**
* CS559 3D World Framework Code
*
* GrWorld - bascially a wrapper around scene, except that it uses
* GrObject instead of Object3D (GrObjects have Object3D)
*
* To make things simple, this keeps a renderer and a default camera.
* Of course, that might complicate things if you want to have multiple
* renderers and cameras
*
* Basically, this keeps some of the basic stuff you need when you use
* three.
* @module GrWorld
* */
// we need to have the BaseClass definition
import { GrObject } from "./GrObject.js";
import { insertElement } from "../CS559/inputHelpers.js";
import { SimpleGroundPlane } from "./GroundPlane.js";
import * as T from "../CS559-Three/build/three.module.js";
import { OrbitControls } from "../CS559-Three/examples/jsm/controls/OrbitControls.js";
import { FlyControls } from "../CS559-Three/examples/jsm/controls/FlyControls.js";
import { VRHelper } from './VRHelper.js'
import Stats from './Stats.js'
// alert("look at TODO in GrWorld");
/** Things to do post 2021 TODO
* Better handling of rideable (let use controls)
* Better documentation (make it so that GrObject parameters show up)
* Convert to always use BufferGeometry (since Geometry is deprecated)
* glTF loader
* */
/**
* Document the parameters for making a world - all are optional
* we'll guess at something if you don't give it to us
* @typedef GrWorldProperties
* @property [camera] - use this camera if passed
* @property [fov] - camera property if we make one
* @property [near] - camera property if we make one
* @property [far] - camera property if we make one
* @property [renderer] - if you don't give one, we'll make it
* @property [renderparams] - parameters for making the renderer
* @property [width] - canvas size
* @property [height] - canvas size
* @property [where] - where in the DOM to insert things
* @property [lights] - a list of lights, or else default ones are made
* @property [lightBrightness=.75] - brightness of the default lights
* @property [lightColoring="cool-to-warm"] - either "c"ool-to-warm, "w"hite, or e"x"treme
* @property [sideLightColors] - to make extreme lighting
* @property [ambient=.5] - brightness of the ambient light in default light
* @property [groundplane] - can be a groundplane, or False (otherwise, one gets made)
* @property [groundplanecolor="green"] - if we create a ground plane, what color
* @property [groundplanesize=5] - if we create a ground plane, how big
* @property [lookfrom] - where to put the camera (only if we make the camera)
* @property [lookat] - where to have the camera looking (only if we make the camera)
* @property [background="black"] - color to set the background
* @property {HTMLInputElement} [runbutton] - a checkbox (HTML) to switch things on or off (can be undefined)
* @property {HTMLInputElement} [speedcontrol] - a slider to get the speed (must be an HTML element, not a LabelSlider)
*/
/** @class GrWorld
*
* The GrWorld is basically a wrapper around THREE.js's `scene`,
* except that it keeps a list of `GrObject` rather than `Object3D`.
*
* It contains a `scene` (and it puts things into it for you).
* It also contains a `renderer` and a `camera`.
*
* When this creates a renderer, it places it into the dom (see the `where` option).
*
* By default, the world is created with a reasonable default `renderer`,
* `camera` and `groundplane`. Orbit controls are installed.
*/
export class GrWorld {
/**
* Construct an empty world
* @param {GrWorldProperties} params
*/
constructor(params = {}) {
/** @type {Number} */
this.objCount = 0;
/** @type {Number} */
this.animCount = 0;
// mainly a set for checking object name legality
/** @type {Object} */
this.objNames = {};
// this keeps a list of objects in the world
/** @type Array<GrObject> */
this.objects = [];
// the GrWorld "has a" of the main things we need in three
this.scene = new T.Scene();
this.solo_scene = new T.Scene(); // secondary scene for showing a solo object.
this.active_scene = this.scene; // active scene to draw.
this.scene.background = new T.Color(params.background ? params.background : "black")
// make a renderer if it isn't given
/** @type THREE.WebGLRenderer */
this.renderer =
"renderer" in params
? params.renderer
: new T.WebGLRenderer(
"renderparams" in params ? params.renderparams : {}
);
// width and height are tricky, since they can come from many places
let width = 600;
let height = 400;
// if the renderer was given, get its DOM
if ("renderer" in params) {
width = params.renderer.domElement.width;
height = params.renderer.domElement.height;
} else if ("renderparams" in params && "canvas" in params.renderparams) {
width = params.renderparams.canvas.width;
height = params.renderparams.canvas.height;
}
// specified width/height overrides everything
if ("width" in params) {
width = params.width;
}
if ("height" in params) {
height = params.height;
}
// get the light brightnesses
if (!("lightBrightness" in params)) params.lightBrightness = 0.75;
if (!("ambient" in params)) params.ambient = 0.5;
// make things be the right size
this.renderer.setSize(width, height);
// make a groundplane (or install a given one)
// we do this before we made the camera, since it's useful for placing the camera
if ("groundplane" in params) {
this.groundplane = params.groundplane;
} else {
// the default is to create a groundplane
this.groundplane = new SimpleGroundPlane(
params.groundplanesize || 5,
0.2,
params.groundplanecolor || "darkgreen"
);
}
if (this.groundplane)
this.add(this.groundplane);
// we need this variable out here since we need to refer to it later
let lookat = params.lookat;
// make a camera
/** @type {THREE.PerspectiveCamera} */
this.camera = undefined;
if ("camera" in params) {
this.camera = params.camera;
} else {
this.camera = new T.PerspectiveCamera(
"fov" in params ? params.fov : 45,
width / height,
"near" in params ? params.near : 0.1,
"far" in params ? params.far : 2000
);
/* figure out a default lookat */
if (!("lookat" in params)) {
lookat = new T.Vector3(0, 0, 0);
}
let lookfrom = params.lookfrom;
if (!("lookfrom" in params)) {
let gpSize = this.groundplane ? this.groundplane.size : 10;
lookfrom = new T.Vector3(gpSize / 2, gpSize, gpSize * 2);
}
this.camera.position.copy(lookfrom);
this.camera.lookAt(lookat);
this.camera.name = "World Camera";
}
this.active_camera = this.camera;
// create a camera for viewing a solo object.
// This isn't something the user should worry about, so values are set directly.
this.solo_camera = new T.PerspectiveCamera(45, width / height, 0.1, 2000);
this.solo_camera.name = "Solo Camera";
this.solo_camera.position.set(1, 1, 1);
// make the controls
if (this.active_camera.isPerspectiveCamera) {
this.orbit_controls = new OrbitControls(
this.active_camera,
this.renderer.domElement
);
this.orbit_controls.keys = { UP: 87, BOTTOM: 83, LEFT: 65, RIGHT: 68 };
this.orbit_controls.target = lookat;
// We also want a pointer to active set of controls.
this.active_controls = this.orbit_controls;
this.fly_controls = new FlyControls(
this.active_camera,
this.renderer.domElement
);
this.fly_controls.dragToLook = true;
this.fly_controls.rollSpeed = 0.1;
this.fly_controls.dispose();
let flySaveState = function () {
this.position0 = new T.Vector3(
this.object.position.x,
this.object.position.y,
this.object.position.z
);
};
let flyReset = function () {
if (this.position0) {
this.object.position.set(
this.position0.x,
this.position0.y,
this.position0.z
);
}
this.update(0.1);
};
let register = function () {
function bind(scope, fn) {
return function () {
fn.apply(scope, arguments);
};
}
this.domElement.addEventListener(
"mousemove",
bind(this, this.mousemove),
false
);
this.domElement.addEventListener(
"mousedown",
bind(this, this.mousedown),
false
);
this.domElement.addEventListener(
"mouseup",
bind(this, this.mouseup),
false
);
window.addEventListener("keydown", bind(this, this.keydown), false);
window.addEventListener("keyup", bind(this, this.keyup), false);
};
if (!this.fly_controls.saveState) {
this.fly_controls.saveState = flySaveState;
this.fly_controls.reset = flyReset;
}
if (!this.fly_controls.register) {
this.fly_controls.register = register;
}
} // only make controls for PerspectiveCameras
// if we either specify where things go in the DOM or we made our
// own canvas, install it
if (
"where" in params ||
!("renderer" in params) ||
"renderparams" in params
) {
insertElement(
this.renderer.domElement,
"where" in params ? params.where : undefined
);
}
/**
* Some Lights
*/
if ("lights" in params) {
if (params.lights.length) {
params.lights.forEach(light => this.scene.add(light));
}
this.ambient = undefined;
} else {
this.ambient = new T.AmbientLight("white", params.ambient);
this.scene.add(this.ambient);
// colors for the three "key" lights - maybe be overridden with sideLightColors
let leftColor = 0xffffff;
let rightColor = 0xffffff;
let bottomColor = 0xffffff;
switch ((params.lightColoring || "cool-to-warm")[0]) {
case "c": // cool to warm
case "C":
leftColor = 0xfff0c0;
rightColor = 0xc0f0ff;
bottomColor = 0xffc0ff;
break;
case "x": // extremely cool to wam
case "X":
case "e":
case "E":
leftColor = 0xffe080;
rightColor = 0x80e0ff;
bottomColor = 0xff80ff;
break;
case "W":
case "w":
break;
default:
console.log(
`Bad coloring ${params.lightColoring} to GrWorld - assuming white`
);
}
// three lights - all a little off white to give some contrast
let leftLight = params.sideLightColors
? params.sideLightColors[0]
: leftColor;
let rightLight = params.sideLightColors
? params.sideLightColors[1]
: rightColor;
let dirLight1 = new T.DirectionalLight(leftLight, params.lightBrightness);
dirLight1.position.set(1, 1, -0.4);
this.scene.add(dirLight1);
let dirLight2 = new T.DirectionalLight(
rightLight,
params.lightBrightness
);
dirLight2.position.set(-1, 1, -0.4);
this.scene.add(dirLight2);
let bottomLight = new T.DirectionalLight(
bottomColor,
params.lightBrightness / 3
);
bottomLight.position.set(0, -1, 0.1);
this.scene.add(bottomLight);
}
// add a pair of lights to the "solo" scene as well.
this.solo_scene.add(new T.AmbientLight(0xfffff8, 0.6));
this.solo_scene.add(new T.DirectionalLight(0xf8f8ff, 1.0));
// Keep track of rendering timings
this.lastRenderTime = 0;
this.lastTimeOfDay = 12;
// Track the "active" object, which we may follow, view solo, etc.
/**@type GrObject */
this.active_object = undefined;
this.solo_mode = false;
this.view_mode = "Orbit Camera";
// Have a switch for turning things on and off
/** @type {HTMLInputElement} */
this.runbutton = params.runbutton;
/** @type {HTMLInputElement} */
this.speedcontrol = params.speedcontrol;
} // end of constructor
restoreActiveObject() {
if (this.active_object) {
// In case we were in drive mode, make the active object visible.
let showObject = function (ob) {
ob.visible = true;
ob.children.forEach(child => {
showObject(child);
});
};
this.active_object.objects.forEach(ob => {
showObject(ob);
});
// In case we were in solo mode, put the active object back in the main scene.
this.active_object.objects.forEach(element => {
this.scene.add(element);
});
}
}
setActiveObject(name) {
// Restore the previous object before setting a new one.
this.restoreActiveObject();
// We assume each object has a unique name to search on.
this.active_object = this.objects.find(ob => ob.name === name);
// In case we are already in an object-centric mode, focus on the new active object.
this.currentStateOn();
if (this.solo_mode) {
this.showSoloObject();
}
}
currentStateOff() {
switch (this.view_mode) {
case "Orbit Camera":
this.orbitControlOff();
break;
case "Fly Camera":
this.flyControlOff();
break;
case "Follow Object":
this.followObjectOff();
break;
case "Drive Object":
this.driveObjectOff();
break;
default:
break;
}
}
currentStateOn() {
switch (this.view_mode) {
case "Orbit Camera":
this.orbitControlOn();
break;
case "Fly Camera":
this.flyControlOn();
break;
case "Follow Object":
this.followObjectOn();
break;
case "Drive Object":
this.driveObjectOn();
break;
default:
break;
}
}
setViewMode(mode) {
// first, turn off old mode.
if (this.active_object) {
this.restoreActiveObject();
}
this.currentStateOff();
// then, turn on new mode.
this.view_mode = mode;
if (this.solo_mode) {
this.showSoloObject();
} else {
this.showWorld();
}
this.currentStateOn();
}
showSoloObject() {
this.solo_mode = true;
// put active object in solo scene, and render the solo scene.
this.active_object.objects.forEach(element => {
this.solo_scene.add(element);
});
this.orbit_controls.object = this.solo_camera;
this.fly_controls.object = this.solo_camera;
this.active_camera = this.solo_camera;
this.active_scene = this.solo_scene;
this.currentStateOn();
}
showWorld() {
this.solo_mode = false;
if (this.active_object) {
this.active_object.objects.forEach(element => {
this.scene.add(element);
});
} else {
console.warn("No active object when expecting one!");
}
this.orbit_controls.object = this.camera;
// this.orbit_controls.update();
if (this.fly_controls) {
this.fly_controls.object = this.camera;
}
this.active_camera = this.camera;
this.active_scene = this.scene;
this.currentStateOn();
}
orbitControlOn() {
this.orbit_controls.enabled = true;
if (this.solo_mode && this.active_object) {
let camparams = this.active_object.lookFromLookAt();
this.solo_camera.position.set(camparams[0], camparams[1], camparams[2]);
this.active_camera.lookAt(camparams[3], camparams[4], camparams[5]);
// set controls to use whatever the active camera is, and position so it can see the active object.
this.orbit_controls.target.set(camparams[3], camparams[4], camparams[5]);
this.orbit_controls.update();
} else {
// @ts-ignore
this.orbit_controls.reset();
}
}
orbitControlOff() {
if (!this.solo_mode) {
// @ts-ignore
this.orbit_controls.saveState();
}
this.orbit_controls.enabled = false;
}
flyControlOn() {
if (this.solo_mode && this.active_object) {
let camparams = this.active_object.lookFromLookAt();
this.solo_camera.position.set(camparams[0], camparams[1], camparams[2]);
this.active_camera.lookAt(camparams[3], camparams[4], camparams[5]);
} else {
// @ts-ignore
this.fly_controls.reset();
}
this.fly_controls.register();
}
flyControlOff() {
if (!this.solo_mode) {
// @ts-ignore
this.fly_controls.saveState();
}
this.fly_controls.dispose();
}
followObjectOn() {
if (this.active_object.rideable) {
this.active_object.rideable.add(this.solo_camera);
this.active_object.rideable.add(this.camera);
let bbox = new T.Box3();
bbox.setFromObject(this.active_object.objects[0]);
this.camera.position.set(
0,
bbox.max.y - bbox.min.y,
-1.5 * (bbox.max.z - bbox.min.z)
);
this.solo_camera.position.set(
0,
bbox.max.y - bbox.min.y,
-1.5 * (bbox.max.z - bbox.min.z)
);
// Set look direction
let target = this.active_object.objects[0].position;
this.camera.lookAt(target);
this.solo_camera.lookAt(target);
} else {
this.followObjectOff();
}
}
followObjectOff() {
this.scene.add(this.camera);
this.solo_scene.add(this.solo_camera);
}
driveObjectOn() {
if (this.active_object.rideable) {
let hideObject = function (ob) {
ob.visible = false;
ob.children.forEach(child => {
hideObject(child);
});
};
this.active_object.rideable.add(this.solo_camera);
this.active_object.rideable.add(this.camera);
this.camera.position.set(0, 0, 0);
this.camera.rotation.set(0, Math.PI, 0);
this.solo_camera.position.set(0, 0, 0);
this.solo_camera.rotation.set(0, Math.PI, 0);
this.active_object.objects.forEach(ob => {
hideObject(ob);
});
} else {
this.driveObjectOff();
}
}
driveObjectOff() {
this.restoreActiveObject();
this.scene.add(this.camera);
this.solo_scene.add(this.solo_camera);
}
/**
* Add an object to the world - this takes care of putting everything
* into the scene, as well as assigning IDs
* @param {GrObject} grobj
*/
add(grobj) {
if (grobj.id) {
console.warn(
`Adding GrObj that already has an assigned ID. Object named "${grobj.name}"`
);
} else {
grobj.id = this.objCount++;
}
if (grobj.name in this.objNames) {
console.warn(
`Adding GrObj with non-unique name. Object named "${grobj.name}"`
);
} else {
this.objNames[grobj.name] = grobj;
}
this.objects.push(grobj);
// be sure to add all the objects to the scene
grobj.objects.forEach(element => {
this.scene.add(element);
});
}
/**
* adds performance stats to the DOM
*/
viewStats() {
this.stats = Stats();
this.stats.setMode(0);
this.stats.dom.style.position = 'absolute';
this.stats.dom.style.left = '0';
this.stats.dom.style.top = '0';
document.body.appendChild( this.stats.dom );
}
/**
* adds VR capability
*/
enableVR() {
this.VRHelper = new VRHelper({
renderer: this.renderer,
scene: this.scene,
camera: this.camera,
flightSpeed: 10,
})
}
/**
* draw the default camera to the default renderer
*/
draw() {
this.lastRenderTime = performance.now();
this.renderer.render(this.active_scene, this.active_camera);
}
/**
* advance all of the objects
*/
stepWorld(delta, timeOfDay) {
this.objects.forEach(obj => obj.stepWorld(delta, timeOfDay));
}
/** callback list - used in 2 places, so document once
* @typedef {Object} WorldCallbacks
* @property {function} [prefirst] - called before the first loop go around
* @property {function} [prestep] - called before the step (even if there is no step)
* @property {function} [stepWorld] - called after the step (only if there is a step)
* @property {function} [predraw] - called before drawing (after the step - if there is one)
* @property {function} [postdraw] - called after drawing
* @property {function} [first] - called after the end of the first loop go-around
*
*/
/**
* perform a cycle of the animation loop - this measures the time since the
* last redraw and advances that much before redrawing
*
* because draw is part of animate, the callbacks are handled here
*
* @param {WorldCallbacks} [callbacks]
*/
animate(callbacks = {}) {
if (!this.animCount && callbacks.prefirst) { callbacks.prefirst(this); }
if (callbacks.prestep) callbacks.prestep(this);
if (!this.runbutton || this.runbutton.checked) {
let delta = performance.now() - this.lastRenderTime;
let speed = this.speedcontrol ? Number(this.speedcontrol.value) : 1.0;
this.stepWorld(delta * speed, this.lastTimeOfDay);
if (callbacks.stepWorld) callbacks.stepWorld(this);
}
// since we're already running an animation loop, update view controls here.
// Pass in a delta since that's what fly controls want. Orbit controls can just ignore.
if ((this.view_mode == "Orbit Camera") && this.orbit_controls) {
this.orbit_controls.update();
}
else if ((this.view_mode == "Fly Camera") && this.fly_controls) {
this.fly_controls.update(0.1);
}
this.VRHelper?.update()
if (callbacks.predraw) callbacks.predraw(this);
this.draw();
if (callbacks.postdraw) callbacks.postdraw(this);
if (!this.animCount && callbacks.first) { callbacks.first(this); }
this.animCount += 1;
}
/**
* start an (endless) animation loop - this just keeps going
*
*
* @param {WorldCallbacks} callbacks
*/
go(callbacks = {}) {
let count = 0;
// remember, this gets redefined (it doesn't follow scope rules)
let self = this;
function loop() {
self.stats?.begin()
self.animate(callbacks);
count += 1;
self.stats?.end()
// self.draw(); // animate does the draw
self.renderer.setAnimationLoop(loop)
}
loop();
}
}