Files
vibemake/js/assembly-viewer.js

614 lines
30 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { RenderBudget, RenderLoop, modelViewerProfile } from './render-budget.js';
import { readLimited, validateEmbeddedGlb, visibleAssemblyParts } from './experience-packages.js';
import { modelAssetUrl } from './model-assets.js';
import { ScrewTransition, screwDuration, inferToolTipAxis } from './assembly-motion.js';
import { createExplodedLayout } from './assembly-explode.js';
import { createAssemblyShot, assemblyShotFrame, assemblyShotFits, assemblyHeadDirection, headFacingView, createCameraMove, sampleCameraMove, watchAssemblyCameraInput } from './assembly-camera.js';
import { constrainedAssemblyDevice, disposeAssemblyObjects as disposeObject } from './assembly-memory.js';
import { assemblyStageKey, stepEntryOffset, isGroupedAssembly } from './assembly-groups.js';
import { buildWorkBounds, componentViewDirection, workBoundsFit } from './assembly-framing.js';
import { ASSEMBLY_PACE, assemblyEase, presentationScrewMotion } from './assembly-animation.js';
export class AssemblyViewer {
constructor(container) {
this.container = container;
this.disposed = false;
this.lifecycle = new AbortController();
this.budget = new RenderBudget(modelViewerProfile());
this.renderer = new THREE.WebGLRenderer({ antialias: this.budget.antialias, alpha: true, powerPreference: 'low-power' });
const renderer = this.renderer;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.AgXToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = this.budget.shadows;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// The model and lights are static: orbiting does not change its shadow.
renderer.shadowMap.autoUpdate = false;
renderer.domElement.setAttribute('aria-label', '装配模型,可拖拽旋转和缩放');
renderer.domElement.style.visibility = 'hidden';
container.prepend(renderer.domElement);
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(32, 1, 0.01, 50);
this.createEnvironment();
this.scene.add(new THREE.HemisphereLight(0xffffff, 0x343840, 0.45));
const key = new THREE.DirectionalLight(0xffecd9, 2.5);
key.position.set(3, 4, -2);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
Object.assign(key.shadow.camera, { left: -1.5, right: 1.5, top: 1.5, bottom: -1.5, near: 0.1, far: 10 });
key.shadow.normalBias = 0.008;
key.shadow.bias = -0.0002;
this.scene.add(key);
const fill = new THREE.DirectionalLight(0xdce7ff, 0.7);
fill.position.set(-2, 2, 3);
this.scene.add(fill);
const ground = new THREE.Mesh(new THREE.PlaneGeometry(200, 200), new THREE.ShadowMaterial({ opacity: 0.25 }));
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.002;
ground.receiveShadow = true;
this.scene.add(ground);
const grid = new THREE.GridHelper(6, 60, 0x626a75, 0x626a75);
grid.material.transparent = true;
grid.material.opacity = 0.1;
grid.material.depthWrite = false;
grid.position.y = -0.004;
this.scene.add(grid);
this.controls = new OrbitControls(this.camera, renderer.domElement);
Object.assign(this.controls, {
enableDamping: true, dampingFactor: 0.075, minDistance: 0.65, maxDistance: 7,
maxPolarAngle: Math.PI * 0.49, autoRotateSpeed: 0.8,
});
this.loop = new RenderLoop({
budget: this.budget,
render: (dt) => this.render(dt),
onQuality: () => this.resize(false),
});
this.controls.addEventListener('change', () => this.loop.invalidate());
watchAssemblyCameraInput(renderer.domElement, () => {
this.cancelCameraTransition();
if (this.explosionTransition) this.explosionTransition.moveCamera = false;
this.setCloseup(false, { restore: false });
}, this.lifecycle.signal);
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(container);
this.resize();
this.onVisibility = () => this.loop.setActive(!document.hidden && !this.contextLost && !this.paused && this.inView !== false);
this.intersectionObserver = new IntersectionObserver(([entry]) => { this.inView = entry.isIntersecting; this.onVisibility(); });
this.intersectionObserver.observe(container);
document.addEventListener('visibilitychange', this.onVisibility);
renderer.domElement.addEventListener('webglcontextlost', (event) => {
if (this.disposed) return;
event.preventDefault();
this.contextLost = true;
this.onVisibility();
this.onContextLost?.();
});
renderer.domElement.addEventListener('webglcontextrestored', () => {
if (this.disposed) return;
this.contextLost = false;
this.createEnvironment();
renderer.shadowMap.needsUpdate = true;
this.onVisibility();
});
this.onVisibility();
}
createEnvironment() {
this.environment?.dispose();
const room = new RoomEnvironment(this.renderer);
const pmrem = new THREE.PMREMGenerator(this.renderer);
this.environment = pmrem.fromScene(room, 0.04);
this.scene.environment = this.environment.texture;
room.dispose();
pmrem.dispose();
}
async loadGlb(url, signal, displayQuaternion = [0, 0, 0, 1]) {
const response = await fetch(modelAssetUrl(url), { signal, credentials: 'omit' });
if (!response.ok) throw new Error(`整机模型请求失败(HTTP ${response.status})`);
const data = await readLimited(response);
await this.load({
files: new Map([['whole.glb', { url, bytes: data.length, data }]]), displayQuaternion,
parts: [{ id: 'whole', file: 'whole.glb', parentId: null, position: [0, 0, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1], installOffset: [0, 0, 0] }], steps: [],
}, signal);
}
setPaused(paused) { this.paused = paused; this.onVisibility(); }
async load(config, signal, onProgress) {
const cancelLoad = () => this.lifecycle.abort(signal.reason);
signal.addEventListener('abort', cancelLoad, { once: true });
if (signal.aborted) cancelLoad();
const callerSignal = signal;
signal = this.lifecycle.signal;
try { await this.loadParts(config, signal, onProgress); }
finally { callerSignal.removeEventListener('abort', cancelLoad); }
}
async loadParts(config, signal, onProgress) {
this.config = config;
this.partConfigs = new Map(config.parts.map(part => [part.id, part]));
this.focusBounds = new Map();
this.headDirections = new Map();
this.templates = new Map();
this.parts = new Map();
const queue = [...new Set([...config.parts, ...(config.tools || [])].map((part) => part.file))];
const count = queue.length;
let completed = 0;
// Compressed uploads use the same local decoder as the main model viewer.
// One decoder worker keeps assembly loading within mobile memory budgets.
const draco = new DRACOLoader().setDecoderPath('/vendor/three/examples/jsm/libs/draco/gltf/').setWorkerLimit(1);
const loader = new GLTFLoader().setDRACOLoader(draco);
// 同一个 GLB 可用于多个螺丝 / 零件实例,只下载和解析一次;限制并行解析数量。
const worker = async () => {
for (let path = queue.shift(); path; path = queue.shift()) {
signal.throwIfAborted();
if (this.disposed) throw new DOMException('预览已关闭', 'AbortError');
const file = config.files.get(path);
let bytes = file.data;
if (!bytes) {
const response = await fetch(modelAssetUrl(file.url), { signal, credentials: 'omit' });
if (!response.ok) throw new Error(`零件请求失败(HTTP ${response.status}):${path}`);
bytes = await readLimited(response, file.bytes);
}
if (bytes.length !== file.bytes) throw new Error(`零件大小与清单不一致:${path}`);
if (file.sha256 && globalThis.crypto?.subtle) {
const digest = await crypto.subtle.digest('SHA-256', bytes);
const hash = [...new Uint8Array(digest)].map((x) => x.toString(16).padStart(2, '0')).join('');
if (hash !== file.sha256) throw new Error(`零件内容与步骤版本不一致:${path}`);
}
validateEmbeddedGlb(bytes.buffer);
signal.throwIfAborted();
const gltf = await loader.parseAsync(bytes.buffer, new URL('.', file.url).href);
try {
signal.throwIfAborted();
} catch (error) {
disposeObject(gltf.scene);
throw error;
}
file.data = undefined;
// Retain the uploaded geometry, material parameters and full-size maps.
// Asset optimization belongs in the source files, not this loader.
this.templates.set(path, gltf.scene);
onProgress?.(Math.round(++completed / count * 100));
// Let the UI respond and discarded decode buffers be reclaimed between
// parts. Original texture images remain intact until the viewer closes.
await new Promise(resolve => setTimeout(resolve, 0));
}
};
// Let in-flight parses settle before terminating the shared decoder worker.
try {
const results = await Promise.allSettled(Array.from({ length: Math.min(constrainedAssemblyDevice() ? 1 : 2, count) }, () => worker().catch(error => {
this.lifecycle.abort(error);
throw error;
})));
const failed = results.find(result => result.status === 'rejected');
if (failed) throw failed.reason;
} finally { draco.dispose(); }
signal.throwIfAborted();
this.toolConfigs = new Map((config.tools || []).map((tool) => [tool.id, {
...tool, tipAxis: tool.tipAxis || inferToolTipAxis(this.templates.get(tool.file), tool.tipPosition),
}]));
const display = new THREE.Group();
display.quaternion.fromArray(config.displayQuaternion);
for (const part of config.parts) {
const instance = new THREE.Group();
instance.name = part.id;
instance.add(this.templates.get(part.file).clone(true));
instance.position.fromArray(part.position);
instance.quaternion.fromArray(part.quaternion);
instance.scale.fromArray(part.scale);
this.parts.set(part.id, instance);
}
for (const part of config.parts) (part.parentId ? this.parts.get(part.parentId) : display).add(this.parts.get(part.id));
const model = new THREE.Group();
model.add(display);
model.updateMatrixWorld(true);
const bounds = new THREE.Box3().setFromObject(model);
const size = bounds.getSize(new THREE.Vector3());
const center = bounds.getCenter(new THREE.Vector3());
const dimension = Math.max(size.x, size.y, size.z);
if (!Number.isFinite(dimension) || dimension <= 0) throw new Error('装配包没有可显示的几何体');
const scale = 1 / dimension;
model.scale.setScalar(scale);
model.position.set(-center.x * scale, -bounds.min.y * scale, -center.z * scale);
this.scene.add(model);
this.model = model;
this.modelSize = size.multiplyScalar(scale);
model.updateMatrixWorld(true);
this.assembledBounds = new THREE.Box3().setFromObject(model);
this.finalPartBounds = new Map(config.parts.map(part => [part.id,
new THREE.Box3().setFromObject(this.templates.get(part.file)).applyMatrix4(this.parts.get(part.id).matrixWorld)]));
this.groupBounds = new Map((config.groups || []).map(group => {
const box = new THREE.Box3();
for (const id of group.parts) box.union(new THREE.Box3().setFromObject(this.parts.get(id)));
return [group.id, box];
}));
this.exploded = false;
this.explosionAmount = 0;
this.explosionTarget = 0;
this.explodedLayout = null;
this.explosionTransition = null;
model.traverse((object) => {
if (!object.isMesh) return;
object.castShadow = true;
object.receiveShadow = true;
// 直接使用 GLTFLoader 读取的原始材质,不覆盖任何材质参数。
});
this.resetView();
this.renderer.shadowMap.needsUpdate = true;
this.loop.invalidate();
this.renderer.domElement.style.visibility = 'visible';
this.stepIndex = null;
this.installed = visibleAssemblyParts(config, null);
this.transitions = [];
}
setStep(index, animate = true) {
if (!this.config || this.disposed) return;
const enteringSteps = this.stepIndex === null && index !== null;
const installed = visibleAssemblyParts(this.config, index);
const wasExploded = this.exploded || this.explosionAmount > 0;
this.exploded = false;
this.explosionAmount = 0;
this.explosionTarget = 0;
this.explosionTransition = null;
for (const transition of this.transitions || []) transition.dispose?.();
this.transitions = [];
this.cancelCameraTransition();
this.animationPaused = false;
const motion = animate && !matchMedia('(prefers-reduced-motion: reduce)').matches;
const step = index === null ? null : this.config.steps[index];
const stageChanged = assemblyStageKey(this.config, this.stepIndex) !== assemblyStageKey(this.config, index);
const activeParts = new Set(step?.parts || []);
const screwDelays = new Map();
const byId = new Map(this.config.parts.map((part) => [part.id, part]));
let screwDelay = 0;
for (const id of activeParts) {
const installation = byId.get(id).installation;
if (step.type !== 'join' && installation?.type === 'screw') {
screwDelays.set(id, screwDelay);
screwDelay += screwDuration(presentationScrewMotion(installation));
}
}
for (const part of this.config.parts) {
const instance = this.parts.get(part.id);
instance.visible = installed.has(part.id);
instance.position.fromArray(part.position);
instance.quaternion.fromArray(part.quaternion);
if (instance.visible && activeParts.has(part.id) && motion) {
if (step.type !== 'join' && part.installation?.type === 'screw') {
const toolConfig = this.toolConfigs.get(part.installation.toolId);
const tool = new THREE.Group();
tool.name = `assembly-tool-${toolConfig.id}`;
tool.add(this.templates.get(toolConfig.file).clone(true));
const playbackPart = { ...part, installation: presentationScrewMotion(part.installation) };
this.transitions.push(new ScrewTransition(instance, playbackPart, tool, toolConfig, screwDelays.get(part.id)));
// One tool works on one fastener at a time; ordinary parts keep sliding in.
continue;
}
const offset = stepEntryOffset(step, part);
if (!offset || !offset.some(v => v !== 0)) continue;
const target = instance.position.clone();
instance.position.add(new THREE.Vector3(...offset));
this.transitions.push({ instance, from: instance.position.clone(), target, elapsed: 0,
duration: step.type === 'join' ? ASSEMBLY_PACE.join : ASSEMBLY_PACE.insertion });
}
}
this.installed = installed;
this.stepIndex = index;
if (index === null) this.resetView();
else if (enteringSteps) this.setCloseup(true, { animate: motion });
else if (wasExploded) this.resetView();
else if (this.closeupEnabled) {
if (stageChanged) this.closeupShot = null;
this.refreshCloseup(true, undefined, motion);
} else if (isGroupedAssembly(this.config) || this.stepHeadDirection()) this.fitBuildView({ stageChanged, animate: motion });
this.renderer.shadowMap.needsUpdate = true;
this.notifyMotion();
this.loop.invalidate();
}
setAnimationPaused(paused) { this.animationPaused = paused; this.loop.invalidate(); }
setExploded(enabled, amount = 0.65, animate = true) {
if (!this.model || this.config.parts.length < 2 || this.disposed) return;
if (this.stepIndex !== null) this.setStep(null, false);
if (!this.explodedLayout) this.explodedLayout = createExplodedLayout(this.config, this.parts);
this.exploded = enabled;
this.setCloseup(false, { restore: false });
this.focusedPartId = null;
this.controls.maxPolarAngle = Math.PI * 0.49;
this.explosionTarget = enabled ? Math.max(0, Math.min(1, Number.isFinite(amount) ? amount : 0.65)) : 0;
const frame = this.frameForBounds(this.explodedLayout.boundsAt(this.explosionTarget));
const motion = animate && !matchMedia('(prefers-reduced-motion: reduce)').matches;
if (motion) {
this.explosionTransition = { from: this.explosionAmount, target: this.explosionTarget, elapsed: 0,
camera: this.camera.position.clone(), focus: this.controls.target.clone(), frame, moveCamera: true };
} else {
this.explosionTransition = null;
this.explosionAmount = this.explosionTarget;
this.explodedLayout.apply(this.explosionAmount);
this.camera.position.copy(frame.position);
this.controls.target.copy(frame.target);
}
this.renderer.shadowMap.needsUpdate = true;
this.loop.invalidate();
}
notifyMotion() {
const active = this.transitions?.find((transition) => transition.phase && !['waiting', 'done'].includes(transition.phase));
const key = active ? `${active.part.id}:${active.phase}` : '';
if (key === this.motionKey) return;
this.motionKey = key;
if (active && this.closeupEnabled && this.focusedPartId !== active.part.id) this.refreshCloseup(false, active.part.id);
const screws = active && Number.isInteger(this.stepIndex) ? this.config.steps[this.stepIndex].parts
.filter((id) => this.config.parts.find((part) => part.id === id)?.installation) : [];
this.onMotionChange?.(active ? { partId: active.part.id, phase: active.phase,
index: screws.indexOf(active.part.id) + 1, count: screws.length } : null);
}
focusPart(id) {
if (!this.parts?.has(id)) return;
this.setCloseup(true, { partId: id });
}
setCloseup(enabled, { restore = true, partId, animate = !this.animationPaused } = {}) {
enabled = !!enabled && Number.isInteger(this.stepIndex) && !this.disposed;
const changed = this.closeupEnabled !== enabled;
this.closeupEnabled = enabled;
if (enabled) {
this.setAutoRotate(false);
this.refreshCloseup(true, partId, animate);
} else {
this.closeupShot = null;
this.closeupKey = this.focusedPartId = null;
if (changed && restore) this.resetView();
}
if (changed) this.onCloseupChange?.(enabled);
this.loop.invalidate();
}
refreshCloseup(force = false, preferredId, animate = !this.animationPaused) {
if (!this.closeupEnabled || !Number.isInteger(this.stepIndex)) return;
const step = this.config.steps[this.stepIndex];
// Joining needs a wider shot, but must not turn off automatic closeups for
// the fasteners that follow it. Only an explicit user action disables them.
if (step.type === 'join') {
this.closeupShot = null;
this.closeupKey = this.focusedPartId = null;
this.fitBuildView({ animate, force: true });
return;
}
const active = this.transitions.find(t => t.phase && !['waiting', 'done'].includes(t.phase));
const id = preferredId && step.parts.includes(preferredId) ? preferredId : active?.part.id;
const ids = id ? [id] : step.parts;
const key = `${this.stepIndex}:${ids.join(',')}`;
if (!force && key === this.closeupKey) return;
this.closeupKey = key;
this.focusedPartId = ids.length === 1 ? ids[0] : null;
const parts = ids.map(id => {
const part = this.partConfigs.get(id);
return { part, tool: this.toolConfigs.get(part.installation?.toolId) };
});
const previousShot = this.closeupShot;
this.closeupShot = createAssemblyShot(parts, this.parts, this.templates, this.focusBounds,
Math.max(this.modelSize.x, this.modelSize.y, this.modelSize.z), this.camera.position.clone().sub(this.controls.target), this.headDirections);
const frame = assemblyShotFrame(this.closeupShot, this.camera);
this.controls.minDistance = 0.03;
this.controls.maxDistance = Math.max(7, frame.position.distanceTo(frame.target) * 2);
this.controls.maxPolarAngle = Math.PI * 0.95;
if (!previousShot || !assemblyShotFits(this.closeupShot, this.camera, this.controls.target)) this.moveCamera(frame, animate);
}
cancelCameraTransition() {
this.cameraTransition = null;
}
moveCamera(frame, animate = false) {
this.cancelCameraTransition();
// Clear any remaining manual-orbit damping before setting a stationary shot.
const damping = this.controls.enableDamping;
this.controls.enableDamping = false;
this.controls.update();
if (animate && !matchMedia('(prefers-reduced-motion: reduce)').matches &&
(this.camera.position.distanceToSquared(frame.position) > 1e-8 || this.controls.target.distanceToSquared(frame.target) > 1e-8)) {
this.cameraTransition = createCameraMove(this.camera, this.controls.target, frame);
this.controls.maxDistance = Math.max(this.controls.maxDistance || 0, this.cameraTransition.cruiseRadius);
} else {
this.controls.target.copy(frame.target);
this.camera.position.copy(frame.position);
this.controls.update();
}
this.controls.enableDamping = damping;
this.loop.invalidate();
}
frameForBounds(bounds, direction = new THREE.Vector3(1, 0.3, -0.65)) {
const size = bounds.getSize(new THREE.Vector3());
const target = bounds.getCenter(new THREE.Vector3());
const fov = THREE.MathUtils.degToRad(this.camera.fov);
// 按实际观察方向投影包围盒,兼顾厚模型与竖屏,避免保守球体取景把细长模型缩得过小。
direction = direction.clone().normalize();
const right = new THREE.Vector3().crossVectors(this.camera.up, direction).normalize();
const up = new THREE.Vector3().crossVectors(direction, right);
const tanY = Math.tan(fov / 2), tanX = tanY * this.camera.aspect;
let distance = 0;
for (const x of [-1, 1]) for (const y of [-1, 1]) for (const z of [-1, 1]) {
const corner = new THREE.Vector3(x * size.x, y * size.y, z * size.z).multiplyScalar(0.5);
const depth = corner.dot(direction);
distance = Math.max(distance, depth + Math.abs(corner.dot(right)) / tanX * 1.3, depth + Math.abs(corner.dot(up)) / tanY * 1.3);
}
this.controls.maxDistance = Math.max(7, distance * 2);
return { target, position: direction.multiplyScalar(distance).add(target) };
}
currentWorkBounds() {
const key = assemblyStageKey(this.config, this.stepIndex);
const context = this.groupBounds?.get(key) || this.assembledBounds;
const step = this.config.steps[this.stepIndex];
const joined = step.type === 'join' ? new Set(step.parts) : null;
const entries = (step?.parts || []).map(id => {
const part = this.partConfigs.get(id), instance = this.parts.get(id);
const offset = step.type === 'join' ? step.installOffset : part.installOffset;
// A nested member inherits the join root's translation, not an offset
// rotated again by its own parent.
let root = part;
while (joined?.has(root.parentId)) root = this.partConfigs.get(root.parentId);
const parent = (joined ? this.parts.get(root.id) : instance).parent;
parent.updateWorldMatrix(true, false);
const matrix = parent.matrixWorld;
return { id, offset:new THREE.Vector3(...offset).applyMatrix4(matrix).sub(new THREE.Vector3().setFromMatrixPosition(matrix)) };
});
return buildWorkBounds(this.finalPartBounds, this.installed, context, entries);
}
fitBuildView({ stageChanged = false, animate = false, force = false } = {}) {
if (!this.finalPartBounds || this.stepIndex === null) return;
const bounds = this.currentWorkBounds();
const currentDirection = this.camera.position.clone().sub(this.controls.target).normalize();
const head = this.stepHeadDirection();
const headVisible = !head || currentDirection.dot(head) >= .35;
if (!stageChanged && !force && headVisible && workBoundsFit(bounds, this.camera)) return;
const group = this.groupBounds?.get(assemblyStageKey(this.config, this.stepIndex));
const direction = headFacingView(stageChanged || force ? (group ? componentViewDirection(group, this.assembledBounds) : new THREE.Vector3(1,.3,-.65))
: currentDirection, head);
const frame = this.frameForBounds(bounds, direction);
this.controls.minDistance = 0.03;
this.controls.maxPolarAngle = Math.PI * .95;
// Keep the work visible while moving to the installation side, then hold.
this.moveCamera(frame, animate);
}
stepHeadDirection() {
const step = this.config?.steps[this.stepIndex];
if (!step || step.type === 'join' || step.parts.length !== 1 || !this.templates) return null;
const part = this.partConfigs.get(step.parts[0]);
return assemblyHeadDirection(part, this.parts.get(part.id), this.templates.get(part.file), this.headDirections);
}
resetView() {
if (!this.assembledBounds) return;
if (this.closeupEnabled) this.setCloseup(false, { restore: false });
this.focusedPartId = null;
this.cancelCameraTransition();
if (isGroupedAssembly(this.config) && Number.isInteger(this.stepIndex) && !this.exploded) {
this.fitBuildView({ force:true });
return;
}
const groupBounds = this.groupBounds?.get(assemblyStageKey(this.config, this.stepIndex ?? null));
this.controls.minDistance = groupBounds ? 0.03 : 0.65;
this.controls.maxPolarAngle = Math.PI * 0.49;
const bounds = this.exploded ? this.explodedLayout.boundsAt(this.explosionTarget) : (groupBounds || this.assembledBounds);
const frame = this.frameForBounds(bounds);
if (this.explosionTransition) {
// Resizing/control-bar changes may happen after the toggle's first frame.
this.explosionTransition.frame = frame;
return;
}
this.moveCamera(frame);
}
setAutoRotate(enabled) { this.controls.autoRotate = enabled; this.loop.invalidate(); }
resize(refit = true) {
const { clientWidth: width, clientHeight: height } = this.container;
if (!width || !height || this.disposed) return;
this.renderer.setPixelRatio(this.budget.pixelRatio(width, height));
this.renderer.shadowMap.enabled = this.budget.shadows;
this.renderer.setSize(width, height);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
if (refit) {
if (this.closeupEnabled) this.refreshCloseup(true, this.focusedPartId, false);
else if (isGroupedAssembly(this.config) && Number.isInteger(this.stepIndex)) {
this.cancelCameraTransition();
this.fitBuildView();
} else this.resetView();
}
this.loop?.invalidate();
}
render(dt) {
if (this.disposed) return;
if (this.explosionTransition) {
const transition = this.explosionTransition;
transition.elapsed += dt;
const t = Math.min(1, transition.elapsed / 0.6), eased = t * t * (3 - 2 * t);
this.explosionAmount = THREE.MathUtils.lerp(transition.from, transition.target, eased);
this.explodedLayout.apply(this.explosionAmount);
if (transition.moveCamera) {
this.camera.position.lerpVectors(transition.camera, transition.frame.position, eased);
this.controls.target.lerpVectors(transition.focus, transition.frame.target, eased);
}
this.renderer.shadowMap.needsUpdate = true;
if (t === 1) this.explosionTransition = null;
}
const cameraSettling = !!this.cameraTransition;
if (cameraSettling && !this.animationPaused) {
const t = this.cameraTransition;
t.elapsed += dt;
sampleCameraMove(t, this.camera, this.controls.target);
if (t.elapsed >= t.duration) this.cancelCameraTransition();
}
const wasAnimating = cameraSettling || this.transitions?.length > 0;
// Settle the shot BEFORE installation; the camera never chases moving parts.
if (!this.animationPaused && !cameraSettling) for (const transition of this.transitions || []) {
if (transition.update) transition.update(dt);
else {
transition.elapsed += dt;
const t = Math.min(1, transition.elapsed / transition.duration);
transition.instance.position.lerpVectors(transition.from, transition.target, assemblyEase(t));
}
if (transition.elapsed >= transition.duration) transition.dispose?.();
this.renderer.shadowMap.needsUpdate = true;
}
this.transitions = (this.transitions || []).filter((transition) => transition.elapsed < transition.duration);
this.notifyMotion();
if (wasAnimating && !this.transitions.length && !this.cameraTransition) this.onAnimationEnd?.();
const moving = this.controls.update(dt);
this.renderer.render(this.scene, this.camera);
return moving || this.controls.autoRotate || !!this.explosionTransition || (!this.animationPaused && (!!this.cameraTransition || this.transitions.length > 0));
}
dispose() {
if (this.disposed) return;
this.disposed = true;
this.lifecycle.abort();
for (const transition of this.transitions || []) transition.dispose?.();
this.transitions = [];
this.loop.dispose();
document.removeEventListener('visibilitychange', this.onVisibility);
this.resizeObserver.disconnect();
this.intersectionObserver.disconnect();
this.controls.dispose();
disposeObject([this.scene, ...this.templates?.values() || []]);
this.templates?.clear();
this.parts?.clear();
this.partConfigs?.clear();
this.focusBounds?.clear();
this.headDirections?.clear();
this.groupBounds?.clear();
this.finalPartBounds?.clear();
this.cameraTransition = null;
this.closeupShot = null;
this.scene.traverse((object) => object.shadow?.dispose());
this.environment.dispose();
this.renderer.dispose();
this.renderer.forceContextLoss();
this.renderer.domElement.remove();
this.scene.clear();
this.model = this.config = this.explodedLayout = this.explosionTransition = null;
}
}