sh2/d2ypp2/web-console/components/LiveStudioScene3D.tsx
2026-06-11 00:45:55 -05:00

335 lines
13 KiB
TypeScript
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.

"use client";
import { MonitorPlay, RefreshCw, Sparkles } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
type Tr = (zh: string, en: string) => string;
type SceneStatus = "idle" | "loading" | "ready" | "failed";
function disposeThreeObject(obj: import("three").Object3D) {
obj.traverse((child) => {
const mesh = child as import("three").Mesh;
if (mesh.geometry) mesh.geometry.dispose();
const mat = mesh.material;
if (Array.isArray(mat)) mat.forEach((m) => m.dispose());
else if (mat) mat.dispose();
});
}
export function LiveStudioScene3D({
tr,
className = "",
liveActive = 0,
onOpenStudio,
}: {
tr: Tr;
className?: string;
liveActive?: number;
onOpenStudio?: () => void;
}) {
const containerRef = useRef<HTMLDivElement>(null);
/** Dedicated host — React must never reconcile children here (canvas is appended imperatively). */
const canvasHostRef = useRef<HTMLDivElement>(null);
const [status, setStatus] = useState<SceneStatus>("idle");
const [retryKey, setRetryKey] = useState(0);
const liveActiveRef = useRef(liveActive);
liveActiveRef.current = liveActive;
const retry = useCallback(() => {
setStatus("idle");
setRetryKey((k) => k + 1);
}, []);
useEffect(() => {
const host = canvasHostRef.current;
const container = containerRef.current;
if (!host || !container) return;
let disposed = false;
let animationId = 0;
let hostResizeObserver: ResizeObserver | null = null;
let sceneStarted = false;
let sceneTeardown: (() => void) | undefined;
let bootRaf = 0;
const cleanup = () => {
cancelAnimationFrame(animationId);
cancelAnimationFrame(bootRaf);
hostResizeObserver?.disconnect();
sceneTeardown?.();
sceneTeardown = undefined;
host.replaceChildren();
};
const tryStart = () => {
if (disposed || sceneStarted) return;
const w = host.clientWidth;
const h = host.clientHeight;
if (w < 16 || h < 16) return;
sceneStarted = true;
setStatus("loading");
void import("three")
.then((THREE) => {
if (disposed || !canvasHostRef.current) return;
const mount = canvasHostRef.current;
const width = mount.clientWidth;
const height = mount.clientHeight;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(48, width / height, 0.1, 80);
camera.position.set(0, 1.1, 7.2);
let renderer: import("three").WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: "high-performance" });
} catch {
if (!disposed) setStatus("failed");
return;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(width, height, false);
renderer.setClearColor(0x000000, 0);
const canvas = renderer.domElement;
canvas.style.display = "block";
canvas.style.width = "100%";
canvas.style.height = "100%";
mount.replaceChildren(canvas);
const hemi = new THREE.HemisphereLight(0xffc4ec, 0x4466ff, 0.85);
scene.add(hemi);
const dir = new THREE.DirectionalLight(0xffffff, 0.9);
dir.position.set(4, 8, 6);
scene.add(dir);
const back = new THREE.PointLight(0x7cf5ff, 0.6, 20);
back.position.set(-3, 2, -2);
scene.add(back);
const group = new THREE.Group();
const studioMat = new THREE.MeshStandardMaterial({ color: 0x2a2540, metalness: 0.15, roughness: 0.55 });
const ringMat = new THREE.MeshStandardMaterial({
color: 0xff3355,
emissive: 0x440011,
metalness: 0.35,
roughness: 0.25,
});
const playMat = new THREE.MeshStandardMaterial({ color: 0xffffff, emissive: 0x222222, metalness: 0.2, roughness: 0.3 });
const tkMat = new THREE.MeshStandardMaterial({ color: 0x25f4ee, emissive: 0x053038, metalness: 0.25, roughness: 0.35 });
const tkCapMat = new THREE.MeshStandardMaterial({ color: 0xfe2c55, emissive: 0x220510, metalness: 0.2, roughness: 0.4 });
const studio = new THREE.Mesh(new THREE.BoxGeometry(3.2, 0.35, 2.2), studioMat);
studio.position.y = -0.85;
group.add(studio);
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.72, 0.09, 12, 48), ringMat);
ring.rotation.x = Math.PI / 2;
ring.position.set(-0.85, 0.15, 0.2);
group.add(ring);
const play = new THREE.Mesh(new THREE.ConeGeometry(0.35, 0.5, 3), playMat);
play.rotation.z = -Math.PI / 2;
play.rotation.y = Math.PI;
play.position.set(-0.55, 0.18, 0.2);
group.add(play);
const tk = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.28, 0.95, 20), tkMat);
tk.position.set(1.05, 0.35, -0.15);
tk.rotation.z = 0.12;
group.add(tk);
const tkCap = new THREE.Mesh(new THREE.SphereGeometry(0.26, 16, 16), tkCapMat);
tkCap.position.set(1.05, 0.92, -0.15);
group.add(tkCap);
const starGeo = new THREE.BufferGeometry();
const starCount = 120;
const positions = new Float32Array(starCount * 3);
for (let i = 0; i < starCount; i++) {
positions[i * 3] = (Math.random() - 0.5) * 14;
positions[i * 3 + 1] = (Math.random() - 0.3) * 8;
positions[i * 3 + 2] = (Math.random() - 0.5) * 8 - 2;
}
starGeo.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const starMat = new THREE.PointsMaterial({ color: 0xffffff, size: 0.06, transparent: true, opacity: 0.7 });
const stars = new THREE.Points(starGeo, starMat);
scene.add(stars);
scene.add(group);
let pointerX = 0;
let pointerY = 0;
const onPointerMove = (e: PointerEvent) => {
const rect = mount.getBoundingClientRect();
if (!rect.width || !rect.height) return;
pointerX = ((e.clientX - rect.left) / rect.width - 0.5) * 2;
pointerY = ((e.clientY - rect.top) / rect.height - 0.5) * 2;
};
const onPointerLeave = () => {
pointerX = 0;
pointerY = 0;
};
container.addEventListener("pointermove", onPointerMove);
container.addEventListener("pointerleave", onPointerLeave);
const resize = () => {
if (!canvasHostRef.current || disposed) return;
const w = canvasHostRef.current.clientWidth;
const h = canvasHostRef.current.clientHeight;
if (w < 16 || h < 16) return;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h, false);
};
const t0 = performance.now();
let visible = !document.hidden;
const onVis = () => {
visible = !document.hidden;
};
document.addEventListener("visibilitychange", onVis);
const tick = () => {
if (disposed) return;
animationId = requestAnimationFrame(tick);
if (!visible) return;
const t = (performance.now() - t0) / 1000;
const live = liveActiveRef.current;
const livePulse = live > 0 ? 0.5 + Math.sin(t * 4) * 0.5 : 0;
group.rotation.y = Math.sin(t * 0.35) * 0.25 + t * 0.12 + pointerX * 0.08;
group.rotation.x = pointerY * -0.06;
group.position.y = Math.sin(t * 0.9) * 0.06;
ring.rotation.z = t * 0.4;
stars.rotation.y = t * 0.02;
camera.position.x += (pointerX * 0.35 - camera.position.x) * 0.06;
camera.position.y += (1.1 + pointerY * -0.2 - camera.position.y) * 0.06;
camera.lookAt(0, 0.1, 0);
if (live > 0) {
ringMat.emissive.setHex(0x440011);
ringMat.emissiveIntensity = 0.4 + livePulse * 1.2;
tkMat.emissiveIntensity = 0.3 + livePulse * 0.5;
} else {
ringMat.emissiveIntensity = 1;
tkMat.emissiveIntensity = 1;
}
renderer.render(scene, camera);
};
tick();
const sceneResizeObserver = new ResizeObserver(resize);
sceneResizeObserver.observe(mount);
if (!disposed) setStatus("ready");
sceneTeardown = () => {
document.removeEventListener("visibilitychange", onVis);
container.removeEventListener("pointermove", onPointerMove);
container.removeEventListener("pointerleave", onPointerLeave);
sceneResizeObserver.disconnect();
disposeThreeObject(group);
disposeThreeObject(stars);
starGeo.dispose();
starMat.dispose();
renderer.dispose();
renderer.forceContextLoss?.();
mount.replaceChildren();
};
})
.catch(() => {
if (!disposed) setStatus("failed");
});
};
let bootAttempts = 0;
const boot = () => {
if (disposed || sceneStarted) return;
bootAttempts += 1;
tryStart();
if (!sceneStarted && bootAttempts < 120) {
bootRaf = requestAnimationFrame(boot);
} else if (!sceneStarted && bootAttempts >= 120) {
setStatus("failed");
}
};
hostResizeObserver = new ResizeObserver(() => {
if (!sceneStarted) tryStart();
});
hostResizeObserver.observe(host);
boot();
return () => {
disposed = true;
cleanup();
};
}, [retryKey]);
return (
<div className={`flex min-h-0 flex-1 flex-col ${className}`}>
<div className="mb-2 flex shrink-0 items-center justify-between gap-2 px-1">
<p className="text-[10px] font-medium uppercase tracking-wider text-fuchsia-200/80">
{tr("直播工作室 · 3D", "Live studio · 3D")}
</p>
{liveActive > 0 ? (
<span className="studio-live-badge inline-flex items-center gap-1 rounded-full bg-rose-500/20 px-2 py-0.5 text-[9px] font-bold uppercase tracking-wide text-rose-100 ring-1 ring-rose-400/40">
<span className="relative flex h-1.5 w-1.5">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-rose-400 opacity-70" />
<span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-rose-400" />
</span>
LIVE ×{liveActive}
</span>
) : null}
</div>
<div
ref={containerRef}
className="studio-scene-shell relative min-h-0 flex-1 overflow-hidden rounded-xl bg-gradient-to-b from-fuchsia-950/40 to-cyan-950/20 ring-1 ring-white/10"
>
<div ref={canvasHostRef} className="absolute inset-0" aria-hidden />
{status === "idle" || status === "loading" ? (
<div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-2">
<div className="studio-scene-shimmer absolute inset-0 opacity-60" />
<Sparkles className="relative h-5 w-5 animate-pulse text-fuchsia-300/70" />
<p className="relative text-[10px] text-zinc-500">{tr("加载 3D 场景…", "Loading 3D scene…")}</p>
</div>
) : null}
{status === "failed" ? (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 px-4 text-center">
<MonitorPlay className="h-8 w-8 text-fuchsia-300/70" />
<p className="text-[11px] text-zinc-400">{tr("WebGL 不可用,已显示占位预览", "WebGL unavailable — showing placeholder")}</p>
<button
type="button"
onClick={retry}
className="inline-flex items-center gap-1.5 rounded-lg border border-fuchsia-400/30 bg-fuchsia-500/10 px-3 py-1.5 text-[10px] font-semibold text-fuchsia-100 transition hover:bg-fuchsia-500/20"
>
<RefreshCw className="h-3 w-3" />
{tr("重试", "Retry")}
</button>
</div>
) : null}
{onOpenStudio ? (
<button
type="button"
onClick={onOpenStudio}
className="absolute bottom-2 right-2 z-10 inline-flex items-center gap-1 rounded-lg border border-white/10 bg-black/45 px-2.5 py-1 text-[10px] font-semibold text-zinc-200 backdrop-blur-sm transition hover:border-fuchsia-400/35 hover:bg-black/60 hover:text-white"
>
<Sparkles className="h-3 w-3 text-fuchsia-300" />
{tr("进入工作室", "Open studio")}
</button>
) : null}
</div>
</div>
);
}