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 {bindDiscreteAction} from './touch-action.mjs';
import {bindFightMouse} from './fight-mouse.mjs';
import {createHeroCombat} from './hero-combat.mjs';import {createHeroCombatRig} from './hero-combat-rig.mjs';import {createHeroWeaponContacts} from './hero-weapon-contacts.mjs';
import {createFightInput} from './fight-input.mjs';
import {portraitDistanceScale} from './view-framing.mjs';
// Browser input/HUD/camera adapter. Default scene remains a face-off until a
// hero is chosen. Live combat has its own fixed-step clock, separate from fleet.
export function createHeroPlay(T,{pair,groundHeight,camera,controls,canvas=controls.domElement,onBeforeStart=()=>{},onStart=()=>{},onStop=()=>{},onPause=()=>{},onResume=()=>{},isPaused=()=>false}){
const rig=createHeroCombatRig(T,{pair,groundHeight}),contacts=createHeroWeaponContacts(T,{pair,rig}),combat=createHeroCombat({contacts}),heldInput=createFightInput(),primary=document.createElement('section'),element=document.createElement('div'),panel=document.createElement('div'),title=document.createElement('p'),result=document.createElement('output'),rows=new Map(),inputLog=[],actionsCleanup=[];let state=combat.state(),lastInput='',previousEnabled=controls.enabled,follow=true;
primary.className='hero-primary fight-primary';primary.hidden=true;primary.setAttribute('aria-label','Fight actions');document.body.append(primary);element.className='hero-play';panel.hidden=true;panel.className='fight-panel';
const button=(text,id,fn)=>{const b=document.createElement('button');b.textContent=text;b.id=id;b.type='button';if(fn)actionsCleanup.push(bindDiscreteAction(b,fn));return b;};
const active=()=>state.status!=='inactive';
function clear(){heldInput.clear();lastInput='';}
function start(side){onBeforeStart(side);clear();inputLog.length=0;follow=true;previousEnabled=active()?previousEnabled:controls.enabled;state=combat.start(side);controls.enabled=false;panel.hidden=false;primary.hidden=false;onStart();refresh();return state;}
function stop(){clear();state=combat.stop();controls.enabled=previousEnabled;panel.hidden=true;primary.hidden=true;onStop();return state;}
function attack(kind){if(!active())return false;const accepted=combat.command(state.player,kind);inputLog.push({time:state.time,attack:kind,accepted});state=combat.state();return accepted;}
if(canvas)actionsCleanup.push(bindFightMouse(canvas,{active,attack}));
element.append(button('Play as Achilles','play-achilles',()=>start('achilles')),button('Play as Hector','play-hector',()=>start('hector')));
for(const id of ['achilles','hector']){const row=document.createElement('div'),hp=document.createElement('progress'),stamina=document.createElement('progress'),label=document.createElement('span');row.className='fighter-bars';label.textContent=id==='achilles'?'Achilles':'Hector';hp.max=stamina.max=100;hp.setAttribute('aria-label',label.textContent+' health');stamina.setAttribute('aria-label',label.textContent+' stamina');row.append(label,document.createTextNode(' Health '),hp,document.createTextNode(' Stamina '),stamina);rows.set(id,{hp,stamina});primary.append(row);}
const actions=document.createElement('div');actions.append(button('Light · J','fight-light',()=>attack('light')),button('Heavy · K','fight-heavy',()=>attack('heavy')));
function hold(b,key){const owned=new Map();b.onpointerdown=e=>{if(!active())return;e.preventDefault();b.setPointerCapture(e.pointerId);owned.set(e.pointerId,heldInput.pointer(e.pointerId,key));};b.onpointerup=b.onpointercancel=b.onlostpointercapture=e=>{heldInput.release(e.pointerId,owned.get(e.pointerId));owned.delete(e.pointerId);};return b;}
actions.append(hold(button('Hold block · Space','fight-block'),'Space'));
const directions=document.createElement('div');directions.className='fight-directions';for(const[text,key]of [['Forward','KeyW'],['Left','KeyA'],['Back','KeyS'],['Right','KeyD']])directions.append(hold(button(text,'fight-'+key.toLowerCase()),key));
const help=document.createElement('p');help.textContent='WASD move · left click or J light · right click or K heavy · hold Space to block. Heavy attacks spend more stamina; an exhausted guard can break.';
const pause=button('Pause fight','fight-pause',()=>isPaused()?onResume():onPause());
primary.append(actions,directions);panel.prepend(title);panel.append(help,result,pause,button('Rematch','fight-rematch',()=>start(state.player)),button('Leave fight','fight-leave',stop));element.append(panel);
function refresh(){if(!active())return;title.textContent='Playing as '+(state.player==='achilles'?'Achilles':'Hector');pause.textContent=isPaused()?'Resume fight':'Pause fight';for(const a of state.actors){const row=rows.get(a.id);row.hp.value=a.health;row.stamina.value=a.stamina;}const p=state.actors.find(a=>a.id===state.player);result.textContent=state.status==='finished'?(state.winner==='draw'?'Draw':state.winner==='achilles'?'Achilles wins':'Hector wins'):p.action?.kind==='stun'?(p.action.result==='guard-break'?'Guard broken':'Hit'):p.action?`${p.action.kind==='heavy'?'Heavy attack':'Light attack'}`:p.blocking?'Blocking':p.stamina<16?'Recover stamina':'Ready';}
const keydown=e=>{if(!active()||['INPUT','SELECT','TEXTAREA'].includes(document.activeElement?.tagName))return;if(['KeyW','KeyA','KeyS','KeyD','Space','KeyJ','KeyK'].includes(e.code)){e.preventDefault();heldInput.key(e.code,true);if(!e.repeat&&e.code==='KeyJ')attack('light');if(!e.repeat&&e.code==='KeyK')attack('heavy');}},keyup=e=>heldInput.key(e.code,false),blur=()=>{clear();if(active())onPause();},visibility=()=>{if(document.hidden)blur();};
addEventListener('keydown',keydown);addEventListener('keyup',keyup);addEventListener('blur',blur);document.addEventListener('visibilitychange',visibility);
function update(dt){if(!active())return;const input=heldInput.value(),encoded=JSON.stringify(input);if(encoded!==lastInput){inputLog.push({time:state.time,input});lastInput=encoded;}if(inputLog.length>4096)inputLog.shift();state=combat.update(dt,input);refresh();if(!follow)return;const p=state.actors.find(a=>a.id===state.player),enemy=state.actors.find(a=>a.id!==state.player),target=new T.Vector3((p.x+enemy.x)/2,groundHeight(p.x,p.z)+1.1,(p.z+enemy.z)/2),offset=new T.Vector3(2.1,1.8,-3.2).applyAxisAngle(new T.Vector3(0,1,0),p.yaw),reference=new T.Vector3(p.x,groundHeight(p.x,p.z),p.z).add(offset),desired=target.clone().add(reference.sub(target).multiplyScalar(portraitDistanceScale(camera.aspect))),blend=dt===0?1:1-Math.exp(-dt*5);camera.position.lerp(desired,blend);controls.target.lerp(target,blend);camera.lookAt(controls.target);}
return {element,active,start,stop,attack,update,setFollow(value){follow=Boolean(value);},poseSnapshot(){pair.group.updateMatrixWorld(true);return pair.actors.map(a=>{const meshes=[];a.body.traverse(n=>{if(n.isMesh)meshes.push({name:n.name,matrix:n.matrixWorld.toArray()});});return {id:a.id,meshes};});},stats:()=>({...combat.stats(),rig:rig.stats(),weaponContacts:contacts.stats(),inputLog:structuredClone(inputLog),input:heldInput.stats()}),dispose(){stop();for(const release of actionsCleanup.splice(0))release();removeEventListener('keydown',keydown);removeEventListener('keyup',keyup);removeEventListener('blur',blur);document.removeEventListener('visibilitychange',visibility);element.remove();primary.remove();}};
}