178 lines
10 KiB
JavaScript
178 lines
10 KiB
JavaScript
import { Box3, Matrix4, Quaternion, Spherical, Vector3 } from '../vendor/three/build/three.module.min.js';
|
|
import { inferScrewHeadDirection, isAssemblyFastener } from './assembly-head.js';
|
|
import { ASSEMBLY_PACE, assemblyEase } from './assembly-animation.js';
|
|
import { alignedToolQuaternion } from './assembly-motion.js';
|
|
|
|
const UP = new Vector3(0, 1, 0);
|
|
|
|
// A tap reveals the mobile player; only an actual camera gesture exits closeup.
|
|
export function watchAssemblyCameraInput(element, onInput, signal) {
|
|
const pointers = new Map();
|
|
let moving = false;
|
|
const takeControl = () => { if (!moving) { moving = true; onInput(); } };
|
|
const options = { capture: true, signal };
|
|
element.addEventListener('pointerdown', event => {
|
|
pointers.set(event.pointerId, [event.clientX, event.clientY]);
|
|
if (pointers.size > 1) takeControl();
|
|
}, options);
|
|
element.addEventListener('pointermove', event => {
|
|
const origin = pointers.get(event.pointerId);
|
|
if (origin && Math.hypot(event.clientX - origin[0], event.clientY - origin[1]) > 6) takeControl();
|
|
}, options);
|
|
const release = event => {
|
|
pointers.delete(event.pointerId);
|
|
if (!pointers.size) moving = false;
|
|
};
|
|
for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) element.addEventListener(type, release, options);
|
|
element.addEventListener('wheel', onInput, { ...options, passive: true });
|
|
}
|
|
|
|
// Orbit around the work, never through it. Keep a level horizon and take the
|
|
// shortest azimuth route, with a small pull-back before a larger side change.
|
|
export function createCameraMove(camera, focus, frame) {
|
|
const rotation = new Quaternion().setFromUnitVectors(camera.up, UP);
|
|
const from = new Spherical().setFromVector3(camera.position.clone().sub(focus).applyQuaternion(rotation));
|
|
const to = new Spherical().setFromVector3(frame.position.clone().sub(frame.target).applyQuaternion(rotation));
|
|
const theta = Math.atan2(Math.sin(to.theta - from.theta), Math.cos(to.theta - from.theta));
|
|
const angle = Math.hypot(theta, to.phi - from.phi);
|
|
const wide = angle > Math.PI / 3;
|
|
const motionDuration = ASSEMBLY_PACE.camera + angle * .95;
|
|
return { from, to, theta, wide, focus: focus.clone(), frame,
|
|
rotation: rotation.invert(), offset: new Vector3(), spherical: new Spherical(),
|
|
cruiseRadius: Math.max(from.radius, to.radius) * 1.16,
|
|
motionDuration, duration: motionDuration + ASSEMBLY_PACE.cameraHold, elapsed: 0 };
|
|
}
|
|
|
|
export function sampleCameraMove(move, camera, target) {
|
|
const t = Math.min(1, move.elapsed / move.motionDuration);
|
|
if (t === 1) {
|
|
camera.position.copy(move.frame.position);
|
|
target.copy(move.frame.target);
|
|
return;
|
|
}
|
|
const eased = assemblyEase(move.wide ? (t - .18) / .64 : t);
|
|
let radius = move.from.radius + (move.to.radius - move.from.radius) * eased;
|
|
if (move.wide) {
|
|
radius = t < .18
|
|
? move.from.radius + (move.cruiseRadius - move.from.radius) * assemblyEase(t / .18)
|
|
: move.cruiseRadius + (move.to.radius - move.cruiseRadius) * assemblyEase((t - .82) / .18);
|
|
}
|
|
move.spherical.set(radius, move.from.phi + (move.to.phi - move.from.phi) * eased, move.from.theta + move.theta * eased);
|
|
target.lerpVectors(move.focus, move.frame.target, eased);
|
|
camera.position.copy(move.offset.setFromSpherical(move.spherical).applyQuaternion(move.rotation)).add(target);
|
|
}
|
|
|
|
export function assemblyHeadDirection(part, instance, template, cache = new Map()) {
|
|
instance.parent.updateWorldMatrix(true, false);
|
|
const finalMatrix = new Matrix4().compose(new Vector3(...part.position), new Quaternion(...part.quaternion),
|
|
new Vector3(...part.scale)).premultiply(instance.parent.matrixWorld);
|
|
if (part.installation) return new Vector3(...part.installation.axis).negate().transformDirection(finalMatrix);
|
|
if (part.focusDirection) return new Vector3(...part.focusDirection).transformDirection(instance.parent.matrixWorld);
|
|
if (!template || !isAssemblyFastener(`${part.label || ''} ${part.file.split('/').pop()}`)) return null;
|
|
if (!cache.has(part.file)) cache.set(part.file, inferScrewHeadDirection(template));
|
|
return cache.get(part.file)?.clone().transformDirection(finalMatrix) || null;
|
|
}
|
|
|
|
// Reuse the current angle while the head faces us. Switch to the nearest
|
|
// head-facing side only when needed; do not chase each screw's position.
|
|
export function headFacingView(viewDirection, headDirection) {
|
|
const direction = viewDirection.clone().normalize();
|
|
if (!headDirection || direction.dot(headDirection) >= .35) return direction;
|
|
const side = direction.clone().addScaledVector(headDirection, -direction.dot(headDirection));
|
|
if (side.lengthSq() < .01) side.crossVectors(headDirection, UP);
|
|
if (side.lengthSq() < .01) side.set(1, 0, 0);
|
|
direction.copy(headDirection).multiplyScalar(.85).add(side.normalize());
|
|
if (Math.abs(headDirection.y) < .9) direction.addScaledVector(UP, .15);
|
|
return direction.normalize();
|
|
}
|
|
|
|
// Frame the installation site once. Neither the moving part nor the rotating
|
|
// tool participates in camera tracking during playback.
|
|
export function createAssemblyShot(parts, instances, templates, boundsCache, contextSize = 1,
|
|
viewDirection = new Vector3(1, 0.16, -0.65), headCache = new Map()) {
|
|
const boundsFor = (file) => {
|
|
if (!boundsCache.has(file)) boundsCache.set(file, new Box3().setFromObject(templates.get(file)));
|
|
return boundsCache.get(file);
|
|
};
|
|
const sweptBounds = new Box3(), anchors = [], entries = [];
|
|
const outward = new Vector3();
|
|
let hasTool = false;
|
|
for (const { part, tool } of parts) {
|
|
const instance = instances.get(part.id);
|
|
instance.updateWorldMatrix(true, false);
|
|
const finalMatrix = new Matrix4().compose(new Vector3(...part.position), new Quaternion(...part.quaternion),
|
|
new Vector3(...part.scale)).premultiply(instance.parent.matrixWorld);
|
|
const localBounds = boundsFor(part.file);
|
|
const finalBounds = localBounds.clone().applyMatrix4(finalMatrix);
|
|
const anchor = part.installation ? new Vector3(...part.installation.socketPosition) : localBounds.getCenter(new Vector3());
|
|
const finalAnchor = anchor.clone().applyMatrix4(finalMatrix);
|
|
anchors.push(finalAnchor);
|
|
// Use the declared path, so replaying or seeking cannot change the zoom.
|
|
const entry = new Vector3(...part.installOffset).applyMatrix4(instance.parent.matrixWorld)
|
|
.sub(new Vector3().setFromMatrixPosition(instance.parent.matrixWorld));
|
|
entries.push(entry);
|
|
sweptBounds.union(finalBounds).union(finalBounds.clone().translate(entry));
|
|
if (tool && part.installation) {
|
|
hasTool = true;
|
|
const motion = part.installation, tip = new Vector3(...tool.tipPosition), box = boundsFor(tool.file);
|
|
const rotation = alignedToolQuaternion(motion, tool);
|
|
const axis = new Vector3(...motion.axis).normalize();
|
|
let axialMin = Infinity, axialMax = -Infinity, radial = 0;
|
|
// Bound the rotating handle as a cylinder around the socket axis. A
|
|
// sphere with the full key length wastes most of a portrait viewport.
|
|
for (const x of [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z]) {
|
|
const delta = new Vector3(x, y, z).sub(tip).applyQuaternion(rotation), axial = delta.dot(axis);
|
|
axialMin = Math.min(axialMin, axial); axialMax = Math.max(axialMax, axial);
|
|
radial = Math.max(radial, delta.addScaledVector(axis, -axial).length());
|
|
}
|
|
const scale = finalMatrix.getMaxScaleOnAxis(), worldAxis = axis.clone().transformDirection(finalMatrix);
|
|
const spread = new Vector3(...worldAxis.toArray().map(value => radial * scale * Math.sqrt(Math.max(0, 1 - value * value))));
|
|
for (const axial of [axialMin - motion.toolClearance - motion.travel, axialMax]) {
|
|
const end = finalAnchor.clone().addScaledVector(worldAxis, axial * scale);
|
|
sweptBounds.expandByPoint(end.clone().sub(spread)).expandByPoint(end.clone().add(spread));
|
|
}
|
|
}
|
|
if (parts.length === 1) outward.copy(assemblyHeadDirection(part, instance, templates.get(part.file), headCache) || new Vector3());
|
|
}
|
|
const headDirection = outward.lengthSq() > 0 ? outward.clone() : null;
|
|
const direction = headFacingView(viewDirection, headDirection);
|
|
const center = anchors.reduce((sum, anchor) => sum.add(anchor), new Vector3())
|
|
.divideScalar(anchors.length);
|
|
// Look between the entry and the seated position. This frames the complete
|
|
// insertion without adding the entire travel distance on BOTH sides of it.
|
|
center.add(entries.reduce((sum, entry) => sum.add(entry), new Vector3()).divideScalar(entries.length).multiplyScalar(.35));
|
|
if (hasTool) sweptBounds.getCenter(center);
|
|
let extent = 0;
|
|
for (const x of [sweptBounds.min.x, sweptBounds.max.x]) for (const y of [sweptBounds.min.y, sweptBounds.max.y]) for (const z of [sweptBounds.min.z, sweptBounds.max.z]) {
|
|
extent = Math.max(extent, new Vector3(x, y, z).distanceTo(center));
|
|
}
|
|
const radius = Math.max(contextSize * 0.08, extent * 1.05);
|
|
return { target: center, direction, radius, headDirection };
|
|
}
|
|
|
|
export function assemblyShotFrame(shot, camera) {
|
|
const target = shot.target.clone();
|
|
const vertical = camera.fov * Math.PI / 360;
|
|
const halfFov = Math.min(vertical, Math.atan(Math.tan(vertical) * camera.aspect));
|
|
const distance = Math.max(0.08, shot.radius / Math.sin(halfFov) * 1.15);
|
|
return { target, position: target.clone().addScaledVector(shot.direction, distance) };
|
|
}
|
|
|
|
// Nearby fasteners share a stationary shot while the new work area still fits.
|
|
export function assemblyShotFits(shot, camera, target) {
|
|
const forward = target.clone().sub(camera.position).normalize();
|
|
if (shot.headDirection && shot.headDirection.dot(forward) > -0.35) return false;
|
|
const right = new Vector3().crossVectors(forward, camera.up).normalize();
|
|
const up = new Vector3().crossVectors(right, forward);
|
|
const relative = shot.target.clone().sub(camera.position), depth = relative.dot(forward);
|
|
const y = camera.fov * Math.PI / 360, x = Math.atan(Math.tan(y) * camera.aspect);
|
|
// Merely being inside the viewport is insufficient: an old whole-model shot
|
|
// can contain a small screw while leaving it impossible to see. Hysteresis
|
|
// still lets neighboring screws share one stable shot.
|
|
const idealDistance = assemblyShotFrame(shot, camera).position.distanceTo(shot.target);
|
|
if (depth > idealDistance * 1.65) return false;
|
|
return depth > camera.near + shot.radius
|
|
&& Math.abs(relative.dot(right)) * Math.cos(x) + shot.radius <= depth * Math.sin(x) * 0.95
|
|
&& Math.abs(relative.dot(up)) * Math.cos(y) + shot.radius <= depth * Math.sin(y) * 0.95;
|
|
}
|