voxel/scene.js

96 lines
2.7 KiB
JavaScript
Raw Normal View History

2022-04-10 12:42:24 -04:00
import * as T from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
2021-07-07 07:00:50 -04:00
export function Scene(inSettings)
{
const renderer = new T.WebGLRenderer({canvas:document.querySelector(inSettings.DOM)});
const scene = new T.Scene();
2021-07-11 09:24:39 -04:00
const camera = new T.PerspectiveCamera(80, 2, 0.1, 100);
2021-07-07 07:00:50 -04:00
const light = new T.DirectionalLight(0xFFFFFF, 1);
const controls = new OrbitControls(camera, renderer.domElement);
let dirty = false;
2021-07-15 14:41:17 -04:00
const Screen = {
Dirty:false,
Drag:0,
Down:false,
Ray:new T.Raycaster(),
Mouse:new T.Vector2(),
Camera:camera,
Event:null,
Update:e=>
{
Screen.Event = e;
Screen.Dirty = true;
Screen.Mouse.x = ( e.clientX / renderer.domElement.clientWidth ) * 2 - 1;
Screen.Mouse.y = - ( e.clientY / renderer.domElement.clientHeight ) * 2 + 1;
Screen.Ray.setFromCamera( Screen.Mouse, Screen.Camera );
},
HandleMove:e=>
{
Screen.Drag = Screen.Down ? 2 : 0;
Screen.Update(e);
},
HandlePress:e=>
{
Screen.Down = true;
Screen.Drag = 1;
Screen.Update(e);
},
HandleRelease:e=>
{
Screen.Down = false;
Screen.Drag = 0;
Screen.Update(e);
}
};
renderer.domElement.addEventListener("pointermove", Screen.HandleMove);
renderer.domElement.addEventListener("pointerdown", Screen.HandlePress);
renderer.domElement.addEventListener("pointerup", Screen.HandleRelease);
2021-07-07 07:00:50 -04:00
const update = inTime =>
{
let timeNew = new Date();
let timeDelta = timeNew - inTime;
let delta = timeDelta * 0.001;
2021-07-15 14:41:17 -04:00
inSettings.Update(scene, Screen, delta);
Screen.Dirty = false;
2021-07-07 07:00:50 -04:00
controls.update();
dirty = true;
setTimeout(()=>update(timeNew), 50);
}
const render = inTime =>
{
if(dirty)
{
renderer.render(scene, camera);
dirty = false;
}
requestAnimationFrame(render);
}
const resize = () =>
{
let canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
};
scene.add(light);
light.position.set(-1, 2, 4);
2021-07-11 18:28:00 -04:00
camera.position.set(-1, 2, -1);
2021-07-11 09:24:39 -04:00
camera.lookAt(new T.Vector3(0,0,0));
2021-07-07 07:00:50 -04:00
controls.update();
inSettings.Init(scene);
window.addEventListener("resize", resize);
resize();
render(0);
update(new Date());
};