scaenae/js/scene.js
Nicolò P. 8434f3bdc9 Draggable clipping plane (buggy...)
TODO: refactor to avoid unnecessary object creation
2026-01-07 16:55:32 +01:00

506 lines
18 KiB
JavaScript

// Global ATON
import { AppState, getSceneStatus, setSceneStatus, getCurrentScene, setCurrentScene } from "./state.js";
import { config } from "../config.js";
const Scene = {};
Scene.UI = {};
Scene.UI.domParser = new DOMParser;
/**
* Resets the UI state (essentially hides the clipper toolbar if visible...)
* @todo Other elements to reset?? Restore inital lighting conditions and viewpoint...
*/
Scene.UI.reset = function() {
document.querySelector('#clipper-bar')?.classList.add('d-none');
document.querySelector('#clipper')?.classList.remove('border', 'border-2', 'border-white');
}
/**
* @todo Get clipping button from state? Review logic!!
* @param {String} triggerSelector
* @param {String} targetSelector The selector for the target toolbar to be displayed
*/
Scene.UI.toggleClipper = function(triggerSelector, targetSelector) {
const trigger = document.querySelector(triggerSelector);
const toolbar = document.querySelector(targetSelector);
if (!AppState.clipping.listeners.button) {
trigger.addEventListener(
'click',
() => {
console.log('Clipping enabled?', AppState.clipping.enabled);
toolbar.classList.toggle('d-none');
const aoCurrentState = AppState.ambientOcclusion;
if (!AppState.clipping.enabled) {
AppState.clipping.enabled = true;
Scene.toggleAmbientOcclusion(false);
const btns = toolbar.querySelectorAll('button');
btns.forEach(btn => {
btn.classList.remove('border', 'border-2', 'border-warning');
});
trigger.className += ' border border-2 border-white';
toolbar.addEventListener('click', event => {
console.log('Clipping target:', event.target);
if (event.target.id === 'clipX') {
// Clip along X...
Scene.addClippingPlane('x', -1);
// Export to function...
event.target.classList.add('border', 'border-2', 'border-warning');
btns.forEach(btn => {
if (btn.id !== event.target.id) {
btn.classList.remove('border', 'border-2', 'border-warning');
}
});
}
else if (event.target.id === 'clipY') {
// Clip along Y...
Scene.addClippingPlane('y', -1);
event.target.classList.add('border', 'border-2', 'border-warning');
btns.forEach(btn => {
if (btn.id !== event.target.id) {
btn.classList.remove('border', 'border-2', 'border-warning');
}
})
}
else if (event.target.id === 'clipZ') {
// Clip along Z...
Scene.addClippingPlane('z', 1);
event.target.classList.add('border', 'border-2', 'border-warning');
btns.forEach(btn => {
if (btn.id !== event.target.id) {
btn.classList.remove('border', 'border-2', 'border-warning');
}
})
}
});
} else {
AppState.clipping.enabled = false;
ATON.disableClipPlanes();
AppState.root.remove(AppState.clipping.helper);
AppState.clipping.helper = null;
let noBorder = trigger.className.replace(/ border.*$/g, '');
trigger.className = noBorder;
Scene.toggleAmbientOcclusion(aoCurrentState);
}
}
);
AppState.clipping.listeners.button = true;
}
}
/**
* @todo Experimental...
* @param {THREE.Object3D} object - A THREE Object3D instance
*/
Scene.showEdges = function(object) {
const edgeMaterial = new THREE.LineBasicMaterial( { color: 0x000000 } );
object.traverse(function(child) {
if (child.isMesh) {
let edges = new THREE.EdgesGeometry(child.geometry, 45);
let line = new THREE.LineSegments(edges, edgeMaterial);
child.add(line);
console.log(child);
}
});
}
/**
* Calculate bounding box for the scene root object
* and return it along with its center and size (bad?).
* It only uses meshes to prevent "empty" nodes in the scene
* from being included in the calculation.
* @todo Use ATON.Node.getBound()? [bounding sphere]
*/
Scene.getRootBoundingBox = function() {
const meshes = [];
AppState.root.traverse(obj => {
if (obj.isMesh) meshes.push(obj);
});
if (meshes.length === 0) return null;
const bbox = new THREE.Box3().setFromObject(meshes[0]);
for (let i = 1; i < meshes.length; i++) {
bbox.union(new THREE.Box3().setFromObject(meshes[i]));
}
const center = bbox.getCenter(new THREE.Vector3());
const size = bbox.getSize(new THREE.Vector3());
return { bbox, center, size };
}
/**
*
* @param {THREE.Vector3} rootBBoxSize - The size of the bounding box for the root object
* @returns {THREE.Mesh}
*/
Scene.createClippingPlaneMesh = function(rootBBoxSize) {
//const averageDim = (Number(rootBBoxSize.x) + Number(rootBBoxSize.y) + Number(rootBBoxSize.z)) / 3;
const planeSize = rootBBoxSize.length() * 1.2;
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(planeSize, planeSize),
new THREE.MeshBasicMaterial({ color: 0xffff00, opacity: 0.1, side: THREE.DoubleSide, transparent: true })
);
return mesh;
}
/**
*
* @param {THREE.Mesh} planeMesh
* @param {String} axis
*/
Scene.dragClipper = function(planeMesh, axis) {
const controls = new THREE.DragControls(
[planeMesh],
AppState.camera,
AppState.renderer.domElement,
);
const startPosition = new THREE.Vector3();
// Only move along the selected axis (exlude the others)
const excludedAxes = ['x', 'y', 'z'].filter(a => a != axis);
controls.addEventListener('dragstart', function (event) {
startPosition.copy(event.object.position);
ATON.Nav.setUserControl(false);
});
const bboxData = AppState.clipping.rootBoundingBox ?? this.getRootBoundingBox();
controls.addEventListener('drag', function (event) {
const point = event.object.position;
Scene.updateClipper(AppState.clipping.vector, point, bboxData);
for (const a of excludedAxes) {
event.object.position[a] = startPosition[a];
}
});
controls.addEventListener('dragend', function (event) {
ATON.Nav.setUserControl(true);
});
}
/**
* @param {String} axis - The axis along which the plane's normal should be directed,
* one of 'x', 'y', 'z'
* @param {Number} orientation - Positive (1) or negative (-1) orientation on the axis
*/
Scene.addClippingPlane = function(axis, orientation = -1) {
axis = axis.toLowerCase();
const bboxData = AppState.clipping.rootBoundingBox ?? this.getRootBoundingBox();
if (!bboxData) return;
const vector = [
axis === 'x' ? orientation : 0,
axis === 'y' ? orientation : 0,
axis === 'z' ? orientation : 0,
];
AppState.clipping.vector = vector;
// First, add a default clipping plane
// at a default point (calculated...)
const defaultPoint = bboxData.center.clone();
Scene.activateClipper(vector, axis, defaultPoint);
}
/**
* @todo WIP!
* Activate clipping plane
* @param {Number[]} vector - The vector array to direct the plane
* @param {String} axis - The x,y,z axis
* @param {?THREE.Vector3} point - The queried scene point
*/
Scene.activateClipper = function(vector, axis, point = null) {
point ??= ATON.getSceneQueriedPoint();
const bboxData = AppState.clipping.rootBoundingBox ?? this.getRootBoundingBox();
if (point) {
Scene.updateClipper(vector, point, bboxData);
Scene.dragClipper(AppState.clipping.helper, axis);
}
}
/**
*
* @param {THREE.Vector3} vector
* @param {THREE.Vector3} point
* @param {Object} bboxData
*/
Scene.updateClipper = function(vector, point, bboxData) {
// First remove any existing clipping planes
ATON.disableClipPlanes();
// Normal of the clipping plane along the Y axis facing down
const normal = new THREE.Vector3(...vector).normalize();
//const constant = -normal.dot(point);
const plane = ATON.addClipPlane(normal, point);
// Add a visible plane helper for the clipping plane
const visiblePlane = AppState.clipping.helper ?? Scene.createClippingPlaneMesh(bboxData.size);
// Remove any already visbile helper plane
if (!AppState.clipping.helper) {
AppState.root.add(visiblePlane);
AppState.clipping.helper = visiblePlane;
}
visiblePlane.position.copy(point);
visiblePlane.lookAt(point.clone().add(normal));
}
/**
*
* @param {THREE.Vector3} vector - An object with x,y,z coordinates
*/
Scene.changeLightDirection = function(vector) {
ATON.setMainLightDirection(vector);
}
/**
*
* @param {Boolean} isEnabled
*/
Scene.toggleAmbientOcclusion = function(isEnabled) {
ATON.FX.togglePass(ATON.FX.PASS_AO, isEnabled);
console.log('Ambient occlusion', isEnabled ? 'ON' : 'OFF');
}
/**
*
* @param {String} direction - The axis direction, one of 'x','y','z'
* @param {String} label - The slider label
* @param {Number[]} range - The slider's range
* @param {Number} step - The slider's step
*/
Scene.createLightSlider = function(direction, label, range, step) {
const currentVal = ATON.getMainLightDirection()[direction];
const lightSlider = ATON.UI.createSlider({
range,
label,
value: Number.parseFloat(currentVal).toPrecision(1),
oninput: val => {
const lightDir = ATON.getMainLightDirection();
// Keep existing direction values for the other axes
lightDir[direction] = Number.parseFloat(val);
this.changeLightDirection(lightDir);
},
});
lightSlider.classList.add('ms-4');
lightSlider.querySelector('input').step = step;
return lightSlider;
}
/**
* Right-side main menu panel
* @param {String} triggerId - The menu button id
*/
Scene.toggleContentMenu = function(triggerId) {
const btn = document.querySelector(`#${triggerId}`);
const audio1 = this.UI.domParser.parseFromString(config.menu.audioBtn1, 'text/html')
.querySelector('button');
btn.addEventListener('click', () => {
ATON.UI.setSidePanelRight();
ATON.UI.showSidePanel({header: '<i class="bi bi-music-note-list me-1"></i> Contenuti'});
ATON.UI.elSidePanel.appendChild(audio1);
});
}
/**
* A left side settings panel
* @param {String} triggerId - The settings button id
*/
Scene.toggleSettingsPanel = function(triggerId) {
const btn = document.querySelector(`#${triggerId}`);
const lightHeading = document.createElement('h2');
lightHeading.className = 'fs-5 ms-2 mb-3 mt-3';
lightHeading.innerHTML = '<i class="bi bi-lightbulb me-1"></i> Direzione luce';
const envHeading = document.createElement('h2');
envHeading.className = 'fs-5 ms-2 mb-3 mt-3';
envHeading.innerHTML = '<i class="bi bi-brightness-high me-1"></i> Ambiente';
btn.addEventListener('click', () => {
ATON.UI.setSidePanelLeft();
ATON.UI.showSidePanel({header: '<i class="bi bi-gear-fill me-1"></i> Impostazioni'});
ATON.UI.elSidePanel.appendChild(lightHeading);
const lightSliderX = this.createLightSlider('x', 'Asse X', [-2, 2], 0.1);
const lightSliderY = this.createLightSlider('y', 'Asse Y', [-2, 2], 0.1);
const lightSliderZ = this.createLightSlider('z', 'Asse Z', [-2, 2], 0.1);
ATON.UI.elSidePanel.appendChild(lightSliderX);
ATON.UI.elSidePanel.appendChild(lightSliderY);
ATON.UI.elSidePanel.appendChild(lightSliderZ);
ATON.UI.elSidePanel.appendChild(envHeading);
const ambientOcclSwitch = document.createElement('div');
ambientOcclSwitch.className = 'form-check form-switch ms-4 mt-2';
ambientOcclSwitch.innerHTML = `
<input class="form-check-input" type="checkbox" role="switch" id="aoSwitch" title="Abilita / disabilita ambient occlusion">
<label class="form-check-label" for="aoSwitch"><em>Ambient occlusion</em> <i class="bi bi-info-circle ms-2 c-hand"></i></label>
`;
const shadowsSwitch = document.createElement('div');
shadowsSwitch.className = 'form-check form-switch ms-4 mt-2';
shadowsSwitch.innerHTML = `
<input class="form-check-input" type="checkbox" role="switch" id="shadowsSwitch" title="Abilita / disabilita ombre">
<label class="form-check-label" for="shadowsSwitch">Ombre <i class="bi bi-info-circle ms-2 c-hand" title=""></i></label>
`;
const lightProbeSwitch = document.createElement('div');
lightProbeSwitch.className = 'form-check form-switch ms-4 mt-2';
lightProbeSwitch.innerHTML = `
<input class="form-check-input" type="checkbox" role="switch" id="lpSwitch" title="Abilita / disabilita mappa HDRi">
<label class="form-check-label" for="lpSwitch">Mappa HDRi <em>(light probe)</em> <i class="bi bi-info-circle ms-2 c-hand"></i></label>
`;
shadowsSwitch.querySelector('input[type="checkbox"').checked = AppState.shadows;
ambientOcclSwitch.querySelector('input[type="checkbox"').checked = AppState.ambientOcclusion;
lightProbeSwitch.querySelector('input[type="checkbox"').checked = AppState.lightProbe;
ATON.UI.elSidePanel.appendChild(ambientOcclSwitch);
ATON.UI.elSidePanel.appendChild(shadowsSwitch);
ATON.UI.elSidePanel.appendChild(lightProbeSwitch);
// TODO: move somewhere else...
document.querySelector('#aoSwitch').addEventListener(
'change',
event => {
this.toggleAmbientOcclusion(event.target.checked);
AppState.ambientOcclusion = event.target.checked;
}
);
document.querySelector('#shadowsSwitch').addEventListener(
'change',
event => {
const checked = event.target.checked;
ATON.toggleShadows(checked);
AppState.shadows = checked;
}
);
// Not working properly?
document.querySelector('#lpSwitch').addEventListener(
'change',
event => {
const checked = event.target.checked;
ATON.setAutoLP(checked);
//if (!checked) ATON.clearLightProbes();
AppState.lightProbe = checked;
if (checked) ATON.updateLightProbes();
console.log('Light probe: ', checked);
}
);
});
}
Scene.init = function() {
ATON.realize();
ATON.UI.addBasicEvents();
ATON.UI.init();
// All assets for this app are stored here
ATON.setPathCollection('./assets/');
// Initial light direction
ATON.setMainLightDirection(new THREE.Vector3(0.2,-0.3,-0.7));
ATON.toggleShadows(true);
ATON.setExposure(config.scene.initialExposure);
// Open settings side panel when clicking on settings btn
Scene.toggleSettingsPanel('settings');
Scene.toggleContentMenu('menu');
AppState.camera = ATON.Nav._camera;
AppState.renderer = ATON._renderer;
}
/**
* @param {String} btnId - The back-to-map button id
*/
Scene.toggleScene = function(btnId) {
const btn = document.querySelector(`#${btnId}`);
const scene = document.querySelector('#scene');
btn.addEventListener('click', () => {
const currentScene = getCurrentScene();
// Deactivate the current scene before toggling
setSceneStatus(currentScene.id, false);
scene.classList.toggle('d-none');
// Pause rendering the 3D scene to free resources (hopefully)
// when browsing the map
ATON.renderPause();
if (AppState.clipping.enabled) {
ATON.disableClipPlanes();
AppState.clipping.enabled = false;
Scene.UI.reset();
AppState.root.remove(AppState.clipping.helper);
AppState.clipping.helper = null;
}
AppState.root.setRotation(AppState.initialRotation ?? new THREE.Vector3(0, 1.5, 0));
document.querySelector('#map').classList.toggle('d-none');
AppState.map.invalidateSize();
});
}
/**
* @param {Object} marker - The marker object from config
*/
Scene.openScene = function(marker) {
let canvas = document.querySelector('canvas');
let scene = document.querySelector('#scene');
if (canvas === null) {
Scene.init();
}
Scene.UI.toggleClipper('#clipper', '#clipper-bar');
scene.classList.toggle('d-none');
ATON.renderResume();
// TODO: reset scene only if changing to a different model from the map
// set scene status to inactive, first get current scene id...
let currentScene = getCurrentScene();
if (currentScene && currentScene.id !== marker.id) {
AppState.root.removeChildren();
currentScene.current = false;
}
if (!AppState.scenes.find(s => s.id === marker.id)) {
const newScene = {id: marker.id, active: false, current: true};
AppState.scenes.push(newScene);
}
if (!getSceneStatus(marker.id)) {
// Set scene as active
setSceneStatus(marker.id, true);
// Load 3D model
let mainNode = ATON.createSceneNode(marker.label).load(marker.model);
ATON.setMainPanorama(marker.pano);
//mainNode.setMaterial(new THREE.MeshPhongMaterial(material));
// TODO: hardcoded...
mainNode.setRotation(0, 1.5, 0)
AppState.initialRotation = new THREE.Vector3(0, 1.5, 0);
Scene.showEdges(mainNode);
mainNode.attachToRoot();
ATON.setAutoLP(config.scene.autoLP);
AppState.lightProbe = config.scene.autoLP;
Scene.toggleAmbientOcclusion(true);
AppState.ambientOcclusion = true;
AppState.root = ATON.getRootScene();
// TODO: set the scene as current!!
setCurrentScene(marker.id);
}
}
export default Scene;