forked from longtao.wu/droboticflow
325 lines
12 KiB
TypeScript
325 lines
12 KiB
TypeScript
import type { KeyboardEvent, PointerEvent, ReactNode } from "react";
|
||
import { useCallback, useEffect, useRef, useState } from "react";
|
||
import * as THREE from "three";
|
||
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
|
||
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
|
||
import { getObjKeyboardPan } from "../lib/obj-model-controls.js";
|
||
import { cn } from "../lib/utils";
|
||
|
||
type ObjModelPreviewProps = {
|
||
src: string;
|
||
title: string;
|
||
actions?: ReactNode;
|
||
className?: string;
|
||
viewerClassName?: string;
|
||
};
|
||
|
||
type ViewerStatus = "loading" | "ready" | "error";
|
||
|
||
const fitObjectToView = (camera: THREE.PerspectiveCamera, controls: OrbitControls, object: THREE.Object3D) => {
|
||
const box = new THREE.Box3().setFromObject(object);
|
||
const size = box.getSize(new THREE.Vector3());
|
||
const center = box.getCenter(new THREE.Vector3());
|
||
const maxSize = Math.max(size.x, size.y, size.z) || 1;
|
||
|
||
object.position.sub(center);
|
||
const normalizedBox = new THREE.Box3().setFromObject(object);
|
||
const normalizedCenter = normalizedBox.getCenter(new THREE.Vector3());
|
||
const normalizedSize = normalizedBox.getSize(new THREE.Vector3());
|
||
const radius = Math.max(normalizedSize.x, normalizedSize.y, normalizedSize.z, maxSize) * 0.72 || 1;
|
||
const distance = radius / Math.sin(THREE.MathUtils.degToRad(camera.fov / 2));
|
||
|
||
camera.near = Math.max(distance / 100, 0.001);
|
||
camera.far = distance * 100;
|
||
camera.position.set(distance * 0.45, distance * 0.35, distance * 0.95);
|
||
camera.lookAt(normalizedCenter);
|
||
camera.updateProjectionMatrix();
|
||
|
||
controls.target.copy(normalizedCenter);
|
||
controls.minDistance = Math.max(distance * 0.08, 0.01);
|
||
controls.maxDistance = distance * 8;
|
||
controls.update();
|
||
};
|
||
|
||
const applyDefaultMaterial = (object: THREE.Object3D) => {
|
||
const material = new THREE.MeshStandardMaterial({
|
||
color: 0x18c7d2,
|
||
metalness: 0.08,
|
||
roughness: 0.62,
|
||
side: THREE.DoubleSide,
|
||
});
|
||
const edgeMaterial = new THREE.LineBasicMaterial({ color: 0xe8fcff, transparent: true, opacity: 0.32 });
|
||
const edges: THREE.LineSegments[] = [];
|
||
|
||
object.traverse((child) => {
|
||
if (child instanceof THREE.Mesh) {
|
||
child.material = material;
|
||
child.castShadow = true;
|
||
child.receiveShadow = true;
|
||
child.geometry.computeVertexNormals();
|
||
const edge = new THREE.LineSegments(new THREE.EdgesGeometry(child.geometry, 28), edgeMaterial);
|
||
edge.position.copy(child.position);
|
||
edge.rotation.copy(child.rotation);
|
||
edge.scale.copy(child.scale);
|
||
edges.push(edge);
|
||
}
|
||
});
|
||
|
||
edges.forEach((edge) => object.add(edge));
|
||
};
|
||
|
||
const disposeObject = (object: THREE.Object3D) => {
|
||
object.traverse((child) => {
|
||
if (child instanceof THREE.Mesh || child instanceof THREE.LineSegments) {
|
||
child.geometry?.dispose();
|
||
const material = child.material;
|
||
if (Array.isArray(material)) {
|
||
material.forEach((item) => item.dispose());
|
||
} else {
|
||
material?.dispose();
|
||
}
|
||
}
|
||
});
|
||
};
|
||
|
||
export function ObjModelPreview({ src, title, actions, className, viewerClassName }: ObjModelPreviewProps) {
|
||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||
const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
|
||
const controlsRef = useRef<OrbitControls | null>(null);
|
||
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
|
||
const modelRef = useRef<THREE.Object3D | null>(null);
|
||
const resetViewRef = useRef<(() => void) | null>(null);
|
||
const [status, setStatus] = useState<ViewerStatus>("loading");
|
||
const [error, setError] = useState("");
|
||
|
||
const handleViewerPointerDown = useCallback((event: PointerEvent<HTMLDivElement>) => {
|
||
event.currentTarget.focus({ preventScroll: true });
|
||
}, []);
|
||
|
||
const handleViewerKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {
|
||
const keyboardPan = getObjKeyboardPan(event.key, event.shiftKey);
|
||
const camera = cameraRef.current;
|
||
const controls = controlsRef.current;
|
||
if (!keyboardPan || !camera || !controls) {
|
||
return;
|
||
}
|
||
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
|
||
camera.updateMatrixWorld();
|
||
const distance = Math.max(camera.position.distanceTo(controls.target), controls.minDistance, 0.01);
|
||
const step = distance * keyboardPan.distanceRatio;
|
||
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrixWorld, 0).normalize();
|
||
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrixWorld, 1).normalize();
|
||
const offset = right
|
||
.multiplyScalar(keyboardPan.horizontal * step)
|
||
.add(up.multiplyScalar(keyboardPan.vertical * step));
|
||
|
||
camera.position.add(offset);
|
||
controls.target.add(offset);
|
||
controls.update();
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
const container = containerRef.current;
|
||
if (!container || !src) {
|
||
return;
|
||
}
|
||
|
||
let disposed = false;
|
||
let animationId = 0;
|
||
let inViewport = typeof IntersectionObserver === "undefined";
|
||
setStatus("loading");
|
||
setError("");
|
||
container.replaceChildren();
|
||
|
||
const scene = new THREE.Scene();
|
||
scene.background = new THREE.Color(0x0f1012);
|
||
|
||
const camera = new THREE.PerspectiveCamera(42, 1, 0.01, 1000);
|
||
cameraRef.current = camera;
|
||
|
||
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
|
||
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
|
||
renderer.shadowMap.enabled = true;
|
||
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
|
||
rendererRef.current = renderer;
|
||
container.appendChild(renderer.domElement);
|
||
|
||
const controls = new OrbitControls(camera, renderer.domElement);
|
||
controls.enableDamping = true;
|
||
controls.dampingFactor = 0.08;
|
||
controls.screenSpacePanning = true;
|
||
controlsRef.current = controls;
|
||
|
||
const ambient = new THREE.HemisphereLight(0xffffff, 0x263449, 1.8);
|
||
scene.add(ambient);
|
||
|
||
const keyLight = new THREE.DirectionalLight(0xffffff, 2.4);
|
||
keyLight.position.set(3, 5, 4);
|
||
keyLight.castShadow = true;
|
||
scene.add(keyLight);
|
||
|
||
const fillLight = new THREE.DirectionalLight(0x9fdcff, 1.1);
|
||
fillLight.position.set(-4, 1, -3);
|
||
scene.add(fillLight);
|
||
|
||
const grid = new THREE.GridHelper(2, 16, 0x3e5361, 0x24313a);
|
||
grid.position.y = -0.55;
|
||
scene.add(grid);
|
||
|
||
const resize = () => {
|
||
const width = Math.max(container.clientWidth, 320);
|
||
const height = Math.max(container.clientHeight, 320);
|
||
camera.aspect = width / height;
|
||
camera.updateProjectionMatrix();
|
||
renderer.setSize(width, height, false);
|
||
};
|
||
resize();
|
||
|
||
const observer = new ResizeObserver(resize);
|
||
observer.observe(container);
|
||
|
||
const animate = () => {
|
||
animationId = 0;
|
||
if (disposed || !inViewport || document.visibilityState !== "visible") return;
|
||
controls.update();
|
||
renderer.render(scene, camera);
|
||
animationId = window.requestAnimationFrame(animate);
|
||
};
|
||
const startAnimation = () => {
|
||
if (!disposed && inViewport && document.visibilityState === "visible" && animationId === 0) {
|
||
animationId = window.requestAnimationFrame(animate);
|
||
}
|
||
};
|
||
const stopAnimation = () => {
|
||
if (animationId !== 0) {
|
||
window.cancelAnimationFrame(animationId);
|
||
animationId = 0;
|
||
}
|
||
};
|
||
const viewportObserver =
|
||
typeof IntersectionObserver === "undefined"
|
||
? null
|
||
: new IntersectionObserver(
|
||
(entries) => {
|
||
inViewport = entries.some((entry) => entry.isIntersecting);
|
||
if (inViewport) {
|
||
startAnimation();
|
||
} else {
|
||
stopAnimation();
|
||
}
|
||
},
|
||
{ rootMargin: "120px" },
|
||
);
|
||
viewportObserver?.observe(container);
|
||
const handleVisibilityChange = () => {
|
||
if (document.visibilityState === "visible") {
|
||
startAnimation();
|
||
} else {
|
||
stopAnimation();
|
||
}
|
||
};
|
||
document.addEventListener("visibilitychange", handleVisibilityChange);
|
||
startAnimation();
|
||
|
||
const load = async () => {
|
||
try {
|
||
const response = await fetch(src, { credentials: "include" });
|
||
if (!response.ok) {
|
||
throw new Error(`HTTP ${response.status}`);
|
||
}
|
||
const text = await response.text();
|
||
if (disposed) return;
|
||
const model = new OBJLoader().parse(text);
|
||
if (!model.children.length) {
|
||
throw new Error("OBJ 文件没有可渲染的 mesh");
|
||
}
|
||
applyDefaultMaterial(model);
|
||
scene.add(model);
|
||
modelRef.current = model;
|
||
resetViewRef.current = () => fitObjectToView(camera, controls, model);
|
||
resetViewRef.current();
|
||
startAnimation();
|
||
setStatus("ready");
|
||
} catch (loadError) {
|
||
if (!disposed) {
|
||
setStatus("error");
|
||
setError(loadError instanceof Error ? loadError.message : String(loadError));
|
||
}
|
||
}
|
||
};
|
||
void load();
|
||
|
||
return () => {
|
||
disposed = true;
|
||
observer.disconnect();
|
||
viewportObserver?.disconnect();
|
||
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
||
stopAnimation();
|
||
controls.dispose();
|
||
if (modelRef.current) {
|
||
disposeObject(modelRef.current);
|
||
scene.remove(modelRef.current);
|
||
}
|
||
disposeObject(scene);
|
||
renderer.dispose();
|
||
renderer.domElement.remove();
|
||
rendererRef.current = null;
|
||
controlsRef.current = null;
|
||
cameraRef.current = null;
|
||
modelRef.current = null;
|
||
resetViewRef.current = null;
|
||
};
|
||
}, [src]);
|
||
|
||
return (
|
||
<div className={cn("overflow-hidden rounded-xl border border-[#2a2b2f] bg-[#0f1012]", className)}>
|
||
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#2a2b2f] p-3">
|
||
<div>
|
||
<div className="text-sm font-semibold text-white">{title}</div>
|
||
<div className="text-xs text-gray-500">OBJ mesh</div>
|
||
</div>
|
||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||
<button
|
||
type="button"
|
||
onClick={() => resetViewRef.current?.()}
|
||
className="inline-flex items-center justify-center rounded-lg border border-[#2a2b2f] bg-white/5 px-3 py-2 text-xs font-semibold text-white transition-colors hover:bg-white/10 disabled:cursor-not-allowed disabled:opacity-50"
|
||
disabled={status !== "ready"}
|
||
>
|
||
重置视角
|
||
</button>
|
||
{actions}
|
||
</div>
|
||
</div>
|
||
<div className={cn("relative min-h-[320px] w-full", viewerClassName || "h-[460px]")}>
|
||
<div
|
||
ref={containerRef}
|
||
role="application"
|
||
aria-label="OBJ 3D 预览,点击后可使用方向键平移视角"
|
||
data-testid="obj-model-viewer"
|
||
tabIndex={0}
|
||
onPointerDown={handleViewerPointerDown}
|
||
onKeyDown={handleViewerKeyDown}
|
||
className="h-full w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-400/70 focus-visible:ring-inset"
|
||
/>
|
||
{status !== "ready" ? (
|
||
<div className="absolute inset-0 flex items-center justify-center bg-[#0f1012]/78 p-6 text-center text-sm">
|
||
{status === "loading" ? (
|
||
<span className="text-gray-300">正在加载 OBJ 预览...</span>
|
||
) : (
|
||
<span className="max-w-[520px] rounded-lg border border-[#3f2424] bg-[#1f1111] p-4 text-red-200">
|
||
OBJ 预览加载失败:{error || "未知错误"}
|
||
</span>
|
||
)}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
<div className="border-t border-[#2a2b2f] px-3 py-2 text-xs text-gray-500">
|
||
拖拽旋转,滚轮缩放,右键或双指平移;点击画布后可用方向键平移,Shift + 方向键加速。
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|