Files
vibemake/js/viewer.js
T

651 lines
28 KiB
JavaScript
Raw 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.
// RobotViewer:加载 URDF、渲染场景、关节拖拽、驾驶跟随。首页轮播和工作台共用。
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';
import { STLLoader } from 'three/addons/loaders/STLLoader.js';
import { ColladaLoader } from 'three/addons/loaders/ColladaLoader.js';
import URDFLoader from 'urdf-loader';
import { URDFDragControls } from 'urdf-loader/src/URDFDragControls.js';
import { MotionController } from './motion.js';
import { prepareRobotMaterial } from './robot-materials.js';
import { createStudioEnvironment } from './studio-environment.js';
export const ACCENT = '#c8ff3e';
const GRID_SPACING = 0.075;
// 只统计看得见的网格(URDF 的碰撞体默认隐藏,不能参与落地计算)
const _tmpBox = new THREE.Box3();
function visibleBox(root, out = new THREE.Box3()) {
out.makeEmpty();
root.traverseVisible((o) => {
if (!o.isMesh || !o.geometry) return;
if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();
out.union(_tmpBox.copy(o.geometry.boundingBox).applyMatrix4(o.matrixWorld));
});
return out;
}
const GRID_RADIUS = 3.2;
let draco;
function dracoLoader() {
if (!draco) {
draco = new DRACOLoader();
draco.setDecoderPath('/vendor/three/examples/jsm/libs/draco/gltf/');
}
return draco;
}
export class RobotViewer extends EventTarget {
constructor(container, opts = {}) {
super();
this.opts = { autoRotate: false, zoom: false, intro: true, dragJoints: true, follow: false, width: 0, height: 0, preserveDrawingBuffer: false, ...opts };
this.studioLighting = this.opts.renderPreset === 'studio';
this.container = container;
this.mode = 'showcase';
this.robot = null;
this.motion = null;
this.loadToken = 0;
this.resumeAt = 0;
this.dragging = false;
this.lastRobotPos = new THREE.Vector3();
// 缩略图共用同一个离屏渲染器(opts.renderer),避免反复创建 / 销毁 WebGL 上下文
const r = (this.renderer = this.opts.renderer || new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: this.opts.preserveDrawingBuffer }));
r.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
r.outputColorSpace = THREE.SRGBColorSpace;
r.toneMapping = THREE.ACESFilmicToneMapping;
r.toneMappingExposure = this.studioLighting ? 0.82 : 0.95;
r.shadowMap.enabled = true;
// PCFShadowMap 的 radius 才能控制采样范围;PCFSoftShadowMap 会忽略它。
r.shadowMap.type = this.studioLighting ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
r.domElement.classList.add('vm-canvas');
// 第一帧画出来之前隐藏,避免刷新时闪白。
// 用 visibility 而不是 opacity 渐变:Chrome 对 WebGL 画布做透明度动画时偶尔会合成出一块白
r.domElement.style.visibility = 'hidden';
container.appendChild(r.domElement);
// 上下文丢失时(GPU 重置、显存紧张)先藏起画布,恢复后再显示,不让用户看到空白画布
if (!this.opts.renderer) {
// 刷新 / 离开页面时 Chrome 会先回收 WebGL 画布,但旧页面最后一帧还会显示一会儿,
// 被回收的画布就是一块白。提前把画布藏起来,露出的是背景。
const hide = () => {
r.domElement.style.visibility = 'hidden';
// 如果最后并没有离开(比如点的是下载链接),稍后再显示回来
setTimeout(() => { if (this.robot) r.domElement.style.visibility = 'visible'; }, 1500);
};
addEventListener('beforeunload', hide);
addEventListener('pagehide', hide);
addEventListener('pageshow', (e) => { if (e.persisted && this.robot) this.revealPending = true; });
r.domElement.addEventListener('webglcontextlost', (e) => { e.preventDefault(); r.domElement.style.visibility = 'hidden'; });
r.domElement.addEventListener('webglcontextrestored', () => { if (this.robot) this.revealPending = true; });
}
this.scene = new THREE.Scene();
const pmrem = new THREE.PMREMGenerator(r);
const environment = this.studioLighting ? createStudioEnvironment() : new RoomEnvironment(r);
this.environmentTarget = pmrem.fromScene(environment, this.studioLighting ? 0.015 : 0.04);
this.scene.environment = this.environmentTarget.texture;
disposeObject(environment);
pmrem.dispose();
this.camera = new THREE.PerspectiveCamera(32, 1, 0.01, 100);
this.camera.position.set(1.8, 0.9, 2.0);
this.addLights();
this.stage = new THREE.Group(); // 统一缩放:机器人最大尺寸 = 1
this.base = new THREE.Group(); // 底盘位姿(米,驾驶时移动)
this.stage.add(this.base);
this.scene.add(this.stage);
this.addGround();
// 必须在 OrbitControls 之前注册:按在关节上时禁止旋转视角
if (this.opts.dragJoints) this.setupDrag();
this.controls = new OrbitControls(this.camera, r.domElement);
Object.assign(this.controls, {
enableDamping: true, dampingFactor: 0.08, enablePan: false,
// 默认不拦截滚轮,滚动就是滚动页面;全屏的工作台再打开缩放
enableZoom: this.opts.zoom,
minDistance: 1.1, maxDistance: 6, maxPolarAngle: Math.PI * 0.49,
autoRotate: this.opts.autoRotate, autoRotateSpeed: 0.35,
});
this.controls.addEventListener('start', () => this.dispatchEvent(new Event('interact')));
this.resize();
if (!this.opts.width) {
this.ro = new ResizeObserver(() => this.resize());
this.ro.observe(container);
}
this.clock = new THREE.Clock();
r.setAnimationLoop(() => this.tick());
// 滚出屏幕时暂停渲染(省 GPU、滚动更顺),回来再继续
// 离屏缩略图(opts.width)的画布不在页面上,不参与
if (!this.opts.width) this.io = new IntersectionObserver(([e]) => {
if (e.isIntersecting === this.visible) return;
this.visible = e.isIntersecting;
r.setAnimationLoop(this.visible ? () => this.tick() : null);
if (this.visible) this.clock.getDelta(); // 丢掉暂停期间的时间,动画不会跳一下
});
this.visible = true;
this.io?.observe(this.renderer.domElement);
}
addLights() {
const s = this.scene;
const studio = this.studioLighting;
s.add(new THREE.HemisphereLight(studio ? 0xffffff : 0xdfe4ea, 0x0b0c0e, studio ? 0.16 : 0.9));
const key = new THREE.DirectionalLight(0xffffff, studio ? 3 : 2.4);
this.keyOffset = new THREE.Vector3(...(studio ? [2.5, 3, 3.5] : [1.6, 3.2, 1.4]));
key.position.copy(this.keyOffset);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
Object.assign(key.shadow.camera, { left: -1.4, right: 1.4, top: 1.4, bottom: -1.4, near: 0.1, far: 8 });
key.shadow.bias = studio ? -0.00015 : -0.0004;
key.shadow.normalBias = studio ? 0.003 : 0.02;
key.shadow.radius = studio ? 4 : 6;
this.key = key;
s.add(key, key.target);
const rim = new THREE.DirectionalLight(studio ? 0xffffff : new THREE.Color(ACCENT), studio ? 0.55 : 1.1);
rim.position.set(-2.2, 1.4, -2.4);
s.add(rim);
const fill = new THREE.DirectionalLight(studio ? 0xffffff : 0x9fb4ff, studio ? 0.18 : 0.35);
fill.position.set(-2, 0.6, 2);
s.add(fill);
}
// 地面:会跟随机器人平移的无限点阵 + 品牌色光圈
addGround() {
const n = Math.ceil(GRID_RADIUS / GRID_SPACING);
const pts = [];
for (let i = -n; i <= n; i++) for (let j = -n; j <= n; j++) {
if (Math.hypot(i, j) * GRID_SPACING <= GRID_RADIUS) pts.push(i * GRID_SPACING, 0, j * GRID_SPACING);
}
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.Float32BufferAttribute(pts, 3));
this.groundUniforms = {
uCenter: { value: new THREE.Vector2() },
uRadius: { value: this.opts.groundRadius ?? GRID_RADIUS * 0.9 },
uScale: { value: this.renderer.getPixelRatio() },
uColor: { value: new THREE.Color('#8b9099') },
uAccent: { value: new THREE.Color(ACCENT) },
uOpacity: { value: this.studioLighting ? 0.22 : 0.5 },
uAccentMix: { value: this.studioLighting ? 0.12 : 0.55 },
};
this.ground = new THREE.Points(geo, new THREE.ShaderMaterial({
uniforms: this.groundUniforms,
transparent: true,
depthWrite: false,
vertexShader: /* glsl */`
uniform vec2 uCenter; uniform float uRadius; uniform float uScale;
varying float vFade; varying float vNear;
void main() {
vec4 world = modelMatrix * vec4(position, 1.0);
float d = distance(world.xz, uCenter);
vFade = 1.0 - smoothstep(uRadius * 0.15, uRadius, d);
vNear = 1.0 - smoothstep(0.0, 0.7, d);
vec4 mv = viewMatrix * world;
gl_PointSize = clamp(uScale * 7.0 / -mv.z, 1.0, 9.0);
gl_Position = projectionMatrix * mv;
}`,
fragmentShader: /* glsl */`
uniform vec3 uColor; uniform vec3 uAccent;
uniform float uOpacity; uniform float uAccentMix;
varying float vFade; varying float vNear;
void main() {
float r = length(gl_PointCoord - 0.5);
if (r > 0.5) discard;
float a = smoothstep(0.5, 0.25, r) * vFade * uOpacity;
gl_FragColor = vec4(mix(uColor, uAccent, vNear * uAccentMix), a);
}`,
}));
this.ground.renderOrder = -1;
this.scene.add(this.ground);
this.shadowPlane = new THREE.Mesh(new THREE.PlaneGeometry(6, 6), new THREE.ShadowMaterial({ opacity: this.studioLighting ? 0.32 : 0.45, depthWrite: false }));
this.shadowPlane.rotation.x = -Math.PI / 2;
this.shadowPlane.receiveShadow = true;
this.scene.add(this.shadowPlane);
const halo = new THREE.Mesh(new THREE.RingGeometry(0.42, 0.424, 128), new THREE.MeshBasicMaterial({
color: ACCENT, transparent: true, opacity: this.studioLighting ? 0.16 : 0.35, depthWrite: false,
}));
halo.rotation.x = -Math.PI / 2;
halo.position.y = 0.002;
const ticks = new THREE.Group();
for (let i = 0; i < 4; i++) {
const t = new THREE.Mesh(new THREE.PlaneGeometry(0.004, 0.05), halo.material);
const a = (i * Math.PI) / 2;
t.position.set(Math.cos(a) * 0.45, Math.sin(a) * 0.45, 0);
t.rotation.z = a + Math.PI / 2;
ticks.add(t);
}
halo.add(ticks);
this.halo = halo;
this.scene.add(halo);
}
setupDrag() {
const dc = (this.drag = new URDFDragControls(this.base));
const canvas = this.renderer.domElement;
const pointer = new THREE.Vector2();
const caster = new THREE.Raycaster();
// moveRay 会根据上一条射线和新射线的差值转动正在拖拽的关节,然后刷新 hover
const ray = (e) => {
const rect = canvas.getBoundingClientRect();
pointer.set(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
caster.setFromCamera(pointer, this.camera);
dc.moveRay(caster.ray);
};
dc.onHover = (joint) => { this.highlight(joint, true); canvas.style.cursor = 'grab'; this.emit('hover', { joint: joint.name }); };
dc.onUnhover = (joint) => { this.highlight(joint, false); canvas.style.cursor = ''; this.emit('hover', { joint: null }); };
dc.onDragStart = () => { this.dragging = true; canvas.style.cursor = 'grabbing'; this.emit('interact'); };
dc.onDragEnd = () => {
this.dragging = false;
this.controls.enabled = true;
canvas.style.cursor = dc.hovered ? 'grab' : '';
this.resumeAt = performance.now() + 2500;
};
dc.updateJoint = (joint, angle) => { joint.setJointValue(angle); this.emit('joint', { joint: joint.name, value: joint.angle }); };
canvas.addEventListener('pointermove', (e) => { if (e.pointerType === 'touch' && !dc.manipulating) return; ray(e); });
canvas.addEventListener('pointerdown', (e) => {
if (e.button !== 0 || !this.robot) return;
ray(e);
if (dc.hovered) {
this.controls.enabled = false;
dc.setGrabbed(true);
canvas.setPointerCapture(e.pointerId);
}
});
const release = () => { if (dc.manipulating) dc.setGrabbed(false); };
canvas.addEventListener('pointerup', release);
canvas.addEventListener('pointercancel', release);
}
highlight(joint, on) {
joint.traverse((o) => {
if (!o.isMesh) return;
for (const mat of [].concat(o.material || [])) {
if (!mat.emissive) continue;
const base = mat.userData.baseEmissive;
mat.emissive.set(on ? ACCENT : base?.color ?? 0x000000);
mat.emissiveIntensity = on ? 0.22 : base?.intensity ?? 0;
}
});
}
emit(type, detail) { this.dispatchEvent(new CustomEvent(type, { detail })); }
resize() {
const w = this.opts.width || this.container.clientWidth || 1;
const h = this.opts.height || this.container.clientHeight || 1;
this.renderer.setSize(w, h, false);
this.camera.aspect = w / h;
this.camera.updateProjectionMatrix();
}
async load(config) {
const token = ++this.loadToken;
this.clearRobot();
// keepModels:加载过的模型留在内存里(首页轮播),切回来直接显示,不再读文件、不重新组装
const key = config.id || config.urdf;
const entry = this.opts.keepModels && this.models?.get(key);
if (entry?.ready) return this.show(entry.ready, config); // 已经组装好:立刻显示
this.emit('loading', { config });
if (entry) { // 正在后台组装:等它完成
const robot = await entry.catch(() => null);
if (token !== this.loadToken) return null;
if (robot) return this.show(robot, config);
}
this.renderer.domElement.style.visibility = 'hidden';
const job = this.build(config, (loaded, total) => this.emit('progress', { loaded, total }));
if (this.opts.keepModels) this.remember(key, job);
const robot = await job;
if (token !== this.loadToken) { if (!this.opts.keepModels) disposeObject(robot); return null; }
return this.show(robot, config);
}
// 后台把模型组装好放进内存(不显示),之后 load 同一个模型时直接用(需要 keepModels)
preload(config) {
const key = config.id || config.urdf;
if (!this.opts.keepModels || this.models?.has(key)) return;
this.remember(key, this.build(config));
}
remember(key, job) {
(this.models ??= new Map()).set(key, job);
job.then((robot) => { job.ready = robot; }, () => this.models.delete(key)); // 失败的不缓存,下次重试
}
// 读 URDF 和网格,组装成可以放进场景的模型
async build(config, onProgress) {
const manager = new THREE.LoadingManager();
const loader = new URDFLoader(manager);
loader.packages = config.packages || '';
// 后端仓库里的文件不是普通静态路径,由配置提供地址改写(见 source.js)
if (config.resolveUrl) manager.setURLModifier(config.resolveUrl);
loader.parseCollision = false;
if (onProgress) manager.onProgress = (_url, loaded, total) => onProgress(loaded, total);
manager.onError = (url) => console.warn('[vibemake] 资源加载失败:', url);
// 自己数网格:LoadingManager 的 onLoad 在网格命中缓存、瞬间返回时会提前触发,
// 那时模型还是空的,取景会算错(缩略图里看不到机器人)
const robot = await new Promise((resolve, reject) => {
let model = null;
let pending = 0;
const check = () => { if (model && pending === 0) resolve(model); };
loader.loadMeshCb = (path, mgr, done) => {
pending++;
const candidates = config.resolveMeshUrls?.(path) || [path];
this.loadMeshWithFallback(candidates, mgr, (mesh, err) => { done(mesh, err); pending--; queueMicrotask(check); });
};
loader.load(config.urdf, (m) => { model = m; queueMicrotask(check); }, undefined, reject);
});
// URDF 多为 z 轴朝上;facing(度)用来把模型的正面转到 +x(我们的「前进」方向)
const upFix = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), (config.upAxis || 'z').toLowerCase() === 'z' ? -Math.PI / 2 : 0);
const facing = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), THREE.MathUtils.degToRad(config.facing || 0));
robot.quaternion.copy(facing.multiply(upFix));
robot.traverse((o) => {
if (!o.isMesh) return;
o.castShadow = true;
o.receiveShadow = true;
o.material = prepareRobotMaterial(o.material, config.paint);
});
this.addExtras(robot, config.extras);
return robot;
}
// 把已经组装好的模型放进场景
show(robot, config) {
this.robot = robot;
this.base.add(robot);
this.motion = new MotionController(robot, config);
this.motion.mode = this.mode;
this.motion.applyStance();
this.frame(config.view || {});
// 登场:淡入 + 从略小的尺寸放大 + 转半圈到位
this.introT = this.opts.intro ? 0 : 1;
this.revealPending = true; // 等这一帧真正画完再显示
const dof = this.motion.movable.length;
this.emit('load', { config, robot, dof, joints: this.motion.movable.map(j => j.name), missing: this.motion.missing });
return robot;
}
loadMesh(path, manager, done) {
const ext = path.split(/[?#]/)[0].split('.').pop().toLowerCase();
const fail = (err) => done(null, err);
if (ext === 'glb' || ext === 'gltf') {
new GLTFLoader(manager).setDRACOLoader(dracoLoader()).load(path, (g) => {
// 只有一个网格(打包时由 STL 转来的)时直接交出网格本身:urdf-loader 只给顶层网格套 URDF 里的材质颜色
const meshes = [];
g.scene.traverse((o) => { if (o.isMesh) meshes.push(o); });
if (meshes.length === 1 && meshes[0].matrixWorld.equals(new THREE.Matrix4())) { meshes[0].removeFromParent(); done(meshes[0]); } else done(g.scene);
}, undefined, fail);
} else if (ext === 'obj') {
new OBJLoader(manager).load(path, done, undefined, fail);
} else if (ext === 'stl') {
new STLLoader(manager).load(path, (geometry) => done(new THREE.Mesh(geometry, new THREE.MeshPhongMaterial())), undefined, fail);
} else if (ext === 'dae') {
new ColladaLoader(manager).load(path, (dae) => done(dae.scene), undefined, fail);
} else {
fail(new Error(`没有可用的网格加载器:${path}`));
}
}
loadMeshWithFallback(paths, manager, done) {
const candidates = [...new Set(paths)].slice(0, 9);
let index = 0;
const attempt = (lastError) => {
const path = candidates[index++];
if (!path) { done(null, lastError); return; }
this.loadMesh(path, manager, (mesh, err) => {
if (err && index < candidates.length) attempt(err);
else done(mesh, err);
});
};
attempt();
}
// 归一化尺寸、落地、居中,并按 view 配置摆相机
frame(view) {
const robot = this.robot;
this.stage.scale.setScalar(1);
this.stage.rotation.set(0, 0, 0);
this.halo.scale.setScalar(1);
this.base.position.set(0, 0, 0);
this.base.rotation.set(0, 0, 0);
robot.position.set(0, 0, 0);
// 必须从 stage 开始更新:否则沿用上一个机器人的缩放,算出的落地高度是错的(切换时会「从天上掉下来」)
this.stage.updateMatrixWorld(true);
const box = visibleBox(robot);
const size = box.getSize(new THREE.Vector3());
const center = box.getCenter(new THREE.Vector3());
const maxDim = Math.max(size.x, size.y, size.z) || 1;
robot.position.set(-center.x, -box.min.y, -center.z);
this.unit = 1 / maxDim;
this.stage.scale.setScalar(this.unit);
this.height = size.y * this.unit;
if (this.studioLighting) this.fitShadows(size.clone().multiplyScalar(this.unit));
const yaw = THREE.MathUtils.degToRad(view.yaw ?? 35);
const pitch = THREE.MathUtils.degToRad(view.pitch ?? 16);
// 竖屏/窄屏时拉远,保证机器人横向不出框
const narrow = Math.max(1, 1.25 / this.camera.aspect);
// 高瘦的机器人(双足)再拉远一点,避免头顶贴边
const tall = Math.max(1, this.height / 0.8);
const dist = (this.opts.framing ?? 2.5) * (view.distance ?? 1) * narrow * tall;
const target = new THREE.Vector3(0, this.height * (this.opts.targetHeight ?? 0.42), 0);
this.controls.target.copy(target);
this.camera.position.set(
target.x + dist * Math.cos(pitch) * Math.sin(yaw),
target.y + dist * Math.sin(pitch),
target.z + dist * Math.cos(pitch) * Math.cos(yaw),
);
this.controls.update();
this.lastRobotPos.set(0, 0, 0);
}
fitShadows(size) {
// 模型已归一化;覆盖本体和地面投影,避免固定大视锥浪费阴影分辨率。
const reach = Math.max(size.x, size.z) * 0.5 + size.y * 0.8 + 0.15;
const camera = this.key.shadow.camera;
Object.assign(camera, { left: -reach, right: reach, top: reach, bottom: -reach, near: 0.1, far: 8 });
camera.updateProjectionMatrix();
}
// 步态会改变腿的高度:每帧把最低的可见部件贴到地面,脚始终着地
// 配置里的 extras:给模型补几何体(比如原模型只有眼窝没有眼珠)
// { link, shape: 'sphere' | 'cylinder', radius, length, xyz: [x, y, z], axis: 'x' | 'y' | 'z', color, roughness, metalness }
addExtras(robot, extras = []) {
for (const e of extras) {
const link = robot.links[e.link];
if (!link) { console.warn('[vibemake] extras 找不到 link:', e.link); continue; }
const geo = e.shape === 'sphere'
? new THREE.SphereGeometry(e.radius, 32, 16)
: new THREE.CylinderGeometry(e.radius, e.radius, e.length ?? e.radius * 0.5, 40);
const mat = new THREE.MeshStandardMaterial({ color: e.color || '#0a0b0d', roughness: e.roughness ?? 0.2, metalness: e.metalness ?? 0.2, envMapIntensity: 1.2 });
const mesh = new THREE.Mesh(geo, mat);
mesh.position.fromArray(e.xyz || [0, 0, 0]);
if (e.axis === 'x') mesh.rotation.z = Math.PI / 2;
if (e.axis === 'z') mesh.rotation.x = Math.PI / 2;
mesh.castShadow = true;
link.add(mesh);
}
}
// 平滑跟随而不是瞬间贴地,否则换脚时身体会一顿一顿地颠
groundRobot(dt) {
this.base.updateMatrixWorld(true);
const box = visibleBox(this.robot, this._groundBox || (this._groundBox = new THREE.Box3()));
if (box.isEmpty()) return;
const target = this.base.position.y - box.min.y / this.stage.scale.y;
this.base.position.y += (target - this.base.position.y) * (1 - Math.exp(-2.5 * dt));
}
setMode(mode) {
this.mode = mode;
if (this.motion) this.motion.mode = mode;
this.controls.autoRotate = this.opts.autoRotate && mode === 'showcase';
}
setInput(input) { this.motion?.setInput(input); }
resetPose() {
if (!this.motion) return;
this.motion.resetBase();
this.motion.applyStance();
this.base.position.set(0, 0, 0);
this.base.rotation.set(0, 0, 0);
this.frame(this.motion.config.view || {});
}
// 爆炸图:每个零件沿「离机器人中心的方向」推开,amount 0(原样)~ 1(完全展开)。
// 展开时按当前姿态计算方向;收回到 0 后清掉,下次按新的姿态重新算
setExplode(amount) {
if (!this.robot) return;
if (amount <= 0) {
for (const p of this._explode || []) p.mesh.position.copy(p.base);
this._explode = null;
this.exploded = 0;
return;
}
if (!this._explode) {
this.robot.updateMatrixWorld(true);
const box = visibleBox(this.robot, new THREE.Box3());
const center = box.getCenter(new THREE.Vector3());
const reach = box.getSize(new THREE.Vector3()).length() * 0.12;
const meshes = [];
this.robot.traverse((o) => { if (o.isMesh && o.visible) meshes.push(o); });
this._explode = meshes.map((mesh) => {
const c = new THREE.Box3().setFromObject(mesh).getCenter(new THREE.Vector3());
const dir = c.clone().sub(center);
if (dir.lengthSq() < 1e-10) dir.set(0, 1, 0).multiplyScalar(1e-3);
const push = dir.clone().multiplyScalar(0.9).add(dir.clone().normalize().multiplyScalar(reach));
const a = mesh.parent.worldToLocal(c.clone());
const b = mesh.parent.worldToLocal(c.clone().add(push));
return { mesh, base: mesh.position.clone(), delta: b.sub(a) };
});
}
this.exploded = amount;
for (const p of this._explode) p.mesh.position.copy(p.base).addScaledVector(p.delta, amount);
}
jointValues() {
const out = {};
for (const j of this.motion?.movable || []) out[j.name] = j.angle;
return out;
}
setJoints(values) {
for (const [name, v] of Object.entries(values)) this.robot?.joints[name]?.setJointValue(v);
}
robotWorldPosition(out = new THREE.Vector3()) {
const m = this.motion;
if (m?.usesBaseJoints) {
const j = m.map['base.yaw'] || m.map['base.y'] || m.map['base.x'];
return j.getWorldPosition(out).setY(0);
}
return this.base.getWorldPosition(out).setY(0);
}
tick() {
const dt = Math.min(this.clock.getDelta(), 0.05);
const m = this.motion;
const paused = this.dragging || performance.now() < this.resumeAt;
if (m && !paused && this.mode !== 'manual' && this.mode !== 'playback') m.update(dt);
if (m && !m.usesBaseJoints && this.mode === 'drive') {
this.base.position.set(m.base.x, this.base.position.y, -m.base.y);
this.base.rotation.y = m.base.yaw;
}
if (this.robot) {
if (this.introT < 1) {
this.introT = Math.min(1, this.introT + dt / 1.1);
const e = 1 - Math.pow(1 - this.introT, 3);
this.stage.scale.setScalar(this.unit * (0.86 + 0.14 * e));
this.stage.rotation.y = -0.9 * (1 - e);
this.halo.scale.setScalar(0.7 + 0.3 * e);
}
if (!this.exploded) this.groundRobot(dt); // 爆炸图展开时保持高度,不跟着零件贴地
const pos = this.robotWorldPosition();
if (this.opts.follow) {
const delta = pos.clone().sub(this.lastRobotPos);
this.camera.position.add(delta);
this.controls.target.add(delta);
}
this.lastRobotPos.copy(pos);
const snap = (v) => Math.round(v / GRID_SPACING) * GRID_SPACING;
this.ground.position.set(snap(pos.x), 0, snap(pos.z));
this.groundUniforms.uCenter.value.set(pos.x, pos.z);
this.halo.position.set(pos.x, 0.002, pos.z);
this.shadowPlane.position.set(pos.x, 0, pos.z);
const lightHeight = this.studioLighting ? this.height * 0.45 : 0;
this.key.target.position.set(pos.x, lightHeight, pos.z);
this.key.position.copy(this.key.target.position).add(this.keyOffset);
}
this.controls.update();
this.renderer.render(this.scene, this.camera);
if (this.revealPending) { this.revealPending = false; this.renderer.domElement.style.visibility = 'visible'; }
this.emit('frame', { dt });
}
snapshot(type = 'image/webp', quality = 0.85) {
this.renderer.render(this.scene, this.camera);
return this.renderer.domElement.toDataURL(type, quality);
}
clearRobot() {
if (!this.robot) return;
this.setExplode(0); // 零件位置复位(缓存的模型下次还要用)
this.base.remove(this.robot);
if (!this.opts.keepModels) disposeObject(this.robot); // 留在内存里的模型不销毁
this.robot = null;
this.motion = null;
}
dispose() {
this.io?.disconnect();
this.renderer.setAnimationLoop(null);
this.ro?.disconnect();
this.clearRobot();
this.controls.dispose();
this.environmentTarget.dispose();
disposeObject(this.ground);
disposeObject(this.shadowPlane);
disposeObject(this.halo);
this.key.shadow.dispose();
this.renderer.domElement.remove();
if (this.opts.renderer) return; // 共用的渲染器不销毁
this.renderer.dispose();
this.renderer.forceContextLoss();
}
}
function disposeObject(obj) {
obj.traverse((o) => {
o.geometry?.dispose();
[].concat(o.material || []).forEach((m) => m.dispose?.());
});
}
// 离屏渲染缩略图(配置里没提供 thumbnail 时使用)
let thumbRenderer;
export async function renderThumbnail(config, width = 560, height = 350) {
thumbRenderer ??= new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
const host = document.createElement('div');
const v = new RobotViewer(host, { width, height, framing: 2.5, targetHeight: 0.5, dragJoints: false, intro: false, renderer: thumbRenderer });
try {
await v.load(config);
v.controls.update();
return v.snapshot();
} finally {
v.dispose();
}
}