Spaces:
Running
Running
Download src/ObjectViewer.tsx from fffiloni/Sand3D-assets-explorer: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/spaces/fffiloni/Sand3D-assets-explorer/resolve/main/src/ObjectViewer.tsx
- Command line
-
hf download hf://spaces/fffiloni/Sand3D-assets-explorer/src/ObjectViewer.tsx
-
curl -L -o ObjectViewer.tsx https://huggingface.co/spaces/fffiloni/Sand3D-assets-explorer/resolve/main/src/ObjectViewer.tsx
15.1 kB
| import {useEffect,useRef,useState} from 'react'; | |
| import {X,Info,Download,Copy,Check,ArrowUpRight,Film,Box,RotateCw,ShoppingBag,Code2} from 'lucide-react'; | |
| import type {Asset} from './types'; | |
| import type {createEngine,Joint} from './viewer-engine'; | |
| import AssetImage from './AssetImage'; | |
| import MotionControls from './MotionControls'; | |
| import ObjectInfo from './ObjectInfo'; | |
| import VisualControls,{type ViewMode,type InspectionInfo} from './VisualControls'; | |
| import CodePanel from './CodePanel'; | |
| import SelectionIndicator from './SelectionIndicator'; | |
| import {homeProgress} from './vendor/kinematics.js'; | |
| import {downloadCommand} from './download'; | |
| import {viewerFrame,selectionInFocus} from './spatial'; | |
| import {formatFileSize} from './file-size'; | |
| import {inspectionLayout} from './inspection-layout'; | |
| type Props={asset:Asset;moving?:boolean;x:number;y:number;scale:number;objectSize:number;width:number;height:number;inBasket:boolean;onToggleBasket:()=>void;onClose:()=>void}; | |
| export default function ObjectViewer({asset,moving=false,x,y,scale,objectSize,width,height,inBasket,onToggleBasket,onClose}:Props){ | |
| const interaction=useRef<HTMLDivElement>(null),host=useRef<HTMLDivElement>(null),video=useRef<HTMLVideoElement>(null),engine=useRef<ReturnType<typeof createEngine>|null>(null); | |
| const inspectorContent=useRef<HTMLDivElement>(null),codeTrigger=useRef<HTMLButtonElement>(null),jointsRef=useRef<Joint[]>([]); | |
| const movingRef=useRef(moving);movingRef.current=moving; | |
| const values=useRef<Record<string,number>>({}),selectedRef=useRef<string[]>([]); | |
| const [status,setStatus]=useState('Preparing 3D…'),[error,setError]=useState(''),[ready,setReady]=useState(false); | |
| const [joints,setJoints]=useState<Joint[]>([]),[selected,setSelected]=useState<string[]>([]),[positions,setPositions]=useState<Record<string,number>>({}),[fixedPart,setFixedPart]=useState(false),[playing,setPlaying]=useState(false),[highlighted,setHighlighted]=useState(!asset.motion); | |
| const [panel,setPanel]=useState<'info'|'download'|'code'|null>(null),[copied,setCopied]=useState(false),[copyError,setCopyError]=useState(false),[mode,setMode]=useState<'3d'|'video'>('3d'),[retry,setRetry]=useState(0),[allowLarge,setAllowLarge]=useState(false); | |
| const [code,setCode]=useState(''),[codeError,setCodeError]=useState(''),[motionWarning,setMotionWarning]=useState(''); | |
| const [viewMode,setViewMode]=useState<ViewMode>('materials'),[explode,setExplode]=useState(0),[part,setPart]=useState(''),[hovered,setHovered]=useState(''); | |
| const [inspection,setInspection]=useState<InspectionInfo|null>(null),[viewBusy,setViewBusy]=useState(false),[viewError,setViewError]=useState(''); | |
| useEffect(()=>{if(panel!=='code'||!asset.program)return;const abort=new AbortController();setCode('');setCodeError('');fetch(asset.program,{signal:abort.signal}).then(r=>{if(!r.ok)throw Error('Program unavailable.');return r.text();}).then(setCode).catch(e=>{if(e.name!=='AbortError')setCodeError(e.message);});return()=>abort.abort();},[panel,asset.program]); | |
| const large=!!asset.bytes&&asset.bytes>50*1024*1024&&!allowLarge; | |
| const {dimension,left,top,inView}=viewerFrame(x,y,scale,width,height,objectSize); | |
| const showControls=inView&&selectionInFocus(x,y,width,height); | |
| const layout=inspectionLayout(width,height),codeOpen=panel==='code'; | |
| useEffect(()=>{if(inspectorContent.current)inspectorContent.current.scrollTop=0;},[asset.id,panel,mode]); | |
| useEffect(()=>{ | |
| if(mode!=='3d'||!asset.model||large)return; | |
| let cancelled=false,start=0;setReady(false);setError('');setMotionWarning('');setJoints([]);setSelected([]);selectedRef.current=[];setFixedPart(false);setPlaying(false);setHighlighted(!asset.motion);setStatus('Preparing 3D…'); | |
| setInspection(null);setViewMode('materials');setExplode(0);setPart('');setHovered('');setViewBusy(false);setViewError(''); | |
| // Center first: rapidly changing selection can cancel before allocating a renderer. | |
| const begin=()=>{ | |
| if(cancelled)return; | |
| if(movingRef.current){start=requestAnimationFrame(begin);return;} | |
| start=requestAnimationFrame(()=>{ | |
| if(movingRef.current){begin();return;} | |
| import('./viewer-engine').then(({createEngine})=>{ | |
| if(cancelled||!host.current)return; | |
| try{ | |
| engine.current=createEngine(host.current,{url:asset.model!,compact:asset.compact,sha256:asset.sha256,motion:asset.motion,motionSha256:asset.motionSha256},value=>{if(!cancelled)setStatus(value);},(items,info={})=>{ | |
| if(cancelled)return; | |
| setInspection((info.inspection as InspectionInfo|undefined)??null); | |
| setMotionWarning(((info.warnings as {code:string;message:string}[]|undefined)??[]).filter(w=>w.code==='motion').map(w=>w.message).join(' '));jointsRef.current=items;setJoints(items);selectedRef.current=items.slice(0,1).map(j=>j.id);setSelected(selectedRef.current); | |
| values.current=Object.fromEntries(items.map(j=>[j.id,homeProgress(j)])); | |
| setPositions({...values.current});setReady(true); | |
| },failure=>{if(!cancelled){setReady(false);setPlaying(false);setJoints([]);setError(failure.message);setStatus('');}},(id,value)=>{ | |
| if(cancelled)return;values.current[id]=value;setPositions(current=>({...current,[id]:value})); | |
| },(kind,item)=>{ | |
| if(cancelled)return; | |
| if(kind==='hover'){setHovered(item?.name??'');return;} | |
| setPart(item?.id??'');if(!item)setFixedPart(false); | |
| if(item&&item.jointId!==undefined){ | |
| engine.current?.play(false);setPlaying(false); | |
| const next=jointsRef.current.find(j=>j.id===item.jointId); | |
| setFixedPart(!next); | |
| // A picked driver joins the group; a fixed part clears playback explicitly. | |
| const ids=next?[...new Set([...selectedRef.current,next.id])]:[]; | |
| selectedRef.current=ids;setSelected(ids);engine.current?.setPlaybackSelection(ids); | |
| } | |
| },interaction.current??undefined); | |
| }catch(failure){if(!cancelled){setError(String(failure));setStatus('');}} | |
| }).catch(failure=>{if(!cancelled){setError(String(failure));setStatus('');}}); | |
| }); | |
| };start=requestAnimationFrame(begin); | |
| return()=>{cancelled=true;cancelAnimationFrame(start);engine.current?.dispose();engine.current=null;}; | |
| },[asset.id,mode,retry,large]); | |
| useEffect(()=>{ | |
| engine.current?.setVisible(inView); | |
| if(!showControls){engine.current?.play(false);setPlaying(false);video.current?.pause();} | |
| },[inView,showControls,ready,mode]); | |
| const hasMovement=mode==='3d'&&ready&&joints.length>0; | |
| const command=downloadCommand(asset); | |
| const copy=async()=>{try{await navigator.clipboard.writeText(command);setCopied(true);setCopyError(false);}catch{setCopied(false);setCopyError(true);}}; | |
| const chooseMovements=(ids:string[])=>{ | |
| selectedRef.current=ids;setSelected(ids);setFixedPart(false); | |
| if(!ids.length)setPlaying(false); | |
| engine.current?.setPlaybackSelection(ids); | |
| engine.current?.selectPart('');setPart(''); | |
| }; | |
| const setPosition=(id:string,value:number)=>{setPlaying(false);engine.current?.setJoint(id,value);}; | |
| const chooseView=(next:ViewMode)=>{ | |
| const current=engine.current;if(!current||viewBusy)return; | |
| setViewBusy(true);setViewError(''); | |
| // Let the busy state paint before the first edge geometry is prepared. | |
| requestAnimationFrame(()=>setTimeout(()=>{ | |
| if(engine.current!==current)return; | |
| try{current.setMode(next);setViewMode(next);}catch{current.setMode('materials');setViewMode('materials');setViewError('Mesh view unavailable for this object. Materials remain available.');} | |
| finally{setViewBusy(false);} | |
| },0)); | |
| }; | |
| const resetAppearance=()=>{engine.current?.resetAppearance();setViewMode('materials');setExplode(0);setPart('');setHovered('');setViewError('');}; | |
| const indicator=error?'error':ready?'ready':large||!asset.model?'idle':'loading'; | |
| return <> | |
| <div className="object-stage" data-ui inert={!inView} style={{left,top,width:dimension,height:dimension}}> | |
| {mode==='3d'&&<><div ref={host} className="viewer-host" style={{inset:'-50%',opacity:ready?1:0,pointerEvents:'none'}}/><div ref={interaction} className="viewer-interaction" style={{inset:`${-50*explode}%`,pointerEvents:ready?'auto':'none'}}/>{!ready&&<AssetImage asset={asset}/>}{inView&&<SelectionIndicator state={indicator} label={error?'Selected object · 3D unavailable':ready?'Selected object · 3D ready':large?'Selected object · Load 3D to continue':!asset.model?'Selected object · Image preview':'Selected object · Preparing 3D'}/>}</>} | |
| {mode==='video'&&asset.video&&<video ref={video} className="motion-video" src={asset.video} poster={asset.renderedPreview??undefined} controls autoPlay muted loop playsInline onError={()=>setError('Motion recording unavailable')}/>} | |
| {ready&&hovered&&<span className="part-tooltip">{hovered}</span>} | |
| </div> | |
| {showControls&&<section className={`object-dock selection-bar inspection-panel ${layout.side?'inspection-side':'inspection-bottom'} ${hasMovement?'with-motion':''}`} style={{left:layout.panel.left,width:layout.panel.width,bottom:76,maxHeight:layout.panel.height,display:codeOpen?'none':undefined}} data-ui aria-label="Object controls"> | |
| <div className="inspector-heading"> | |
| <div className="selection-summary"> | |
| <div className="selection-identity"><strong title={asset.name}>{asset.name}</strong><span className="selection-meta"><span className="selection-generator" title={asset.dataset}>{asset.author}</span><span className="selection-size" title={asset.bytes!=null?`Source USDA · ${asset.bytes.toLocaleString('en-US')} bytes`:'Prepared USD preview size unavailable'}>USDA{asset.bytes!=null?` · ${formatFileSize(asset.bytes)}`:''}</span></span></div> | |
| <div className="selection-actions"> | |
| <button className={`icon-button ${panel==='info'?'active':''}`} aria-label="Object information" aria-expanded={panel==='info'} aria-controls="selection-details" title="Object information" onClick={()=>setPanel(panel==='info'?null:'info')}><Info size={18}/></button> | |
| <button className={`icon-button ${panel==='download'?'active':''}`} aria-label="Download object" aria-expanded={panel==='download'} aria-controls="selection-details" title="Download object" onClick={()=>setPanel(panel==='download'?null:'download')}><Download size={18}/></button> | |
| <button className={`icon-button add-to-basket ${inBasket?'active':''}`} aria-label={inBasket?'Remove from basket':'Add to basket'} title={inBasket?'Remove from basket':'Add to basket'} aria-pressed={inBasket} onClick={onToggleBasket}><ShoppingBag size={18}/>{inBasket&&<Check className="bag-check" size={10}/>}</button> | |
| {asset.program&&<button ref={codeTrigger} className={`icon-button ${panel==='code'?'active':''}`} aria-label="Read Python program" title="Read Python program" aria-expanded={panel==='code'} onClick={()=>setPanel(panel==='code'?null:'code')}><Code2 size={18}/></button>}<span className="divider"/><button className="icon-button selection-close" aria-label="Close object" title="Close object" onClick={onClose}><X size={18}/></button> | |
| </div> | |
| </div> | |
| <div className={`selection-status ${ready&&!error&&!motionWarning&&!asset.video&&mode==='3d'?'sr-only':''}`} role="status"> | |
| {mode==='video'?<span>{error||'Recorded motion · all parts'}</span>:!asset.model?<span>Image preview · 3D unavailable for this object</span>:large?<button className="quiet-button" onClick={()=>setAllowLarge(true)}>Load large 3D preview · {formatFileSize(asset.bytes!)}</button>:error?<><span>3D unavailable · Showing source image</span><button className="icon-button" aria-label="Retry 3D preview" title="Retry 3D preview" onClick={()=>setRetry(n=>n+1)}><RotateCw size={15}/></button></>:ready?<><Check size={12} className="selection-ready-icon"/><span>{motionWarning?'3D ready · Movement unavailable — see information':'3D ready · Drag to rotate'}</span></>:<><i className="tiny-spinner"/><span>{moving?'Centering object…':status}</span></>} | |
| {asset.video&&<button className="video-toggle" aria-label={mode==='3d'?'Watch recorded motion of all parts':'Return to interactive 3D'} onClick={()=>{setPlaying(false);setReady(false);setError('');setMode(mode==='3d'?'video':'3d');}}>{mode==='3d'?<Film size={14}/>:<Box size={14}/>} {mode==='3d'?'Watch recording':'Interactive 3D'}</button>} | |
| </div> | |
| </div> | |
| <div ref={inspectorContent} className={`inspector-content ${!panel&&hasMovement?'inspector-with-motion':''}`}> | |
| {!panel&&mode==='3d'&&ready&&inspection&&<><VisualControls mode={viewMode} amount={explode} part={part} busy={viewBusy} info={inspection} | |
| onMode={chooseView} onExplode={value=>{setExplode(value);engine.current?.explode(value);}} | |
| onPart={id=>engine.current?.selectPart(id)} onReset={resetAppearance}/> | |
| {viewError&&<p className="view-error" role="alert">{viewError}</p>}</>} | |
| {!panel&&hasMovement&&<MotionControls joints={joints} selected={selected} positions={positions} playing={playing} highlighted={highlighted} fixedPart={fixedPart} | |
| onSelect={chooseMovements} onProgress={setPosition} | |
| onPlay={()=>{engine.current?.play(!playing);setPlaying(!playing);}} | |
| onReset={()=>{engine.current?.resetMovements();setPlaying(false);}} | |
| onHighlight={()=>{engine.current?.setHighlight(!highlighted);setHighlighted(!highlighted);}}/>} | |
| {panel==='info'&&<ObjectInfo asset={asset} ready={ready} movementCount={joints.length} inspection={inspection} motionWarning={motionWarning} error={error}/>} | |
| {panel==='download'&&<div id="selection-details" className="dock-panel selection-details"><h2>Take this object with you.</h2><p>Download the original USDA, its Python program and attribution together from your basket.</p><button className="download-action" onClick={onToggleBasket}><ShoppingBag size={16}/>{inBasket?'Remove from basket':'Add to basket'}</button><button className="download-action" onClick={copy}>{copied?<Check size={16}/>:<Copy size={16}/>} {copied?'Command copied':'Copy download command'}</button>{copyError&&<p className="selection-copy-error" role="alert">Clipboard unavailable. Open the command below and copy it manually.</p>}<a className="download-action" href={asset.sourceFolder} target="_blank" rel="noreferrer">Browse source files<ArrowUpRight size={15}/></a><details open={copyError||undefined}><summary>Show command</summary><code>{command}</code></details><small>Source version: {asset.revision.slice(0,8)}</small></div>} | |
| </div> | |
| </section>} | |
| {showControls&&codeOpen&&asset.program&&<div className={`code-pane inspection-panel ${layout.side?'inspection-side':'inspection-bottom'}`} style={layout.panel} data-ui> | |
| <CodePanel key={asset.id} code={code} error={codeError} url={asset.program} id={asset.id} version={asset.sand3dVersion??''} onClose={()=>{setPanel(null);requestAnimationFrame(()=>codeTrigger.current?.focus({preventScroll:true}));}}/> | |
| </div>} | |
| </>; | |
| } | |