This commit is contained in:
+206
-148
@@ -12,6 +12,7 @@ import { PointerControls } from './PointerControls';
|
||||
import { ARButton } from 'three/addons/webxr/ARButton.js';
|
||||
import { XRButton } from 'three/addons/webxr/XRButton.js';
|
||||
import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
|
||||
import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
|
||||
import { Physics } from './Physics.js';
|
||||
import { Clickable } from './Clickable.js';
|
||||
import { DashBoard } from './Dashboard.js';
|
||||
@@ -26,14 +27,9 @@ const assetPath = '/asset/default/';
|
||||
const defaultLightIntensity = 22;
|
||||
|
||||
class GameEngine extends EventManager{
|
||||
async init(domNode, opts = {}) {
|
||||
this.w = domNode.clientWidth || 1200, this.h = domNode.clientHeight || 800;
|
||||
this.aspect = this.w / this.h
|
||||
this.opts = opts;
|
||||
const gameEngine = this;
|
||||
|
||||
async initScene(){
|
||||
this.perspectiveCamera = new THREE.PerspectiveCamera(45, this.aspect, 0.001, 99);
|
||||
this.raycaster = new THREE.Raycaster();
|
||||
//this.perspectiveCamera.position.set(0, 0, 10);
|
||||
|
||||
this.camera = this.perspectiveCamera;
|
||||
@@ -67,7 +63,7 @@ class GameEngine extends EventManager{
|
||||
dirLight.position.set(12, 33, -37);
|
||||
dirLight.position.multiplyScalar( 0.20 );
|
||||
// hemiLight.position.multiplyScalar( 0.20 );
|
||||
//scene.add(dirLight);
|
||||
scene.add(dirLight);
|
||||
dirLight.castShadow = true;
|
||||
dirLight.shadow.mapSize.width = 1024;
|
||||
dirLight.shadow.mapSize.height = 1024;
|
||||
@@ -82,11 +78,83 @@ class GameEngine extends EventManager{
|
||||
// const spotLight = new THREE.SpotLight(0xffffff);
|
||||
// scene.add(spotLight);
|
||||
|
||||
this.listener = new THREE.AudioListener();
|
||||
this.camera.add(this.listener);
|
||||
this.ambientSound = new THREE.Audio(this.listener);
|
||||
|
||||
this.activeObjects = new THREE.Group();
|
||||
scene.add(this.activeObjects);
|
||||
|
||||
if (this.opts.gizmo) {
|
||||
this.orbitControls = new OrbitControls(this.camera, this.renderer.domElement);
|
||||
this.orbitControls.enableZoom = false;
|
||||
const gizmo = new ViewportGizmo(this.camera, this.renderer, {
|
||||
container: '.renderer-gizmo',
|
||||
//type:'cube'
|
||||
});
|
||||
gizmo.attachControls(this.orbitControls);
|
||||
this.gizmo = gizmo;
|
||||
this.perspectiveCamera.position.set(0, 0, 10);
|
||||
this.orthographicCamera.position.set(0, 0, 100);
|
||||
this.cameraRig.rotation.y = 0;
|
||||
}
|
||||
|
||||
//const controls = new MapControls( camera, renderer.domElement );
|
||||
|
||||
if (this.opts.mode == 'GameDesigner'){
|
||||
const gameEngine = this;
|
||||
this.transformControls = new TransformControls(this.camera, this.renderer.domElement);
|
||||
this.transformControls.addEventListener('dragging-changed', function (event) {
|
||||
if (gameEngine.orbitControls){
|
||||
gameEngine.orbitControls.enabled = !event.value;
|
||||
}
|
||||
});
|
||||
scene.add(this.transformControls.getHelper());
|
||||
}else if (['GamePlay', 'GamePreview'].includes(this.opts.mode)){
|
||||
const dashboard = new DashBoard(this);
|
||||
this.dashboard = dashboard;
|
||||
dashboard.enable();
|
||||
}
|
||||
|
||||
this.pointerControls = new PointerControls(this);
|
||||
|
||||
scene.background = new THREE.Color(1, 1, 1);
|
||||
|
||||
const mixer = new THREE.AnimationMixer(this.scene);
|
||||
const clock = new THREE.Clock();
|
||||
|
||||
this.clock = clock;
|
||||
this.mixers = [mixer];
|
||||
|
||||
await this.initPhysics();
|
||||
|
||||
if (this.opts.xr){
|
||||
this.cameraRig.add(this.xrController1);
|
||||
this.cameraRig.add(this.xrController2);
|
||||
this.cameraRig.add(this.xrControllerGrip1);
|
||||
this.cameraRig.add(this.xrControllerGrip2);
|
||||
|
||||
const geometry = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, - 1)]);
|
||||
|
||||
let line = new THREE.Line(geometry);
|
||||
line.scale.z = 5;
|
||||
|
||||
this.controllerLine = line;
|
||||
}
|
||||
}
|
||||
|
||||
async init(domNode, opts = {}) {
|
||||
this.w = domNode.clientWidth || 1200, this.h = domNode.clientHeight || 800;
|
||||
this.aspect = this.w / this.h
|
||||
this.opts = opts;
|
||||
const gameEngine = this;
|
||||
this.raycaster = new THREE.Raycaster();
|
||||
|
||||
const renderer = new THREE.WebGLRenderer({
|
||||
antialias: true,
|
||||
alpha: false,
|
||||
preserveDrawingBuffer: true, //this is important for screenshots capturing
|
||||
powerPreference: "high-performance",
|
||||
//powerPreference: "high-performance",
|
||||
//precision: 'mediump'
|
||||
});
|
||||
renderer.setPixelRatio(window.devicePixelRatio);
|
||||
@@ -114,111 +182,16 @@ class GameEngine extends EventManager{
|
||||
this.motionQueue = new MotionEngine();
|
||||
this.assetPath = assetPath;
|
||||
|
||||
const dashboard = new DashBoard(this);
|
||||
this.dashboard = dashboard;
|
||||
|
||||
this.listener = new THREE.AudioListener();
|
||||
this.camera.add(this.listener);
|
||||
this.ambientSound = new THREE.Audio(this.listener);
|
||||
|
||||
this.activeObjects = new THREE.Group();
|
||||
scene.add(this.activeObjects);
|
||||
|
||||
if (opts.gizmo) {
|
||||
this.orbitControls = new OrbitControls(this.camera, renderer.domElement);
|
||||
this.orbitControls.enableZoom = false;
|
||||
const gizmo = new ViewportGizmo(this.camera, renderer, {
|
||||
container: '.renderer-gizmo',
|
||||
//type:'cube'
|
||||
});
|
||||
gizmo.attachControls(this.orbitControls);
|
||||
this.gizmo = gizmo;
|
||||
this.perspectiveCamera.position.set(0, 0, 10);
|
||||
this.orthographicCamera.position.set(0, 0, 100);
|
||||
this.cameraRig.rotation.y = 0;
|
||||
}
|
||||
|
||||
if (opts.telemetry){
|
||||
this.tm = new Telemetry(opts.telemetry, opts.mode);
|
||||
}
|
||||
|
||||
//const controls = new MapControls( camera, renderer.domElement );
|
||||
this.transformControls = new TransformControls(this.camera, renderer.domElement);
|
||||
this.transformControls.addEventListener('dragging-changed', function (event) {
|
||||
if (gameEngine.orbitControls){
|
||||
gameEngine.orbitControls.enabled = !event.value;
|
||||
}
|
||||
});
|
||||
|
||||
this.pointerControls = new PointerControls(this);
|
||||
// controls.enableDamping = true;
|
||||
// controls.screenSpacePanning = true;
|
||||
|
||||
this.renderType = 'ST';
|
||||
|
||||
|
||||
this.handleXrAction = ['ObjectPreview', 'DesignMode'].includes(opts.mode) ? this.handleXrActionDesignMode : this.handleXrActionGameMode;
|
||||
|
||||
function animate(time) {
|
||||
let delta = clock.getDelta();
|
||||
gameEngine.physics?.step();
|
||||
gameEngine.handleXrAction(gameEngine, delta);
|
||||
gameEngine.hero?.update(delta);
|
||||
gameEngine.mixers.forEach(m => m.update(delta));
|
||||
gameEngine.dispatchEvent({type: 'beforeRender'})
|
||||
gameEngine.processHideIfFar();
|
||||
this.motionQueue.update(delta);
|
||||
|
||||
gameEngine.render(scene, gameEngine.camera);
|
||||
if (!renderer.xr.isPresenting) {
|
||||
gameEngine.gizmo?.render();
|
||||
}
|
||||
// renderer.autoClear = false;
|
||||
// dashboard.render();
|
||||
// renderer.autoClear = true;
|
||||
}
|
||||
renderer.setAnimationLoop(animate.bind(this));
|
||||
|
||||
const mixer = new THREE.AnimationMixer(this.scene);
|
||||
const clock = new THREE.Clock();
|
||||
|
||||
this.clock = clock;
|
||||
|
||||
this.draco = new DRACOLoader().setDecoderPath('/3rdparty/draco/');
|
||||
this.loader = new GLTFLoader();
|
||||
this.loader.setDRACOLoader(this.draco);
|
||||
this.mixers = [mixer];
|
||||
|
||||
domNode.appendChild(renderer.domElement);
|
||||
|
||||
// let texture = await GameEngine.loadTexture('/static/textures/bck.webp', '');
|
||||
// // let bck = await this.loadTexture('/static/textures/bck.webp');
|
||||
// // bck.premultiplyAlpha = true;
|
||||
// texture.mapping = THREE.EquirectangularReflectionMapping;
|
||||
// // scene.background = bck; //new THREE.Color(0.7,0.7,0.7);
|
||||
// scene.environment = texture;
|
||||
scene.background = new THREE.Color(1, 1, 1);
|
||||
//console.log('GameEngine started')
|
||||
renderer.domElement.addEventListener('wheel', (event) => {
|
||||
event.preventDefault();
|
||||
if (gameEngine.hero){
|
||||
if (!gameEngine.pointerControls.isLocked){
|
||||
gameEngine.hero.cameraZ += event.deltaY / 100;
|
||||
}else{
|
||||
gameEngine.camera.fov += event.deltaY / 100;
|
||||
gameEngine.camera.fov = Math.min(Math.max(gameEngine.camera.fov, 0.01), 90);
|
||||
gameEngine.camera.updateProjectionMatrix();
|
||||
}
|
||||
}else{
|
||||
gameEngine.camera.zoom -= event.deltaY / (1000 / gameEngine.camera.zoom);
|
||||
gameEngine.camera.zoom = Math.max(gameEngine.camera.zoom, .01);
|
||||
//controls.rotateSpeed = 1 / Math.sqrt(gameEngine.camera.zoom);
|
||||
gameEngine.orbitControls.panSpeed = 1 / gameEngine.camera.zoom;
|
||||
gameEngine.camera.updateProjectionMatrix();
|
||||
}
|
||||
})
|
||||
|
||||
await this.initPhysics();
|
||||
|
||||
if (opts.stats){
|
||||
this.stats = new Stats();
|
||||
this.stats.dom.classList.add('engine-stats');
|
||||
@@ -250,6 +223,50 @@ class GameEngine extends EventManager{
|
||||
|
||||
this.clickable = new Clickable(this, 20);
|
||||
this.draggable = new Draggable(this, 20);
|
||||
|
||||
await this.initScene();
|
||||
|
||||
function animate(time) {
|
||||
let delta = gameEngine.clock.getDelta();
|
||||
gameEngine.physics?.step();
|
||||
gameEngine.handleXrAction(gameEngine, delta);
|
||||
gameEngine.hero?.update(delta);
|
||||
gameEngine.mixers.forEach(m => m.update(delta));
|
||||
gameEngine.dispatchEvent({type: 'beforeRender'})
|
||||
gameEngine.processHideIfFar();
|
||||
this.motionQueue.update(delta);
|
||||
|
||||
gameEngine.render(gameEngine.scene, gameEngine.camera);
|
||||
if (!renderer.xr.isPresenting) {
|
||||
gameEngine.gizmo?.render();
|
||||
}
|
||||
}
|
||||
renderer.setAnimationLoop(animate.bind(this));
|
||||
|
||||
this.loadedObjects = [];
|
||||
|
||||
domNode.appendChild(renderer.domElement);
|
||||
|
||||
renderer.domElement.addEventListener('wheel', (event) => {
|
||||
event.preventDefault();
|
||||
if (gameEngine.hero){
|
||||
if (!gameEngine.pointerControls.isLocked){
|
||||
gameEngine.hero.cameraZ += event.deltaY / 100;
|
||||
}else{
|
||||
gameEngine.camera.fov += event.deltaY / 100;
|
||||
gameEngine.camera.fov = Math.min(Math.max(gameEngine.camera.fov, 0.01), 90);
|
||||
gameEngine.camera.updateProjectionMatrix();
|
||||
}
|
||||
}else{
|
||||
gameEngine.camera.zoom -= event.deltaY / (1000 / gameEngine.camera.zoom);
|
||||
gameEngine.camera.zoom = Math.max(gameEngine.camera.zoom, .01);
|
||||
//controls.rotateSpeed = 1 / Math.sqrt(gameEngine.camera.zoom);
|
||||
gameEngine.orbitControls.panSpeed = 1 / gameEngine.camera.zoom;
|
||||
gameEngine.camera.updateProjectionMatrix();
|
||||
}
|
||||
})
|
||||
|
||||
GameEngine.ktxLoader.detectSupport(renderer);
|
||||
}
|
||||
|
||||
initXr() {
|
||||
@@ -264,7 +281,6 @@ class GameEngine extends EventManager{
|
||||
// this.session = this.renderer.xr.getSession();
|
||||
// this.session.addEventListener('selectstart', this.onControllerEvent.bind(this));
|
||||
})
|
||||
this.cameraRig.add(c1);
|
||||
|
||||
let c2 = this.renderer.xr.getController(1);
|
||||
c2.addEventListener('select', this.onSelect.bind(this));
|
||||
@@ -275,47 +291,25 @@ class GameEngine extends EventManager{
|
||||
c2.addEventListener('connected', e => {
|
||||
c2.gamepad = e.data.gamepad;
|
||||
})
|
||||
this.cameraRig.add(c2);
|
||||
|
||||
const controllerModelFactory = new XRControllerModelFactory();
|
||||
|
||||
let controllerGrip1 = this.renderer.xr.getControllerGrip(0);
|
||||
controllerGrip1.add(controllerModelFactory.createControllerModel(controllerGrip1));
|
||||
this.cameraRig.add(controllerGrip1);
|
||||
|
||||
let controllerGrip2 = this.renderer.xr.getControllerGrip(1);
|
||||
controllerGrip2.add(controllerModelFactory.createControllerModel(controllerGrip2));
|
||||
this.cameraRig.add(controllerGrip2);
|
||||
|
||||
const geometry = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, - 1)]);
|
||||
|
||||
let line = new THREE.Line(geometry);
|
||||
line.name = 'line';
|
||||
line.scale.z = 5;
|
||||
|
||||
this.controllerLine = line;
|
||||
|
||||
this.xrController1 = c1
|
||||
this.xrController2 = c2
|
||||
|
||||
this.xrControllerGrip1 = controllerGrip1;
|
||||
this.xrControllerGrip2 = controllerGrip2;
|
||||
|
||||
this.xrCamera = this.renderer.xr.getCamera();
|
||||
}
|
||||
|
||||
initCameraPivot() {
|
||||
// const pivot = new THREE.Object3D()
|
||||
// pivot.position.set(0, 0, 0)
|
||||
|
||||
// const yaw = new THREE.Object3D()
|
||||
// const pitch = new THREE.Object3D()
|
||||
|
||||
// this.scene.add(pivot)
|
||||
// pivot.add(yaw)
|
||||
// yaw.add(pitch)
|
||||
// this.scene.add(this.perspectiveCamera);
|
||||
// this.scene.add(this.orthographicCamera);
|
||||
// this.cameraPivot = pivot;
|
||||
// this.cameraYaw = yaw;
|
||||
|
||||
this.cameraWorld = new THREE.Group();
|
||||
this.cameraRig = new THREE.Group();
|
||||
this.cameraRig.add(this.perspectiveCamera);
|
||||
@@ -443,7 +437,7 @@ class GameEngine extends EventManager{
|
||||
|
||||
async load(url, path = assetPath, progress) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.loader.load(`${path}${url}`, o => {
|
||||
GameEngine.gltfLoader.load(`${path}${url}`, o => {
|
||||
o.scene.traverse(object => {
|
||||
if (object.name == 'environment' || object.material){
|
||||
//console.log('env recomputing')
|
||||
@@ -470,6 +464,7 @@ class GameEngine extends EventManager{
|
||||
object.receiveShadow = true;
|
||||
});
|
||||
resolve(o);
|
||||
this.loadedObjects.push(o);
|
||||
}, progress, reject)
|
||||
})
|
||||
}
|
||||
@@ -477,9 +472,13 @@ class GameEngine extends EventManager{
|
||||
async loadPanorama(url, path = assetPath) {
|
||||
let t = await GameEngine.loadTexture(url, path);
|
||||
t.mapping = THREE.EquirectangularReflectionMapping;
|
||||
t.generateMipmaps = false;
|
||||
t.minFilter = THREE.LinearFilter;
|
||||
this.scene.background?.dispose?.();
|
||||
this.scene.environment?.dispose?.();
|
||||
this.scene.background = t;
|
||||
//this.scene.environment = t;
|
||||
this.scene.environment = this.pmremGenerator.fromEquirectangular(t).texture;
|
||||
this.scene.environment = t;
|
||||
//this.scene.environment = this.pmremGenerator.fromEquirectangular(t).texture;
|
||||
}
|
||||
|
||||
async captureScreenshot(type = 'image/webp', quality = 80) {
|
||||
@@ -635,19 +634,6 @@ class GameEngine extends EventManager{
|
||||
})
|
||||
}
|
||||
|
||||
clearScene(){
|
||||
this.hero?.destroy();
|
||||
this.dashboard?.reset();
|
||||
this.activeObjects.clear();
|
||||
this.physics.stop();
|
||||
this.physics.clear();
|
||||
this.clickable.removeAll();
|
||||
this.motionQueue.clearAll();
|
||||
this.ambientSound.stop();
|
||||
this.tm?.setScene(null);
|
||||
this.removeAllListenersOfType('beforeRender')
|
||||
}
|
||||
|
||||
async playAmbientSound(source, path){
|
||||
let buffer = await GameEngine.loadAudio(source, path);
|
||||
this.ambientSound.setBuffer(buffer);
|
||||
@@ -671,25 +657,97 @@ class GameEngine extends EventManager{
|
||||
])
|
||||
}
|
||||
|
||||
destroy(){
|
||||
clearObject(o){
|
||||
let disposables = []
|
||||
o.traverse(object => {
|
||||
if (!object.isMesh) return;
|
||||
disposables.push(object);
|
||||
});
|
||||
disposables.forEach(object=>{
|
||||
object.removeFromParent();
|
||||
object.geometry.dispose();
|
||||
if (object.material.isMaterial) {
|
||||
this.clearMaterial(object.material)
|
||||
} else {
|
||||
for (const material of object.material) this.clearMaterial(material)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
clearMaterial(material) {
|
||||
material.dispose();
|
||||
for (const key of Object.keys(material)) {
|
||||
const value = material[key]
|
||||
if (value && typeof value == 'object' && 'minFilter' in value) {
|
||||
//console.log('Disposing', value.name, this.renderer.info.memory.textures );
|
||||
value.dispose();
|
||||
//console.log('Disposed', value.name, this.renderer.info.memory.textures );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clearScene(){
|
||||
this.hero?.dispose();
|
||||
this.dashboard?.reset();
|
||||
//this.activeObjects.clear();
|
||||
this.physics.stop();
|
||||
this.physics.clear();
|
||||
this.clickable.removeAll();
|
||||
this.gizmo?.dispose();
|
||||
this.motionQueue.clearAll();
|
||||
this.ambientSound.stop();
|
||||
this.loadedObjects.forEach(o=>this.clearObject(o.scene))
|
||||
GameEngine.loadedTextures.forEach(t=>{
|
||||
//console.log('Disposing', t.name, this.renderer.info.memory.textures );
|
||||
t.dispose();
|
||||
//console.log('Disposed', t.name, this.renderer.info.memory.textures );
|
||||
});
|
||||
this.scene.background?.dispose?.();
|
||||
this.scene.environment?.dispose?.();
|
||||
this.clearObject(this.scene);
|
||||
this.scene = null;
|
||||
this.tm?.setScene(null);
|
||||
this.removeAllListenersOfType('beforeRender');
|
||||
this.renderer.renderLists.dispose();
|
||||
this.renderer.properties.dispose();
|
||||
}
|
||||
|
||||
async resetScene(){
|
||||
this.clearScene();
|
||||
await this.initScene();
|
||||
}
|
||||
|
||||
dispose(){
|
||||
this.stop();
|
||||
this.clearScene();
|
||||
this.renderer.dispose();
|
||||
this.pmremGenerator.dispose();
|
||||
this.arBtn?.remove();
|
||||
this.xrBtn?.remove();
|
||||
this.stats?.dom?.remove();
|
||||
this.renderer.domElement.remove();
|
||||
//console.log('Engine Disposed', this.renderer.info.memory.textures );
|
||||
}
|
||||
|
||||
static textureLoader = new THREE.TextureLoader();
|
||||
static audioLoader = new THREE.AudioLoader();
|
||||
static draco = new DRACOLoader().setDecoderPath('/3rdparty/draco/');
|
||||
static gltfLoader = new GLTFLoader().setDRACOLoader(this.draco);
|
||||
static ktxLoader = new KTX2Loader().setTranscoderPath( '/3rdparty/basis/' );
|
||||
|
||||
static loadedTextures = []
|
||||
|
||||
static async loadTexture(url, path = assetPath, progress, assignTo) {
|
||||
let loader = url.toLowerCase().endsWith('.ktx2') ? GameEngine.ktxLoader : GameEngine.textureLoader;
|
||||
return new Promise((resolve, reject) => {
|
||||
GameEngine.textureLoader.load(`${path}${url}`, texture => {
|
||||
loader.load(`${path}${url}`, texture => {
|
||||
texture.colorSpace = THREE.SRGBColorSpace;
|
||||
texture.name = url;
|
||||
if (assignTo){
|
||||
assignTo[0][assignTo[1]] = texture;
|
||||
}
|
||||
resolve(texture)
|
||||
GameEngine.loadedTextures.push(texture);
|
||||
}, progress, reject)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user