Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
import React,{useCallback,useEffect,useMemo,useRef,useState} from 'react';
import {createRoot} from 'react-dom/client';
import {Canvas,useFrame,useThree} from '@react-three/fiber';
import * as THREE from 'three/webgpu';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
import {loadAssetCollection} from './assets.mjs';
import {GameWorld} from './GameWorld.jsx';
import {REVIEW_VIEWS} from './layout.mjs';
import './game.css';
import {createFrameHost} from './frame-host.mjs';
import {BENCHMARK_REVIEW_VIEWS} from './benchmark-scene.mjs';
import {initialCameraMode} from './view-camera.mjs';
import {createSkinBoundsUpdater} from './skin-bounds.mjs';
import {createFullscreenControl} from './fullscreen.mjs';
const frameHost=createFrameHost(),query=new URLSearchParams(location.search),optimized=query.get('optimized')!=='0',benchmark=query.get('benchmark')==='1';
const vegetationStrategy=benchmark&&query.get('vegetation')==='cells'?'cells':'family-frustum';
const benchmarkPreset=benchmark?(query.get('preset')??'axeFlash'):null,reviewViews=benchmark?{...REVIEW_VIEWS,...BENCHMARK_REVIEW_VIEWS}:REVIEW_VIEWS;
const initialView=initialCameraMode({benchmark,camera:query.get('camera')});
function Inspection({collection,assetKey,phase,clipName,lighting,psx,onProof}){
const {camera,gl,scene}=useThree();
const instance=useMemo(()=>collection.instantiate(assetKey),[collection,assetKey]);
const skinBounds=useMemo(()=>createSkinBoundsUpdater(instance.root),[instance]);
const controls=useRef(null),elapsed=useRef(0),frames=useRef(0);
useEffect(()=>{
camera.fov=42;camera.zoom=1;camera.updateProjectionMatrix();
instance.root.updateMatrixWorld(true);const box=new THREE.Box3().setFromObject(instance.root),center=box.getCenter(new THREE.Vector3()),extent=box.getSize(new THREE.Vector3());
const distance=Math.max(.7,extent.length()*.5/Math.sin(camera.fov*Math.PI/360)/Math.min(1,camera.aspect)*1.12);camera.position.copy(center).add(new THREE.Vector3(1,.36,.62).normalize().multiplyScalar(distance));camera.near=.02;camera.far=200;camera.updateProjectionMatrix();
const orbit=new OrbitControls(camera,gl.domElement);orbit.target.copy(center);orbit.minDistance=.15;orbit.maxDistance=80;orbit.enableDamping=true;orbit.update();controls.current=orbit;
return()=>{controls.current=null;orbit.dispose();instance.mixer.stopAllAction();instance.mixer.uncacheRoot(instance.root);const materials=new Set();instance.root.traverse(n=>{for(const m of n.material?(Array.isArray(n.material)?n.material:[n.material]):[])materials.add(m);});for(const m of materials)m.dispose();};
},[instance,camera,gl]);
useEffect(()=>{
instance.mixer.stopAllAction();const clip=instance.animations.find(c=>c.name===clipName)??instance.animations[0];
if(clip){const action=instance.mixer.clipAction(clip);action.reset().setLoop(THREE.LoopOnce,1);action.clampWhenFinished=true;action.play();instance.mixer.setTime(clip.duration*phase);}
},[instance,phase,clipName]);
useEffect(()=>{scene.background=new THREE.Color(lighting==='neutral'?'#92978d':'#111d19');scene.fog=null;},[lighting,scene]);
useFrame((_,dt)=>{controls.current?.update();instance.root.updateMatrixWorld(true);skinBounds.update();gl.info.reset();gl.render(scene,camera);frames.current++;elapsed.current+=dt;if(elapsed.current>.3){elapsed.current=0;const buffer=gl.getDrawingBufferSize(new THREE.Vector2());onProof({asset:assetKey,sha256:instance.entry.sha256,frames:frames.current,draws:gl.info.render.drawCalls,triangles:gl.info.render.triangles,buffer:[buffer.x,buffer.y],backend:gl.backend.isWebGPUBackend?'WebGPUBackend':'unsupported',phase,clip:clipName??instance.animations[0]?.name??null});}},1);
return <><hemisphereLight args={[lighting==='neutral'?'#ffffff':'#8ba999',lighting==='neutral'?'#b2b2b2':'#18221b',lighting==='neutral'?2.4:1.1]}/><directionalLight position={[4,7,5]} intensity={lighting==='neutral'?2:2.6} color={lighting==='neutral'?'#ffffff':'#e8c07c'}/><directionalLight position={[-4,2,-3]} intensity={lighting==='neutral'?.65:1} color={lighting==='neutral'?'#ffffff':'#577986'}/><primitive object={instance.root}/></>;
}
function App(){
const shell=useRef(null),fullscreenControl=useRef(null),[fullscreen,setFullscreen]=useState(false),[fullscreenError,setFullscreenError]=useState(null);
const standalone=window.top===window.self;
useEffect(()=>{const control=createFullscreenControl({element:shell.current,document,onChange:setFullscreen,onError:setFullscreenError});fullscreenControl.current=control;return()=>{control.dispose();fullscreenControl.current=null;};},[]);
const [mode,setMode]=useState('scene'),[cameraMode,setCameraMode]=useState(initialView),[playEntry,setPlayEntry]=useState(0),[panel,setPanel]=useState(null),[hud,setHud]=useState({}),[resetKey,setResetKey]=useState(0);
const controls=useMemo(()=>({active:false,keys:new Set(),commands:[],cameraMode:initialView}),[]);
const [inventoryText,setInventoryText]=useState(''),onInventory=useCallback(value=>setInventoryText(JSON.stringify(value)),[]);
const canvasElement=useRef(null),[canvasWidth,setCanvasWidth]=useState(window.innerWidth);
const cameraProps=useMemo(()=>({position:[4,2,4],fov:mode==='inspect'?42:70,near:.025,far:200}),[mode]);
const [collection,setCollection]=useState(null),[error,setError]=useState(null),[progress,setProgress]=useState('Reading the saved collection…'),[assetKey,setAssetKey]=useState(null),[lighting,setLighting]=useState('game'),[psx,setPsx]=useState(true),[phase,setPhase]=useState(0),[clipName,setClipName]=useState(''),[proof,setProof]=useState({}),[backend,setBackend]=useState(null);
useEffect(()=>{const element=canvasElement.current;if(!element)return;const measure=()=>setCanvasWidth(element.getBoundingClientRect().width);measure();const observer=new ResizeObserver(measure);observer.observe(element);return()=>observer.disconnect();},[collection,mode]);
useEffect(()=>{let cancelled=false,result;loadAssetCollection(new URL('./woodland/collection.json',document.baseURI).href,(n,total,key)=>setProgress(`Loading ${n} of ${total}: ${key}`)).then(value=>{result=value;if(cancelled){value.dispose();return;}const first=Object.keys(value.manifest.assets)[0];if(!first)throw Error('No saved production assets in this collection yet.');setAssetKey(first);setCollection(value);}).catch(e=>{if(!cancelled)setError(e.message);});return()=>{cancelled=true;result?.dispose();};},[]);
useEffect(()=>{frameHost.progress(progress);},[progress]);
useEffect(()=>{if(error)frameHost.fail(error);},[error]);
const hostReady=useRef(false);useEffect(()=>{if(!hostReady.current&&backend&&collection&&proof.frames>1){hostReady.current=true;frameHost.ready();}},[backend,collection,proof.frames]);
const entry=collection?.manifest.assets[assetKey],clips=collection?.masters.get(assetKey)?.animations??[];
const sceneReady=!!collection&&!!backend&&proof.frames>1&&typeof controls.requestPlay==='function';
const navigation=next=>{controls.pause?.();controls.active=false;controls.keys.clear();controls.commands.length=0;controls.cameraMode=next;setCameraMode(next);if(document.pointerLockElement===document.querySelector('.game-canvas canvas'))document.exitPointerLock();};
const enterScene=()=>{if(!sceneReady)return;navigation('caretaker');setPlayEntry(value=>value+1);setPanel(null);document.querySelector('.game-canvas')?.focus({preventScroll:true});controls.requestPlay();};
const togglePanel=next=>{controls.pause?.();setPanel(value=>value===next?null:next);};
useEffect(()=>{if(!panel&&mode!=='inspect')return;const close=event=>{if(event.key==='Escape'){event.preventDefault();event.stopPropagation();if(panel){setPanel(null);document.getElementById(`${panel}-toggle`)?.focus();}else{navigation('overview');setMode('scene');document.querySelector('.game-canvas')?.focus({preventScroll:true});}}};window.addEventListener('keydown',close,true);return()=>window.removeEventListener('keydown',close,true);},[panel,mode]);
const renderer=useCallback(async function renderer(props){
if(!navigator.gpu)throw Error('This review requires a browser with WebGPU.');const gl=new THREE.WebGPURenderer({...props,antialias:false});await gl.init();
if(!gl.backend.isWebGPUBackend){gl.dispose();throw Error('WebGPU initialization fell back to a different renderer.');}
gl.info.autoReset=false;gl.outputColorSpace=THREE.SRGBColorSpace;gl.toneMapping=THREE.NeutralToneMapping;gl.toneMappingExposure=1;setBackend('WebGPU');
gl.backend.device.addEventListener('uncapturederror',event=>setError(String(event.error?.message??event.error)));return gl;
},[]);
return <main ref={shell} className="game-shell">
{benchmark&&<pre hidden id="scene-benchmark">{JSON.stringify(proof)}</pre>}
{benchmark&&<pre hidden id="scene-benchmark-inventory">{inventoryText}</pre>}
{collection&&assetKey&&<div ref={canvasElement} className={`game-canvas ${mode==='inspect'?'inspection-canvas':''}`} tabIndex={0} aria-label="3D scene"><Canvas camera={cameraProps} dpr={psx?Math.min(1,(mode==='inspect'?700:760)/Math.max(1,canvasWidth)):1} shadows={{enabled:false,type:THREE.PCFShadowMap}} gl={renderer} onError={e=>setError(String(e))}>{mode==='inspect'?<Inspection collection={collection} assetKey={assetKey} phase={phase} clipName={clipName} lighting={lighting} psx={psx} onProof={setProof}/>:<GameWorld key={resetKey} collection={collection} controls={controls} cameraMode={cameraMode} playEntry={playEntry} optimized={optimized} vegetationStrategy={vegetationStrategy} benchmark={benchmark} benchmarkPreset={benchmarkPreset} reviewViews={reviewViews} onInventory={onInventory} lighting={lighting} psx={psx} onHud={setHud} onProof={setProof}/>}</Canvas></div>}
{!collection&&<div className="loading-screen"><span className="eyebrow">CABIN IN THE WOODS: PSX HORROR</span><h2>First collection</h2><p className={error?'fatal':''}>{error??progress}</p></div>}
<header className="game-top"><div className="brand"><h1>Cabin in the Woods</h1><p>PSX Horror · Kiln</p></div><nav className="mode-controls" aria-label="Scene navigation">
{mode==='scene'?<><button data-active={cameraMode==='overview'} disabled={!collection} onClick={()=>navigation('overview')}>Aerial view</button><button aria-pressed={cameraMode==='orbit'} disabled={!collection} onClick={()=>navigation(cameraMode==='orbit'?'overview':'orbit')}>Orbit</button><button className="play-button" disabled={!sceneReady} onClick={()=>hud.active?controls.commands.push('pause'):enterScene()}>{hud.active?'Pause Caretaker':'Play as Caretaker'}</button><button id="controls-toggle" aria-expanded={panel==='controls'} aria-controls="controls-panel" onClick={()=>togglePanel('controls')}>Controls</button></>:<button onClick={()=>{navigation('overview');setMode('scene');setPanel(null);}}>Back to scene</button>}
{standalone&&document.fullscreenEnabled&&<button aria-pressed={fullscreen} onClick={()=>{setFullscreenError(null);void fullscreenControl.current?.toggle();}}>{fullscreen?'Leave fullscreen':'Fullscreen'}</button>}
<button id="more-toggle" aria-expanded={panel==='more'} aria-controls="more-panel" onClick={()=>togglePanel('more')}>More</button>
</nav></header>
{fullscreenError&&<p className="fullscreen-status" role="status">{fullscreenError}</p>}
{cameraMode==='caretaker'&&!hud.active&&hud.pointerLockError&&<div className="play-status" role="status"><p>Mouse capture was blocked. You can retry Play or use keyboard controls.</p><button onClick={()=>{if(controls.requestKeyboardPlay?.())document.querySelector('.game-canvas')?.focus({preventScroll:true});}}>Use keyboard controls</button></div>}
{cameraMode==='caretaker'&&hud.active&&hud.keyboardMode&&<p className="keyboard-status">Keyboard mode · WASD moves · Arrow keys turn · Page Up/Down looks · Space acts · Escape pauses</p>}
<aside id="more-panel" hidden={panel!=='more'} className="menu-panel" aria-label="Scene options"><div className="panel-actions"><button data-active={lighting==='neutral'} onClick={()=>setLighting('neutral')}>Neutral light</button><button data-active={lighting==='game'} onClick={()=>setLighting('game')}>Cabin light</button><button aria-pressed={psx} data-active={psx} onClick={()=>setPsx(value=>!value)}>PSX pixels</button>{mode==='scene'&&<button onClick={()=>{navigation('overview');setMode('inspect');setPanel(null);}}>Asset inspection</button>}<button onClick={()=>{navigation('overview');setMode('scene');setPanel(null);setResetKey(key=>key+1);}}>Reset scene</button></div><details><summary>Renderer diagnostics</summary><p>{proof.draws??'—'} draw calls · {proof.triangles?.toLocaleString()??'—'} triangles. Local timing is diagnostic only.</p><pre className="review-proof">{JSON.stringify(proof,null,2)}</pre></details></aside>
{collection&&mode==='inspect'&&<aside className="side-panel"><span className="eyebrow">SAVED ASSET REVIEW</span><h2>{entry?.name??assetKey}</h2><label htmlFor="asset">Collection</label><select id="asset" value={assetKey} onChange={e=>{setAssetKey(e.target.value);setPhase(0);setClipName('');}}>{Object.entries(collection.manifest.assets).map(([key,item])=><option key={key} value={key}>{item.name??key}</option>)}</select><p>{entry?.description}</p><p>Drag to orbit. Scroll to zoom. Switch lighting to compare the original materials in a neutral view and a warm cabin setting.</p>{clips.length>0&&<><label htmlFor="clip">Animation</label><select id="clip" value={clipName||clips[0].name} onChange={e=>setClipName(e.target.value)}>{clips.map(c=><option key={c.name}>{c.name}</option>)}</select><label htmlFor="phase">Pose · {Math.round(phase*100)}%</label><input id="phase" aria-label="Animation phase" type="range" min="0" max="1" step="0.01" value={phase} onChange={e=>setPhase(Number(e.target.value))}/></>}<p className="scene-status">Inspect the saved originals here, then enter the cabin and forest to try them in play. This first collection is ready for your feedback.</p><details><summary>Revision and renderer</summary><pre className="review-proof">{JSON.stringify({collection:entry?.collection,assetId:entry?.assetId,revisionId:entry?.revisionId,...proof},null,2)}</pre></details>{error&&<p className="fatal">{error}</p>}</aside>}
{mode==='scene'&&<>{cameraMode==='caretaker'&&<><div className="crosshair"/>{hud.target&&<div className="target-prompt">{['tree','nightman','spider'].includes(hud.target.kind)?hud.weapon==='unarmed'?(hud.target.kind==='tree'?'2 · Equip axe':'2 / 3 · Equip weapon'):'Click / Space':'E'} · {hud.target.label}</div>}</>}<section id="controls-panel" hidden={panel!=='controls'} className="scene-controls" aria-label="Scene controls"><h2>Controls</h2><p>Orbit: drag to look around the cabin; scroll to zoom. The aerial view stays fixed until you choose Orbit.</p><p>Play as Caretaker captures the mouse. WASD walks, Shift runs, E interacts, Escape releases the mouse. Click or Space swings or fires; 1 stows your weapon, 2 equips the axe, 3 equips the shotgun; F toggles the left-hand flashlight; R reloads the shotgun.</p><details><summary>Review controls</summary><label htmlFor="review-view">Review viewpoint</label><select id="review-view" defaultValue="" onChange={event=>{navigation('caretaker');controls.commands.push(`view:${event.target.value}`);}}><option value="" disabled>Choose a place</option>{Object.entries(reviewViews).map(([id,view])=><option key={id} value={id}>{view.label}</option>)}</select><div className="panel-actions">{[['step-forward','Walk forward 1 m'],['step-back','Walk back 1 m'],['turn-left','Turn left'],['turn-right','Turn right'],['use','Use'],['attack','Swing / fire'],['look-down','Look down'],['look-level','Look level'],['unarmed','Empty hands'],['axe','Axe'],['shotgun','Shotgun'],['flashlight','Flashlight'],['reload','Reload shotgun'],['take-logs','Take log'],['take-planks','Take board'],['take-firewood','Take firewood'],['breach','Breach aimed window'],['encounter','Begin encounter']].map(([command,label])=><button key={command} onClick={()=>controls.commands.push(command)}>{label}</button>)}</div><p>Arrow keys turn/walk; Page Up/Down looks vertically. Review viewpoints pause the demo without granting items.</p></details></section></>}
<footer className="game-bottom"><div><div className="game-message">{mode==='inspect'?entry?.reviewNote:cameraMode==='caretaker'?hud.message:cameraMode==='orbit'?'Drag to orbit · Scroll to zoom':'Fixed aerial view · Choose Orbit or Play as Caretaker'}</div>{mode==='scene'&&cameraMode==='caretaker'&&hud.inventory&&<div className="inventory">{[['Logs',hud.inventory.logs],['Firewood',hud.inventory.firewood],['Boards',hud.inventory.planks],['Shells',hud.weapon==='shotgun'?`${hud.loadedShells??0}/2`:hud.inventory.shells]].map(([label,value])=><div key={label}><b>{value}</b>{label}</div>)}</div>}<span className="scene-status">{backend??'Initializing WebGPU'} · {collection?Object.keys(collection.manifest.assets).length:0} saved assets</span>{error&&<p className="fatal">{error}</p>}</div>{mode==='scene'&&cameraMode==='caretaker'&&<nav className="weapon-slots" aria-label="Equipment">{[['unarmed','Empty hands','1'],['axe','Axe','2'],['shotgun','Shotgun','3']].map(([weapon,label,key])=><button key={weapon} aria-label={`${label} (${key})`} aria-keyshortcuts={key} aria-pressed={(hud.weapon??'unarmed')===weapon} data-active={(hud.weapon??'unarmed')===weapon} disabled={hud.reloading===true} onClick={()=>{controls.commands.push(weapon);document.querySelector('.game-canvas')?.focus({preventScroll:true});}}><kbd>{key}</kbd><span>{label}</span></button>)}</nav>}</footer>
</main>;
}
createRoot(document.getElementById('root')).render(<App/>);