incanto 0.35.0 → 0.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4108,7 +4108,7 @@ void main() {
4108
4108
  import { incantoScenes } from 'incanto/vite';
4109
4109
  export default defineConfig({ plugins: [incantoScenes()] });
4110
4110
 
4111
- It also validates every scene you save, before the page reloads into a broken one.`;async function Em(e){let t=await fetch(`/api/scene?file=${encodeURIComponent(e)}`);if(t.ok)return await t.json();let n=await t.json().catch(()=>null);throw Error(n?.error??`could not open ${e}: HTTP ${t.status}`)}async function Dm(e){let t;try{t=await ym(()=>Promise.resolve().then(()=>WB),void 0,import.meta.url)}catch(e){throw Error(`createGame3D editor: could not load 'incanto/editor'. If this app aliases incanto to the engine SOURCE (the examples and playground do), add an alias for 'incanto/editor' → packages/editor/src/main.ts — or pass editor: { open } and load it yourself. (${e instanceof Error?e.message:String(e)})`)}let n=null,r=await wm(),i=t.formatSceneJson??(e=>JSON.stringify(e,null,2)),a=async(e,t)=>{let n=await fetch(`/api/scene?file=${encodeURIComponent(e)}`,{method:`PUT`,body:i(t)});if(!n.ok)throw Error(`could not save ${e}: HTTP ${n.status} ${await n.text()}`)};n=await t.mountEditor({...e.camera?{camera:e.camera}:{},api:{meta:async()=>({version:`live`,mode:`project`,root:``,input:null,output:null}),loadScene:async t=>t?await Em(t):e.scene,...e.save||r?{saveScene:async(t,n)=>{if(n)return a(n,t);await e.save?.(t)}}:{},scenes:async()=>{let e=await wm();if(!e)throw Error(Tm);return e},createScene:async e=>{let t=await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})});if(t.status===404)throw Error(Tm);if(!t.ok)throw Error(`could not create ${e}: ${await t.text()}`);return await t.json()},...e.library?{library:e.library}:{}},onPlay:(t,r)=>{if(t!==`debug`)return;let i=n?.camera();return Om(async()=>{n?.dispose(),n=null,await e.play(r,i)},`starting the game…`)},...e.exit?{onExit:()=>Om(async()=>{n?.dispose(),n=null,await e.exit?.()},`back to the game…`)}:{}})}async function Om(e,t=``){let n=xm(t);await Sm();try{await e()}finally{await Sm(0),n.lift()}}function km(e,t=8){let n=e.cameraBasis,r=e.lastCameraPosition;if(typeof n!=`function`||typeof r!=`function`)return;let i=r.call(e);if(!i)return;let{forward:a}=n.call(e);return{position:[i.x,i.y,i.z],target:[i.x+a.x*t,i.y+a.y*t,i.z+a.z*t]}}function Am(e,t=jm){let n=[];for(let r of e){if(!r)continue;let[e,i]=r;try{i()}catch(r){n.push({what:e,error:r});try{t(e,r)}catch{}}}return{failures:n}}function jm(e,t){console.error(`[incanto] teardown: ${e} failed (continuing)`,t)}var Mm=new Oc,Nm=new G,Pm=new hs;function Fm(e,t,n){return Nm.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Mm.setFromProjectionMatrix(Nm),Pm.center.set(t.x,t.y,t.z),Pm.radius=n,Mm.intersectsSphere(Pm)}function Im(e){if(!e||typeof e!=`object`)return 0;switch(e.shape){case`capsule`:return(e.height??0)/2+(e.radius??0);case`sphere`:return e.radius??0;case`box`:return(e.size?.[1]??0)/2;default:return 0}}function Lm(e){return .55+Math.min(Math.max(e,0),12)/12*.45}function Rm(e,t,n=0){let r=[],i=[],a=new Set;for(let o of t){let t=e.has(o.id);(t?o.y<=o.waterline+n:o.y<o.waterline)?(a.add(o.id),t||r.push(o)):t&&i.push(o)}return{entered:r,exited:i,inWater:a}}function zm(e,t,n,r,i=0,a=8){if(e.length>=a){let t=0;for(let n=1;n<e.length;n++)e[n].age>e[t].age&&(t=n);e.splice(t,1)}e.push({x:t,z:n,age:0,amp:r,foam:i})}function Bm(e,t,n=3){for(let r=e.length-1;r>=0;r--){let i=e[r];i.age+=t,i.age>=n&&e.splice(r,1)}}function Vm(e,t,n){let r=e-n.x,i=t-n.z,a=Math.sqrt(r*r+i*i);return n.amp*Math.sin(6*a-8*n.age)*Math.exp(-1.1*n.age)*Math.exp(-.15*a*a)}function Hm(e,t,n){let r=0;for(let i of n)r+=Vm(e,t,i);return r}function Um(e,t,n,r){let i=[];for(let n of e.keys())t.has(n)||e.delete(n);for(let a of t){let t=(e.get(a)??0)+n;t>=r?(i.push(a),e.set(a,t-r)):e.set(a,t)}return i}var Wm=`
4111
+ It also validates every scene you save, before the page reloads into a broken one.`;async function Em(e){let t=await fetch(`/api/scene?file=${encodeURIComponent(e)}`);if(t.ok)return await t.json();let n=await t.json().catch(()=>null);throw Error(n?.error??`could not open ${e}: HTTP ${t.status}`)}async function Dm(e){let t;try{t=await ym(()=>Promise.resolve().then(()=>KB),void 0,import.meta.url)}catch(e){throw Error(`createGame3D editor: could not load 'incanto/editor'. If this app aliases incanto to the engine SOURCE (the examples and playground do), add an alias for 'incanto/editor' → packages/editor/src/main.ts — or pass editor: { open } and load it yourself. (${e instanceof Error?e.message:String(e)})`)}let n=null,r=await wm(),i=t.formatSceneJson??(e=>JSON.stringify(e,null,2)),a=async(e,t)=>{let n=await fetch(`/api/scene?file=${encodeURIComponent(e)}`,{method:`PUT`,body:i(t)});if(!n.ok)throw Error(`could not save ${e}: HTTP ${n.status} ${await n.text()}`)};n=await t.mountEditor({...e.camera?{camera:e.camera}:{},api:{meta:async()=>({version:`live`,mode:`project`,root:``,input:null,output:null}),loadScene:async t=>t?await Em(t):e.scene,...e.save||r?{saveScene:async(t,n)=>{if(n)return a(n,t);await e.save?.(t)}}:{},scenes:async()=>{let e=await wm();if(!e)throw Error(Tm);return e},createScene:async e=>{let t=await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})});if(t.status===404)throw Error(Tm);if(!t.ok)throw Error(`could not create ${e}: ${await t.text()}`);return await t.json()},...e.library?{library:e.library}:{}},onPlay:(t,r)=>{if(t!==`debug`)return;let i=n?.camera();return Om(async()=>{n?.dispose(),n=null,await e.play(r,i)},`starting the game…`)},...e.exit?{onExit:()=>Om(async()=>{n?.dispose(),n=null,await e.exit?.()},`back to the game…`)}:{}})}async function Om(e,t=``){let n=xm(t);await Sm();try{await e()}finally{await Sm(0),n.lift()}}function km(e,t=8){let n=e.cameraBasis,r=e.lastCameraPosition;if(typeof n!=`function`||typeof r!=`function`)return;let i=r.call(e);if(!i)return;let{forward:a}=n.call(e);return{position:[i.x,i.y,i.z],target:[i.x+a.x*t,i.y+a.y*t,i.z+a.z*t]}}function Am(e,t=jm){let n=[];for(let r of e){if(!r)continue;let[e,i]=r;try{i()}catch(r){n.push({what:e,error:r});try{t(e,r)}catch{}}}return{failures:n}}function jm(e,t){console.error(`[incanto] teardown: ${e} failed (continuing)`,t)}var Mm=new Oc,Nm=new G,Pm=new hs;function Fm(e,t,n){return Nm.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Mm.setFromProjectionMatrix(Nm),Pm.center.set(t.x,t.y,t.z),Pm.radius=n,Mm.intersectsSphere(Pm)}function Im(e){if(!e||typeof e!=`object`)return 0;switch(e.shape){case`capsule`:return(e.height??0)/2+(e.radius??0);case`sphere`:return e.radius??0;case`box`:return(e.size?.[1]??0)/2;default:return 0}}function Lm(e){return .55+Math.min(Math.max(e,0),12)/12*.45}function Rm(e,t,n=0){let r=[],i=[],a=new Set;for(let o of t){let t=e.has(o.id);(t?o.y<=o.waterline+n:o.y<o.waterline)?(a.add(o.id),t||r.push(o)):t&&i.push(o)}return{entered:r,exited:i,inWater:a}}function zm(e,t,n,r,i=0,a=8){if(e.length>=a){let t=0;for(let n=1;n<e.length;n++)e[n].age>e[t].age&&(t=n);e.splice(t,1)}e.push({x:t,z:n,age:0,amp:r,foam:i})}function Bm(e,t,n=3){for(let r=e.length-1;r>=0;r--){let i=e[r];i.age+=t,i.age>=n&&e.splice(r,1)}}function Vm(e,t,n){let r=e-n.x,i=t-n.z,a=Math.sqrt(r*r+i*i);return n.amp*Math.sin(6*a-8*n.age)*Math.exp(-1.1*n.age)*Math.exp(-.15*a*a)}function Hm(e,t,n){let r=0;for(let i of n)r+=Vm(e,t,i);return r}function Um(e,t,n,r){let i=[];for(let n of e.keys())t.has(n)||e.delete(n);for(let a of t){let t=(e.get(a)??0)+n;t>=r?(i.push(a),e.set(a,t-r)):e.set(a,t)}return i}var Wm=`
4112
4112
  precision highp float;
4113
4113
 
4114
4114
  // atmosphere: three's linear fog rides the standard chunks (compiled out
@@ -5753,7 +5753,7 @@ void main() {
5753
5753
  if (any(greaterThan(abs(vCutLocal), uHalf))) discard;
5754
5754
  gl_FragColor = vec4(0.0);
5755
5755
  }
5756
- `,colorWrite:!1,depthWrite:!0,depthTest:!1,side:2}),Jg=9.81,Yg=6,Xg=.15,Zg=class extends et{static props={water:{default:``,nodePath:!0},draft:{default:.35},stiffness:{default:3},damping:{default:3.5},drift:{default:.6},drag:{default:.9},samples:{default:4},size:{default:[1,1]}};static signals=[`submerged`,`surfaced`];water=``;draft=.35;stiffness=3;damping=3.5;drift=.6;drag=.9;samples=4;size=[1,1];surface=null;wet=!1;update(e){if(e<=0)return;let t=this.resolveWater();if(!t)return;let n=this.node;if(!n.applyImpulse)return;let[r,i,a]=[n.position[0]??0,n.position[1]??0,n.position[2]??0],o=[(this.size[0]??1)/2,(this.size[1]??1)/2],s=this.samplePoints(r,a,o[0],o[1]),c=n.mass??1,l=n.linearVelocity??[0,0,0],u=0,d=0,f=0,p=0;for(let[e,n]of s){let r=t.heightAt(e,n)-(i-this.draft);if(r<=0)continue;p++,u+=Jg*(1+this.stiffness*(r/Math.max(this.draft,Xg)));let a=.6;d+=t.heightAt(e+a,n)-t.heightAt(e-a,n),f+=t.heightAt(e,n+a)-t.heightAt(e,n-a)}let m=p>0;if(m!==this.wet&&(this.wet=m,this.emit(m?`submerged`:`surfaced`,this.node)),!m)return;let h=p/s.length,g=Math.min(u/s.length-this.damping*(l[1]??0),Yg*Jg)*e*c,_=(-d*this.drift*12-(l[0]??0)*this.drag)*h*e*c,v=(-f*this.drift*12-(l[2]??0)*this.drag)*h*e*c;n.applyImpulse([_,g,v])}samplePoints(e,t,n,r){let i=Math.max(1,Math.round(this.samples));if(i===1)return[[e,t]];let a=[];for(let o=0;o<i;o++){let s=o/i*Math.PI*2+Math.PI/4;a.push([e+Math.cos(s)*n,t+Math.sin(s)*r])}return a}resolveWater(){if(this.surface)return this.surface;if(this.water!==``){let e=this.node.getNodeOrNull(this.water);if(!(e instanceof mg))throw new N(`NODE_NOT_FOUND`,`Buoyancy on '${this.node.getPath()}': water '${this.water}' is not a Water3D in the tree.`,{prop:`water`});return this.surface=e,e}return this.surface=Qg(this.node.getRoot()),this.surface}};function Qg(e){if(e instanceof mg)return e;for(let t of e.children){let e=Qg(t);if(e)return e}return null}function $g(e){return Array.isArray(e.position)}function e_(e){let t=e.node;if(!$g(t)){let n=e.constructor.name;throw new N(`PROP_TYPE_MISMATCH`,`${n} on '${t.getPath()}' needs a spatial node with a numeric 'position' array (a Node2D/Node3D subtype). '${t.name}' has none.`,{path:t.getPath()})}return t}function t_(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}function n_(e,t){let n=Math.max(e.length,t.length),r=Array(n);for(let i=0;i<n;i++)r[i]=(e[i]??0)+(t[i]??0);return r}function r_(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t)}function i_(e){let t=r_(e);return t===0?e.map(()=>0):e.map(e=>e/t)}function a_(e,t,n){let r=Math.max(e.length,t.length),i=0;for(let n=0;n<r;n++){let r=(t[n]??0)-(e[n]??0);i+=r*r}let a=Math.sqrt(i),o=Array(r);if(a<=n||a===0){for(let e=0;e<r;e++)o[e]=t[e]??0;return{position:o,reached:!0}}let s=n/a;for(let n=0;n<r;n++){let r=e[n]??0;o[n]=r+((t[n]??0)-r)*s}return{position:o,reached:!1}}function o_(e,t){let n=Math.min(Math.max(e,0),.99);return n<=0?1:1-n**(t*60)}var s_=class extends et{static props={target:{default:``,nodePath:!0},speed:{default:60},stopRange:{default:0},loseRange:{default:0},moveParent:{default:!1}};static signals=[`reachedTarget`,`lostTarget`];target=``;speed=60;stopRange=0;loseRange=0;moveParent=!1;inRange=!1;lost=!1;onReady(){if(this.target===``)throw new N(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.moveParent){let e=this.node.parent;if(!e||!$g(e))throw new N(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else e_(this)}update(e){let t=this.moveParent?this.node.parent:this.node;if(!t||!$g(t))return;let n=this.node.getNodeOrNull(this.target);if(!n||!$g(n))return;let r=t_(t.position,n.position);if(this.loseRange>0&&r>this.loseRange){this.lost||(this.lost=!0,this.inRange=!1,this.emit(`lostTarget`));return}if(this.lost=!1,this.stopRange>0&&r<=this.stopRange){this.inRange||(this.inRange=!0,this.emit(`reachedTarget`));return}this.inRange=!1;let i=Math.min(this.speed*e,this.stopRange>0?r-this.stopRange:r),{position:a}=a_(t.position,n.position,Math.max(0,i));t.position=a}},c_=class extends et{static props={button:{default:0},maxDistance:{default:0},enabled:{default:!0}};static signals=[`clicked`,`hovered`,`unhovered`];button=0;maxDistance=0;enabled=!0;hovering=!1;pressedHere=!1;update(){let e=this.node.tree?.engine;if(!e||!this.enabled)return;let t=e.picker,n=e.input.pointerPosition();if(!t||!n){this.hovering&&this.setHover(!1);return}let r=t(n.x,n.y),i=r!==null&&this.isSelfOrDescendant(r)&&this.withinRange(r);i!==this.hovering&&this.setHover(i),e.input.mouseJustPressed(this.button)&&(this.pressedHere=i),e.input.mouseJustReleased(this.button)&&(this.pressedHere&&i&&this.emit(`clicked`,this.node),this.pressedHere=!1)}setHover(e){this.hovering=e,this.emit(e?`hovered`:`unhovered`,this.node)}isSelfOrDescendant(e){for(let t=e;t;t=t.parent)if(t===this.node)return!0;return!1}withinRange(e){if(this.maxDistance<=0||!this.node.tree?.engine?.scene?.root)return!0;let t=this.node.position,n=e.position;if(!Array.isArray(t)||!Array.isArray(n))return!0;let r=0;for(let e=0;e<Math.max(t.length,n.length);e++){let i=(t[e]??0)-(n[e]??0);r+=i*i}return Math.sqrt(r)<=this.maxDistance}},l_=class extends et{static props={group:{default:`player`}};static signals=[`totalChanged`];group=`player`;total=0;onReady(){this.node.addToGroup(this.group)}collect(e){this.total+=e,this.emit(`totalChanged`,this.total)}serialize(){return{total:this.total}}deserialize(e){let t=e;typeof t.total==`number`&&(this.total=t.total)}},u_=class extends et{static props={max:{default:100},regenPerSec:{default:0},invulnerableFor:{default:0},freeOnDeath:{default:!1}};static signals=[`damaged`,`healed`,`died`];max=100;regenPerSec=0;invulnerableFor=0;freeOnDeath=!1;current=0;invulnTimer=0;dead=!1;get isDead(){return this.dead}get invulnerableRemaining(){return this.invulnTimer}onReady(){if(!(this.max>0))throw new N(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "max" must be > 0, got ${this.max}.`,{prop:`max`});if(this.regenPerSec<0)throw new N(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "regenPerSec" must be >= 0, got ${this.regenPerSec}.`,{prop:`regenPerSec`});if(this.invulnerableFor<0)throw new N(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "invulnerableFor" must be >= 0, got ${this.invulnerableFor}.`,{prop:`invulnerableFor`});this.current=this.max}update(e){this.invulnTimer>0&&(this.invulnTimer=Math.max(0,this.invulnTimer-e)),this.regenPerSec>0&&!this.dead&&this.current<this.max&&this.setCurrent(this.current+this.regenPerSec*e)}damage(e){this.dead||e<=0||this.invulnTimer>0||(this.setCurrent(this.current-e),this.emit(`damaged`,e,this.current),this.invulnerableFor>0&&(this.invulnTimer=this.invulnerableFor),this.current<=0&&this.die())}heal(e){this.dead||e<=0||(this.setCurrent(this.current+e),this.emit(`healed`,e,this.current))}kill(){this.dead||(this.setCurrent(0),this.die())}setCurrent(e){this.current=Math.max(0,Math.min(this.max,e))}die(){this.dead||(this.dead=!0,this.current=0,this.emit(`died`),this.freeOnDeath&&this.node.queueFree())}serialize(){return{current:this.current,dead:this.dead}}deserialize(e){let t=e;typeof t.current==`number`&&(this.current=Math.min(this.max,Math.max(0,t.current))),typeof t.dead==`boolean`&&(this.dead=t.dead)}};function d_(e,t){let n=e.node;if(!n.declaredSignalNames().includes(`triggerEnter`)){let t=e.constructor.name;throw new N(`UNKNOWN_SIGNAL`,`${t} on '${n.getPath()}' needs a node that emits 'triggerEnter' — attach it to an Area2D/Area3D (or another body that declares the collision signals). '${n.name}' declares: [${n.declaredSignalNames().join(`, `)}].`,{signal:`triggerEnter`,path:n.getPath()})}n.on(`triggerEnter`,e=>t(e))}var f_=class extends et{static props={amount:{default:10},targetGroup:{default:``},oncePerTarget:{default:!0},repeatEvery:{default:0},destroySelf:{default:!1}};static signals=[`dealtDamage`];amount=10;targetGroup=``;oncePerTarget=!0;repeatEvery=0;destroySelf=!1;hit=new WeakSet;inside=new Map;onReady(){d_(this,e=>{this.inside.set(e,this.repeatEvery),this.tryDamage(e)}),this.node.on(`triggerExit`,e=>{this.inside.delete(e)})}update(e){if(!(this.repeatEvery<=0||this.inside.size===0))for(let[t,n]of this.inside){if(!t.tree){this.inside.delete(t);continue}let r=n-e;r>0?this.inside.set(t,r):(this.inside.set(t,this.repeatEvery),this.tryDamage(t,{repeat:!0}))}}tryDamage(e,t){if(!t?.repeat&&this.oncePerTarget&&this.hit.has(e))return;let n=p_(e);n&&(this.targetGroup!==``&&!n.owner.isInGroup(this.targetGroup)||(this.oncePerTarget&&this.hit.add(e),n.health.damage(this.amount),this.emit(`dealtDamage`,this.amount,n.owner),this.destroySelf&&this.node.queueFree()))}};function p_(e){let t=[e];for(;t.length>0;){let e=t.shift();if(e.behavior instanceof u_)return{health:e.behavior,owner:e};t.push(...e.children)}for(let t=e.parent;t;t=t.parent)if(t.behavior instanceof u_)return{health:t.behavior,owner:t};return null}var m_=class extends et{static signals=[`dayPhaseChanged`];static props={daySeconds:{default:240},startHour:{default:10},maxSunElevationDeg:{default:55},nightDarkness:{default:.75},paused:{default:!1}};daySeconds=240;startHour=10;maxSunElevationDeg=55;nightDarkness=.75;paused=!1;hour=0;phase=``;applyClock=0;baseAmbient=.3;baseExposure=1;captured=!1;onReady(){this.hour=this.startHour}update(e){if(this.paused||(this.hour=(this.hour+e/this.daySeconds*24)%24),this.applyClock-=e,this.applyClock>0)return;this.applyClock=.2,this.applyHour();let t=h_(this.hour);t!==this.phase&&(this.phase=t,this.emit(`dayPhaseChanged`,t))}applyHour(){let e=this.node.tree?.engine,t=e?.scene?.environment;if(!e||!t?.sky)return;this.captured||(this.captured=!0,this.baseAmbient=t.ambient?.intensity??.3,this.baseExposure=t.exposure??1);let n=(this.hour-6)/12*Math.PI,r=Math.sin(n);t.sky.elevationDeg=r*this.maxSunElevationDeg+(r<0?r*10:0),t.sky.azimuthDeg=this.hour/24*360+90;let i=Math.max(0,r),a=this.nightDarkness;t.ambient={...t.ambient??{},intensity:this.baseAmbient*(1-a+a*i)},t.exposure=this.baseExposure*(1-a*.55*(1-i))}};function h_(e){return e<5||e>=20?`night`:e<7.5?`dawn`:e<17.5?`day`:`dusk`}var g_=class extends et{static props={target:{default:``,nodePath:!0},offset:{default:[]},smoothing:{default:0},deadzone:{default:0}};static signals=[];target=``;offset=[];smoothing=0;deadzone=0;onReady(){if(this.target===``)throw new N(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.deadzone<0)throw new N(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "deadzone" must be >= 0, got ${this.deadzone}.`,{prop:`deadzone`});e_(this)}shakeMag=0;shakeT=0;shakeFalloff=.28;shake(e,t=.28){this.shakeMag=Math.max(this.shakeMag,e),this.shakeT=t,this.shakeFalloff=t}update(e){let t=this.node;if(!$g(t))return;let n=t.getNodeOrNull(this.target);if(!n||!$g(n))return;let r=n_(n.position,this.offset);if(!(this.deadzone>0&&t_(t.position,r)<=this.deadzone)){let n=o_(this.smoothing,e);n>=1?t.position=[...r]:t.position=t.position.map((e,t)=>e+((r[t]??e)-e)*n)}if(this.shakeT>0){this.shakeT-=e;let n=this.shakeMag*Math.max(0,this.shakeT)/this.shakeFalloff;this.shakeT<=0&&(this.shakeMag=0);let r=t.position.slice();for(let e=0;e<r.length;e++){let t=r.length>=3&&e===1?.5:1;r[e]=(r[e]??0)+(this.engine.rng.next()*2-1)*n*t}t.position=r}}};function __(e){let t=e.scene?.source;t&&(e.timeScale=1,e.setScene(kn(He(t))))}function v_(e,t,n){let r=n?.fadeSeconds??.4,i=()=>{e.timeScale=1,e.setScene(kn(He(t)))};if(typeof document>`u`||r<=0){i();return}let a=`incanto-scene-fade`,o=document.getElementById(a);o||(o=document.createElement(`div`),o.id=a,o.style.cssText=`position:fixed;inset:0;z-index:10001;background:#000;opacity:0;pointer-events:none;`,document.body.appendChild(o)),o.style.transition=`opacity ${r/2}s`,o.style.opacity=`1`,setTimeout(()=>{i();let e=document.getElementById(a);e&&(e.style.opacity=`0`,setTimeout(()=>e.remove(),r*500+60))},r*500+30)}var y_=class extends et{static signals=[`flowChanged`];static props={restartAction:{default:`restart`},freezeOnEnd:{default:!0},bannerPath:{default:`%Banner`,nodePath:!0}};restartAction=`restart`;freezeOnEnd=!0;bannerPath=`%Banner`;state=`playing`;frozeScale=!1;gameOver(e=`GAME OVER`,t=`#ef4444`){this.transition(`gameover`,e,t)}win(e=`YOU WIN`,t=`#4ade80`){this.transition(`won`,e,t)}pause(){this.state===`playing`&&(this.state=`paused`,this.freeze(),this.node.emit(`flowChanged`,this.state))}resume(){this.state===`paused`&&(this.state=`playing`,this.thaw(),this.node.emit(`flowChanged`,this.state))}restart(){this.thaw(),__(this.engine)}goToScene(e,t){this.thaw(),v_(this.engine,e,t)}transition(e,t,n){this.state===`gameover`||this.state===`won`||(this.state=e,this.freezeOnEnd&&this.freeze(),this.bannerPath!==``&&this.node.getNodeOrNull(this.bannerPath)?.show(t,{color:n,seconds:0}),this.node.emit(`flowChanged`,e))}freeze(){this.frozeScale||(this.frozeScale=!0,this.engine.timeScale=0)}thaw(){this.frozeScale&&(this.frozeScale=!1,this.engine.timeScale=1)}update(){if(!(this.state!==`gameover`&&this.state!==`won`))try{this.engine.input.justPressed(this.restartAction)&&this.restart()}catch{}}};function b_(e){return Array.isArray(e.position)}function x_(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}var S_=class extends et{static props={action:{default:`interact`},range:{default:2},actorGroup:{default:`player`}};static signals=[`interacted`];action=`interact`;range=2;actorGroup=`player`;update(){let e=this.node.tree?.engine;if(!e?.scene||!e.input.justPressed(this.action)||!b_(this.node))return;let t=this.node.position,n=null,r=1/0,i=this.node.tree?.getNodesInGroup(this.actorGroup)??C_(this.node.getRoot(),this.actorGroup);for(let e of i){if(!b_(e))continue;let i=x_(t,e.position);i<=this.range&&i<r&&(n=e,r=i)}n&&this.emit(`interacted`,n)}};function C_(e,t){let n=[],r=e=>{e.isInGroup(t)&&n.push(e);for(let t of e.children)r(t)};return r(e),n}var w_=.28,T_=class extends et{static props={falloff:{default:w_}};falloff=w_;magnitude=0;t=0;prev=[];shake(e,t){this.magnitude=Math.max(this.magnitude,e),this.t=t??this.falloff}update(e){let t=e_(this),n=t.position;for(let e=0;e<this.prev.length;e++)n[e]=(n[e]??0)-(this.prev[e]??0);if(this.t<=0){this.prev.length>0&&(t.position=n.slice(),this.prev.length=0);return}this.t-=e;let r=this.magnitude*Math.max(0,this.t)/this.falloff;this.t<=0&&(this.magnitude=0);let i=n.slice();this.prev.length!==i.length&&(this.prev=Array(i.length).fill(0));for(let e=0;e<i.length;e++){let t=i.length>=3&&e===1?.5:1;this.prev[e]=(this.engine.rng.next()*2-1)*r*t,i[e]=(i[e]??0)+this.prev[e]}t.position=i}},E_=class extends et{static props={seconds:{default:1},startOnSignal:{default:!1}};static signals=[`expired`];seconds=1;startOnSignal=!1;elapsed=0;running=!1;fired=!1;onReady(){if(!(this.seconds>0))throw new N(`PROP_TYPE_MISMATCH`,`Lifetime on '${this.node.getPath()}': "seconds" must be > 0, got ${this.seconds}.`,{prop:`seconds`});this.running=!this.startOnSignal}startTimer(){this.elapsed=0,this.fired=!1,this.running=!0}update(e){!this.running||this.fired||(this.elapsed+=e,this.elapsed>=this.seconds&&(this.fired=!0,this.running=!1,this.emit(`expired`),this.node.queueFree()))}},D_=[`linear`,`easeIn`,`easeOut`,`easeInOut`];function O_(e,t){let n=t<0?0:t>1?1:t;switch(e){case`linear`:return n;case`easeIn`:return n*n;case`easeOut`:return 1-(1-n)*(1-n);case`easeInOut`:return n<.5?2*n*n:1-(-2*n+2)**2/2}}var k_=class extends et{static props={to:{default:[]},duration:{default:1},ease:{default:`easeInOut`,options:[...D_]},startOnSignal:{default:!1}};static signals=[`arrived`];to=[];duration=1;ease=`easeInOut`;startOnSignal=!1;from=[];elapsed=0;running=!1;arrivedFired=!1;onReady(){if(!(this.duration>0))throw new N(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "duration" must be > 0, got ${this.duration}.`,{prop:`duration`});if(!D_.includes(this.ease))throw new N(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "ease" must be one of [${D_.join(`, `)}], got '${this.ease}'.`,{prop:`ease`});let e=e_(this);this.from=[...e.position],this.startOnSignal||(this.running=!0)}start(){let e=this.node;this.from=[...e.position],this.elapsed=0,this.arrivedFired=!1,this.running=!0}update(e){if(!this.running)return;let t=this.node;this.elapsed+=e;let n=Math.min(1,this.elapsed/this.duration),r=O_(this.ease,n);t.position=this.from.map((e,t)=>e+((this.to[t]??e)-e)*r),n>=1&&!this.arrivedFired&&(this.arrivedFired=!0,this.running=!1,this.emit(`arrived`))}},A_=[`x`,`y`,`z`],j_=[`position`,`rotation`,`scale`],M_={x:0,y:1,z:2},N_=class extends et{static props={axis:{default:`y`,options:[...A_]},amplitude:{default:1},frequency:{default:1},mode:{default:`position`,options:[...j_]}};static signals=[];axis=`y`;amplitude=1;frequency=1;mode=`position`;base=0;time=0;onReady(){if(!A_.includes(this.axis))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "axis" must be one of [${A_.join(`, `)}], got '${this.axis}'.`,{prop:`axis`});if(!j_.includes(this.mode))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "mode" must be one of [${j_.join(`, `)}], got '${this.mode}'.`,{prop:`mode`});this.base=this.readChannel()}update(e){this.time+=e;let t=this.amplitude*Math.sin(2*Math.PI*this.frequency*this.time);this.writeChannel(this.base+t)}isScalarRotation(){return this.mode===`rotation`&&typeof this.node.rotation==`number`}readChannel(){if(this.isScalarRotation())return this.node.rotation;let e=this.node[this.mode];if(!Array.isArray(e))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': node has no '${this.mode}' array to oscillate.`,{prop:`mode`});return e[M_[this.axis]]??0}writeChannel(e){if(this.isScalarRotation()){this.node.rotation=e;return}let t=[...this.node[this.mode]];t[M_[this.axis]]=e,this.node[this.mode]=t}},P_=class extends et{static signals=[`waypointReached`,`arrived`];static props={speed:{default:120},loop:{default:!1}};speed=120;loop=!1;waypoints=[];index=0;get moving(){return this.index<this.waypoints.length}setPath(e){this.waypoints=e.map(e=>[...e]),this.index=0}stop(){this.waypoints=[],this.index=0}update(e){if(!this.moving)return;let t=e_(this),n=this.speed*e;for(;n>0&&this.index<this.waypoints.length;){let e=this.waypoints[this.index],r=a_(t.position,e,n),i=F_(t.position,r.position);if(t.position=r.position,n-=i,r.reached){if(this.node.emit(`waypointReached`,this.index),this.index+=1,this.index>=this.waypoints.length)if(this.loop&&this.waypoints.length>1)this.index=0;else{this.node.emit(`arrived`);return}}else return}}};function F_(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(t[i]??0)-(e[i]??0);n+=r*r}return Math.sqrt(n)}var I_=class extends et{static props={points:{default:[]},speed:{default:60},loop:{default:!0},mode:{default:`loop`,options:[`loop`,`pingpong`]},pauseAt:{default:0}};static signals=[`reachedPoint`];points=[];speed=60;loop=!0;mode=`loop`;pauseAt=0;index=0;direction=1;pauseTimer=0;onReady(){if(!Array.isArray(this.points)||this.points.length===0)throw new N(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "points" must be a non-empty array of position arrays or node paths.`,{prop:`points`});if(this.mode!==`loop`&&this.mode!==`pingpong`)throw new N(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "mode" must be 'loop' or 'pingpong', got '${this.mode}'.`,{prop:`mode`});e_(this)}update(e){if(this.pauseTimer>0){this.pauseTimer=Math.max(0,this.pauseTimer-e);return}let t=this.node,n=this.pointAt(this.index);if(!n)return;let{position:r,reached:i}=a_(t.position,n,this.speed*e);t.position=r,i&&(this.emit(`reachedPoint`,this.index),this.advance(),this.pauseAt>0&&(this.pauseTimer=this.pauseAt))}pointAt(e){let t=this.points[e];if(Array.isArray(t))return t;if(typeof t==`string`){let e=this.node.getNodeOrNull(t);return Array.isArray(e?.position)?e.position:null}return null}advance(){let e=this.points.length-1;if(this.mode===`pingpong`){this.index>=e?this.direction=-1:this.index<=0&&(this.direction=1),this.index=Math.min(e,Math.max(0,this.index+this.direction));return}this.index<e?this.index+=1:this.loop&&(this.index=0)}},L_=class extends et{static props={value:{default:1},kind:{default:`coin`},collectorGroup:{default:`player`}};static signals=[`collected`];value=1;kind=`coin`;collectorGroup=`player`;collectedAlready=!1;onReady(){d_(this,e=>this.tryCollect(e))}tryCollect(e){this.collectedAlready||e.isInGroup(this.collectorGroup)&&(this.collectedAlready=!0,this.emit(`collected`,this.value,e),this.node.queueFree())}},R_=class extends et{static props={speed:{default:300},direction:{default:null},gravity:{default:0}};static signals=[];speed=300;direction=null;gravity=0;velocity=[];onReady(){if(this.speed===0&&this.gravity===0)throw new N(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': a projectile with "speed" 0 and "gravity" 0 never moves — set one of them.`,{prop:`speed`});let e=e_(this),t=this.resolveDirection();for(this.velocity=t.map(e=>e*this.speed);this.velocity.length<e.position.length;)this.velocity.push(0)}update(e){let t=this.node;this.gravity!==0&&(this.velocity[1]=(this.velocity[1]??0)+this.gravity*e);let n=t.position,r=Math.max(n.length,this.velocity.length),i=Array(r);for(let t=0;t<r;t++)i[t]=(n[t]??0)+(this.velocity[t]??0)*e;t.position=i}resolveDirection(){if(Array.isArray(this.direction))return i_(this.direction);if(this.direction===null||this.direction===`forward`)return this.forwardFromRotation();throw new N(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': "direction" must be a vector or 'forward', got ${JSON.stringify(this.direction)}.`,{prop:`direction`})}forwardFromRotation(){let e=this.node.rotation;if(typeof e==`number`){let t=e*Math.PI/180;return[Math.cos(t),Math.sin(t)]}if(Array.isArray(e)){let t=(e[1]??0)*Math.PI/180,n=(e[0]??0)*Math.PI/180;return i_([-Math.sin(t)*Math.cos(n),Math.sin(n),-Math.cos(t)*Math.cos(n)])}return[1,0]}},z_=class extends et{static props={score:{default:0},lives:{default:0},scoreToWin:{default:0}};static signals=[`scoreChanged`,`won`,`lost`,`lifeLost`];score=0;lives=0;scoreToWin=0;hasWon=!1;hasLost=!1;onReady(){if(this.lives<0)throw new N(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "lives" must be >= 0, got ${this.lives}.`,{prop:`lives`});if(this.scoreToWin<0)throw new N(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "scoreToWin" must be >= 0, got ${this.scoreToWin}.`,{prop:`scoreToWin`})}addScore(e){this.setScore(this.score+e)}setScore(e){this.score=e,this.emit(`scoreChanged`,this.score),this.scoreToWin>0&&!this.hasWon&&this.score>=this.scoreToWin&&(this.hasWon=!0,this.emit(`won`))}loseLife(){this.lives<=0||this.hasLost||(--this.lives,this.emit(`lifeLost`,this.lives),this.lives<=0&&(this.hasLost=!0,this.emit(`lost`)))}serialize(){return{score:this.score,lives:this.lives,hasWon:this.hasWon,hasLost:this.hasLost}}deserialize(e){let t=e;typeof t.score==`number`&&(this.score=t.score),typeof t.lives==`number`&&(this.lives=t.lives),typeof t.hasWon==`boolean`&&(this.hasWon=t.hasWon),typeof t.hasLost==`boolean`&&(this.hasLost=t.hasLost)}},B_=class{behavior;detached=new Map;constructor(e){this.behavior=e}resolveTemplate(e){let t=this.detached.get(e);if(t)return t;let n=this.behavior.node,r=e===``?null:n.getNodeOrNull(e);if(!r){let t=this.behavior.constructor.name;throw new N(`NODE_NOT_FOUND`,`${t} on '${n.getPath()}': "prefab" '${e}' does not resolve to a template node. Point it at a (usually hidden) child node to clone.`,{prop:`prefab`,path:n.getPath()})}return r.parent&&r.parent.removeChild(r),this.detached.set(e,r),r}spawn(e,t){let n=Un(e),r=t?.at;return r&&r.length>0&&$g(n)&&(n.position=n_($g(this.behavior.node)?this.behavior.node.position:[],r)),typeof n.visible==`boolean`&&(n.visible=!0),(t?.parent??this.behavior.node).addChild(n),n}},V_={CameraShake:T_,DayNight:m_,GameFlow:y_,PathFollow:P_,Health:u_,Lifetime:E_,ScoreKeeper:z_,Pickup:L_,Collector:l_,DamageOnContact:f_,Interactable:S_,Clickable:c_,FollowCamera:g_,Patrol:I_,Chase:s_,Wander:class extends et{static props={speed:{default:40},radius:{default:50},changeEvery:{default:2}};static signals=[];speed=40;radius=50;changeEvery=2;origin=[];goal=[];timer=0;onReady(){if(!(this.radius>0))throw new N(`PROP_TYPE_MISMATCH`,`Wander on '${this.node.getPath()}': "radius" must be > 0, got ${this.radius}.`,{prop:`radius`});let e=e_(this);this.origin=[...e.position],this.goal=[...e.position],this.pickGoal()}update(e){let t=this.node;this.timer-=e;let{position:n,reached:r}=a_(t.position,this.goal,this.speed*e);t.position=n,(r||this.timer<=0)&&this.pickGoal()}pickGoal(){this.timer=this.changeEvery;let e=this.origin.length,t=Array(e);for(let n=0;n<8;n++){for(let n=0;n<e;n++)t[n]=(this.origin[n]??0)+this.rng.range(-this.radius,this.radius);if(t_(t,this.origin)<=this.radius){this.goal=t;return}}this.goal=t.map((e,n)=>{let r=this.origin[n]??0,i=t_(t,this.origin)||1;return r+(e-r)/i*this.radius})}},ZombieAI:class extends et{static props={aggroTarget:{default:``,nodePath:!0},aggroRange:{default:12},deAggroRange:{default:0},chaseSpeed:{default:4},wanderSpeed:{default:1.4},wanderRadius:{default:8},wanderChangeEvery:{default:3},goalTarget:{default:``,nodePath:!0},stopRange:{default:1.2},moveParent:{default:!1}};static signals=[`enteredAggro`,`exitedAggro`,`movementStateChanged`];aggroTarget=``;aggroRange=12;deAggroRange=0;chaseSpeed=4;wanderSpeed=1.4;wanderRadius=8;wanderChangeEvery=3;goalTarget=``;stopRange=1.2;moveParent=!1;aggro=!1;started=!1;home=[];goal=[];timer=0;lastState=``;mover(){let e=this.moveParent?this.node.parent:this.node;return e&&$g(e)?e:null}effectiveDeAggro(){return this.deAggroRange>0?this.deAggroRange:this.aggroRange*1.5}onReady(){if(this.moveParent){let e=this.node.parent;if(!e||!$g(e))throw new N(`PROP_TYPE_MISMATCH`,`ZombieAI on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else e_(this)}update(e){let t=this.mover();if(!t)return;this.started||(this.started=!0,this.home=[...t.position],this.pickGoal());let n=this.aggroTarget?this.node.getNodeOrNull(this.aggroTarget):null,r=n&&$g(n)?n.position:null,i=r?this.groundDistance(t.position,r):1/0;if(!this.aggro&&i<=this.aggroRange?(this.aggro=!0,this.emit(`enteredAggro`)):this.aggro&&i>=this.effectiveDeAggro()&&(this.aggro=!1,this.emit(`exitedAggro`),this.pickGoal()),this.aggro&&r){let n=this.approach(t,r,this.chaseSpeed,e);this.setState(n?`idle`:`run`);return}this.timer-=e;let a=this.approach(t,this.goal,this.wanderSpeed,e);this.setState(a?`idle`:`walk`),(a||this.timer<=0)&&this.pickGoal()}approach(e,t,n,r){let i=e.position;if(this.groundDistance(i,t)<=this.stopRange)return!0;let a=i.length>=3?1:-1,o=[...t];a>=0&&(o[a]=i[a]??0);let s=this.groundDistance(i,o),{position:c}=a_(i,o,Math.min(n*r,Math.max(0,s-this.stopRange)));return e.position=c,!1}groundDistance(e,t){if(e.length>=3){let n=(e[0]??0)-(t[0]??0),r=(e[2]??0)-(t[2]??0);return Math.hypot(n,r)}return t_(e,t)}setState(e){e!==this.lastState&&(this.lastState=e,this.emit(`movementStateChanged`,e))}pickGoal(){this.timer=this.wanderChangeEvery;let e=this.mover(),t=e?e.position:this.home,n=t.length>=3?1:-1,r=this.home,i=this.goalTarget?this.node.getNodeOrNull(this.goalTarget):null;if(i&&$g(i)){let e=i.position;r=t.map((t,n)=>t+((e[n]??0)-t)*.4)}let a=[...r];for(let e=0;e<a.length;e++)e!==n&&(a[e]=(r[e]??0)+this.rng.range(-this.wanderRadius,this.wanderRadius));n>=0&&(a[n]=t[n]??0),this.goal=a}},MoveTo:k_,Oscillate:N_,Spawner:class extends et{static props={prefab:{default:``,nodePath:!0},interval:{default:1},max:{default:0},at:{default:[]},autoStart:{default:!0},total:{default:0}};static signals=[`spawned`,`finished`];prefab=``;interval=1;max=0;at=[];autoStart=!0;total=0;source=new B_(this);template;live=new Set;timer=0;running=!1;spawnedCount=0;done=!1;get liveCount(){return this.prune(),this.live.size}_templateForTest(){return this.template}onReady(){this.template=this.source.resolveTemplate(this.prefab),this.running=this.autoStart,this.timer=this.interval}start(){this.done||(this.running=!0)}stop(){this.running=!1}spawn(){if(this.prune(),this.done||this.max>0&&this.live.size>=this.max)return null;let e=this.source.spawn(this.template,this.at.length>0?{at:this.at}:void 0);return this.live.add(e),this.spawnedCount+=1,this.emit(`spawned`,e),this.total>0&&this.spawnedCount>=this.total&&(this.done=!0,this.running=!1,this.emit(`finished`)),e}update(e){this.running&&(this.timer-=e,!(this.timer>0)&&(this.timer+=this.interval,this.spawn()))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}},WaveSpawner:class extends et{static props={waves:{default:[]},autoStart:{default:!0}};static signals=[`waveStarted`,`waveCleared`,`allCleared`];waves=[];autoStart=!0;source=new B_(this);parsed=[];live=new Set;waveIndex=-1;phase=`idle`;timer=0;spawnedThisWave=0;announced=!1;onReady(){if(!Array.isArray(this.waves)||this.waves.length===0)throw new N(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': "waves" must be a non-empty array of { prefab, count, interval, delayBefore }.`,{prop:`waves`});this.parsed=this.waves.map((e,t)=>this.parseWave(e,t));for(let e of this.parsed)this.source.resolveTemplate(e.prefab);this.autoStart&&this.beginWave(0)}start(){this.beginWave(0)}update(e){if(this.phase===`idle`||this.phase===`done`)return;let t=this.parsed[this.waveIndex];if(t){if(this.announced||(this.announced=!0,this.emit(`waveStarted`,this.waveIndex)),this.phase===`delay`){this.timer-=e,this.timer<=0&&(this.phase=`spawning`,this.timer=0);return}if(this.phase===`spawning`){for(this.timer-=e;this.timer<=0&&this.spawnedThisWave<t.count;){let e=this.source.spawn(this.source.resolveTemplate(t.prefab));this.live.add(e),this.spawnedThisWave+=1,this.timer+=t.interval}this.spawnedThisWave>=t.count&&(this.phase=`clearing`);return}if(this.phase===`clearing`&&(this.prune(),this.live.size===0)){this.emit(`waveCleared`,this.waveIndex);let e=this.waveIndex+1;e<this.parsed.length?this.beginWave(e):(this.phase=`done`,this.emit(`allCleared`))}}}beginWave(e){this.waveIndex=e,this.spawnedThisWave=0,this.announced=!1,this.live.clear();let t=this.parsed[e];t&&(t.delayBefore>0?(this.phase=`delay`,this.timer=t.delayBefore):(this.phase=`spawning`,this.timer=0))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}parseWave(e,t){let n=e,r=typeof n?.prefab==`string`?n.prefab:``;if(r===``)throw new N(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': wave ${t} needs a "prefab" template path.`,{prop:`waves`});return{prefab:r,count:typeof n?.count==`number`?n.count:1,interval:typeof n?.interval==`number`?n.interval:.5,delayBefore:typeof n?.delayBefore==`number`?n.delayBefore:0}}},Projectile:R_,Buoyancy:Zg};function H_(e){let t=e?.replace??!0;for(let[e,n]of Object.entries(V_))it(e,n,{replace:t})}function U_(e,t){let n=e.shape;if(n!==void 0){if(e.oneWay!==void 0&&typeof e.oneWay!=`boolean`)throw new N(`BAD_FORMAT`,`Collider on '${t}': "oneWay" must be a boolean (platforms you jump up through), got ${JSON.stringify(e.oneWay)}.`);if(n===`rect`){let n=e.size;if(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`))throw new N(`BAD_FORMAT`,`Collider on '${t}': rect needs "size": [width, height].`);return}if(n===`circle`){if(typeof e.radius!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${t}': circle needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}throw new N(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(n)}.`)}}var W_=class extends At{static typeName=`Node2D`;static props={position:{default:[0,0]},rotation:{default:0},static:{default:!1},scale:{default:[1,1]},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},visible:{default:!0}};static propAliases={zIndex:`renderOrder`};position=[0,0];rotation=0;static=!1;scale=[1,1];renderOrder=0;orderGroup=`default`;get effectiveRenderOrder(){return un(this.orderGroup,this.renderOrder)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new ho}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-ya.degToRad(this.rotation),t.scale.set(this.scale[0]??1,this.scale[1]??1,1),t.visible=this.visible}free(){super.free(),this._object2D?.removeFromParent(),this._object2D=null}},G_=class extends W_{static props={collider:{default:{},variants:{tag:`shape`,byTag:{rect:{shape:`rect`,size:[32,32]},circle:{shape:`circle`,radius:16},capsule:{shape:`capsule`,radius:12,height:32}}}}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}static validateJson(e){U_(e.collider,e.name)}_physics=null},K_=class extends G_{static typeName=`StaticBody2D`},q_=class extends G_{static typeName=`Area2D`},J_=class extends G_{static typeName=`RigidBody2D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0]}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearVelocity=[0,0]},Y_=class extends G_{static typeName=`CharacterBody2D`;static props={velocity:{default:[0,0]},snapToGround:{default:!0},slopeLimitDeg:{default:45}};velocity=[0,0];snapToGround=!0;slopeLimitDeg=45;_grounded=!1;moveAndSlide(){if(!this._physics)throw new N(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody2D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody2D '${this.name}' has no physics world — await enablePhysics2D(engine) first.`);this._physics.moveAndSlide(this)}_onWall=0;_onCeiling=!1;isOnWall(){return this._onWall!==0}wallSide(){return this._onWall}isOnCeiling(){return this._onCeiling}isOnFloor(){return this._grounded}},X_=new Set;function Z_(e){return X_.add(e),()=>X_.delete(e)}function Q_(e,t){return[...X_].filter(n=>n.dimension===e&&(t===void 0||n.engine===t))}var $_=class extends W_{static typeName=`Joint2D`;static props={type:{default:`revolute`,options:[`fixed`,`revolute`,`rope`,`spring`]},target:{default:``,nodePath:!0},anchor:{default:[0,0]},targetAnchor:{default:[0,0]},length:{default:0},stiffness:{default:50},damping:{default:5}};type=`revolute`;target=``;anchor=[0,0];targetAnchor=[0,0];length=0;stiffness=50;damping=5;onEnterTree(){if(!(this.parent instanceof G_))throw new N(`TREE_VIOLATION`,`Joint2D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new N(`BAD_FORMAT`,`Joint2D '${this.name}' needs a "target" node path to the body it links to.`)}_resolveBodies(){let e=this.parent,t=this.getNodeOrNull(this.target);if(!(t instanceof G_))throw new N(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},Z=100,ev=Math.PI/180;async function tv(e,t){let n=await ym(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await n.init({}),new nv(n,e,t)}var nv=class{R;engine;debugDraw=!1;debugScope=null;dimension=`2d`;unregisterDebug;warnedNoCollider=new WeakSet;entries=new Map;byColliderHandle=new Map;world;events;kcc;disconnect;lastDt=1/60;optsGravity;lastScene=null;constructor(e,t,n){this.R=e,this.engine=t,this.optsGravity=n?.gravity,this.simulate=n?.simulate??!0,this.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,980];this.world=new e.World({x:(i[0]??0)/Z,y:(i[1]??0)/Z}),this.kcc=this.world.createCharacterController(.01),this.kcc.setUp({x:0,y:-1}),this.events=new e.EventQueue(!0),this.unregisterDebug=Z_(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.syncBodies()}simulate;step(e){if(this.lastDt=e,!this.simulate){this.syncBodies(),this.poseFromTree();return}if(this.engine.scene!==this.lastScene&&(this.lastScene=this.engine.scene,!this.optsGravity)){let e=this.engine.scene?.physics?.gravity??[0,980];this.world.gravity={x:(e[0]??0)/Z,y:(e[1]??0)/Z}}this.syncBodies(),this.world.timestep=e,this.world.step(this.events);for(let[e,t]of this.entries){let n=t.body.translation();if(!t.body.isFixed()){let[t,r]=lv(e);e.position=[n.x*Z-t,n.y*Z-r]}if(e instanceof J_){e.fixedRotation||(e.rotation=t.body.rotation()/ev);let n=t.body.linvel();e.linearVelocity=[n.x*Z,n.y*Z],t.lastVX=e.linearVelocity[0]??0,t.lastVY=e.linearVelocity[1]??0}let[r,i]=cv(e);t.lastX=r,t.lastY=i}this.events.drainCollisionEvents((e,t,n)=>{let r=this.byColliderHandle.get(e),i=this.byColliderHandle.get(t);if(!r||!i)return;let a=n?`triggerEnter`:`triggerExit`;try{r.emit(a,i),i.emit(a,r)}catch(e){lt(this.engine,`error`,`incanto: error in a '${a}' handler (${r.name} ↔ ${i.name}):`,e)}})}moveAndSlide(e){let t=this.ensureEntry(e),n=e.velocity[1]??0;e.snapToGround&&n>=0?this.kcc.enableSnapToGround(.05):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*ev);let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=cv(t.ground);r=e-(t.groundX??e),i=n-(t.groundY??n)}else t.ground=null;let a={x:((e.velocity[0]??0)*this.lastDt+r)/Z*1,y:(n*this.lastDt+i)/Z*1},o=t.body.translation().y*Z+ov(e);this.kcc.computeColliderMovement(t.collider,a,this.R.QueryFilterFlags.EXCLUDE_SENSORS,void 0,t=>{let r=this.byColliderHandle.get(t.handle);return!(r&&r!==e&&r.collider.oneWay===!0&&(n<0||o>sv(r)+av))});let s=this.kcc.computedMovement(),c=t.body.translation();t.body.setNextKinematicTranslation({x:c.x+s.x,y:c.y+s.y}),e._grounded=this.kcc.computedGrounded(),e._onWall=0,e._onCeiling=!1;let l=this.kcc.numComputedCollisions();for(let t=0;t<l;t++){let n=this.kcc.computedCollision(t)?.normal1;n&&(Math.abs(n.y)>.7?e._grounded||(e._onCeiling=!0):Math.abs(n.x)>.7&&(e._onWall=n.x>0?-1:1))}if(e._grounded){let n=(c.x+s.x)*Z,r=(c.y+s.y)*Z+ov(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&!(i.node instanceof Y_)){t.ground=i.node;let[e,n]=cv(i.node);t.groundX=e,t.groundY=n}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope?this.scopedLines(this.debugScope):this.world.debugRender().vertices,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]*Z;return t}scopedLines(e){let t=[],n=[],r=e=>{let t=this.entries.get(e);t&&n.push(t.body);for(let t of e.children)r(t)};r(e);for(let t=e.parent;t&&n.length===0;t=t.parent){let e=this.entries.get(t);e&&n.push(e.body)}for(let e of n)for(let n=0;n<e.numColliders();n++){let r=e.collider(n);if(!r)continue;let i=r.translation(),a=r.rotation(),o=Math.cos(a),s=Math.sin(a),c=(e,n)=>{t.push(i.x+e*o-n*s,i.y+e*s+n*o)},l=(e,t,n,r)=>{c(e,t),c(n,r)},u=r.shape;if(u.halfExtents){let{x:e,y:t}=u.halfExtents;l(-e,-t,e,-t),l(e,-t,e,t),l(e,t,-e,t),l(-e,t,-e,-t)}else if(u.radius!==void 0){let e=u.radius,t=u.halfHeight??0;for(let n=0;n<24;n++){let r=n/24*Math.PI*2,i=(n+1)/24*Math.PI*2,a=e=>e>=0?t:-t;l(Math.cos(r)*e,Math.sin(r)*e+a(Math.sin(r)),Math.cos(i)*e,Math.sin(i)*e+a(Math.sin(i)))}t>0&&(l(-e,-t,-e,t),l(e,-t,e,t))}}return new Float32Array(t)}syncJoints(e){let t=this.R;if(e)for(let[e,t]of this.joints)this.jointSet.has(e)||(this.world.removeImpulseJoint(t,!0),this.joints.delete(e));for(let e of this.jointSet){if(this.joints.has(e))continue;let{a:n,b:r}=e._resolveBodies(),i=this.entries.get(n),a=this.entries.get(r);if(!i||!a)continue;let o={x:(e.anchor[0]??0)/Z,y:(e.anchor[1]??0)/Z},s={x:(e.targetAnchor[0]??0)/Z,y:(e.targetAnchor[1]??0)/Z},c=e.length/Z;if(e.length===0&&(e.type===`rope`||e.type===`spring`)){let e=i.body.translation(),t=a.body.translation();c=Math.hypot(t.x-e.x,t.y-e.y)}let l;l=e.type===`fixed`?t.JointData.fixed(o,0,s,0):e.type===`rope`?t.JointData.rope(c,o,s):e.type===`spring`?t.JointData.spring(c,e.stiffness,e.damping,o,s):t.JointData.revolute(o,s),this.joints.set(e,this.world.createImpulseJoint(l,i.body,a.body,!0))}}castRay(e,t,n,r,i){let a=Math.hypot(t[0],t[1])||1,o=new this.R.Ray({x:e[0]/Z,y:e[1]/Z},{x:t[0]/a,y:t[1]/a}),s=r?this.entries.get(r)?.collider:void 0,c=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castRayAndGetNormal(o,n/Z,!0,c,void 0,s,void 0,e=>!e.isSensor());return l?{distance:l.timeOfImpact*Z,normal:[l.normal.x,l.normal.y],node:this.byColliderHandle.get(l.collider.handle)??null}:null}dispose(){this.disconnect(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;bodySet=new Set;poseFromTree(){for(let[e,t]of this.entries){let[n,r]=cv(e);t.body.setTranslation({x:n/Z,y:r/Z},!1),t.body.setRotation(e.rotation*ev,!1)}this.world.propagateModifiedBodyPositionsToColliders()}syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=e.root===this.lastRoot,r=t!==this.lastStructure||!n;if(r){let r=n?e.tree._structureSince(this.lastStructure):null;if(this.lastStructure=t,this.lastRoot=e.root,r){let t=!1;for(let{node:e,added:n}of r)e instanceof G_&&(n?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof $_&&(t=!0);t&&(this.jointSet.clear(),rv(e.root,this.jointSet))}else this.bodySet.clear(),iv(e.root,this.bodySet),this.jointSet.clear(),rv(e.root,this.jointSet)}let i=this.bodySet;for(let e of i){if(e.collider.shape===void 0){let t=this.entries.get(e);t&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.warnedNoCollider.has(e)||(this.warnedNoCollider.add(e),lt(this.engine,`warn`,`[incanto] '${e.name}' has no collider — physics skips it.`));continue}let t=this.entries.get(e);t&&e._colliderChanged&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.ensureEntry(e)}if(this.syncJoints(r),r)for(let[e,t]of this.entries)i.has(e)||(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let[r,i]=cv(e),a=r/Z,o=i/Z,s;s=e instanceof J_?n.RigidBodyDesc.dynamic():e instanceof Y_||e instanceof q_?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),s.setTranslation(a,o).setRotation(e.rotation*ev),e instanceof J_&&(s.setGravityScale(e.gravityScale),s.setLinvel((e.linearVelocity[0]??0)/Z,(e.linearVelocity[1]??0)/Z),e.fixedRotation&&s.lockRotations());let c=this.world.createRigidBody(s),l=uv(n,e.collider,e.name);l.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof q_&&l.setSensor(!0),e instanceof J_&&l.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let u=this.world.createCollider(l,c);return t={body:c,collider:u,lastX:r,lastY:i,lastVX:0,lastVY:0},this.entries.set(e,t),this.byColliderHandle.set(u.handle,e),e._colliderChanged=!1,e._physics=this,t}let[r,i]=cv(e);if((r!==t.lastX||i!==t.lastY)&&(t.body.setTranslation({x:r/Z,y:i/Z},!0),t.lastX=r,t.lastY=i),e instanceof J_){let n=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(n!==t.lastVX||r!==t.lastVY)&&(t.body.setLinvel({x:n/Z,y:r/Z},!0),t.lastVX=n,t.lastVY=r)}return t}};function rv(e,t){e instanceof $_&&t.add(e);for(let n of e.children)rv(n,t)}function iv(e,t){e instanceof G_&&t.add(e);for(let n of e.children)iv(n,t)}var av=4;function ov(e){let t=e.collider;return t.shape===`rect`?(t.size?.[1]??32)/2:t.shape===`capsule`?(t.height??32)/2+(t.radius??8):t.radius??16}function sv(e){let[,t]=cv(e),n=e.collider;return t-(n.shape===`rect`?(n.size?.[1]??32)/2:n.shape===`capsule`?(n.height??32)/2+(n.radius??8):n.radius??16)}function cv(e){let t=0,n=0;for(let r=e;r;r=r.parent)r instanceof W_&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function lv(e){let t=0,n=0;for(let r=e.parent;r;r=r.parent)r instanceof W_&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function uv(e,t,n){U_(t,n);let r=dv(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Z,(i[1]??0)/Z),r}function dv(e,t,n){let r=t.shape;if(r===`rect`){let r=t.size;if(!Array.isArray(r)||r.length!==2||r.some(e=>typeof e!=`number`))throw new N(`BAD_FORMAT`,`Collider on '${n}': rect needs "size": [width, height].`);return e.ColliderDesc.cuboid(r[0]/2/Z,r[1]/2/Z)}if(r===`circle`){if(typeof t.radius!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${n}': circle needs "radius".`);return e.ColliderDesc.ball(t.radius/Z)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2/Z,t.radius/Z)}throw new N(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(r)}.`)}var fv=new sl(1,1),pv=class extends W_{static typeName=`Sprite2D`;static props={texture:{default:``},anchor:{default:[.5,.5]},flipX:{default:!1},flipY:{default:!1},tint:{default:`#ffffff`},opacity:{default:1}};texture=``;anchor=[.5,.5];flipX=!1;flipY=!1;tint=`#ffffff`;opacity=1;quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Js(fv,new Is({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_createObject2D(){return super._createObject2D()}resolveTexture(e){if(!this.texture||!e)return null;let t=e.getTexture(this.texture),n=t.image;return!n?.width||!n.height?null:{texture:t,width:n.width,height:n.height}}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=t.material,r=this.resolveTexture(e);if(!r){t.visible=!1;return}t.visible=!0,n.map!==r.texture&&(n.map=r.texture,n.needsUpdate=!0);let i=r.width,a=r.height;t.scale.set(this.flipX?-i:i,this.flipY?-a:a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??.5;t.position.set((.5-o)*i,(s-.5)*a,0),t.renderOrder=this.effectiveRenderOrder,n.color.set(this.tint),n.opacity=this.opacity}},mv=class extends pv{static typeName=`AnimatedSprite2D`;static signals=[`animationFinished`];static props={sheet:{default:``},animations:{default:{}},autoplay:{default:``}};sheet=``;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;ownTexture=null;loadedSheetRef=``;play(e){let t=this.animations[e];if(!t)throw new N(`UNKNOWN_ANIMATION`,`No animation '${e}' on '${this.name}'. Available: [${Object.keys(this.animations).join(`, `)}].`);this.currentAnimation=e,this.frameList=hv(t.frames,e),this.frameIndex=0,this.currentFrame=this.frameList[0]??0,this.frameTime=0,this.playing=!0}stop(){this.playing=!1}onReady(){this.autoplay&&this.play(this.autoplay)}update(e){if(!this.playing||this.currentAnimation===``)return;let t=this.animations[this.currentAnimation];if(!t||!Number.isFinite(t.fps)||t.fps<=0)return;let n=1/t.fps;for(this.frameTime+=e;this.frameTime>=n;)if(this.frameTime-=n,this.frameIndex+=1,this.frameIndex>=this.frameList.length)if(t.loop)this.frameIndex=0;else{this.frameIndex=this.frameList.length-1,this.playing=!1,this.emit(`animationFinished`,this.currentAnimation);break}this.currentFrame=this.frameList[this.frameIndex]??0}resolveTexture(e){if(!this.sheet||!e)return null;let t=e.getSheet(this.sheet);this.loadedSheetRef!==this.sheet&&(this.ownTexture=t.texture.clone(),this.ownTexture.needsUpdate=!0,this.loadedSheetRef=this.sheet);let n=this.ownTexture,r=t.texture.image;if(!r?.width||!r.height)return null;let i=Math.max(1,Math.floor(r.width/t.frameWidth)),a=this.currentFrame%i,o=Math.floor(this.currentFrame/i);return n.repeat.set(t.frameWidth/r.width,t.frameHeight/r.height),n.offset.set(a*t.frameWidth/r.width,1-(o+1)*t.frameHeight/r.height),{texture:n,width:t.frameWidth,height:t.frameHeight}}};function hv(e,t){if(!Array.isArray(e)||e.length===0)throw new N(`BAD_FORMAT`,`Animation '${t}': "frames" must be a non-empty array.`);if(e.length===2){let[t,n]=e;if(n>=t){let e=[];for(let r=t;r<=n;r++)e.push(r);return e}}return[...e]}var gv=class extends W_{static typeName=`Camera2D`;static props={follow:{default:``,nodePath:!0},smoothing:{default:0},zoom:{default:1},limits:{default:[]},current:{default:!1}};follow=``;smoothing=0;zoom=1;limits=[];current=!1;get effectiveZoom(){return Math.max(.01,this.zoom)}update(e){if(!this.follow)return;let t=this.getNodeOrNull(this.follow);if(!(t instanceof W_))return;let n=t.position[0]??0,r=t.position[1]??0,i=Math.min(Math.max(this.smoothing,0),.99),a=i<=0?1:1-i**(e*60),o=this.position[0]??0,s=this.position[1]??0;this.position=[o+(n-o)*a,s+(r-s)*a]}clampedCenter(e,t){let n=this.position[0]??0,r=this.position[1]??0;if(this.limits.length!==0&&this.limits.length!==4)throw new N(`BAD_FORMAT`,`Camera2D '${this.name}' limits must be [] or [minX,minY,maxX,maxY], got length ${this.limits.length}.`);if(this.limits.length===4){let[i,a,o,s]=this.limits,c=e/(2*this.effectiveZoom),l=t/(2*this.effectiveZoom);n=_v(n,i+c,o-c),r=_v(r,a+l,s-l)}return{x:n,y:r}}};function _v(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var vv=class extends At{static typeName=`CharacterController2D`;static props={mode:{default:`platformer`,options:[`platformer`,`topDown`]},maxSpeed:{default:220},jumpHeight:{default:64},moveAction:{default:`move`},jumpAction:{default:`jump`},coyoteSeconds:{default:0},jumpBufferSeconds:{default:0},jumpCutMultiplier:{default:1},maxJumps:{default:1},dashSpeed:{default:0},dashSeconds:{default:.15},dashAction:{default:`dash`},wallSlideSpeed:{default:0},wallJumpImpulse:{default:[0,0]}};static signals=[`movementStateChanged`];mode=`platformer`;maxSpeed=220;jumpHeight=64;moveAction=`move`;jumpAction=`jump`;coyoteSeconds=0;jumpBufferSeconds=0;jumpCutMultiplier=1;maxJumps=1;dashSpeed=0;dashSeconds=.15;dashAction=`dash`;wallSlideSpeed=0;wallJumpImpulse=[0,0];state=`idle`;coyoteLeft=0;bufferLeft=0;jumpsUsed=0;dashLeft=0;dashDir=1;rising=!1;onReady(){if(!(this.parent instanceof Y_))throw new N(`TREE_VIOLATION`,`CharacterController2D '${this.name}' must be a child of a CharacterBody2D (parent is '${this.parent?.name??`none`}').`);if(this.mode!==`platformer`&&this.mode!==`topDown`)throw new N(`PROP_TYPE_MISMATCH`,`CharacterController2D.mode must be 'platformer' or 'topDown', got '${this.mode}'.`)}fixedUpdate(e){let t=this.tree?.engine;if(!t?.scene)return;let n=this.parent;if(!(n instanceof Y_))return;let r=t.input,i=r.getVector(this.moveAction);if(this.mode===`topDown`){n.velocity=[i.x*this.maxSpeed,i.y*this.maxSpeed],n.moveAndSlide();return}let a=t.scene.physics?.gravity?.[1]??980,o=n.isOnFloor(),s=-Math.sqrt(2*a*this.jumpHeight);if(this.dashLeft>0){this.dashLeft-=e,n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}if(this.dashSpeed>0&&r.justPressed(this.dashAction)){this.dashLeft=this.dashSeconds,this.dashDir=i.x===0?this.dashDir:Math.sign(i.x),n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}n.velocity[0]=i.x*this.maxSpeed,o?(this.coyoteLeft=this.coyoteSeconds,this.jumpsUsed=0):(this.coyoteLeft=Math.max(0,this.coyoteLeft-e),this.coyoteLeft<=0&&this.jumpsUsed===0&&(this.jumpsUsed=1)),r.justPressed(this.jumpAction)?this.bufferLeft=Math.max(this.jumpBufferSeconds,0):this.bufferLeft=Math.max(0,this.bufferLeft-e);let c=this.bufferLeft>0||r.justPressed(this.jumpAction),l=this.wallSlideSpeed>0||this.wallJumpImpulse.some(e=>e!==0)?n.isOnWall():!1;if(c&&l&&!o&&this.wallJumpImpulse.some(e=>e!==0)){let e=-n.wallSide();n.velocity[0]=e*(this.wallJumpImpulse[0]??0),n.velocity[1]=-(this.wallJumpImpulse[1]??0),this.bufferLeft=0,this.rising=!0,this.jumpsUsed=1}else c&&(o||this.coyoteLeft>0||this.jumpsUsed<this.maxJumps)?(n.velocity[1]=s,this.bufferLeft=0,this.coyoteLeft=0,this.rising=!0,this.jumpsUsed=o?1:this.jumpsUsed+1):o?(n.velocity[1]=20,this.rising=!1):(n.velocity[1]=(n.velocity[1]??0)+a*e,this.rising&&this.jumpCutMultiplier<1&&!r.isPressed(this.jumpAction)&&(n.velocity[1]=(n.velocity[1]??0)*this.jumpCutMultiplier,this.rising=!1),(n.velocity[1]??0)>=0&&(this.rising=!1),this.wallSlideSpeed>0&&l&&(n.velocity[1]??0)>this.wallSlideSpeed&&(n.velocity[1]=this.wallSlideSpeed));n.isOnCeiling()&&(n.velocity[1]??0)<0&&(n.velocity[1]=0,this.rising=!1),n.moveAndSlide();let u=n.velocity[1]??0;this.wallSlideSpeed>0&&!n.isOnFloor()&&n.isOnWall()&&u>0?this.setState(`wallSlide`):n.isOnFloor()?this.setState(Math.abs(i.x)>.01?`run`:`idle`):this.setState(u<0?`jump`:`fall`)}setState(e){e!==this.state&&(this.state=e,this.emit(`movementStateChanged`,e))}},yv=new sl(1,1),bv=class extends W_{static typeName=`ColorRect2D`;static props={size:{default:[100,100]},color:{default:`#ffffff`},opacity:{default:1},anchor:{default:[.5,.5]}};size=[100,100];color=`#ffffff`;opacity=1;anchor=[.5,.5];quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Js(yv,new Is({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=this.size[0]??0,r=this.size[1]??0;t.visible=n>0&&r>0&&this.opacity>0,t.scale.set(n,r,1);let i=this.anchor[0]??.5,a=this.anchor[1]??.5;t.position.set((.5-i)*n,(a-.5)*r,0),t.renderOrder=this.effectiveRenderOrder;let o=t.material;o.color.set(this.color),o.opacity=this.opacity}},xv=new sl(1,1),Sv=class extends W_{static typeName=`Label`;static props={text:{default:``},fontSize:{default:16},color:{default:`#ffffff`},font:{default:`monospace`},align:{default:`left`}};text=``;fontSize=16;color=`#ffffff`;font=`monospace`;align=`left`;quadMesh=null;canvas=null;lastKey=``;_quad(){return this.quadMesh||(this.quadMesh=new Js(xv,new Is({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad();if(typeof document>`u`||this.text===``){t.visible=!1;return}let n=`${this.text}\0${this.fontSize}\0${this.color}\0${this.font}\0${this.align}`;n!==this.lastKey&&(this.lastKey=n,this.rasterize()),t.visible=!0,t.renderOrder=this.effectiveRenderOrder}rasterize(){let e=Math.min(globalThis.devicePixelRatio??1,2);this.canvas??=document.createElement(`canvas`);let t=this.canvas.getContext(`2d`);if(!t)return;let n=`${this.fontSize*e}px ${this.font}`;t.font=n;let r=t.measureText(this.text),i=Math.max(1,Math.ceil(r.width)),a=Math.ceil(this.fontSize*e*1.4);this.canvas.width=i,this.canvas.height=a,t.font=n,t.fillStyle=this.color,t.textBaseline=`middle`,t.fillText(this.text,0,a/2);let o=this._quad(),s=o.material;s.map?.dispose(),s.map=new Zc(this.canvas),s.needsUpdate=!0;let c=i/e,l=a/e;o.scale.set(c,l,1);let u=this.align===`center`?.5:+(this.align===`right`);o.position.set((.5-u)*c,0,0)}},Cv=new sl(1,1),wv=class e extends W_{orderGroup=`effects`;static typeName=`Particles2D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...fn]},emitting:{default:!0},rate:{default:40},burst:{default:0},lifetime:{default:[.6,1.2]},speed:{default:[40,120]},directionDeg:{default:-90},spreadDeg:{default:30},gravity:{default:[0,0]},drag:{default:0},sizeStart:{default:8},sizeEnd:{default:2},colorStart:{default:`#ffffff`},colorEnd:{default:`#ffffff`},paletteColors:{default:[]},alphaStart:{default:1},alphaEnd:{default:0},shimmer:{default:0},blend:{default:`add`,options:[`add`,`normal`]},maxParticles:{default:256}};preset=`custom`;emitting=!0;rate=40;burst=0;lifetime=[.6,1.2];speed=[40,120];directionDeg=-90;spreadDeg=30;gravity=[0,0];drag=0;sizeStart=8;sizeEnd=2;colorStart=`#ffffff`;colorEnd=`#ffffff`;paletteColors=[];alphaStart=1;alphaEnd=0;shimmer=0;blend=`add`;maxParticles=256;static validateJson(e){let t=e;if(t.preset!==`custom`&&!fn.includes(t.preset))throw new N(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${fn.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:fn});if(t.blend!==`add`&&t.blend!==`normal`)throw new N(`BAD_FORMAT`,`Particles2D '${e.name}' blend must be 'add' or 'normal', got '${t.blend}'.`,{prop:`blend`,validOptions:[`add`,`normal`]})}sim=null;bursted=!1;finishedEmitted=!1;_ensureSim(){if(!this.sim){pn(this,this.preset,qe(e.typeName));let t=this.tree?.engine?.rng??new P(4660);this.sim=new hn({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[this.speed[0]??0,this.speed[1]??0],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[this.gravity[0]??0,this.gravity[1]??0,0],drag:this.drag,maxParticles:this.maxParticles},t)}return this.sim}update(e){let t=this._ensureSim();this.burst>0&&!this.bursted&&(this.bursted=!0,t.burst(this.burst)),t.update(e),(!this.emitting||this.rate===0)&&this.bursted&&t.done&&!this.finishedEmitted&&(this.finishedEmitted=!0,this.emit(`finished`))}replay(){this.bursted=!1,this.finishedEmitted=!1}mesh=null;paletteCache=[];paletteCacheKey=``;refreshPalette(){let e=this.paletteColors;if(e.length===0)return null;let t=e.join(`|`);if(t!==this.paletteCacheKey){this.paletteCacheKey=t;for(let t=0;t<e.length;t++){let n=this.paletteCache[t];n||(n=new K,this.paletteCache[t]=n),n.set(e[t])}this.paletteCache.length=e.length}return this.paletteCache}_syncObject2D(e){super._syncObject2D(e);let t=this._ensureSim();if(!this.mesh||this.mesh.count!==this.maxParticles){this.mesh&&this.mesh.removeFromParent();let e=new Is({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new bc(Cv,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(Ni),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let n=this.mesh,r=this.refreshPalette(),i=r?null:Ev.set(this.colorStart),a=Dv.set(this.colorEnd),o=this.shimmer,s=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;Tv.makeScale(t,t,1),Tv.setPosition(e.x,-e.y,0),n.setMatrixAt(s,Tv);let c=r?r[Math.floor(e.seed*r.length)]:i,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);o>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*o+e.seed))),Ov.copy(c).lerp(a,e.t).multiplyScalar(l),n.setColorAt(s,Ov),s+=1}),n.count=s,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),n.renderOrder=this.effectiveRenderOrder}},Tv=new G,Ev=new K,Dv=new K,Ov=new K;function kv(e,t){let n=[],r=0;for(let i of e){let e=[];if(typeof i==`string`)for(let n of i){let r=t[n];if(r!==void 0)e.push(r);else if(n===`.`||n===` `)e.push(-1);else if(n>=`0`&&n<=`9`)e.push(n.charCodeAt(0)-48);else throw new N(`BAD_FORMAT`,`TileMap2D: unknown tile char '${n}' — add it to "legend" (char → tile index), or use '.'/' ' for empty and digits 0-9.`)}else for(let t of i)e.push(t);r=Math.max(r,e.length),n.push(e)}for(let e of n)for(;e.length<r;)e.push(-1);return n}function Av(e,t){let n=e.length,r=n>0?e[0].length:0,i=e.map(e=>e.map(()=>!1)),a=(n,r)=>t.has(e[r][n]),o=[];for(let e=0;e<n;e++)for(let t=0;t<r;t++){if(!a(t,e)||i[e][t])continue;let s=1;for(;t+s<r&&a(t+s,e)&&!i[e][t+s];)s++;let c=1;grow:for(;e+c<n;){for(let n=0;n<s;n++)if(!a(t+n,e+c)||i[e+c][t+n])break grow;c++}for(let n=0;n<c;n++)for(let r=0;r<s;r++)i[e+n][t+r]=!0;o.push({x:t,y:e,w:s,h:c})}return o}var jv=class extends W_{static typeName=`TileMap2D`;static props={texture:{default:``},tileSize:{default:32},columns:{default:0},cells:{default:[]},legend:{default:{}},solid:{default:[]},opacity:{default:1}};texture=``;tileSize=32;columns=0;_cells=[];_legend={};_solid=[];geometryDirty=!0;collidersDirty=!0;get cells(){return this._cells}set cells(e){this._cells=e,this.geometryDirty=!0,this.collidersDirty=!0}get legend(){return this._legend}set legend(e){this._legend=e,this.geometryDirty=!0,this.collidersDirty=!0}get solid(){return this._solid}set solid(e){this._solid=e,this.collidersDirty=!0}opacity=1;tileMesh=null;builtColumns=0;builtRows=0;static validateJson(e){let t=e;kv(t._cells,t._legend)}grid(){return kv(this._cells,this._legend)}onReady(){this.rebuildColliders()}update(e){this.collidersDirty&&this.rebuildColliders()}rebuildColliders(){this.collidersDirty=!1;for(let e of[...this.children])e.name.startsWith(`__tileSolid`)&&e.free();if(this._solid.length===0)return;let e=this.tileSize;Av(this.grid(),new Set(this._solid)).forEach((t,n)=>{let r=new K_(`__tileSolid${n}`);r.position=[(t.x+t.w/2)*e,(t.y+t.h/2)*e],r.collider={shape:`rect`,size:[t.w*e,t.h*e]},this.addChild(r)})}_mesh(){return this.tileMesh||(this.tileMesh=new Js(new J,new Is({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.tileMesh)),this.tileMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._mesh(),n=t.material;if(!this.texture||!e){t.visible=!1;return}let r=e.getTexture(this.texture),i=r.image;if(!i?.width||!i.height){t.visible=!1;return}t.visible=this.opacity>0,t.renderOrder=this.effectiveRenderOrder,n.opacity=this.opacity,n.map!==r&&(r.magFilter=nr,n.map=r,n.needsUpdate=!0,this.geometryDirty=!0);let a=this.columns>0?this.columns:Math.max(1,Math.floor(i.width/this.tileSize)),o=Math.max(1,Math.floor(i.height/this.tileSize));(a!==this.builtColumns||o!==this.builtRows)&&(this.geometryDirty=!0),this.geometryDirty&&(this.geometryDirty=!1,this.builtColumns=a,this.builtRows=o,this.buildGeometry(t.geometry,a,o))}buildGeometry(e,t,n){let r=this.grid(),i=this.tileSize,a=[],o=[],s=[];for(let e=0;e<r.length;e++){let c=r[e];for(let r=0;r<c.length;r++){let l=c[r];if(l<0)continue;let u=r*i,d=u+i,f=-(e*i),p=-((e+1)*i),m=a.length/3;a.push(u,f,0,d,f,0,d,p,0,u,p,0);let h=l%t,g=Math.floor(l/t),_=h/t,v=(h+1)/t,y=1-g/n,b=1-(g+1)/n;o.push(_,y,v,y,v,b,_,b),s.push(m,m+2,m+1,m,m+3,m+2)}}e.setAttribute(`position`,new q(new Float32Array(a),3)),e.setAttribute(`uv`,new q(new Float32Array(o),2)),e.setIndex(s),e.computeBoundingSphere()}get renderedTileCount(){let e=this.tileMesh?.geometry.getAttribute(`position`);return e?e.count/4:0}free(){this.tileMesh?.geometry.dispose(),super.free()}},Mv=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],Nv=class extends At{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:Mv}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new go,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!Mv.includes(t))throw new N(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${Mv.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:Mv})}_anchorOrigin(e,t){let n=this.anchor;return{x:n.includes(`right`)?e:n===`top`||n===`center`||n===`bottom`?e/2:0,y:n.includes(`bottom`)?t:n===`left`||n===`center`||n===`right`?t/2:0}}};function Pv(){gn(),R(W_),R(pv),R(bv),R(wv),R(mv),R(gv),R(Sv),R(Nv),R(K_),R(J_),R(q_),R(Y_),R(vv),R($_),R(jv)}function Fv(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function Iv(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}var Lv=new Bo,Rv=new U,zv=12,Bv=new Float32Array(16);function Vv(e){if(!(e instanceof W_))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),Lv.setFromObject(t),Lv.getSize(Rv);let n,r,i,a;if(!Number.isFinite(Rv.x)||Rv.x===0&&Rv.y===0){let e=new U().setFromMatrixPosition(t.matrixWorld);n=e.x-zv,i=e.x+zv,r=e.y-zv,a=e.y+zv}else n=Lv.min.x-2,i=Lv.max.x+2,r=Lv.min.y-2,a=Lv.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return Bv.set(o),Bv}function Hv(){return{visited:new Set,cameras:[]}}function Uv(e,t,n,r,i,a,o){let s=a??Hv();s.visited.clear(),s.cameras.length=0,Wv(e,t,n,!1,s.visited,s.cameras,r,i,o?.ignoreStatic===!0),Gv(t,s.visited),Gv(n,s.visited);let c=null;for(let e=0;e<s.cameras.length;e++){let t=s.cameras[e];if(t.current){c=t;break}}return c||=s.cameras[0]??null,{activeCamera:c}}function Wv(e,t,n,r,i,a,o,s,c){let l=t,u=r;if(e instanceof W_&&!(e instanceof Nv)){let t=e._ensureObject2D();if(e.static&&!c&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof Nv){let t=e._ensureGroup();t.parent!==n&&n.add(t);let r=s?e._anchorOrigin(s.width,s.height):{x:0,y:0};t.position.set(r.x,-r.y,0),i.add(t),u=!0,l=t}else if(e instanceof W_){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(o),i.add(n),e instanceof gv&&!r&&a.push(e),l=n}for(let t of e.children)Wv(t,l,n,u,i,a,o,s,c);if(e instanceof W_&&!(e instanceof Nv)){let t=e._ensureObject2D();e.static&&!c?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}function Gv(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&Gv(i,t)}}var Kv=class{viewOverride=null;webgl;worldScene=new To;syncScratch=Hv();ignoreStatic=!1;uiScene=new To;worldCam=new _u(-1,1,1,-1,-1e3,1e3);uiCam=new _u(-1,1,1,-1,-1e3,1e3);engine;assets;loadedAssetScenes=new WeakSet;disconnect;canvas;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.assets=e.assets??new hm(void 0,this.engine);let t=_n(e.engine.scene?.environment,{antialias:!0,pixelRatio:1,preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,e);this.webgl=new mm({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer}),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.webgl.setPixelRatio(t.pixelRatio),this.webgl.info.autoReset=!1,this.debugLines=new Vc(new J,new kc({color:`#00ff6e`,transparent:!0,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.worldScene.add(this.debugLines),this.selectionLines=new Vc(new J,new kc({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.worldScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>this.render())}debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?Vv(t):null;if(this.selectionLines.visible=n!==null,!n)return;let r=new Float32Array(n.length/2*3);for(let e=0,t=0;e<n.length;e+=2,t+=3)r[t]=n[e],r[t+1]=n[e+1],r[t+2]=0;this.selectionLines.geometry.setAttribute(`position`,new q(r,3)),this.selectionLines.geometry.getAttribute(`position`).needsUpdate=!0}syncDebugLines(){let e=null;for(let t of Q_(`2d`,this.engine))if(e=t.debugLines(),e)break;if(this.debugLines.visible=e!==null,!e)return;let t=new Float32Array(e.length/2*3);for(let n=0,r=0;n<e.length;n+=2,r+=3)t[r]=e[n],t[r+1]=e[n+1],t[r+2]=0;this.debugLines.geometry.setAttribute(`position`,new q(t,3))}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e));let t=e.environment?.background;this.worldScene.background=typeof t==`string`?new K(t):null;let n=this.canvas.clientWidth||this.canvas.width,r=this.canvas.clientHeight||this.canvas.height,i=this.webgl.getSize(Jv);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:wn(e.viewport),o=a?Tn(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r,{activeCamera:l}=Uv(e.root,this.worldScene,this.uiScene,this.assets,{width:s,height:c},this.syncScratch),u=a?{x:a.design[0]/2,y:a.design[1]/2}:{x:n/2,y:r/2},d=1;this.viewOverride?(u={x:this.viewOverride.cx,y:this.viewOverride.cy},d=this.viewOverride.zoom):l&&(u=l.clampedCenter(s,c),d=l.effectiveZoom);let f=o?.scale??1;this.lastView={cx:u.x,cy:u.y,zoom:d*f,w:n,h:r},this.lastViewport=o,o&&(o.offsetX>.5||o.offsetY>.5)?(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r),this.webgl.clear(),this.webgl.setViewport(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissor(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissorTest(!0)):(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r)),qv(this.worldCam,u.x,u.y,s/d,c/d),qv(this.uiCam,s/2,c/2,s,c),this.webgl.info.reset(),this.webgl.autoClear=!0,this.webgl.render(this.worldScene,this.worldCam),this.webgl.autoClear=!1,this.webgl.render(this.uiScene,this.uiCam),this.webgl.autoClear=!0}lastViewport=null;lastView={cx:0,cy:0,zoom:1,w:1,h:1};view(){return{...this.lastView}}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}worldFromScreen(e,t){return Iv(this.lastView,e,t)}screenFromWorld(e,t){return Fv(this.lastView,e,t)}pick(e,t){let{w:n,h:r}=this.lastView,i=this.lastViewport?.offsetX??0,a=this.lastViewport?.offsetY??0,o=this.lastViewport?.contentW??n,s=this.lastViewport?.contentH??r;Xv.set((e-i)/o*2-1,-((t-a)/s*2-1)),Zv.setFromCamera(Xv,this.worldCam);let c=Zv.intersectObjects(this.worldScene.children,!0),l=null;for(let e of c){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(!n)continue;let r=e.object.renderOrder??0;(!l||r>=l.order)&&(l={node:n,order:r})}return l?.node??null}boundsOf(e){let t=e._object2D;if(!t||(Qv.makeEmpty(),Qv.expandByObject(t),Qv.isEmpty())||(Qv.getSize(Yv),Yv.x===0&&Yv.y===0))return null;let n=this.screenFromWorld(Qv.min.x,-Qv.max.y),r=this.screenFromWorld(Qv.max.x,-Qv.min.y);return{x:n.x,y:n.y,w:r.x-n.x,h:r.y-n.y}}dispose(){this.engine.picker&&(this.engine.picker=null),this.disconnect();for(let e of[this.worldScene,this.uiScene])e.traverse(e=>{let t=e;if(!t.isMesh)return;let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)e?.map?.dispose(),e?.dispose()});this.webgl.dispose()}};function qv(e,t,n,r,i){e.position.set(t,-n,10),e.left=-r/2,e.right=r/2,e.top=i/2,e.bottom=-i/2,e.updateProjectionMatrix()}var Jv=new V,Yv=new U,Xv=new V,Zv=new Ku,Qv=new Bo;async function $v(e){Pv(),(e.gameplay??!0)&&H_();for(let[t,n]of Object.entries(e.behaviors??{}))it(t,n,{replace:!0});let t=new Et({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),n=ey(e.scene),r=kn(ey(n),{resolveScene:e.resolveScene,engine:t});t.setScene(r);let i=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&ty(r.root))&&(i=await tv(t));let a=[],o=e.keyboard??(typeof window<`u`?window:!1);o&&t.input.attachKeyboard(o),a.push(ny(t,r.root,e.canvas)),a.push(t.settings.bindAudio(t.audio)),a.push(t.settings.bindLocale(t.locale));let s=e.touch??`auto`;if(s!==!1){let n=e.touchContainer??e.canvas.parentElement??null;if(n){let r={force:s===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=Kn(t,n,r),o=t.sceneChanged.connect(()=>{i?.dispose(),i=Kn(t,n,r)});a.push(()=>{o(),i?.dispose()})}}let c=e._rendererFactory?e._rendererFactory(t,e.canvas):new Kv({canvas:e.canvas,engine:t,...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.antialias===void 0?{}:{antialias:e.antialias}}),l=e.debug??!1,u=e.editor??l,d=u===!0?{}:u||null,f={label:`✎ edit this scene`,run:async()=>{if(!d)return;let t=d.open??Dm,r=async t=>{await $v({...e,scene:t})};await Om(async()=>{p();try{await t({scene:n,play:r,exit:()=>r(n),...d.save?{save:d.save}:{},...d.library?{library:d.library===!0?Cm():d.library}:{}})}catch(e){console.error(`[incanto] could not open the editor:`,e),await r(n)}},`opening the editor…`)}};if(l){let n=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(n){let{attachDebugOverlay:r}=await ym(async()=>{let{attachDebugOverlay:e}=await import(`./debug-CX0LDd1r.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(t,{container:n,statsSource:()=>c.stats?.()??{},...d?{actions:[f]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&a.push(()=>i.dispose())}}t.start();function p(){Am([i?[`physics`,()=>i?.dispose()]:null,[`app cleanups`,()=>{for(let e of a)e()}],[`engine`,()=>t.dispose()],[`renderer`,()=>c.dispose()]])}return{engine:t,scene:r,sourceJson:n,renderer:c,physics:i,pick(e,n){return t.picker?.(e,n)??null},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...t.stats(),...c.stats?.()}},openEditor:d?f.run:null,dispose:p}}function ey(e){try{return structuredClone(e)}catch{throw new N(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function ty(e){if(e instanceof G_)return!0;for(let t of e.children)if(ty(t))return!0;return!1}function ny(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`&&r.push({target:window,type:`keydown`}),r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Ft&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}function ry(e,t){let n=e;if(typeof n?.frame?.width!=`number`||typeof n.frame.height!=`number`||!n.animations||Object.keys(n.animations).length===0)throw new N(`BAD_FORMAT`,`Library sprite metadata needs {frame: {width, height}, animations: {<name>: {start, end, frameRate, repeat}}} — got ${JSON.stringify(e).slice(0,120)}.`);let r={},i=null,a=null;for(let[e,t]of Object.entries(n.animations)){if(typeof t.start!=`number`||typeof t.end!=`number`||typeof t.frameRate!=`number`)throw new N(`BAD_FORMAT`,`Library animation '${e}' needs numeric start/end/frameRate, got ${JSON.stringify(t)}.`);let n=t.repeat===-1;r[e]={frames:[t.start,t.end],fps:t.frameRate,loop:n},i??=e,n&&a===null&&(a=e)}let o=t.autoplay??a??i;return{asset:{type:`spritesheet`,url:t.url,frameWidth:n.frame.width,frameHeight:n.frame.height},props:{sheet:`$${t.assetKey}`,autoplay:o,animations:r}}}var iy=e({createGame2D:()=>$v,enablePhysics2D:()=>tv}),ay=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),oy=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),sy=class extends ho{constructor(e){super(),this.weight=0,this.isBinary=!1,this.overrideBlink=`none`,this.overrideLookAt=`none`,this.overrideMouth=`none`,this._binds=[],this.name=`VRMExpression_${e}`,this.expressionName=e,this.type=`VRMExpression`,this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink===`block`?+(0<this.outputWeight):this.overrideBlink===`blend`?this.outputWeight:0}get overrideLookAtAmount(){return this.overrideLookAt===`block`?+(0<this.outputWeight):this.overrideLookAt===`blend`?this.outputWeight:0}get overrideMouthAmount(){return this.overrideMouth===`block`?+(0<this.outputWeight):this.overrideMouth===`blend`?this.outputWeight:0}get outputWeight(){return this.isBinary?+(this.weight>.5):this.weight}addBind(e){this._binds.push(e)}deleteBind(e){let t=this._binds.indexOf(e);t>=0&&this._binds.splice(t,1)}applyWeight(e){let t=this.outputWeight;t*=e?.multiplier??1,this.isBinary&&t<1&&(t=0),this._binds.forEach(e=>e.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(e=>e.clearAppliedWeight())}};function cy(e,t,n){let r=e.parser.json,i=r.nodes?.[t];if(i==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${t}] of glTF but the node doesn't exist`),null;let a=i.mesh;if(a==null)return null;let o=r.meshes?.[a];if(o==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${a}] of glTF but the mesh doesn't exist`),null;let s=o.primitives.length,c=[];return n.traverse(e=>{c.length<s&&e.isMesh&&c.push(e)}),c}function ly(e,t){return oy(this,null,function*(){return cy(e,t,yield e.parser.getDependency(`node`,t))})}function uy(e){return oy(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=cy(e,r,t);i!=null&&n.set(r,i)}),n})}var dy={Aa:`aa`,Ih:`ih`,Ou:`ou`,Ee:`ee`,Oh:`oh`,Blink:`blink`,Happy:`happy`,Angry:`angry`,Sad:`sad`,Relaxed:`relaxed`,LookUp:`lookUp`,Surprised:`surprised`,LookDown:`lookDown`,LookLeft:`lookLeft`,LookRight:`lookRight`,BlinkLeft:`blinkLeft`,BlinkRight:`blinkRight`,Neutral:`neutral`};function fy(e){return Math.max(Math.min(e,1),0)}var py=class e{constructor(){this.blinkExpressionNames=[`blink`,`blinkLeft`,`blinkRight`],this.lookAtExpressionNames=[`lookLeft`,`lookRight`,`lookUp`,`lookDown`],this.mouthExpressionNames=[`aa`,`ee`,`ih`,`oh`,`ou`],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},t=new Set(Object.values(dy));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(dy));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)||(e[n]=r)}),e}copy(e){return this._expressions.concat().forEach(e=>{this.unregisterExpression(e)}),e._expressions.forEach(e=>{this.registerExpression(e)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new e().copy(this)}getExpression(e){return this._expressionMap[e]??null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){let t=this._expressions.indexOf(e);t===-1&&console.warn(`VRMExpressionManager: The specified expressions is not registered`),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){return this.getExpression(e)?.weight??null}setValue(e,t){let n=this.getExpression(e);n&&(n.weight=fy(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){let t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(e=>{e.clearAppliedWeight()}),this._expressions.forEach(t=>{let n=1,r=t.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(n*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(n*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(n*=e.mouth),t.applyWeight({multiplier:n})})}_calculateWeightMultipliers(){let e=1,t=1,n=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,t-=r.overrideLookAtAmount,n-=r.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),n=Math.max(0,n),{blink:e,lookAt:t,mouth:n}}},my={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},hy={_Color:my.Color,_EmissionColor:my.EmissionColor,_ShadeColor:my.ShadeColor,_RimColor:my.RimColor,_OutlineColor:my.OutlineColor},gy=new K,_y=class e{constructor({material:e,type:t,targetValue:n,targetAlpha:r}){this.material=e,this.type=t,this.targetValue=n,this.targetAlpha=r??1;let i=this._initColorBindState(),a=this._initAlphaBindState();this._state={color:i,alpha:a}}applyWeight(e){let{color:t,alpha:n}=this._state;if(t!=null){let{propertyName:n,deltaValue:r}=t;this.material[n]?.add(gy.copy(r).multiplyScalar(e))}if(n!=null){let{propertyName:t,deltaValue:r}=n;this.material[t]!=null&&(this.material[t]+=r*e)}}clearAppliedWeight(){let{color:e,alpha:t}=this._state;if(e!=null){let{propertyName:t,initialValue:n}=e;this.material[t]?.copy(n)}if(t!=null){let{propertyName:e,initialValue:n}=t;this.material[e]!=null&&(this.material[e]=n)}}_initColorBindState(){let{material:e,type:t,targetValue:n}=this,r=this._getPropertyNameMap()?.[t]?.[0]??null;if(r==null)return console.warn(`Tried to add a material color bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type is not supported.`),null;let i=e[r].clone();return{propertyName:r,initialValue:i,deltaValue:new K(n.r-i.r,n.g-i.g,n.b-i.b)}}_initAlphaBindState(){let{material:e,type:t,targetAlpha:n}=this,r=this._getPropertyNameMap()?.[t]?.[1]??null;if(r==null&&n!==1)return console.warn(`Tried to add a material alpha bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type does not support alpha.`),null;if(r==null)return null;let i=e[r];return{propertyName:r,initialValue:i,deltaValue:n-i}}_getPropertyNameMap(){return Object.entries(e._propertyNameMapMap).find(([e])=>this.material[e]===!0)?.[1]??null}};_y._propertyNameMapMap={isMeshStandardMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null]},isMeshBasicMaterial:{color:[`color`,`opacity`]},isMToonMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null],outlineColor:[`outlineColorFactor`,null],matcapColor:[`matcapFactor`,null],rimColor:[`parametricRimColorFactor`,null],shadeColor:[`shadeColorFactor`,null]}};var vy=_y,yy=class{constructor({primitives:e,index:t,weight:n}){this.primitives=e,this.index=t,this.weight=n}applyWeight(e){this.primitives.forEach(t=>{t.morphTargetInfluences?.[this.index]!=null&&(t.morphTargetInfluences[this.index]+=this.weight*e)})}clearAppliedWeight(){this.primitives.forEach(e=>{e.morphTargetInfluences?.[this.index]!=null&&(e.morphTargetInfluences[this.index]=0)})}},by=new V,xy=class e{constructor({material:t,scale:n,offset:r}){this.material=t,this.scale=n,this.offset=r;let i=Object.entries(e._propertyNamesMap).find(([e])=>t[e]===!0)?.[1];i==null?(console.warn(`Tried to add a texture transform bind to the material ${t.name??`(no name)`} but the material is not supported.`),this._properties=[]):(this._properties=[],i.forEach(e=>{let i=t[e]?.clone();if(!i)return null;t[e]=i;let a=i.offset.clone(),o=i.repeat.clone(),s=r.clone().sub(a),c=n.clone().sub(o);this._properties.push({name:e,initialOffset:a,deltaOffset:s,initialScale:o,deltaScale:c})}))}applyWeight(e){this._properties.forEach(t=>{let n=this.material[t.name];n!==void 0&&(n.offset.add(by.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(by.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};xy._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var Sy=xy,Cy=new Set([`1.0`,`1.0-beta`]),wy=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return oy(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return oy(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return oy(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!Cy.has(r))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.expressions;if(!i)return null;let a=new Set(Object.values(dy)),o=new Map;i.preset!=null&&Object.entries(i.preset).forEach(([e,t])=>{if(t!=null){if(!a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`);return}o.set(e,t)}}),i.custom!=null&&Object.entries(i.custom).forEach(([e,t])=>{if(a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`);return}o.set(e,t)});let s=new py;return yield Promise.all(Array.from(o.entries()).map(t=>oy(this,[t],function*([t,n]){var r,i,a;let o=new sy(t);if(e.scene.add(o),o.isBinary=n.isBinary??!1,o.overrideBlink=n.overrideBlink??`none`,o.overrideLookAt=n.overrideLookAt??`none`,o.overrideMouth=n.overrideMouth??`none`,(r=n.morphTargetBinds)==null||r.forEach(t=>oy(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield ly(e,t.node),i=t.index;if(!r.every(e=>Array.isArray(e.morphTargetInfluences)&&i<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${n.name} attempts to index morph #${i} but not found.`);return}o.addBind(new yy({primitives:r,index:i,weight:t.weight??1}))})),n.materialColorBinds||n.textureTransformBinds){let t=[];e.scene.traverse(e=>{let n=e.material;n&&(Array.isArray(n)?t.push(...n):t.push(n))}),(i=n.materialColorBinds)==null||i.forEach(e=>oy(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new vy({material:t,type:e.type,targetValue:new K().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>oy(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new Sy({material:t,offset:new V().fromArray(e.offset??[0,0]),scale:new V().fromArray(e.scale??[1,1])}))})}))}s.registerExpression(o)}))),s})}_v0Import(t){return oy(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.blendShapeMaster;if(!i)return null;let a=new py,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>oy(this,null,function*(){let i=r.presetName,o=(i!=null&&e.v0v1PresetNameMap[i]||null)??r.name;if(o==null){console.warn(`VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression`);return}if(s.has(o)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${i} has duplicated entries. Ignoring the expression`);return}s.add(o);let c=new sy(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>oy(this,null,function*(){var i;if(e.mesh===void 0||e.index===void 0)return;let a=[];(i=n.nodes)==null||i.forEach((t,n)=>{t.mesh===e.mesh&&a.push(n)});let o=e.index;yield Promise.all(a.map(n=>oy(this,null,function*(){let i=yield ly(t,n);if(!i.every(e=>Array.isArray(e.morphTargetInfluences)&&o<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${r.name} attempts to index ${o}th morph but not found.`);return}c.addBind(new yy({primitives:i,index:o,weight:.01*(e.weight??100)}))})))}));let l=r.materialValues;l&&l.length!==0&&l.forEach(e=>{if(e.materialName===void 0||e.propertyName===void 0||e.targetValue===void 0)return;let n=[];t.scene.traverse(t=>{if(t.material){let r=t.material;Array.isArray(r)?n.push(...r.filter(t=>(t.name===e.materialName||t.name===e.materialName+` (Outline)`)&&n.indexOf(t)===-1)):r.name===e.materialName&&n.indexOf(r)===-1&&n.push(r)}});let r=e.propertyName;n.forEach(t=>{if(r===`_MainTex_ST`){let n=new V(e.targetValue[0],e.targetValue[1]),r=new V(e.targetValue[2],e.targetValue[3]);r.y=1-r.y-n.y,c.addBind(new Sy({material:t,scale:n,offset:r}));return}let n=hy[r];if(n){c.addBind(new vy({material:t,type:n,targetValue:new K().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}));return}console.warn(r+` is not supported`)})}),a.registerExpression(c)}))),a})}};wy.v0v1PresetNameMap={a:`aa`,e:`ee`,i:`ih`,o:`oh`,u:`ou`,blink:`blink`,joy:`happy`,angry:`angry`,sorrow:`sad`,fun:`relaxed`,lookup:`lookUp`,lookdown:`lookDown`,lookleft:`lookLeft`,lookright:`lookRight`,blink_l:`blinkLeft`,blink_r:`blinkRight`,neutral:`neutral`};var Ty=wy,Ey=class e{constructor(t,n){this._firstPersonOnlyLayer=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=e.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=t,this.meshAnnotations=n}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMFirstPerson: humanoid must be same in order to copy`);return this.meshAnnotations=e.meshAnnotations.map(e=>({meshes:e.meshes.concat(),type:e.type})),this}clone(){return new e(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:t=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:n=e.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||=(this._firstPersonOnlyLayer=t,this._thirdPersonOnlyLayer=n,this.meshAnnotations.forEach(e=>{e.meshes.forEach(t=>{e.type===`firstPersonOnly`?(t.layers.set(this._firstPersonOnlyLayer),t.traverse(e=>e.layers.set(this._firstPersonOnlyLayer))):e.type===`thirdPersonOnly`?(t.layers.set(this._thirdPersonOnlyLayer),t.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer))):e.type===`auto`&&this._createHeadlessModel(t)})}),!0)}_excludeTriangles(e,t,n,r){let i=0;if(t!=null&&t.length>0)for(let a=0;a<e.length;a+=3){let o=e[a],s=e[a+1],c=e[a+2],l=t[o],u=n[o];if(l[0]>0&&r.includes(u[0])||l[1]>0&&r.includes(u[1])||l[2]>0&&r.includes(u[2])||l[3]>0&&r.includes(u[3]))continue;let d=t[s],f=n[s];if(d[0]>0&&r.includes(f[0])||d[1]>0&&r.includes(f[1])||d[2]>0&&r.includes(f[2])||d[3]>0&&r.includes(f[3]))continue;let p=t[c],m=n[c];p[0]>0&&r.includes(m[0])||p[1]>0&&r.includes(m[1])||p[2]>0&&r.includes(m[2])||p[3]>0&&r.includes(m[3])||(e[i++]=o,e[i++]=s,e[i++]=c)}return i}_createErasedMesh(e,t){let n=new oc(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);let r=n.geometry,i=r.getAttribute(`skinIndex`),a=i instanceof Wu?[]:i.array,o=[];for(let e=0;e<a.length;e+=4)o.push([a[e],a[e+1],a[e+2],a[e+3]]);let s=r.getAttribute(`skinWeight`),c=s instanceof Wu?[]:s.array,l=[];for(let e=0;e<c.length;e+=4)l.push([c[e],c[e+1],c[e+2],c[e+3]]);let u=r.getIndex();if(!u)throw Error(`The geometry doesn't have an index buffer`);let d=Array.from(u.array),f=this._excludeTriangles(d,l,o,t),p=[];for(let e=0;e<f;e++)p[e]=d[e];return r.setIndex(p),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new dc(e.skeleton.bones,e.skeleton.boneInverses),new G),n}_createHeadlessModelForSkinnedMesh(e,t){let n=[];if(t.skeleton.bones.forEach((e,t)=>{this._isEraseTarget(e)&&n.push(t)}),!n.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(t,n);e.add(r)}_createHeadlessModel(e){if(e.type===`Group`)if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer));else{let t=new go;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(e=>e.type===`SkinnedMesh`).forEach(e=>{let n=e;this._createHeadlessModelForSkinnedMesh(t,n)})}else if(e.type===`SkinnedMesh`){let t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode(`head`)?!0:e.parent?this._isEraseTarget(e.parent):!1}};Ey.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,Ey.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var Dy=Ey,Oy=new Set([`1.0`,`1.0-beta`]),ky=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return oy(this,null,function*(){let t=e.userData.vrmHumanoid;if(t!==null){if(t===void 0)throw Error(`VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);e.userData.vrmFirstPerson=yield this._import(e,t)}})}_import(e,t){return oy(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return oy(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=n.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!Oy.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield uy(e);return Array.from(s.entries()).forEach(([e,t])=>{let n=(a?.meshAnnotations)?.find(t=>t.node===e);o.push({meshes:t,type:n?.type??`auto`})}),new Dy(t,o)})}_v0Import(e,t){return oy(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.firstPerson;if(!i)return null;let a=[],o=yield uy(e);return Array.from(o.entries()).forEach(([e,t])=>{let r=n.nodes[e],o=i.meshAnnotations?i.meshAnnotations.find(e=>e.mesh===r.mesh):void 0;a.push({meshes:t,type:this._convertV0FlagToV1Type(o?.firstPersonFlag)})}),new Dy(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},Ay=new U,jy=new U,My=new H,Ny=class extends go{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new Yu(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(e=>{e.geometry.dispose(),e.material.dispose()})}updateMatrixWorld(e){Array.from(this._boneAxesMap.entries()).forEach(([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(Ay,My,jy);let n=Ay.set(.1,.1,.1).divide(jy);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},Py=`hips.spine.chest.upperChest.neck.head.leftEye.rightEye.jaw.leftUpperLeg.leftLowerLeg.leftFoot.leftToes.rightUpperLeg.rightLowerLeg.rightFoot.rightToes.leftShoulder.leftUpperArm.leftLowerArm.leftHand.rightShoulder.rightUpperArm.rightLowerArm.rightHand.leftThumbMetacarpal.leftThumbProximal.leftThumbDistal.leftIndexProximal.leftIndexIntermediate.leftIndexDistal.leftMiddleProximal.leftMiddleIntermediate.leftMiddleDistal.leftRingProximal.leftRingIntermediate.leftRingDistal.leftLittleProximal.leftLittleIntermediate.leftLittleDistal.rightThumbMetacarpal.rightThumbProximal.rightThumbDistal.rightIndexProximal.rightIndexIntermediate.rightIndexDistal.rightMiddleProximal.rightMiddleIntermediate.rightMiddleDistal.rightRingProximal.rightRingIntermediate.rightRingDistal.rightLittleProximal.rightLittleIntermediate.rightLittleDistal`.split(`.`),Fy={hips:null,spine:`hips`,chest:`spine`,upperChest:`chest`,neck:`upperChest`,head:`neck`,leftEye:`head`,rightEye:`head`,jaw:`head`,leftUpperLeg:`hips`,leftLowerLeg:`leftUpperLeg`,leftFoot:`leftLowerLeg`,leftToes:`leftFoot`,rightUpperLeg:`hips`,rightLowerLeg:`rightUpperLeg`,rightFoot:`rightLowerLeg`,rightToes:`rightFoot`,leftShoulder:`upperChest`,leftUpperArm:`leftShoulder`,leftLowerArm:`leftUpperArm`,leftHand:`leftLowerArm`,rightShoulder:`upperChest`,rightUpperArm:`rightShoulder`,rightLowerArm:`rightUpperArm`,rightHand:`rightLowerArm`,leftThumbMetacarpal:`leftHand`,leftThumbProximal:`leftThumbMetacarpal`,leftThumbDistal:`leftThumbProximal`,leftIndexProximal:`leftHand`,leftIndexIntermediate:`leftIndexProximal`,leftIndexDistal:`leftIndexIntermediate`,leftMiddleProximal:`leftHand`,leftMiddleIntermediate:`leftMiddleProximal`,leftMiddleDistal:`leftMiddleIntermediate`,leftRingProximal:`leftHand`,leftRingIntermediate:`leftRingProximal`,leftRingDistal:`leftRingIntermediate`,leftLittleProximal:`leftHand`,leftLittleIntermediate:`leftLittleProximal`,leftLittleDistal:`leftLittleIntermediate`,rightThumbMetacarpal:`rightHand`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbDistal:`rightThumbProximal`,rightIndexProximal:`rightHand`,rightIndexIntermediate:`rightIndexProximal`,rightIndexDistal:`rightIndexIntermediate`,rightMiddleProximal:`rightHand`,rightMiddleIntermediate:`rightMiddleProximal`,rightMiddleDistal:`rightMiddleIntermediate`,rightRingProximal:`rightHand`,rightRingIntermediate:`rightRingProximal`,rightRingDistal:`rightRingIntermediate`,rightLittleProximal:`rightHand`,rightLittleIntermediate:`rightLittleProximal`,rightLittleDistal:`rightLittleIntermediate`};function Iy(e){return e.invert?e.invert():e.inverse(),e}var Ly=new U,Ry=new H,zy=class{constructor(e){this.humanBones=e,this.restPose=this.getAbsolutePose()}getAbsolutePose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);r&&(Ly.copy(r.position),Ry.copy(r.quaternion),e[n]={position:Ly.toArray(),rotation:Ry.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;Ly.set(0,0,0),Ry.identity();let i=this.restPose[n];i?.position&&Ly.fromArray(i.position).negate(),i?.rotation&&Iy(Ry.fromArray(i.rotation)),Ly.add(r.position),Ry.premultiply(r.quaternion),e[n]={position:Ly.toArray(),rotation:Ry.toArray()}}),e}setPose(e){Object.entries(e).forEach(([e,t])=>{let n=e,r=this.getBoneNode(n);if(!r)return;let i=this.restPose[n];i&&(t?.position&&(r.position.fromArray(t.position),i.position&&r.position.add(Ly.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(Ry.fromArray(i.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([e,t])=>{let n=this.getBoneNode(e);n&&(t?.position&&n.position.fromArray(t.position),t?.rotation&&n.quaternion.fromArray(t.rotation))})}getBone(e){return this.humanBones[e]??void 0}getBoneNode(e){return this.humanBones[e]?.node??null}},By=new U,Vy=new H,Hy=new U,Uy=class e extends zy{static _setupTransforms(e){let t=new ho;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};Py.forEach(t=>{var o;let s=e.getBoneNode(t);if(s){let e=new U,c=new H;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(e,c,By),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new H;(o=s.parent)==null||o.matrixWorld.decompose(By,l,By),a[t]=l}});let o={};return Py.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=Fy[a],a!=null);)s=n[a];let c=new ho;c.name=`Normalized_`+i.name,(a?o[a]?.node:t).add(c),c.position.copy(e),s&&c.position.sub(s),o[r]={node:c}}}),{rigBones:o,root:t,parentWorldRotations:a,boneRotations:i}}constructor(t){let{rigBones:n,root:r,parentWorldRotations:i,boneRotations:a}=e._setupTransforms(t);super(n),this.original=t,this.root=r,this._parentWorldRotations=i,this._boneRotations=a}update(){Py.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=Vy.copy(r).invert(),a=this._boneRotations[e];if(t.quaternion.copy(n.quaternion).multiply(r).premultiply(i).multiply(a),e===`hips`){let e=n.getWorldPosition(Hy);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},Wy=class e{get restPose(){return console.warn(`VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead.`),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,t){this.autoUpdateHumanBones=t?.autoUpdateHumanBones??!0,this._rawHumanBones=new zy(e),this._normalizedHumanBones=new Uy(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new zy(e.humanBones),this._normalizedHumanBones=new Uy(this._rawHumanBones),this}clone(){return new e(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn(`VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead.`),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn(`VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead.`),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn(`VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead.`),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn(`VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead.`),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn(`VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead.`),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn(`VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead.`),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},Gy={Hips:`hips`,Spine:`spine`,Head:`head`,LeftUpperLeg:`leftUpperLeg`,LeftLowerLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,RightUpperLeg:`rightUpperLeg`,RightLowerLeg:`rightLowerLeg`,RightFoot:`rightFoot`,LeftUpperArm:`leftUpperArm`,LeftLowerArm:`leftLowerArm`,LeftHand:`leftHand`,RightUpperArm:`rightUpperArm`,RightLowerArm:`rightLowerArm`,RightHand:`rightHand`},Ky=new Set([`1.0`,`1.0-beta`]),qy={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},Jy=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return oy(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return oy(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return oy(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!Ky.has(r))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.humanoid;if(!i)return null;let a=i.humanBones.leftThumbIntermediate!=null||i.humanBones.rightThumbIntermediate!=null,o={};i.humanBones!=null&&(yield Promise.all(Object.entries(i.humanBones).map(e=>oy(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=qy[n];e!=null&&(n=e)}let i=yield this.parser.getDependency(`node`,r);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${n} (index = ${r}) does not exist`);return}o[n]={node:i}}))));let s=new Wy(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new Ny(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return oy(this,null,function*(){let t=this.parser.json.extensions?.VRM;if(!t)return null;let n=t.humanoid;if(!n)return null;let r={};n.humanBones!=null&&(yield Promise.all(n.humanBones.map(e=>oy(this,null,function*(){let t=e.bone,n=e.node;if(t==null||n==null)return;let i=yield this.parser.getDependency(`node`,n);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${t} (index = ${n}) does not exist`);return}let a=qy[t]??t;if(r[a]!=null){console.warn(`Multiple bone entries for ${a} detected (index = ${n}), ignoring duplicated entries.`);return}r[a]={node:i}}))));let i=new Wy(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new Ny(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(Gy).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},Yy=class extends J{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new q(new Float32Array(195),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new q(new Uint16Array(189),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,e=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let e=0;e<64;e++){let t=e/63*this._currentTheta;this._attrPos.setXYZ(e+1,this._currentRadius*Math.sin(t),0,this._currentRadius*Math.cos(t))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<63;e++)this._attrIndex.setXYZ(e*3,0,e+1,e+2);this._attrIndex.needsUpdate=!0}},Xy=class extends J{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new U,this._currentTail=new U,this._attrPos=new q(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new q(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},Zy=new H,Qy=new H,$y=new U,eb=new U,tb=Math.sqrt(2)/2,nb=new H(0,0,-tb,tb),rb=new U(0,1,0),ib=class extends go{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new Yy;e.radius=.5;let t=new Is({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new Js(e,t),this.add(this._meshPitch)}{let e=new Yy;e.radius=.5;let t=new Is({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new Js(e,t),this.add(this._meshYaw)}{let e=new Xy;e.radius=.1;let t=new kc({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new Vc(e,t),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(e){let t=ya.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=ya.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition($y),this.vrmLookAt.getLookAtWorldQuaternion(Zy),Zy.multiply(this.vrmLookAt.getFaceFrontQuaternion(Qy)),this._meshYaw.position.copy($y),this._meshYaw.quaternion.copy(Zy),this._meshPitch.position.copy($y),this._meshPitch.quaternion.copy(Zy),this._meshPitch.quaternion.multiply(Qy.setFromAxisAngle(rb,t)),this._meshPitch.quaternion.multiply(nb);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(eb).sub($y),this._lineTarget.geometry.tail.copy(eb),this._lineTarget.geometry.update(),this._lineTarget.position.copy($y)),super.updateMatrixWorld(e)}},ab=new U,ob=new U;function sb(e,t){return e.matrixWorld.decompose(ab,t,ob),t}function cb(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function lb(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var ub=new U(0,0,1),db=new U,fb=new U,pb=new U,mb=new H,hb=new H,gb=new H,_b=new H,vb=new Za,yb=class e{constructor(e,t){this.offsetFromHeadBone=new U,this.autoUpdate=!0,this.faceFront=new U(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new H)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn(`VRMLookAt: euler is deprecated. use getEuler() instead.`),this.getEuler(new Za)}getEuler(e){return e.set(ya.DEG2RAD*this._pitch,ya.DEG2RAD*this._yaw,0,`YXZ`)}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMLookAt: humanoid must be same in order to copy`);return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new e(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let t=this.humanoid.getRawBoneNode(`head`);return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){return sb(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(ub)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=cb(this.faceFront);return vb.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(vb).premultiply(_b.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(hb),this.getFaceFrontQuaternion(gb),e.copy(ub).applyQuaternion(hb).applyQuaternion(gb).applyEuler(this.getEuler(vb))}lookAt(e){let t=mb.copy(this._restHeadWorldQuaternion).multiply(Iy(this.getLookAtWorldQuaternion(hb))),n=this.getLookAtWorldPosition(fb),r=pb.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=cb(this.faceFront),[o,s]=cb(r),c=lb(o-i),l=lb(a-s);this._yaw=ya.RAD2DEG*c,this._pitch=ya.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(db)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};yb.EULER_ORDER=`YXZ`;var bb=yb,xb=new U(0,0,1),Sb=new H,Cb=new H,wb=new Za(0,0,0,`YXZ`),Tb=class{constructor(e,t,n,r,i){this.humanoid=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i,this.faceFront=new U(0,0,1),this._restQuatLeftEye=new H,this._restQuatRightEye=new H,this._restLeftEyeParentWorldQuat=new H,this._restRightEyeParentWorldQuat=new H;let a=this.humanoid.getRawBoneNode(`leftEye`),o=this.humanoid.getRawBoneNode(`rightEye`);a&&(this._restQuatLeftEye.copy(a.quaternion),sb(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),sb(o.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(e,t){let n=this.humanoid.getRawBoneNode(`leftEye`),r=this.humanoid.getRawBoneNode(`rightEye`),i=this.humanoid.getNormalizedBoneNode(`leftEye`),a=this.humanoid.getNormalizedBoneNode(`rightEye`);n&&(t<0?wb.x=-ya.DEG2RAD*this.rangeMapVerticalDown.map(-t):wb.x=ya.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?wb.y=-ya.DEG2RAD*this.rangeMapHorizontalInner.map(-e):wb.y=ya.DEG2RAD*this.rangeMapHorizontalOuter.map(e),Sb.setFromEuler(wb),this._getWorldFaceFrontQuat(Cb),i.quaternion.copy(Cb).multiply(Sb).multiply(Cb.invert()),Sb.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(Sb).premultiply(Sb.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?wb.x=-ya.DEG2RAD*this.rangeMapVerticalDown.map(-t):wb.x=ya.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?wb.y=-ya.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):wb.y=ya.DEG2RAD*this.rangeMapHorizontalInner.map(e),Sb.setFromEuler(wb),this._getWorldFaceFrontQuat(Cb),a.quaternion.copy(Cb).multiply(Sb).multiply(Cb.invert()),Sb.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(Sb).premultiply(Sb.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=ya.RAD2DEG*e.y,n=ya.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(xb)<.01)return e.identity();let[t,n]=cb(this.faceFront);return wb.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(wb)}};Tb.type=`bone`;var Eb=class{constructor(e,t,n,r,i){this.expressions=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i}applyYawPitch(e,t){t<0?(this.expressions.setValue(`lookDown`,0),this.expressions.setValue(`lookUp`,this.rangeMapVerticalUp.map(-t))):(this.expressions.setValue(`lookUp`,0),this.expressions.setValue(`lookDown`,this.rangeMapVerticalDown.map(t))),e<0?(this.expressions.setValue(`lookLeft`,0),this.expressions.setValue(`lookRight`,this.rangeMapHorizontalOuter.map(-e))):(this.expressions.setValue(`lookRight`,0),this.expressions.setValue(`lookLeft`,this.rangeMapHorizontalOuter.map(e)))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=ya.RAD2DEG*e.y,n=ya.RAD2DEG*e.x;this.applyYawPitch(t,n)}};Eb.type=`expression`;var Db=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*fy(e/this.inputMaxValue)}},Ob=new Set([`1.0`,`1.0-beta`]),kb=.01,Ab=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return oy(this,null,function*(){let t=e.userData.vrmHumanoid;if(t===null)return;if(t===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);let n=e.userData.vrmExpressionManager;if(n!==null){if(n===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first`);e.userData.vrmLookAt=yield this._import(e,t,n)}})}_import(e,t,n){return oy(this,null,function*(){return t==null||n==null?null:(yield this._v1Import(e,t,n))||(yield this._v0Import(e,t,n))||null})}_v1Import(e,t,n){return oy(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=e.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!Ob.has(i))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.lookAt;if(!a)return null;let o=a.type===`expression`?1:10,s=this._v1ImportRangeMap(a.rangeMapHorizontalInner,o),c=this._v1ImportRangeMap(a.rangeMapHorizontalOuter,o),l=this._v1ImportRangeMap(a.rangeMapVerticalDown,o),u=this._v1ImportRangeMap(a.rangeMapVerticalUp,o),d;d=a.type===`expression`?new Eb(n,s,c,l,u):new Tb(t,s,c,l,u);let f=this._importLookAt(t,d);return f.offsetFromHeadBone.fromArray(a.offsetFromHeadBone??[0,.06,0]),f})}_v1ImportRangeMap(e,t){let n=e?.inputMaxValue??90,r=e?.outputScale??t;return n<kb&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=kb),new Db(n,r)}_v0Import(e,t,n){return oy(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let r=e.firstPerson;if(!r)return null;let i=r.lookAtTypeName===`BlendShape`?1:10,a=this._v0ImportDegreeMap(r.lookAtHorizontalInner,i),o=this._v0ImportDegreeMap(r.lookAtHorizontalOuter,i),s=this._v0ImportDegreeMap(r.lookAtVerticalDown,i),c=this._v0ImportDegreeMap(r.lookAtVerticalUp,i),l;l=r.lookAtTypeName===`BlendShape`?new Eb(n,a,o,s,c):new Tb(t,a,o,s,c);let u=this._importLookAt(t,l);return r.firstPersonBoneOffset?u.offsetFromHeadBone.set(r.firstPersonBoneOffset.x??0,r.firstPersonBoneOffset.y??.06,-(r.firstPersonBoneOffset.z??0)):u.offsetFromHeadBone.set(0,.06,0),u.faceFront.set(0,0,-1),l instanceof Tb&&l.faceFront.set(0,0,-1),u})}_v0ImportDegreeMap(e,t){let n=e?.curve;JSON.stringify(n)!==`[0,0,0,1,1,1,1,0]`&&console.warn(`Curves of LookAtDegreeMap defined in VRM 0.0 are not supported`);let r=e?.xRange??90,i=e?.yRange??t;return r<kb&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=kb),new Db(r,i)}_importLookAt(e,t){let n=new bb(e,t);if(this.helperRoot){let e=new ib(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function jb(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}var Mb=new Set([`1.0`,`1.0-beta`]),Nb=class{get name(){return`VRMMetaLoaderPlugin`}constructor(e,t){this.parser=e,this.needThumbnailImage=t?.needThumbnailImage??!1,this.acceptLicenseUrls=t?.acceptLicenseUrls??[`https://vrm.dev/licenses/1.0/`],this.acceptV0Meta=t?.acceptV0Meta??!0}afterRoot(e){return oy(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return oy(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return oy(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let t=e.extensions?.VRMC_vrm;if(t==null)return null;let n=t.specVersion;if(!Mb.has(n))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${n}"`),null;let r=t.meta;if(!r)return null;let i=r.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(i))throw Error(`VRMMetaLoaderPlugin: The license url "${i}" is not accepted`);let a;return this.needThumbnailImage&&r.thumbnailImage!=null&&(a=(yield this._extractGLTFImage(r.thumbnailImage))??void 0),{metaVersion:`1`,name:r.name,version:r.version,authors:r.authors,copyrightInformation:r.copyrightInformation,contactInformation:r.contactInformation,references:r.references,thirdPartyLicenses:r.thirdPartyLicenses,thumbnailImage:a,licenseUrl:r.licenseUrl,avatarPermission:r.avatarPermission,allowExcessivelyViolentUsage:r.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:r.allowExcessivelySexualUsage,commercialUsage:r.commercialUsage,allowPoliticalOrReligiousUsage:r.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:r.allowAntisocialOrHateUsage,creditNotation:r.creditNotation,allowRedistribution:r.allowRedistribution,modification:r.modification,otherLicenseUrl:r.otherLicenseUrl}})}_v0Import(e){return oy(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let t=e.meta;if(!t)return null;if(!this.acceptV0Meta)throw Error(`VRMMetaLoaderPlugin: Attempted to load VRM0.0 meta but acceptV0Meta is false`);let n;return this.needThumbnailImage&&t.texture!=null&&t.texture!==-1&&(n=yield this.parser.getDependency(`texture`,t.texture)),{metaVersion:`0`,allowedUserName:t.allowedUserName,author:t.author,commercialUssageName:t.commercialUssageName,contactInformation:t.contactInformation,licenseName:t.licenseName,otherLicenseUrl:t.otherLicenseUrl,otherPermissionUrl:t.otherPermissionUrl,reference:t.reference,sexualUssageName:t.sexualUssageName,texture:n??void 0,title:t.title,version:t.version,violentUssageName:t.violentUssageName}})}_extractGLTFImage(e){return oy(this,null,function*(){let t=this.parser.json.images?.[e];if(t==null)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image doesn't exist`),null;let n=t.uri;if(t.bufferView!=null){let e=yield this.parser.getDependency(`bufferView`,t.bufferView),r=new Blob([e],{type:t.mimeType});n=URL.createObjectURL(r)}return n==null?(console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image couldn't load properly`),null):yield new Zl().loadAsync(jb(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},Pb=class{constructor(e){this.scene=e.scene,this.meta=e.meta,this.humanoid=e.humanoid,this.expressionManager=e.expressionManager,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt}update(e){this.humanoid.update(),this.lookAt&&this.lookAt.update(e),this.expressionManager&&this.expressionManager.update()}},Fb=class extends Pb{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach(t=>{t.update&&t.update(e)})}},Ib=Object.defineProperty,Lb=Object.getOwnPropertySymbols,Rb=Object.prototype.hasOwnProperty,zb=Object.prototype.propertyIsEnumerable,Bb=(e,t,n)=>t in e?Ib(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Vb=(e,t)=>{for(var n in t||={})Rb.call(t,n)&&Bb(e,n,t[n]);if(Lb)for(var n of Lb(t))zb.call(t,n)&&Bb(e,n,t[n]);return e},Hb=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});function Ub(e,t){e.colorSpace=t}var Wb=class{get pending(){return Promise.all(this._pendings)}constructor(e,t){this._parser=e,this._materialParams=t,this._pendings=[]}assignPrimitive(e,t){t!=null&&(this._materialParams[e]=t)}assignColor(e,t,n){if(t!=null){let r=new K().fromArray(t);n&&r.convertSRGBToLinear(),this._materialParams[e]=r}}assignTexture(e,t,n){return Hb(this,null,function*(){let r=Hb(this,null,function*(){if(t!=null){let r=yield this._parser.assignTexture(this._materialParams,e,t);if(r==null){console.warn(`GLTFMToonMaterialParamsAssignHelper: Failed to load texture. The rendering result may be wrong`);return}n&&Ub(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return Hb(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},Gb=`// #define PHONG
5756
+ `,colorWrite:!1,depthWrite:!0,depthTest:!1,side:2}),Jg=9.81,Yg=6,Xg=.15,Zg=class extends et{static props={water:{default:``,nodePath:!0},draft:{default:.35},stiffness:{default:3},damping:{default:3.5},drift:{default:.6},drag:{default:.9},samples:{default:4},size:{default:[1,1]}};static signals=[`submerged`,`surfaced`];water=``;draft=.35;stiffness=3;damping=3.5;drift=.6;drag=.9;samples=4;size=[1,1];surface=null;wet=!1;update(e){if(e<=0)return;let t=this.resolveWater();if(!t)return;let n=this.node;if(!n.applyImpulse)return;let[r,i,a]=[n.position[0]??0,n.position[1]??0,n.position[2]??0],o=[(this.size[0]??1)/2,(this.size[1]??1)/2],s=this.samplePoints(r,a,o[0],o[1]),c=n.mass??1,l=n.linearVelocity??[0,0,0],u=0,d=0,f=0,p=0;for(let[e,n]of s){let r=t.heightAt(e,n)-(i-this.draft);if(r<=0)continue;p++,u+=Jg*(1+this.stiffness*(r/Math.max(this.draft,Xg)));let a=.6;d+=t.heightAt(e+a,n)-t.heightAt(e-a,n),f+=t.heightAt(e,n+a)-t.heightAt(e,n-a)}let m=p>0;if(m!==this.wet&&(this.wet=m,this.emit(m?`submerged`:`surfaced`,this.node)),!m)return;let h=p/s.length,g=Math.min(u/s.length-this.damping*(l[1]??0),Yg*Jg)*e*c,_=(-d*this.drift*12-(l[0]??0)*this.drag)*h*e*c,v=(-f*this.drift*12-(l[2]??0)*this.drag)*h*e*c;n.applyImpulse([_,g,v])}samplePoints(e,t,n,r){let i=Math.max(1,Math.round(this.samples));if(i===1)return[[e,t]];let a=[];for(let o=0;o<i;o++){let s=o/i*Math.PI*2+Math.PI/4;a.push([e+Math.cos(s)*n,t+Math.sin(s)*r])}return a}resolveWater(){if(this.surface)return this.surface;if(this.water!==``){let e=this.node.getNodeOrNull(this.water);if(!(e instanceof mg))throw new N(`NODE_NOT_FOUND`,`Buoyancy on '${this.node.getPath()}': water '${this.water}' is not a Water3D in the tree.`,{prop:`water`});return this.surface=e,e}return this.surface=Qg(this.node.getRoot()),this.surface}};function Qg(e){if(e instanceof mg)return e;for(let t of e.children){let e=Qg(t);if(e)return e}return null}function $g(e){return Array.isArray(e.position)}function e_(e){let t=e.node;if(!$g(t)){let n=e.constructor.name;throw new N(`PROP_TYPE_MISMATCH`,`${n} on '${t.getPath()}' needs a spatial node with a numeric 'position' array (a Node2D/Node3D subtype). '${t.name}' has none.`,{path:t.getPath()})}return t}function t_(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}function n_(e,t){let n=Math.max(e.length,t.length),r=Array(n);for(let i=0;i<n;i++)r[i]=(e[i]??0)+(t[i]??0);return r}function r_(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t)}function i_(e){let t=r_(e);return t===0?e.map(()=>0):e.map(e=>e/t)}function a_(e,t,n){let r=Math.max(e.length,t.length),i=0;for(let n=0;n<r;n++){let r=(t[n]??0)-(e[n]??0);i+=r*r}let a=Math.sqrt(i),o=Array(r);if(a<=n||a===0){for(let e=0;e<r;e++)o[e]=t[e]??0;return{position:o,reached:!0}}let s=n/a;for(let n=0;n<r;n++){let r=e[n]??0;o[n]=r+((t[n]??0)-r)*s}return{position:o,reached:!1}}function o_(e,t){let n=Math.min(Math.max(e,0),.99);return n<=0?1:1-n**(t*60)}var s_=class extends et{static props={target:{default:``,nodePath:!0},speed:{default:60},stopRange:{default:0},loseRange:{default:0},moveParent:{default:!1}};static signals=[`reachedTarget`,`lostTarget`];target=``;speed=60;stopRange=0;loseRange=0;moveParent=!1;inRange=!1;lost=!1;onReady(){if(this.target===``)throw new N(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.moveParent){let e=this.node.parent;if(!e||!$g(e))throw new N(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else e_(this)}update(e){let t=this.moveParent?this.node.parent:this.node;if(!t||!$g(t))return;let n=this.node.getNodeOrNull(this.target);if(!n||!$g(n))return;let r=t_(t.position,n.position);if(this.loseRange>0&&r>this.loseRange){this.lost||(this.lost=!0,this.inRange=!1,this.emit(`lostTarget`));return}if(this.lost=!1,this.stopRange>0&&r<=this.stopRange){this.inRange||(this.inRange=!0,this.emit(`reachedTarget`));return}this.inRange=!1;let i=Math.min(this.speed*e,this.stopRange>0?r-this.stopRange:r),{position:a}=a_(t.position,n.position,Math.max(0,i));t.position=a}},c_=class extends et{static props={button:{default:0},maxDistance:{default:0},enabled:{default:!0}};static signals=[`clicked`,`hovered`,`unhovered`];button=0;maxDistance=0;enabled=!0;hovering=!1;pressedHere=!1;update(){let e=this.node.tree?.engine;if(!e||!this.enabled)return;let t=e.picker,n=e.input.pointerPosition();if(!t||!n){this.hovering&&this.setHover(!1);return}let r=t(n.x,n.y),i=r!==null&&this.isSelfOrDescendant(r)&&this.withinRange(r);i!==this.hovering&&this.setHover(i),e.input.mouseJustPressed(this.button)&&(this.pressedHere=i),e.input.mouseJustReleased(this.button)&&(this.pressedHere&&i&&this.emit(`clicked`,this.node),this.pressedHere=!1)}setHover(e){this.hovering=e,this.emit(e?`hovered`:`unhovered`,this.node)}isSelfOrDescendant(e){for(let t=e;t;t=t.parent)if(t===this.node)return!0;return!1}withinRange(e){if(this.maxDistance<=0||!this.node.tree?.engine?.scene?.root)return!0;let t=this.node.position,n=e.position;if(!Array.isArray(t)||!Array.isArray(n))return!0;let r=0;for(let e=0;e<Math.max(t.length,n.length);e++){let i=(t[e]??0)-(n[e]??0);r+=i*i}return Math.sqrt(r)<=this.maxDistance}},l_=class extends et{static props={group:{default:`player`}};static signals=[`totalChanged`];group=`player`;total=0;onReady(){this.node.addToGroup(this.group)}collect(e){this.total+=e,this.emit(`totalChanged`,this.total)}serialize(){return{total:this.total}}deserialize(e){let t=e;typeof t.total==`number`&&(this.total=t.total)}},u_=class extends et{static props={max:{default:100},regenPerSec:{default:0},invulnerableFor:{default:0},freeOnDeath:{default:!1}};static signals=[`damaged`,`healed`,`died`];max=100;regenPerSec=0;invulnerableFor=0;freeOnDeath=!1;current=0;invulnTimer=0;dead=!1;get isDead(){return this.dead}get invulnerableRemaining(){return this.invulnTimer}onReady(){if(!(this.max>0))throw new N(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "max" must be > 0, got ${this.max}.`,{prop:`max`});if(this.regenPerSec<0)throw new N(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "regenPerSec" must be >= 0, got ${this.regenPerSec}.`,{prop:`regenPerSec`});if(this.invulnerableFor<0)throw new N(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "invulnerableFor" must be >= 0, got ${this.invulnerableFor}.`,{prop:`invulnerableFor`});this.current=this.max}update(e){this.invulnTimer>0&&(this.invulnTimer=Math.max(0,this.invulnTimer-e)),this.regenPerSec>0&&!this.dead&&this.current<this.max&&this.setCurrent(this.current+this.regenPerSec*e)}damage(e){this.dead||e<=0||this.invulnTimer>0||(this.setCurrent(this.current-e),this.emit(`damaged`,e,this.current),this.invulnerableFor>0&&(this.invulnTimer=this.invulnerableFor),this.current<=0&&this.die())}heal(e){this.dead||e<=0||(this.setCurrent(this.current+e),this.emit(`healed`,e,this.current))}kill(){this.dead||(this.setCurrent(0),this.die())}setCurrent(e){this.current=Math.max(0,Math.min(this.max,e))}die(){this.dead||(this.dead=!0,this.current=0,this.emit(`died`),this.freeOnDeath&&this.node.queueFree())}serialize(){return{current:this.current,dead:this.dead}}deserialize(e){let t=e;typeof t.current==`number`&&(this.current=Math.min(this.max,Math.max(0,t.current))),typeof t.dead==`boolean`&&(this.dead=t.dead)}};function d_(e,t){let n=e.node;if(!n.declaredSignalNames().includes(`triggerEnter`)){let t=e.constructor.name;throw new N(`UNKNOWN_SIGNAL`,`${t} on '${n.getPath()}' needs a node that emits 'triggerEnter' — attach it to an Area2D/Area3D (or another body that declares the collision signals). '${n.name}' declares: [${n.declaredSignalNames().join(`, `)}].`,{signal:`triggerEnter`,path:n.getPath()})}n.on(`triggerEnter`,e=>t(e))}var f_=class extends et{static props={amount:{default:10},targetGroup:{default:``},oncePerTarget:{default:!0},repeatEvery:{default:0},destroySelf:{default:!1}};static signals=[`dealtDamage`];amount=10;targetGroup=``;oncePerTarget=!0;repeatEvery=0;destroySelf=!1;hit=new WeakSet;inside=new Map;onReady(){d_(this,e=>{this.inside.set(e,this.repeatEvery),this.tryDamage(e)}),this.node.on(`triggerExit`,e=>{this.inside.delete(e)})}update(e){if(!(this.repeatEvery<=0||this.inside.size===0))for(let[t,n]of this.inside){if(!t.tree){this.inside.delete(t);continue}let r=n-e;r>0?this.inside.set(t,r):(this.inside.set(t,this.repeatEvery),this.tryDamage(t,{repeat:!0}))}}tryDamage(e,t){if(!t?.repeat&&this.oncePerTarget&&this.hit.has(e))return;let n=p_(e);n&&(this.targetGroup!==``&&!n.owner.isInGroup(this.targetGroup)||(this.oncePerTarget&&this.hit.add(e),n.health.damage(this.amount),this.emit(`dealtDamage`,this.amount,n.owner),this.destroySelf&&this.node.queueFree()))}};function p_(e){let t=[e];for(;t.length>0;){let e=t.shift();if(e.behavior instanceof u_)return{health:e.behavior,owner:e};t.push(...e.children)}for(let t=e.parent;t;t=t.parent)if(t.behavior instanceof u_)return{health:t.behavior,owner:t};return null}var m_=class extends et{static signals=[`dayPhaseChanged`];static props={daySeconds:{default:240},startHour:{default:10},maxSunElevationDeg:{default:55},nightDarkness:{default:.75},paused:{default:!1}};daySeconds=240;startHour=10;maxSunElevationDeg=55;nightDarkness=.75;paused=!1;hour=0;phase=``;applyClock=0;baseAmbient=.3;baseExposure=1;captured=!1;onReady(){this.hour=this.startHour}update(e){if(this.paused||(this.hour=(this.hour+e/this.daySeconds*24)%24),this.applyClock-=e,this.applyClock>0)return;this.applyClock=.2,this.applyHour();let t=h_(this.hour);t!==this.phase&&(this.phase=t,this.emit(`dayPhaseChanged`,t))}applyHour(){let e=this.node.tree?.engine,t=e?.scene?.environment;if(!e||!t?.sky)return;this.captured||(this.captured=!0,this.baseAmbient=t.ambient?.intensity??.3,this.baseExposure=t.exposure??1);let n=(this.hour-6)/12*Math.PI,r=Math.sin(n);t.sky.elevationDeg=r*this.maxSunElevationDeg+(r<0?r*10:0),t.sky.azimuthDeg=this.hour/24*360+90;let i=Math.max(0,r),a=this.nightDarkness;t.ambient={...t.ambient??{},intensity:this.baseAmbient*(1-a+a*i)},t.exposure=this.baseExposure*(1-a*.55*(1-i))}};function h_(e){return e<5||e>=20?`night`:e<7.5?`dawn`:e<17.5?`day`:`dusk`}var g_=class extends et{static props={target:{default:``,nodePath:!0},offset:{default:[]},smoothing:{default:0},deadzone:{default:0}};static signals=[];target=``;offset=[];smoothing=0;deadzone=0;onReady(){if(this.target===``)throw new N(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.deadzone<0)throw new N(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "deadzone" must be >= 0, got ${this.deadzone}.`,{prop:`deadzone`});e_(this)}shakeMag=0;shakeT=0;shakeFalloff=.28;shake(e,t=.28){this.shakeMag=Math.max(this.shakeMag,e),this.shakeT=t,this.shakeFalloff=t}update(e){let t=this.node;if(!$g(t))return;let n=t.getNodeOrNull(this.target);if(!n||!$g(n))return;let r=n_(n.position,this.offset);if(!(this.deadzone>0&&t_(t.position,r)<=this.deadzone)){let n=o_(this.smoothing,e);n>=1?t.position=[...r]:t.position=t.position.map((e,t)=>e+((r[t]??e)-e)*n)}if(this.shakeT>0){this.shakeT-=e;let n=this.shakeMag*Math.max(0,this.shakeT)/this.shakeFalloff;this.shakeT<=0&&(this.shakeMag=0);let r=t.position.slice();for(let e=0;e<r.length;e++){let t=r.length>=3&&e===1?.5:1;r[e]=(r[e]??0)+(this.engine.rng.next()*2-1)*n*t}t.position=r}}};function __(e){let t=e.scene?.source;t&&(e.timeScale=1,e.setScene(kn(He(t))))}function v_(e,t,n){let r=n?.fadeSeconds??.4,i=()=>{e.timeScale=1,e.setScene(kn(He(t)))};if(typeof document>`u`||r<=0){i();return}let a=`incanto-scene-fade`,o=document.getElementById(a);o||(o=document.createElement(`div`),o.id=a,o.style.cssText=`position:fixed;inset:0;z-index:10001;background:#000;opacity:0;pointer-events:none;`,document.body.appendChild(o)),o.style.transition=`opacity ${r/2}s`,o.style.opacity=`1`,setTimeout(()=>{i();let e=document.getElementById(a);e&&(e.style.opacity=`0`,setTimeout(()=>e.remove(),r*500+60))},r*500+30)}var y_=class extends et{static signals=[`flowChanged`];static props={restartAction:{default:`restart`},freezeOnEnd:{default:!0},bannerPath:{default:`%Banner`,nodePath:!0}};restartAction=`restart`;freezeOnEnd=!0;bannerPath=`%Banner`;state=`playing`;frozeScale=!1;gameOver(e=`GAME OVER`,t=`#ef4444`){this.transition(`gameover`,e,t)}win(e=`YOU WIN`,t=`#4ade80`){this.transition(`won`,e,t)}pause(){this.state===`playing`&&(this.state=`paused`,this.freeze(),this.node.emit(`flowChanged`,this.state))}resume(){this.state===`paused`&&(this.state=`playing`,this.thaw(),this.node.emit(`flowChanged`,this.state))}restart(){this.thaw(),__(this.engine)}goToScene(e,t){this.thaw(),v_(this.engine,e,t)}transition(e,t,n){this.state===`gameover`||this.state===`won`||(this.state=e,this.freezeOnEnd&&this.freeze(),this.bannerPath!==``&&this.node.getNodeOrNull(this.bannerPath)?.show(t,{color:n,seconds:0}),this.node.emit(`flowChanged`,e))}freeze(){this.frozeScale||(this.frozeScale=!0,this.engine.timeScale=0)}thaw(){this.frozeScale&&(this.frozeScale=!1,this.engine.timeScale=1)}update(){if(!(this.state!==`gameover`&&this.state!==`won`))try{this.engine.input.justPressed(this.restartAction)&&this.restart()}catch{}}};function b_(e){return Array.isArray(e.position)}function x_(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}var S_=class extends et{static props={action:{default:`interact`},range:{default:2},actorGroup:{default:`player`}};static signals=[`interacted`];action=`interact`;range=2;actorGroup=`player`;update(){let e=this.node.tree?.engine;if(!e?.scene||!e.input.justPressed(this.action)||!b_(this.node))return;let t=this.node.position,n=null,r=1/0,i=this.node.tree?.getNodesInGroup(this.actorGroup)??C_(this.node.getRoot(),this.actorGroup);for(let e of i){if(!b_(e))continue;let i=x_(t,e.position);i<=this.range&&i<r&&(n=e,r=i)}n&&this.emit(`interacted`,n)}};function C_(e,t){let n=[],r=e=>{e.isInGroup(t)&&n.push(e);for(let t of e.children)r(t)};return r(e),n}var w_=.28,T_=class extends et{static props={falloff:{default:w_}};falloff=w_;magnitude=0;t=0;prev=[];shake(e,t){this.magnitude=Math.max(this.magnitude,e),this.t=t??this.falloff}update(e){let t=e_(this),n=t.position;for(let e=0;e<this.prev.length;e++)n[e]=(n[e]??0)-(this.prev[e]??0);if(this.t<=0){this.prev.length>0&&(t.position=n.slice(),this.prev.length=0);return}this.t-=e;let r=this.magnitude*Math.max(0,this.t)/this.falloff;this.t<=0&&(this.magnitude=0);let i=n.slice();this.prev.length!==i.length&&(this.prev=Array(i.length).fill(0));for(let e=0;e<i.length;e++){let t=i.length>=3&&e===1?.5:1;this.prev[e]=(this.engine.rng.next()*2-1)*r*t,i[e]=(i[e]??0)+this.prev[e]}t.position=i}},E_=class extends et{static props={seconds:{default:1},startOnSignal:{default:!1}};static signals=[`expired`];seconds=1;startOnSignal=!1;elapsed=0;running=!1;fired=!1;onReady(){if(!(this.seconds>0))throw new N(`PROP_TYPE_MISMATCH`,`Lifetime on '${this.node.getPath()}': "seconds" must be > 0, got ${this.seconds}.`,{prop:`seconds`});this.running=!this.startOnSignal}startTimer(){this.elapsed=0,this.fired=!1,this.running=!0}update(e){!this.running||this.fired||(this.elapsed+=e,this.elapsed>=this.seconds&&(this.fired=!0,this.running=!1,this.emit(`expired`),this.node.queueFree()))}},D_=[`linear`,`easeIn`,`easeOut`,`easeInOut`];function O_(e,t){let n=t<0?0:t>1?1:t;switch(e){case`linear`:return n;case`easeIn`:return n*n;case`easeOut`:return 1-(1-n)*(1-n);case`easeInOut`:return n<.5?2*n*n:1-(-2*n+2)**2/2}}var k_=class extends et{static props={to:{default:[]},duration:{default:1},ease:{default:`easeInOut`,options:[...D_]},startOnSignal:{default:!1}};static signals=[`arrived`];to=[];duration=1;ease=`easeInOut`;startOnSignal=!1;from=[];elapsed=0;running=!1;arrivedFired=!1;onReady(){if(!(this.duration>0))throw new N(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "duration" must be > 0, got ${this.duration}.`,{prop:`duration`});if(!D_.includes(this.ease))throw new N(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "ease" must be one of [${D_.join(`, `)}], got '${this.ease}'.`,{prop:`ease`});let e=e_(this);this.from=[...e.position],this.startOnSignal||(this.running=!0)}start(){let e=this.node;this.from=[...e.position],this.elapsed=0,this.arrivedFired=!1,this.running=!0}update(e){if(!this.running)return;let t=this.node;this.elapsed+=e;let n=Math.min(1,this.elapsed/this.duration),r=O_(this.ease,n);t.position=this.from.map((e,t)=>e+((this.to[t]??e)-e)*r),n>=1&&!this.arrivedFired&&(this.arrivedFired=!0,this.running=!1,this.emit(`arrived`))}},A_=[`x`,`y`,`z`],j_=[`position`,`rotation`,`scale`],M_={x:0,y:1,z:2},N_=class extends et{static props={axis:{default:`y`,options:[...A_]},amplitude:{default:1},frequency:{default:1},mode:{default:`position`,options:[...j_]}};static signals=[];axis=`y`;amplitude=1;frequency=1;mode=`position`;base=0;time=0;onReady(){if(!A_.includes(this.axis))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "axis" must be one of [${A_.join(`, `)}], got '${this.axis}'.`,{prop:`axis`});if(!j_.includes(this.mode))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "mode" must be one of [${j_.join(`, `)}], got '${this.mode}'.`,{prop:`mode`});this.base=this.readChannel()}update(e){this.time+=e;let t=this.amplitude*Math.sin(2*Math.PI*this.frequency*this.time);this.writeChannel(this.base+t)}isScalarRotation(){return this.mode===`rotation`&&typeof this.node.rotation==`number`}readChannel(){if(this.isScalarRotation())return this.node.rotation;let e=this.node[this.mode];if(!Array.isArray(e))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': node has no '${this.mode}' array to oscillate.`,{prop:`mode`});return e[M_[this.axis]]??0}writeChannel(e){if(this.isScalarRotation()){this.node.rotation=e;return}let t=[...this.node[this.mode]];t[M_[this.axis]]=e,this.node[this.mode]=t}},P_=class extends et{static signals=[`waypointReached`,`arrived`];static props={speed:{default:120},loop:{default:!1}};speed=120;loop=!1;waypoints=[];index=0;get moving(){return this.index<this.waypoints.length}setPath(e){this.waypoints=e.map(e=>[...e]),this.index=0}stop(){this.waypoints=[],this.index=0}update(e){if(!this.moving)return;let t=e_(this),n=this.speed*e;for(;n>0&&this.index<this.waypoints.length;){let e=this.waypoints[this.index],r=a_(t.position,e,n),i=F_(t.position,r.position);if(t.position=r.position,n-=i,r.reached){if(this.node.emit(`waypointReached`,this.index),this.index+=1,this.index>=this.waypoints.length)if(this.loop&&this.waypoints.length>1)this.index=0;else{this.node.emit(`arrived`);return}}else return}}};function F_(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(t[i]??0)-(e[i]??0);n+=r*r}return Math.sqrt(n)}var I_=class extends et{static props={points:{default:[]},speed:{default:60},loop:{default:!0},mode:{default:`loop`,options:[`loop`,`pingpong`]},pauseAt:{default:0}};static signals=[`reachedPoint`];points=[];speed=60;loop=!0;mode=`loop`;pauseAt=0;index=0;direction=1;pauseTimer=0;onReady(){if(!Array.isArray(this.points)||this.points.length===0)throw new N(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "points" must be a non-empty array of position arrays or node paths.`,{prop:`points`});if(this.mode!==`loop`&&this.mode!==`pingpong`)throw new N(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "mode" must be 'loop' or 'pingpong', got '${this.mode}'.`,{prop:`mode`});e_(this)}update(e){if(this.pauseTimer>0){this.pauseTimer=Math.max(0,this.pauseTimer-e);return}let t=this.node,n=this.pointAt(this.index);if(!n)return;let{position:r,reached:i}=a_(t.position,n,this.speed*e);t.position=r,i&&(this.emit(`reachedPoint`,this.index),this.advance(),this.pauseAt>0&&(this.pauseTimer=this.pauseAt))}pointAt(e){let t=this.points[e];if(Array.isArray(t))return t;if(typeof t==`string`){let e=this.node.getNodeOrNull(t);return Array.isArray(e?.position)?e.position:null}return null}advance(){let e=this.points.length-1;if(this.mode===`pingpong`){this.index>=e?this.direction=-1:this.index<=0&&(this.direction=1),this.index=Math.min(e,Math.max(0,this.index+this.direction));return}this.index<e?this.index+=1:this.loop&&(this.index=0)}},L_=class extends et{static props={value:{default:1},kind:{default:`coin`},collectorGroup:{default:`player`}};static signals=[`collected`];value=1;kind=`coin`;collectorGroup=`player`;collectedAlready=!1;onReady(){d_(this,e=>this.tryCollect(e))}tryCollect(e){this.collectedAlready||e.isInGroup(this.collectorGroup)&&(this.collectedAlready=!0,this.emit(`collected`,this.value,e),this.node.queueFree())}},R_=class extends et{static props={speed:{default:300},direction:{default:null},gravity:{default:0}};static signals=[];speed=300;direction=null;gravity=0;velocity=[];onReady(){if(this.speed===0&&this.gravity===0)throw new N(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': a projectile with "speed" 0 and "gravity" 0 never moves — set one of them.`,{prop:`speed`});let e=e_(this),t=this.resolveDirection();for(this.velocity=t.map(e=>e*this.speed);this.velocity.length<e.position.length;)this.velocity.push(0)}update(e){let t=this.node;this.gravity!==0&&(this.velocity[1]=(this.velocity[1]??0)+this.gravity*e);let n=t.position,r=Math.max(n.length,this.velocity.length),i=Array(r);for(let t=0;t<r;t++)i[t]=(n[t]??0)+(this.velocity[t]??0)*e;t.position=i}resolveDirection(){if(Array.isArray(this.direction))return i_(this.direction);if(this.direction===null||this.direction===`forward`)return this.forwardFromRotation();throw new N(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': "direction" must be a vector or 'forward', got ${JSON.stringify(this.direction)}.`,{prop:`direction`})}forwardFromRotation(){let e=this.node.rotation;if(typeof e==`number`){let t=e*Math.PI/180;return[Math.cos(t),Math.sin(t)]}if(Array.isArray(e)){let t=(e[1]??0)*Math.PI/180,n=(e[0]??0)*Math.PI/180;return i_([-Math.sin(t)*Math.cos(n),Math.sin(n),-Math.cos(t)*Math.cos(n)])}return[1,0]}},z_=class extends et{static props={score:{default:0},lives:{default:0},scoreToWin:{default:0}};static signals=[`scoreChanged`,`won`,`lost`,`lifeLost`];score=0;lives=0;scoreToWin=0;hasWon=!1;hasLost=!1;onReady(){if(this.lives<0)throw new N(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "lives" must be >= 0, got ${this.lives}.`,{prop:`lives`});if(this.scoreToWin<0)throw new N(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "scoreToWin" must be >= 0, got ${this.scoreToWin}.`,{prop:`scoreToWin`})}addScore(e){this.setScore(this.score+e)}setScore(e){this.score=e,this.emit(`scoreChanged`,this.score),this.scoreToWin>0&&!this.hasWon&&this.score>=this.scoreToWin&&(this.hasWon=!0,this.emit(`won`))}loseLife(){this.lives<=0||this.hasLost||(--this.lives,this.emit(`lifeLost`,this.lives),this.lives<=0&&(this.hasLost=!0,this.emit(`lost`)))}serialize(){return{score:this.score,lives:this.lives,hasWon:this.hasWon,hasLost:this.hasLost}}deserialize(e){let t=e;typeof t.score==`number`&&(this.score=t.score),typeof t.lives==`number`&&(this.lives=t.lives),typeof t.hasWon==`boolean`&&(this.hasWon=t.hasWon),typeof t.hasLost==`boolean`&&(this.hasLost=t.hasLost)}},B_=class{behavior;detached=new Map;constructor(e){this.behavior=e}resolveTemplate(e){let t=this.detached.get(e);if(t)return t;let n=this.behavior.node,r=e===``?null:n.getNodeOrNull(e);if(!r){let t=this.behavior.constructor.name;throw new N(`NODE_NOT_FOUND`,`${t} on '${n.getPath()}': "prefab" '${e}' does not resolve to a template node. Point it at a (usually hidden) child node to clone.`,{prop:`prefab`,path:n.getPath()})}return r.parent&&r.parent.removeChild(r),this.detached.set(e,r),r}spawn(e,t){let n=Un(e),r=t?.at;return r&&r.length>0&&$g(n)&&(n.position=n_($g(this.behavior.node)?this.behavior.node.position:[],r)),typeof n.visible==`boolean`&&(n.visible=!0),(t?.parent??this.behavior.node).addChild(n),n}},V_={CameraShake:T_,DayNight:m_,GameFlow:y_,PathFollow:P_,Health:u_,Lifetime:E_,ScoreKeeper:z_,Pickup:L_,Collector:l_,DamageOnContact:f_,Interactable:S_,Clickable:c_,FollowCamera:g_,Patrol:I_,Chase:s_,Wander:class extends et{static props={speed:{default:40},radius:{default:50},changeEvery:{default:2}};static signals=[];speed=40;radius=50;changeEvery=2;origin=[];goal=[];timer=0;onReady(){if(!(this.radius>0))throw new N(`PROP_TYPE_MISMATCH`,`Wander on '${this.node.getPath()}': "radius" must be > 0, got ${this.radius}.`,{prop:`radius`});let e=e_(this);this.origin=[...e.position],this.goal=[...e.position],this.pickGoal()}update(e){let t=this.node;this.timer-=e;let{position:n,reached:r}=a_(t.position,this.goal,this.speed*e);t.position=n,(r||this.timer<=0)&&this.pickGoal()}pickGoal(){this.timer=this.changeEvery;let e=this.origin.length,t=Array(e);for(let n=0;n<8;n++){for(let n=0;n<e;n++)t[n]=(this.origin[n]??0)+this.rng.range(-this.radius,this.radius);if(t_(t,this.origin)<=this.radius){this.goal=t;return}}this.goal=t.map((e,n)=>{let r=this.origin[n]??0,i=t_(t,this.origin)||1;return r+(e-r)/i*this.radius})}},ZombieAI:class extends et{static props={aggroTarget:{default:``,nodePath:!0},aggroRange:{default:12},deAggroRange:{default:0},chaseSpeed:{default:4},wanderSpeed:{default:1.4},wanderRadius:{default:8},wanderChangeEvery:{default:3},goalTarget:{default:``,nodePath:!0},stopRange:{default:1.2},moveParent:{default:!1}};static signals=[`enteredAggro`,`exitedAggro`,`movementStateChanged`];aggroTarget=``;aggroRange=12;deAggroRange=0;chaseSpeed=4;wanderSpeed=1.4;wanderRadius=8;wanderChangeEvery=3;goalTarget=``;stopRange=1.2;moveParent=!1;aggro=!1;started=!1;home=[];goal=[];timer=0;lastState=``;mover(){let e=this.moveParent?this.node.parent:this.node;return e&&$g(e)?e:null}effectiveDeAggro(){return this.deAggroRange>0?this.deAggroRange:this.aggroRange*1.5}onReady(){if(this.moveParent){let e=this.node.parent;if(!e||!$g(e))throw new N(`PROP_TYPE_MISMATCH`,`ZombieAI on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else e_(this)}update(e){let t=this.mover();if(!t)return;this.started||(this.started=!0,this.home=[...t.position],this.pickGoal());let n=this.aggroTarget?this.node.getNodeOrNull(this.aggroTarget):null,r=n&&$g(n)?n.position:null,i=r?this.groundDistance(t.position,r):1/0;if(!this.aggro&&i<=this.aggroRange?(this.aggro=!0,this.emit(`enteredAggro`)):this.aggro&&i>=this.effectiveDeAggro()&&(this.aggro=!1,this.emit(`exitedAggro`),this.pickGoal()),this.aggro&&r){let n=this.approach(t,r,this.chaseSpeed,e);this.setState(n?`idle`:`run`);return}this.timer-=e;let a=this.approach(t,this.goal,this.wanderSpeed,e);this.setState(a?`idle`:`walk`),(a||this.timer<=0)&&this.pickGoal()}approach(e,t,n,r){let i=e.position;if(this.groundDistance(i,t)<=this.stopRange)return!0;let a=i.length>=3?1:-1,o=[...t];a>=0&&(o[a]=i[a]??0);let s=this.groundDistance(i,o),{position:c}=a_(i,o,Math.min(n*r,Math.max(0,s-this.stopRange)));return e.position=c,!1}groundDistance(e,t){if(e.length>=3){let n=(e[0]??0)-(t[0]??0),r=(e[2]??0)-(t[2]??0);return Math.hypot(n,r)}return t_(e,t)}setState(e){e!==this.lastState&&(this.lastState=e,this.emit(`movementStateChanged`,e))}pickGoal(){this.timer=this.wanderChangeEvery;let e=this.mover(),t=e?e.position:this.home,n=t.length>=3?1:-1,r=this.home,i=this.goalTarget?this.node.getNodeOrNull(this.goalTarget):null;if(i&&$g(i)){let e=i.position;r=t.map((t,n)=>t+((e[n]??0)-t)*.4)}let a=[...r];for(let e=0;e<a.length;e++)e!==n&&(a[e]=(r[e]??0)+this.rng.range(-this.wanderRadius,this.wanderRadius));n>=0&&(a[n]=t[n]??0),this.goal=a}},MoveTo:k_,Oscillate:N_,Spawner:class extends et{static props={prefab:{default:``,nodePath:!0},interval:{default:1},max:{default:0},at:{default:[]},autoStart:{default:!0},total:{default:0}};static signals=[`spawned`,`finished`];prefab=``;interval=1;max=0;at=[];autoStart=!0;total=0;source=new B_(this);template;live=new Set;timer=0;running=!1;spawnedCount=0;done=!1;get liveCount(){return this.prune(),this.live.size}_templateForTest(){return this.template}onReady(){this.template=this.source.resolveTemplate(this.prefab),this.running=this.autoStart,this.timer=this.interval}start(){this.done||(this.running=!0)}stop(){this.running=!1}spawn(){if(this.prune(),this.done||this.max>0&&this.live.size>=this.max)return null;let e=this.source.spawn(this.template,this.at.length>0?{at:this.at}:void 0);return this.live.add(e),this.spawnedCount+=1,this.emit(`spawned`,e),this.total>0&&this.spawnedCount>=this.total&&(this.done=!0,this.running=!1,this.emit(`finished`)),e}update(e){this.running&&(this.timer-=e,!(this.timer>0)&&(this.timer+=this.interval,this.spawn()))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}},WaveSpawner:class extends et{static props={waves:{default:[]},autoStart:{default:!0}};static signals=[`waveStarted`,`waveCleared`,`allCleared`];waves=[];autoStart=!0;source=new B_(this);parsed=[];live=new Set;waveIndex=-1;phase=`idle`;timer=0;spawnedThisWave=0;announced=!1;onReady(){if(!Array.isArray(this.waves)||this.waves.length===0)throw new N(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': "waves" must be a non-empty array of { prefab, count, interval, delayBefore }.`,{prop:`waves`});this.parsed=this.waves.map((e,t)=>this.parseWave(e,t));for(let e of this.parsed)this.source.resolveTemplate(e.prefab);this.autoStart&&this.beginWave(0)}start(){this.beginWave(0)}update(e){if(this.phase===`idle`||this.phase===`done`)return;let t=this.parsed[this.waveIndex];if(t){if(this.announced||(this.announced=!0,this.emit(`waveStarted`,this.waveIndex)),this.phase===`delay`){this.timer-=e,this.timer<=0&&(this.phase=`spawning`,this.timer=0);return}if(this.phase===`spawning`){for(this.timer-=e;this.timer<=0&&this.spawnedThisWave<t.count;){let e=this.source.spawn(this.source.resolveTemplate(t.prefab));this.live.add(e),this.spawnedThisWave+=1,this.timer+=t.interval}this.spawnedThisWave>=t.count&&(this.phase=`clearing`);return}if(this.phase===`clearing`&&(this.prune(),this.live.size===0)){this.emit(`waveCleared`,this.waveIndex);let e=this.waveIndex+1;e<this.parsed.length?this.beginWave(e):(this.phase=`done`,this.emit(`allCleared`))}}}beginWave(e){this.waveIndex=e,this.spawnedThisWave=0,this.announced=!1,this.live.clear();let t=this.parsed[e];t&&(t.delayBefore>0?(this.phase=`delay`,this.timer=t.delayBefore):(this.phase=`spawning`,this.timer=0))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}parseWave(e,t){let n=e,r=typeof n?.prefab==`string`?n.prefab:``;if(r===``)throw new N(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': wave ${t} needs a "prefab" template path.`,{prop:`waves`});return{prefab:r,count:typeof n?.count==`number`?n.count:1,interval:typeof n?.interval==`number`?n.interval:.5,delayBefore:typeof n?.delayBefore==`number`?n.delayBefore:0}}},Projectile:R_,Buoyancy:Zg};function H_(e){let t=e?.replace??!0;for(let[e,n]of Object.entries(V_))it(e,n,{replace:t})}function U_(e,t){let n=e.shape;if(n!==void 0){if(e.oneWay!==void 0&&typeof e.oneWay!=`boolean`)throw new N(`BAD_FORMAT`,`Collider on '${t}': "oneWay" must be a boolean (platforms you jump up through), got ${JSON.stringify(e.oneWay)}.`);if(n===`rect`){let n=e.size;if(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`))throw new N(`BAD_FORMAT`,`Collider on '${t}': rect needs "size": [width, height].`);return}if(n===`circle`){if(typeof e.radius!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${t}': circle needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}throw new N(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(n)}.`)}}var W_=class extends At{static typeName=`Node2D`;static props={position:{default:[0,0]},rotation:{default:0},static:{default:!1},scale:{default:[1,1]},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},visible:{default:!0}};static propAliases={zIndex:`renderOrder`};position=[0,0];rotation=0;static=!1;scale=[1,1];renderOrder=0;orderGroup=`default`;get effectiveRenderOrder(){return un(this.orderGroup,this.renderOrder)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new ho}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-ya.degToRad(this.rotation),t.scale.set(this.scale[0]??1,this.scale[1]??1,1),t.visible=this.visible}free(){super.free(),this._object2D?.removeFromParent(),this._object2D=null}},G_=class extends W_{static props={collider:{default:{},variants:{tag:`shape`,byTag:{rect:{shape:`rect`,size:[32,32]},circle:{shape:`circle`,radius:16},capsule:{shape:`capsule`,radius:12,height:32}}}}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}static validateJson(e){U_(e.collider,e.name)}_physics=null},K_=class extends G_{static typeName=`StaticBody2D`},q_=class extends G_{static typeName=`Area2D`},J_=class extends G_{static typeName=`RigidBody2D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0]}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearVelocity=[0,0]},Y_=class extends G_{static typeName=`CharacterBody2D`;static props={velocity:{default:[0,0]},snapToGround:{default:!0},slopeLimitDeg:{default:45}};velocity=[0,0];snapToGround=!0;slopeLimitDeg=45;_grounded=!1;moveAndSlide(){if(!this._physics)throw new N(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody2D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody2D '${this.name}' has no physics world — await enablePhysics2D(engine) first.`);this._physics.moveAndSlide(this)}_onWall=0;_onCeiling=!1;isOnWall(){return this._onWall!==0}wallSide(){return this._onWall}isOnCeiling(){return this._onCeiling}isOnFloor(){return this._grounded}},X_=new Set;function Z_(e){return X_.add(e),()=>X_.delete(e)}function Q_(e,t){return[...X_].filter(n=>n.dimension===e&&(t===void 0||n.engine===t))}var $_=class extends W_{static typeName=`Joint2D`;static props={type:{default:`revolute`,options:[`fixed`,`revolute`,`rope`,`spring`]},target:{default:``,nodePath:!0},anchor:{default:[0,0]},targetAnchor:{default:[0,0]},length:{default:0},stiffness:{default:50},damping:{default:5}};type=`revolute`;target=``;anchor=[0,0];targetAnchor=[0,0];length=0;stiffness=50;damping=5;onEnterTree(){if(!(this.parent instanceof G_))throw new N(`TREE_VIOLATION`,`Joint2D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new N(`BAD_FORMAT`,`Joint2D '${this.name}' needs a "target" node path to the body it links to.`)}_resolveBodies(){let e=this.parent,t=this.getNodeOrNull(this.target);if(!(t instanceof G_))throw new N(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},Z=100,ev=Math.PI/180;async function tv(e,t){let n=await ym(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await n.init({}),new nv(n,e,t)}var nv=class{R;engine;debugDraw=!1;debugScope=null;dimension=`2d`;unregisterDebug;warnedNoCollider=new WeakSet;entries=new Map;byColliderHandle=new Map;world;events;kcc;disconnect;lastDt=1/60;optsGravity;lastScene=null;constructor(e,t,n){this.R=e,this.engine=t,this.optsGravity=n?.gravity,this.simulate=n?.simulate??!0,this.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,980];this.world=new e.World({x:(i[0]??0)/Z,y:(i[1]??0)/Z}),this.kcc=this.world.createCharacterController(.01),this.kcc.setUp({x:0,y:-1}),this.events=new e.EventQueue(!0),this.unregisterDebug=Z_(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.syncBodies()}simulate;step(e){if(this.lastDt=e,!this.simulate){this.syncBodies(),this.poseFromTree();return}if(this.engine.scene!==this.lastScene&&(this.lastScene=this.engine.scene,!this.optsGravity)){let e=this.engine.scene?.physics?.gravity??[0,980];this.world.gravity={x:(e[0]??0)/Z,y:(e[1]??0)/Z}}this.syncBodies(),this.world.timestep=e,this.world.step(this.events);for(let[e,t]of this.entries){let n=t.body.translation();if(!t.body.isFixed()){let[t,r]=lv(e);e.position=[n.x*Z-t,n.y*Z-r]}if(e instanceof J_){e.fixedRotation||(e.rotation=t.body.rotation()/ev);let n=t.body.linvel();e.linearVelocity=[n.x*Z,n.y*Z],t.lastVX=e.linearVelocity[0]??0,t.lastVY=e.linearVelocity[1]??0}let[r,i]=cv(e);t.lastX=r,t.lastY=i}this.events.drainCollisionEvents((e,t,n)=>{let r=this.byColliderHandle.get(e),i=this.byColliderHandle.get(t);if(!r||!i)return;let a=n?`triggerEnter`:`triggerExit`;try{r.emit(a,i),i.emit(a,r)}catch(e){lt(this.engine,`error`,`incanto: error in a '${a}' handler (${r.name} ↔ ${i.name}):`,e)}})}moveAndSlide(e){let t=this.ensureEntry(e),n=e.velocity[1]??0;e.snapToGround&&n>=0?this.kcc.enableSnapToGround(.05):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*ev);let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=cv(t.ground);r=e-(t.groundX??e),i=n-(t.groundY??n)}else t.ground=null;let a={x:((e.velocity[0]??0)*this.lastDt+r)/Z*1,y:(n*this.lastDt+i)/Z*1},o=t.body.translation().y*Z+ov(e);this.kcc.computeColliderMovement(t.collider,a,this.R.QueryFilterFlags.EXCLUDE_SENSORS,void 0,t=>{let r=this.byColliderHandle.get(t.handle);return!(r&&r!==e&&r.collider.oneWay===!0&&(n<0||o>sv(r)+av))});let s=this.kcc.computedMovement(),c=t.body.translation();t.body.setNextKinematicTranslation({x:c.x+s.x,y:c.y+s.y}),e._grounded=this.kcc.computedGrounded(),e._onWall=0,e._onCeiling=!1;let l=this.kcc.numComputedCollisions();for(let t=0;t<l;t++){let n=this.kcc.computedCollision(t)?.normal1;n&&(Math.abs(n.y)>.7?e._grounded||(e._onCeiling=!0):Math.abs(n.x)>.7&&(e._onWall=n.x>0?-1:1))}if(e._grounded){let n=(c.x+s.x)*Z,r=(c.y+s.y)*Z+ov(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&!(i.node instanceof Y_)){t.ground=i.node;let[e,n]=cv(i.node);t.groundX=e,t.groundY=n}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope?this.scopedLines(this.debugScope):this.world.debugRender().vertices,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]*Z;return t}scopedLines(e){let t=[],n=[],r=e=>{let t=this.entries.get(e);t&&n.push(t.body);for(let t of e.children)r(t)};r(e);for(let t=e.parent;t&&n.length===0;t=t.parent){let e=this.entries.get(t);e&&n.push(e.body)}for(let e of n)for(let n=0;n<e.numColliders();n++){let r=e.collider(n);if(!r)continue;let i=r.translation(),a=r.rotation(),o=Math.cos(a),s=Math.sin(a),c=(e,n)=>{t.push(i.x+e*o-n*s,i.y+e*s+n*o)},l=(e,t,n,r)=>{c(e,t),c(n,r)},u=r.shape;if(u.halfExtents){let{x:e,y:t}=u.halfExtents;l(-e,-t,e,-t),l(e,-t,e,t),l(e,t,-e,t),l(-e,t,-e,-t)}else if(u.radius!==void 0){let e=u.radius,t=u.halfHeight??0;for(let n=0;n<24;n++){let r=n/24*Math.PI*2,i=(n+1)/24*Math.PI*2,a=e=>e>=0?t:-t;l(Math.cos(r)*e,Math.sin(r)*e+a(Math.sin(r)),Math.cos(i)*e,Math.sin(i)*e+a(Math.sin(i)))}t>0&&(l(-e,-t,-e,t),l(e,-t,e,t))}}return new Float32Array(t)}syncJoints(e){let t=this.R;if(e)for(let[e,t]of this.joints)this.jointSet.has(e)||(this.world.removeImpulseJoint(t,!0),this.joints.delete(e));for(let e of this.jointSet){if(this.joints.has(e))continue;let{a:n,b:r}=e._resolveBodies(),i=this.entries.get(n),a=this.entries.get(r);if(!i||!a)continue;let o={x:(e.anchor[0]??0)/Z,y:(e.anchor[1]??0)/Z},s={x:(e.targetAnchor[0]??0)/Z,y:(e.targetAnchor[1]??0)/Z},c=e.length/Z;if(e.length===0&&(e.type===`rope`||e.type===`spring`)){let e=i.body.translation(),t=a.body.translation();c=Math.hypot(t.x-e.x,t.y-e.y)}let l;l=e.type===`fixed`?t.JointData.fixed(o,0,s,0):e.type===`rope`?t.JointData.rope(c,o,s):e.type===`spring`?t.JointData.spring(c,e.stiffness,e.damping,o,s):t.JointData.revolute(o,s),this.joints.set(e,this.world.createImpulseJoint(l,i.body,a.body,!0))}}castRay(e,t,n,r,i){let a=Math.hypot(t[0],t[1])||1,o=new this.R.Ray({x:e[0]/Z,y:e[1]/Z},{x:t[0]/a,y:t[1]/a}),s=r?this.entries.get(r)?.collider:void 0,c=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castRayAndGetNormal(o,n/Z,!0,c,void 0,s,void 0,e=>!e.isSensor());return l?{distance:l.timeOfImpact*Z,normal:[l.normal.x,l.normal.y],node:this.byColliderHandle.get(l.collider.handle)??null}:null}dispose(){this.disconnect(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;bodySet=new Set;poseFromTree(){for(let[e,t]of this.entries){let[n,r]=cv(e);t.body.setTranslation({x:n/Z,y:r/Z},!1),t.body.setRotation(e.rotation*ev,!1)}this.world.propagateModifiedBodyPositionsToColliders()}syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=e.root===this.lastRoot,r=t!==this.lastStructure||!n;if(r){let r=n?e.tree._structureSince(this.lastStructure):null;if(this.lastStructure=t,this.lastRoot=e.root,r){let t=!1;for(let{node:e,added:n}of r)e instanceof G_&&(n?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof $_&&(t=!0);t&&(this.jointSet.clear(),rv(e.root,this.jointSet))}else this.bodySet.clear(),iv(e.root,this.bodySet),this.jointSet.clear(),rv(e.root,this.jointSet)}let i=this.bodySet;for(let e of i){if(e.collider.shape===void 0){let t=this.entries.get(e);t&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.warnedNoCollider.has(e)||(this.warnedNoCollider.add(e),lt(this.engine,`warn`,`[incanto] '${e.name}' has no collider — physics skips it.`));continue}let t=this.entries.get(e);t&&e._colliderChanged&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.ensureEntry(e)}if(this.syncJoints(r),r)for(let[e,t]of this.entries)i.has(e)||(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let[r,i]=cv(e),a=r/Z,o=i/Z,s;s=e instanceof J_?n.RigidBodyDesc.dynamic():e instanceof Y_||e instanceof q_?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),s.setTranslation(a,o).setRotation(e.rotation*ev),e instanceof J_&&(s.setGravityScale(e.gravityScale),s.setLinvel((e.linearVelocity[0]??0)/Z,(e.linearVelocity[1]??0)/Z),e.fixedRotation&&s.lockRotations());let c=this.world.createRigidBody(s),l=uv(n,e.collider,e.name);l.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof q_&&l.setSensor(!0),e instanceof J_&&l.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let u=this.world.createCollider(l,c);return t={body:c,collider:u,lastX:r,lastY:i,lastVX:0,lastVY:0},this.entries.set(e,t),this.byColliderHandle.set(u.handle,e),e._colliderChanged=!1,e._physics=this,t}let[r,i]=cv(e);if((r!==t.lastX||i!==t.lastY)&&(t.body.setTranslation({x:r/Z,y:i/Z},!0),t.lastX=r,t.lastY=i),e instanceof J_){let n=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(n!==t.lastVX||r!==t.lastVY)&&(t.body.setLinvel({x:n/Z,y:r/Z},!0),t.lastVX=n,t.lastVY=r)}return t}};function rv(e,t){e instanceof $_&&t.add(e);for(let n of e.children)rv(n,t)}function iv(e,t){e instanceof G_&&t.add(e);for(let n of e.children)iv(n,t)}var av=4;function ov(e){let t=e.collider;return t.shape===`rect`?(t.size?.[1]??32)/2:t.shape===`capsule`?(t.height??32)/2+(t.radius??8):t.radius??16}function sv(e){let[,t]=cv(e),n=e.collider;return t-(n.shape===`rect`?(n.size?.[1]??32)/2:n.shape===`capsule`?(n.height??32)/2+(n.radius??8):n.radius??16)}function cv(e){let t=0,n=0;for(let r=e;r;r=r.parent)r instanceof W_&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function lv(e){let t=0,n=0;for(let r=e.parent;r;r=r.parent)r instanceof W_&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function uv(e,t,n){U_(t,n);let r=dv(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Z,(i[1]??0)/Z),r}function dv(e,t,n){let r=t.shape;if(r===`rect`){let r=t.size;if(!Array.isArray(r)||r.length!==2||r.some(e=>typeof e!=`number`))throw new N(`BAD_FORMAT`,`Collider on '${n}': rect needs "size": [width, height].`);return e.ColliderDesc.cuboid(r[0]/2/Z,r[1]/2/Z)}if(r===`circle`){if(typeof t.radius!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${n}': circle needs "radius".`);return e.ColliderDesc.ball(t.radius/Z)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2/Z,t.radius/Z)}throw new N(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(r)}.`)}var fv=new sl(1,1),pv=class extends W_{static typeName=`Sprite2D`;static props={texture:{default:``},anchor:{default:[.5,.5]},flipX:{default:!1},flipY:{default:!1},tint:{default:`#ffffff`},opacity:{default:1}};texture=``;anchor=[.5,.5];flipX=!1;flipY=!1;tint=`#ffffff`;opacity=1;quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Js(fv,new Is({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_createObject2D(){return super._createObject2D()}resolveTexture(e){if(!this.texture||!e)return null;let t=e.getTexture(this.texture),n=t.image;return!n?.width||!n.height?null:{texture:t,width:n.width,height:n.height}}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=t.material,r=this.resolveTexture(e);if(!r){t.visible=!1;return}t.visible=!0,n.map!==r.texture&&(n.map=r.texture,n.needsUpdate=!0);let i=r.width,a=r.height;t.scale.set(this.flipX?-i:i,this.flipY?-a:a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??.5;t.position.set((.5-o)*i,(s-.5)*a,0),t.renderOrder=this.effectiveRenderOrder,n.color.set(this.tint),n.opacity=this.opacity}},mv=class extends pv{static typeName=`AnimatedSprite2D`;static signals=[`animationFinished`];static props={sheet:{default:``},animations:{default:{}},autoplay:{default:``}};sheet=``;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;ownTexture=null;loadedSheetRef=``;play(e){let t=this.animations[e];if(!t)throw new N(`UNKNOWN_ANIMATION`,`No animation '${e}' on '${this.name}'. Available: [${Object.keys(this.animations).join(`, `)}].`);this.currentAnimation=e,this.frameList=hv(t.frames,e),this.frameIndex=0,this.currentFrame=this.frameList[0]??0,this.frameTime=0,this.playing=!0}stop(){this.playing=!1}onReady(){this.autoplay&&this.play(this.autoplay)}update(e){if(!this.playing||this.currentAnimation===``)return;let t=this.animations[this.currentAnimation];if(!t||!Number.isFinite(t.fps)||t.fps<=0)return;let n=1/t.fps;for(this.frameTime+=e;this.frameTime>=n;)if(this.frameTime-=n,this.frameIndex+=1,this.frameIndex>=this.frameList.length)if(t.loop)this.frameIndex=0;else{this.frameIndex=this.frameList.length-1,this.playing=!1,this.emit(`animationFinished`,this.currentAnimation);break}this.currentFrame=this.frameList[this.frameIndex]??0}resolveTexture(e){if(!this.sheet||!e)return null;let t=e.getSheet(this.sheet);this.loadedSheetRef!==this.sheet&&(this.ownTexture=t.texture.clone(),this.ownTexture.needsUpdate=!0,this.loadedSheetRef=this.sheet);let n=this.ownTexture,r=t.texture.image;if(!r?.width||!r.height)return null;let i=Math.max(1,Math.floor(r.width/t.frameWidth)),a=this.currentFrame%i,o=Math.floor(this.currentFrame/i);return n.repeat.set(t.frameWidth/r.width,t.frameHeight/r.height),n.offset.set(a*t.frameWidth/r.width,1-(o+1)*t.frameHeight/r.height),{texture:n,width:t.frameWidth,height:t.frameHeight}}};function hv(e,t){if(!Array.isArray(e)||e.length===0)throw new N(`BAD_FORMAT`,`Animation '${t}': "frames" must be a non-empty array.`);if(e.length===2){let[t,n]=e;if(n>=t){let e=[];for(let r=t;r<=n;r++)e.push(r);return e}}return[...e]}var gv=class extends W_{static typeName=`Camera2D`;static props={follow:{default:``,nodePath:!0},smoothing:{default:0},zoom:{default:1},limits:{default:[]},current:{default:!1}};follow=``;smoothing=0;zoom=1;limits=[];current=!1;get effectiveZoom(){return Math.max(.01,this.zoom)}update(e){if(!this.follow)return;let t=this.getNodeOrNull(this.follow);if(!(t instanceof W_))return;let n=t.position[0]??0,r=t.position[1]??0,i=Math.min(Math.max(this.smoothing,0),.99),a=i<=0?1:1-i**(e*60),o=this.position[0]??0,s=this.position[1]??0;this.position=[o+(n-o)*a,s+(r-s)*a]}clampedCenter(e,t){let n=this.position[0]??0,r=this.position[1]??0;if(this.limits.length!==0&&this.limits.length!==4)throw new N(`BAD_FORMAT`,`Camera2D '${this.name}' limits must be [] or [minX,minY,maxX,maxY], got length ${this.limits.length}.`);if(this.limits.length===4){let[i,a,o,s]=this.limits,c=e/(2*this.effectiveZoom),l=t/(2*this.effectiveZoom);n=_v(n,i+c,o-c),r=_v(r,a+l,s-l)}return{x:n,y:r}}};function _v(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var vv=class extends At{static typeName=`CharacterController2D`;static props={mode:{default:`platformer`,options:[`platformer`,`topDown`]},maxSpeed:{default:220},jumpHeight:{default:64},moveAction:{default:`move`},jumpAction:{default:`jump`},coyoteSeconds:{default:0},jumpBufferSeconds:{default:0},jumpCutMultiplier:{default:1},maxJumps:{default:1},dashSpeed:{default:0},dashSeconds:{default:.15},dashAction:{default:`dash`},wallSlideSpeed:{default:0},wallJumpImpulse:{default:[0,0]}};static signals=[`movementStateChanged`];mode=`platformer`;maxSpeed=220;jumpHeight=64;moveAction=`move`;jumpAction=`jump`;coyoteSeconds=0;jumpBufferSeconds=0;jumpCutMultiplier=1;maxJumps=1;dashSpeed=0;dashSeconds=.15;dashAction=`dash`;wallSlideSpeed=0;wallJumpImpulse=[0,0];state=`idle`;coyoteLeft=0;bufferLeft=0;jumpsUsed=0;dashLeft=0;dashDir=1;rising=!1;onReady(){if(!(this.parent instanceof Y_))throw new N(`TREE_VIOLATION`,`CharacterController2D '${this.name}' must be a child of a CharacterBody2D (parent is '${this.parent?.name??`none`}').`);if(this.mode!==`platformer`&&this.mode!==`topDown`)throw new N(`PROP_TYPE_MISMATCH`,`CharacterController2D.mode must be 'platformer' or 'topDown', got '${this.mode}'.`)}fixedUpdate(e){let t=this.tree?.engine;if(!t?.scene)return;let n=this.parent;if(!(n instanceof Y_))return;let r=t.input,i=r.getVector(this.moveAction);if(this.mode===`topDown`){n.velocity=[i.x*this.maxSpeed,i.y*this.maxSpeed],n.moveAndSlide();return}let a=t.scene.physics?.gravity?.[1]??980,o=n.isOnFloor(),s=-Math.sqrt(2*a*this.jumpHeight);if(this.dashLeft>0){this.dashLeft-=e,n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}if(this.dashSpeed>0&&r.justPressed(this.dashAction)){this.dashLeft=this.dashSeconds,this.dashDir=i.x===0?this.dashDir:Math.sign(i.x),n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}n.velocity[0]=i.x*this.maxSpeed,o?(this.coyoteLeft=this.coyoteSeconds,this.jumpsUsed=0):(this.coyoteLeft=Math.max(0,this.coyoteLeft-e),this.coyoteLeft<=0&&this.jumpsUsed===0&&(this.jumpsUsed=1)),r.justPressed(this.jumpAction)?this.bufferLeft=Math.max(this.jumpBufferSeconds,0):this.bufferLeft=Math.max(0,this.bufferLeft-e);let c=this.bufferLeft>0||r.justPressed(this.jumpAction),l=this.wallSlideSpeed>0||this.wallJumpImpulse.some(e=>e!==0)?n.isOnWall():!1;if(c&&l&&!o&&this.wallJumpImpulse.some(e=>e!==0)){let e=-n.wallSide();n.velocity[0]=e*(this.wallJumpImpulse[0]??0),n.velocity[1]=-(this.wallJumpImpulse[1]??0),this.bufferLeft=0,this.rising=!0,this.jumpsUsed=1}else c&&(o||this.coyoteLeft>0||this.jumpsUsed<this.maxJumps)?(n.velocity[1]=s,this.bufferLeft=0,this.coyoteLeft=0,this.rising=!0,this.jumpsUsed=o?1:this.jumpsUsed+1):o?(n.velocity[1]=20,this.rising=!1):(n.velocity[1]=(n.velocity[1]??0)+a*e,this.rising&&this.jumpCutMultiplier<1&&!r.isPressed(this.jumpAction)&&(n.velocity[1]=(n.velocity[1]??0)*this.jumpCutMultiplier,this.rising=!1),(n.velocity[1]??0)>=0&&(this.rising=!1),this.wallSlideSpeed>0&&l&&(n.velocity[1]??0)>this.wallSlideSpeed&&(n.velocity[1]=this.wallSlideSpeed));n.isOnCeiling()&&(n.velocity[1]??0)<0&&(n.velocity[1]=0,this.rising=!1),n.moveAndSlide();let u=n.velocity[1]??0;this.wallSlideSpeed>0&&!n.isOnFloor()&&n.isOnWall()&&u>0?this.setState(`wallSlide`):n.isOnFloor()?this.setState(Math.abs(i.x)>.01?`run`:`idle`):this.setState(u<0?`jump`:`fall`)}setState(e){e!==this.state&&(this.state=e,this.emit(`movementStateChanged`,e))}},yv=new sl(1,1),bv=class extends W_{static typeName=`ColorRect2D`;static props={size:{default:[100,100]},color:{default:`#ffffff`},opacity:{default:1},anchor:{default:[.5,.5]}};size=[100,100];color=`#ffffff`;opacity=1;anchor=[.5,.5];quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Js(yv,new Is({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=this.size[0]??0,r=this.size[1]??0;t.visible=n>0&&r>0&&this.opacity>0,t.scale.set(n,r,1);let i=this.anchor[0]??.5,a=this.anchor[1]??.5;t.position.set((.5-i)*n,(a-.5)*r,0),t.renderOrder=this.effectiveRenderOrder;let o=t.material;o.color.set(this.color),o.opacity=this.opacity}},xv=new sl(1,1),Sv=class extends W_{static typeName=`Label`;static props={text:{default:``},fontSize:{default:16},color:{default:`#ffffff`},font:{default:`monospace`},align:{default:`left`}};text=``;fontSize=16;color=`#ffffff`;font=`monospace`;align=`left`;quadMesh=null;canvas=null;lastKey=``;_quad(){return this.quadMesh||(this.quadMesh=new Js(xv,new Is({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad();if(typeof document>`u`||this.text===``){t.visible=!1;return}let n=`${this.text}\0${this.fontSize}\0${this.color}\0${this.font}\0${this.align}`;n!==this.lastKey&&(this.lastKey=n,this.rasterize()),t.visible=!0,t.renderOrder=this.effectiveRenderOrder}rasterize(){let e=Math.min(globalThis.devicePixelRatio??1,2);this.canvas??=document.createElement(`canvas`);let t=this.canvas.getContext(`2d`);if(!t)return;let n=`${this.fontSize*e}px ${this.font}`;t.font=n;let r=t.measureText(this.text),i=Math.max(1,Math.ceil(r.width)),a=Math.ceil(this.fontSize*e*1.4);this.canvas.width=i,this.canvas.height=a,t.font=n,t.fillStyle=this.color,t.textBaseline=`middle`,t.fillText(this.text,0,a/2);let o=this._quad(),s=o.material;s.map?.dispose(),s.map=new Zc(this.canvas),s.needsUpdate=!0;let c=i/e,l=a/e;o.scale.set(c,l,1);let u=this.align===`center`?.5:+(this.align===`right`);o.position.set((.5-u)*c,0,0)}},Cv=new sl(1,1),wv=class e extends W_{orderGroup=`effects`;static typeName=`Particles2D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...fn]},emitting:{default:!0},rate:{default:40},burst:{default:0},lifetime:{default:[.6,1.2]},speed:{default:[40,120]},directionDeg:{default:-90},spreadDeg:{default:30},gravity:{default:[0,0]},drag:{default:0},sizeStart:{default:8},sizeEnd:{default:2},colorStart:{default:`#ffffff`},colorEnd:{default:`#ffffff`},paletteColors:{default:[]},alphaStart:{default:1},alphaEnd:{default:0},shimmer:{default:0},blend:{default:`add`,options:[`add`,`normal`]},maxParticles:{default:256}};preset=`custom`;emitting=!0;rate=40;burst=0;lifetime=[.6,1.2];speed=[40,120];directionDeg=-90;spreadDeg=30;gravity=[0,0];drag=0;sizeStart=8;sizeEnd=2;colorStart=`#ffffff`;colorEnd=`#ffffff`;paletteColors=[];alphaStart=1;alphaEnd=0;shimmer=0;blend=`add`;maxParticles=256;static validateJson(e){let t=e;if(t.preset!==`custom`&&!fn.includes(t.preset))throw new N(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${fn.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:fn});if(t.blend!==`add`&&t.blend!==`normal`)throw new N(`BAD_FORMAT`,`Particles2D '${e.name}' blend must be 'add' or 'normal', got '${t.blend}'.`,{prop:`blend`,validOptions:[`add`,`normal`]})}sim=null;bursted=!1;finishedEmitted=!1;_ensureSim(){if(!this.sim){pn(this,this.preset,qe(e.typeName));let t=this.tree?.engine?.rng??new P(4660);this.sim=new hn({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[this.speed[0]??0,this.speed[1]??0],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[this.gravity[0]??0,this.gravity[1]??0,0],drag:this.drag,maxParticles:this.maxParticles},t)}return this.sim}update(e){let t=this._ensureSim();this.burst>0&&!this.bursted&&(this.bursted=!0,t.burst(this.burst)),t.update(e),(!this.emitting||this.rate===0)&&this.bursted&&t.done&&!this.finishedEmitted&&(this.finishedEmitted=!0,this.emit(`finished`))}replay(){this.bursted=!1,this.finishedEmitted=!1}mesh=null;paletteCache=[];paletteCacheKey=``;refreshPalette(){let e=this.paletteColors;if(e.length===0)return null;let t=e.join(`|`);if(t!==this.paletteCacheKey){this.paletteCacheKey=t;for(let t=0;t<e.length;t++){let n=this.paletteCache[t];n||(n=new K,this.paletteCache[t]=n),n.set(e[t])}this.paletteCache.length=e.length}return this.paletteCache}_syncObject2D(e){super._syncObject2D(e);let t=this._ensureSim();if(!this.mesh||this.mesh.count!==this.maxParticles){this.mesh&&this.mesh.removeFromParent();let e=new Is({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new bc(Cv,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(Ni),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let n=this.mesh,r=this.refreshPalette(),i=r?null:Ev.set(this.colorStart),a=Dv.set(this.colorEnd),o=this.shimmer,s=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;Tv.makeScale(t,t,1),Tv.setPosition(e.x,-e.y,0),n.setMatrixAt(s,Tv);let c=r?r[Math.floor(e.seed*r.length)]:i,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);o>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*o+e.seed))),Ov.copy(c).lerp(a,e.t).multiplyScalar(l),n.setColorAt(s,Ov),s+=1}),n.count=s,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),n.renderOrder=this.effectiveRenderOrder}},Tv=new G,Ev=new K,Dv=new K,Ov=new K;function kv(e,t){let n=[],r=0;for(let i of e){let e=[];if(typeof i==`string`)for(let n of i){let r=t[n];if(r!==void 0)e.push(r);else if(n===`.`||n===` `)e.push(-1);else if(n>=`0`&&n<=`9`)e.push(n.charCodeAt(0)-48);else throw new N(`BAD_FORMAT`,`TileMap2D: unknown tile char '${n}' — add it to "legend" (char → tile index), or use '.'/' ' for empty and digits 0-9.`)}else for(let t of i)e.push(t);r=Math.max(r,e.length),n.push(e)}for(let e of n)for(;e.length<r;)e.push(-1);return n}function Av(e,t){let n=e.length,r=n>0?e[0].length:0,i=e.map(e=>e.map(()=>!1)),a=(n,r)=>t.has(e[r][n]),o=[];for(let e=0;e<n;e++)for(let t=0;t<r;t++){if(!a(t,e)||i[e][t])continue;let s=1;for(;t+s<r&&a(t+s,e)&&!i[e][t+s];)s++;let c=1;grow:for(;e+c<n;){for(let n=0;n<s;n++)if(!a(t+n,e+c)||i[e+c][t+n])break grow;c++}for(let n=0;n<c;n++)for(let r=0;r<s;r++)i[e+n][t+r]=!0;o.push({x:t,y:e,w:s,h:c})}return o}var jv=class extends W_{static typeName=`TileMap2D`;static props={texture:{default:``},tileSize:{default:32},columns:{default:0},cells:{default:[]},legend:{default:{}},solid:{default:[]},opacity:{default:1}};texture=``;tileSize=32;columns=0;_cells=[];_legend={};_solid=[];geometryDirty=!0;collidersDirty=!0;get cells(){return this._cells}set cells(e){this._cells=e,this.geometryDirty=!0,this.collidersDirty=!0}get legend(){return this._legend}set legend(e){this._legend=e,this.geometryDirty=!0,this.collidersDirty=!0}get solid(){return this._solid}set solid(e){this._solid=e,this.collidersDirty=!0}opacity=1;tileMesh=null;builtColumns=0;builtRows=0;static validateJson(e){let t=e;kv(t._cells,t._legend)}grid(){return kv(this._cells,this._legend)}onReady(){this.rebuildColliders()}update(e){this.collidersDirty&&this.rebuildColliders()}rebuildColliders(){this.collidersDirty=!1;for(let e of[...this.children])e.name.startsWith(`__tileSolid`)&&e.free();if(this._solid.length===0)return;let e=this.tileSize;Av(this.grid(),new Set(this._solid)).forEach((t,n)=>{let r=new K_(`__tileSolid${n}`);r.position=[(t.x+t.w/2)*e,(t.y+t.h/2)*e],r.collider={shape:`rect`,size:[t.w*e,t.h*e]},this.addChild(r)})}_mesh(){return this.tileMesh||(this.tileMesh=new Js(new J,new Is({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.tileMesh)),this.tileMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._mesh(),n=t.material;if(!this.texture||!e){t.visible=!1;return}let r=e.getTexture(this.texture),i=r.image;if(!i?.width||!i.height){t.visible=!1;return}t.visible=this.opacity>0,t.renderOrder=this.effectiveRenderOrder,n.opacity=this.opacity,n.map!==r&&(r.magFilter=nr,n.map=r,n.needsUpdate=!0,this.geometryDirty=!0);let a=this.columns>0?this.columns:Math.max(1,Math.floor(i.width/this.tileSize)),o=Math.max(1,Math.floor(i.height/this.tileSize));(a!==this.builtColumns||o!==this.builtRows)&&(this.geometryDirty=!0),this.geometryDirty&&(this.geometryDirty=!1,this.builtColumns=a,this.builtRows=o,this.buildGeometry(t.geometry,a,o))}buildGeometry(e,t,n){let r=this.grid(),i=this.tileSize,a=[],o=[],s=[];for(let e=0;e<r.length;e++){let c=r[e];for(let r=0;r<c.length;r++){let l=c[r];if(l<0)continue;let u=r*i,d=u+i,f=-(e*i),p=-((e+1)*i),m=a.length/3;a.push(u,f,0,d,f,0,d,p,0,u,p,0);let h=l%t,g=Math.floor(l/t),_=h/t,v=(h+1)/t,y=1-g/n,b=1-(g+1)/n;o.push(_,y,v,y,v,b,_,b),s.push(m,m+2,m+1,m,m+3,m+2)}}e.setAttribute(`position`,new q(new Float32Array(a),3)),e.setAttribute(`uv`,new q(new Float32Array(o),2)),e.setIndex(s),e.computeBoundingSphere()}get renderedTileCount(){let e=this.tileMesh?.geometry.getAttribute(`position`);return e?e.count/4:0}free(){this.tileMesh?.geometry.dispose(),super.free()}},Mv=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],Nv=class extends At{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:Mv}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new go,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!Mv.includes(t))throw new N(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${Mv.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:Mv})}_anchorOrigin(e,t){let n=this.anchor;return{x:n.includes(`right`)?e:n===`top`||n===`center`||n===`bottom`?e/2:0,y:n.includes(`bottom`)?t:n===`left`||n===`center`||n===`right`?t/2:0}}};function Pv(){gn(),R(W_),R(pv),R(bv),R(wv),R(mv),R(gv),R(Sv),R(Nv),R(K_),R(J_),R(q_),R(Y_),R(vv),R($_),R(jv)}function Fv(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function Iv(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}var Lv=new Bo,Rv=new U,zv=12,Bv=new Float32Array(16);function Vv(e){if(!(e instanceof W_))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),Lv.setFromObject(t),Lv.getSize(Rv);let n,r,i,a;if(!Number.isFinite(Rv.x)||Rv.x===0&&Rv.y===0){let e=new U().setFromMatrixPosition(t.matrixWorld);n=e.x-zv,i=e.x+zv,r=e.y-zv,a=e.y+zv}else n=Lv.min.x-2,i=Lv.max.x+2,r=Lv.min.y-2,a=Lv.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return Bv.set(o),Bv}function Hv(){return{visited:new Set,cameras:[]}}function Uv(e,t,n,r,i,a,o){let s=a??Hv();s.visited.clear(),s.cameras.length=0,Wv(e,t,n,!1,s.visited,s.cameras,r,i,o?.ignoreStatic===!0),Gv(t,s.visited),Gv(n,s.visited);let c=null;for(let e=0;e<s.cameras.length;e++){let t=s.cameras[e];if(t.current){c=t;break}}return c||=s.cameras[0]??null,{activeCamera:c}}function Wv(e,t,n,r,i,a,o,s,c){let l=t,u=r;if(e instanceof W_&&!(e instanceof Nv)){let t=e._ensureObject2D();if(e.static&&!c&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof Nv){let t=e._ensureGroup();t.parent!==n&&n.add(t);let r=s?e._anchorOrigin(s.width,s.height):{x:0,y:0};t.position.set(r.x,-r.y,0),i.add(t),u=!0,l=t}else if(e instanceof W_){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(o),i.add(n),e instanceof gv&&!r&&a.push(e),l=n}for(let t of e.children)Wv(t,l,n,u,i,a,o,s,c);if(e instanceof W_&&!(e instanceof Nv)){let t=e._ensureObject2D();e.static&&!c?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}function Gv(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&Gv(i,t)}}var Kv=class{viewOverride=null;webgl;worldScene=new To;syncScratch=Hv();ignoreStatic=!1;uiScene=new To;worldCam=new _u(-1,1,1,-1,-1e3,1e3);uiCam=new _u(-1,1,1,-1,-1e3,1e3);engine;assets;loadedAssetScenes=new WeakSet;disconnect;canvas;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.assets=e.assets??new hm(void 0,this.engine);let t=_n(e.engine.scene?.environment,{antialias:!0,pixelRatio:1,preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,e);this.webgl=new mm({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer}),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.webgl.setPixelRatio(t.pixelRatio),this.webgl.info.autoReset=!1,this.debugLines=new Vc(new J,new kc({color:`#00ff6e`,transparent:!0,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.worldScene.add(this.debugLines),this.selectionLines=new Vc(new J,new kc({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.worldScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>this.render())}debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?Vv(t):null;if(this.selectionLines.visible=n!==null,!n)return;let r=new Float32Array(n.length/2*3);for(let e=0,t=0;e<n.length;e+=2,t+=3)r[t]=n[e],r[t+1]=n[e+1],r[t+2]=0;this.selectionLines.geometry.setAttribute(`position`,new q(r,3)),this.selectionLines.geometry.getAttribute(`position`).needsUpdate=!0}syncDebugLines(){let e=null;for(let t of Q_(`2d`,this.engine))if(e=t.debugLines(),e)break;if(this.debugLines.visible=e!==null,!e)return;let t=new Float32Array(e.length/2*3);for(let n=0,r=0;n<e.length;n+=2,r+=3)t[r]=e[n],t[r+1]=e[n+1],t[r+2]=0;this.debugLines.geometry.setAttribute(`position`,new q(t,3))}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e));let t=e.environment?.background;this.worldScene.background=typeof t==`string`?new K(t):null;let n=this.canvas.clientWidth||this.canvas.width,r=this.canvas.clientHeight||this.canvas.height,i=this.webgl.getSize(Jv);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:wn(e.viewport),o=a?Tn(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r,{activeCamera:l}=Uv(e.root,this.worldScene,this.uiScene,this.assets,{width:s,height:c},this.syncScratch),u=a?{x:a.design[0]/2,y:a.design[1]/2}:{x:n/2,y:r/2},d=1;this.viewOverride?(u={x:this.viewOverride.cx,y:this.viewOverride.cy},d=this.viewOverride.zoom):l&&(u=l.clampedCenter(s,c),d=l.effectiveZoom);let f=o?.scale??1;this.lastView={cx:u.x,cy:u.y,zoom:d*f,w:n,h:r},this.lastViewport=o,o&&(o.offsetX>.5||o.offsetY>.5)?(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r),this.webgl.clear(),this.webgl.setViewport(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissor(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissorTest(!0)):(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r)),qv(this.worldCam,u.x,u.y,s/d,c/d),qv(this.uiCam,s/2,c/2,s,c),this.webgl.info.reset(),this.webgl.autoClear=!0,this.webgl.render(this.worldScene,this.worldCam),this.webgl.autoClear=!1,this.webgl.render(this.uiScene,this.uiCam),this.webgl.autoClear=!0}lastViewport=null;lastView={cx:0,cy:0,zoom:1,w:1,h:1};view(){return{...this.lastView}}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}worldFromScreen(e,t){return Iv(this.lastView,e,t)}screenFromWorld(e,t){return Fv(this.lastView,e,t)}pick(e,t){let{w:n,h:r}=this.lastView,i=this.lastViewport?.offsetX??0,a=this.lastViewport?.offsetY??0,o=this.lastViewport?.contentW??n,s=this.lastViewport?.contentH??r;Xv.set((e-i)/o*2-1,-((t-a)/s*2-1)),Zv.setFromCamera(Xv,this.worldCam);let c=Zv.intersectObjects(this.worldScene.children,!0),l=null;for(let e of c){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(!n)continue;let r=e.object.renderOrder??0;(!l||r>=l.order)&&(l={node:n,order:r})}return l?.node??null}boundsOf(e){let t=e._object2D;if(!t||(Qv.makeEmpty(),Qv.expandByObject(t),Qv.isEmpty())||(Qv.getSize(Yv),Yv.x===0&&Yv.y===0))return null;let n=this.screenFromWorld(Qv.min.x,-Qv.max.y),r=this.screenFromWorld(Qv.max.x,-Qv.min.y);return{x:n.x,y:n.y,w:r.x-n.x,h:r.y-n.y}}dispose(){this.engine.picker&&(this.engine.picker=null),this.disconnect();for(let e of[this.worldScene,this.uiScene])e.traverse(e=>{let t=e;if(!t.isMesh)return;let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)e?.map?.dispose(),e?.dispose()});this.webgl.dispose()}};function qv(e,t,n,r,i){e.position.set(t,-n,10),e.left=-r/2,e.right=r/2,e.top=i/2,e.bottom=-i/2,e.updateProjectionMatrix()}var Jv=new V,Yv=new U,Xv=new V,Zv=new Ku,Qv=new Bo;async function $v(e){Pv(),(e.gameplay??!0)&&H_();for(let[t,n]of Object.entries(e.behaviors??{}))it(t,n,{replace:!0});let t=new Et({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),n=ey(e.scene),r=kn(ey(n),{resolveScene:e.resolveScene,engine:t});t.setScene(r);let i=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&ty(r.root))&&(i=await tv(t));let a=[],o=e.keyboard??(typeof window<`u`?window:!1);o&&t.input.attachKeyboard(o),a.push(ny(t,r.root,e.canvas)),a.push(t.settings.bindAudio(t.audio)),a.push(t.settings.bindLocale(t.locale));let s=e.touch??`auto`;if(s!==!1){let n=e.touchContainer??e.canvas.parentElement??null;if(n){let r={force:s===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=Kn(t,n,r),o=t.sceneChanged.connect(()=>{i?.dispose(),i=Kn(t,n,r)});a.push(()=>{o(),i?.dispose()})}}let c=e._rendererFactory?e._rendererFactory(t,e.canvas):new Kv({canvas:e.canvas,engine:t,...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.antialias===void 0?{}:{antialias:e.antialias}}),l=e.debug??!1,u=e.editor??l,d=u===!0?{}:u||null,f={label:`✎ edit this scene`,run:async()=>{if(!d)return;let t=d.open??Dm,r=async t=>{await $v({...e,scene:t})};await Om(async()=>{p();try{await t({scene:n,play:r,exit:()=>r(n),...d.save?{save:d.save}:{},...d.library?{library:d.library===!0?Cm():d.library}:{}})}catch(e){console.error(`[incanto] could not open the editor:`,e),await r(n)}},`opening the editor…`)}};if(l){let n=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(n){let{attachDebugOverlay:r}=await ym(async()=>{let{attachDebugOverlay:e}=await import(`./debug-OR_wzFkM.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(t,{container:n,statsSource:()=>c.stats?.()??{},...d?{actions:[f]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&a.push(()=>i.dispose())}}t.start();function p(){Am([i?[`physics`,()=>i?.dispose()]:null,[`app cleanups`,()=>{for(let e of a)e()}],[`engine`,()=>t.dispose()],[`renderer`,()=>c.dispose()]])}return{engine:t,scene:r,sourceJson:n,renderer:c,physics:i,pick(e,n){return t.picker?.(e,n)??null},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...t.stats(),...c.stats?.()}},openEditor:d?f.run:null,dispose:p}}function ey(e){try{return structuredClone(e)}catch{throw new N(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function ty(e){if(e instanceof G_)return!0;for(let t of e.children)if(ty(t))return!0;return!1}function ny(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`&&r.push({target:window,type:`keydown`}),r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Ft&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}function ry(e,t){let n=e;if(typeof n?.frame?.width!=`number`||typeof n.frame.height!=`number`||!n.animations||Object.keys(n.animations).length===0)throw new N(`BAD_FORMAT`,`Library sprite metadata needs {frame: {width, height}, animations: {<name>: {start, end, frameRate, repeat}}} — got ${JSON.stringify(e).slice(0,120)}.`);let r={},i=null,a=null;for(let[e,t]of Object.entries(n.animations)){if(typeof t.start!=`number`||typeof t.end!=`number`||typeof t.frameRate!=`number`)throw new N(`BAD_FORMAT`,`Library animation '${e}' needs numeric start/end/frameRate, got ${JSON.stringify(t)}.`);let n=t.repeat===-1;r[e]={frames:[t.start,t.end],fps:t.frameRate,loop:n},i??=e,n&&a===null&&(a=e)}let o=t.autoplay??a??i;return{asset:{type:`spritesheet`,url:t.url,frameWidth:n.frame.width,frameHeight:n.frame.height},props:{sheet:`$${t.assetKey}`,autoplay:o,animations:r}}}var iy=e({createGame2D:()=>$v,enablePhysics2D:()=>tv}),ay=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),oy=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),sy=class extends ho{constructor(e){super(),this.weight=0,this.isBinary=!1,this.overrideBlink=`none`,this.overrideLookAt=`none`,this.overrideMouth=`none`,this._binds=[],this.name=`VRMExpression_${e}`,this.expressionName=e,this.type=`VRMExpression`,this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink===`block`?+(0<this.outputWeight):this.overrideBlink===`blend`?this.outputWeight:0}get overrideLookAtAmount(){return this.overrideLookAt===`block`?+(0<this.outputWeight):this.overrideLookAt===`blend`?this.outputWeight:0}get overrideMouthAmount(){return this.overrideMouth===`block`?+(0<this.outputWeight):this.overrideMouth===`blend`?this.outputWeight:0}get outputWeight(){return this.isBinary?+(this.weight>.5):this.weight}addBind(e){this._binds.push(e)}deleteBind(e){let t=this._binds.indexOf(e);t>=0&&this._binds.splice(t,1)}applyWeight(e){let t=this.outputWeight;t*=e?.multiplier??1,this.isBinary&&t<1&&(t=0),this._binds.forEach(e=>e.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(e=>e.clearAppliedWeight())}};function cy(e,t,n){let r=e.parser.json,i=r.nodes?.[t];if(i==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${t}] of glTF but the node doesn't exist`),null;let a=i.mesh;if(a==null)return null;let o=r.meshes?.[a];if(o==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${a}] of glTF but the mesh doesn't exist`),null;let s=o.primitives.length,c=[];return n.traverse(e=>{c.length<s&&e.isMesh&&c.push(e)}),c}function ly(e,t){return oy(this,null,function*(){return cy(e,t,yield e.parser.getDependency(`node`,t))})}function uy(e){return oy(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=cy(e,r,t);i!=null&&n.set(r,i)}),n})}var dy={Aa:`aa`,Ih:`ih`,Ou:`ou`,Ee:`ee`,Oh:`oh`,Blink:`blink`,Happy:`happy`,Angry:`angry`,Sad:`sad`,Relaxed:`relaxed`,LookUp:`lookUp`,Surprised:`surprised`,LookDown:`lookDown`,LookLeft:`lookLeft`,LookRight:`lookRight`,BlinkLeft:`blinkLeft`,BlinkRight:`blinkRight`,Neutral:`neutral`};function fy(e){return Math.max(Math.min(e,1),0)}var py=class e{constructor(){this.blinkExpressionNames=[`blink`,`blinkLeft`,`blinkRight`],this.lookAtExpressionNames=[`lookLeft`,`lookRight`,`lookUp`,`lookDown`],this.mouthExpressionNames=[`aa`,`ee`,`ih`,`oh`,`ou`],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},t=new Set(Object.values(dy));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(dy));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)||(e[n]=r)}),e}copy(e){return this._expressions.concat().forEach(e=>{this.unregisterExpression(e)}),e._expressions.forEach(e=>{this.registerExpression(e)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new e().copy(this)}getExpression(e){return this._expressionMap[e]??null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){let t=this._expressions.indexOf(e);t===-1&&console.warn(`VRMExpressionManager: The specified expressions is not registered`),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){return this.getExpression(e)?.weight??null}setValue(e,t){let n=this.getExpression(e);n&&(n.weight=fy(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){let t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(e=>{e.clearAppliedWeight()}),this._expressions.forEach(t=>{let n=1,r=t.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(n*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(n*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(n*=e.mouth),t.applyWeight({multiplier:n})})}_calculateWeightMultipliers(){let e=1,t=1,n=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,t-=r.overrideLookAtAmount,n-=r.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),n=Math.max(0,n),{blink:e,lookAt:t,mouth:n}}},my={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},hy={_Color:my.Color,_EmissionColor:my.EmissionColor,_ShadeColor:my.ShadeColor,_RimColor:my.RimColor,_OutlineColor:my.OutlineColor},gy=new K,_y=class e{constructor({material:e,type:t,targetValue:n,targetAlpha:r}){this.material=e,this.type=t,this.targetValue=n,this.targetAlpha=r??1;let i=this._initColorBindState(),a=this._initAlphaBindState();this._state={color:i,alpha:a}}applyWeight(e){let{color:t,alpha:n}=this._state;if(t!=null){let{propertyName:n,deltaValue:r}=t;this.material[n]?.add(gy.copy(r).multiplyScalar(e))}if(n!=null){let{propertyName:t,deltaValue:r}=n;this.material[t]!=null&&(this.material[t]+=r*e)}}clearAppliedWeight(){let{color:e,alpha:t}=this._state;if(e!=null){let{propertyName:t,initialValue:n}=e;this.material[t]?.copy(n)}if(t!=null){let{propertyName:e,initialValue:n}=t;this.material[e]!=null&&(this.material[e]=n)}}_initColorBindState(){let{material:e,type:t,targetValue:n}=this,r=this._getPropertyNameMap()?.[t]?.[0]??null;if(r==null)return console.warn(`Tried to add a material color bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type is not supported.`),null;let i=e[r].clone();return{propertyName:r,initialValue:i,deltaValue:new K(n.r-i.r,n.g-i.g,n.b-i.b)}}_initAlphaBindState(){let{material:e,type:t,targetAlpha:n}=this,r=this._getPropertyNameMap()?.[t]?.[1]??null;if(r==null&&n!==1)return console.warn(`Tried to add a material alpha bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type does not support alpha.`),null;if(r==null)return null;let i=e[r];return{propertyName:r,initialValue:i,deltaValue:n-i}}_getPropertyNameMap(){return Object.entries(e._propertyNameMapMap).find(([e])=>this.material[e]===!0)?.[1]??null}};_y._propertyNameMapMap={isMeshStandardMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null]},isMeshBasicMaterial:{color:[`color`,`opacity`]},isMToonMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null],outlineColor:[`outlineColorFactor`,null],matcapColor:[`matcapFactor`,null],rimColor:[`parametricRimColorFactor`,null],shadeColor:[`shadeColorFactor`,null]}};var vy=_y,yy=class{constructor({primitives:e,index:t,weight:n}){this.primitives=e,this.index=t,this.weight=n}applyWeight(e){this.primitives.forEach(t=>{t.morphTargetInfluences?.[this.index]!=null&&(t.morphTargetInfluences[this.index]+=this.weight*e)})}clearAppliedWeight(){this.primitives.forEach(e=>{e.morphTargetInfluences?.[this.index]!=null&&(e.morphTargetInfluences[this.index]=0)})}},by=new V,xy=class e{constructor({material:t,scale:n,offset:r}){this.material=t,this.scale=n,this.offset=r;let i=Object.entries(e._propertyNamesMap).find(([e])=>t[e]===!0)?.[1];i==null?(console.warn(`Tried to add a texture transform bind to the material ${t.name??`(no name)`} but the material is not supported.`),this._properties=[]):(this._properties=[],i.forEach(e=>{let i=t[e]?.clone();if(!i)return null;t[e]=i;let a=i.offset.clone(),o=i.repeat.clone(),s=r.clone().sub(a),c=n.clone().sub(o);this._properties.push({name:e,initialOffset:a,deltaOffset:s,initialScale:o,deltaScale:c})}))}applyWeight(e){this._properties.forEach(t=>{let n=this.material[t.name];n!==void 0&&(n.offset.add(by.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(by.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};xy._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var Sy=xy,Cy=new Set([`1.0`,`1.0-beta`]),wy=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return oy(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return oy(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return oy(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!Cy.has(r))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.expressions;if(!i)return null;let a=new Set(Object.values(dy)),o=new Map;i.preset!=null&&Object.entries(i.preset).forEach(([e,t])=>{if(t!=null){if(!a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`);return}o.set(e,t)}}),i.custom!=null&&Object.entries(i.custom).forEach(([e,t])=>{if(a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`);return}o.set(e,t)});let s=new py;return yield Promise.all(Array.from(o.entries()).map(t=>oy(this,[t],function*([t,n]){var r,i,a;let o=new sy(t);if(e.scene.add(o),o.isBinary=n.isBinary??!1,o.overrideBlink=n.overrideBlink??`none`,o.overrideLookAt=n.overrideLookAt??`none`,o.overrideMouth=n.overrideMouth??`none`,(r=n.morphTargetBinds)==null||r.forEach(t=>oy(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield ly(e,t.node),i=t.index;if(!r.every(e=>Array.isArray(e.morphTargetInfluences)&&i<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${n.name} attempts to index morph #${i} but not found.`);return}o.addBind(new yy({primitives:r,index:i,weight:t.weight??1}))})),n.materialColorBinds||n.textureTransformBinds){let t=[];e.scene.traverse(e=>{let n=e.material;n&&(Array.isArray(n)?t.push(...n):t.push(n))}),(i=n.materialColorBinds)==null||i.forEach(e=>oy(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new vy({material:t,type:e.type,targetValue:new K().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>oy(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new Sy({material:t,offset:new V().fromArray(e.offset??[0,0]),scale:new V().fromArray(e.scale??[1,1])}))})}))}s.registerExpression(o)}))),s})}_v0Import(t){return oy(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.blendShapeMaster;if(!i)return null;let a=new py,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>oy(this,null,function*(){let i=r.presetName,o=(i!=null&&e.v0v1PresetNameMap[i]||null)??r.name;if(o==null){console.warn(`VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression`);return}if(s.has(o)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${i} has duplicated entries. Ignoring the expression`);return}s.add(o);let c=new sy(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>oy(this,null,function*(){var i;if(e.mesh===void 0||e.index===void 0)return;let a=[];(i=n.nodes)==null||i.forEach((t,n)=>{t.mesh===e.mesh&&a.push(n)});let o=e.index;yield Promise.all(a.map(n=>oy(this,null,function*(){let i=yield ly(t,n);if(!i.every(e=>Array.isArray(e.morphTargetInfluences)&&o<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${r.name} attempts to index ${o}th morph but not found.`);return}c.addBind(new yy({primitives:i,index:o,weight:.01*(e.weight??100)}))})))}));let l=r.materialValues;l&&l.length!==0&&l.forEach(e=>{if(e.materialName===void 0||e.propertyName===void 0||e.targetValue===void 0)return;let n=[];t.scene.traverse(t=>{if(t.material){let r=t.material;Array.isArray(r)?n.push(...r.filter(t=>(t.name===e.materialName||t.name===e.materialName+` (Outline)`)&&n.indexOf(t)===-1)):r.name===e.materialName&&n.indexOf(r)===-1&&n.push(r)}});let r=e.propertyName;n.forEach(t=>{if(r===`_MainTex_ST`){let n=new V(e.targetValue[0],e.targetValue[1]),r=new V(e.targetValue[2],e.targetValue[3]);r.y=1-r.y-n.y,c.addBind(new Sy({material:t,scale:n,offset:r}));return}let n=hy[r];if(n){c.addBind(new vy({material:t,type:n,targetValue:new K().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}));return}console.warn(r+` is not supported`)})}),a.registerExpression(c)}))),a})}};wy.v0v1PresetNameMap={a:`aa`,e:`ee`,i:`ih`,o:`oh`,u:`ou`,blink:`blink`,joy:`happy`,angry:`angry`,sorrow:`sad`,fun:`relaxed`,lookup:`lookUp`,lookdown:`lookDown`,lookleft:`lookLeft`,lookright:`lookRight`,blink_l:`blinkLeft`,blink_r:`blinkRight`,neutral:`neutral`};var Ty=wy,Ey=class e{constructor(t,n){this._firstPersonOnlyLayer=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=e.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=t,this.meshAnnotations=n}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMFirstPerson: humanoid must be same in order to copy`);return this.meshAnnotations=e.meshAnnotations.map(e=>({meshes:e.meshes.concat(),type:e.type})),this}clone(){return new e(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:t=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:n=e.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||=(this._firstPersonOnlyLayer=t,this._thirdPersonOnlyLayer=n,this.meshAnnotations.forEach(e=>{e.meshes.forEach(t=>{e.type===`firstPersonOnly`?(t.layers.set(this._firstPersonOnlyLayer),t.traverse(e=>e.layers.set(this._firstPersonOnlyLayer))):e.type===`thirdPersonOnly`?(t.layers.set(this._thirdPersonOnlyLayer),t.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer))):e.type===`auto`&&this._createHeadlessModel(t)})}),!0)}_excludeTriangles(e,t,n,r){let i=0;if(t!=null&&t.length>0)for(let a=0;a<e.length;a+=3){let o=e[a],s=e[a+1],c=e[a+2],l=t[o],u=n[o];if(l[0]>0&&r.includes(u[0])||l[1]>0&&r.includes(u[1])||l[2]>0&&r.includes(u[2])||l[3]>0&&r.includes(u[3]))continue;let d=t[s],f=n[s];if(d[0]>0&&r.includes(f[0])||d[1]>0&&r.includes(f[1])||d[2]>0&&r.includes(f[2])||d[3]>0&&r.includes(f[3]))continue;let p=t[c],m=n[c];p[0]>0&&r.includes(m[0])||p[1]>0&&r.includes(m[1])||p[2]>0&&r.includes(m[2])||p[3]>0&&r.includes(m[3])||(e[i++]=o,e[i++]=s,e[i++]=c)}return i}_createErasedMesh(e,t){let n=new oc(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);let r=n.geometry,i=r.getAttribute(`skinIndex`),a=i instanceof Wu?[]:i.array,o=[];for(let e=0;e<a.length;e+=4)o.push([a[e],a[e+1],a[e+2],a[e+3]]);let s=r.getAttribute(`skinWeight`),c=s instanceof Wu?[]:s.array,l=[];for(let e=0;e<c.length;e+=4)l.push([c[e],c[e+1],c[e+2],c[e+3]]);let u=r.getIndex();if(!u)throw Error(`The geometry doesn't have an index buffer`);let d=Array.from(u.array),f=this._excludeTriangles(d,l,o,t),p=[];for(let e=0;e<f;e++)p[e]=d[e];return r.setIndex(p),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new dc(e.skeleton.bones,e.skeleton.boneInverses),new G),n}_createHeadlessModelForSkinnedMesh(e,t){let n=[];if(t.skeleton.bones.forEach((e,t)=>{this._isEraseTarget(e)&&n.push(t)}),!n.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(t,n);e.add(r)}_createHeadlessModel(e){if(e.type===`Group`)if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer));else{let t=new go;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(e=>e.type===`SkinnedMesh`).forEach(e=>{let n=e;this._createHeadlessModelForSkinnedMesh(t,n)})}else if(e.type===`SkinnedMesh`){let t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode(`head`)?!0:e.parent?this._isEraseTarget(e.parent):!1}};Ey.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,Ey.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var Dy=Ey,Oy=new Set([`1.0`,`1.0-beta`]),ky=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return oy(this,null,function*(){let t=e.userData.vrmHumanoid;if(t!==null){if(t===void 0)throw Error(`VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);e.userData.vrmFirstPerson=yield this._import(e,t)}})}_import(e,t){return oy(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return oy(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=n.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!Oy.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield uy(e);return Array.from(s.entries()).forEach(([e,t])=>{let n=(a?.meshAnnotations)?.find(t=>t.node===e);o.push({meshes:t,type:n?.type??`auto`})}),new Dy(t,o)})}_v0Import(e,t){return oy(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.firstPerson;if(!i)return null;let a=[],o=yield uy(e);return Array.from(o.entries()).forEach(([e,t])=>{let r=n.nodes[e],o=i.meshAnnotations?i.meshAnnotations.find(e=>e.mesh===r.mesh):void 0;a.push({meshes:t,type:this._convertV0FlagToV1Type(o?.firstPersonFlag)})}),new Dy(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},Ay=new U,jy=new U,My=new H,Ny=class extends go{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new Yu(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(e=>{e.geometry.dispose(),e.material.dispose()})}updateMatrixWorld(e){Array.from(this._boneAxesMap.entries()).forEach(([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(Ay,My,jy);let n=Ay.set(.1,.1,.1).divide(jy);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},Py=`hips.spine.chest.upperChest.neck.head.leftEye.rightEye.jaw.leftUpperLeg.leftLowerLeg.leftFoot.leftToes.rightUpperLeg.rightLowerLeg.rightFoot.rightToes.leftShoulder.leftUpperArm.leftLowerArm.leftHand.rightShoulder.rightUpperArm.rightLowerArm.rightHand.leftThumbMetacarpal.leftThumbProximal.leftThumbDistal.leftIndexProximal.leftIndexIntermediate.leftIndexDistal.leftMiddleProximal.leftMiddleIntermediate.leftMiddleDistal.leftRingProximal.leftRingIntermediate.leftRingDistal.leftLittleProximal.leftLittleIntermediate.leftLittleDistal.rightThumbMetacarpal.rightThumbProximal.rightThumbDistal.rightIndexProximal.rightIndexIntermediate.rightIndexDistal.rightMiddleProximal.rightMiddleIntermediate.rightMiddleDistal.rightRingProximal.rightRingIntermediate.rightRingDistal.rightLittleProximal.rightLittleIntermediate.rightLittleDistal`.split(`.`),Fy={hips:null,spine:`hips`,chest:`spine`,upperChest:`chest`,neck:`upperChest`,head:`neck`,leftEye:`head`,rightEye:`head`,jaw:`head`,leftUpperLeg:`hips`,leftLowerLeg:`leftUpperLeg`,leftFoot:`leftLowerLeg`,leftToes:`leftFoot`,rightUpperLeg:`hips`,rightLowerLeg:`rightUpperLeg`,rightFoot:`rightLowerLeg`,rightToes:`rightFoot`,leftShoulder:`upperChest`,leftUpperArm:`leftShoulder`,leftLowerArm:`leftUpperArm`,leftHand:`leftLowerArm`,rightShoulder:`upperChest`,rightUpperArm:`rightShoulder`,rightLowerArm:`rightUpperArm`,rightHand:`rightLowerArm`,leftThumbMetacarpal:`leftHand`,leftThumbProximal:`leftThumbMetacarpal`,leftThumbDistal:`leftThumbProximal`,leftIndexProximal:`leftHand`,leftIndexIntermediate:`leftIndexProximal`,leftIndexDistal:`leftIndexIntermediate`,leftMiddleProximal:`leftHand`,leftMiddleIntermediate:`leftMiddleProximal`,leftMiddleDistal:`leftMiddleIntermediate`,leftRingProximal:`leftHand`,leftRingIntermediate:`leftRingProximal`,leftRingDistal:`leftRingIntermediate`,leftLittleProximal:`leftHand`,leftLittleIntermediate:`leftLittleProximal`,leftLittleDistal:`leftLittleIntermediate`,rightThumbMetacarpal:`rightHand`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbDistal:`rightThumbProximal`,rightIndexProximal:`rightHand`,rightIndexIntermediate:`rightIndexProximal`,rightIndexDistal:`rightIndexIntermediate`,rightMiddleProximal:`rightHand`,rightMiddleIntermediate:`rightMiddleProximal`,rightMiddleDistal:`rightMiddleIntermediate`,rightRingProximal:`rightHand`,rightRingIntermediate:`rightRingProximal`,rightRingDistal:`rightRingIntermediate`,rightLittleProximal:`rightHand`,rightLittleIntermediate:`rightLittleProximal`,rightLittleDistal:`rightLittleIntermediate`};function Iy(e){return e.invert?e.invert():e.inverse(),e}var Ly=new U,Ry=new H,zy=class{constructor(e){this.humanBones=e,this.restPose=this.getAbsolutePose()}getAbsolutePose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);r&&(Ly.copy(r.position),Ry.copy(r.quaternion),e[n]={position:Ly.toArray(),rotation:Ry.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;Ly.set(0,0,0),Ry.identity();let i=this.restPose[n];i?.position&&Ly.fromArray(i.position).negate(),i?.rotation&&Iy(Ry.fromArray(i.rotation)),Ly.add(r.position),Ry.premultiply(r.quaternion),e[n]={position:Ly.toArray(),rotation:Ry.toArray()}}),e}setPose(e){Object.entries(e).forEach(([e,t])=>{let n=e,r=this.getBoneNode(n);if(!r)return;let i=this.restPose[n];i&&(t?.position&&(r.position.fromArray(t.position),i.position&&r.position.add(Ly.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(Ry.fromArray(i.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([e,t])=>{let n=this.getBoneNode(e);n&&(t?.position&&n.position.fromArray(t.position),t?.rotation&&n.quaternion.fromArray(t.rotation))})}getBone(e){return this.humanBones[e]??void 0}getBoneNode(e){return this.humanBones[e]?.node??null}},By=new U,Vy=new H,Hy=new U,Uy=class e extends zy{static _setupTransforms(e){let t=new ho;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};Py.forEach(t=>{var o;let s=e.getBoneNode(t);if(s){let e=new U,c=new H;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(e,c,By),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new H;(o=s.parent)==null||o.matrixWorld.decompose(By,l,By),a[t]=l}});let o={};return Py.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=Fy[a],a!=null);)s=n[a];let c=new ho;c.name=`Normalized_`+i.name,(a?o[a]?.node:t).add(c),c.position.copy(e),s&&c.position.sub(s),o[r]={node:c}}}),{rigBones:o,root:t,parentWorldRotations:a,boneRotations:i}}constructor(t){let{rigBones:n,root:r,parentWorldRotations:i,boneRotations:a}=e._setupTransforms(t);super(n),this.original=t,this.root=r,this._parentWorldRotations=i,this._boneRotations=a}update(){Py.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=Vy.copy(r).invert(),a=this._boneRotations[e];if(t.quaternion.copy(n.quaternion).multiply(r).premultiply(i).multiply(a),e===`hips`){let e=n.getWorldPosition(Hy);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},Wy=class e{get restPose(){return console.warn(`VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead.`),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,t){this.autoUpdateHumanBones=t?.autoUpdateHumanBones??!0,this._rawHumanBones=new zy(e),this._normalizedHumanBones=new Uy(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new zy(e.humanBones),this._normalizedHumanBones=new Uy(this._rawHumanBones),this}clone(){return new e(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn(`VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead.`),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn(`VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead.`),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn(`VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead.`),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn(`VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead.`),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn(`VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead.`),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn(`VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead.`),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},Gy={Hips:`hips`,Spine:`spine`,Head:`head`,LeftUpperLeg:`leftUpperLeg`,LeftLowerLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,RightUpperLeg:`rightUpperLeg`,RightLowerLeg:`rightLowerLeg`,RightFoot:`rightFoot`,LeftUpperArm:`leftUpperArm`,LeftLowerArm:`leftLowerArm`,LeftHand:`leftHand`,RightUpperArm:`rightUpperArm`,RightLowerArm:`rightLowerArm`,RightHand:`rightHand`},Ky=new Set([`1.0`,`1.0-beta`]),qy={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},Jy=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return oy(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return oy(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return oy(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!Ky.has(r))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.humanoid;if(!i)return null;let a=i.humanBones.leftThumbIntermediate!=null||i.humanBones.rightThumbIntermediate!=null,o={};i.humanBones!=null&&(yield Promise.all(Object.entries(i.humanBones).map(e=>oy(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=qy[n];e!=null&&(n=e)}let i=yield this.parser.getDependency(`node`,r);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${n} (index = ${r}) does not exist`);return}o[n]={node:i}}))));let s=new Wy(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new Ny(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return oy(this,null,function*(){let t=this.parser.json.extensions?.VRM;if(!t)return null;let n=t.humanoid;if(!n)return null;let r={};n.humanBones!=null&&(yield Promise.all(n.humanBones.map(e=>oy(this,null,function*(){let t=e.bone,n=e.node;if(t==null||n==null)return;let i=yield this.parser.getDependency(`node`,n);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${t} (index = ${n}) does not exist`);return}let a=qy[t]??t;if(r[a]!=null){console.warn(`Multiple bone entries for ${a} detected (index = ${n}), ignoring duplicated entries.`);return}r[a]={node:i}}))));let i=new Wy(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new Ny(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(Gy).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},Yy=class extends J{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new q(new Float32Array(195),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new q(new Uint16Array(189),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,e=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let e=0;e<64;e++){let t=e/63*this._currentTheta;this._attrPos.setXYZ(e+1,this._currentRadius*Math.sin(t),0,this._currentRadius*Math.cos(t))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<63;e++)this._attrIndex.setXYZ(e*3,0,e+1,e+2);this._attrIndex.needsUpdate=!0}},Xy=class extends J{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new U,this._currentTail=new U,this._attrPos=new q(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new q(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},Zy=new H,Qy=new H,$y=new U,eb=new U,tb=Math.sqrt(2)/2,nb=new H(0,0,-tb,tb),rb=new U(0,1,0),ib=class extends go{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new Yy;e.radius=.5;let t=new Is({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new Js(e,t),this.add(this._meshPitch)}{let e=new Yy;e.radius=.5;let t=new Is({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new Js(e,t),this.add(this._meshYaw)}{let e=new Xy;e.radius=.1;let t=new kc({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new Vc(e,t),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(e){let t=ya.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=ya.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition($y),this.vrmLookAt.getLookAtWorldQuaternion(Zy),Zy.multiply(this.vrmLookAt.getFaceFrontQuaternion(Qy)),this._meshYaw.position.copy($y),this._meshYaw.quaternion.copy(Zy),this._meshPitch.position.copy($y),this._meshPitch.quaternion.copy(Zy),this._meshPitch.quaternion.multiply(Qy.setFromAxisAngle(rb,t)),this._meshPitch.quaternion.multiply(nb);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(eb).sub($y),this._lineTarget.geometry.tail.copy(eb),this._lineTarget.geometry.update(),this._lineTarget.position.copy($y)),super.updateMatrixWorld(e)}},ab=new U,ob=new U;function sb(e,t){return e.matrixWorld.decompose(ab,t,ob),t}function cb(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function lb(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var ub=new U(0,0,1),db=new U,fb=new U,pb=new U,mb=new H,hb=new H,gb=new H,_b=new H,vb=new Za,yb=class e{constructor(e,t){this.offsetFromHeadBone=new U,this.autoUpdate=!0,this.faceFront=new U(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new H)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn(`VRMLookAt: euler is deprecated. use getEuler() instead.`),this.getEuler(new Za)}getEuler(e){return e.set(ya.DEG2RAD*this._pitch,ya.DEG2RAD*this._yaw,0,`YXZ`)}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMLookAt: humanoid must be same in order to copy`);return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new e(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let t=this.humanoid.getRawBoneNode(`head`);return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){return sb(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(ub)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=cb(this.faceFront);return vb.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(vb).premultiply(_b.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(hb),this.getFaceFrontQuaternion(gb),e.copy(ub).applyQuaternion(hb).applyQuaternion(gb).applyEuler(this.getEuler(vb))}lookAt(e){let t=mb.copy(this._restHeadWorldQuaternion).multiply(Iy(this.getLookAtWorldQuaternion(hb))),n=this.getLookAtWorldPosition(fb),r=pb.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=cb(this.faceFront),[o,s]=cb(r),c=lb(o-i),l=lb(a-s);this._yaw=ya.RAD2DEG*c,this._pitch=ya.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(db)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};yb.EULER_ORDER=`YXZ`;var bb=yb,xb=new U(0,0,1),Sb=new H,Cb=new H,wb=new Za(0,0,0,`YXZ`),Tb=class{constructor(e,t,n,r,i){this.humanoid=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i,this.faceFront=new U(0,0,1),this._restQuatLeftEye=new H,this._restQuatRightEye=new H,this._restLeftEyeParentWorldQuat=new H,this._restRightEyeParentWorldQuat=new H;let a=this.humanoid.getRawBoneNode(`leftEye`),o=this.humanoid.getRawBoneNode(`rightEye`);a&&(this._restQuatLeftEye.copy(a.quaternion),sb(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),sb(o.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(e,t){let n=this.humanoid.getRawBoneNode(`leftEye`),r=this.humanoid.getRawBoneNode(`rightEye`),i=this.humanoid.getNormalizedBoneNode(`leftEye`),a=this.humanoid.getNormalizedBoneNode(`rightEye`);n&&(t<0?wb.x=-ya.DEG2RAD*this.rangeMapVerticalDown.map(-t):wb.x=ya.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?wb.y=-ya.DEG2RAD*this.rangeMapHorizontalInner.map(-e):wb.y=ya.DEG2RAD*this.rangeMapHorizontalOuter.map(e),Sb.setFromEuler(wb),this._getWorldFaceFrontQuat(Cb),i.quaternion.copy(Cb).multiply(Sb).multiply(Cb.invert()),Sb.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(Sb).premultiply(Sb.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?wb.x=-ya.DEG2RAD*this.rangeMapVerticalDown.map(-t):wb.x=ya.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?wb.y=-ya.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):wb.y=ya.DEG2RAD*this.rangeMapHorizontalInner.map(e),Sb.setFromEuler(wb),this._getWorldFaceFrontQuat(Cb),a.quaternion.copy(Cb).multiply(Sb).multiply(Cb.invert()),Sb.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(Sb).premultiply(Sb.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=ya.RAD2DEG*e.y,n=ya.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(xb)<.01)return e.identity();let[t,n]=cb(this.faceFront);return wb.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(wb)}};Tb.type=`bone`;var Eb=class{constructor(e,t,n,r,i){this.expressions=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i}applyYawPitch(e,t){t<0?(this.expressions.setValue(`lookDown`,0),this.expressions.setValue(`lookUp`,this.rangeMapVerticalUp.map(-t))):(this.expressions.setValue(`lookUp`,0),this.expressions.setValue(`lookDown`,this.rangeMapVerticalDown.map(t))),e<0?(this.expressions.setValue(`lookLeft`,0),this.expressions.setValue(`lookRight`,this.rangeMapHorizontalOuter.map(-e))):(this.expressions.setValue(`lookRight`,0),this.expressions.setValue(`lookLeft`,this.rangeMapHorizontalOuter.map(e)))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=ya.RAD2DEG*e.y,n=ya.RAD2DEG*e.x;this.applyYawPitch(t,n)}};Eb.type=`expression`;var Db=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*fy(e/this.inputMaxValue)}},Ob=new Set([`1.0`,`1.0-beta`]),kb=.01,Ab=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return oy(this,null,function*(){let t=e.userData.vrmHumanoid;if(t===null)return;if(t===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);let n=e.userData.vrmExpressionManager;if(n!==null){if(n===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first`);e.userData.vrmLookAt=yield this._import(e,t,n)}})}_import(e,t,n){return oy(this,null,function*(){return t==null||n==null?null:(yield this._v1Import(e,t,n))||(yield this._v0Import(e,t,n))||null})}_v1Import(e,t,n){return oy(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=e.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!Ob.has(i))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.lookAt;if(!a)return null;let o=a.type===`expression`?1:10,s=this._v1ImportRangeMap(a.rangeMapHorizontalInner,o),c=this._v1ImportRangeMap(a.rangeMapHorizontalOuter,o),l=this._v1ImportRangeMap(a.rangeMapVerticalDown,o),u=this._v1ImportRangeMap(a.rangeMapVerticalUp,o),d;d=a.type===`expression`?new Eb(n,s,c,l,u):new Tb(t,s,c,l,u);let f=this._importLookAt(t,d);return f.offsetFromHeadBone.fromArray(a.offsetFromHeadBone??[0,.06,0]),f})}_v1ImportRangeMap(e,t){let n=e?.inputMaxValue??90,r=e?.outputScale??t;return n<kb&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=kb),new Db(n,r)}_v0Import(e,t,n){return oy(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let r=e.firstPerson;if(!r)return null;let i=r.lookAtTypeName===`BlendShape`?1:10,a=this._v0ImportDegreeMap(r.lookAtHorizontalInner,i),o=this._v0ImportDegreeMap(r.lookAtHorizontalOuter,i),s=this._v0ImportDegreeMap(r.lookAtVerticalDown,i),c=this._v0ImportDegreeMap(r.lookAtVerticalUp,i),l;l=r.lookAtTypeName===`BlendShape`?new Eb(n,a,o,s,c):new Tb(t,a,o,s,c);let u=this._importLookAt(t,l);return r.firstPersonBoneOffset?u.offsetFromHeadBone.set(r.firstPersonBoneOffset.x??0,r.firstPersonBoneOffset.y??.06,-(r.firstPersonBoneOffset.z??0)):u.offsetFromHeadBone.set(0,.06,0),u.faceFront.set(0,0,-1),l instanceof Tb&&l.faceFront.set(0,0,-1),u})}_v0ImportDegreeMap(e,t){let n=e?.curve;JSON.stringify(n)!==`[0,0,0,1,1,1,1,0]`&&console.warn(`Curves of LookAtDegreeMap defined in VRM 0.0 are not supported`);let r=e?.xRange??90,i=e?.yRange??t;return r<kb&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=kb),new Db(r,i)}_importLookAt(e,t){let n=new bb(e,t);if(this.helperRoot){let e=new ib(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function jb(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}var Mb=new Set([`1.0`,`1.0-beta`]),Nb=class{get name(){return`VRMMetaLoaderPlugin`}constructor(e,t){this.parser=e,this.needThumbnailImage=t?.needThumbnailImage??!1,this.acceptLicenseUrls=t?.acceptLicenseUrls??[`https://vrm.dev/licenses/1.0/`],this.acceptV0Meta=t?.acceptV0Meta??!0}afterRoot(e){return oy(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return oy(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return oy(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let t=e.extensions?.VRMC_vrm;if(t==null)return null;let n=t.specVersion;if(!Mb.has(n))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${n}"`),null;let r=t.meta;if(!r)return null;let i=r.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(i))throw Error(`VRMMetaLoaderPlugin: The license url "${i}" is not accepted`);let a;return this.needThumbnailImage&&r.thumbnailImage!=null&&(a=(yield this._extractGLTFImage(r.thumbnailImage))??void 0),{metaVersion:`1`,name:r.name,version:r.version,authors:r.authors,copyrightInformation:r.copyrightInformation,contactInformation:r.contactInformation,references:r.references,thirdPartyLicenses:r.thirdPartyLicenses,thumbnailImage:a,licenseUrl:r.licenseUrl,avatarPermission:r.avatarPermission,allowExcessivelyViolentUsage:r.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:r.allowExcessivelySexualUsage,commercialUsage:r.commercialUsage,allowPoliticalOrReligiousUsage:r.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:r.allowAntisocialOrHateUsage,creditNotation:r.creditNotation,allowRedistribution:r.allowRedistribution,modification:r.modification,otherLicenseUrl:r.otherLicenseUrl}})}_v0Import(e){return oy(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let t=e.meta;if(!t)return null;if(!this.acceptV0Meta)throw Error(`VRMMetaLoaderPlugin: Attempted to load VRM0.0 meta but acceptV0Meta is false`);let n;return this.needThumbnailImage&&t.texture!=null&&t.texture!==-1&&(n=yield this.parser.getDependency(`texture`,t.texture)),{metaVersion:`0`,allowedUserName:t.allowedUserName,author:t.author,commercialUssageName:t.commercialUssageName,contactInformation:t.contactInformation,licenseName:t.licenseName,otherLicenseUrl:t.otherLicenseUrl,otherPermissionUrl:t.otherPermissionUrl,reference:t.reference,sexualUssageName:t.sexualUssageName,texture:n??void 0,title:t.title,version:t.version,violentUssageName:t.violentUssageName}})}_extractGLTFImage(e){return oy(this,null,function*(){let t=this.parser.json.images?.[e];if(t==null)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image doesn't exist`),null;let n=t.uri;if(t.bufferView!=null){let e=yield this.parser.getDependency(`bufferView`,t.bufferView),r=new Blob([e],{type:t.mimeType});n=URL.createObjectURL(r)}return n==null?(console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image couldn't load properly`),null):yield new Zl().loadAsync(jb(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},Pb=class{constructor(e){this.scene=e.scene,this.meta=e.meta,this.humanoid=e.humanoid,this.expressionManager=e.expressionManager,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt}update(e){this.humanoid.update(),this.lookAt&&this.lookAt.update(e),this.expressionManager&&this.expressionManager.update()}},Fb=class extends Pb{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach(t=>{t.update&&t.update(e)})}},Ib=Object.defineProperty,Lb=Object.getOwnPropertySymbols,Rb=Object.prototype.hasOwnProperty,zb=Object.prototype.propertyIsEnumerable,Bb=(e,t,n)=>t in e?Ib(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Vb=(e,t)=>{for(var n in t||={})Rb.call(t,n)&&Bb(e,n,t[n]);if(Lb)for(var n of Lb(t))zb.call(t,n)&&Bb(e,n,t[n]);return e},Hb=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});function Ub(e,t){e.colorSpace=t}var Wb=class{get pending(){return Promise.all(this._pendings)}constructor(e,t){this._parser=e,this._materialParams=t,this._pendings=[]}assignPrimitive(e,t){t!=null&&(this._materialParams[e]=t)}assignColor(e,t,n){if(t!=null){let r=new K().fromArray(t);n&&r.convertSRGBToLinear(),this._materialParams[e]=r}}assignTexture(e,t,n){return Hb(this,null,function*(){let r=Hb(this,null,function*(){if(t!=null){let r=yield this._parser.assignTexture(this._materialParams,e,t);if(r==null){console.warn(`GLTFMToonMaterialParamsAssignHelper: Failed to load texture. The rendering result may be wrong`);return}n&&Ub(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return Hb(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},Gb=`// #define PHONG
5757
5757
 
5758
5758
  varying vec3 vViewPosition;
5759
5759
 
@@ -8410,7 +8410,7 @@ void main() {
8410
8410
  #include <tonemapping_fragment>
8411
8411
  #include <colorspace_fragment>
8412
8412
 
8413
- }`};var fN=[`type`,`sunPosition`,`elevationDeg`,`azimuthDeg`,`turbidity`,`rayleigh`],pN=[`color`,`near`,`far`],mN=[`coverage`,`density`,`base`,`top`,`color`,`shadeColor`,`speed`,`scale`],hN=[`threshold`,`strength`],gN=[`vignette`,`saturation`,`contrast`],_N=[`mapSize`,`radius`,`static`],vN=[1024,2048],yN=2,bN=1,xN=50,SN=800,CN=`#cfd8e0`,wN=Math.PI/180;function TN(e){return{exposure:kN(e?.exposure),sky:AN(e?.sky),fog:jN(e?.fog,e?.sky!==void 0),clouds:MN(e?.clouds),bloom:NN(e?.bloom),post:PN(e?.post),shadows:FN(e?.shadows)}}function EN(e,t){let n=(90-e)*wN,r=t*wN;return[Math.sin(n)*Math.sin(r),Math.cos(n),Math.sin(n)*Math.cos(r)]}function DN(e){let[t,n,r]=e.sunPosition,i=Math.hypot(t,n,r)||1;return[t/i,n/i,r/i]}function ON(e){let t=[191,213,232],n=[233,228,217],r=[242,201,150],i=RN((e.turbidity-yN)/8),a=DN(e),o=RN((18-Math.asin(LN(a[1],-1,1))/wN)/18)*.8,s=e=>Math.round(zN(zN(t[e],n[e],i),r[e],o));return`#${[s(0),s(1),s(2)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}function kN(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw new N(`BAD_FORMAT`,`environment.exposure must be a finite number > 0 (tone-mapping exposure, default 1), got ${JSON.stringify(e)}.`,{prop:`exposure`});return e}function AN(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.sky must be an object ({ type?: "atmosphere", sunPosition? | elevationDeg?+azimuthDeg?, turbidity?, rayleigh? }), got ${JSON.stringify(e)}.`,{prop:`sky`});let t=e;for(let e of Object.keys(t))if(!fN.includes(e))throw new N(`BAD_FORMAT`,`environment.sky has unknown key '${e}'. Valid keys: [${fN.join(`, `)}].`,{prop:`sky`,validOptions:fN});if(t.type!==void 0&&t.type!==`atmosphere`)throw new N(`BAD_FORMAT`,`environment.sky.type must be 'atmosphere' (the only sky type so far), got ${JSON.stringify(t.type)}.`,{prop:`sky`,validOptions:[`atmosphere`]});let n=t.elevationDeg!==void 0||t.azimuthDeg!==void 0;if(t.sunPosition!==void 0&&n)throw new N(`BAD_FORMAT`,`environment.sky takes sunPosition OR elevationDeg/azimuthDeg, not both.`,{prop:`sky`,validOptions:[`sunPosition`,`elevationDeg+azimuthDeg`]});let r;if(t.sunPosition!==void 0){let e=t.sunPosition;if(!Array.isArray(e)||e.length!==3||!e.every(e=>typeof e==`number`&&Number.isFinite(e))||Math.hypot(e[0],e[1],e[2])===0)throw new N(`BAD_FORMAT`,`environment.sky.sunPosition must be a non-zero [x, y, z] vector, got ${JSON.stringify(e)}.`,{prop:`sky`});r=[e[0],e[1],e[2]]}else{let e=IN(t.elevationDeg,32,`sky.elevationDeg`),n=IN(t.azimuthDeg,135,`sky.azimuthDeg`);if(e<-90||e>90)throw new N(`BAD_FORMAT`,`environment.sky.elevationDeg must be in [-90, 90] (degrees above the horizon), got ${e}.`,{prop:`sky`});r=EN(e,n)}let i=IN(t.turbidity,yN,`sky.turbidity`);if(i<=0)throw new N(`BAD_FORMAT`,`environment.sky.turbidity must be > 0 (atmospheric haze; 2 ≈ clear day), got ${i}.`,{prop:`sky`});let a=IN(t.rayleigh,bN,`sky.rayleigh`);if(a<0)throw new N(`BAD_FORMAT`,`environment.sky.rayleigh must be >= 0 (Rayleigh scattering; 1 ≈ earth-like), got ${a}.`,{prop:`sky`});return{sunPosition:r,turbidity:i,rayleigh:a}}function jN(e,t){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.fog must be an object ({ color?, near?, far? }), got ${JSON.stringify(e)}.`,{prop:`fog`});let n=e;for(let e of Object.keys(n))if(!pN.includes(e))throw new N(`BAD_FORMAT`,`environment.fog has unknown key '${e}'. Valid keys: [${pN.join(`, `)}].`,{prop:`fog`,validOptions:pN});if(n.color!==void 0&&typeof n.color!=`string`)throw new N(`BAD_FORMAT`,`environment.fog.color must be a hex color string, got ${JSON.stringify(n.color)}.`,{prop:`fog`});let r=IN(n.near,xN,`fog.near`),i=IN(n.far,SN,`fog.far`);if(r<0)throw new N(`BAD_FORMAT`,`environment.fog.near must be >= 0 meters, got ${r}.`,{prop:`fog`});if(i<=r)throw new N(`BAD_FORMAT`,`environment.fog.far must be > near (got near ${r}, far ${i}).`,{prop:`fog`});return{color:n.color??(t?``:CN),near:r,far:i}}function MN(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.clouds must be an object ({ coverage?, density?, base?, top?, color?, shadeColor?, speed?, scale? }), got ${JSON.stringify(e)}.`,{prop:`clouds`});let t=e;for(let e of Object.keys(t))if(!mN.includes(e))throw new N(`BAD_FORMAT`,`environment.clouds has unknown key '${e}'. Valid keys: [${mN.join(`, `)}].`,{prop:`clouds`,validOptions:mN});for(let e of[`color`,`shadeColor`])if(t[e]!==void 0&&typeof t[e]!=`string`)throw new N(`BAD_FORMAT`,`environment.clouds.${e} must be a hex color string, got ${JSON.stringify(t[e])}.`,{prop:`clouds`});let n=IN(t.coverage,.5,`clouds.coverage`);if(n<0||n>1)throw new N(`BAD_FORMAT`,`environment.clouds.coverage must be in [0, 1] (how much sky is cloudy), got ${n}.`,{prop:`clouds`});let r=IN(t.density,1,`clouds.density`);if(r<0)throw new N(`BAD_FORMAT`,`environment.clouds.density must be >= 0 (optical thickness), got ${r}.`,{prop:`clouds`});let i=IN(t.base,120,`clouds.base`),a=IN(t.top,320,`clouds.top`);if(a<=i)throw new N(`BAD_FORMAT`,`environment.clouds.top must be > base (got base ${i}, top ${a}).`,{prop:`clouds`});let o=IN(t.speed,1,`clouds.speed`),s=IN(t.scale,240,`clouds.scale`);if(s<=0)throw new N(`BAD_FORMAT`,`environment.clouds.scale must be > 0 (feature size in world units), got ${s}.`,{prop:`clouds`});return{coverage:n,density:r,base:i,top:a,color:t.color??`#ffffff`,shadeColor:t.shadeColor??`#9fb0c8`,speed:o,scale:s}}function NN(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.bloom must be an object ({ threshold?, strength? }), got ${JSON.stringify(e)}.`,{prop:`bloom`});let t=e;for(let e of Object.keys(t))if(!hN.includes(e))throw new N(`BAD_FORMAT`,`environment.bloom has unknown key '${e}'. Valid keys: [${hN.join(`, `)}].`,{prop:`bloom`,validOptions:hN});let n=IN(t.threshold,1,`bloom.threshold`);if(n<0||n>8)throw new N(`BAD_FORMAT`,`environment.bloom.threshold must be in [0, 8] (linear-HDR luminance; 1 = white), got ${n}.`,{prop:`bloom`});let r=IN(t.strength,.8,`bloom.strength`);if(r<0)throw new N(`BAD_FORMAT`,`environment.bloom.strength must be >= 0, got ${r}.`,{prop:`bloom`});return{threshold:n,strength:r}}function PN(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.post must be an object ({ vignette?, saturation?, contrast? }), got ${JSON.stringify(e)}.`,{prop:`post`});let t=e;for(let e of Object.keys(t))if(!gN.includes(e))throw new N(`BAD_FORMAT`,`environment.post has unknown key '${e}'. Valid keys: [${gN.join(`, `)}].`,{prop:`post`,validOptions:gN});let n=IN(t.vignette,0,`post.vignette`);if(n<0||n>1)throw new N(`BAD_FORMAT`,`environment.post.vignette must be in [0, 1], got ${n}.`,{prop:`post`});let r=IN(t.saturation,1,`post.saturation`);if(r<0||r>4)throw new N(`BAD_FORMAT`,`environment.post.saturation must be in [0, 4] (1 = neutral), got ${r}.`,{prop:`post`});let i=IN(t.contrast,1,`post.contrast`);if(i<.2||i>3)throw new N(`BAD_FORMAT`,`environment.post.contrast must be in [0.2, 3] (1 = neutral), got ${i}.`,{prop:`post`});return{vignette:n,saturation:r,contrast:i}}function FN(e){if(e===void 0)return null;if(e===!1)return!1;if(e===!0)return{mapSize:2048,radius:1,static:!1};if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.shadows must be true, false or an object ({ mapSize?, radius? }), got ${JSON.stringify(e)}.`,{prop:`shadows`});let t=e;for(let e of Object.keys(t))if(!_N.includes(e))throw new N(`BAD_FORMAT`,`environment.shadows has unknown key '${e}'. Valid keys: [${_N.join(`, `)}].`,{prop:`shadows`,validOptions:_N});let n=t.mapSize===void 0?2048:t.mapSize;if(!vN.includes(n))throw new N(`BAD_FORMAT`,`environment.shadows.mapSize must be one of [${vN.join(`, `)}], got ${JSON.stringify(t.mapSize)}.`,{prop:`shadows`,validOptions:vN.map(String)});let r=IN(t.radius,1,`shadows.radius`);if(r<0)throw new N(`BAD_FORMAT`,`environment.shadows.radius must be >= 0, got ${r}.`,{prop:`shadows`});let i=t.static===void 0?!1:t.static;if(typeof i!=`boolean`)throw new N(`BAD_FORMAT`,`environment.shadows.static must be a boolean, got ${JSON.stringify(t.static)}.`,{prop:`shadows`});return{mapSize:n,radius:r,static:i}}function IN(e,t,n){if(e===void 0)return t;if(typeof e!=`number`||!Number.isFinite(e))throw new N(`BAD_FORMAT`,`environment.${n} must be a finite number, got ${JSON.stringify(e)}.`,{prop:n});return e}function LN(e,t,n){return Math.min(Math.max(e,t),n)}function RN(e){return LN(e,0,1)}function zN(e,t,n){return e+(t-e)*n}var BN=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,VN={apartment:`lebombo_1k.hdr`,city:`potsdamer_platz_1k.hdr`,dawn:`kiara_1_dawn_1k.hdr`,forest:`forest_slope_1k.hdr`,lobby:`st_fagans_interior_1k.hdr`,night:`dikhololo_night_1k.hdr`,park:`rooitou_park_1k.hdr`,studio:`studio_small_03_1k.hdr`,sunset:`venice_sunset_1k.hdr`,warehouse:`empty_warehouse_01_1k.hdr`};function HN(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=VN[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(VN).join(`, `)}.`);return`${BN}/${t}`}return null}var UN=75,WN=class{scene;ambient=new bu(`#ffffff`,0);envKey=null;config=TN(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new wo(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new K;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?DN(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get post(){return this.config.post}get sceneFog(){return this.scene.fog instanceof wo?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=TN(e));let r=this.config,i=e?.ambient;if(this.ambient.color.set(i?.color??`#ffffff`),this.ambient.intensity=i?.intensity??0,t&&(t.toneMappingExposure=r.exposure,t.shadowMap.enabled=r.shadows!==!1,r.shadows!==!1&&r.shadows!==null&&r.shadows.static?t.shadowMap.autoUpdate&&(t.shadowMap.autoUpdate=!1,t.shadowMap.needsUpdate=!0):t.shadowMap.autoUpdate||(t.shadowMap.autoUpdate=!0)),this.applyHdri(e),this.applySky(r.sky,t),this._sky&&(this._sky.visible=!0),this.applyFog(r),this.scene.environment=this.hdriTexture??this.skyEnvTarget?.texture??null,this.scene.environmentIntensity=(this.scene.environment===this.skyEnvTarget?.texture&&this.skyEnvTarget?.55:1)*GN(e?.iblIntensity),e?.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new K(t):null}}applySunLight(e,t=null){if(!e)return;let n=this.sunDirection;if(t){let r=e.position.length()||100,i,a,o;if(n)[i,a,o]=n;else{i=e.position.x-e.target.position.x,a=e.position.y-e.target.position.y,o=e.position.z-e.target.position.z;let t=Math.hypot(i,a,o)||1;i/=t,a/=t,o/=t}e.target.position.set(t.x,t.y,t.z),e.target.updateMatrixWorld(),e.position.set(t.x+i*r,t.y+a*r,t.z+o*r)}else if(n){let t=e.position.length()||100;e.position.set(n[0],n[1],n[2]).multiplyScalar(t)}let r=this.config.shadows;if(r&&typeof r==`object`){if(!e.castShadow){let t=e.shadow.camera;`left`in t&&t.left===-5&&(t.left=-75,t.right=UN,t.top=UN,t.bottom=-75,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.castShadow=!0}e.shadow.mapSize.x!==r.mapSize&&(e.shadow.mapSize.set(r.mapSize,r.mapSize),e.shadow.map?.dispose(),e.shadow.map=null),e.shadow.radius=r.radius}}applyUnderwater(e){e&&(this.underwaterFog||=new wo(`#000000`,.5,e.visibility),this.underwaterFog.color.set(e.color),this.underwaterFog.near=.5,this.underwaterFog.far=e.visibility,this.scene.fog=this.underwaterFog,this.scene.background=this.underwaterBg.set(e.color),this._sky&&(this._sky.visible=!1))}applyHdri(e){let t=HN(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new uN().load(t,e=>{if(this.hdriUrl!==t){e.dispose();return}e.mapping=303,this.hdriTexture=e}))}applySky(e,t){let n=e?JSON.stringify(e):``;if(n!==this.skyKey&&(this.skyKey=n,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null),e)){this._sky=new dN,this._sky.scale.setScalar(45e4);let t=this._sky.material.uniforms;(t.sunPosition?.value).set(...e.sunPosition),t.turbidity&&(t.turbidity.value=e.turbidity),t.rayleigh&&(t.rayleigh.value=e.rayleigh),this.scene.add(this._sky)}if(e&&t&&this._sky&&this.skyEnvKey!==n){this.skyEnvKey=n,this.skyEnvTarget?.dispose();let e=new bd(t),r=new To;r.add(this._sky),this.skyEnvTarget=e.fromScene(r),e.dispose(),this.scene.add(this._sky)}!e&&this.skyEnvTarget&&(this.skyEnvTarget.dispose(),this.skyEnvTarget=null,this.skyEnvKey=``)}applyFog(e){if(!e.fog){this.scene.fog=null;return}let t=e.fog.color||(e.sky?ON(e.sky):`#cfd8e0`);this.fog.color.set(t),this.fog.near=e.fog.near,this.fog.far=e.fog.far,this.scene.fog=this.fog}dispose(){this.hdriTexture?.dispose(),this.hdriTexture=null,this.skyEnvTarget?.dispose(),this.skyEnvTarget=null,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null)}};function GN(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new N(`BAD_FORMAT`,`environment.iblIntensity must be a finite number >= 0 (multiplies the image-based ambience: sky-derived base 0.55, HDRI base 1; default 1), got ${JSON.stringify(e)}.`,{prop:`iblIntensity`});return e}var KN=new Bo,qN=new Bo,JN=new G,YN=new G,XN=new U,ZN=Array.from({length:8},()=>new U),QN=.4,$N=new Float32Array(72),eP=[[0,0,0],[1,0,0],[1,0,1],[0,0,1],[0,1,0],[1,1,0],[1,1,1],[0,1,1]],tP=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];function nP(e,t){t.makeEmpty(),JN.copy(e.matrixWorld).invert(),e.traverse(e=>{let n=e,r;n.isInstancedMesh?(n.boundingBox||n.computeBoundingBox?.(),r=n.boundingBox):n.geometry&&(n.geometry.boundingBox||n.geometry.computeBoundingBox(),r=n.geometry.boundingBox),r&&(qN.copy(r).applyMatrix4(YN.multiplyMatrices(JN,e.matrixWorld)),t.union(qN))})}function rP(e){if(!(e instanceof Dh))return null;let t=e._ensureObject3D();t.updateWorldMatrix(!0,!0),nP(t,KN);let n=!0;KN.isEmpty()?(n=!1,XN.setFromMatrixPosition(t.matrixWorld),KN.min.set(XN.x-QN,XN.y-QN,XN.z-QN),KN.max.set(XN.x+QN,XN.y+QN,XN.z+QN)):KN.expandByScalar(.02);let{min:r,max:i}=KN;for(let e=0;e<8;e++){let[a,o,s]=eP[e],c=ZN[e].set(a?i.x:r.x,o?i.y:r.y,s?i.z:r.z);n&&c.applyMatrix4(t.matrixWorld)}let a=0;for(let[e,t]of tP){let n=ZN[e],r=ZN[t];$N[a++]=n.x,$N[a++]=n.y,$N[a++]=n.z,$N[a++]=r.x,$N[a++]=r.y,$N[a++]=r.z}return $N}function iP(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function aP(){let e=new Set,t=[],n=[],r=[];return{visited:e,cameras:t,renderHooks:n,emitters:r,state:{visited:e,cameras:t,renderHooks:n,emitters:r,assets:void 0,sunDirection:null,sunLight:null,alpha:1,ignoreStatic:!1}}}function oP(e,t,n,r,i){let a=i??aP();a.visited.clear(),a.cameras.length=0,a.renderHooks.length=0,a.emitters.length=0;let o=a.state;o.assets=n,o.sunDirection=r?.sunDirection??null,o.ignoreStatic=r?.ignoreStatic===!0,o.sunLight=null,o.alpha=r?.alpha??1,fP(e,t,o),hP(t,a.visited);let s=null;for(let e=0;e<a.cameras.length;e++){let t=a.cameras[e];if(t.current){s=t;break}}s||=a.cameras[0]??null;let c=s?s._ensureObject3D():null;return dP(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var sP=new U,cP=new U,lP=new U,uP=new U;function dP(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(cP),t.getWorldDirection(lP),uP.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[cP.x,cP.y,cP.z],forward:[lP.x,lP.y,lP.z],up:[uP.x,uP.y,uP.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(sP),t._setSpatialPose({position:[sP.x,sP.y,sP.z],listener:n})}function fP(e,t,n){let r=t;if(e instanceof Dh){let i=e._ensureObject3D();if(e.static&&!n.ignoreStatic&&i.userData.incantoStaticSynced===!0){i.userData.incantoStatic=!0,n.visited.add(i);return}if(i.parent!==t&&t.add(i),e._syncObject3D(n.alpha,n.assets??null),n.assets&&e instanceof Jk&&e._syncModel(n.assets),typeof e._onRender3D==`function`&&n.renderHooks.push(e),n.sunDirection){let t=e._applySunDirection;typeof t==`function`&&t.call(e,n.sunDirection)}e instanceof Mk&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof BE&&n.cameras.push(e),r=i}else iP(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)fP(t,r,n);if(e instanceof Dh){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,mP(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var pP=new WeakSet;function mP(e){if(pP.has(e))return;pP.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof BE)&&t.push(`${e.name} (${e.constructor.typeName??`?`})`);for(let t of e.children)n(t)};n(e),t.length>0&&console.warn(`[incanto] static subtree '${e.name}' freezes animated/per-frame nodes: ${t.join(`, `)} — they will stop updating. Unmark static or move them out.`)}function hP(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&hP(i,t)}}var gP=class{viewOverride=null;overrideCam=new fu(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new To;environment=new WN(this.threeScene);engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;warmCamera=null;deferCompile=!1;syncScratch=aP();ignoreStatic=!1;renderCtx=null;causticsTarget=null;causticsScene=null;causticsUniforms=null;cloudsTarget=null;cloudsHalfTarget=null;cloudsBlurTarget=null;cloudsScene=null;cloudsUniforms=null;cloudsBlurScene=null;cloudsBlurUniforms=null;cloudsCompositeScene=null;cloudsCompositeUniforms=null;bloomTarget=null;bloomBrightTarget=null;bloomBlurTarget=null;bloomBrightScene=null;bloomBrightUniforms=null;bloomBlurScene=null;bloomBlurUniforms=null;bloomCompositeScene=null;bloomCompositeUniforms=null;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.ownsAssets=!e.assets,this.assets=e.assets??new gw(this.engine);let t=_n(e.engine.scene?.environment,{antialias:!0,pixelRatio:Math.min(globalThis.devicePixelRatio??1,2),preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio,preserveDrawingBuffer:e.preserveDrawingBuffer});this.webgl=new mm({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer}),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.adaptive=e.adaptiveResolution===!1?null:new qM,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new Vc(new J,new kc({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new Vc(new J,new kc({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.threeScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>this.render())}basePixelRatio;adaptive;lastFrameAt=0;debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?rP(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new q(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of Q_(`3d`,this.engine))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new q(e,3))}governResolution(){let e=this.adaptive;if(!e)return;let t=globalThis.performance?.now?.()??0,n=this.lastFrameAt;if(this.lastFrameAt=t,n===0)return;let r=t-n;if(r>500){e.reset();return}let i=e.push(r);if(i===null)return;this.webgl.setPixelRatio(this.basePixelRatio*i);let a=this.lastSize;a.w>0&&a.h>0&&this.webgl.setSize(a.w,a.h,!1)}deferFirstCompile(){this.deferCompile=!0}async warmUp(e){this.deferCompile=!1;let t=this.warmCamera;if(!t)return;let n=[];this.threeScene.traverse(e=>{(e.isMesh||e.isPoints)&&n.push(e)});let r=n.filter(e=>e.visible);if(r.length===0){this.webgl.compile(this.threeScene,t),e?.(1);return}for(let e of r)e.visible=!1;let i=Math.min(_P,r.length),a=Math.ceil(r.length/i);try{for(let n=0;n<i;n++){for(let e=n*a;e<Math.min((n+1)*a,r.length);e++)r[e].visible=!0;this.webgl.compile(this.threeScene,t),e?.((n+1)/i),typeof requestAnimationFrame==`function`&&await new Promise(e=>{requestAnimationFrame(()=>setTimeout(e,0))})}}finally{for(let e of r)e.visible=!0}}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.governResolution(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e)),this.environment.apply(e.environment,this.webgl);let{activeCamera:t,renderHooks:n,sunLight:r}=oP(e.root,this.threeScene,this.assets,{sunDirection:this.environment.sunDirection,alpha:this.engine.interpolationAlpha,ignoreStatic:this.ignoreStatic},this.syncScratch),i=t;if(this.viewOverride){let[e,t,n]=this.viewOverride.position,[r,a,o]=this.viewOverride.target;this.overrideCam.position.set(e,t,n),this.overrideCam.lookAt(yP.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(TP),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&!this.deferCompile&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i)),this.warmCamera=i;let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(vP);(u.x!==c||u.y!==l)&&this.webgl.setSize(c,l,!1),this.lastSize={w:c,h:l};let d=l===0?1:c/l;i.aspect!==d&&(i.aspect=d,i.updateProjectionMatrix()),this.renderCtx||={gl:this.webgl,scene:this.threeScene,camera:i};let f=this.renderCtx;f.camera=i,o?(o.updateWorldMatrix(!0,!1),o.target.updateWorldMatrix(!0,!1),f.sunDir=xP.setFromMatrixPosition(o.matrixWorld).sub(SP.setFromMatrixPosition(o.target.matrixWorld)).normalize()):f.sunDir=null;for(let e=0;e<n.length;e++)n[e]?._onRender3D(f);let p=null;for(let e=0;e<n.length;e++){let t=n[e].underwaterAt?.(a.x,a.y,a.z);if(t){p=t;break}}this.environment.applyUnderwater(p);let m=this.environment.clouds,h=this.environment.bloom,g=this.environment.post;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):(h||g)&&!p?this.renderWithBloom(i,h,g):this.webgl.render(this.threeScene,i)}renderWithBloom(e,t,n=null){let r=this.webgl.getDrawingBufferSize(vP),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/2)),s=Math.max(1,Math.ceil(a/2));if(this.bloomTarget&&(this.bloomTarget.width!==i||this.bloomTarget.height!==a)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new za(i,a,{type:hr,samples:4}),this.bloomBrightTarget=new za(o,s,{type:hr}),this.bloomBlurTarget=new za(o,s,{type:hr})),!this.bloomBrightScene){let e=$M();this.bloomBrightScene=new To,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=eN();this.bloomBlurScene=new To,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=tN();this.bloomCompositeScene=new To,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let c=this.bloomBrightTarget,l=this.bloomBlurTarget;if(this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e),t){let n=this.bloomBrightUniforms;n.tScene.value=this.bloomTarget.texture,n.uThreshold.value=t.threshold,this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBrightScene,e);let r=this.bloomBlurUniforms;r.tTex.value=c.texture,r.uDir.value.set(1/o,0),this.webgl.setRenderTarget(l),this.webgl.render(this.bloomBlurScene,e),r.tTex.value=l.texture,r.uDir.value.set(0,1/s),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e)}let u=this.bloomCompositeUniforms;u.tScene.value=this.bloomTarget.texture,u.tBloom.value=t?c.texture:this.bloomTarget.texture,u.uStrength.value=t?t.strength:0,u.uVignette.value=n?.vignette??0,u.uSaturation.value=n?.saturation??1,u.uContrast.value=n?.contrast??1,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(vP),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/3)),s=Math.max(1,Math.ceil(a/3));if(this.cloudsTarget&&(this.cloudsTarget.width!==i||this.cloudsTarget.height!==a)&&(this.cloudsTarget.depthTexture?.dispose(),this.cloudsTarget.dispose(),this.cloudsTarget=null,this.cloudsHalfTarget?.dispose(),this.cloudsHalfTarget=null,this.cloudsBlurTarget?.dispose(),this.cloudsBlurTarget=null),!this.cloudsTarget){let e=new Qc(i,a);e.type=mr,this.cloudsTarget=new za(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new za(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new za(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=sN();this.cloudsScene=new To,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=oN();this.cloudsBlurScene=new To,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=cN();this.cloudsCompositeScene=new To,this.cloudsCompositeScene.add(e),this.cloudsCompositeUniforms=t}this.webgl.setRenderTarget(this.cloudsTarget),this.webgl.render(this.threeScene,e);let c=this.cloudsUniforms;c.tDepth.value=this.cloudsTarget.depthTexture,c.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(c.uCameraPos.value),c.uTime.value=(globalThis.performance?.now()??0)*.001*t.speed;let l=this.environment.sunDirection??[.4,.8,.3];c.uSunDir.value.set(l[0],l[1],l[2]).normalize(),n&&c.uSunColor.value.copy(n.color),c.uCloudColor.value.set(t.color),c.uShadeColor.value.set(t.shadeColor);let u=this.environment.sceneFog;u?(c.uHorizonColor.value.copy(u.color),c.uFarFade.value=u.far):(c.uHorizonColor.value.set(`#cdd9e6`),c.uFarFade.value=6e3),c.uBase.value=t.base,c.uTop.value=t.top,c.uCoverage.value=t.coverage,c.uDensity.value=t.density,c.uScale.value=t.scale,c.uWind.value.set(1,.35),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(this.cloudsScene,e);let d=this.cloudsBlurUniforms,f=this.cloudsBlurScene;d.tTex.value=this.cloudsHalfTarget.texture,d.uDir.value.set(1/o,0),this.webgl.setRenderTarget(this.cloudsBlurTarget),this.webgl.render(f,e),d.tTex.value=this.cloudsBlurTarget.texture,d.uDir.value.set(0,1/s),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(f,e),this.webgl.setRenderTarget(null);let p=this.cloudsCompositeUniforms;p.tScene.value=this.cloudsTarget.texture,p.tClouds.value=this.cloudsHalfTarget.texture,this.webgl.render(this.cloudsCompositeScene,e)}renderWithCaustics(e,t){let n=this.webgl.getDrawingBufferSize(vP),r=Math.max(1,n.x),i=Math.max(1,n.y);if(this.causticsTarget&&(this.causticsTarget.width!==r||this.causticsTarget.height!==i)&&(this.causticsTarget.depthTexture?.dispose(),this.causticsTarget.dispose(),this.causticsTarget=null),!this.causticsTarget){let e=new Qc(r,i);e.type=mr,this.causticsTarget=new za(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=Qm();this.causticsScene=new To,this.causticsScene.add(e),this.causticsUniforms=t}this.webgl.setRenderTarget(this.causticsTarget),this.webgl.render(this.threeScene,e),this.webgl.setRenderTarget(null);let a=this.causticsUniforms;a.tColor.value=this.causticsTarget.texture,a.tDepth.value=this.causticsTarget.depthTexture,a.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(a.uCameraPos.value),a.uWaterLevel.value=t.surfaceY,a.uTime.value=(globalThis.performance?.now()??0)*.001*t.caustics.speed,a.uCausticColor.value.set(t.caustics.color),a.uCausticIntensity.value=t.caustics.intensity,a.uCausticScale.value=t.caustics.scale,a.uMaxDist.value=t.visibility;let o=this.environment.sunDirection;o&&a.uSunDirection.value.set(o[0],o[1],o[2]),a.uRayStrength.value=t.rays.enabled?t.rays.strength:0,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(bP.set(e,t,n).project(r),{x:(bP.x+1)/2*this.lastSize.w,y:(1-bP.y)/2*this.lastSize.h,behind:bP.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;DP.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),EP.setFromCamera(DP,n);let r=EP.intersectObjects(this.threeScene.children,!0);for(let e of r){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(n)return n}return null}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}lastCameraPosition(){let e=this.lastCamera;return e?(e.getWorldPosition(wP),{x:wP.x,y:wP.y,z:wP.z}):null}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(CP):CP.identity();return{right:new U(1,0,0).applyQuaternion(t),up:new U(0,1,0).applyQuaternion(t),forward:new U(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){this.engine.picker&&(this.engine.picker=null),this.disconnect(),this.threeScene.traverse(e=>{let t=e;if(!(!t.isMesh||t.userData?.incantoModelShared))if(t.geometry?.dispose(),Array.isArray(t.material))for(let e of t.material)e.dispose();else t.material?.dispose()}),this.causticsTarget?.depthTexture?.dispose(),this.causticsTarget?.dispose();let e=this.causticsScene?.children[0];e?.geometry?.dispose(),e?.material?.dispose(),this.cloudsTarget?.depthTexture?.dispose(),this.cloudsTarget?.dispose(),this.cloudsHalfTarget?.dispose(),this.cloudsBlurTarget?.dispose(),this.bloomTarget?.dispose(),this.bloomBrightTarget?.dispose(),this.bloomBlurTarget?.dispose();for(let e of[this.cloudsScene,this.cloudsBlurScene,this.cloudsCompositeScene,this.bloomBrightScene,this.bloomBlurScene,this.bloomCompositeScene]){let t=e?.children[0];t?.geometry?.dispose(),t?.material?.dispose()}this.ownsAssets&&this.assets.dispose(),this.environment.dispose(),this.webgl.dispose()}},_P=12,vP=new V,yP=new U,bP=new U,xP=new U,SP=new U,CP=new H,wP=new U,TP=new U,EP=new Ku,DP=new V;async function OP(e){let t=async(t,n)=>{e.onProgress&&(e.onProgress(t,n),typeof requestAnimationFrame==`function`&&await new Promise(e=>{requestAnimationFrame(()=>setTimeout(e,0))}))};GM(),(e.gameplay??!0)&&H_();for(let[t,n]of Object.entries(e.behaviors??{}))it(t,n,{replace:!0});let n=new Et({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),r=kP(e.scene),i=kn(kP(r),{resolveScene:e.resolveScene,engine:n});n.setScene(i),await t(.06,`scene`);let a=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&AP(i.root))&&(a=await DT(n)),await t(.1,`physics`);let o=[],s=e.keyboard??(typeof window<`u`?window:!1);if(s&&n.input.attachKeyboard(s),e.pointer){let t=typeof e.pointer==`object`?e.pointer.lockOnClick??!0:!0;n.input.attachPointer(e.canvas,{lockOnClick:t})}o.push(jP(n,i.root,e.canvas));let c=e.touch??`auto`;if(c!==!1){let t=e.touchContainer??e.canvas.parentElement??null;if(t){let r={force:c===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=Kn(n,t,r),a=n.sceneChanged.connect(()=>{i?.dispose(),i=Kn(n,t,r)});o.push(()=>{a(),i?.dispose()})}}let l=e._rendererFactory?e._rendererFactory(n,e.canvas):new gP({canvas:e.canvas,engine:n,...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.adaptiveResolution===void 0?{}:{adaptiveResolution:e.adaptiveResolution},...e.preserveDrawingBuffer===void 0?{}:{preserveDrawingBuffer:e.preserveDrawingBuffer}});await t(.14,`renderer`);let u=e.debug??!1,d=e.editor??u,f=d===!0?{}:d||null,p={label:`✎ edit this scene`,run:async()=>{if(!f)return;let t=km(l),n=f.open??Dm,i=async t=>{await OP({...e,scene:t})};await Om(async()=>{m();try{await n({scene:r,...t?{camera:t}:{},play:i,exit:()=>i(r),...f.save?{save:f.save}:{},...f.library?{library:f.library===!0?Cm():f.library}:{}})}catch(e){console.error(`[incanto] could not open the editor:`,e),await i(r)}},`opening the editor…`)}};if(u){let t=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(t){let{attachDebugOverlay:r}=await ym(async()=>{let{attachDebugOverlay:e}=await import(`./debug-CX0LDd1r.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(n,{container:t,statsSource:()=>l.stats?.()??{},...f?{actions:[p]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&o.push(()=>i.dispose())}}n.start(),await t(.16,`shaders`);try{l.deferFirstCompile?.();let t=globalThis.performance?.now?.()??0;n.tick(t),n.tick(t+16),await l.warmUp?.(t=>{e.onProgress?.(.16+t*.82,`shaders`)})}catch{}o.push(n.settings.bindAudio(n.audio)),o.push(n.settings.bindLocale(n.locale)),await t(1,`ready`);function m(){Am([a?[`physics`,()=>a?.dispose()]:null,[`app cleanups`,()=>{for(let e of o)e()}],[`engine`,()=>n.dispose()],[`renderer`,()=>l.dispose()]])}return{engine:n,scene:i,sourceJson:r,renderer:l,physics:a,assetErrors(){return l.assets?.errors()??[]},pick(e,t){return n.picker?.(e,t)??null},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...n.stats(),...l.stats?.()}},openEditor:f?p.run:null,dispose:m}}function kP(e){try{return structuredClone(e)}catch{throw new N(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function AP(e){if(e instanceof Oh)return!0;for(let t of e.children)if(AP(t))return!0;return!1}function jP(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`&&r.push({target:window,type:`keydown`}),r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Ft&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}var MP=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>eT,WATER_CUTOUT_MAX:()=>4,WATER_MAX_RIPPLES:()=>8,createGame3D:()=>OP,enablePhysics3D:()=>DT}),NP=new WeakMap,PP=class e{account;roomId;roomState=new j;allUserStates=new j;userJoined=new j;userLeft=new j;globalState=new j;globalMyState=new j;asset=new j;latestUserStates={};latestRoomState={};latestGlobalState={};latestGlobalMyState={};latestAsset={};server;engine;throttleMs;subs=[];messageSignals=new Map;collectionSignals=new Map;latestCollections=new Map;globalMessageSignals=new Map;globalCollectionSignals=new Map;latestGlobalCollections=new Map;scenes=new Map;lastSent=new Map;sendAccumulator=0;detachReplication=null;lastOwner=null;boundScene=null;static get(e){return NP.get(e)??null}static async create(t,n={}){await NP.get(t)?.dispose();let r=n.transport??await zP(n.config);await r.connect();let i=n.room??t.scene?.multiplayer?.room??`auto`,a=new e(t,r,await r.remoteFunction(`joinRoom`,[i===`auto`?void 0:i],{needResponse:!0}),n.throttleMs??50);return NP.set(t,a),a}constructor(e,t,n,r){this.engine=e,this.server=t,this.roomId=n,this.account=t.account,this.throttleMs=Math.max(30,r),this.boundScene=e.scene,this.subs.push(t.subscribeRoomState(n,e=>{this.latestRoomState=e,this.roomState.emit(e)}),t.subscribeRoomAllUserStates(n,e=>{this.latestUserStates=e,this.allUserStates.emit(e)}),t.onRoomUserJoin(n,e=>this.userJoined.emit(e)),t.onRoomUserLeave(n,e=>this.userLeft.emit(e))),t.subscribeGlobalState&&this.subs.push(t.subscribeGlobalState(e=>{this.latestGlobalState=e,this.globalState.emit(e)})),t.subscribeGlobalMyState&&this.subs.push(t.subscribeGlobalMyState(e=>{this.latestGlobalMyState=e,this.globalMyState.emit(e)})),t.subscribeAsset&&this.subs.push(t.subscribeAsset(this.account,e=>{this.latestAsset=e,this.asset.emit(e)})),this.detachReplication=e.fixedUpdated.connect(e=>this.replicate(e))}message(e){let t=this.messageSignals.get(e);return t||(t=new j,this.messageSignals.set(e,t),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>t?.emit(e)))),t}collection(e){let t=this.collectionSignals.get(e);return t||(t=new j,this.collectionSignals.set(e,t),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,n=>{this.latestCollections.set(e,n),t?.emit(n)}))),t}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let t=this.globalMessageSignals.get(e);if(!t){t=new j,this.globalMessageSignals.set(e,t);let n=this.server.onGlobalMessage?.(e,e=>t?.emit(e));n&&this.subs.push(n)}return t}globalCollection(e){let t=this.globalCollectionSignals.get(e);if(!t){t=new j,this.globalCollectionSignals.set(e,t);let n=this.server.subscribeGlobalCollection?.(e,n=>{this.latestGlobalCollections.set(e,n),t?.emit(n)});n&&this.subs.push(n)}return t}latestGlobalCollection(e){return this.globalCollection(e),this.latestGlobalCollections.get(e)??{}}setMyState(e){return this.server.remoteFunction(`setMyState`,[this.roomId,e],{throttle:this.throttleMs,throttleKey:`incanto:myState`})}patchRoomState(e){return this.server.remoteFunction(`patchRoomState`,[this.roomId,e])}addEntity(e,t){return this.server.remoteFunction(`addEntity`,[this.roomId,e,t])}updateEntity(e,t,n){return this.server.remoteFunction(`updateEntity`,[this.roomId,e,t,n])}removeEntity(e,t){return this.server.remoteFunction(`removeEntity`,[this.roomId,e,t])}sendEvent(e,t){return this.server.remoteFunction(`sendEvent`,[this.roomId,e,t])}call(e,...t){return this.server.remoteFunction(e,[this.roomId,...t],{needResponse:!0})}registerScene(e,t){this.scenes.set(e,t)}resolveScene(e){let t=this.scenes.get(e);if(!t)throw new N(`UNRESOLVED_INSTANCE`,`No scene registered for '${e}'. Registered: [${[...this.scenes.keys()].join(`, `)}]. Call manager.registerScene('${e}', sceneJson).`);return t}async dispose(){this.detachReplication?.();for(let e of this.subs)e();await this.server.remoteFunction(`leaveRoom`,[this.roomId]),NP.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3;let n=FP(t.root,!0);if(!n)return;n!==this.lastOwner&&(this.lastOwner=n,this.lastSent.clear());let r=n.network,i=Math.max(30,typeof r.throttleMs==`number`?r.throttleMs:this.throttleMs),a=Array.isArray(r.sync)?r.sync:[],o={};for(let e of a){let t=LP(n,e);t!==void 0&&(Ve(this.lastSent.get(e)??null,t)||(o[e]=He(t)))}if(!(this.sendAccumulator<i)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,He(t));this.sendAccumulator=0,this.setMyState({sync:o})}}};function FP(e,t=!1){let n=[];if(IP(e,n),t&&n.length>1)throw new N(`BAD_FORMAT`,`Multiple network owner nodes found (${n.map(e=>e.getPath()).join(`, `)}). Exactly ONE node per player may declare network.mode 'owner' — replicate spawned entities through collections instead.`);return n[0]??null}function IP(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)IP(n,t)}function LP(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:e.getNodeOrNull(t.slice(0,n))??void 0,i=n===-1?t:t.slice(n+1);if(r)return r[i]}function RP(e,t,n){for(let[r,i]of Object.entries(t)){let t=r.lastIndexOf(`.`),a=t===-1?e:e.getNodeOrNull(r.slice(0,t)),o=t===-1?r:r.slice(t+1);a&&n(a,o,i)}}async function zP(e){let{createAgent8Server:t}=await ym(async()=>{let{createAgent8Server:e}=await import(`./agent8-D3_GWeuh.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var BP=class extends At{static typeName=`NetworkSpawner`;static signals=[`spawned`,`despawned`];static props={source:{default:`users`},scene:{default:``},interpolate:{default:!0}};source=`users`;scene=``;interpolate=!0;spawned=new Map;positionTargets=new Map;failedKeys=new Set;update(e){let t=this.tree?.engine;if(!t)return;let n=PP.get(t);if(!n||this.scene===``)return;let r=this.currentEntries(n);for(let[e,t]of Object.entries(r)){let r=this.spawned.get(e);if(!r){if(this.failedKeys.has(e))continue;try{r=An(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=VP(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=t.sync;i&&RP(r,i,(e,t,n)=>this.setProp(e,t,n))}for(let[e,t]of[...this.spawned.entries()])e in r||(this.spawned.delete(e),this.positionTargets.delete(t),this.emit(`despawned`,t,e),t.free());this.interpolate&&this.stepInterpolation(e)}currentEntries(e){if(this.source===`users`){let t={};for(let[n,r]of Object.entries(e.latestUserStates))n!==e.account&&(t[n]=r);return t}return this.source.startsWith(`collection:`)?e.latestCollection(this.source.slice(11)):{}}setProp(e,t,n){if(this.interpolate&&t===`position`&&Array.isArray(n)){this.positionTargets.set(e,n);return}e[t]=n}stepInterpolation(e){let t=Math.min(1,e*8);for(let[e,n]of this.positionTargets){let r=e.position;Array.isArray(r)&&(e.position=r.map((e,r)=>e+((n[r]??e)-e)*t))}}};function VP(e){return e.replace(/[/%]/g,`_`)||`remote`}function HP(){gn(),R(BP)}var UP=localStorage.getItem(`incanto-editor-lang`)??`en`,WP=new Set;function GP(){return UP}function KP(e){UP=e,localStorage.setItem(`incanto-editor-lang`,e);for(let e of WP)e()}function qP(e){WP.add(e)}function JP(e){return e[UP]}var YP={node:{paths:[`M5 5h14v14H5z`]},move:{paths:[`M12 3v18M3 12h18`,`M8 7l4-4 4 4M8 17l4 4 4-4M7 8l-4 4 4 4M17 8l4 4-4 4`]},image:{paths:[`M4 5h16v14H4z`,`M4 15l5-5 4 4 3-3 4 4`],circles:[[9,9,1.6]]},film:{paths:[`M4 4h16v16H4z`,`M4 9h16M4 15h16`,`M9 4v16M15 4v16`]},video:{paths:[`M3 7h12v10H3z`,`M15 10l6-3v10l-6-3`]},text:{paths:[`M5 7V5h14v2`,`M12 5v14`,`M9 19h6`]},layers:{paths:[`M12 3 3 8l9 5 9-5-9-5z`,`M3 12l9 5 9-5`,`M3 16l9 5 9-5`]},square:{paths:[`M5 5h14v14H5z`,`M5 12h14`]},ball:{paths:[`M12 8v0`],circles:[[12,12,8],[12,12,1.4]]},person:{paths:[`M5 21v-1a7 7 0 0 1 14 0v1`],circles:[[12,7,4]]},area:{paths:[`M5 5h14v14H5z`],dashed:!0},gamepad:{paths:[`M7 9h-0M6 12h4M8 10v4`,`M4 8h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2z`],circles:[[16,11,1],[18.5,13.5,1]]},clock:{paths:[`M12 7v5l3 2`],circles:[[12,12,9]]},cube:{paths:[`M21 16V8l-9-5-9 5v8l9 5 9-5z`,`M3.3 7.5 12 12.5l8.7-5`,`M12 22V12.5`]},sun:{paths:[`M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9 17 7M7 17l-2.1 2.1`],circles:[[12,12,4]]},bulb:{paths:[`M9 18h6M10 21h4`,`M8 13a6 6 0 1 1 8 0c-1 1-1.5 2-1.5 3h-5c0-1-.5-2-1.5-3z`]},globe:{paths:[`M2 12h20`,`M12 2a15 15 0 0 1 0 20a15 15 0 0 1 0-20z`],circles:[[12,12,10]]},link:{paths:[`M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1`,`M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1`]},speaker:{paths:[`M11 5 6 9H3v6h3l5 4V5z`,`M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13`]},swatch:{paths:[`M4 4h16v16H4z`,`M4 4l16 16`]},sparkles:{paths:[`M12 4v5M12 15v5M5 12h5M14 12h5`],circles:[[6,5,1],[18,19,1]]},waves:{paths:[`M2 8c3-3 5 3 8 0s5 3 8 0`,`M2 14c3-3 5 3 8 0s5 3 8 0`,`M2 20c3-3 5 3 8 0s5 3 8 0`]},plant:{paths:[`M12 21v-8`,`M12 13c0-4-3-6-7-6 0 4 3 6 7 6z`,`M12 11c0-4 3-6 7-6 0 4-3 6-7 6z`]},flower:{paths:[`M12 21v-7`],circles:[[12,9,2],[12,4.5,2.2],[16.3,7.5,2.2],[14.7,12.6,2.2],[9.3,12.6,2.2],[7.7,7.5,2.2]]},voxels:{paths:[`M4 14h8v8H4z`,`M12 14h8v8h-8z`,`M8 6h8v8H8z`]}},XP={Node:`node`,Timer:`clock`,AudioPlayer:`speaker`,ColorRect2D:`swatch`,Particles2D:`sparkles`,Particles3D:`sparkles`,Water3D:`waves`,Foliage3D:`plant`,Flowers3D:`flower`,VoxelGrid3D:`voxels`,ModelInstance3D:`person`,CharacterController3D:`gamepad`,Node2D:`move`,Sprite2D:`image`,AnimatedSprite2D:`film`,Camera2D:`video`,Label:`text`,UILayer:`layers`,StaticBody2D:`square`,RigidBody2D:`ball`,CharacterBody2D:`person`,Area2D:`area`,CharacterController2D:`gamepad`,Node3D:`move`,Billboard3D:`layers`,MeshInstance3D:`cube`,LoftMesh3D:`cube`,Camera3D:`video`,DirectionalLight3D:`sun`,OmniLight3D:`bulb`,StaticBody3D:`square`,RigidBody3D:`ball`,CharacterBody3D:`person`,Area3D:`area`,NetworkSpawner:`globe`};function ZP(e){let t=YP[XP[e??``]??(e?`node`:`link`)],n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`width`,`13`),n.setAttribute(`height`,`13`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),t.dashed&&n.setAttribute(`stroke-dasharray`,`3 2.4`);for(let e of t.paths){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,e),n.appendChild(t)}for(let[e,r,i]of t.circles??[]){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);t.setAttribute(`cx`,String(e)),t.setAttribute(`cy`,String(r)),t.setAttribute(`r`,String(i)),n.appendChild(t)}return n}function QP(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`width`,`12`),e.setAttribute(`height`,`12`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2.4`),e.setAttribute(`aria-hidden`,`true`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`d`,`m6 9 6 6 6-6`),e.appendChild(t),e}var $P=[{type:`texture`,label:`image (texture)`,metaHints:[`filter`]},{type:`spritesheet`,label:`spritesheet`,metaHints:[`filter`,`frameWidth`,`frameHeight`]},{type:`model`,label:`3D model (GLB/VRM)`,metaHints:[]},{type:`animation`,label:`animation (GLB clips)`,metaHints:[`clip`]}],eF=new Set,tF=null,nF=null;function rF(e,t,n){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e;let i=()=>{let i=r.value.trim().replace(/\//g,``);i&&i!==e?t(i):n()};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`/`&&e.preventDefault(),e.key===`Enter`&&i(),e.key===`Escape`&&n()});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());return r.addEventListener(`blur`,i),queueMicrotask(()=>{r.focus(),r.select()}),r}function iF(e,t){let n={path:``,name:``,folders:new Map,assets:[]},r=e=>{let t=n;if(e===``)return t;for(let n of e.split(`/`)){let e=t.folders.get(n);e||(e={path:t.path?`${t.path}/${n}`:n,name:n,folders:new Map,assets:[]},t.folders.set(n,e)),t=e}return t};for(let t of e){let e=t.lastIndexOf(`/`);r(e===-1?``:t.slice(0,e)).assets.push(t)}for(let e of t)r(e);return n}function aF(e){let t=e.assets.length;for(let n of e.folders.values())t+=aF(n);return t}function oF(e,t){e.textContent=``;let n=t.working.assets??{},r=Object.keys(n);if(r.length===0&&t.pendingGroups.size===0&&!t.addingAsset&&!t.addingGroup){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no assets yet — + adds textures, models, animations`,e.appendChild(t);return}let i=(e,n)=>{e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.add(`drop-target`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-target`)),e.addEventListener(`drop`,r=>{r.preventDefault(),r.stopPropagation(),e.classList.remove(`drop-target`);let i=r.dataTransfer?.getData(`text/incanto-asset`);i&&t.moveAsset(i,n);let a=r.dataTransfer?.getData(`text/incanto-group`);a&&t.moveGroup(a,n)})};i(e,``);let a=(e,r)=>{let i=n[e],a=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,o=document.createElement(`div`);o.className=`tree-row asset-row${t.selectedAsset===e?` selected`:``}`,o.draggable=!0,o.addEventListener(`dragstart`,t=>{t.dataTransfer?.setData(`text/incanto-asset`,e)});let s=document.createElement(`span`);if(s.className=`tree-icon`,s.appendChild(SF(i.type??``)),s.addEventListener(`click`,e=>{e.stopPropagation(),CF(s,i.type??``)}),tF===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;o.appendChild(rF(a,r=>{tF=null,t.renameAssetKey(e,n+r)},()=>{tF=null,t.selectAsset(t.selectedAsset)})),o.draggable=!1,o.insertBefore(s,o.firstChild),r.appendChild(o);return}let c=document.createElement(`span`);c.className=`tree-name asset-key`,c.textContent=`$${a}`,c.title=`$${e}`,c.addEventListener(`dblclick`,n=>{n.stopPropagation(),tF=e,t.selectAsset(e)}),o.append(s,c),o.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(o)},o=(e,n)=>{let r=eF.has(e.path),s=document.createElement(`div`);s.className=`asset-folder${r?` collapsed`:``}${t.selectedGroup===e.path?` selected`:``}`,s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.stopPropagation(),t.dataTransfer?.setData(`text/incanto-group`,e.path)});let c=document.createElement(`span`);c.className=`chev`,c.appendChild(QP());let l=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);l.setAttribute(`viewBox`,`0 0 24 24`),l.setAttribute(`width`,`12`),l.setAttribute(`height`,`12`),l.setAttribute(`fill`,`none`),l.setAttribute(`stroke`,`currentColor`),l.setAttribute(`stroke-width`,`1.8`),l.setAttribute(`aria-hidden`,`true`);let u=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);if(u.setAttribute(`d`,`M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`),l.appendChild(u),nF===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,rF(e.name,n=>{nF=null,t.renameGroup(e.path,i+n)},()=>{nF=null,t.selectGroup(t.selectedGroup)})),s.draggable=!1,n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}return}let d=document.createElement(`span`);d.textContent=e.name,d.addEventListener(`dblclick`,n=>{n.stopPropagation(),nF=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${aF(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{eF.has(e.path)?eF.delete(e.path):eF.add(e.path),t.selectGroup(e.path)}),i(s,e.path),n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}},s=iF(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function sF(e,t,n,r){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(DF(t.newGroupParent?`NEW GROUP IN ${t.newGroupParent}/`:`NEW GROUP`));let n=document.createElement(`input`);n.placeholder=t.newGroupParent?`heroes`:`characters (or a/b to nest)`,n.className=`mono`,e.appendChild(_F(`name`,n));let r=document.createElement(`button`);r.type=`button`,r.className=`primary`,r.textContent=`add`;let i=()=>{let e=n.value.trim().replace(/^\/+|\/+$/g,``);e&&(t.cancelAddForms(),t.addGroup(t.newGroupParent?`${t.newGroupParent}/${e}`:e))};r.addEventListener(`click`,i),n.addEventListener(`keydown`,e=>{e.key===`Enter`&&i()});let a=document.createElement(`div`);return a.className=`pop-actions`,a.appendChild(r),e.appendChild(a),setTimeout(()=>n.focus(),0),!0}if(t.addingAsset)return dF(e,t,r);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(DF(`GROUP (${i} asset${i===1?``:`s`})`));let a=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)+1):``,o=r.includes(`/`)?r.slice(r.lastIndexOf(`/`)+1):r;e.appendChild(vF(`name`,o,e=>{let n=e.trim().replace(/\/+/g,``);n&&n!==o&&t.renameGroup(r,a+n)}));let s=document.createElement(`button`);return s.type=`button`,s.className=`ghost danger`,s.textContent=`delete group`,s.addEventListener(`click`,()=>{if(i===0){t.deleteGroup(r);return}n(`'${r}/' contains ${i} asset${i===1?``:`s`} — deleting the group deletes them too.`,`delete group & assets`,()=>t.deleteGroup(r))}),e.appendChild(s),!0}let i=t.selectedAsset;if(i===null)return!1;let a=t.working.assets??{};if(!(i in a))return!1;e.appendChild(DF(`ASSET — ${String(a[i].type??`?`)}`)),e.appendChild(wF(i)),e.appendChild(TF(t,i)),e.appendChild(cF(t,a,i,r));let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost danger`,o.textContent=`delete asset`,o.addEventListener(`click`,()=>{t.selectAsset(null),t.mutate(()=>{delete a[i],Object.keys(a).length===0&&delete t.working.assets})}),e.appendChild(o),!0}function cF(e,t,n,r){let i=t[n],a=document.createElement(`div`);a.className=`asset-editor`;let o=n.includes(`/`)?n.slice(n.lastIndexOf(`/`)+1):n,s=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)+1):``,c=vF(`name`,o,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==o&&e.renameAssetKey(n,s+r)});EF(c.querySelector(`input`)),a.appendChild(c);let l=vF(`url`,String(i.url??``),t=>{e.mutate(()=>{i.url=t.trim()})}),u=l.querySelector(`input`);if(r&&u){let t=pF(String(i.type??``));l.appendChild(gF(()=>t,`asset url`,r,t=>{u.value=t,e.mutate(()=>{i.url=t})},()=>hF(t,e)))}a.appendChild(l);let d=document.createElement(`div`);d.className=`muted-note`,d.textContent=`meta (key · value)`,a.appendChild(d);for(let[t,n]of Object.entries(i))t===`type`||t===`url`||a.appendChild(lF(e,i,t,n));return a.appendChild(uF(e,i)),a}function lF(e,t,n,r){let i=document.createElement(`div`);i.className=`meta-row`;let a=document.createElement(`input`);a.value=n,a.className=`mono`;let o=document.createElement(`input`);o.value=typeof r==`string`?r:JSON.stringify(r),o.className=`mono`;let s=()=>{let r=a.value.trim();e.mutate(()=>{delete t[n],r&&(t[r]=yF(o.value))})};a.addEventListener(`change`,s),o.addEventListener(`change`,s);let c=document.createElement(`button`);return c.type=`button`,c.className=`linklike danger-link`,c.textContent=`✕`,c.addEventListener(`click`,()=>{e.mutate(()=>{delete t[n]})}),i.append(a,o,c),i}function uF(e,t){let n=document.createElement(`div`);n.className=`meta-row`;let r=document.createElement(`input`);r.placeholder=`filter…`,r.className=`mono`;let i=document.createElement(`input`);i.placeholder=`nearest`,i.className=`mono`;let a=()=>{let n=r.value.trim();!n||i.value.trim()===``||e.mutate(()=>{t[n]=yF(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function dF(e,t,n){return e.appendChild(DF(`NEW ASSET`)),e.appendChild(fF(t,n)),!0}function fF(e,t){let n=document.createElement(`div`);n.className=`asset-editor`;let r=document.createElement(`select`);for(let e of $P){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,r.appendChild(t)}n.appendChild(_F(`type`,r));let i=document.createElement(`input`);i.placeholder=`(optional) characters`,i.className=`mono`,i.value=e.newAssetGroup;let a=`asset-groups-list`;i.setAttribute(`list`,a);let o=document.createElement(`datalist`);o.id=a;let s=new Set;for(let t of Object.keys(e.working.assets??{})){let e=t.lastIndexOf(`/`);e!==-1&&s.add(t.slice(0,e))}for(let t of e.pendingGroups)s.add(t);for(let e of s){let t=document.createElement(`option`);t.value=e,o.appendChild(t)}n.appendChild(_F(`group`,i)),n.appendChild(o);let c=document.createElement(`input`);c.placeholder=`coin`,c.className=`mono`,EF(c),n.appendChild(_F(`key`,c));let l=document.createElement(`input`);l.placeholder=`/textures/coin.png · https://… · data:…`,l.className=`mono`;let u=_F(`url`,l);t&&u.appendChild(gF(()=>pF(r.value),`new asset`,t,e=>{l.value=e,c.value.trim()||(c.value=mF(e))},()=>hF(pF(r.value),e))),n.appendChild(u);let d=document.createElement(`textarea`);d.rows=2,d.placeholder=`or paste a JSON object: { "type": "model", "url": "/m.glb" }`,n.appendChild(d);let f=document.createElement(`button`);f.type=`button`,f.className=`primary`,f.textContent=`add`,f.addEventListener(`click`,()=>{let t=c.value.trim().replace(/^\$/,``);if(!t)return;let n=i.value.trim().replace(/\/+$/,``),a=n?`${n}/${t}`:t,o=null,s=d.value.trim();if(s)try{o=JSON.parse(s)}catch{d.classList.add(`invalid`);return}else l.value.trim()&&(o={type:r.value,url:l.value.trim()});o&&(e.cancelAddForms(),e.selectedAsset=a,e.mutate(()=>{e.working.assets||(e.working.assets={});let t=e.working.assets;t[a]=o}))});let p=document.createElement(`div`);return p.className=`pop-actions`,p.appendChild(f),n.appendChild(p),n}function pF(e){return e===`model`||e===`animation`?`model`:e===`audio`?`audio`:e===`texture`||e===`spritesheet`?`image`:`any`}function mF(e){return((e.split(/[?#]/)[0]??``).split(`/`).pop()??``).replace(/\.[^.]+$/,``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function hF(e,t){let n=(t.working.dimension??`2d`)===`3d`;if(e===`image`)return n?[`3d`,`textures`]:[`2d`,`sprite_characters`];if(e===`model`)return[`3d`,`characters`]}function gF(e,t,n,r,i){let a=document.createElement(`button`);return a.type=`button`,a.className=`asset-lib`,a.textContent=`📚`,a.title=`Browse the agent8 library`,a.addEventListener(`click`,a=>{a.preventDefault();let o=i?.();n({kind:e(),target:t,...o?{shelf:o}:{}}).then(e=>{e&&r(e)})}),a}function _F(e,t){let n=document.createElement(`label`);n.className=`field`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n}function vF(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),_F(e,r)}function yF(e){let t=e.trim();if(t===`true`)return!0;if(t===`false`)return!1;if(t!==``&&Number.isFinite(Number(t)))return Number(t);if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.parse(t)}catch{return e}return e}var bF={texture:`M3 5h18v14H3z M3 15l5-5 4 4 3-3 6 6 M8.5 9.5h.01`,spritesheet:`M3 4h18v16H3z M9 4v16 M15 4v16 M3 12h18`,model:`M12 2l9 5v10l-9 5-9-5V7z M12 12l9-5 M12 12L3 7 M12 12v10`,animation:`M12 2a10 10 0 1 0 10 10 M22 12l-3-3m3 3l3-3 M12 7v5l3 3`},xF={texture:{en:`image (texture) — Sprite2D.texture references it as "$key".`,ko:`이미지(텍스처) — Sprite2D.texture에서 "$키"로 참조합니다.`},spritesheet:{en:`spritesheet — AnimatedSprite2D slices it into named frame animations.`,ko:`스프라이트시트 — AnimatedSprite2D가 이름 붙은 프레임 애니메이션으로 자릅니다.`},model:{en:`3D model (GLB/glTF/VRM) — ModelInstance3D.model references it as "$key".`,ko:`3D 모델(GLB/glTF/VRM) — ModelInstance3D.model에서 "$키"로 참조합니다.`},animation:{en:`animation clips (GLB, in memory — drawn nowhere) — any model can play them; mixamo retargets onto VRM.`,ko:`애니메이션 클립(GLB, 메모리 전용 — 그려지지 않음) — 어떤 모델이든 재생 가능, mixamo는 VRM에 자동 리타게팅.`}};function SF(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`width`,`13`),t.setAttribute(`height`,`13`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.8`),t.setAttribute(`aria-hidden`,`true`);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return n.setAttribute(`d`,bF[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function CF(e,t){document.querySelector(`.balloon`)?.remove();let n=xF[t];if(!n)return;let r=document.createElement(`div`);r.className=`balloon floating`;let i=document.createElement(`div`);i.className=`balloon-title`,i.textContent=t;let a=document.createElement(`span`);a.textContent=JP(n),r.append(i,a),document.body.appendChild(r);let o=e.getBoundingClientRect();r.style.left=`${o.right+8}px`,r.style.top=`${Math.max(8,o.top-8)}px`;let s=()=>{r.remove(),document.removeEventListener(`pointerdown`,s,!0)};setTimeout(()=>document.addEventListener(`pointerdown`,s,!0),0)}function wF(e){let t=document.createElement(`div`);t.className=`field uid-line`;let n=document.createElement(`span`);n.textContent=`key`;let r=document.createElement(`div`);r.className=`uid-value`;let i=document.createElement(`code`);i.textContent=`$${e}`;let a=document.createElement(`button`);return a.type=`button`,a.className=`uid-copy`,a.title=`Copy key`,a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,a.addEventListener(`click`,()=>{navigator.clipboard?.writeText(`$${e}`),a.classList.add(`copied`),setTimeout(()=>a.classList.remove(`copied`),600)}),r.append(i,a),t.append(n,r),t}function TF(e,t){let n=t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``,r=document.createElement(`select`),i=new Set([``]);for(let t of Object.keys(e.working.assets??{})){let e=t.split(`/`);for(let t=1;t<e.length;t++)i.add(e.slice(0,t).join(`/`))}for(let t of e.pendingGroups)i.add(t);for(let e of[...i].sort()){let t=document.createElement(`option`);t.value=e,t.textContent=e===``?`(root)`:`${e}/`,e===n&&(t.selected=!0),r.appendChild(t)}r.addEventListener(`change`,()=>{e.moveAsset(t,r.value)});let a=document.createElement(`label`);a.className=`field`;let o=document.createElement(`span`);return o.textContent=`group`,a.append(o,r),a}function EF(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function DF(e){let t=document.createElement(`div`);t.className=`section-title`,t.textContent=e;let n=document.createElement(`span`);return n.className=`rule`,t.appendChild(n),t}var OF=window.parent!==window,kF=new URLSearchParams(window.location.search).get(`parentOrigin`),AF=!1;function jF(e){if(OF){if(!kF){AF||(AF=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,kF)}}var MF={ready(e,t,n){jF({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){jF({type:`incanto-editor:open`,input:e,output:t})},change(e){jF({type:`incanto-editor:change`,dirty:e})},save(e,t,n){jF({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){jF({type:`incanto-editor:error`,message:e})}},NF=[[`Core`,e=>!e.endsWith(`2D`)&&!e.endsWith(`3D`)&&e!==`Label`&&e!==`UILayer`&&e!==`NetworkSpawner`],[`2D`,e=>e.endsWith(`2D`)&&!/Body|Area|Controller/.test(e)||e===`Label`||e===`UILayer`],[`2D Physics`,e=>e.endsWith(`2D`)&&/Body|Area|Controller/.test(e)],[`3D`,e=>e.endsWith(`3D`)&&!/Body|Area|Controller/.test(e)],[`3D Physics`,e=>e.endsWith(`3D`)&&/Body|Area|Controller/.test(e)],[`Network`,e=>e===`NetworkSpawner`]],PF=[...NF,[`Other`,e=>NF.every(([,t])=>!t(e))]],FF={title:{en:`How Incanto scenes work`,ko:`Incanto 씬은 어떻게 동작하나`},sections:[{heading:{en:`Everything is a node in a tree`,ko:`모든 것은 트리 위의 노드`},text:{en:`A scene is ONE tree of typed nodes (Godot-style). Each node has a name (unique among its siblings), a type that defines its props and behavior, optional children, and an optional scene-wide-unique uid. The whole structure lives in a *.scene.json file — there is no hidden state: what you see in this editor IS the file.`,ko:`씬은 타입을 가진 노드들의 단일 트리입니다(Godot 방식). 각 노드는 이름(형제 간 유일), props와 동작을 결정하는 타입, 선택적 자식들, 그리고 선택적인 씬 전역 유일 uid를 가집니다. 전체 구조가 *.scene.json 파일 하나에 들어있고 숨겨진 상태는 없습니다 — 이 에디터에서 보는 것이 곧 파일 그 자체입니다.`}},{heading:{en:`Props are delta-only`,ko:`Props는 변경분만 기록`},text:{en:`Every prop has a default defined by the engine. The JSON only stores values that DIFFER from the default — so files stay small and diffs stay meaningful. This editor follows the same rule: set a value back to its default and it disappears from the file.`,ko:`모든 prop에는 엔진이 정의한 기본값이 있습니다. JSON에는 기본값과 다른 값만 기록되어 파일이 작고 diff가 의미를 가집니다. 이 에디터도 같은 규칙을 따릅니다 — 값을 기본값으로 되돌리면 파일에서 사라집니다.`}},{heading:{en:`Addressing: paths, names, uid, groups`,ko:`노드 찾기: 경로·이름·uid·그룹`},text:{en:`Code reaches nodes four ways: a path like "Player/Skin" (relative) or "%Unique" (marked-unique name), getNodesByName("Enemy") which returns a LIST (names repeat across the tree), getNodeByUid("n_x1y2") which returns exactly one node and survives moves/renames, and groups — free tags for queries like "every coin".`,ko:`코드는 네 가지 방법으로 노드에 접근합니다: "Player/Skin" 같은 경로(상대) 또는 "%Unique"(유일 표시 이름), 트리 전체에서 같은 이름을 모두 찾는 getNodesByName("Enemy") — 이름은 중복될 수 있어 리스트가 돌아옵니다 —, 정확히 한 노드를 돌려주고 이동/개명에도 살아남는 getNodeByUid("n_x1y2"), 그리고 "모든 코인"처럼 묶어 조회하는 자유 태그 groups.`}},{heading:{en:`Signals connect, behaviors act`,ko:`시그널로 잇고 비헤이비어로 움직인다`},text:{en:`Nodes emit signals (an Area2D fires triggerEnter, a Timer fires timeout). The scene's "connections" wire a signal to a handler — declaratively, in JSON. Game logic itself is a Behavior: a TypeScript class in YOUR game, attached by name via "script". The inspector's CONNECTIONS section shows and edits these links on the selected node — what it emits, what reaches it, and any end that no longer resolves. The handler code itself lives in your game.`,ko:`노드는 시그널을 발산합니다(Area2D의 triggerEnter, Timer의 timeout). 씬의 "connections"가 시그널을 핸들러에 선언적으로(JSON으로) 연결합니다. 게임 로직 자체는 Behavior — 게임 쪽 TypeScript 클래스이며 "script"에 이름으로 연결됩니다. 인스펙터의 CONNECTIONS 섹션이 선택한 노드의 연결을 보여주고 편집합니다 — 나가는 것, 들어오는 것, 그리고 더 이상 찾을 수 없는 끝. 핸들러 코드 자체는 게임에 있습니다.`}},{heading:{en:`Assets are declared, then referenced`,ko:`에셋은 선언하고 $키로 참조`},text:{en:`The scene header declares assets (textures, spritesheets, 3D models, animation clips) under a key; nodes reference them as "$key". Animations are data too: an {type:"animation"} asset loads GLB clips into memory and any ModelInstance3D can play them — Mixamo clips retarget onto VRM avatars automatically.`,ko:`씬 헤더에서 에셋(텍스처·스프라이트시트·3D 모델·애니메이션 클립)을 키로 선언하고, 노드는 "$key"로 참조합니다. 애니메이션도 데이터입니다 — {type:"animation"} 에셋이 GLB 클립을 메모리에 올리고 어떤 ModelInstance3D든 재생할 수 있으며, Mixamo 클립은 VRM 아바타에 자동 리타게팅됩니다.`}}]},Q=(e,t,...n)=>({type:e,summary:t,body:n}),IF=[{id:`core`,label:{en:`Core`,ko:`Core`},intro:{en:`Dimension-free building blocks: plain containers and the game clock. They render nothing themselves.`,ko:`차원과 무관한 기본 블록 — 순수 컨테이너와 게임 시계입니다. 스스로는 아무것도 그리지 않습니다.`},nodes:[Q(`Node`,{en:`A plain container with no transform.`,ko:`변환 없이 자식을 묶는 순수 컨테이너.`},{en:`Use it to group related nodes (all coins, all UI) without affecting their positions. Lifecycle, signals, groups, script — everything works; it just has no visual or spatial meaning of its own.`,ko:`위치에 영향을 주지 않으면서 관련 노드(코인 전부, UI 전부)를 묶을 때 씁니다. 라이프사이클·시그널·그룹·스크립트가 모두 동작하며, 시각적·공간적 의미만 없습니다.`}),Q(`Timer`,{en:"A serializable countdown that emits `timeout`.",ko:"`timeout` 시그널을 쏘는 직렬화 가능한 카운트다운."},{en:`Set waitTime (seconds), optionally autostart or oneShot, and connect its timeout signal to any handler. Because it is a node, the whole timing setup lives in the scene file — agents can read and tune it.`,ko:`waitTime(초)을 정하고 autostart·oneShot을 선택한 뒤 timeout 시그널을 핸들러에 연결하세요. 노드이기 때문에 타이밍 설정 전체가 씬 파일에 남아 에이전트가 읽고 조정할 수 있습니다.`}),Q(`HudLayer`,{en:`Screen-space HUD overlay above the canvas — parent for UiText/UiBar/UiBanner.`,ko:`캔버스 위 화면 고정 HUD 오버레이 — UiText/UiBar/UiBanner의 부모.`},{en:`A DOM overlay (position:fixed) that never blocks pointer input. Put UI widgets as children; each picks one of 9 anchors (topLeft…bottomRight). Works identically over 2D and 3D renderers; in headless/tests it is a silent no-op. zIndex lifts it above the canvas.`,ko:`포인터 입력을 가로막지 않는 DOM 오버레이(position:fixed)입니다. UI 위젯을 자식으로 두면 각자 9개 앵커(topLeft…bottomRight) 중 하나에 붙습니다. 2D·3D 렌더러 어디서나 동일하게 동작하고, 헤드리스/테스트에서는 조용히 no-op입니다. zIndex로 캔버스 위에 올립니다.`}),Q(`UiText`,{en:`A HUD text line — score, timers, hints.`,ko:`HUD 텍스트 한 줄 — 점수, 타이머, 힌트.`},{en:`Child of HudLayer. Set text/size/color in JSON; update from behaviors: (getNode('%Score') as UiText).text = String(score). shadow adds a soft outline for readability over any scene.`,ko:`HudLayer의 자식. text/size/color를 JSON으로 정하고, 비헤이비어에서 (getNode('%Score') as UiText).text = String(score) 로 갱신하세요. shadow는 어떤 화면 위에서도 읽히도록 부드러운 그림자를 더합니다.`}),Q(`UiBar`,{en:`A labeled progress bar — health, stamina, reload, boss HP.`,ko:`라벨 달린 진행 바 — 체력, 스태미나, 재장전, 보스 HP.`},{en:`Child of HudLayer. Drive value/max from behaviors; the fill animates and turns lowColor under lowThreshold (default 30%). width/height/color/background style it; label prefixes a small caption.`,ko:`HudLayer의 자식. 비헤이비어에서 value/max를 갱신하면 채움이 애니메이션되고 lowThreshold(기본 30%) 아래로 떨어지면 lowColor로 바뀝니다. width/height/color/background로 스타일, label로 작은 캡션을 붙입니다.`}),Q(`UiBanner`,{en:`Center-screen announcements with fade and a queue — "WAVE 2", "YOU DIED".`,ko:`페이드·큐가 있는 중앙 공지 — "WAVE 2", "YOU DIED".`},{en:`Child of HudLayer. Call show('WAVE 2', { color, seconds }) from behaviors; messages queue and fade in/out. seconds 0 = sticky until the next show(). clear() drops everything. Emits bannerShown(text).`,ko:`HudLayer의 자식. 비헤이비어에서 show('WAVE 2', { color, seconds })를 호출하면 메시지가 큐에 쌓여 페이드 인/아웃됩니다. seconds 0이면 다음 show()까지 고정, clear()로 전부 제거. bannerShown(text) 시그널을 냅니다.`}),Q(`UiButton`,{en:`A clickable HUD button — menus, START screens, dialog choices.`,ko:`클릭 가능한 HUD 버튼 — 메뉴, 시작 화면, 대화 선택지.`},{en:`Child of HudLayer. Set text/size/color/background; disabled greys it out. Emits the 'pressed' signal (behaviors: node.on('pressed', ...)); press() triggers it programmatically (gamepad menus, tests).`,ko:`HudLayer의 자식. text/size/color/background를 설정하고 disabled로 비활성화합니다. 'pressed' 시그널을 내며(비헤이비어에서 node.on('pressed', ...)), press()로 코드에서도 누를 수 있습니다(게임패드 메뉴, 테스트).`}),Q(`UiPanel`,{en:`A box that holds other widgets — the thing a menu, options screen or inventory actually is.`,ko:`다른 위젯을 담는 상자 — 메뉴·설정 화면·인벤토리가 실제로 이것입니다.`},{en:`Child of HudLayer. Widgets under it mount INSIDE it, so tree structure becomes screen structure; panels nest. layout column|row|grid with columns (an inventory is a grid panel, one child per slot), plus gap/padding/background/radius/width/height/border. width or height 0 = size to the contents.`,ko:`HudLayer의 자식. 그 아래 위젯들이 이 안에 마운트되어 트리 구조가 화면 구조가 됩니다(중첩 가능). layout은 column|row|grid이고 columns와 함께 씁니다(인벤토리 = grid 패널, 슬롯당 자식 하나). gap/padding/background/radius/width/height/border 지원. width·height가 0이면 내용에 맞춰집니다.`}),Q(`UiImage`,{en:`A picture in the HUD — item icons, portraits, a logo.`,ko:`HUD 안의 그림 — 아이템 아이콘, 초상화, 로고.`},{en:`src takes a url or a $assetKey (declare the icon once like any other asset). fit contain|cover|fill; tint multiplies through the picture, which is how an unaffordable item greys out in one prop; opacity for disabled states.`,ko:`src는 url 또는 $assetKey(아이콘도 다른 에셋처럼 한 번만 선언). fit은 contain|cover|fill, tint는 그림에 곱해져서 살 수 없는 아이템을 프롭 하나로 회색 처리합니다. opacity로 비활성 표현.`}),Q(`UiSlider`,{en:`A value the player sets — volume, sensitivity, difficulty.`,ko:`플레이어가 조절하는 값 — 볼륨, 감도, 난이도.`},{en:`Emits changed(value). label/value/min/max/step/width/color. Setting .value from a behavior updates the control WITHOUT re-emitting, so restoring a saved setting does not fire the handler that saved it.`,ko:`changed(value) 시그널. label/value/min/max/step/width/color. 비헤이비어에서 .value를 설정하면 컨트롤만 갱신되고 changed는 다시 발생하지 않습니다 — 저장된 설정을 복원할 때 저장 핸들러가 다시 도는 것을 막습니다.`}),Q(`UiToggle`,{en:`An on/off switch — mute, invert-Y, fullscreen.`,ko:`켜기/끄기 스위치 — 음소거, Y축 반전, 전체화면.`},{en:`Emits changed(boolean). label/value. Same no-re-emit rule as UiSlider when set from code.`,ko:`changed(boolean) 시그널. label/value. 코드에서 설정할 때 재발생하지 않는 규칙은 UiSlider와 같습니다.`}),Q(`UiLanguageSelect`,{en:`The language picker, already wired.`,ko:`이미 연결된 언어 선택기.`},{en:`Options are the locales the scene declares in "strings", each labeled with its own endonym. Picking one switches the game live and persists it. English is the base: any key a locale omits falls back to it, on purpose.`,ko:`옵션은 씬의 "strings"가 선언한 로케일이며, 각 언어의 자기 이름으로 표시됩니다. 선택하면 즉시 바뀌고 저장됩니다. 영어가 기준이라 로케일이 빠뜨린 키는 의도적으로 영어로 표시됩니다.`}),Q(`UiSelect`,{en:`One of several — quality, resolution, language.`,ko:`여러 개 중 하나 — 품질, 해상도, 언어.`},{en:`options is a comma-separated list ("low,medium,high"); value is the current one. Emits changed(value).`,ko:`options는 쉼표로 구분된 목록("low,medium,high"), value가 현재 선택입니다. changed(value) 시그널.`}),Q(`UiDialogue`,{en:`A typewriter dialogue box with a queue and choice buttons — the RPG conversation layer.`,ko:`타자기 효과·큐·선택지 버튼을 갖춘 대화창 — RPG 대화 레이어.`},{en:`Child of HudLayer (anchor bottom by default). say(speaker, text, choices?) queues lines; clicking (or advance()) reveals then advances; choice lines wait for choose(i). Signals: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0 = instant. Check .active to pause player input during conversations.`,ko:`HudLayer의 자식(기본 anchor bottom). say(화자, 텍스트, 선택지?)로 줄을 큐에 넣고, 클릭(또는 advance())이 전체 공개→다음 줄로 진행하며, 선택지 줄은 choose(i)를 기다립니다. 시그널: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0이면 즉시 표시. 대화 중 플레이어 입력을 멈추려면 .active를 확인하세요.`}),Q(`AudioPlayer`,{en:`Plays a sound: zero-asset procedural SFX, BGM loops, or one-shot effects.`,ko:`소리 재생 — 무에셋 절차적 효과음, 배경음 루프, 단발 효과음.`},{en:`Set preset (coin/jump/hurt/explosion/…) for an instant zero-asset SFX (pitch/seed vary it), or leave it "custom" and set src (URL or "$assetKey"). volume 0..1; bus routes through engine.audio (sfx|music) for global volume/mute; loop for music; autoplay starts on ready (browsers may hold it until the first user gesture). Call play()/stop() from game code. Dimension-free — 2D and 3D alike.`,ko:`preset(coin/jump/hurt/explosion/…)을 설정하면 즉시 무에셋 효과음이 납니다(pitch·seed로 변형). 아니면 "custom"으로 두고 src(URL 또는 "$에셋키")를 쓰세요. volume은 0..1, bus는 engine.audio(sfx|music)를 통해 전역 볼륨/음소거에 연결, 음악은 loop, autoplay는 준비되면 재생합니다(브라우저가 첫 입력까지 보류 가능). 게임 코드에서 play()/stop()을 부르세요. 2D·3D 어디서나 동작합니다.`})]},{id:`2d`,label:{en:`2D`,ko:`2D`},intro:{en:`The 2D world is y-down pixels: 1 unit = 1 px, (0,0) top-left, rotation in clockwise degrees. Rendering needs a current Camera2D.`,ko:`2D 세계는 y-아래 픽셀 좌표입니다: 1유닛=1px, (0,0)은 좌상단, 회전은 시계방향 도(degree). 렌더링에는 current 카메라(Camera2D)가 필요합니다.`},nodes:[Q(`Node2D`,{en:`The 2D transform container (position/rotation/scale).`,ko:`2D 변환 컨테이너(position/rotation/scale).`},{en:`Children inherit its transform — move the parent, everything follows. renderOrder orders drawing; visible hides the subtree.`,ko:`자식은 변환을 상속합니다 — 부모를 움직이면 전부 따라옵니다. renderOrder로 그리기 순서를, visible로 서브트리 표시를 제어합니다.`}),Q(`Sprite2D`,{en:`A textured quad.`,ko:`텍스처 사각형(스프라이트).`},{en:`texture is "$assetKey" from the scene assets. anchor [0.5,0.5] centers; flipX/flipY mirror; tint multiplies color; opacity fades. Size comes from the texture × scale.`,ko:`texture는 씬 에셋의 "$키"입니다. anchor [0.5,0.5]면 중앙 기준, flipX/flipY로 반전, tint로 색 곱, opacity로 투명도. 크기는 텍스처 × scale로 정해집니다.`}),Q(`ColorRect2D`,{en:`A flat colored rectangle — no texture needed.`,ko:`단색 사각형 — 텍스처 불필요.`},{en:`size [w,h] px, color, opacity, anchor. Backgrounds, platforms, walls, UI panels, generated-level tiles (maze2d/dungeon2d emit these) — blocky art without any asset.`,ko:`size [w,h] px, color, opacity, anchor. 배경·플랫폼·벽·UI 패널·생성 레벨 타일(maze2d/dungeon2d가 이걸 만듭니다) — 에셋 없이 만드는 블록 그래픽입니다.`}),Q(`TileMap2D`,{en:`A whole tile level as ONE node — grid render + merged static colliders.`,ko:`타일 레벨 전체를 노드 하나로 — 그리드 렌더 + 병합된 정적 콜라이더.`},{en:`Author cells as rows of characters: "." / space = empty, digits 0-9 = atlas tile index, other chars map through legend ({"G": 12}). texture is a "$atlas" asset read left-to-right top-to-bottom in tileSize squares (columns: 0 derives from the texture width). Tile indices listed in solid become static colliders, greedy-merged into a few rectangles. Cell (0,0) hangs its top-left on the node origin.`,ko:`cells를 문자 행으로 작성합니다: "."/공백 = 빈 칸, 숫자 0-9 = 아틀라스 타일 번호, 그 외 문자는 legend({"G": 12})로 매핑. texture는 tileSize 정사각형을 좌→우, 상→하로 읽는 "$아틀라스" 에셋입니다(columns: 0이면 텍스처 폭에서 유도). solid에 나열된 타일 번호는 정적 콜라이더가 되며 소수의 직사각형으로 탐욕 병합됩니다. (0,0) 칸의 좌상단이 노드 원점에 걸립니다.`}),Q(`AnimatedSprite2D`,{en:`Spritesheet animation player.`,ko:`스프라이트시트 애니메이션 플레이어.`},{en:`Point sheet at a "$sheet" asset, define animations as named frame ranges with fps/loop in JSON, set autoplay. Emits animationFinished(name) for one-shot chains.`,ko:`sheet에 "$시트" 에셋을 연결하고, JSON에 fps/loop를 가진 이름별 프레임 구간으로 animations를 정의한 뒤 autoplay를 지정하세요. 단발 애니메이션 연결을 위해 animationFinished(name)를 발산합니다.`}),Q(`Camera2D`,{en:`The 2D view: follow, zoom, limits.`,ko:`2D 시점 — 추적·줌·경계.`},{en:`position is the view CENTER. follow tracks a node path with smoothing (0..1, higher = snappier). limits [minX,minY,maxX,maxY] clamps the view inside a world region. current: true makes it THE camera.`,ko:`position은 화면의 중심입니다. follow가 노드 경로를 smoothing(0..1, 높을수록 빠릿)으로 추적합니다. limits [minX,minY,maxX,maxY]가 시점을 월드 영역 안에 가둡니다. current: true인 카메라가 실제 시점이 됩니다.`}),Q(`Particles2D`,{en:`A 2D particle emitter (fire, sparks, smoke…).`,ko:`2D 파티클 이미터(불·스파크·연기…).`},{en:`Start from a preset (fire/smoke/sparks/…) then override any prop: rate, lifetime/speed ranges, direction + spread, gravity, size/color/alpha start→end, additive blend. burst > 0 with emitting: false makes a one-shot that emits finished. Animates LIVE in this editor.`,ko:`preset(fire/smoke/sparks/…)에서 시작해 어떤 prop이든 덮어쓰세요: rate, lifetime/speed 구간, direction+spread, gravity, size/color/alpha 시작→끝, additive blend. emitting: false에 burst > 0이면 단발 발사 후 finished를 발산합니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Label`,{en:`Text rendered to a quad.`,ko:`텍스트를 그리는 노드.`},{en:`text/fontSize/color/font/align — rendered via CanvasTexture, so any system font string works. Inside a UILayer it pins to the screen (HUD).`,ko:`text/fontSize/color/font/align — CanvasTexture로 그려져 시스템 폰트 문자열을 그대로 쓸 수 있습니다. UILayer 아래에 두면 화면에 고정됩니다(HUD).`}),Q(`UILayer`,{en:`A screen-space subtree (HUD).`,ko:`화면 고정 서브트리(HUD).`},{en:`Everything under it ignores the camera: positions are screen pixels from the top-left. Score counters, prompts, menus go here.`,ko:`이 아래의 모든 것은 카메라를 무시합니다 — 좌상단 기준 화면 픽셀 좌표입니다. 점수, 안내 문구, 메뉴를 여기에 둡니다.`})]},{id:`2d-physics`,label:{en:`2D Physics`,ko:`2D 물리`},intro:{en:`Rapier-backed. Colliders are PROPS ({shape, …}) — the green dashed wireframes in this editor. Physics runs when the game calls enablePhysics2D (and in play mode). Gravity lives on the scene row.`,ko:`Rapier 기반입니다. 콜라이더는 prop({shape, …})이며 에디터의 초록 점선이 그것입니다. 물리는 게임이 enablePhysics2D를 부를 때(그리고 플레이 모드에서) 돌고, 중력은 씬 행에 있습니다.`},nodes:[Q(`StaticBody2D`,{en:`Immovable collision: ground, walls, platforms.`,ko:`움직이지 않는 충돌체 — 바닥·벽·플랫폼.`},{en:`Other bodies collide with it; it never moves. Cheapest body type — use it for all level geometry.`,ko:`다른 바디가 부딪히지만 자신은 절대 움직이지 않습니다. 가장 저렴한 바디 — 레벨 지형 전부에 쓰세요.`}),Q(`RigidBody2D`,{en:`Fully simulated: falls, bounces, pushes.`,ko:`완전 시뮬레이션 — 떨어지고 튕기고 밀립니다.`},{en:`Gravity and collisions drive it. Set linearVelocity to launch. For player characters prefer CharacterBody2D (direct control).`,ko:`중력과 충돌이 움직임을 결정합니다. linearVelocity로 발사하세요. 플레이어 캐릭터에는 직접 제어가 가능한 CharacterBody2D를 권합니다.`}),Q(`CharacterBody2D`,{en:`Kinematic character: you set velocity, it slides.`,ko:`키네마틱 캐릭터 — 속도를 주면 미끄러지듯 이동.`},{en:`moveAndSlide() resolves collisions without physics pushing back; isOnFloor() gates jumps. Sensors (Area2D) do not block it but still fire triggers.`,ko:`moveAndSlide()가 밀려나지 않으면서 충돌을 처리하고 isOnFloor()로 점프를 판정합니다. 센서(Area2D)는 길을 막지 않으면서 트리거를 발사합니다.`}),Q(`Area2D`,{en:`A sensor: overlap triggers, no collision response.`,ko:`센서 — 겹침 감지만, 충돌 반응 없음.`},{en:`Fires triggerEnter(other)/triggerExit(other). Coins, checkpoints, damage zones. Filter with other.isInGroup("player").`,ko:`triggerEnter(other)/triggerExit(other)를 발산합니다. 코인·체크포인트·데미지 존에 쓰고, other.isInGroup("player")로 거릅니다.`}),Q(`CharacterController2D`,{en:`Zero-code platformer/top-down movement.`,ko:`코드 없는 플랫포머/탑다운 이동.`},{en:`Put it UNDER a CharacterBody2D. mode "platformer" (gravity + jump via jumpAction) or "topDown" (free 2-axis). Reads the scene input map actions (moveAction/jumpAction). maxSpeed/jumpHeight are intent-level numbers.`,ko:`CharacterBody2D의 자식으로 두세요. mode는 "platformer"(중력+jumpAction 점프) 또는 "topDown"(자유 2축)이며 씬 입력 맵의 액션(moveAction/jumpAction)을 읽습니다. maxSpeed/jumpHeight는 의도 그대로의 숫자입니다.`}),Q(`Joint2D`,{en:`A physics joint linking its parent body to a target body — weld, hinge, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 힌지, 로프, 스프링.`},{en:`Child of body A (a physics body); "target" is a node path to body B. type: fixed (rigid weld) / revolute (pin at the anchors) / rope (caps anchor distance at length px; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL px offsets.`,ko:`바디 A(물리 바디)의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / revolute(앵커 핀 힌지) / rope(앵커 간 거리를 length px로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 px 오프셋.`})]},{id:`3d`,label:{en:`3D`,ko:`3D`},intro:{en:`Meters, y-up, rotations in degrees. Standard materials need LIGHT — add a DirectionalLight3D or scene ambient, or you get silhouettes.`,ko:`미터 단위, y-위, 회전은 도(degree)입니다. 표준 머티리얼은 빛이 필요합니다 — DirectionalLight3D나 씬 ambient가 없으면 실루엣만 보입니다.`},nodes:[Q(`Node3D`,{en:`The 3D transform container.`,ko:`3D 변환 컨테이너.`},{en:`position [x,y,z] in meters, rotation [x,y,z] in degrees, scale per axis. Children inherit.`,ko:`position [x,y,z] 미터, rotation [x,y,z] 도, scale은 축별. 자식이 상속합니다.`}),Q(`MeshInstance3D`,{en:`A primitive mesh + material.`,ko:`프리미티브 메시 + 머티리얼.`},{en:`mesh: box/sphere/plane/cylinder…, size per primitive, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat} (this editor gives it swatches, sliders, texture-URL fields, and a repeat [u,v] tiling vector). map/normalMap are texture URLs; repeat only takes effect with a map. castShadow/receiveShadow per node.`,ko:`mesh: box/sphere/plane/cylinder…, 프리미티브별 size, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat}(에디터가 스와치·슬라이더·텍스처 URL 입력·repeat [u,v] 타일링 벡터 제공). map/normalMap은 텍스처 URL, repeat는 map이 있을 때만 적용. 그림자는 castShadow/receiveShadow.`}),Q(`LoftMesh3D`,{en:`A smooth swept hull (loft).`,ko:`부드러운 스윕 선체(로프트).`},{en:`sections: ≥2 cross-section stations {z, width, height, y, corner 0..1} interpolated into ONE smooth curved surface — vehicle bodies, glass canopies, boat hulls. slices/smooth control tessellation. Same material as MeshInstance3D minus textures (no UVs); pair clearcoat paint or high-envMapIntensity glass with the smooth normals for the automotive look.`,ko:`sections: 단면 스테이션 {z, width, height, y, corner 0..1} 2개 이상을 보간해 하나의 매끈한 곡면을 만듭니다 — 차체, 유리 캐노피, 선체. slices/smooth로 테셀레이션 조절. material은 MeshInstance3D와 동일하되 텍스처 제외(UV 없음). clearcoat 도장이나 높은 envMapIntensity 유리를 곡면 법선과 조합하면 자동차 룩이 납니다.`}),Q(`ModelInstance3D`,{en:`A GLB/glTF/VRM model file.`,ko:`GLB/glTF/VRM 모델 파일.`},{en:'model: "$assetKey" or URL. targetHeight scales the model to stand N units tall (run `npx incanto-model file.glb` to read its real size first). animation plays an embedded clip name OR an "$animation" asset — Mixamo clips retarget onto VRM humanoids automatically. One node per VRM asset (the avatar runtime mounts live). To make it SOLID, park it under a body with collider {shape:"auto"}: the collider is built from the model\'s own triangles — a triangle mesh on a static body (keeps its holes, so you walk through an archway) and a convex hull on a moving one.',ko:'model은 "$에셋키" 또는 URL입니다. targetHeight가 모델을 N유닛 높이로 맞춥니다(먼저 `npx incanto-model 파일.glb`로 실제 크기를 확인하세요). animation은 내장 클립 이름 또는 "$애니메이션" 에셋을 재생하며, Mixamo 클립은 VRM 휴머노이드에 자동 리타게팅됩니다. VRM 에셋은 노드 하나만 쓸 수 있습니다(아바타 런타임이 라이브로 마운트됨). 단단하게 만들려면 collider {shape:"auto"}인 바디 아래에 두세요 — 모델 자신의 삼각형에서 콜라이더가 만들어집니다(정적 바디는 트라이메시라 아치 구멍도 그대로, 움직이는 바디는 볼록 껍질).'}),Q(`Sprite3D`,{en:`A 2D image as a camera-facing billboard (the 2.5D look).`,ko:`카메라를 향하는 2D 빌보드 스프라이트(2.5D 룩).`},{en:`A textured quad that turns to face the camera inside the 3D world (Octopath / Don't Starve / MapleStory-in-3D). texture is an image URL; size is [w,h] in METERS. billboard: "y" stays upright with a screen-aligned yaw — off-center sprites never roll (characters/props), "full" faces it completely (items/FX), "none" is fixed to the node rotation. anchor [0.5,0] plants the feet on the ground. pixelArt nearest-filters for crisp pixels; alphaTest is a hard cutout that depth-sorts against 3D geometry (a tree occludes it); flipX mirrors left/right; tint/opacity recolor.`,ko:`3D 월드 안에서 카메라를 향해 도는 텍스처 쿼드(Octopath/Don't Starve, 3D 속 메이플스토리 룩). texture는 이미지 URL, size는 [너비,높이] 미터. billboard: "y"는 세로로 선 채 카메라 방향과 정렬된 yaw — 화면 가장자리에서도 기울지 않음(캐릭터/사물), "full"은 완전히 향함(아이템/FX), "none"은 노드 회전에 고정. anchor [0.5,0]은 발을 바닥에 둡니다. pixelArt는 nearest 필터로 픽셀을 또렷하게, alphaTest는 3D 지형과 깊이정렬되는 하드 컷아웃(나무가 가림), flipX는 좌우 반전, tint/opacity로 색·투명도.`}),Q(`AnimatedSprite3D`,{en:`A billboard sprite that plays spritesheet animations.`,ko:`스프라이트시트 애니를 재생하는 빌보드 스프라이트.`},{en:`Everything Sprite3D does, plus frame animation. sheet is a spritesheet image URL whose cells are frameWidth×frameHeight; animations maps a name to {frames, fps, loop} where frames is an inclusive [start,end] range or an explicit list; autoplay starts one on load. Game code calls play("walk") / stop(); a non-looping clip clamps on its last frame and emits animationFinished(name) — chain attack→idle from it.`,ko:`Sprite3D의 모든 기능 + 프레임 애니. sheet는 frameWidth×frameHeight 칸을 가진 스프라이트시트 URL, animations는 이름→{frames, fps, loop}(frames는 포함 [시작,끝] 범위 또는 명시 목록), autoplay는 로드 시 하나를 시작. 게임 코드에서 play("walk")/stop() 호출, 비반복 클립은 마지막 프레임에 머물며 animationFinished(name)를 emit(attack→idle 연결).`}),Q(`Billboard3D`,{en:`A group that turns toward the camera — children follow.`,ko:`카메라를 향해 도는 그룹 — 자식들이 함께 회전.`},{en:`A transform container that orients itself toward the camera every frame; children inherit the rotation, so hang world-space UI under it — HP bars, markers, floating icons (text is a canvas-rendered texture on a child Sprite3D). mode: "screen" (default) copies the camera orientation so a child rectangle stays an upright rectangle anywhere on screen (a yaw-only look-at visibly tilts off-center shapes under a pitched camera); "y" stays upright with a screen-aligned yaw (no off-center roll); "none" turns billboarding off. While billboarding, the node's own rotation prop (and the rotate gizmo) is overwritten every frame — switch to "none" to pose children, then switch back. Unlike Sprite3D (a textured quad that spins only its own image), Billboard3D rotates the whole group.`,ko:`매 프레임 카메라를 향해 자신을 회전시키는 변환 컨테이너로, 자식이 회전을 상속합니다 — HP바·마커·아이콘 같은 월드 UI를 자식으로 붙이세요(텍스트는 캔버스로 그린 텍스처를 자식 Sprite3D에). mode: "screen"(기본)은 카메라 자세를 그대로 복사해 자식 직사각형이 화면 어디서든 똑바른 직사각형으로 보입니다(yaw만 도는 look-at은 기울어진 카메라에서 중앙 밖 도형이 눈에 띄게 비스듬해짐); "y"는 세로로 선 채 카메라로 yaw만; "none"은 빌보드 끔. 빌보드 중에는 노드 자신의 rotation(회전 기즈모 포함)이 매 프레임 덮어써집니다 — 자식을 배치할 땐 "none"으로 바꿨다가 되돌리세요. 자기 그림만 도는 Sprite3D(텍스처 쿼드)와 달리 그룹 전체가 회전합니다.`}),Q(`Camera3D`,{en:`The 3D view.`,ko:`3D 시점.`},{en:`Perspective camera; fov in degrees; current: true selects it. Use the editor's "game cam" (0) to preview exactly what it renders.`,ko:`원근 카메라이며 fov는 도 단위, current: true가 실제 시점이 됩니다. 에디터의 "game cam"(0)으로 정확한 렌더 결과를 미리 보세요.`}),Q(`DirectionalLight3D`,{en:`Sun-like light from a direction.`,ko:`태양광 — 방향에서 평행하게.`},{en:`Position sets the direction toward the origin. intensity/color; pair with scene ambient for soft fill.`,ko:`위치가 원점을 향한 방향을 정합니다. intensity/color를 조절하고 부드러운 채움광은 씬 ambient와 함께 쓰세요.`}),Q(`OmniLight3D`,{en:`A point light radiating everywhere.`,ko:`점광 — 사방으로 퍼지는 빛.`},{en:`Lamps, torches, glows. range limits reach; intensity/color shape the falloff.`,ko:`램프·횃불·발광체. range로 도달 거리를, intensity/color로 감쇠를 만듭니다.`}),Q(`Particles3D`,{en:`A 3D particle emitter (fire, magic, weather…).`,ko:`3D 파티클 이미터(불·마법·날씨…).`},{en:`The same preset + override model as Particles2D, in meters with [x,y,z] gravity. Camera-facing billboard quads, instanced — hundreds are cheap. Animates LIVE in this editor.`,ko:`Particles2D와 같은 preset+덮어쓰기 모델을 미터 단위와 [x,y,z] 중력으로. 카메라를 향하는 빌보드 쿼드를 인스턴싱해 수백 개도 가볍습니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Terrain3D`,{en:`Procedural heightfield terrain with biome texture splatting.`,ko:`바이옴 텍스처 스플래팅이 적용된 절차적 하이트필드 지형.`},{en:`Seeded simplex hills displaced once on the CPU; theme (island/alpine/plains/desert/custom) picks the 4 blended biome textures by height and slope. heightAt(x,z) answers the surface height anywhere. For physics, parent it under a StaticBody3D with collider {shape:'heightfield'}.`,ko:`시드 기반 심플렉스 언덕을 CPU에서 한 번 변위합니다. theme(island/alpine/plains/desert/custom)이 높이·경사로 블렌딩되는 바이옴 텍스처 4장을 고릅니다. heightAt(x,z)로 어디서든 지표 높이를 얻고, 물리는 StaticBody3D 아래에 두고 collider {shape:'heightfield'}를 쓰세요.`}),Q(`Water3D`,{en:`A shader-water surface with splash signals.`,ko:`스플래시 신호를 내는 셰이더 물 표면.`},{en:`size [w,d] meters on XZ. quality 'fancy' (default) = FBM wave shader with a trough/surface/peak ramp (colors), CubeCamera reflections (reflection/reflectionInterval) and opt-in shoreline foam; 'simple' = the cheap sine material (color). Bodies crossing the surface emit entered/exited(body) and raise ripples (interaction). Volumetric gameplay still wants an Area3D. Waves animate LIVE in this editor.`,ko:`XZ 평면에 size [w,d] 미터. quality 'fancy'(기본)는 FBM 파도 셰이더 — trough/surface/peak 램프(colors), CubeCamera 반사(reflection/reflectionInterval), 옵트인 해안 거품(foam). 'simple'은 저사양용 사인파 머티리얼(color). 바디가 수면을 지나면 entered/exited(body) 신호와 물결이 일어납니다(interaction). 부피 기반 게임플레이엔 여전히 Area3D를 쓰세요. 이 에디터에서 파도가 라이브로 움직입니다.`}),Q(`River3D`,{en:`Running water derived from a path and the ground under it.`,ko:`경로와 그 아래 지형에서 유도되는 흐르는 물.`},{en:`Author a centerline path [[x,z],…] plus width/widths (a profile source→mouth) and depth; the node samples the Terrain3D underneath and derives the rest. It CARVES ITS OWN BED by default (carve): a trench per reach that heightAt, the collider, the splat and draped vegetation all see, with a floor that only ever falls, so a path over a rise digs through instead of burying the water. Its surface is then FITTED to that ground — never higher than the lowest rim holding it, ending where the ground comes up to meet it (asymmetric on a sloping reach), lying down as a film where a bank has fallen away, so a river can never hang in the air. Plus a current that speeds up where the channel pinches or tips (flowSpeed is the mean) and whitewater from grade, bank shear and thinning column. Boulders in the channel are answered without wiring: the node finds MeshInstance3D/InstancedMesh3D footprints standing in the water column and the current piles a white cushion on the upstream face, tears a wake downstream and bends its sheen around them. A trench thinner than a terrain cell cannot survive the grid: a 2.4 m creek on a 260 m map wants Terrain3D resolution 256. flowForce drags bodies downstream (drag, never thrust) and sampleAt(x,z) answers where a world point sits in the channel. No extra render passes — a map can carry a dozen.`,ko:`중심선 path [[x,z],…]와 width/widths(상류→하류 프로파일), depth만 주면 나머지는 아래 Terrain3D를 샘플링해 유도합니다. 기본적으로 강이 자기 바닥을 직접 팝니다(carve) — 구간마다 하나씩 도랑을 내고, heightAt·콜라이더·스플랫·식생 드레이프가 모두 그 지형을 봅니다. 파낸 바닥은 계속 내려가기만 하므로 경로가 언덕을 넘어도 물이 묻히지 않고 뚫고 흐릅니다. 그리고 수면은 그 지형에 맞춰집니다 — 자기를 담는 가장 낮은 둑보다 높아질 수 없고, 지면이 올라오는 지점에서 끝나며(비스듬한 구간에서는 좌우 폭이 다릅니다), 둑이 아예 없는 쪽에서는 경사면에 얇은 막처럼 누워버립니다. 그래서 강이 공중에 뜨는 일이 없습니다. 여기에 폭이 좁아지거나 경사가 급해지면 빨라지는 유속(flowSpeed는 평균)과 경사·둑 전단·얕아지는 수심에서 나오는 흰 물살이 더해집니다. 수로에 놓인 바위도 배선 없이 반응합니다 — MeshInstance3D/InstancedMesh3D 중 실제로 물기둥과 겹치는 것을 찾아, 상류면에 흰 물이 쌓이고 하류로 후류가 찢어지며 수면 광택이 바위를 돌아 휩니다. 지형 셀보다 얇은 도랑은 그리드에서 살아남지 못합니다 — 260 m 맵의 2.4 m 개울이라면 Terrain3D resolution 256이 필요합니다. flowForce가 바디를 하류로 끌고(밀지 않고 끌어당김), sampleAt(x,z)로 월드 좌표가 수로 어디에 있는지 알 수 있습니다. 추가 렌더 패스가 없어 한 맵에 여러 개를 둘 수 있습니다.`}),Q(`WaterCutout3D`,{en:`Marks its parent as something that holds the water back — a dry hull, a diving bell, a well.`,ko:`부모 오브젝트가 물을 막는다고 표시 — 마른 선실, 잠수종, 우물.`},{en:`Water is ONE surface and knows nothing about interiors, so an open hull floating on it fills with sea every time a crest clears its floor — freeboard alone can never promise otherwise. This node names the geometry that keeps the water out: it MUST be a CHILD of that thing (a hull, a bell, a dock's well, a cave mouth), and the water re-draws the part of it inside the box into its depth pre-pass, then hides behind it exactly as it hides behind any solid object. Nothing is ever cut OUT of the water, so a hole in open sea is impossible: overshoot the box and more of that hull holds water back, undershoot and water stands in the bow. size is the box extent in meters; enabled toggles it live (a scuttled hull starts letting the sea in). Four per water surface; needs quality fancy.`,ko:`물은 하나의 표면이라 '안쪽'이라는 개념이 없습니다. 그래서 뚜껑 없는 배를 띄우면 파도 마루가 바닥을 넘을 때마다 배 안에 바다가 차 보이고, 건현(freeboard)만으로는 절대 막을 수 없습니다. 이 노드는 '물을 막는 지오메트리'를 지정합니다. 반드시 그 물체(선체·잠수종·부두 우물·동굴 입구)의 자식이어야 하며, 물이 상자 안쪽의 그 지오메트리를 자기 깊이 프리패스에 다시 그린 뒤 평범한 불투명 물체 뒤에 숨듯 그 뒤로 숨습니다. 물에서 무언가를 '도려내지' 않으므로 열린 바다에 구멍이 나는 일은 원리적으로 불가능합니다 — 상자가 크면 그 배가 물을 더 많이 막을 뿐이고, 작으면 뱃머리에 물이 남습니다. size는 미터 단위 상자 크기, enabled는 런타임 토글(침수 시작 연출). 수면 하나당 4개, quality fancy 필요.`}),Q(`Foliage3D`,{en:`An instanced grass/flower carpet that sways.`,ko:`바람에 흔들리는 인스턴스 풀밭/꽃밭. `},{en:`kind grass/flowers/reeds scattered over area [w,d] at density (capped by maxInstances — instanced, tens of thousands of blades cheap). Grass defaults to style 'mesh': every instance is a REAL tapered blade curved by a bezier vertex shader — Voronoi-clump hue/lean, groundColor soil roots (match the terrain), sunDirection tip sheen, 2-octave rolling wind, fadeStart/fadeEnd camera LOD, and (interaction) blade-bending around moving bodies. style 'blades' keeps the 8-SDF-blades-per-quad ported shader, 'simple' the legacy quads. colorA/colorB tint bottom→top, sway sets the wind, seed makes the scatter reproducible. avoidWater (on by default) keeps blades OUT of standing and running water — a creek cutting its bed through the field gets banks, not blades waving in the current; turn it off for reeds and paddy fields.`,ko:`kind grass/flowers/reeds를 area [w,d]에 density로 흩뿌립니다(maxInstances 상한 — 인스턴싱이라 수만 가닥도 가벼움). grass는 기본 style 'mesh': 인스턴스 하나하나가 베지어 버텍스 셰이더로 휘어지는 진짜 잎 메시 — 보로노이 클럼프 색/기울기, groundColor 흙빛 뿌리(지형 색에 맞추세요), sunDirection 잎끝 광택, 2옥타브 굽이치는 바람, fadeStart/fadeEnd 카메라 LOD, (interaction) 움직이는 바디 주변 풀 눕힘까지. style 'blades'는 쿼드당 8가닥 SDF 셰이더, 'simple'은 기존 쿼드 룩. colorA/colorB가 아래→위 색, sway가 바람 세기, seed가 배치를 재현 가능하게 합니다. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 잎을 심지 않습니다 — 개울이 들판을 가르고 지나가면 물살 속에 풀이 서 있는 대신 둑이 생깁니다. 갈대·논은 꺼서 쓰세요.`}),Q(`Flowers3D`,{en:`Instanced flower PLANTS — stems, leaves, multi-petal heads.`,ko:`인스턴스 꽃밭 — 줄기·잎·여러 장 꽃잎의 진짜 꽃 식물.`},{en:`Real procedural flower plants (curved stem, 2-3 leaves, a 5-8 petal head around a contrasting center disc, 1-3 blooms per plant) scattered over area [w,d]. density is the vibe dial: 'lush' / 'sparse' (default) / 'none', or a number in plants/m². varieties picks a subset of daisy/cosmos/bellflower ([] = all three); palette sets the head colors ([] = white/yellow/violet). clustering 0-1 gathers plants into Voronoi patches that bloom one species + color together; sway bobs the heads in a gentle wind; seed makes the field reproducible. ≤3 varieties → ≤6 draw calls. avoidWater (on by default) keeps plants out of standing and running water — a meadow a stream runs through has a bank of flowers, not flowers in the current.`,ko:`진짜 프로시저럴 꽃 식물(휘어진 줄기, 잎 2-3장, 대비되는 중심 원반을 두른 꽃잎 5-8장 머리, 포기당 꽃 1-3송이)을 area [w,d]에 흩뿌립니다. density가 바이브 다이얼: 'lush'(풍성하게) / 'sparse'(듬성듬성, 기본) / 'none'(없게) 또는 m²당 개수. varieties는 daisy/cosmos/bellflower 부분집합([] = 셋 다), palette는 꽃 색([] = 흰/노랑/보라). clustering 0-1이 보로노이 패치로 모아 한 패치가 같은 종·같은 색으로 피고, sway가 바람에 머리를 끄덕이며, seed로 배치가 재현됩니다. 품종 ≤3 → 드로우 콜 ≤6. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 꽃을 심지 않습니다 — 시내가 지나는 들판에는 물살 속 꽃이 아니라 꽃이 핀 둑이 생깁니다.`}),Q(`Tree3D`,{en:`Procedural ez-tree groves — branchy trunks, textured leaves.`,ko:`프로시저럴 ez-tree 나무 — 가지 달린 줄기와 텍스처 잎까지.`},{en:`type conifer/broadleaf/dead picks the recipe family; tier is the cost dial: simple = primitive low-poly, medium = light forest presets (≤3k tris/tree), high = full ez-tree presets (8–20k, hero trees). count > 1 scatters a forest patch over area [w,d] — up to 3 seed variants, each branches + leaves InstancedMesh (≤6 draw calls); count × tris/tree is budget-checked at load. seed makes every branch and leaf reproducible; height jitters ±20% per instance; leaves sway in a simplex wind.`,ko:`type conifer/broadleaf/dead가 수종을, tier가 비용을 정합니다: simple = 기존 로우폴리, medium = 가벼운 forest 프리셋(나무당 ≤3k tris), high = 풀 ez-tree 프리셋(8–20k, 주인공 나무). count > 1이면 area [w,d]에 숲 패치를 흩뿌립니다 — 시드 변형 최대 3종, 변형마다 가지+잎 InstancedMesh(드로우 콜 ≤6), count × tris는 로드 시 예산 검사. seed로 가지와 잎이 전부 재현되고 height는 인스턴스마다 ±20% 지터링, 잎은 심플렉스 바람에 흔들립니다.`}),Q(`VoxelGrid3D`,{en:`A Minecraft-style block grid in ONE node.`,ko:`마인크래프트식 블록 그리드 — 노드 하나로.`},{en:`voxels is a list of [x,y,z,palette] integer cells (terrain/island generators emit these). Greedy-meshed and instanced — large worlds stay one draw batch. Game code edits blocks via setBlock/getBlock; emits blocksChanged.`,ko:`voxels는 [x,y,z,팔레트] 정수 셀 목록입니다(terrain/island 생성기가 만들어 냅니다). 그리디 메싱+인스턴싱으로 큰 월드도 드로우 배치 하나를 유지합니다. 게임 코드는 setBlock/getBlock으로 수정하고 blocksChanged가 발산됩니다.`})]},{id:`3d-physics`,label:{en:`3D Physics`,ko:`3D 물리`},intro:{en:`Same model as 2D, in meters with y-up gravity ([0,-9.81,0] default). Colliders: box {size}, sphere {radius}, capsule {radius,height}.`,ko:`2D와 같은 모델을 미터·y-위 중력([0,-9.81,0] 기본)으로. 콜라이더는 box {size}, sphere {radius}, capsule {radius,height}.`},nodes:[Q(`StaticBody3D`,{en:`Immovable 3D collision.`,ko:`움직이지 않는 3D 충돌체.`},{en:`Floors, walls, level geometry. collider {shape:"auto"} takes the shape from the MeshInstance3D or ModelInstance3D the body carries as a child, so the blocker can never be bigger or smaller than what the player sees — the fix for hand-typed extents that leave you stopping in mid-air. A GLB becomes a triangle mesh here, holes and all.`,ko:`바닥·벽·레벨 지형. collider {shape:"auto"}는 바디가 자식으로 들고 있는 MeshInstance3D 또는 ModelInstance3D의 생김새를 그대로 씁니다 — 보이는 것보다 크거나 작은 콜라이더가 생길 수 없습니다. 손으로 적은 크기 때문에 허공에서 막히는 문제의 해법입니다. GLB는 여기서 구멍까지 살아있는 트라이메시가 됩니다.`}),Q(`RigidBody3D`,{en:`Simulated 3D body.`,ko:`시뮬레이션되는 3D 바디.`},{en:`Crates, balls, debris — gravity and impacts drive it.`,ko:`상자·공·파편 — 중력과 충격이 움직입니다.`}),Q(`CharacterBody3D`,{en:`Kinematic 3D character.`,ko:`키네마틱 3D 캐릭터.`},{en:`moveAndSlide with up = +y; isOnFloor for jumps.`,ko:`+y를 위로 moveAndSlide, 점프 판정은 isOnFloor.`}),Q(`Area3D`,{en:`3D overlap sensor.`,ko:`3D 겹침 센서.`},{en:`triggerEnter/Exit — pickups, zones, goals.`,ko:`triggerEnter/Exit — 아이템·존·골인 지점.`}),Q(`CharacterController3D`,{en:`Zero-code 3D movement + camera rig.`,ko:`코드 없는 3D 이동 + 카메라 리그.`},{en:`Put it UNDER a CharacterBody3D. view: thirdPerson (orbit + zoom), firstPerson (eyeHeight, mouseLook), sideView or flightView. Reads moveAction/jumpAction/sprintAction from the scene input map; skinPath turns the visual child to face travel. Intent-level numbers: maxSpeed, jumpVelocity, camDistance.`,ko:`CharacterBody3D의 자식으로 두세요. view는 thirdPerson(궤도+줌), firstPerson(eyeHeight, mouseLook), sideView, flightView 중 하나입니다. 씬 입력 맵의 moveAction/jumpAction/sprintAction을 읽고 skinPath의 비주얼 자식을 진행 방향으로 돌립니다. maxSpeed·jumpVelocity·camDistance 같은 의도 수준의 숫자만 만집니다.`}),Q(`BoneLookAt3D`,{en:`Look-at IK for one bone — the head turns toward a target on top of the animation.`,ko:`본 하나의 룩앳 IK — 애니메이션 위에서 머리가 대상을 향해 돌아갑니다.`},{en:`"target" = ModelInstance3D path, "bone" = bone name (default Head), "lookAt" = the node to watch (e.g. "%Player"). Blends in/out smoothly and DISENGAGES beyond maxAngleDeg (no owl necks); weight sets how far it commits. forwardAxis names the bone's facing axis (mixamo heads: +z). Purely visual — headless no-op.`,ko:`"target"에 ModelInstance3D 경로, "bone"에 본 이름(기본 Head), "lookAt"에 바라볼 노드(예: "%Player")를 줍니다. 부드럽게 페이드 인/아웃하고 maxAngleDeg 밖에서는 해제됩니다(목이 돌아가지 않음). weight로 몰입도를 조절하고 forwardAxis는 본의 정면 축입니다(mixamo 머리: +z). 순수 시각 기능 — 헤드리스에서는 no-op.`}),Q(`InstancedMesh3D`,{en:`Hundreds of copies of one mesh in ONE draw call — rocks, posts, crates.`,ko:`메시 하나의 수백 개 복사본을 드로우콜 1개로 — 바위, 말뚝, 상자.`},{en:`Same mesh/size/material surface as MeshInstance3D; "transforms" places the copies — each row [x, y, z, yawDeg?, scale?]. Replace the whole array to update (mutations are not watched). The scattering workhorse for open worlds. collider: {} makes the whole field solid — every row gets its own collider SHAPED LIKE THE MESH (a faceted gem stone collides as that stone's hull, not as a ball tucked inside it), all hanging off one fixed body. A boulder field the player walks straight through is the tell that a world is scenery rather than a place.`,ko:`MeshInstance3D와 같은 mesh/size/material 표면에 "transforms"로 복사본을 배치합니다 — 각 행은 [x, y, z, yawDeg?, scale?]. 갱신은 배열 전체 교체로 하세요(내부 변경은 감지되지 않음). 오픈월드 스캐터링의 주력입니다. collider: {}를 주면 필드 전체가 단단해집니다 — 행마다 메시 생김새 그대로의 콜라이더가 생기고(각진 gem 바위는 안에 박힌 구가 아니라 그 바위 자신의 볼록 껍질로 부딪힙니다), 전부 하나의 고정 바디에 붙습니다. 플레이어가 통과해버리는 바위밭은 그 세계가 배경 그림이라는 신호입니다.`}),Q(`BoneAttachment3D`,{en:`Rides a skeleton bone of an animated model — swords in hands, hats on heads.`,ko:`애니메이션 모델의 스켈레톤 본을 따라다님 — 손에 쥔 검, 머리 위 모자.`},{en:`"target" is a node path to the ModelInstance3D, "bone" the bone name ("RightHand" also matches the Mixamo spellings). Children inherit the live animated transform; this node's own position/rotation become a bone-space offset. Purely visual — headless it stays where its props put it, so keep gameplay checks range-based.`,ko:`"target"에 ModelInstance3D 노드 경로, "bone"에 본 이름을 줍니다("RightHand"는 Mixamo 표기도 자동 매칭). 자식들이 살아있는 애니메이션 트랜스폼을 물려받고, 이 노드의 position/rotation은 본 기준 오프셋이 됩니다. 순수 시각 기능 — 헤드리스에서는 prop 위치에 머무니 게임 판정은 거리 기반으로 유지하세요.`}),Q(`Trail3D`,{en:`A fading world-space ribbon behind the parent — wingtip trails, sword arcs, tyre streaks.`,ko:`부모 뒤로 남는 페이드아웃 월드 리본 — 날개끝 궤적, 검격 궤적, 타이어 자국.`},{en:"Child of the moving node. Records the world position over `seconds` and renders a camera-facing strip that tapers and fades to the tail. width (m), color, opacity, additive for glowing energy trails, minDistance filters jitter. emitting: false stops laying new ribbon while the old tail fades out.",ko:`움직이는 노드의 자식으로 두세요. seconds 동안의 월드 위치를 기록해 꼬리로 갈수록 가늘어지고 투명해지는 카메라 지향 스트립을 그립니다. width(m), color, opacity, 빛나는 에너지 궤적에는 additive, minDistance로 떨림을 걸러냅니다. emitting: false면 새 리본만 멈추고 기존 꼬리는 자연스럽게 사라집니다.`}),Q(`Joint3D`,{en:`A physics joint linking its parent body to a target body — weld, ball joint, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 볼 조인트, 로프, 스프링.`},{en:`Child of body A; "target" is a node path to body B. type: fixed (rigid weld) / spherical (ball joint at the anchors) / rope (caps anchor distance at length m; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL meter offsets.`,ko:`바디 A의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / spherical(앵커 볼 조인트) / rope(앵커 간 거리를 length m로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 미터 오프셋.`})]},{id:`network`,label:{en:`Network`,ko:`네트워크`},intro:{en:`Multiplayer is transport-agnostic: the engine speaks one NetworkTransport interface (built-in offline Loopback + an @agent8/gameserver adapter). The scene declares replication; one owner node per player broadcasts its sync keys.`,ko:`멀티플레이어는 트랜스포트 불가지론입니다 — 엔진은 NetworkTransport 인터페이스 하나만 사용합니다(내장 오프라인 Loopback + @agent8/gameserver 어댑터). 복제는 씬이 선언하며, 플레이어당 하나의 owner 노드가 sync 키를 송출합니다.`},nodes:[Q(`NetworkSpawner`,{en:`Spawns a registered scene per remote player/entity.`,ko:`원격 플레이어/엔티티마다 등록된 씬을 생성.`},{en:`source "users" mirrors every OTHER account in the room (self skipped); "collection:<id>" mirrors a room collection. Replicated sync patches apply to each instance; position interpolates. Emits spawned/despawned.`,ko:`source "users"는 방의 다른 모든 계정을 미러링하고(자신 제외) "collection:<id>"는 방 컬렉션을 미러링합니다. 복제 sync 패치가 인스턴스에 적용되고 position은 보간됩니다. spawned/despawned를 발산합니다.`})]}],LF=`overview`,RF=null;function zF(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),HF()}function BF(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function VF(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&BF()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,BF))}function HF(){let e=document.querySelector(`#docs-tabs`),t=document.querySelector(`#docs-body`);if(!e||!t)return;e.textContent=``;let n=(t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`docs-tab${LF===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{LF=t,RF=null,HF()}),e.appendChild(r)};n(`overview`,JP({en:`Overview`,ko:`개요`}));for(let e of IF)n(e.id,JP(e.label));if(t.textContent=``,LF===`overview`){UF(t);return}let r=IF.find(e=>e.id===LF);r&&WF(t,r)}function UF(e){let t=document.createElement(`h2`);t.textContent=JP(FF.title),e.appendChild(t);for(let t of FF.sections){let n=document.createElement(`h3`);n.textContent=JP(t.heading);let r=document.createElement(`p`);r.textContent=JP(t.text),e.append(n,r)}}function WF(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=JP(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${RF===n.type?` open`:``}`;let r=document.createElement(`button`);r.type=`button`,r.className=`docs-node-head`;let i=document.createElement(`span`);i.className=`tree-icon`,i.appendChild(ZP(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=JP(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{RF=RF===n.type?null:n.type,HF()}),t.appendChild(r),RF===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=JP(t),e.appendChild(n)}e.appendChild(GF(n.type)),t.appendChild(e)}e.appendChild(t)}}function GF(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[JP({en:`prop`,ko:`prop`}),JP({en:`default`,ko:`기본값`})]){let t=document.createElement(`th`);t.textContent=e,n.appendChild(t)}t.appendChild(n);try{let n=qe(e);for(let[e,r]of Object.entries(n)){let n=document.createElement(`tr`),i=document.createElement(`td`);i.className=`mono`,i.textContent=e;let a=document.createElement(`td`);a.className=`mono`,a.textContent=JSON.stringify(r.default),n.append(i,a),t.appendChild(n)}}catch{}return t}function $(e){return Math.round(e*100)/100}function KF(e,t,n,r,i){return{name:e,type:`StaticBody3D`,props:{collider:{shape:`box`,size:t},position:n,...i?{rotation:i}:{}},children:[{name:`Skin`,type:`MeshInstance3D`,props:{mesh:`box`,size:t,...r}}]}}function qF(e,t,n,r,i,a){let o=$(r.range(i[0],i[1])),s=$(r.range(.5,.7));return{name:`Rock${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[t,$(o*s*.6),n],rotation:[0,r.int(0,359),0],scale:[o,$(o*s),$(o*r.range(.8,1.1))],material:{color:a??JF(r),roughness:1},castShadow:!0}}}function JF(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function YF(e){return[{name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(e*.8),$(e*1.5),$(e*.6)],intensity:1,castShadow:!0,shadowArea:$(e*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-e*.8),$(e*.8),$(-e*.6)],intensity:.4,color:`#b9d4ff`}}]}function XF(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function ZF(e,t,n){return Math.min(Math.max(e,t),n)}var QF=[`boxes`,`ruins`,`garden`],$F=.5,eI=.1,tI=2,nI={boxes:{floor:`#3f3f3f`,wall:`#55504a`,obstacles:[`#b0413e`,`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#878787`]},ruins:{floor:`#7d766b`,wall:`#8a8378`,obstacles:[`#8a8378`,`#979085`,`#a39a8d`,`#7b746a`]},garden:{floor:`#4d7c3a`,wall:`#2f6b2f`,obstacles:[`#2f6b2f`,`#3a7a38`,`#356e33`]}};function rI(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!QF.includes(o))throw new N(`BAD_FORMAT`,`generateArena theme must be one of [${QF.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...QF]});let s=nI[o],c=new P(t),l=[KF(`Floor`,[n,eI,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+$F*2,i,$F],f=[$F,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(KF(`Wall1`,d,[0,u,-(r+$F)/2],p),KF(`Wall2`,d,[0,u,(r+$F)/2],p),KF(`Wall3`,f,[-(n+$F)/2,u,0],p),KF(`Wall4`,f,[(n+$F)/2,u,0],p)),o===`ruins`?l.push(...aI(c,s,n,r,i,a)):l.push(...iI(c,s,n,r,i,a,o)),o===`garden`&&l.push(...oI(c,n,r));let m=Math.max(n,r);return l.push({name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(m*.8),$(m*1.5),$(m*.6)],intensity:1,castShadow:!0,shadowArea:$(m*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-m*.8),$(m*.8),$(-m*.6)],intensity:.4,color:`#b9d4ff`}},{name:`Lamp`,type:`OmniLight3D`,props:{position:[0,$(i+2),0],intensity:.5,color:`#fff3d6`,range:$(m)}}),{name:`Arena`,type:`Node3D`,children:l}}function iI(e,t,n,r,i,a,o){let s=[],c=o===`garden`?Math.min(n,r)*.16:0;for(let o=1;o<=a;o++){let a=[$(e.range(.8,2.6)),$(e.range(.8,Math.max(1.2,i*.8))),$(e.range(.8,2.6))],l=$(e.range(-(n/2-tI),n/2-tI)),u=$(e.range(-(r/2-tI),r/2-tI));if(c>0&&Math.hypot(l,u)<c+1.5){let t=Math.max(Math.hypot(l,u),.001);l=$(l/t*(c+1.5+e.range(0,2))),u=$(u/t*(c+1.5+e.range(0,2)))}let d=e.int(0,359);s.push(KF(`Obstacle${o}`,a,[l,$(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function aI(e,t,n,r,i,a){let o=[];if(a<=0)return o;let s=Math.max(1,Math.round(Math.sqrt(a/2))),c=Math.ceil(a/s),l=n-tI*2,u=r-tI*2,d=0;for(let n=0;n<s&&d<a;n++){let r=$(s===1?0:-u/2+n/(s-1)*u);for(let n=0;n<c&&d<a;n++){d++;let a=$((c===1?0:-l/2+n/(c-1)*l)+e.range(-.4,.4)),s=$(e.next()>.35?e.range(i*.7,i*1.2):e.range(.4,.9)),u=$(e.range(.8,1.2));o.push(KF(`Obstacle${d}`,[u,s,u],[a,$(s/2),$(r+e.range(-.4,.4))],{material:{color:e.pick(t.obstacles),roughness:.95},castShadow:!0},[0,e.int(-8,8),0]))}}return o}function oI(e,t,n){let r=[],i=Math.min(t,n)*.16,a=r=>{let a=Math.min(t,n)/2-r/2-1,o=$(e.range(-a,a)),s=$(e.range(-a,a)),c=Math.max(Math.hypot(o,s),.001);return c<i+r/2&&(o=$(o/c*(i+r/2+.5)),s=$(s/c*(i+r/2+.5))),[o,s]};for(let i=1;i<=3;i++){let o=$(Math.min(t,n)*e.range(.18,.26)),[s,c]=a(o);r.push({name:`Grass${i}`,type:`Foliage3D`,props:{kind:`grass`,area:[o,o],density:10,seed:e.int(1,1e9),position:[s,0,c]}})}for(let i=1;i<=2;i++){let o=$(Math.min(t,n)*e.range(.12,.18)),[s,c]=a(o);r.push({name:`FlowerBed${i}`,type:`Flowers3D`,props:{density:`lush`,clustering:.3,area:[o,o],seed:e.int(1,1e9),position:[s,0,c]}})}return r.push({name:`Pool`,type:`Water3D`,props:{size:[$(i*2),$(i*2)],position:[0,.3,0],waveHeight:.04}}),r}var sI=32,cI=[4,8],lI=`#332f3a`,uI=`#6b6357`;function dI(e){let{seed:t,rooms:n=5}=e,[r,i]=XF(e.size,[960,720]),a=Math.max(8,Math.floor(r/sI)),o=Math.max(8,Math.floor(i/sI)),s=new P(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(cI[0],cI[1]),t=s.int(cI[0],cI[1]),n={x:s.int(1,Math.max(1,a-e-1)),y:s.int(1,Math.max(1,o-t-1)),w:e,h:t};c.some(e=>fI(e,n,1))||c.push(n)}let l=new Set,u=e=>{for(let t=e.y;t<e.y+e.h;t++)for(let n=e.x;n<e.x+e.w;n++)l.add(`${n},${t}`)};for(let e of c)u(e);let d=[];for(let e=1;e<c.length;e++){let[t,n]=pI(c[e-1]),[r,i]=pI(c[e]),a={x:Math.min(t,r),y:n,w:Math.abs(t-r)+1,h:1},o={x:r,y:Math.min(n,i),w:1,h:Math.abs(n-i)+1};for(let[t,n]of[[`H`,a],[`V`,o]])u(n),(n.w>1||n.h>1)&&d.push({name:`Corridor${e}${t}`,rect:n})}let f=new Set;for(let e of l){let[t,n]=e.split(`,`).map(Number);for(let e=-1;e<=1;e++)for(let r=-1;r<=1;r++){let i=`${t+r},${n+e}`;l.has(i)||f.add(i)}}let p=-(a*sI)/2,m=-(o*sI)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*sI,m+(t.y+t.h/2)*sI],size:[t.w*sI,t.h*sI],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,lI));for(let e of d)g.push(h(e.name,e.rect,lI));let _=0;for(let e=-1;e<=o;e++){let t=-1;for(;t<=a;){if(!f.has(`${t},${e}`)){t++;continue}let n=1;for(;t+n<=a&&f.has(`${t+n},${e}`);)n++;_++;let r=[n*sI,sI];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*sI,m+(e+.5)*sI],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:uI}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function fI(e,t,n){return e.x-n<t.x+t.w&&e.x+e.w+n>t.x&&e.y-n<t.y+t.h&&e.y+e.h+n>t.y}function pI(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var mI=[[0,-1],[1,0],[0,1],[-1,0]];function hI(e,t,n){let r=2*t+1,i=2*n+1,a=Array.from({length:i},()=>Array(r).fill(!1)),o=(e,t)=>{a[t][e]=!0};o(1,1);let s=new Set([`0,0`]),c=[[0,0]];for(;c.length>0;){let[r,i]=c[c.length-1],a=[];for(let[e,o]of mI){let c=r+e,l=i+o;c>=0&&c<t&&l>=0&&l<n&&!s.has(`${c},${l}`)&&a.push([c,l])}if(a.length===0){c.pop();continue}let[l,u]=e.pick(a);s.add(`${l},${u}`),o(2*l+1,2*u+1),o(r+l+1,i+u+1),c.push([l,u])}return o(0,1),o(2*t,2*n-1),{cols:t,rows:n,cells:a}}var gI=[`stone`,`hedge`,`canyon`],_I=.1,vI=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,yI=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,bI={stone:{wall:{color:`#e8e2d8`,map:`${vI}/blocks.png`,normalMap:`${vI}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${yI}/stone.png`,normalMap:`${yI}/stone_normal.png`,tile:3,roughness:1},cap:`#6b5848`,pillar:`#cfc8bb`,path:`#665f55`,sun:{color:`#c9d6ea`,intensity:.75,height:.5},fill:`#9fb4cc`,mood:{sky:{elevationDeg:10,azimuthDeg:150,turbidity:16,rayleigh:3.2},fog:{near:.5,far:3.5,color:`#86909c`},exposure:.82,ambient:{color:`#c9d4e2`,intensity:.12}}},hedge:{wall:{color:`#55a83e`,map:`${yI}/grass.png`,normalMap:`${yI}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${yI}/grass.png`,normalMap:`${yI}/grass_normal.png`,tile:3,roughness:1},pillar:`#3d7531`,path:`#7d6845`,sun:{color:`#e9eee6`,intensity:.7,height:1},fill:`#b9c8b4`,mood:{sky:{elevationDeg:35,azimuthDeg:150,turbidity:18,rayleigh:4.2},fog:{near:.8,far:5,color:`#aab8a6`},exposure:.88,ambient:{color:`#dde5d8`,intensity:.15}}},canyon:{wall:{color:`#f0b070`,map:`${yI}/stone.png`,normalMap:`${yI}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${yI}/sand.png`,normalMap:`${yI}/sand_normal.png`,tile:3.5,roughness:1},pillar:`#d8a868`,path:`#a98a58`,sun:{color:`#ffb572`,intensity:1.15,height:.35},fill:`#caa37e`,mood:{sky:{elevationDeg:9,azimuthDeg:230,turbidity:9,rayleigh:3.5},fog:{near:.7,far:4.5,color:`#c79c6e`},exposure:.92,ambient:{color:`#ffdcb6`,intensity:.13}}}};function xI(e,t,n){return{color:e.color,roughness:e.roughness,map:e.map,...e.normalMap?{normalMap:e.normalMap}:{},repeat:[$(t/e.tile),$(n/e.tile)]}}var SI=10;function CI(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!gI.includes(o))throw new N(`BAD_FORMAT`,`generateMaze theme must be one of [${gI.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...gI]});let s=bI[o],c=new P(t),l=hI(c,n,r),u=2*n+1,d=2*r+1,f=$(u*i),p=$(d*i),m=(e,t)=>[$((e+.5)*i-f/2),$((t+.5)*i-p/2)],h=[KF(`Floor`,[f,_I,p],[0,-.1/2,0],{material:xI(s.floor,f,p),receiveShadow:!0})],g=[],_=0;for(let e=0;e<d;e++){let t=0;for(;t<u;){if(l.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<u&&!l.cells[e]?.[t+n];)n++;g.push({gx:t,gz:e,run:n}),_++;let r=$(n*i);h.push(KF(`Wall${_}`,[r,a,i],[$((t+n/2)*i-f/2),$(a/2),$((e+.5)*i-p/2)],{material:xI(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...wI(g,i,a,f,p,s.cap)),h.push(...TI(c,l,i,a,m,s)),o===`hedge`?(h.push(...kI(c,g,i,a,m)),h.push(...AI(c,l,i,m,n,r))):o===`canyon`&&h.push(...jI(c,g,i,a,m)),h.push(...DI(l,i,a,m,s)),h.push(...YF(Math.max(f,p)).map((e,t)=>{if(t!==0)return{...e,props:{...e.props,color:s.fill}};let n=e.props?.position;return{...e,props:{...e.props,color:s.sun.color,intensity:s.sun.intensity,position:[n[0]??0,$((n[1]??0)*s.sun.height),n[2]??0]}}})),{name:`Maze`,type:`Node3D`,children:h}}function wI(e,t,n,r,i,a){return e.map((e,o)=>({name:`Cap${o+1}`,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(e.run*t+.16),.12,$(t+.16)],position:[$((e.gx+e.run/2)*t-r/2),$(n+.06),$((e.gz+.5)*t-i/2)],material:{color:a,roughness:1},castShadow:!0,receiveShadow:!0}}))}function TI(e,t,n,r,i,a){let o=[],s=(e,n)=>t.cells[n]?.[e]===!1;for(let e=2;e<t.cells.length-1;e+=2)for(let n=2;n<(t.cells[e]?.length??0)-1;n+=2)s(n,e)&&Number(s(n-1,e))+Number(s(n+1,e))+Number(s(n,e-1))+Number(s(n,e+1))>=3&&o.push([n,e]);let c=Math.min(SI,o.length),l=[],u=new Set,d=$(n*1.2),f=$(r*1.12);for(let t=1;t<=c;t++){let n=e.int(0,o.length-1);for(;u.has(n);)n=(n+1)%o.length;u.add(n);let[r,s]=o[n],[c,p]=i(r,s);l.push(EI(`Pillar${t}`,c,p,d,f,a))}return l}function EI(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,$(i/2),n],material:{...xI(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function DI(e,t,n,r,i){let a=2*e.cols,o=2*e.rows-1,s=$(t*1.1),c=$(n*1.25),l=[[0,0],[0,2],[a,o-1],[a,o+1]].map(([e,t],n)=>{let[a,o]=r(e,t);return EI(`Gate${n+1}`,a,o,s,c,i)});for(let[e,n,s]of[[`EntrancePath`,0,1],[`ExitPath`,a,o]]){let[a,o]=r(n,s);l.push({name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(t*.96),.04,$(t*.96)],position:[a,.02,o],material:{...xI(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var OI=10;function kI(e,t,n,r,i){return[...t].filter(e=>e.run>=2).sort((e,t)=>t.run-e.run||e.gz-t.gz||e.gx-t.gx).slice(0,OI).map((t,a)=>{let[,o]=i(t.gx,t.gz),[s]=i(t.gx,t.gz),[c]=i(t.gx+t.run-1,t.gz);return{name:`HedgeTop${a+1}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[$(t.run*n*.92),$(n*.7)],density:14,height:.35,sway:.4,colorA:`#2f5e26`,colorB:`#5d8a3c`,seed:e.int(1,1e9),position:[$((s+c)/2),r,o]}}})}function AI(e,t,n,r,i,a){let o=[];for(let e=0;e<t.cells.length;e++)for(let n=0;n<(t.cells[e]?.length??0);n++)t.cells[e]?.[n]&&o.push([n,e]);let s=Math.min(o.length,Math.max(3,Math.floor(i*a/12))),c=[],l=new Set;for(let t=1;t<=s&&l.size<o.length;t++){let i=e.int(0,o.length-1);for(;l.has(i);)i=(i+1)%o.length;l.add(i);let[a,s]=o[i],[u,d]=r(a,s),f=$(n*.8);c.push({name:`Grass${t}`,type:`Foliage3D`,props:{kind:`grass`,area:[f,f],density:8,seed:e.int(1,1e9),position:[u,0,d]}})}return c}function jI(e,t,n,r,i){let a=[];if(t.length===0)return a;let o=Math.min(8,t.length);for(let s=1;s<=o;s++){let o=e.pick(t),[c,l]=i(o.gx+e.int(0,o.run-1),o.gz),u=qF(s,c,l,e,[.3,$(n*.35)],`#8f7355`),d=u.props?.position;d[1]=$(d[1]+r),a.push(u)}return a}var MI=`#23222b`,NI=`#5f6672`;function PI(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=hI(new P(t),n,r),o=2*n+1,s=2*r+1,c=$(o*i),l=$(s*i),u=[{name:`Floor`,type:`ColorRect2D`,props:{size:[c,l],color:MI}}],d=0;for(let e=0;e<s;e++){let t=0;for(;t<o;){if(a.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<o&&!a.cells[e]?.[t+n];)n++;d++;let r=[$(n*i),i];u.push({name:`Wall${d}`,type:`StaticBody2D`,props:{position:[$((t+n/2)*i-c/2),$((e+.5)*i-l/2)],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:NI}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var FI=16,II=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function LI(e){let{seed:t,count:n=10,width:r=[80,160],gapX:i=[40,120],stepY:a=[-80,40],start:o=[0,300]}=e,s=new P(t),c=[],l=$(s.range(r[0],r[1])),u=o[0],d=o[1];for(let e=1;e<=n&&(c.push(RI(e,u,d,l,s.pick(II))),e!==n);e++){let e=$(s.range(r[0],r[1])),t=$(s.range(i[0],i[1]));u=$(u+l/2+t+e/2),d=$(d+s.range(a[0],a[1])),l=e}return{name:`Platforms`,type:`Node2D`,children:c}}function RI(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,FI]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,FI],color:i}}]}}var zI=[3,5],BI=3,VI={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function HI(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=XF(e.area,[60,60]),o=new P(t),s=[];for(let e=1;e<=n;e++){let t=o.int(zI[0],zI[1]),n=[];for(let e=1;e<=t;e++){let r=$(o.range(1,2.2));n.push({name:`Puff${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[$((e-(t+1)/2)*o.range(1,1.6)),$(o.range(-.3,.3)),$(o.range(-.6,.6))],scale:[$(r*o.range(1.1,1.6)),$(r*.55),r],material:VI}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[$(o.range(-i/2,i/2)),$(r+o.range(-3,BI)),$(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,children:s}}var UI=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],WI=128,GI=20,KI=.8,qI=.12,JI={island:{splat:`island`,maxHeight:4.5,sun:`#fff4d6`,fill:`#b9d4ff`,sky:{elevationDeg:38,azimuthDeg:145,turbidity:2.6,rayleigh:1.1},fog:{near:1,far:4},iblIntensity:.72},alpine:{splat:`alpine`,maxHeight:8,roughness:.65,detail:5,sun:`#f4f7ff`,fill:`#c9d8f2`,sky:{elevationDeg:45,azimuthDeg:35,turbidity:1.4,rayleigh:1.3},fog:{near:1.8,far:6.5},sunIntensity:1.1,exposure:.92,iblIntensity:.72},plains:{splat:`plains`,maxHeight:4,sun:`#fff2cf`,fill:`#bcd3ef`,sky:{elevationDeg:36,azimuthDeg:140,turbidity:2.4,rayleigh:1},fog:{near:.9,far:4},iblIntensity:.58},desert:{splat:`desert`,maxHeight:5,sun:`#ffe3b3`,fill:`#e8c9a6`,sky:{elevationDeg:42,azimuthDeg:160,turbidity:7,rayleigh:.6},fog:{near:.8,far:3.2,color:`#e8d3ae`},sunIntensity:1.35,iblIntensity:.75},meadow:{splat:`grassland`,maxHeight:1.2,sun:`#fff8e2`,fill:`#bfe0c9`,sky:{elevationDeg:55,azimuthDeg:125,turbidity:2.4,rayleigh:.95},fog:{near:1,far:4.4},sunIntensity:2.6,exposure:1.12,iblIntensity:.62},forest:{splat:`forest`,maxHeight:2.5,sun:`#ffdca8`,fill:`#a9c8b4`,sky:{elevationDeg:29,azimuthDeg:120,turbidity:5.5,rayleigh:1},fog:{near:.22,far:1.8,color:`#9fb494`},sunIntensity:2.6,ambient:.26,iblIntensity:.55},savanna:{splat:`savanna`,maxHeight:3,sun:`#ffdca0`,fill:`#e6d2a4`,sky:{elevationDeg:34,azimuthDeg:150,turbidity:5,rayleigh:.7},fog:{near:1,far:4.2,color:`#e3cf9f`},sunIntensity:2,exposure:1.05,iblIntensity:.6},snow:{splat:`snow`,maxHeight:2.2,sun:`#dfe9ff`,fill:`#c2d2f0`,sky:{elevationDeg:22,azimuthDeg:35,turbidity:1.6,rayleigh:1.6},fog:{near:1.2,far:5,color:`#dbe6f5`},sunIntensity:1,exposure:.9,iblIntensity:.72},wetland:{splat:`wetland`,maxHeight:1.4,sun:`#d6ddc8`,fill:`#9fb29a`,sky:{elevationDeg:24,azimuthDeg:115,turbidity:9,rayleigh:1.1},fog:{near:.5,far:2,color:`#92a288`},sunIntensity:1.5,exposure:.94,ambient:.24,iblIntensity:.66},volcanic:{splat:`volcanic`,maxHeight:4,roughness:.7,sun:`#ff8a4a`,fill:`#7a4a3a`,sky:{elevationDeg:14,azimuthDeg:135,turbidity:10,rayleigh:.3},fog:{near:.18,far:1.4,color:`#2a211c`},sunIntensity:1.7,exposure:.86,ambient:.22,iblIntensity:.5}};function YI(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=JI[n];if(!a)throw new N(`BAD_FORMAT`,`generateTerrain theme must be one of [${UI.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...UI]});let o=Math.max(2,Math.round(e.resolution??WI)),s=e.maxHeight||a.maxHeight,c=new P(t),l=n===`island`,u=e=>Bw({width:r,depth:r,segsX:o,segsZ:o,maxHeight:e,seed:t,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},islandEdge:l}),d=u(s);if(l)for(let e=0;e<3;e++){let e=ZI(d)-GI,t=d.maxHeight-d.minHeight,n=d.minHeight+qI*t;if(e+KI<=n)break;let r=GI-KI,i=ZI(d)-d.minHeight-qI*t;s=$(s*Math.min(r/i*.95,.9)),d=u(s)}let f=[{name:`Ground`,type:`StaticBody3D`,props:{collider:{shape:`heightfield`}},children:[{name:`Surface`,type:`Terrain3D`,props:{size:[r,r],maxHeight:s,seed:t,theme:a.splat,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},...o===WI?{}:{resolution:o}}}]}],p=n===`wetland`;if(l)f.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,XI(d),0],opacity:1}});else if(p){let e=d.maxHeight-d.minHeight||1,t=$(d.minHeight+.22*e);f.push({name:`Swamp`,type:`Water3D`,props:{size:[r,r],position:[0,t,0],waveHeight:.02,quality:`simple`,color:`#3a4a30`,opacity:.95}})}else if(i){let e=$(d.minHeight+.1*(d.maxHeight-d.minHeight));f.push({name:`Lake`,type:`Water3D`,props:{size:[r,r],position:[0,e,0],waveHeight:.04}})}return f.push(...pL(n,c,d,r)),l&&f.push(HI({seed:c.int(1,1e9),count:6,area:r,altitude:Math.round(d.maxHeight+12)})),f.push(...YF(r).map((e,t)=>mL(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:f}}function XI(e){let t=ZI(e)-GI,n=e.minHeight+qI*(e.maxHeight-e.minHeight);return $(Math.max(Math.min(t+KI,n),t+.55))}function ZI(e){let t=-1/0,n=e.width/2,r=e.depth/2,i=e.segsX;for(let a=0;a<=i;a++){let o=-n+a/i*e.width,s=-r+a/i*e.depth;t=Math.max(t,e.baseHeight(o,-r),e.baseHeight(o,r),e.baseHeight(-n,s),e.baseHeight(n,s))}return t}function QI(e,t,n){let r=Math.min(t.width/2-n.margin,n.within??1/0),i=t.maxHeight-t.minHeight||1,a=[];for(let o=0;o<n.count*30&&a.length<n.count;o++){let o=$(e.range(-r,r)),s=$(e.range(-r,r));if(n.clearing&&Math.hypot(o,s)<n.clearing||n.within&&Math.hypot(o,s)>n.within)continue;let c=t.heightAt(o,s),l=(c-t.minHeight)/i;l<n.band[0]||l>n.band[1]||t.slopeAt(o,s)>n.maxSlope||a.push({x:o,z:s,y:c})}return a}var $I=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],eL=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],tL={canopy:`#9aa052`,trunk:`#8a6a44`},nL={canopy:`#39513f`,trunk:`#5a5650`};function rL(e,t){return e===`conifer`?t.pick($I):e===`broadleaf`?t.pick(eL):null}function iL(e,t,n,r,i){let a=i?.height??[4.5,7],o=i?.sink??(i?.count===void 0?.05:.3),s={};i?.tier!==void 0&&(s.tier=i.tier),i?.count!==void 0&&i.area!==void 0&&(s.count=i.count,s.area=[i.area,i.area]);let c=rL(r,n),l=i?.palette??c;return l&&(s.canopyColor=l.canopy,s.trunkColor=l.trunk),{name:e,type:`Tree3D`,props:{type:r,seed:n.int(1,1e9),height:$(n.range(a[0],a[1])),position:[t.x,$(t.y-o),t.z],...s}}}function aL(e,t,n,r,i,a=0,o){return{name:e,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[r,r],density:i,height:o?.height??.3,...o?.colors?{colorA:o.colors[0],colorB:o.colors[1]}:{},seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z],...a>0?{flowers:a}:{}}}}function oL(e,t,n,r,i){return{name:e,type:`Foliage3D`,props:{kind:`reeds`,style:`simple`,area:[r,r],density:i,height:.9,colorA:`#2f4a26`,colorB:`#5a6f33`,seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function sL(e,t,n,r,i){return{name:e,type:`Flowers3D`,props:{density:i,area:[r,r],seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function cL(e,t,n,r){return e.map((e,i)=>{let a=qF(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=$(o[1]+e.y),a})}function lL(e){let t=Math.round(e.range(104,128)),n=Math.round(t-e.range(10,18)),r=Math.round(t-e.range(20,30)),i=e=>e.toString(16).padStart(2,`0`);return`#${i(n)}${i(t)}${i(r)}`}function uL(e){let t=Math.round(e.range(196,224)),n=Math.min(255,t+Math.round(e.range(4,12))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(t)}${r(t)}${r(n)}`}function dL(e){let t=Math.round(e.range(34,56)),n=Math.min(255,t+Math.round(e.range(2,8))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(n)}${r(t)}${r(t)}`}var fL=[`#6f5b41`,`#7a644a`,`#665439`];function pL(e,t,n,r){let i=[];switch(e){case`island`:{let e=QI(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>iL(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=QI(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>iL(`Tree${n+1}`,e,t,`conifer`)));let r=QI(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...cL(r,t,[.6,1.8]));break}case`plains`:{let e=QI(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>iL(`Tree${n+1}`,e,t,`broadleaf`)));let r=QI(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...cL(r,t,[.4,1.2]));break}case`desert`:{let e=QI(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>iL(`Tree${n+1}`,e,t,`dead`)));let r=QI(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...cL(r,t,[.5,1.6]));break}case`meadow`:{let e=$(r*.09),a=QI(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>aL(`Carpet${r+1}`,n,t,e,30)));let o=$(r*.07),s=QI(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>sL(`Flowers${n+1}`,e,t,o,`sparse`)));let c=QI(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>iL(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=QI(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...cL(l,t,[.3,.9]));break}case`forest`:{let e=$(r*.12),a=r/2-8,o=cn(t.int(1,1e9)),s=(e,t,n)=>{let r=o(e/70,t/70);return r>.12?`conifer`:r<-.12?`broadleaf`:n%2==0?`conifer`:`broadleaf`},c=QI(t,n,{count:40,band:[0,1],maxSlope:.18,margin:8,clearing:e+6}),l=c.map((e,t)=>s(e.x,e.z,t));i.push(...c.map((e,n)=>iL(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(iL(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=QI(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>iL(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=QI(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>iL(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=QI(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>iL(`Bush${n+1}`,e,t,`bush`,{count:4,area:10,height:[2.1,3.1],sink:.12})));let p=0;c.forEach((e,r)=>{if(r%3==2)return;let o=t.range(0,Math.PI*2),s=t.range(2,4.5),c=t.int(1,1e9),l=$(ZF(e.x+Math.cos(o)*s,-a,a)),u=$(ZF(e.z+Math.sin(o)*s,-a,a));n.slopeAt(l,u)>.09||(p++,i.push({name:`Fern${p}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,tuftStyle:`fern`,area:[8,8],density:9,height:.4,colorA:`#4a6b34`,colorB:`#82a258`,seed:c,position:[l,$(n.heightAt(l,u)+.02),u]}}))});let m=$(r*.08),h=QI(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>aL(`Grass${n+1}`,e,t,m,20,0,{height:.24,colors:[`#4f7034`,`#85a154`]})));let g=u.length>0?t.int(3,5):0;for(let e=0;e<g;e++){let r=u[e%u.length],o=t.range(0,Math.PI*2),s=t.range(2.5,4.5),c=$(ZF(r.x+Math.cos(o)*s,-a,a)),l=$(ZF(r.z+Math.sin(o)*s,-a,a));i.push({name:`Log${e+1}`,type:`Tree3D`,props:{type:`dead`,seed:t.int(1,1e9),height:$(t.range(4.2,5.6)),trunkColor:`#4a4236`,position:[c,$(n.heightAt(c,l)+.12),l],rotation:[0,t.int(0,359),$(t.range(81,97))]}})}QI(t,n,{count:5,band:[0,1],maxSlope:.25,margin:9,clearing:e}).forEach((e,n)=>{let r=$(t.range(.16,.28)),a=$(t.range(.3,.55));i.push({name:`Stump${n+1}`,type:`MeshInstance3D`,props:{mesh:`cylinder`,size:[r,a,r],position:[e.x,$(e.y+a/2-.06),e.z],rotation:[0,t.int(0,359),0],material:{color:t.pick(fL),roughness:1},castShadow:!0}})});let _=QI(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...cL(_,t,[.3,1],lL));let v=$(e*.75),y=QI(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-$(v/Math.SQRT2)});i.push(...y.map((e,n)=>aL(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=$(e*.45),x=QI(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-$(b/Math.SQRT2)});i.push(...x.map((e,n)=>sL(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=QI(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>iL(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:tL})));let a=$(r*.09),o=QI(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>aL(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=QI(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...cL(s,t,[.4,1.4]));let c=QI(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>iL(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=QI(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>iL(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:nL})));let r=QI(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...cL(r,t,[.5,1.8],uL));break}case`wetland`:{let e=$(r*.08),a=QI(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>oL(`Reeds${r+1}`,n,t,e,4)));let o=$(r*.08),s=QI(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>aL(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=QI(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>iL(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=QI(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>iL(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=QI(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...cL(u,t,[.3,1],lL));break}case`volcanic`:{let e=QI(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>iL(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=QI(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...cL(r,t,[.4,1.8],dL)),QI(t,n,{count:3,band:[0,.6],maxSlope:.18,margin:12}).forEach((e,n)=>{t.int(1,1e9),i.push({name:`Smoke${n+1}`,type:`Particles3D`,props:{preset:`smoke`,position:[e.x,$(e.y+.2),e.z],rate:8,maxParticles:64,colorStart:`#5a5048`,colorEnd:`#2a2422`,sizeStart:18,sizeEnd:44}}),i.push({name:`Embers${n+1}`,type:`Particles3D`,props:{position:[e.x,$(e.y+.1),e.z],rate:10,maxParticles:48,lifetime:[.8,1.8],speed:[12,34],directionDeg:-90,spreadDeg:40,gravity:[0,-18],sizeStart:4,sizeEnd:1,colorStart:`#ffce6a`,colorEnd:`#d83a14`,blend:`add`}})});break}}return i}function mL(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var hL={arena:{description:`FPS stage: floor, 4 perimeter walls, obstacles, lights — themes: boxes (crates), ruins (broken stone rows), garden (hedges, grass, pool)`,dimension:`3d`,params:{theme:{type:`string`,default:`boxes`,options:[...QF]},width:{type:`number`,default:30,min:4},depth:{type:`number`,default:30,min:4},wallHeight:{type:`number`,default:3,min:.5},obstacles:{type:`number`,default:8,min:0}}},terrain:{description:`Heightfield world: StaticBody3D{heightfield} + Terrain3D + theme dressing (trees, rocks, grass, sea/clouds on island, broad swamp water on wetland, smoke/ember emitters on volcanic; maxHeight 0 = theme default; water adds a lake to non-island themes)`,dimension:`3d`,params:{theme:{type:`string`,default:`island`,options:[...UI]},size:{type:`number`,default:200,min:40,max:400},maxHeight:{type:`number`,default:0,min:0},water:{type:`boolean`,default:!1}}},maze:{description:`Recursive-backtracker 3D maze, west→east — themes: stone, hedge (green + grass), canyon (sandstone + rim rocks)`,dimension:`3d`,params:{theme:{type:`string`,default:`stone`,options:[...gI]},width:{type:`number`,default:8,min:2,max:40},depth:{type:`number`,default:8,min:2,max:40},cellSize:{type:`number`,default:2,min:.5},wallHeight:{type:`number`,default:2.5,min:.5}}},maze2d:{description:`The same maze algorithm as 2D ColorRect2D + StaticBody2D tiles`,dimension:`2d`,params:{cols:{type:`number`,default:10,min:2,max:40},rows:{type:`number`,default:8,min:2,max:40},cellPx:{type:`number`,default:64,min:8}}},dungeon2d:{description:`Roguelike rooms + L-corridors: floor rects, wall bodies (32px tiles)`,dimension:`2d`,params:{rooms:{type:`number`,default:5,min:1,max:20},size:{type:`number`,default:960,min:256}}},platforms2d:{description:`Left-to-right 2D platform course (tune ranges via the library)`,dimension:`2d`,params:{count:{type:`number`,default:10,min:1}}}},gL={arena:rI,terrain:YI,maze:CI,maze2d:PI,dungeon2d:dI,platforms2d:LI};function _L(e,t){let n=gL[e];if(!n){let t=Object.keys(gL);throw new N(`BAD_FORMAT`,`Unknown generator '${e}'. Valid: [${t.join(`, `)}] — the old meadow/forest/island/rocks/clouds generators became themes (e.g. terrain theme: 'meadow', arena theme: 'garden'); scatter is library-only (needs item templates).`,{validOptions:t})}return n(t)}function vL(e){return Object.entries(hL).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function yL(e,t){if(e.type===`boolean`)return t===!0||t===`true`;if(e.type===`number`){let n=typeof t==`boolean`?NaN:Number(t);return(t===``||!Number.isFinite(n))&&(n=e.default),e.min!==void 0&&(n=Math.max(e.min,n)),e.max!==void 0&&(n=Math.min(e.max,n)),n}let n=String(t);return e.options&&!e.options.includes(n)?e.default:n}function bL(){return Math.floor(Math.random()*1e6)}var xL=[],SL=new Map,CL=null;function wL(e){let t=document.querySelector(`#generate`);t&&(DL(e),t.removeAttribute(`hidden`))}function TL(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function EL(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&TL()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,TL),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,TL),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>OL(e)))}function DL(e){let t=document.querySelector(`#generate-body`),n=document.querySelector(`#generate-status`);if(!t)return;n&&(n.textContent=``),t.textContent=``;let r=e.working.dimension??`2d`;xL=vL(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=JP({en:`Deterministic ${r.toUpperCase()} environment generators — the subtree inserts under the selected node (the root when nothing is selected). The same seed always generates the same level.`,ko:`결정적 ${r.toUpperCase()} 환경 생성기 — 생성된 서브트리는 선택한 노드 아래에(선택이 없으면 루트에) 들어갑니다. 같은 시드는 항상 같은 레벨을 만듭니다.`}),t.appendChild(i);let a=kL(JP({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of xL){let t=document.createElement(`option`);t.value=e,t.textContent=e,o.appendChild(t)}a.appendChild(o),t.appendChild(a);let s=document.createElement(`p`);s.className=`gen-desc`,t.appendChild(s);let c=document.createElement(`div`);c.id=`generate-params`,t.appendChild(c);let l=kL(`seed`);CL=document.createElement(`input`),CL.type=`number`,CL.step=`1`,CL.value=String(bL());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=JP({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{CL&&(CL.value=String(bL()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(CL,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=xL.find(e=>e.name===o.value)??xL[0];if(e){s.textContent=e.meta.description,c.textContent=``,SL=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=kL(t),r;if(n.type===`boolean`)r=document.createElement(`input`),r.type=`checkbox`,r.checked=n.default===!0;else if(n.type===`string`&&n.options){r=document.createElement(`select`);for(let e of n.options){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}r.value=String(n.default)}else r=document.createElement(`input`),r.type=n.type===`number`?`number`:`text`,n.type===`number`&&(r.step=`any`,n.min!==void 0&&(r.min=String(n.min)),n.max!==void 0&&(r.max=String(n.max))),r.value=String(n.default),(n.min!==void 0||n.max!==void 0)&&(r.title=`${n.min??``}–${n.max??``}`);SL.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function OL(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=xL.find(e=>e.name===n?.value);if(!r||!CL)return;let i={seed:yL({type:`number`,default:bL(),min:0},CL.value)};for(let[e,t]of SL){let n=r.meta.params[e];n&&(i[e]=yL(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=_L(r.name,i)}catch(e){t&&(t.textContent=e instanceof Error?e.message:String(e));return}let o=e.insertNode(a,e.selection??[]);if(o===null){t&&(t.textContent=JP({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),CL&&(CL.value=String(bL())),TL()}function kL(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var AL={connections:{title:{en:`connections — wire a signal to a handler`,ko:`connections — 시그널을 핸들러에 연결`},body:{en:'A connection says "when THIS node emits THIS signal, call THIS method on THAT node" — declaratively, in the scene JSON, with no TypeScript. emits = leaving this node; receives = arriving at it. Paths resolve from the scene ROOT (`Player/Sword`, `.` for the root itself). A red target does not resolve and the game will refuse to load the scene. Handlers on a scripted node are free text: they live in your behavior, which the editor never loads.',ko:'연결은 "이 노드가 이 시그널을 보내면, 저 노드의 이 메서드를 호출한다"를 씬 JSON에 선언합니다 — TypeScript 없이. emits는 이 노드에서 나가는 것, receives는 들어오는 것입니다. 경로는 씬 루트 기준입니다(`Player/Sword`, 루트 자신은 `.`). 빨간 대상은 찾을 수 없다는 뜻이고, 게임은 그 씬을 열지 못합니다. 스크립트가 있는 노드의 핸들러는 자유 입력입니다 — 에디터가 읽지 않는 게임 코드에 있기 때문입니다.'}},groups:{title:{en:`groups — tag nodes for queries`,ko:`groups — 조회용 태그`},body:{en:`Free-form tags. Game code finds nodes with tree-wide queries like getNodesInGroup("coins"), and triggers can filter by group (e.g. only react to "player"). Type a name and press Enter.`,ko:`자유 형식 태그입니다. 게임 코드가 getNodesInGroup("coins")처럼 트리 전체에서 노드를 찾고, 트리거는 그룹으로 거릅니다(예: "player"에만 반응). 이름을 입력하고 Enter를 누르세요.`},example:`triggerEnter → if (other.isInGroup("player")) collect()`},script:{title:{en:`script — attach YOUR game logic`,ko:`script — 게임 로직 연결`},body:{en:`A Behavior is a TypeScript class living in YOUR game code, linked by name. The editor stores the link; the class itself must be registered in the game before loadScene. Props here are passed to the behavior instance.`,ko:`Behavior는 게임 코드에 있는 TypeScript 클래스이며 이름으로 연결됩니다. 에디터는 연결만 저장하고, 클래스 자체는 loadScene 전에 게임에서 등록되어야 합니다. 여기의 props가 비헤이비어 인스턴스로 전달됩니다.`},example:`registerBehavior('CoinCounter', CoinCounter) // in your main.ts`,copy:{label:`copy behavior boilerplate`,text:`import { Behavior, registerBehavior } from 'incanto';
8413
+ }`};var fN=[`type`,`sunPosition`,`elevationDeg`,`azimuthDeg`,`turbidity`,`rayleigh`],pN=[`color`,`near`,`far`],mN=[`coverage`,`density`,`base`,`top`,`color`,`shadeColor`,`speed`,`scale`],hN=[`threshold`,`strength`],gN=[`vignette`,`saturation`,`contrast`],_N=[`mapSize`,`radius`,`static`],vN=[1024,2048],yN=2,bN=1,xN=50,SN=800,CN=`#cfd8e0`,wN=Math.PI/180;function TN(e){return{exposure:kN(e?.exposure),sky:AN(e?.sky),fog:jN(e?.fog,e?.sky!==void 0),clouds:MN(e?.clouds),bloom:NN(e?.bloom),post:PN(e?.post),shadows:FN(e?.shadows)}}function EN(e,t){let n=(90-e)*wN,r=t*wN;return[Math.sin(n)*Math.sin(r),Math.cos(n),Math.sin(n)*Math.cos(r)]}function DN(e){let[t,n,r]=e.sunPosition,i=Math.hypot(t,n,r)||1;return[t/i,n/i,r/i]}function ON(e){let t=[191,213,232],n=[233,228,217],r=[242,201,150],i=RN((e.turbidity-yN)/8),a=DN(e),o=RN((18-Math.asin(LN(a[1],-1,1))/wN)/18)*.8,s=e=>Math.round(zN(zN(t[e],n[e],i),r[e],o));return`#${[s(0),s(1),s(2)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}function kN(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw new N(`BAD_FORMAT`,`environment.exposure must be a finite number > 0 (tone-mapping exposure, default 1), got ${JSON.stringify(e)}.`,{prop:`exposure`});return e}function AN(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.sky must be an object ({ type?: "atmosphere", sunPosition? | elevationDeg?+azimuthDeg?, turbidity?, rayleigh? }), got ${JSON.stringify(e)}.`,{prop:`sky`});let t=e;for(let e of Object.keys(t))if(!fN.includes(e))throw new N(`BAD_FORMAT`,`environment.sky has unknown key '${e}'. Valid keys: [${fN.join(`, `)}].`,{prop:`sky`,validOptions:fN});if(t.type!==void 0&&t.type!==`atmosphere`)throw new N(`BAD_FORMAT`,`environment.sky.type must be 'atmosphere' (the only sky type so far), got ${JSON.stringify(t.type)}.`,{prop:`sky`,validOptions:[`atmosphere`]});let n=t.elevationDeg!==void 0||t.azimuthDeg!==void 0;if(t.sunPosition!==void 0&&n)throw new N(`BAD_FORMAT`,`environment.sky takes sunPosition OR elevationDeg/azimuthDeg, not both.`,{prop:`sky`,validOptions:[`sunPosition`,`elevationDeg+azimuthDeg`]});let r;if(t.sunPosition!==void 0){let e=t.sunPosition;if(!Array.isArray(e)||e.length!==3||!e.every(e=>typeof e==`number`&&Number.isFinite(e))||Math.hypot(e[0],e[1],e[2])===0)throw new N(`BAD_FORMAT`,`environment.sky.sunPosition must be a non-zero [x, y, z] vector, got ${JSON.stringify(e)}.`,{prop:`sky`});r=[e[0],e[1],e[2]]}else{let e=IN(t.elevationDeg,32,`sky.elevationDeg`),n=IN(t.azimuthDeg,135,`sky.azimuthDeg`);if(e<-90||e>90)throw new N(`BAD_FORMAT`,`environment.sky.elevationDeg must be in [-90, 90] (degrees above the horizon), got ${e}.`,{prop:`sky`});r=EN(e,n)}let i=IN(t.turbidity,yN,`sky.turbidity`);if(i<=0)throw new N(`BAD_FORMAT`,`environment.sky.turbidity must be > 0 (atmospheric haze; 2 ≈ clear day), got ${i}.`,{prop:`sky`});let a=IN(t.rayleigh,bN,`sky.rayleigh`);if(a<0)throw new N(`BAD_FORMAT`,`environment.sky.rayleigh must be >= 0 (Rayleigh scattering; 1 ≈ earth-like), got ${a}.`,{prop:`sky`});return{sunPosition:r,turbidity:i,rayleigh:a}}function jN(e,t){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.fog must be an object ({ color?, near?, far? }), got ${JSON.stringify(e)}.`,{prop:`fog`});let n=e;for(let e of Object.keys(n))if(!pN.includes(e))throw new N(`BAD_FORMAT`,`environment.fog has unknown key '${e}'. Valid keys: [${pN.join(`, `)}].`,{prop:`fog`,validOptions:pN});if(n.color!==void 0&&typeof n.color!=`string`)throw new N(`BAD_FORMAT`,`environment.fog.color must be a hex color string, got ${JSON.stringify(n.color)}.`,{prop:`fog`});let r=IN(n.near,xN,`fog.near`),i=IN(n.far,SN,`fog.far`);if(r<0)throw new N(`BAD_FORMAT`,`environment.fog.near must be >= 0 meters, got ${r}.`,{prop:`fog`});if(i<=r)throw new N(`BAD_FORMAT`,`environment.fog.far must be > near (got near ${r}, far ${i}).`,{prop:`fog`});return{color:n.color??(t?``:CN),near:r,far:i}}function MN(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.clouds must be an object ({ coverage?, density?, base?, top?, color?, shadeColor?, speed?, scale? }), got ${JSON.stringify(e)}.`,{prop:`clouds`});let t=e;for(let e of Object.keys(t))if(!mN.includes(e))throw new N(`BAD_FORMAT`,`environment.clouds has unknown key '${e}'. Valid keys: [${mN.join(`, `)}].`,{prop:`clouds`,validOptions:mN});for(let e of[`color`,`shadeColor`])if(t[e]!==void 0&&typeof t[e]!=`string`)throw new N(`BAD_FORMAT`,`environment.clouds.${e} must be a hex color string, got ${JSON.stringify(t[e])}.`,{prop:`clouds`});let n=IN(t.coverage,.5,`clouds.coverage`);if(n<0||n>1)throw new N(`BAD_FORMAT`,`environment.clouds.coverage must be in [0, 1] (how much sky is cloudy), got ${n}.`,{prop:`clouds`});let r=IN(t.density,1,`clouds.density`);if(r<0)throw new N(`BAD_FORMAT`,`environment.clouds.density must be >= 0 (optical thickness), got ${r}.`,{prop:`clouds`});let i=IN(t.base,120,`clouds.base`),a=IN(t.top,320,`clouds.top`);if(a<=i)throw new N(`BAD_FORMAT`,`environment.clouds.top must be > base (got base ${i}, top ${a}).`,{prop:`clouds`});let o=IN(t.speed,1,`clouds.speed`),s=IN(t.scale,240,`clouds.scale`);if(s<=0)throw new N(`BAD_FORMAT`,`environment.clouds.scale must be > 0 (feature size in world units), got ${s}.`,{prop:`clouds`});return{coverage:n,density:r,base:i,top:a,color:t.color??`#ffffff`,shadeColor:t.shadeColor??`#9fb0c8`,speed:o,scale:s}}function NN(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.bloom must be an object ({ threshold?, strength? }), got ${JSON.stringify(e)}.`,{prop:`bloom`});let t=e;for(let e of Object.keys(t))if(!hN.includes(e))throw new N(`BAD_FORMAT`,`environment.bloom has unknown key '${e}'. Valid keys: [${hN.join(`, `)}].`,{prop:`bloom`,validOptions:hN});let n=IN(t.threshold,1,`bloom.threshold`);if(n<0||n>8)throw new N(`BAD_FORMAT`,`environment.bloom.threshold must be in [0, 8] (linear-HDR luminance; 1 = white), got ${n}.`,{prop:`bloom`});let r=IN(t.strength,.8,`bloom.strength`);if(r<0)throw new N(`BAD_FORMAT`,`environment.bloom.strength must be >= 0, got ${r}.`,{prop:`bloom`});return{threshold:n,strength:r}}function PN(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.post must be an object ({ vignette?, saturation?, contrast? }), got ${JSON.stringify(e)}.`,{prop:`post`});let t=e;for(let e of Object.keys(t))if(!gN.includes(e))throw new N(`BAD_FORMAT`,`environment.post has unknown key '${e}'. Valid keys: [${gN.join(`, `)}].`,{prop:`post`,validOptions:gN});let n=IN(t.vignette,0,`post.vignette`);if(n<0||n>1)throw new N(`BAD_FORMAT`,`environment.post.vignette must be in [0, 1], got ${n}.`,{prop:`post`});let r=IN(t.saturation,1,`post.saturation`);if(r<0||r>4)throw new N(`BAD_FORMAT`,`environment.post.saturation must be in [0, 4] (1 = neutral), got ${r}.`,{prop:`post`});let i=IN(t.contrast,1,`post.contrast`);if(i<.2||i>3)throw new N(`BAD_FORMAT`,`environment.post.contrast must be in [0.2, 3] (1 = neutral), got ${i}.`,{prop:`post`});return{vignette:n,saturation:r,contrast:i}}function FN(e){if(e===void 0)return null;if(e===!1)return!1;if(e===!0)return{mapSize:2048,radius:1,static:!1};if(typeof e!=`object`||!e||Array.isArray(e))throw new N(`BAD_FORMAT`,`environment.shadows must be true, false or an object ({ mapSize?, radius? }), got ${JSON.stringify(e)}.`,{prop:`shadows`});let t=e;for(let e of Object.keys(t))if(!_N.includes(e))throw new N(`BAD_FORMAT`,`environment.shadows has unknown key '${e}'. Valid keys: [${_N.join(`, `)}].`,{prop:`shadows`,validOptions:_N});let n=t.mapSize===void 0?2048:t.mapSize;if(!vN.includes(n))throw new N(`BAD_FORMAT`,`environment.shadows.mapSize must be one of [${vN.join(`, `)}], got ${JSON.stringify(t.mapSize)}.`,{prop:`shadows`,validOptions:vN.map(String)});let r=IN(t.radius,1,`shadows.radius`);if(r<0)throw new N(`BAD_FORMAT`,`environment.shadows.radius must be >= 0, got ${r}.`,{prop:`shadows`});let i=t.static===void 0?!1:t.static;if(typeof i!=`boolean`)throw new N(`BAD_FORMAT`,`environment.shadows.static must be a boolean, got ${JSON.stringify(t.static)}.`,{prop:`shadows`});return{mapSize:n,radius:r,static:i}}function IN(e,t,n){if(e===void 0)return t;if(typeof e!=`number`||!Number.isFinite(e))throw new N(`BAD_FORMAT`,`environment.${n} must be a finite number, got ${JSON.stringify(e)}.`,{prop:n});return e}function LN(e,t,n){return Math.min(Math.max(e,t),n)}function RN(e){return LN(e,0,1)}function zN(e,t,n){return e+(t-e)*n}var BN=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,VN={apartment:`lebombo_1k.hdr`,city:`potsdamer_platz_1k.hdr`,dawn:`kiara_1_dawn_1k.hdr`,forest:`forest_slope_1k.hdr`,lobby:`st_fagans_interior_1k.hdr`,night:`dikhololo_night_1k.hdr`,park:`rooitou_park_1k.hdr`,studio:`studio_small_03_1k.hdr`,sunset:`venice_sunset_1k.hdr`,warehouse:`empty_warehouse_01_1k.hdr`};function HN(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=VN[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(VN).join(`, `)}.`);return`${BN}/${t}`}return null}var UN=75,WN=class{scene;ambient=new bu(`#ffffff`,0);envKey=null;config=TN(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new wo(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new K;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?DN(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get post(){return this.config.post}get sceneFog(){return this.scene.fog instanceof wo?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=TN(e));let r=this.config,i=e?.ambient;if(this.ambient.color.set(i?.color??`#ffffff`),this.ambient.intensity=i?.intensity??0,t&&(t.toneMappingExposure=r.exposure,t.shadowMap.enabled=r.shadows!==!1,r.shadows!==!1&&r.shadows!==null&&r.shadows.static?t.shadowMap.autoUpdate&&(t.shadowMap.autoUpdate=!1,t.shadowMap.needsUpdate=!0):t.shadowMap.autoUpdate||(t.shadowMap.autoUpdate=!0)),this.applyHdri(e),this.applySky(r.sky,t),this._sky&&(this._sky.visible=!0),this.applyFog(r),this.scene.environment=this.hdriTexture??this.skyEnvTarget?.texture??null,this.scene.environmentIntensity=(this.scene.environment===this.skyEnvTarget?.texture&&this.skyEnvTarget?.55:1)*GN(e?.iblIntensity),e?.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new K(t):null}}applySunLight(e,t=null){if(!e)return;let n=this.sunDirection;if(t){let r=e.position.length()||100,i,a,o;if(n)[i,a,o]=n;else{i=e.position.x-e.target.position.x,a=e.position.y-e.target.position.y,o=e.position.z-e.target.position.z;let t=Math.hypot(i,a,o)||1;i/=t,a/=t,o/=t}e.target.position.set(t.x,t.y,t.z),e.target.updateMatrixWorld(),e.position.set(t.x+i*r,t.y+a*r,t.z+o*r)}else if(n){let t=e.position.length()||100;e.position.set(n[0],n[1],n[2]).multiplyScalar(t)}let r=this.config.shadows;if(r&&typeof r==`object`){if(!e.castShadow){let t=e.shadow.camera;`left`in t&&t.left===-5&&(t.left=-75,t.right=UN,t.top=UN,t.bottom=-75,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.castShadow=!0}e.shadow.mapSize.x!==r.mapSize&&(e.shadow.mapSize.set(r.mapSize,r.mapSize),e.shadow.map?.dispose(),e.shadow.map=null),e.shadow.radius=r.radius}}applyUnderwater(e){e&&(this.underwaterFog||=new wo(`#000000`,.5,e.visibility),this.underwaterFog.color.set(e.color),this.underwaterFog.near=.5,this.underwaterFog.far=e.visibility,this.scene.fog=this.underwaterFog,this.scene.background=this.underwaterBg.set(e.color),this._sky&&(this._sky.visible=!1))}applyHdri(e){let t=HN(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new uN().load(t,e=>{if(this.hdriUrl!==t){e.dispose();return}e.mapping=303,this.hdriTexture=e}))}applySky(e,t){let n=e?JSON.stringify(e):``;if(n!==this.skyKey&&(this.skyKey=n,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null),e)){this._sky=new dN,this._sky.scale.setScalar(45e4);let t=this._sky.material.uniforms;(t.sunPosition?.value).set(...e.sunPosition),t.turbidity&&(t.turbidity.value=e.turbidity),t.rayleigh&&(t.rayleigh.value=e.rayleigh),this.scene.add(this._sky)}if(e&&t&&this._sky&&this.skyEnvKey!==n){this.skyEnvKey=n,this.skyEnvTarget?.dispose();let e=new bd(t),r=new To;r.add(this._sky),this.skyEnvTarget=e.fromScene(r),e.dispose(),this.scene.add(this._sky)}!e&&this.skyEnvTarget&&(this.skyEnvTarget.dispose(),this.skyEnvTarget=null,this.skyEnvKey=``)}applyFog(e){if(!e.fog){this.scene.fog=null;return}let t=e.fog.color||(e.sky?ON(e.sky):`#cfd8e0`);this.fog.color.set(t),this.fog.near=e.fog.near,this.fog.far=e.fog.far,this.scene.fog=this.fog}dispose(){this.hdriTexture?.dispose(),this.hdriTexture=null,this.skyEnvTarget?.dispose(),this.skyEnvTarget=null,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null)}};function GN(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new N(`BAD_FORMAT`,`environment.iblIntensity must be a finite number >= 0 (multiplies the image-based ambience: sky-derived base 0.55, HDRI base 1; default 1), got ${JSON.stringify(e)}.`,{prop:`iblIntensity`});return e}var KN=new Bo,qN=new Bo,JN=new G,YN=new G,XN=new U,ZN=Array.from({length:8},()=>new U),QN=.4,$N=new Float32Array(72),eP=[[0,0,0],[1,0,0],[1,0,1],[0,0,1],[0,1,0],[1,1,0],[1,1,1],[0,1,1]],tP=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];function nP(e,t){t.makeEmpty(),JN.copy(e.matrixWorld).invert(),e.traverse(e=>{let n=e,r;n.isInstancedMesh?(n.boundingBox||n.computeBoundingBox?.(),r=n.boundingBox):n.geometry&&(n.geometry.boundingBox||n.geometry.computeBoundingBox(),r=n.geometry.boundingBox),r&&(qN.copy(r).applyMatrix4(YN.multiplyMatrices(JN,e.matrixWorld)),t.union(qN))})}function rP(e){if(!(e instanceof Dh))return null;let t=e._ensureObject3D();t.updateWorldMatrix(!0,!0),nP(t,KN);let n=!0;KN.isEmpty()?(n=!1,XN.setFromMatrixPosition(t.matrixWorld),KN.min.set(XN.x-QN,XN.y-QN,XN.z-QN),KN.max.set(XN.x+QN,XN.y+QN,XN.z+QN)):KN.expandByScalar(.02);let{min:r,max:i}=KN;for(let e=0;e<8;e++){let[a,o,s]=eP[e],c=ZN[e].set(a?i.x:r.x,o?i.y:r.y,s?i.z:r.z);n&&c.applyMatrix4(t.matrixWorld)}let a=0;for(let[e,t]of tP){let n=ZN[e],r=ZN[t];$N[a++]=n.x,$N[a++]=n.y,$N[a++]=n.z,$N[a++]=r.x,$N[a++]=r.y,$N[a++]=r.z}return $N}function iP(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function aP(){let e=new Set,t=[],n=[],r=[];return{visited:e,cameras:t,renderHooks:n,emitters:r,state:{visited:e,cameras:t,renderHooks:n,emitters:r,assets:void 0,sunDirection:null,sunLight:null,alpha:1,ignoreStatic:!1}}}function oP(e,t,n,r,i){let a=i??aP();a.visited.clear(),a.cameras.length=0,a.renderHooks.length=0,a.emitters.length=0;let o=a.state;o.assets=n,o.sunDirection=r?.sunDirection??null,o.ignoreStatic=r?.ignoreStatic===!0,o.sunLight=null,o.alpha=r?.alpha??1,fP(e,t,o),hP(t,a.visited);let s=null;for(let e=0;e<a.cameras.length;e++){let t=a.cameras[e];if(t.current){s=t;break}}s||=a.cameras[0]??null;let c=s?s._ensureObject3D():null;return dP(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var sP=new U,cP=new U,lP=new U,uP=new U;function dP(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(cP),t.getWorldDirection(lP),uP.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[cP.x,cP.y,cP.z],forward:[lP.x,lP.y,lP.z],up:[uP.x,uP.y,uP.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(sP),t._setSpatialPose({position:[sP.x,sP.y,sP.z],listener:n})}function fP(e,t,n){let r=t;if(e instanceof Dh){let i=e._ensureObject3D();if(e.static&&!n.ignoreStatic&&i.userData.incantoStaticSynced===!0){i.userData.incantoStatic=!0,n.visited.add(i);return}if(i.parent!==t&&t.add(i),e._syncObject3D(n.alpha,n.assets??null),n.assets&&e instanceof Jk&&e._syncModel(n.assets),typeof e._onRender3D==`function`&&n.renderHooks.push(e),n.sunDirection){let t=e._applySunDirection;typeof t==`function`&&t.call(e,n.sunDirection)}e instanceof Mk&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof BE&&n.cameras.push(e),r=i}else iP(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)fP(t,r,n);if(e instanceof Dh){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,mP(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var pP=new WeakSet;function mP(e){if(pP.has(e))return;pP.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof BE)&&t.push(`${e.name} (${e.constructor.typeName??`?`})`);for(let t of e.children)n(t)};n(e),t.length>0&&console.warn(`[incanto] static subtree '${e.name}' freezes animated/per-frame nodes: ${t.join(`, `)} — they will stop updating. Unmark static or move them out.`)}function hP(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&hP(i,t)}}var gP=class{viewOverride=null;overrideCam=new fu(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new To;environment=new WN(this.threeScene);engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;warmCamera=null;deferCompile=!1;syncScratch=aP();ignoreStatic=!1;renderCtx=null;causticsTarget=null;causticsScene=null;causticsUniforms=null;cloudsTarget=null;cloudsHalfTarget=null;cloudsBlurTarget=null;cloudsScene=null;cloudsUniforms=null;cloudsBlurScene=null;cloudsBlurUniforms=null;cloudsCompositeScene=null;cloudsCompositeUniforms=null;bloomTarget=null;bloomBrightTarget=null;bloomBlurTarget=null;bloomBrightScene=null;bloomBrightUniforms=null;bloomBlurScene=null;bloomBlurUniforms=null;bloomCompositeScene=null;bloomCompositeUniforms=null;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.ownsAssets=!e.assets,this.assets=e.assets??new gw(this.engine);let t=_n(e.engine.scene?.environment,{antialias:!0,pixelRatio:Math.min(globalThis.devicePixelRatio??1,2),preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio,preserveDrawingBuffer:e.preserveDrawingBuffer});this.webgl=new mm({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer}),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.adaptive=e.adaptiveResolution===!1?null:new qM,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new Vc(new J,new kc({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new Vc(new J,new kc({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.threeScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>this.render())}basePixelRatio;adaptive;lastFrameAt=0;debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?rP(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new q(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of Q_(`3d`,this.engine))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new q(e,3))}governResolution(){let e=this.adaptive;if(!e)return;let t=globalThis.performance?.now?.()??0,n=this.lastFrameAt;if(this.lastFrameAt=t,n===0)return;let r=t-n;if(r>500){e.reset();return}let i=e.push(r);if(i===null)return;this.webgl.setPixelRatio(this.basePixelRatio*i);let a=this.lastSize;a.w>0&&a.h>0&&this.webgl.setSize(a.w,a.h,!1)}deferFirstCompile(){this.deferCompile=!0}async warmUp(e){this.deferCompile=!1;let t=this.warmCamera;if(!t)return;let n=[];this.threeScene.traverse(e=>{(e.isMesh||e.isPoints)&&n.push(e)});let r=n.filter(e=>e.visible);if(r.length===0){this.webgl.compile(this.threeScene,t),e?.(1);return}for(let e of r)e.visible=!1;let i=Math.min(_P,r.length),a=Math.ceil(r.length/i);try{for(let n=0;n<i;n++){for(let e=n*a;e<Math.min((n+1)*a,r.length);e++)r[e].visible=!0;this.webgl.compile(this.threeScene,t),e?.((n+1)/i),typeof requestAnimationFrame==`function`&&await new Promise(e=>{requestAnimationFrame(()=>setTimeout(e,0))})}}finally{for(let e of r)e.visible=!0}}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.governResolution(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e)),this.environment.apply(e.environment,this.webgl);let{activeCamera:t,renderHooks:n,sunLight:r}=oP(e.root,this.threeScene,this.assets,{sunDirection:this.environment.sunDirection,alpha:this.engine.interpolationAlpha,ignoreStatic:this.ignoreStatic},this.syncScratch),i=t;if(this.viewOverride){let[e,t,n]=this.viewOverride.position,[r,a,o]=this.viewOverride.target;this.overrideCam.position.set(e,t,n),this.overrideCam.lookAt(yP.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(TP),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&!this.deferCompile&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i)),this.warmCamera=i;let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(vP);(u.x!==c||u.y!==l)&&this.webgl.setSize(c,l,!1),this.lastSize={w:c,h:l};let d=l===0?1:c/l;i.aspect!==d&&(i.aspect=d,i.updateProjectionMatrix()),this.renderCtx||={gl:this.webgl,scene:this.threeScene,camera:i};let f=this.renderCtx;f.camera=i,o?(o.updateWorldMatrix(!0,!1),o.target.updateWorldMatrix(!0,!1),f.sunDir=xP.setFromMatrixPosition(o.matrixWorld).sub(SP.setFromMatrixPosition(o.target.matrixWorld)).normalize()):f.sunDir=null;for(let e=0;e<n.length;e++)n[e]?._onRender3D(f);let p=null;for(let e=0;e<n.length;e++){let t=n[e].underwaterAt?.(a.x,a.y,a.z);if(t){p=t;break}}this.environment.applyUnderwater(p);let m=this.environment.clouds,h=this.environment.bloom,g=this.environment.post;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):(h||g)&&!p?this.renderWithBloom(i,h,g):this.webgl.render(this.threeScene,i)}renderWithBloom(e,t,n=null){let r=this.webgl.getDrawingBufferSize(vP),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/2)),s=Math.max(1,Math.ceil(a/2));if(this.bloomTarget&&(this.bloomTarget.width!==i||this.bloomTarget.height!==a)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new za(i,a,{type:hr,samples:4}),this.bloomBrightTarget=new za(o,s,{type:hr}),this.bloomBlurTarget=new za(o,s,{type:hr})),!this.bloomBrightScene){let e=$M();this.bloomBrightScene=new To,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=eN();this.bloomBlurScene=new To,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=tN();this.bloomCompositeScene=new To,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let c=this.bloomBrightTarget,l=this.bloomBlurTarget;if(this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e),t){let n=this.bloomBrightUniforms;n.tScene.value=this.bloomTarget.texture,n.uThreshold.value=t.threshold,this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBrightScene,e);let r=this.bloomBlurUniforms;r.tTex.value=c.texture,r.uDir.value.set(1/o,0),this.webgl.setRenderTarget(l),this.webgl.render(this.bloomBlurScene,e),r.tTex.value=l.texture,r.uDir.value.set(0,1/s),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e)}let u=this.bloomCompositeUniforms;u.tScene.value=this.bloomTarget.texture,u.tBloom.value=t?c.texture:this.bloomTarget.texture,u.uStrength.value=t?t.strength:0,u.uVignette.value=n?.vignette??0,u.uSaturation.value=n?.saturation??1,u.uContrast.value=n?.contrast??1,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(vP),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/3)),s=Math.max(1,Math.ceil(a/3));if(this.cloudsTarget&&(this.cloudsTarget.width!==i||this.cloudsTarget.height!==a)&&(this.cloudsTarget.depthTexture?.dispose(),this.cloudsTarget.dispose(),this.cloudsTarget=null,this.cloudsHalfTarget?.dispose(),this.cloudsHalfTarget=null,this.cloudsBlurTarget?.dispose(),this.cloudsBlurTarget=null),!this.cloudsTarget){let e=new Qc(i,a);e.type=mr,this.cloudsTarget=new za(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new za(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new za(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=sN();this.cloudsScene=new To,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=oN();this.cloudsBlurScene=new To,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=cN();this.cloudsCompositeScene=new To,this.cloudsCompositeScene.add(e),this.cloudsCompositeUniforms=t}this.webgl.setRenderTarget(this.cloudsTarget),this.webgl.render(this.threeScene,e);let c=this.cloudsUniforms;c.tDepth.value=this.cloudsTarget.depthTexture,c.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(c.uCameraPos.value),c.uTime.value=(globalThis.performance?.now()??0)*.001*t.speed;let l=this.environment.sunDirection??[.4,.8,.3];c.uSunDir.value.set(l[0],l[1],l[2]).normalize(),n&&c.uSunColor.value.copy(n.color),c.uCloudColor.value.set(t.color),c.uShadeColor.value.set(t.shadeColor);let u=this.environment.sceneFog;u?(c.uHorizonColor.value.copy(u.color),c.uFarFade.value=u.far):(c.uHorizonColor.value.set(`#cdd9e6`),c.uFarFade.value=6e3),c.uBase.value=t.base,c.uTop.value=t.top,c.uCoverage.value=t.coverage,c.uDensity.value=t.density,c.uScale.value=t.scale,c.uWind.value.set(1,.35),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(this.cloudsScene,e);let d=this.cloudsBlurUniforms,f=this.cloudsBlurScene;d.tTex.value=this.cloudsHalfTarget.texture,d.uDir.value.set(1/o,0),this.webgl.setRenderTarget(this.cloudsBlurTarget),this.webgl.render(f,e),d.tTex.value=this.cloudsBlurTarget.texture,d.uDir.value.set(0,1/s),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(f,e),this.webgl.setRenderTarget(null);let p=this.cloudsCompositeUniforms;p.tScene.value=this.cloudsTarget.texture,p.tClouds.value=this.cloudsHalfTarget.texture,this.webgl.render(this.cloudsCompositeScene,e)}renderWithCaustics(e,t){let n=this.webgl.getDrawingBufferSize(vP),r=Math.max(1,n.x),i=Math.max(1,n.y);if(this.causticsTarget&&(this.causticsTarget.width!==r||this.causticsTarget.height!==i)&&(this.causticsTarget.depthTexture?.dispose(),this.causticsTarget.dispose(),this.causticsTarget=null),!this.causticsTarget){let e=new Qc(r,i);e.type=mr,this.causticsTarget=new za(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=Qm();this.causticsScene=new To,this.causticsScene.add(e),this.causticsUniforms=t}this.webgl.setRenderTarget(this.causticsTarget),this.webgl.render(this.threeScene,e),this.webgl.setRenderTarget(null);let a=this.causticsUniforms;a.tColor.value=this.causticsTarget.texture,a.tDepth.value=this.causticsTarget.depthTexture,a.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(a.uCameraPos.value),a.uWaterLevel.value=t.surfaceY,a.uTime.value=(globalThis.performance?.now()??0)*.001*t.caustics.speed,a.uCausticColor.value.set(t.caustics.color),a.uCausticIntensity.value=t.caustics.intensity,a.uCausticScale.value=t.caustics.scale,a.uMaxDist.value=t.visibility;let o=this.environment.sunDirection;o&&a.uSunDirection.value.set(o[0],o[1],o[2]),a.uRayStrength.value=t.rays.enabled?t.rays.strength:0,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(bP.set(e,t,n).project(r),{x:(bP.x+1)/2*this.lastSize.w,y:(1-bP.y)/2*this.lastSize.h,behind:bP.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;DP.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),EP.setFromCamera(DP,n);let r=EP.intersectObjects(this.threeScene.children,!0);for(let e of r){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(n)return n}return null}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}lastCameraPosition(){let e=this.lastCamera;return e?(e.getWorldPosition(wP),{x:wP.x,y:wP.y,z:wP.z}):null}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(CP):CP.identity();return{right:new U(1,0,0).applyQuaternion(t),up:new U(0,1,0).applyQuaternion(t),forward:new U(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){this.engine.picker&&(this.engine.picker=null),this.disconnect(),this.threeScene.traverse(e=>{let t=e;if(!(!t.isMesh||t.userData?.incantoModelShared))if(t.geometry?.dispose(),Array.isArray(t.material))for(let e of t.material)e.dispose();else t.material?.dispose()}),this.causticsTarget?.depthTexture?.dispose(),this.causticsTarget?.dispose();let e=this.causticsScene?.children[0];e?.geometry?.dispose(),e?.material?.dispose(),this.cloudsTarget?.depthTexture?.dispose(),this.cloudsTarget?.dispose(),this.cloudsHalfTarget?.dispose(),this.cloudsBlurTarget?.dispose(),this.bloomTarget?.dispose(),this.bloomBrightTarget?.dispose(),this.bloomBlurTarget?.dispose();for(let e of[this.cloudsScene,this.cloudsBlurScene,this.cloudsCompositeScene,this.bloomBrightScene,this.bloomBlurScene,this.bloomCompositeScene]){let t=e?.children[0];t?.geometry?.dispose(),t?.material?.dispose()}this.ownsAssets&&this.assets.dispose(),this.environment.dispose(),this.webgl.dispose()}},_P=12,vP=new V,yP=new U,bP=new U,xP=new U,SP=new U,CP=new H,wP=new U,TP=new U,EP=new Ku,DP=new V;async function OP(e){let t=async(t,n)=>{e.onProgress&&(e.onProgress(t,n),typeof requestAnimationFrame==`function`&&await new Promise(e=>{requestAnimationFrame(()=>setTimeout(e,0))}))};GM(),(e.gameplay??!0)&&H_();for(let[t,n]of Object.entries(e.behaviors??{}))it(t,n,{replace:!0});let n=new Et({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),r=kP(e.scene),i=kn(kP(r),{resolveScene:e.resolveScene,engine:n});n.setScene(i),await t(.06,`scene`);let a=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&AP(i.root))&&(a=await DT(n)),await t(.1,`physics`);let o=[],s=e.keyboard??(typeof window<`u`?window:!1);if(s&&n.input.attachKeyboard(s),e.pointer){let t=typeof e.pointer==`object`?e.pointer.lockOnClick??!0:!0;n.input.attachPointer(e.canvas,{lockOnClick:t})}o.push(jP(n,i.root,e.canvas));let c=e.touch??`auto`;if(c!==!1){let t=e.touchContainer??e.canvas.parentElement??null;if(t){let r={force:c===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=Kn(n,t,r),a=n.sceneChanged.connect(()=>{i?.dispose(),i=Kn(n,t,r)});o.push(()=>{a(),i?.dispose()})}}let l=e._rendererFactory?e._rendererFactory(n,e.canvas):new gP({canvas:e.canvas,engine:n,...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.adaptiveResolution===void 0?{}:{adaptiveResolution:e.adaptiveResolution},...e.preserveDrawingBuffer===void 0?{}:{preserveDrawingBuffer:e.preserveDrawingBuffer}});await t(.14,`renderer`);let u=e.debug??!1,d=e.editor??u,f=d===!0?{}:d||null,p={label:`✎ edit this scene`,run:async()=>{if(!f)return;let t=km(l),n=f.open??Dm,i=async t=>{await OP({...e,scene:t})};await Om(async()=>{m();try{await n({scene:r,...t?{camera:t}:{},play:i,exit:()=>i(r),...f.save?{save:f.save}:{},...f.library?{library:f.library===!0?Cm():f.library}:{}})}catch(e){console.error(`[incanto] could not open the editor:`,e),await i(r)}},`opening the editor…`)}};if(u){let t=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(t){let{attachDebugOverlay:r}=await ym(async()=>{let{attachDebugOverlay:e}=await import(`./debug-OR_wzFkM.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(n,{container:t,statsSource:()=>l.stats?.()??{},...f?{actions:[p]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&o.push(()=>i.dispose())}}n.start(),await t(.16,`shaders`);try{l.deferFirstCompile?.();let t=globalThis.performance?.now?.()??0;n.tick(t),n.tick(t+16),await l.warmUp?.(t=>{e.onProgress?.(.16+t*.82,`shaders`)})}catch{}o.push(n.settings.bindAudio(n.audio)),o.push(n.settings.bindLocale(n.locale)),await t(1,`ready`);function m(){Am([a?[`physics`,()=>a?.dispose()]:null,[`app cleanups`,()=>{for(let e of o)e()}],[`engine`,()=>n.dispose()],[`renderer`,()=>l.dispose()]])}return{engine:n,scene:i,sourceJson:r,renderer:l,physics:a,assetErrors(){return l.assets?.errors()??[]},pick(e,t){return n.picker?.(e,t)??null},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...n.stats(),...l.stats?.()}},openEditor:f?p.run:null,dispose:m}}function kP(e){try{return structuredClone(e)}catch{throw new N(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function AP(e){if(e instanceof Oh)return!0;for(let t of e.children)if(AP(t))return!0;return!1}function jP(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`&&r.push({target:window,type:`keydown`}),r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Ft&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}var MP=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>eT,WATER_CUTOUT_MAX:()=>4,WATER_MAX_RIPPLES:()=>8,createGame3D:()=>OP,enablePhysics3D:()=>DT}),NP=new WeakMap,PP=class e{account;roomId;roomState=new j;allUserStates=new j;userJoined=new j;userLeft=new j;globalState=new j;globalMyState=new j;asset=new j;latestUserStates={};latestRoomState={};latestGlobalState={};latestGlobalMyState={};latestAsset={};server;engine;throttleMs;subs=[];messageSignals=new Map;collectionSignals=new Map;latestCollections=new Map;globalMessageSignals=new Map;globalCollectionSignals=new Map;latestGlobalCollections=new Map;scenes=new Map;lastSent=new Map;sendAccumulator=0;detachReplication=null;lastOwner=null;boundScene=null;static get(e){return NP.get(e)??null}static async create(t,n={}){await NP.get(t)?.dispose();let r=n.transport??await zP(n.config);await r.connect();let i=n.room??t.scene?.multiplayer?.room??`auto`,a=new e(t,r,await r.remoteFunction(`joinRoom`,[i===`auto`?void 0:i],{needResponse:!0}),n.throttleMs??50);return NP.set(t,a),a}constructor(e,t,n,r){this.engine=e,this.server=t,this.roomId=n,this.account=t.account,this.throttleMs=Math.max(30,r),this.boundScene=e.scene,this.subs.push(t.subscribeRoomState(n,e=>{this.latestRoomState=e,this.roomState.emit(e)}),t.subscribeRoomAllUserStates(n,e=>{this.latestUserStates=e,this.allUserStates.emit(e)}),t.onRoomUserJoin(n,e=>this.userJoined.emit(e)),t.onRoomUserLeave(n,e=>this.userLeft.emit(e))),t.subscribeGlobalState&&this.subs.push(t.subscribeGlobalState(e=>{this.latestGlobalState=e,this.globalState.emit(e)})),t.subscribeGlobalMyState&&this.subs.push(t.subscribeGlobalMyState(e=>{this.latestGlobalMyState=e,this.globalMyState.emit(e)})),t.subscribeAsset&&this.subs.push(t.subscribeAsset(this.account,e=>{this.latestAsset=e,this.asset.emit(e)})),this.detachReplication=e.fixedUpdated.connect(e=>this.replicate(e))}message(e){let t=this.messageSignals.get(e);return t||(t=new j,this.messageSignals.set(e,t),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>t?.emit(e)))),t}collection(e){let t=this.collectionSignals.get(e);return t||(t=new j,this.collectionSignals.set(e,t),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,n=>{this.latestCollections.set(e,n),t?.emit(n)}))),t}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let t=this.globalMessageSignals.get(e);if(!t){t=new j,this.globalMessageSignals.set(e,t);let n=this.server.onGlobalMessage?.(e,e=>t?.emit(e));n&&this.subs.push(n)}return t}globalCollection(e){let t=this.globalCollectionSignals.get(e);if(!t){t=new j,this.globalCollectionSignals.set(e,t);let n=this.server.subscribeGlobalCollection?.(e,n=>{this.latestGlobalCollections.set(e,n),t?.emit(n)});n&&this.subs.push(n)}return t}latestGlobalCollection(e){return this.globalCollection(e),this.latestGlobalCollections.get(e)??{}}setMyState(e){return this.server.remoteFunction(`setMyState`,[this.roomId,e],{throttle:this.throttleMs,throttleKey:`incanto:myState`})}patchRoomState(e){return this.server.remoteFunction(`patchRoomState`,[this.roomId,e])}addEntity(e,t){return this.server.remoteFunction(`addEntity`,[this.roomId,e,t])}updateEntity(e,t,n){return this.server.remoteFunction(`updateEntity`,[this.roomId,e,t,n])}removeEntity(e,t){return this.server.remoteFunction(`removeEntity`,[this.roomId,e,t])}sendEvent(e,t){return this.server.remoteFunction(`sendEvent`,[this.roomId,e,t])}call(e,...t){return this.server.remoteFunction(e,[this.roomId,...t],{needResponse:!0})}registerScene(e,t){this.scenes.set(e,t)}resolveScene(e){let t=this.scenes.get(e);if(!t)throw new N(`UNRESOLVED_INSTANCE`,`No scene registered for '${e}'. Registered: [${[...this.scenes.keys()].join(`, `)}]. Call manager.registerScene('${e}', sceneJson).`);return t}async dispose(){this.detachReplication?.();for(let e of this.subs)e();await this.server.remoteFunction(`leaveRoom`,[this.roomId]),NP.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3;let n=FP(t.root,!0);if(!n)return;n!==this.lastOwner&&(this.lastOwner=n,this.lastSent.clear());let r=n.network,i=Math.max(30,typeof r.throttleMs==`number`?r.throttleMs:this.throttleMs),a=Array.isArray(r.sync)?r.sync:[],o={};for(let e of a){let t=LP(n,e);t!==void 0&&(Ve(this.lastSent.get(e)??null,t)||(o[e]=He(t)))}if(!(this.sendAccumulator<i)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,He(t));this.sendAccumulator=0,this.setMyState({sync:o})}}};function FP(e,t=!1){let n=[];if(IP(e,n),t&&n.length>1)throw new N(`BAD_FORMAT`,`Multiple network owner nodes found (${n.map(e=>e.getPath()).join(`, `)}). Exactly ONE node per player may declare network.mode 'owner' — replicate spawned entities through collections instead.`);return n[0]??null}function IP(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)IP(n,t)}function LP(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:e.getNodeOrNull(t.slice(0,n))??void 0,i=n===-1?t:t.slice(n+1);if(r)return r[i]}function RP(e,t,n){for(let[r,i]of Object.entries(t)){let t=r.lastIndexOf(`.`),a=t===-1?e:e.getNodeOrNull(r.slice(0,t)),o=t===-1?r:r.slice(t+1);a&&n(a,o,i)}}async function zP(e){let{createAgent8Server:t}=await ym(async()=>{let{createAgent8Server:e}=await import(`./agent8-DJlovKKL.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var BP=class extends At{static typeName=`NetworkSpawner`;static signals=[`spawned`,`despawned`];static props={source:{default:`users`},scene:{default:``},interpolate:{default:!0}};source=`users`;scene=``;interpolate=!0;spawned=new Map;positionTargets=new Map;failedKeys=new Set;update(e){let t=this.tree?.engine;if(!t)return;let n=PP.get(t);if(!n||this.scene===``)return;let r=this.currentEntries(n);for(let[e,t]of Object.entries(r)){let r=this.spawned.get(e);if(!r){if(this.failedKeys.has(e))continue;try{r=An(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=VP(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=t.sync;i&&RP(r,i,(e,t,n)=>this.setProp(e,t,n))}for(let[e,t]of[...this.spawned.entries()])e in r||(this.spawned.delete(e),this.positionTargets.delete(t),this.emit(`despawned`,t,e),t.free());this.interpolate&&this.stepInterpolation(e)}currentEntries(e){if(this.source===`users`){let t={};for(let[n,r]of Object.entries(e.latestUserStates))n!==e.account&&(t[n]=r);return t}return this.source.startsWith(`collection:`)?e.latestCollection(this.source.slice(11)):{}}setProp(e,t,n){if(this.interpolate&&t===`position`&&Array.isArray(n)){this.positionTargets.set(e,n);return}e[t]=n}stepInterpolation(e){let t=Math.min(1,e*8);for(let[e,n]of this.positionTargets){let r=e.position;Array.isArray(r)&&(e.position=r.map((e,r)=>e+((n[r]??e)-e)*t))}}};function VP(e){return e.replace(/[/%]/g,`_`)||`remote`}function HP(){gn(),R(BP)}function UP(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}var WP=UP()?.getItem(`incanto-editor-lang`)??`en`,GP=new Set;function KP(){return WP}function qP(e){WP=e,UP()?.setItem(`incanto-editor-lang`,e);for(let e of GP)e()}function JP(e){GP.add(e)}function YP(e){return e[WP]}var XP={node:{paths:[`M5 5h14v14H5z`]},move:{paths:[`M12 3v18M3 12h18`,`M8 7l4-4 4 4M8 17l4 4 4-4M7 8l-4 4 4 4M17 8l4 4-4 4`]},image:{paths:[`M4 5h16v14H4z`,`M4 15l5-5 4 4 3-3 4 4`],circles:[[9,9,1.6]]},film:{paths:[`M4 4h16v16H4z`,`M4 9h16M4 15h16`,`M9 4v16M15 4v16`]},video:{paths:[`M3 7h12v10H3z`,`M15 10l6-3v10l-6-3`]},text:{paths:[`M5 7V5h14v2`,`M12 5v14`,`M9 19h6`]},layers:{paths:[`M12 3 3 8l9 5 9-5-9-5z`,`M3 12l9 5 9-5`,`M3 16l9 5 9-5`]},square:{paths:[`M5 5h14v14H5z`,`M5 12h14`]},ball:{paths:[`M12 8v0`],circles:[[12,12,8],[12,12,1.4]]},person:{paths:[`M5 21v-1a7 7 0 0 1 14 0v1`],circles:[[12,7,4]]},area:{paths:[`M5 5h14v14H5z`],dashed:!0},gamepad:{paths:[`M7 9h-0M6 12h4M8 10v4`,`M4 8h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2z`],circles:[[16,11,1],[18.5,13.5,1]]},clock:{paths:[`M12 7v5l3 2`],circles:[[12,12,9]]},cube:{paths:[`M21 16V8l-9-5-9 5v8l9 5 9-5z`,`M3.3 7.5 12 12.5l8.7-5`,`M12 22V12.5`]},sun:{paths:[`M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9 17 7M7 17l-2.1 2.1`],circles:[[12,12,4]]},bulb:{paths:[`M9 18h6M10 21h4`,`M8 13a6 6 0 1 1 8 0c-1 1-1.5 2-1.5 3h-5c0-1-.5-2-1.5-3z`]},globe:{paths:[`M2 12h20`,`M12 2a15 15 0 0 1 0 20a15 15 0 0 1 0-20z`],circles:[[12,12,10]]},link:{paths:[`M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1`,`M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1`]},speaker:{paths:[`M11 5 6 9H3v6h3l5 4V5z`,`M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13`]},swatch:{paths:[`M4 4h16v16H4z`,`M4 4l16 16`]},sparkles:{paths:[`M12 4v5M12 15v5M5 12h5M14 12h5`],circles:[[6,5,1],[18,19,1]]},waves:{paths:[`M2 8c3-3 5 3 8 0s5 3 8 0`,`M2 14c3-3 5 3 8 0s5 3 8 0`,`M2 20c3-3 5 3 8 0s5 3 8 0`]},plant:{paths:[`M12 21v-8`,`M12 13c0-4-3-6-7-6 0 4 3 6 7 6z`,`M12 11c0-4 3-6 7-6 0 4-3 6-7 6z`]},flower:{paths:[`M12 21v-7`],circles:[[12,9,2],[12,4.5,2.2],[16.3,7.5,2.2],[14.7,12.6,2.2],[9.3,12.6,2.2],[7.7,7.5,2.2]]},voxels:{paths:[`M4 14h8v8H4z`,`M12 14h8v8h-8z`,`M8 6h8v8H8z`]}},ZP={Node:`node`,Timer:`clock`,AudioPlayer:`speaker`,ColorRect2D:`swatch`,Particles2D:`sparkles`,Particles3D:`sparkles`,Water3D:`waves`,Foliage3D:`plant`,Flowers3D:`flower`,VoxelGrid3D:`voxels`,ModelInstance3D:`person`,CharacterController3D:`gamepad`,Node2D:`move`,Sprite2D:`image`,AnimatedSprite2D:`film`,Camera2D:`video`,Label:`text`,UILayer:`layers`,StaticBody2D:`square`,RigidBody2D:`ball`,CharacterBody2D:`person`,Area2D:`area`,CharacterController2D:`gamepad`,Node3D:`move`,Billboard3D:`layers`,MeshInstance3D:`cube`,LoftMesh3D:`cube`,Camera3D:`video`,DirectionalLight3D:`sun`,OmniLight3D:`bulb`,StaticBody3D:`square`,RigidBody3D:`ball`,CharacterBody3D:`person`,Area3D:`area`,NetworkSpawner:`globe`};function QP(e){let t=XP[ZP[e??``]??(e?`node`:`link`)],n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`width`,`13`),n.setAttribute(`height`,`13`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),t.dashed&&n.setAttribute(`stroke-dasharray`,`3 2.4`);for(let e of t.paths){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,e),n.appendChild(t)}for(let[e,r,i]of t.circles??[]){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);t.setAttribute(`cx`,String(e)),t.setAttribute(`cy`,String(r)),t.setAttribute(`r`,String(i)),n.appendChild(t)}return n}function $P(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`width`,`12`),e.setAttribute(`height`,`12`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2.4`),e.setAttribute(`aria-hidden`,`true`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`d`,`m6 9 6 6 6-6`),e.appendChild(t),e}var eF=[{type:`texture`,label:`image (texture)`,metaHints:[`filter`]},{type:`spritesheet`,label:`spritesheet`,metaHints:[`filter`,`frameWidth`,`frameHeight`]},{type:`model`,label:`3D model (GLB/VRM)`,metaHints:[]},{type:`animation`,label:`animation (GLB clips)`,metaHints:[`clip`]}],tF=new Set,nF=null,rF=null;function iF(e,t,n){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e;let i=()=>{let i=r.value.trim().replace(/\//g,``);i&&i!==e?t(i):n()};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`/`&&e.preventDefault(),e.key===`Enter`&&i(),e.key===`Escape`&&n()});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());return r.addEventListener(`blur`,i),queueMicrotask(()=>{r.focus(),r.select()}),r}function aF(e,t){let n={path:``,name:``,folders:new Map,assets:[]},r=e=>{let t=n;if(e===``)return t;for(let n of e.split(`/`)){let e=t.folders.get(n);e||(e={path:t.path?`${t.path}/${n}`:n,name:n,folders:new Map,assets:[]},t.folders.set(n,e)),t=e}return t};for(let t of e){let e=t.lastIndexOf(`/`);r(e===-1?``:t.slice(0,e)).assets.push(t)}for(let e of t)r(e);return n}function oF(e){let t=e.assets.length;for(let n of e.folders.values())t+=oF(n);return t}function sF(e,t){e.textContent=``;let n=t.working.assets??{},r=Object.keys(n);if(r.length===0&&t.pendingGroups.size===0&&!t.addingAsset&&!t.addingGroup){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no assets yet — + adds textures, models, animations`,e.appendChild(t);return}let i=(e,n)=>{e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.add(`drop-target`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-target`)),e.addEventListener(`drop`,r=>{r.preventDefault(),r.stopPropagation(),e.classList.remove(`drop-target`);let i=r.dataTransfer?.getData(`text/incanto-asset`);i&&t.moveAsset(i,n);let a=r.dataTransfer?.getData(`text/incanto-group`);a&&t.moveGroup(a,n)})};i(e,``);let a=(e,r)=>{let i=n[e],a=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,o=document.createElement(`div`);o.className=`tree-row asset-row${t.selectedAsset===e?` selected`:``}`,o.draggable=!0,o.addEventListener(`dragstart`,t=>{t.dataTransfer?.setData(`text/incanto-asset`,e)});let s=document.createElement(`span`);if(s.className=`tree-icon`,s.appendChild(CF(i.type??``)),s.addEventListener(`click`,e=>{e.stopPropagation(),wF(s,i.type??``)}),nF===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;o.appendChild(iF(a,r=>{nF=null,t.renameAssetKey(e,n+r)},()=>{nF=null,t.selectAsset(t.selectedAsset)})),o.draggable=!1,o.insertBefore(s,o.firstChild),r.appendChild(o);return}let c=document.createElement(`span`);c.className=`tree-name asset-key`,c.textContent=`$${a}`,c.title=`$${e}`,c.addEventListener(`dblclick`,n=>{n.stopPropagation(),nF=e,t.selectAsset(e)}),o.append(s,c),o.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(o)},o=(e,n)=>{let r=tF.has(e.path),s=document.createElement(`div`);s.className=`asset-folder${r?` collapsed`:``}${t.selectedGroup===e.path?` selected`:``}`,s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.stopPropagation(),t.dataTransfer?.setData(`text/incanto-group`,e.path)});let c=document.createElement(`span`);c.className=`chev`,c.appendChild($P());let l=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);l.setAttribute(`viewBox`,`0 0 24 24`),l.setAttribute(`width`,`12`),l.setAttribute(`height`,`12`),l.setAttribute(`fill`,`none`),l.setAttribute(`stroke`,`currentColor`),l.setAttribute(`stroke-width`,`1.8`),l.setAttribute(`aria-hidden`,`true`);let u=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);if(u.setAttribute(`d`,`M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`),l.appendChild(u),rF===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,iF(e.name,n=>{rF=null,t.renameGroup(e.path,i+n)},()=>{rF=null,t.selectGroup(t.selectedGroup)})),s.draggable=!1,n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}return}let d=document.createElement(`span`);d.textContent=e.name,d.addEventListener(`dblclick`,n=>{n.stopPropagation(),rF=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${oF(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{tF.has(e.path)?tF.delete(e.path):tF.add(e.path),t.selectGroup(e.path)}),i(s,e.path),n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}},s=aF(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function cF(e,t,n,r){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(OF(t.newGroupParent?`NEW GROUP IN ${t.newGroupParent}/`:`NEW GROUP`));let n=document.createElement(`input`);n.placeholder=t.newGroupParent?`heroes`:`characters (or a/b to nest)`,n.className=`mono`,e.appendChild(vF(`name`,n));let r=document.createElement(`button`);r.type=`button`,r.className=`primary`,r.textContent=`add`;let i=()=>{let e=n.value.trim().replace(/^\/+|\/+$/g,``);e&&(t.cancelAddForms(),t.addGroup(t.newGroupParent?`${t.newGroupParent}/${e}`:e))};r.addEventListener(`click`,i),n.addEventListener(`keydown`,e=>{e.key===`Enter`&&i()});let a=document.createElement(`div`);return a.className=`pop-actions`,a.appendChild(r),e.appendChild(a),setTimeout(()=>n.focus(),0),!0}if(t.addingAsset)return fF(e,t,r);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(OF(`GROUP (${i} asset${i===1?``:`s`})`));let a=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)+1):``,o=r.includes(`/`)?r.slice(r.lastIndexOf(`/`)+1):r;e.appendChild(yF(`name`,o,e=>{let n=e.trim().replace(/\/+/g,``);n&&n!==o&&t.renameGroup(r,a+n)}));let s=document.createElement(`button`);return s.type=`button`,s.className=`ghost danger`,s.textContent=`delete group`,s.addEventListener(`click`,()=>{if(i===0){t.deleteGroup(r);return}n(`'${r}/' contains ${i} asset${i===1?``:`s`} — deleting the group deletes them too.`,`delete group & assets`,()=>t.deleteGroup(r))}),e.appendChild(s),!0}let i=t.selectedAsset;if(i===null)return!1;let a=t.working.assets??{};if(!(i in a))return!1;e.appendChild(OF(`ASSET — ${String(a[i].type??`?`)}`)),e.appendChild(TF(i)),e.appendChild(EF(t,i)),e.appendChild(lF(t,a,i,r));let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost danger`,o.textContent=`delete asset`,o.addEventListener(`click`,()=>{t.selectAsset(null),t.mutate(()=>{delete a[i],Object.keys(a).length===0&&delete t.working.assets})}),e.appendChild(o),!0}function lF(e,t,n,r){let i=t[n],a=document.createElement(`div`);a.className=`asset-editor`;let o=n.includes(`/`)?n.slice(n.lastIndexOf(`/`)+1):n,s=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)+1):``,c=yF(`name`,o,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==o&&e.renameAssetKey(n,s+r)});DF(c.querySelector(`input`)),a.appendChild(c);let l=yF(`url`,String(i.url??``),t=>{e.mutate(()=>{i.url=t.trim()})}),u=l.querySelector(`input`);if(r&&u){let t=mF(String(i.type??``));l.appendChild(_F(()=>t,`asset url`,r,t=>{u.value=t,e.mutate(()=>{i.url=t})},()=>gF(t,e)))}a.appendChild(l);let d=document.createElement(`div`);d.className=`muted-note`,d.textContent=`meta (key · value)`,a.appendChild(d);for(let[t,n]of Object.entries(i))t===`type`||t===`url`||a.appendChild(uF(e,i,t,n));return a.appendChild(dF(e,i)),a}function uF(e,t,n,r){let i=document.createElement(`div`);i.className=`meta-row`;let a=document.createElement(`input`);a.value=n,a.className=`mono`;let o=document.createElement(`input`);o.value=typeof r==`string`?r:JSON.stringify(r),o.className=`mono`;let s=()=>{let r=a.value.trim();e.mutate(()=>{delete t[n],r&&(t[r]=bF(o.value))})};a.addEventListener(`change`,s),o.addEventListener(`change`,s);let c=document.createElement(`button`);return c.type=`button`,c.className=`linklike danger-link`,c.textContent=`✕`,c.addEventListener(`click`,()=>{e.mutate(()=>{delete t[n]})}),i.append(a,o,c),i}function dF(e,t){let n=document.createElement(`div`);n.className=`meta-row`;let r=document.createElement(`input`);r.placeholder=`filter…`,r.className=`mono`;let i=document.createElement(`input`);i.placeholder=`nearest`,i.className=`mono`;let a=()=>{let n=r.value.trim();!n||i.value.trim()===``||e.mutate(()=>{t[n]=bF(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function fF(e,t,n){return e.appendChild(OF(`NEW ASSET`)),e.appendChild(pF(t,n)),!0}function pF(e,t){let n=document.createElement(`div`);n.className=`asset-editor`;let r=document.createElement(`select`);for(let e of eF){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,r.appendChild(t)}n.appendChild(vF(`type`,r));let i=document.createElement(`input`);i.placeholder=`(optional) characters`,i.className=`mono`,i.value=e.newAssetGroup;let a=`asset-groups-list`;i.setAttribute(`list`,a);let o=document.createElement(`datalist`);o.id=a;let s=new Set;for(let t of Object.keys(e.working.assets??{})){let e=t.lastIndexOf(`/`);e!==-1&&s.add(t.slice(0,e))}for(let t of e.pendingGroups)s.add(t);for(let e of s){let t=document.createElement(`option`);t.value=e,o.appendChild(t)}n.appendChild(vF(`group`,i)),n.appendChild(o);let c=document.createElement(`input`);c.placeholder=`coin`,c.className=`mono`,DF(c),n.appendChild(vF(`key`,c));let l=document.createElement(`input`);l.placeholder=`/textures/coin.png · https://… · data:…`,l.className=`mono`;let u=vF(`url`,l);t&&u.appendChild(_F(()=>mF(r.value),`new asset`,t,e=>{l.value=e,c.value.trim()||(c.value=hF(e))},()=>gF(mF(r.value),e))),n.appendChild(u);let d=document.createElement(`textarea`);d.rows=2,d.placeholder=`or paste a JSON object: { "type": "model", "url": "/m.glb" }`,n.appendChild(d);let f=document.createElement(`button`);f.type=`button`,f.className=`primary`,f.textContent=`add`,f.addEventListener(`click`,()=>{let t=c.value.trim().replace(/^\$/,``);if(!t)return;let n=i.value.trim().replace(/\/+$/,``),a=n?`${n}/${t}`:t,o=null,s=d.value.trim();if(s)try{o=JSON.parse(s)}catch{d.classList.add(`invalid`);return}else l.value.trim()&&(o={type:r.value,url:l.value.trim()});o&&(e.cancelAddForms(),e.selectedAsset=a,e.mutate(()=>{e.working.assets||(e.working.assets={});let t=e.working.assets;t[a]=o}))});let p=document.createElement(`div`);return p.className=`pop-actions`,p.appendChild(f),n.appendChild(p),n}function mF(e){return e===`model`||e===`animation`?`model`:e===`audio`?`audio`:e===`texture`||e===`spritesheet`?`image`:`any`}function hF(e){return((e.split(/[?#]/)[0]??``).split(`/`).pop()??``).replace(/\.[^.]+$/,``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function gF(e,t){let n=(t.working.dimension??`2d`)===`3d`;if(e===`image`)return n?[`3d`,`textures`]:[`2d`,`sprite_characters`];if(e===`model`)return[`3d`,`characters`]}function _F(e,t,n,r,i){let a=document.createElement(`button`);return a.type=`button`,a.className=`asset-lib`,a.textContent=`📚`,a.title=`Browse the agent8 library`,a.addEventListener(`click`,a=>{a.preventDefault();let o=i?.();n({kind:e(),target:t,...o?{shelf:o}:{}}).then(e=>{e&&r(e)})}),a}function vF(e,t){let n=document.createElement(`label`);n.className=`field`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n}function yF(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),vF(e,r)}function bF(e){let t=e.trim();if(t===`true`)return!0;if(t===`false`)return!1;if(t!==``&&Number.isFinite(Number(t)))return Number(t);if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.parse(t)}catch{return e}return e}var xF={texture:`M3 5h18v14H3z M3 15l5-5 4 4 3-3 6 6 M8.5 9.5h.01`,spritesheet:`M3 4h18v16H3z M9 4v16 M15 4v16 M3 12h18`,model:`M12 2l9 5v10l-9 5-9-5V7z M12 12l9-5 M12 12L3 7 M12 12v10`,animation:`M12 2a10 10 0 1 0 10 10 M22 12l-3-3m3 3l3-3 M12 7v5l3 3`},SF={texture:{en:`image (texture) — Sprite2D.texture references it as "$key".`,ko:`이미지(텍스처) — Sprite2D.texture에서 "$키"로 참조합니다.`},spritesheet:{en:`spritesheet — AnimatedSprite2D slices it into named frame animations.`,ko:`스프라이트시트 — AnimatedSprite2D가 이름 붙은 프레임 애니메이션으로 자릅니다.`},model:{en:`3D model (GLB/glTF/VRM) — ModelInstance3D.model references it as "$key".`,ko:`3D 모델(GLB/glTF/VRM) — ModelInstance3D.model에서 "$키"로 참조합니다.`},animation:{en:`animation clips (GLB, in memory — drawn nowhere) — any model can play them; mixamo retargets onto VRM.`,ko:`애니메이션 클립(GLB, 메모리 전용 — 그려지지 않음) — 어떤 모델이든 재생 가능, mixamo는 VRM에 자동 리타게팅.`}};function CF(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`width`,`13`),t.setAttribute(`height`,`13`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.8`),t.setAttribute(`aria-hidden`,`true`);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return n.setAttribute(`d`,xF[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function wF(e,t){document.querySelector(`.balloon`)?.remove();let n=SF[t];if(!n)return;let r=document.createElement(`div`);r.className=`balloon floating`;let i=document.createElement(`div`);i.className=`balloon-title`,i.textContent=t;let a=document.createElement(`span`);a.textContent=YP(n),r.append(i,a),document.body.appendChild(r);let o=e.getBoundingClientRect();r.style.left=`${o.right+8}px`,r.style.top=`${Math.max(8,o.top-8)}px`;let s=()=>{r.remove(),document.removeEventListener(`pointerdown`,s,!0)};setTimeout(()=>document.addEventListener(`pointerdown`,s,!0),0)}function TF(e){let t=document.createElement(`div`);t.className=`field uid-line`;let n=document.createElement(`span`);n.textContent=`key`;let r=document.createElement(`div`);r.className=`uid-value`;let i=document.createElement(`code`);i.textContent=`$${e}`;let a=document.createElement(`button`);return a.type=`button`,a.className=`uid-copy`,a.title=`Copy key`,a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,a.addEventListener(`click`,()=>{navigator.clipboard?.writeText(`$${e}`),a.classList.add(`copied`),setTimeout(()=>a.classList.remove(`copied`),600)}),r.append(i,a),t.append(n,r),t}function EF(e,t){let n=t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``,r=document.createElement(`select`),i=new Set([``]);for(let t of Object.keys(e.working.assets??{})){let e=t.split(`/`);for(let t=1;t<e.length;t++)i.add(e.slice(0,t).join(`/`))}for(let t of e.pendingGroups)i.add(t);for(let e of[...i].sort()){let t=document.createElement(`option`);t.value=e,t.textContent=e===``?`(root)`:`${e}/`,e===n&&(t.selected=!0),r.appendChild(t)}r.addEventListener(`change`,()=>{e.moveAsset(t,r.value)});let a=document.createElement(`label`);a.className=`field`;let o=document.createElement(`span`);return o.textContent=`group`,a.append(o,r),a}function DF(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function OF(e){let t=document.createElement(`div`);t.className=`section-title`,t.textContent=e;let n=document.createElement(`span`);return n.className=`rule`,t.appendChild(n),t}var kF=window.parent!==window,AF=new URLSearchParams(window.location.search).get(`parentOrigin`),jF=!1;function MF(e){if(kF){if(!AF){jF||(jF=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,AF)}}var NF={ready(e,t,n){MF({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){MF({type:`incanto-editor:open`,input:e,output:t})},change(e){MF({type:`incanto-editor:change`,dirty:e})},save(e,t,n){MF({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){MF({type:`incanto-editor:error`,message:e})}},PF=[[`Core`,e=>!e.endsWith(`2D`)&&!e.endsWith(`3D`)&&e!==`Label`&&e!==`UILayer`&&e!==`NetworkSpawner`],[`2D`,e=>e.endsWith(`2D`)&&!/Body|Area|Controller/.test(e)||e===`Label`||e===`UILayer`],[`2D Physics`,e=>e.endsWith(`2D`)&&/Body|Area|Controller/.test(e)],[`3D`,e=>e.endsWith(`3D`)&&!/Body|Area|Controller/.test(e)],[`3D Physics`,e=>e.endsWith(`3D`)&&/Body|Area|Controller/.test(e)],[`Network`,e=>e===`NetworkSpawner`]],FF=[...PF,[`Other`,e=>PF.every(([,t])=>!t(e))]],IF={title:{en:`How Incanto scenes work`,ko:`Incanto 씬은 어떻게 동작하나`},sections:[{heading:{en:`Everything is a node in a tree`,ko:`모든 것은 트리 위의 노드`},text:{en:`A scene is ONE tree of typed nodes (Godot-style). Each node has a name (unique among its siblings), a type that defines its props and behavior, optional children, and an optional scene-wide-unique uid. The whole structure lives in a *.scene.json file — there is no hidden state: what you see in this editor IS the file.`,ko:`씬은 타입을 가진 노드들의 단일 트리입니다(Godot 방식). 각 노드는 이름(형제 간 유일), props와 동작을 결정하는 타입, 선택적 자식들, 그리고 선택적인 씬 전역 유일 uid를 가집니다. 전체 구조가 *.scene.json 파일 하나에 들어있고 숨겨진 상태는 없습니다 — 이 에디터에서 보는 것이 곧 파일 그 자체입니다.`}},{heading:{en:`Props are delta-only`,ko:`Props는 변경분만 기록`},text:{en:`Every prop has a default defined by the engine. The JSON only stores values that DIFFER from the default — so files stay small and diffs stay meaningful. This editor follows the same rule: set a value back to its default and it disappears from the file.`,ko:`모든 prop에는 엔진이 정의한 기본값이 있습니다. JSON에는 기본값과 다른 값만 기록되어 파일이 작고 diff가 의미를 가집니다. 이 에디터도 같은 규칙을 따릅니다 — 값을 기본값으로 되돌리면 파일에서 사라집니다.`}},{heading:{en:`Addressing: paths, names, uid, groups`,ko:`노드 찾기: 경로·이름·uid·그룹`},text:{en:`Code reaches nodes four ways: a path like "Player/Skin" (relative) or "%Unique" (marked-unique name), getNodesByName("Enemy") which returns a LIST (names repeat across the tree), getNodeByUid("n_x1y2") which returns exactly one node and survives moves/renames, and groups — free tags for queries like "every coin".`,ko:`코드는 네 가지 방법으로 노드에 접근합니다: "Player/Skin" 같은 경로(상대) 또는 "%Unique"(유일 표시 이름), 트리 전체에서 같은 이름을 모두 찾는 getNodesByName("Enemy") — 이름은 중복될 수 있어 리스트가 돌아옵니다 —, 정확히 한 노드를 돌려주고 이동/개명에도 살아남는 getNodeByUid("n_x1y2"), 그리고 "모든 코인"처럼 묶어 조회하는 자유 태그 groups.`}},{heading:{en:`Signals connect, behaviors act`,ko:`시그널로 잇고 비헤이비어로 움직인다`},text:{en:`Nodes emit signals (an Area2D fires triggerEnter, a Timer fires timeout). The scene's "connections" wire a signal to a handler — declaratively, in JSON. Game logic itself is a Behavior: a TypeScript class in YOUR game, attached by name via "script". The inspector's CONNECTIONS section shows and edits these links on the selected node — what it emits, what reaches it, and any end that no longer resolves. The handler code itself lives in your game.`,ko:`노드는 시그널을 발산합니다(Area2D의 triggerEnter, Timer의 timeout). 씬의 "connections"가 시그널을 핸들러에 선언적으로(JSON으로) 연결합니다. 게임 로직 자체는 Behavior — 게임 쪽 TypeScript 클래스이며 "script"에 이름으로 연결됩니다. 인스펙터의 CONNECTIONS 섹션이 선택한 노드의 연결을 보여주고 편집합니다 — 나가는 것, 들어오는 것, 그리고 더 이상 찾을 수 없는 끝. 핸들러 코드 자체는 게임에 있습니다.`}},{heading:{en:`Assets are declared, then referenced`,ko:`에셋은 선언하고 $키로 참조`},text:{en:`The scene header declares assets (textures, spritesheets, 3D models, animation clips) under a key; nodes reference them as "$key". Animations are data too: an {type:"animation"} asset loads GLB clips into memory and any ModelInstance3D can play them — Mixamo clips retarget onto VRM avatars automatically.`,ko:`씬 헤더에서 에셋(텍스처·스프라이트시트·3D 모델·애니메이션 클립)을 키로 선언하고, 노드는 "$key"로 참조합니다. 애니메이션도 데이터입니다 — {type:"animation"} 에셋이 GLB 클립을 메모리에 올리고 어떤 ModelInstance3D든 재생할 수 있으며, Mixamo 클립은 VRM 아바타에 자동 리타게팅됩니다.`}}]},Q=(e,t,...n)=>({type:e,summary:t,body:n}),LF=[{id:`core`,label:{en:`Core`,ko:`Core`},intro:{en:`Dimension-free building blocks: plain containers and the game clock. They render nothing themselves.`,ko:`차원과 무관한 기본 블록 — 순수 컨테이너와 게임 시계입니다. 스스로는 아무것도 그리지 않습니다.`},nodes:[Q(`Node`,{en:`A plain container with no transform.`,ko:`변환 없이 자식을 묶는 순수 컨테이너.`},{en:`Use it to group related nodes (all coins, all UI) without affecting their positions. Lifecycle, signals, groups, script — everything works; it just has no visual or spatial meaning of its own.`,ko:`위치에 영향을 주지 않으면서 관련 노드(코인 전부, UI 전부)를 묶을 때 씁니다. 라이프사이클·시그널·그룹·스크립트가 모두 동작하며, 시각적·공간적 의미만 없습니다.`}),Q(`Timer`,{en:"A serializable countdown that emits `timeout`.",ko:"`timeout` 시그널을 쏘는 직렬화 가능한 카운트다운."},{en:`Set waitTime (seconds), optionally autostart or oneShot, and connect its timeout signal to any handler. Because it is a node, the whole timing setup lives in the scene file — agents can read and tune it.`,ko:`waitTime(초)을 정하고 autostart·oneShot을 선택한 뒤 timeout 시그널을 핸들러에 연결하세요. 노드이기 때문에 타이밍 설정 전체가 씬 파일에 남아 에이전트가 읽고 조정할 수 있습니다.`}),Q(`HudLayer`,{en:`Screen-space HUD overlay above the canvas — parent for UiText/UiBar/UiBanner.`,ko:`캔버스 위 화면 고정 HUD 오버레이 — UiText/UiBar/UiBanner의 부모.`},{en:`A DOM overlay (position:fixed) that never blocks pointer input. Put UI widgets as children; each picks one of 9 anchors (topLeft…bottomRight). Works identically over 2D and 3D renderers; in headless/tests it is a silent no-op. zIndex lifts it above the canvas.`,ko:`포인터 입력을 가로막지 않는 DOM 오버레이(position:fixed)입니다. UI 위젯을 자식으로 두면 각자 9개 앵커(topLeft…bottomRight) 중 하나에 붙습니다. 2D·3D 렌더러 어디서나 동일하게 동작하고, 헤드리스/테스트에서는 조용히 no-op입니다. zIndex로 캔버스 위에 올립니다.`}),Q(`UiText`,{en:`A HUD text line — score, timers, hints.`,ko:`HUD 텍스트 한 줄 — 점수, 타이머, 힌트.`},{en:`Child of HudLayer. Set text/size/color in JSON; update from behaviors: (getNode('%Score') as UiText).text = String(score). shadow adds a soft outline for readability over any scene.`,ko:`HudLayer의 자식. text/size/color를 JSON으로 정하고, 비헤이비어에서 (getNode('%Score') as UiText).text = String(score) 로 갱신하세요. shadow는 어떤 화면 위에서도 읽히도록 부드러운 그림자를 더합니다.`}),Q(`UiBar`,{en:`A labeled progress bar — health, stamina, reload, boss HP.`,ko:`라벨 달린 진행 바 — 체력, 스태미나, 재장전, 보스 HP.`},{en:`Child of HudLayer. Drive value/max from behaviors; the fill animates and turns lowColor under lowThreshold (default 30%). width/height/color/background style it; label prefixes a small caption.`,ko:`HudLayer의 자식. 비헤이비어에서 value/max를 갱신하면 채움이 애니메이션되고 lowThreshold(기본 30%) 아래로 떨어지면 lowColor로 바뀝니다. width/height/color/background로 스타일, label로 작은 캡션을 붙입니다.`}),Q(`UiBanner`,{en:`Center-screen announcements with fade and a queue — "WAVE 2", "YOU DIED".`,ko:`페이드·큐가 있는 중앙 공지 — "WAVE 2", "YOU DIED".`},{en:`Child of HudLayer. Call show('WAVE 2', { color, seconds }) from behaviors; messages queue and fade in/out. seconds 0 = sticky until the next show(). clear() drops everything. Emits bannerShown(text).`,ko:`HudLayer의 자식. 비헤이비어에서 show('WAVE 2', { color, seconds })를 호출하면 메시지가 큐에 쌓여 페이드 인/아웃됩니다. seconds 0이면 다음 show()까지 고정, clear()로 전부 제거. bannerShown(text) 시그널을 냅니다.`}),Q(`UiButton`,{en:`A clickable HUD button — menus, START screens, dialog choices.`,ko:`클릭 가능한 HUD 버튼 — 메뉴, 시작 화면, 대화 선택지.`},{en:`Child of HudLayer. Set text/size/color/background; disabled greys it out. Emits the 'pressed' signal (behaviors: node.on('pressed', ...)); press() triggers it programmatically (gamepad menus, tests).`,ko:`HudLayer의 자식. text/size/color/background를 설정하고 disabled로 비활성화합니다. 'pressed' 시그널을 내며(비헤이비어에서 node.on('pressed', ...)), press()로 코드에서도 누를 수 있습니다(게임패드 메뉴, 테스트).`}),Q(`UiPanel`,{en:`A box that holds other widgets — the thing a menu, options screen or inventory actually is.`,ko:`다른 위젯을 담는 상자 — 메뉴·설정 화면·인벤토리가 실제로 이것입니다.`},{en:`Child of HudLayer. Widgets under it mount INSIDE it, so tree structure becomes screen structure; panels nest. layout column|row|grid with columns (an inventory is a grid panel, one child per slot), plus gap/padding/background/radius/width/height/border. width or height 0 = size to the contents.`,ko:`HudLayer의 자식. 그 아래 위젯들이 이 안에 마운트되어 트리 구조가 화면 구조가 됩니다(중첩 가능). layout은 column|row|grid이고 columns와 함께 씁니다(인벤토리 = grid 패널, 슬롯당 자식 하나). gap/padding/background/radius/width/height/border 지원. width·height가 0이면 내용에 맞춰집니다.`}),Q(`UiImage`,{en:`A picture in the HUD — item icons, portraits, a logo.`,ko:`HUD 안의 그림 — 아이템 아이콘, 초상화, 로고.`},{en:`src takes a url or a $assetKey (declare the icon once like any other asset). fit contain|cover|fill; tint multiplies through the picture, which is how an unaffordable item greys out in one prop; opacity for disabled states.`,ko:`src는 url 또는 $assetKey(아이콘도 다른 에셋처럼 한 번만 선언). fit은 contain|cover|fill, tint는 그림에 곱해져서 살 수 없는 아이템을 프롭 하나로 회색 처리합니다. opacity로 비활성 표현.`}),Q(`UiSlider`,{en:`A value the player sets — volume, sensitivity, difficulty.`,ko:`플레이어가 조절하는 값 — 볼륨, 감도, 난이도.`},{en:`Emits changed(value). label/value/min/max/step/width/color. Setting .value from a behavior updates the control WITHOUT re-emitting, so restoring a saved setting does not fire the handler that saved it.`,ko:`changed(value) 시그널. label/value/min/max/step/width/color. 비헤이비어에서 .value를 설정하면 컨트롤만 갱신되고 changed는 다시 발생하지 않습니다 — 저장된 설정을 복원할 때 저장 핸들러가 다시 도는 것을 막습니다.`}),Q(`UiToggle`,{en:`An on/off switch — mute, invert-Y, fullscreen.`,ko:`켜기/끄기 스위치 — 음소거, Y축 반전, 전체화면.`},{en:`Emits changed(boolean). label/value. Same no-re-emit rule as UiSlider when set from code.`,ko:`changed(boolean) 시그널. label/value. 코드에서 설정할 때 재발생하지 않는 규칙은 UiSlider와 같습니다.`}),Q(`UiLanguageSelect`,{en:`The language picker, already wired.`,ko:`이미 연결된 언어 선택기.`},{en:`Options are the locales the scene declares in "strings", each labeled with its own endonym. Picking one switches the game live and persists it. English is the base: any key a locale omits falls back to it, on purpose.`,ko:`옵션은 씬의 "strings"가 선언한 로케일이며, 각 언어의 자기 이름으로 표시됩니다. 선택하면 즉시 바뀌고 저장됩니다. 영어가 기준이라 로케일이 빠뜨린 키는 의도적으로 영어로 표시됩니다.`}),Q(`UiSelect`,{en:`One of several — quality, resolution, language.`,ko:`여러 개 중 하나 — 품질, 해상도, 언어.`},{en:`options is a comma-separated list ("low,medium,high"); value is the current one. Emits changed(value).`,ko:`options는 쉼표로 구분된 목록("low,medium,high"), value가 현재 선택입니다. changed(value) 시그널.`}),Q(`UiDialogue`,{en:`A typewriter dialogue box with a queue and choice buttons — the RPG conversation layer.`,ko:`타자기 효과·큐·선택지 버튼을 갖춘 대화창 — RPG 대화 레이어.`},{en:`Child of HudLayer (anchor bottom by default). say(speaker, text, choices?) queues lines; clicking (or advance()) reveals then advances; choice lines wait for choose(i). Signals: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0 = instant. Check .active to pause player input during conversations.`,ko:`HudLayer의 자식(기본 anchor bottom). say(화자, 텍스트, 선택지?)로 줄을 큐에 넣고, 클릭(또는 advance())이 전체 공개→다음 줄로 진행하며, 선택지 줄은 choose(i)를 기다립니다. 시그널: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0이면 즉시 표시. 대화 중 플레이어 입력을 멈추려면 .active를 확인하세요.`}),Q(`AudioPlayer`,{en:`Plays a sound: zero-asset procedural SFX, BGM loops, or one-shot effects.`,ko:`소리 재생 — 무에셋 절차적 효과음, 배경음 루프, 단발 효과음.`},{en:`Set preset (coin/jump/hurt/explosion/…) for an instant zero-asset SFX (pitch/seed vary it), or leave it "custom" and set src (URL or "$assetKey"). volume 0..1; bus routes through engine.audio (sfx|music) for global volume/mute; loop for music; autoplay starts on ready (browsers may hold it until the first user gesture). Call play()/stop() from game code. Dimension-free — 2D and 3D alike.`,ko:`preset(coin/jump/hurt/explosion/…)을 설정하면 즉시 무에셋 효과음이 납니다(pitch·seed로 변형). 아니면 "custom"으로 두고 src(URL 또는 "$에셋키")를 쓰세요. volume은 0..1, bus는 engine.audio(sfx|music)를 통해 전역 볼륨/음소거에 연결, 음악은 loop, autoplay는 준비되면 재생합니다(브라우저가 첫 입력까지 보류 가능). 게임 코드에서 play()/stop()을 부르세요. 2D·3D 어디서나 동작합니다.`})]},{id:`2d`,label:{en:`2D`,ko:`2D`},intro:{en:`The 2D world is y-down pixels: 1 unit = 1 px, (0,0) top-left, rotation in clockwise degrees. Rendering needs a current Camera2D.`,ko:`2D 세계는 y-아래 픽셀 좌표입니다: 1유닛=1px, (0,0)은 좌상단, 회전은 시계방향 도(degree). 렌더링에는 current 카메라(Camera2D)가 필요합니다.`},nodes:[Q(`Node2D`,{en:`The 2D transform container (position/rotation/scale).`,ko:`2D 변환 컨테이너(position/rotation/scale).`},{en:`Children inherit its transform — move the parent, everything follows. renderOrder orders drawing; visible hides the subtree.`,ko:`자식은 변환을 상속합니다 — 부모를 움직이면 전부 따라옵니다. renderOrder로 그리기 순서를, visible로 서브트리 표시를 제어합니다.`}),Q(`Sprite2D`,{en:`A textured quad.`,ko:`텍스처 사각형(스프라이트).`},{en:`texture is "$assetKey" from the scene assets. anchor [0.5,0.5] centers; flipX/flipY mirror; tint multiplies color; opacity fades. Size comes from the texture × scale.`,ko:`texture는 씬 에셋의 "$키"입니다. anchor [0.5,0.5]면 중앙 기준, flipX/flipY로 반전, tint로 색 곱, opacity로 투명도. 크기는 텍스처 × scale로 정해집니다.`}),Q(`ColorRect2D`,{en:`A flat colored rectangle — no texture needed.`,ko:`단색 사각형 — 텍스처 불필요.`},{en:`size [w,h] px, color, opacity, anchor. Backgrounds, platforms, walls, UI panels, generated-level tiles (maze2d/dungeon2d emit these) — blocky art without any asset.`,ko:`size [w,h] px, color, opacity, anchor. 배경·플랫폼·벽·UI 패널·생성 레벨 타일(maze2d/dungeon2d가 이걸 만듭니다) — 에셋 없이 만드는 블록 그래픽입니다.`}),Q(`TileMap2D`,{en:`A whole tile level as ONE node — grid render + merged static colliders.`,ko:`타일 레벨 전체를 노드 하나로 — 그리드 렌더 + 병합된 정적 콜라이더.`},{en:`Author cells as rows of characters: "." / space = empty, digits 0-9 = atlas tile index, other chars map through legend ({"G": 12}). texture is a "$atlas" asset read left-to-right top-to-bottom in tileSize squares (columns: 0 derives from the texture width). Tile indices listed in solid become static colliders, greedy-merged into a few rectangles. Cell (0,0) hangs its top-left on the node origin.`,ko:`cells를 문자 행으로 작성합니다: "."/공백 = 빈 칸, 숫자 0-9 = 아틀라스 타일 번호, 그 외 문자는 legend({"G": 12})로 매핑. texture는 tileSize 정사각형을 좌→우, 상→하로 읽는 "$아틀라스" 에셋입니다(columns: 0이면 텍스처 폭에서 유도). solid에 나열된 타일 번호는 정적 콜라이더가 되며 소수의 직사각형으로 탐욕 병합됩니다. (0,0) 칸의 좌상단이 노드 원점에 걸립니다.`}),Q(`AnimatedSprite2D`,{en:`Spritesheet animation player.`,ko:`스프라이트시트 애니메이션 플레이어.`},{en:`Point sheet at a "$sheet" asset, define animations as named frame ranges with fps/loop in JSON, set autoplay. Emits animationFinished(name) for one-shot chains.`,ko:`sheet에 "$시트" 에셋을 연결하고, JSON에 fps/loop를 가진 이름별 프레임 구간으로 animations를 정의한 뒤 autoplay를 지정하세요. 단발 애니메이션 연결을 위해 animationFinished(name)를 발산합니다.`}),Q(`Camera2D`,{en:`The 2D view: follow, zoom, limits.`,ko:`2D 시점 — 추적·줌·경계.`},{en:`position is the view CENTER. follow tracks a node path with smoothing (0..1, higher = snappier). limits [minX,minY,maxX,maxY] clamps the view inside a world region. current: true makes it THE camera.`,ko:`position은 화면의 중심입니다. follow가 노드 경로를 smoothing(0..1, 높을수록 빠릿)으로 추적합니다. limits [minX,minY,maxX,maxY]가 시점을 월드 영역 안에 가둡니다. current: true인 카메라가 실제 시점이 됩니다.`}),Q(`Particles2D`,{en:`A 2D particle emitter (fire, sparks, smoke…).`,ko:`2D 파티클 이미터(불·스파크·연기…).`},{en:`Start from a preset (fire/smoke/sparks/…) then override any prop: rate, lifetime/speed ranges, direction + spread, gravity, size/color/alpha start→end, additive blend. burst > 0 with emitting: false makes a one-shot that emits finished. Animates LIVE in this editor.`,ko:`preset(fire/smoke/sparks/…)에서 시작해 어떤 prop이든 덮어쓰세요: rate, lifetime/speed 구간, direction+spread, gravity, size/color/alpha 시작→끝, additive blend. emitting: false에 burst > 0이면 단발 발사 후 finished를 발산합니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Label`,{en:`Text rendered to a quad.`,ko:`텍스트를 그리는 노드.`},{en:`text/fontSize/color/font/align — rendered via CanvasTexture, so any system font string works. Inside a UILayer it pins to the screen (HUD).`,ko:`text/fontSize/color/font/align — CanvasTexture로 그려져 시스템 폰트 문자열을 그대로 쓸 수 있습니다. UILayer 아래에 두면 화면에 고정됩니다(HUD).`}),Q(`UILayer`,{en:`A screen-space subtree (HUD).`,ko:`화면 고정 서브트리(HUD).`},{en:`Everything under it ignores the camera: positions are screen pixels from the top-left. Score counters, prompts, menus go here.`,ko:`이 아래의 모든 것은 카메라를 무시합니다 — 좌상단 기준 화면 픽셀 좌표입니다. 점수, 안내 문구, 메뉴를 여기에 둡니다.`})]},{id:`2d-physics`,label:{en:`2D Physics`,ko:`2D 물리`},intro:{en:`Rapier-backed. Colliders are PROPS ({shape, …}) — the green dashed wireframes in this editor. Physics runs when the game calls enablePhysics2D (and in play mode). Gravity lives on the scene row.`,ko:`Rapier 기반입니다. 콜라이더는 prop({shape, …})이며 에디터의 초록 점선이 그것입니다. 물리는 게임이 enablePhysics2D를 부를 때(그리고 플레이 모드에서) 돌고, 중력은 씬 행에 있습니다.`},nodes:[Q(`StaticBody2D`,{en:`Immovable collision: ground, walls, platforms.`,ko:`움직이지 않는 충돌체 — 바닥·벽·플랫폼.`},{en:`Other bodies collide with it; it never moves. Cheapest body type — use it for all level geometry.`,ko:`다른 바디가 부딪히지만 자신은 절대 움직이지 않습니다. 가장 저렴한 바디 — 레벨 지형 전부에 쓰세요.`}),Q(`RigidBody2D`,{en:`Fully simulated: falls, bounces, pushes.`,ko:`완전 시뮬레이션 — 떨어지고 튕기고 밀립니다.`},{en:`Gravity and collisions drive it. Set linearVelocity to launch. For player characters prefer CharacterBody2D (direct control).`,ko:`중력과 충돌이 움직임을 결정합니다. linearVelocity로 발사하세요. 플레이어 캐릭터에는 직접 제어가 가능한 CharacterBody2D를 권합니다.`}),Q(`CharacterBody2D`,{en:`Kinematic character: you set velocity, it slides.`,ko:`키네마틱 캐릭터 — 속도를 주면 미끄러지듯 이동.`},{en:`moveAndSlide() resolves collisions without physics pushing back; isOnFloor() gates jumps. Sensors (Area2D) do not block it but still fire triggers.`,ko:`moveAndSlide()가 밀려나지 않으면서 충돌을 처리하고 isOnFloor()로 점프를 판정합니다. 센서(Area2D)는 길을 막지 않으면서 트리거를 발사합니다.`}),Q(`Area2D`,{en:`A sensor: overlap triggers, no collision response.`,ko:`센서 — 겹침 감지만, 충돌 반응 없음.`},{en:`Fires triggerEnter(other)/triggerExit(other). Coins, checkpoints, damage zones. Filter with other.isInGroup("player").`,ko:`triggerEnter(other)/triggerExit(other)를 발산합니다. 코인·체크포인트·데미지 존에 쓰고, other.isInGroup("player")로 거릅니다.`}),Q(`CharacterController2D`,{en:`Zero-code platformer/top-down movement.`,ko:`코드 없는 플랫포머/탑다운 이동.`},{en:`Put it UNDER a CharacterBody2D. mode "platformer" (gravity + jump via jumpAction) or "topDown" (free 2-axis). Reads the scene input map actions (moveAction/jumpAction). maxSpeed/jumpHeight are intent-level numbers.`,ko:`CharacterBody2D의 자식으로 두세요. mode는 "platformer"(중력+jumpAction 점프) 또는 "topDown"(자유 2축)이며 씬 입력 맵의 액션(moveAction/jumpAction)을 읽습니다. maxSpeed/jumpHeight는 의도 그대로의 숫자입니다.`}),Q(`Joint2D`,{en:`A physics joint linking its parent body to a target body — weld, hinge, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 힌지, 로프, 스프링.`},{en:`Child of body A (a physics body); "target" is a node path to body B. type: fixed (rigid weld) / revolute (pin at the anchors) / rope (caps anchor distance at length px; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL px offsets.`,ko:`바디 A(물리 바디)의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / revolute(앵커 핀 힌지) / rope(앵커 간 거리를 length px로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 px 오프셋.`})]},{id:`3d`,label:{en:`3D`,ko:`3D`},intro:{en:`Meters, y-up, rotations in degrees. Standard materials need LIGHT — add a DirectionalLight3D or scene ambient, or you get silhouettes.`,ko:`미터 단위, y-위, 회전은 도(degree)입니다. 표준 머티리얼은 빛이 필요합니다 — DirectionalLight3D나 씬 ambient가 없으면 실루엣만 보입니다.`},nodes:[Q(`Node3D`,{en:`The 3D transform container.`,ko:`3D 변환 컨테이너.`},{en:`position [x,y,z] in meters, rotation [x,y,z] in degrees, scale per axis. Children inherit.`,ko:`position [x,y,z] 미터, rotation [x,y,z] 도, scale은 축별. 자식이 상속합니다.`}),Q(`MeshInstance3D`,{en:`A primitive mesh + material.`,ko:`프리미티브 메시 + 머티리얼.`},{en:`mesh: box/sphere/plane/cylinder…, size per primitive, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat} (this editor gives it swatches, sliders, texture-URL fields, and a repeat [u,v] tiling vector). map/normalMap are texture URLs; repeat only takes effect with a map. castShadow/receiveShadow per node.`,ko:`mesh: box/sphere/plane/cylinder…, 프리미티브별 size, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat}(에디터가 스와치·슬라이더·텍스처 URL 입력·repeat [u,v] 타일링 벡터 제공). map/normalMap은 텍스처 URL, repeat는 map이 있을 때만 적용. 그림자는 castShadow/receiveShadow.`}),Q(`LoftMesh3D`,{en:`A smooth swept hull (loft).`,ko:`부드러운 스윕 선체(로프트).`},{en:`sections: ≥2 cross-section stations {z, width, height, y, corner 0..1} interpolated into ONE smooth curved surface — vehicle bodies, glass canopies, boat hulls. slices/smooth control tessellation. Same material as MeshInstance3D minus textures (no UVs); pair clearcoat paint or high-envMapIntensity glass with the smooth normals for the automotive look.`,ko:`sections: 단면 스테이션 {z, width, height, y, corner 0..1} 2개 이상을 보간해 하나의 매끈한 곡면을 만듭니다 — 차체, 유리 캐노피, 선체. slices/smooth로 테셀레이션 조절. material은 MeshInstance3D와 동일하되 텍스처 제외(UV 없음). clearcoat 도장이나 높은 envMapIntensity 유리를 곡면 법선과 조합하면 자동차 룩이 납니다.`}),Q(`ModelInstance3D`,{en:`A GLB/glTF/VRM model file.`,ko:`GLB/glTF/VRM 모델 파일.`},{en:'model: "$assetKey" or URL. targetHeight scales the model to stand N units tall (run `npx incanto-model file.glb` to read its real size first). animation plays an embedded clip name OR an "$animation" asset — Mixamo clips retarget onto VRM humanoids automatically. One node per VRM asset (the avatar runtime mounts live). To make it SOLID, park it under a body with collider {shape:"auto"}: the collider is built from the model\'s own triangles — a triangle mesh on a static body (keeps its holes, so you walk through an archway) and a convex hull on a moving one.',ko:'model은 "$에셋키" 또는 URL입니다. targetHeight가 모델을 N유닛 높이로 맞춥니다(먼저 `npx incanto-model 파일.glb`로 실제 크기를 확인하세요). animation은 내장 클립 이름 또는 "$애니메이션" 에셋을 재생하며, Mixamo 클립은 VRM 휴머노이드에 자동 리타게팅됩니다. VRM 에셋은 노드 하나만 쓸 수 있습니다(아바타 런타임이 라이브로 마운트됨). 단단하게 만들려면 collider {shape:"auto"}인 바디 아래에 두세요 — 모델 자신의 삼각형에서 콜라이더가 만들어집니다(정적 바디는 트라이메시라 아치 구멍도 그대로, 움직이는 바디는 볼록 껍질).'}),Q(`Sprite3D`,{en:`A 2D image as a camera-facing billboard (the 2.5D look).`,ko:`카메라를 향하는 2D 빌보드 스프라이트(2.5D 룩).`},{en:`A textured quad that turns to face the camera inside the 3D world (Octopath / Don't Starve / MapleStory-in-3D). texture is an image URL; size is [w,h] in METERS. billboard: "y" stays upright with a screen-aligned yaw — off-center sprites never roll (characters/props), "full" faces it completely (items/FX), "none" is fixed to the node rotation. anchor [0.5,0] plants the feet on the ground. pixelArt nearest-filters for crisp pixels; alphaTest is a hard cutout that depth-sorts against 3D geometry (a tree occludes it); flipX mirrors left/right; tint/opacity recolor.`,ko:`3D 월드 안에서 카메라를 향해 도는 텍스처 쿼드(Octopath/Don't Starve, 3D 속 메이플스토리 룩). texture는 이미지 URL, size는 [너비,높이] 미터. billboard: "y"는 세로로 선 채 카메라 방향과 정렬된 yaw — 화면 가장자리에서도 기울지 않음(캐릭터/사물), "full"은 완전히 향함(아이템/FX), "none"은 노드 회전에 고정. anchor [0.5,0]은 발을 바닥에 둡니다. pixelArt는 nearest 필터로 픽셀을 또렷하게, alphaTest는 3D 지형과 깊이정렬되는 하드 컷아웃(나무가 가림), flipX는 좌우 반전, tint/opacity로 색·투명도.`}),Q(`AnimatedSprite3D`,{en:`A billboard sprite that plays spritesheet animations.`,ko:`스프라이트시트 애니를 재생하는 빌보드 스프라이트.`},{en:`Everything Sprite3D does, plus frame animation. sheet is a spritesheet image URL whose cells are frameWidth×frameHeight; animations maps a name to {frames, fps, loop} where frames is an inclusive [start,end] range or an explicit list; autoplay starts one on load. Game code calls play("walk") / stop(); a non-looping clip clamps on its last frame and emits animationFinished(name) — chain attack→idle from it.`,ko:`Sprite3D의 모든 기능 + 프레임 애니. sheet는 frameWidth×frameHeight 칸을 가진 스프라이트시트 URL, animations는 이름→{frames, fps, loop}(frames는 포함 [시작,끝] 범위 또는 명시 목록), autoplay는 로드 시 하나를 시작. 게임 코드에서 play("walk")/stop() 호출, 비반복 클립은 마지막 프레임에 머물며 animationFinished(name)를 emit(attack→idle 연결).`}),Q(`Billboard3D`,{en:`A group that turns toward the camera — children follow.`,ko:`카메라를 향해 도는 그룹 — 자식들이 함께 회전.`},{en:`A transform container that orients itself toward the camera every frame; children inherit the rotation, so hang world-space UI under it — HP bars, markers, floating icons (text is a canvas-rendered texture on a child Sprite3D). mode: "screen" (default) copies the camera orientation so a child rectangle stays an upright rectangle anywhere on screen (a yaw-only look-at visibly tilts off-center shapes under a pitched camera); "y" stays upright with a screen-aligned yaw (no off-center roll); "none" turns billboarding off. While billboarding, the node's own rotation prop (and the rotate gizmo) is overwritten every frame — switch to "none" to pose children, then switch back. Unlike Sprite3D (a textured quad that spins only its own image), Billboard3D rotates the whole group.`,ko:`매 프레임 카메라를 향해 자신을 회전시키는 변환 컨테이너로, 자식이 회전을 상속합니다 — HP바·마커·아이콘 같은 월드 UI를 자식으로 붙이세요(텍스트는 캔버스로 그린 텍스처를 자식 Sprite3D에). mode: "screen"(기본)은 카메라 자세를 그대로 복사해 자식 직사각형이 화면 어디서든 똑바른 직사각형으로 보입니다(yaw만 도는 look-at은 기울어진 카메라에서 중앙 밖 도형이 눈에 띄게 비스듬해짐); "y"는 세로로 선 채 카메라로 yaw만; "none"은 빌보드 끔. 빌보드 중에는 노드 자신의 rotation(회전 기즈모 포함)이 매 프레임 덮어써집니다 — 자식을 배치할 땐 "none"으로 바꿨다가 되돌리세요. 자기 그림만 도는 Sprite3D(텍스처 쿼드)와 달리 그룹 전체가 회전합니다.`}),Q(`Camera3D`,{en:`The 3D view.`,ko:`3D 시점.`},{en:`Perspective camera; fov in degrees; current: true selects it. Use the editor's "game cam" (0) to preview exactly what it renders.`,ko:`원근 카메라이며 fov는 도 단위, current: true가 실제 시점이 됩니다. 에디터의 "game cam"(0)으로 정확한 렌더 결과를 미리 보세요.`}),Q(`DirectionalLight3D`,{en:`Sun-like light from a direction.`,ko:`태양광 — 방향에서 평행하게.`},{en:`Position sets the direction toward the origin. intensity/color; pair with scene ambient for soft fill.`,ko:`위치가 원점을 향한 방향을 정합니다. intensity/color를 조절하고 부드러운 채움광은 씬 ambient와 함께 쓰세요.`}),Q(`OmniLight3D`,{en:`A point light radiating everywhere.`,ko:`점광 — 사방으로 퍼지는 빛.`},{en:`Lamps, torches, glows. range limits reach; intensity/color shape the falloff.`,ko:`램프·횃불·발광체. range로 도달 거리를, intensity/color로 감쇠를 만듭니다.`}),Q(`Particles3D`,{en:`A 3D particle emitter (fire, magic, weather…).`,ko:`3D 파티클 이미터(불·마법·날씨…).`},{en:`The same preset + override model as Particles2D, in meters with [x,y,z] gravity. Camera-facing billboard quads, instanced — hundreds are cheap. Animates LIVE in this editor.`,ko:`Particles2D와 같은 preset+덮어쓰기 모델을 미터 단위와 [x,y,z] 중력으로. 카메라를 향하는 빌보드 쿼드를 인스턴싱해 수백 개도 가볍습니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Terrain3D`,{en:`Procedural heightfield terrain with biome texture splatting.`,ko:`바이옴 텍스처 스플래팅이 적용된 절차적 하이트필드 지형.`},{en:`Seeded simplex hills displaced once on the CPU; theme (island/alpine/plains/desert/custom) picks the 4 blended biome textures by height and slope. heightAt(x,z) answers the surface height anywhere. For physics, parent it under a StaticBody3D with collider {shape:'heightfield'}.`,ko:`시드 기반 심플렉스 언덕을 CPU에서 한 번 변위합니다. theme(island/alpine/plains/desert/custom)이 높이·경사로 블렌딩되는 바이옴 텍스처 4장을 고릅니다. heightAt(x,z)로 어디서든 지표 높이를 얻고, 물리는 StaticBody3D 아래에 두고 collider {shape:'heightfield'}를 쓰세요.`}),Q(`Water3D`,{en:`A shader-water surface with splash signals.`,ko:`스플래시 신호를 내는 셰이더 물 표면.`},{en:`size [w,d] meters on XZ. quality 'fancy' (default) = FBM wave shader with a trough/surface/peak ramp (colors), CubeCamera reflections (reflection/reflectionInterval) and opt-in shoreline foam; 'simple' = the cheap sine material (color). Bodies crossing the surface emit entered/exited(body) and raise ripples (interaction). Volumetric gameplay still wants an Area3D. Waves animate LIVE in this editor.`,ko:`XZ 평면에 size [w,d] 미터. quality 'fancy'(기본)는 FBM 파도 셰이더 — trough/surface/peak 램프(colors), CubeCamera 반사(reflection/reflectionInterval), 옵트인 해안 거품(foam). 'simple'은 저사양용 사인파 머티리얼(color). 바디가 수면을 지나면 entered/exited(body) 신호와 물결이 일어납니다(interaction). 부피 기반 게임플레이엔 여전히 Area3D를 쓰세요. 이 에디터에서 파도가 라이브로 움직입니다.`}),Q(`River3D`,{en:`Running water derived from a path and the ground under it.`,ko:`경로와 그 아래 지형에서 유도되는 흐르는 물.`},{en:`Author a centerline path [[x,z],…] plus width/widths (a profile source→mouth) and depth; the node samples the Terrain3D underneath and derives the rest. It CARVES ITS OWN BED by default (carve): a trench per reach that heightAt, the collider, the splat and draped vegetation all see, with a floor that only ever falls, so a path over a rise digs through instead of burying the water. Its surface is then FITTED to that ground — never higher than the lowest rim holding it, ending where the ground comes up to meet it (asymmetric on a sloping reach), lying down as a film where a bank has fallen away, so a river can never hang in the air. Plus a current that speeds up where the channel pinches or tips (flowSpeed is the mean) and whitewater from grade, bank shear and thinning column. Boulders in the channel are answered without wiring: the node finds MeshInstance3D/InstancedMesh3D footprints standing in the water column and the current piles a white cushion on the upstream face, tears a wake downstream and bends its sheen around them. A trench thinner than a terrain cell cannot survive the grid: a 2.4 m creek on a 260 m map wants Terrain3D resolution 256. flowForce drags bodies downstream (drag, never thrust) and sampleAt(x,z) answers where a world point sits in the channel. No extra render passes — a map can carry a dozen.`,ko:`중심선 path [[x,z],…]와 width/widths(상류→하류 프로파일), depth만 주면 나머지는 아래 Terrain3D를 샘플링해 유도합니다. 기본적으로 강이 자기 바닥을 직접 팝니다(carve) — 구간마다 하나씩 도랑을 내고, heightAt·콜라이더·스플랫·식생 드레이프가 모두 그 지형을 봅니다. 파낸 바닥은 계속 내려가기만 하므로 경로가 언덕을 넘어도 물이 묻히지 않고 뚫고 흐릅니다. 그리고 수면은 그 지형에 맞춰집니다 — 자기를 담는 가장 낮은 둑보다 높아질 수 없고, 지면이 올라오는 지점에서 끝나며(비스듬한 구간에서는 좌우 폭이 다릅니다), 둑이 아예 없는 쪽에서는 경사면에 얇은 막처럼 누워버립니다. 그래서 강이 공중에 뜨는 일이 없습니다. 여기에 폭이 좁아지거나 경사가 급해지면 빨라지는 유속(flowSpeed는 평균)과 경사·둑 전단·얕아지는 수심에서 나오는 흰 물살이 더해집니다. 수로에 놓인 바위도 배선 없이 반응합니다 — MeshInstance3D/InstancedMesh3D 중 실제로 물기둥과 겹치는 것을 찾아, 상류면에 흰 물이 쌓이고 하류로 후류가 찢어지며 수면 광택이 바위를 돌아 휩니다. 지형 셀보다 얇은 도랑은 그리드에서 살아남지 못합니다 — 260 m 맵의 2.4 m 개울이라면 Terrain3D resolution 256이 필요합니다. flowForce가 바디를 하류로 끌고(밀지 않고 끌어당김), sampleAt(x,z)로 월드 좌표가 수로 어디에 있는지 알 수 있습니다. 추가 렌더 패스가 없어 한 맵에 여러 개를 둘 수 있습니다.`}),Q(`WaterCutout3D`,{en:`Marks its parent as something that holds the water back — a dry hull, a diving bell, a well.`,ko:`부모 오브젝트가 물을 막는다고 표시 — 마른 선실, 잠수종, 우물.`},{en:`Water is ONE surface and knows nothing about interiors, so an open hull floating on it fills with sea every time a crest clears its floor — freeboard alone can never promise otherwise. This node names the geometry that keeps the water out: it MUST be a CHILD of that thing (a hull, a bell, a dock's well, a cave mouth), and the water re-draws the part of it inside the box into its depth pre-pass, then hides behind it exactly as it hides behind any solid object. Nothing is ever cut OUT of the water, so a hole in open sea is impossible: overshoot the box and more of that hull holds water back, undershoot and water stands in the bow. size is the box extent in meters; enabled toggles it live (a scuttled hull starts letting the sea in). Four per water surface; needs quality fancy.`,ko:`물은 하나의 표면이라 '안쪽'이라는 개념이 없습니다. 그래서 뚜껑 없는 배를 띄우면 파도 마루가 바닥을 넘을 때마다 배 안에 바다가 차 보이고, 건현(freeboard)만으로는 절대 막을 수 없습니다. 이 노드는 '물을 막는 지오메트리'를 지정합니다. 반드시 그 물체(선체·잠수종·부두 우물·동굴 입구)의 자식이어야 하며, 물이 상자 안쪽의 그 지오메트리를 자기 깊이 프리패스에 다시 그린 뒤 평범한 불투명 물체 뒤에 숨듯 그 뒤로 숨습니다. 물에서 무언가를 '도려내지' 않으므로 열린 바다에 구멍이 나는 일은 원리적으로 불가능합니다 — 상자가 크면 그 배가 물을 더 많이 막을 뿐이고, 작으면 뱃머리에 물이 남습니다. size는 미터 단위 상자 크기, enabled는 런타임 토글(침수 시작 연출). 수면 하나당 4개, quality fancy 필요.`}),Q(`Foliage3D`,{en:`An instanced grass/flower carpet that sways.`,ko:`바람에 흔들리는 인스턴스 풀밭/꽃밭. `},{en:`kind grass/flowers/reeds scattered over area [w,d] at density (capped by maxInstances — instanced, tens of thousands of blades cheap). Grass defaults to style 'mesh': every instance is a REAL tapered blade curved by a bezier vertex shader — Voronoi-clump hue/lean, groundColor soil roots (match the terrain), sunDirection tip sheen, 2-octave rolling wind, fadeStart/fadeEnd camera LOD, and (interaction) blade-bending around moving bodies. style 'blades' keeps the 8-SDF-blades-per-quad ported shader, 'simple' the legacy quads. colorA/colorB tint bottom→top, sway sets the wind, seed makes the scatter reproducible. avoidWater (on by default) keeps blades OUT of standing and running water — a creek cutting its bed through the field gets banks, not blades waving in the current; turn it off for reeds and paddy fields.`,ko:`kind grass/flowers/reeds를 area [w,d]에 density로 흩뿌립니다(maxInstances 상한 — 인스턴싱이라 수만 가닥도 가벼움). grass는 기본 style 'mesh': 인스턴스 하나하나가 베지어 버텍스 셰이더로 휘어지는 진짜 잎 메시 — 보로노이 클럼프 색/기울기, groundColor 흙빛 뿌리(지형 색에 맞추세요), sunDirection 잎끝 광택, 2옥타브 굽이치는 바람, fadeStart/fadeEnd 카메라 LOD, (interaction) 움직이는 바디 주변 풀 눕힘까지. style 'blades'는 쿼드당 8가닥 SDF 셰이더, 'simple'은 기존 쿼드 룩. colorA/colorB가 아래→위 색, sway가 바람 세기, seed가 배치를 재현 가능하게 합니다. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 잎을 심지 않습니다 — 개울이 들판을 가르고 지나가면 물살 속에 풀이 서 있는 대신 둑이 생깁니다. 갈대·논은 꺼서 쓰세요.`}),Q(`Flowers3D`,{en:`Instanced flower PLANTS — stems, leaves, multi-petal heads.`,ko:`인스턴스 꽃밭 — 줄기·잎·여러 장 꽃잎의 진짜 꽃 식물.`},{en:`Real procedural flower plants (curved stem, 2-3 leaves, a 5-8 petal head around a contrasting center disc, 1-3 blooms per plant) scattered over area [w,d]. density is the vibe dial: 'lush' / 'sparse' (default) / 'none', or a number in plants/m². varieties picks a subset of daisy/cosmos/bellflower ([] = all three); palette sets the head colors ([] = white/yellow/violet). clustering 0-1 gathers plants into Voronoi patches that bloom one species + color together; sway bobs the heads in a gentle wind; seed makes the field reproducible. ≤3 varieties → ≤6 draw calls. avoidWater (on by default) keeps plants out of standing and running water — a meadow a stream runs through has a bank of flowers, not flowers in the current.`,ko:`진짜 프로시저럴 꽃 식물(휘어진 줄기, 잎 2-3장, 대비되는 중심 원반을 두른 꽃잎 5-8장 머리, 포기당 꽃 1-3송이)을 area [w,d]에 흩뿌립니다. density가 바이브 다이얼: 'lush'(풍성하게) / 'sparse'(듬성듬성, 기본) / 'none'(없게) 또는 m²당 개수. varieties는 daisy/cosmos/bellflower 부분집합([] = 셋 다), palette는 꽃 색([] = 흰/노랑/보라). clustering 0-1이 보로노이 패치로 모아 한 패치가 같은 종·같은 색으로 피고, sway가 바람에 머리를 끄덕이며, seed로 배치가 재현됩니다. 품종 ≤3 → 드로우 콜 ≤6. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 꽃을 심지 않습니다 — 시내가 지나는 들판에는 물살 속 꽃이 아니라 꽃이 핀 둑이 생깁니다.`}),Q(`Tree3D`,{en:`Procedural tree groves — real branching trunks, textured leaves, one node per forest.`,ko:`프로시저럴 나무 숲 — 진짜 가지가 뻗은 줄기와 텍스처 잎, 숲 하나가 노드 하나.`},{en:`type conifer/broadleaf/dead picks the recipe family; tier is the cost dial: simple = primitive low-poly, medium = light forest presets (≤3k tris/tree), high = full ez-tree presets (8–20k, hero trees). count > 1 scatters a forest patch over area [w,d] — up to 3 seed variants, each branches + leaves InstancedMesh (≤6 draw calls); count × tris/tree is budget-checked at load. seed makes every branch and leaf reproducible; height jitters ±20% per instance; leaves sway in a simplex wind.`,ko:`type conifer/broadleaf/dead가 수종을, tier가 비용을 정합니다: simple = 기존 로우폴리, medium = 가벼운 forest 프리셋(나무당 ≤3k tris), high = 풀 ez-tree 프리셋(8–20k, 주인공 나무). count > 1이면 area [w,d]에 숲 패치를 흩뿌립니다 — 시드 변형 최대 3종, 변형마다 가지+잎 InstancedMesh(드로우 콜 ≤6), count × tris는 로드 시 예산 검사. seed로 가지와 잎이 전부 재현되고 height는 인스턴스마다 ±20% 지터링, 잎은 심플렉스 바람에 흔들립니다.`}),Q(`VoxelGrid3D`,{en:`A Minecraft-style block grid in ONE node.`,ko:`마인크래프트식 블록 그리드 — 노드 하나로.`},{en:`voxels is a list of [x,y,z,palette] integer cells (terrain/island generators emit these). Greedy-meshed and instanced — large worlds stay one draw batch. Game code edits blocks via setBlock/getBlock; emits blocksChanged.`,ko:`voxels는 [x,y,z,팔레트] 정수 셀 목록입니다(terrain/island 생성기가 만들어 냅니다). 그리디 메싱+인스턴싱으로 큰 월드도 드로우 배치 하나를 유지합니다. 게임 코드는 setBlock/getBlock으로 수정하고 blocksChanged가 발산됩니다.`})]},{id:`3d-physics`,label:{en:`3D Physics`,ko:`3D 물리`},intro:{en:`Same model as 2D, in meters with y-up gravity ([0,-9.81,0] default). Colliders: box {size}, sphere {radius}, capsule {radius,height}.`,ko:`2D와 같은 모델을 미터·y-위 중력([0,-9.81,0] 기본)으로. 콜라이더는 box {size}, sphere {radius}, capsule {radius,height}.`},nodes:[Q(`StaticBody3D`,{en:`Immovable 3D collision.`,ko:`움직이지 않는 3D 충돌체.`},{en:`Floors, walls, level geometry. collider {shape:"auto"} takes the shape from the MeshInstance3D or ModelInstance3D the body carries as a child, so the blocker can never be bigger or smaller than what the player sees — the fix for hand-typed extents that leave you stopping in mid-air. A GLB becomes a triangle mesh here, holes and all.`,ko:`바닥·벽·레벨 지형. collider {shape:"auto"}는 바디가 자식으로 들고 있는 MeshInstance3D 또는 ModelInstance3D의 생김새를 그대로 씁니다 — 보이는 것보다 크거나 작은 콜라이더가 생길 수 없습니다. 손으로 적은 크기 때문에 허공에서 막히는 문제의 해법입니다. GLB는 여기서 구멍까지 살아있는 트라이메시가 됩니다.`}),Q(`RigidBody3D`,{en:`Simulated 3D body.`,ko:`시뮬레이션되는 3D 바디.`},{en:`Crates, balls, debris — gravity and impacts drive it.`,ko:`상자·공·파편 — 중력과 충격이 움직입니다.`}),Q(`CharacterBody3D`,{en:`Kinematic 3D character.`,ko:`키네마틱 3D 캐릭터.`},{en:`moveAndSlide with up = +y; isOnFloor for jumps.`,ko:`+y를 위로 moveAndSlide, 점프 판정은 isOnFloor.`}),Q(`Area3D`,{en:`3D overlap sensor.`,ko:`3D 겹침 센서.`},{en:`triggerEnter/Exit — pickups, zones, goals.`,ko:`triggerEnter/Exit — 아이템·존·골인 지점.`}),Q(`CharacterController3D`,{en:`Zero-code 3D movement + camera rig.`,ko:`코드 없는 3D 이동 + 카메라 리그.`},{en:`Put it UNDER a CharacterBody3D. view: thirdPerson (orbit + zoom), firstPerson (eyeHeight, mouseLook), sideView or flightView. Reads moveAction/jumpAction/sprintAction from the scene input map; skinPath turns the visual child to face travel. Intent-level numbers: maxSpeed, jumpVelocity, camDistance.`,ko:`CharacterBody3D의 자식으로 두세요. view는 thirdPerson(궤도+줌), firstPerson(eyeHeight, mouseLook), sideView, flightView 중 하나입니다. 씬 입력 맵의 moveAction/jumpAction/sprintAction을 읽고 skinPath의 비주얼 자식을 진행 방향으로 돌립니다. maxSpeed·jumpVelocity·camDistance 같은 의도 수준의 숫자만 만집니다.`}),Q(`BoneLookAt3D`,{en:`Look-at IK for one bone — the head turns toward a target on top of the animation.`,ko:`본 하나의 룩앳 IK — 애니메이션 위에서 머리가 대상을 향해 돌아갑니다.`},{en:`"target" = ModelInstance3D path, "bone" = bone name (default Head), "lookAt" = the node to watch (e.g. "%Player"). Blends in/out smoothly and DISENGAGES beyond maxAngleDeg (no owl necks); weight sets how far it commits. forwardAxis names the bone's facing axis (mixamo heads: +z). Purely visual — headless no-op.`,ko:`"target"에 ModelInstance3D 경로, "bone"에 본 이름(기본 Head), "lookAt"에 바라볼 노드(예: "%Player")를 줍니다. 부드럽게 페이드 인/아웃하고 maxAngleDeg 밖에서는 해제됩니다(목이 돌아가지 않음). weight로 몰입도를 조절하고 forwardAxis는 본의 정면 축입니다(mixamo 머리: +z). 순수 시각 기능 — 헤드리스에서는 no-op.`}),Q(`InstancedMesh3D`,{en:`Hundreds of copies of one mesh in ONE draw call — rocks, posts, crates.`,ko:`메시 하나의 수백 개 복사본을 드로우콜 1개로 — 바위, 말뚝, 상자.`},{en:`Same mesh/size/material surface as MeshInstance3D; "transforms" places the copies — each row [x, y, z, yawDeg?, scale?]. Replace the whole array to update (mutations are not watched). The scattering workhorse for open worlds. collider: {} makes the whole field solid — every row gets its own collider SHAPED LIKE THE MESH (a faceted gem stone collides as that stone's hull, not as a ball tucked inside it), all hanging off one fixed body. A boulder field the player walks straight through is the tell that a world is scenery rather than a place.`,ko:`MeshInstance3D와 같은 mesh/size/material 표면에 "transforms"로 복사본을 배치합니다 — 각 행은 [x, y, z, yawDeg?, scale?]. 갱신은 배열 전체 교체로 하세요(내부 변경은 감지되지 않음). 오픈월드 스캐터링의 주력입니다. collider: {}를 주면 필드 전체가 단단해집니다 — 행마다 메시 생김새 그대로의 콜라이더가 생기고(각진 gem 바위는 안에 박힌 구가 아니라 그 바위 자신의 볼록 껍질로 부딪힙니다), 전부 하나의 고정 바디에 붙습니다. 플레이어가 통과해버리는 바위밭은 그 세계가 배경 그림이라는 신호입니다.`}),Q(`BoneAttachment3D`,{en:`Rides a skeleton bone of an animated model — swords in hands, hats on heads.`,ko:`애니메이션 모델의 스켈레톤 본을 따라다님 — 손에 쥔 검, 머리 위 모자.`},{en:`"target" is a node path to the ModelInstance3D, "bone" the bone name ("RightHand" also matches the Mixamo spellings). Children inherit the live animated transform; this node's own position/rotation become a bone-space offset. Purely visual — headless it stays where its props put it, so keep gameplay checks range-based.`,ko:`"target"에 ModelInstance3D 노드 경로, "bone"에 본 이름을 줍니다("RightHand"는 Mixamo 표기도 자동 매칭). 자식들이 살아있는 애니메이션 트랜스폼을 물려받고, 이 노드의 position/rotation은 본 기준 오프셋이 됩니다. 순수 시각 기능 — 헤드리스에서는 prop 위치에 머무니 게임 판정은 거리 기반으로 유지하세요.`}),Q(`Trail3D`,{en:`A fading world-space ribbon behind the parent — wingtip trails, sword arcs, tyre streaks.`,ko:`부모 뒤로 남는 페이드아웃 월드 리본 — 날개끝 궤적, 검격 궤적, 타이어 자국.`},{en:"Child of the moving node. Records the world position over `seconds` and renders a camera-facing strip that tapers and fades to the tail. width (m), color, opacity, additive for glowing energy trails, minDistance filters jitter. emitting: false stops laying new ribbon while the old tail fades out.",ko:`움직이는 노드의 자식으로 두세요. seconds 동안의 월드 위치를 기록해 꼬리로 갈수록 가늘어지고 투명해지는 카메라 지향 스트립을 그립니다. width(m), color, opacity, 빛나는 에너지 궤적에는 additive, minDistance로 떨림을 걸러냅니다. emitting: false면 새 리본만 멈추고 기존 꼬리는 자연스럽게 사라집니다.`}),Q(`Joint3D`,{en:`A physics joint linking its parent body to a target body — weld, ball joint, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 볼 조인트, 로프, 스프링.`},{en:`Child of body A; "target" is a node path to body B. type: fixed (rigid weld) / spherical (ball joint at the anchors) / rope (caps anchor distance at length m; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL meter offsets.`,ko:`바디 A의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / spherical(앵커 볼 조인트) / rope(앵커 간 거리를 length m로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 미터 오프셋.`})]},{id:`network`,label:{en:`Network`,ko:`네트워크`},intro:{en:`Multiplayer is transport-agnostic: the engine speaks one NetworkTransport interface (built-in offline Loopback + an @agent8/gameserver adapter). The scene declares replication; one owner node per player broadcasts its sync keys.`,ko:`멀티플레이어는 트랜스포트 불가지론입니다 — 엔진은 NetworkTransport 인터페이스 하나만 사용합니다(내장 오프라인 Loopback + @agent8/gameserver 어댑터). 복제는 씬이 선언하며, 플레이어당 하나의 owner 노드가 sync 키를 송출합니다.`},nodes:[Q(`NetworkSpawner`,{en:`Spawns a registered scene per remote player/entity.`,ko:`원격 플레이어/엔티티마다 등록된 씬을 생성.`},{en:`source "users" mirrors every OTHER account in the room (self skipped); "collection:<id>" mirrors a room collection. Replicated sync patches apply to each instance; position interpolates. Emits spawned/despawned.`,ko:`source "users"는 방의 다른 모든 계정을 미러링하고(자신 제외) "collection:<id>"는 방 컬렉션을 미러링합니다. 복제 sync 패치가 인스턴스에 적용되고 position은 보간됩니다. spawned/despawned를 발산합니다.`})]}],RF=`overview`,zF=null;function BF(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),UF()}function VF(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function HF(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&VF()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,VF))}function UF(){let e=document.querySelector(`#docs-tabs`),t=document.querySelector(`#docs-body`);if(!e||!t)return;e.textContent=``;let n=(t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`docs-tab${RF===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{RF=t,zF=null,UF()}),e.appendChild(r)};n(`overview`,YP({en:`Overview`,ko:`개요`}));for(let e of LF)n(e.id,YP(e.label));if(t.textContent=``,RF===`overview`){WF(t);return}let r=LF.find(e=>e.id===RF);r&&GF(t,r)}function WF(e){let t=document.createElement(`h2`);t.textContent=YP(IF.title),e.appendChild(t);for(let t of IF.sections){let n=document.createElement(`h3`);n.textContent=YP(t.heading);let r=document.createElement(`p`);r.textContent=YP(t.text),e.append(n,r)}}function GF(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=YP(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${zF===n.type?` open`:``}`;let r=document.createElement(`button`);r.type=`button`,r.className=`docs-node-head`;let i=document.createElement(`span`);i.className=`tree-icon`,i.appendChild(QP(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=YP(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{zF=zF===n.type?null:n.type,UF()}),t.appendChild(r),zF===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=YP(t),e.appendChild(n)}e.appendChild(KF(n.type)),t.appendChild(e)}e.appendChild(t)}}function KF(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[YP({en:`prop`,ko:`prop`}),YP({en:`default`,ko:`기본값`})]){let t=document.createElement(`th`);t.textContent=e,n.appendChild(t)}t.appendChild(n);try{let n=qe(e);for(let[e,r]of Object.entries(n)){let n=document.createElement(`tr`),i=document.createElement(`td`);i.className=`mono`,i.textContent=e;let a=document.createElement(`td`);a.className=`mono`,a.textContent=JSON.stringify(r.default),n.append(i,a),t.appendChild(n)}}catch{}return t}function $(e){return Math.round(e*100)/100}function qF(e,t,n,r,i){return{name:e,type:`StaticBody3D`,props:{collider:{shape:`box`,size:t},position:n,...i?{rotation:i}:{}},children:[{name:`Skin`,type:`MeshInstance3D`,props:{mesh:`box`,size:t,...r}}]}}function JF(e,t,n,r,i,a){let o=$(r.range(i[0],i[1])),s=$(r.range(.5,.7));return{name:`Rock${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[t,$(o*s*.6),n],rotation:[0,r.int(0,359),0],scale:[o,$(o*s),$(o*r.range(.8,1.1))],material:{color:a??YF(r),roughness:1},castShadow:!0}}}function YF(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function XF(e){return[{name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(e*.8),$(e*1.5),$(e*.6)],intensity:1,castShadow:!0,shadowArea:$(e*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-e*.8),$(e*.8),$(-e*.6)],intensity:.4,color:`#b9d4ff`}}]}function ZF(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function QF(e,t,n){return Math.min(Math.max(e,t),n)}var $F=[`boxes`,`ruins`,`garden`],eI=.5,tI=.1,nI=2,rI={boxes:{floor:`#3f3f3f`,wall:`#55504a`,obstacles:[`#b0413e`,`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#878787`]},ruins:{floor:`#7d766b`,wall:`#8a8378`,obstacles:[`#8a8378`,`#979085`,`#a39a8d`,`#7b746a`]},garden:{floor:`#4d7c3a`,wall:`#2f6b2f`,obstacles:[`#2f6b2f`,`#3a7a38`,`#356e33`]}};function iI(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!$F.includes(o))throw new N(`BAD_FORMAT`,`generateArena theme must be one of [${$F.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...$F]});let s=rI[o],c=new P(t),l=[qF(`Floor`,[n,tI,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+eI*2,i,eI],f=[eI,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(qF(`Wall1`,d,[0,u,-(r+eI)/2],p),qF(`Wall2`,d,[0,u,(r+eI)/2],p),qF(`Wall3`,f,[-(n+eI)/2,u,0],p),qF(`Wall4`,f,[(n+eI)/2,u,0],p)),o===`ruins`?l.push(...oI(c,s,n,r,i,a)):l.push(...aI(c,s,n,r,i,a,o)),o===`garden`&&l.push(...sI(c,n,r));let m=Math.max(n,r);return l.push({name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(m*.8),$(m*1.5),$(m*.6)],intensity:1,castShadow:!0,shadowArea:$(m*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-m*.8),$(m*.8),$(-m*.6)],intensity:.4,color:`#b9d4ff`}},{name:`Lamp`,type:`OmniLight3D`,props:{position:[0,$(i+2),0],intensity:.5,color:`#fff3d6`,range:$(m)}}),{name:`Arena`,type:`Node3D`,children:l}}function aI(e,t,n,r,i,a,o){let s=[],c=o===`garden`?Math.min(n,r)*.16:0;for(let o=1;o<=a;o++){let a=[$(e.range(.8,2.6)),$(e.range(.8,Math.max(1.2,i*.8))),$(e.range(.8,2.6))],l=$(e.range(-(n/2-nI),n/2-nI)),u=$(e.range(-(r/2-nI),r/2-nI));if(c>0&&Math.hypot(l,u)<c+1.5){let t=Math.max(Math.hypot(l,u),.001);l=$(l/t*(c+1.5+e.range(0,2))),u=$(u/t*(c+1.5+e.range(0,2)))}let d=e.int(0,359);s.push(qF(`Obstacle${o}`,a,[l,$(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function oI(e,t,n,r,i,a){let o=[];if(a<=0)return o;let s=Math.max(1,Math.round(Math.sqrt(a/2))),c=Math.ceil(a/s),l=n-nI*2,u=r-nI*2,d=0;for(let n=0;n<s&&d<a;n++){let r=$(s===1?0:-u/2+n/(s-1)*u);for(let n=0;n<c&&d<a;n++){d++;let a=$((c===1?0:-l/2+n/(c-1)*l)+e.range(-.4,.4)),s=$(e.next()>.35?e.range(i*.7,i*1.2):e.range(.4,.9)),u=$(e.range(.8,1.2));o.push(qF(`Obstacle${d}`,[u,s,u],[a,$(s/2),$(r+e.range(-.4,.4))],{material:{color:e.pick(t.obstacles),roughness:.95},castShadow:!0},[0,e.int(-8,8),0]))}}return o}function sI(e,t,n){let r=[],i=Math.min(t,n)*.16,a=r=>{let a=Math.min(t,n)/2-r/2-1,o=$(e.range(-a,a)),s=$(e.range(-a,a)),c=Math.max(Math.hypot(o,s),.001);return c<i+r/2&&(o=$(o/c*(i+r/2+.5)),s=$(s/c*(i+r/2+.5))),[o,s]};for(let i=1;i<=3;i++){let o=$(Math.min(t,n)*e.range(.18,.26)),[s,c]=a(o);r.push({name:`Grass${i}`,type:`Foliage3D`,props:{kind:`grass`,area:[o,o],density:10,seed:e.int(1,1e9),position:[s,0,c]}})}for(let i=1;i<=2;i++){let o=$(Math.min(t,n)*e.range(.12,.18)),[s,c]=a(o);r.push({name:`FlowerBed${i}`,type:`Flowers3D`,props:{density:`lush`,clustering:.3,area:[o,o],seed:e.int(1,1e9),position:[s,0,c]}})}return r.push({name:`Pool`,type:`Water3D`,props:{size:[$(i*2),$(i*2)],position:[0,.3,0],waveHeight:.04}}),r}var cI=32,lI=[4,8],uI=`#332f3a`,dI=`#6b6357`;function fI(e){let{seed:t,rooms:n=5}=e,[r,i]=ZF(e.size,[960,720]),a=Math.max(8,Math.floor(r/cI)),o=Math.max(8,Math.floor(i/cI)),s=new P(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(lI[0],lI[1]),t=s.int(lI[0],lI[1]),n={x:s.int(1,Math.max(1,a-e-1)),y:s.int(1,Math.max(1,o-t-1)),w:e,h:t};c.some(e=>pI(e,n,1))||c.push(n)}let l=new Set,u=e=>{for(let t=e.y;t<e.y+e.h;t++)for(let n=e.x;n<e.x+e.w;n++)l.add(`${n},${t}`)};for(let e of c)u(e);let d=[];for(let e=1;e<c.length;e++){let[t,n]=mI(c[e-1]),[r,i]=mI(c[e]),a={x:Math.min(t,r),y:n,w:Math.abs(t-r)+1,h:1},o={x:r,y:Math.min(n,i),w:1,h:Math.abs(n-i)+1};for(let[t,n]of[[`H`,a],[`V`,o]])u(n),(n.w>1||n.h>1)&&d.push({name:`Corridor${e}${t}`,rect:n})}let f=new Set;for(let e of l){let[t,n]=e.split(`,`).map(Number);for(let e=-1;e<=1;e++)for(let r=-1;r<=1;r++){let i=`${t+r},${n+e}`;l.has(i)||f.add(i)}}let p=-(a*cI)/2,m=-(o*cI)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*cI,m+(t.y+t.h/2)*cI],size:[t.w*cI,t.h*cI],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,uI));for(let e of d)g.push(h(e.name,e.rect,uI));let _=0;for(let e=-1;e<=o;e++){let t=-1;for(;t<=a;){if(!f.has(`${t},${e}`)){t++;continue}let n=1;for(;t+n<=a&&f.has(`${t+n},${e}`);)n++;_++;let r=[n*cI,cI];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*cI,m+(e+.5)*cI],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:dI}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function pI(e,t,n){return e.x-n<t.x+t.w&&e.x+e.w+n>t.x&&e.y-n<t.y+t.h&&e.y+e.h+n>t.y}function mI(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var hI=[[0,-1],[1,0],[0,1],[-1,0]];function gI(e,t,n){let r=2*t+1,i=2*n+1,a=Array.from({length:i},()=>Array(r).fill(!1)),o=(e,t)=>{a[t][e]=!0};o(1,1);let s=new Set([`0,0`]),c=[[0,0]];for(;c.length>0;){let[r,i]=c[c.length-1],a=[];for(let[e,o]of hI){let c=r+e,l=i+o;c>=0&&c<t&&l>=0&&l<n&&!s.has(`${c},${l}`)&&a.push([c,l])}if(a.length===0){c.pop();continue}let[l,u]=e.pick(a);s.add(`${l},${u}`),o(2*l+1,2*u+1),o(r+l+1,i+u+1),c.push([l,u])}return o(0,1),o(2*t,2*n-1),{cols:t,rows:n,cells:a}}var _I=[`stone`,`hedge`,`canyon`],vI=.1,yI=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,bI=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,xI={stone:{wall:{color:`#e8e2d8`,map:`${yI}/blocks.png`,normalMap:`${yI}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${bI}/stone.png`,normalMap:`${bI}/stone_normal.png`,tile:3,roughness:1},cap:`#6b5848`,pillar:`#cfc8bb`,path:`#665f55`,sun:{color:`#c9d6ea`,intensity:.75,height:.5},fill:`#9fb4cc`,mood:{sky:{elevationDeg:10,azimuthDeg:150,turbidity:16,rayleigh:3.2},fog:{near:.5,far:3.5,color:`#86909c`},exposure:.82,ambient:{color:`#c9d4e2`,intensity:.12}}},hedge:{wall:{color:`#55a83e`,map:`${bI}/grass.png`,normalMap:`${bI}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${bI}/grass.png`,normalMap:`${bI}/grass_normal.png`,tile:3,roughness:1},pillar:`#3d7531`,path:`#7d6845`,sun:{color:`#e9eee6`,intensity:.7,height:1},fill:`#b9c8b4`,mood:{sky:{elevationDeg:35,azimuthDeg:150,turbidity:18,rayleigh:4.2},fog:{near:.8,far:5,color:`#aab8a6`},exposure:.88,ambient:{color:`#dde5d8`,intensity:.15}}},canyon:{wall:{color:`#f0b070`,map:`${bI}/stone.png`,normalMap:`${bI}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${bI}/sand.png`,normalMap:`${bI}/sand_normal.png`,tile:3.5,roughness:1},pillar:`#d8a868`,path:`#a98a58`,sun:{color:`#ffb572`,intensity:1.15,height:.35},fill:`#caa37e`,mood:{sky:{elevationDeg:9,azimuthDeg:230,turbidity:9,rayleigh:3.5},fog:{near:.7,far:4.5,color:`#c79c6e`},exposure:.92,ambient:{color:`#ffdcb6`,intensity:.13}}}};function SI(e,t,n){return{color:e.color,roughness:e.roughness,map:e.map,...e.normalMap?{normalMap:e.normalMap}:{},repeat:[$(t/e.tile),$(n/e.tile)]}}var CI=10;function wI(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!_I.includes(o))throw new N(`BAD_FORMAT`,`generateMaze theme must be one of [${_I.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[..._I]});let s=xI[o],c=new P(t),l=gI(c,n,r),u=2*n+1,d=2*r+1,f=$(u*i),p=$(d*i),m=(e,t)=>[$((e+.5)*i-f/2),$((t+.5)*i-p/2)],h=[qF(`Floor`,[f,vI,p],[0,-.1/2,0],{material:SI(s.floor,f,p),receiveShadow:!0})],g=[],_=0;for(let e=0;e<d;e++){let t=0;for(;t<u;){if(l.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<u&&!l.cells[e]?.[t+n];)n++;g.push({gx:t,gz:e,run:n}),_++;let r=$(n*i);h.push(qF(`Wall${_}`,[r,a,i],[$((t+n/2)*i-f/2),$(a/2),$((e+.5)*i-p/2)],{material:SI(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...TI(g,i,a,f,p,s.cap)),h.push(...EI(c,l,i,a,m,s)),o===`hedge`?(h.push(...AI(c,g,i,a,m)),h.push(...jI(c,l,i,m,n,r))):o===`canyon`&&h.push(...MI(c,g,i,a,m)),h.push(...OI(l,i,a,m,s)),h.push(...XF(Math.max(f,p)).map((e,t)=>{if(t!==0)return{...e,props:{...e.props,color:s.fill}};let n=e.props?.position;return{...e,props:{...e.props,color:s.sun.color,intensity:s.sun.intensity,position:[n[0]??0,$((n[1]??0)*s.sun.height),n[2]??0]}}})),{name:`Maze`,type:`Node3D`,children:h}}function TI(e,t,n,r,i,a){return e.map((e,o)=>({name:`Cap${o+1}`,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(e.run*t+.16),.12,$(t+.16)],position:[$((e.gx+e.run/2)*t-r/2),$(n+.06),$((e.gz+.5)*t-i/2)],material:{color:a,roughness:1},castShadow:!0,receiveShadow:!0}}))}function EI(e,t,n,r,i,a){let o=[],s=(e,n)=>t.cells[n]?.[e]===!1;for(let e=2;e<t.cells.length-1;e+=2)for(let n=2;n<(t.cells[e]?.length??0)-1;n+=2)s(n,e)&&Number(s(n-1,e))+Number(s(n+1,e))+Number(s(n,e-1))+Number(s(n,e+1))>=3&&o.push([n,e]);let c=Math.min(CI,o.length),l=[],u=new Set,d=$(n*1.2),f=$(r*1.12);for(let t=1;t<=c;t++){let n=e.int(0,o.length-1);for(;u.has(n);)n=(n+1)%o.length;u.add(n);let[r,s]=o[n],[c,p]=i(r,s);l.push(DI(`Pillar${t}`,c,p,d,f,a))}return l}function DI(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,$(i/2),n],material:{...SI(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function OI(e,t,n,r,i){let a=2*e.cols,o=2*e.rows-1,s=$(t*1.1),c=$(n*1.25),l=[[0,0],[0,2],[a,o-1],[a,o+1]].map(([e,t],n)=>{let[a,o]=r(e,t);return DI(`Gate${n+1}`,a,o,s,c,i)});for(let[e,n,s]of[[`EntrancePath`,0,1],[`ExitPath`,a,o]]){let[a,o]=r(n,s);l.push({name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(t*.96),.04,$(t*.96)],position:[a,.02,o],material:{...SI(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var kI=10;function AI(e,t,n,r,i){return[...t].filter(e=>e.run>=2).sort((e,t)=>t.run-e.run||e.gz-t.gz||e.gx-t.gx).slice(0,kI).map((t,a)=>{let[,o]=i(t.gx,t.gz),[s]=i(t.gx,t.gz),[c]=i(t.gx+t.run-1,t.gz);return{name:`HedgeTop${a+1}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[$(t.run*n*.92),$(n*.7)],density:14,height:.35,sway:.4,colorA:`#2f5e26`,colorB:`#5d8a3c`,seed:e.int(1,1e9),position:[$((s+c)/2),r,o]}}})}function jI(e,t,n,r,i,a){let o=[];for(let e=0;e<t.cells.length;e++)for(let n=0;n<(t.cells[e]?.length??0);n++)t.cells[e]?.[n]&&o.push([n,e]);let s=Math.min(o.length,Math.max(3,Math.floor(i*a/12))),c=[],l=new Set;for(let t=1;t<=s&&l.size<o.length;t++){let i=e.int(0,o.length-1);for(;l.has(i);)i=(i+1)%o.length;l.add(i);let[a,s]=o[i],[u,d]=r(a,s),f=$(n*.8);c.push({name:`Grass${t}`,type:`Foliage3D`,props:{kind:`grass`,area:[f,f],density:8,seed:e.int(1,1e9),position:[u,0,d]}})}return c}function MI(e,t,n,r,i){let a=[];if(t.length===0)return a;let o=Math.min(8,t.length);for(let s=1;s<=o;s++){let o=e.pick(t),[c,l]=i(o.gx+e.int(0,o.run-1),o.gz),u=JF(s,c,l,e,[.3,$(n*.35)],`#8f7355`),d=u.props?.position;d[1]=$(d[1]+r),a.push(u)}return a}var NI=`#23222b`,PI=`#5f6672`;function FI(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=gI(new P(t),n,r),o=2*n+1,s=2*r+1,c=$(o*i),l=$(s*i),u=[{name:`Floor`,type:`ColorRect2D`,props:{size:[c,l],color:NI}}],d=0;for(let e=0;e<s;e++){let t=0;for(;t<o;){if(a.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<o&&!a.cells[e]?.[t+n];)n++;d++;let r=[$(n*i),i];u.push({name:`Wall${d}`,type:`StaticBody2D`,props:{position:[$((t+n/2)*i-c/2),$((e+.5)*i-l/2)],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:PI}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var II=16,LI=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function RI(e){let{seed:t,count:n=10,width:r=[80,160],gapX:i=[40,120],stepY:a=[-80,40],start:o=[0,300]}=e,s=new P(t),c=[],l=$(s.range(r[0],r[1])),u=o[0],d=o[1];for(let e=1;e<=n&&(c.push(zI(e,u,d,l,s.pick(LI))),e!==n);e++){let e=$(s.range(r[0],r[1])),t=$(s.range(i[0],i[1]));u=$(u+l/2+t+e/2),d=$(d+s.range(a[0],a[1])),l=e}return{name:`Platforms`,type:`Node2D`,children:c}}function zI(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,II]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,II],color:i}}]}}var BI=[3,5],VI=3,HI={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function UI(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=ZF(e.area,[60,60]),o=new P(t),s=[];for(let e=1;e<=n;e++){let t=o.int(BI[0],BI[1]),n=[];for(let e=1;e<=t;e++){let r=$(o.range(1,2.2));n.push({name:`Puff${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[$((e-(t+1)/2)*o.range(1,1.6)),$(o.range(-.3,.3)),$(o.range(-.6,.6))],scale:[$(r*o.range(1.1,1.6)),$(r*.55),r],material:HI}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[$(o.range(-i/2,i/2)),$(r+o.range(-3,VI)),$(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,children:s}}var WI=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],GI=128,KI=20,qI=.8,JI=.12,YI={island:{splat:`island`,maxHeight:4.5,sun:`#fff4d6`,fill:`#b9d4ff`,sky:{elevationDeg:38,azimuthDeg:145,turbidity:2.6,rayleigh:1.1},fog:{near:1,far:4},iblIntensity:.72},alpine:{splat:`alpine`,maxHeight:8,roughness:.65,detail:5,sun:`#f4f7ff`,fill:`#c9d8f2`,sky:{elevationDeg:45,azimuthDeg:35,turbidity:1.4,rayleigh:1.3},fog:{near:1.8,far:6.5},sunIntensity:1.1,exposure:.92,iblIntensity:.72},plains:{splat:`plains`,maxHeight:4,sun:`#fff2cf`,fill:`#bcd3ef`,sky:{elevationDeg:36,azimuthDeg:140,turbidity:2.4,rayleigh:1},fog:{near:.9,far:4},iblIntensity:.58},desert:{splat:`desert`,maxHeight:5,sun:`#ffe3b3`,fill:`#e8c9a6`,sky:{elevationDeg:42,azimuthDeg:160,turbidity:7,rayleigh:.6},fog:{near:.8,far:3.2,color:`#e8d3ae`},sunIntensity:1.35,iblIntensity:.75},meadow:{splat:`grassland`,maxHeight:1.2,sun:`#fff8e2`,fill:`#bfe0c9`,sky:{elevationDeg:55,azimuthDeg:125,turbidity:2.4,rayleigh:.95},fog:{near:1,far:4.4},sunIntensity:2.6,exposure:1.12,iblIntensity:.62},forest:{splat:`forest`,maxHeight:2.5,sun:`#ffdca8`,fill:`#a9c8b4`,sky:{elevationDeg:29,azimuthDeg:120,turbidity:5.5,rayleigh:1},fog:{near:.22,far:1.8,color:`#9fb494`},sunIntensity:2.6,ambient:.26,iblIntensity:.55},savanna:{splat:`savanna`,maxHeight:3,sun:`#ffdca0`,fill:`#e6d2a4`,sky:{elevationDeg:34,azimuthDeg:150,turbidity:5,rayleigh:.7},fog:{near:1,far:4.2,color:`#e3cf9f`},sunIntensity:2,exposure:1.05,iblIntensity:.6},snow:{splat:`snow`,maxHeight:2.2,sun:`#dfe9ff`,fill:`#c2d2f0`,sky:{elevationDeg:22,azimuthDeg:35,turbidity:1.6,rayleigh:1.6},fog:{near:1.2,far:5,color:`#dbe6f5`},sunIntensity:1,exposure:.9,iblIntensity:.72},wetland:{splat:`wetland`,maxHeight:1.4,sun:`#d6ddc8`,fill:`#9fb29a`,sky:{elevationDeg:24,azimuthDeg:115,turbidity:9,rayleigh:1.1},fog:{near:.5,far:2,color:`#92a288`},sunIntensity:1.5,exposure:.94,ambient:.24,iblIntensity:.66},volcanic:{splat:`volcanic`,maxHeight:4,roughness:.7,sun:`#ff8a4a`,fill:`#7a4a3a`,sky:{elevationDeg:14,azimuthDeg:135,turbidity:10,rayleigh:.3},fog:{near:.18,far:1.4,color:`#2a211c`},sunIntensity:1.7,exposure:.86,ambient:.22,iblIntensity:.5}};function XI(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=YI[n];if(!a)throw new N(`BAD_FORMAT`,`generateTerrain theme must be one of [${WI.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...WI]});let o=Math.max(2,Math.round(e.resolution??GI)),s=e.maxHeight||a.maxHeight,c=new P(t),l=n===`island`,u=e=>Bw({width:r,depth:r,segsX:o,segsZ:o,maxHeight:e,seed:t,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},islandEdge:l}),d=u(s);if(l)for(let e=0;e<3;e++){let e=QI(d)-KI,t=d.maxHeight-d.minHeight,n=d.minHeight+JI*t;if(e+qI<=n)break;let r=KI-qI,i=QI(d)-d.minHeight-JI*t;s=$(s*Math.min(r/i*.95,.9)),d=u(s)}let f=[{name:`Ground`,type:`StaticBody3D`,props:{collider:{shape:`heightfield`}},children:[{name:`Surface`,type:`Terrain3D`,props:{size:[r,r],maxHeight:s,seed:t,theme:a.splat,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},...o===GI?{}:{resolution:o}}}]}],p=n===`wetland`;if(l)f.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,ZI(d),0],opacity:1}});else if(p){let e=d.maxHeight-d.minHeight||1,t=$(d.minHeight+.22*e);f.push({name:`Swamp`,type:`Water3D`,props:{size:[r,r],position:[0,t,0],waveHeight:.02,quality:`simple`,color:`#3a4a30`,opacity:.95}})}else if(i){let e=$(d.minHeight+.1*(d.maxHeight-d.minHeight));f.push({name:`Lake`,type:`Water3D`,props:{size:[r,r],position:[0,e,0],waveHeight:.04}})}return f.push(...mL(n,c,d,r)),l&&f.push(UI({seed:c.int(1,1e9),count:6,area:r,altitude:Math.round(d.maxHeight+12)})),f.push(...XF(r).map((e,t)=>hL(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:f}}function ZI(e){let t=QI(e)-KI,n=e.minHeight+JI*(e.maxHeight-e.minHeight);return $(Math.max(Math.min(t+qI,n),t+.55))}function QI(e){let t=-1/0,n=e.width/2,r=e.depth/2,i=e.segsX;for(let a=0;a<=i;a++){let o=-n+a/i*e.width,s=-r+a/i*e.depth;t=Math.max(t,e.baseHeight(o,-r),e.baseHeight(o,r),e.baseHeight(-n,s),e.baseHeight(n,s))}return t}function $I(e,t,n){let r=Math.min(t.width/2-n.margin,n.within??1/0),i=t.maxHeight-t.minHeight||1,a=[];for(let o=0;o<n.count*30&&a.length<n.count;o++){let o=$(e.range(-r,r)),s=$(e.range(-r,r));if(n.clearing&&Math.hypot(o,s)<n.clearing||n.within&&Math.hypot(o,s)>n.within)continue;let c=t.heightAt(o,s),l=(c-t.minHeight)/i;l<n.band[0]||l>n.band[1]||t.slopeAt(o,s)>n.maxSlope||a.push({x:o,z:s,y:c})}return a}var eL=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],tL=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],nL={canopy:`#9aa052`,trunk:`#8a6a44`},rL={canopy:`#39513f`,trunk:`#5a5650`};function iL(e,t){return e===`conifer`?t.pick(eL):e===`broadleaf`?t.pick(tL):null}function aL(e,t,n,r,i){let a=i?.height??[4.5,7],o=i?.sink??(i?.count===void 0?.05:.3),s={};i?.tier!==void 0&&(s.tier=i.tier),i?.count!==void 0&&i.area!==void 0&&(s.count=i.count,s.area=[i.area,i.area]);let c=iL(r,n),l=i?.palette??c;return l&&(s.canopyColor=l.canopy,s.trunkColor=l.trunk),{name:e,type:`Tree3D`,props:{type:r,seed:n.int(1,1e9),height:$(n.range(a[0],a[1])),position:[t.x,$(t.y-o),t.z],...s}}}function oL(e,t,n,r,i,a=0,o){return{name:e,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[r,r],density:i,height:o?.height??.3,...o?.colors?{colorA:o.colors[0],colorB:o.colors[1]}:{},seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z],...a>0?{flowers:a}:{}}}}function sL(e,t,n,r,i){return{name:e,type:`Foliage3D`,props:{kind:`reeds`,style:`simple`,area:[r,r],density:i,height:.9,colorA:`#2f4a26`,colorB:`#5a6f33`,seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function cL(e,t,n,r,i){return{name:e,type:`Flowers3D`,props:{density:i,area:[r,r],seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function lL(e,t,n,r){return e.map((e,i)=>{let a=JF(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=$(o[1]+e.y),a})}function uL(e){let t=Math.round(e.range(104,128)),n=Math.round(t-e.range(10,18)),r=Math.round(t-e.range(20,30)),i=e=>e.toString(16).padStart(2,`0`);return`#${i(n)}${i(t)}${i(r)}`}function dL(e){let t=Math.round(e.range(196,224)),n=Math.min(255,t+Math.round(e.range(4,12))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(t)}${r(t)}${r(n)}`}function fL(e){let t=Math.round(e.range(34,56)),n=Math.min(255,t+Math.round(e.range(2,8))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(n)}${r(t)}${r(t)}`}var pL=[`#6f5b41`,`#7a644a`,`#665439`];function mL(e,t,n,r){let i=[];switch(e){case`island`:{let e=$I(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>aL(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=$I(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>aL(`Tree${n+1}`,e,t,`conifer`)));let r=$I(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...lL(r,t,[.6,1.8]));break}case`plains`:{let e=$I(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>aL(`Tree${n+1}`,e,t,`broadleaf`)));let r=$I(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...lL(r,t,[.4,1.2]));break}case`desert`:{let e=$I(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>aL(`Tree${n+1}`,e,t,`dead`)));let r=$I(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...lL(r,t,[.5,1.6]));break}case`meadow`:{let e=$(r*.09),a=$I(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>oL(`Carpet${r+1}`,n,t,e,30)));let o=$(r*.07),s=$I(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>cL(`Flowers${n+1}`,e,t,o,`sparse`)));let c=$I(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>aL(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=$I(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...lL(l,t,[.3,.9]));break}case`forest`:{let e=$(r*.12),a=r/2-8,o=cn(t.int(1,1e9)),s=(e,t,n)=>{let r=o(e/70,t/70);return r>.12?`conifer`:r<-.12?`broadleaf`:n%2==0?`conifer`:`broadleaf`},c=$I(t,n,{count:40,band:[0,1],maxSlope:.18,margin:8,clearing:e+6}),l=c.map((e,t)=>s(e.x,e.z,t));i.push(...c.map((e,n)=>aL(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(aL(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=$I(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>aL(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=$I(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>aL(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=$I(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>aL(`Bush${n+1}`,e,t,`bush`,{count:4,area:10,height:[2.1,3.1],sink:.12})));let p=0;c.forEach((e,r)=>{if(r%3==2)return;let o=t.range(0,Math.PI*2),s=t.range(2,4.5),c=t.int(1,1e9),l=$(QF(e.x+Math.cos(o)*s,-a,a)),u=$(QF(e.z+Math.sin(o)*s,-a,a));n.slopeAt(l,u)>.09||(p++,i.push({name:`Fern${p}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,tuftStyle:`fern`,area:[8,8],density:9,height:.4,colorA:`#4a6b34`,colorB:`#82a258`,seed:c,position:[l,$(n.heightAt(l,u)+.02),u]}}))});let m=$(r*.08),h=$I(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>oL(`Grass${n+1}`,e,t,m,20,0,{height:.24,colors:[`#4f7034`,`#85a154`]})));let g=u.length>0?t.int(3,5):0;for(let e=0;e<g;e++){let r=u[e%u.length],o=t.range(0,Math.PI*2),s=t.range(2.5,4.5),c=$(QF(r.x+Math.cos(o)*s,-a,a)),l=$(QF(r.z+Math.sin(o)*s,-a,a));i.push({name:`Log${e+1}`,type:`Tree3D`,props:{type:`dead`,seed:t.int(1,1e9),height:$(t.range(4.2,5.6)),trunkColor:`#4a4236`,position:[c,$(n.heightAt(c,l)+.12),l],rotation:[0,t.int(0,359),$(t.range(81,97))]}})}$I(t,n,{count:5,band:[0,1],maxSlope:.25,margin:9,clearing:e}).forEach((e,n)=>{let r=$(t.range(.16,.28)),a=$(t.range(.3,.55));i.push({name:`Stump${n+1}`,type:`MeshInstance3D`,props:{mesh:`cylinder`,size:[r,a,r],position:[e.x,$(e.y+a/2-.06),e.z],rotation:[0,t.int(0,359),0],material:{color:t.pick(pL),roughness:1},castShadow:!0}})});let _=$I(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...lL(_,t,[.3,1],uL));let v=$(e*.75),y=$I(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-$(v/Math.SQRT2)});i.push(...y.map((e,n)=>oL(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=$(e*.45),x=$I(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-$(b/Math.SQRT2)});i.push(...x.map((e,n)=>cL(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=$I(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>aL(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:nL})));let a=$(r*.09),o=$I(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>oL(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=$I(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...lL(s,t,[.4,1.4]));let c=$I(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>aL(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=$I(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>aL(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:rL})));let r=$I(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...lL(r,t,[.5,1.8],dL));break}case`wetland`:{let e=$(r*.08),a=$I(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>sL(`Reeds${r+1}`,n,t,e,4)));let o=$(r*.08),s=$I(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>oL(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=$I(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>aL(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=$I(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>aL(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=$I(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...lL(u,t,[.3,1],uL));break}case`volcanic`:{let e=$I(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>aL(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=$I(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...lL(r,t,[.4,1.8],fL)),$I(t,n,{count:3,band:[0,.6],maxSlope:.18,margin:12}).forEach((e,n)=>{t.int(1,1e9),i.push({name:`Smoke${n+1}`,type:`Particles3D`,props:{preset:`smoke`,position:[e.x,$(e.y+.2),e.z],rate:8,maxParticles:64,colorStart:`#5a5048`,colorEnd:`#2a2422`,sizeStart:18,sizeEnd:44}}),i.push({name:`Embers${n+1}`,type:`Particles3D`,props:{position:[e.x,$(e.y+.1),e.z],rate:10,maxParticles:48,lifetime:[.8,1.8],speed:[12,34],directionDeg:-90,spreadDeg:40,gravity:[0,-18],sizeStart:4,sizeEnd:1,colorStart:`#ffce6a`,colorEnd:`#d83a14`,blend:`add`}})});break}}return i}function hL(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var gL={arena:{description:`FPS stage: floor, 4 perimeter walls, obstacles, lights — themes: boxes (crates), ruins (broken stone rows), garden (hedges, grass, pool)`,dimension:`3d`,params:{theme:{type:`string`,default:`boxes`,options:[...$F]},width:{type:`number`,default:30,min:4},depth:{type:`number`,default:30,min:4},wallHeight:{type:`number`,default:3,min:.5},obstacles:{type:`number`,default:8,min:0}}},terrain:{description:`Heightfield world: StaticBody3D{heightfield} + Terrain3D + theme dressing (trees, rocks, grass, sea/clouds on island, broad swamp water on wetland, smoke/ember emitters on volcanic; maxHeight 0 = theme default; water adds a lake to non-island themes)`,dimension:`3d`,params:{theme:{type:`string`,default:`island`,options:[...WI]},size:{type:`number`,default:200,min:40,max:400},maxHeight:{type:`number`,default:0,min:0},water:{type:`boolean`,default:!1}}},maze:{description:`Recursive-backtracker 3D maze, west→east — themes: stone, hedge (green + grass), canyon (sandstone + rim rocks)`,dimension:`3d`,params:{theme:{type:`string`,default:`stone`,options:[..._I]},width:{type:`number`,default:8,min:2,max:40},depth:{type:`number`,default:8,min:2,max:40},cellSize:{type:`number`,default:2,min:.5},wallHeight:{type:`number`,default:2.5,min:.5}}},maze2d:{description:`The same maze algorithm as 2D ColorRect2D + StaticBody2D tiles`,dimension:`2d`,params:{cols:{type:`number`,default:10,min:2,max:40},rows:{type:`number`,default:8,min:2,max:40},cellPx:{type:`number`,default:64,min:8}}},dungeon2d:{description:`Roguelike rooms + L-corridors: floor rects, wall bodies (32px tiles)`,dimension:`2d`,params:{rooms:{type:`number`,default:5,min:1,max:20},size:{type:`number`,default:960,min:256}}},platforms2d:{description:`Left-to-right 2D platform course (tune ranges via the library)`,dimension:`2d`,params:{count:{type:`number`,default:10,min:1}}}},_L={arena:iI,terrain:XI,maze:wI,maze2d:FI,dungeon2d:fI,platforms2d:RI};function vL(e,t){let n=_L[e];if(!n){let t=Object.keys(_L);throw new N(`BAD_FORMAT`,`Unknown generator '${e}'. Valid: [${t.join(`, `)}] — the old meadow/forest/island/rocks/clouds generators became themes (e.g. terrain theme: 'meadow', arena theme: 'garden'); scatter is library-only (needs item templates).`,{validOptions:t})}return n(t)}function yL(e){return Object.entries(gL).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function bL(e,t){if(e.type===`boolean`)return t===!0||t===`true`;if(e.type===`number`){let n=typeof t==`boolean`?NaN:Number(t);return(t===``||!Number.isFinite(n))&&(n=e.default),e.min!==void 0&&(n=Math.max(e.min,n)),e.max!==void 0&&(n=Math.min(e.max,n)),n}let n=String(t);return e.options&&!e.options.includes(n)?e.default:n}function xL(){return Math.floor(Math.random()*1e6)}var SL=[],CL=new Map,wL=null;function TL(e){let t=document.querySelector(`#generate`);t&&(OL(e),t.removeAttribute(`hidden`))}function EL(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function DL(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&EL()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,EL),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,EL),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>kL(e)))}function OL(e){let t=document.querySelector(`#generate-body`),n=document.querySelector(`#generate-status`);if(!t)return;n&&(n.textContent=``),t.textContent=``;let r=e.working.dimension??`2d`;SL=yL(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=YP({en:`Deterministic ${r.toUpperCase()} environment generators — the subtree inserts under the selected node (the root when nothing is selected). The same seed always generates the same level.`,ko:`결정적 ${r.toUpperCase()} 환경 생성기 — 생성된 서브트리는 선택한 노드 아래에(선택이 없으면 루트에) 들어갑니다. 같은 시드는 항상 같은 레벨을 만듭니다.`}),t.appendChild(i);let a=AL(YP({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of SL){let t=document.createElement(`option`);t.value=e,t.textContent=e,o.appendChild(t)}a.appendChild(o),t.appendChild(a);let s=document.createElement(`p`);s.className=`gen-desc`,t.appendChild(s);let c=document.createElement(`div`);c.id=`generate-params`,t.appendChild(c);let l=AL(`seed`);wL=document.createElement(`input`),wL.type=`number`,wL.step=`1`,wL.value=String(xL());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=YP({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{wL&&(wL.value=String(xL()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(wL,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=SL.find(e=>e.name===o.value)??SL[0];if(e){s.textContent=e.meta.description,c.textContent=``,CL=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=AL(t),r;if(n.type===`boolean`)r=document.createElement(`input`),r.type=`checkbox`,r.checked=n.default===!0;else if(n.type===`string`&&n.options){r=document.createElement(`select`);for(let e of n.options){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}r.value=String(n.default)}else r=document.createElement(`input`),r.type=n.type===`number`?`number`:`text`,n.type===`number`&&(r.step=`any`,n.min!==void 0&&(r.min=String(n.min)),n.max!==void 0&&(r.max=String(n.max))),r.value=String(n.default),(n.min!==void 0||n.max!==void 0)&&(r.title=`${n.min??``}–${n.max??``}`);CL.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function kL(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=SL.find(e=>e.name===n?.value);if(!r||!wL)return;let i={seed:bL({type:`number`,default:xL(),min:0},wL.value)};for(let[e,t]of CL){let n=r.meta.params[e];n&&(i[e]=bL(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=vL(r.name,i)}catch(e){t&&(t.textContent=e instanceof Error?e.message:String(e));return}let o=e.insertNode(a,e.selection??[]);if(o===null){t&&(t.textContent=YP({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),wL&&(wL.value=String(xL())),EL()}function AL(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var jL={connections:{title:{en:`connections — wire a signal to a handler`,ko:`connections — 시그널을 핸들러에 연결`},body:{en:'A connection says "when THIS node emits THIS signal, call THIS method on THAT node" — declaratively, in the scene JSON, with no TypeScript. emits = leaving this node; receives = arriving at it. Paths resolve from the scene ROOT (`Player/Sword`, `.` for the root itself). A red target does not resolve and the game will refuse to load the scene. Handlers on a scripted node are free text: they live in your behavior, which the editor never loads.',ko:'연결은 "이 노드가 이 시그널을 보내면, 저 노드의 이 메서드를 호출한다"를 씬 JSON에 선언합니다 — TypeScript 없이. emits는 이 노드에서 나가는 것, receives는 들어오는 것입니다. 경로는 씬 루트 기준입니다(`Player/Sword`, 루트 자신은 `.`). 빨간 대상은 찾을 수 없다는 뜻이고, 게임은 그 씬을 열지 못합니다. 스크립트가 있는 노드의 핸들러는 자유 입력입니다 — 에디터가 읽지 않는 게임 코드에 있기 때문입니다.'}},groups:{title:{en:`groups — tag nodes for queries`,ko:`groups — 조회용 태그`},body:{en:`Free-form tags. Game code finds nodes with tree-wide queries like getNodesInGroup("coins"), and triggers can filter by group (e.g. only react to "player"). Type a name and press Enter.`,ko:`자유 형식 태그입니다. 게임 코드가 getNodesInGroup("coins")처럼 트리 전체에서 노드를 찾고, 트리거는 그룹으로 거릅니다(예: "player"에만 반응). 이름을 입력하고 Enter를 누르세요.`},example:`triggerEnter → if (other.isInGroup("player")) collect()`},script:{title:{en:`script — attach YOUR game logic`,ko:`script — 게임 로직 연결`},body:{en:`A Behavior is a TypeScript class living in YOUR game code, linked by name. The editor stores the link; the class itself must be registered in the game before loadScene. Props here are passed to the behavior instance.`,ko:`Behavior는 게임 코드에 있는 TypeScript 클래스이며 이름으로 연결됩니다. 에디터는 연결만 저장하고, 클래스 자체는 loadScene 전에 게임에서 등록되어야 합니다. 여기의 props가 비헤이비어 인스턴스로 전달됩니다.`},example:`registerBehavior('CoinCounter', CoinCounter) // in your main.ts`,copy:{label:`copy behavior boilerplate`,text:`import { Behavior, registerBehavior } from 'incanto';
8414
8414
 
8415
8415
  export class MyBehavior extends Behavior {
8416
8416
  static props = { speed: { default: 100 } };
@@ -8420,7 +8420,7 @@ export class MyBehavior extends Behavior {
8420
8420
  update(dt: number): void {}
8421
8421
  }
8422
8422
  registerBehavior('MyBehavior', MyBehavior); // before loadScene()
8423
- `}},network:{title:{en:`network — replicate to other players`,ko:`network — 다른 플레이어에게 복제`},body:{en:`mode "owner" means THIS player owns the node and broadcasts the listed sync keys to everyone in the room (one owner node per player — usually your player character). Other players see it via a NetworkSpawner. Keys are relative to this node: "position", or "Skin.animation" for a child prop.`,ko:`mode "owner"는 이 플레이어가 노드를 소유하고 sync 키 목록을 방의 모두에게 송출한다는 뜻입니다(플레이어당 owner 노드 하나 — 보통 내 캐릭터). 다른 플레이어는 NetworkSpawner로 봅니다. 키는 이 노드 기준 상대 표기입니다: "position", 자식 prop은 "Skin.animation".`},example:`{ "mode": "owner", "sync": ["position"], "throttleMs": 50 }`},collider:{title:{en:`collider — the physics shape`,ko:`collider — 물리 모양`},body:{en:`Shapes: rect (size [w,h]), circle (radius), capsule (radius + height — good for characters). offset shifts the shape from the node position. The green dashed outline in the viewport shows exactly where it is.`,ko:`모양: rect(size [w,h]), circle(radius), capsule(radius+height — 캐릭터에 적합). offset이 노드 위치에서 모양을 이동시킵니다. 뷰포트의 초록 점선이 정확한 위치를 보여줍니다.`},example:`{ "shape": "capsule", "radius": 12, "height": 16 }`},physics:{title:{en:`physics — scene gravity`,ko:`physics — 씬 중력`},body:{en:`World gravity in px/s² (y-down: positive y pulls DOWN). [0, 1400] feels platformer-y; [0, 0] for top-down. Takes effect when the game calls enablePhysics2D — and in the editor’s play mode.`,ko:`월드 중력, px/s² 단위(y-아래: 양수 y가 아래로 당김). [0, 1400]이면 플랫포머 느낌, 탑다운은 [0, 0]. 게임이 enablePhysics2D를 부를 때 — 그리고 에디터 플레이 모드에서 — 적용됩니다.`},example:`"physics": { "gravity": [0, 1400] }`}},jL=null;function ML(e){document.addEventListener(`click`,t=>{let n=t.target,r=n.closest(`[data-help]`);if(!r){e.contains(n)||(e.hidden=!0);return}let i=AL[r.dataset.help??``];if(!i)return;if(!e.hidden&&jL===r){e.hidden=!0;return}jL=r,e.textContent=``;let a=document.createElement(`h4`);a.textContent=JP(i.title);let o=document.createElement(`div`);if(o.textContent=JP(i.body),e.append(a,o),i.example){let t=document.createElement(`pre`);t.textContent=i.example,e.appendChild(t)}if(i.copy){let t=document.createElement(`div`);t.className=`pop-actions`;let n=document.createElement(`button`);n.type=`button`,n.className=`linklike`,n.textContent=`⧉ ${i.copy.label}`,n.addEventListener(`click`,()=>{navigator.clipboard.writeText(i.copy?.text??``),n.textContent=`✓ copied`}),t.appendChild(n),e.appendChild(t)}e.hidden=!1;let s=r.getBoundingClientRect();e.style.left=`${Math.max(8,Math.min(innerWidth-300-8,s.left-300+20))}px`,e.style.top=`${Math.min(innerHeight-60,s.bottom+8)}px`})}function NL(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`help-btn`,t.dataset.help=e,t.textContent=`?`,t.title=`What is this?`,t}var PL=JSON.parse('[{"name":"2dbasic","file":"characters/2dbasic.png","url":"incanto/assets/characters/2dbasic.png","kind":"character","bytes":30499,"description":"2dbasic sprite sheet image.anything,base character. (frame size 192x192)","animation":"characters/2dbasic.json","frameWidth":111,"frameHeight":83},{"name":"attacked","file":"audio/attacked.mp3","url":"incanto/assets/audio/attacked.mp3","kind":"audio","bytes":8757,"description":"Short hurt / took-damage SFX for the player or an enemy."},{"name":"bark_birch_color","file":"vegetation/bark/birch_color_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/birch_color_1k.jpg","kind":"foliage","bytes":194186,"description":"Birch bark base color texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_birch_normal","file":"vegetation/bark/birch_normal_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/birch_normal_1k.jpg","kind":"foliage","bytes":378046,"description":"Birch bark tangent-space normal texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_birch_roughness","file":"vegetation/bark/birch_roughness_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/birch_roughness_1k.jpg","kind":"foliage","bytes":127387,"description":"Birch bark roughness texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_oak_color","file":"vegetation/bark/oak_color_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/oak_color_1k.jpg","kind":"foliage","bytes":297877,"description":"Oak bark base color texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_oak_normal","file":"vegetation/bark/oak_normal_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/oak_normal_1k.jpg","kind":"foliage","bytes":67610,"description":"Oak bark tangent-space normal texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_oak_roughness","file":"vegetation/bark/oak_roughness_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/oak_roughness_1k.jpg","kind":"foliage","bytes":16648,"description":"Oak bark roughness texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_pine_color","file":"vegetation/bark/pine_color_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/pine_color_1k.jpg","kind":"foliage","bytes":196361,"description":"Pine bark base color texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_pine_normal","file":"vegetation/bark/pine_normal_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/pine_normal_1k.jpg","kind":"foliage","bytes":58237,"description":"Pine bark tangent-space normal texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_pine_roughness","file":"vegetation/bark/pine_roughness_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/pine_roughness_1k.jpg","kind":"foliage","bytes":36136,"description":"Pine bark roughness texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"box","file":"items/box.png","url":"incanto/assets/items/box.png","kind":"item","bytes":10861,"description":"Item box sprite for Dungeons and Dungeoners. Container sprite that holds random items or rewards when opened by player."},{"name":"buff_potion","file":"items/buff_potion.png","url":"incanto/assets/items/buff_potion.png","kind":"item","bytes":3809,"description":"Buff potion item sprite for Dungeons and Dungeoners. Consumable item that grants temporary stat boosts or positive effects to player character."},{"name":"coin","file":"items/coin.png","url":"incanto/assets/items/coin.png","kind":"item","bytes":1689,"description":"Gold coin collectible sprite for Dungeons and Dungeoners. Currency item with metallic sheen, used as in-game money or collectible reward."},{"name":"explosion","file":"audio/explosion.mp3","url":"incanto/assets/audio/explosion.mp3","kind":"audio","bytes":40124,"description":"Impactful explosion / large destructive hit SFX. Pair with the Particles2D \\"explosion\\" preset."},{"name":"floor00","file":"tiles/floor00.jpg","url":"incanto/assets/tiles/floor00.jpg","kind":"tile","bytes":28736,"description":"Basic floor tile texture for Dungeons and Dungeoners project, suitable for dungeon ground surfaces."},{"name":"gem","file":"items/gem.png","url":"incanto/assets/items/gem.png","kind":"item","bytes":8762,"description":"Gem collectible sprite for Dungeons and Dungeoners. Valuable gemstone item used as currency, crafting material, or quest objective."},{"name":"ghost","file":"characters/ghost.png","url":"incanto/assets/characters/ghost.png","kind":"character","bytes":22933,"description":"Ghost character with translucent appearance sprite sheet image (frame size 112x128)","animation":"characters/ghost.json","frameWidth":112,"frameHeight":128},{"name":"goblin","file":"characters/goblin.png","url":"incanto/assets/characters/goblin.png","kind":"character","bytes":57994,"description":"Medieval goblin with torch sprite sheet image (frame size 192x192)","animation":"characters/goblin.json","frameWidth":192,"frameHeight":192},{"name":"gold","file":"items/gold.png","url":"incanto/assets/items/gold.png","kind":"item","bytes":22313,"description":"Gold item sprite for Dungeons and Dungeoners. Gold pile or gold bar sprite representing valuable currency or treasure reward."},{"name":"gold-loot","file":"audio/gold_loot.mp3","url":"incanto/assets/audio/gold_loot.mp3","kind":"audio","bytes":7506,"description":"Metallic coin / gold pickup jingle — collecting currency."},{"name":"ground_dirt","file":"vegetation/ground/dirt_color.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground/dirt_color.jpg","kind":"foliage","bytes":231383,"description":"Dense dirt/gravel ground texture (1024px) from the ez-tree demo app (MIT) — the reference meadow ground. Terrain3D grassland themes tile it for slope + noise-patch dirt by default; also bundled in `incanto/assets` (see `file`) for offline use."},{"name":"ground_dirt_normal","file":"vegetation/ground/dirt_normal.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground/dirt_normal.jpg","kind":"foliage","bytes":123478,"description":"Dirt ground normal map (1024px) from the ez-tree demo app (MIT). Terrain3D grassland themes apply it across the whole ground band (demo parity); also bundled in `incanto/assets` (see `file`) for offline use."},{"name":"ground_grass","file":"vegetation/ground/grass.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground/grass.jpg","kind":"foliage","bytes":322486,"description":"Mossy meadow grass ground texture (1024px) from the ez-tree demo app (MIT). Terrain3D grassland themes (meadow/forest generators) tile it as the grass splat layer by default; also bundled in `incanto/assets` (see `file`) for offline use."},{"name":"heal","file":"audio/heal.mp3","url":"incanto/assets/audio/heal.mp3","kind":"audio","bytes":29764,"description":"Soothing health-restore / heal spell SFX."},{"name":"hit-metal-bang","file":"audio/hit_metal_bang.mp3","url":"incanto/assets/audio/hit_metal_bang.mp3","kind":"audio","bytes":17972,"description":"Metallic impact — hitting armor, metal, or a blocked attack."},{"name":"hp_potion","file":"items/hp_potion.png","url":"incanto/assets/items/hp_potion.png","kind":"item","bytes":3513,"description":"Health potion item sprite for Dungeons and Dungeoners. Consumable healing item that restores player health points when used."},{"name":"ice-spear","file":"audio/ice_spear.mp3","url":"incanto/assets/audio/ice_spear.mp3","kind":"audio","bytes":21315,"description":"Sharp piercing ice projectile fire SFX."},{"name":"leaves_ash","file":"vegetation/ash_color.png","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ash_color.png","kind":"foliage","bytes":181423,"description":"Ash leaf-cluster alpha-cutout texture (1024px) from ez-tree by Dan Greenheck (MIT). Tree3D samples it for broadleaf/dead ash variants by default; copy it next to your game and set leafTexture to serve offline."},{"name":"leaves_aspen","file":"vegetation/aspen_color.png","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/aspen_color.png","kind":"foliage","bytes":142116,"description":"Aspen leaf-cluster alpha-cutout texture (1024px) from ez-tree by Dan Greenheck (MIT). Tree3D samples it for high-tier broadleaf aspen variants; copy + leafTexture for offline serving."},{"name":"leaves_oak","file":"vegetation/oak_color.png","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/oak_color.png","kind":"foliage","bytes":238115,"description":"Oak leaf-cluster alpha-cutout texture (1024px) from ez-tree by Dan Greenheck (MIT). Tree3D samples it for broadleaf oak variants by default; copy + leafTexture for offline serving."},{"name":"leaves_pine","file":"vegetation/pine_color.png","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/pine_color.png","kind":"foliage","bytes":303684,"description":"Pine needle-cluster alpha-cutout texture (1024px) from ez-tree by Dan Greenheck (MIT). Tree3D samples it for conifer variants by default; copy + leafTexture for offline serving."},{"name":"locked_item_box","file":"items/locked_item_box.png","url":"incanto/assets/items/locked_item_box.png","kind":"item","bytes":11074,"description":"Locked item box sprite for Dungeons and Dungeoners. Container sprite requiring key or lockpick to open, containing valuable rewards."},{"name":"map","file":"items/map.png","url":"incanto/assets/items/map.png","kind":"item","bytes":3754,"description":"Map item sprite for Dungeons and Dungeoners. Navigation item revealing dungeon layout or providing exploration assistance."},{"name":"medieval-knight","file":"characters/medieval-knight.png","url":"incanto/assets/characters/medieval-knight.png","kind":"character","bytes":84367,"description":"(frame size 192x192) Using a medieval-themed SD(Super Deformed) knight sprite sheet image, you can apply idle, move, and attack animations, among others.","animation":"characters/medieval-knight.json","frameWidth":192,"frameHeight":192},{"name":"minecraft-tiles","file":"tiles/minecraft-tiles.png","url":"incanto/assets/tiles/minecraft-tiles.png","kind":"tile","bytes":10511,"description":"Minecraft-themed tiles sprite sheet image (frame size 16x16)"},{"name":"monster-died","file":"audio/monster_died.mp3","url":"incanto/assets/audio/monster_died.mp3","kind":"audio","bytes":16836,"description":"Enemy defeat / death SFX."},{"name":"resurrection_potion","file":"items/resurrection_potion.png","url":"incanto/assets/items/resurrection_potion.png","kind":"item","bytes":3471,"description":"Resurrection potion item sprite for Dungeons and Dungeoners. Rare consumable that revives fallen party members or prevents death."},{"name":"slash","file":"audio/slash.mp3","url":"incanto/assets/audio/slash.mp3","kind":"audio","bytes":10425,"description":"Quick sword swing / melee slash SFX."},{"name":"smite","file":"audio/smite.mp3","url":"incanto/assets/audio/smite.mp3","kind":"audio","bytes":12956,"description":"Powerful holy downward-strike SFX."},{"name":"spells-cast","file":"audio/spells_cast.mp3","url":"incanto/assets/audio/spells_cast.mp3","kind":"audio","bytes":22151,"description":"Generic magical spell-cast / chant SFX."},{"name":"super_box","file":"items/super_box.png","url":"incanto/assets/items/super_box.png","kind":"item","bytes":12184,"description":"Super item box sprite for Dungeons and Dungeoners. Premium container sprite containing rare or powerful items and equipment."},{"name":"swoosh","file":"effects/swoosh.png","url":"incanto/assets/effects/swoosh.png","kind":"effect","bytes":2599,"description":"Swoosh effect sprite for Dungeons and Dungeoners. Motion blur or attack trail effect used for melee attacks, sword slashes, or fast movement animations."},{"name":"trap","file":"items/trap.png","url":"incanto/assets/items/trap.png","kind":"item","bytes":3969,"description":"Trap object sprite for Dungeons and Dungeoners. Hazard sprite that damages players when triggered in dungeon exploration."},{"name":"ui-click","file":"audio/ui_click.wav","url":"incanto/assets/audio/ui_click.wav","kind":"audio","bytes":17332,"description":"Short tactile UI click for menus and buttons."},{"name":"walk","file":"audio/walk.mp3","url":"incanto/assets/audio/walk.mp3","kind":"audio","bytes":5642,"description":"Single footstep SFX for character movement (loop or one-shot)."},{"name":"wall00","file":"tiles/wall00.jpg","url":"incanto/assets/tiles/wall00.jpg","kind":"tile","bytes":44344,"description":"Basic wall tile texture for Dungeons and Dungeoners project, suitable for dungeon vertical boundaries."}]');function FL(e){let t=e.connections;return Array.isArray(t)?t:[]}function IL(e,t){if(!e||t===``)return null;if(t===`.`)return[];if(t.startsWith(`%`)){let n=t.slice(1);if(n===``||n.includes(`/`))return null;let r=[],i=(e,t)=>{e.name===n&&r.push(t),(e.children??[]).forEach((e,n)=>{i(e,[...t,n])})};return i(e,[]),r.length===1?r[0]:null}let n=t.startsWith(`/`),r=(n?t.slice(1):t).split(`/`);if(r.some(e=>e===``))return null;let i=r;if(n){if(r[0]!==e.name&&r[0]!==`root`)return null;i=r.slice(1)}let a=[],o=e;for(let t of i){if(t===`..`){if(a.length===0)return null;a.pop(),o=LL(e,a);continue}let n=(o.children??[]).findIndex(e=>e.name===t);if(n===-1)return null;a.push(n),o=o.children?.[n]}return a}function LL(e,t){let n=e;for(let e of t)n=n?.children?.[e];return n??null}function RL(e,t){if(!e)return``;if(t.length===0)return`.`;let n=[],r=e;for(let e of t){let t=r.children?.[e];if(!t)return``;n.push(String(t.name??``)),r=t}return n.join(`/`)}function zL(e,t){let n=e.root,r=e=>{if(typeof e!=`string`)return!1;let r=IL(n,e);return r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n])},i=[],a=[];return FL(e).forEach((e,t)=>{r(e.from)&&i.push({index:t,conn:e}),r(e.to)&&a.push({index:t,conn:e})}),{outgoing:i,incoming:a}}function BL(e){if(!e)return[];let t=[];if(typeof e.type==`string`&&e.type!==``)try{t.push(...Ye(e.type))}catch{}let n=e.script;return typeof n?.name==`string`&&t.push(...st(n.name)),[...new Set(t)]}function VL(e){if(!e||e.script?.name)return[];let t=typeof e.type==`string`?e.type:``;if(!t)return[];let n=null;try{n=Ge(t)}catch{return[]}let r=new Set;for(let e=n.prototype;e&&e!==Object.prototype;){for(let t of Object.getOwnPropertyNames(e))t===`constructor`||t.startsWith(`_`)||typeof Object.getOwnPropertyDescriptor(e,t)?.value==`function`&&r.add(t);e=Object.getPrototypeOf(e)}for(let e of HL)r.delete(e);return[...r].sort()}var HL=new Set([`addChild`,`removeChild`,`addToGroup`,`removeFromGroup`,`isInGroup`,`getNode`,`getNodeOrNull`,`getPath`,`getRoot`,`find`,`findAll`,`on`,`off`,`once`,`emit`,`declareSignal`,`update`,`fixedUpdate`,`toJSON`,`diagnose`]);function UL(e){if(!e)return[];let t=[{path:`.`,label:`${e.name} (root)`}],n=(r,i)=>{(r.children??[]).forEach((r,a)=>{let o=[...i,a];t.push({path:RL(e,o),label:RL(e,o)}),n(r,o)})};return n(e,[]),t}function WL(e,t){Array.isArray(e.connections)||(e.connections=[]);let n=e.connections;return n.push(t),n.length-1}function GL(e,t,n){let r=FL(e)[t];r&&Object.assign(r,n)}function KL(e,t){let n=FL(e);t<0||t>=n.length||(n.splice(t,1),n.length===0&&delete e.connections)}function qL(e,t){let n=e.working.root;if(!n)return null;let r=e.nodeAt(t);if(!r)return null;let i=document.createElement(`div`);i.className=`connections`;let{outgoing:a,incoming:o}=zL(e.working,t),s=RL(n,t);i.appendChild(JL(JP({en:`emits (${a.length})`,ko:`보냄 (${a.length})`})));for(let t of a)i.appendChild(YL(e,t,`out`));if(i.appendChild(XL(e,r,s)),o.length>0){i.appendChild(JL(JP({en:`receives (${o.length})`,ko:`받음 (${o.length})`})));for(let t of o)i.appendChild(YL(e,t,`in`))}return i}function JL(e){let t=document.createElement(`div`);return t.className=`conn-group`,t.textContent=e,t}function YL(e,{index:t,conn:n},r){let i=e.working.root,a=document.createElement(`div`);a.className=`conn-row`;let o=e.nodeAt(IL(i,String(n.from??``))??[-1]),s=r===`out`?`to`:`from`,c=String(n[s]??``),l=IL(i,c)===null,u=ZL(BL(o),String(n.signal??``),n=>{e.mutate(()=>GL(e.working,t,{signal:n}))});u.title=JP({en:`signal`,ko:`시그널`});let d=document.createElement(`span`);d.className=`conn-arrow`,d.textContent=r===`out`?`→`:`←`;let f=ZL(UL(i).map(e=>e.path),c,n=>{e.mutate(()=>GL(e.working,t,{[s]:n}))});f.title=JP({en:s,ko:s===`to`?`대상`:`출처`}),l&&f.classList.add(`dangling`);let p=VL(e.nodeAt(IL(i,String(n.to??``))??[-1])),m=n=>{e.mutate(()=>GL(e.working,t,{handler:n.trim()}))},h;if(p.length>0){let e=ZL(p,String(n.handler??``),m);e.title=JP({en:`handler method`,ko:`핸들러 메서드`}),h=e}else{let e=document.createElement(`input`);e.type=`text`,e.className=`conn-handler`,e.value=String(n.handler??``),e.placeholder=`onSomething`,e.title=JP({en:`handler method on the target (defined in your behavior)`,ko:`대상의 핸들러 메서드 (비헤이비어에 정의)`}),e.addEventListener(`change`,()=>m(e.value)),h=e}let g=document.createElement(`button`);if(g.type=`button`,g.className=`conn-remove`,g.textContent=`✕`,g.title=JP({en:`remove this connection`,ko:`이 연결 삭제`}),g.addEventListener(`click`,()=>{e.mutate(()=>KL(e.working,t))}),a.append(u,d,f,h,g),l){let e=document.createElement(`div`);e.className=`conn-warn`,e.textContent=JP({en:`'${c}' does not resolve — the game will refuse to load this scene.`,ko:`'${c}' 을(를) 찾을 수 없습니다 — 게임이 이 씬을 열지 못합니다.`});let t=document.createElement(`div`);return t.append(a,e),t}return a}function XL(e,t,n){let r=BL(t),i=document.createElement(`div`);i.className=`conn-add`;let a=document.createElement(`button`);return a.type=`button`,a.textContent=JP({en:`+ connect`,ko:`+ 연결`}),a.disabled=r.length===0,r.length===0&&(a.title=JP({en:`this node declares no signals`,ko:`이 노드는 시그널을 선언하지 않습니다`})),a.addEventListener(`click`,()=>{let i=r[0]??``,a={from:n,signal:i,to:n,handler:VL(t)[0]??`on${i.charAt(0).toUpperCase()}${i.slice(1)}`};e.mutate(()=>{WL(e.working,a)})}),i.appendChild(a),i}function ZL(e,t,n){let r=document.createElement(`select`);r.className=`conn-select`;for(let n of e.includes(t)?e:[t,...e]){let e=document.createElement(`option`);e.value=n,e.textContent=n===``?`—`:n,n===t&&(e.selected=!0),r.appendChild(e)}return r.addEventListener(`change`,()=>n(r.value)),r}function QL(e,t,n,r){return{cx:Math.floor((n-e.x)/t),cy:Math.floor((r-e.y)/t)}}function $L(e,t,n,r){if(t<0||n<0||r.length!==1)return null;let i=e.map(e=>typeof e==`string`?e:e.map(e=>e>=0&&e<=9?String(e):`.`).join(``)),a=Math.max(t+1,...i.map(e=>e.length)),o=Math.max(n+1,i.length),s=[];for(let e=0;e<o;e++){let o=i[e]??``;o=o.padEnd(a,`.`),e===n&&(o=o.slice(0,t)+r+o.slice(t+1)),s.push(o)}return s}function eR(e,t){let n=new Set([`.`,`0`,`1`]);for(let t of e)if(typeof t==`string`)for(let e of t)e!==` `&&n.add(e);for(let e of Object.keys(t))n.add(e);return[...n]}var tR=PL;function nR(e){return(e.kind===`foliage`||e.kind===`tile`)&&!e.animation}function rR(e,t,n){if(e.textContent=``,t.selection===null){aR(e,t,n);return}let r=t.nodeAt(t.selection);r&&mR(e,t,r,n)}var iR=[`connections`,`input`,`multiplayer`];function aR(e,t,n){e.appendChild(zR(`scene`)),e.appendChild(UR(`name`,String(t.working.name??``),e=>{t.mutate(()=>{t.working.name=e})}));let r=document.createElement(`select`);for(let e of[`2d`,`3d`]){let n=document.createElement(`option`);n.value=e,n.textContent=e,(t.working.dimension??`2d`)===e&&(n.selected=!0),r.appendChild(n)}r.addEventListener(`change`,()=>{t.mutate(()=>{t.working.dimension=r.value})}),e.appendChild(VR(`dimension`,r)),e.appendChild(zR(`physics`,`physics`));let i=(t.working.physics??{}).gravity??(t.working.dimension===`3d`?[0,-9.81,0]:[0,980]),a=t.working.dimension===`3d`?[0,-9.81,0]:[0,980];e.appendChild(GR(`gravity`,i,e=>{t.mutate(()=>{if(JSON.stringify(e)===JSON.stringify(a)){let e={...t.working.physics};delete e.gravity,Object.keys(e).length===0?delete t.working.physics:t.working.physics=e}else t.working.physics={...t.working.physics,gravity:e}})})),e.appendChild(zR(`environment`)),oR(e,t),e.appendChild(zR(`constants`)),NR(e,t,n),e.appendChild(zR(`advanced`));for(let n of iR)e.appendChild(qR(n,t.working[n],e=>{t.mutate(()=>{e===void 0?delete t.working[n]:t.working[n]=e})}))}function oR(e,t){let n=t.working.environment??{},r=e=>{t.mutate(()=>{let n={...t.working.environment??{},...e};for(let e of Object.keys(n))n[e]===void 0&&delete n[e];Object.keys(n).length===0?delete t.working.environment:t.working.environment=n})};e.appendChild(sR(`background`,n.background??``,e=>{r({background:e===``?void 0:e})})),e.appendChild(sR(`ambient color`,n.ambient?.color??``,e=>{let t={...n.ambient,color:e===``?void 0:e};t.color===void 0&&delete t.color,r({ambient:Object.keys(t).length?t:void 0})})),e.appendChild(WR(`ambient power`,n.ambient?.intensity??0,e=>{r({ambient:{...n.ambient,intensity:e}})}));let i=n.rendering??{},a=e=>{let t={...i,...e};for(let e of Object.keys(t))t[e]===void 0&&delete t[e];r({rendering:Object.keys(t).length?t:void 0})},o=document.createElement(`input`);o.type=`checkbox`,o.checked=i.antialias!==!1,o.addEventListener(`change`,()=>{a({antialias:o.checked?void 0:!1})}),e.appendChild(VR(`antialias`,o));let s=document.createElement(`select`);for(let[e,t]of[[``,`1 — soft hiDPI upscale (default)`],[`device`,`device — crisp retina`],[`2`,`2`]]){let n=document.createElement(`option`);n.value=e,n.textContent=t,String(i.pixelRatio??``)===e&&(n.selected=!0),s.appendChild(n)}s.addEventListener(`change`,()=>{a({pixelRatio:s.value===``?void 0:s.value===`device`?`device`:Number(s.value)})}),e.appendChild(VR(`pixel ratio`,s))}function sR(e,t,n){let r=document.createElement(`div`);r.className=`color-row`;let i=document.createElement(`input`);i.type=`color`,i.value=/^#[0-9a-fA-F]{6}$/.test(t)?t:`#000000`;let a=document.createElement(`input`);return a.type=`text`,a.className=`mono`,a.placeholder=`unset`,a.value=t,i.addEventListener(`input`,()=>{a.value=i.value}),i.addEventListener(`change`,()=>n(i.value)),a.addEventListener(`change`,()=>n(a.value.trim())),r.append(i,a),VR(e,r)}function cR(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.textContent=`underwater`,n.appendChild(r);let i=t.props?.underwater,a=i!==!1,o=i&&typeof i==`object`&&!Array.isArray(i)?i:{},s=n=>{e.mutate(()=>{t.props||={},n===!0?delete t.props.underwater:t.props.underwater=n,Object.keys(t.props).length===0&&delete t.props})},c=(e,t)=>{let n={...o};t===void 0||t===``?delete n[e]:n[e]=t,s(Object.keys(n).length===0?!0:n)},l=document.createElement(`input`);if(l.type=`checkbox`,l.checked=a,l.addEventListener(`change`,()=>s(l.checked)),n.appendChild(VR(`enabled`,l)),a){n.appendChild(sR(`murk color`,String(o.color??``),e=>c(`color`,e))),n.appendChild(WR(`visibility (m)`,Number(o.visibility??22),e=>c(`visibility`,e===22?void 0:e),()=>c(`visibility`,void 0)));let e=document.createElement(`input`);e.type=`checkbox`,e.checked=(o.caustics??!0)!==!1,e.addEventListener(`change`,()=>c(`caustics`,e.checked?void 0:!1)),n.appendChild(VR(`caustics`,e))}return n}function lR(e,t,n){let r=document.createElement(`div`);r.className=`subcard`;let i=document.createElement(`div`);i.className=`subcard-head`,i.textContent=`material`,r.appendChild(i);let a=t.props?.material??{},o=(n,r)=>{let i={...t.props?.material??{}};r===void 0||r===``?delete i[n]:i[n]=r;let a=Object.keys(i).length===0?void 0:i;e.mutate(()=>{t.props||={},a===void 0?(delete t.props.material,Object.keys(t.props).length===0&&delete t.props):t.props.material=a},e.selection?{path:e.selection,key:`material`,value:a}:void 0)};r.appendChild(sR(`color`,String(a.color??``),e=>o(`color`,e))),r.appendChild(pR(`roughness`,Number(a.roughness??1),e=>o(`roughness`,e))),r.appendChild(pR(`metalness`,Number(a.metalness??0),e=>o(`metalness`,e))),r.appendChild(sR(`emissive`,String(a.emissive??``),e=>o(`emissive`,e))),r.appendChild(pR(`emissive power`,Number(a.emissiveIntensity??1),e=>o(`emissiveIntensity`,e===1?void 0:e),2)),r.appendChild(pR(`opacity`,Number(a.opacity??1),e=>o(`opacity`,e===1?void 0:e))),r.appendChild(pR(`clearcoat`,Number(a.clearcoat??0),e=>o(`clearcoat`,e===0?void 0:e))),r.appendChild(pR(`clearcoat rough`,Number(a.clearcoatRoughness??0),e=>o(`clearcoatRoughness`,e===0?void 0:e))),r.appendChild(pR(`reflection`,Number(a.envMapIntensity??1),e=>o(`envMapIntensity`,e===1?void 0:e),3));let s=document.createElement(`input`);s.type=`checkbox`,s.checked=a.wireframe===!0,s.addEventListener(`change`,()=>o(`wireframe`,s.checked||void 0)),r.appendChild(VR(`wireframe`,s));let c=document.createElement(`input`);c.type=`checkbox`,c.checked=a.flatShading===!0,c.addEventListener(`change`,()=>o(`flatShading`,c.checked||void 0)),r.appendChild(VR(`flatShading`,c));let l=document.createElement(`input`);l.type=`checkbox`,l.checked=a.depthTest===!1,l.addEventListener(`change`,()=>{o(`depthTest`,l.checked?!1:void 0),o(`depthWrite`,l.checked?!1:void 0)}),r.appendChild(VR(`draw on top (decal)`,l)),r.appendChild(wR(`map (texture)`,String(a.map??``),TR(e=>nR(e)&&!e.name.includes(`normal`)&&!e.name.includes(`roughness`)),e=>o(`map`,e.trim()),{placeholder:`built-in or custom URL`,library:{kind:`image`,target:`map`,shelf:[`3d`,`textures`]},ctx:n})),r.appendChild(wR(`normal map`,String(a.normalMap??``),TR(e=>nR(e)&&e.name.includes(`normal`)),e=>o(`normalMap`,e.trim()),{placeholder:`built-in or custom URL`,library:{kind:`image`,target:`normal map`,shelf:[`3d`,`textures`]},ctx:n}));let u=!!(a.map||a.normalMap),d=Array.isArray(a.repeat)?a.repeat:[1,1],f=GR(`repeat [u,v]`,[d[0]??1,d[1]??1],e=>{let[t,n]=e;!Number.isFinite(t)||!Number.isFinite(n)||t===1&&n===1||!t&&!n?o(`repeat`,void 0):o(`repeat`,[t,n])});return f.title=u?`Texture tiling across the mesh UVs.`:`Only takes effect with a map/normal map set (engine validates).`,r.appendChild(f),r}var uR=new Set([`animationLoop`,`animationSpeed`,`animationOffset`,`animationUpper`,`animationUpperLoop`,`upperBodyRoot`]);function dR(e,t,n,r){let i=document.createElement(`div`);i.className=`subcard anim-card`;let a=document.createElement(`div`);a.className=`subcard-head`;let o=document.createElement(`strong`);o.textContent=`animation`,a.appendChild(o),i.appendChild(a);let s=String(t.props?.animation??``);if(i.appendChild(wR(`clip`,s,n.animationsForSelection().map(e=>({label:e,value:e,hint:e.startsWith(`$`)?`scene asset`:`clip in this model`})),n=>bR(e,t,`animation`,n.trim(),``),{placeholder:`clip name or $assetKey — empty = still`,library:{kind:`model`,target:`animation`,shelf:[`3d`,`animations`],asAsset:!0,assetType:`animation`},ctx:n})),!s){let a=document.createElement(`div`);return a.className=`muted-note`,a.textContent=`Pick a clip and it plays as soon as the scene loads — no script needed.`,i.appendChild(a),i.appendChild(fR(e,t,n,r)),i}i.appendChild(FR(e,t,`animationLoop`,r.animationLoop?.default??!0,void 0,`loop`));let c=pR(`speed`,Number(t.props?.animationSpeed??1),n=>bR(e,t,`animationSpeed`,n,1),3,-3);c.title=`1 = as authored · 0 freezes the pose · negative plays backwards (a closing door is an opening one reversed).`,i.appendChild(c);let l=FR(e,t,`animationOffset`,r.animationOffset?.default??0,void 0,`offset (s)`);return l.title=`Seconds into the clip to start at. Give copies different offsets so a row of torches stops flickering in lockstep.`,i.appendChild(l),i.appendChild(fR(e,t,n,r)),i}function fR(e,t,n,r){let i=document.createElement(`details`);i.className=`anim-upper`,t.props?.animationUpper&&(i.open=!0);let a=document.createElement(`summary`);return a.textContent=`upper-body layer`,a.title=`Play a second clip on the upper body only — attack while running, wave while walking.`,i.appendChild(a),i.appendChild(wR(`clip`,String(t.props?.animationUpper??``),n.animationsForSelection().map(e=>({label:e,value:e})),n=>bR(e,t,`animationUpper`,n.trim(),``),{placeholder:`empty = off`,ctx:n})),i.appendChild(FR(e,t,`animationUpperLoop`,r.animationUpperLoop?.default??!1,void 0,`loop`)),i.appendChild(FR(e,t,`upperBodyRoot`,r.upperBodyRoot?.default??`Spine`,void 0,`root bone`)),i}function pR(e,t,n,r=1,i=0){let a=document.createElement(`div`);a.className=`slider-row`;let o=document.createElement(`input`);o.type=`range`,o.min=String(i),o.max=String(r),o.step=`0.05`,o.value=String(Number.isFinite(t)?t:0);let s=document.createElement(`input`);return s.type=`number`,s.step=`0.05`,s.min=String(i),s.max=String(r),s.value=o.value,o.addEventListener(`input`,()=>{s.value=o.value}),o.addEventListener(`change`,()=>n(Number(o.value))),s.addEventListener(`change`,()=>{o.value=s.value,n(Number(s.value))}),a.append(o,s),VR(e,a)}function mR(e,t,n,r){if(e.appendChild(zR(n.type??`instance`)),e.appendChild(hR(n)),e.appendChild(UR(`name`,n.name??``,e=>{e.trim()===``||t.selection===null||t.renameNode(t.selection,e.trim())})),n.type===`TileMap2D`&&r?.paint&&e.appendChild(KR(n,r.paint)),n.type){let i;try{i=qe(n.type)}catch{i={}}for(let[a,o]of Object.entries(i))if(a===`collider`)e.appendChild(yR(t,n,o.default));else if(a===`material`)e.appendChild(lR(t,n,r));else if(n.type===`ModelInstance3D`&&a===`model`&&r)e.appendChild(wR(`model`,String(n.props?.model??``),r.modelRefs().map(e=>({label:e,value:e,hint:`scene asset`})),e=>bR(t,n,`model`,e.trim(),``),{placeholder:`$assetKey`,library:{kind:`model`,target:`model`,shelf:[`3d`,`characters`],asAsset:!0},ctx:r}));else if(n.type===`BoneAttachment3D`&&a===`bone`&&r?.bonesForSelection)e.appendChild(SR(`bone`,String(n.props?.bone??``),r.bonesForSelection(String(n.props?.target??``)),e=>bR(t,n,`bone`,e,``)));else if(n.type===`ModelInstance3D`&&a===`animation`&&r)e.appendChild(dR(t,n,r,i));else if(!(n.type===`ModelInstance3D`&&uR.has(a)))if((n.type===`Sprite3D`||n.type===`AnimatedSprite3D`)&&(a===`texture`||a===`sheet`))e.appendChild(wR(a===`sheet`?`sheet (image URL)`:`texture (image URL)`,String(n.props?.[a]??``),TR(e=>e.kind===`character`||e.kind===`item`),e=>bR(t,n,a,e.trim(),``),{placeholder:`image URL — empty hides the sprite`,library:{kind:`image`,target:a,shelf:[`2d`,`sprite_characters`]},ctx:r}));else if(n.type===`TileMap2D`&&a===`texture`)e.appendChild(wR(`texture (atlas $ref)`,String(n.props?.texture??``),(r?.assetRefs?.([`texture`,`spritesheet`])??[]).map(e=>({label:e,value:e,hint:`scene asset`})),e=>bR(t,n,`texture`,e.trim(),``),{placeholder:`$assetKey`,library:{kind:`image`,target:`tile atlas`,shelf:[`2d`,`sprite_characters`],asAsset:!0,assetType:`texture`},ctx:r}));else if(n.type===`Tree3D`&&a===`leafTexture`)e.appendChild(wR(`leaf texture`,String(n.props?.leafTexture??``),TR(e=>e.name.startsWith(`leaves_`)),e=>bR(t,n,`leafTexture`,e.trim(),``),{placeholder:`default (per-type) or URL`,library:{kind:`image`,target:`leaf texture`,shelf:[`3d`,`textures`]},ctx:r}));else if(n.type===`Terrain3D`&&a===`textureBase`)e.appendChild(wR(`texture base`,String(n.props?.textureBase??o.default??``),DR,e=>bR(t,n,`textureBase`,e.trim(),o.default),{placeholder:`splat texture base URL`}));else if(n.type===`AnimatedSprite2D`&&a===`sheet`||n.type===`Sprite2D`&&a===`texture`){let i=a===`sheet`;e.appendChild(OR(t,n,a,r,i))}else n.type===`AudioPlayer`&&a===`src`?e.appendChild(wR(`src (audio file)`,String(n.props?.src??``),ER(),e=>bR(t,n,`src`,e.trim(),``),{placeholder:`built-in or custom URL — or use preset`,note:"For zero-asset SFX, set the `preset` prop instead of src.",library:{kind:`audio`,target:`audio src`},ctx:r})):n.type===`Flowers3D`&&a===`varieties`?e.appendChild(kR(t,n)):n.type===`Water3D`&&a===`underwater`?e.appendChild(cR(t,n)):e.appendChild(FR(t,n,a,o.default,o.options))}if(e.appendChild(zR(`structure`)),e.appendChild(gR(t,n)),e.appendChild(_R(t,n)),e.appendChild(vR(t,n)),t.selection){let n=qL(t,t.selection);n&&(e.appendChild(zR(`connections`,`connections`)),e.appendChild(n))}}function hR(e){let t=document.createElement(`div`);t.className=`field uid-line`;let n=document.createElement(`span`);n.textContent=`uid`;let r=document.createElement(`div`);r.className=`uid-value`;let i=document.createElement(`code`);i.textContent=String(e.uid??``);let a=document.createElement(`button`);return a.type=`button`,a.className=`uid-copy`,a.title=`Copy uid`,a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,a.addEventListener(`click`,()=>{navigator.clipboard?.writeText(String(e.uid??``)),a.classList.add(`copied`),a.innerHTML=`✓`,setTimeout(()=>{a.classList.remove(`copied`),a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`},800)}),r.append(i,a),t.append(n,r),t}function gR(e,t){let n=document.createElement(`label`);n.className=`field wide`;let r=document.createElement(`span`);r.append(`groups `,NL(`groups`));let i=document.createElement(`div`);i.className=`chips`;for(let n of t.groups??[])i.appendChild(BR(n,()=>{e.mutate(()=>{t.groups=(t.groups??[]).filter(e=>e!==n),t.groups.length===0&&delete t.groups})}));let a=document.createElement(`input`);return a.placeholder=(t.groups?.length??0)===0?`add a tag… (e.g. coins)`:``,a.addEventListener(`keydown`,n=>{if(n.key!==`Enter`)return;let r=a.value.trim();r&&e.mutate(()=>{t.groups=[...t.groups??[],r]})}),i.appendChild(a),i.addEventListener(`click`,()=>a.focus()),n.append(r,i),n}function _R(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`script `,NL(`script`));let i=document.createElement(`span`);i.className=`spacer`,r.appendChild(i);let a=t.script;if(a){let n=document.createElement(`button`);n.type=`button`,n.className=`linklike`,n.textContent=`detach`,n.addEventListener(`click`,()=>{e.mutate(()=>{delete t.script})}),r.appendChild(n)}if(n.appendChild(r),!a){let r=document.createElement(`div`);r.className=`muted-note`,r.textContent=`No behavior attached. Behaviors are TypeScript classes in your game.`;let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=`+ attach behavior`,i.addEventListener(`click`,()=>{e.mutate(()=>{t.script={name:`MyBehavior`}})}),n.append(r,i),n}n.appendChild(UR(`name`,a.name??``,n=>{e.mutate(()=>{t.script.name=n.trim()})})),n.appendChild(qR(`props`,a.props,n=>{e.mutate(()=>{n===void 0?delete t.script.props:t.script.props=n})}));let o=document.createElement(`div`);return o.className=`muted-note`,o.textContent=`? has copy-paste boilerplate for the game side.`,n.appendChild(o),n}function vR(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`network `,NL(`network`)),n.appendChild(r);let i=t.network,a=document.createElement(`select`);for(let[e,t]of[[``,`not replicated`],[`owner`,`owner — this player broadcasts it`]]){let n=document.createElement(`option`);n.value=e,n.textContent=t,(i?.mode??``)===e&&(n.selected=!0),a.appendChild(n)}if(a.addEventListener(`change`,()=>{e.mutate(()=>{a.value===``?delete t.network:t.network={mode:a.value,sync:i?.sync??[`position`]}})}),n.appendChild(VR(`mode`,a)),i?.mode===`owner`){let r=document.createElement(`div`);r.className=`chips`;for(let n of i.sync??[])r.appendChild(BR(n,()=>{e.mutate(()=>{t.network.sync=(i.sync??[]).filter(e=>e!==n)})}));let a=document.createElement(`input`);a.placeholder=`position · Skin.animation…`,a.addEventListener(`keydown`,n=>{if(n.key!==`Enter`)return;let r=a.value.trim();r&&e.mutate(()=>{t.network.sync=[...i.sync??[],r]})}),r.appendChild(a);let o=document.createElement(`label`);o.className=`field wide`;let s=document.createElement(`span`);s.textContent=`sync keys`,o.append(s,r),n.appendChild(o),n.appendChild(WR(`throttle ms`,i.throttleMs??50,n=>{e.mutate(()=>{t.network.throttleMs=n})}))}return n}function yR(e,t,n){let r=document.createElement(`div`);r.className=`subcard`;let i=document.createElement(`div`);i.className=`subcard-head`,i.append(`collider `,NL(`collider`)),r.appendChild(i);let a=t.props?.collider??{},o=n=>{e.mutate(()=>{t.props||={};let e=t.props;Object.keys(n).length===0?(delete e.collider,Object.keys(e).length===0&&delete t.props):e.collider=n})},s=(t.type??``).endsWith(`3D`),c=s?[[``,`none`],[`box`,`box — crates, floors`],[`sphere`,`sphere — balls, pickups`],[`capsule`,`capsule — characters`]]:[[``,`none`],[`rect`,`rect — boxes, platforms`],[`circle`,`circle — coins, balls`],[`capsule`,`capsule — characters`]],l=document.createElement(`select`);for(let[e,t]of c){let n=document.createElement(`option`);n.value=e,n.textContent=t,(a.shape??``)===e&&(n.selected=!0),l.appendChild(n)}return l.addEventListener(`change`,()=>{l.value===``?o({}):l.value===`rect`?o({shape:`rect`,size:a.size??[32,32]}):l.value===`box`?o({shape:`box`,size:a.size??[1,1,1]}):l.value===`circle`?o({shape:`circle`,radius:a.radius??16}):l.value===`sphere`?o({shape:`sphere`,radius:a.radius??.5}):o(s?{shape:`capsule`,radius:a.radius??.4,height:a.height??1}:{shape:`capsule`,radius:a.radius??12,height:a.height??16})}),r.appendChild(VR(`shape`,l)),a.shape===`rect`||a.shape===`box`?r.appendChild(GR(`size`,a.size??(s?[1,1,1]:[32,32]),e=>o({...a,size:e}))):a.shape===`circle`||a.shape===`sphere`?r.appendChild(WR(`radius`,a.radius??(s?.5:16),e=>o({...a,radius:e}))):a.shape===`capsule`&&(r.appendChild(WR(`radius`,a.radius??12,e=>o({...a,radius:e}))),r.appendChild(WR(`height`,a.height??16,e=>o({...a,height:e})))),a.shape&&r.appendChild(GR(`offset`,a.offset??(s?[0,0,0]:[0,0]),e=>o({...a,offset:e}))),r}function bR(e,t,n,r,i){e.mutate(()=>{t.props||={},JSON.stringify(r)===JSON.stringify(i)?(delete t.props[n],Object.keys(t.props).length===0&&delete t.props):t.props[n]=r})}var xR=0;function SR(e,t,n,r){let i=document.createElement(`input`);i.type=`text`,i.value=t;let a=`suggest-${xR++}`;i.setAttribute(`list`,a);let o=document.createElement(`datalist`);o.id=a;for(let e of n){let t=document.createElement(`option`);t.value=e,o.appendChild(t)}i.addEventListener(`change`,()=>r(i.value.trim()));let s=VR(e,i);return s.appendChild(o),s}var CR=0;function wR(e,t,n,r,i={}){let a=document.createElement(`label`);a.className=`field wide asset-field`;let o=document.createElement(`span`);o.textContent=e,a.appendChild(o);let s=document.createElement(`input`);s.type=`text`,s.value=t,i.placeholder&&(s.placeholder=i.placeholder),s.addEventListener(`change`,()=>r(s.value.trim()));let c=document.createElement(`button`);c.type=`button`,c.className=`asset-toggle`,c.title=`Browse built-in assets`,c.textContent=`▾`;let l=document.createElement(`div`);if(l.className=`asset-control`,l.append(s),i.library&&i.ctx?.openLibrary){let t=document.createElement(`button`);t.type=`button`,t.className=`asset-lib`,t.textContent=`📚`,t.title=`Browse the agent8 library for a ${i.library.kind}`,t.addEventListener(`click`,t=>{t.preventDefault();let n=i.ctx?.openLibrary;n&&n({kind:i.library?.kind??`any`,target:i.library?.target??e,...i.library?.shelf?{shelf:i.library.shelf}:{},...i.library?.asAsset?{asAsset:!0}:{},...i.library?.assetType?{assetType:i.library.assetType}:{},...i.library?.onProps?{onProps:i.library.onProps}:{}}).then(e=>{e!==null&&(s.value=e,r(e))})}),l.append(t)}l.append(c),a.appendChild(l);let u=document.createElement(`div`);u.className=`asset-panel`,u.hidden=!0;let d=document.createElement(`input`);d.type=`text`,d.className=`asset-search`,d.placeholder=`search ${n.length} built-in${n.length===1?``:`s`}…`;let f=document.createElement(`div`);f.className=`asset-options`,u.append(d,f),a.appendChild(u);let p=e=>{f.textContent=``;let t=e.trim().toLowerCase(),i=n.filter(e=>t===``||e.label.toLowerCase().includes(t)||(e.hint?.toLowerCase().includes(t)??!1)||e.value.toLowerCase().includes(t));if(i.length===0){let e=document.createElement(`div`);e.className=`asset-empty`,e.textContent=`no match — type a custom URL above`,f.appendChild(e);return}for(let e of i){let t=document.createElement(`button`);t.type=`button`,t.className=`asset-option`;let n=document.createElement(`strong`);if(n.textContent=e.label,t.appendChild(n),e.hint){let n=document.createElement(`small`);n.textContent=e.hint,t.appendChild(n)}t.addEventListener(`click`,()=>{s.value=e.value,u.hidden=!0,r(e.value)}),f.appendChild(t)}};if(c.addEventListener(`click`,()=>{u.hidden=!u.hidden,u.hidden||(p(d.value),d.focus())}),d.addEventListener(`input`,()=>p(d.value)),d.addEventListener(`keydown`,e=>{e.key===`Escape`&&(u.hidden=!0)}),i.note){let e=document.createElement(`div`);e.className=`muted-note asset-note`,e.textContent=i.note,a.appendChild(e)}return s.id=`asset-input-${CR++}`,a.htmlFor=s.id,a}function TR(e){return tR.filter(e).map(e=>({label:e.name,value:e.url,hint:`${e.kind} · ${e.description.slice(0,70)}`}))}function ER(){return tR.filter(e=>e.kind===`audio`).map(e=>({label:e.name,value:e.url,hint:`audio · ${e.description.slice(0,70)}`}))}var DR=[{label:`agent8 default terrain`,value:`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,hint:`sand/grass/stone/snow splat set (Terrain3D default)`}];function OR(e,t,n,r,i){let a=String(t.props?.[n]??``),o=i?[`spritesheet`]:[`texture`,`spritesheet`],s=(r?.assetRefs?.(o)??[]).map(e=>({label:e,value:e,hint:`scene asset`})),c=tR.filter(e=>i?!!e.animation:e.kind===`character`||e.kind===`item`||e.kind===`tile`);for(let e of c)s.push({label:`built-in: ${e.name}`,value:`$${e.name}`,hint:`${e.kind} · creates a scene asset (${e.animation?`spritesheet`:`texture`})`});return wR(i?`sheet`:`texture`,a,s,i=>{let a=i.startsWith(`$`)&&c.find(e=>`$${e.name}`===i);if(a&&r?.addAsset){let i={type:a.animation?`spritesheet`:`texture`,url:a.url};if(a.animation){let e=a.frameWidth,t=a.frameHeight;e&&(i.frameWidth=e),t&&(i.frameHeight=t)}bR(e,t,n,`$${r.addAsset(a.name,i).replace(/^\$/,``)}`,``);return}bR(e,t,n,i.trim(),``)},{placeholder:`$assetKey`,note:"Picks a $asset ref. Built-ins create the scene asset; packaged sprites need `incanto-assets copy` (or a bundler import) to serve at runtime.",library:{kind:`image`,target:i?`sheet`:`texture`,shelf:[`2d`,`sprite_characters`],asAsset:!0,assetType:i?`spritesheet`:`texture`,onProps:n=>{for(let[r,i]of Object.entries(n))bR(e,t,r,i,void 0)}},ctx:r})}function kR(e,t){let n=document.createElement(`label`);n.className=`field wide`;let r=document.createElement(`span`);r.textContent=`varieties`,n.appendChild(r);let i=new Set(Array.isArray(t.props?.varieties)?t.props.varieties:[]),a=document.createElement(`div`);a.className=`chips varieties`;let o=()=>{let n=kD.filter(e=>i.has(e));bR(e,t,`varieties`,n.length===0||n.length===kD.length?[]:n,[])};for(let e of kD){let t=document.createElement(`label`);t.className=`variety-opt`;let n=document.createElement(`input`);n.type=`checkbox`,n.checked=i.size===0||i.has(e),n.addEventListener(`change`,()=>{if(i.size===0)for(let e of kD)i.add(e);n.checked?i.add(e):i.delete(e),o()});let r=document.createElement(`span`);r.textContent=e,t.append(n,r),a.appendChild(t)}n.appendChild(a);let s=document.createElement(`div`);return s.className=`muted-note`,s.textContent=`All (or none) = the default mix of all three.`,n.appendChild(s),n}var AR=[[`number`,()=>0],[`text`,()=>``],[`boolean`,()=>!1],[`color`,()=>`#ffffff`],[`vec2`,()=>[0,0]],[`vec3`,()=>[0,0,0]]];function jR(e,t){let n=0,r=e=>{if(yn(e)){e[`@const`]===t&&(n+=1);return}if(Array.isArray(e))for(let t of e)r(t);else if(e&&typeof e==`object`)for(let t of Object.values(e))r(t)};for(let[t,n]of Object.entries(e))t!==`constants`&&r(n);return n}function MR(e,t,n){let r=e=>{if(yn(e))return e[`@const`]===t?JSON.parse(JSON.stringify(n??null)):e;if(Array.isArray(e))return e.map(r);if(e&&typeof e==`object`){let t=e;for(let e of Object.keys(t))t[e]=r(t[e]);return t}return e};for(let t of Object.keys(e))t!==`constants`&&(e[t]=r(e[t]))}function NR(e,t,n){let r=t.working.constants??{},i=Object.keys(r),a=(e,n)=>{t.mutate(()=>{let r={...t.working.constants??{}};r[e]=n,t.working.constants=r})},o=(e,n)=>{t.mutate(()=>{n&&MR(t.working,e,r[e]);let i={...t.working.constants??{}};delete i[e],Object.keys(i).length===0?delete t.working.constants:t.working.constants=i})},s=e=>{let r=jR(t.working,e);if(r>0&&n?.confirm){n.confirm(`"${e}" is used by ${r} prop${r===1?``:`s`}. Unlink them (inline its current value) and delete?`,`unlink & delete`,()=>o(e,!0));return}o(e,r>0)};if(i.length===0){let t=document.createElement(`div`);t.className=`hint`,t.textContent=`No constants yet. Add one, then bind props to it with the 🔗 picker.`,e.appendChild(t)}for(let t of i){let n=document.createElement(`div`);n.className=`const-row`,n.appendChild(PR(t,r[t],e=>a(t,e)));let i=document.createElement(`button`);i.type=`button`,i.className=`const-del`,i.textContent=`✕`,i.title=`delete constant "${t}"`,i.addEventListener(`click`,()=>s(t)),n.appendChild(i),e.appendChild(n)}let c=document.createElement(`div`);c.className=`const-add`;let l=document.createElement(`input`);l.type=`text`,l.placeholder=`new constant name`;let u=document.createElement(`select`);for(let[e]of AR){let t=document.createElement(`option`);t.value=e,t.textContent=e,u.appendChild(t)}let d=document.createElement(`button`);d.type=`button`,d.textContent=`+ add`,d.addEventListener(`click`,()=>{let e=l.value.trim();e&&(t.working.constants??{})[e]===void 0&&(a(e,(AR.find(([e])=>e===u.value)?.[1]??(()=>0))()),l.value=``)}),c.append(l,u,d),e.appendChild(c)}function PR(e,t,n){let r=Be(t);if(r===`number`)return WR(e,t,e=>n(e),()=>n(0));if(r===`boolean`){let r=document.createElement(`input`);return r.type=`checkbox`,r.checked=t===!0,r.addEventListener(`change`,()=>n(r.checked)),VR(e,r)}return r===`array`&&Array.isArray(t)&&t.every(e=>typeof e==`number`)?GR(e,t,e=>n(e)):r===`string`?UR(e,String(t),e=>n(e)):qR(e,t,e=>n(e??null),JSON.stringify(t))}function FR(e,t,n,r,i,a){let o=t.props?.[n]??r,s=Be(r),c=s===`number`||s===`boolean`||s===`string`||s===`array`,l=i=>{let a=yn(i);e.mutate(()=>{t.props||={};let e=t.props;JSON.stringify(i)===JSON.stringify(r)?(delete e[n],Object.keys(e).length===0&&delete t.props):e[n]=i},e.selection&&c&&!a?{path:e.selection,key:n,value:i}:void 0)},u=IR(e,s,r);if(yn(o))return LR(n,o[`@const`],u,l,r);let d=e=>u.length>0?RR(e,u,l):e;if(s===`number`)return d(WR(a??n,o,e=>l(e),()=>l(r)));if(s===`boolean`){let e=document.createElement(`input`);return e.type=`checkbox`,e.checked=o===!0,e.addEventListener(`change`,()=>l(e.checked)),d(VR(a??n,e))}return s===`string`?i&&i.length>0?d(HR(a??n,String(o??``),i,e=>l(e))):d(UR(a??n,String(o??``),e=>l(e))):s===`array`&&Array.isArray(r)&&r.length>0&&r.every(e=>typeof e==`number`)?d(GR(n,o??r,e=>l(e))):qR(n,o===r?void 0:o,e=>{l(e===void 0?r:e)},JSON.stringify(r))}function IR(e,t,n){let r=e.working.constants??{};return Object.keys(r).filter(e=>{let i=r[e];return Be(i)===t?t===`array`&&Array.isArray(n)&&Array.isArray(i)?i.length===n.length:!0:!1})}function LR(e,t,n,r,i){let a=document.createElement(`select`),o=n.includes(t)?n:[t,...n];for(let e of o){let n=document.createElement(`option`);n.value=e,n.textContent=e,e===t&&(n.selected=!0),a.appendChild(n)}let s=document.createElement(`option`);s.value=``,s.textContent=`↺ custom value`,a.appendChild(s),a.addEventListener(`change`,()=>{r(a.value?{"@const":a.value}:i)});let c=VR(`🔗 ${e}`,a);return c.classList.add(`const-bound`),c}function RR(e,t,n){let r=document.createElement(`select`);r.className=`const-picker`,r.title=`Bind to a named constant`;let i=document.createElement(`option`);i.value=``,i.textContent=`🔗`,r.appendChild(i);for(let e of t){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}return r.value=``,r.addEventListener(`change`,()=>{r.value&&n({"@const":r.value})}),e.appendChild(r),e}function zR(e,t){let n=document.createElement(`div`);n.className=`section-title`,n.textContent=e,t&&n.appendChild(NL(t));let r=document.createElement(`span`);return r.className=`rule`,n.appendChild(r),n}function BR(e,t){let n=document.createElement(`span`);n.className=`chip`,n.textContent=e;let r=document.createElement(`button`);return r.type=`button`,r.textContent=`✕`,r.addEventListener(`click`,e=>{e.stopPropagation(),t()}),n.appendChild(r),n}function VR(e,t){let n=document.createElement(`label`);n.className=`field`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n}function HR(e,t,n,r){let i=document.createElement(`select`);for(let e of n.includes(t)?n:[t,...n]){let n=document.createElement(`option`);n.value=e,n.textContent=e,e===t&&(n.selected=!0),i.appendChild(n)}return i.addEventListener(`change`,()=>r(i.value)),VR(e,i)}function UR(e,t,n){let r=document.createElement(`input`);return r.type=`text`,r.value=t,r.addEventListener(`change`,()=>n(r.value)),VR(e,r)}function WR(e,t,n,r){let i=document.createElement(`input`);return i.type=`number`,i.step=`any`,i.value=String(t),i.addEventListener(`change`,()=>{if(i.value.trim()===``){r?.();return}let e=Number(i.value);Number.isFinite(e)&&n(e)}),VR(e,i)}function GR(e,t,n){let r=document.createElement(`div`);r.className=`vector-row`;let i=[...t];return i.forEach((e,t)=>{let a=document.createElement(`input`);a.type=`number`,a.step=`any`,a.value=String(e??0),a.addEventListener(`change`,()=>{let e=Number(a.value);Number.isFinite(e)&&(i[t]=e,n([...i]))}),r.appendChild(a)}),VR(e,r)}function KR(e,t){let n=document.createElement(`div`);n.className=`field wide tile-paint`;let r=document.createElement(`button`);r.type=`button`,r.className=t.active()?`paint-toggle on`:`paint-toggle`,r.textContent=t.active()?`🖌 painting — click the canvas`:`🖌 paint tiles`,r.addEventListener(`click`,()=>t.toggle()),n.appendChild(r);let i=document.createElement(`div`);i.className=`paint-palette`;let a=e.props?.cells??[],o=e.props?.legend??{};for(let e of eR(a,o)){let n=document.createElement(`button`);n.type=`button`,n.className=t.brush()===e?`paint-chip on`:`paint-chip`,n.textContent=e===`.`?`␡`:e,n.title=e===`.`?`eraser (empty cell)`:`tile '${e}'`,n.addEventListener(`click`,()=>t.setBrush(e)),i.appendChild(n)}let s=document.createElement(`input`);s.type=`text`,s.maxLength=1,s.className=`paint-brush-input`,s.value=t.brush(),s.title=`brush char (digit or a legend char)`,s.addEventListener(`change`,()=>{s.value.length===1&&t.setBrush(s.value)}),i.appendChild(s),n.appendChild(i);let c=document.createElement(`div`);return c.className=`paint-hint`,c.textContent=`grid grows right/down; digits map to atlas tiles, others need legend`,n.appendChild(c),n}function qR(e,t,n,r=``){let i=document.createElement(`textarea`);i.rows=3,i.placeholder=r,i.value=t===void 0?``:JSON.stringify(t,null,2),i.addEventListener(`change`,()=>{let e=i.value.trim();if(e===``){i.classList.remove(`invalid`),n(void 0);return}try{let t=JSON.parse(e);i.classList.remove(`invalid`),n(t)}catch{i.classList.add(`invalid`)}});let a=VR(e,i);return a.className=`field wide`,a}var JR=2.4,YR=1.35,XR=[0,.5,0];function ZR(e){return{format:1,type:`scene`,dimension:`3d`,name:`Preview`,environment:{sky:{type:`atmosphere`,elevationDeg:35,azimuthDeg:140,turbidity:3},ambient:{intensity:.55},exposure:1.05},assets:{model:{type:`model`,url:e}},root:{name:`Preview`,type:`Node3D`,children:[{name:`Cam`,type:`Camera3D`,props:{current:!0,position:[0,YR,JR]}},{name:`Sun`,type:`DirectionalLight3D`,props:{position:[3,6,4],intensity:2.2}},{name:`Model`,type:`ModelInstance3D`,props:{model:`$model`,targetHeight:1}}]}}}var QR=class{canvas=null;engine=null;renderer=null;raf=0;angle=.9;dragging=!1;lastX=0;url=``;mount(e){let t=document.createElement(`div`);t.className=`lib-preview3d`;let n=this.ensure();return t.appendChild(n),e!==this.url&&(this.url=e,this.load(e)),this.start(),t}detach(){this.stop(),this.canvas?.remove()}dispose(){this.stop(),this.renderer?.dispose(),this.engine?.dispose(),this.renderer=null,this.engine=null,this.canvas?.remove(),this.canvas=null,this.url=``}ensure(){if(this.canvas)return this.canvas;let e=document.createElement(`canvas`);e.className=`lib-preview-canvas`,this.canvas=e,this.engine=new Et({scheduler:()=>()=>{}}),this.renderer=new gP({canvas:e,engine:this.engine}),e.addEventListener(`pointerdown`,t=>{this.dragging=!0,this.lastX=t.clientX,e.setPointerCapture(t.pointerId)}),e.addEventListener(`pointermove`,e=>{this.dragging&&(this.angle-=(e.clientX-this.lastX)*.01,this.lastX=e.clientX)});let t=()=>{this.dragging=!1};return e.addEventListener(`pointerup`,t),e.addEventListener(`pointercancel`,t),e}load(e){if(this.engine)try{this.engine.setScene(kn(ZR(e)))}catch(t){console.warn(`[incanto] library preview could not load`,e,t)}}start(){if(this.raf)return;let e=0,t=n=>{this.raf=requestAnimationFrame(t);let r=e?Math.min(.05,(n-e)/1e3):0;e=n,this.dragging||(this.angle+=r*.5);let i=this.renderer;i&&(i.viewOverride={position:[Math.sin(this.angle)*JR,YR,Math.cos(this.angle)*JR],target:XR},this.engine?.tick(n))};this.raf=requestAnimationFrame(t)}stop(){this.raf&&cancelAnimationFrame(this.raf),this.raf=0}},$R=`incanto-editor-v8-token`,ez=24;async function tz(e,t,n){if(!C(e.url)||n!==`spritesheet`&&n!==`texture`)return null;try{let n=ry(await(await fetch(e.url)).json(),{url:w(e.url),assetKey:t});return{asset:n.asset,props:Object.fromEntries(Object.entries(n.props).filter(([e])=>e!==`sheet`))}}catch(t){return console.warn(`[incanto] not a usable sprite config:`,e.url,t),null}}function nz(){try{return localStorage.getItem($R)??``}catch{return``}}function rz(e){try{e?localStorage.setItem($R,e):localStorage.removeItem($R)}catch{}}function iz(e,t){return new Promise(n=>{let r=[...t.shelf??[]],i=``,a=1,o=!1,c=[],u=[],d=null,f=!1,b=!1,x=document.createElement(`div`);x.className=`lib-backdrop`;let T=document.createElement(`div`);T.className=`lib-dialog`,x.appendChild(T);let E=document.createElement(`header`);E.className=`lib-head`;let D=document.createElement(`strong`);D.textContent=`agent8 library`;let O=document.createElement(`span`);O.className=`lib-sub`,O.textContent=t.target?`→ ${t.target}`:``;let k=document.createElement(`input`);k.type=`search`,k.className=`lib-search`,k.placeholder=`search descriptions…`;let A=document.createElement(`button`);A.type=`button`,A.className=`ghost`,A.id=`lib-close`,A.textContent=`✕`,A.title=`Close (Esc)`,E.append(D,O,k,A),T.appendChild(E);let ee=document.createElement(`div`);ee.className=`lib-body`,T.appendChild(ee);let te=document.createElement(`nav`);te.className=`lib-shelves`;let ne=document.createElement(`div`);ne.className=`lib-grid-pane`;let re=document.createElement(`div`);re.className=`lib-grid`;let j=document.createElement(`div`);j.className=`lib-status`;let ie=document.createElement(`button`);ie.type=`button`,ie.className=`ghost lib-more`,ie.textContent=`load more`,ie.hidden=!0,ne.append(j,re,ie);let ae=document.createElement(`aside`);ae.className=`lib-detail`,ee.append(te,ne,ae);let M=new QR,oe=e=>{b||(b=!0,M.dispose(),document.removeEventListener(`keydown`,se,!0),x.remove(),n(e))},se=e=>{e.key===`Escape`&&(e.stopPropagation(),oe(null))};document.addEventListener(`keydown`,se,!0),x.addEventListener(`pointerdown`,e=>{e.target===x&&oe(null)}),A.addEventListener(`click`,()=>oe(null));let ce=e=>{r=e,a=1,u=[],pe(!1)},le=()=>{te.textContent=``;let e=[[`Everything`,[]]];for(let t=0;t<r.length;t++)e.push([r[t],r.slice(0,t+1)]);for(let[t,n]of e){let e=document.createElement(`button`);e.type=`button`,e.className=`lib-shelf crumb`,e.style.paddingLeft=`${10+(n.length?n.length-1:0)*12}px`,e.textContent=t,e.classList.toggle(`active`,n.length===r.length),e.addEventListener(`click`,()=>{n.length!==r.length&&ce(n)}),te.appendChild(e)}let t=s(u,r);if(t.length>0){let e=document.createElement(`div`);e.className=`lib-shelf-head`,e.textContent=`in here`,te.appendChild(e)}for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`lib-shelf`,t.style.paddingLeft=`${16+r.length*12}px`;let n=document.createElement(`span`);n.textContent=e.tag;let i=document.createElement(`small`);i.className=`lib-shelf-count`,i.textContent=String(e.count),t.append(n,i),t.addEventListener(`click`,()=>ce([...r,e.tag])),te.appendChild(t)}},ue=()=>{if(ae.textContent=``,M.detach(),!d){let e=document.createElement(`div`);e.className=`lib-empty`,e.textContent=`pick an asset to preview it`,ae.appendChild(e);return}let e=d,n=document.createElement(`div`);n.className=`lib-stage`;let r=m(e.url);if(r===`image`||C(e.url)){let t=document.createElement(`img`);t.src=C(e.url)?w(e.url):e.url,t.alt=g(e),t.loading=`lazy`,n.appendChild(t)}else if(r===`audio`){let t=document.createElement(`audio`);t.controls=!0,t.src=e.url,n.appendChild(t)}else if(r===`model`)n.appendChild(M.mount(e.url));else{let t=document.createElement(`div`);t.className=`lib-empty`,t.textContent=`no preview for ${p(e.url)||`this file`}`,n.appendChild(t)}if(ae.appendChild(n),C(e.url)){let e=document.createElement(`p`);e.className=`lib-desc lib-note`,e.textContent=`Sprite config — picking it declares the sheet AND wires its named animations onto the node.`,ae.appendChild(e)}let i=document.createElement(`h3`);if(i.className=`lib-name`,i.textContent=g(e),ae.appendChild(i),e.description){let t=document.createElement(`p`);t.className=`lib-desc`,t.textContent=e.description,ae.appendChild(t)}let a=v(e);if(a.length){let e=document.createElement(`div`);e.className=`lib-tags`;for(let t of a){let n=document.createElement(`span`);n.className=`lib-tag`,n.textContent=t,e.appendChild(n)}ae.appendChild(e)}let o=y(e);if(o.length){let e=document.createElement(`dl`);e.className=`lib-facts`;for(let[t,n]of o){let r=document.createElement(`dt`);r.textContent=t;let i=document.createElement(`dd`);i.textContent=n,e.append(r,i)}ae.appendChild(e)}let s=document.createElement(`div`);s.className=`lib-url`;let c=document.createElement(`code`);c.textContent=e.url;let l=document.createElement(`button`);l.type=`button`,l.className=`ghost`,l.textContent=`copy`,l.addEventListener(`click`,()=>{navigator.clipboard?.writeText(e.url),l.textContent=`copied`,setTimeout(()=>{l.textContent=`copy`},1200)}),s.append(c,l),ae.appendChild(s);let u=document.createElement(`div`);u.className=`lib-actions`;let f=document.createElement(`button`);f.type=`button`,f.className=`primary`,f.id=`lib-use`,f.textContent=t.onAsset?`use as scene asset`:`use this`,f.addEventListener(`click`,()=>{if(!t.onAsset){oe(e.url);return}(async()=>{let n=_(e),r=await tz(e,n,t.assetType),i=r?.asset??S(e,t.kind,t.assetType),a=t.onAsset?.(e,i,n)??e.url;r&&t.onProps?.(r.props),oe(a)})()}),u.appendChild(f),ae.appendChild(u)},de=()=>{re.textContent=``;let e=c.filter(e=>h(e.url,t.kind));if(e.length===0&&!f){let e=document.createElement(`div`);e.className=`lib-empty`,e.textContent=c.length===0?`nothing on this shelf`:`this shelf has ${c.length} asset${c.length===1?``:`s`}, none of them a ${t.kind}`,re.appendChild(e)}for(let t of e){let e=document.createElement(`button`);e.type=`button`,e.className=`lib-card`,e.classList.toggle(`active`,t===d);let n=document.createElement(`div`);n.className=`lib-thumb`;let r=m(t.url);if(r===`image`){let e=document.createElement(`img`);e.src=t.url,e.alt=``,e.loading=`lazy`,n.appendChild(e)}else{let e=ZP(r===`audio`?`AudioPlayer`:`ModelInstance3D`);e.classList.add(`lib-glyph`),n.appendChild(e)}if(C(t.url)){let e=document.createElement(`em`);e.className=`lib-badge`,e.textContent=`animated`,e.title=`A sprite config: frame grid + named animations. Picking it wires them up.`,n.appendChild(e)}let i=document.createElement(`span`);i.className=`lib-card-name`,i.textContent=g(t),e.append(n,i),e.title=t.description||t.url,e.addEventListener(`click`,()=>{d=t,de(),ue()}),re.appendChild(e)}ie.hidden=!o||f},fe=e=>{re.textContent=``,ie.hidden=!0;let t=document.createElement(`div`);t.className=`lib-token`;let n=document.createElement(`p`);n.className=`lib-token-line`,n.textContent=e;let r=document.createElement(`p`);r.className=`lib-token-line lib-token-how`,r.textContent=`The catalog is per-account. Paste a Verse8 access token to browse it here — it is kept in this browser and sent only to your own editor server. Starting the editor with --token (or INCANTO_V8_TOKEN) skips this.`;let i=document.createElement(`input`);i.type=`password`,i.className=`mono`,i.placeholder=`v8 access token`,i.value=nz();let o=document.createElement(`button`);o.type=`button`,o.className=`primary`,o.textContent=`connect`,o.addEventListener(`click`,()=>{rz(i.value.trim()),a=1,pe(!1)}),i.addEventListener(`keydown`,e=>{e.key===`Enter`&&o.click()});let s=document.createElement(`div`);s.className=`lib-token-row`,s.append(i,o),t.append(n,r,s),re.appendChild(t)},pe=async t=>{if(!(!e.library||f)){f=!0,j.textContent=t?`loading more…`:`loading ${l(r)}…`,t||(c=[],d=null,de(),ue()),le();try{let n=await e.library({tags:r,keyword:i.trim()||void 0,page:a,limit:ez},nz()||void 0);if(b)return;c=t?[...c,...n.items]:n.items,u=c,o=n.hasNext;let s=n.total===void 0?``:` of ${n.total}`;j.textContent=`${l(r)} · ${c.length}${s} loaded`,le(),de()}catch(e){if(b)return;let t=e.needsToken===!0;if(j.textContent=l(r),t)fe(e instanceof Error?e.message:String(e));else{re.textContent=``;let t=document.createElement(`div`);t.className=`lib-error`,t.textContent=e instanceof Error?e.message:String(e),re.appendChild(t)}}finally{f=!1,ie.hidden=!o}}};ie.addEventListener(`click`,()=>{a+=1,pe(!0)});let me=0;k.addEventListener(`input`,()=>{i=k.value,clearTimeout(me),me=window.setTimeout(()=>{a=1,pe(!1)},350)}),le(),ue(),document.body.appendChild(x),k.focus(),pe(!1)})}var az=`.scene.json`;function oz(e){let t=e.split(`/`).pop()??e;return t.endsWith(az)?t.slice(0,-11):t}function sz(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function cz(e,t){return{path:e,name:t,dirs:new Map,files:[]}}function lz(e){let t=cz(``,``);for(let n of e){let e=n.rel.split(`/`);if(!e.pop())continue;let r=t;for(let t of e){let e=r.path?`${r.path}/${t}`:t,n=r.dirs.get(t);n||(n=cz(e,t),r.dirs.set(t,n)),r=n}r.files.push(n)}return t}function uz(e){let t=e.files.length;for(let n of e.dirs.values())t+=uz(n);return t}function dz(e){let t=e.files.filter(e=>e.scene).length;for(let n of e.dirs.values())t+=dz(n);return t}function fz(e){let t=e,n=e.name;for(;t.files.length===0&&t.dirs.size===1;){let e=[...t.dirs.values()][0];if(!e)break;t=e,n=`${n} / ${e.name}`}return{dir:t,label:n}}function pz(e){let t=sz(e??``).split(`/`).filter(Boolean),n=[],r=``;for(let e of t)r=r?`${r}/${e}`:e,n.push(r);return n}function mz(e,t={}){let n=(t.query??``).trim().toLowerCase(),r=n?e.filter(e=>e.rel.toLowerCase().includes(n)):e,i=t.expanded??new Set,a=[],o=(e,r)=>{let s=[...e.dirs.values()].sort((e,t)=>e.name.localeCompare(t.name));for(let e of s){let{dir:t,label:s}=fz(e),c=uz(t);if(c===0)continue;let l=n!==``||i.has(t.path);a.push({kind:`folder`,path:t.path,label:s,depth:r,count:c,scenes:dz(t),open:l}),l&&o(t,r+1)}let c=[...e.files].sort((e,t)=>oz(e.rel).localeCompare(oz(t.rel)));for(let e of c)a.push({kind:`scene`,entry:e,label:oz(e.rel),folder:sz(e.rel),depth:r,current:e.rel===t.current})};return o(lz(r),0),a}function hz(e,t){let n=new Set(pz(t));if(e.length<=24)for(let t of e)for(let e of pz(t.rel))n.add(e);return n}function gz(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?``:e<1e3?`${e} B`:e<1e3*1e3?`${(e/1e3).toFixed(1)} kB`:`${(e/1e3/1e3).toFixed(1)} MB`}function _z(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return``;let n=Math.round((t-e)/1e3);if(n<90)return`just now`;let r=Math.round(n/60);if(r<60)return`${r}m ago`;let i=Math.round(r/60);return i<24?`${i}h ago`:i<48?`yesterday`:new Date(e).toISOString().slice(0,10)}function vz(e,t=`new-level`){let n=e?e.kind===`folder`?e.path:e.folder:``;return n?`${n}/${t}${az}`:`${t}${az}`}function yz(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}function bz(e,t,n=()=>Date.now()){let r=[],i=new Set,a=[],o=0,s=!0,c=()=>{let c=t.current();if(a=mz(r,{expanded:i,query:e.search.value,current:c}),o>=a.length&&(o=a.length-1),o<0&&(o=0),s){let e=a.findIndex(e=>e.kind===`scene`&&e.current);e>=0&&(o=e),s=!1}if(e.list.textContent=``,a.length===0){let t=document.createElement(`div`);t.className=`scene-empty`,t.textContent=r.length?`no scene matches “${e.search.value.trim()}”`:`no .json files in this project yet — create a scene below`,e.list.appendChild(t)}let u=n();a.forEach((n,r)=>{let i=document.createElement(`div`);i.className=n.kind===`folder`?`scene-row scene-folder`:`scene-row`,i.style.paddingLeft=`${6+n.depth*14}px`,r===o&&i.classList.add(`active`);let a=yz(`scene-caret`,``);n.kind===`folder`?(a.classList.add(`chevron`),n.open||a.classList.add(`collapsed`),a.appendChild(QP())):a.textContent=`◇`,i.append(a,yz(`scene-name`,n.label),yz(`scene-meta`,n.kind===`folder`?n.scenes>0?`${n.scenes} scene${n.scenes===1?``:`s`}`:`${n.count} file${n.count===1?``:`s`}`:[n.entry.scene?[n.entry.scene.dimension,`${n.entry.scene.nodes} node${n.entry.scene.nodes===1?``:`s`}`].filter(Boolean).join(` · `):`not a scene`,_z(n.entry.modified,u),gz(n.entry.size)].filter(Boolean).join(` · `))),n.kind===`scene`&&(n.current&&i.classList.add(`current`),n.entry.notScene?(i.classList.add(`not-scene`),i.title=`${n.entry.rel}\n\nnot a scene: ${n.entry.notScene}`):i.title=n.entry.rel),i.addEventListener(`click`,()=>{o=r,n.kind===`folder`?l(n.path):t.open(n.entry)}),e.list.appendChild(i)});let d=r.length,f=a.filter(e=>e.kind===`scene`).length;e.count.textContent=d===0?``:f===d?`${d}`:`${f} / ${d}`,e.path.placeholder=vz(a[o]),e.list.querySelector(`.active`)?.scrollIntoView({block:`nearest`})},l=e=>{i.has(e)?i.delete(e):i.add(e),c()},u=e=>{a.length!==0&&(o=Math.min(a.length-1,Math.max(0,o+e)),c())};return e.search.addEventListener(`input`,()=>{o=0,c()}),e.search.addEventListener(`keydown`,e=>{let n=a[o];switch(e.key){case`ArrowDown`:e.preventDefault(),u(1);return;case`ArrowUp`:e.preventDefault(),u(-1);return;case`ArrowRight`:n?.kind===`folder`&&!n.open&&(e.preventDefault(),l(n.path));return;case`ArrowLeft`:n?.kind===`folder`&&n.open&&(e.preventDefault(),l(n.path));return;case`Enter`:e.preventDefault(),n?.kind===`folder`?l(n.path):n&&t.open(n.entry);return;default:}}),{async refresh(){try{r=await t.entries()}catch(t){r=[],e.list.textContent=``;let n=document.createElement(`div`);n.className=`scene-empty`,n.textContent=`could not list scenes: ${t instanceof Error?t.message:String(t)}`,e.list.appendChild(n),e.count.textContent=``;return}if(i.size===0)i=hz(r,t.current());else for(let e of pz(t.current()))i.add(e);s=!0,c(),e.search.focus(),e.search.select()}}}var xz=`
8423
+ `}},network:{title:{en:`network — replicate to other players`,ko:`network — 다른 플레이어에게 복제`},body:{en:`mode "owner" means THIS player owns the node and broadcasts the listed sync keys to everyone in the room (one owner node per player — usually your player character). Other players see it via a NetworkSpawner. Keys are relative to this node: "position", or "Skin.animation" for a child prop.`,ko:`mode "owner"는 이 플레이어가 노드를 소유하고 sync 키 목록을 방의 모두에게 송출한다는 뜻입니다(플레이어당 owner 노드 하나 — 보통 내 캐릭터). 다른 플레이어는 NetworkSpawner로 봅니다. 키는 이 노드 기준 상대 표기입니다: "position", 자식 prop은 "Skin.animation".`},example:`{ "mode": "owner", "sync": ["position"], "throttleMs": 50 }`},collider:{title:{en:`collider — the physics shape`,ko:`collider — 물리 모양`},body:{en:`Shapes: rect (size [w,h]), circle (radius), capsule (radius + height — good for characters). offset shifts the shape from the node position. The green dashed outline in the viewport shows exactly where it is.`,ko:`모양: rect(size [w,h]), circle(radius), capsule(radius+height — 캐릭터에 적합). offset이 노드 위치에서 모양을 이동시킵니다. 뷰포트의 초록 점선이 정확한 위치를 보여줍니다.`},example:`{ "shape": "capsule", "radius": 12, "height": 16 }`},physics:{title:{en:`physics — scene gravity`,ko:`physics — 씬 중력`},body:{en:`World gravity in px/s² (y-down: positive y pulls DOWN). [0, 1400] feels platformer-y; [0, 0] for top-down. Takes effect when the game calls enablePhysics2D — and in the editor’s play mode.`,ko:`월드 중력, px/s² 단위(y-아래: 양수 y가 아래로 당김). [0, 1400]이면 플랫포머 느낌, 탑다운은 [0, 0]. 게임이 enablePhysics2D를 부를 때 — 그리고 에디터 플레이 모드에서 — 적용됩니다.`},example:`"physics": { "gravity": [0, 1400] }`}},ML=null;function NL(e){document.addEventListener(`click`,t=>{let n=t.target,r=n.closest(`[data-help]`);if(!r){e.contains(n)||(e.hidden=!0);return}let i=jL[r.dataset.help??``];if(!i)return;if(!e.hidden&&ML===r){e.hidden=!0;return}ML=r,e.textContent=``;let a=document.createElement(`h4`);a.textContent=YP(i.title);let o=document.createElement(`div`);if(o.textContent=YP(i.body),e.append(a,o),i.example){let t=document.createElement(`pre`);t.textContent=i.example,e.appendChild(t)}if(i.copy){let t=document.createElement(`div`);t.className=`pop-actions`;let n=document.createElement(`button`);n.type=`button`,n.className=`linklike`,n.textContent=`⧉ ${i.copy.label}`,n.addEventListener(`click`,()=>{navigator.clipboard.writeText(i.copy?.text??``),n.textContent=`✓ copied`}),t.appendChild(n),e.appendChild(t)}e.hidden=!1;let s=e.getBoundingClientRect(),{left:c,top:l}=PL(r.getBoundingClientRect(),{width:s.width,height:s.height},{width:innerWidth,height:innerHeight});e.style.left=`${c}px`,e.style.top=`${l}px`})}function PL(e,t,n,r=8){let i=t.width||300,a=e.left-i+20,o=Math.max(r,Math.min(n.width-i-r,a)),s=e.bottom+r,c=e.top-t.height-r,l;return l=s+t.height+r<=n.height?s:c>=r?c:r,{left:o,top:l}}function FL(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`help-btn`,t.dataset.help=e,t.textContent=`?`,t.title=`What is this?`,t}var IL=JSON.parse('[{"name":"2dbasic","file":"characters/2dbasic.png","url":"incanto/assets/characters/2dbasic.png","kind":"character","bytes":30499,"description":"2dbasic sprite sheet image.anything,base character. (frame size 192x192)","animation":"characters/2dbasic.json","frameWidth":111,"frameHeight":83},{"name":"attacked","file":"audio/attacked.mp3","url":"incanto/assets/audio/attacked.mp3","kind":"audio","bytes":8757,"description":"Short hurt / took-damage SFX for the player or an enemy."},{"name":"bark_birch_color","file":"vegetation/bark/birch_color_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/birch_color_1k.jpg","kind":"foliage","bytes":194186,"description":"Birch bark base color texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_birch_normal","file":"vegetation/bark/birch_normal_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/birch_normal_1k.jpg","kind":"foliage","bytes":378046,"description":"Birch bark tangent-space normal texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_birch_roughness","file":"vegetation/bark/birch_roughness_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/birch_roughness_1k.jpg","kind":"foliage","bytes":127387,"description":"Birch bark roughness texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_oak_color","file":"vegetation/bark/oak_color_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/oak_color_1k.jpg","kind":"foliage","bytes":297877,"description":"Oak bark base color texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_oak_normal","file":"vegetation/bark/oak_normal_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/oak_normal_1k.jpg","kind":"foliage","bytes":67610,"description":"Oak bark tangent-space normal texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_oak_roughness","file":"vegetation/bark/oak_roughness_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/oak_roughness_1k.jpg","kind":"foliage","bytes":16648,"description":"Oak bark roughness texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_pine_color","file":"vegetation/bark/pine_color_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/pine_color_1k.jpg","kind":"foliage","bytes":196361,"description":"Pine bark base color texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_pine_normal","file":"vegetation/bark/pine_normal_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/pine_normal_1k.jpg","kind":"foliage","bytes":58237,"description":"Pine bark tangent-space normal texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"bark_pine_roughness","file":"vegetation/bark/pine_roughness_1k.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark/pine_roughness_1k.jpg","kind":"foliage","bytes":36136,"description":"Pine bark roughness texture (1k), ambientcg Bark (CC0) packaged by ez-tree (MIT). Tree3D trunks/branches sample it by default from the agent8 CDN (the only sanctioned external host); the bundled `incanto/assets` copy (see this entry’s `file`) serves it offline."},{"name":"box","file":"items/box.png","url":"incanto/assets/items/box.png","kind":"item","bytes":10861,"description":"Item box sprite for Dungeons and Dungeoners. Container sprite that holds random items or rewards when opened by player."},{"name":"buff_potion","file":"items/buff_potion.png","url":"incanto/assets/items/buff_potion.png","kind":"item","bytes":3809,"description":"Buff potion item sprite for Dungeons and Dungeoners. Consumable item that grants temporary stat boosts or positive effects to player character."},{"name":"coin","file":"items/coin.png","url":"incanto/assets/items/coin.png","kind":"item","bytes":1689,"description":"Gold coin collectible sprite for Dungeons and Dungeoners. Currency item with metallic sheen, used as in-game money or collectible reward."},{"name":"explosion","file":"audio/explosion.mp3","url":"incanto/assets/audio/explosion.mp3","kind":"audio","bytes":40124,"description":"Impactful explosion / large destructive hit SFX. Pair with the Particles2D \\"explosion\\" preset."},{"name":"floor00","file":"tiles/floor00.jpg","url":"incanto/assets/tiles/floor00.jpg","kind":"tile","bytes":28736,"description":"Basic floor tile texture for Dungeons and Dungeoners project, suitable for dungeon ground surfaces."},{"name":"gem","file":"items/gem.png","url":"incanto/assets/items/gem.png","kind":"item","bytes":8762,"description":"Gem collectible sprite for Dungeons and Dungeoners. Valuable gemstone item used as currency, crafting material, or quest objective."},{"name":"ghost","file":"characters/ghost.png","url":"incanto/assets/characters/ghost.png","kind":"character","bytes":22933,"description":"Ghost character with translucent appearance sprite sheet image (frame size 112x128)","animation":"characters/ghost.json","frameWidth":112,"frameHeight":128},{"name":"goblin","file":"characters/goblin.png","url":"incanto/assets/characters/goblin.png","kind":"character","bytes":57994,"description":"Medieval goblin with torch sprite sheet image (frame size 192x192)","animation":"characters/goblin.json","frameWidth":192,"frameHeight":192},{"name":"gold","file":"items/gold.png","url":"incanto/assets/items/gold.png","kind":"item","bytes":22313,"description":"Gold item sprite for Dungeons and Dungeoners. Gold pile or gold bar sprite representing valuable currency or treasure reward."},{"name":"gold-loot","file":"audio/gold_loot.mp3","url":"incanto/assets/audio/gold_loot.mp3","kind":"audio","bytes":7506,"description":"Metallic coin / gold pickup jingle — collecting currency."},{"name":"ground_dirt","file":"vegetation/ground/dirt_color.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground/dirt_color.jpg","kind":"foliage","bytes":231383,"description":"Dense dirt/gravel ground texture (1024px) from the ez-tree demo app (MIT) — the reference meadow ground. Terrain3D grassland themes tile it for slope + noise-patch dirt by default; also bundled in `incanto/assets` (see `file`) for offline use."},{"name":"ground_dirt_normal","file":"vegetation/ground/dirt_normal.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground/dirt_normal.jpg","kind":"foliage","bytes":123478,"description":"Dirt ground normal map (1024px) from the ez-tree demo app (MIT). Terrain3D grassland themes apply it across the whole ground band (demo parity); also bundled in `incanto/assets` (see `file`) for offline use."},{"name":"ground_grass","file":"vegetation/ground/grass.jpg","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground/grass.jpg","kind":"foliage","bytes":322486,"description":"Mossy meadow grass ground texture (1024px) from the ez-tree demo app (MIT). Terrain3D grassland themes (meadow/forest generators) tile it as the grass splat layer by default; also bundled in `incanto/assets` (see `file`) for offline use."},{"name":"heal","file":"audio/heal.mp3","url":"incanto/assets/audio/heal.mp3","kind":"audio","bytes":29764,"description":"Soothing health-restore / heal spell SFX."},{"name":"hit-metal-bang","file":"audio/hit_metal_bang.mp3","url":"incanto/assets/audio/hit_metal_bang.mp3","kind":"audio","bytes":17972,"description":"Metallic impact — hitting armor, metal, or a blocked attack."},{"name":"hp_potion","file":"items/hp_potion.png","url":"incanto/assets/items/hp_potion.png","kind":"item","bytes":3513,"description":"Health potion item sprite for Dungeons and Dungeoners. Consumable healing item that restores player health points when used."},{"name":"ice-spear","file":"audio/ice_spear.mp3","url":"incanto/assets/audio/ice_spear.mp3","kind":"audio","bytes":21315,"description":"Sharp piercing ice projectile fire SFX."},{"name":"leaves_ash","file":"vegetation/ash_color.png","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ash_color.png","kind":"foliage","bytes":181423,"description":"Ash leaf-cluster alpha-cutout texture (1024px) from ez-tree by Dan Greenheck (MIT). Tree3D samples it for broadleaf/dead ash variants by default; copy it next to your game and set leafTexture to serve offline."},{"name":"leaves_aspen","file":"vegetation/aspen_color.png","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/aspen_color.png","kind":"foliage","bytes":142116,"description":"Aspen leaf-cluster alpha-cutout texture (1024px) from ez-tree by Dan Greenheck (MIT). Tree3D samples it for high-tier broadleaf aspen variants; copy + leafTexture for offline serving."},{"name":"leaves_oak","file":"vegetation/oak_color.png","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/oak_color.png","kind":"foliage","bytes":238115,"description":"Oak leaf-cluster alpha-cutout texture (1024px) from ez-tree by Dan Greenheck (MIT). Tree3D samples it for broadleaf oak variants by default; copy + leafTexture for offline serving."},{"name":"leaves_pine","file":"vegetation/pine_color.png","url":"https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/pine_color.png","kind":"foliage","bytes":303684,"description":"Pine needle-cluster alpha-cutout texture (1024px) from ez-tree by Dan Greenheck (MIT). Tree3D samples it for conifer variants by default; copy + leafTexture for offline serving."},{"name":"locked_item_box","file":"items/locked_item_box.png","url":"incanto/assets/items/locked_item_box.png","kind":"item","bytes":11074,"description":"Locked item box sprite for Dungeons and Dungeoners. Container sprite requiring key or lockpick to open, containing valuable rewards."},{"name":"map","file":"items/map.png","url":"incanto/assets/items/map.png","kind":"item","bytes":3754,"description":"Map item sprite for Dungeons and Dungeoners. Navigation item revealing dungeon layout or providing exploration assistance."},{"name":"medieval-knight","file":"characters/medieval-knight.png","url":"incanto/assets/characters/medieval-knight.png","kind":"character","bytes":84367,"description":"(frame size 192x192) Using a medieval-themed SD(Super Deformed) knight sprite sheet image, you can apply idle, move, and attack animations, among others.","animation":"characters/medieval-knight.json","frameWidth":192,"frameHeight":192},{"name":"minecraft-tiles","file":"tiles/minecraft-tiles.png","url":"incanto/assets/tiles/minecraft-tiles.png","kind":"tile","bytes":10511,"description":"Minecraft-themed tiles sprite sheet image (frame size 16x16)"},{"name":"monster-died","file":"audio/monster_died.mp3","url":"incanto/assets/audio/monster_died.mp3","kind":"audio","bytes":16836,"description":"Enemy defeat / death SFX."},{"name":"resurrection_potion","file":"items/resurrection_potion.png","url":"incanto/assets/items/resurrection_potion.png","kind":"item","bytes":3471,"description":"Resurrection potion item sprite for Dungeons and Dungeoners. Rare consumable that revives fallen party members or prevents death."},{"name":"slash","file":"audio/slash.mp3","url":"incanto/assets/audio/slash.mp3","kind":"audio","bytes":10425,"description":"Quick sword swing / melee slash SFX."},{"name":"smite","file":"audio/smite.mp3","url":"incanto/assets/audio/smite.mp3","kind":"audio","bytes":12956,"description":"Powerful holy downward-strike SFX."},{"name":"spells-cast","file":"audio/spells_cast.mp3","url":"incanto/assets/audio/spells_cast.mp3","kind":"audio","bytes":22151,"description":"Generic magical spell-cast / chant SFX."},{"name":"super_box","file":"items/super_box.png","url":"incanto/assets/items/super_box.png","kind":"item","bytes":12184,"description":"Super item box sprite for Dungeons and Dungeoners. Premium container sprite containing rare or powerful items and equipment."},{"name":"swoosh","file":"effects/swoosh.png","url":"incanto/assets/effects/swoosh.png","kind":"effect","bytes":2599,"description":"Swoosh effect sprite for Dungeons and Dungeoners. Motion blur or attack trail effect used for melee attacks, sword slashes, or fast movement animations."},{"name":"trap","file":"items/trap.png","url":"incanto/assets/items/trap.png","kind":"item","bytes":3969,"description":"Trap object sprite for Dungeons and Dungeoners. Hazard sprite that damages players when triggered in dungeon exploration."},{"name":"ui-click","file":"audio/ui_click.wav","url":"incanto/assets/audio/ui_click.wav","kind":"audio","bytes":17332,"description":"Short tactile UI click for menus and buttons."},{"name":"walk","file":"audio/walk.mp3","url":"incanto/assets/audio/walk.mp3","kind":"audio","bytes":5642,"description":"Single footstep SFX for character movement (loop or one-shot)."},{"name":"wall00","file":"tiles/wall00.jpg","url":"incanto/assets/tiles/wall00.jpg","kind":"tile","bytes":44344,"description":"Basic wall tile texture for Dungeons and Dungeoners project, suitable for dungeon vertical boundaries."}]');function LL(e){let t=e.connections;return Array.isArray(t)?t:[]}function RL(e,t){if(!e||t===``)return null;if(t===`.`)return[];if(t.startsWith(`%`)){let n=t.slice(1);if(n===``||n.includes(`/`))return null;let r=[],i=(e,t)=>{e.name===n&&r.push(t),(e.children??[]).forEach((e,n)=>{i(e,[...t,n])})};return i(e,[]),r.length===1?r[0]:null}let n=t.startsWith(`/`),r=(n?t.slice(1):t).split(`/`);if(r.some(e=>e===``))return null;let i=r;if(n){if(r[0]!==e.name&&r[0]!==`root`)return null;i=r.slice(1)}let a=[],o=e;for(let t of i){if(t===`..`){if(a.length===0)return null;a.pop(),o=zL(e,a);continue}let n=(o.children??[]).findIndex(e=>e.name===t);if(n===-1)return null;a.push(n),o=o.children?.[n]}return a}function zL(e,t){let n=e;for(let e of t)n=n?.children?.[e];return n??null}function BL(e,t){if(!e)return``;if(t.length===0)return`.`;let n=[],r=e;for(let e of t){let t=r.children?.[e];if(!t)return``;n.push(String(t.name??``)),r=t}return n.join(`/`)}function VL(e,t){let n=e.root,r=e=>{if(typeof e!=`string`)return!1;let r=RL(n,e);return r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n])},i=[],a=[];return LL(e).forEach((e,t)=>{r(e.from)&&i.push({index:t,conn:e}),r(e.to)&&a.push({index:t,conn:e})}),{outgoing:i,incoming:a}}function HL(e){if(!e)return[];let t=[];if(typeof e.type==`string`&&e.type!==``)try{t.push(...Ye(e.type))}catch{}let n=e.script;return typeof n?.name==`string`&&t.push(...st(n.name)),[...new Set(t)]}function UL(e){if(!e||e.script?.name)return[];let t=typeof e.type==`string`?e.type:``;if(!t)return[];let n=null;try{n=Ge(t)}catch{return[]}let r=new Set;for(let e=n.prototype;e&&e!==Object.prototype;){for(let t of Object.getOwnPropertyNames(e))t===`constructor`||t.startsWith(`_`)||typeof Object.getOwnPropertyDescriptor(e,t)?.value==`function`&&r.add(t);e=Object.getPrototypeOf(e)}for(let e of WL)r.delete(e);return[...r].sort()}var WL=new Set([`addChild`,`removeChild`,`addToGroup`,`removeFromGroup`,`isInGroup`,`getNode`,`getNodeOrNull`,`getPath`,`getRoot`,`find`,`findAll`,`on`,`off`,`once`,`emit`,`declareSignal`,`update`,`fixedUpdate`,`toJSON`,`diagnose`]);function GL(e){if(!e)return[];let t=[{path:`.`,label:`${e.name} (root)`}],n=(r,i)=>{(r.children??[]).forEach((r,a)=>{let o=[...i,a];t.push({path:BL(e,o),label:BL(e,o)}),n(r,o)})};return n(e,[]),t}function KL(e,t){Array.isArray(e.connections)||(e.connections=[]);let n=e.connections;return n.push(t),n.length-1}function qL(e,t,n){let r=LL(e)[t];r&&Object.assign(r,n)}function JL(e,t){let n=LL(e);t<0||t>=n.length||(n.splice(t,1),n.length===0&&delete e.connections)}function YL(e,t){let n=e.working.root;if(!n)return null;let r=e.nodeAt(t);if(!r)return null;let i=document.createElement(`div`);i.className=`connections`;let{outgoing:a,incoming:o}=VL(e.working,t),s=BL(n,t);i.appendChild(XL(YP({en:`emits (${a.length})`,ko:`보냄 (${a.length})`})));for(let t of a)i.appendChild(ZL(e,t,`out`));if(i.appendChild(QL(e,r,s)),o.length>0){i.appendChild(XL(YP({en:`receives (${o.length})`,ko:`받음 (${o.length})`})));for(let t of o)i.appendChild(ZL(e,t,`in`))}return i}function XL(e){let t=document.createElement(`div`);return t.className=`conn-group`,t.textContent=e,t}function ZL(e,{index:t,conn:n},r){let i=e.working.root,a=document.createElement(`div`);a.className=`conn-row`;let o=e.nodeAt(RL(i,String(n.from??``))??[-1]),s=r===`out`?`to`:`from`,c=String(n[s]??``),l=RL(i,c)===null,u=$L(HL(o),String(n.signal??``),n=>{e.mutate(()=>qL(e.working,t,{signal:n}))});u.title=YP({en:`signal`,ko:`시그널`});let d=document.createElement(`span`);d.className=`conn-arrow`,d.textContent=r===`out`?`→`:`←`;let f=$L(GL(i).map(e=>e.path),c,n=>{e.mutate(()=>qL(e.working,t,{[s]:n}))});f.title=YP({en:s,ko:s===`to`?`대상`:`출처`}),l&&f.classList.add(`dangling`);let p=UL(e.nodeAt(RL(i,String(n.to??``))??[-1])),m=n=>{e.mutate(()=>qL(e.working,t,{handler:n.trim()}))},h;if(p.length>0){let e=$L(p,String(n.handler??``),m);e.title=YP({en:`handler method`,ko:`핸들러 메서드`}),h=e}else{let e=document.createElement(`input`);e.type=`text`,e.className=`conn-handler`,e.value=String(n.handler??``),e.placeholder=`onSomething`,e.title=YP({en:`handler method on the target (defined in your behavior)`,ko:`대상의 핸들러 메서드 (비헤이비어에 정의)`}),e.addEventListener(`change`,()=>m(e.value)),h=e}let g=document.createElement(`button`);if(g.type=`button`,g.className=`conn-remove`,g.textContent=`✕`,g.title=YP({en:`remove this connection`,ko:`이 연결 삭제`}),g.addEventListener(`click`,()=>{e.mutate(()=>JL(e.working,t))}),a.append(u,d,f,h,g),l){let e=document.createElement(`div`);e.className=`conn-warn`,e.textContent=YP({en:`'${c}' does not resolve — the game will refuse to load this scene.`,ko:`'${c}' 을(를) 찾을 수 없습니다 — 게임이 이 씬을 열지 못합니다.`});let t=document.createElement(`div`);return t.append(a,e),t}return a}function QL(e,t,n){let r=HL(t),i=document.createElement(`div`);i.className=`conn-add`;let a=document.createElement(`button`);return a.type=`button`,a.textContent=YP({en:`+ connect`,ko:`+ 연결`}),a.disabled=r.length===0,r.length===0&&(a.title=YP({en:`this node declares no signals`,ko:`이 노드는 시그널을 선언하지 않습니다`})),a.addEventListener(`click`,()=>{let i=r[0]??``,a={from:n,signal:i,to:n,handler:UL(t)[0]??`on${i.charAt(0).toUpperCase()}${i.slice(1)}`};e.mutate(()=>{KL(e.working,a)})}),i.appendChild(a),i}function $L(e,t,n){let r=document.createElement(`select`);r.className=`conn-select`;for(let n of e.includes(t)?e:[t,...e]){let e=document.createElement(`option`);e.value=n,e.textContent=n===``?`—`:n,n===t&&(e.selected=!0),r.appendChild(e)}return r.addEventListener(`change`,()=>n(r.value)),r}function eR(e,t,n,r){return{cx:Math.floor((n-e.x)/t),cy:Math.floor((r-e.y)/t)}}function tR(e,t,n,r){if(t<0||n<0||r.length!==1)return null;let i=e.map(e=>typeof e==`string`?e:e.map(e=>e>=0&&e<=9?String(e):`.`).join(``)),a=Math.max(t+1,...i.map(e=>e.length)),o=Math.max(n+1,i.length),s=[];for(let e=0;e<o;e++){let o=i[e]??``;o=o.padEnd(a,`.`),e===n&&(o=o.slice(0,t)+r+o.slice(t+1)),s.push(o)}return s}function nR(e,t){let n=new Set([`.`,`0`,`1`]);for(let t of e)if(typeof t==`string`)for(let e of t)e!==` `&&n.add(e);for(let e of Object.keys(t))n.add(e);return[...n]}var rR=IL;function iR(e){return(e.kind===`foliage`||e.kind===`tile`)&&!e.animation}function aR(e,t,n){if(e.textContent=``,t.selection===null){sR(e,t,n);return}let r=t.nodeAt(t.selection);r&&gR(e,t,r,n)}var oR=[`connections`,`input`,`multiplayer`];function sR(e,t,n){e.appendChild(VR(`scene`)),e.appendChild(GR(`name`,String(t.working.name??``),e=>{t.mutate(()=>{t.working.name=e})}));let r=document.createElement(`select`);for(let e of[`2d`,`3d`]){let n=document.createElement(`option`);n.value=e,n.textContent=e,(t.working.dimension??`2d`)===e&&(n.selected=!0),r.appendChild(n)}r.addEventListener(`change`,()=>{t.mutate(()=>{t.working.dimension=r.value})}),e.appendChild(UR(`dimension`,r)),e.appendChild(VR(`physics`,`physics`));let i=(t.working.physics??{}).gravity??(t.working.dimension===`3d`?[0,-9.81,0]:[0,980]),a=t.working.dimension===`3d`?[0,-9.81,0]:[0,980];e.appendChild(qR(`gravity`,i,e=>{t.mutate(()=>{if(JSON.stringify(e)===JSON.stringify(a)){let e={...t.working.physics};delete e.gravity,Object.keys(e).length===0?delete t.working.physics:t.working.physics=e}else t.working.physics={...t.working.physics,gravity:e}})})),e.appendChild(VR(`environment`)),cR(e,t),e.appendChild(VR(`constants`)),FR(e,t,n),e.appendChild(VR(`advanced`));for(let n of oR)e.appendChild(YR(n,t.working[n],e=>{t.mutate(()=>{e===void 0?delete t.working[n]:t.working[n]=e})}))}function cR(e,t){let n=t.working.environment??{},r=e=>{t.mutate(()=>{let n={...t.working.environment??{},...e};for(let e of Object.keys(n))n[e]===void 0&&delete n[e];Object.keys(n).length===0?delete t.working.environment:t.working.environment=n})};e.appendChild(lR(`background`,n.background??``,e=>{r({background:e===``?void 0:e})})),e.appendChild(lR(`ambient color`,n.ambient?.color??``,e=>{let t={...n.ambient,color:e===``?void 0:e};t.color===void 0&&delete t.color,r({ambient:Object.keys(t).length?t:void 0})})),e.appendChild(KR(`ambient power`,n.ambient?.intensity??0,e=>{r({ambient:{...n.ambient,intensity:e}})}));let i=n.rendering??{},a=e=>{let t={...i,...e};for(let e of Object.keys(t))t[e]===void 0&&delete t[e];r({rendering:Object.keys(t).length?t:void 0})},o=document.createElement(`input`);o.type=`checkbox`,o.checked=i.antialias!==!1,o.addEventListener(`change`,()=>{a({antialias:o.checked?void 0:!1})}),e.appendChild(UR(`antialias`,o));let s=document.createElement(`select`);for(let[e,t]of[[``,`1 — soft hiDPI upscale (default)`],[`device`,`device — crisp retina`],[`2`,`2`]]){let n=document.createElement(`option`);n.value=e,n.textContent=t,String(i.pixelRatio??``)===e&&(n.selected=!0),s.appendChild(n)}s.addEventListener(`change`,()=>{a({pixelRatio:s.value===``?void 0:s.value===`device`?`device`:Number(s.value)})}),e.appendChild(UR(`pixel ratio`,s))}function lR(e,t,n){let r=document.createElement(`div`);r.className=`color-row`;let i=document.createElement(`input`);i.type=`color`,i.value=/^#[0-9a-fA-F]{6}$/.test(t)?t:`#000000`;let a=document.createElement(`input`);return a.type=`text`,a.className=`mono`,a.placeholder=`unset`,a.value=t,i.addEventListener(`input`,()=>{a.value=i.value}),i.addEventListener(`change`,()=>n(i.value)),a.addEventListener(`change`,()=>n(a.value.trim())),r.append(i,a),UR(e,r)}function uR(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.textContent=`underwater`,n.appendChild(r);let i=t.props?.underwater,a=i!==!1,o=i&&typeof i==`object`&&!Array.isArray(i)?i:{},s=n=>{e.mutate(()=>{t.props||={},n===!0?delete t.props.underwater:t.props.underwater=n,Object.keys(t.props).length===0&&delete t.props})},c=(e,t)=>{let n={...o};t===void 0||t===``?delete n[e]:n[e]=t,s(Object.keys(n).length===0?!0:n)},l=document.createElement(`input`);if(l.type=`checkbox`,l.checked=a,l.addEventListener(`change`,()=>s(l.checked)),n.appendChild(UR(`enabled`,l)),a){n.appendChild(lR(`murk color`,String(o.color??``),e=>c(`color`,e))),n.appendChild(KR(`visibility (m)`,Number(o.visibility??22),e=>c(`visibility`,e===22?void 0:e),()=>c(`visibility`,void 0)));let e=document.createElement(`input`);e.type=`checkbox`,e.checked=(o.caustics??!0)!==!1,e.addEventListener(`change`,()=>c(`caustics`,e.checked?void 0:!1)),n.appendChild(UR(`caustics`,e))}return n}function dR(e,t,n){let r=document.createElement(`div`);r.className=`subcard`;let i=document.createElement(`div`);i.className=`subcard-head`,i.textContent=`material`,r.appendChild(i);let a=t.props?.material??{},o=(n,r)=>{let i={...t.props?.material??{}};r===void 0||r===``?delete i[n]:i[n]=r;let a=Object.keys(i).length===0?void 0:i;e.mutate(()=>{t.props||={},a===void 0?(delete t.props.material,Object.keys(t.props).length===0&&delete t.props):t.props.material=a},e.selection?{path:e.selection,key:`material`,value:a}:void 0)};r.appendChild(lR(`color`,String(a.color??``),e=>o(`color`,e))),r.appendChild(hR(`roughness`,Number(a.roughness??1),e=>o(`roughness`,e))),r.appendChild(hR(`metalness`,Number(a.metalness??0),e=>o(`metalness`,e))),r.appendChild(lR(`emissive`,String(a.emissive??``),e=>o(`emissive`,e))),r.appendChild(hR(`emissive power`,Number(a.emissiveIntensity??1),e=>o(`emissiveIntensity`,e===1?void 0:e),2)),r.appendChild(hR(`opacity`,Number(a.opacity??1),e=>o(`opacity`,e===1?void 0:e))),r.appendChild(hR(`clearcoat`,Number(a.clearcoat??0),e=>o(`clearcoat`,e===0?void 0:e))),r.appendChild(hR(`clearcoat rough`,Number(a.clearcoatRoughness??0),e=>o(`clearcoatRoughness`,e===0?void 0:e))),r.appendChild(hR(`reflection`,Number(a.envMapIntensity??1),e=>o(`envMapIntensity`,e===1?void 0:e),3));let s=document.createElement(`input`);s.type=`checkbox`,s.checked=a.wireframe===!0,s.addEventListener(`change`,()=>o(`wireframe`,s.checked||void 0)),r.appendChild(UR(`wireframe`,s));let c=document.createElement(`input`);c.type=`checkbox`,c.checked=a.flatShading===!0,c.addEventListener(`change`,()=>o(`flatShading`,c.checked||void 0)),r.appendChild(UR(`flatShading`,c));let l=document.createElement(`input`);l.type=`checkbox`,l.checked=a.depthTest===!1,l.addEventListener(`change`,()=>{o(`depthTest`,l.checked?!1:void 0),o(`depthWrite`,l.checked?!1:void 0)}),r.appendChild(UR(`draw on top (decal)`,l)),r.appendChild(ER(`map (texture)`,String(a.map??``),DR(e=>iR(e)&&!e.name.includes(`normal`)&&!e.name.includes(`roughness`)),e=>o(`map`,e.trim()),{placeholder:`built-in or custom URL`,library:{kind:`image`,target:`map`,shelf:[`3d`,`textures`]},ctx:n})),r.appendChild(ER(`normal map`,String(a.normalMap??``),DR(e=>iR(e)&&e.name.includes(`normal`)),e=>o(`normalMap`,e.trim()),{placeholder:`built-in or custom URL`,library:{kind:`image`,target:`normal map`,shelf:[`3d`,`textures`]},ctx:n}));let u=!!(a.map||a.normalMap),d=Array.isArray(a.repeat)?a.repeat:[1,1],f=qR(`repeat [u,v]`,[d[0]??1,d[1]??1],e=>{let[t,n]=e;!Number.isFinite(t)||!Number.isFinite(n)||t===1&&n===1||!t&&!n?o(`repeat`,void 0):o(`repeat`,[t,n])});return f.title=u?`Texture tiling across the mesh UVs.`:`Only takes effect with a map/normal map set (engine validates).`,r.appendChild(f),r}var fR=new Set([`animationLoop`,`animationSpeed`,`animationOffset`,`animationUpper`,`animationUpperLoop`,`upperBodyRoot`]);function pR(e,t,n,r){let i=document.createElement(`div`);i.className=`subcard anim-card`;let a=document.createElement(`div`);a.className=`subcard-head`;let o=document.createElement(`strong`);o.textContent=`animation`,a.appendChild(o),i.appendChild(a);let s=String(t.props?.animation??``);if(i.appendChild(ER(`clip`,s,n.animationsForSelection().map(e=>({label:e,value:e,hint:e.startsWith(`$`)?`scene asset`:`clip in this model`})),n=>SR(e,t,`animation`,n.trim(),``),{placeholder:`clip name or $assetKey — empty = still`,library:{kind:`model`,target:`animation`,shelf:[`3d`,`animations`],asAsset:!0,assetType:`animation`},ctx:n})),!s){let a=document.createElement(`div`);return a.className=`muted-note`,a.textContent=`Pick a clip and it plays as soon as the scene loads — no script needed.`,i.appendChild(a),i.appendChild(mR(e,t,n,r)),i}i.appendChild(LR(e,t,`animationLoop`,r.animationLoop?.default??!0,void 0,`loop`));let c=hR(`speed`,Number(t.props?.animationSpeed??1),n=>SR(e,t,`animationSpeed`,n,1),3,-3);c.title=`1 = as authored · 0 freezes the pose · negative plays backwards (a closing door is an opening one reversed).`,i.appendChild(c);let l=LR(e,t,`animationOffset`,r.animationOffset?.default??0,void 0,`offset (s)`);return l.title=`Seconds into the clip to start at. Give copies different offsets so a row of torches stops flickering in lockstep.`,i.appendChild(l),i.appendChild(mR(e,t,n,r)),i}function mR(e,t,n,r){let i=document.createElement(`details`);i.className=`anim-upper`,t.props?.animationUpper&&(i.open=!0);let a=document.createElement(`summary`);return a.textContent=`upper-body layer`,a.title=`Play a second clip on the upper body only — attack while running, wave while walking.`,i.appendChild(a),i.appendChild(ER(`clip`,String(t.props?.animationUpper??``),n.animationsForSelection().map(e=>({label:e,value:e})),n=>SR(e,t,`animationUpper`,n.trim(),``),{placeholder:`empty = off`,ctx:n})),i.appendChild(LR(e,t,`animationUpperLoop`,r.animationUpperLoop?.default??!1,void 0,`loop`)),i.appendChild(LR(e,t,`upperBodyRoot`,r.upperBodyRoot?.default??`Spine`,void 0,`root bone`)),i}function hR(e,t,n,r=1,i=0){let a=document.createElement(`div`);a.className=`slider-row`;let o=document.createElement(`input`);o.type=`range`,o.min=String(i),o.max=String(r),o.step=`0.05`,o.value=String(Number.isFinite(t)?t:0);let s=document.createElement(`input`);return s.type=`number`,s.step=`0.05`,s.min=String(i),s.max=String(r),s.value=o.value,o.addEventListener(`input`,()=>{s.value=o.value}),o.addEventListener(`change`,()=>n(Number(o.value))),s.addEventListener(`change`,()=>{o.value=s.value,n(Number(s.value))}),a.append(o,s),UR(e,a)}function gR(e,t,n,r){if(e.appendChild(VR(n.type??`instance`)),e.appendChild(_R(n)),e.appendChild(GR(`name`,n.name??``,e=>{e.trim()===``||t.selection===null||t.renameNode(t.selection,e.trim())})),n.type===`TileMap2D`&&r?.paint&&e.appendChild(JR(n,r.paint)),n.type){let i;try{i=qe(n.type)}catch{i={}}for(let[a,o]of Object.entries(i))if(a===`collider`)e.appendChild(xR(t,n,o.default));else if(a===`material`)e.appendChild(dR(t,n,r));else if(n.type===`ModelInstance3D`&&a===`model`&&r)e.appendChild(ER(`model`,String(n.props?.model??``),r.modelRefs().map(e=>({label:e,value:e,hint:`scene asset`})),e=>SR(t,n,`model`,e.trim(),``),{placeholder:`$assetKey`,library:{kind:`model`,target:`model`,shelf:[`3d`,`characters`],asAsset:!0},ctx:r}));else if(n.type===`BoneAttachment3D`&&a===`bone`&&r?.bonesForSelection)e.appendChild(wR(`bone`,String(n.props?.bone??``),r.bonesForSelection(String(n.props?.target??``)),e=>SR(t,n,`bone`,e,``)));else if(n.type===`ModelInstance3D`&&a===`animation`&&r)e.appendChild(pR(t,n,r,i));else if(!(n.type===`ModelInstance3D`&&fR.has(a)))if((n.type===`Sprite3D`||n.type===`AnimatedSprite3D`)&&(a===`texture`||a===`sheet`))e.appendChild(ER(a===`sheet`?`sheet (image URL)`:`texture (image URL)`,String(n.props?.[a]??``),DR(e=>e.kind===`character`||e.kind===`item`),e=>SR(t,n,a,e.trim(),``),{placeholder:`image URL — empty hides the sprite`,library:{kind:`image`,target:a,shelf:[`2d`,`sprite_characters`]},ctx:r}));else if(n.type===`TileMap2D`&&a===`texture`)e.appendChild(ER(`texture (atlas $ref)`,String(n.props?.texture??``),(r?.assetRefs?.([`texture`,`spritesheet`])??[]).map(e=>({label:e,value:e,hint:`scene asset`})),e=>SR(t,n,`texture`,e.trim(),``),{placeholder:`$assetKey`,library:{kind:`image`,target:`tile atlas`,shelf:[`2d`,`sprite_characters`],asAsset:!0,assetType:`texture`},ctx:r}));else if(n.type===`Tree3D`&&a===`leafTexture`)e.appendChild(ER(`leaf texture`,String(n.props?.leafTexture??``),DR(e=>e.name.startsWith(`leaves_`)),e=>SR(t,n,`leafTexture`,e.trim(),``),{placeholder:`default (per-type) or URL`,library:{kind:`image`,target:`leaf texture`,shelf:[`3d`,`textures`]},ctx:r}));else if(n.type===`Terrain3D`&&a===`textureBase`)e.appendChild(ER(`texture base`,String(n.props?.textureBase??o.default??``),kR,e=>SR(t,n,`textureBase`,e.trim(),o.default),{placeholder:`splat texture base URL`}));else if(n.type===`AnimatedSprite2D`&&a===`sheet`||n.type===`Sprite2D`&&a===`texture`){let i=a===`sheet`;e.appendChild(AR(t,n,a,r,i))}else n.type===`AudioPlayer`&&a===`src`?e.appendChild(ER(`src (audio file)`,String(n.props?.src??``),OR(),e=>SR(t,n,`src`,e.trim(),``),{placeholder:`built-in or custom URL — or use preset`,note:"For zero-asset SFX, set the `preset` prop instead of src.",library:{kind:`audio`,target:`audio src`},ctx:r})):n.type===`Flowers3D`&&a===`varieties`?e.appendChild(jR(t,n)):n.type===`Water3D`&&a===`underwater`?e.appendChild(uR(t,n)):e.appendChild(LR(t,n,a,o.default,o.options))}if(e.appendChild(VR(`structure`)),e.appendChild(vR(t,n)),e.appendChild(yR(t,n)),e.appendChild(bR(t,n)),t.selection){let n=YL(t,t.selection);n&&(e.appendChild(VR(`connections`,`connections`)),e.appendChild(n))}}function _R(e){let t=document.createElement(`div`);t.className=`field uid-line`;let n=document.createElement(`span`);n.textContent=`uid`;let r=document.createElement(`div`);r.className=`uid-value`;let i=document.createElement(`code`);i.textContent=String(e.uid??``);let a=document.createElement(`button`);return a.type=`button`,a.className=`uid-copy`,a.title=`Copy uid`,a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,a.addEventListener(`click`,()=>{navigator.clipboard?.writeText(String(e.uid??``)),a.classList.add(`copied`),a.innerHTML=`✓`,setTimeout(()=>{a.classList.remove(`copied`),a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`},800)}),r.append(i,a),t.append(n,r),t}function vR(e,t){let n=document.createElement(`label`);n.className=`field wide`;let r=document.createElement(`span`);r.append(`groups `,FL(`groups`));let i=document.createElement(`div`);i.className=`chips`;for(let n of t.groups??[])i.appendChild(HR(n,()=>{e.mutate(()=>{t.groups=(t.groups??[]).filter(e=>e!==n),t.groups.length===0&&delete t.groups})}));let a=document.createElement(`input`);return a.placeholder=(t.groups?.length??0)===0?`add a tag… (e.g. coins)`:``,a.addEventListener(`keydown`,n=>{if(n.key!==`Enter`)return;let r=a.value.trim();r&&e.mutate(()=>{t.groups=[...t.groups??[],r]})}),i.appendChild(a),i.addEventListener(`click`,()=>a.focus()),n.append(r,i),n}function yR(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`script `,FL(`script`));let i=document.createElement(`span`);i.className=`spacer`,r.appendChild(i);let a=t.script;if(a){let n=document.createElement(`button`);n.type=`button`,n.className=`linklike`,n.textContent=`detach`,n.addEventListener(`click`,()=>{e.mutate(()=>{delete t.script})}),r.appendChild(n)}if(n.appendChild(r),!a){let r=document.createElement(`div`);r.className=`muted-note`,r.textContent=`No behavior attached. Behaviors are TypeScript classes in your game.`;let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=`+ attach behavior`,i.addEventListener(`click`,()=>{e.mutate(()=>{t.script={name:`MyBehavior`}})}),n.append(r,i),n}n.appendChild(GR(`name`,a.name??``,n=>{e.mutate(()=>{t.script.name=n.trim()})})),n.appendChild(YR(`props`,a.props,n=>{e.mutate(()=>{n===void 0?delete t.script.props:t.script.props=n})}));let o=document.createElement(`div`);return o.className=`muted-note`,o.textContent=`? has copy-paste boilerplate for the game side.`,n.appendChild(o),n}function bR(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`network `,FL(`network`)),n.appendChild(r);let i=t.network,a=document.createElement(`select`);for(let[e,t]of[[``,`not replicated`],[`owner`,`owner — this player broadcasts it`]]){let n=document.createElement(`option`);n.value=e,n.textContent=t,(i?.mode??``)===e&&(n.selected=!0),a.appendChild(n)}if(a.addEventListener(`change`,()=>{e.mutate(()=>{a.value===``?delete t.network:t.network={mode:a.value,sync:i?.sync??[`position`]}})}),n.appendChild(UR(`mode`,a)),i?.mode===`owner`){let r=document.createElement(`div`);r.className=`chips`;for(let n of i.sync??[])r.appendChild(HR(n,()=>{e.mutate(()=>{t.network.sync=(i.sync??[]).filter(e=>e!==n)})}));let a=document.createElement(`input`);a.placeholder=`position · Skin.animation…`,a.addEventListener(`keydown`,n=>{if(n.key!==`Enter`)return;let r=a.value.trim();r&&e.mutate(()=>{t.network.sync=[...i.sync??[],r]})}),r.appendChild(a);let o=document.createElement(`label`);o.className=`field wide`;let s=document.createElement(`span`);s.textContent=`sync keys`,o.append(s,r),n.appendChild(o),n.appendChild(KR(`throttle ms`,i.throttleMs??50,n=>{e.mutate(()=>{t.network.throttleMs=n})}))}return n}function xR(e,t,n){let r=document.createElement(`div`);r.className=`subcard`;let i=document.createElement(`div`);i.className=`subcard-head`,i.append(`collider `,FL(`collider`)),r.appendChild(i);let a=t.props?.collider??{},o=n=>{e.mutate(()=>{t.props||={};let e=t.props;Object.keys(n).length===0?(delete e.collider,Object.keys(e).length===0&&delete t.props):e.collider=n})},s=(t.type??``).endsWith(`3D`),c=s?[[``,`none`],[`box`,`box — crates, floors`],[`sphere`,`sphere — balls, pickups`],[`capsule`,`capsule — characters`]]:[[``,`none`],[`rect`,`rect — boxes, platforms`],[`circle`,`circle — coins, balls`],[`capsule`,`capsule — characters`]],l=document.createElement(`select`);for(let[e,t]of c){let n=document.createElement(`option`);n.value=e,n.textContent=t,(a.shape??``)===e&&(n.selected=!0),l.appendChild(n)}return l.addEventListener(`change`,()=>{l.value===``?o({}):l.value===`rect`?o({shape:`rect`,size:a.size??[32,32]}):l.value===`box`?o({shape:`box`,size:a.size??[1,1,1]}):l.value===`circle`?o({shape:`circle`,radius:a.radius??16}):l.value===`sphere`?o({shape:`sphere`,radius:a.radius??.5}):o(s?{shape:`capsule`,radius:a.radius??.4,height:a.height??1}:{shape:`capsule`,radius:a.radius??12,height:a.height??16})}),r.appendChild(UR(`shape`,l)),a.shape===`rect`||a.shape===`box`?r.appendChild(qR(`size`,a.size??(s?[1,1,1]:[32,32]),e=>o({...a,size:e}))):a.shape===`circle`||a.shape===`sphere`?r.appendChild(KR(`radius`,a.radius??(s?.5:16),e=>o({...a,radius:e}))):a.shape===`capsule`&&(r.appendChild(KR(`radius`,a.radius??12,e=>o({...a,radius:e}))),r.appendChild(KR(`height`,a.height??16,e=>o({...a,height:e})))),a.shape&&r.appendChild(qR(`offset`,a.offset??(s?[0,0,0]:[0,0]),e=>o({...a,offset:e}))),r}function SR(e,t,n,r,i){e.mutate(()=>{t.props||={},JSON.stringify(r)===JSON.stringify(i)?(delete t.props[n],Object.keys(t.props).length===0&&delete t.props):t.props[n]=r})}var CR=0;function wR(e,t,n,r){let i=document.createElement(`input`);i.type=`text`,i.value=t;let a=`suggest-${CR++}`;i.setAttribute(`list`,a);let o=document.createElement(`datalist`);o.id=a;for(let e of n){let t=document.createElement(`option`);t.value=e,o.appendChild(t)}i.addEventListener(`change`,()=>r(i.value.trim()));let s=UR(e,i);return s.appendChild(o),s}var TR=0;function ER(e,t,n,r,i={}){let a=document.createElement(`label`);a.className=`field wide asset-field`;let o=document.createElement(`span`);o.textContent=e,a.appendChild(o);let s=document.createElement(`input`);s.type=`text`,s.value=t,i.placeholder&&(s.placeholder=i.placeholder),s.addEventListener(`change`,()=>r(s.value.trim()));let c=document.createElement(`button`);c.type=`button`,c.className=`asset-toggle`,c.title=`Browse built-in assets`,c.textContent=`▾`;let l=document.createElement(`div`);if(l.className=`asset-control`,l.append(s),i.library&&i.ctx?.openLibrary){let t=document.createElement(`button`);t.type=`button`,t.className=`asset-lib`,t.textContent=`📚`,t.title=`Browse the agent8 library for a ${i.library.kind}`,t.addEventListener(`click`,t=>{t.preventDefault();let n=i.ctx?.openLibrary;n&&n({kind:i.library?.kind??`any`,target:i.library?.target??e,...i.library?.shelf?{shelf:i.library.shelf}:{},...i.library?.asAsset?{asAsset:!0}:{},...i.library?.assetType?{assetType:i.library.assetType}:{},...i.library?.onProps?{onProps:i.library.onProps}:{}}).then(e=>{e!==null&&(s.value=e,r(e))})}),l.append(t)}l.append(c),a.appendChild(l);let u=document.createElement(`div`);u.className=`asset-panel`,u.hidden=!0;let d=document.createElement(`input`);d.type=`text`,d.className=`asset-search`,d.placeholder=`search ${n.length} built-in${n.length===1?``:`s`}…`;let f=document.createElement(`div`);f.className=`asset-options`,u.append(d,f),a.appendChild(u);let p=e=>{f.textContent=``;let t=e.trim().toLowerCase(),i=n.filter(e=>t===``||e.label.toLowerCase().includes(t)||(e.hint?.toLowerCase().includes(t)??!1)||e.value.toLowerCase().includes(t));if(i.length===0){let e=document.createElement(`div`);e.className=`asset-empty`,e.textContent=`no match — type a custom URL above`,f.appendChild(e);return}for(let e of i){let t=document.createElement(`button`);t.type=`button`,t.className=`asset-option`;let n=document.createElement(`strong`);if(n.textContent=e.label,t.appendChild(n),e.hint){let n=document.createElement(`small`);n.textContent=e.hint,t.appendChild(n)}t.addEventListener(`click`,()=>{s.value=e.value,u.hidden=!0,r(e.value)}),f.appendChild(t)}};if(c.addEventListener(`click`,()=>{u.hidden=!u.hidden,u.hidden||(p(d.value),d.focus())}),d.addEventListener(`input`,()=>p(d.value)),d.addEventListener(`keydown`,e=>{e.key===`Escape`&&(u.hidden=!0)}),i.note){let e=document.createElement(`div`);e.className=`muted-note asset-note`,e.textContent=i.note,a.appendChild(e)}return s.id=`asset-input-${TR++}`,a.htmlFor=s.id,a}function DR(e){return rR.filter(e).map(e=>({label:e.name,value:e.url,hint:`${e.kind} · ${e.description.slice(0,70)}`}))}function OR(){return rR.filter(e=>e.kind===`audio`).map(e=>({label:e.name,value:e.url,hint:`audio · ${e.description.slice(0,70)}`}))}var kR=[{label:`agent8 default terrain`,value:`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,hint:`sand/grass/stone/snow splat set (Terrain3D default)`}];function AR(e,t,n,r,i){let a=String(t.props?.[n]??``),o=i?[`spritesheet`]:[`texture`,`spritesheet`],s=(r?.assetRefs?.(o)??[]).map(e=>({label:e,value:e,hint:`scene asset`})),c=rR.filter(e=>i?!!e.animation:e.kind===`character`||e.kind===`item`||e.kind===`tile`);for(let e of c)s.push({label:`built-in: ${e.name}`,value:`$${e.name}`,hint:`${e.kind} · creates a scene asset (${e.animation?`spritesheet`:`texture`})`});return ER(i?`sheet`:`texture`,a,s,i=>{let a=i.startsWith(`$`)&&c.find(e=>`$${e.name}`===i);if(a&&r?.addAsset){let i={type:a.animation?`spritesheet`:`texture`,url:a.url};if(a.animation){let e=a.frameWidth,t=a.frameHeight;e&&(i.frameWidth=e),t&&(i.frameHeight=t)}SR(e,t,n,`$${r.addAsset(a.name,i).replace(/^\$/,``)}`,``);return}SR(e,t,n,i.trim(),``)},{placeholder:`$assetKey`,note:"Picks a $asset ref. Built-ins create the scene asset; packaged sprites need `incanto-assets copy` (or a bundler import) to serve at runtime.",library:{kind:`image`,target:i?`sheet`:`texture`,shelf:[`2d`,`sprite_characters`],asAsset:!0,assetType:i?`spritesheet`:`texture`,onProps:n=>{for(let[r,i]of Object.entries(n))SR(e,t,r,i,void 0)}},ctx:r})}function jR(e,t){let n=document.createElement(`label`);n.className=`field wide`;let r=document.createElement(`span`);r.textContent=`varieties`,n.appendChild(r);let i=new Set(Array.isArray(t.props?.varieties)?t.props.varieties:[]),a=document.createElement(`div`);a.className=`chips varieties`;let o=()=>{let n=kD.filter(e=>i.has(e));SR(e,t,`varieties`,n.length===0||n.length===kD.length?[]:n,[])};for(let e of kD){let t=document.createElement(`label`);t.className=`variety-opt`;let n=document.createElement(`input`);n.type=`checkbox`,n.checked=i.size===0||i.has(e),n.addEventListener(`change`,()=>{if(i.size===0)for(let e of kD)i.add(e);n.checked?i.add(e):i.delete(e),o()});let r=document.createElement(`span`);r.textContent=e,t.append(n,r),a.appendChild(t)}n.appendChild(a);let s=document.createElement(`div`);return s.className=`muted-note`,s.textContent=`All (or none) = the default mix of all three.`,n.appendChild(s),n}var MR=[[`number`,()=>0],[`text`,()=>``],[`boolean`,()=>!1],[`color`,()=>`#ffffff`],[`vec2`,()=>[0,0]],[`vec3`,()=>[0,0,0]]];function NR(e,t){let n=0,r=e=>{if(yn(e)){e[`@const`]===t&&(n+=1);return}if(Array.isArray(e))for(let t of e)r(t);else if(e&&typeof e==`object`)for(let t of Object.values(e))r(t)};for(let[t,n]of Object.entries(e))t!==`constants`&&r(n);return n}function PR(e,t,n){let r=e=>{if(yn(e))return e[`@const`]===t?JSON.parse(JSON.stringify(n??null)):e;if(Array.isArray(e))return e.map(r);if(e&&typeof e==`object`){let t=e;for(let e of Object.keys(t))t[e]=r(t[e]);return t}return e};for(let t of Object.keys(e))t!==`constants`&&(e[t]=r(e[t]))}function FR(e,t,n){let r=t.working.constants??{},i=Object.keys(r),a=(e,n)=>{t.mutate(()=>{let r={...t.working.constants??{}};r[e]=n,t.working.constants=r})},o=(e,n)=>{t.mutate(()=>{n&&PR(t.working,e,r[e]);let i={...t.working.constants??{}};delete i[e],Object.keys(i).length===0?delete t.working.constants:t.working.constants=i})},s=e=>{let r=NR(t.working,e);if(r>0&&n?.confirm){n.confirm(`"${e}" is used by ${r} prop${r===1?``:`s`}. Unlink them (inline its current value) and delete?`,`unlink & delete`,()=>o(e,!0));return}o(e,r>0)};if(i.length===0){let t=document.createElement(`div`);t.className=`hint`,t.textContent=`No constants yet. Add one, then bind props to it with the 🔗 picker.`,e.appendChild(t)}for(let t of i){let n=document.createElement(`div`);n.className=`const-row`,n.appendChild(IR(t,r[t],e=>a(t,e)));let i=document.createElement(`button`);i.type=`button`,i.className=`const-del`,i.textContent=`✕`,i.title=`delete constant "${t}"`,i.addEventListener(`click`,()=>s(t)),n.appendChild(i),e.appendChild(n)}let c=document.createElement(`div`);c.className=`const-add`;let l=document.createElement(`input`);l.type=`text`,l.placeholder=`new constant name`;let u=document.createElement(`select`);for(let[e]of MR){let t=document.createElement(`option`);t.value=e,t.textContent=e,u.appendChild(t)}let d=document.createElement(`button`);d.type=`button`,d.textContent=`+ add`,d.addEventListener(`click`,()=>{let e=l.value.trim();e&&(t.working.constants??{})[e]===void 0&&(a(e,(MR.find(([e])=>e===u.value)?.[1]??(()=>0))()),l.value=``)}),c.append(l,u,d),e.appendChild(c)}function IR(e,t,n){let r=Be(t);if(r===`number`)return KR(e,t,e=>n(e),()=>n(0));if(r===`boolean`){let r=document.createElement(`input`);return r.type=`checkbox`,r.checked=t===!0,r.addEventListener(`change`,()=>n(r.checked)),UR(e,r)}return r===`array`&&Array.isArray(t)&&t.every(e=>typeof e==`number`)?qR(e,t,e=>n(e)):r===`string`?GR(e,String(t),e=>n(e)):YR(e,t,e=>n(e??null),JSON.stringify(t))}function LR(e,t,n,r,i,a){let o=t.props?.[n]??r,s=Be(r),c=s===`number`||s===`boolean`||s===`string`||s===`array`,l=i=>{let a=yn(i);e.mutate(()=>{t.props||={};let e=t.props;JSON.stringify(i)===JSON.stringify(r)?(delete e[n],Object.keys(e).length===0&&delete t.props):e[n]=i},e.selection&&c&&!a?{path:e.selection,key:n,value:i}:void 0)},u=RR(e,s,r);if(yn(o))return zR(n,o[`@const`],u,l,r);let d=e=>u.length>0?BR(e,u,l):e;if(s===`number`)return d(KR(a??n,o,e=>l(e),()=>l(r)));if(s===`boolean`){let e=document.createElement(`input`);return e.type=`checkbox`,e.checked=o===!0,e.addEventListener(`change`,()=>l(e.checked)),d(UR(a??n,e))}return s===`string`?i&&i.length>0?d(WR(a??n,String(o??``),i,e=>l(e))):d(GR(a??n,String(o??``),e=>l(e))):s===`array`&&Array.isArray(r)&&r.length>0&&r.every(e=>typeof e==`number`)?d(qR(n,o??r,e=>l(e))):YR(n,o===r?void 0:o,e=>{l(e===void 0?r:e)},JSON.stringify(r))}function RR(e,t,n){let r=e.working.constants??{};return Object.keys(r).filter(e=>{let i=r[e];return Be(i)===t?t===`array`&&Array.isArray(n)&&Array.isArray(i)?i.length===n.length:!0:!1})}function zR(e,t,n,r,i){let a=document.createElement(`select`),o=n.includes(t)?n:[t,...n];for(let e of o){let n=document.createElement(`option`);n.value=e,n.textContent=e,e===t&&(n.selected=!0),a.appendChild(n)}let s=document.createElement(`option`);s.value=``,s.textContent=`↺ custom value`,a.appendChild(s),a.addEventListener(`change`,()=>{r(a.value?{"@const":a.value}:i)});let c=UR(`🔗 ${e}`,a);return c.classList.add(`const-bound`),c}function BR(e,t,n){let r=document.createElement(`select`);r.className=`const-picker`,r.title=`Bind to a named constant`;let i=document.createElement(`option`);i.value=``,i.textContent=`🔗`,r.appendChild(i);for(let e of t){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}return r.value=``,r.addEventListener(`change`,()=>{r.value&&n({"@const":r.value})}),e.appendChild(r),e}function VR(e,t){let n=document.createElement(`div`);n.className=`section-title`,n.textContent=e,t&&n.appendChild(FL(t));let r=document.createElement(`span`);return r.className=`rule`,n.appendChild(r),n}function HR(e,t){let n=document.createElement(`span`);n.className=`chip`,n.textContent=e;let r=document.createElement(`button`);return r.type=`button`,r.textContent=`✕`,r.addEventListener(`click`,e=>{e.stopPropagation(),t()}),n.appendChild(r),n}function UR(e,t){let n=document.createElement(`label`);n.className=`field`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n}function WR(e,t,n,r){let i=document.createElement(`select`);for(let e of n.includes(t)?n:[t,...n]){let n=document.createElement(`option`);n.value=e,n.textContent=e,e===t&&(n.selected=!0),i.appendChild(n)}return i.addEventListener(`change`,()=>r(i.value)),UR(e,i)}function GR(e,t,n){let r=document.createElement(`input`);return r.type=`text`,r.value=t,r.addEventListener(`change`,()=>n(r.value)),UR(e,r)}function KR(e,t,n,r){let i=document.createElement(`input`);return i.type=`number`,i.step=`any`,i.value=String(t),i.addEventListener(`change`,()=>{if(i.value.trim()===``){r?.();return}let e=Number(i.value);Number.isFinite(e)&&n(e)}),UR(e,i)}function qR(e,t,n){let r=document.createElement(`div`);r.className=`vector-row`;let i=[...t];return i.forEach((e,t)=>{let a=document.createElement(`input`);a.type=`number`,a.step=`any`,a.value=String(e??0),a.addEventListener(`change`,()=>{let e=Number(a.value);Number.isFinite(e)&&(i[t]=e,n([...i]))}),r.appendChild(a)}),UR(e,r)}function JR(e,t){let n=document.createElement(`div`);n.className=`field wide tile-paint`;let r=document.createElement(`button`);r.type=`button`,r.className=t.active()?`paint-toggle on`:`paint-toggle`,r.textContent=t.active()?`🖌 painting — click the canvas`:`🖌 paint tiles`,r.addEventListener(`click`,()=>t.toggle()),n.appendChild(r);let i=document.createElement(`div`);i.className=`paint-palette`;let a=e.props?.cells??[],o=e.props?.legend??{};for(let e of nR(a,o)){let n=document.createElement(`button`);n.type=`button`,n.className=t.brush()===e?`paint-chip on`:`paint-chip`,n.textContent=e===`.`?`␡`:e,n.title=e===`.`?`eraser (empty cell)`:`tile '${e}'`,n.addEventListener(`click`,()=>t.setBrush(e)),i.appendChild(n)}let s=document.createElement(`input`);s.type=`text`,s.maxLength=1,s.className=`paint-brush-input`,s.value=t.brush(),s.title=`brush char (digit or a legend char)`,s.addEventListener(`change`,()=>{s.value.length===1&&t.setBrush(s.value)}),i.appendChild(s),n.appendChild(i);let c=document.createElement(`div`);return c.className=`paint-hint`,c.textContent=`grid grows right/down; digits map to atlas tiles, others need legend`,n.appendChild(c),n}function YR(e,t,n,r=``){let i=document.createElement(`textarea`);i.rows=3,i.placeholder=r,i.value=t===void 0?``:JSON.stringify(t,null,2),i.addEventListener(`change`,()=>{let e=i.value.trim();if(e===``){i.classList.remove(`invalid`),n(void 0);return}try{let t=JSON.parse(e);i.classList.remove(`invalid`),n(t)}catch{i.classList.add(`invalid`)}});let a=UR(e,i);return a.className=`field wide`,a}var XR=2.4,ZR=1.35,QR=[0,.5,0];function $R(e){return{format:1,type:`scene`,dimension:`3d`,name:`Preview`,environment:{sky:{type:`atmosphere`,elevationDeg:35,azimuthDeg:140,turbidity:3},ambient:{intensity:.55},exposure:1.05},assets:{model:{type:`model`,url:e}},root:{name:`Preview`,type:`Node3D`,children:[{name:`Cam`,type:`Camera3D`,props:{current:!0,position:[0,ZR,XR]}},{name:`Sun`,type:`DirectionalLight3D`,props:{position:[3,6,4],intensity:2.2}},{name:`Model`,type:`ModelInstance3D`,props:{model:`$model`,targetHeight:1}}]}}}var ez=class{canvas=null;engine=null;renderer=null;raf=0;angle=.9;dragging=!1;lastX=0;url=``;mount(e){let t=document.createElement(`div`);t.className=`lib-preview3d`;let n=this.ensure();return t.appendChild(n),e!==this.url&&(this.url=e,this.load(e)),this.start(),t}detach(){this.stop(),this.canvas?.remove()}dispose(){this.stop(),this.renderer?.dispose(),this.engine?.dispose(),this.renderer=null,this.engine=null,this.canvas?.remove(),this.canvas=null,this.url=``}ensure(){if(this.canvas)return this.canvas;let e=document.createElement(`canvas`);e.className=`lib-preview-canvas`,this.canvas=e,this.engine=new Et({scheduler:()=>()=>{}}),this.renderer=new gP({canvas:e,engine:this.engine}),e.addEventListener(`pointerdown`,t=>{this.dragging=!0,this.lastX=t.clientX,e.setPointerCapture(t.pointerId)}),e.addEventListener(`pointermove`,e=>{this.dragging&&(this.angle-=(e.clientX-this.lastX)*.01,this.lastX=e.clientX)});let t=()=>{this.dragging=!1};return e.addEventListener(`pointerup`,t),e.addEventListener(`pointercancel`,t),e}load(e){if(this.engine)try{this.engine.setScene(kn($R(e)))}catch(t){console.warn(`[incanto] library preview could not load`,e,t)}}start(){if(this.raf)return;let e=0,t=n=>{this.raf=requestAnimationFrame(t);let r=e?Math.min(.05,(n-e)/1e3):0;e=n,this.dragging||(this.angle+=r*.5);let i=this.renderer;i&&(i.viewOverride={position:[Math.sin(this.angle)*XR,ZR,Math.cos(this.angle)*XR],target:QR},this.engine?.tick(n))};this.raf=requestAnimationFrame(t)}stop(){this.raf&&cancelAnimationFrame(this.raf),this.raf=0}},tz=`incanto-editor-v8-token`,nz=24;async function rz(e,t,n){if(!C(e.url)||n!==`spritesheet`&&n!==`texture`)return null;try{let n=ry(await(await fetch(e.url)).json(),{url:w(e.url),assetKey:t});return{asset:n.asset,props:Object.fromEntries(Object.entries(n.props).filter(([e])=>e!==`sheet`))}}catch(t){return console.warn(`[incanto] not a usable sprite config:`,e.url,t),null}}function iz(){try{return localStorage.getItem(tz)??``}catch{return``}}function az(e){try{e?localStorage.setItem(tz,e):localStorage.removeItem(tz)}catch{}}function oz(e,t){return new Promise(n=>{let r=[...t.shelf??[]],i=``,a=1,o=!1,c=[],u=[],d=null,f=!1,b=!1,x=document.createElement(`div`);x.className=`lib-backdrop`;let T=document.createElement(`div`);T.className=`lib-dialog`,x.appendChild(T);let E=document.createElement(`header`);E.className=`lib-head`;let D=document.createElement(`strong`);D.textContent=`agent8 library`;let O=document.createElement(`span`);O.className=`lib-sub`,O.textContent=t.target?`→ ${t.target}`:``;let k=document.createElement(`input`);k.type=`search`,k.className=`lib-search`,k.placeholder=`search descriptions…`;let A=document.createElement(`button`);A.type=`button`,A.className=`ghost`,A.id=`lib-close`,A.textContent=`✕`,A.title=`Close (Esc)`,E.append(D,O,k,A),T.appendChild(E);let ee=document.createElement(`div`);ee.className=`lib-body`,T.appendChild(ee);let te=document.createElement(`nav`);te.className=`lib-shelves`;let ne=document.createElement(`div`);ne.className=`lib-grid-pane`;let re=document.createElement(`div`);re.className=`lib-grid`;let j=document.createElement(`div`);j.className=`lib-status`;let ie=document.createElement(`button`);ie.type=`button`,ie.className=`ghost lib-more`,ie.textContent=`load more`,ie.hidden=!0,ne.append(j,re,ie);let ae=document.createElement(`aside`);ae.className=`lib-detail`,ee.append(te,ne,ae);let M=new ez,oe=e=>{b||(b=!0,M.dispose(),document.removeEventListener(`keydown`,se,!0),x.remove(),n(e))},se=e=>{e.key===`Escape`&&(e.stopPropagation(),oe(null))};document.addEventListener(`keydown`,se,!0),x.addEventListener(`pointerdown`,e=>{e.target===x&&oe(null)}),A.addEventListener(`click`,()=>oe(null));let ce=e=>{r=e,a=1,u=[],pe(!1)},le=()=>{te.textContent=``;let e=[[`Everything`,[]]];for(let t=0;t<r.length;t++)e.push([r[t],r.slice(0,t+1)]);for(let[t,n]of e){let e=document.createElement(`button`);e.type=`button`,e.className=`lib-shelf crumb`,e.style.paddingLeft=`${10+(n.length?n.length-1:0)*12}px`,e.textContent=t,e.classList.toggle(`active`,n.length===r.length),e.addEventListener(`click`,()=>{n.length!==r.length&&ce(n)}),te.appendChild(e)}let t=s(u,r);if(t.length>0){let e=document.createElement(`div`);e.className=`lib-shelf-head`,e.textContent=`in here`,te.appendChild(e)}for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`lib-shelf`,t.style.paddingLeft=`${16+r.length*12}px`;let n=document.createElement(`span`);n.textContent=e.tag;let i=document.createElement(`small`);i.className=`lib-shelf-count`,i.textContent=String(e.count),t.append(n,i),t.addEventListener(`click`,()=>ce([...r,e.tag])),te.appendChild(t)}},ue=()=>{if(ae.textContent=``,M.detach(),!d){let e=document.createElement(`div`);e.className=`lib-empty`,e.textContent=`pick an asset to preview it`,ae.appendChild(e);return}let e=d,n=document.createElement(`div`);n.className=`lib-stage`;let r=m(e.url);if(r===`image`||C(e.url)){let t=document.createElement(`img`);t.src=C(e.url)?w(e.url):e.url,t.alt=g(e),t.loading=`lazy`,n.appendChild(t)}else if(r===`audio`){let t=document.createElement(`audio`);t.controls=!0,t.src=e.url,n.appendChild(t)}else if(r===`model`)n.appendChild(M.mount(e.url));else{let t=document.createElement(`div`);t.className=`lib-empty`,t.textContent=`no preview for ${p(e.url)||`this file`}`,n.appendChild(t)}if(ae.appendChild(n),C(e.url)){let e=document.createElement(`p`);e.className=`lib-desc lib-note`,e.textContent=`Sprite config — picking it declares the sheet AND wires its named animations onto the node.`,ae.appendChild(e)}let i=document.createElement(`h3`);if(i.className=`lib-name`,i.textContent=g(e),ae.appendChild(i),e.description){let t=document.createElement(`p`);t.className=`lib-desc`,t.textContent=e.description,ae.appendChild(t)}let a=v(e);if(a.length){let e=document.createElement(`div`);e.className=`lib-tags`;for(let t of a){let n=document.createElement(`span`);n.className=`lib-tag`,n.textContent=t,e.appendChild(n)}ae.appendChild(e)}let o=y(e);if(o.length){let e=document.createElement(`dl`);e.className=`lib-facts`;for(let[t,n]of o){let r=document.createElement(`dt`);r.textContent=t;let i=document.createElement(`dd`);i.textContent=n,e.append(r,i)}ae.appendChild(e)}let s=document.createElement(`div`);s.className=`lib-url`;let c=document.createElement(`code`);c.textContent=e.url;let l=document.createElement(`button`);l.type=`button`,l.className=`ghost`,l.textContent=`copy`,l.addEventListener(`click`,()=>{navigator.clipboard?.writeText(e.url),l.textContent=`copied`,setTimeout(()=>{l.textContent=`copy`},1200)}),s.append(c,l),ae.appendChild(s);let u=document.createElement(`div`);u.className=`lib-actions`;let f=document.createElement(`button`);f.type=`button`,f.className=`primary`,f.id=`lib-use`,f.textContent=t.onAsset?`use as scene asset`:`use this`,f.addEventListener(`click`,()=>{if(!t.onAsset){oe(e.url);return}(async()=>{let n=_(e),r=await rz(e,n,t.assetType),i=r?.asset??S(e,t.kind,t.assetType),a=t.onAsset?.(e,i,n)??e.url;r&&t.onProps?.(r.props),oe(a)})()}),u.appendChild(f),ae.appendChild(u)},de=()=>{re.textContent=``;let e=c.filter(e=>h(e.url,t.kind));if(e.length===0&&!f){let e=document.createElement(`div`);e.className=`lib-empty`,e.textContent=c.length===0?`nothing on this shelf`:`this shelf has ${c.length} asset${c.length===1?``:`s`}, none of them a ${t.kind}`,re.appendChild(e)}for(let t of e){let e=document.createElement(`button`);e.type=`button`,e.className=`lib-card`,e.classList.toggle(`active`,t===d);let n=document.createElement(`div`);n.className=`lib-thumb`;let r=m(t.url);if(r===`image`){let e=document.createElement(`img`);e.src=t.url,e.alt=``,e.loading=`lazy`,n.appendChild(e)}else{let e=QP(r===`audio`?`AudioPlayer`:`ModelInstance3D`);e.classList.add(`lib-glyph`),n.appendChild(e)}if(C(t.url)){let e=document.createElement(`em`);e.className=`lib-badge`,e.textContent=`animated`,e.title=`A sprite config: frame grid + named animations. Picking it wires them up.`,n.appendChild(e)}let i=document.createElement(`span`);i.className=`lib-card-name`,i.textContent=g(t),e.append(n,i),e.title=t.description||t.url,e.addEventListener(`click`,()=>{d=t,de(),ue()}),re.appendChild(e)}ie.hidden=!o||f},fe=e=>{re.textContent=``,ie.hidden=!0;let t=document.createElement(`div`);t.className=`lib-token`;let n=document.createElement(`p`);n.className=`lib-token-line`,n.textContent=e;let r=document.createElement(`p`);r.className=`lib-token-line lib-token-how`,r.textContent=`The catalog is per-account. Paste a Verse8 access token to browse it here — it is kept in this browser and sent only to your own editor server. Starting the editor with --token (or INCANTO_V8_TOKEN) skips this.`;let i=document.createElement(`input`);i.type=`password`,i.className=`mono`,i.placeholder=`v8 access token`,i.value=iz();let o=document.createElement(`button`);o.type=`button`,o.className=`primary`,o.textContent=`connect`,o.addEventListener(`click`,()=>{az(i.value.trim()),a=1,pe(!1)}),i.addEventListener(`keydown`,e=>{e.key===`Enter`&&o.click()});let s=document.createElement(`div`);s.className=`lib-token-row`,s.append(i,o),t.append(n,r,s),re.appendChild(t)},pe=async t=>{if(!(!e.library||f)){f=!0,j.textContent=t?`loading more…`:`loading ${l(r)}…`,t||(c=[],d=null,de(),ue()),le();try{let n=await e.library({tags:r,keyword:i.trim()||void 0,page:a,limit:nz},iz()||void 0);if(b)return;c=t?[...c,...n.items]:n.items,u=c,o=n.hasNext;let s=n.total===void 0?``:` of ${n.total}`;j.textContent=`${l(r)} · ${c.length}${s} loaded`,le(),de()}catch(e){if(b)return;let t=e.needsToken===!0;if(j.textContent=l(r),t)fe(e instanceof Error?e.message:String(e));else{re.textContent=``;let t=document.createElement(`div`);t.className=`lib-error`,t.textContent=e instanceof Error?e.message:String(e),re.appendChild(t)}}finally{f=!1,ie.hidden=!o}}};ie.addEventListener(`click`,()=>{a+=1,pe(!0)});let me=0;k.addEventListener(`input`,()=>{i=k.value,clearTimeout(me),me=window.setTimeout(()=>{a=1,pe(!1)},350)}),le(),ue(),document.body.appendChild(x),k.focus(),pe(!1)})}var sz=`.scene.json`;function cz(e){let t=e.split(`/`).pop()??e;return t.endsWith(sz)?t.slice(0,-11):t}function lz(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function uz(e,t){return{path:e,name:t,dirs:new Map,files:[]}}function dz(e){let t=uz(``,``);for(let n of e){let e=n.rel.split(`/`);if(!e.pop())continue;let r=t;for(let t of e){let e=r.path?`${r.path}/${t}`:t,n=r.dirs.get(t);n||(n=uz(e,t),r.dirs.set(t,n)),r=n}r.files.push(n)}return t}function fz(e){let t=e.files.length;for(let n of e.dirs.values())t+=fz(n);return t}function pz(e){let t=e.files.filter(e=>e.scene).length;for(let n of e.dirs.values())t+=pz(n);return t}function mz(e){let t=e,n=e.name;for(;t.files.length===0&&t.dirs.size===1;){let e=[...t.dirs.values()][0];if(!e)break;t=e,n=`${n} / ${e.name}`}return{dir:t,label:n}}function hz(e){let t=lz(e??``).split(`/`).filter(Boolean),n=[],r=``;for(let e of t)r=r?`${r}/${e}`:e,n.push(r);return n}function gz(e,t={}){let n=(t.query??``).trim().toLowerCase(),r=n?e.filter(e=>e.rel.toLowerCase().includes(n)):e,i=t.expanded??new Set,a=[],o=(e,r)=>{let s=[...e.dirs.values()].sort((e,t)=>e.name.localeCompare(t.name));for(let e of s){let{dir:t,label:s}=mz(e),c=fz(t);if(c===0)continue;let l=n!==``||i.has(t.path);a.push({kind:`folder`,path:t.path,label:s,depth:r,count:c,scenes:pz(t),open:l}),l&&o(t,r+1)}let c=[...e.files].sort((e,t)=>cz(e.rel).localeCompare(cz(t.rel)));for(let e of c)a.push({kind:`scene`,entry:e,label:cz(e.rel),folder:lz(e.rel),depth:r,current:e.rel===t.current})};return o(dz(r),0),a}function _z(e,t){let n=new Set(hz(t));if(e.length<=24)for(let t of e)for(let e of hz(t.rel))n.add(e);return n}function vz(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?``:e<1e3?`${e} B`:e<1e3*1e3?`${(e/1e3).toFixed(1)} kB`:`${(e/1e3/1e3).toFixed(1)} MB`}function yz(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return``;let n=Math.round((t-e)/1e3);if(n<90)return`just now`;let r=Math.round(n/60);if(r<60)return`${r}m ago`;let i=Math.round(r/60);return i<24?`${i}h ago`:i<48?`yesterday`:new Date(e).toISOString().slice(0,10)}function bz(e,t=`new-level`){let n=e?e.kind===`folder`?e.path:e.folder:``;return n?`${n}/${t}${sz}`:`${t}${sz}`}function xz(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}function Sz(e,t,n=()=>Date.now()){let r=[],i=new Set,a=[],o=0,s=!0,c=()=>{let c=t.current();if(a=gz(r,{expanded:i,query:e.search.value,current:c}),o>=a.length&&(o=a.length-1),o<0&&(o=0),s){let e=a.findIndex(e=>e.kind===`scene`&&e.current);e>=0&&(o=e),s=!1}if(e.list.textContent=``,a.length===0){let t=document.createElement(`div`);t.className=`scene-empty`,t.textContent=r.length?`no scene matches “${e.search.value.trim()}”`:`no .json files in this project yet — create a scene below`,e.list.appendChild(t)}let u=n();a.forEach((n,r)=>{let i=document.createElement(`div`);i.className=n.kind===`folder`?`scene-row scene-folder`:`scene-row`,i.style.paddingLeft=`${6+n.depth*14}px`,r===o&&i.classList.add(`active`);let a=xz(`scene-caret`,``);n.kind===`folder`?(a.classList.add(`chevron`),n.open||a.classList.add(`collapsed`),a.appendChild($P())):a.textContent=`◇`,i.append(a,xz(`scene-name`,n.label),xz(`scene-meta`,n.kind===`folder`?n.scenes>0?`${n.scenes} scene${n.scenes===1?``:`s`}`:`${n.count} file${n.count===1?``:`s`}`:[n.entry.scene?[n.entry.scene.dimension,`${n.entry.scene.nodes} node${n.entry.scene.nodes===1?``:`s`}`].filter(Boolean).join(` · `):`not a scene`,yz(n.entry.modified,u),vz(n.entry.size)].filter(Boolean).join(` · `))),n.kind===`scene`&&(n.current&&i.classList.add(`current`),n.entry.notScene?(i.classList.add(`not-scene`),i.title=`${n.entry.rel}\n\nnot a scene: ${n.entry.notScene}`):i.title=n.entry.rel),i.addEventListener(`click`,()=>{o=r,n.kind===`folder`?l(n.path):t.open(n.entry)}),e.list.appendChild(i)});let d=r.length,f=a.filter(e=>e.kind===`scene`).length;e.count.textContent=d===0?``:f===d?`${d}`:`${f} / ${d}`,e.path.placeholder=bz(a[o]),e.list.querySelector(`.active`)?.scrollIntoView({block:`nearest`})},l=e=>{i.has(e)?i.delete(e):i.add(e),c()},u=e=>{a.length!==0&&(o=Math.min(a.length-1,Math.max(0,o+e)),c())};return e.search.addEventListener(`input`,()=>{o=0,c()}),e.search.addEventListener(`keydown`,e=>{let n=a[o];switch(e.key){case`ArrowDown`:e.preventDefault(),u(1);return;case`ArrowUp`:e.preventDefault(),u(-1);return;case`ArrowRight`:n?.kind===`folder`&&!n.open&&(e.preventDefault(),l(n.path));return;case`ArrowLeft`:n?.kind===`folder`&&n.open&&(e.preventDefault(),l(n.path));return;case`Enter`:e.preventDefault(),n?.kind===`folder`?l(n.path):n&&t.open(n.entry);return;default:}}),{async refresh(){try{r=await t.entries()}catch(t){r=[],e.list.textContent=``;let n=document.createElement(`div`);n.className=`scene-empty`,n.textContent=`could not list scenes: ${t instanceof Error?t.message:String(t)}`,e.list.appendChild(n),e.count.textContent=``;return}if(i.size===0)i=_z(r,t.current());else for(let e of hz(t.current()))i.add(e);s=!0,c(),e.search.focus(),e.search.select()}}}var Cz=`
8424
8424
  <header id="topbar">
8425
8425
  <div class="brand">
8426
8426
  <span class="brand-mark">in</span>
@@ -8584,7 +8584,7 @@ registerBehavior('MyBehavior', MyBehavior); // before loadScene()
8584
8584
  </div>
8585
8585
  </div>
8586
8586
  <div id="popover" hidden></div>
8587
- `;function Sz(e,t){let n=[String(e.name??``)],r=e;for(let e of t){let t=r.children?.[e];if(!t)return n;n.push(String(t.name??``)),r=t}return n}function Cz(e,t,n,r){if(e===``||e===`.`)return null;let i=n[n.length-1];if(i===void 0||i===r)return null;if(e.startsWith(`%`))return e.slice(1)===i?`%${r}`:null;let a=e.startsWith(`/`),o=(a?e.slice(1):e).split(`/`);if(o.some(e=>e===``))return null;let s,c=0;if(a)s=0;else{let e=0;for(;o[e]===`..`;)e++;if(c=e,s=t.length-e,s<0)return null}let l=[...t.slice(0,s),...o.slice(c)],u=a&&o[0]===`root`&&t[0]!==`root`;u&&(l[0]=t[0]??``);let d=n.length-1;for(let e=0;e<=d;e++)if(l[e]!==n[e])return null;let f=d-s+c;if(f<c||f>=o.length||u&&f===0)return null;let p=[...o];return p[f]=r,(a?`/`:``)+p.join(`/`)}function wz(e){let t=[],n=e=>{for(let[n,r]of Object.entries(e))r?.nodePath&&t.push(n)},r=typeof e.type==`string`?e.type:``;if(r)try{n(qe(r))}catch{}let i=e.script;return typeof i?.name==`string`&&n(ot(i.name)),t}function Tz(e,t,n){let r=e.root;if(!r||t.length===0)return r&&t.length===0?Ez(e,r,n):[];let i=Sz(r,t),a=Dz(r,t);if(!a)return[];let o=Oz(e,r,i,n);return a.name=n,o}function Ez(e,t,n){let r=Oz(e,t,[String(t.name??``)],n);return t.name=n,r}function Dz(e,t){let n=e;for(let e of t)if(n=n?.children?.[e],!n)return null;return n??null}function Oz(e,t,n,r){let i=[],a=String(t.name??``),o=e.connections;Array.isArray(o)&&o.forEach((e,t)=>{let o=e;for(let e of[`from`,`to`]){let s=o[e];if(typeof s!=`string`)continue;let c=Cz(s,[a],n,r);c!==null&&(o[e]=c,i.push({where:`connections[${t}].${e}`,from:s,to:c}))}});let s=(a,o)=>{let c=a.props;if(c)for(let s of wz(a)){let a=c[s],l=`${o.join(`/`)}.${s}`;if(typeof a==`string`){let e=Cz(a,o,n,r);e!==null&&(c[s]=e,i.push({where:l,from:a,to:e}))}else Array.isArray(a)?a.forEach((e,t)=>{if(typeof e!=`string`)return;let s=Cz(e,o,n,r);s!==null&&(a[t]=s,i.push({where:`${l}[${t}]`,from:e,to:s}))}):yn(a)&&kz(e,t,a,n,r,l,i)}let l=a.children??[];for(let e of l)s(e,[...o,String(e.name??``)])};return s(t,[a]),i}function kz(e,t,n,r,i,a,o){let s=n[`@const`];if(typeof s!=`string`)return;let c=e.constants,l=c?.[s];if(typeof l!=`string`||!l.startsWith(`%`)&&!l.startsWith(`/`))return;let u=Cz(l,[String(t.name??``)],r,i);u!==null&&(c[s]=u,o.push({where:`constants.${s} (${a})`,from:l,to:u}))}var Az=class{working;selection=[];extra=[];validator=null;selectedAsset=null;selectedGroup=null;pendingGroups=new Set;pendingLivePatch=null;addingAsset=!1;addingGroup=!1;newAssetGroup=``;newGroupParent=``;startAddingAsset(){this.addingAsset=!0,this.addingGroup=!1,this.newAssetGroup=this.selectedGroup??``,this.clearFocus()}startAddingGroup(){this.addingGroup=!0,this.addingAsset=!1,this.newGroupParent=this.selectedGroup??``,this.clearFocus()}cancelAddForms(){this.addingAsset=!1,this.addingGroup=!1}onError=null;original;undoStack=[];listeners=new Set;constructor(e){this.working=e,this.original=JSON.stringify(e),this.working.root&&jz(this.working.root)}get dirty(){return JSON.stringify(this.working)!==this.original}get canUndo(){return this.undoStack.length>0}nodeAt(e){if(e===null)return null;let t=this.working.root;for(let n of e)t=t?.children?.[n];return t??null}parentOf(e){return e.length===0?null:this.nodeAt(e.slice(0,-1))}mutate(e,t,n){(!n?.coalesce||this.undoStack.length===0)&&(this.undoStack.push(JSON.stringify(this.working)),this.undoStack.length>100&&this.undoStack.shift()),e(),this.pendingLivePatch=t??null,this.emit()}undo(){let e=this.undoStack.pop();e!==void 0&&(this.working=JSON.parse(e),this.selection=[],this.emit())}transact(e){let t=JSON.stringify(this.working),n=e(),r=e=>(this.working=JSON.parse(t),e&&this.onError?.(e),null);if(n===null)return r();let i=this.validator?.(this.working)??null;return i&&i!==this.priorError(t)?r(i):(this.undoStack.push(t),this.undoStack.length>100&&this.undoStack.shift(),this.emit(),n)}renameNode(e,t){let n=this.nodeAt(e);if(!n)return null;let r=this.parentOf(e),i=r?Bz(r,t,n):t;return i===n.name?[]:this.transact(()=>Tz(this.working,e,i))}priorError(e){if(!this.validator)return null;try{return this.validator(JSON.parse(e))}catch{return null}}moveNode(e,t,n){return this.moveNodes([e],t,n)?.[0]??null}moveNodes(e,t,n){let r=Iz(e).filter(e=>e.length>0);if(r.length===0)return null;for(let e of r)if(e.length<=t.length&&e.every((e,n)=>e===t[n]))return null;let i=this.working.root,a=r.map(e=>this.nodeAt(e)).filter(e=>e!==null);if(a.length!==r.length)return null;let o=this.nodeAt(t);return!o||a.includes(o)?null:this.transact(()=>{for(let e of a)Rz(i,e);let e,t;if(n===`into`)e=o,e.children||=[],t=e.children.length;else{let r=Lz(i,o);if(!r)return null;e=r.parent,t=r.index+ +(n===`after`)}let r=[];a.forEach((n,r)=>{n.name=Bz(e,n.name??`Node`),e.children?.splice(t+r,0,n)});for(let e of a){let t=zz(i,e);if(!t)return null;r.push(t)}return r})}duplicateNode(e){if(e.length===0)return null;let t=this.nodeAt(e),n=this.parentOf(e);return!t||!n?.children?null:this.transact(()=>{let r=JSON.parse(JSON.stringify(t));r.name=Bz(n,t.name??`Node`),Mz(r);let i=e[e.length-1]+1;return n.children?.splice(i,0,r),[...e.slice(0,-1),i]})}removeNodes(e){let t=Iz(e).filter(e=>e.length>0);if(t.length===0)return!1;let n=this.working.root,r=t.map(e=>this.nodeAt(e)).filter(e=>e!==null);return this.transact(()=>{for(let e of r)Rz(n,e);return!0})===!0}deleteRoot(){this.undoStack.push(JSON.stringify(this.working)),delete this.working.root,this.selection=null,this.extra=[],this.emit()}insertNode(e,t){if(!this.working.root){let t=JSON.parse(JSON.stringify(e));return Mz(t),this.transact(()=>(this.working.root=t,[]))}let n=this.nodeAt(t);return n?this.transact(()=>{let r=JSON.parse(JSON.stringify(e));return r.name=Bz(n,r.name??`Node`),Mz(r),n.children||=[],n.children.push(r),[...t,n.children.length-1]}):null}findRemovalReferences(e){let t=Iz(e).filter(e=>e.length>0),n=this.working.root,r=t.map(e=>this.nodeAt(e)).filter(e=>e!==null),i=new Set,a=[];for(let e of t){let t=[],r=n;for(let n of e){let e=r.children?.[n];if(!e)break;t.push(String(e.name)),r=e}a.push(t.join(`/`))}let o=e=>{typeof e.uid==`string`&&i.add(e.uid);for(let t of e.children??[])o(t)};for(let e of r)o(e);let s=[];if((this.working.connections??[]).forEach((e,t)=>{for(let n of[`from`,`to`]){let r=String(e[n]??``);if(a.some(e=>r===e||r.startsWith(`${e}/`))){s.push({kind:`connection`,where:`connections[${t}] ${String(e.signal)}: ${String(e.from)} → ${String(e.to)}`,connectionIndex:t});return}}}),i.size>0){let e=(t,n,a)=>{if(typeof t==`string`){!a&&i.has(t)&&s.push({kind:`uid`,where:n,value:t});return}if(Array.isArray(t)){t.forEach((t,r)=>{e(t,`${n}[${r}]`,a)});return}if(typeof t==`object`&&t){let i=t,o=a||r.includes(i),s=typeof i.name==`string`&&(i.type||i.children||i.instance)?n?`${n} › ${i.name}`:String(i.name):n;for(let[n,r]of Object.entries(t))n!==`uid`&&e(r,n===`children`||n===`root`?s:`${s?`${s}.`:``}${n}`,o)}};e(this.working,``,!1)}return s}removeNodesUnlinking(e){let t=this.findRemovalReferences(e),n=Iz(e).filter(e=>e.length>0),r=this.working.root,i=n.map(e=>this.nodeAt(e)).filter(e=>e!==null),a=new Set(t.filter(e=>e.kind===`uid`).map(e=>e.value)),o=new Set(t.filter(e=>e.kind===`connection`).map(e=>e.connectionIndex));return this.transact(()=>{o.size>0&&(this.working.connections=(this.working.connections??[]).filter((e,t)=>!o.has(t))),a.size>0&&Nz(this.working,a,i);for(let e of i)Rz(r,e);return!0})===!0}reset(e){this.working=e,this.original=JSON.stringify(e),this.working.root&&jz(this.working.root),this.undoStack=[],this.selection=[],this.emit()}markSaved(){this.original=JSON.stringify(this.working),this.emit()}emitChange(){this.emit()}clearFocus(){this.selection=null,this.extra=[],this.selectedAsset=null,this.selectedGroup=null,this.emit()}selectAsset(e){this.selectedAsset=e,e!==null&&(this.cancelAddForms(),this.selectedGroup=null,this.selection=null,this.extra=[]),this.emit()}selectGroup(e){this.selectedGroup=e,e!==null&&(this.cancelAddForms(),this.selectedAsset=null,this.selection=null,this.extra=[]),this.emit()}assetMap(){return this.working.assets??{}}groupCount(e){return Object.keys(this.assetMap()).filter(t=>t.startsWith(`${e}/`)).length}addGroup(e){this.pendingGroups.add(e),this.selectGroup(e)}renameGroup(e,t){if(!t||t===e)return!1;let n=this.assetMap(),r=Object.keys(n).filter(t=>t.startsWith(`${e}/`));return this.pendingGroups.delete(e)&&this.pendingGroups.add(t),this.selectedGroup=t,this.mutate(()=>{for(let i of r){let r=`${t}/${i.slice(e.length+1)}`;n[r]=n[i],delete n[i],Pz(this.working,`$${i}`,`$${r}`)}}),r.length===0&&this.emit(),!0}moveGroup(e,t){if(t===e||t.startsWith(`${e}/`))return!1;let n=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,r=t?`${t}/${n}`:n;return r===e?!1:this.renameGroup(e,r)}renameAssetKey(e,t){let n=this.assetMap();return!(e in n)||!t||t===e||t in n?!1:(this.selectedAsset=t,this.mutate(()=>{n[t]=n[e],delete n[e],Pz(this.working,`$${e}`,`$${t}`)}),!0)}deleteGroup(e){let t=this.assetMap(),n=Object.keys(t).filter(t=>t.startsWith(`${e}/`));n.length>0&&this.mutate(()=>{for(let e of n)delete t[e];Object.keys(t).length===0&&delete this.working.assets}),this.pendingGroups.delete(e),this.selectedGroup===e&&(this.selectedGroup=null),this.emit()}moveAsset(e,t){let n=this.assetMap();if(!(e in n))return!1;let r=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,i=t?`${t}/${r}`:r;if(i===e)return!1;for(;i in n;)i=`${i}2`;return this.renameAssetKey(e,i)}select(e,t){if(this.cancelAddForms(),this.selectedAsset=null,this.selectedGroup=null,t?.toggle&&e!==null){let t=e.join(`.`);this.selection!==null&&this.selection.join(`.`)===t?this.selection=this.extra.shift()??this.selection:this.extra.some(e=>e.join(`.`)===t)?this.extra=this.extra.filter(e=>e.join(`.`)!==t):this.selection===null?this.selection=e:this.extra.push(e)}else this.selection=e,this.extra=[];this.emit()}allSelections(){return[...this.selection===null?[]:[this.selection,...this.extra]].sort(Fz)}isSelected(e){let t=e.join(`.`);return this.selection!==null&&this.selection.join(`.`)===t||this.extra.some(e=>e.join(`.`)===t)}onChange(e){this.listeners.add(e)}emit(){for(let e of this.listeners)e()}};function jz(e){(typeof e.uid!=`string`||e.uid===``)&&(e.uid=Zn());for(let t of e.children??[])jz(t)}function Mz(e){e.uid=Zn();for(let t of e.children??[])Mz(t)}function Nz(e,t,n){if(Array.isArray(e)){for(let r=e.length-1;r>=0;r--)typeof e[r]==`string`&&t.has(e[r])?e.splice(r,1):Nz(e[r],t,n);return}if(typeof e==`object`&&e){if(n.includes(e))return;for(let[r,i]of Object.entries(e))r!==`uid`&&(typeof i==`string`&&t.has(i)?delete e[r]:Nz(i,t,n))}}function Pz(e,t,n){if(Array.isArray(e)){e.forEach((r,i)=>{r===t?e[i]=n:Pz(r,t,n)});return}if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))i===t?e[r]=n:Pz(i,t,n)}function Fz(e,t){for(let n=0;n<Math.min(e.length,t.length);n++)if(e[n]!==t[n])return e[n]-t[n];return e.length-t.length}function Iz(e){let t=[...e].sort(Fz),n=[];for(let e of t)n.some(t=>t.length<=e.length&&t.every((t,n)=>t===e[n]))||n.push(e);return n}function Lz(e,t){let n=e.children?.indexOf(t)??-1;if(n>=0)return{parent:e,index:n};for(let n of e.children??[]){let e=Lz(n,t);if(e)return e}return null}function Rz(e,t){let n=Lz(e,t);n?.parent.children?.splice(n.index,1)}function zz(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=zz(r,t);if(e)return[n,...e]}return null}function Bz(e,t,n){let r=new Set((e.children??[]).filter(e=>e!==n).map(e=>e.name));if(!r.has(t))return t;let i=2;for(;r.has(`${t}${i}`);)i+=1;return`${t}${i}`}var Vz=`
8587
+ `;function wz(e,t){let n=[String(e.name??``)],r=e;for(let e of t){let t=r.children?.[e];if(!t)return n;n.push(String(t.name??``)),r=t}return n}function Tz(e,t,n,r){if(e===``||e===`.`)return null;let i=n[n.length-1];if(i===void 0||i===r)return null;if(e.startsWith(`%`))return e.slice(1)===i?`%${r}`:null;let a=e.startsWith(`/`),o=(a?e.slice(1):e).split(`/`);if(o.some(e=>e===``))return null;let s,c=0;if(a)s=0;else{let e=0;for(;o[e]===`..`;)e++;if(c=e,s=t.length-e,s<0)return null}let l=[...t.slice(0,s),...o.slice(c)],u=a&&o[0]===`root`&&t[0]!==`root`;u&&(l[0]=t[0]??``);let d=n.length-1;for(let e=0;e<=d;e++)if(l[e]!==n[e])return null;let f=d-s+c;if(f<c||f>=o.length||u&&f===0)return null;let p=[...o];return p[f]=r,(a?`/`:``)+p.join(`/`)}function Ez(e){let t=[],n=e=>{for(let[n,r]of Object.entries(e))r?.nodePath&&t.push(n)},r=typeof e.type==`string`?e.type:``;if(r)try{n(qe(r))}catch{}let i=e.script;return typeof i?.name==`string`&&n(ot(i.name)),t}function Dz(e,t,n){let r=e.root;if(!r||t.length===0)return r&&t.length===0?Oz(e,r,n):[];let i=wz(r,t),a=kz(r,t);if(!a)return[];let o=Az(e,r,i,n);return a.name=n,o}function Oz(e,t,n){let r=Az(e,t,[String(t.name??``)],n);return t.name=n,r}function kz(e,t){let n=e;for(let e of t)if(n=n?.children?.[e],!n)return null;return n??null}function Az(e,t,n,r){let i=[],a=String(t.name??``),o=e.connections;Array.isArray(o)&&o.forEach((e,t)=>{let o=e;for(let e of[`from`,`to`]){let s=o[e];if(typeof s!=`string`)continue;let c=Tz(s,[a],n,r);c!==null&&(o[e]=c,i.push({where:`connections[${t}].${e}`,from:s,to:c}))}});let s=(a,o)=>{let c=a.props;if(c)for(let s of Ez(a)){let a=c[s],l=`${o.join(`/`)}.${s}`;if(typeof a==`string`){let e=Tz(a,o,n,r);e!==null&&(c[s]=e,i.push({where:l,from:a,to:e}))}else Array.isArray(a)?a.forEach((e,t)=>{if(typeof e!=`string`)return;let s=Tz(e,o,n,r);s!==null&&(a[t]=s,i.push({where:`${l}[${t}]`,from:e,to:s}))}):yn(a)&&jz(e,t,a,n,r,l,i)}let l=a.children??[];for(let e of l)s(e,[...o,String(e.name??``)])};return s(t,[a]),i}function jz(e,t,n,r,i,a,o){let s=n[`@const`];if(typeof s!=`string`)return;let c=e.constants,l=c?.[s];if(typeof l!=`string`||!l.startsWith(`%`)&&!l.startsWith(`/`))return;let u=Tz(l,[String(t.name??``)],r,i);u!==null&&(c[s]=u,o.push({where:`constants.${s} (${a})`,from:l,to:u}))}var Mz=class{working;selection=[];extra=[];validator=null;selectedAsset=null;selectedGroup=null;pendingGroups=new Set;pendingLivePatch=null;addingAsset=!1;addingGroup=!1;newAssetGroup=``;newGroupParent=``;startAddingAsset(){this.addingAsset=!0,this.addingGroup=!1,this.newAssetGroup=this.selectedGroup??``,this.clearFocus()}startAddingGroup(){this.addingGroup=!0,this.addingAsset=!1,this.newGroupParent=this.selectedGroup??``,this.clearFocus()}cancelAddForms(){this.addingAsset=!1,this.addingGroup=!1}onError=null;original;undoStack=[];listeners=new Set;constructor(e){this.working=e,this.original=JSON.stringify(e),this.working.root&&Nz(this.working.root)}get dirty(){return JSON.stringify(this.working)!==this.original}get canUndo(){return this.undoStack.length>0}nodeAt(e){if(e===null)return null;let t=this.working.root;for(let n of e)t=t?.children?.[n];return t??null}parentOf(e){return e.length===0?null:this.nodeAt(e.slice(0,-1))}mutate(e,t,n){(!n?.coalesce||this.undoStack.length===0)&&(this.undoStack.push(JSON.stringify(this.working)),this.undoStack.length>100&&this.undoStack.shift()),e(),this.pendingLivePatch=t??null,this.emit()}undo(){let e=this.undoStack.pop();e!==void 0&&(this.working=JSON.parse(e),this.selection=[],this.emit())}transact(e){let t=JSON.stringify(this.working),n=e(),r=e=>(this.working=JSON.parse(t),e&&this.onError?.(e),null);if(n===null)return r();let i=this.validator?.(this.working)??null;return i&&i!==this.priorError(t)?r(i):(this.undoStack.push(t),this.undoStack.length>100&&this.undoStack.shift(),this.emit(),n)}renameNode(e,t){let n=this.nodeAt(e);if(!n)return null;let r=this.parentOf(e),i=r?Hz(r,t,n):t;return i===n.name?[]:this.transact(()=>Dz(this.working,e,i))}priorError(e){if(!this.validator)return null;try{return this.validator(JSON.parse(e))}catch{return null}}moveNode(e,t,n){return this.moveNodes([e],t,n)?.[0]??null}moveNodes(e,t,n){let r=Rz(e).filter(e=>e.length>0);if(r.length===0)return null;for(let e of r)if(e.length<=t.length&&e.every((e,n)=>e===t[n]))return null;let i=this.working.root,a=r.map(e=>this.nodeAt(e)).filter(e=>e!==null);if(a.length!==r.length)return null;let o=this.nodeAt(t);return!o||a.includes(o)?null:this.transact(()=>{for(let e of a)Bz(i,e);let e,t;if(n===`into`)e=o,e.children||=[],t=e.children.length;else{let r=zz(i,o);if(!r)return null;e=r.parent,t=r.index+ +(n===`after`)}let r=[];a.forEach((n,r)=>{n.name=Hz(e,n.name??`Node`),e.children?.splice(t+r,0,n)});for(let e of a){let t=Vz(i,e);if(!t)return null;r.push(t)}return r})}duplicateNode(e){if(e.length===0)return null;let t=this.nodeAt(e),n=this.parentOf(e);return!t||!n?.children?null:this.transact(()=>{let r=JSON.parse(JSON.stringify(t));r.name=Hz(n,t.name??`Node`),Pz(r);let i=e[e.length-1]+1;return n.children?.splice(i,0,r),[...e.slice(0,-1),i]})}removeNodes(e){let t=Rz(e).filter(e=>e.length>0);if(t.length===0)return!1;let n=this.working.root,r=t.map(e=>this.nodeAt(e)).filter(e=>e!==null);return this.transact(()=>{for(let e of r)Bz(n,e);return!0})===!0}deleteRoot(){this.undoStack.push(JSON.stringify(this.working)),delete this.working.root,this.selection=null,this.extra=[],this.emit()}insertNode(e,t){if(!this.working.root){let t=JSON.parse(JSON.stringify(e));return Pz(t),this.transact(()=>(this.working.root=t,[]))}let n=this.nodeAt(t);return n?this.transact(()=>{let r=JSON.parse(JSON.stringify(e));return r.name=Hz(n,r.name??`Node`),Pz(r),n.children||=[],n.children.push(r),[...t,n.children.length-1]}):null}findRemovalReferences(e){let t=Rz(e).filter(e=>e.length>0),n=this.working.root,r=t.map(e=>this.nodeAt(e)).filter(e=>e!==null),i=new Set,a=[];for(let e of t){let t=[],r=n;for(let n of e){let e=r.children?.[n];if(!e)break;t.push(String(e.name)),r=e}a.push(t.join(`/`))}let o=e=>{typeof e.uid==`string`&&i.add(e.uid);for(let t of e.children??[])o(t)};for(let e of r)o(e);let s=[];if((this.working.connections??[]).forEach((e,t)=>{for(let n of[`from`,`to`]){let r=String(e[n]??``);if(a.some(e=>r===e||r.startsWith(`${e}/`))){s.push({kind:`connection`,where:`connections[${t}] ${String(e.signal)}: ${String(e.from)} → ${String(e.to)}`,connectionIndex:t});return}}}),i.size>0){let e=(t,n,a)=>{if(typeof t==`string`){!a&&i.has(t)&&s.push({kind:`uid`,where:n,value:t});return}if(Array.isArray(t)){t.forEach((t,r)=>{e(t,`${n}[${r}]`,a)});return}if(typeof t==`object`&&t){let i=t,o=a||r.includes(i),s=typeof i.name==`string`&&(i.type||i.children||i.instance)?n?`${n} › ${i.name}`:String(i.name):n;for(let[n,r]of Object.entries(t))n!==`uid`&&e(r,n===`children`||n===`root`?s:`${s?`${s}.`:``}${n}`,o)}};e(this.working,``,!1)}return s}removeNodesUnlinking(e){let t=this.findRemovalReferences(e),n=Rz(e).filter(e=>e.length>0),r=this.working.root,i=n.map(e=>this.nodeAt(e)).filter(e=>e!==null),a=new Set(t.filter(e=>e.kind===`uid`).map(e=>e.value)),o=new Set(t.filter(e=>e.kind===`connection`).map(e=>e.connectionIndex));return this.transact(()=>{o.size>0&&(this.working.connections=(this.working.connections??[]).filter((e,t)=>!o.has(t))),a.size>0&&Fz(this.working,a,i);for(let e of i)Bz(r,e);return!0})===!0}reset(e){this.working=e,this.original=JSON.stringify(e),this.working.root&&Nz(this.working.root),this.undoStack=[],this.selection=[],this.emit()}markSaved(){this.original=JSON.stringify(this.working),this.emit()}emitChange(){this.emit()}clearFocus(){this.selection=null,this.extra=[],this.selectedAsset=null,this.selectedGroup=null,this.emit()}selectAsset(e){this.selectedAsset=e,e!==null&&(this.cancelAddForms(),this.selectedGroup=null,this.selection=null,this.extra=[]),this.emit()}selectGroup(e){this.selectedGroup=e,e!==null&&(this.cancelAddForms(),this.selectedAsset=null,this.selection=null,this.extra=[]),this.emit()}assetMap(){return this.working.assets??{}}groupCount(e){return Object.keys(this.assetMap()).filter(t=>t.startsWith(`${e}/`)).length}addGroup(e){this.pendingGroups.add(e),this.selectGroup(e)}renameGroup(e,t){if(!t||t===e)return!1;let n=this.assetMap(),r=Object.keys(n).filter(t=>t.startsWith(`${e}/`));return this.pendingGroups.delete(e)&&this.pendingGroups.add(t),this.selectedGroup=t,this.mutate(()=>{for(let i of r){let r=`${t}/${i.slice(e.length+1)}`;n[r]=n[i],delete n[i],Iz(this.working,`$${i}`,`$${r}`)}}),r.length===0&&this.emit(),!0}moveGroup(e,t){if(t===e||t.startsWith(`${e}/`))return!1;let n=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,r=t?`${t}/${n}`:n;return r===e?!1:this.renameGroup(e,r)}renameAssetKey(e,t){let n=this.assetMap();return!(e in n)||!t||t===e||t in n?!1:(this.selectedAsset=t,this.mutate(()=>{n[t]=n[e],delete n[e],Iz(this.working,`$${e}`,`$${t}`)}),!0)}deleteGroup(e){let t=this.assetMap(),n=Object.keys(t).filter(t=>t.startsWith(`${e}/`));n.length>0&&this.mutate(()=>{for(let e of n)delete t[e];Object.keys(t).length===0&&delete this.working.assets}),this.pendingGroups.delete(e),this.selectedGroup===e&&(this.selectedGroup=null),this.emit()}moveAsset(e,t){let n=this.assetMap();if(!(e in n))return!1;let r=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,i=t?`${t}/${r}`:r;if(i===e)return!1;for(;i in n;)i=`${i}2`;return this.renameAssetKey(e,i)}select(e,t){if(this.cancelAddForms(),this.selectedAsset=null,this.selectedGroup=null,t?.toggle&&e!==null){let t=e.join(`.`);this.selection!==null&&this.selection.join(`.`)===t?this.selection=this.extra.shift()??this.selection:this.extra.some(e=>e.join(`.`)===t)?this.extra=this.extra.filter(e=>e.join(`.`)!==t):this.selection===null?this.selection=e:this.extra.push(e)}else this.selection=e,this.extra=[];this.emit()}allSelections(){return[...this.selection===null?[]:[this.selection,...this.extra]].sort(Lz)}isSelected(e){let t=e.join(`.`);return this.selection!==null&&this.selection.join(`.`)===t||this.extra.some(e=>e.join(`.`)===t)}onChange(e){this.listeners.add(e)}emit(){for(let e of this.listeners)e()}};function Nz(e){(typeof e.uid!=`string`||e.uid===``)&&(e.uid=Zn());for(let t of e.children??[])Nz(t)}function Pz(e){e.uid=Zn();for(let t of e.children??[])Pz(t)}function Fz(e,t,n){if(Array.isArray(e)){for(let r=e.length-1;r>=0;r--)typeof e[r]==`string`&&t.has(e[r])?e.splice(r,1):Fz(e[r],t,n);return}if(typeof e==`object`&&e){if(n.includes(e))return;for(let[r,i]of Object.entries(e))r!==`uid`&&(typeof i==`string`&&t.has(i)?delete e[r]:Fz(i,t,n))}}function Iz(e,t,n){if(Array.isArray(e)){e.forEach((r,i)=>{r===t?e[i]=n:Iz(r,t,n)});return}if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))i===t?e[r]=n:Iz(i,t,n)}function Lz(e,t){for(let n=0;n<Math.min(e.length,t.length);n++)if(e[n]!==t[n])return e[n]-t[n];return e.length-t.length}function Rz(e){let t=[...e].sort(Lz),n=[];for(let e of t)n.some(t=>t.length<=e.length&&t.every((t,n)=>t===e[n]))||n.push(e);return n}function zz(e,t){let n=e.children?.indexOf(t)??-1;if(n>=0)return{parent:e,index:n};for(let n of e.children??[]){let e=zz(n,t);if(e)return e}return null}function Bz(e,t){let n=zz(e,t);n?.parent.children?.splice(n.index,1)}function Vz(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=Vz(r,t);if(e)return[n,...e]}return null}function Hz(e,t,n){let r=new Set((e.children??[]).filter(e=>e!==n).map(e=>e.name));if(!r.has(t))return t;let i=2;for(;r.has(`${t}${i}`);)i+=1;return`${t}${i}`}var Uz=`
8588
8588
  /* ─── incanto editor · design system ──────────────────────────────────────── */
8589
8589
  :root {
8590
8590
  --bg-0: #0b0d14;
@@ -9342,6 +9342,11 @@ button.asset-option small {
9342
9342
  position: fixed;
9343
9343
  z-index: 50;
9344
9344
  width: 300px;
9345
+ /* A topic longer than the window still has to be readable to the end: the
9346
+ positioner pins it to the top and this lets the rest scroll. */
9347
+ max-height: calc(100vh - 16px);
9348
+ overflow-y: auto;
9349
+ overscroll-behavior: contain;
9345
9350
  background: var(--bg-3);
9346
9351
  border: 1px solid var(--line-strong);
9347
9352
  border-radius: var(--r-md);
@@ -10770,4 +10775,4 @@ body.playing #gameview-btn {
10770
10775
  opacity: 0.4;
10771
10776
  cursor: default;
10772
10777
  }
10773
- `,Hz=new Map(IF.flatMap(e=>e.nodes.map(e=>[e.type,e.summary]))),Uz=new Set,Wz=null,Gz=null,Kz=null;function qz(e){Gz=e}function Jz(e){Wz=e}function Yz(e){Kz=e}var Xz=null,Zz=null,Qz=null;function $z(e){return e?e.includes(`Body`)||e.includes(`Area`)||e.includes(`Controller`)?`cat-body`:e===`NetworkSpawner`?`cat-net`:e.endsWith(`3D`)?`cat-3d`:e.endsWith(`2D`)||e===`Label`||e===`UILayer`?`cat-2d`:`cat-core`:`cat-core`}function eB(e,t){e.textContent=``;let n=document.createElement(`div`);n.className=`tree-row scene-row${t.selection===null&&t.selectedAsset===null&&t.selectedGroup===null&&!t.addingAsset&&!t.addingGroup?` selected`:``}`,n.textContent=`⚙ ${String(t.working.name??`scene`)}`,n.addEventListener(`click`,()=>t.select(null)),e.appendChild(n);let r=t.working.root;if(!r){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no root node — pick a type below and + to start the scene`,e.appendChild(t);return}iB(r,t.selection),e.appendChild(aB(r,[],t,``)),nB(e,t.selection)}var tB=null;function nB(e,t){let n=JSON.stringify(t);n!==tB&&(tB=n,e.querySelector(`.tree-row.selected`)?.scrollIntoView?.({block:`nearest`,inline:`nearest`}))}function rB(){tB=null}function iB(e,t){if(!t)return;let n=e,r=``;for(let e of t){r=r?`${r}/${n.name}`:String(n.name),Uz.delete(r);let t=n.children?.[e];if(!t)return;n=t}}function aB(e,t,n,r){let i=r?`${r}/${e.name}`:String(e.name),a=(e.children?.length??0)>0,o=Uz.has(i),s=document.createElement(`div`);s.className=`tree-branch`;let c=document.createElement(`div`);c.className=`tree-row${n.isSelected(t)?` selected`:``}`,c.draggable=t.length>0&&Qz!==i;let l=document.createElement(`span`);l.className=`chevron${a?``:` leaf`}${o?` collapsed`:``}`,a?l.appendChild(QP()):l.textContent=`·`,a&&l.addEventListener(`click`,e=>{e.stopPropagation(),o?Uz.delete(i):Uz.add(i),n.select(n.selection)});let u=document.createElement(`span`);if(u.className=`tree-icon ${$z(e.type)}`,u.appendChild(ZP(e.type)),u.title=e.type??`instance`,u.addEventListener(`click`,t=>{t.stopPropagation(),oB(u,e.type??`instance`)}),c.append(l,u),Qz===i){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e.name??``;let i=()=>{Qz=null;let i=r.value.trim();if(i&&i!==e.name){let e=n.renameNode(t,i)??[];e.length>0&&Kz?.(e)}else n.select(n.selection)};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`&&i(),e.key===`Escape`&&(Qz=null,n.select(n.selection))});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());r.addEventListener(`blur`,i),c.appendChild(r),queueMicrotask(()=>{r.focus(),r.select()})}else{let r=document.createElement(`span`);r.className=`tree-name`,r.textContent=e.name??`(unnamed)`,r.addEventListener(`dblclick`,e=>{e.stopPropagation(),Qz=i,n.select(t)}),c.appendChild(r)}if(c.addEventListener(`click`,e=>{a&&!e.metaKey&&!e.ctrlKey&&(o?Uz.delete(i):Uz.add(i)),n.select(t,{toggle:e.metaKey||e.ctrlKey})}),c.addEventListener(`contextmenu`,e=>{e.preventDefault(),n.isSelected(t)||n.select(t),sB(e.clientX,e.clientY,n,t,i)}),gB(c,t,n),s.appendChild(c),a&&!o){let r=document.createElement(`div`);r.className=`tree-children`,(e.children??[]).forEach((e,a)=>{r.appendChild(aB(e,[...t,a],n,i))}),s.appendChild(r)}return s}function oB(e,t){fB();let n=document.createElement(`div`);n.className=`balloon floating`;let r=document.createElement(`span`);r.className=`balloon-title`,r.textContent=t,n.appendChild(r);let i=Hz.get(t);if(i){let e=document.createElement(`span`);e.textContent=JP(i),n.appendChild(e)}document.body.appendChild(n);let a=e.getBoundingClientRect();n.style.left=`${Math.min(innerWidth-240,a.right+8)}px`,n.style.top=`${Math.max(8,a.top-6)}px`,pB(n)}function sB(e,t,n,r,i){fB();let a=n.allSelections(),o=a.length===1&&r.length>0,s=document.createElement(`div`);s.className=`context-menu floating`;let c=(e,t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item${n?.danger?` danger`:``}`,r.disabled=t===null;let i=document.createElement(`span`);if(i.textContent=e,r.appendChild(i),n?.kbd){let e=document.createElement(`kbd`);e.textContent=n.kbd,r.appendChild(e)}t&&r.addEventListener(`click`,()=>{fB(),t()}),s.appendChild(r)};c(`duplicate${a.length>1?` ×${a.length}`:``}`,()=>{for(let e of[...a].reverse())n.duplicateNode(e)}),c(`frame in view`,Gz&&r.length>0?()=>{n.select(r),Gz?.()}:null,{kbd:`F`}),c(`rename`,o?()=>{Qz=i,n.select(r)}:null,{kbd:`dbl-click`}),s.appendChild(cB()),c(`cut`,r.length>0?()=>lB(n,!0):null),c(`copy`,r.length>0?()=>lB(n,!1):null),c(`paste as child${Zz?` (${Zz.nodes.length})`:``}`,Zz?()=>uB(n,r):null),s.appendChild(cB()),c(`delete`,r.length>0?()=>(Wz??(e=>n.removeNodes(e)))(a):null,{danger:!0}),document.body.appendChild(s),s.style.left=`${Math.min(innerWidth-200-8,e)}px`,s.style.top=`${Math.min(innerHeight-s.offsetHeight-8,t)}px`,pB(s)}function cB(){let e=document.createElement(`div`);return e.className=`menu-divider`,e}function lB(e,t){let n=e.allSelections().filter(e=>e.length>0).map(t=>e.nodeAt(t)).filter(e=>e!==null);Zz={nodes:n.map(e=>JSON.parse(JSON.stringify(e))),cut:t?n:null}}function uB(e,t){if(Zz){for(let n of Zz.nodes)e.insertNode(n,t);if(Zz.cut){let t=e.working.root,n=Zz.cut.map(e=>dB(t,e)).filter(e=>e!==null);n.length>0&&e.removeNodes(n),Zz={nodes:Zz.nodes,cut:null}}}}function dB(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=dB(r,t);if(e)return[n,...e]}return null}function fB(){for(let e of document.querySelectorAll(`.floating`))e.remove()}function pB(e){let t=r=>{e.contains(r.target)||(e.remove(),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,n,!0))},n=r=>{r.key===`Escape`&&(e.remove(),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,n,!0))};setTimeout(()=>{document.addEventListener(`pointerdown`,t,!0),document.addEventListener(`keydown`,n,!0)},0)}function mB(e,t){let n=t.getBoundingClientRect(),r=(e.clientY-n.top)/n.height;return r<.25?`before`:r>.75?`after`:`into`}function hB(e){e.classList.remove(`drop-into`,`drop-before`,`drop-after`)}function gB(e,t,n){e.addEventListener(`dragstart`,r=>{Xz=n.isSelected(t)?n.allSelections():[t],r.dataTransfer?.setData(`text/plain`,``),r.dataTransfer&&(r.dataTransfer.effectAllowed=`move`),e.classList.add(`dragging`)}),e.addEventListener(`dragend`,()=>{Xz=null,e.classList.remove(`dragging`)}),e.addEventListener(`dragover`,n=>{if(!Xz||Xz.some(e=>e.length<=t.length&&e.every((e,n)=>e===t[n])))return;n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=`move`),hB(e);let r=t.length===0?`into`:mB(n,e);e.classList.add(`drop-${r}`)}),e.addEventListener(`dragleave`,()=>hB(e)),e.addEventListener(`drop`,r=>{if(hB(e),!Xz)return;r.preventDefault();let i=t.length===0?`into`:mB(r,e),a=n.moveNodes(Xz,t,i);Xz=null,a?.[0]&&n.select(a[0])})}var _B={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`};function vB(e,t,n){let r=t-e.origin.x,i=n-e.origin.y;if(Math.abs(r)<=e.centerSize&&Math.abs(i)<=e.centerSize)return{kind:`center`};for(let t of e.axes){let e=t.sx*t.sx+t.sy*t.sy;if(e<1)continue;let n=Math.max(0,Math.min(1,(r*t.sx+i*t.sy)/e)),a=r-t.sx*n,o=i-t.sy*n;if(n>.25&&Math.hypot(a,o)<=8)return{kind:`axis`,axis:t.axis}}return null}function yB(e,t,n){let r=e.sx*e.sx+e.sy*e.sy;return r<1?0:(t*e.sx+n*e.sy)/r*e.worldPerUnit}function bB(e,t,n,r=!1){let{origin:i,axes:a,centerSize:o}=t;for(let t of a){let a=n?.kind===`axis`&&n.axis===t.axis;e.strokeStyle=t.color,e.fillStyle=t.color,e.globalAlpha=a?1:.9,e.lineWidth=a?3:2,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x+t.sx,i.y+t.sy),e.stroke();let o=Math.hypot(t.sx,t.sy)||1,s=t.sx/o,c=t.sy/o,l=i.x+t.sx,u=i.y+t.sy;e.beginPath(),r?e.rect(l-5,u-5,10,10):(e.moveTo(l+s*9,u+c*9),e.lineTo(l-c*4.5,u+s*4.5),e.lineTo(l+c*4.5,u-s*4.5),e.closePath()),e.fill(),e.font=`700 9px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(t.axis.toUpperCase(),l+s*18,u+c*18)}let s=n?.kind===`center`;e.globalAlpha=s?1:.95,e.fillStyle=s?`#ffffff`:`#e2e6f0`,e.strokeStyle=`#0b0d14`,e.lineWidth=1.5,e.beginPath(),e.rect(i.x-o,i.y-o,o*2,o*2),e.fill(),e.stroke(),e.globalAlpha=1}function xB(e,t,n){return Math.atan2(n-e.y,t-e.x)*180/Math.PI}function SB(e,t){let n=t-e;for(;n>180;)n-=360;for(;n<=-180;)n+=360;return n}function CB(e,t,n,r){let i=null,a=r;for(let r of e)for(let e of r.points){let o=Math.hypot(t-e.x,n-e.y);o<a&&(a=o,i=r.axis)}return i}function wB(e,t,n){for(let r of t){if(r.points.length<2)continue;let t=n===r.axis;e.strokeStyle=_B[r.axis],e.globalAlpha=t?1:.75,e.lineWidth=t?3:2,e.beginPath();let i=r.points[0];e.moveTo(i.x,i.y);for(let t of r.points.slice(1))e.lineTo(t.x,t.y);e.closePath(),e.stroke()}e.globalAlpha=1}function TB(e,t,n,r){e.font=`600 11px ui-monospace, Menlo, monospace`;let i=e.measureText(r).width+14;e.fillStyle=`rgba(16, 19, 29, 0.92)`,e.strokeStyle=`rgba(110, 231, 220, 0.5)`,e.lineWidth=1,e.beginPath(),e.roundRect(t+14,n-26,i,20,5),e.fill(),e.stroke(),e.fillStyle=`#6ee7dc`,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(r,t+21,n-16)}var EB=class{engine;editCanvas;overlay;playCanvas;cb;editUiHost=null;playUiHost=null;renderer2d=null;renderer3d=null;rendererDim=null;orbit={yaw:.6,pitch:.35,dist:10,target:[0,1,0]};pathOf=new Map;reindexNeeded=!1;nodeAtPath=new Map;selectedPath=null;paintHandler=null;extraPaths=[];hoveredNode=null;hoveredGizmo=null;lastGood=null;lastAppliedKey=null;playEngine=null;playRenderer=null;playPhysics=null;setPaintHandler(e){this.paintHandler=e}get playing(){return this.playEngine!==null}constructor(e,t,n,r){this.editCanvas=e,this.overlay=t,this.playCanvas=n,this.cb=r;let i=this;this.engine=new Et({scheduler:e=>{let t=0,n=performance.now(),r=requestAnimationFrame(function a(o){t+=.001;let s=Math.min(.1,(o-n)/1e3);n=o;try{e(t),i.tickAmbientPreviews(s)}catch(e){console.error(`incanto-editor viewport:`,e)}r=requestAnimationFrame(a)});return()=>cancelAnimationFrame(r)}}),this.editUiHost=this.makeUiHost(e.parentElement,4),this.playUiHost=this.makeUiHost(n.parentElement,5),this.engine.uiHost=this.editUiHost,this.engine.start(),this.engine.updated.connect(()=>this.drawOverlay());let a=e=>{e.key===`Shift`&&(this.shiftHeld=!0)},o=e=>{e.key===`Shift`&&(this.shiftHeld=!1)};window.addEventListener(`keydown`,a),window.addEventListener(`keyup`,o),this.cleanups.push(()=>{window.removeEventListener(`keydown`,a),window.removeEventListener(`keyup`,o)}),this.bindPointer()}cleanups=[];makeUiHost(e,t){if(!e)return null;let n=document.createElement(`div`);return n.style.cssText=`position:absolute;inset:0;pointer-events:none;z-index:${t};`,e.appendChild(n),this.cleanups.push(()=>n.remove()),n}dispose(){this.stop(),this.editPhysics?.dispose(),this.editPhysics=null,this.engine.stop(),this.engine.dispose(),this.renderer2d?.dispose(),this.renderer3d?.dispose(),this.renderer2d=null,this.renderer3d=null;for(let e of this.cleanups.splice(0))e()}setEditCamera(e,t){let n=(e[0]??0)-(t[0]??0),r=(e[1]??0)-(t[1]??0),i=(e[2]??0)-(t[2]??0),a=Math.hypot(n,r,i);a>.01&&(this.orbit.target=[t[0]??0,t[1]??0,t[2]??0],this.orbit.dist=Math.min(800,Math.max(.3,a)),this.orbit.yaw=Math.atan2(n,i),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,r/a))),this.syncOrbit())}editCamera(){let{pos:e}=this.orbitVectors();return{position:[e.x,e.y,e.z],target:[...this.orbit.target]}}apply(e){e.root||(e={...e,root:{name:`__empty`,type:(e.dimension??`2d`)===`3d`?`Node3D`:`Node2D`}});let t=JSON.stringify(e);if(t===this.lastAppliedKey&&this.rendererDim===(e.dimension??`2d`))return null;let n;try{let t=structuredClone(e);UB(t),n=kn(t,{stubAllBehaviors:!0})}catch(e){return e instanceof Error?e.message:String(e)}this.lastGood=e,this.lastAppliedKey=t;let r=e.dimension??`2d`;if(this.rendererDim!==r){if(this.renderer2d?.dispose(),this.renderer3d?.dispose(),this.renderer2d=null,this.renderer3d=null,r===`2d`)this.renderer2d=new Kv({canvas:this.editCanvas,engine:this.engine}),this.renderer2d.ignoreStatic=!0,this.renderer2d.viewOverride=this.defaultView(e);else{this.renderer3d=new gP({canvas:this.editCanvas,engine:this.engine}),this.renderer3d.ignoreStatic=!0;let t=zB(e.root);if(t){let[e,n,r]=t;this.orbit.dist=Math.max(2,Math.hypot(e,n,r)),this.orbit.yaw=Math.atan2(e,r),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,n/this.orbit.dist))),this.orbit.target=[0,Math.min(2,Math.abs(n)/2),0]}this.syncOrbit()}this.rendererDim=r}return this.engine.setScene(n),this.indexTree(n.root),this.hoveredNode=null,null}setSelection(e,t=[]){this.selectedPath=e,this.extraPaths=t}validate(e){if(!e.root)return null;try{let t=structuredClone(e);return UB(t),kn(t,{stubAllBehaviors:!0}),null}catch(e){return e instanceof Error?e.message:String(e)}}defaultView(e){let t=BB(e.root);if(t)return{cx:t[0],cy:t[1],zoom:1};let n=this.editCanvas.clientWidth||960,r=this.editCanvas.clientHeight||540;return{cx:n/2,cy:r/2,zoom:1}}indexTree(e){this.pathOf=new Map,this.nodeAtPath=new Map;let t=(e,n)=>{this.pathOf.set(e,n),this.nodeAtPath.set(n.join(`.`),e),e.children.forEach((e,r)=>{t(e,[...n,r])})};t(e,[])}liveSelected(){return this.selectedPath===null?null:this.nodeAtPath.get(this.selectedPath.join(`.`))??null}patchProp(e,t,n,r){if(this.playing)return!1;let i=this.nodeAtPath.get(t.join(`.`));if(!i)return!1;try{i[n]=r===void 0?void 0:structuredClone(r)}catch{return!1}return this.reindexNeeded=!0,this.lastAppliedKey=JSON.stringify(e),!0}gizmoActive=null;gizmoMode=`move`;activeRing=null;readout=null;cancelActiveDrag=()=>{};shiftHeld=!1;get showColliders(){return this.collidersOn}set showColliders(e){this.collidersOn=e,this.editPhysics&&(this.editPhysics.debugDraw=e),e&&this.ensureOutlinePhysics()}collidersOn=!0;editPhysics=null;outlinePending=null;async ensureOutlinePhysics(){if(this.editPhysics||this.outlinePending)return this.outlinePending??void 0;let e=this.rendererDim;if(e)return this.outlinePending=(async()=>{try{if(e===`2d`){let{enablePhysics2D:e}=await ym(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>iy);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(this.engine,{simulate:!1});t.debugDraw=this.collidersOn,this.editPhysics=t}else{let{enablePhysics3D:e}=await ym(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>MP);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(this.engine,{simulate:!1});t.debugDraw=this.collidersOn,this.editPhysics=t}}catch(e){console.warn(`[incanto] collider outlines unavailable:`,e)}finally{this.outlinePending=null}})(),this.outlinePending}get mode(){return this.gizmoMode}setMode(e){this.gizmoMode=e,this.cb.onModeChanged(e)}gizmoLayout(){let e=this.liveSelected();if(!e)return null;if(this.rendererDim===`2d`&&this.renderer2d){let t=e.position;if(!Array.isArray(t))return null;let n=RB(e),r=this.renderer2d.screenFromWorld(n.x,n.y),i=this.renderer2d.view().zoom;return{origin:r,centerSize:7,axes:[{axis:`x`,sx:64,sy:0,worldPerUnit:64/i,color:_B.x},{axis:`y`,sx:0,sy:64,worldPerUnit:64/i,color:_B.y}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D,n=e.position;if(!t||!Array.isArray(n))return null;t.getWorldPosition(MB);let r=this.renderer3d.screenFromWorld(MB.x,MB.y,MB.z);if(r.behind)return null;let i=[],a=this.orbit.dist,o=Math.max(.2,a*.18);for(let[e,t]of[[`x`,[1,0,0]],[`y`,[0,1,0]],[`z`,[0,0,1]]]){let n=this.renderer3d.screenFromWorld(MB.x+t[0]*o,MB.y+t[1]*o,MB.z+t[2]*o);n.behind||i.push({axis:e,sx:n.x-r.x,sy:n.y-r.y,worldPerUnit:o,color:_B[e]})}return{origin:{x:r.x,y:r.y},centerSize:7,axes:i}}return null}ringLayout(){let e=this.liveSelected();if(!e)return null;if(this.rendererDim===`2d`&&this.renderer2d){let t=RB(e),n=this.renderer2d.screenFromWorld(t.x,t.y),r=[];for(let e=0;e<48;e++){let t=e/48*Math.PI*2;r.push({x:n.x+56*Math.cos(t),y:n.y+56*Math.sin(t)})}return{origin:n,rings:[{axis:`z`,points:r}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D;if(!t)return null;t.getWorldPosition(MB);let n={x:MB.x,y:MB.y,z:MB.z},r=this.renderer3d.screenFromWorld(n.x,n.y,n.z);if(r.behind)return null;let i=Math.max(.2,this.orbit.dist*.16),a=[];for(let e of[`x`,`y`,`z`]){let t=[];for(let r=0;r<48;r++){let a=r/48*Math.PI*2,o=Math.cos(a)*i,s=Math.sin(a)*i,c=e===`x`?this.renderer3d.screenFromWorld(n.x,n.y+o,n.z+s):e===`y`?this.renderer3d.screenFromWorld(n.x+o,n.y,n.z+s):this.renderer3d.screenFromWorld(n.x+o,n.y+s,n.z);c.behind||t.push({x:c.x,y:c.y})}a.push({axis:e,points:t})}return{origin:{x:r.x,y:r.y},rings:a}}return null}orbitVectors(){let{yaw:e,pitch:t,dist:n,target:r}=this.orbit,i=Math.cos(t),a=new U(r[0]+n*i*Math.sin(e),r[1]+n*Math.sin(t),r[2]+n*i*Math.cos(e)),o=new U(r[0],r[1],r[2]).sub(a).normalize(),s=new U().crossVectors(o,OB).normalize();return{pos:a,right:s,up:new U().crossVectors(s,o).normalize(),forward:o}}syncOrbit(){if(!this.renderer3d)return;let{pos:e}=this.orbitVectors();this.renderer3d.viewOverride={position:[e.x,e.y,e.z],target:[...this.orbit.target]}}gameView(){if(this.rendererDim===`3d`&&this.renderer3d){let e=null;for(let[t]of this.pathOf)if(t instanceof BE&&(t.current||!e)&&(e=t,t.current))break;let t=e?e._ensureObject3D():null;if(t){t.getWorldPosition(kB),AB.set(0,0,-1).applyQuaternion(t.getWorldQuaternion(jB));let e=Math.min(40,Math.max(3,this.orbit.dist));this.orbit.target=[kB.x+AB.x*e,kB.y+AB.y*e,kB.z+AB.z*e],this.orbit.dist=e,this.orbit.yaw=Math.atan2(-AB.x,-AB.z),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,-AB.y)))}this.renderer3d.viewOverride=null;return}this.renderer2d&&(this.renderer2d.viewOverride=null)}snapView(e,t){e===`y`?(this.orbit.pitch=t*1.45,this.orbit.yaw=0):(this.orbit.pitch=0,this.orbit.yaw=e===`z`?t===1?0:Math.PI:Math.PI/2*t),this.syncOrbit()}gizmoCenter(){return{x:this.overlay.clientWidth-58,y:58,r:36}}gizmoHandles(){let{right:e,up:t,forward:n}=this.orbitVectors(),r=this.gizmoCenter(),i=[];for(let[a,o]of[[`x`,new U(1,0,0)],[`y`,new U(0,1,0)],[`z`,new U(0,0,1)]])for(let s of[1,-1]){let c=o.clone().multiplyScalar(s);i.push({axis:a,sign:s,x:r.x+c.dot(e)*26,y:r.y-c.dot(t)*26,z:-c.dot(n)})}return i.sort((e,t)=>e.z-t.z)}gizmoHit(e,t){let n=this.gizmoCenter();if(Math.hypot(e-n.x,t-n.y)>n.r+8)return null;let r=null,i=14;for(let n of this.gizmoHandles()){let a=Math.hypot(e-n.x,t-n.y);a<i&&(i=a,r={axis:n.axis,sign:n.sign})}return r??{axis:`z`,sign:1}}gizmoHandleAt(e,t){let n=this.gizmoCenter();if(Math.hypot(e-n.x,t-n.y)>n.r+8)return null;let r=null,i=12;for(let n of this.gizmoHandles()){let a=Math.hypot(e-n.x,t-n.y);a<i&&(i=a,r={axis:n.axis,sign:n.sign})}return r}tickAmbientPreviews(e){if(!this.playing)for(let[t]of this.pathOf)(t instanceof Jk||t instanceof wv||t instanceof Zk||t instanceof mg||t instanceof yk)&&t.update(e)}modelAnimationsAt(e){let t=this.nodeAtPath.get(e.join(`.`));return t instanceof Jk?t.availableAnimations():[]}boneNamesAt(e,t){let n=this.nodeAtPath.get(e.join(`.`));if(!n||t===``)return[];let r=n.getNodeOrNull(t);return r instanceof Jk?r.boneNames():[]}drawOverlay(){if(this.reindexNeeded){this.reindexNeeded=!1;let e=this.engine.scene?.tree.root;e&&this.indexTree(e)}let e=this.overlay.getContext(`2d`);if(!e)return;let t=this.overlay.clientWidth,n=this.overlay.clientHeight,r=Math.min(devicePixelRatio||1,2);if((this.overlay.width!==t*r||this.overlay.height!==n*r)&&(this.overlay.width=t*r,this.overlay.height=n*r),e.setTransform(r,0,0,r,0,0),e.clearRect(0,0,t,n),this.playing)return;if(this.rendererDim===`3d`){this.drawGizmo(e),this.drawModeGizmo(e),this.readout&&TB(e,this.readout.x,this.readout.y,this.readout.text);return}if(!this.renderer2d)return;if(this.drawAxes2D(e),this.hoveredNode&&this.hoveredNode!==this.liveSelected()){let t=this.renderer2d.boundsOf(this.hoveredNode);t&&(e.strokeStyle=`rgba(110, 231, 220, 0.45)`,e.lineWidth=1.5,e.setLineDash([]),e.strokeRect(t.x,t.y,t.w,t.h))}for(let t of this.extraPaths){let n=this.nodeAtPath.get(t.join(`.`)),r=n?this.renderer2d.boundsOf(n):null;r&&(e.strokeStyle=`rgba(110, 231, 220, 0.7)`,e.lineWidth=1.5,e.setLineDash([4,3]),e.strokeRect(r.x-2,r.y-2,r.w+4,r.h+4),e.setLineDash([]))}let i=this.liveSelected();if(i){let t=this.renderer2d.boundsOf(i)??this.pointBounds(i);if(t){e.strokeStyle=`#6ee7dc`,e.lineWidth=2,e.setLineDash([6,4]),e.lineDashOffset=-(performance.now()/50%10),e.strokeRect(t.x-2,t.y-2,t.w+4,t.h+4),e.setLineDash([]),e.fillStyle=`#6ee7dc`;for(let[n,r]of[[t.x-2,t.y-2],[t.x+t.w+2,t.y-2],[t.x-2,t.y+t.h+2],[t.x+t.w+2,t.y+t.h+2]])e.fillRect(n-3,r-3,6,6)}}this.drawModeGizmo(e),this.readout&&TB(e,this.readout.x,this.readout.y,this.readout.text)}drawModeGizmo(e){if(this.gizmoMode===`rotate`){let t=this.ringLayout();t&&wB(e,t.rings,this.activeRing);return}let t=this.gizmoLayout();t&&bB(e,t,this.gizmoActive,this.gizmoMode===`scale`)}pointBounds(e){if(!this.renderer2d)return null;let t=e.position;if(!Array.isArray(t))return null;let n=RB(e),r=this.renderer2d.screenFromWorld(n.x,n.y);return{x:r.x-12,y:r.y-12,w:24,h:24}}drawGizmo(e){let t=this.gizmoCenter();e.beginPath(),e.arc(t.x,t.y,t.r,0,Math.PI*2),e.fillStyle=`rgba(16, 19, 29, 0.72)`,e.fill(),e.strokeStyle=`rgba(52, 60, 84, 0.9)`,e.lineWidth=1,e.stroke();let n={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`},r={x1:`right`,"x-1":`left`,y1:`top`,"y-1":`bottom`,z1:`front`,"z-1":`back`};for(let r of this.gizmoHandles()){let i=this.hoveredGizmo?.axis===r.axis&&this.hoveredGizmo?.sign===r.sign,a=n[r.axis],o=(r.z+1)/2;e.globalAlpha=i?1:.45+o*.55,e.strokeStyle=a,e.lineWidth=1.5,e.beginPath(),e.moveTo(t.x,t.y),e.lineTo(r.x,r.y),e.stroke(),e.beginPath(),e.arc(r.x,r.y,(r.sign===1?7:5)+(i?2:0),0,Math.PI*2),r.sign===1?(e.fillStyle=a,e.fill(),e.fillStyle=`#0b0d14`,e.font=`700 8px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(r.axis.toUpperCase(),r.x,r.y+.5)):(e.fillStyle=`rgba(16, 19, 29, 0.9)`,e.fill(),e.stroke())}if(e.globalAlpha=1,this.hoveredGizmo){let n=r[`${this.hoveredGizmo.axis}${this.hoveredGizmo.sign}`];e.fillStyle=`#9aa3bd`,e.font=`600 10px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(`${n} view`,t.x,t.y-t.r-6)}}drawAxes2D(e){let t=this.gizmoCenter();e.save(),e.shadowColor=`rgba(0, 0, 0, 0.25)`,e.shadowBlur=10,e.shadowOffsetY=2,e.beginPath(),e.arc(t.x,t.y,31,0,Math.PI*2),e.fillStyle=`rgba(13, 16, 24, 0.42)`,e.fill(),e.shadowColor=`transparent`,e.strokeStyle=`rgba(255, 255, 255, 0.16)`,e.lineWidth=1,e.stroke();let n=t.x-9,r=t.y-9;e.lineCap=`round`;let i=(t,i,a,o)=>{let s=n+t*21,c=r+i*21,l=e.createLinearGradient(n,r,s,c);l.addColorStop(0,`${a}55`),l.addColorStop(1,a),e.strokeStyle=l,e.lineWidth=2,e.beginPath(),e.moveTo(n,r),e.lineTo(s,c),e.stroke(),e.beginPath(),e.arc(s,c,6.5,0,Math.PI*2),e.fillStyle=a,e.fill(),e.font=`800 8px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#0b0d14`,e.fillText(o,s,c+.5)};i(1,0,`#fb7185`,`X`),i(0,1,`#86efac`,`Y`),e.beginPath(),e.arc(n,r,2.5,0,Math.PI*2),e.fillStyle=`#e2e6f0`,e.fill(),e.restore()}bindPointer(){let e=this.overlay,t=null,n=null,r=!1,i=null,a=null,o=null,s=null,c=null,l=t=>{let n=this.ringLayout();if(!n)return!1;let r=CB(n.rings,t.offsetX,t.offsetY,9);if(!r)return!1;let i=this.liveSelected();if(!i)return!1;e.setPointerCapture(t.pointerId);let a=i.rotation,o=1;if(this.rendererDim===`3d`&&this.renderer3d){let{forward:e}=this.renderer3d.cameraBasis();o=(r===`x`?e.x:r===`y`?e.y:e.z)>0?1:-1}return c={axis:r,node:i,origin:n.origin,startAngle:xB(n.origin,t.offsetX,t.offsetY),startRotation:Array.isArray(a)?[...a]:a??0,sign:o},this.activeRing=r,!0},u=e=>{if(!c)return;let{axis:t,node:n,origin:r,startAngle:i,startRotation:a,sign:o}=c,s=SB(i,xB(r,e.offsetX,e.offsetY))*o,l=e.shiftKey||this.shiftHeld?15:null,u=e=>{let t=e+s;return l?Math.round(t/l)*l:Math.round(t*10)/10},d;if(Array.isArray(a)){let e={x:0,y:1,z:2}[t],r=[...a];r[e]=u(a[e]??0),d=r[e],n.rotation=r}else{let e=u(a);d=e,n.rotation=e}this.readout={x:e.offsetX,y:e.offsetY,text:`${d}°${l?` ⌁15°`:``}`}},d=e=>{if(!c)return;let{node:t,startRotation:n}=c;if(!e)t.rotation=n;else{let e=this.pathOf.get(t),n=t.rotation;e!==void 0&&n!==void 0&&(Array.isArray(n)?this.cb.onNodeRotated3D(e,[n[0]??0,n[1]??0,n[2]??0]):this.cb.onNodeRotated2D(e,n))}c=null,this.activeRing=null,this.readout=null};this.cancelActiveDrag=()=>{d(!1),s&&(s.node.position=s.startPos,s.node.scale=s.startScale,s=null,this.gizmoActive=null,this.readout=null)};let f=t=>{if(this.gizmoMode===`rotate`)return l(t);let n=this.gizmoLayout();if(!n)return!1;let r=vB(n,t.offsetX,t.offsetY);if(!r)return!1;let i=this.liveSelected();if(!i)return!1;e.setPointerCapture(t.pointerId);let a=[...i.position??[]],o=[...i.scale??[]];return s={hit:r,mode:this.gizmoMode===`scale`||t.button===2?`scale`:`move`,startX:t.offsetX,startY:t.offsetY,layout:n,node:i,startPos:a,startScale:o},this.gizmoActive=r,!0},p=e=>{if(!s)return;let{hit:t,mode:n,layout:r,node:i,startPos:a,startScale:o}=s,c=e.offsetX-s.startX,l=e.offsetY-s.startY,u=this.rendererDim===`3d`,d={x:0,y:1,z:2},f=e.shiftKey||this.shiftHeld,p=f?u?.5:10:null,m=f?.25:null,h=e=>p?Math.round(e/p)*p:e,g=e=>m?Math.max(m,Math.round(e/m)*m):e;if(n===`scale`){let n=Math.max(.05,1+(c-l)*.005),r=[...o];if(t.kind===`axis`)r[d[t.axis]]=DB(g((o[d[t.axis]]??1)*n));else for(let e=0;e<r.length;e++)r[e]=DB(g((o[e]??1)*n));i.scale=r,this.readout={x:e.offsetX,y:e.offsetY,text:`×${r.map(e=>DB(e)).join(`, `)}`};return}let _=[...a];if(t.kind===`axis`){let e=r.axes.find(e=>e.axis===t.axis);if(!e)return;let n=yB(e,c,l);if(u)_[d[t.axis]]=DB(h((a[d[t.axis]]??0)+n));else{let e=IB(i,t.axis===`x`?n:0,t.axis===`y`?n:0),r=t.axis===`x`?e.x:e.y;_[d[t.axis]]=Math.round(h((a[d[t.axis]]??0)+r))}}else if(u&&this.renderer3d){let{right:e,up:t}=this.renderer3d.cameraBasis(),n=this.orbit.dist*.0016;_[0]=DB(h((a[0]??0)+(e.x*c-t.x*l)*n)),_[1]=DB(h((a[1]??0)+(e.y*c-t.y*l)*n)),_[2]=DB(h((a[2]??0)+(e.z*c-t.z*l)*n))}else if(this.renderer2d){let e=this.renderer2d.view(),t=IB(i,c/e.zoom,l/e.zoom);_[0]=Math.round(h((a[0]??0)+t.x)),_[1]=Math.round(h((a[1]??0)+t.y))}i.position=_,this.readout={x:e.offsetX,y:e.offsetY,text:`[${_.map(e=>DB(e)).join(`, `)}]`}},m=()=>{if(!s)return;let{node:e,mode:t}=s,n=this.pathOf.get(e);if(n)if(t===`scale`){let t=e.scale??[];this.rendererDim===`3d`?this.cb.onNodeScaled3D(n,[t[0]??1,t[1]??1,t[2]??1]):this.cb.onNodeScaled(n,[t[0]??1,t[1]??1])}else{let t=e.position??[];this.rendererDim===`3d`?this.cb.onNodeMoved3D(n,[t[0]??0,t[1]??0,t[2]??0]):this.cb.onNodeMoved(n,[t[0]??0,t[1]??0])}s=null,this.gizmoActive=null};e.addEventListener(`pointerdown`,s=>{if(this.playing||f(s))return;if(this.rendererDim===`3d`){let t=this.gizmoHit(s.offsetX,s.offsetY);if(t){this.snapView(t.axis,t.sign);return}e.setPointerCapture(s.pointerId),s.button===1||s.button===2||s.shiftKey?a={x:s.offsetX,y:s.offsetY,target:[...this.orbit.target]}:(i={x:s.offsetX,y:s.offsetY,yaw:this.orbit.yaw,pitch:this.orbit.pitch},o={x:s.offsetX,y:s.offsetY,toggle:s.ctrlKey||s.metaKey});return}if(!this.renderer2d)return;if(e.setPointerCapture(s.pointerId),s.button===1||s.button===2||s.shiftKey){let e=this.renderer2d.view();n={startX:s.offsetX,startY:s.offsetY,cx:e.cx,cy:e.cy};return}if(this.paintHandler&&s.button===0){let e=this.renderer2d.worldFromScreen(s.offsetX,s.offsetY);this.paintHandler(e.x,e.y,!0),r=!0;return}let c=this.renderer2d.pick(s.offsetX,s.offsetY),l=c?this.pathOf.get(c)??null:null;if(this.cb.onPick(l,{toggle:s.ctrlKey||s.metaKey}),this.selectedPath=l,c&&l&&Array.isArray(c.position)){let e=c.position;t={node:c,startWorld:this.renderer2d.worldFromScreen(s.offsetX,s.offsetY),startPos:[e[0]??0,e[1]??0]}}}),e.addEventListener(`pointermove`,o=>{if(!this.playing){if(c){u(o);return}if(s){p(o);return}if(this.rendererDim===`3d`){if(!i&&!a?(this.hoveredGizmo=this.gizmoHandleAt(o.offsetX,o.offsetY),e.style.cursor=this.hoveredGizmo?`pointer`:`grab`):e.style.cursor=`grabbing`,i)this.orbit.yaw=i.yaw-(o.offsetX-i.x)*.006,this.orbit.pitch=Math.max(-1.5,Math.min(1.5,i.pitch+(o.offsetY-i.y)*.006)),this.syncOrbit();else if(a){let{right:e,up:t}=this.orbitVectors(),n=this.orbit.dist*.0016,r=(o.offsetX-a.x)*n,i=(o.offsetY-a.y)*n;this.orbit.target=[a.target[0]-e.x*r+t.x*i,a.target[1]-e.y*r+t.y*i,a.target[2]-e.z*r+t.z*i],this.syncOrbit()}return}if(this.renderer2d){if(e.style.cursor=`crosshair`,r&&this.paintHandler){let e=this.renderer2d.worldFromScreen(o.offsetX,o.offsetY);this.paintHandler(e.x,e.y,!1);return}if(n){let e=this.renderer2d.view();this.renderer2d.viewOverride={cx:n.cx-(o.offsetX-n.startX)/e.zoom,cy:n.cy-(o.offsetY-n.startY)/e.zoom,zoom:e.zoom};return}if(t){let e=this.renderer2d.worldFromScreen(o.offsetX,o.offsetY),n=IB(t.node,e.x-t.startWorld.x,e.y-t.startWorld.y),r=Math.round(t.startPos[0]+n.x),i=Math.round(t.startPos[1]+n.y);t.node.position=[r,i];return}this.hoveredNode=this.renderer2d.pick(o.offsetX,o.offsetY)}}});let h=e=>{if(r=!1,d(!0),m(),this.readout=null,o&&e&&this.renderer3d&&Math.hypot(e.offsetX-o.x,e.offsetY-o.y)<4){let e=this.renderer3d.pick(o.x,o.y),t=e?this.pathOf.get(e)??null:null;t&&(this.cb.onPick(t,{toggle:o.toggle}),this.selectedPath=t)}if(o=null,i=null,a=null,t){let e=this.pathOf.get(t.node),n=t.node.position;e&&(n[0]!==t.startPos[0]||n[1]!==t.startPos[1])&&this.cb.onNodeMoved(e,[n[0]??0,n[1]??0]),t=null}n=null};e.addEventListener(`pointerup`,h),e.addEventListener(`pointercancel`,h),e.addEventListener(`contextmenu`,e=>e.preventDefault()),e.addEventListener(`dblclick`,e=>{if(this.playing)return;let t=this.rendererDim===`3d`?this.renderer3d?.pick(e.offsetX,e.offsetY)??null:this.renderer2d?.pick(e.offsetX,e.offsetY)??null,n=t?this.pathOf.get(t)??null:null;n&&(this.cb.onPick(n,{toggle:e.ctrlKey||e.metaKey}),this.selectedPath=n)}),e.addEventListener(`wheel`,e=>{if(this.playing)return;e.preventDefault();let t=e.deltaY<0?1.1:1/1.1;if(this.rendererDim===`3d`){this.orbit.dist=Math.max(.3,Math.min(800,this.orbit.dist/t)),this.syncOrbit();return}if(!this.renderer2d)return;let n=this.liveSelected();if(e.altKey&&n&&Array.isArray(n.scale)){let e=n.scale,r=[Math.round((e[0]??1)*t*100)/100,Math.round((e[1]??1)*t*100)/100];n.scale=r;let i=this.pathOf.get(n);i&&this.cb.onNodeScaled(i,r);return}let r=this.renderer2d.view(),i=this.renderer2d.worldFromScreen(e.offsetX,e.offsetY),a=Math.min(8,Math.max(.1,r.zoom*t));this.renderer2d.viewOverride={cx:i.x-(e.offsetX-r.w/2)/a,cy:i.y-(e.offsetY-r.h/2)/a,zoom:a}},{passive:!1})}zoomToFit(){let e=this.liveSelected();if(this.rendererDim===`3d`){let t=new Bo;for(let[n]of this.pathOf){if(e&&n!==e&&!LB(n,e))continue;let r=n._object3D;r&&(t.expandByObject(r),t.expandByPoint(r.getWorldPosition(MB)))}if(t.isEmpty()&&e){let t=e._object3D,n=t?t.getWorldPosition(MB):null;this.orbit.target=n?[n.x,n.y,n.z]:[0,1,0],this.orbit.dist=6}else if(t.isEmpty())this.orbit.target=[0,1,0],this.orbit.dist=10;else{let e=t.getCenter(new U),n=t.getSize(new U);this.orbit.target=[e.x,e.y,e.z],this.orbit.dist=Math.max(2.5,n.length()*.85)}this.syncOrbit();return}if(!this.renderer2d)return;let t=this.editCanvas.clientWidth||960,n=this.editCanvas.clientHeight||540,r=1/0,i=1/0,a=-1/0,o=-1/0;for(let[t]of this.pathOf){if(e&&t!==e&&!LB(t,e))continue;let n=t.position;if(!Array.isArray(n))continue;let s=RB(t);r=Math.min(r,s.x),i=Math.min(i,s.y),a=Math.max(a,s.x),o=Math.max(o,s.y)}if(!Number.isFinite(r))return;let s=(r+a)/2,c=(i+o)/2,l=e?600:200,u=Math.max(a-r+l,l),d=Math.max(o-i+l,l),f=Math.min(2,Math.min(t/u,n/d));this.renderer2d.viewOverride={cx:s,cy:c,zoom:f}}async play(e){if(this.playing)return null;let t=structuredClone(e);UB(t);let n;try{n=kn(t,{stubAllBehaviors:!0,declareConnectionSignals:!0})}catch(e){return e instanceof Error?e.message:String(e)}let r=new Et;r.uiHost=this.playUiHost,this.editUiHost&&(this.editUiHost.style.display=`none`),r.setScene(n),r.input.attachKeyboard(window),this.playCanvas.hidden=!1;let i=e.dimension??`2d`;try{if(i===`2d`){this.playRenderer=new Kv({canvas:this.playCanvas,engine:r});let{enablePhysics2D:e}=await ym(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>iy);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}else{this.playRenderer=new gP({canvas:this.playCanvas,engine:r,assets:this.renderer3d?.assets});let{enablePhysics3D:e}=await ym(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>MP);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}}catch(e){return this.stop(),e instanceof Error?e.message:String(e)}return r.start(),this.playEngine=r,this.cb.onPlayStateChanged(!0),null}stop(){this.playEngine?.input.dispose(),this.playEngine?.stop(),this.playEngine?.dispose(),this.playEngine=null,this.playPhysics?.dispose(),this.playPhysics=null,this.editUiHost&&(this.editUiHost.style.display=``),this.playRenderer?.dispose(),this.playRenderer=null,this.playCanvas.hidden=!0,this.cb.onPlayStateChanged(!1),this.lastAppliedKey=null,this.lastGood&&this.apply(this.lastGood)}};function DB(e){return Math.round(e*100)/100}var OB=new U(0,1,0),kB=new U,AB=new U,jB=new H,MB=new U,NB=new G,PB=new U,FB=new U;function IB(e,t,n){let r=e._object2D?.parent;return r?(NB.copy(r.matrixWorld).invert(),PB.set(t,-n,0).applyMatrix4(NB),FB.set(0,0,0).applyMatrix4(NB),{x:PB.x-FB.x,y:-(PB.y-FB.y)}):{x:t,y:n}}function LB(e,t){for(let n=e.parent;n;n=n.parent)if(n===t)return!0;return!1}function RB(e){let t=e._object2D;if(t)return t.getWorldPosition(MB),{x:MB.x,y:-MB.y};let n=0,r=0,i=e;for(;i;)Array.isArray(i.position)&&(n+=i.position[0]??0,r+=i.position[1]??0),i=i.parent;return{x:n,y:r}}function zB(e){if(!e)return null;if(e.type===`Camera3D`){let t=e.props?.position??[0,2,8];return[t[0]??0,t[1]??2,t[2]??8]}for(let t of e.children??[]){let e=zB(t);if(e)return e}return null}function BB(e){if(!e)return null;if(e.type===`Camera2D`){let t=e.props?.position??[0,0];return[t[0]??0,t[1]??0]}for(let t of e.children??[]){let e=BB(t);if(e)return e}return null}var VB=null;function HB(){if(VB)return VB;let e=document.createElement(`canvas`);e.width=16,e.height=16;let t=e.getContext(`2d`);for(let e=0;e<2;e++)for(let n=0;n<2;n++)t.fillStyle=(n+e)%2==0?`#c252c2`:`#2b2b3b`,t.fillRect(n*8,e*8,8,8);return VB=e.toDataURL(),VB}function UB(e){let t=e.assets;if(t)for(let e of Object.values(t))typeof e?.url==`string`&&!e.url.includes(`/`)&&!e.url.includes(`.`)&&(e.url=HB())}var WB=e({formatSceneJson:()=>r,httpEditorApi:()=>re,mountEditor:()=>GB});gn(),Pv(),GM(),HP(),H_();async function GB(e={}){let t=e.api??re,n=[],r=document.createElement(`style`);r.dataset.incantoEditor=`true`,r.textContent=Vz,document.head.appendChild(r),n.push(()=>r.remove());let i=document.createElement(`div`);i.className=`incanto-editor-root`,i.innerHTML=xz,(e.host??document.body).appendChild(i),n.push(()=>i.remove());let a=e=>{let t=i.querySelector(e);if(!t)throw Error(`missing ${e}`);return t},o=await t.meta();a(`#engine-version`).textContent=`incanto@${o.version}`,ML(a(`#popover`)),VF(),a(`#docs-btn`).addEventListener(`click`,()=>zF());let s=a(`#lang-btn`),c=[{code:`en`,label:`English`},{code:`ko`,label:`한국어`}],l=()=>{a(`#lang-current`).textContent=GP()===`ko`?`한국어`:`EN`};l(),s.addEventListener(`click`,()=>{document.querySelector(`.lang-menu`)?.remove();let e=document.createElement(`div`);e.className=`context-menu floating lang-menu`;for(let{code:t,label:n}of c){let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item`;let i=document.createElement(`span`);i.textContent=n;let a=document.createElement(`span`);a.textContent=GP()===t?`✓`:``,a.className=`lang-check`,r.append(i,a),r.addEventListener(`click`,()=>{e.remove(),KP(t)}),e.appendChild(r)}document.body.appendChild(e);let t=s.getBoundingClientRect();e.style.left=`${t.left}px`,e.style.top=`${t.bottom+6}px`;let n=t=>{e.contains(t.target)||t.target===s||(e.remove(),document.removeEventListener(`pointerdown`,n,!0))};setTimeout(()=>document.addEventListener(`pointerdown`,n,!0),0)}),qP(()=>{l(),HF(),u.select(u.selection)});let u=new Az({format:1,type:`scene`,name:``,root:null}),d=a(`#tree`),f=a(`#inspector`),p=a(`#save-btn`),m=a(`#undo-btn`),h=a(`#play-btn`),g=a(`#error-banner`),_=a(`#play-notice`),v=a(`#add-type`),y=a(`#picker`),b=a(`#picker-list`),x=a(`#scenes-btn`),S=o.input,C=o.output,w,T=!1,E=a(`#error-text`),D=e=>{g.hidden=!1,E.textContent=e,MF.error(e)},O=()=>{g.hidden=!0,E.textContent=``};a(`#error-close`).addEventListener(`click`,O);let k=a(`#edit-notice`),A=null,ee=e=>{k.hidden=!1,k.textContent=e,A&&clearTimeout(A),A=setTimeout(()=>{k.hidden=!0,k.textContent=``},6e3)},te={on:!1,brush:`0`},ne=e=>{let t=0,n=0,r=u.working.root,i=e=>{let r=e?.props?.position;Array.isArray(r)&&(t+=Number(r[0]??0),n+=Number(r[1]??0))};i(r);for(let t of e)r=r?.children?.[t],i(r);return{x:t,y:n}},j=!1,ie=(e,t,n=!0)=>{n&&(j=!1);let r=u.selection,i=u.nodeAt(r);if(!r||i?.type!==`TileMap2D`)return;let{cx:a,cy:o}=QL(ne(r),Number(i.props?.tileSize??32),e,t),s=i.props?.cells??[],c=$L(s,a,o,te.brush);!c||JSON.stringify(c)===JSON.stringify(s)||(u.mutate(()=>{i.props||={},i.props.cells=c},{path:r,key:`cells`,value:c},{coalesce:j}),j=!0)},ae=()=>{let e=u.nodeAt(u.selection);te.on&&e?.type!==`TileMap2D`&&(te.on=!1),M.setPaintHandler(te.on?ie:null)},M=new EB(a(`#viewport`),a(`#overlay`),a(`#play-canvas`),{onPick:(e,t)=>u.select(e??null,t),onNodeMoved:(e,t)=>me(e,`position`,t,[0,0]),onNodeScaled:(e,t)=>me(e,`scale`,t,[1,1]),onNodeMoved3D:(e,t)=>me(e,`position`,t,[0,0,0]),onNodeScaled3D:(e,t)=>me(e,`scale`,t,[1,1,1]),onNodeRotated2D:(e,t)=>pe(e,`rotation`,t,0),onNodeRotated3D:(e,t)=>me(e,`rotation`,t,[0,0,0]),onModeChanged:e=>{for(let t of[`move`,`rotate`,`scale`])a(`#tool-${t}`).classList.toggle(`active`,t===e)},onPlayStateChanged:e=>{document.body.classList.toggle(`playing`,e),n.push(()=>document.body.classList.remove(`playing`)),h.classList.toggle(`stop`,e),h.innerHTML=e?`<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12"/></svg> stop`:`<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg> play`,_.hidden=!e,e&&(_.textContent=`▶ simulating — physics + input live; game scripts run only in your real game. Esc or stop to return.`)},onError:D}),oe=Ke().sort(),se=``,ce=e=>{if(e===se)return;se=e,v.textContent=``;let t=e===`3d`?[`3D`,`3D Physics`,`Core`,`Network`,`2D`,`2D Physics`]:[`2D`,`2D Physics`,`Core`,`Network`,`3D`,`3D Physics`];for(let[e]of PF)t.includes(e)||t.push(e);for(let e of t){let t=PF.find(([t])=>t===e)?.[1];if(!t)continue;let n=document.createElement(`optgroup`);n.label=e;for(let e of oe.filter(t)){let t=document.createElement(`option`);t.value=e,t.textContent=e,n.appendChild(t)}n.children.length>0&&v.appendChild(n)}v.value=e===`3d`?`MeshInstance3D`:`Sprite2D`};ce(`2d`);let le=()=>{let e=u.selection??[];if(M.validate(u.working)!==null){for(let e of v.querySelectorAll(`option`))e.disabled=!1;return}for(let t of v.querySelectorAll(`option`)){let n=structuredClone(u.working),r=n.root;if(!n.root)n.root={name:`__probe`,type:t.value};else{for(let t of e)r=r?.children?.[t];if(!r)continue;r.children||=[],r.children.push({name:`__probe`,type:t.value})}t.disabled=M.validate(n)!==null}};v.addEventListener(`mousedown`,le),v.addEventListener(`focus`,le);let ue=t.library?e=>iz(t,{kind:e.kind,...e.target?{target:e.target}:{},...e.shelf?{shelf:e.shelf}:{},...e.assetType?{assetType:e.assetType}:{},...e.onProps?{onProps:e.onProps}:{},...e.asAsset?{onAsset:(e,t,n)=>YB(u,n,t)}:{}}):void 0,de=!1,fe=()=>{if(!T)return;eB(d,u),oF(a(`#asset-tree`),u),f.textContent=``,sF(f,u,Se,ue)||rR(f,u,{modelRefs:()=>qB(u,`model`),animationsForSelection:()=>u.selection?M.modelAnimationsAt(u.selection):[],bonesForSelection:e=>u.selection?M.boneNamesAt(u.selection,e):[],assetRefs:e=>JB(u,e),addAsset:(e,t)=>YB(u,e,t),...ue?{openLibrary:ue}:{},confirm:Se,paint:{active:()=>te.on,brush:()=>te.brush,toggle:()=>{te.on=!te.on,ae(),fe()},setBrush:e=>{te.brush=e,fe()}}}),ce(u.working.dimension??`2d`),a(`#hints`).hidden=(u.working.dimension??`2d`)===`3d`,a(`#hints-3d`).hidden=(u.working.dimension??`2d`)!==`3d`,M.setSelection(u.selection,u.extra),ae();let e=u.pendingLivePatch;if(u.pendingLivePatch=null,!M.playing)if(e&&M.patchProp(u.working,e.path,e.key,e.value))g.hidden=!0;else{let e=M.apply(u.working);g.hidden=e===null,e!==null&&D(e)}p.disabled=!u.dirty||!u.working.root,p.title=u.working.root?``:`Add a root node before saving`,m.disabled=!u.canUndo,u.dirty!==de&&(de=u.dirty,MF.change(u.dirty))};u.onChange(fe),u.validator=e=>M.validate(e),u.onError=D;let pe=(e,t,n,r)=>{let i=u.nodeAt(e);i&&u.mutate(()=>{i.props||={},n===r?(delete i.props[t],Object.keys(i.props).length===0&&delete i.props):i.props[t]=n},{path:e,key:t,value:n})},me=(e,t,n,r)=>{let i=u.nodeAt(e);i&&u.mutate(()=>{i.props||={},JSON.stringify(n)===JSON.stringify(r)?(delete i.props[t],Object.keys(i.props).length===0&&delete i.props):i.props[t]=n},{path:e,key:t,value:n})},he=async(e,n,r)=>{M.playing&&M.stop();let i=await t.loadScene(e);w=e,S=n,C=r,T=!0;let s=e??n;a(`#file-chip`).hidden=!s,a(`#file-path`).textContent=s??``,a(`#file-chip`).title=`input: ${n}\noutput: ${r}`,y.hidden=!0,O(),rB(),u.reset(i),o.mode===`project`&&n&&MF.open(n,r)},ge=bz({list:b,search:a(`#picker-search`),count:a(`#picker-count`),path:a(`#picker-path`)},{entries:async()=>t.scenes?await t.scenes():[],current:()=>w,open:e=>_e(e.rel,e.abs)}),_e=(e,t)=>{let n=()=>{he(e,t,t).catch(e=>D(e instanceof Error?e.message:String(e)))};if(!u.dirty||!u.canUndo){n();return}Se(`'${w??`This scene`}' has unsaved changes. Opening '${e}' discards them.`,`discard & open`,n)},ve=async()=>{y.hidden=!1,await ge.refresh()},ye=()=>{y.hidden=!0};if(a(`#picker-close`).addEventListener(`click`,ye),y.addEventListener(`pointerdown`,e=>{e.target===y&&ye()}),a(`#picker-create`).addEventListener(`click`,()=>{(async()=>{let e=a(`#picker-path`),n=(e.value.trim()||e.placeholder).trim();if(n)try{if(!t.createScene)return;let e=await t.createScene(n.endsWith(`.scene.json`)?n:`${n}.scene.json`);await he(e.rel,e.abs,e.abs)}catch(e){D(e instanceof Error?e.message:String(e))}})()}),o.mode===`project`&&t.scenes&&(x.hidden=!1,x.addEventListener(`click`,()=>void ve())),o.mode===`project`&&o.input===null)await he(void 0,``,``);else if(o.mode===`project`&&t.scenes){let e=await t.scenes(),n=e.length===1?e[0]:void 0;n?await he(n.rel,n.abs,n.abs):await ve()}else await he(void 0,o.input,o.output);a(`#add-btn`).addEventListener(`click`,()=>{let e=u.selection??[],t=v.value,n=u.insertNode({name:t,type:t},e);n&&u.select(n)});let N=a(`#generate`);EL(u),a(`#generate-btn`).addEventListener(`click`,()=>wL(u));let P=a(`#confirm`),F=e=>{if(u.selection===null&&e.length===0){D(`The scene itself cannot be deleted — it IS the file.`);return}if(e.length===0){let e=u.working.root;if(!e)return;let t=KB(e);Se(`This deletes the ROOT '${String(e.name??``)}'${t>0?` AND its ${t} descendant node${t===1?``:`s`}`:``} — the scene goes empty, and the next node you add becomes the new root.`,`delete root`,()=>u.deleteRoot());return}let t=e[0]?.slice(0,-1)??[],n=u.findRemovalReferences(e);if(n.length===0){let n=e.reduce((e,t)=>{let n=u.nodeAt(t);return e+(n?KB(n):0)},0);if(n>0){Se(`This deletes ${e.length>1?`${e.length} nodes`:`'${String(u.nodeAt(e[0]??[])?.name??``)}'`} AND ${n} descendant node${n===1?``:`s`}.`,`delete ${e.length+n} nodes`,()=>{u.removeNodes(e)&&u.select(t)});return}u.removeNodes(e)&&u.select(t);return}a(`#confirm-text`).textContent=`${n.length} reference${n.length>1?`s`:``} still point at the node(s) you are deleting. Unlink them and delete, or cancel.`;let r=a(`#confirm-list`);r.textContent=``;for(let e of n){let t=document.createElement(`div`);t.textContent=`${e.kind===`uid`?`◆ uid`:`⇄ connection`} ${e.where}`,r.appendChild(t)}a(`#confirm-title`).textContent=`still referenced`,a(`#confirm-delete`).textContent=`unlink & delete`,P.hidden=!1,be={selections:e,parentOfFirst:t}},be=null,xe=null;function Se(e,t,n){a(`#confirm-title`).textContent=`are you sure?`,a(`#confirm-text`).textContent=e,a(`#confirm-list`).textContent=``,a(`#confirm-delete`).textContent=t,xe=n,P.hidden=!1}function I(){P.hidden=!0,be=null,xe=null}a(`#confirm-close`).addEventListener(`click`,I),a(`#confirm-cancel`).addEventListener(`click`,I),P.addEventListener(`pointerdown`,e=>{e.target===P&&I()}),a(`#confirm-delete`).addEventListener(`click`,()=>{if(xe){xe(),I();return}be&&u.removeNodesUnlinking(be.selections)&&u.select(be.parentOfFirst),I()}),Jz(F),Yz(e=>{ee(`${JP({en:`Rename: repaired ${e.length} reference${e.length===1?``:`s`}`,ko:`이름 변경: 참조 ${e.length}건 수정`})} — ${e.map(e=>e.where).join(`, `)}`)}),a(`#asset-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),u.startAddingAsset()}),a(`#group-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),u.startAddingGroup()});for(let e of document.querySelectorAll(`.section-toggle`)){let t=e.dataset.section??``,n=document.querySelector(`[data-body="${t}"]`),r=`incanto-editor-section-${t}`,i=t=>{e.classList.toggle(`collapsed`,t),n&&(n.hidden=t),localStorage.setItem(r,t?`1`:``)};i(localStorage.getItem(r)===`1`),e.addEventListener(`click`,()=>i(!e.classList.contains(`collapsed`)))}a(`#delete-btn`).addEventListener(`click`,()=>{F(u.allSelections().filter(e=>e.length>0))});let Ce=()=>{g.hidden=!0,M.play(u.working).then(e=>{e&&D(e)})};if(h.addEventListener(`click`,()=>{if(M.playing){M.stop(),fe();return}if(!e.onPlay){Ce();return}i.querySelector(`.play-menu`)?.remove();let t=document.createElement(`div`);t.className=`context-menu floating play-menu`;let r=[[`preview`,`▶ preview here`,e.playHints?.preview??`simulate in the editor · scripts stripped`],[`debug`,`⤢ run as the game`,e.playHints?.debug??`this page becomes the game, with the debug overlay`]];for(let[n,i,a]of r){let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item play-menu-item`;let o=document.createElement(`span`);o.textContent=i;let s=document.createElement(`span`);s.className=`play-menu-hint`,s.textContent=a,r.append(o,s),r.addEventListener(`click`,()=>{t.remove(),n===`preview`?Ce():e.onPlay?.(n,u.working)}),t.appendChild(r)}i.appendChild(t);let a=h.getBoundingClientRect(),o=t.getBoundingClientRect().width;t.style.left=`${Math.min(Math.max(8,a.right-o),window.innerWidth-o-8)}px`,t.style.top=`${a.bottom+6}px`;let s=e=>{e.type===`keydown`&&e.key!==`Escape`||e.type!==`keydown`&&(t.contains(e.target)||e.target===h)||(t.remove(),document.removeEventListener(`pointerdown`,s,!0),document.removeEventListener(`keydown`,s,!0))};setTimeout(()=>{document.addEventListener(`pointerdown`,s,!0),document.addEventListener(`keydown`,s,!0)},0),n.push(()=>{document.removeEventListener(`pointerdown`,s,!0),document.removeEventListener(`keydown`,s,!0)})}),e.onExit){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.id=`exit-btn`,t.title=`Back to the game`,t.textContent=`✕ exit`,h.parentElement?.insertBefore(t,h),t.addEventListener(`click`,()=>void e.onExit?.())}for(let e of[`move`,`rotate`,`scale`])a(`#tool-${e}`).addEventListener(`click`,()=>M.setMode(e));M.setMode(`move`);let L=a(`#tool-colliders`),we=`incanto-editor-show-colliders`,Te=e=>{M.showColliders=e,L.classList.toggle(`active`,e),localStorage.setItem(we,e?``:`0`)};Te(localStorage.getItem(we)!==`0`),L.addEventListener(`click`,()=>Te(!M.showColliders));let Ee=a(`#hints-dock`),De=`incanto-editor-hints-open`;Ee.classList.toggle(`open`,localStorage.getItem(De)===`1`),a(`#hints-toggle`).addEventListener(`click`,()=>{let e=Ee.classList.toggle(`open`);localStorage.setItem(De,e?`1`:``)}),a(`#fit-btn`).addEventListener(`click`,()=>M.zoomToFit()),qz(()=>M.zoomToFit()),a(`#gameview-btn`).addEventListener(`click`,()=>M.gameView()),t.saveScene||(p.hidden=!0),p.addEventListener(`click`,()=>{(async()=>{try{await t.saveScene?.(u.working,w),u.markSaved(),MF.save(S,C,u.working)}catch(e){D(e instanceof Error?e.message:String(e))}})()}),m.addEventListener(`click`,()=>u.undo());let Oe=e=>{if(e.key===`Escape`&&M.cancelActiveDrag(),e.key===`Escape`&&!g.hidden&&a(`#docs`).hidden&&P.hidden&&N.hidden&&y.hidden&&!M.playing){O();return}if(e.key===`Escape`&&!a(`#docs`).hidden){BF();return}if(e.key===`Escape`&&!P.hidden){I();return}if(e.key===`Escape`&&!N.hidden){TL();return}if(e.key===`Escape`&&!y.hidden){ye();return}if(e.key===`Escape`&&M.playing){M.stop(),fe();return}if(M.playing)return;let t=e.target.matches(`input, textarea, select`);(e.metaKey||e.ctrlKey)&&e.key===`z`?(e.preventDefault(),u.undo()):(e.metaKey||e.ctrlKey)&&e.key===`s`?(e.preventDefault(),p.disabled||p.click()):!t&&e.code===`KeyF`?M.zoomToFit():!t&&(e.code===`Digit0`||e.code===`Numpad0`)?M.gameView():!t&&e.code===`KeyW`?M.setMode(`move`):!t&&e.code===`KeyE`?M.setMode(`rotate`):!t&&e.code===`KeyR`&&M.setMode(`scale`)};return window.addEventListener(`keydown`,Oe),n.push(()=>window.removeEventListener(`keydown`,Oe)),fe(),e.camera&&M.setEditCamera(e.camera.position,e.camera.target),MF.ready(S,C,o.version),{working:()=>u.working,camera:()=>M.editCamera(),showError:D,dispose(){M.dispose();for(let e of document.querySelectorAll(`.context-menu, .balloon`))e.remove();for(let e of n.splice(0).reverse())e()}}}function KB(e){let t=0;for(let n of e.children??[])t+=1+KB(n);return t}function qB(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>e?.type===t).map(([e])=>`$${e}`):[]}function JB(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>!t||e?.type!==void 0&&t.includes(e.type)).map(([e])=>`$${e}`):[]}function YB(e,t,n){let r=e.working.assets??{};for(let[e,t]of Object.entries(r))if(t?.url===n.url)return`$${e}`;let i=t;for(let e=2;i in r;e++)i=`${t}-${e}`;return e.mutate(()=>{e.working.assets||(e.working.assets={}),e.working.assets[i]=n}),`$${i}`}var XB=null,ZB=null;function QB(){return ZB||(ZB=document.createElement(`canvas`),ZB.style.cssText=`position:fixed; inset:0; width:100%; height:100%; display:block;`,document.body.appendChild(ZB)),ZB.style.visibility=``,ZB}async function $B(e,t){return XB=await GB({api:re,...e?{camera:e}:{},onPlay:(e,t)=>{e===`debug`&&eV(t)},playHints:{debug:`this page becomes the game — needs a scene with no project behaviors`},...t?{onExit:()=>(XB?.dispose(),XB=null,QB(),t())}:{}}),XB}async function eV(e){let t=e.dimension??`2d`;XB?.dispose(),XB=null;let n=async e=>{ZB&&(ZB.style.visibility=`hidden`),await $B(e.camera,e.exit)};try{if(t===`3d`){let{createGame3D:t}=await ym(async()=>{let{createGame3D:e}=await Promise.resolve().then(()=>MP);return{createGame3D:e}},void 0,import.meta.url);await t({canvas:QB(),scene:e,debug:!0,editor:{open:n}})}else{let{createGame2D:t}=await ym(async()=>{let{createGame2D:e}=await Promise.resolve().then(()=>iy);return{createGame2D:e}},void 0,import.meta.url);await t({canvas:QB(),scene:e,debug:!0,editor:{open:n}})}}catch(e){ZB&&(ZB.style.visibility=`hidden`),(await $B()).showError(`${e instanceof Error?e.message:String(e)}\n\nRunning as the game needs your project's behaviors, which live in your app, not in this page. Start your own dev server with debug enabled and use the ☰ debug menu's "✎ edit this scene" — the switch works both ways from there, with every behavior loaded.`)}}$B().catch(e=>{let t=document.createElement(`div`);t.id=`error-banner`,t.style.cssText=`position:fixed;inset:0 0 auto 0;z-index:99;padding:10px 14px;background:#5b1a24;color:#ffd9df;font:13px ui-monospace,monospace`,t.textContent=e instanceof Error?e.message:String(e),document.body.appendChild(t)});export{He as i,ym as n,Xe as r,Q_ as t};
10778
+ `,Wz=new Map(LF.flatMap(e=>e.nodes.map(e=>[e.type,e.summary]))),Gz=new Set,Kz=null,qz=null,Jz=null;function Yz(e){qz=e}function Xz(e){Kz=e}function Zz(e){Jz=e}var Qz=null,$z=null,eB=null;function tB(e){return e?e.includes(`Body`)||e.includes(`Area`)||e.includes(`Controller`)?`cat-body`:e===`NetworkSpawner`?`cat-net`:e.endsWith(`3D`)?`cat-3d`:e.endsWith(`2D`)||e===`Label`||e===`UILayer`?`cat-2d`:`cat-core`:`cat-core`}function nB(e,t){e.textContent=``;let n=document.createElement(`div`);n.className=`tree-row scene-row${t.selection===null&&t.selectedAsset===null&&t.selectedGroup===null&&!t.addingAsset&&!t.addingGroup?` selected`:``}`,n.textContent=`⚙ ${String(t.working.name??`scene`)}`,n.addEventListener(`click`,()=>t.select(null)),e.appendChild(n);let r=t.working.root;if(!r){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no root node — pick a type below and + to start the scene`,e.appendChild(t);return}oB(r,t.selection),e.appendChild(sB(r,[],t,``)),iB(e,t.selection)}var rB=null;function iB(e,t){let n=JSON.stringify(t);n!==rB&&(rB=n,e.querySelector(`.tree-row.selected`)?.scrollIntoView?.({block:`nearest`,inline:`nearest`}))}function aB(){rB=null}function oB(e,t){if(!t)return;let n=e,r=``;for(let e of t){r=r?`${r}/${n.name}`:String(n.name),Gz.delete(r);let t=n.children?.[e];if(!t)return;n=t}}function sB(e,t,n,r){let i=r?`${r}/${e.name}`:String(e.name),a=(e.children?.length??0)>0,o=Gz.has(i),s=document.createElement(`div`);s.className=`tree-branch`;let c=document.createElement(`div`);c.className=`tree-row${n.isSelected(t)?` selected`:``}`,c.draggable=t.length>0&&eB!==i;let l=document.createElement(`span`);l.className=`chevron${a?``:` leaf`}${o?` collapsed`:``}`,a?l.appendChild($P()):l.textContent=`·`,a&&l.addEventListener(`click`,e=>{e.stopPropagation(),o?Gz.delete(i):Gz.add(i),n.select(n.selection)});let u=document.createElement(`span`);if(u.className=`tree-icon ${tB(e.type)}`,u.appendChild(QP(e.type)),u.title=e.type??`instance`,u.addEventListener(`click`,t=>{t.stopPropagation(),cB(u,e.type??`instance`)}),c.append(l,u),eB===i){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e.name??``;let i=()=>{eB=null;let i=r.value.trim();if(i&&i!==e.name){let e=n.renameNode(t,i)??[];e.length>0&&Jz?.(e)}else n.select(n.selection)};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`&&i(),e.key===`Escape`&&(eB=null,n.select(n.selection))});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());r.addEventListener(`blur`,i),c.appendChild(r),queueMicrotask(()=>{r.focus(),r.select()})}else{let r=document.createElement(`span`);r.className=`tree-name`,r.textContent=e.name??`(unnamed)`,r.addEventListener(`dblclick`,e=>{e.stopPropagation(),eB=i,n.select(t)}),c.appendChild(r)}if(c.addEventListener(`click`,e=>{a&&!e.metaKey&&!e.ctrlKey&&(o?Gz.delete(i):Gz.add(i)),n.select(t,{toggle:e.metaKey||e.ctrlKey})}),c.addEventListener(`contextmenu`,e=>{e.preventDefault(),n.isSelected(t)||n.select(t),lB(e.clientX,e.clientY,n,t,i)}),vB(c,t,n),s.appendChild(c),a&&!o){let r=document.createElement(`div`);r.className=`tree-children`,(e.children??[]).forEach((e,a)=>{r.appendChild(sB(e,[...t,a],n,i))}),s.appendChild(r)}return s}function cB(e,t){mB();let n=document.createElement(`div`);n.className=`balloon floating`;let r=document.createElement(`span`);r.className=`balloon-title`,r.textContent=t,n.appendChild(r);let i=Wz.get(t);if(i){let e=document.createElement(`span`);e.textContent=YP(i),n.appendChild(e)}document.body.appendChild(n);let a=e.getBoundingClientRect();n.style.left=`${Math.min(innerWidth-240,a.right+8)}px`,n.style.top=`${Math.max(8,a.top-6)}px`,hB(n)}function lB(e,t,n,r,i){mB();let a=n.allSelections(),o=a.length===1&&r.length>0,s=document.createElement(`div`);s.className=`context-menu floating`;let c=(e,t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item${n?.danger?` danger`:``}`,r.disabled=t===null;let i=document.createElement(`span`);if(i.textContent=e,r.appendChild(i),n?.kbd){let e=document.createElement(`kbd`);e.textContent=n.kbd,r.appendChild(e)}t&&r.addEventListener(`click`,()=>{mB(),t()}),s.appendChild(r)};c(`duplicate${a.length>1?` ×${a.length}`:``}`,()=>{for(let e of[...a].reverse())n.duplicateNode(e)}),c(`frame in view`,qz&&r.length>0?()=>{n.select(r),qz?.()}:null,{kbd:`F`}),c(`rename`,o?()=>{eB=i,n.select(r)}:null,{kbd:`dbl-click`}),s.appendChild(uB()),c(`cut`,r.length>0?()=>dB(n,!0):null),c(`copy`,r.length>0?()=>dB(n,!1):null),c(`paste as child${$z?` (${$z.nodes.length})`:``}`,$z?()=>fB(n,r):null),s.appendChild(uB()),c(`delete`,r.length>0?()=>(Kz??(e=>n.removeNodes(e)))(a):null,{danger:!0}),document.body.appendChild(s),s.style.left=`${Math.min(innerWidth-200-8,e)}px`,s.style.top=`${Math.min(innerHeight-s.offsetHeight-8,t)}px`,hB(s)}function uB(){let e=document.createElement(`div`);return e.className=`menu-divider`,e}function dB(e,t){let n=e.allSelections().filter(e=>e.length>0).map(t=>e.nodeAt(t)).filter(e=>e!==null);$z={nodes:n.map(e=>JSON.parse(JSON.stringify(e))),cut:t?n:null}}function fB(e,t){if($z){for(let n of $z.nodes)e.insertNode(n,t);if($z.cut){let t=e.working.root,n=$z.cut.map(e=>pB(t,e)).filter(e=>e!==null);n.length>0&&e.removeNodes(n),$z={nodes:$z.nodes,cut:null}}}}function pB(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=pB(r,t);if(e)return[n,...e]}return null}function mB(){for(let e of document.querySelectorAll(`.floating`))e.remove()}function hB(e){let t=r=>{e.contains(r.target)||(e.remove(),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,n,!0))},n=r=>{r.key===`Escape`&&(e.remove(),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,n,!0))};setTimeout(()=>{document.addEventListener(`pointerdown`,t,!0),document.addEventListener(`keydown`,n,!0)},0)}function gB(e,t){let n=t.getBoundingClientRect(),r=(e.clientY-n.top)/n.height;return r<.25?`before`:r>.75?`after`:`into`}function _B(e){e.classList.remove(`drop-into`,`drop-before`,`drop-after`)}function vB(e,t,n){e.addEventListener(`dragstart`,r=>{Qz=n.isSelected(t)?n.allSelections():[t],r.dataTransfer?.setData(`text/plain`,``),r.dataTransfer&&(r.dataTransfer.effectAllowed=`move`),e.classList.add(`dragging`)}),e.addEventListener(`dragend`,()=>{Qz=null,e.classList.remove(`dragging`)}),e.addEventListener(`dragover`,n=>{if(!Qz||Qz.some(e=>e.length<=t.length&&e.every((e,n)=>e===t[n])))return;n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=`move`),_B(e);let r=t.length===0?`into`:gB(n,e);e.classList.add(`drop-${r}`)}),e.addEventListener(`dragleave`,()=>_B(e)),e.addEventListener(`drop`,r=>{if(_B(e),!Qz)return;r.preventDefault();let i=t.length===0?`into`:gB(r,e),a=n.moveNodes(Qz,t,i);Qz=null,a?.[0]&&n.select(a[0])})}var yB={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`};function bB(e,t,n){let r=t-e.origin.x,i=n-e.origin.y;if(Math.abs(r)<=e.centerSize&&Math.abs(i)<=e.centerSize)return{kind:`center`};for(let t of e.axes){let e=t.sx*t.sx+t.sy*t.sy;if(e<1)continue;let n=Math.max(0,Math.min(1,(r*t.sx+i*t.sy)/e)),a=r-t.sx*n,o=i-t.sy*n;if(n>.25&&Math.hypot(a,o)<=8)return{kind:`axis`,axis:t.axis}}return null}function xB(e,t,n){let r=e.sx*e.sx+e.sy*e.sy;return r<1?0:(t*e.sx+n*e.sy)/r*e.worldPerUnit}function SB(e,t,n,r=!1){let{origin:i,axes:a,centerSize:o}=t;for(let t of a){let a=n?.kind===`axis`&&n.axis===t.axis;e.strokeStyle=t.color,e.fillStyle=t.color,e.globalAlpha=a?1:.9,e.lineWidth=a?3:2,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x+t.sx,i.y+t.sy),e.stroke();let o=Math.hypot(t.sx,t.sy)||1,s=t.sx/o,c=t.sy/o,l=i.x+t.sx,u=i.y+t.sy;e.beginPath(),r?e.rect(l-5,u-5,10,10):(e.moveTo(l+s*9,u+c*9),e.lineTo(l-c*4.5,u+s*4.5),e.lineTo(l+c*4.5,u-s*4.5),e.closePath()),e.fill(),e.font=`700 9px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(t.axis.toUpperCase(),l+s*18,u+c*18)}let s=n?.kind===`center`;e.globalAlpha=s?1:.95,e.fillStyle=s?`#ffffff`:`#e2e6f0`,e.strokeStyle=`#0b0d14`,e.lineWidth=1.5,e.beginPath(),e.rect(i.x-o,i.y-o,o*2,o*2),e.fill(),e.stroke(),e.globalAlpha=1}function CB(e,t,n){return Math.atan2(n-e.y,t-e.x)*180/Math.PI}function wB(e,t){let n=t-e;for(;n>180;)n-=360;for(;n<=-180;)n+=360;return n}function TB(e,t,n,r){let i=null,a=r;for(let r of e)for(let e of r.points){let o=Math.hypot(t-e.x,n-e.y);o<a&&(a=o,i=r.axis)}return i}function EB(e,t,n){for(let r of t){if(r.points.length<2)continue;let t=n===r.axis;e.strokeStyle=yB[r.axis],e.globalAlpha=t?1:.75,e.lineWidth=t?3:2,e.beginPath();let i=r.points[0];e.moveTo(i.x,i.y);for(let t of r.points.slice(1))e.lineTo(t.x,t.y);e.closePath(),e.stroke()}e.globalAlpha=1}function DB(e,t,n,r){e.font=`600 11px ui-monospace, Menlo, monospace`;let i=e.measureText(r).width+14;e.fillStyle=`rgba(16, 19, 29, 0.92)`,e.strokeStyle=`rgba(110, 231, 220, 0.5)`,e.lineWidth=1,e.beginPath(),e.roundRect(t+14,n-26,i,20,5),e.fill(),e.stroke(),e.fillStyle=`#6ee7dc`,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(r,t+21,n-16)}var OB=class{engine;editCanvas;overlay;playCanvas;cb;editUiHost=null;playUiHost=null;renderer2d=null;renderer3d=null;rendererDim=null;orbit={yaw:.6,pitch:.35,dist:10,target:[0,1,0]};pathOf=new Map;reindexNeeded=!1;nodeAtPath=new Map;selectedPath=null;paintHandler=null;extraPaths=[];hoveredNode=null;hoveredGizmo=null;lastGood=null;lastAppliedKey=null;playEngine=null;playRenderer=null;playPhysics=null;setPaintHandler(e){this.paintHandler=e}get playing(){return this.playEngine!==null}constructor(e,t,n,r){this.editCanvas=e,this.overlay=t,this.playCanvas=n,this.cb=r;let i=this;this.engine=new Et({scheduler:e=>{let t=0,n=performance.now(),r=requestAnimationFrame(function a(o){t+=.001;let s=Math.min(.1,(o-n)/1e3);n=o;try{e(t),i.tickAmbientPreviews(s)}catch(e){console.error(`incanto-editor viewport:`,e)}r=requestAnimationFrame(a)});return()=>cancelAnimationFrame(r)}}),this.editUiHost=this.makeUiHost(e.parentElement,4),this.playUiHost=this.makeUiHost(n.parentElement,5),this.engine.uiHost=this.editUiHost,this.engine.start(),this.engine.updated.connect(()=>this.drawOverlay());let a=e=>{e.key===`Shift`&&(this.shiftHeld=!0)},o=e=>{e.key===`Shift`&&(this.shiftHeld=!1)};window.addEventListener(`keydown`,a),window.addEventListener(`keyup`,o),this.cleanups.push(()=>{window.removeEventListener(`keydown`,a),window.removeEventListener(`keyup`,o)}),this.bindPointer()}cleanups=[];makeUiHost(e,t){if(!e)return null;let n=document.createElement(`div`);return n.style.cssText=`position:absolute;inset:0;pointer-events:none;z-index:${t};`,e.appendChild(n),this.cleanups.push(()=>n.remove()),n}dispose(){this.stop(),this.editPhysics?.dispose(),this.editPhysics=null,this.engine.stop(),this.engine.dispose(),this.renderer2d?.dispose(),this.renderer3d?.dispose(),this.renderer2d=null,this.renderer3d=null;for(let e of this.cleanups.splice(0))e()}setEditCamera(e,t){let n=(e[0]??0)-(t[0]??0),r=(e[1]??0)-(t[1]??0),i=(e[2]??0)-(t[2]??0),a=Math.hypot(n,r,i);a>.01&&(this.orbit.target=[t[0]??0,t[1]??0,t[2]??0],this.orbit.dist=Math.min(800,Math.max(.3,a)),this.orbit.yaw=Math.atan2(n,i),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,r/a))),this.syncOrbit())}editCamera(){let{pos:e}=this.orbitVectors();return{position:[e.x,e.y,e.z],target:[...this.orbit.target]}}apply(e){e.root||(e={...e,root:{name:`__empty`,type:(e.dimension??`2d`)===`3d`?`Node3D`:`Node2D`}});let t=JSON.stringify(e);if(t===this.lastAppliedKey&&this.rendererDim===(e.dimension??`2d`))return null;let n;try{let t=structuredClone(e);GB(t),n=kn(t,{stubAllBehaviors:!0})}catch(e){return e instanceof Error?e.message:String(e)}this.lastGood=e,this.lastAppliedKey=t;let r=e.dimension??`2d`;if(this.rendererDim!==r){if(this.renderer2d?.dispose(),this.renderer3d?.dispose(),this.renderer2d=null,this.renderer3d=null,r===`2d`)this.renderer2d=new Kv({canvas:this.editCanvas,engine:this.engine}),this.renderer2d.ignoreStatic=!0,this.renderer2d.viewOverride=this.defaultView(e);else{this.renderer3d=new gP({canvas:this.editCanvas,engine:this.engine}),this.renderer3d.ignoreStatic=!0;let t=VB(e.root);if(t){let[e,n,r]=t;this.orbit.dist=Math.max(2,Math.hypot(e,n,r)),this.orbit.yaw=Math.atan2(e,r),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,n/this.orbit.dist))),this.orbit.target=[0,Math.min(2,Math.abs(n)/2),0]}this.syncOrbit()}this.rendererDim=r}return this.engine.setScene(n),this.indexTree(n.root),this.hoveredNode=null,null}setSelection(e,t=[]){this.selectedPath=e,this.extraPaths=t}validate(e){if(!e.root)return null;try{let t=structuredClone(e);return GB(t),kn(t,{stubAllBehaviors:!0}),null}catch(e){return e instanceof Error?e.message:String(e)}}defaultView(e){let t=HB(e.root);if(t)return{cx:t[0],cy:t[1],zoom:1};let n=this.editCanvas.clientWidth||960,r=this.editCanvas.clientHeight||540;return{cx:n/2,cy:r/2,zoom:1}}indexTree(e){this.pathOf=new Map,this.nodeAtPath=new Map;let t=(e,n)=>{this.pathOf.set(e,n),this.nodeAtPath.set(n.join(`.`),e),e.children.forEach((e,r)=>{t(e,[...n,r])})};t(e,[])}liveSelected(){return this.selectedPath===null?null:this.nodeAtPath.get(this.selectedPath.join(`.`))??null}patchProp(e,t,n,r){if(this.playing)return!1;let i=this.nodeAtPath.get(t.join(`.`));if(!i)return!1;try{i[n]=r===void 0?void 0:structuredClone(r)}catch{return!1}return this.reindexNeeded=!0,this.lastAppliedKey=JSON.stringify(e),!0}gizmoActive=null;gizmoMode=`move`;activeRing=null;readout=null;cancelActiveDrag=()=>{};shiftHeld=!1;get showColliders(){return this.collidersOn}set showColliders(e){this.collidersOn=e,this.editPhysics&&(this.editPhysics.debugDraw=e),e&&this.ensureOutlinePhysics()}collidersOn=!0;editPhysics=null;outlinePending=null;async ensureOutlinePhysics(){if(this.editPhysics||this.outlinePending)return this.outlinePending??void 0;let e=this.rendererDim;if(e)return this.outlinePending=(async()=>{try{if(e===`2d`){let{enablePhysics2D:e}=await ym(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>iy);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(this.engine,{simulate:!1});t.debugDraw=this.collidersOn,this.editPhysics=t}else{let{enablePhysics3D:e}=await ym(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>MP);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(this.engine,{simulate:!1});t.debugDraw=this.collidersOn,this.editPhysics=t}}catch(e){console.warn(`[incanto] collider outlines unavailable:`,e)}finally{this.outlinePending=null}})(),this.outlinePending}get mode(){return this.gizmoMode}setMode(e){this.gizmoMode=e,this.cb.onModeChanged(e)}gizmoLayout(){let e=this.liveSelected();if(!e)return null;if(this.rendererDim===`2d`&&this.renderer2d){let t=e.position;if(!Array.isArray(t))return null;let n=BB(e),r=this.renderer2d.screenFromWorld(n.x,n.y),i=this.renderer2d.view().zoom;return{origin:r,centerSize:7,axes:[{axis:`x`,sx:64,sy:0,worldPerUnit:64/i,color:yB.x},{axis:`y`,sx:0,sy:64,worldPerUnit:64/i,color:yB.y}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D,n=e.position;if(!t||!Array.isArray(n))return null;t.getWorldPosition(PB);let r=this.renderer3d.screenFromWorld(PB.x,PB.y,PB.z);if(r.behind)return null;let i=[],a=this.orbit.dist,o=Math.max(.2,a*.18);for(let[e,t]of[[`x`,[1,0,0]],[`y`,[0,1,0]],[`z`,[0,0,1]]]){let n=this.renderer3d.screenFromWorld(PB.x+t[0]*o,PB.y+t[1]*o,PB.z+t[2]*o);n.behind||i.push({axis:e,sx:n.x-r.x,sy:n.y-r.y,worldPerUnit:o,color:yB[e]})}return{origin:{x:r.x,y:r.y},centerSize:7,axes:i}}return null}ringLayout(){let e=this.liveSelected();if(!e)return null;if(this.rendererDim===`2d`&&this.renderer2d){let t=BB(e),n=this.renderer2d.screenFromWorld(t.x,t.y),r=[];for(let e=0;e<48;e++){let t=e/48*Math.PI*2;r.push({x:n.x+56*Math.cos(t),y:n.y+56*Math.sin(t)})}return{origin:n,rings:[{axis:`z`,points:r}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D;if(!t)return null;t.getWorldPosition(PB);let n={x:PB.x,y:PB.y,z:PB.z},r=this.renderer3d.screenFromWorld(n.x,n.y,n.z);if(r.behind)return null;let i=Math.max(.2,this.orbit.dist*.16),a=[];for(let e of[`x`,`y`,`z`]){let t=[];for(let r=0;r<48;r++){let a=r/48*Math.PI*2,o=Math.cos(a)*i,s=Math.sin(a)*i,c=e===`x`?this.renderer3d.screenFromWorld(n.x,n.y+o,n.z+s):e===`y`?this.renderer3d.screenFromWorld(n.x+o,n.y,n.z+s):this.renderer3d.screenFromWorld(n.x+o,n.y+s,n.z);c.behind||t.push({x:c.x,y:c.y})}a.push({axis:e,points:t})}return{origin:{x:r.x,y:r.y},rings:a}}return null}orbitVectors(){let{yaw:e,pitch:t,dist:n,target:r}=this.orbit,i=Math.cos(t),a=new U(r[0]+n*i*Math.sin(e),r[1]+n*Math.sin(t),r[2]+n*i*Math.cos(e)),o=new U(r[0],r[1],r[2]).sub(a).normalize(),s=new U().crossVectors(o,AB).normalize();return{pos:a,right:s,up:new U().crossVectors(s,o).normalize(),forward:o}}syncOrbit(){if(!this.renderer3d)return;let{pos:e}=this.orbitVectors();this.renderer3d.viewOverride={position:[e.x,e.y,e.z],target:[...this.orbit.target]}}gameView(){if(this.rendererDim===`3d`&&this.renderer3d){let e=null;for(let[t]of this.pathOf)if(t instanceof BE&&(t.current||!e)&&(e=t,t.current))break;let t=e?e._ensureObject3D():null;if(t){t.getWorldPosition(jB),MB.set(0,0,-1).applyQuaternion(t.getWorldQuaternion(NB));let e=Math.min(40,Math.max(3,this.orbit.dist));this.orbit.target=[jB.x+MB.x*e,jB.y+MB.y*e,jB.z+MB.z*e],this.orbit.dist=e,this.orbit.yaw=Math.atan2(-MB.x,-MB.z),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,-MB.y)))}this.renderer3d.viewOverride=null;return}this.renderer2d&&(this.renderer2d.viewOverride=null)}snapView(e,t){e===`y`?(this.orbit.pitch=t*1.45,this.orbit.yaw=0):(this.orbit.pitch=0,this.orbit.yaw=e===`z`?t===1?0:Math.PI:Math.PI/2*t),this.syncOrbit()}gizmoCenter(){return{x:this.overlay.clientWidth-58,y:58,r:36}}gizmoHandles(){let{right:e,up:t,forward:n}=this.orbitVectors(),r=this.gizmoCenter(),i=[];for(let[a,o]of[[`x`,new U(1,0,0)],[`y`,new U(0,1,0)],[`z`,new U(0,0,1)]])for(let s of[1,-1]){let c=o.clone().multiplyScalar(s);i.push({axis:a,sign:s,x:r.x+c.dot(e)*26,y:r.y-c.dot(t)*26,z:-c.dot(n)})}return i.sort((e,t)=>e.z-t.z)}gizmoHit(e,t){let n=this.gizmoCenter();if(Math.hypot(e-n.x,t-n.y)>n.r+8)return null;let r=null,i=14;for(let n of this.gizmoHandles()){let a=Math.hypot(e-n.x,t-n.y);a<i&&(i=a,r={axis:n.axis,sign:n.sign})}return r??{axis:`z`,sign:1}}gizmoHandleAt(e,t){let n=this.gizmoCenter();if(Math.hypot(e-n.x,t-n.y)>n.r+8)return null;let r=null,i=12;for(let n of this.gizmoHandles()){let a=Math.hypot(e-n.x,t-n.y);a<i&&(i=a,r={axis:n.axis,sign:n.sign})}return r}tickAmbientPreviews(e){if(!this.playing)for(let[t]of this.pathOf)(t instanceof Jk||t instanceof wv||t instanceof Zk||t instanceof mg||t instanceof yk)&&t.update(e)}modelAnimationsAt(e){let t=this.nodeAtPath.get(e.join(`.`));return t instanceof Jk?t.availableAnimations():[]}boneNamesAt(e,t){let n=this.nodeAtPath.get(e.join(`.`));if(!n||t===``)return[];let r=n.getNodeOrNull(t);return r instanceof Jk?r.boneNames():[]}drawOverlay(){if(this.reindexNeeded){this.reindexNeeded=!1;let e=this.engine.scene?.tree.root;e&&this.indexTree(e)}let e=this.overlay.getContext(`2d`);if(!e)return;let t=this.overlay.clientWidth,n=this.overlay.clientHeight,r=Math.min(devicePixelRatio||1,2);if((this.overlay.width!==t*r||this.overlay.height!==n*r)&&(this.overlay.width=t*r,this.overlay.height=n*r),e.setTransform(r,0,0,r,0,0),e.clearRect(0,0,t,n),this.playing)return;if(this.rendererDim===`3d`){this.drawGizmo(e),this.drawModeGizmo(e),this.readout&&DB(e,this.readout.x,this.readout.y,this.readout.text);return}if(!this.renderer2d)return;if(this.drawAxes2D(e),this.hoveredNode&&this.hoveredNode!==this.liveSelected()){let t=this.renderer2d.boundsOf(this.hoveredNode);t&&(e.strokeStyle=`rgba(110, 231, 220, 0.45)`,e.lineWidth=1.5,e.setLineDash([]),e.strokeRect(t.x,t.y,t.w,t.h))}for(let t of this.extraPaths){let n=this.nodeAtPath.get(t.join(`.`)),r=n?this.renderer2d.boundsOf(n):null;r&&(e.strokeStyle=`rgba(110, 231, 220, 0.7)`,e.lineWidth=1.5,e.setLineDash([4,3]),e.strokeRect(r.x-2,r.y-2,r.w+4,r.h+4),e.setLineDash([]))}let i=this.liveSelected();if(i){let t=this.renderer2d.boundsOf(i)??this.pointBounds(i);if(t){e.strokeStyle=`#6ee7dc`,e.lineWidth=2,e.setLineDash([6,4]),e.lineDashOffset=-(performance.now()/50%10),e.strokeRect(t.x-2,t.y-2,t.w+4,t.h+4),e.setLineDash([]),e.fillStyle=`#6ee7dc`;for(let[n,r]of[[t.x-2,t.y-2],[t.x+t.w+2,t.y-2],[t.x-2,t.y+t.h+2],[t.x+t.w+2,t.y+t.h+2]])e.fillRect(n-3,r-3,6,6)}}this.drawModeGizmo(e),this.readout&&DB(e,this.readout.x,this.readout.y,this.readout.text)}drawModeGizmo(e){if(this.gizmoMode===`rotate`){let t=this.ringLayout();t&&EB(e,t.rings,this.activeRing);return}let t=this.gizmoLayout();t&&SB(e,t,this.gizmoActive,this.gizmoMode===`scale`)}pointBounds(e){if(!this.renderer2d)return null;let t=e.position;if(!Array.isArray(t))return null;let n=BB(e),r=this.renderer2d.screenFromWorld(n.x,n.y);return{x:r.x-12,y:r.y-12,w:24,h:24}}drawGizmo(e){let t=this.gizmoCenter();e.beginPath(),e.arc(t.x,t.y,t.r,0,Math.PI*2),e.fillStyle=`rgba(16, 19, 29, 0.72)`,e.fill(),e.strokeStyle=`rgba(52, 60, 84, 0.9)`,e.lineWidth=1,e.stroke();let n={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`},r={x1:`right`,"x-1":`left`,y1:`top`,"y-1":`bottom`,z1:`front`,"z-1":`back`};for(let r of this.gizmoHandles()){let i=this.hoveredGizmo?.axis===r.axis&&this.hoveredGizmo?.sign===r.sign,a=n[r.axis],o=(r.z+1)/2;e.globalAlpha=i?1:.45+o*.55,e.strokeStyle=a,e.lineWidth=1.5,e.beginPath(),e.moveTo(t.x,t.y),e.lineTo(r.x,r.y),e.stroke(),e.beginPath(),e.arc(r.x,r.y,(r.sign===1?7:5)+(i?2:0),0,Math.PI*2),r.sign===1?(e.fillStyle=a,e.fill(),e.fillStyle=`#0b0d14`,e.font=`700 8px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(r.axis.toUpperCase(),r.x,r.y+.5)):(e.fillStyle=`rgba(16, 19, 29, 0.9)`,e.fill(),e.stroke())}if(e.globalAlpha=1,this.hoveredGizmo){let n=r[`${this.hoveredGizmo.axis}${this.hoveredGizmo.sign}`];e.fillStyle=`#9aa3bd`,e.font=`600 10px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(`${n} view`,t.x,t.y-t.r-6)}}drawAxes2D(e){let t=this.gizmoCenter();e.save(),e.shadowColor=`rgba(0, 0, 0, 0.25)`,e.shadowBlur=10,e.shadowOffsetY=2,e.beginPath(),e.arc(t.x,t.y,31,0,Math.PI*2),e.fillStyle=`rgba(13, 16, 24, 0.42)`,e.fill(),e.shadowColor=`transparent`,e.strokeStyle=`rgba(255, 255, 255, 0.16)`,e.lineWidth=1,e.stroke();let n=t.x-9,r=t.y-9;e.lineCap=`round`;let i=(t,i,a,o)=>{let s=n+t*21,c=r+i*21,l=e.createLinearGradient(n,r,s,c);l.addColorStop(0,`${a}55`),l.addColorStop(1,a),e.strokeStyle=l,e.lineWidth=2,e.beginPath(),e.moveTo(n,r),e.lineTo(s,c),e.stroke(),e.beginPath(),e.arc(s,c,6.5,0,Math.PI*2),e.fillStyle=a,e.fill(),e.font=`800 8px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#0b0d14`,e.fillText(o,s,c+.5)};i(1,0,`#fb7185`,`X`),i(0,1,`#86efac`,`Y`),e.beginPath(),e.arc(n,r,2.5,0,Math.PI*2),e.fillStyle=`#e2e6f0`,e.fill(),e.restore()}bindPointer(){let e=this.overlay,t=null,n=null,r=!1,i=null,a=null,o=null,s=null,c=null,l=t=>{let n=this.ringLayout();if(!n)return!1;let r=TB(n.rings,t.offsetX,t.offsetY,9);if(!r)return!1;let i=this.liveSelected();if(!i)return!1;e.setPointerCapture(t.pointerId);let a=i.rotation,o=1;if(this.rendererDim===`3d`&&this.renderer3d){let{forward:e}=this.renderer3d.cameraBasis();o=(r===`x`?e.x:r===`y`?e.y:e.z)>0?1:-1}return c={axis:r,node:i,origin:n.origin,startAngle:CB(n.origin,t.offsetX,t.offsetY),startRotation:Array.isArray(a)?[...a]:a??0,sign:o},this.activeRing=r,!0},u=e=>{if(!c)return;let{axis:t,node:n,origin:r,startAngle:i,startRotation:a,sign:o}=c,s=wB(i,CB(r,e.offsetX,e.offsetY))*o,l=e.shiftKey||this.shiftHeld?15:null,u=e=>{let t=e+s;return l?Math.round(t/l)*l:Math.round(t*10)/10},d;if(Array.isArray(a)){let e={x:0,y:1,z:2}[t],r=[...a];r[e]=u(a[e]??0),d=r[e],n.rotation=r}else{let e=u(a);d=e,n.rotation=e}this.readout={x:e.offsetX,y:e.offsetY,text:`${d}°${l?` ⌁15°`:``}`}},d=e=>{if(!c)return;let{node:t,startRotation:n}=c;if(!e)t.rotation=n;else{let e=this.pathOf.get(t),n=t.rotation;e!==void 0&&n!==void 0&&(Array.isArray(n)?this.cb.onNodeRotated3D(e,[n[0]??0,n[1]??0,n[2]??0]):this.cb.onNodeRotated2D(e,n))}c=null,this.activeRing=null,this.readout=null};this.cancelActiveDrag=()=>{d(!1),s&&(s.node.position=s.startPos,s.node.scale=s.startScale,s=null,this.gizmoActive=null,this.readout=null)};let f=t=>{if(this.gizmoMode===`rotate`)return l(t);let n=this.gizmoLayout();if(!n)return!1;let r=bB(n,t.offsetX,t.offsetY);if(!r)return!1;let i=this.liveSelected();if(!i)return!1;e.setPointerCapture(t.pointerId);let a=[...i.position??[]],o=[...i.scale??[]];return s={hit:r,mode:this.gizmoMode===`scale`||t.button===2?`scale`:`move`,startX:t.offsetX,startY:t.offsetY,layout:n,node:i,startPos:a,startScale:o},this.gizmoActive=r,!0},p=e=>{if(!s)return;let{hit:t,mode:n,layout:r,node:i,startPos:a,startScale:o}=s,c=e.offsetX-s.startX,l=e.offsetY-s.startY,u=this.rendererDim===`3d`,d={x:0,y:1,z:2},f=e.shiftKey||this.shiftHeld,p=f?u?.5:10:null,m=f?.25:null,h=e=>p?Math.round(e/p)*p:e,g=e=>m?Math.max(m,Math.round(e/m)*m):e;if(n===`scale`){let n=Math.max(.05,1+(c-l)*.005),r=[...o];if(t.kind===`axis`)r[d[t.axis]]=kB(g((o[d[t.axis]]??1)*n));else for(let e=0;e<r.length;e++)r[e]=kB(g((o[e]??1)*n));i.scale=r,this.readout={x:e.offsetX,y:e.offsetY,text:`×${r.map(e=>kB(e)).join(`, `)}`};return}let _=[...a];if(t.kind===`axis`){let e=r.axes.find(e=>e.axis===t.axis);if(!e)return;let n=xB(e,c,l);if(u)_[d[t.axis]]=kB(h((a[d[t.axis]]??0)+n));else{let e=RB(i,t.axis===`x`?n:0,t.axis===`y`?n:0),r=t.axis===`x`?e.x:e.y;_[d[t.axis]]=Math.round(h((a[d[t.axis]]??0)+r))}}else if(u&&this.renderer3d){let{right:e,up:t}=this.renderer3d.cameraBasis(),n=this.orbit.dist*.0016;_[0]=kB(h((a[0]??0)+(e.x*c-t.x*l)*n)),_[1]=kB(h((a[1]??0)+(e.y*c-t.y*l)*n)),_[2]=kB(h((a[2]??0)+(e.z*c-t.z*l)*n))}else if(this.renderer2d){let e=this.renderer2d.view(),t=RB(i,c/e.zoom,l/e.zoom);_[0]=Math.round(h((a[0]??0)+t.x)),_[1]=Math.round(h((a[1]??0)+t.y))}i.position=_,this.readout={x:e.offsetX,y:e.offsetY,text:`[${_.map(e=>kB(e)).join(`, `)}]`}},m=()=>{if(!s)return;let{node:e,mode:t}=s,n=this.pathOf.get(e);if(n)if(t===`scale`){let t=e.scale??[];this.rendererDim===`3d`?this.cb.onNodeScaled3D(n,[t[0]??1,t[1]??1,t[2]??1]):this.cb.onNodeScaled(n,[t[0]??1,t[1]??1])}else{let t=e.position??[];this.rendererDim===`3d`?this.cb.onNodeMoved3D(n,[t[0]??0,t[1]??0,t[2]??0]):this.cb.onNodeMoved(n,[t[0]??0,t[1]??0])}s=null,this.gizmoActive=null};e.addEventListener(`pointerdown`,s=>{if(this.playing||f(s))return;if(this.rendererDim===`3d`){let t=this.gizmoHit(s.offsetX,s.offsetY);if(t){this.snapView(t.axis,t.sign);return}e.setPointerCapture(s.pointerId),s.button===1||s.button===2||s.shiftKey?a={x:s.offsetX,y:s.offsetY,target:[...this.orbit.target]}:(i={x:s.offsetX,y:s.offsetY,yaw:this.orbit.yaw,pitch:this.orbit.pitch},o={x:s.offsetX,y:s.offsetY,toggle:s.ctrlKey||s.metaKey});return}if(!this.renderer2d)return;if(e.setPointerCapture(s.pointerId),s.button===1||s.button===2||s.shiftKey){let e=this.renderer2d.view();n={startX:s.offsetX,startY:s.offsetY,cx:e.cx,cy:e.cy};return}if(this.paintHandler&&s.button===0){let e=this.renderer2d.worldFromScreen(s.offsetX,s.offsetY);this.paintHandler(e.x,e.y,!0),r=!0;return}let c=this.renderer2d.pick(s.offsetX,s.offsetY),l=c?this.pathOf.get(c)??null:null;if(this.cb.onPick(l,{toggle:s.ctrlKey||s.metaKey}),this.selectedPath=l,c&&l&&Array.isArray(c.position)){let e=c.position;t={node:c,startWorld:this.renderer2d.worldFromScreen(s.offsetX,s.offsetY),startPos:[e[0]??0,e[1]??0]}}}),e.addEventListener(`pointermove`,o=>{if(!this.playing){if(c){u(o);return}if(s){p(o);return}if(this.rendererDim===`3d`){if(!i&&!a?(this.hoveredGizmo=this.gizmoHandleAt(o.offsetX,o.offsetY),e.style.cursor=this.hoveredGizmo?`pointer`:`grab`):e.style.cursor=`grabbing`,i)this.orbit.yaw=i.yaw-(o.offsetX-i.x)*.006,this.orbit.pitch=Math.max(-1.5,Math.min(1.5,i.pitch+(o.offsetY-i.y)*.006)),this.syncOrbit();else if(a){let{right:e,up:t}=this.orbitVectors(),n=this.orbit.dist*.0016,r=(o.offsetX-a.x)*n,i=(o.offsetY-a.y)*n;this.orbit.target=[a.target[0]-e.x*r+t.x*i,a.target[1]-e.y*r+t.y*i,a.target[2]-e.z*r+t.z*i],this.syncOrbit()}return}if(this.renderer2d){if(e.style.cursor=`crosshair`,r&&this.paintHandler){let e=this.renderer2d.worldFromScreen(o.offsetX,o.offsetY);this.paintHandler(e.x,e.y,!1);return}if(n){let e=this.renderer2d.view();this.renderer2d.viewOverride={cx:n.cx-(o.offsetX-n.startX)/e.zoom,cy:n.cy-(o.offsetY-n.startY)/e.zoom,zoom:e.zoom};return}if(t){let e=this.renderer2d.worldFromScreen(o.offsetX,o.offsetY),n=RB(t.node,e.x-t.startWorld.x,e.y-t.startWorld.y),r=Math.round(t.startPos[0]+n.x),i=Math.round(t.startPos[1]+n.y);t.node.position=[r,i];return}this.hoveredNode=this.renderer2d.pick(o.offsetX,o.offsetY)}}});let h=e=>{if(r=!1,d(!0),m(),this.readout=null,o&&e&&this.renderer3d&&Math.hypot(e.offsetX-o.x,e.offsetY-o.y)<4){let e=this.renderer3d.pick(o.x,o.y),t=e?this.pathOf.get(e)??null:null;t&&(this.cb.onPick(t,{toggle:o.toggle}),this.selectedPath=t)}if(o=null,i=null,a=null,t){let e=this.pathOf.get(t.node),n=t.node.position;e&&(n[0]!==t.startPos[0]||n[1]!==t.startPos[1])&&this.cb.onNodeMoved(e,[n[0]??0,n[1]??0]),t=null}n=null};e.addEventListener(`pointerup`,h),e.addEventListener(`pointercancel`,h),e.addEventListener(`contextmenu`,e=>e.preventDefault()),e.addEventListener(`dblclick`,e=>{if(this.playing)return;let t=this.rendererDim===`3d`?this.renderer3d?.pick(e.offsetX,e.offsetY)??null:this.renderer2d?.pick(e.offsetX,e.offsetY)??null,n=t?this.pathOf.get(t)??null:null;n&&(this.cb.onPick(n,{toggle:e.ctrlKey||e.metaKey}),this.selectedPath=n)}),e.addEventListener(`wheel`,e=>{if(this.playing)return;e.preventDefault();let t=e.deltaY<0?1.1:1/1.1;if(this.rendererDim===`3d`){this.orbit.dist=Math.max(.3,Math.min(800,this.orbit.dist/t)),this.syncOrbit();return}if(!this.renderer2d)return;let n=this.liveSelected();if(e.altKey&&n&&Array.isArray(n.scale)){let e=n.scale,r=[Math.round((e[0]??1)*t*100)/100,Math.round((e[1]??1)*t*100)/100];n.scale=r;let i=this.pathOf.get(n);i&&this.cb.onNodeScaled(i,r);return}let r=this.renderer2d.view(),i=this.renderer2d.worldFromScreen(e.offsetX,e.offsetY),a=Math.min(8,Math.max(.1,r.zoom*t));this.renderer2d.viewOverride={cx:i.x-(e.offsetX-r.w/2)/a,cy:i.y-(e.offsetY-r.h/2)/a,zoom:a}},{passive:!1})}zoomToFit(){let e=this.liveSelected();if(this.rendererDim===`3d`){let t=new Bo;for(let[n]of this.pathOf){if(e&&n!==e&&!zB(n,e))continue;let r=n._object3D;r&&(t.expandByObject(r),t.expandByPoint(r.getWorldPosition(PB)))}if(t.isEmpty()&&e){let t=e._object3D,n=t?t.getWorldPosition(PB):null;this.orbit.target=n?[n.x,n.y,n.z]:[0,1,0],this.orbit.dist=6}else if(t.isEmpty())this.orbit.target=[0,1,0],this.orbit.dist=10;else{let e=t.getCenter(new U),n=t.getSize(new U);this.orbit.target=[e.x,e.y,e.z],this.orbit.dist=Math.max(2.5,n.length()*.85)}this.syncOrbit();return}if(!this.renderer2d)return;let t=this.editCanvas.clientWidth||960,n=this.editCanvas.clientHeight||540,r=1/0,i=1/0,a=-1/0,o=-1/0;for(let[t]of this.pathOf){if(e&&t!==e&&!zB(t,e))continue;let n=t.position;if(!Array.isArray(n))continue;let s=BB(t);r=Math.min(r,s.x),i=Math.min(i,s.y),a=Math.max(a,s.x),o=Math.max(o,s.y)}if(!Number.isFinite(r))return;let s=(r+a)/2,c=(i+o)/2,l=e?600:200,u=Math.max(a-r+l,l),d=Math.max(o-i+l,l),f=Math.min(2,Math.min(t/u,n/d));this.renderer2d.viewOverride={cx:s,cy:c,zoom:f}}async play(e){if(this.playing)return null;let t=structuredClone(e);GB(t);let n;try{n=kn(t,{stubAllBehaviors:!0,declareConnectionSignals:!0})}catch(e){return e instanceof Error?e.message:String(e)}let r=new Et;r.uiHost=this.playUiHost,this.editUiHost&&(this.editUiHost.style.display=`none`),r.setScene(n),r.input.attachKeyboard(window),this.playCanvas.hidden=!1;let i=e.dimension??`2d`;try{if(i===`2d`){this.playRenderer=new Kv({canvas:this.playCanvas,engine:r});let{enablePhysics2D:e}=await ym(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>iy);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}else{this.playRenderer=new gP({canvas:this.playCanvas,engine:r,assets:this.renderer3d?.assets});let{enablePhysics3D:e}=await ym(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>MP);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}}catch(e){return this.stop(),e instanceof Error?e.message:String(e)}return r.start(),this.playEngine=r,this.cb.onPlayStateChanged(!0),null}stop(){this.playEngine?.input.dispose(),this.playEngine?.stop(),this.playEngine?.dispose(),this.playEngine=null,this.playPhysics?.dispose(),this.playPhysics=null,this.editUiHost&&(this.editUiHost.style.display=``),this.playRenderer?.dispose(),this.playRenderer=null,this.playCanvas.hidden=!0,this.cb.onPlayStateChanged(!1),this.lastAppliedKey=null,this.lastGood&&this.apply(this.lastGood)}};function kB(e){return Math.round(e*100)/100}var AB=new U(0,1,0),jB=new U,MB=new U,NB=new H,PB=new U,FB=new G,IB=new U,LB=new U;function RB(e,t,n){let r=e._object2D?.parent;return r?(FB.copy(r.matrixWorld).invert(),IB.set(t,-n,0).applyMatrix4(FB),LB.set(0,0,0).applyMatrix4(FB),{x:IB.x-LB.x,y:-(IB.y-LB.y)}):{x:t,y:n}}function zB(e,t){for(let n=e.parent;n;n=n.parent)if(n===t)return!0;return!1}function BB(e){let t=e._object2D;if(t)return t.getWorldPosition(PB),{x:PB.x,y:-PB.y};let n=0,r=0,i=e;for(;i;)Array.isArray(i.position)&&(n+=i.position[0]??0,r+=i.position[1]??0),i=i.parent;return{x:n,y:r}}function VB(e){if(!e)return null;if(e.type===`Camera3D`){let t=e.props?.position??[0,2,8];return[t[0]??0,t[1]??2,t[2]??8]}for(let t of e.children??[]){let e=VB(t);if(e)return e}return null}function HB(e){if(!e)return null;if(e.type===`Camera2D`){let t=e.props?.position??[0,0];return[t[0]??0,t[1]??0]}for(let t of e.children??[]){let e=HB(t);if(e)return e}return null}var UB=null;function WB(){if(UB)return UB;let e=document.createElement(`canvas`);e.width=16,e.height=16;let t=e.getContext(`2d`);for(let e=0;e<2;e++)for(let n=0;n<2;n++)t.fillStyle=(n+e)%2==0?`#c252c2`:`#2b2b3b`,t.fillRect(n*8,e*8,8,8);return UB=e.toDataURL(),UB}function GB(e){let t=e.assets;if(t)for(let e of Object.values(t))typeof e?.url==`string`&&!e.url.includes(`/`)&&!e.url.includes(`.`)&&(e.url=WB())}var KB=e({formatSceneJson:()=>r,httpEditorApi:()=>re,mountEditor:()=>qB});gn(),Pv(),GM(),HP(),H_();async function qB(e={}){let t=e.api??re,n=[],r=document.createElement(`style`);r.dataset.incantoEditor=`true`,r.textContent=Uz,document.head.appendChild(r),n.push(()=>r.remove());let i=document.createElement(`div`);i.className=`incanto-editor-root`,i.innerHTML=Cz,(e.host??document.body).appendChild(i),n.push(()=>i.remove());let a=e=>{let t=i.querySelector(e);if(!t)throw Error(`missing ${e}`);return t},o=await t.meta();a(`#engine-version`).textContent=`incanto@${o.version}`,NL(a(`#popover`)),HF(),a(`#docs-btn`).addEventListener(`click`,()=>BF());let s=a(`#lang-btn`),c=[{code:`en`,label:`English`},{code:`ko`,label:`한국어`}],l=()=>{a(`#lang-current`).textContent=KP()===`ko`?`한국어`:`EN`};l(),s.addEventListener(`click`,()=>{document.querySelector(`.lang-menu`)?.remove();let e=document.createElement(`div`);e.className=`context-menu floating lang-menu`;for(let{code:t,label:n}of c){let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item`;let i=document.createElement(`span`);i.textContent=n;let a=document.createElement(`span`);a.textContent=KP()===t?`✓`:``,a.className=`lang-check`,r.append(i,a),r.addEventListener(`click`,()=>{e.remove(),qP(t)}),e.appendChild(r)}document.body.appendChild(e);let t=s.getBoundingClientRect();e.style.left=`${t.left}px`,e.style.top=`${t.bottom+6}px`;let n=t=>{e.contains(t.target)||t.target===s||(e.remove(),document.removeEventListener(`pointerdown`,n,!0))};setTimeout(()=>document.addEventListener(`pointerdown`,n,!0),0)}),JP(()=>{l(),UF(),u.select(u.selection)});let u=new Mz({format:1,type:`scene`,name:``,root:null}),d=a(`#tree`),f=a(`#inspector`),p=a(`#save-btn`),m=a(`#undo-btn`),h=a(`#play-btn`),g=a(`#error-banner`),_=a(`#play-notice`),v=a(`#add-type`),y=a(`#picker`),b=a(`#picker-list`),x=a(`#scenes-btn`),S=o.input,C=o.output,w,T=!1,E=a(`#error-text`),D=e=>{g.hidden=!1,E.textContent=e,NF.error(e)},O=()=>{g.hidden=!0,E.textContent=``};a(`#error-close`).addEventListener(`click`,O);let k=a(`#edit-notice`),A=null,ee=e=>{k.hidden=!1,k.textContent=e,A&&clearTimeout(A),A=setTimeout(()=>{k.hidden=!0,k.textContent=``},6e3)},te={on:!1,brush:`0`},ne=e=>{let t=0,n=0,r=u.working.root,i=e=>{let r=e?.props?.position;Array.isArray(r)&&(t+=Number(r[0]??0),n+=Number(r[1]??0))};i(r);for(let t of e)r=r?.children?.[t],i(r);return{x:t,y:n}},j=!1,ie=(e,t,n=!0)=>{n&&(j=!1);let r=u.selection,i=u.nodeAt(r);if(!r||i?.type!==`TileMap2D`)return;let{cx:a,cy:o}=eR(ne(r),Number(i.props?.tileSize??32),e,t),s=i.props?.cells??[],c=tR(s,a,o,te.brush);!c||JSON.stringify(c)===JSON.stringify(s)||(u.mutate(()=>{i.props||={},i.props.cells=c},{path:r,key:`cells`,value:c},{coalesce:j}),j=!0)},ae=()=>{let e=u.nodeAt(u.selection);te.on&&e?.type!==`TileMap2D`&&(te.on=!1),M.setPaintHandler(te.on?ie:null)},M=new OB(a(`#viewport`),a(`#overlay`),a(`#play-canvas`),{onPick:(e,t)=>u.select(e??null,t),onNodeMoved:(e,t)=>me(e,`position`,t,[0,0]),onNodeScaled:(e,t)=>me(e,`scale`,t,[1,1]),onNodeMoved3D:(e,t)=>me(e,`position`,t,[0,0,0]),onNodeScaled3D:(e,t)=>me(e,`scale`,t,[1,1,1]),onNodeRotated2D:(e,t)=>pe(e,`rotation`,t,0),onNodeRotated3D:(e,t)=>me(e,`rotation`,t,[0,0,0]),onModeChanged:e=>{for(let t of[`move`,`rotate`,`scale`])a(`#tool-${t}`).classList.toggle(`active`,t===e)},onPlayStateChanged:e=>{document.body.classList.toggle(`playing`,e),n.push(()=>document.body.classList.remove(`playing`)),h.classList.toggle(`stop`,e),h.innerHTML=e?`<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12"/></svg> stop`:`<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg> play`,_.hidden=!e,e&&(_.textContent=`▶ simulating — physics + input live; game scripts run only in your real game. Esc or stop to return.`)},onError:D}),oe=Ke().sort(),se=``,ce=e=>{if(e===se)return;se=e,v.textContent=``;let t=e===`3d`?[`3D`,`3D Physics`,`Core`,`Network`,`2D`,`2D Physics`]:[`2D`,`2D Physics`,`Core`,`Network`,`3D`,`3D Physics`];for(let[e]of FF)t.includes(e)||t.push(e);for(let e of t){let t=FF.find(([t])=>t===e)?.[1];if(!t)continue;let n=document.createElement(`optgroup`);n.label=e;for(let e of oe.filter(t)){let t=document.createElement(`option`);t.value=e,t.textContent=e,n.appendChild(t)}n.children.length>0&&v.appendChild(n)}v.value=e===`3d`?`MeshInstance3D`:`Sprite2D`};ce(`2d`);let le=()=>{let e=u.selection??[];if(M.validate(u.working)!==null){for(let e of v.querySelectorAll(`option`))e.disabled=!1;return}for(let t of v.querySelectorAll(`option`)){let n=structuredClone(u.working),r=n.root;if(!n.root)n.root={name:`__probe`,type:t.value};else{for(let t of e)r=r?.children?.[t];if(!r)continue;r.children||=[],r.children.push({name:`__probe`,type:t.value})}t.disabled=M.validate(n)!==null}};v.addEventListener(`mousedown`,le),v.addEventListener(`focus`,le);let ue=t.library?e=>oz(t,{kind:e.kind,...e.target?{target:e.target}:{},...e.shelf?{shelf:e.shelf}:{},...e.assetType?{assetType:e.assetType}:{},...e.onProps?{onProps:e.onProps}:{},...e.asAsset?{onAsset:(e,t,n)=>ZB(u,n,t)}:{}}):void 0,de=!1,fe=()=>{if(!T)return;nB(d,u),sF(a(`#asset-tree`),u),f.textContent=``,cF(f,u,Se,ue)||aR(f,u,{modelRefs:()=>YB(u,`model`),animationsForSelection:()=>u.selection?M.modelAnimationsAt(u.selection):[],bonesForSelection:e=>u.selection?M.boneNamesAt(u.selection,e):[],assetRefs:e=>XB(u,e),addAsset:(e,t)=>ZB(u,e,t),...ue?{openLibrary:ue}:{},confirm:Se,paint:{active:()=>te.on,brush:()=>te.brush,toggle:()=>{te.on=!te.on,ae(),fe()},setBrush:e=>{te.brush=e,fe()}}}),ce(u.working.dimension??`2d`),a(`#hints`).hidden=(u.working.dimension??`2d`)===`3d`,a(`#hints-3d`).hidden=(u.working.dimension??`2d`)!==`3d`,M.setSelection(u.selection,u.extra),ae();let e=u.pendingLivePatch;if(u.pendingLivePatch=null,!M.playing)if(e&&M.patchProp(u.working,e.path,e.key,e.value))g.hidden=!0;else{let e=M.apply(u.working);g.hidden=e===null,e!==null&&D(e)}p.disabled=!u.dirty||!u.working.root,p.title=u.working.root?``:`Add a root node before saving`,m.disabled=!u.canUndo,u.dirty!==de&&(de=u.dirty,NF.change(u.dirty))};u.onChange(fe),u.validator=e=>M.validate(e),u.onError=D;let pe=(e,t,n,r)=>{let i=u.nodeAt(e);i&&u.mutate(()=>{i.props||={},n===r?(delete i.props[t],Object.keys(i.props).length===0&&delete i.props):i.props[t]=n},{path:e,key:t,value:n})},me=(e,t,n,r)=>{let i=u.nodeAt(e);i&&u.mutate(()=>{i.props||={},JSON.stringify(n)===JSON.stringify(r)?(delete i.props[t],Object.keys(i.props).length===0&&delete i.props):i.props[t]=n},{path:e,key:t,value:n})},he=async(e,n,r)=>{M.playing&&M.stop();let i=await t.loadScene(e);w=e,S=n,C=r,T=!0;let s=e??n;a(`#file-chip`).hidden=!s,a(`#file-path`).textContent=s??``,a(`#file-chip`).title=`input: ${n}\noutput: ${r}`,y.hidden=!0,O(),aB(),u.reset(i),o.mode===`project`&&n&&NF.open(n,r)},ge=Sz({list:b,search:a(`#picker-search`),count:a(`#picker-count`),path:a(`#picker-path`)},{entries:async()=>t.scenes?await t.scenes():[],current:()=>w,open:e=>_e(e.rel,e.abs)}),_e=(e,t)=>{let n=()=>{he(e,t,t).catch(e=>D(e instanceof Error?e.message:String(e)))};if(!u.dirty||!u.canUndo){n();return}Se(`'${w??`This scene`}' has unsaved changes. Opening '${e}' discards them.`,`discard & open`,n)},ve=async()=>{y.hidden=!1,await ge.refresh()},ye=()=>{y.hidden=!0};if(a(`#picker-close`).addEventListener(`click`,ye),y.addEventListener(`pointerdown`,e=>{e.target===y&&ye()}),a(`#picker-create`).addEventListener(`click`,()=>{(async()=>{let e=a(`#picker-path`),n=(e.value.trim()||e.placeholder).trim();if(n)try{if(!t.createScene)return;let e=await t.createScene(n.endsWith(`.scene.json`)?n:`${n}.scene.json`);await he(e.rel,e.abs,e.abs)}catch(e){D(e instanceof Error?e.message:String(e))}})()}),o.mode===`project`&&t.scenes&&(x.hidden=!1,x.addEventListener(`click`,()=>void ve())),o.mode===`project`&&o.input===null)await he(void 0,``,``);else if(o.mode===`project`&&t.scenes){let e=await t.scenes(),n=e.length===1?e[0]:void 0;n?await he(n.rel,n.abs,n.abs):await ve()}else await he(void 0,o.input,o.output);a(`#add-btn`).addEventListener(`click`,()=>{let e=u.selection??[],t=v.value,n=u.insertNode({name:t,type:t},e);n&&u.select(n)});let N=a(`#generate`);DL(u),a(`#generate-btn`).addEventListener(`click`,()=>TL(u));let P=a(`#confirm`),F=e=>{if(u.selection===null&&e.length===0){D(`The scene itself cannot be deleted — it IS the file.`);return}if(e.length===0){let e=u.working.root;if(!e)return;let t=JB(e);Se(`This deletes the ROOT '${String(e.name??``)}'${t>0?` AND its ${t} descendant node${t===1?``:`s`}`:``} — the scene goes empty, and the next node you add becomes the new root.`,`delete root`,()=>u.deleteRoot());return}let t=e[0]?.slice(0,-1)??[],n=u.findRemovalReferences(e);if(n.length===0){let n=e.reduce((e,t)=>{let n=u.nodeAt(t);return e+(n?JB(n):0)},0);if(n>0){Se(`This deletes ${e.length>1?`${e.length} nodes`:`'${String(u.nodeAt(e[0]??[])?.name??``)}'`} AND ${n} descendant node${n===1?``:`s`}.`,`delete ${e.length+n} nodes`,()=>{u.removeNodes(e)&&u.select(t)});return}u.removeNodes(e)&&u.select(t);return}a(`#confirm-text`).textContent=`${n.length} reference${n.length>1?`s`:``} still point at the node(s) you are deleting. Unlink them and delete, or cancel.`;let r=a(`#confirm-list`);r.textContent=``;for(let e of n){let t=document.createElement(`div`);t.textContent=`${e.kind===`uid`?`◆ uid`:`⇄ connection`} ${e.where}`,r.appendChild(t)}a(`#confirm-title`).textContent=`still referenced`,a(`#confirm-delete`).textContent=`unlink & delete`,P.hidden=!1,be={selections:e,parentOfFirst:t}},be=null,xe=null;function Se(e,t,n){a(`#confirm-title`).textContent=`are you sure?`,a(`#confirm-text`).textContent=e,a(`#confirm-list`).textContent=``,a(`#confirm-delete`).textContent=t,xe=n,P.hidden=!1}function I(){P.hidden=!0,be=null,xe=null}a(`#confirm-close`).addEventListener(`click`,I),a(`#confirm-cancel`).addEventListener(`click`,I),P.addEventListener(`pointerdown`,e=>{e.target===P&&I()}),a(`#confirm-delete`).addEventListener(`click`,()=>{if(xe){xe(),I();return}be&&u.removeNodesUnlinking(be.selections)&&u.select(be.parentOfFirst),I()}),Xz(F),Zz(e=>{ee(`${YP({en:`Rename: repaired ${e.length} reference${e.length===1?``:`s`}`,ko:`이름 변경: 참조 ${e.length}건 수정`})} — ${e.map(e=>e.where).join(`, `)}`)}),a(`#asset-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),u.startAddingAsset()}),a(`#group-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),u.startAddingGroup()});for(let e of document.querySelectorAll(`.section-toggle`)){let t=e.dataset.section??``,n=document.querySelector(`[data-body="${t}"]`),r=`incanto-editor-section-${t}`,i=t=>{e.classList.toggle(`collapsed`,t),n&&(n.hidden=t),localStorage.setItem(r,t?`1`:``)};i(localStorage.getItem(r)===`1`),e.addEventListener(`click`,()=>i(!e.classList.contains(`collapsed`)))}a(`#delete-btn`).addEventListener(`click`,()=>{F(u.allSelections().filter(e=>e.length>0))});let Ce=()=>{g.hidden=!0,M.play(u.working).then(e=>{e&&D(e)})};if(h.addEventListener(`click`,()=>{if(M.playing){M.stop(),fe();return}if(!e.onPlay){Ce();return}i.querySelector(`.play-menu`)?.remove();let t=document.createElement(`div`);t.className=`context-menu floating play-menu`;let r=[[`preview`,`▶ preview here`,e.playHints?.preview??`simulate in the editor · scripts stripped`],[`debug`,`⤢ run as the game`,e.playHints?.debug??`this page becomes the game, with the debug overlay`]];for(let[n,i,a]of r){let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item play-menu-item`;let o=document.createElement(`span`);o.textContent=i;let s=document.createElement(`span`);s.className=`play-menu-hint`,s.textContent=a,r.append(o,s),r.addEventListener(`click`,()=>{t.remove(),n===`preview`?Ce():e.onPlay?.(n,u.working)}),t.appendChild(r)}i.appendChild(t);let a=h.getBoundingClientRect(),o=t.getBoundingClientRect().width;t.style.left=`${Math.min(Math.max(8,a.right-o),window.innerWidth-o-8)}px`,t.style.top=`${a.bottom+6}px`;let s=e=>{e.type===`keydown`&&e.key!==`Escape`||e.type!==`keydown`&&(t.contains(e.target)||e.target===h)||(t.remove(),document.removeEventListener(`pointerdown`,s,!0),document.removeEventListener(`keydown`,s,!0))};setTimeout(()=>{document.addEventListener(`pointerdown`,s,!0),document.addEventListener(`keydown`,s,!0)},0),n.push(()=>{document.removeEventListener(`pointerdown`,s,!0),document.removeEventListener(`keydown`,s,!0)})}),e.onExit){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.id=`exit-btn`,t.title=`Back to the game`,t.textContent=`✕ exit`,h.parentElement?.insertBefore(t,h),t.addEventListener(`click`,()=>void e.onExit?.())}for(let e of[`move`,`rotate`,`scale`])a(`#tool-${e}`).addEventListener(`click`,()=>M.setMode(e));M.setMode(`move`);let L=a(`#tool-colliders`),we=`incanto-editor-show-colliders`,Te=e=>{M.showColliders=e,L.classList.toggle(`active`,e),localStorage.setItem(we,e?``:`0`)};Te(localStorage.getItem(we)!==`0`),L.addEventListener(`click`,()=>Te(!M.showColliders));let Ee=a(`#hints-dock`),De=`incanto-editor-hints-open`;Ee.classList.toggle(`open`,localStorage.getItem(De)===`1`),a(`#hints-toggle`).addEventListener(`click`,()=>{let e=Ee.classList.toggle(`open`);localStorage.setItem(De,e?`1`:``)}),a(`#fit-btn`).addEventListener(`click`,()=>M.zoomToFit()),Yz(()=>M.zoomToFit()),a(`#gameview-btn`).addEventListener(`click`,()=>M.gameView()),t.saveScene||(p.hidden=!0),p.addEventListener(`click`,()=>{(async()=>{try{await t.saveScene?.(u.working,w),u.markSaved(),NF.save(S,C,u.working)}catch(e){D(e instanceof Error?e.message:String(e))}})()}),m.addEventListener(`click`,()=>u.undo());let Oe=e=>{if(e.key===`Escape`&&M.cancelActiveDrag(),e.key===`Escape`&&!g.hidden&&a(`#docs`).hidden&&P.hidden&&N.hidden&&y.hidden&&!M.playing){O();return}if(e.key===`Escape`&&!a(`#docs`).hidden){VF();return}if(e.key===`Escape`&&!P.hidden){I();return}if(e.key===`Escape`&&!N.hidden){EL();return}if(e.key===`Escape`&&!y.hidden){ye();return}if(e.key===`Escape`&&M.playing){M.stop(),fe();return}if(M.playing)return;let t=e.target.matches(`input, textarea, select`);(e.metaKey||e.ctrlKey)&&e.key===`z`?(e.preventDefault(),u.undo()):(e.metaKey||e.ctrlKey)&&e.key===`s`?(e.preventDefault(),p.disabled||p.click()):!t&&e.code===`KeyF`?M.zoomToFit():!t&&(e.code===`Digit0`||e.code===`Numpad0`)?M.gameView():!t&&e.code===`KeyW`?M.setMode(`move`):!t&&e.code===`KeyE`?M.setMode(`rotate`):!t&&e.code===`KeyR`&&M.setMode(`scale`)};return window.addEventListener(`keydown`,Oe),n.push(()=>window.removeEventListener(`keydown`,Oe)),fe(),e.camera&&M.setEditCamera(e.camera.position,e.camera.target),NF.ready(S,C,o.version),{working:()=>u.working,camera:()=>M.editCamera(),showError:D,dispose(){M.dispose();for(let e of document.querySelectorAll(`.context-menu, .balloon`))e.remove();for(let e of n.splice(0).reverse())e()}}}function JB(e){let t=0;for(let n of e.children??[])t+=1+JB(n);return t}function YB(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>e?.type===t).map(([e])=>`$${e}`):[]}function XB(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>!t||e?.type!==void 0&&t.includes(e.type)).map(([e])=>`$${e}`):[]}function ZB(e,t,n){let r=e.working.assets??{};for(let[e,t]of Object.entries(r))if(t?.url===n.url)return`$${e}`;let i=t;for(let e=2;i in r;e++)i=`${t}-${e}`;return e.mutate(()=>{e.working.assets||(e.working.assets={}),e.working.assets[i]=n}),`$${i}`}var QB=null,$B=null;function eV(){return $B||($B=document.createElement(`canvas`),$B.style.cssText=`position:fixed; inset:0; width:100%; height:100%; display:block;`,document.body.appendChild($B)),$B.style.visibility=``,$B}async function tV(e,t){return QB=await qB({api:re,...e?{camera:e}:{},onPlay:(e,t)=>{e===`debug`&&nV(t)},playHints:{debug:`this page becomes the game — needs a scene with no project behaviors`},...t?{onExit:()=>(QB?.dispose(),QB=null,eV(),t())}:{}}),QB}async function nV(e){let t=e.dimension??`2d`;QB?.dispose(),QB=null;let n=async e=>{$B&&($B.style.visibility=`hidden`),await tV(e.camera,e.exit)};try{if(t===`3d`){let{createGame3D:t}=await ym(async()=>{let{createGame3D:e}=await Promise.resolve().then(()=>MP);return{createGame3D:e}},void 0,import.meta.url);await t({canvas:eV(),scene:e,debug:!0,editor:{open:n}})}else{let{createGame2D:t}=await ym(async()=>{let{createGame2D:e}=await Promise.resolve().then(()=>iy);return{createGame2D:e}},void 0,import.meta.url);await t({canvas:eV(),scene:e,debug:!0,editor:{open:n}})}}catch(e){$B&&($B.style.visibility=`hidden`),(await tV()).showError(`${e instanceof Error?e.message:String(e)}\n\nRunning as the game needs your project's behaviors, which live in your app, not in this page. Start your own dev server with debug enabled and use the ☰ debug menu's "✎ edit this scene" — the switch works both ways from there, with every behavior loaded.`)}}tV().catch(e=>{let t=document.createElement(`div`);t.id=`error-banner`,t.style.cssText=`position:fixed;inset:0 0 auto 0;z-index:99;padding:10px 14px;background:#5b1a24;color:#ffd9df;font:13px ui-monospace,monospace`,t.textContent=e instanceof Error?e.message:String(e),document.body.appendChild(t)});export{He as i,ym as n,Xe as r,Q_ as t};