import React, { useState, useRef, useEffect, Suspense, useMemo, useCallback } from 'react'; import { Canvas, useFrame, useLoader } from '@react-three/fiber'; import { OrbitControls, Environment, useGLTF, Html, useAnimations, ContactShadows, PerspectiveCamera } from '@react-three/drei'; import * as THREE from 'three'; import { STLLoader } from 'three/examples/jsm/loaders/STLLoader'; import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'; import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader'; import { USDZLoader } from 'three/examples/jsm/loaders/USDZLoader'; import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader'; import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader'; import { Upload, RotateCw, Smartphone, Monitor, Square, Image as ImageIcon, Palette, X, Layers, ChevronDown, ChevronUp, Box, Grid, Play, Pause, Film, SkipForward, Video, StopCircle, RefreshCcw, Sun, Trash2, Globe } from 'lucide-react'; // --- Types --- type WireframeMode = 'none' | 'overlay' | 'pure' | 'points'; type ExportFormat = 'webm' | 'mp4' | 'mov'; type BgType = 'color' | 'hdri'; const DRACO_URL = 'https://www.gstatic.com/draco/versioned/decoders/1.5.5/'; const GUMROAD_URL = 'https://artel3d.gumroad.com/l/canva3Dpro'; // --- Loader Components --- const GLBModel = ({ url, onLoaded }: any) => { // Fix: Cast useGLTF result to any to avoid ambiguity between object and array return types const { scene, animations } = useGLTF(url, DRACO_URL) as any; useEffect(() => { if (scene) onLoaded(scene, animations); }, [scene, animations, onLoaded]); return ; }; const FBXModel = ({ url, onLoaded }: any) => { // Fix: Cast useLoader result to any to safely access the animations property const fbx = useLoader(FBXLoader, url) as any; useEffect(() => { if (fbx) onLoaded(fbx, fbx.animations || []); }, [fbx, onLoaded]); return ; }; const OBJModel = ({ url, onLoaded }: any) => { const obj = useLoader(OBJLoader, url); useEffect(() => { if (obj) onLoaded(obj, []); }, [obj, onLoaded]); return ; }; const STLModel = ({ url, onLoaded }: any) => { // Fix: Cast useLoader result to any because STLLoader returns a single BufferGeometry for one URL const geometry = useLoader(STLLoader, url) as any; const mesh = useMemo(() => new THREE.Mesh(geometry, new THREE.MeshStandardMaterial()), [geometry]); useEffect(() => { if (mesh) onLoaded(mesh, []); }, [mesh, onLoaded]); return ; }; const USDZModel = ({ url, onLoaded }: any) => { // Fix: Cast useLoader result to any to safely access the animations property const usdz = useLoader(USDZLoader, url) as any; useEffect(() => { if (usdz) onLoaded(usdz, usdz.animations || []); }, [usdz, onLoaded]); return ; }; // --- Custom Environment --- const CustomEnvironment = ({ url, type, background, intensity }: { url: string, type: string, background: boolean, intensity: number }) => { let loader: any = THREE.TextureLoader; if (type === 'hdr') loader = RGBELoader; if (type === 'exr') loader = EXRLoader; const texture = useLoader(loader, url, (loaderInstance: any) => { if (type === 'exr' || type === 'hdr') { loaderInstance.setDataType(THREE.HalfFloatType); } }) as THREE.Texture; // Configure synchronously during render so drei receives the correct mapping immediately. // useEffect is too late — drei processes the texture before the effect fires, causing black screen. texture.mapping = THREE.EquirectangularReflectionMapping; if (type === 'exr' || type === 'hdr') { texture.minFilter = THREE.LinearFilter; texture.magFilter = THREE.LinearFilter; texture.generateMipmaps = false; } else { texture.colorSpace = THREE.SRGBColorSpace; } // Use a large sphere for the background to avoid WebGL crashes with large EXR DataTextures on scene.background return ( <> {background && ( )} > ); }; // --- Model Wrapper --- const ModelManager = ({ url, type, isAlbedo, isNeutral, wireframeMode, techColor, animationIndex, isPlaying, onAnimsLoaded, rotationSpeed, rotationDirection }: any) => { const groupRef = useRef(null); const [model, setModel] = useState(null); const [animations, setAnimations] = useState([]); const { actions, names } = useAnimations(animations, groupRef); const handleLoaded = useCallback((obj: THREE.Object3D, anims: THREE.AnimationClip[]) => { if (groupRef.current) groupRef.current.rotation.set(0, 0, 0); const box = new THREE.Box3().setFromObject(obj); const size = box.getSize(new THREE.Vector3()); const center = box.getCenter(new THREE.Vector3()); const maxDim = Math.max(size.x, size.y, size.z); const scale = 3.5 / (maxDim || 1); obj.scale.setScalar(scale); obj.position.set(-center.x * scale, -center.y * scale + (size.y * scale) / 2, -center.z * scale); setModel(obj); setAnimations(anims); }, []); useEffect(() => { if (names.length > 0) onAnimsLoaded(names); }, [names, onAnimsLoaded]); useEffect(() => { if (actions && names.length > 0) { const action = actions[names[animationIndex % names.length]]; if (action) { if (isPlaying) action.reset().fadeIn(0.2).play(); else action.fadeOut(0.2); } return () => { action?.fadeOut(0.2); }; } }, [animationIndex, isPlaying, actions, names]); useFrame((state, delta) => { if (groupRef.current && rotationSpeed > 0) { groupRef.current.rotation.y += delta * rotationSpeed * rotationDirection * 0.5; } }); useEffect(() => { if (!model) return; model.traverse((child: any) => { if (child.isMesh) { if (!child.userData.originalMat) child.userData.originalMat = child.material.clone(); const orig = child.userData.originalMat; if (wireframeMode === 'pure') { child.material = new THREE.MeshStandardMaterial({ color: techColor, wireframe: true, emissive: techColor, emissiveIntensity: 0.5 }); } else if (isNeutral) { child.material = new THREE.MeshStandardMaterial({ color: '#444', roughness: 0.8, metalness: 0.2 }); } else if (isAlbedo) { child.material = new THREE.MeshBasicMaterial({ map: orig.map, color: 'white' }); } else { child.material = orig; child.material.wireframe = (wireframeMode === 'overlay'); } } }); }, [model, wireframeMode, isNeutral, isAlbedo, techColor]); const ext = type.toLowerCase(); return ( {(ext === 'glb' || ext === 'gltf') && } {ext === 'fbx' && } {ext === 'obj' && } {ext === 'stl' && } {ext === 'usdz' && } ); }; // --- Props Interface --- interface Viewer3DProps { modelUrl: string | null; onModelLoaded?: () => void; } // --- Main Component --- export default function Viewer3D({ modelUrl, onModelLoaded }: Viewer3DProps) { const [fileUrl, setFileUrl] = useState(null); const [fileType, setFileType] = useState(''); const [anims, setAnims] = useState([]); const [animIndex, setAnimIndex] = useState(0); const [isPlaying, setIsPlaying] = useState(true); const [wireframe, setWireframe] = useState('none'); const [isNeutral, setIsNeutral] = useState(false); const [isAlbedo, setIsAlbedo] = useState(false); const [bgColor, setBgColor] = useState('#050505'); const [rotationSpeed, setRotationSpeed] = useState(0.4); const [rotationDirection, setRotationDirection] = useState<1 | -1>(1); const [lightIntensity, setLightIntensity] = useState(1.5); const [aspect, setAspect] = useState<'9:16' | '1:1' | '16:9'>('1:1'); const [uiCollapsed, setUiCollapsed] = useState(false); // Background & HDRI const [bgType, setBgType] = useState('color'); const [hdriFile, setHdriFile] = useState<{url: string, type: string} | null>(null); const [hdriPreset, setHdriPreset] = useState('city'); // Export const [isRecording, setIsRecording] = useState(false); const [recordTime, setRecordTime] = useState(0); const [exportFormat, setExportFormat] = useState('mp4'); const canvasRef = useRef(null); const controlsRef = useRef(null); const fileInputRef = useRef(null); const hdriInputRef = useRef(null); const timerRef = useRef(null); const mediaRecorderRef = useRef(null); const chunksRef = useRef([]); // Load model from external URL when prop changes useEffect(() => { if (modelUrl) { setFileUrl(modelUrl); setFileType('glb'); if (onModelLoaded) onModelLoaded(); } }, [modelUrl]); const handleUpload = (file: File) => { if (fileUrl) URL.revokeObjectURL(fileUrl); setAnims([]); setAnimIndex(0); const ext = file.name.split('.').pop()?.toLowerCase() || ''; setFileType(ext); setFileUrl(URL.createObjectURL(file)); }; const handleHdriUpload = (file: File) => { if (hdriFile) URL.revokeObjectURL(hdriFile.url); const ext = file.name.split('.').pop()?.toLowerCase() || 'hdr'; setHdriFile({ url: URL.createObjectURL(file), type: ext }); setBgType('hdri'); }; const startRecording = () => { if (!canvasRef.current) return; chunksRef.current = []; const stream = canvasRef.current.captureStream(60); let mimeType = 'video/webm;codecs=vp9'; if (exportFormat === 'mp4') { mimeType = MediaRecorder.isTypeSupported('video/mp4') ? 'video/mp4' : 'video/webm;codecs=h264'; } else if (exportFormat === 'mov') { mimeType = 'video/quicktime'; } try { const recorder = new MediaRecorder(stream, { mimeType: MediaRecorder.isTypeSupported(mimeType) ? mimeType : 'video/webm', videoBitsPerSecond: 12000000 }); recorder.ondataavailable = (e) => chunksRef.current.push(e.data); recorder.onstop = () => { const blob = new Blob(chunksRef.current, { type: mimeType }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `3d-studio-render-${Date.now()}.${exportFormat}`; a.click(); }; recorder.start(); mediaRecorderRef.current = recorder; setIsRecording(true); setRecordTime(0); timerRef.current = window.setInterval(() => setRecordTime(t => t + 1), 1000); } catch (e) { alert("Recording error: Check browser compatibility for this format."); } }; const stopRecording = () => { mediaRecorderRef.current?.stop(); setIsRecording(false); if (timerRef.current) clearInterval(timerRef.current); }; const dim = useMemo(() => { const base = Math.min(window.innerWidth, window.innerHeight) * 0.75; if (aspect === '9:16') return { w: base * 0.56, h: base }; if (aspect === '16:9') return { w: base * 1.4, h: base * 0.8 }; return { w: base, h: base }; }, [aspect]); return ( {/* Bouton Get Pro */} ⬆ Get Pro {isRecording && ( {Math.floor(recordTime/60)}:{(recordTime%60).toString().padStart(2, '0')} - RECORDING {exportFormat.toUpperCase()} )} {!fileUrl ? ( fileInputRef.current?.click()}> CANVA 3D GLB, FBX, OBJ, STL ) : (
GLB, FBX, OBJ, STL