incanto 0.36.2 → 0.37.0

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.
Files changed (55) hide show
  1. package/bin/incanto-feel.mjs +93 -0
  2. package/bin/incanto-playtest.mjs +136 -0
  3. package/dist/2d.d.ts +2 -2
  4. package/dist/2d.js +3 -3
  5. package/dist/3d.d.ts +14 -3
  6. package/dist/3d.js +4 -4
  7. package/dist/{behavior-DibCwrW7.d.ts → behavior-5o1EkbLD.d.ts} +11 -0
  8. package/dist/{create-game-D-StzrTj.js → create-game-DmGc-Mrn.js} +5 -5
  9. package/dist/{create-game-DnOu2aAa.js → create-game-QqrrK3yr.js} +5 -5
  10. package/dist/debug.d.ts +1 -1
  11. package/dist/{duplicate-Cvb1BSca.js → duplicate-CRtihGmC.js} +1 -1
  12. package/dist/{environment-presets-fK9oyrrR.js → environment-presets-DWHxLHM5.js} +75 -9
  13. package/dist/{gameplay-C0MUMSak.js → gameplay-CsJDUQh_.js} +2 -2
  14. package/dist/gameplay.d.ts +1 -1
  15. package/dist/gameplay.js +1 -1
  16. package/dist/index.d.ts +4 -50
  17. package/dist/index.js +5 -75
  18. package/dist/{loader-BqigZsfF.d.ts → loader-iGq2PT_k.d.ts} +1 -1
  19. package/dist/{loader-DAZlgqeC.js → loader-r49nDwB4.js} +15 -0
  20. package/dist/net.d.ts +1 -1
  21. package/dist/net.js +3 -3
  22. package/dist/{pathfinding-B3QtdhvZ.d.ts → pathfinding-pPrqtlWS.d.ts} +1 -1
  23. package/dist/{physics-2d-B4v39hca.js → physics-2d-C8Hi40qb.js} +2 -2
  24. package/dist/{physics-3d-DFJVMYET.js → physics-3d-C0mWoWXC.js} +3 -3
  25. package/dist/react.d.ts +1 -1
  26. package/dist/react.js +1 -1
  27. package/dist/{register-COGCNitr.js → register-DFSW2Y30.js} +2 -2
  28. package/dist/{register-BHAwM4bK.js → register-DOWGnxe1.js} +1 -1
  29. package/dist/{register-DXwtIVqP.js → register-t15rydSm.js} +2 -2
  30. package/dist/{audit-D7F3n3Nt.js → replay-BuOTl5rM.js} +72 -2
  31. package/dist/replay-DGzhZWrM.d.ts +86 -0
  32. package/dist/test-BiIO9ULW.js +1404 -0
  33. package/dist/test.d.ts +113 -4
  34. package/dist/test.js +3 -3
  35. package/dist/vite.js +1 -1
  36. package/editor/assets/{agent8-DMvBVhe4.js → agent8-CeeI7P_0.js} +1 -1
  37. package/editor/assets/{debug-BgAq55oC.js → debug-DN9X9G6z.js} +1 -1
  38. package/editor/assets/{index-Cy_QsKbh.js → index-C833FBzB.js} +42 -42
  39. package/editor/index.html +1 -1
  40. package/package.json +3 -1
  41. package/schemas/scene.schema.json +24 -0
  42. package/skills/incanto-3d-character.md +35 -0
  43. package/skills/incanto-building-2d-games.md +6 -0
  44. package/skills/incanto-building-3d-games.md +6 -0
  45. package/skills/incanto-game-feel.md +76 -0
  46. package/skills/incanto-node-reference.md +6 -0
  47. package/skills/incanto-playtesting.md +143 -0
  48. package/skills/incanto-verifying-your-game.md +41 -0
  49. package/templates-app/beacon-isle-3d/package.json +1 -1
  50. package/templates-app/tps-3d/package.json +1 -1
  51. package/templates-app/village-quest-3d/package.json +1 -1
  52. package/templates-app/village-quest-3d/src/village.scene.json +3 -1
  53. package/templates-app/village-quest-3d/verify.ts +55 -5
  54. package/dist/errors-DGRtWlSx.d.ts +0 -39
  55. package/dist/test-X_xE6Yay.js +0 -642
@@ -1,6 +1,6 @@
1
1
  import{t as e}from"./GameServer-C56iOUgF.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=80,n=` `;function r(e){return`${i(e,0)}\n`}function i(e,r){if(typeof e!=`object`||!e)return JSON.stringify(e);let o=a(e);if(r*2+o.length<=t)return o;let s=n.repeat(r+1),c=n.repeat(r);if(Array.isArray(e))return e.length===0?`[]`:`[\n${e.map(e=>s+i(e,r+1)).join(`,
2
2
  `)}\n${c}]`;let l=Object.entries(e);return l.length===0?`{}`:`{\n${l.map(([e,t])=>`${s}${JSON.stringify(e)}: ${i(t,r+1)}`).join(`,
3
- `)}\n${c}}`}function a(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return e.length===0?`[]`:`[${e.map(a).join(`, `)}]`;let t=Object.entries(e);return t.length===0?`{}`:`{ ${t.map(([e,t])=>`${JSON.stringify(e)}: ${a(t)}`).join(`, `)} }`}var o=class extends Error{needsToken=!0;constructor(e=`the asset library needs a Verse8 access token`){super(e),this.name=`LibraryAuthError`}};function s(e,t){let n=new Map;for(let r of e){let e=v(r);if(t.length>0&&!c(e,t))continue;let i=e[t.length];i!==void 0&&n.set(i,(n.get(i)??0)+1)}return[...n.entries()].map(([e,t])=>({tag:e,count:t})).sort((e,t)=>t.count-e.count||e.tag.localeCompare(t.tag))}function c(e,t){return t.every((t,n)=>e[n]===t)}function l(e){return e.length===0?`Everything`:e.join(` / `)}var u=[`.glb`,`.gltf`,`.vrm`,`.fbx`],d=[`.png`,`.jpg`,`.jpeg`,`.webp`,`.gif`,`.avif`,`.svg`,`.ktx2`,`.basis`],f=[`.mp3`,`.wav`,`.ogg`,`.m4a`,`.aac`,`.flac`];function p(e){let t=e.split(/[?#]/)[0]??``,n=t.lastIndexOf(`/`),r=n===-1?t:t.slice(n+1),i=r.lastIndexOf(`.`);return i<=0?``:r.slice(i).toLowerCase()}function m(e){let t=p(e);return u.includes(t)?`model`:d.includes(t)?`image`:f.includes(t)?`audio`:`any`}function h(e,t){if(t===`any`)return!0;let n=m(e);return n===t||n===`any`}function g(e){let t=e.metadata,n=(typeof t.originalName==`string`?t.originalName:void 0)??e.url.split(/[?#]/)[0]??``,r=n.slice(n.lastIndexOf(`/`)+1),i=p(r),a=i?r.slice(0,-i.length):r;return decodeURIComponent(a||e.id)}function _(e){return g(e).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function v(e){let t=e.metadata.tags;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function y(e){let t=e.metadata,n=[],r=p(e.url);r&&n.push([`format`,r.replace(`.`,``)]);let i=b(e);return i&&n.push([`pixels`,`${i[0]} × ${i[1]}`]),typeof t.size==`number`&&n.push([`bytes`,x(t.size)]),typeof t.type==`string`&&n.push([`kind`,t.type]),typeof t.style==`string`&&n.push([`style`,t.style]),typeof t.uploadedAt==`string`&&n.push([`added`,t.uploadedAt.slice(0,10)]),n}function b(e){let t=e.metadata,n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?e:null,r=[n(t.width),n(t.height)];if(r[0]&&r[1])return[r[0],r[1]];for(let e of[`size`,`dimensions`]){let r=t[e],i=n(r?.width),a=n(r?.height);if(i&&a)return[i,a]}return null}function x(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function S(e,t=`any`,n){let r=t===`any`?m(e.url):t,i=n??(r===`model`?`model`:r===`audio`?`audio`:`texture`),a={type:i,url:e.url};if(i===`spritesheet`){let t=T(e);t&&(a.frameWidth=t[0],a.frameHeight=t[1])}return a}function C(e){return p(e)===`.json`}function w(e){return e.replace(/\.json(\?.*)?$/,`.png$1`)}function T(e){let t=e.metadata,n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?e:null,r=n(t.frameWidth),i=n(t.frameHeight);if(r&&i)return[r,i];let a=t.frame,o=n(a?.width),s=n(a?.height);return o&&s?[o,s]:null}async function E(e){if(e.ok)return e;let t=await e.text(),n=t;try{n=JSON.parse(t).error??t}catch{}throw Error(n||`HTTP ${e.status}`)}async function D(){return await(await E(await fetch(`/api/meta`))).json()}async function O(){return await(await E(await fetch(`/api/scenes`))).json()}async function k(e){return await(await E(await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})}))).json()}function A(e){return e?`/api/scene?file=${encodeURIComponent(e)}`:`/api/scene`}async function ee(e){return await(await E(await fetch(A(e)))).json()}async function te(e,t){await E(await fetch(A(t),{method:`PUT`,body:r(e)}))}async function ne(e,t){let n=new URLSearchParams({tags:e.tags.join(`,`),page:String(e.page??1),limit:String(e.limit??24)});e.keyword?.trim()&&n.set(`keyword`,e.keyword.trim());let r=await fetch(`/api/library?${n}`,{headers:t?{"x-incanto-v8-token":t}:{}});if(r.status===401)throw new o((await r.json().catch(()=>({}))).error);return await(await E(r)).json()}var re={meta:D,loadScene:ee,saveScene:te,scenes:O,createScene:k,library:ne},j=class{connections=[];connect(e,t){return this.connections.some(t=>t.fn===e)||this.connections.push({fn:e,once:t?.once??!1}),()=>this.disconnect(e)}disconnect(e){let t=this.connections.findIndex(t=>t.fn===e);t!==-1&&this.connections.splice(t,1)}disconnectAll(){this.connections.length=0}emit(...e){let t=[...this.connections];for(let n of t)this.connections.includes(n)&&(n.once&&this.disconnect(n.fn),n.fn(...e))}get connectionCount(){return this.connections.length}},ie=class{changed=new j;_master=1;_sfx=1;_music=1;_muted=!1;get master(){return this._master}set master(e){this.assign(`_master`,e)}get sfx(){return this._sfx}set sfx(e){this.assign(`_sfx`,e)}get music(){return this._music}set music(e){this.assign(`_music`,e)}get muted(){return this._muted}set muted(e){e!==this._muted&&(this._muted=e,this.changed.emit())}effectiveVolume(e,t){if(this._muted)return 0;let n=e===`music`?this._music:this._sfx;return this._master*n*ae(t)}assign(e,t){if(!Number.isFinite(t))return;let n=ae(t);n!==this[e]&&(this[e]=n,this.changed.emit())}};function ae(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}function M(e,t,n){let r=se(e,t);return n===`in`?r:1-r}function oe(e,t){let n=se(e,t)*Math.PI/2;return{out:ce(Math.cos(n)),in:ce(Math.sin(n))}}function se(e,t){return!Number.isFinite(e)||t<=0?1:ce(e/t)}function ce(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}var le=null,ue=null;function de(){let e=globalThis;return e.AudioContext??e.webkitAudioContext??null}function fe(){if(le)return le();let e=de();return e?new e:null}function pe(){return ue?ue():typeof Audio>`u`?null:new Audio}var me={src:``,setGain(){},setLoop(){},play(){},stop(){}},he=class{src;el;gainNode;constructor(e,t,n){this.src=e,this.el=t;try{t.crossOrigin=`anonymous`}catch{}t.src=e;let r=n.createMediaElementSource(t);this.gainNode=n.createGain(),r.connect(this.gainNode),this.gainNode.connect(n.destination)}setGain(e){this.gainNode.gain.value=e}setLoop(e){this.el.loop=e}play(){this.el.play().catch(()=>{})}stop(){this.el.pause(),this.el.currentTime=0}},ge=class{ctx=null;resolved=!1;get available(){return this.ensure()!==null}ensure(){return this.resolved||=(this.ctx=fe(),!0),this.ctx}createTrack(e){let t=this.ensure(),n=pe();return!t||!n?{...me,src:e}:(t.state===`suspended`&&t.resume(),new he(e,n,t))}unlock(){let e=this.ensure();e&&e.state===`suspended`&&e.resume()}},_e=null,ve=class{buses;backend=null;resolved=!1;active=null;outgoing=null;_bus=`music`;_volume=1;constructor(e){this.buses=e}get current(){return this.active?.track.src??null}get volume(){return this._volume}ensure(){if(!this.resolved){let e=_e?_e(this.buses):new ge;this.backend=e&&e.available===!1?null:e,this.resolved=!0}return this.backend}unlock(){this.ensure()?.unlock(),this.active?.track.play()}play(e,t={}){let n=this.ensure();if(!n)return;this.killOutgoing(),this.active?.track.stop(),this._bus=t.bus??`music`;let r=n.createTrack(e);r.setLoop(t.loop??!0);let i=Math.max(0,t.fadeIn??0);this.active={track:r,phase:i>0?`fadeIn`:`steady`,t:0,duration:i,freeOnEnd:!1},r.setGain(i>0?0:this.busGain()),r.play()}crossfadeTo(e,t=2){let n=this.ensure();if(!n||this.active&&this.active.track.src===e&&this.active.phase!==`fadeOut`)return;let r=Math.max(0,t);if(!this.active){this.play(e,{fadeIn:r});return}this.killOutgoing(),this.outgoing={...this.active,phase:`crossOut`,t:0,duration:r,freeOnEnd:!0};let i=n.createTrack(e);i.setLoop(!0),i.setGain(0),i.play(),this.active={track:i,phase:`crossIn`,t:0,duration:r,freeOnEnd:!1},this.applyGains()}stop(e=0){this.killOutgoing();let t=this.active;if(this.active=null,!t)return;let n=Math.max(0,e);if(n<=0){t.track.stop();return}this.outgoing={...t,phase:`fadeOut`,t:0,duration:n,freeOnEnd:!0},this.applyGains()}setVolume(e){this._volume=ye(e)}tick(e){this.active&&(this.active.phase===`fadeIn`||this.active.phase===`crossIn`)&&(this.active.t+=e,this.active.t>=this.active.duration&&(this.active.phase=`steady`)),this.outgoing&&(this.outgoing.t+=e,this.outgoing.t>=this.outgoing.duration&&(this.outgoing.track.setGain(0),this.outgoing.track.stop(),this.outgoing=null)),this.applyGains()}busGain(){return this.buses.effectiveVolume(this._bus,this._volume)}applyGains(){let e=this.busGain();if(this.active?.phase===`crossIn`&&this.outgoing?.phase===`crossOut`){let t=oe(this.active.t,this.active.duration);this.active.track.setGain(e*t.in),this.outgoing.track.setGain(e*t.out);return}if(this.active){let t=this.active.phase===`fadeIn`?M(this.active.t,this.active.duration,`in`):1;this.active.track.setGain(e*t)}if(this.outgoing){let t=this.outgoing.phase===`fadeOut`||this.outgoing.phase===`crossOut`?M(this.outgoing.t,this.outgoing.duration,`out`):0;this.outgoing.track.setGain(e*t)}}killOutgoing(){this.outgoing?.track.stop(),this.outgoing=null}};function ye(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}var N=class extends Error{code;details;constructor(e,t,n={}){super(t),this.name=`IncantoError`,this.code=e,this.details=n}},P=class{state;constructor(e){this.state=e>>>0,this.state===0&&(this.state=2654435769)}next(){this.state=this.state+1831565813>>>0;let e=this.state;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}range(e,t){return e+this.next()*(t-e)}int(e,t){return Math.floor(this.range(e,t+1))}pick(e){if(e.length===0)throw new N(`BAD_FORMAT`,`Rng.pick needs a non-empty array.`);return e[this.int(0,e.length-1)]}},F={coin:{wave:`square`,baseFreq:988,freqRamp:1800,attack:0,sustain:.04,decay:.18,duty:.5,volume:.4},pickup:{wave:`sine`,baseFreq:660,freqRamp:900,attack:.005,sustain:.05,decay:.12,volume:.45},jump:{wave:`square`,baseFreq:320,freqRamp:600,attack:0,sustain:.03,decay:.12,duty:.35,volume:.4},hurt:{wave:`sawtooth`,baseFreq:380,freqRamp:-520,attack:0,sustain:.05,decay:.16,volume:.5},hit:{wave:`noise`,baseFreq:600,freqRamp:-400,attack:0,sustain:.02,decay:.1,volume:.55},explosion:{wave:`noise`,baseFreq:420,freqRamp:-360,attack:0,sustain:.12,decay:.5,volume:.6},powerup:{wave:`square`,baseFreq:440,freqRamp:1200,attack:.01,sustain:.18,decay:.22,duty:.5,vibratoDepth:.08,vibratoRate:18,volume:.4},laser:{wave:`sawtooth`,baseFreq:1400,freqRamp:-2600,attack:0,sustain:.03,decay:.14,volume:.4},shoot:{wave:`square`,baseFreq:900,freqRamp:-1400,attack:0,sustain:.02,decay:.1,duty:.25,volume:.45},blip:{wave:`square`,baseFreq:760,freqRamp:0,attack:0,sustain:.015,decay:.04,duty:.5,volume:.35},select:{wave:`triangle`,baseFreq:520,freqRamp:420,attack:.002,sustain:.04,decay:.08,volume:.4},step:{wave:`noise`,baseFreq:220,freqRamp:-120,attack:0,sustain:.01,decay:.05,volume:.3},win:{wave:`square`,baseFreq:523,freqRamp:900,attack:.01,sustain:.35,decay:.3,duty:.5,vibratoDepth:.05,vibratoRate:10,volume:.42},lose:{wave:`sawtooth`,baseFreq:392,freqRamp:-300,attack:.01,sustain:.3,decay:.4,volume:.45}},be=Object.keys(F),xe=Math.PI*2;function Se(e,t={}){let n=t.sampleRate??44100,r=t.pitch??1,i=new P((t.seed??0)^42405),a=e.attack+e.sustain+e.decay,o=Math.max(1,Math.ceil(a*n)),s=new Float32Array(o),c=e.duty??.5,l=e.vibratoDepth??0,u=e.vibratoRate??0,d=0,f=i.range(-1,1),p=0;for(let t=0;t<o;t++){let a=t/n,o;if(a<e.attack)o=e.attack>0?a/e.attack:1;else if(a<e.attack+e.sustain)o=1;else{let t=a-e.attack-e.sustain;o=e.decay>0?Math.max(0,1-t/e.decay):0}let m=(e.baseFreq+e.freqRamp*a)*r;l>0&&u>0&&(m+=m*l*Math.sin(xe*u*a)),m=Math.max(0,m),d+=m/n,d-=Math.floor(d);let h;switch(e.wave){case`square`:h=d<c?1:-1;break;case`sawtooth`:h=2*d-1;break;case`triangle`:h=4*Math.abs(d-.5)-1;break;case`sine`:h=Math.sin(xe*d);break;default:p-=m/n,p<=0&&(f=i.range(-1,1),p+=1),h=f;break}s[t]=I(h*o*e.volume)}return s}function I(e){return e<-1?-1:e>1?1:e}var Ce=[`inverse`,`linear`,`exponential`];function L(e,t){let n=Math.max(0,t.refDistance),r=Math.max(n,t.maxDistance),i=t.rolloffFactor??1;if(!Number.isFinite(e))return 1;let a=we(e,n,r);if(a<=n)return 1;let o;switch(t.rolloff){case`linear`:{let e=r-n;o=e<=0?1:1-i*(a-n)/e;break}case`exponential`:o=n<=0?1:(a/n)**-i;break;default:o=n/(n+i*(a-n));break}return Number.isFinite(o)?Te(o):0}function we(e,t,n){return e<t?t:e>n?n:e}function Te(e){return e<0?0:e>1?1:e}var Ee={engine:{oscillators:[[`sawtooth`,55,0],[`sawtooth`,55,12]],noise:null,lowpassHz:900},wind:{oscillators:[],noise:[700,.6,1],lowpassHz:4e3},hum:{oscillators:[[`sine`,110,0],[`triangle`,110,5]],noise:null,lowpassHz:1200},noise:{oscillators:[],noise:[1200,.3,1],lowpassHz:6e3}},De={set:()=>{},stop:()=>{},stopped:!0};function Oe(e,t,n){let r=Ee[t]??Ee.hum,i=e.createGain();i.gain.value=0,i.connect(e.destination);let a=n,o=e.createBiquadFilter();o.type=`lowpass`,o.frequency.value=r.lowpassHz,o.connect(i);let s=[];for(let[t,n,i]of r.oscillators){let r=e.createOscillator();r.type=t,r.frequency.value=n,r.detune.value=i,r.connect(o),r.start(),s.push(r)}let c=null,l=null;if(r.noise){let[t,n,i]=r.noise,a=e.createBuffer(1,e.sampleRate*2,e.sampleRate),s=a.getChannelData(0),u=987654321;for(let e=0;e<s.length;e++)u=u*1664525+1013904223>>>0,s[e]=u/4294967295*2-1;c=e.createBufferSource(),c.buffer=a,c.loop=!0,l=e.createBiquadFilter(),l.type=`bandpass`,l.frequency.value=t,l.Q.value=n;let d=e.createGain();d.gain.value=i,c.connect(l),l.connect(d),d.connect(o),c.start()}let u=r.oscillators.map(([,e])=>e),d=r.noise?.[0]??0,f=!1,p=()=>e.currentTime;return i.gain.setTargetAtTime(.4*a,p(),.05),{get stopped(){return f},set({pitch:e,volume:t}){if(!f){if(e!==void 0){let t=Math.max(.05,e);s.forEach((e,n)=>{e.frequency.setTargetAtTime(u[n]*t,p(),.03)}),l&&l.frequency.setTargetAtTime(d*t,p(),.03)}t!==void 0&&i.gain.setTargetAtTime(Math.max(0,Math.min(1,t))*a,p(),.04)}},stop(e=.15){f||(f=!0,i.gain.setTargetAtTime(0,p(),Math.max(.01,e/3)),setTimeout(()=>{for(let e of s)e.stop();c?.stop(),i.disconnect()},e*1e3+120))}}}var ke=De;function Ae(e,t){let[n,r,i]=t.position,[a,o,s]=t.forward,[c,l,u]=t.up,d=e;d.positionX&&d.forwardX&&d.upX?(d.positionX.value=n,d.positionY&&(d.positionY.value=r),d.positionZ&&(d.positionZ.value=i),d.forwardX.value=a,d.forwardY&&(d.forwardY.value=o),d.forwardZ&&(d.forwardZ.value=s),d.upX.value=c,d.upY&&(d.upY.value=l),d.upZ&&(d.upZ.value=u)):(d.setPosition?.(n,r,i),d.setOrientation?.(a,o,s,c,l,u))}function je(e,t){let n=e;n.positionX?(n.positionX.value=t[0],n.positionY&&(n.positionY.value=t[1]),n.positionZ&&(n.positionZ.value=t[2])):n.setPosition?.(t[0],t[1],t[2])}var Me=null;function Ne(){let e=globalThis;return e.AudioContext??e.webkitAudioContext??null}function Pe(){if(Me)return Me();let e=Ne();return e?new e:null}function Fe(e,t,n){return`${e.wave}|${e.baseFreq}|${e.freqRamp}|${e.attack}|${e.sustain}|${e.decay}|${e.duty}|${e.vibratoDepth}|${e.vibratoRate}|${e.volume}|${t.pitch??1}|${t.seed??0}|${n}`}var Ie=class{ctx=null;resolved=!1;pcmCache=new Map;get available(){return this.ensure()!==null}ensure(){return this.resolved||=(this.ctx=Pe(),!0),this.ctx}startVoice(e,t=1){let n=this.ensure();return n?(n.state===`suspended`&&n.resume(),Oe(n,e,t)):ke}unlock(){let e=this.ensure();e&&e.state===`suspended`&&e.resume()}play(e,t,n={}){let r=this.ensure();if(!r||(r.state===`suspended`&&r.resume(),t<=0))return;let i=r.sampleRate||44100,a={sampleRate:i,pitch:n.pitch,seed:n.seed},o=Fe(e,a,i),s=this.pcmCache.get(o);s||(s=Se(e,a),this.pcmCache.set(o,s));let c=r.createBuffer(1,s.length,i);c.getChannelData(0).set(s);let l=r.createGain();if(l.gain.value=t,n.spatial&&typeof r.createPanner==`function`){let e=n.spatial,t=r.createPanner();t.panningModel=`HRTF`,t.distanceModel=e.rolloff,t.refDistance=Math.max(0,e.refDistance),t.maxDistance=Math.max(e.refDistance,e.maxDistance),t.rolloffFactor=e.rolloffFactor??1,je(t,e.position),r.listener&&Ae(r.listener,e.listener),l.connect(t),t.connect(r.destination)}else l.connect(r.destination);let u=r.createBufferSource();u.buffer=c,u.connect(l),u.start()}};function Le(e){return e.startsWith(`@t:`)?e.slice(3):null}function Re(e,t){return t?e.replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e):e}var ze=class{changed=new j;tables={};current=`en`;constructor(e,t){e&&this.load(e),t&&(this.locale=t)}load(e){for(let[t,n]of Object.entries(e)){this.tables[t]??={};let e=this.tables[t];for(let[t,r]of Object.entries(n))typeof r==`string`&&(e[t]=r)}}get locale(){return this.current}set locale(e){e===this.current||e===``||(this.current=e,this.changed.emit(e))}available(){let e=new Set([`en`]);for(let[t,n]of Object.entries(this.tables))Object.keys(n).length>0&&e.add(t);return[...e]}t(e,t){let n=this.tables[this.current]?.[e];if(n!==void 0)return Re(n,t);let r=this.tables.en?.[e];return r===void 0?e:Re(r,t)}resolve(e,t){let n=Le(e);return n===null?e:this.t(n,t)}has(e){for(let t of Object.values(this.tables))if(t[e]!==void 0)return!0;return!1}};function Be(e){if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=typeof e;return t===`string`||t===`number`||t===`boolean`?t:`object`}function Ve(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>Ve(e,t[n]));if(e!==null&&t!==null&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)||Array.isArray(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>n in t&&Ve(e[n],t[n]))}return!1}function He(e){return typeof e!=`object`||!e?e:JSON.parse(JSON.stringify(e))}function Ue(e,t,n,r){if(r&&typeof e==`string`&&!r.includes(e))throw new N(`PROP_TYPE_MISMATCH`,`Prop '${n}' is ${JSON.stringify(e)}, which is not one of: ${r.map(e=>JSON.stringify(e)).join(`, `)}.`,{prop:n,validOptions:[...r]});let i=Be(t);if(i===`null`)return;let a=Be(e);if(a!==i)throw new N(`PROP_TYPE_MISMATCH`,`Prop '${n}' expects ${i} (default ${JSON.stringify(t)}), got ${a} (${JSON.stringify(e)}).`,{prop:n});if(typeof e==`number`&&!Number.isFinite(e))throw new N(`PROP_TYPE_MISMATCH`,`Prop '${n}' is ${e} — props must be finite numbers.`,{prop:n});if(Array.isArray(t)&&Array.isArray(e)&&t.length>0){if(e.length!==t.length)throw new N(`PROP_TYPE_MISMATCH`,`Prop '${n}' expects an array of length ${t.length} (default ${JSON.stringify(t)}), got length ${e.length}.`,{prop:n});for(let r=0;r<t.length;r++)Ue(e[r],t[r],`${n}[${r}]`)}}var We=new Map;function R(e,t){let n=We.get(e.typeName);if(n&&n!==e&&!t?.replace)throw new N(`DUPLICATE_NODE_TYPE`,`Node type '${e.typeName}' is already registered by a different class. Replacing an implementation (e.g. under hot reload) needs registerNode(ctor, { replace: true }).`,{nodeType:e.typeName});We.set(e.typeName,e)}function Ge(e){let t=We.get(e);if(!t){let t=[...We.keys()];throw new N(`UNKNOWN_NODE_TYPE`,`Unknown node type '${e}'. Registered types: [${t.join(`, `)}].`,{nodeType:e,validOptions:t})}return t}function Ke(){return[...We.keys()]}function qe(e){return Xe(Ge(e))}function Je(e){let t=[],n=e;for(;n;){Object.hasOwn(n,`signals`)&&n.signals&&t.unshift(...n.signals);let e=Object.getPrototypeOf(n);n=typeof e==`function`?e:null}return[...new Set(t)]}function Ye(e){return Je(Ge(e))}function Xe(e){let t=[],n=e;for(;n;){Object.hasOwn(n,`props`)&&n.props&&t.unshift(n.props);let e=Object.getPrototypeOf(n);n=typeof e==`function`?e:null}return Object.assign({},...t)}function Ze(e){let t=[],n=e;for(;n;){Object.hasOwn(n,`propAliases`)&&n.propAliases&&t.unshift(n.propAliases);let e=Object.getPrototypeOf(n);n=typeof e==`function`?e:null}return Object.assign({},...t)}function Qe(e,t,n,r,i={},a={}){for(let[n,r]of Object.entries(t))e[n]=He(r.default);if(n)for(let[o,s]of Object.entries(n)){let n=t[o]?o:i[o]??o,c=t[n];if(!c){let e=Object.keys(t);throw new N(`UNKNOWN_PROP`,`Unknown prop '${o}' on '${r}'. Valid props: [${e.join(`, `)}].`,{prop:o,nodeType:r,validOptions:e})}let l=a[n],u=c.options&&l&&l.length>0?[...c.options,...l]:c.options;Ue(s,c.default,`${r}.${n}`,u),e[n]=He(s)}}function $e(e,t,n){let r=Ge(e),i=new r;return Qe(i,qe(e),t,e,Ze(r),n),i}var et=class{static props;static signals;node;get engine(){let e=this.node?.tree?.engine;if(!e)throw new N(`TREE_VIOLATION`,`Behavior on '${this.node?.name??`?`}' is not attached to a running engine (node must be in a scene set on an Engine).`);return e}get input(){return this.engine.input}get rng(){return this.engine.rng}get log(){return this.engine.log}getNode(e){return this.node.getNode(e)}emit(e,...t){this.node.emit(e,...t)}on(e,t,n){return this.node.on(e,t,n)}},tt=class extends et{},nt=new Map;function rt(e){return nt.has(e)}function it(e,t,n){let r=nt.get(e);if(r&&r!==t&&!n?.replace)throw new N(`DUPLICATE_BEHAVIOR`,`Behavior '${e}' is already registered by a different class. Replacing an implementation (e.g. under hot reload) needs registerBehavior(name, ctor, { replace: true }).`);nt.set(e,t)}function at(e){let t=nt.get(e);if(!t){let t=[...nt.keys()];throw new N(`UNKNOWN_BEHAVIOR`,`Unknown behavior '${e}'. Registered behaviors: [${t.join(`, `)}]. Did you forget registerBehavior('${e}', ${e})?`,{validOptions:t})}return t}function ot(e){let t=nt.get(e);return t?Xe(t):{}}function st(e){let t=nt.get(e);return t?Je(t):[]}function ct(e,t){let n=at(e),r=new n;return Qe(r,Xe(n),t,`script:${e}`),r}function lt(e,t,...n){e?.log[t](...n),t===`error`?console.error(...n):t===`warn`?console.warn(...n):console.info(...n)}var ut=class{capacity;times;head=0;count=0;constructor(e=60){this.capacity=e,this.times=Array(e)}push(e){this.times[(this.head+this.count)%this.capacity]=e,this.count<this.capacity?this.count+=1:this.head=(this.head+1)%this.capacity}fps(){let e=this.spanMs();return e>0?(this.count-1)/e*1e3:0}frameMs(){let e=this.spanMs();return e>0?e/(this.count-1):0}clear(){this.head=0,this.count=0}spanMs(){if(this.count<2)return 0;let e=this.times[this.head];return this.times[(this.head+this.count-1)%this.capacity]-e}};function dt(e){let t=e;return!!t&&(t.isContentEditable===!0||t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`)}var ft=class{actions=new Map;down=new Set;pressedEdge=new Set;releasedEdge=new Set;detach=null;declare(e){for(let[t,n]of pt(e))this.actions.set(t,n)}pointerPosition(){return this.pointerPos?{...this.pointerPos}:null}setPointerPosition(e,t,n){let r=n?.getBoundingClientRect?.();if(!r||r.width===0||r.height===0){this.pointerPos={x:e,y:t};return}let i=n,a=typeof i.width==`number`&&i.width>0?i.width/r.width:1,o=typeof i.height==`number`&&i.height>0?i.height/r.height:1;this.pointerPos={x:(e-r.left)*a,y:(t-r.top)*o}}pointerPos=null;handleKey(e,t){t?this.down.has(e)||(this.down.add(e),this.pressedEdge.add(e)):this.down.has(e)&&(this.down.delete(e),this.releasedEdge.add(e))}injectedDown=new Set;injectedPressed=new Set;injectedReleased=new Set;injectedVectors=new Map;pressAction(e){this.button(e),this.injectedDown.has(e)||(this.injectedDown.add(e),this.injectedPressed.add(e))}releaseAction(e){this.button(e),this.injectedDown.delete(e)&&this.injectedReleased.add(e)}setActionVector(e,t,n){if(this.get(e).type!==`vector2`)throw new N(`BAD_FORMAT`,`Input action '${e}' is a button — use pressAction/releaseAction, not setActionVector.`);if(!Number.isFinite(t)||!Number.isFinite(n))throw new N(`BAD_FORMAT`,`setActionVector('${e}') needs finite numbers, got (${t}, ${n}).`);t===0&&n===0?this.injectedVectors.delete(e):this.injectedVectors.set(e,{x:t,y:n})}touchControls(){let e=[];for(let[t,n]of this.actions)n.touch&&e.push({action:t,kind:n.touch});return e}clearInjected(){this.injectedDown.clear(),this.injectedPressed.clear(),this.injectedReleased.clear(),this.injectedVectors.clear()}dx=0;dy=0;wheel=0;handleMouseButton(e,t){this.handleKey(`Mouse${e}`,t)}handlePointerMove(e,t){this.dx+=e,this.dy+=t}handleWheel(e){this.wheel+=e}pointerDelta(){let e={x:this.dx,y:this.dy};return this.dx=0,this.dy=0,e}wheelDelta(){let e=this.wheel;return this.wheel=0,e}padAxesState={lx:0,ly:0,rx:0,ry:0};padButtonsDown=0;pollGamepad(e){let t=e=>Math.abs(e)<.15?0:e;if(!e){for(let e=0;e<17;e++)this.padButtonsDown&1<<e&&this.handleKey(`Pad${e}`,!1);this.padButtonsDown=0,this.padAxesState.lx=0,this.padAxesState.ly=0,this.padAxesState.rx=0,this.padAxesState.ry=0;return}for(let t=0;t<Math.min(17,e.buttons.length);t++){let n=e.buttons[t]?.pressed===!0;n!==((this.padButtonsDown&1<<t)!=0)&&(this.handleKey(`Pad${t}`,n),this.padButtonsDown=n?this.padButtonsDown|1<<t:this.padButtonsDown&~(1<<t))}this.padAxesState.lx=t(e.axes[0]??0),this.padAxesState.ly=t(e.axes[1]??0),this.padAxesState.rx=t(e.axes[2]??0),this.padAxesState.ry=t(e.axes[3]??0)}padAxes(e=0){return e===0?{x:this.padAxesState.lx,y:this.padAxesState.ly}:{x:this.padAxesState.rx,y:this.padAxesState.ry}}attachGamepad(e){if(typeof navigator>`u`||typeof navigator.getGamepads!=`function`)return()=>{};let t=e.updated.connect(()=>{let e=navigator.getGamepads(),t=null;for(let n of e)if(n?.connected){t=n;break}this.pollGamepad(t)}),n=this.detach;return this.detach=()=>{n?.(),t()},t}attachPointer(e,t){let n=0,r=r=>{n++,this.setPointerPosition(r.clientX,r.clientY,e),this.handleMouseButton(r.button,!0),t?.lockOnClick&&document.pointerLockElement!==e&&e.requestPointerLock?.()},i=e=>{n=Math.max(0,n-1),this.handleMouseButton(e.button,!1)},a=t=>{this.setPointerPosition(t.clientX,t.clientY,e),(document.pointerLockElement===e||n>0)&&this.handlePointerMove(t.movementX,t.movementY)},o=e=>{e.preventDefault(),this.handleWheel(e.deltaY)},s=e=>e.preventDefault();e.addEventListener(`mousedown`,r),window.addEventListener(`mouseup`,i),window.addEventListener(`mousemove`,a),e.addEventListener(`wheel`,o,{passive:!1}),e.addEventListener(`contextmenu`,s);let c=()=>{e.removeEventListener(`mousedown`,r),window.removeEventListener(`mouseup`,i),window.removeEventListener(`mousemove`,a),e.removeEventListener(`wheel`,o),e.removeEventListener(`contextmenu`,s)},l=this.detach;return this.detach=()=>{l?.(),c()},c}attachKeyboard(e,t){let n=t?.preventDefault??`bound`,r=e=>{dt(e.target)||(e.ctrlKey||e.metaKey)&&!e.code.startsWith(`Control`)&&!e.code.startsWith(`Meta`)||(n===`bound`&&this.codeIsBound(e.code)&&e.preventDefault?.(),e.repeat||this.handleKey(e.code,!0))},i=e=>{dt(e.target)||this.handleKey(e.code,!1)};e.addEventListener(`keydown`,r),e.addEventListener(`keyup`,i);let a=()=>{e.removeEventListener(`keydown`,r),e.removeEventListener(`keyup`,i)},o=this.detach;return this.detach=()=>{o?.(),a()},a}codeIsBound(e){for(let t of this.actions.values())if(t.type===`button`){if(t.keys.includes(e))return!0}else{let n=t.keys;if(n.up.includes(e)||n.down.includes(e)||n.left.includes(e)||n.right.includes(e))return!0}return!1}dispose(){this.detach?.(),this.detach=null}isPressed(e){return this.button(e).keys.some(e=>this.down.has(e))||this.injectedDown.has(e)}justPressed(e){return this.button(e).keys.some(e=>this.pressedEdge.has(e))||this.injectedPressed.has(e)}justReleased(e){return this.button(e).keys.some(e=>this.releasedEdge.has(e))||this.injectedReleased.has(e)}keyPressed(e){return this.down.has(e)}keyJustPressed(e){return this.pressedEdge.has(e)}mousePressed(e=0){return this.down.has(`Mouse${e}`)}mouseJustPressed(e=0){return this.pressedEdge.has(`Mouse${e}`)}mouseJustReleased(e=0){return this.releasedEdge.has(`Mouse${e}`)}getVector(e){let t=this.get(e);if(t.type!==`vector2`)throw new N(`BAD_FORMAT`,`Input action '${e}' is a button — use isPressed/justPressed, not getVector.`);let n=e=>+!!e.some(e=>this.down.has(e)),r=n(t.keys.right)-n(t.keys.left),i=n(t.keys.down)-n(t.keys.up),a=this.injectedVectors.get(e);a&&(r+=a.x,i+=a.y);let o=Math.hypot(r,i);return o>1&&(r/=o,i/=o),{x:r,y:i}}endFrame(){this.pressedEdge.clear(),this.releasedEdge.clear(),this.injectedPressed.clear(),this.injectedReleased.clear()}clear(){this.actions.clear(),this.pressedEdge.clear(),this.releasedEdge.clear(),this.clearInjected()}get(e){let t=this.actions.get(e);if(!t)throw new N(`BAD_FORMAT`,`Unknown input action '${e}'. Declared actions: [${[...this.actions.keys()].join(`, `)}].`);return t}button(e){let t=this.get(e);if(t.type!==`button`)throw new N(`BAD_FORMAT`,`Input action '${e}' is a vector2 — use getVector, not button queries.`);return t}};function pt(e){let t=new Map;for(let[n,r]of Object.entries(e)){let e=r;if(e.type===`button`){let r=e.keys;if(!Array.isArray(r)||r.some(e=>typeof e!=`string`))throw new N(`BAD_FORMAT`,`Input action '${n}': button "keys" must be an array of KeyboardEvent.code strings.`);if(e.touch!==void 0&&e.touch!==`button`)throw new N(`BAD_FORMAT`,`Input action '${n}': button "touch" must be 'button', got ${JSON.stringify(e.touch)}.`);t.set(n,{type:`button`,keys:[...r],...e.touch===`button`?{touch:`button`}:{}})}else if(e.type===`vector2`){let r=e.keys;for(let e of[`up`,`down`,`left`,`right`])if(!Array.isArray(r?.[e]))throw new N(`BAD_FORMAT`,`Input action '${n}': vector2 "keys" needs arrays for up/down/left/right.`);if(e.touch!==void 0&&e.touch!==`joystick`)throw new N(`BAD_FORMAT`,`Input action '${n}': vector2 "touch" must be 'joystick', got ${JSON.stringify(e.touch)}.`);let i=r;t.set(n,{type:`vector2`,keys:{up:[...i.up],down:[...i.down],left:[...i.left],right:[...i.right]},...e.touch===`joystick`?{touch:`joystick`}:{}})}else throw new N(`BAD_FORMAT`,`Input action '${n}': "type" must be 'button' or 'vector2', got ${JSON.stringify(e.type)}.`)}return t}var mt=class{added=new j;buffer=[];capacity;seq=0;constructor(e=1e3){this.capacity=e}debug(...e){this.push(`debug`,e)}info(...e){this.push(`info`,e)}warn(...e){this.push(`warn`,e)}error(...e){this.push(`error`,e)}entries(){return this.buffer}clear(){this.buffer.length=0}push(e,t){this.seq+=1;let n={seq:this.seq,timeMs:globalThis.performance?.now()??0,level:e,parts:t};this.buffer.push(n),this.buffer.length>this.capacity&&this.buffer.splice(0,this.buffer.length-this.capacity),this.added.emit(n)}},ht={background:-2e3,terrain:-1e3,default:0,characters:1e3,effects:2e3,overlay:3e3};function gt(e){return e?{...ht,...e}:ht}function _t(e,t,n=ht){return(n[e]??0)+t}var vt=new Map;function yt(e){let t=`incanto:${e}:`,n=xt();if(!n){let t=vt.get(e);t||(t=new Map,vt.set(e,t));let n=t;return{get:(e,t)=>bt(n.get(e),t),set:(e,t)=>void n.set(e,JSON.stringify(t)),remove:e=>void n.delete(e),clear:()=>n.clear()}}return{get:(e,r)=>bt(n.getItem(t+e)??void 0,r),set:(e,r)=>n.setItem(t+e,JSON.stringify(r)),remove:e=>n.removeItem(t+e),clear:()=>{let e=[];for(let r=0;r<n.length;r++){let i=n.key(r);i?.startsWith(t)&&e.push(i)}for(let t of e)n.removeItem(t)}}}function bt(e,t){if(e==null)return t;try{return JSON.parse(e)}catch{return t}}function xt(){try{if(typeof localStorage>`u`)return null;let e=`__incanto_probe__`;return localStorage.setItem(e,`1`),localStorage.removeItem(e),localStorage}catch{return null}}function St(e){let t={},n=[],r=e=>{let i=e.behavior;if(i&&typeof i.serialize==`function`){let r=i.serialize();r!==void 0&&(e.uid?t[e.uid]=r:n.push(e.getPath()))}for(let t of e.children)r(t)};return r(e),{state:t,unaddressable:n}}function Ct(e,t){let n={missing:[],skipped:[],restored:0};for(let[r,i]of Object.entries(t)){let t=e.getNodeByUid(r);if(!t){n.missing.push(r);continue}let a=t.behavior;if(!a||typeof a.deserialize!=`function`){n.skipped.push(r);continue}try{a.deserialize(i),n.restored+=1}catch{n.skipped.push(r)}}return n}var wt={master:1,sfx:1,music:1,muted:!1,quality:`high`,sensitivity:1,invertY:!1,reduceMotion:!1,language:`en`},Tt=[`low`,`medium`,`high`],Et=class{changed=new j;store;values;constructor(e=`settings`,t){this.store=t??yt(e),this.values={...wt};for(let e of Object.keys(wt)){let t=this.store.get(e,wt[e]);this.values[e]=t}Tt.includes(this.values.quality)||(this.values.quality=wt.quality)}get(e){return this.values[e]}set(e,t){this.values[e]!==t&&(this.values[e]=t,this.store.set(e,t),this.changed.emit(e))}all(){return{...this.values}}reset(){for(let e of Object.keys(wt))this.set(e,wt[e])}bindLocale(e){return e.locale=this.values.language,e.changed.connect(e=>{this.set(`language`,e)})}bindAudio(e){return e.master=this.values.master,e.sfx=this.values.sfx,e.music=this.values.music,e.muted=this.values.muted,e.changed.connect(()=>{this.set(`master`,e.master),this.set(`sfx`,e.sfx),this.set(`music`,e.music),this.set(`muted`,e.muted)})}},Dt=.25;function Ot(e){let t=!0,n=requestAnimationFrame(function r(i){t&&(e(i),n=requestAnimationFrame(r))});return()=>{t=!1,cancelAnimationFrame(n)}}var kt=class{updated=new j;fixedUpdated=new j;sceneChanged=new j;input=new ft;rng;log=new mt;picker=null;audio=new ie;settings=new Et;locale=new ze;orderGroups=ht;sfx=new Ie;music=new ve(this.audio);uiHost=null;fixedStep;maxFixedSteps;scheduler;_scene=null;lastMs=null;accumulator=0;disposeScheduler=null;frameStats=new ut;timeScale=1;debugSelection=null;_time=0;_unscaledTime=0;get time(){return this._time}get unscaledTime(){return this._unscaledTime}constructor(e={}){this.fixedStep=1/(e.fixedHz??60),this.maxFixedSteps=e.maxFixedStepsPerTick??5,this.scheduler=e.scheduler??Ot,this.rng=new P(e.seed??Math.random()*4294967295>>>0)}get scene(){return this._scene}setScene(e){e!==this._scene&&(this._scene?.tree._setEngine(null),this._scene?.root.free(),this._scene=e,e.tree._setEngine(this),this.input.clear(),this._time=0,this._unscaledTime=0,e.input&&this.input.declare(e.input),e.strings&&this.locale.load(e.strings),this.orderGroups=gt(e.orderGroups),this.sceneChanged.emit(e))}start(){this.disposeScheduler||=this.scheduler(e=>{try{this.tick(e)}catch(e){this.reportFrameError(e)}})}reportFrameError(e){this.errorCount+=1;let t=e instanceof Error?`${e.name}: ${e.message}`:String(e);t!==this.lastFrameError&&(this.lastFrameError=t,this.log.error(`[incanto] a frame threw — the loop keeps running:`,e),console.error(`[incanto] a frame threw — the loop keeps running:`,e))}_nodeErrored(e){this.errorCount+=1}errorCount=0;lastFrameError=null;t(e,t){return this.locale.t(e,t)}captureState(){let e=this.scene?.root;if(!e)return{};let{state:t,unaddressable:n}=St(e);for(let e of n)lt(this,`warn`,`save: ${e} has state to save and no uid to key it under.`);return t}restoreState(e){let t=this.scene?.root;return t?Ct(t,e):{missing:Object.keys(e),skipped:[],restored:0}}erroredNodes(){let e=[],t=n=>{(n.errored||n.behaviorErrored)&&e.push(n);for(let e of n.children)t(e)};return this._scene?.root&&t(this._scene.root),e}resumeErroredNodes(){let e=this.erroredNodes();for(let t of e)t.errored=!1,t.behaviorErrored=!1;return this.lastFrameError=null,e.length}stop(){this.disposeScheduler?.(),this.disposeScheduler=null,this.lastMs=null,this.accumulator=0,this.frameStats.clear()}stats(){return{fps:this.frameStats.fps(),frameMs:this.frameStats.frameMs(),nodes:this._scene?.tree.root?At(this._scene.tree.root):0,running:this.disposeScheduler!==null,errors:this.errorCount}}get interpolationAlpha(){return this.fixedStep>0?Math.min(this.accumulator/this.fixedStep,1):1}dispose(){this.stop(),this._scene&&(this._scene.tree._setEngine(null),this._scene.root.free(),this._scene=null,this.sceneChanged.emit(null)),this.input.dispose(),this.input.clear()}step(){let e=this._scene;e&&(e.tree.fixedUpdate(this.fixedStep),this.fixedUpdated.emit(this.fixedStep),e.tree.update(this.fixedStep),this.music.tick(this.fixedStep),this.updated.emit(this.fixedStep),this.input.endFrame())}tick(e){if(this.frameStats.push(e),this.lastMs===null){this.lastMs=e;return}let t=Math.max(0,Math.min((e-this.lastMs)/1e3,Dt)),n=t*this.timeScale;this._time+=n,this._unscaledTime+=t,this.lastMs=e;let r=this._scene;if(!r)return;this.accumulator+=n;let i=0;for(;this.accumulator>=this.fixedStep&&i<this.maxFixedSteps;)r.tree.fixedUpdate(this.fixedStep),this.fixedUpdated.emit(this.fixedStep),this.accumulator-=this.fixedStep,i+=1;this.accumulator>=this.fixedStep&&(this.accumulator%=this.fixedStep),r.tree.update(n),this.music.tick(n),this.updated.emit(n),this.input.endFrame()}};function At(e){let t=1;for(let n of e.children)t+=At(n);return t}function jt(e){if(e===``)throw new N(`BAD_NODE_PATH`,`Node path must not be empty.`);if(e.startsWith(`%`)){let t=e.slice(1);if(t===``||t.includes(`/`)||t.includes(`%`))throw new N(`BAD_NODE_PATH`,`Invalid unique-name path '${e}'. Expected '%NodeName'.`);return{kind:`unique`,name:t}}if(e===`.`)return{kind:`relative`,segments:[]};let t=e.startsWith(`/`),n=t?e.slice(1):e;if(n===``||n.split(`/`).some(e=>e===``))throw new N(`BAD_NODE_PATH`,`Invalid node path '${e}'. Segments must be non-empty (no leading/trailing/double '/').`);let r=n.split(`/`);for(let t of r){if(t.includes(`%`))throw new N(`BAD_NODE_PATH`,`Invalid node path '${e}'. '%' is only allowed as a whole-path prefix ('%Name').`);if(t===`.`)throw new N(`BAD_NODE_PATH`,`Invalid node path '${e}'. '.' is only valid as the whole path — drop the './' prefix.`)}if(t&&r.includes(`..`))throw new N(`BAD_NODE_PATH`,`Invalid node path '${e}'. Absolute paths must not contain '..'.`);return{kind:t?`absolute`:`relative`,segments:r}}function Mt(e){if(e===``||e.includes(`/`)||e.includes(`%`))throw new N(`TREE_VIOLATION`,`Invalid node name '${e}'. Names must be non-empty and must not contain '/' or '%'.`)}var Nt=class{static typeName=`Node`;_name;_parent=null;_children=[];_groups=new Set;_signals=new Map;_declared=null;_tree=null;_ready=!1;uid=null;tags={};script=null;behavior=null;network=null;constructor(e){let t=this.constructor;this._name=e??t.typeName,Mt(this._name)}get name(){return this._name}set name(e){Mt(e);let t=this._name;this._parent?this._name=Ft(e,this._parent._children,this):this._name=e,this._tree&&this._name!==t&&this._tree._reindexName(this,t)}get parent(){return this._parent}get children(){return this._children}get groups(){return this._groups}get tree(){return this._tree}get isReady(){return this._ready}addChild(e){if(e._parent!==null)throw new N(`TREE_VIOLATION`,`Cannot add '${e.name}': it already has parent '${e._parent.name}'. removeChild/reparent first.`);for(let t=this;t;t=t._parent)if(t===e)throw new N(`TREE_VIOLATION`,`Cannot add '${e.name}' to '${this.name}': it is this node or an ancestor (cycle).`);return e._name=Ft(e._name,this._children,e),e._parent=this,this._children.push(e),this._tree&&(e._propagateEnterTree(this._tree),e._propagateReady()),e}removeChild(e){let t=this._children.indexOf(e);if(t===-1)throw new N(`TREE_VIOLATION`,`'${e.name}' is not a child of '${this.name}'.`);e._tree&&e._propagateExitTree(),this._children.splice(t,1),e._parent=null}reparent(e){this._parent?.removeChild(this),e.addChild(this)}findChild(e,t=!0){for(let t of this._children)if(t._name===e)return t;if(t)for(let t of this._children){let n=t.findChild(e,!0);if(n)return n}return null}getRoot(){let e=this;for(;e._parent;)e=e._parent;return e}getNodeByUid(e){if(this.uid===e)return this;for(let t of this.children){let n=t.getNodeByUid(e);if(n)return n}return null}getNodesByName(e){if(this._tree&&this._parent===null){let t=this._tree._nodesNamed(e);return t?[...t]:[]}let t=[],n=r=>{r.name===e&&t.push(r);for(let e of r.children)n(e)};return n(this),t}getPath(){let e=[];for(let t=this;t;t=t._parent)e.unshift(t._name);return`/${e.join(`/`)}`}getNode(e){let t=this.resolve(e);if(t)return t;throw new N(`NODE_NOT_FOUND`,`No node at '${e}' from '${this.getPath()}'. Children here: [${this._children.map(e=>e._name).join(`, `)}].`)}getNodeOrNull(e){return this.resolve(e)}resolve(e){let t=jt(e);if(t.kind===`unique`){let e=this._tree;if(e){let n=e._nodesNamed(t.name);if(!n||n.size===0)return null;if(n.size>1){let e=[];for(let t of n)e.push(t.getPath());throw new N(`DUPLICATE_UNIQUE_NAME`,`'%${t.name}' is ambiguous: ${n.size} nodes named '${t.name}' (${e.join(`, `)}).`)}for(let e of n)return e}let n=[];if(Pt(this.getRoot(),t.name,n),n.length>1)throw new N(`DUPLICATE_UNIQUE_NAME`,`'%${t.name}' is ambiguous: ${n.length} nodes named '${t.name}' (${n.map(e=>e.getPath()).join(`, `)}).`);return n[0]??null}let n,r=t.segments;if(t.kind===`absolute`){let e=this.getRoot();if(r[0]!==e._name&&r[0]!==`root`)return null;n=e,r=r.slice(1)}else n=this;for(let e of r){if(!n)return null;if(e===`..`){n=n._parent;continue}n=n._children.find(t=>t._name===e)??null}return n}addToGroup(e){this._groups.add(e)}removeFromGroup(e){this._groups.delete(e)}isInGroup(e){return this._groups.has(e)}declaredSignals(){if(!this._declared){this._declared=new Set;let e=this.constructor;for(;typeof e==`function`;){let t=e;if(Object.hasOwn(e,`signals`)&&t.signals)for(let e of t.signals)this._declared.add(e);e=Object.getPrototypeOf(e)}}return this._declared}declareSignal(e){this.declaredSignals().add(e)}declaredSignalNames(){return[...this.declaredSignals()]}assertDeclared(e){if(this.declaredSignals().has(e))return;let t=this.constructor,n=[...this.declaredSignals()];throw new N(`UNKNOWN_SIGNAL`,`Unknown signal '${e}' on '${this.getPath()}' (${t.typeName}). Declared signals: [${n.join(`, `)}]. Declare it with "static signals = ['${e}']" on the node class or its behavior, or call node.declareSignal('${e}').`,{signal:e,path:this.getPath(),nodeType:t.typeName,validOptions:n})}signal(e){this.assertDeclared(e);let t=this._signals.get(e);return t||(t=new j,this._signals.set(e,t)),t}on(e,t,n){return this.signal(e).connect(t,n)}off(e,t){this._signals.get(e)?.disconnect(t)}emit(e,...t){this.assertDeclared(e),this._signals.get(e)?.emit(...t)}queueFree(){this._tree?this._tree._queueFree(this):this.free()}free(){let e=this._tree;for(let e of[...this._children])e.free();this._parent?.removeChild(this),this._tree&&this._propagateExitTree(),e?._detachRoot(this);for(let e of this._signals.values())e.disconnectAll();this._signals.clear()}_propagateEnterTree(e){this._tree=e,e._indexName(this),this.onEnterTree(),this.behavior?.onEnterTree?.();for(let t of[...this._children])t._tree!==e&&t._propagateEnterTree(e)}_propagateReady(){for(let e of[...this._children])e._tree&&e._propagateReady();this._ready||(this._ready=!0,this.onReady(),this.behavior?.onReady?.())}_propagateExitTree(){for(let e of[...this._children])e._propagateExitTree();this.onExitTree(),this.behavior?.onExitTree?.(),this._tree?._unindexName(this),this._tree=null}_propagateUpdate(e){if(!this.errored)try{this.update(e)}catch(e){this._quarantine(`update`,e,`node`)}if(this.behavior&&!this.behaviorErrored)try{this.behavior.update?.(e)}catch(e){this._quarantine(`update`,e,`behavior`)}let t=this._children;for(let n=0,r=t.length;n<r;n++)t[n]?._propagateUpdate(e)}_propagateFixedUpdate(e){if(!this.errored)try{this.fixedUpdate(e)}catch(e){this._quarantine(`fixedUpdate`,e,`node`)}if(this.behavior&&!this.behaviorErrored)try{this.behavior.fixedUpdate?.(e)}catch(e){this._quarantine(`fixedUpdate`,e,`behavior`)}let t=this._children;for(let n=0,r=t.length;n<r;n++)t[n]?._propagateFixedUpdate(e)}diagnose(e,...t){lt(this._tree?.engine??null,e,...t)}errored=!1;behaviorErrored=!1;_quarantine(e,t,n){let r=`${this.getPath()} (${this.constructor.typeName??`Node`})`,i;n===`behavior`?(this.behaviorErrored=!0,i=`[incanto] behavior '${this.behavior?.constructor.name??`?`}' on ${r} threw in ${e} — THE SCRIPT is now skipped; the node itself and the rest of the scene keep running.`):(this.errored=!0,i=`[incanto] ${r} threw in ${e} — this node is now SKIPPED. Its children and the rest of the scene keep running.`);let a=this._tree?.engine;a?.log.error(i,t),a?._nodeErrored(this),console.error(i,t)}onEnterTree(){}onReady(){}onExitTree(){}update(e){}fixedUpdate(e){}};function Pt(e,t,n){e.name===t&&n.push(e);for(let r of e.children)Pt(r,t,n)}function Ft(e,t,n){let r=new Set(t.filter(e=>e!==n).map(e=>e.name));if(!r.has(e))return e;let i=e.match(/^(.*?)(\d+)$/),a=i?i[1]:e,o=i?Number(i[2])+1:2;for(;r.has(`${a}${o}`);)o+=1;return`${a}${o}`}var It=null;function Lt(){return It?It():typeof Audio>`u`?null:new Audio}var Rt=class extends Nt{static typeName=`AudioPlayer`;static signals=[`finished`];static props={src:{default:``},preset:{default:`custom`,options:[`custom`,...be]},volume:{default:1},pitch:{default:1},seed:{default:0},bus:{default:`sfx`,options:[`sfx`,`music`]},loop:{default:!1},autoplay:{default:!1},spatial:{default:!1},refDistance:{default:1},maxDistance:{default:50},rolloff:{default:`inverse`,options:[...Ce]}};src=``;preset=`custom`;volume=1;pitch=1;seed=0;bus=`sfx`;loop=!1;autoplay=!1;spatial=!1;refDistance=1;maxDistance=50;rolloff=`inverse`;static validateJson(e){let t=e;if(t.preset!==`custom`&&!be.includes(t.preset))throw new N(`BAD_FORMAT`,`AudioPlayer '${e.name}' preset must be 'custom' or one of [${be.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:be});if(t.bus!==`sfx`&&t.bus!==`music`)throw new N(`BAD_FORMAT`,`AudioPlayer '${e.name}' bus must be 'sfx' or 'music', got '${t.bus}'.`,{prop:`bus`,validOptions:[`sfx`,`music`]});if(!Ce.includes(t.rolloff))throw new N(`BAD_FORMAT`,`AudioPlayer '${e.name}' rolloff must be one of [${Ce.join(`, `)}], got '${t.rolloff}'.`,{prop:`rolloff`,validOptions:[...Ce]})}pendingGesture=!1;element=null;_playing=!1;autoplayed=!1;_spatialPose=null;get playing(){return this._playing}_setSpatialPose(e){this._spatialPose=e}gain(){let e=this.tree?.engine?.audio;return e?e.effectiveVolume(this.bus,this.volume):this.volume}spatialElementGain(){if(!this.spatial||!this._spatialPose)return 1;let{position:e,listener:t}=this._spatialPose,n=e[0]-t.position[0],r=e[1]-t.position[1],i=e[2]-t.position[2];return L(Math.hypot(n,r,i),{refDistance:this.refDistance,maxDistance:this.maxDistance,rolloff:this.rolloff})}spatialPlay(){if(!(!this.spatial||!this._spatialPose))return{position:this._spatialPose.position,listener:this._spatialPose.listener,refDistance:this.refDistance,maxDistance:this.maxDistance,rolloff:this.rolloff}}play(){if(this.preset!==`custom`){this.playPreset();return}if(!this.src)return;if(!this.element){if(this.element=Lt(),!this.element)return;this.element.addEventListener(`ended`,()=>{this.loop||(this._playing=!1,this.emit(`finished`))})}let e=this.element;e.src=this.src,e.volume=this.gain()*this.spatialElementGain(),e.loop=this.loop,this._playing=!0,this.pendingGesture=!1,e.play().catch(()=>{this._playing=!1,this.pendingGesture=!0})}playPreset(){let e=F[this.preset];if(!e)return;let t=this.tree?.engine?.sfx;t&&t.play(e,this.gain(),{pitch:this.pitch,seed:this.seed,spatial:this.spatialPlay()})}stop(){this.element&&(this.element.pause(),this.element.currentTime=0),this._playing=!1,this.pendingGesture=!1}retryPending(){this.pendingGesture&&this.play()}update(e){this.autoplay&&!this.autoplayed&&(this.autoplayed=!0,this.play()),this.element&&this._playing&&(this.element.volume=this.gain()*this.spatialElementGain(),this.element.loop=this.loop)}},zt={topLeft:`left:16px;top:16px;align-items:flex-start;`,top:`left:50%;top:16px;transform:translateX(-50%);align-items:center;`,topRight:`right:16px;top:16px;align-items:flex-end;`,left:`left:16px;top:50%;transform:translateY(-50%);align-items:flex-start;`,center:`left:50%;top:50%;transform:translate(-50%,-50%);align-items:center;`,right:`right:16px;top:50%;transform:translateY(-50%);align-items:flex-end;`,bottomLeft:`left:16px;bottom:16px;align-items:flex-start;`,bottom:`left:50%;bottom:16px;transform:translateX(-50%);align-items:center;`,bottomRight:`right:16px;bottom:16px;align-items:flex-end;`},Bt=`600 14px system-ui, -apple-system, 'Segoe UI', sans-serif`;function Vt(){return typeof document<`u`}var Ht=class extends Nt{static typeName=`HudLayer`;static props={zIndex:{default:100},visible:{default:!0},focusNavigation:{default:!1}};zIndex=100;visible=!0;focusNavigation=!1;_element=null;slots=new Map;onEnterTree(){if(!Vt())return;let e=document.createElement(`div`);e.dataset.incantoHud=this.name,e.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${this.zIndex};font:${Bt};`,this._element=e,this._mount()}_mount(){let e=this._element;if(!e)return;let t=this.tree?.engine?.uiHost??document.body;e.parentElement!==t&&(e.style.position=t===document.body?`fixed`:`absolute`,t.appendChild(e))}onExitTree(){this._element?.remove(),this._element=null,this.slots.clear()}update(){this._element&&(this._mount(),this._element.style.display=this.visible?``:`none`),this.focusNavigation&&this.stepFocus()}stepFocus(){let e=this.tree?.engine;if(!e)return;let t=this.focusables();if(t.length===0)return;let n=e.input,r=n.keyJustPressed(`ArrowDown`)||n.keyJustPressed(`Pad13`),i=n.keyJustPressed(`ArrowUp`)||n.keyJustPressed(`Pad12`),a=n.keyJustPressed(`ArrowLeft`)||n.keyJustPressed(`Pad14`),o=n.keyJustPressed(`ArrowRight`)||n.keyJustPressed(`Pad15`),s=n.keyJustPressed(`Enter`)||n.keyJustPressed(`Pad0`),c=t.findIndex(e=>e._focused);if(c===-1&&(r||i||s)?c=0:r?c=(c+1)%t.length:i&&(c=(c-1+t.length)%t.length),c!==-1){for(let e of t){let n=e===t[c];n!==e._focused&&(e._focused=n,e._paintFocus())}let e=t[c];e&&(s?e._activate(0):a?e._activate(-1):o&&e._activate(1))}}focusables(){let e=[],t=n=>{n instanceof Kt&&n.focusable&&n.visible&&e.push(n);for(let e of n.children)t(e)};return t(this),e}focus(e){for(let t of this.focusables()){let n=t===e;n!==t._focused&&(t._focused=n,t._paintFocus())}}_slot(e){if(!this._element)return null;let t=this.slots.get(e);return t||(t=document.createElement(`div`),t.style.cssText=`position:absolute;display:flex;flex-direction:column;gap:8px;${zt[e]??zt.topLeft}`,this._element.appendChild(t),this.slots.set(e,t)),t}},Ut=new WeakMap;function Wt(e){for(let t=e;t;t=t.parentElement){let e=Ut.get(t);if(e)return e}return null}var Gt=null,Kt=class extends Nt{static props={anchor:{default:`topLeft`,options:[`topLeft`,`top`,`topRight`,`left`,`center`,`right`,`bottomLeft`,`bottom`,`bottomRight`]},visible:{default:!0},focusable:{default:!1},draggable:{default:!1},dropTarget:{default:!1}};static signals=[`dragStarted`,`dragCancelled`,`droppedOn`,`dropped`];anchor=`topLeft`;visible=!0;focusable=!1;draggable=!1;dropTarget=!1;_focused=!1;_activate(e){}_paintFocus(){this._element&&(this._element.style.outline=this._focused?`2px solid #6ee7dc`:``,this._element.style.outlineOffset=this._focused?`2px`:``)}_element=null;layer(){for(let e=this.parent;e;e=e.parent)if(e instanceof Ht)return e;return null}onReady(){Vt()&&this._mountWidget()}_mountWidget(){if(this._element||!Vt())return;let e=this.host()??this.layer()?._slot(this.anchor);e&&(this._element=this._build(),Ut.set(this._element,this),(this.draggable||this.dropTarget)&&this._wireDrag(this._element),e.appendChild(this._element))}_wireDrag(e){e.style.touchAction=`none`,this.draggable&&(e.style.cursor=`grab`,e.addEventListener(`pointerdown`,t=>{this.draggable&&(t.preventDefault(),e.setPointerCapture?.(t.pointerId),Gt=this,e.style.opacity=`0.6`,this.emit(`dragStarted`,this))}),e.addEventListener(`pointerup`,t=>{if(Gt!==this)return;e.style.opacity=``,e.releasePointerCapture?.(t.pointerId);let n=Wt(document.elementFromPoint?.(t.clientX,t.clientY)??null);Gt=null,n&&n!==this&&n.dropTarget?(this.emit(`droppedOn`,n),n.emit(`dropped`,this)):this.emit(`dragCancelled`,this)}))}host(){for(let e=this.parent;e;e=e.parent){let t=e;if(typeof t._container==`function`)return t._container();if(e instanceof Ht)return null}return null}onExitTree(){this._element?.remove(),this._element=null}update(e){!this._element&&(this._mountWidget(),!this._element)||(this._element.style.display=this.visible?``:`none`,this._sync())}_sync(){}_t(e){let t=this.tree?.engine?.locale;return t?t.resolve(e):e}},qt=class extends Kt{static typeName=`UiText`;static props={...Kt.props,text:{default:``},size:{default:16},color:{default:`#ffffff`},shadow:{default:!0}};text=``;size=16;color=`#ffffff`;shadow=!0;last=`\0`;_build(){let e=document.createElement(`div`);return e.style.cssText=`font-size:${this.size}px;color:${this.color};${this.shadow?`text-shadow:0 1px 3px rgba(0,0,0,.7);`:``}white-space:pre;`,e}_sync(){let e=this._t(this.text);e!==this.last&&this._element&&(this.last=e,this._element.textContent=e)}},Jt=class extends Kt{static typeName=`UiBar`;static props={...Kt.props,value:{default:100},max:{default:100},width:{default:180},height:{default:14},color:{default:`#4ade80`},lowColor:{default:`#ef4444`},lowThreshold:{default:.3},background:{default:`rgba(0,0,0,0.5)`},label:{default:``}};value=100;max=100;width=180;height=14;color=`#4ade80`;lowColor=`#ef4444`;lowThreshold=.3;background=`rgba(0,0,0,0.5)`;label=``;fill=null;tag=null;lastLabel=`\0`;lastRatio=-1;get ratio(){return this.max>0?Math.min(1,Math.max(0,this.value/this.max)):0}_build(){let e=document.createElement(`div`);if(e.style.cssText=`display:flex;align-items:center;gap:6px;`,this.label){let t=document.createElement(`span`);t.style.cssText=`color:#fff;font-size:12px;text-shadow:0 1px 3px rgba(0,0,0,.7);`,this.tag=t,e.appendChild(t)}let t=document.createElement(`div`);return t.style.cssText=`width:${this.width}px;height:${this.height}px;background:${this.background};border-radius:${this.height/2}px;overflow:hidden;`,this.fill=document.createElement(`div`),this.fill.style.cssText=`height:100%;width:100%;background:${this.color};border-radius:inherit;transition:width .15s;`,t.appendChild(this.fill),e.appendChild(t),e}_sync(){let e=this._t(this.label);e!==this.lastLabel&&this.tag&&(this.lastLabel=e,this.tag.textContent=e);let t=this.ratio;t===this.lastRatio||!this.fill||(this.lastRatio=t,this.fill.style.width=`${t*100}%`,this.fill.style.background=t<=this.lowThreshold?this.lowColor:this.color)}},Yt=class extends Kt{static typeName=`UiBanner`;static signals=[`bannerShown`];static props={...Kt.props,anchor:{default:`center`,options:[`topLeft`,`top`,`topRight`,`left`,`center`,`right`,`bottomLeft`,`bottom`,`bottomRight`]},size:{default:42},seconds:{default:2}};anchor=`center`;size=42;seconds=2;queue=[];current=null;remaining=0;get showing(){return this.current?.text??``}show(e,t){this.queue.push({text:e,color:t?.color??`#ffffff`,seconds:t?.seconds??this.seconds})}clear(){this.queue.length=0,this.current=null,this.remaining=0,this._element&&(this._element.style.opacity=`0`)}_build(){let e=document.createElement(`div`);return e.style.cssText=`font-size:${this.size}px;font-weight:800;color:#fff;text-shadow:0 2px 12px rgba(0,0,0,.8);opacity:0;transition:opacity .25s;text-align:center;`,e}update(e){super.update(e),this.current&&(this.current.seconds>0?(this.remaining-=e,this.remaining<=0&&(this.current=null,this._element&&(this._element.style.opacity=`0`))):this.queue.length>0&&(this.current=null)),!this.current&&this.queue.length>0&&(this.current=this.queue.shift(),this.current.text=this._t(this.current.text),this.remaining=this.current.seconds,this._element&&(this._element.textContent=this.current.text,this._element.style.color=this.current.color,this._element.style.opacity=`1`),this.emit(`bannerShown`,this.current.text))}},Xt=class extends Kt{static typeName=`UiButton`;static signals=[`pressed`];static props={...Kt.props,text:{default:`OK`},size:{default:16},color:{default:`#ffffff`},background:{default:`rgba(255,255,255,0.14)`},disabled:{default:!1},focusable:{default:!0}};text=`OK`;size=16;color=`#ffffff`;background=`rgba(255,255,255,0.14)`;disabled=!1;focusable=!0;_activate(e){this.press()}lastText=``;press(){this.disabled||this.emit(`pressed`)}_build(){let e=document.createElement(`button`);return e.type=`button`,e.style.cssText=`pointer-events:auto;cursor:pointer;font:600 ${this.size}px system-ui,sans-serif;color:${this.color};background:${this.background};border:1px solid rgba(255,255,255,0.25);border-radius:8px;padding:8px 18px;transition:transform .08s, background .15s;`,e.addEventListener(`mouseenter`,()=>{this.disabled||(e.style.background=`rgba(255,255,255,0.24)`)}),e.addEventListener(`mouseleave`,()=>{e.style.background=this.background}),e.addEventListener(`pointerdown`,()=>{this.disabled||(e.style.transform=`scale(0.95)`)}),e.addEventListener(`pointerup`,()=>{e.style.transform=``}),e.addEventListener(`click`,()=>this.press()),e}_sync(){if(!this._element)return;let e=this._t(this.text);e!==this.lastText&&(this.lastText=e,this._element.textContent=e),this._element.disabled=this.disabled,this._element.style.opacity=this.disabled?`0.45`:`1`}},Zt=class extends Kt{static typeName=`UiDialogue`;static signals=[`lineShown`,`choiceMade`,`dialogueFinished`];static props={...Kt.props,anchor:{default:`bottom`,options:[`topLeft`,`top`,`topRight`,`left`,`center`,`right`,`bottomLeft`,`bottom`,`bottomRight`]},charsPerSecond:{default:40},width:{default:520}};anchor=`bottom`;charsPerSecond=40;width=520;queue=[];current=null;revealed=0;speakerEl=null;textEl=null;choicesEl=null;hintEl=null;get active(){return this.current!==null||this.queue.length>0}get showing(){return this.current?this.current.text.slice(0,Math.floor(this.revealed)):``}say(e,t,n){this.queue.push({speaker:e,text:t,choices:n??null})}advance(){if(this.current){if(this.revealed<this.current.text.length){this.revealed=this.current.text.length;return}this.current.choices||this.next()}}choose(e){this.current?.choices&&(e<0||e>=this.current.choices.length||(this.emit(`choiceMade`,e),this.next()))}clear(){this.queue.length=0,this.current=null,this.revealed=0,this._element&&(this._element.style.display=`none`)}next(){this.current=null,this.revealed=0,this.queue.length===0&&(this._element&&(this._element.style.display=`none`),this.emit(`dialogueFinished`))}_build(){let e=document.createElement(`div`);return e.style.cssText=`pointer-events:auto;width:${this.width}px;max-width:86vw;background:rgba(12,14,22,0.92);border:1px solid rgba(255,255,255,0.2);border-radius:12px;padding:14px 18px;display:none;font:15px/1.5 system-ui,sans-serif;color:#fff;cursor:pointer;user-select:none;`,this.speakerEl=document.createElement(`div`),this.speakerEl.style.cssText=`font-weight:800;color:#ffd166;margin-bottom:4px;font-size:13px;`,this.textEl=document.createElement(`div`),this.textEl.style.cssText=`min-height:3em;white-space:pre-wrap;`,this.choicesEl=document.createElement(`div`),this.choicesEl.style.cssText=`display:flex;gap:8px;margin-top:10px;flex-wrap:wrap;`,this.hintEl=document.createElement(`div`),this.hintEl.textContent=`▼`,this.hintEl.style.cssText=`text-align:right;opacity:0.5;font-size:11px;animation:none;`,e.append(this.speakerEl,this.textEl,this.choicesEl,this.hintEl),e.addEventListener(`click`,()=>this.advance()),e}update(e){if(super.update(e),!this.current&&this.queue.length>0&&(this.current=this.queue.shift(),this.current.text=this._t(this.current.text),this.current.speaker=this._t(this.current.speaker),this.current.choices&&(this.current.choices=this.current.choices.map(e=>this._t(e))),this.revealed=this.charsPerSecond<=0?this.current.text.length:0,this.emit(`lineShown`,this.current.text),this._element&&(this.speakerEl&&(this.speakerEl.textContent=this.current.speaker),this.choicesEl&&this.choicesEl.replaceChildren())),this._element&&(this._element.style.display=this.visible&&this.current?`block`:`none`),!this.current)return;let t=this.revealed<this.current.text.length;t&&(this.revealed=Math.min(this.current.text.length,this.revealed+this.charsPerSecond*e));let n=this.revealed>=this.current.text.length;this.textEl&&(this.textEl.textContent=this.showing),this.hintEl&&(this.hintEl.style.visibility=n&&!this.current.choices?`visible`:`hidden`),n&&t&&this.current.choices&&this.choicesEl&&this.current.choices.forEach((e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.textContent=e,n.style.cssText=`pointer-events:auto;cursor:pointer;font:600 13px system-ui,sans-serif;color:#fff;background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.3);border-radius:8px;padding:6px 14px;`,n.addEventListener(`click`,e=>{e.stopPropagation(),this.choose(t)}),this.choicesEl?.appendChild(n)})}},Qt=class extends Nt{static typeName=`Timer`;static signals=[`timeout`];static props={waitTime:{default:1},oneShot:{default:!1},autostart:{default:!1}};waitTime=1;oneShot=!1;autostart=!1;running=!1;remaining=0;start(e){e!==void 0&&(this.waitTime=e),this.remaining=this.waitTime,this.running=!0}stop(){this.running=!1}onReady(){this.autostart&&this.start()}update(e){if(this.running){if(this.waitTime<=0){this.stop();return}for(this.remaining-=e;this.remaining<=0&&this.running;)this.emit(`timeout`),this.oneShot||this.waitTime<=0?this.stop():this.remaining+=this.waitTime}}};function $t(e){return`${e}px`}var en=class extends Kt{static typeName=`UiPanel`;static props={...Kt.props,layout:{default:`column`,options:[`column`,`row`,`grid`]},columns:{default:4},gap:{default:8},padding:{default:12},background:{default:`rgba(0,0,0,0.55)`},radius:{default:10},width:{default:0},height:{default:0},border:{default:``}};layout=`column`;columns=4;gap=8;padding=12;background=`rgba(0,0,0,0.55)`;radius=10;width=0;height=0;border=``;lastKey=``;_build(){let e=document.createElement(`div`);return e.style.cssText=this.css(),this.lastKey=this.css(),e}_container(){return this._element||this._mountWidget(),this._element}css(){return`${this.layout===`grid`?`display:grid;grid-template-columns:repeat(${Math.max(1,this.columns)},auto);`:`display:flex;flex-direction:${this.layout};align-items:stretch;`}gap:${$t(this.gap)};padding:${$t(this.padding)};background:${this.background};border-radius:${$t(this.radius)};`+(this.width>0?`width:${$t(this.width)};`:``)+(this.height>0?`height:${$t(this.height)};`:``)+(this.border?`border:${this.border};`:``)+`box-sizing:border-box;pointer-events:auto;`}_sync(){let e=this.css();e!==this.lastKey&&this._element&&(this.lastKey=e,this._element.style.cssText=e)}},tn=class extends Kt{static typeName=`UiImage`;static props={...Kt.props,src:{default:``},width:{default:48},height:{default:48},fit:{default:`contain`,options:[`contain`,`cover`,`fill`]},tint:{default:``},opacity:{default:1}};src=``;width=48;height=48;fit=`contain`;tint=``;opacity=1;last=`\0`;_build(){let e=document.createElement(`div`);return e.style.cssText=this.css(),this.last=this.key(),e}resolved(){return this.src.startsWith(`$`)?(this.tree?.engine?.scene?.assets)?.[this.src.slice(1)]?.url??``:this.src}key(){return`${this.resolved()}|${this.width}|${this.height}|${this.fit}|${this.tint}|${this.opacity}`}css(){let e=this.resolved();return`width:${$t(this.width)};height:${$t(this.height)};flex:none;`+(e?`background-image:url("${e}");`:``)+`background-size:${this.fit===`fill`?`100% 100%`:this.fit};background-position:center;background-repeat:no-repeat;opacity:${this.opacity};`+(this.tint?`background-color:${this.tint};background-blend-mode:multiply;`:``)}_sync(){let e=this.key();e!==this.last&&this._element&&(this.last=e,this._element.style.cssText=this.css())}},nn=class extends Kt{static typeName=`UiSlider`;static props={...Kt.props,label:{default:``},value:{default:.5},min:{default:0},max:{default:1},step:{default:.01},width:{default:180},color:{default:`#6ee7dc`},focusable:{default:!0}};static signals=[...Kt.signals,`changed`];label=``;value=.5;min=0;max=1;step=.01;width=180;color=`#6ee7dc`;focusable=!0;_activate(e){if(e===0)return;let t=Math.min(this.max,Math.max(this.min,this.value+e*this.step));t!==this.value&&(this.value=t,this.last=t,this.input&&(this.input.value=String(t)),this.emit(`changed`,t))}input=null;text=null;last=NaN;_build(){let e=document.createElement(`div`);e.style.cssText=`display:flex;align-items:center;gap:8px;pointer-events:auto;font:600 13px system-ui,-apple-system,'Segoe UI',sans-serif;color:#fff;`;let t=document.createElement(`span`);t.textContent=this.label;let n=document.createElement(`input`);return n.type=`range`,n.min=String(this.min),n.max=String(this.max),n.step=String(this.step),n.value=String(this.value),n.style.cssText=`width:${$t(this.width)};accent-color:${this.color};`,n.addEventListener(`input`,()=>{this.value=Number(n.value),this.last=this.value,this.emit(`changed`,this.value)}),this.label&&e.appendChild(t),e.appendChild(n),this.input=n,this.text=t,this.last=this.value,e}_sync(){this.input&&this.value!==this.last&&(this.last=this.value,this.input.value=String(this.value)),this.text&&this.text.textContent!==this.label&&(this.text.textContent=this.label)}},rn=class extends Kt{static typeName=`UiToggle`;static props={...Kt.props,label:{default:``},value:{default:!1},focusable:{default:!0}};static signals=[...Kt.signals,`changed`];label=``;value=!1;focusable=!0;_activate(e){let t=e===0?!this.value:e>0;t!==this.value&&(this.value=t,this.last=t,this.input&&(this.input.checked=t),this.emit(`changed`,t))}input=null;last=null;_build(){let e=document.createElement(`label`);e.style.cssText=`display:flex;align-items:center;gap:8px;pointer-events:auto;cursor:pointer;font:600 13px system-ui,-apple-system,'Segoe UI',sans-serif;color:#fff;`;let t=document.createElement(`input`);t.type=`checkbox`,t.checked=this.value,t.addEventListener(`change`,()=>{this.value=t.checked,this.last=this.value,this.emit(`changed`,this.value)});let n=document.createElement(`span`);return n.textContent=this.label,e.append(t,n),this.input=t,this.last=this.value,e}_sync(){this.input&&this.value!==this.last&&(this.last=this.value,this.input.checked=this.value)}},an=class extends Kt{static typeName=`UiSelect`;static props={...Kt.props,label:{default:``},options:{default:``},value:{default:``},focusable:{default:!0}};static signals=[...Kt.signals,`changed`];label=``;options=``;value=``;focusable=!0;_activate(e){let t=this.options.split(`,`).map(e=>e.trim()).filter(Boolean);if(t.length===0)return;let n=t[(Math.max(0,t.indexOf(this.value))+(e===0?1:e)+t.length)%t.length];!n||n===this.value||(this.value=n,this.last=n,this.select&&(this.select.value=n),this.emit(`changed`,n))}select=null;labelEl=null;lastLabel=`x`;lastOptions=`\0`;last=`\0`;_build(){let e=document.createElement(`label`);e.style.cssText=`display:flex;align-items:center;gap:8px;pointer-events:auto;font:600 13px system-ui,-apple-system,'Segoe UI',sans-serif;color:#fff;`;let t=document.createElement(`span`);this.labelEl=t;let n=document.createElement(`select`);return n.addEventListener(`change`,()=>{this.value=n.value,this.last=this.value,this.emit(`changed`,this.value)}),this.label&&e.appendChild(t),e.appendChild(n),this.select=n,this.fillOptions(),e}_optionLabel(e){return e}fillOptions(){let e=this.select;if(!(!e||this.options===this.lastOptions)){this.lastOptions=this.options,e.textContent=``;for(let t of this.options.split(`,`)){let n=t.trim();if(!n)continue;let r=document.createElement(`option`);r.value=n,r.textContent=this._optionLabel(n),e.appendChild(r)}this.value&&(e.value=this.value),this.last=this.value}}_sync(){let e=this._t(this.label);e!==this.lastLabel&&this.labelEl&&(this.lastLabel=e,this.labelEl.textContent=e),this.fillOptions(),this.select&&this.value!==this.last&&(this.last=this.value,this.select.value=this.value)}},on={en:`English`,ko:`한국어`,ja:`日本語`,"zh-CN":`简体中文`,"zh-TW":`繁體中文`,es:`Español`,fr:`Français`,de:`Deutsch`,pt:`Português`,ru:`Русский`,it:`Italiano`,th:`ไทย`,vi:`Tiếng Việt`,id:`Bahasa Indonesia`},sn=class extends an{static typeName=`UiLanguageSelect`;static props={...an.props,label:{default:`Language`}};label=`Language`;lastLocale=``;_sync(){let e=this.tree?.engine?.locale;if(e){let t=e.available(),n=t.join(`,`);n!==this.options&&(this.options=n),e.locale===this.lastLocale?this.value!==e.locale&&t.includes(this.value)&&(e.locale=this.value,this.lastLocale=this.value):(this.lastLocale=e.locale,this.value=e.locale)}super._sync()}_optionLabel(e){return on[e]??e}},cn=.5*(Math.sqrt(3)-1),ln=(3-Math.sqrt(3))/6,un=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,0,1,0,-1]);function dn(e){let t=new P(e),n=new Uint8Array(512),r=new Uint8Array(256);for(let e=0;e<256;e++)r[e]=e;for(let e=255;e>0;e--){let n=t.int(0,e),i=r[e];r[e]=r[n],r[n]=i}for(let e=0;e<512;e++)n[e]=r[e&255];return(e,t)=>{let r=(e+t)*cn,i=Math.floor(e+r),a=Math.floor(t+r),o=(i+a)*ln,s=e-(i-o),c=t-(a-o),l=+(s>c),u=s>c?0:1,d=s-l+ln,f=c-u+ln,p=s-1+2*ln,m=c-1+2*ln,h=i&255,g=a&255,_=0,v=.5-s*s-c*c;if(v>0){v*=v;let e=n[h+n[g]]%8*2;_+=v*v*(un[e]*s+un[e+1]*c)}let y=.5-d*d-f*f;if(y>0){y*=y;let e=n[h+l+n[g+u]]%8*2;_+=y*y*(un[e]*d+un[e+1]*f)}let b=.5-p*p-m*m;if(b>0){b*=b;let e=n[h+1+n[g+1]]%8*2;_+=b*b*(un[e]*p+un[e+1]*m)}return 70*_}}var fn={fire:{rate:60,lifetime:[.4,.9],speed:[30,70],directionDeg:-90,spreadDeg:35,gravity:[0,-30],sizeStart:14,sizeEnd:3,colorStart:`#ffcf5a`,colorEnd:`#e8401f`,alphaStart:.9,alphaEnd:0,blend:`add`},smoke:{rate:20,lifetime:[1.5,2.5],speed:[10,25],directionDeg:-90,spreadDeg:40,gravity:[0,-12],sizeStart:10,sizeEnd:26,colorStart:`#8a8a8a`,colorEnd:`#3a3a3a`,alphaStart:.35,alphaEnd:0,blend:`normal`},sparks:{rate:80,lifetime:[.3,.7],speed:[120,260],spreadDeg:360,gravity:[0,240],drag:1,sizeStart:4,sizeEnd:1,colorStart:`#fff3b0`,colorEnd:`#ff9d2e`,blend:`add`},fireworks:{rate:0,burst:120,lifetime:[.8,1.6],speed:[80,240],spreadDeg:360,gravity:[0,90],drag:.6,sizeStart:5,sizeEnd:1,colorStart:`#9ad8ff`,colorEnd:`#ff5ad8`,blend:`add`},explosion:{rate:0,burst:60,lifetime:[.25,.6],speed:[150,420],spreadDeg:360,drag:3,sizeStart:16,sizeEnd:2,colorStart:`#ffe08a`,colorEnd:`#ff3b1f`,blend:`add`},flash:{rate:0,burst:8,lifetime:[.08,.16],speed:[0,30],spreadDeg:360,sizeStart:64,sizeEnd:96,colorStart:`#ffffff`,colorEnd:`#ffffff`,alphaStart:1,alphaEnd:0,blend:`add`},lightning:{rate:90,lifetime:[.05,.12],speed:[400,900],directionDeg:-90,spreadDeg:14,sizeStart:6,sizeEnd:2,colorStart:`#eaf2ff`,colorEnd:`#7fb4ff`,blend:`add`},rain:{rate:160,lifetime:[.8,1.2],speed:[300,420],directionDeg:90,spreadDeg:6,sizeStart:3,sizeEnd:3,colorStart:`#9ec8ff`,colorEnd:`#9ec8ff`,alphaStart:.5,alphaEnd:.2,blend:`normal`},snow:{rate:40,lifetime:[3,5],speed:[20,50],directionDeg:90,spreadDeg:30,drag:.2,sizeStart:5,sizeEnd:4,colorStart:`#ffffff`,colorEnd:`#ffffff`,alphaStart:.9,alphaEnd:.6,blend:`normal`},magic:{rate:50,lifetime:[.6,1.4],speed:[20,80],spreadDeg:360,gravity:[0,-20],sizeStart:7,sizeEnd:1,colorStart:`#9dffe8`,colorEnd:`#7a5cff`,blend:`add`}},pn=Object.keys(fn);function mn(e,t,n){if(t===`custom`)return;let r=fn[t];if(r)for(let[t,i]of Object.entries(r)){let r=n[t]?.default,a=e[t];r!==void 0&&Ve(a,r)&&(e[t]=Array.isArray(i)?[...i]:i)}}var hn=9,gn=class{config;rng;data;alive=0;spawnAccumulator=0;everSpawned=!1;constructor(e,t){this.config=e,this.rng=t,this.data=new Float64Array(Math.max(1,e.maxParticles)*hn)}setRate(e){this.config.rate=e,e<=0&&(this.spawnAccumulator=0)}get count(){return this.alive}get done(){return this.everSpawned&&this.alive===0}burst(e){for(let t=0;t<e;t++)this.spawn()}update(e){if(this.config.rate>0)for(this.spawnAccumulator+=this.config.rate*e;this.spawnAccumulator>=1;)--this.spawnAccumulator,this.spawn();let t=this.data,[n,r,i]=this.config.gravity,a=this.config.drag>0?Math.exp(-this.config.drag*e):1,o=0;for(;o<this.alive;){let s=o*hn,c=t[s+6]+e;if(c>=t[s+7]){this.kill(o);continue}t[s+6]=c,t[s+3]=(t[s+3]+n*e)*a,t[s+4]=(t[s+4]+r*e)*a,t[s+5]=(t[s+5]+i*e)*a,t[s+0]=t[s+0]+t[s+3]*e,t[s+1]=t[s+1]+t[s+4]*e,t[s+2]=t[s+2]+t[s+5]*e,o+=1}}forEach(e){let t=this.data;for(let n=0;n<this.alive;n++){let r=n*hn,i=t[r+6],a=t[r+7];e({x:t[r+0],y:t[r+1],z:t[r+2],vx:t[r+3],vy:t[r+4],vz:t[r+5],age:i,life:a,t:a>0?i/a:1,seed:t[r+8]})}}spawn(){if(this.alive>=this.config.maxParticles)return;let e=this.alive*hn,t=this.data,n=this.config,r=(n.directionDeg+(this.rng.next()-.5)*n.spreadDeg)*Math.PI/180,i=n.speed[0]+this.rng.next()*(n.speed[1]-n.speed[0]),a=n.spreadZ?(this.rng.next()-.5)*(n.spreadDeg*Math.PI/180):0,o=Math.cos(a);t[e+0]=0,t[e+1]=0,t[e+2]=0,t[e+3]=Math.cos(r)*i*o,t[e+4]=Math.sin(r)*i*o,t[e+5]=Math.sin(a)*i,t[e+6]=0,t[e+7]=n.lifetime[0]+this.rng.next()*(n.lifetime[1]-n.lifetime[0]),t[e+8]=this.rng.next(),this.alive+=1,this.everSpawned=!0}kill(e){let t=this.alive-1;e!==t&&this.data.copyWithin(e*hn,t*hn,t*hn+hn),this.alive=t}};function _n(){R(Nt),R(Qt),R(Rt),R(Ht),R(qt),R(Jt),R(Yt),R(Xt),R(Zt),R(en),R(tn),R(nn),R(rn),R(an),R(sn)}function vn(e,t,n,r){let i=e?.rendering??{},a=i.pixelRatio===`device`?n:i.pixelRatio;return{antialias:r?.antialias??i.antialias??t.antialias,pixelRatio:r?.pixelRatio??a??t.pixelRatio,preserveDrawingBuffer:r?.preserveDrawingBuffer??i.preserveDrawingBuffer??t.preserveDrawingBuffer}}var yn=`@const`;function bn(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.keys(e);return t.length===1&&t[0]===`@const`&&typeof e[`@const`]==`string`}function xn(e,t){if(e==null)return e;if(bn(e)){let n=e[yn];if(!t||!(n in t)){let e=t?Object.keys(t):[];throw new N(`UNKNOWN_CONSTANT`,`Unknown constant '@const: ${n}'. Declared constants: ${e.length?e.join(`, `):`(none — add a "constants" section)`}.`)}return He(t[n])}if(Array.isArray(e))return e.map(e=>xn(e,t));if(typeof e==`object`){let n={};for(let[r,i]of Object.entries(e))n[r]=xn(i,t);return n}return e}var Sn=class e{_root=null;_engine=null;freeQueue=new Set;_nameIndex=new Map;_structureVersion=0;_structureLog=[];_structureLogBase=0;static STRUCTURE_LOG_MAX=2048;_structureSince(e){return e>this._structureVersion||e<this._structureLogBase?null:this._structureLog.slice(e-this._structureLogBase)}_logStructure(t,n){this._structureVersion++,this._structureLog.push({node:t,added:n});let r=this._structureLog.length-e.STRUCTURE_LOG_MAX;r>0&&(this._structureLog.splice(0,r),this._structureLogBase+=r)}_frameId=0;get frameId(){return this._frameId}_indexName(e){this._logStructure(e,!0);let t=this._nameIndex.get(e.name);t||(t=new Set,this._nameIndex.set(e.name,t)),t.add(e)}_reindexName(e,t){let n=this._nameIndex.get(t);n&&(n.delete(e),n.size===0&&this._nameIndex.delete(t));let r=this._nameIndex.get(e.name);r||(r=new Set,this._nameIndex.set(e.name,r)),r.add(e)}_unindexName(e,t=e.name){this._logStructure(e,!1);let n=this._nameIndex.get(t);n&&(n.delete(e),n.size===0&&this._nameIndex.delete(t))}_nodesNamed(e){return this._nameIndex.get(e)}_frameScratch=null;get root(){return this._root}get engine(){return this._engine}_setEngine(e){this._engine=e}setRoot(e){if(this._root)throw new N(`TREE_VIOLATION`,`SceneTree already has a root.`);if(e.parent)throw new N(`TREE_VIOLATION`,`Root must not have a parent ('${e.name}' is a child of '${e.parent.name}').`);this._root=e,e._propagateEnterTree(this),e._propagateReady()}update(e){this._frameId++,this._root?._propagateUpdate(e),this.flushFreeQueue()}fixedUpdate(e){this._root?._propagateFixedUpdate(e),this.flushFreeQueue()}getNodesInGroup(e){let t=[];return this._root&&Cn(this._root,e,t),t}callGroup(e,t,...n){for(let r of this.getNodesInGroup(e)){let e=r[t];typeof e==`function`&&e.apply(r,n)}}_queueFree(e){this.freeQueue.add(e)}_detachRoot(e){this._root===e&&(this._root=null)}flushFreeQueue(){if(this.freeQueue.size===0)return;let e=[...this.freeQueue];this.freeQueue.clear();for(let t of e)t.free()}};function Cn(e,t,n){e.isInGroup(t)&&n.push(e);for(let r of e.children)Cn(r,t,n)}var wn=[`expand`,`letterbox`,`integer`];function Tn(e){if(e===void 0)return null;let t=e.design;if(!Array.isArray(t)||t.length!==2||typeof t[0]!=`number`||typeof t[1]!=`number`||t[0]<=0||t[1]<=0)throw new N(`BAD_FORMAT`,`Scene "viewport.design" must be [width, height] with positive numbers, got ${JSON.stringify(t)}.`);let n=e.fit??`expand`;if(typeof n!=`string`||!wn.includes(n))throw new N(`BAD_FORMAT`,`Scene "viewport.fit" must be one of [${wn.join(`, `)}], got ${JSON.stringify(n)}.`);return{design:[t[0],t[1]],fit:n}}function En(e,t,n){let r=n.design[0],i=n.design[1],a=Math.min(e/r,t/i),o=n.fit===`integer`?Math.max(1,Math.floor(a)):a;if(n.fit===`letterbox`){let n=r*o,a=i*o;return{scale:o,viewW:r,viewH:i,offsetX:(e-n)/2,offsetY:(t-a)/2,contentW:n,contentH:a}}return{scale:o,viewW:e/o,viewH:t/o,offsetX:0,offsetY:0,contentW:e,contentH:t}}function Dn(e){let t=e.constructor,n={name:e.name,type:t.typeName};e.uid!==null&&(n.uid=e.uid),e.groups.size>0&&(n.groups=[...e.groups]),Object.keys(e.tags).length>0&&(n.tags=He(e.tags));let r=qe(t.typeName),i={};for(let[t,n]of Object.entries(r)){let r=e[t];r!==void 0&&(On(r,`${e.name}.${t}`),Ve(r,n.default)||(i[t]=He(r)))}return Object.keys(i).length>0&&(n.props=i),e.script&&(n.script=He(e.script)),e.network&&(n.network=He(e.network)),e.children.length>0&&(n.children=e.children.map(e=>Dn(e))),n}function On(e,t){if(typeof e==`number`&&!Number.isFinite(e))throw new N(`PROP_TYPE_MISMATCH`,`Prop '${t}' is ${e} — scene props must be finite numbers (NaN/Infinity become null in JSON).`);if(Array.isArray(e))for(let n=0;n<e.length;n++)On(e[n],`${t}[${n}]`);else if(typeof e==`object`&&e)for(let[n,r]of Object.entries(e))On(r,`${t}.${n}`)}var kn=class{name;dimension;root;tree;environment;assets;constants;input;strings;orderGroups;physics;multiplayer;viewport;connections;source;constructor(e,t,n){this.source=He(e),this.name=e.name,this.dimension=e.dimension,this.root=t,this.tree=n,this.assets=e.assets?He(e.assets):void 0,this.constants=e.constants?He(e.constants):void 0,this.input=e.input?He(e.input):void 0,this.orderGroups=e.orderGroups?{...e.orderGroups}:void 0,this.strings=e.strings?He(e.strings):void 0,this.physics=e.physics?He(e.physics):void 0,this.multiplayer=e.multiplayer?He(e.multiplayer):void 0,this.environment=e.environment?He(e.environment):void 0,this.viewport=e.viewport?He(e.viewport):void 0,this.connections=e.connections?He(e.connections):[]}toJSON(){return{format:1,type:`scene`,name:this.name,...this.dimension?{dimension:this.dimension}:{},...this.assets?{assets:He(this.assets)}:{},...this.constants?{constants:He(this.constants)}:{},...this.input?{input:He(this.input)}:{},...this.orderGroups?{orderGroups:{...this.orderGroups}}:{},...this.strings?{strings:He(this.strings)}:{},...this.physics?{physics:He(this.physics)}:{},...this.multiplayer?{multiplayer:He(this.multiplayer)}:{},...this.environment?{environment:He(this.environment)}:{},...this.viewport?{viewport:He(this.viewport)}:{},root:Dn(this.root),...this.connections.length>0?{connections:He(this.connections)}:{}}}};function An(e,t){if(typeof e!=`object`||!e)throw new N(`BAD_FORMAT`,`Scene JSON must be an object, got ${e===null?`null`:typeof e}.`);let n=e;Mn(n);let r=Pn(n.root,t,[],``,n.constants,Object.keys(n.orderGroups??{}));Hn(r);let i=new Sn;return t?.engine&&i._setEngine(t.engine),i.setRoot(r),zn(r,n.connections??[],t?.declareConnectionSignals),new kn(n,r,i)}function jn(e,t){return Pn(e,t,[],``,void 0)}function Mn(e){if(e.format!==1)throw new N(`BAD_FORMAT`,`Unsupported scene format ${JSON.stringify(e.format)}; this engine reads format 1.`);if(e.type!==`scene`)throw new N(`BAD_FORMAT`,`Expected "type": "scene", got ${JSON.stringify(e.type)}.`);if(typeof e.name!=`string`||e.name===``)throw new N(`BAD_FORMAT`,`Scene "name" must be a non-empty string.`);if(e.dimension!==void 0&&e.dimension!==`2d`&&e.dimension!==`3d`)throw new N(`BAD_FORMAT`,`Scene "dimension" must be "2d" or "3d", got ${JSON.stringify(e.dimension)}.`);if(typeof e.root!=`object`||e.root===null)throw new N(`BAD_FORMAT`,`Scene "root" must be a node object.`);if(Tn(e.viewport),e.input!==void 0){if(typeof e.input!=`object`||e.input===null||Array.isArray(e.input))throw new N(`BAD_FORMAT`,`Scene "input" must be an object of action declarations.`);pt(e.input)}if(e.orderGroups!==void 0){let t=e.orderGroups;if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`BAD_FORMAT`,`Scene "orderGroups" must be an object of band name → base offset, e.g. { "ui-back": 2500 }.`);for(let[e,n]of Object.entries(t))if(typeof n!=`number`||!Number.isFinite(n))throw new N(`BAD_FORMAT`,`Order group '${e}' must be a finite number (its base draw offset), got ${JSON.stringify(n)}. A band is a NUMBER — a bare name would sort exactly like "default" and mean nothing.`,{prop:e})}if(e.assets!==void 0){if(typeof e.assets!=`object`||e.assets===null||Array.isArray(e.assets))throw new N(`BAD_FORMAT`,`Scene "assets" must be an object of asset declarations.`);for(let[t,n]of Object.entries(e.assets)){if(typeof n!=`object`||!n||Array.isArray(n))throw new N(`BAD_FORMAT`,`Asset '${t}' must be an object, got ${JSON.stringify(n)}.`);let e=n.url;if(typeof e!=`string`||e===``)throw new N(`BAD_FORMAT`,`Asset '${t}' needs a non-empty "url" string.`)}}}function Nn(e,t,n){return e instanceof N&&!e.details.path?new N(e.code,`${e.message} (at '${t}')`,{...e.details,path:t,...typeof n.uid==`string`&&n.uid!==``?{uid:n.uid}:{},...e.details.nodeType===void 0&&n.type?{nodeType:n.type}:{}}):e}function Pn(e,t,n,r,i,a=[]){let o=`${r}/${e.name}`;try{if(e.instance!==void 0&&e.type!==void 0)throw new N(`BAD_FORMAT`,`Node '${e.name}' declares both "type" and "instance" — they are mutually exclusive.`);if(e.instance!==void 0)return Fn(e,t,n,o,i,a);if(e.type===void 0)throw new N(`BAD_FORMAT`,`Node '${e.name}' must declare either "type" or "instance".`);let r=$e(e.type,xn(e.props,i),{orderGroup:a});Ln(r,e,t),r.constructor.validateJson?.(r);for(let s of e.children??[])r.addChild(Pn(s,t,n,o,i,a));return r}catch(t){throw Nn(t,o,e)}}function Fn(e,t,n,r,i,a){let o=e.instance;if(!t?.resolveScene)throw new N(`UNRESOLVED_INSTANCE`,`Node '${e.name}' references instance '${o}' but no resolveScene option was provided.`);if(n.includes(o))throw new N(`UNRESOLVED_INSTANCE`,`Instance cycle detected: ${[...n,o].join(` → `)}.`);let s=t.resolveScene(o);if(!s)throw new N(`UNRESOLVED_INSTANCE`,`resolveScene returned nothing for instance '${o}' (node '${e.name}').`);Mn(s);let c=xn(e.overrides??{},i),l=Pn({...s.root,name:e.name,props:Rn(s.root.props??{},c)},t,[...n,o],In(r),s.constants,Object.keys(s.orderGroups??{}));Ln(l,{...e,type:void 0,props:void 0},t);for(let o of e.children??[])l.addChild(Pn(o,t,n,r,i,a));return zn(l,s.connections??[],t?.declareConnectionSignals),l}function In(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function Ln(e,t,n){typeof t.uid==`string`&&t.uid!==``&&(e.uid=t.uid),e.name=t.name;for(let n of t.groups??[])e.addToGroup(n);if(t.tags&&(e.tags=He(t.tags)),t.script){e.script=He(t.script);let r=t.script.name;if(typeof r!=`string`||r===``)throw new N(`BAD_FORMAT`,`Node '${t.name}': "script" needs a non-empty "name" (a registered behavior).`);let i=n?.stubAllBehaviors||n?.stubMissingBehaviors&&!rt(r)?new class extends tt{}:ct(r,t.script.props);i.node=e,e.behavior=i;for(let t of Je(i.constructor))e.declareSignal(t)}t.network&&(e.network=He(t.network))}function Rn(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t!==null&&r!==null&&typeof t==`object`&&typeof r==`object`&&!Array.isArray(t)&&!Array.isArray(r)?n[e]=Rn(t,r):n[e]=r}return n}function zn(e,t,n=!1){for(let r of t){let t=Bn(e,r.from,r,`from`);(n||t.behavior instanceof tt)&&t.declareSignal(r.signal);let i=Bn(e,r.to,r,`to`),a=i[r.handler],o=i.behavior?i.behavior[r.handler]:void 0;if(typeof a!=`function`&&typeof o!=`function`&&!(i.behavior instanceof tt))throw new N(`UNKNOWN_HANDLER`,`Connection '${r.signal}' → '${r.to}' names handler '${r.handler}', but '${i.name}' has no such method`+(i.behavior?` (nor does its behavior '${i.script?.name}')`:``)+`.`);let s=(...e)=>{if(r.filter&&!Vn(e[0],r.filter))return;r.once&&t.off(r.signal,s);let n=i[r.handler];if(typeof n==`function`){n.apply(i,e);return}let a=i.behavior?i.behavior[r.handler]:void 0;typeof a==`function`&&a.apply(i.behavior,e)};try{t.on(r.signal,s)}catch(e){throw e instanceof N&&e.code===`UNKNOWN_SIGNAL`?new N(`UNKNOWN_SIGNAL`,`Connection from '${r.from}': ${e.message}`,e.details):e}}}function Bn(e,t,n,r){try{return e.getNode(t)}catch(e){throw e instanceof N?new N(`DANGLING_CONNECTION`,`Connection '${n.signal}' has a dangling '${r}' path '${t}': ${e.message}`):e}}function Vn(e,t){if(!(e instanceof Nt)||t.group&&!e.isInGroup(t.group))return!1;if(t.tag){for(let[n,r]of Object.entries(t.tag))if(JSON.stringify(e.tags[n])!==JSON.stringify(r))return!1}return!0}function Hn(e){let t=new Map,n=e=>{if(e.uid!==null){let n=t.get(e.uid);if(n)throw new N(`DUPLICATE_UID`,`duplicate uid '${e.uid}' on ${n.getPath()} and ${e.getPath()} — uids must be unique across the scene.`);t.set(e.uid,e)}for(let t of e.children)n(t)};n(e)}function Un(e){let{uid:t,...n}=e;return{...n,children:e.children?.map(Un)}}function Wn(e){return jn(Un(Dn(e)))}var Gn=.08;function Kn(e,t,n){let r=e/n,i=t/n,a=Math.hypot(r,i);return a<Gn?{x:0,y:0}:(a>1&&(r/=a,i/=a),{x:r,y:i})}function qn(e,t,n={}){let r=e.input.touchControls();if(r.length===0||!n.force&&!Jn())return null;let i=n.doc??(typeof document<`u`?document:null);return!i||typeof t.appendChild!=`function`?null:new Yn(e,t,r,i)}function Jn(){return typeof matchMedia<`u`&&matchMedia(`(pointer: coarse)`).matches}var Yn=class{elements=[];detachers=[];constructor(e,t,n,r){let i=0,a=0;for(let o of n)o.kind===`joystick`?(this.buildJoystick(e,t,o.action,a,r),a+=1):(this.buildButton(e,t,o.action,i,r),i+=1)}dispose(){for(let e of this.detachers)e();for(let e of this.elements)e.remove();this.elements.length=0,this.detachers.length=0}buildJoystick(e,t,n,r,i){let a=i.createElement(`div`);Zn(a,{position:`absolute`,left:`${24+r*140}px`,bottom:`24px`,width:`120px`,height:`120px`,borderRadius:`50%`,background:`rgba(255,255,255,0.10)`,border:`2px solid rgba(255,255,255,0.25)`,touchAction:`none`,pointerEvents:`auto`,zIndex:`20`});let o=i.createElement(`div`);Zn(o,{position:`absolute`,left:`50%`,top:`50%`,width:`48px`,height:`48px`,marginLeft:`-24px`,marginTop:`-24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.35)`,pointerEvents:`none`}),a.appendChild(o),t.appendChild(a),this.elements.push(a);let s=null,c=0,l=0,u=60,d=(t,r)=>{let i=Kn(t-c,r-l,u);Xn(()=>e.input.setActionVector(n,i.x,i.y)),o.style.transform=`translate(${i.x*u*.6}px, ${i.y*u*.6}px)`},f=e=>{s=e.pointerId;let t=a.getBoundingClientRect();c=t.left+t.width/2,l=t.top+t.height/2,u=t.width/2,a.setPointerCapture?.(e.pointerId),d(e.clientX,e.clientY)},p=e=>{e.pointerId===s&&d(e.clientX,e.clientY)},m=t=>{t.pointerId===s&&(s=null,o.style.transform=``,Xn(()=>e.input.setActionVector(n,0,0)))};a.addEventListener(`pointerdown`,f),a.addEventListener(`pointermove`,p),a.addEventListener(`pointerup`,m),a.addEventListener(`pointercancel`,m),this.detachers.push(()=>{a.removeEventListener(`pointerdown`,f),a.removeEventListener(`pointermove`,p),a.removeEventListener(`pointerup`,m),a.removeEventListener(`pointercancel`,m)})}buildButton(e,t,n,r,i){let a=i.createElement(`div`);a.textContent=n,Zn(a,{position:`absolute`,right:`24px`,bottom:`${24+r*80}px`,width:`64px`,height:`64px`,borderRadius:`50%`,background:`rgba(255,255,255,0.12)`,border:`2px solid rgba(255,255,255,0.3)`,color:`rgba(255,255,255,0.85)`,font:`600 12px system-ui, sans-serif`,display:`flex`,alignItems:`center`,justifyContent:`center`,userSelect:`none`,touchAction:`none`,pointerEvents:`auto`,zIndex:`20`}),t.appendChild(a),this.elements.push(a);let o=null,s=t=>{o=t.pointerId,a.setPointerCapture?.(t.pointerId),Xn(()=>e.input.pressAction(n)),a.style.background=`rgba(255,255,255,0.3)`},c=t=>{t.pointerId===o&&(o=null,Xn(()=>e.input.releaseAction(n)),a.style.background=`rgba(255,255,255,0.12)`)};a.addEventListener(`pointerdown`,s),a.addEventListener(`pointerup`,c),a.addEventListener(`pointercancel`,c),this.detachers.push(()=>{a.removeEventListener(`pointerdown`,s),a.removeEventListener(`pointerup`,c),a.removeEventListener(`pointercancel`,c)})}};function Xn(e){try{e()}catch{}}function Zn(e,t){for(let[n,r]of Object.entries(t))e.style[n]=r}function Qn(){let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);let t=``;for(let n of e)t+=(n%36).toString(36);return`n_${t.slice(0,16)}`}var $n=`attached`,er=1e3,tr=1001,nr=1002,rr=1003,ir=1004,ar=1005,or=1006,sr=1007,cr=1008,lr=1009,ur=1010,dr=1011,fr=1012,pr=1013,mr=1014,hr=1015,gr=1016,_r=1017,vr=1018,yr=1020,br=35902,xr=35899,Sr=1021,Cr=1022,wr=1023,Tr=1026,Er=1027,Dr=1028,Or=1029,kr=1030,Ar=1031,jr=1033,Mr=33776,Nr=33777,Pr=33778,Fr=33779,Ir=35840,Lr=35841,Rr=35842,zr=35843,Br=36196,Vr=37492,Hr=37496,Ur=37488,Wr=37489,Gr=37490,Kr=37491,qr=37808,Jr=37809,Yr=37810,Xr=37811,Zr=37812,Qr=37813,$r=37814,ei=37815,ti=37816,ni=37817,ri=37818,ii=37819,ai=37820,oi=37821,si=36492,ci=36494,li=36495,ui=36283,di=36284,fi=36285,pi=36286,mi=2200,hi=2201,gi=2202,_i=2300,vi=2301,yi=2302,bi=2303,xi=2400,Si=2401,Ci=2402,wi=2500,Ti=2501,Ei=3200,Di=3201,Oi=`srgb`,ki=`srgb-linear`,Ai=`linear`,ji=`srgb`,Mi=7680,Ni=35044,Pi=35048,Fi=2e3;function Ii(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Li(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Ri(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function zi(){let e=Ri(`canvas`);return e.style.display=`block`,e}var Bi={},Vi=null;function Hi(...e){let t=`THREE.`+e.shift();Vi?Vi(`log`,t,...e):console.log(t,...e)}function Ui(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function z(...e){e=Ui(e);let t=`THREE.`+e.shift();if(Vi)Vi(`warn`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function B(...e){e=Ui(e);let t=`THREE.`+e.shift();if(Vi)Vi(`error`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function Wi(...e){let t=e.join(` `);t in Bi||(Bi[t]=!0,z(...e))}function Gi(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var Ki={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},qi=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},Ji=`00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),Yi=1234567,Xi=Math.PI/180,Zi=180/Math.PI;function Qi(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(Ji[e&255]+Ji[e>>8&255]+Ji[e>>16&255]+Ji[e>>24&255]+`-`+Ji[t&255]+Ji[t>>8&255]+`-`+Ji[t>>16&15|64]+Ji[t>>24&255]+`-`+Ji[n&63|128]+Ji[n>>8&255]+`-`+Ji[n>>16&255]+Ji[n>>24&255]+Ji[r&255]+Ji[r>>8&255]+Ji[r>>16&255]+Ji[r>>24&255]).toLowerCase()}function $i(e,t,n){return Math.max(t,Math.min(n,e))}function ea(e,t){return(e%t+t)%t}function ta(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function na(e,t,n){return e===t?0:(n-e)/(t-e)}function ra(e,t,n){return(1-n)*e+n*t}function ia(e,t,n,r){return ra(e,t,1-Math.exp(-n*r))}function aa(e,t=1){return t-Math.abs(ea(e,t*2)-t)}function oa(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function sa(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function ca(e,t){return e+Math.floor(Math.random()*(t-e+1))}function la(e,t){return e+Math.random()*(t-e)}function ua(e){return e*(.5-Math.random())}function da(e){e!==void 0&&(Yi=e);let t=Yi+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function fa(e){return e*Xi}function pa(e){return e*Zi}function ma(e){return(e&e-1)==0&&e!==0}function ha(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function ga(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function _a(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:z(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function va(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`Invalid component type.`)}}function ya(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}var ba={DEG2RAD:Xi,RAD2DEG:Zi,generateUUID:Qi,clamp:$i,euclideanModulo:ea,mapLinear:ta,inverseLerp:na,lerp:ra,damp:ia,pingpong:aa,smoothstep:oa,smootherstep:sa,randInt:ca,randFloat:la,randFloatSpread:ua,seededRandom:da,degToRad:fa,radToDeg:pa,isPowerOfTwo:ma,ceilPowerOfTwo:ha,floorPowerOfTwo:ga,setQuaternionFromProperEuler:_a,normalize:ya,denormalize:va},V=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=$i(this.x,e.x,t.x),this.y=$i(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=$i(this.x,e,t),this.y=$i(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar($i(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos($i(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},H=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:z(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs($i(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},U=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Sa.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Sa.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=$i(this.x,e.x,t.x),this.y=$i(this.y,e.y,t.y),this.z=$i(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=$i(this.x,e,t),this.y=$i(this.y,e,t),this.z=$i(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar($i(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return xa.copy(this).projectOnVector(e),this.sub(xa)}reflect(e){return this.sub(xa.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos($i(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},xa=new U,Sa=new H,W=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Ca.makeScale(e,t)),this}rotate(e){return this.premultiply(Ca.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ca.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Ca=new W,wa=new W().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Ta=new W().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Ea(){let e={enabled:!0,workingColorSpace:ki,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=Oa(e.r),e.g=Oa(e.g),e.b=Oa(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=ka(e.r),e.g=ka(e.g),e.b=ka(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Ai:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return Wi(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Wi(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[ki]:{primaries:t,whitePoint:r,transfer:Ai,toXYZ:wa,fromXYZ:Ta,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Oi},outputColorSpaceConfig:{drawingBufferColorSpace:Oi}},[Oi]:{primaries:t,whitePoint:r,transfer:ji,toXYZ:wa,fromXYZ:Ta,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Oi}}}),e}var Da=Ea();function Oa(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function ka(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Aa,ja=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Aa===void 0&&(Aa=Ri(`canvas`)),Aa.width=e.width,Aa.height=e.height;let t=Aa.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Aa}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=Ri(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=Oa(i[e]/255)*255;return n.putImageData(r,0,0),t}else if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(Oa(t[e]/255)*255):t[e]=Oa(t[e]);return{data:t,width:e.width,height:e.height}}else return z(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},Ma=0,Na=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Ma++}),this.uuid=Qi(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<`u`&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(Pa(r[t].image)):e.push(Pa(r[t]))}else e=Pa(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function Pa(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?ja.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(z(`Texture: Unable to serialize Texture.`),{})}var Fa=0,Ia=new U,La=class e extends qi{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=tr,i=tr,a=or,o=cr,s=wr,c=lr,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Fa++}),this.uuid=Qi(),this.name=``,this.source=new Na(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new V(0,0),this.repeat=new V(1,1),this.center=new V(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new W,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Ia).x}get height(){return this.source.getSize(Ia).y}get depth(){return this.source.getSize(Ia).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){z(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){z(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case er:e.x-=Math.floor(e.x);break;case tr:e.x=e.x<0?0:1;break;case nr:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case er:e.y-=Math.floor(e.y);break;case tr:e.y=e.y<0?0:1;break;case nr:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};La.DEFAULT_IMAGE=null,La.DEFAULT_MAPPING=300,La.DEFAULT_ANISOTROPY=1;var Ra=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=$i(this.x,e.x,t.x),this.y=$i(this.y,e.y,t.y),this.z=$i(this.z,e.z,t.z),this.w=$i(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=$i(this.x,e,t),this.y=$i(this.y,e,t),this.z=$i(this.z,e,t),this.w=$i(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar($i(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},za=class extends qi{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:or,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Ra(0,0,e,t),this.scissorTest=!1,this.viewport=new Ra(0,0,e,t),this.textures=[];let r=new La({width:e,height:t,depth:n.depth}),i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){let t={minFilter:or,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new Na(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this.multiview=e.multiview,this}dispose(){this.dispatchEvent({type:`dispose`})}},Ba=class extends za{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},Va=class extends La{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=rr,this.minFilter=rr,this.wrapR=tr,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Ha=class extends La{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=rr,this.minFilter=rr,this.wrapR=tr,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},G=class e{static{e.prototype.isMatrix4=!0}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();let t=this.elements,n=e.elements,r=1/Ua.setFromMatrixColumn(e,0).length(),i=1/Ua.setFromMatrixColumn(e,1).length(),a=1/Ua.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Ga,e,Ka)}lookAt(e,t,n){let r=this.elements;return Ya.subVectors(e,t),Ya.lengthSq()===0&&(Ya.z=1),Ya.normalize(),qa.crossVectors(n,Ya),qa.lengthSq()===0&&(Math.abs(n.z)===1?Ya.x+=1e-4:Ya.z+=1e-4,Ya.normalize(),qa.crossVectors(n,Ya)),qa.normalize(),Ja.crossVectors(Ya,qa),r[0]=qa.x,r[4]=Ja.x,r[8]=Ya.x,r[1]=qa.y,r[5]=Ja.y,r[9]=Ya.y,r[2]=qa.z,r[6]=Ja.z,r[10]=Ya.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],k=r[2],A=r[6],ee=r[10],te=r[14],ne=r[3],re=r[7],j=r[11],ie=r[15];return i[0]=a*x+o*T+s*k+c*ne,i[4]=a*S+o*E+s*A+c*re,i[8]=a*C+o*D+s*ee+c*j,i[12]=a*w+o*O+s*te+c*ie,i[1]=l*x+u*T+d*k+f*ne,i[5]=l*S+u*E+d*A+f*re,i[9]=l*C+u*D+d*ee+f*j,i[13]=l*w+u*O+d*te+f*ie,i[2]=p*x+m*T+h*k+g*ne,i[6]=p*S+m*E+h*A+g*re,i[10]=p*C+m*D+h*ee+g*j,i[14]=p*w+m*O+h*te+g*ie,i[3]=_*x+v*T+y*k+b*ne,i[7]=_*S+v*E+y*A+b*re,i[11]=_*C+v*D+y*ee+b*j,i[15]=_*w+v*O+y*te+b*ie,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15],_=s*f-c*d,v=o*f-c*u,y=o*d-s*u,b=a*f-c*l,x=a*d-s*l,S=a*u-o*l;return t*(m*_-h*v+g*y)-n*(p*_-h*b+g*x)+r*(p*v-m*b+g*S)-i*(p*y-m*x+h*S)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=t*o-n*a,v=t*s-r*a,y=t*c-i*a,b=n*s-r*o,x=n*c-i*o,S=r*c-i*s,C=l*m-u*p,w=l*h-d*p,T=l*g-f*p,E=u*h-d*m,D=u*g-f*m,O=d*g-f*h,k=_*O-v*D+y*E+b*T-x*w+S*C;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let A=1/k;return e[0]=(o*O-s*D+c*E)*A,e[1]=(r*D-n*O-i*E)*A,e[2]=(m*S-h*x+g*b)*A,e[3]=(d*x-u*S-f*b)*A,e[4]=(s*T-a*O-c*w)*A,e[5]=(t*O-r*T+i*w)*A,e[6]=(h*y-p*S-g*v)*A,e[7]=(l*S-d*y+f*v)*A,e[8]=(a*D-o*T+c*C)*A,e[9]=(n*T-t*D-i*C)*A,e[10]=(p*x-m*y+g*_)*A,e[11]=(u*y-l*x-f*_)*A,e[12]=(o*w-a*E-s*C)*A,e[13]=(t*E-n*w+r*C)*A,e[14]=(m*v-p*b-h*_)*A,e[15]=(l*b-u*v+d*_)*A,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let i=this.determinant();if(i===0)return n.set(1,1,1),t.identity(),this;let a=Ua.set(r[0],r[1],r[2]).length(),o=Ua.set(r[4],r[5],r[6]).length(),s=Ua.set(r[8],r[9],r[10]).length();i<0&&(a=-a),Wa.copy(this);let c=1/a,l=1/o,u=1/s;return Wa.elements[0]*=c,Wa.elements[1]*=c,Wa.elements[2]*=c,Wa.elements[4]*=l,Wa.elements[5]*=l,Wa.elements[6]*=l,Wa.elements[8]*=u,Wa.elements[9]*=u,Wa.elements[10]*=u,t.setFromRotationMatrix(Wa),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=Fi,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=Fi,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},Ua=new U,Wa=new G,Ga=new U(0,0,0),Ka=new U(1,1,1),qa=new U,Ja=new U,Ya=new U,Xa=new G,Za=new H,Qa=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin($i(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-$i(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin($i(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-$i(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin($i(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-$i(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:z(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Xa.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Xa,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Za.setFromEuler(this),this.setFromQuaternion(Za,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};Qa.DEFAULT_ORDER=`XYZ`;var $a=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!=0}},eo=0,to=new U,no=new H,ro=new G,io=new U,ao=new U,oo=new U,so=new H,co=new U(1,0,0),lo=new U(0,1,0),uo=new U(0,0,1),fo={type:`added`},po={type:`removed`},mo={type:`childadded`,child:null},ho={type:`childremoved`,child:null},go=class e extends qi{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:eo++}),this.uuid=Qi(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new U,n=new Qa,r=new H,i=new U(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new G},normalMatrix:{value:new W}}),this.matrix=new G,this.matrixWorld=new G,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new $a,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return no.setFromAxisAngle(e,t),this.quaternion.multiply(no),this}rotateOnWorldAxis(e,t){return no.setFromAxisAngle(e,t),this.quaternion.premultiply(no),this}rotateX(e){return this.rotateOnAxis(co,e)}rotateY(e){return this.rotateOnAxis(lo,e)}rotateZ(e){return this.rotateOnAxis(uo,e)}translateOnAxis(e,t){return to.copy(e).applyQuaternion(this.quaternion),this.position.add(to.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(co,e)}translateY(e){return this.translateOnAxis(lo,e)}translateZ(e){return this.translateOnAxis(uo,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(ro.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?io.copy(e):io.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),ao.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?ro.lookAt(ao,io,this.up):ro.lookAt(io,ao,this.up),this.quaternion.setFromRotationMatrix(ro),r&&(ro.extractRotation(r.matrixWorld),no.setFromRotationMatrix(ro),this.quaternion.premultiply(no.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(B(`Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(fo),mo.child=e,this.dispatchEvent(mo),mo.child=null):B(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(po),ho.child=e,this.dispatchEvent(ho),ho.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),ro.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),ro.multiply(e.parent.matrixWorld)),e.applyMatrix4(ro),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(fo),mo.child=e,this.dispatchEvent(mo),mo.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ao,e,oo),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ao,so,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,r=e.z,i=this.matrix.elements;i[12]+=t-i[0]*t-i[4]*n-i[8]*r,i[13]+=n-i[1]*t-i[5]*n-i[9]*r,i[14]+=r-i[2]*t-i[6]*n-i[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let e=this.children;for(let t=0,n=e.length;t<n;t++)e[t].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,this.name!==``&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),this.static!==!1&&(r.static=this.static),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material);if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}};go.DEFAULT_UP=new U(0,1,0),go.DEFAULT_MATRIX_AUTO_UPDATE=!0,go.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var _o=class extends go{constructor(){super(),this.isGroup=!0,this.type=`Group`}},vo={type:`move`},yo=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new _o,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new _o,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new U,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new U),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new _o,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new U,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new U,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position);c.inputState.pinching&&o>.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(vo)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new _o;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},bo={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},xo={h:0,s:0,l:0},So={h:0,s:0,l:0};function Co(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var K=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Oi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Da.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=Da.workingColorSpace){return this.r=e,this.g=t,this.b=n,Da.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=Da.workingColorSpace){if(e=ea(e,1),t=$i(t,0,1),n=$i(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=Co(i,r,e+1/3),this.g=Co(i,r,e),this.b=Co(i,r,e-1/3)}return Da.colorSpaceToWorking(this,r),this}setStyle(e,t=Oi){function n(t){t!==void 0&&parseFloat(t)<1&&z(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:z(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);z(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Oi){let n=bo[e.toLowerCase()];return n===void 0?z(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Oa(e.r),this.g=Oa(e.g),this.b=Oa(e.b),this}copyLinearToSRGB(e){return this.r=ka(e.r),this.g=ka(e.g),this.b=ka(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Oi){return Da.workingToColorSpace(wo.copy(this),e),Math.round($i(wo.r*255,0,255))*65536+Math.round($i(wo.g*255,0,255))*256+Math.round($i(wo.b*255,0,255))}getHexString(e=Oi){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Da.workingColorSpace){Da.workingToColorSpace(wo.copy(this),t);let n=wo.r,r=wo.g,i=wo.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4;break}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=Da.workingColorSpace){return Da.workingToColorSpace(wo.copy(this),t),e.r=wo.r,e.g=wo.g,e.b=wo.b,e}getStyle(e=Oi){Da.workingToColorSpace(wo.copy(this),e);let t=wo.r,n=wo.g,r=wo.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(xo),this.setHSL(xo.h+e,xo.s+t,xo.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(xo),e.getHSL(So);let n=ra(xo.h,So.h,t),r=ra(xo.s,So.s,t),i=ra(xo.l,So.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},wo=new K;K.NAMES=bo;var To=class e{constructor(e,t=1,n=1e3){this.isFog=!0,this.name=``,this.color=new K(e),this.near=t,this.far=n}clone(){return new e(this.color,this.near,this.far)}toJSON(){return{type:`Fog`,name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}},Eo=class extends go{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Qa,this.environmentIntensity=1,this.environmentRotation=new Qa,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},Do=new U,Oo=new U,ko=new U,Ao=new U,jo=new U,Mo=new U,No=new U,Po=new U,Fo=new U,Io=new U,Lo=new Ra,Ro=new Ra,zo=new Ra,Bo=class e{constructor(e=new U,t=new U,n=new U){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),Do.subVectors(e,t),r.cross(Do);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){Do.subVectors(r,t),Oo.subVectors(n,t),ko.subVectors(e,t);let a=Do.dot(Do),o=Do.dot(Oo),s=Do.dot(ko),c=Oo.dot(Oo),l=Oo.dot(ko),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Ao)===null?!1:Ao.x>=0&&Ao.y>=0&&Ao.x+Ao.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Ao)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Ao.x),s.addScaledVector(a,Ao.y),s.addScaledVector(o,Ao.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Lo.setScalar(0),Ro.setScalar(0),zo.setScalar(0),Lo.fromBufferAttribute(e,t),Ro.fromBufferAttribute(e,n),zo.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Lo,i.x),a.addScaledVector(Ro,i.y),a.addScaledVector(zo,i.z),a}static isFrontFacing(e,t,n,r){return Do.subVectors(n,t),Oo.subVectors(e,t),Do.cross(Oo).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Do.subVectors(this.c,this.b),Oo.subVectors(this.a,this.b),Do.cross(Oo).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;jo.subVectors(r,n),Mo.subVectors(i,n),Po.subVectors(e,n);let s=jo.dot(Po),c=Mo.dot(Po);if(s<=0&&c<=0)return t.copy(n);Fo.subVectors(e,r);let l=jo.dot(Fo),u=Mo.dot(Fo);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(jo,a);Io.subVectors(e,i);let f=jo.dot(Io),p=Mo.dot(Io);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(Mo,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return No.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(No,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(jo,a).addScaledVector(Mo,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Vo=class{constructor(e=new U(1/0,1/0,1/0),t=new U(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Uo.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Uo.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=Uo.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,Uo):Uo.fromBufferAttribute(r,t),Uo.applyMatrix4(e.matrixWorld),this.expandByPoint(Uo);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Wo.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Wo.copy(e.boundingBox)),Wo.applyMatrix4(e.matrixWorld),this.union(Wo)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Uo),Uo.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Zo),Qo.subVectors(this.max,Zo),Go.subVectors(e.a,Zo),Ko.subVectors(e.b,Zo),qo.subVectors(e.c,Zo),Jo.subVectors(Ko,Go),Yo.subVectors(qo,Ko),Xo.subVectors(Go,qo);let t=[0,-Jo.z,Jo.y,0,-Yo.z,Yo.y,0,-Xo.z,Xo.y,Jo.z,0,-Jo.x,Yo.z,0,-Yo.x,Xo.z,0,-Xo.x,-Jo.y,Jo.x,0,-Yo.y,Yo.x,0,-Xo.y,Xo.x,0];return!ts(t,Go,Ko,qo,Qo)||(t=[1,0,0,0,1,0,0,0,1],!ts(t,Go,Ko,qo,Qo))?!1:($o.crossVectors(Jo,Yo),t=[$o.x,$o.y,$o.z],ts(t,Go,Ko,qo,Qo))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Uo).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Uo).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Ho[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ho[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ho[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ho[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ho[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ho[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ho[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ho[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ho),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},Ho=[new U,new U,new U,new U,new U,new U,new U,new U],Uo=new U,Wo=new Vo,Go=new U,Ko=new U,qo=new U,Jo=new U,Yo=new U,Xo=new U,Zo=new U,Qo=new U,$o=new U,es=new U;function ts(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){es.fromArray(e,a);let o=i.x*Math.abs(es.x)+i.y*Math.abs(es.y)+i.z*Math.abs(es.z),s=t.dot(es),c=n.dot(es),l=r.dot(es);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var ns=rs();function rs(){let e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),r=new Uint32Array(512),i=new Uint32Array(512);for(let e=0;e<256;++e){let t=e-127;t<-27?(r[e]=0,r[e|256]=32768,i[e]=24,i[e|256]=24):t<-14?(r[e]=1024>>-t-14,r[e|256]=1024>>-t-14|32768,i[e]=-t-1,i[e|256]=-t-1):t<=15?(r[e]=t+15<<10,r[e|256]=t+15<<10|32768,i[e]=13,i[e|256]=13):t<128?(r[e]=31744,r[e|256]=64512,i[e]=24,i[e|256]=24):(r[e]=31744,r[e|256]=64512,i[e]=13,i[e|256]=13)}let a=new Uint32Array(2048),o=new Uint32Array(64),s=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(t&8388608);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,a[e]=t|n}for(let e=1024;e<2048;++e)a[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)e!==32&&(s[e]=1024);return{floatView:t,uint32View:n,baseTable:r,shiftTable:i,mantissaTable:a,exponentTable:o,offsetTable:s}}function is(e){Math.abs(e)>65504&&z(`DataUtils.toHalfFloat(): Value out of range.`),e=$i(e,-65504,65504),ns.floatView[0]=e;let t=ns.uint32View[0],n=t>>23&511;return ns.baseTable[n]+((t&8388607)>>ns.shiftTable[n])}function as(e){let t=e>>10;return ns.uint32View[0]=ns.mantissaTable[ns.offsetTable[t]+(e&1023)]+ns.exponentTable[t],ns.floatView[0]}var os=class{static toHalfFloat(e){return is(e)}static fromHalfFloat(e){return as(e)}},ss=new U,cs=new V,ls=0,q=class extends qi{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:ls++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Ni,this.updateRanges=[],this.gpuType=hr,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)cs.fromBufferAttribute(this,t),cs.applyMatrix3(e),this.setXY(t,cs.x,cs.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)ss.fromBufferAttribute(this,t),ss.applyMatrix3(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)ss.fromBufferAttribute(this,t),ss.applyMatrix4(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)ss.fromBufferAttribute(this,t),ss.applyNormalMatrix(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)ss.fromBufferAttribute(this,t),ss.transformDirection(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=va(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ya(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=va(t,this.array)),t}setX(e,t){return this.normalized&&(t=ya(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=va(t,this.array)),t}setY(e,t){return this.normalized&&(t=ya(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=va(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ya(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=va(t,this.array)),t}setW(e,t){return this.normalized&&(t=ya(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array),r=ya(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array),r=ya(r,this.array),i=ya(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==``&&(e.name=this.name),this.usage!==35044&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:`dispose`})}},us=class extends q{constructor(e,t,n){super(new Uint16Array(e),t,n)}},ds=class extends q{constructor(e,t,n){super(new Uint32Array(e),t,n)}},fs=class extends q{constructor(e,t,n){super(new Float32Array(e),t,n)}},ps=new Vo,ms=new U,hs=new U,gs=class{constructor(e=new U,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?ps.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;ms.subVectors(e,this.center);let t=ms.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(ms,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(hs.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ms.copy(e.center).add(hs)),this.expandByPoint(ms.copy(e.center).sub(hs))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},_s=0,vs=new G,ys=new go,bs=new U,xs=new Vo,Ss=new Vo,Cs=new U,J=class e extends qi{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:_s++}),this.uuid=Qi(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Ii(e)?ds:us)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new W().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return vs.makeRotationFromQuaternion(e),this.applyMatrix4(vs),this}rotateX(e){return vs.makeRotationX(e),this.applyMatrix4(vs),this}rotateY(e){return vs.makeRotationY(e),this.applyMatrix4(vs),this}rotateZ(e){return vs.makeRotationZ(e),this.applyMatrix4(vs),this}translate(e,t,n){return vs.makeTranslation(e,t,n),this.applyMatrix4(vs),this}scale(e,t,n){return vs.makeScale(e,t,n),this.applyMatrix4(vs),this}lookAt(e){return ys.lookAt(e),ys.updateMatrix(),this.applyMatrix4(ys.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(bs).negate(),this.translate(bs.x,bs.y,bs.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new fs(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&z(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Vo);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){B(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new U(-1/0,-1/0,-1/0),new U(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];xs.setFromBufferAttribute(n),this.morphTargetsRelative?(Cs.addVectors(this.boundingBox.min,xs.min),this.boundingBox.expandByPoint(Cs),Cs.addVectors(this.boundingBox.max,xs.max),this.boundingBox.expandByPoint(Cs)):(this.boundingBox.expandByPoint(xs.min),this.boundingBox.expandByPoint(xs.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&B(`BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new gs);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){B(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new U,1/0);return}if(e){let n=this.boundingSphere.center;if(xs.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];Ss.setFromBufferAttribute(n),this.morphTargetsRelative?(Cs.addVectors(xs.min,Ss.min),xs.expandByPoint(Cs),Cs.addVectors(xs.max,Ss.max),xs.expandByPoint(Cs)):(xs.expandByPoint(Ss.min),xs.expandByPoint(Ss.max))}xs.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)Cs.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(Cs));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)Cs.fromBufferAttribute(a,t),o&&(bs.fromBufferAttribute(e,t),Cs.add(bs)),r=Math.max(r,n.distanceToSquared(Cs))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&B(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){B(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv;this.hasAttribute(`tangent`)===!1&&this.setAttribute(`tangent`,new q(new Float32Array(4*n.count),4));let a=this.getAttribute(`tangent`),o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new U,s[e]=new U;let c=new U,l=new U,u=new U,d=new V,f=new V,p=new V,m=new U,h=new U;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new U,y=new U,b=new U,x=new U;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0)n=new q(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new U,i=new U,a=new U,o=new U,s=new U,c=new U,l=new U,u=new U;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Cs.fromBufferAttribute(e,t),Cs.normalize(),e.setXYZ(t,Cs.x,Cs.y,Cs.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new q(a,r,i)}if(this.index===null)return z(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.type,this.name!==``&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:`dispose`})}},ws=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e===void 0?0:e.length/t,this.usage=Ni,this.updateRanges=[],this.version=0,this.uuid=Qi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let r=0,i=this.stride;r<i;r++)this.array[e+r]=t.array[n+r];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Qi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Qi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},Ts=new U,Es=class e{constructor(e,t,n,r=!1){this.isInterleavedBufferAttribute=!0,this.name=``,this.data=e,this.itemSize=t,this.offset=n,this.normalized=r}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)Ts.fromBufferAttribute(this,t),Ts.applyMatrix4(e),this.setXYZ(t,Ts.x,Ts.y,Ts.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ts.fromBufferAttribute(this,t),Ts.applyNormalMatrix(e),this.setXYZ(t,Ts.x,Ts.y,Ts.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ts.fromBufferAttribute(this,t),Ts.transformDirection(e),this.setXYZ(t,Ts.x,Ts.y,Ts.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=va(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ya(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=ya(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=ya(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=ya(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=ya(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=va(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=va(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=va(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=va(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array),r=ya(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array),r=ya(r,this.array),i=ya(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this.data.array[e+3]=i,this}clone(t){if(t===void 0){Hi(`InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new q(new this.array.constructor(e),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new e(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){Hi(`InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},Ds=0,Os=class extends qi{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Ds++}),this.uuid=Qi(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new K(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Mi,this.stencilZFail=Mi,this.stencilZPass=Mi,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){z(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){z(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},ks=new U,As=new U,js=new U,Ms=new U,Ns=new U,Ps=new U,Fs=new U,Is=class{constructor(e=new U,t=new U(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,ks)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=ks.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(ks.copy(this.origin).addScaledVector(this.direction,t),ks.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){As.copy(e).add(t).multiplyScalar(.5),js.copy(t).sub(e).normalize(),Ms.copy(this.origin).sub(As);let i=e.distanceTo(t)*.5,a=-this.direction.dot(js),o=Ms.dot(this.direction),s=-Ms.dot(js),c=Ms.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0)if(u=a*s-o,d=a*o-s,p=i*l,u>=0)if(d>=-p)if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c);else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(As).addScaledVector(js,d),f}intersectSphere(e,t){ks.subVectors(e.center,this.origin);let n=ks.dot(this.direction),r=ks.dot(ks)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,ks)!==null}intersectTriangle(e,t,n,r,i){Ns.subVectors(t,e),Ps.subVectors(n,e),Fs.crossVectors(Ns,Ps);let a=this.direction.dot(Fs),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Ms.subVectors(this.origin,e);let s=o*this.direction.dot(Ps.crossVectors(Ms,Ps));if(s<0)return null;let c=o*this.direction.dot(Ns.cross(Ms));if(c<0||s+c>a)return null;let l=-o*Ms.dot(Fs);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Ls=class extends Os{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new K(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Qa,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Rs=new G,zs=new Is,Bs=new gs,Vs=new U,Hs=new U,Us=new U,Ws=new U,Gs=new U,Ks=new U,qs=new U,Js=new U,Ys=class extends go{constructor(e=new J,t=new Ls){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){Ks.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(Gs.fromBufferAttribute(s,e),a?Ks.addScaledVector(Gs,r):Ks.addScaledVector(Gs.sub(t),r))}t.add(Ks)}return t}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Bs.copy(n.boundingSphere),Bs.applyMatrix4(i),zs.copy(e.ray).recast(e.near),!(Bs.containsPoint(zs.origin)===!1&&(zs.intersectSphere(Bs,Vs)===null||zs.origin.distanceToSquared(Vs)>(e.far-e.near)**2))&&(Rs.copy(i).invert(),zs.copy(e.ray).applyMatrix4(Rs),!(n.boundingBox!==null&&zs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,zs)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null)if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=Zs(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=Zs(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}else if(s!==void 0)if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=Zs(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=Zs(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}};function Xs(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;Js.copy(s),Js.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(Js);return l<n.near||l>n.far?null:{distance:l,point:Js.clone(),object:e}}function Zs(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,Hs),e.getVertexPosition(c,Us),e.getVertexPosition(l,Ws);let u=Xs(e,t,n,r,Hs,Us,Ws,qs);if(u){let e=new U;Bo.getBarycoord(qs,Hs,Us,Ws,e),i&&(u.uv=Bo.getInterpolatedAttribute(i,s,c,l,e,new V)),a&&(u.uv1=Bo.getInterpolatedAttribute(a,s,c,l,e,new V)),o&&(u.normal=Bo.getInterpolatedAttribute(o,s,c,l,e,new U),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new U,materialIndex:0};Bo.getNormal(Hs,Us,Ws,t.normal),u.face=t,u.barycoord=e}return u}var Qs=new Ra,$s=new Ra,ec=new Ra,tc=new Ra,nc=new G,rc=new U,ic=new gs,ac=new G,oc=new Is,sc=class extends Ys{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type=`SkinnedMesh`,this.bindMode=$n,this.bindMatrix=new G,this.bindMatrixInverse=new G,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Vo),this.boundingBox.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,rc),this.boundingBox.expandByPoint(rc)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new gs),this.boundingSphere.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,rc),this.boundingSphere.expandByPoint(rc)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){let n=this.material,r=this.matrixWorld;n!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),ic.copy(this.boundingSphere),ic.applyMatrix4(r),e.ray.intersectsSphere(ic)!==!1&&(ac.copy(r).invert(),oc.copy(e.ray).applyMatrix4(ac),!(this.boundingBox!==null&&oc.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,oc)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let e=new Ra,t=this.geometry.attributes.skinWeight;for(let n=0,r=t.count;n<r;n++){e.fromBufferAttribute(t,n);let r=1/e.manhattanLength();r===1/0?e.set(1,0,0,0):e.multiplyScalar(r),t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===`attached`?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===`detached`?this.bindMatrixInverse.copy(this.bindMatrix).invert():z(`SkinnedMesh: Unrecognized bindMode: `+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,r=this.geometry;$s.fromBufferAttribute(r.attributes.skinIndex,e),ec.fromBufferAttribute(r.attributes.skinWeight,e),t.isVector4?(Qs.copy(t),t.set(0,0,0,0)):(Qs.set(...t,1),t.set(0,0,0)),Qs.applyMatrix4(this.bindMatrix);for(let e=0;e<4;e++){let r=ec.getComponent(e);if(r!==0){let i=$s.getComponent(e);nc.multiplyMatrices(n.bones[i].matrixWorld,n.boneInverses[i]),t.addScaledVector(tc.copy(Qs).applyMatrix4(nc),r)}}return t.isVector4&&(t.w=Qs.w),t.applyMatrix4(this.bindMatrixInverse)}},cc=class extends go{constructor(){super(),this.isBone=!0,this.type=`Bone`}},lc=class extends La{constructor(e=null,t=1,n=1,r,i,a,o,s,c=rr,l=rr,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},uc=new G,dc=new G,fc=class e{constructor(e=[],t=[]){this.uuid=Qi(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.previousBoneMatrices=null,this.boneTexture=null,this.init()}init(){let e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){z(`Skeleton: Number of inverse bone matrices does not match amount of bones.`),this.boneInverses=[];for(let e=0,t=this.bones.length;e<t;e++)this.boneInverses.push(new G)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let t=new G;this.bones[e]&&t.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(t)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){let t=this.bones[e];t&&t.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){let t=this.bones[e];t&&(t.parent&&t.parent.isBone?(t.matrix.copy(t.parent.matrixWorld).invert(),t.matrix.multiply(t.matrixWorld)):t.matrix.copy(t.matrixWorld),t.matrix.decompose(t.position,t.quaternion,t.scale))}}update(){let e=this.bones,t=this.boneInverses,n=this.boneMatrices,r=this.boneTexture;for(let r=0,i=e.length;r<i;r++){let i=e[r]?e[r].matrixWorld:dc;uc.multiplyMatrices(i,t[r]),uc.toArray(n,r*16)}r!==null&&(r.needsUpdate=!0)}clone(){return new e(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4);t.set(this.boneMatrices);let n=new lc(t,e,e,wr,hr);return n.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=n,this}getBoneByName(e){for(let t=0,n=this.bones.length;t<n;t++){let n=this.bones[t];if(n.name===e)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,r=e.bones.length;n<r;n++){let r=e.bones[n],i=t[r];i===void 0&&(z(`Skeleton: No bone found with UUID:`,r),i=new cc),this.bones.push(i),this.boneInverses.push(new G().fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){let e={metadata:{version:4.7,type:`Skeleton`,generator:`Skeleton.toJSON`},bones:[],boneInverses:[]};e.uuid=this.uuid;let t=this.bones,n=this.boneInverses;for(let r=0,i=t.length;r<i;r++){let i=t[r];e.bones.push(i.uuid);let a=n[r];e.boneInverses.push(a.toArray())}return e}},pc=class extends q{constructor(e,t,n,r=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},mc=new G,hc=new G,gc=[],_c=new Vo,vc=new G,yc=new Ys,bc=new gs,xc=class extends Ys{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new pc(new Float32Array(n*16),16),this.previousInstanceMatrix=null,this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let e=0;e<n;e++)this.setMatrixAt(e,vc)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Vo),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,mc),_c.copy(e.boundingBox).applyMatrix4(mc),this.boundingBox.union(_c)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new gs),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,mc),bc.copy(e.boundingSphere).applyMatrix4(mc),this.boundingSphere.union(bc)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.previousInstanceMatrix!==null&&(this.previousInstanceMatrix=e.previousInstanceMatrix.clone()),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){return this.instanceColor===null?t.setRGB(1,1,1):t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){return t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){let n=t.morphTargetInfluences,r=this.morphTexture.source.data.data,i=e*(n.length+1)+1;for(let e=0;e<n.length;e++)n[e]=r[i+e]}raycast(e,t){let n=this.matrixWorld,r=this.count;if(yc.geometry=this.geometry,yc.material=this.material,yc.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),bc.copy(this.boundingSphere),bc.applyMatrix4(n),e.ray.intersectsSphere(bc)!==!1))for(let i=0;i<r;i++){this.getMatrixAt(i,mc),hc.multiplyMatrices(n,mc),yc.matrixWorld=hc,yc.raycast(e,gc);for(let e=0,n=gc.length;e<n;e++){let n=gc[e];n.instanceId=i,n.object=this,t.push(n)}gc.length=0}}setColorAt(e,t){return this.instanceColor===null&&(this.instanceColor=new pc(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3),this}setMatrixAt(e,t){return t.toArray(this.instanceMatrix.array,e*16),this}setMorphAt(e,t){let n=t.morphTargetInfluences,r=n.length+1;this.morphTexture===null&&(this.morphTexture=new lc(new Float32Array(r*this.count),r,this.count,Dr,hr));let i=this.morphTexture.source.data.data,a=0;for(let e=0;e<n.length;e++)a+=n[e];let o=this.geometry.morphTargetsRelative?1:1-a,s=r*e;return i[s]=o,i.set(n,s+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:`dispose`}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}},Sc=new U,Cc=new U,wc=new W,Tc=class{constructor(e=new U(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=Sc.subVectors(n,t).cross(Cc.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(Sc),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||wc.getNormalMatrix(e),r=this.coplanarPoint(Sc).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Ec=new gs,Dc=new V(.5,.5),Oc=new U,kc=class{constructor(e=new Tc,t=new Tc,n=new Tc,r=new Tc,i=new Tc,a=new Tc){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Fi,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Ec.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Ec.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ec)}intersectsSprite(e){return Ec.center.set(0,0,0),Ec.radius=.7071067811865476+Dc.distanceTo(e.center),Ec.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ec)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(Oc.x=r.normal.x>0?e.max.x:e.min.x,Oc.y=r.normal.y>0?e.max.y:e.min.y,Oc.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Oc)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Ac=class extends Os{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new K(16777215),this.map=null,this.linewidth=1,this.linecap=`round`,this.linejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},jc=new U,Mc=new U,Nc=new G,Pc=new Is,Fc=new gs,Ic=new U,Lc=new U,Rc=class extends go{constructor(e=new J,t=new Ac){super(),this.isLine=!0,this.type=`Line`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let e=1,r=t.count;e<r;e++)jc.fromBufferAttribute(t,e-1),Mc.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=jc.distanceTo(Mc);e.setAttribute(`lineDistance`,new fs(n,1))}else z(`Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Line.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Fc.copy(n.boundingSphere),Fc.applyMatrix4(r),Fc.radius+=i,e.ray.intersectsSphere(Fc)===!1)return;Nc.copy(r).invert(),Pc.copy(e.ray).applyMatrix4(Nc);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=this.isLineSegments?2:1,l=n.index,u=n.attributes.position;if(l!==null){let n=Math.max(0,a.start),r=Math.min(l.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=l.getX(i),r=l.getX(i+1),a=zc(this,e,Pc,s,n,r,i);a&&t.push(a)}if(this.isLineLoop){let i=l.getX(r-1),a=l.getX(n),o=zc(this,e,Pc,s,i,a,r-1);o&&t.push(o)}}else{let n=Math.max(0,a.start),r=Math.min(u.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=zc(this,e,Pc,s,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){let i=zc(this,e,Pc,s,r-1,n,r-1);i&&t.push(i)}}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function zc(e,t,n,r,i,a,o){let s=e.geometry.attributes.position;if(jc.fromBufferAttribute(s,i),Mc.fromBufferAttribute(s,a),n.distanceSqToSegment(jc,Mc,Ic,Lc)>r)return;Ic.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(Ic);if(!(c<t.near||c>t.far))return{distance:c,point:Lc.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var Bc=new U,Vc=new U,Hc=class extends Rc{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type=`LineSegments`}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let e=0,r=t.count;e<r;e+=2)Bc.fromBufferAttribute(t,e),Vc.fromBufferAttribute(t,e+1),n[e]=e===0?0:n[e-1],n[e+1]=n[e]+Bc.distanceTo(Vc);e.setAttribute(`lineDistance`,new fs(n,1))}else z(`LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}},Uc=class extends Rc{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type=`LineLoop`}},Wc=class extends Os{constructor(e){super(),this.isPointsMaterial=!0,this.type=`PointsMaterial`,this.color=new K(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Gc=new G,Kc=new Is,qc=new gs,Jc=new U,Yc=class extends go{constructor(e=new J,t=new Wc){super(),this.isPoints=!0,this.type=`Points`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Points.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),qc.copy(n.boundingSphere),qc.applyMatrix4(r),qc.radius+=i,e.ray.intersectsSphere(qc)===!1)return;Gc.copy(r).invert(),Kc.copy(e.ray).applyMatrix4(Gc);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=n.index,l=n.attributes.position;if(c!==null){let n=Math.max(0,a.start),i=Math.min(c.count,a.start+a.count);for(let a=n,o=i;a<o;a++){let n=c.getX(a);Jc.fromBufferAttribute(l,n),Xc(Jc,n,s,r,e,t,this)}}else{let n=Math.max(0,a.start),i=Math.min(l.count,a.start+a.count);for(let a=n,o=i;a<o;a++)Jc.fromBufferAttribute(l,a),Xc(Jc,a,s,r,e,t,this)}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function Xc(e,t,n,r,i,a,o){let s=Kc.distanceSqToPoint(e);if(s<n){let n=new U;Kc.closestPointToPoint(e,n),n.applyMatrix4(r);let c=i.ray.origin.distanceTo(n);if(c<i.near||c>i.far)return;a.push({distance:c,distanceToRay:Math.sqrt(s),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}var Zc=class extends La{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},Qc=class extends La{constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isCanvasTexture=!0,this.needsUpdate=!0}},$c=class extends La{constructor(e,t,n=mr,r,i,a,o=rr,s=rr,c,l=Tr,u=1){if(l!==1026&&l!==1027)throw Error(`DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Na(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},el=class extends $c{constructor(e,t=mr,n=301,r,i,a=rr,o=rr,s,c=Tr){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},tl=class extends La{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},nl=class e extends J{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new fs(c,3)),this.setAttribute(`normal`,new fs(l,3)),this.setAttribute(`uv`,new fs(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new U;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}},rl=class e extends J{constructor(e=1,t=1,n=4,r=8,i=1){super(),this.type=`CapsuleGeometry`,this.parameters={radius:e,height:t,capSegments:n,radialSegments:r,heightSegments:i},t=Math.max(0,t),n=Math.max(1,Math.floor(n)),r=Math.max(3,Math.floor(r)),i=Math.max(1,Math.floor(i));let a=[],o=[],s=[],c=[],l=t/2,u=Math.PI/2*e,d=t,f=2*u+d,p=n*2+i,m=r+1,h=new U,g=new U;for(let _=0;_<=p;_++){let v=0,y=0,b=0,x=0;if(_<=n){let t=_/n,r=t*Math.PI/2;y=-l-e*Math.cos(r),b=e*Math.sin(r),x=-e*Math.cos(r),v=t*u}else if(_<=n+i){let r=(_-n)/i;y=-l+r*t,b=e,x=0,v=u+r*d}else{let t=(_-n-i)/n,r=t*Math.PI/2;y=l+e*Math.sin(r),b=e*Math.cos(r),x=e*Math.sin(r),v=u+d+t*u}let S=Math.max(0,Math.min(1,v/f)),C=0;_===0?C=.5/r:_===p&&(C=-.5/r);for(let e=0;e<=r;e++){let t=e/r,n=t*Math.PI*2,i=Math.sin(n),a=Math.cos(n);g.x=-b*a,g.y=y,g.z=b*i,o.push(g.x,g.y,g.z),h.set(-b*a,x,b*i),h.normalize(),s.push(h.x,h.y,h.z),c.push(t+C,S)}if(_>0){let e=(_-1)*m;for(let t=0;t<r;t++){let n=e+t,r=e+t+1,i=_*m+t,o=_*m+t+1;a.push(n,r,i),a.push(r,o,i)}}}this.setIndex(a),this.setAttribute(`position`,new fs(o,3)),this.setAttribute(`normal`,new fs(s,3)),this.setAttribute(`uv`,new fs(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radius,t.height,t.capSegments,t.radialSegments,t.heightSegments)}},il=class e extends J{constructor(e=1,t=1,n=1,r=32,i=1,a=!1,o=0,s=Math.PI*2){super(),this.type=`CylinderGeometry`,this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:r,heightSegments:i,openEnded:a,thetaStart:o,thetaLength:s};let c=this;r=Math.floor(r),i=Math.floor(i);let l=[],u=[],d=[],f=[],p=0,m=[],h=n/2,g=0;_(),a===!1&&(e>0&&v(!0),t>0&&v(!1)),this.setIndex(l),this.setAttribute(`position`,new fs(u,3)),this.setAttribute(`normal`,new fs(d,3)),this.setAttribute(`uv`,new fs(f,2));function _(){let a=new U,_=new U,v=0,y=(t-e)/n;for(let c=0;c<=i;c++){let l=[],g=c/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){let t=e/r,i=t*s+o,c=Math.sin(i),m=Math.cos(i);_.x=v*c,_.y=-g*n+h,_.z=v*m,u.push(_.x,_.y,_.z),a.set(c,y,m).normalize(),d.push(a.x,a.y,a.z),f.push(t,1-g),l.push(p++)}m.push(l)}for(let n=0;n<r;n++)for(let r=0;r<i;r++){let a=m[r][n],o=m[r+1][n],s=m[r+1][n+1],c=m[r][n+1];(e>0||r!==0)&&(l.push(a,o,c),v+=3),(t>0||r!==i-1)&&(l.push(o,s,c),v+=3)}c.addGroup(g,v,0),g+=v}function v(n){let i=p,a=new V,m=new U,_=0,v=n===!0?e:t,y=n===!0?1:-1;for(let e=1;e<=r;e++)u.push(0,h*y,0),d.push(0,y,0),f.push(.5,.5),p++;let b=p;for(let e=0;e<=r;e++){let t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=v*i,m.y=h*y,m.z=v*n,u.push(m.x,m.y,m.z),d.push(0,y,0),a.x=n*.5+.5,a.y=i*.5*y+.5,f.push(a.x,a.y),p++}for(let e=0;e<r;e++){let t=i+e,r=b+e;n===!0?l.push(r,r+1,t):l.push(r+1,r,t),_+=3}c.addGroup(g,_,n===!0?1:2),g+=_}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},al=class e extends il{constructor(e=1,t=1,n=32,r=1,i=!1,a=0,o=Math.PI*2){super(0,e,t,n,r,i,a,o),this.type=`ConeGeometry`,this.parameters={radius:e,height:t,radialSegments:n,heightSegments:r,openEnded:i,thetaStart:a,thetaLength:o}}static fromJSON(t){return new e(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},ol=class e extends J{constructor(e=[],t=[],n=1,r=0){super(),this.type=`PolyhedronGeometry`,this.parameters={vertices:e,indices:t,radius:n,detail:r};let i=[],a=[];o(r),c(n),l(),this.setAttribute(`position`,new fs(i,3)),this.setAttribute(`normal`,new fs(i.slice(),3)),this.setAttribute(`uv`,new fs(a,2)),r===0?this.computeVertexNormals():this.normalizeNormals();function o(e){let n=new U,r=new U,i=new U;for(let a=0;a<t.length;a+=3)f(t[a+0],n),f(t[a+1],r),f(t[a+2],i),s(n,r,i,e)}function s(e,t,n,r){let i=r+1,a=[];for(let r=0;r<=i;r++){a[r]=[];let o=e.clone().lerp(n,r/i),s=t.clone().lerp(n,r/i),c=i-r;for(let e=0;e<=c;e++)e===0&&r===i?a[r][e]=o:a[r][e]=o.clone().lerp(s,e/c)}for(let e=0;e<i;e++)for(let t=0;t<2*(i-e)-1;t++){let n=Math.floor(t/2);t%2==0?(d(a[e][n+1]),d(a[e+1][n]),d(a[e][n])):(d(a[e][n+1]),d(a[e+1][n+1]),d(a[e+1][n]))}}function c(e){let t=new U;for(let n=0;n<i.length;n+=3)t.x=i[n+0],t.y=i[n+1],t.z=i[n+2],t.normalize().multiplyScalar(e),i[n+0]=t.x,i[n+1]=t.y,i[n+2]=t.z}function l(){let e=new U;for(let t=0;t<i.length;t+=3){e.x=i[t+0],e.y=i[t+1],e.z=i[t+2];let n=h(e)/2/Math.PI+.5,r=g(e)/Math.PI+.5;a.push(n,1-r)}p(),u()}function u(){for(let e=0;e<a.length;e+=6){let t=a[e+0],n=a[e+2],r=a[e+4];Math.max(t,n,r)>.9&&Math.min(t,n,r)<.1&&(t<.2&&(a[e+0]+=1),n<.2&&(a[e+2]+=1),r<.2&&(a[e+4]+=1))}}function d(e){i.push(e.x,e.y,e.z)}function f(t,n){let r=t*3;n.x=e[r+0],n.y=e[r+1],n.z=e[r+2]}function p(){let e=new U,t=new U,n=new U,r=new U,o=new V,s=new V,c=new V;for(let l=0,u=0;l<i.length;l+=9,u+=6){e.set(i[l+0],i[l+1],i[l+2]),t.set(i[l+3],i[l+4],i[l+5]),n.set(i[l+6],i[l+7],i[l+8]),o.set(a[u+0],a[u+1]),s.set(a[u+2],a[u+3]),c.set(a[u+4],a[u+5]),r.copy(e).add(t).add(n).divideScalar(3);let d=h(r);m(o,u+0,e,d),m(s,u+2,t,d),m(c,u+4,n,d)}}function m(e,t,n,r){r<0&&e.x===1&&(a[t]=e.x-1),n.x===0&&n.z===0&&(a[t]=r/2/Math.PI+.5)}function h(e){return Math.atan2(e.z,-e.x)}function g(e){return Math.atan2(-e.y,Math.sqrt(e.x*e.x+e.z*e.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.vertices,t.indices,t.radius,t.detail)}},sl=class e extends ol{constructor(e=1,t=0){let n=(1+Math.sqrt(5))/2,r=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1];super(r,[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],e,t),this.type=`IcosahedronGeometry`,this.parameters={radius:e,detail:t}}static fromJSON(t){return new e(t.radius,t.detail)}},cl=class e extends J{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new fs(p,3)),this.setAttribute(`normal`,new fs(m,3)),this.setAttribute(`uv`,new fs(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}},ll=class e extends J{constructor(e=1,t=32,n=16,r=0,i=Math.PI*2,a=0,o=Math.PI){super(),this.type=`SphereGeometry`,this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:r,phiLength:i,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));let s=Math.min(a+o,Math.PI),c=0,l=[],u=new U,d=new U,f=[],p=[],m=[],h=[];for(let f=0;f<=n;f++){let g=[],_=f/n,v=0;f===0&&a===0?v=.5/t:f===n&&s===Math.PI&&(v=-.5/t);for(let n=0;n<=t;n++){let s=n/t;u.x=-e*Math.cos(r+s*i)*Math.sin(a+_*o),u.y=e*Math.cos(a+_*o),u.z=e*Math.sin(r+s*i)*Math.sin(a+_*o),p.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),h.push(s+v,1-_),g.push(c++)}l.push(g)}for(let e=0;e<n;e++)for(let r=0;r<t;r++){let t=l[e][r+1],i=l[e][r],o=l[e+1][r],c=l[e+1][r+1];(e!==0||a>0)&&f.push(t,i,c),(e!==n-1||s<Math.PI)&&f.push(i,o,c)}this.setIndex(f),this.setAttribute(`position`,new fs(p,3)),this.setAttribute(`normal`,new fs(m,3)),this.setAttribute(`uv`,new fs(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}};function ul(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(fl(i))i.isRenderTargetTexture?(z(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone();else if(Array.isArray(i))if(fl(i[0])){let e=[];for(let t=0,n=i.length;t<n;t++)e[t]=i[t].clone();t[n][r]=e}else t[n][r]=i.slice();else t[n][r]=i}}return t}function dl(e){let t={};for(let n=0;n<e.length;n++){let r=ul(e[n]);for(let e in r)t[e]=r[e]}return t}function fl(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function pl(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function ml(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:Da.workingColorSpace}var hl={clone:ul,merge:dl},gl=`void main() {
3
+ `)}\n${c}}`}function a(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return e.length===0?`[]`:`[${e.map(a).join(`, `)}]`;let t=Object.entries(e);return t.length===0?`{}`:`{ ${t.map(([e,t])=>`${JSON.stringify(e)}: ${a(t)}`).join(`, `)} }`}var o=class extends Error{needsToken=!0;constructor(e=`the asset library needs a Verse8 access token`){super(e),this.name=`LibraryAuthError`}};function s(e,t){let n=new Map;for(let r of e){let e=v(r);if(t.length>0&&!c(e,t))continue;let i=e[t.length];i!==void 0&&n.set(i,(n.get(i)??0)+1)}return[...n.entries()].map(([e,t])=>({tag:e,count:t})).sort((e,t)=>t.count-e.count||e.tag.localeCompare(t.tag))}function c(e,t){return t.every((t,n)=>e[n]===t)}function l(e){return e.length===0?`Everything`:e.join(` / `)}var u=[`.glb`,`.gltf`,`.vrm`,`.fbx`],d=[`.png`,`.jpg`,`.jpeg`,`.webp`,`.gif`,`.avif`,`.svg`,`.ktx2`,`.basis`],f=[`.mp3`,`.wav`,`.ogg`,`.m4a`,`.aac`,`.flac`];function p(e){let t=e.split(/[?#]/)[0]??``,n=t.lastIndexOf(`/`),r=n===-1?t:t.slice(n+1),i=r.lastIndexOf(`.`);return i<=0?``:r.slice(i).toLowerCase()}function m(e){let t=p(e);return u.includes(t)?`model`:d.includes(t)?`image`:f.includes(t)?`audio`:`any`}function h(e,t){if(t===`any`)return!0;let n=m(e);return n===t||n===`any`}function g(e){let t=e.metadata,n=(typeof t.originalName==`string`?t.originalName:void 0)??e.url.split(/[?#]/)[0]??``,r=n.slice(n.lastIndexOf(`/`)+1),i=p(r),a=i?r.slice(0,-i.length):r;return decodeURIComponent(a||e.id)}function _(e){return g(e).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function v(e){let t=e.metadata.tags;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function y(e){let t=e.metadata,n=[],r=p(e.url);r&&n.push([`format`,r.replace(`.`,``)]);let i=b(e);return i&&n.push([`pixels`,`${i[0]} × ${i[1]}`]),typeof t.size==`number`&&n.push([`bytes`,x(t.size)]),typeof t.type==`string`&&n.push([`kind`,t.type]),typeof t.style==`string`&&n.push([`style`,t.style]),typeof t.uploadedAt==`string`&&n.push([`added`,t.uploadedAt.slice(0,10)]),n}function b(e){let t=e.metadata,n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?e:null,r=[n(t.width),n(t.height)];if(r[0]&&r[1])return[r[0],r[1]];for(let e of[`size`,`dimensions`]){let r=t[e],i=n(r?.width),a=n(r?.height);if(i&&a)return[i,a]}return null}function x(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function S(e,t=`any`,n){let r=t===`any`?m(e.url):t,i=n??(r===`model`?`model`:r===`audio`?`audio`:`texture`),a={type:i,url:e.url};if(i===`spritesheet`){let t=T(e);t&&(a.frameWidth=t[0],a.frameHeight=t[1])}return a}function C(e){return p(e)===`.json`}function w(e){return e.replace(/\.json(\?.*)?$/,`.png$1`)}function T(e){let t=e.metadata,n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?e:null,r=n(t.frameWidth),i=n(t.frameHeight);if(r&&i)return[r,i];let a=t.frame,o=n(a?.width),s=n(a?.height);return o&&s?[o,s]:null}async function E(e){if(e.ok)return e;let t=await e.text(),n=t;try{n=JSON.parse(t).error??t}catch{}throw Error(n||`HTTP ${e.status}`)}async function D(){return await(await E(await fetch(`/api/meta`))).json()}async function O(){return await(await E(await fetch(`/api/scenes`))).json()}async function k(e){return await(await E(await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})}))).json()}function A(e){return e?`/api/scene?file=${encodeURIComponent(e)}`:`/api/scene`}async function ee(e){return await(await E(await fetch(A(e)))).json()}async function te(e,t){await E(await fetch(A(t),{method:`PUT`,body:r(e)}))}async function ne(e,t){let n=new URLSearchParams({tags:e.tags.join(`,`),page:String(e.page??1),limit:String(e.limit??24)});e.keyword?.trim()&&n.set(`keyword`,e.keyword.trim());let r=await fetch(`/api/library?${n}`,{headers:t?{"x-incanto-v8-token":t}:{}});if(r.status===401)throw new o((await r.json().catch(()=>({}))).error);return await(await E(r)).json()}var re={meta:D,loadScene:ee,saveScene:te,scenes:O,createScene:k,library:ne},j=class{connections=[];connect(e,t){return this.connections.some(t=>t.fn===e)||this.connections.push({fn:e,once:t?.once??!1}),()=>this.disconnect(e)}disconnect(e){let t=this.connections.findIndex(t=>t.fn===e);t!==-1&&this.connections.splice(t,1)}disconnectAll(){this.connections.length=0}emit(...e){let t=[...this.connections];for(let n of t)this.connections.includes(n)&&(n.once&&this.disconnect(n.fn),n.fn(...e))}get connectionCount(){return this.connections.length}},ie=class{changed=new j;_master=1;_sfx=1;_music=1;_muted=!1;get master(){return this._master}set master(e){this.assign(`_master`,e)}get sfx(){return this._sfx}set sfx(e){this.assign(`_sfx`,e)}get music(){return this._music}set music(e){this.assign(`_music`,e)}get muted(){return this._muted}set muted(e){e!==this._muted&&(this._muted=e,this.changed.emit())}effectiveVolume(e,t){if(this._muted)return 0;let n=e===`music`?this._music:this._sfx;return this._master*n*ae(t)}assign(e,t){if(!Number.isFinite(t))return;let n=ae(t);n!==this[e]&&(this[e]=n,this.changed.emit())}};function ae(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}function M(e,t,n){let r=se(e,t);return n===`in`?r:1-r}function oe(e,t){let n=se(e,t)*Math.PI/2;return{out:ce(Math.cos(n)),in:ce(Math.sin(n))}}function se(e,t){return!Number.isFinite(e)||t<=0?1:ce(e/t)}function ce(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}var le=null,ue=null;function de(){let e=globalThis;return e.AudioContext??e.webkitAudioContext??null}function fe(){if(le)return le();let e=de();return e?new e:null}function pe(){return ue?ue():typeof Audio>`u`?null:new Audio}var me={src:``,setGain(){},setLoop(){},play(){},stop(){}},he=class{src;el;gainNode;constructor(e,t,n){this.src=e,this.el=t;try{t.crossOrigin=`anonymous`}catch{}t.src=e;let r=n.createMediaElementSource(t);this.gainNode=n.createGain(),r.connect(this.gainNode),this.gainNode.connect(n.destination)}setGain(e){this.gainNode.gain.value=e}setLoop(e){this.el.loop=e}play(){this.el.play().catch(()=>{})}stop(){this.el.pause(),this.el.currentTime=0}},ge=class{ctx=null;resolved=!1;get available(){return this.ensure()!==null}ensure(){return this.resolved||=(this.ctx=fe(),!0),this.ctx}createTrack(e){let t=this.ensure(),n=pe();return!t||!n?{...me,src:e}:(t.state===`suspended`&&t.resume(),new he(e,n,t))}unlock(){let e=this.ensure();e&&e.state===`suspended`&&e.resume()}},_e=null,ve=class{buses;backend=null;resolved=!1;active=null;outgoing=null;_bus=`music`;_volume=1;constructor(e){this.buses=e}get current(){return this.active?.track.src??null}get volume(){return this._volume}ensure(){if(!this.resolved){let e=_e?_e(this.buses):new ge;this.backend=e&&e.available===!1?null:e,this.resolved=!0}return this.backend}unlock(){this.ensure()?.unlock(),this.active?.track.play()}play(e,t={}){let n=this.ensure();if(!n)return;this.killOutgoing(),this.active?.track.stop(),this._bus=t.bus??`music`;let r=n.createTrack(e);r.setLoop(t.loop??!0);let i=Math.max(0,t.fadeIn??0);this.active={track:r,phase:i>0?`fadeIn`:`steady`,t:0,duration:i,freeOnEnd:!1},r.setGain(i>0?0:this.busGain()),r.play()}crossfadeTo(e,t=2){let n=this.ensure();if(!n||this.active&&this.active.track.src===e&&this.active.phase!==`fadeOut`)return;let r=Math.max(0,t);if(!this.active){this.play(e,{fadeIn:r});return}this.killOutgoing(),this.outgoing={...this.active,phase:`crossOut`,t:0,duration:r,freeOnEnd:!0};let i=n.createTrack(e);i.setLoop(!0),i.setGain(0),i.play(),this.active={track:i,phase:`crossIn`,t:0,duration:r,freeOnEnd:!1},this.applyGains()}stop(e=0){this.killOutgoing();let t=this.active;if(this.active=null,!t)return;let n=Math.max(0,e);if(n<=0){t.track.stop();return}this.outgoing={...t,phase:`fadeOut`,t:0,duration:n,freeOnEnd:!0},this.applyGains()}setVolume(e){this._volume=ye(e)}tick(e){this.active&&(this.active.phase===`fadeIn`||this.active.phase===`crossIn`)&&(this.active.t+=e,this.active.t>=this.active.duration&&(this.active.phase=`steady`)),this.outgoing&&(this.outgoing.t+=e,this.outgoing.t>=this.outgoing.duration&&(this.outgoing.track.setGain(0),this.outgoing.track.stop(),this.outgoing=null)),this.applyGains()}busGain(){return this.buses.effectiveVolume(this._bus,this._volume)}applyGains(){let e=this.busGain();if(this.active?.phase===`crossIn`&&this.outgoing?.phase===`crossOut`){let t=oe(this.active.t,this.active.duration);this.active.track.setGain(e*t.in),this.outgoing.track.setGain(e*t.out);return}if(this.active){let t=this.active.phase===`fadeIn`?M(this.active.t,this.active.duration,`in`):1;this.active.track.setGain(e*t)}if(this.outgoing){let t=this.outgoing.phase===`fadeOut`||this.outgoing.phase===`crossOut`?M(this.outgoing.t,this.outgoing.duration,`out`):0;this.outgoing.track.setGain(e*t)}}killOutgoing(){this.outgoing?.track.stop(),this.outgoing=null}};function ye(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}var N=class extends Error{code;details;constructor(e,t,n={}){super(t),this.name=`IncantoError`,this.code=e,this.details=n}},P=class{state;constructor(e){this.state=e>>>0,this.state===0&&(this.state=2654435769)}next(){this.state=this.state+1831565813>>>0;let e=this.state;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}range(e,t){return e+this.next()*(t-e)}int(e,t){return Math.floor(this.range(e,t+1))}pick(e){if(e.length===0)throw new N(`BAD_FORMAT`,`Rng.pick needs a non-empty array.`);return e[this.int(0,e.length-1)]}},F={coin:{wave:`square`,baseFreq:988,freqRamp:1800,attack:0,sustain:.04,decay:.18,duty:.5,volume:.4},pickup:{wave:`sine`,baseFreq:660,freqRamp:900,attack:.005,sustain:.05,decay:.12,volume:.45},jump:{wave:`square`,baseFreq:320,freqRamp:600,attack:0,sustain:.03,decay:.12,duty:.35,volume:.4},hurt:{wave:`sawtooth`,baseFreq:380,freqRamp:-520,attack:0,sustain:.05,decay:.16,volume:.5},hit:{wave:`noise`,baseFreq:600,freqRamp:-400,attack:0,sustain:.02,decay:.1,volume:.55},explosion:{wave:`noise`,baseFreq:420,freqRamp:-360,attack:0,sustain:.12,decay:.5,volume:.6},powerup:{wave:`square`,baseFreq:440,freqRamp:1200,attack:.01,sustain:.18,decay:.22,duty:.5,vibratoDepth:.08,vibratoRate:18,volume:.4},laser:{wave:`sawtooth`,baseFreq:1400,freqRamp:-2600,attack:0,sustain:.03,decay:.14,volume:.4},shoot:{wave:`square`,baseFreq:900,freqRamp:-1400,attack:0,sustain:.02,decay:.1,duty:.25,volume:.45},blip:{wave:`square`,baseFreq:760,freqRamp:0,attack:0,sustain:.015,decay:.04,duty:.5,volume:.35},select:{wave:`triangle`,baseFreq:520,freqRamp:420,attack:.002,sustain:.04,decay:.08,volume:.4},step:{wave:`noise`,baseFreq:220,freqRamp:-120,attack:0,sustain:.01,decay:.05,volume:.3},win:{wave:`square`,baseFreq:523,freqRamp:900,attack:.01,sustain:.35,decay:.3,duty:.5,vibratoDepth:.05,vibratoRate:10,volume:.42},lose:{wave:`sawtooth`,baseFreq:392,freqRamp:-300,attack:.01,sustain:.3,decay:.4,volume:.45}},be=Object.keys(F),xe=Math.PI*2;function Se(e,t={}){let n=t.sampleRate??44100,r=t.pitch??1,i=new P((t.seed??0)^42405),a=e.attack+e.sustain+e.decay,o=Math.max(1,Math.ceil(a*n)),s=new Float32Array(o),c=e.duty??.5,l=e.vibratoDepth??0,u=e.vibratoRate??0,d=0,f=i.range(-1,1),p=0;for(let t=0;t<o;t++){let a=t/n,o;if(a<e.attack)o=e.attack>0?a/e.attack:1;else if(a<e.attack+e.sustain)o=1;else{let t=a-e.attack-e.sustain;o=e.decay>0?Math.max(0,1-t/e.decay):0}let m=(e.baseFreq+e.freqRamp*a)*r;l>0&&u>0&&(m+=m*l*Math.sin(xe*u*a)),m=Math.max(0,m),d+=m/n,d-=Math.floor(d);let h;switch(e.wave){case`square`:h=d<c?1:-1;break;case`sawtooth`:h=2*d-1;break;case`triangle`:h=4*Math.abs(d-.5)-1;break;case`sine`:h=Math.sin(xe*d);break;default:p-=m/n,p<=0&&(f=i.range(-1,1),p+=1),h=f;break}s[t]=I(h*o*e.volume)}return s}function I(e){return e<-1?-1:e>1?1:e}var Ce=[`inverse`,`linear`,`exponential`];function L(e,t){let n=Math.max(0,t.refDistance),r=Math.max(n,t.maxDistance),i=t.rolloffFactor??1;if(!Number.isFinite(e))return 1;let a=we(e,n,r);if(a<=n)return 1;let o;switch(t.rolloff){case`linear`:{let e=r-n;o=e<=0?1:1-i*(a-n)/e;break}case`exponential`:o=n<=0?1:(a/n)**-i;break;default:o=n/(n+i*(a-n));break}return Number.isFinite(o)?Te(o):0}function we(e,t,n){return e<t?t:e>n?n:e}function Te(e){return e<0?0:e>1?1:e}var Ee={engine:{oscillators:[[`sawtooth`,55,0],[`sawtooth`,55,12]],noise:null,lowpassHz:900},wind:{oscillators:[],noise:[700,.6,1],lowpassHz:4e3},hum:{oscillators:[[`sine`,110,0],[`triangle`,110,5]],noise:null,lowpassHz:1200},noise:{oscillators:[],noise:[1200,.3,1],lowpassHz:6e3}},De={set:()=>{},stop:()=>{},stopped:!0};function Oe(e,t,n){let r=Ee[t]??Ee.hum,i=e.createGain();i.gain.value=0,i.connect(e.destination);let a=n,o=e.createBiquadFilter();o.type=`lowpass`,o.frequency.value=r.lowpassHz,o.connect(i);let s=[];for(let[t,n,i]of r.oscillators){let r=e.createOscillator();r.type=t,r.frequency.value=n,r.detune.value=i,r.connect(o),r.start(),s.push(r)}let c=null,l=null;if(r.noise){let[t,n,i]=r.noise,a=e.createBuffer(1,e.sampleRate*2,e.sampleRate),s=a.getChannelData(0),u=987654321;for(let e=0;e<s.length;e++)u=u*1664525+1013904223>>>0,s[e]=u/4294967295*2-1;c=e.createBufferSource(),c.buffer=a,c.loop=!0,l=e.createBiquadFilter(),l.type=`bandpass`,l.frequency.value=t,l.Q.value=n;let d=e.createGain();d.gain.value=i,c.connect(l),l.connect(d),d.connect(o),c.start()}let u=r.oscillators.map(([,e])=>e),d=r.noise?.[0]??0,f=!1,p=()=>e.currentTime;return i.gain.setTargetAtTime(.4*a,p(),.05),{get stopped(){return f},set({pitch:e,volume:t}){if(!f){if(e!==void 0){let t=Math.max(.05,e);s.forEach((e,n)=>{e.frequency.setTargetAtTime(u[n]*t,p(),.03)}),l&&l.frequency.setTargetAtTime(d*t,p(),.03)}t!==void 0&&i.gain.setTargetAtTime(Math.max(0,Math.min(1,t))*a,p(),.04)}},stop(e=.15){f||(f=!0,i.gain.setTargetAtTime(0,p(),Math.max(.01,e/3)),setTimeout(()=>{for(let e of s)e.stop();c?.stop(),i.disconnect()},e*1e3+120))}}}var ke=De;function Ae(e,t){let[n,r,i]=t.position,[a,o,s]=t.forward,[c,l,u]=t.up,d=e;d.positionX&&d.forwardX&&d.upX?(d.positionX.value=n,d.positionY&&(d.positionY.value=r),d.positionZ&&(d.positionZ.value=i),d.forwardX.value=a,d.forwardY&&(d.forwardY.value=o),d.forwardZ&&(d.forwardZ.value=s),d.upX.value=c,d.upY&&(d.upY.value=l),d.upZ&&(d.upZ.value=u)):(d.setPosition?.(n,r,i),d.setOrientation?.(a,o,s,c,l,u))}function je(e,t){let n=e;n.positionX?(n.positionX.value=t[0],n.positionY&&(n.positionY.value=t[1]),n.positionZ&&(n.positionZ.value=t[2])):n.setPosition?.(t[0],t[1],t[2])}var Me=null;function Ne(){let e=globalThis;return e.AudioContext??e.webkitAudioContext??null}function Pe(){if(Me)return Me();let e=Ne();return e?new e:null}function Fe(e,t,n){return`${e.wave}|${e.baseFreq}|${e.freqRamp}|${e.attack}|${e.sustain}|${e.decay}|${e.duty}|${e.vibratoDepth}|${e.vibratoRate}|${e.volume}|${t.pitch??1}|${t.seed??0}|${n}`}var Ie=class{ctx=null;resolved=!1;pcmCache=new Map;get available(){return this.ensure()!==null}ensure(){return this.resolved||=(this.ctx=Pe(),!0),this.ctx}startVoice(e,t=1){let n=this.ensure();return n?(n.state===`suspended`&&n.resume(),Oe(n,e,t)):ke}unlock(){let e=this.ensure();e&&e.state===`suspended`&&e.resume()}play(e,t,n={}){let r=this.ensure();if(!r||(r.state===`suspended`&&r.resume(),t<=0))return;let i=r.sampleRate||44100,a={sampleRate:i,pitch:n.pitch,seed:n.seed},o=Fe(e,a,i),s=this.pcmCache.get(o);s||(s=Se(e,a),this.pcmCache.set(o,s));let c=r.createBuffer(1,s.length,i);c.getChannelData(0).set(s);let l=r.createGain();if(l.gain.value=t,n.spatial&&typeof r.createPanner==`function`){let e=n.spatial,t=r.createPanner();t.panningModel=`HRTF`,t.distanceModel=e.rolloff,t.refDistance=Math.max(0,e.refDistance),t.maxDistance=Math.max(e.refDistance,e.maxDistance),t.rolloffFactor=e.rolloffFactor??1,je(t,e.position),r.listener&&Ae(r.listener,e.listener),l.connect(t),t.connect(r.destination)}else l.connect(r.destination);let u=r.createBufferSource();u.buffer=c,u.connect(l),u.start()}};function Le(e){return e.startsWith(`@t:`)?e.slice(3):null}function Re(e,t){return t?e.replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e):e}var ze=class{changed=new j;tables={};current=`en`;constructor(e,t){e&&this.load(e),t&&(this.locale=t)}load(e){for(let[t,n]of Object.entries(e)){this.tables[t]??={};let e=this.tables[t];for(let[t,r]of Object.entries(n))typeof r==`string`&&(e[t]=r)}}get locale(){return this.current}set locale(e){e===this.current||e===``||(this.current=e,this.changed.emit(e))}available(){let e=new Set([`en`]);for(let[t,n]of Object.entries(this.tables))Object.keys(n).length>0&&e.add(t);return[...e]}t(e,t){let n=this.tables[this.current]?.[e];if(n!==void 0)return Re(n,t);let r=this.tables.en?.[e];return r===void 0?e:Re(r,t)}resolve(e,t){let n=Le(e);return n===null?e:this.t(n,t)}has(e){for(let t of Object.values(this.tables))if(t[e]!==void 0)return!0;return!1}};function Be(e){if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=typeof e;return t===`string`||t===`number`||t===`boolean`?t:`object`}function Ve(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>Ve(e,t[n]));if(e!==null&&t!==null&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)||Array.isArray(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>n in t&&Ve(e[n],t[n]))}return!1}function He(e){return typeof e!=`object`||!e?e:JSON.parse(JSON.stringify(e))}function Ue(e,t,n,r){if(r&&typeof e==`string`&&!r.includes(e))throw new N(`PROP_TYPE_MISMATCH`,`Prop '${n}' is ${JSON.stringify(e)}, which is not one of: ${r.map(e=>JSON.stringify(e)).join(`, `)}.`,{prop:n,validOptions:[...r]});let i=Be(t);if(i===`null`)return;let a=Be(e);if(a!==i)throw new N(`PROP_TYPE_MISMATCH`,`Prop '${n}' expects ${i} (default ${JSON.stringify(t)}), got ${a} (${JSON.stringify(e)}).`,{prop:n});if(typeof e==`number`&&!Number.isFinite(e))throw new N(`PROP_TYPE_MISMATCH`,`Prop '${n}' is ${e} — props must be finite numbers.`,{prop:n});if(Array.isArray(t)&&Array.isArray(e)&&t.length>0){if(e.length!==t.length)throw new N(`PROP_TYPE_MISMATCH`,`Prop '${n}' expects an array of length ${t.length} (default ${JSON.stringify(t)}), got length ${e.length}.`,{prop:n});for(let r=0;r<t.length;r++)Ue(e[r],t[r],`${n}[${r}]`)}}var We=new Map;function R(e,t){let n=We.get(e.typeName);if(n&&n!==e&&!t?.replace)throw new N(`DUPLICATE_NODE_TYPE`,`Node type '${e.typeName}' is already registered by a different class. Replacing an implementation (e.g. under hot reload) needs registerNode(ctor, { replace: true }).`,{nodeType:e.typeName});We.set(e.typeName,e)}function Ge(e){let t=We.get(e);if(!t){let t=[...We.keys()];throw new N(`UNKNOWN_NODE_TYPE`,`Unknown node type '${e}'. Registered types: [${t.join(`, `)}].`,{nodeType:e,validOptions:t})}return t}function Ke(){return[...We.keys()]}function qe(e){return Xe(Ge(e))}function Je(e){let t=[],n=e;for(;n;){Object.hasOwn(n,`signals`)&&n.signals&&t.unshift(...n.signals);let e=Object.getPrototypeOf(n);n=typeof e==`function`?e:null}return[...new Set(t)]}function Ye(e){return Je(Ge(e))}function Xe(e){let t=[],n=e;for(;n;){Object.hasOwn(n,`props`)&&n.props&&t.unshift(n.props);let e=Object.getPrototypeOf(n);n=typeof e==`function`?e:null}return Object.assign({},...t)}function Ze(e){let t=[],n=e;for(;n;){Object.hasOwn(n,`propAliases`)&&n.propAliases&&t.unshift(n.propAliases);let e=Object.getPrototypeOf(n);n=typeof e==`function`?e:null}return Object.assign({},...t)}function Qe(e,t,n,r,i={},a={}){for(let[n,r]of Object.entries(t))e[n]=He(r.default);if(n)for(let[o,s]of Object.entries(n)){let n=t[o]?o:i[o]??o,c=t[n];if(!c){let e=Object.keys(t);throw new N(`UNKNOWN_PROP`,`Unknown prop '${o}' on '${r}'. Valid props: [${e.join(`, `)}].`,{prop:o,nodeType:r,validOptions:e})}let l=a[n],u=c.options&&l&&l.length>0?[...c.options,...l]:c.options;Ue(s,c.default,`${r}.${n}`,u),e[n]=He(s)}}function $e(e,t,n){let r=Ge(e),i=new r;return Qe(i,qe(e),t,e,Ze(r),n),i}var et=class{static props;static signals;node;get engine(){let e=this.node?.tree?.engine;if(!e)throw new N(`TREE_VIOLATION`,`Behavior on '${this.node?.name??`?`}' is not attached to a running engine (node must be in a scene set on an Engine).`);return e}get input(){return this.engine.input}get rng(){return this.engine.rng}get log(){return this.engine.log}getNode(e){return this.node.getNode(e)}emit(e,...t){this.node.emit(e,...t)}on(e,t,n){return this.node.on(e,t,n)}},tt=class extends et{},nt=new Map;function rt(e){return nt.has(e)}function it(e,t,n){let r=nt.get(e);if(r&&r!==t&&!n?.replace)throw new N(`DUPLICATE_BEHAVIOR`,`Behavior '${e}' is already registered by a different class. Replacing an implementation (e.g. under hot reload) needs registerBehavior(name, ctor, { replace: true }).`);nt.set(e,t)}function at(e){let t=nt.get(e);if(!t){let t=[...nt.keys()];throw new N(`UNKNOWN_BEHAVIOR`,`Unknown behavior '${e}'. Registered behaviors: [${t.join(`, `)}]. Did you forget registerBehavior('${e}', ${e})?`,{validOptions:t})}return t}function ot(e){let t=nt.get(e);return t?Xe(t):{}}function st(e){let t=nt.get(e);return t?Je(t):[]}function ct(e,t){let n=at(e),r=new n;return Qe(r,Xe(n),t,`script:${e}`),r}function lt(e,t,...n){e?.log[t](...n),t===`error`?console.error(...n):t===`warn`?console.warn(...n):console.info(...n)}var ut=class{capacity;times;head=0;count=0;constructor(e=60){this.capacity=e,this.times=Array(e)}push(e){this.times[(this.head+this.count)%this.capacity]=e,this.count<this.capacity?this.count+=1:this.head=(this.head+1)%this.capacity}fps(){let e=this.spanMs();return e>0?(this.count-1)/e*1e3:0}frameMs(){let e=this.spanMs();return e>0?e/(this.count-1):0}clear(){this.head=0,this.count=0}spanMs(){if(this.count<2)return 0;let e=this.times[this.head];return this.times[(this.head+this.count-1)%this.capacity]-e}};function dt(e){let t=e;return!!t&&(t.isContentEditable===!0||t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`)}var ft=class{actions=new Map;down=new Set;pressedEdge=new Set;releasedEdge=new Set;detach=null;declare(e){for(let[t,n]of pt(e))this.actions.set(t,n)}pointerPosition(){return this.pointerPos?{...this.pointerPos}:null}setPointerPosition(e,t,n){let r=n?.getBoundingClientRect?.();if(!r||r.width===0||r.height===0){this.pointerPos={x:e,y:t};return}let i=n,a=typeof i.width==`number`&&i.width>0?i.width/r.width:1,o=typeof i.height==`number`&&i.height>0?i.height/r.height:1;this.pointerPos={x:(e-r.left)*a,y:(t-r.top)*o}}pointerPos=null;handleKey(e,t){t?this.down.has(e)||(this.down.add(e),this.pressedEdge.add(e)):this.down.has(e)&&(this.down.delete(e),this.releasedEdge.add(e))}injectedDown=new Set;injectedPressed=new Set;injectedReleased=new Set;injectedVectors=new Map;declaredActions(){let e=[];for(let[t,n]of this.actions)e.push({name:t,type:n.type});return e}pressAction(e){this.button(e),this.injectedDown.has(e)||(this.injectedDown.add(e),this.injectedPressed.add(e))}releaseAction(e){this.button(e),this.injectedDown.delete(e)&&this.injectedReleased.add(e)}setActionVector(e,t,n){if(this.get(e).type!==`vector2`)throw new N(`BAD_FORMAT`,`Input action '${e}' is a button — use pressAction/releaseAction, not setActionVector.`);if(!Number.isFinite(t)||!Number.isFinite(n))throw new N(`BAD_FORMAT`,`setActionVector('${e}') needs finite numbers, got (${t}, ${n}).`);t===0&&n===0?this.injectedVectors.delete(e):this.injectedVectors.set(e,{x:t,y:n})}touchControls(){let e=[];for(let[t,n]of this.actions)n.touch&&e.push({action:t,kind:n.touch});return e}clearInjected(){this.injectedDown.clear(),this.injectedPressed.clear(),this.injectedReleased.clear(),this.injectedVectors.clear()}dx=0;dy=0;wheel=0;handleMouseButton(e,t){this.handleKey(`Mouse${e}`,t)}handlePointerMove(e,t){this.dx+=e,this.dy+=t}handleWheel(e){this.wheel+=e}pointerDelta(){let e={x:this.dx,y:this.dy};return this.dx=0,this.dy=0,e}wheelDelta(){let e=this.wheel;return this.wheel=0,e}padAxesState={lx:0,ly:0,rx:0,ry:0};padButtonsDown=0;pollGamepad(e){let t=e=>Math.abs(e)<.15?0:e;if(!e){for(let e=0;e<17;e++)this.padButtonsDown&1<<e&&this.handleKey(`Pad${e}`,!1);this.padButtonsDown=0,this.padAxesState.lx=0,this.padAxesState.ly=0,this.padAxesState.rx=0,this.padAxesState.ry=0;return}for(let t=0;t<Math.min(17,e.buttons.length);t++){let n=e.buttons[t]?.pressed===!0;n!==((this.padButtonsDown&1<<t)!=0)&&(this.handleKey(`Pad${t}`,n),this.padButtonsDown=n?this.padButtonsDown|1<<t:this.padButtonsDown&~(1<<t))}this.padAxesState.lx=t(e.axes[0]??0),this.padAxesState.ly=t(e.axes[1]??0),this.padAxesState.rx=t(e.axes[2]??0),this.padAxesState.ry=t(e.axes[3]??0)}padAxes(e=0){return e===0?{x:this.padAxesState.lx,y:this.padAxesState.ly}:{x:this.padAxesState.rx,y:this.padAxesState.ry}}attachGamepad(e){if(typeof navigator>`u`||typeof navigator.getGamepads!=`function`)return()=>{};let t=e.updated.connect(()=>{let e=navigator.getGamepads(),t=null;for(let n of e)if(n?.connected){t=n;break}this.pollGamepad(t)}),n=this.detach;return this.detach=()=>{n?.(),t()},t}attachPointer(e,t){let n=0,r=r=>{n++,this.setPointerPosition(r.clientX,r.clientY,e),this.handleMouseButton(r.button,!0),t?.lockOnClick&&document.pointerLockElement!==e&&e.requestPointerLock?.()},i=e=>{n=Math.max(0,n-1),this.handleMouseButton(e.button,!1)},a=t=>{this.setPointerPosition(t.clientX,t.clientY,e),(document.pointerLockElement===e||n>0)&&this.handlePointerMove(t.movementX,t.movementY)},o=e=>{e.preventDefault(),this.handleWheel(e.deltaY)},s=e=>e.preventDefault();e.addEventListener(`mousedown`,r),window.addEventListener(`mouseup`,i),window.addEventListener(`mousemove`,a),e.addEventListener(`wheel`,o,{passive:!1}),e.addEventListener(`contextmenu`,s);let c=()=>{e.removeEventListener(`mousedown`,r),window.removeEventListener(`mouseup`,i),window.removeEventListener(`mousemove`,a),e.removeEventListener(`wheel`,o),e.removeEventListener(`contextmenu`,s)},l=this.detach;return this.detach=()=>{l?.(),c()},c}attachKeyboard(e,t){let n=t?.preventDefault??`bound`,r=e=>{dt(e.target)||(e.ctrlKey||e.metaKey)&&!e.code.startsWith(`Control`)&&!e.code.startsWith(`Meta`)||(n===`bound`&&this.codeIsBound(e.code)&&e.preventDefault?.(),e.repeat||this.handleKey(e.code,!0))},i=e=>{dt(e.target)||this.handleKey(e.code,!1)};e.addEventListener(`keydown`,r),e.addEventListener(`keyup`,i);let a=()=>{e.removeEventListener(`keydown`,r),e.removeEventListener(`keyup`,i)},o=this.detach;return this.detach=()=>{o?.(),a()},a}codeIsBound(e){for(let t of this.actions.values())if(t.type===`button`){if(t.keys.includes(e))return!0}else{let n=t.keys;if(n.up.includes(e)||n.down.includes(e)||n.left.includes(e)||n.right.includes(e))return!0}return!1}dispose(){this.detach?.(),this.detach=null}isPressed(e){return this.button(e).keys.some(e=>this.down.has(e))||this.injectedDown.has(e)}justPressed(e){return this.button(e).keys.some(e=>this.pressedEdge.has(e))||this.injectedPressed.has(e)}justReleased(e){return this.button(e).keys.some(e=>this.releasedEdge.has(e))||this.injectedReleased.has(e)}keyPressed(e){return this.down.has(e)}keyJustPressed(e){return this.pressedEdge.has(e)}mousePressed(e=0){return this.down.has(`Mouse${e}`)}mouseJustPressed(e=0){return this.pressedEdge.has(`Mouse${e}`)}mouseJustReleased(e=0){return this.releasedEdge.has(`Mouse${e}`)}getVector(e){let t=this.get(e);if(t.type!==`vector2`)throw new N(`BAD_FORMAT`,`Input action '${e}' is a button — use isPressed/justPressed, not getVector.`);let n=e=>+!!e.some(e=>this.down.has(e)),r=n(t.keys.right)-n(t.keys.left),i=n(t.keys.down)-n(t.keys.up),a=this.injectedVectors.get(e);a&&(r+=a.x,i+=a.y);let o=Math.hypot(r,i);return o>1&&(r/=o,i/=o),{x:r,y:i}}endFrame(){this.pressedEdge.clear(),this.releasedEdge.clear(),this.injectedPressed.clear(),this.injectedReleased.clear()}clear(){this.actions.clear(),this.pressedEdge.clear(),this.releasedEdge.clear(),this.clearInjected()}get(e){let t=this.actions.get(e);if(!t)throw new N(`BAD_FORMAT`,`Unknown input action '${e}'. Declared actions: [${[...this.actions.keys()].join(`, `)}].`);return t}button(e){let t=this.get(e);if(t.type!==`button`)throw new N(`BAD_FORMAT`,`Input action '${e}' is a vector2 — use getVector, not button queries.`);return t}};function pt(e){let t=new Map;for(let[n,r]of Object.entries(e)){let e=r;if(e.type===`button`){let r=e.keys;if(!Array.isArray(r)||r.some(e=>typeof e!=`string`))throw new N(`BAD_FORMAT`,`Input action '${n}': button "keys" must be an array of KeyboardEvent.code strings.`);if(e.touch!==void 0&&e.touch!==`button`)throw new N(`BAD_FORMAT`,`Input action '${n}': button "touch" must be 'button', got ${JSON.stringify(e.touch)}.`);t.set(n,{type:`button`,keys:[...r],...e.touch===`button`?{touch:`button`}:{}})}else if(e.type===`vector2`){let r=e.keys;for(let e of[`up`,`down`,`left`,`right`])if(!Array.isArray(r?.[e]))throw new N(`BAD_FORMAT`,`Input action '${n}': vector2 "keys" needs arrays for up/down/left/right.`);if(e.touch!==void 0&&e.touch!==`joystick`)throw new N(`BAD_FORMAT`,`Input action '${n}': vector2 "touch" must be 'joystick', got ${JSON.stringify(e.touch)}.`);let i=r;t.set(n,{type:`vector2`,keys:{up:[...i.up],down:[...i.down],left:[...i.left],right:[...i.right]},...e.touch===`joystick`?{touch:`joystick`}:{}})}else throw new N(`BAD_FORMAT`,`Input action '${n}': "type" must be 'button' or 'vector2', got ${JSON.stringify(e.type)}.`)}return t}var mt=class{added=new j;buffer=[];capacity;seq=0;constructor(e=1e3){this.capacity=e}debug(...e){this.push(`debug`,e)}info(...e){this.push(`info`,e)}warn(...e){this.push(`warn`,e)}error(...e){this.push(`error`,e)}entries(){return this.buffer}clear(){this.buffer.length=0}push(e,t){this.seq+=1;let n={seq:this.seq,timeMs:globalThis.performance?.now()??0,level:e,parts:t};this.buffer.push(n),this.buffer.length>this.capacity&&this.buffer.splice(0,this.buffer.length-this.capacity),this.added.emit(n)}},ht={background:-2e3,terrain:-1e3,default:0,characters:1e3,effects:2e3,overlay:3e3};function gt(e){return e?{...ht,...e}:ht}function _t(e,t,n=ht){return(n[e]??0)+t}var vt=new Map;function yt(e){let t=`incanto:${e}:`,n=xt();if(!n){let t=vt.get(e);t||(t=new Map,vt.set(e,t));let n=t;return{get:(e,t)=>bt(n.get(e),t),set:(e,t)=>void n.set(e,JSON.stringify(t)),remove:e=>void n.delete(e),clear:()=>n.clear()}}return{get:(e,r)=>bt(n.getItem(t+e)??void 0,r),set:(e,r)=>n.setItem(t+e,JSON.stringify(r)),remove:e=>n.removeItem(t+e),clear:()=>{let e=[];for(let r=0;r<n.length;r++){let i=n.key(r);i?.startsWith(t)&&e.push(i)}for(let t of e)n.removeItem(t)}}}function bt(e,t){if(e==null)return t;try{return JSON.parse(e)}catch{return t}}function xt(){try{if(typeof localStorage>`u`)return null;let e=`__incanto_probe__`;return localStorage.setItem(e,`1`),localStorage.removeItem(e),localStorage}catch{return null}}function St(e){let t={},n=[],r=e=>{let i=e.behavior;if(i&&typeof i.serialize==`function`){let r=i.serialize();r!==void 0&&(e.uid?t[e.uid]=r:n.push(e.getPath()))}for(let t of e.children)r(t)};return r(e),{state:t,unaddressable:n}}function Ct(e,t){let n={missing:[],skipped:[],restored:0};for(let[r,i]of Object.entries(t)){let t=e.getNodeByUid(r);if(!t){n.missing.push(r);continue}let a=t.behavior;if(!a||typeof a.deserialize!=`function`){n.skipped.push(r);continue}try{a.deserialize(i),n.restored+=1}catch{n.skipped.push(r)}}return n}var wt={master:1,sfx:1,music:1,muted:!1,quality:`high`,sensitivity:1,invertY:!1,reduceMotion:!1,language:`en`},Tt=[`low`,`medium`,`high`],Et=class{changed=new j;store;values;constructor(e=`settings`,t){this.store=t??yt(e),this.values={...wt};for(let e of Object.keys(wt)){let t=this.store.get(e,wt[e]);this.values[e]=t}Tt.includes(this.values.quality)||(this.values.quality=wt.quality)}get(e){return this.values[e]}set(e,t){this.values[e]!==t&&(this.values[e]=t,this.store.set(e,t),this.changed.emit(e))}all(){return{...this.values}}reset(){for(let e of Object.keys(wt))this.set(e,wt[e])}bindLocale(e){return e.locale=this.values.language,e.changed.connect(e=>{this.set(`language`,e)})}bindAudio(e){return e.master=this.values.master,e.sfx=this.values.sfx,e.music=this.values.music,e.muted=this.values.muted,e.changed.connect(()=>{this.set(`master`,e.master),this.set(`sfx`,e.sfx),this.set(`music`,e.music),this.set(`muted`,e.muted)})}},Dt=.25;function Ot(e){let t=!0,n=requestAnimationFrame(function r(i){t&&(e(i),n=requestAnimationFrame(r))});return()=>{t=!1,cancelAnimationFrame(n)}}var kt=class{updated=new j;fixedUpdated=new j;sceneChanged=new j;input=new ft;rng;log=new mt;picker=null;audio=new ie;settings=new Et;locale=new ze;orderGroups=ht;sfx=new Ie;music=new ve(this.audio);uiHost=null;fixedStep;maxFixedSteps;scheduler;_scene=null;lastMs=null;accumulator=0;disposeScheduler=null;frameStats=new ut;timeScale=1;debugSelection=null;_time=0;_unscaledTime=0;get time(){return this._time}get unscaledTime(){return this._unscaledTime}constructor(e={}){this.fixedStep=1/(e.fixedHz??60),this.maxFixedSteps=e.maxFixedStepsPerTick??5,this.scheduler=e.scheduler??Ot,this.rng=new P(e.seed??Math.random()*4294967295>>>0)}get scene(){return this._scene}setScene(e){e!==this._scene&&(this._scene?.tree._setEngine(null),this._scene?.root.free(),this._scene=e,e.tree._setEngine(this),this.input.clear(),this._time=0,this._unscaledTime=0,e.input&&this.input.declare(e.input),e.strings&&this.locale.load(e.strings),this.orderGroups=gt(e.orderGroups),this.sceneChanged.emit(e))}start(){this.disposeScheduler||=this.scheduler(e=>{try{this.tick(e)}catch(e){this.reportFrameError(e)}})}reportFrameError(e){this.errorCount+=1;let t=e instanceof Error?`${e.name}: ${e.message}`:String(e);t!==this.lastFrameError&&(this.lastFrameError=t,this.log.error(`[incanto] a frame threw — the loop keeps running:`,e),console.error(`[incanto] a frame threw — the loop keeps running:`,e))}_nodeErrored(e){this.errorCount+=1}errorCount=0;lastFrameError=null;t(e,t){return this.locale.t(e,t)}captureState(){let e=this.scene?.root;if(!e)return{};let{state:t,unaddressable:n}=St(e);for(let e of n)lt(this,`warn`,`save: ${e} has state to save and no uid to key it under.`);return t}restoreState(e){let t=this.scene?.root;return t?Ct(t,e):{missing:Object.keys(e),skipped:[],restored:0}}erroredNodes(){let e=[],t=n=>{(n.errored||n.behaviorErrored)&&e.push(n);for(let e of n.children)t(e)};return this._scene?.root&&t(this._scene.root),e}resumeErroredNodes(){let e=this.erroredNodes();for(let t of e)t.errored=!1,t.behaviorErrored=!1;return this.lastFrameError=null,e.length}stop(){this.disposeScheduler?.(),this.disposeScheduler=null,this.lastMs=null,this.accumulator=0,this.frameStats.clear()}stats(){return{fps:this.frameStats.fps(),frameMs:this.frameStats.frameMs(),nodes:this._scene?.tree.root?At(this._scene.tree.root):0,running:this.disposeScheduler!==null,errors:this.errorCount}}get interpolationAlpha(){return this.fixedStep>0?Math.min(this.accumulator/this.fixedStep,1):1}dispose(){this.stop(),this._scene&&(this._scene.tree._setEngine(null),this._scene.root.free(),this._scene=null,this.sceneChanged.emit(null)),this.input.dispose(),this.input.clear()}step(){let e=this._scene;e&&(e.tree.fixedUpdate(this.fixedStep),this.fixedUpdated.emit(this.fixedStep),e.tree.update(this.fixedStep),this.music.tick(this.fixedStep),this.updated.emit(this.fixedStep),this.input.endFrame())}tick(e){if(this.frameStats.push(e),this.lastMs===null){this.lastMs=e;return}let t=Math.max(0,Math.min((e-this.lastMs)/1e3,Dt)),n=t*this.timeScale;this._time+=n,this._unscaledTime+=t,this.lastMs=e;let r=this._scene;if(!r)return;this.accumulator+=n;let i=0;for(;this.accumulator>=this.fixedStep&&i<this.maxFixedSteps;)r.tree.fixedUpdate(this.fixedStep),this.fixedUpdated.emit(this.fixedStep),this.accumulator-=this.fixedStep,i+=1;this.accumulator>=this.fixedStep&&(this.accumulator%=this.fixedStep),r.tree.update(n),this.music.tick(n),this.updated.emit(n),this.input.endFrame()}};function At(e){let t=1;for(let n of e.children)t+=At(n);return t}function jt(e){if(e===``)throw new N(`BAD_NODE_PATH`,`Node path must not be empty.`);if(e.startsWith(`%`)){let t=e.slice(1);if(t===``||t.includes(`/`)||t.includes(`%`))throw new N(`BAD_NODE_PATH`,`Invalid unique-name path '${e}'. Expected '%NodeName'.`);return{kind:`unique`,name:t}}if(e===`.`)return{kind:`relative`,segments:[]};let t=e.startsWith(`/`),n=t?e.slice(1):e;if(n===``||n.split(`/`).some(e=>e===``))throw new N(`BAD_NODE_PATH`,`Invalid node path '${e}'. Segments must be non-empty (no leading/trailing/double '/').`);let r=n.split(`/`);for(let t of r){if(t.includes(`%`))throw new N(`BAD_NODE_PATH`,`Invalid node path '${e}'. '%' is only allowed as a whole-path prefix ('%Name').`);if(t===`.`)throw new N(`BAD_NODE_PATH`,`Invalid node path '${e}'. '.' is only valid as the whole path — drop the './' prefix.`)}if(t&&r.includes(`..`))throw new N(`BAD_NODE_PATH`,`Invalid node path '${e}'. Absolute paths must not contain '..'.`);return{kind:t?`absolute`:`relative`,segments:r}}function Mt(e){if(e===``||e.includes(`/`)||e.includes(`%`))throw new N(`TREE_VIOLATION`,`Invalid node name '${e}'. Names must be non-empty and must not contain '/' or '%'.`)}var Nt=class{static typeName=`Node`;_name;_parent=null;_children=[];_groups=new Set;_signals=new Map;_declared=null;_tree=null;_ready=!1;uid=null;tags={};script=null;behavior=null;network=null;constructor(e){let t=this.constructor;this._name=e??t.typeName,Mt(this._name)}get name(){return this._name}set name(e){Mt(e);let t=this._name;this._parent?this._name=Ft(e,this._parent._children,this):this._name=e,this._tree&&this._name!==t&&this._tree._reindexName(this,t)}get parent(){return this._parent}get children(){return this._children}get groups(){return this._groups}get tree(){return this._tree}get isReady(){return this._ready}addChild(e){if(e._parent!==null)throw new N(`TREE_VIOLATION`,`Cannot add '${e.name}': it already has parent '${e._parent.name}'. removeChild/reparent first.`);for(let t=this;t;t=t._parent)if(t===e)throw new N(`TREE_VIOLATION`,`Cannot add '${e.name}' to '${this.name}': it is this node or an ancestor (cycle).`);return e._name=Ft(e._name,this._children,e),e._parent=this,this._children.push(e),this._tree&&(e._propagateEnterTree(this._tree),e._propagateReady()),e}removeChild(e){let t=this._children.indexOf(e);if(t===-1)throw new N(`TREE_VIOLATION`,`'${e.name}' is not a child of '${this.name}'.`);e._tree&&e._propagateExitTree(),this._children.splice(t,1),e._parent=null}reparent(e){this._parent?.removeChild(this),e.addChild(this)}findChild(e,t=!0){for(let t of this._children)if(t._name===e)return t;if(t)for(let t of this._children){let n=t.findChild(e,!0);if(n)return n}return null}getRoot(){let e=this;for(;e._parent;)e=e._parent;return e}getNodeByUid(e){if(this.uid===e)return this;for(let t of this.children){let n=t.getNodeByUid(e);if(n)return n}return null}getNodesByName(e){if(this._tree&&this._parent===null){let t=this._tree._nodesNamed(e);return t?[...t]:[]}let t=[],n=r=>{r.name===e&&t.push(r);for(let e of r.children)n(e)};return n(this),t}getPath(){let e=[];for(let t=this;t;t=t._parent)e.unshift(t._name);return`/${e.join(`/`)}`}getNode(e){let t=this.resolve(e);if(t)return t;throw new N(`NODE_NOT_FOUND`,`No node at '${e}' from '${this.getPath()}'. Children here: [${this._children.map(e=>e._name).join(`, `)}].`)}getNodeOrNull(e){return this.resolve(e)}resolve(e){let t=jt(e);if(t.kind===`unique`){let e=this._tree;if(e){let n=e._nodesNamed(t.name);if(!n||n.size===0)return null;if(n.size>1){let e=[];for(let t of n)e.push(t.getPath());throw new N(`DUPLICATE_UNIQUE_NAME`,`'%${t.name}' is ambiguous: ${n.size} nodes named '${t.name}' (${e.join(`, `)}).`)}for(let e of n)return e}let n=[];if(Pt(this.getRoot(),t.name,n),n.length>1)throw new N(`DUPLICATE_UNIQUE_NAME`,`'%${t.name}' is ambiguous: ${n.length} nodes named '${t.name}' (${n.map(e=>e.getPath()).join(`, `)}).`);return n[0]??null}let n,r=t.segments;if(t.kind===`absolute`){let e=this.getRoot();if(r[0]!==e._name&&r[0]!==`root`)return null;n=e,r=r.slice(1)}else n=this;for(let e of r){if(!n)return null;if(e===`..`){n=n._parent;continue}n=n._children.find(t=>t._name===e)??null}return n}addToGroup(e){this._groups.add(e)}removeFromGroup(e){this._groups.delete(e)}isInGroup(e){return this._groups.has(e)}declaredSignals(){if(!this._declared){this._declared=new Set;let e=this.constructor;for(;typeof e==`function`;){let t=e;if(Object.hasOwn(e,`signals`)&&t.signals)for(let e of t.signals)this._declared.add(e);e=Object.getPrototypeOf(e)}}return this._declared}declareSignal(e){this.declaredSignals().add(e)}declaredSignalNames(){return[...this.declaredSignals()]}assertDeclared(e){if(this.declaredSignals().has(e))return;let t=this.constructor,n=[...this.declaredSignals()];throw new N(`UNKNOWN_SIGNAL`,`Unknown signal '${e}' on '${this.getPath()}' (${t.typeName}). Declared signals: [${n.join(`, `)}]. Declare it with "static signals = ['${e}']" on the node class or its behavior, or call node.declareSignal('${e}').`,{signal:e,path:this.getPath(),nodeType:t.typeName,validOptions:n})}signal(e){this.assertDeclared(e);let t=this._signals.get(e);return t||(t=new j,this._signals.set(e,t)),t}on(e,t,n){return this.signal(e).connect(t,n)}off(e,t){this._signals.get(e)?.disconnect(t)}emit(e,...t){this.assertDeclared(e),this._signals.get(e)?.emit(...t)}queueFree(){this._tree?this._tree._queueFree(this):this.free()}free(){let e=this._tree;for(let e of[...this._children])e.free();this._parent?.removeChild(this),this._tree&&this._propagateExitTree(),e?._detachRoot(this);for(let e of this._signals.values())e.disconnectAll();this._signals.clear()}_propagateEnterTree(e){this._tree=e,e._indexName(this),this.onEnterTree(),this.behavior?.onEnterTree?.();for(let t of[...this._children])t._tree!==e&&t._propagateEnterTree(e)}_propagateReady(){for(let e of[...this._children])e._tree&&e._propagateReady();this._ready||(this._ready=!0,this.onReady(),this.behavior?.onReady?.())}_propagateExitTree(){for(let e of[...this._children])e._propagateExitTree();this.onExitTree(),this.behavior?.onExitTree?.(),this._tree?._unindexName(this),this._tree=null}_propagateUpdate(e){if(!this.errored)try{this.update(e)}catch(e){this._quarantine(`update`,e,`node`)}if(this.behavior&&!this.behaviorErrored)try{this.behavior.update?.(e)}catch(e){this._quarantine(`update`,e,`behavior`)}let t=this._children;for(let n=0,r=t.length;n<r;n++)t[n]?._propagateUpdate(e)}_propagateFixedUpdate(e){if(!this.errored)try{this.fixedUpdate(e)}catch(e){this._quarantine(`fixedUpdate`,e,`node`)}if(this.behavior&&!this.behaviorErrored)try{this.behavior.fixedUpdate?.(e)}catch(e){this._quarantine(`fixedUpdate`,e,`behavior`)}let t=this._children;for(let n=0,r=t.length;n<r;n++)t[n]?._propagateFixedUpdate(e)}diagnose(e,...t){lt(this._tree?.engine??null,e,...t)}errored=!1;behaviorErrored=!1;_quarantine(e,t,n){let r=`${this.getPath()} (${this.constructor.typeName??`Node`})`,i;n===`behavior`?(this.behaviorErrored=!0,i=`[incanto] behavior '${this.behavior?.constructor.name??`?`}' on ${r} threw in ${e} — THE SCRIPT is now skipped; the node itself and the rest of the scene keep running.`):(this.errored=!0,i=`[incanto] ${r} threw in ${e} — this node is now SKIPPED. Its children and the rest of the scene keep running.`);let a=this._tree?.engine;a?.log.error(i,t),a?._nodeErrored(this),console.error(i,t)}onEnterTree(){}onReady(){}onExitTree(){}update(e){}fixedUpdate(e){}};function Pt(e,t,n){e.name===t&&n.push(e);for(let r of e.children)Pt(r,t,n)}function Ft(e,t,n){let r=new Set(t.filter(e=>e!==n).map(e=>e.name));if(!r.has(e))return e;let i=e.match(/^(.*?)(\d+)$/),a=i?i[1]:e,o=i?Number(i[2])+1:2;for(;r.has(`${a}${o}`);)o+=1;return`${a}${o}`}var It=null;function Lt(){return It?It():typeof Audio>`u`?null:new Audio}var Rt=class extends Nt{static typeName=`AudioPlayer`;static signals=[`finished`];static props={src:{default:``},preset:{default:`custom`,options:[`custom`,...be]},volume:{default:1},pitch:{default:1},seed:{default:0},bus:{default:`sfx`,options:[`sfx`,`music`]},loop:{default:!1},autoplay:{default:!1},spatial:{default:!1},refDistance:{default:1},maxDistance:{default:50},rolloff:{default:`inverse`,options:[...Ce]}};src=``;preset=`custom`;volume=1;pitch=1;seed=0;bus=`sfx`;loop=!1;autoplay=!1;spatial=!1;refDistance=1;maxDistance=50;rolloff=`inverse`;static validateJson(e){let t=e;if(t.preset!==`custom`&&!be.includes(t.preset))throw new N(`BAD_FORMAT`,`AudioPlayer '${e.name}' preset must be 'custom' or one of [${be.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:be});if(t.bus!==`sfx`&&t.bus!==`music`)throw new N(`BAD_FORMAT`,`AudioPlayer '${e.name}' bus must be 'sfx' or 'music', got '${t.bus}'.`,{prop:`bus`,validOptions:[`sfx`,`music`]});if(!Ce.includes(t.rolloff))throw new N(`BAD_FORMAT`,`AudioPlayer '${e.name}' rolloff must be one of [${Ce.join(`, `)}], got '${t.rolloff}'.`,{prop:`rolloff`,validOptions:[...Ce]})}pendingGesture=!1;element=null;_playing=!1;autoplayed=!1;_spatialPose=null;get playing(){return this._playing}_setSpatialPose(e){this._spatialPose=e}gain(){let e=this.tree?.engine?.audio;return e?e.effectiveVolume(this.bus,this.volume):this.volume}spatialElementGain(){if(!this.spatial||!this._spatialPose)return 1;let{position:e,listener:t}=this._spatialPose,n=e[0]-t.position[0],r=e[1]-t.position[1],i=e[2]-t.position[2];return L(Math.hypot(n,r,i),{refDistance:this.refDistance,maxDistance:this.maxDistance,rolloff:this.rolloff})}spatialPlay(){if(!(!this.spatial||!this._spatialPose))return{position:this._spatialPose.position,listener:this._spatialPose.listener,refDistance:this.refDistance,maxDistance:this.maxDistance,rolloff:this.rolloff}}play(){if(this.preset!==`custom`){this.playPreset();return}if(!this.src)return;if(!this.element){if(this.element=Lt(),!this.element)return;this.element.addEventListener(`ended`,()=>{this.loop||(this._playing=!1,this.emit(`finished`))})}let e=this.element;e.src=this.src,e.volume=this.gain()*this.spatialElementGain(),e.loop=this.loop,this._playing=!0,this.pendingGesture=!1,e.play().catch(()=>{this._playing=!1,this.pendingGesture=!0})}playPreset(){let e=F[this.preset];if(!e)return;let t=this.tree?.engine?.sfx;t&&t.play(e,this.gain(),{pitch:this.pitch,seed:this.seed,spatial:this.spatialPlay()})}stop(){this.element&&(this.element.pause(),this.element.currentTime=0),this._playing=!1,this.pendingGesture=!1}retryPending(){this.pendingGesture&&this.play()}update(e){this.autoplay&&!this.autoplayed&&(this.autoplayed=!0,this.play()),this.element&&this._playing&&(this.element.volume=this.gain()*this.spatialElementGain(),this.element.loop=this.loop)}},zt={topLeft:`left:16px;top:16px;align-items:flex-start;`,top:`left:50%;top:16px;transform:translateX(-50%);align-items:center;`,topRight:`right:16px;top:16px;align-items:flex-end;`,left:`left:16px;top:50%;transform:translateY(-50%);align-items:flex-start;`,center:`left:50%;top:50%;transform:translate(-50%,-50%);align-items:center;`,right:`right:16px;top:50%;transform:translateY(-50%);align-items:flex-end;`,bottomLeft:`left:16px;bottom:16px;align-items:flex-start;`,bottom:`left:50%;bottom:16px;transform:translateX(-50%);align-items:center;`,bottomRight:`right:16px;bottom:16px;align-items:flex-end;`},Bt=`600 14px system-ui, -apple-system, 'Segoe UI', sans-serif`;function Vt(){return typeof document<`u`}var Ht=class extends Nt{static typeName=`HudLayer`;static props={zIndex:{default:100},visible:{default:!0},focusNavigation:{default:!1}};zIndex=100;visible=!0;focusNavigation=!1;_element=null;slots=new Map;onEnterTree(){if(!Vt())return;let e=document.createElement(`div`);e.dataset.incantoHud=this.name,e.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${this.zIndex};font:${Bt};`,this._element=e,this._mount()}_mount(){let e=this._element;if(!e)return;let t=this.tree?.engine?.uiHost??document.body;e.parentElement!==t&&(e.style.position=t===document.body?`fixed`:`absolute`,t.appendChild(e))}onExitTree(){this._element?.remove(),this._element=null,this.slots.clear()}update(){this._element&&(this._mount(),this._element.style.display=this.visible?``:`none`),this.focusNavigation&&this.stepFocus()}stepFocus(){let e=this.tree?.engine;if(!e)return;let t=this.focusables();if(t.length===0)return;let n=e.input,r=n.keyJustPressed(`ArrowDown`)||n.keyJustPressed(`Pad13`),i=n.keyJustPressed(`ArrowUp`)||n.keyJustPressed(`Pad12`),a=n.keyJustPressed(`ArrowLeft`)||n.keyJustPressed(`Pad14`),o=n.keyJustPressed(`ArrowRight`)||n.keyJustPressed(`Pad15`),s=n.keyJustPressed(`Enter`)||n.keyJustPressed(`Pad0`),c=t.findIndex(e=>e._focused);if(c===-1&&(r||i||s)?c=0:r?c=(c+1)%t.length:i&&(c=(c-1+t.length)%t.length),c!==-1){for(let e of t){let n=e===t[c];n!==e._focused&&(e._focused=n,e._paintFocus())}let e=t[c];e&&(s?e._activate(0):a?e._activate(-1):o&&e._activate(1))}}focusables(){let e=[],t=n=>{n instanceof Kt&&n.focusable&&n.visible&&e.push(n);for(let e of n.children)t(e)};return t(this),e}focus(e){for(let t of this.focusables()){let n=t===e;n!==t._focused&&(t._focused=n,t._paintFocus())}}_slot(e){if(!this._element)return null;let t=this.slots.get(e);return t||(t=document.createElement(`div`),t.style.cssText=`position:absolute;display:flex;flex-direction:column;gap:8px;${zt[e]??zt.topLeft}`,this._element.appendChild(t),this.slots.set(e,t)),t}},Ut=new WeakMap;function Wt(e){for(let t=e;t;t=t.parentElement){let e=Ut.get(t);if(e)return e}return null}var Gt=null,Kt=class extends Nt{static props={anchor:{default:`topLeft`,options:[`topLeft`,`top`,`topRight`,`left`,`center`,`right`,`bottomLeft`,`bottom`,`bottomRight`]},visible:{default:!0},focusable:{default:!1},draggable:{default:!1},dropTarget:{default:!1}};static signals=[`dragStarted`,`dragCancelled`,`droppedOn`,`dropped`];anchor=`topLeft`;visible=!0;focusable=!1;draggable=!1;dropTarget=!1;_focused=!1;_activate(e){}_paintFocus(){this._element&&(this._element.style.outline=this._focused?`2px solid #6ee7dc`:``,this._element.style.outlineOffset=this._focused?`2px`:``)}_element=null;layer(){for(let e=this.parent;e;e=e.parent)if(e instanceof Ht)return e;return null}onReady(){Vt()&&this._mountWidget()}_mountWidget(){if(this._element||!Vt())return;let e=this.host()??this.layer()?._slot(this.anchor);e&&(this._element=this._build(),Ut.set(this._element,this),(this.draggable||this.dropTarget)&&this._wireDrag(this._element),e.appendChild(this._element))}_wireDrag(e){e.style.touchAction=`none`,this.draggable&&(e.style.cursor=`grab`,e.addEventListener(`pointerdown`,t=>{this.draggable&&(t.preventDefault(),e.setPointerCapture?.(t.pointerId),Gt=this,e.style.opacity=`0.6`,this.emit(`dragStarted`,this))}),e.addEventListener(`pointerup`,t=>{if(Gt!==this)return;e.style.opacity=``,e.releasePointerCapture?.(t.pointerId);let n=Wt(document.elementFromPoint?.(t.clientX,t.clientY)??null);Gt=null,n&&n!==this&&n.dropTarget?(this.emit(`droppedOn`,n),n.emit(`dropped`,this)):this.emit(`dragCancelled`,this)}))}host(){for(let e=this.parent;e;e=e.parent){let t=e;if(typeof t._container==`function`)return t._container();if(e instanceof Ht)return null}return null}onExitTree(){this._element?.remove(),this._element=null}update(e){!this._element&&(this._mountWidget(),!this._element)||(this._element.style.display=this.visible?``:`none`,this._sync())}_sync(){}_t(e){let t=this.tree?.engine?.locale;return t?t.resolve(e):e}},qt=class extends Kt{static typeName=`UiText`;static props={...Kt.props,text:{default:``},size:{default:16},color:{default:`#ffffff`},shadow:{default:!0}};text=``;size=16;color=`#ffffff`;shadow=!0;last=`\0`;_build(){let e=document.createElement(`div`);return e.style.cssText=`font-size:${this.size}px;color:${this.color};${this.shadow?`text-shadow:0 1px 3px rgba(0,0,0,.7);`:``}white-space:pre;`,e}_sync(){let e=this._t(this.text);e!==this.last&&this._element&&(this.last=e,this._element.textContent=e)}},Jt=class extends Kt{static typeName=`UiBar`;static props={...Kt.props,value:{default:100},max:{default:100},width:{default:180},height:{default:14},color:{default:`#4ade80`},lowColor:{default:`#ef4444`},lowThreshold:{default:.3},background:{default:`rgba(0,0,0,0.5)`},label:{default:``}};value=100;max=100;width=180;height=14;color=`#4ade80`;lowColor=`#ef4444`;lowThreshold=.3;background=`rgba(0,0,0,0.5)`;label=``;fill=null;tag=null;lastLabel=`\0`;lastRatio=-1;get ratio(){return this.max>0?Math.min(1,Math.max(0,this.value/this.max)):0}_build(){let e=document.createElement(`div`);if(e.style.cssText=`display:flex;align-items:center;gap:6px;`,this.label){let t=document.createElement(`span`);t.style.cssText=`color:#fff;font-size:12px;text-shadow:0 1px 3px rgba(0,0,0,.7);`,this.tag=t,e.appendChild(t)}let t=document.createElement(`div`);return t.style.cssText=`width:${this.width}px;height:${this.height}px;background:${this.background};border-radius:${this.height/2}px;overflow:hidden;`,this.fill=document.createElement(`div`),this.fill.style.cssText=`height:100%;width:100%;background:${this.color};border-radius:inherit;transition:width .15s;`,t.appendChild(this.fill),e.appendChild(t),e}_sync(){let e=this._t(this.label);e!==this.lastLabel&&this.tag&&(this.lastLabel=e,this.tag.textContent=e);let t=this.ratio;t===this.lastRatio||!this.fill||(this.lastRatio=t,this.fill.style.width=`${t*100}%`,this.fill.style.background=t<=this.lowThreshold?this.lowColor:this.color)}},Yt=class extends Kt{static typeName=`UiBanner`;static signals=[`bannerShown`];static props={...Kt.props,anchor:{default:`center`,options:[`topLeft`,`top`,`topRight`,`left`,`center`,`right`,`bottomLeft`,`bottom`,`bottomRight`]},size:{default:42},seconds:{default:2}};anchor=`center`;size=42;seconds=2;queue=[];current=null;remaining=0;get showing(){return this.current?.text??``}show(e,t){this.queue.push({text:e,color:t?.color??`#ffffff`,seconds:t?.seconds??this.seconds})}clear(){this.queue.length=0,this.current=null,this.remaining=0,this._element&&(this._element.style.opacity=`0`)}_build(){let e=document.createElement(`div`);return e.style.cssText=`font-size:${this.size}px;font-weight:800;color:#fff;text-shadow:0 2px 12px rgba(0,0,0,.8);opacity:0;transition:opacity .25s;text-align:center;`,e}update(e){super.update(e),this.current&&(this.current.seconds>0?(this.remaining-=e,this.remaining<=0&&(this.current=null,this._element&&(this._element.style.opacity=`0`))):this.queue.length>0&&(this.current=null)),!this.current&&this.queue.length>0&&(this.current=this.queue.shift(),this.current.text=this._t(this.current.text),this.remaining=this.current.seconds,this._element&&(this._element.textContent=this.current.text,this._element.style.color=this.current.color,this._element.style.opacity=`1`),this.emit(`bannerShown`,this.current.text))}},Xt=class extends Kt{static typeName=`UiButton`;static signals=[`pressed`];static props={...Kt.props,text:{default:`OK`},size:{default:16},color:{default:`#ffffff`},background:{default:`rgba(255,255,255,0.14)`},disabled:{default:!1},focusable:{default:!0}};text=`OK`;size=16;color=`#ffffff`;background=`rgba(255,255,255,0.14)`;disabled=!1;focusable=!0;_activate(e){this.press()}lastText=``;press(){this.disabled||this.emit(`pressed`)}_build(){let e=document.createElement(`button`);return e.type=`button`,e.style.cssText=`pointer-events:auto;cursor:pointer;font:600 ${this.size}px system-ui,sans-serif;color:${this.color};background:${this.background};border:1px solid rgba(255,255,255,0.25);border-radius:8px;padding:8px 18px;transition:transform .08s, background .15s;`,e.addEventListener(`mouseenter`,()=>{this.disabled||(e.style.background=`rgba(255,255,255,0.24)`)}),e.addEventListener(`mouseleave`,()=>{e.style.background=this.background}),e.addEventListener(`pointerdown`,()=>{this.disabled||(e.style.transform=`scale(0.95)`)}),e.addEventListener(`pointerup`,()=>{e.style.transform=``}),e.addEventListener(`click`,()=>this.press()),e}_sync(){if(!this._element)return;let e=this._t(this.text);e!==this.lastText&&(this.lastText=e,this._element.textContent=e),this._element.disabled=this.disabled,this._element.style.opacity=this.disabled?`0.45`:`1`}},Zt=class extends Kt{static typeName=`UiDialogue`;static signals=[`lineShown`,`choiceMade`,`dialogueFinished`];static props={...Kt.props,anchor:{default:`bottom`,options:[`topLeft`,`top`,`topRight`,`left`,`center`,`right`,`bottomLeft`,`bottom`,`bottomRight`]},charsPerSecond:{default:40},width:{default:520}};anchor=`bottom`;charsPerSecond=40;width=520;queue=[];current=null;revealed=0;speakerEl=null;textEl=null;choicesEl=null;hintEl=null;get active(){return this.current!==null||this.queue.length>0}get showing(){return this.current?this.current.text.slice(0,Math.floor(this.revealed)):``}say(e,t,n){this.queue.push({speaker:e,text:t,choices:n??null})}advance(){if(this.current){if(this.revealed<this.current.text.length){this.revealed=this.current.text.length;return}this.current.choices||this.next()}}choose(e){this.current?.choices&&(e<0||e>=this.current.choices.length||(this.emit(`choiceMade`,e),this.next()))}clear(){this.queue.length=0,this.current=null,this.revealed=0,this._element&&(this._element.style.display=`none`)}next(){this.current=null,this.revealed=0,this.queue.length===0&&(this._element&&(this._element.style.display=`none`),this.emit(`dialogueFinished`))}_build(){let e=document.createElement(`div`);return e.style.cssText=`pointer-events:auto;width:${this.width}px;max-width:86vw;background:rgba(12,14,22,0.92);border:1px solid rgba(255,255,255,0.2);border-radius:12px;padding:14px 18px;display:none;font:15px/1.5 system-ui,sans-serif;color:#fff;cursor:pointer;user-select:none;`,this.speakerEl=document.createElement(`div`),this.speakerEl.style.cssText=`font-weight:800;color:#ffd166;margin-bottom:4px;font-size:13px;`,this.textEl=document.createElement(`div`),this.textEl.style.cssText=`min-height:3em;white-space:pre-wrap;`,this.choicesEl=document.createElement(`div`),this.choicesEl.style.cssText=`display:flex;gap:8px;margin-top:10px;flex-wrap:wrap;`,this.hintEl=document.createElement(`div`),this.hintEl.textContent=`▼`,this.hintEl.style.cssText=`text-align:right;opacity:0.5;font-size:11px;animation:none;`,e.append(this.speakerEl,this.textEl,this.choicesEl,this.hintEl),e.addEventListener(`click`,()=>this.advance()),e}update(e){if(super.update(e),!this.current&&this.queue.length>0&&(this.current=this.queue.shift(),this.current.text=this._t(this.current.text),this.current.speaker=this._t(this.current.speaker),this.current.choices&&(this.current.choices=this.current.choices.map(e=>this._t(e))),this.revealed=this.charsPerSecond<=0?this.current.text.length:0,this.emit(`lineShown`,this.current.text),this._element&&(this.speakerEl&&(this.speakerEl.textContent=this.current.speaker),this.choicesEl&&this.choicesEl.replaceChildren())),this._element&&(this._element.style.display=this.visible&&this.current?`block`:`none`),!this.current)return;let t=this.revealed<this.current.text.length;t&&(this.revealed=Math.min(this.current.text.length,this.revealed+this.charsPerSecond*e));let n=this.revealed>=this.current.text.length;this.textEl&&(this.textEl.textContent=this.showing),this.hintEl&&(this.hintEl.style.visibility=n&&!this.current.choices?`visible`:`hidden`),n&&t&&this.current.choices&&this.choicesEl&&this.current.choices.forEach((e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.textContent=e,n.style.cssText=`pointer-events:auto;cursor:pointer;font:600 13px system-ui,sans-serif;color:#fff;background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.3);border-radius:8px;padding:6px 14px;`,n.addEventListener(`click`,e=>{e.stopPropagation(),this.choose(t)}),this.choicesEl?.appendChild(n)})}},Qt=class extends Nt{static typeName=`Timer`;static signals=[`timeout`];static props={waitTime:{default:1},oneShot:{default:!1},autostart:{default:!1}};waitTime=1;oneShot=!1;autostart=!1;running=!1;remaining=0;start(e){e!==void 0&&(this.waitTime=e),this.remaining=this.waitTime,this.running=!0}stop(){this.running=!1}onReady(){this.autostart&&this.start()}update(e){if(this.running){if(this.waitTime<=0){this.stop();return}for(this.remaining-=e;this.remaining<=0&&this.running;)this.emit(`timeout`),this.oneShot||this.waitTime<=0?this.stop():this.remaining+=this.waitTime}}};function $t(e){return`${e}px`}var en=class extends Kt{static typeName=`UiPanel`;static props={...Kt.props,layout:{default:`column`,options:[`column`,`row`,`grid`]},columns:{default:4},gap:{default:8},padding:{default:12},background:{default:`rgba(0,0,0,0.55)`},radius:{default:10},width:{default:0},height:{default:0},border:{default:``}};layout=`column`;columns=4;gap=8;padding=12;background=`rgba(0,0,0,0.55)`;radius=10;width=0;height=0;border=``;lastKey=``;_build(){let e=document.createElement(`div`);return e.style.cssText=this.css(),this.lastKey=this.css(),e}_container(){return this._element||this._mountWidget(),this._element}css(){return`${this.layout===`grid`?`display:grid;grid-template-columns:repeat(${Math.max(1,this.columns)},auto);`:`display:flex;flex-direction:${this.layout};align-items:stretch;`}gap:${$t(this.gap)};padding:${$t(this.padding)};background:${this.background};border-radius:${$t(this.radius)};`+(this.width>0?`width:${$t(this.width)};`:``)+(this.height>0?`height:${$t(this.height)};`:``)+(this.border?`border:${this.border};`:``)+`box-sizing:border-box;pointer-events:auto;`}_sync(){let e=this.css();e!==this.lastKey&&this._element&&(this.lastKey=e,this._element.style.cssText=e)}},tn=class extends Kt{static typeName=`UiImage`;static props={...Kt.props,src:{default:``},width:{default:48},height:{default:48},fit:{default:`contain`,options:[`contain`,`cover`,`fill`]},tint:{default:``},opacity:{default:1}};src=``;width=48;height=48;fit=`contain`;tint=``;opacity=1;last=`\0`;_build(){let e=document.createElement(`div`);return e.style.cssText=this.css(),this.last=this.key(),e}resolved(){return this.src.startsWith(`$`)?(this.tree?.engine?.scene?.assets)?.[this.src.slice(1)]?.url??``:this.src}key(){return`${this.resolved()}|${this.width}|${this.height}|${this.fit}|${this.tint}|${this.opacity}`}css(){let e=this.resolved();return`width:${$t(this.width)};height:${$t(this.height)};flex:none;`+(e?`background-image:url("${e}");`:``)+`background-size:${this.fit===`fill`?`100% 100%`:this.fit};background-position:center;background-repeat:no-repeat;opacity:${this.opacity};`+(this.tint?`background-color:${this.tint};background-blend-mode:multiply;`:``)}_sync(){let e=this.key();e!==this.last&&this._element&&(this.last=e,this._element.style.cssText=this.css())}},nn=class extends Kt{static typeName=`UiSlider`;static props={...Kt.props,label:{default:``},value:{default:.5},min:{default:0},max:{default:1},step:{default:.01},width:{default:180},color:{default:`#6ee7dc`},focusable:{default:!0}};static signals=[...Kt.signals,`changed`];label=``;value=.5;min=0;max=1;step=.01;width=180;color=`#6ee7dc`;focusable=!0;_activate(e){if(e===0)return;let t=Math.min(this.max,Math.max(this.min,this.value+e*this.step));t!==this.value&&(this.value=t,this.last=t,this.input&&(this.input.value=String(t)),this.emit(`changed`,t))}input=null;text=null;last=NaN;_build(){let e=document.createElement(`div`);e.style.cssText=`display:flex;align-items:center;gap:8px;pointer-events:auto;font:600 13px system-ui,-apple-system,'Segoe UI',sans-serif;color:#fff;`;let t=document.createElement(`span`);t.textContent=this.label;let n=document.createElement(`input`);return n.type=`range`,n.min=String(this.min),n.max=String(this.max),n.step=String(this.step),n.value=String(this.value),n.style.cssText=`width:${$t(this.width)};accent-color:${this.color};`,n.addEventListener(`input`,()=>{this.value=Number(n.value),this.last=this.value,this.emit(`changed`,this.value)}),this.label&&e.appendChild(t),e.appendChild(n),this.input=n,this.text=t,this.last=this.value,e}_sync(){this.input&&this.value!==this.last&&(this.last=this.value,this.input.value=String(this.value)),this.text&&this.text.textContent!==this.label&&(this.text.textContent=this.label)}},rn=class extends Kt{static typeName=`UiToggle`;static props={...Kt.props,label:{default:``},value:{default:!1},focusable:{default:!0}};static signals=[...Kt.signals,`changed`];label=``;value=!1;focusable=!0;_activate(e){let t=e===0?!this.value:e>0;t!==this.value&&(this.value=t,this.last=t,this.input&&(this.input.checked=t),this.emit(`changed`,t))}input=null;last=null;_build(){let e=document.createElement(`label`);e.style.cssText=`display:flex;align-items:center;gap:8px;pointer-events:auto;cursor:pointer;font:600 13px system-ui,-apple-system,'Segoe UI',sans-serif;color:#fff;`;let t=document.createElement(`input`);t.type=`checkbox`,t.checked=this.value,t.addEventListener(`change`,()=>{this.value=t.checked,this.last=this.value,this.emit(`changed`,this.value)});let n=document.createElement(`span`);return n.textContent=this.label,e.append(t,n),this.input=t,this.last=this.value,e}_sync(){this.input&&this.value!==this.last&&(this.last=this.value,this.input.checked=this.value)}},an=class extends Kt{static typeName=`UiSelect`;static props={...Kt.props,label:{default:``},options:{default:``},value:{default:``},focusable:{default:!0}};static signals=[...Kt.signals,`changed`];label=``;options=``;value=``;focusable=!0;_activate(e){let t=this.options.split(`,`).map(e=>e.trim()).filter(Boolean);if(t.length===0)return;let n=t[(Math.max(0,t.indexOf(this.value))+(e===0?1:e)+t.length)%t.length];!n||n===this.value||(this.value=n,this.last=n,this.select&&(this.select.value=n),this.emit(`changed`,n))}select=null;labelEl=null;lastLabel=`x`;lastOptions=`\0`;last=`\0`;_build(){let e=document.createElement(`label`);e.style.cssText=`display:flex;align-items:center;gap:8px;pointer-events:auto;font:600 13px system-ui,-apple-system,'Segoe UI',sans-serif;color:#fff;`;let t=document.createElement(`span`);this.labelEl=t;let n=document.createElement(`select`);return n.addEventListener(`change`,()=>{this.value=n.value,this.last=this.value,this.emit(`changed`,this.value)}),this.label&&e.appendChild(t),e.appendChild(n),this.select=n,this.fillOptions(),e}_optionLabel(e){return e}fillOptions(){let e=this.select;if(!(!e||this.options===this.lastOptions)){this.lastOptions=this.options,e.textContent=``;for(let t of this.options.split(`,`)){let n=t.trim();if(!n)continue;let r=document.createElement(`option`);r.value=n,r.textContent=this._optionLabel(n),e.appendChild(r)}this.value&&(e.value=this.value),this.last=this.value}}_sync(){let e=this._t(this.label);e!==this.lastLabel&&this.labelEl&&(this.lastLabel=e,this.labelEl.textContent=e),this.fillOptions(),this.select&&this.value!==this.last&&(this.last=this.value,this.select.value=this.value)}},on={en:`English`,ko:`한국어`,ja:`日本語`,"zh-CN":`简体中文`,"zh-TW":`繁體中文`,es:`Español`,fr:`Français`,de:`Deutsch`,pt:`Português`,ru:`Русский`,it:`Italiano`,th:`ไทย`,vi:`Tiếng Việt`,id:`Bahasa Indonesia`},sn=class extends an{static typeName=`UiLanguageSelect`;static props={...an.props,label:{default:`Language`}};label=`Language`;lastLocale=``;_sync(){let e=this.tree?.engine?.locale;if(e){let t=e.available(),n=t.join(`,`);n!==this.options&&(this.options=n),e.locale===this.lastLocale?this.value!==e.locale&&t.includes(this.value)&&(e.locale=this.value,this.lastLocale=this.value):(this.lastLocale=e.locale,this.value=e.locale)}super._sync()}_optionLabel(e){return on[e]??e}},cn=.5*(Math.sqrt(3)-1),ln=(3-Math.sqrt(3))/6,un=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,0,1,0,-1]);function dn(e){let t=new P(e),n=new Uint8Array(512),r=new Uint8Array(256);for(let e=0;e<256;e++)r[e]=e;for(let e=255;e>0;e--){let n=t.int(0,e),i=r[e];r[e]=r[n],r[n]=i}for(let e=0;e<512;e++)n[e]=r[e&255];return(e,t)=>{let r=(e+t)*cn,i=Math.floor(e+r),a=Math.floor(t+r),o=(i+a)*ln,s=e-(i-o),c=t-(a-o),l=+(s>c),u=s>c?0:1,d=s-l+ln,f=c-u+ln,p=s-1+2*ln,m=c-1+2*ln,h=i&255,g=a&255,_=0,v=.5-s*s-c*c;if(v>0){v*=v;let e=n[h+n[g]]%8*2;_+=v*v*(un[e]*s+un[e+1]*c)}let y=.5-d*d-f*f;if(y>0){y*=y;let e=n[h+l+n[g+u]]%8*2;_+=y*y*(un[e]*d+un[e+1]*f)}let b=.5-p*p-m*m;if(b>0){b*=b;let e=n[h+1+n[g+1]]%8*2;_+=b*b*(un[e]*p+un[e+1]*m)}return 70*_}}var fn={fire:{rate:60,lifetime:[.4,.9],speed:[30,70],directionDeg:-90,spreadDeg:35,gravity:[0,-30],sizeStart:14,sizeEnd:3,colorStart:`#ffcf5a`,colorEnd:`#e8401f`,alphaStart:.9,alphaEnd:0,blend:`add`},smoke:{rate:20,lifetime:[1.5,2.5],speed:[10,25],directionDeg:-90,spreadDeg:40,gravity:[0,-12],sizeStart:10,sizeEnd:26,colorStart:`#8a8a8a`,colorEnd:`#3a3a3a`,alphaStart:.35,alphaEnd:0,blend:`normal`},sparks:{rate:80,lifetime:[.3,.7],speed:[120,260],spreadDeg:360,gravity:[0,240],drag:1,sizeStart:4,sizeEnd:1,colorStart:`#fff3b0`,colorEnd:`#ff9d2e`,blend:`add`},fireworks:{rate:0,burst:120,lifetime:[.8,1.6],speed:[80,240],spreadDeg:360,gravity:[0,90],drag:.6,sizeStart:5,sizeEnd:1,colorStart:`#9ad8ff`,colorEnd:`#ff5ad8`,blend:`add`},explosion:{rate:0,burst:60,lifetime:[.25,.6],speed:[150,420],spreadDeg:360,drag:3,sizeStart:16,sizeEnd:2,colorStart:`#ffe08a`,colorEnd:`#ff3b1f`,blend:`add`},flash:{rate:0,burst:8,lifetime:[.08,.16],speed:[0,30],spreadDeg:360,sizeStart:64,sizeEnd:96,colorStart:`#ffffff`,colorEnd:`#ffffff`,alphaStart:1,alphaEnd:0,blend:`add`},lightning:{rate:90,lifetime:[.05,.12],speed:[400,900],directionDeg:-90,spreadDeg:14,sizeStart:6,sizeEnd:2,colorStart:`#eaf2ff`,colorEnd:`#7fb4ff`,blend:`add`},rain:{rate:160,lifetime:[.8,1.2],speed:[300,420],directionDeg:90,spreadDeg:6,sizeStart:3,sizeEnd:3,colorStart:`#9ec8ff`,colorEnd:`#9ec8ff`,alphaStart:.5,alphaEnd:.2,blend:`normal`},snow:{rate:40,lifetime:[3,5],speed:[20,50],directionDeg:90,spreadDeg:30,drag:.2,sizeStart:5,sizeEnd:4,colorStart:`#ffffff`,colorEnd:`#ffffff`,alphaStart:.9,alphaEnd:.6,blend:`normal`},magic:{rate:50,lifetime:[.6,1.4],speed:[20,80],spreadDeg:360,gravity:[0,-20],sizeStart:7,sizeEnd:1,colorStart:`#9dffe8`,colorEnd:`#7a5cff`,blend:`add`}},pn=Object.keys(fn);function mn(e,t,n){if(t===`custom`)return;let r=fn[t];if(r)for(let[t,i]of Object.entries(r)){let r=n[t]?.default,a=e[t];r!==void 0&&Ve(a,r)&&(e[t]=Array.isArray(i)?[...i]:i)}}var hn=9,gn=class{config;rng;data;alive=0;spawnAccumulator=0;everSpawned=!1;constructor(e,t){this.config=e,this.rng=t,this.data=new Float64Array(Math.max(1,e.maxParticles)*hn)}setRate(e){this.config.rate=e,e<=0&&(this.spawnAccumulator=0)}get count(){return this.alive}get done(){return this.everSpawned&&this.alive===0}burst(e){for(let t=0;t<e;t++)this.spawn()}update(e){if(this.config.rate>0)for(this.spawnAccumulator+=this.config.rate*e;this.spawnAccumulator>=1;)--this.spawnAccumulator,this.spawn();let t=this.data,[n,r,i]=this.config.gravity,a=this.config.drag>0?Math.exp(-this.config.drag*e):1,o=0;for(;o<this.alive;){let s=o*hn,c=t[s+6]+e;if(c>=t[s+7]){this.kill(o);continue}t[s+6]=c,t[s+3]=(t[s+3]+n*e)*a,t[s+4]=(t[s+4]+r*e)*a,t[s+5]=(t[s+5]+i*e)*a,t[s+0]=t[s+0]+t[s+3]*e,t[s+1]=t[s+1]+t[s+4]*e,t[s+2]=t[s+2]+t[s+5]*e,o+=1}}forEach(e){let t=this.data;for(let n=0;n<this.alive;n++){let r=n*hn,i=t[r+6],a=t[r+7];e({x:t[r+0],y:t[r+1],z:t[r+2],vx:t[r+3],vy:t[r+4],vz:t[r+5],age:i,life:a,t:a>0?i/a:1,seed:t[r+8]})}}spawn(){if(this.alive>=this.config.maxParticles)return;let e=this.alive*hn,t=this.data,n=this.config,r=(n.directionDeg+(this.rng.next()-.5)*n.spreadDeg)*Math.PI/180,i=n.speed[0]+this.rng.next()*(n.speed[1]-n.speed[0]),a=n.spreadZ?(this.rng.next()-.5)*(n.spreadDeg*Math.PI/180):0,o=Math.cos(a);t[e+0]=0,t[e+1]=0,t[e+2]=0,t[e+3]=Math.cos(r)*i*o,t[e+4]=Math.sin(r)*i*o,t[e+5]=Math.sin(a)*i,t[e+6]=0,t[e+7]=n.lifetime[0]+this.rng.next()*(n.lifetime[1]-n.lifetime[0]),t[e+8]=this.rng.next(),this.alive+=1,this.everSpawned=!0}kill(e){let t=this.alive-1;e!==t&&this.data.copyWithin(e*hn,t*hn,t*hn+hn),this.alive=t}};function _n(){R(Nt),R(Qt),R(Rt),R(Ht),R(qt),R(Jt),R(Yt),R(Xt),R(Zt),R(en),R(tn),R(nn),R(rn),R(an),R(sn)}function vn(e,t,n,r){let i=e?.rendering??{},a=i.pixelRatio===`device`?n:i.pixelRatio;return{antialias:r?.antialias??i.antialias??t.antialias,pixelRatio:r?.pixelRatio??a??t.pixelRatio,preserveDrawingBuffer:r?.preserveDrawingBuffer??i.preserveDrawingBuffer??t.preserveDrawingBuffer}}var yn=`@const`;function bn(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.keys(e);return t.length===1&&t[0]===`@const`&&typeof e[`@const`]==`string`}function xn(e,t){if(e==null)return e;if(bn(e)){let n=e[yn];if(!t||!(n in t)){let e=t?Object.keys(t):[];throw new N(`UNKNOWN_CONSTANT`,`Unknown constant '@const: ${n}'. Declared constants: ${e.length?e.join(`, `):`(none — add a "constants" section)`}.`)}return He(t[n])}if(Array.isArray(e))return e.map(e=>xn(e,t));if(typeof e==`object`){let n={};for(let[r,i]of Object.entries(e))n[r]=xn(i,t);return n}return e}var Sn=class e{_root=null;_engine=null;freeQueue=new Set;_nameIndex=new Map;_structureVersion=0;_structureLog=[];_structureLogBase=0;static STRUCTURE_LOG_MAX=2048;_structureSince(e){return e>this._structureVersion||e<this._structureLogBase?null:this._structureLog.slice(e-this._structureLogBase)}_logStructure(t,n){this._structureVersion++,this._structureLog.push({node:t,added:n});let r=this._structureLog.length-e.STRUCTURE_LOG_MAX;r>0&&(this._structureLog.splice(0,r),this._structureLogBase+=r)}_frameId=0;get frameId(){return this._frameId}_indexName(e){this._logStructure(e,!0);let t=this._nameIndex.get(e.name);t||(t=new Set,this._nameIndex.set(e.name,t)),t.add(e)}_reindexName(e,t){let n=this._nameIndex.get(t);n&&(n.delete(e),n.size===0&&this._nameIndex.delete(t));let r=this._nameIndex.get(e.name);r||(r=new Set,this._nameIndex.set(e.name,r)),r.add(e)}_unindexName(e,t=e.name){this._logStructure(e,!1);let n=this._nameIndex.get(t);n&&(n.delete(e),n.size===0&&this._nameIndex.delete(t))}_nodesNamed(e){return this._nameIndex.get(e)}_frameScratch=null;get root(){return this._root}get engine(){return this._engine}_setEngine(e){this._engine=e}setRoot(e){if(this._root)throw new N(`TREE_VIOLATION`,`SceneTree already has a root.`);if(e.parent)throw new N(`TREE_VIOLATION`,`Root must not have a parent ('${e.name}' is a child of '${e.parent.name}').`);this._root=e,e._propagateEnterTree(this),e._propagateReady()}update(e){this._frameId++,this._root?._propagateUpdate(e),this.flushFreeQueue()}fixedUpdate(e){this._root?._propagateFixedUpdate(e),this.flushFreeQueue()}getNodesInGroup(e){let t=[];return this._root&&Cn(this._root,e,t),t}callGroup(e,t,...n){for(let r of this.getNodesInGroup(e)){let e=r[t];typeof e==`function`&&e.apply(r,n)}}_queueFree(e){this.freeQueue.add(e)}_detachRoot(e){this._root===e&&(this._root=null)}flushFreeQueue(){if(this.freeQueue.size===0)return;let e=[...this.freeQueue];this.freeQueue.clear();for(let t of e)t.free()}};function Cn(e,t,n){e.isInGroup(t)&&n.push(e);for(let r of e.children)Cn(r,t,n)}var wn=[`expand`,`letterbox`,`integer`];function Tn(e){if(e===void 0)return null;let t=e.design;if(!Array.isArray(t)||t.length!==2||typeof t[0]!=`number`||typeof t[1]!=`number`||t[0]<=0||t[1]<=0)throw new N(`BAD_FORMAT`,`Scene "viewport.design" must be [width, height] with positive numbers, got ${JSON.stringify(t)}.`);let n=e.fit??`expand`;if(typeof n!=`string`||!wn.includes(n))throw new N(`BAD_FORMAT`,`Scene "viewport.fit" must be one of [${wn.join(`, `)}], got ${JSON.stringify(n)}.`);return{design:[t[0],t[1]],fit:n}}function En(e,t,n){let r=n.design[0],i=n.design[1],a=Math.min(e/r,t/i),o=n.fit===`integer`?Math.max(1,Math.floor(a)):a;if(n.fit===`letterbox`){let n=r*o,a=i*o;return{scale:o,viewW:r,viewH:i,offsetX:(e-n)/2,offsetY:(t-a)/2,contentW:n,contentH:a}}return{scale:o,viewW:e/o,viewH:t/o,offsetX:0,offsetY:0,contentW:e,contentH:t}}function Dn(e){let t=e.constructor,n={name:e.name,type:t.typeName};e.uid!==null&&(n.uid=e.uid),e.groups.size>0&&(n.groups=[...e.groups]),Object.keys(e.tags).length>0&&(n.tags=He(e.tags));let r=qe(t.typeName),i={};for(let[t,n]of Object.entries(r)){let r=e[t];r!==void 0&&(On(r,`${e.name}.${t}`),Ve(r,n.default)||(i[t]=He(r)))}return Object.keys(i).length>0&&(n.props=i),e.script&&(n.script=He(e.script)),e.network&&(n.network=He(e.network)),e.children.length>0&&(n.children=e.children.map(e=>Dn(e))),n}function On(e,t){if(typeof e==`number`&&!Number.isFinite(e))throw new N(`PROP_TYPE_MISMATCH`,`Prop '${t}' is ${e} — scene props must be finite numbers (NaN/Infinity become null in JSON).`);if(Array.isArray(e))for(let n=0;n<e.length;n++)On(e[n],`${t}[${n}]`);else if(typeof e==`object`&&e)for(let[n,r]of Object.entries(e))On(r,`${t}.${n}`)}var kn=class{name;dimension;root;tree;environment;assets;constants;input;strings;orderGroups;physics;multiplayer;viewport;connections;source;constructor(e,t,n){this.source=He(e),this.name=e.name,this.dimension=e.dimension,this.root=t,this.tree=n,this.assets=e.assets?He(e.assets):void 0,this.constants=e.constants?He(e.constants):void 0,this.input=e.input?He(e.input):void 0,this.orderGroups=e.orderGroups?{...e.orderGroups}:void 0,this.strings=e.strings?He(e.strings):void 0,this.physics=e.physics?He(e.physics):void 0,this.multiplayer=e.multiplayer?He(e.multiplayer):void 0,this.environment=e.environment?He(e.environment):void 0,this.viewport=e.viewport?He(e.viewport):void 0,this.connections=e.connections?He(e.connections):[]}toJSON(){return{format:1,type:`scene`,name:this.name,...this.dimension?{dimension:this.dimension}:{},...this.assets?{assets:He(this.assets)}:{},...this.constants?{constants:He(this.constants)}:{},...this.input?{input:He(this.input)}:{},...this.orderGroups?{orderGroups:{...this.orderGroups}}:{},...this.strings?{strings:He(this.strings)}:{},...this.physics?{physics:He(this.physics)}:{},...this.multiplayer?{multiplayer:He(this.multiplayer)}:{},...this.environment?{environment:He(this.environment)}:{},...this.viewport?{viewport:He(this.viewport)}:{},root:Dn(this.root),...this.connections.length>0?{connections:He(this.connections)}:{}}}};function An(e,t){if(typeof e!=`object`||!e)throw new N(`BAD_FORMAT`,`Scene JSON must be an object, got ${e===null?`null`:typeof e}.`);let n=e;Mn(n);let r=Pn(n.root,t,[],``,n.constants,Object.keys(n.orderGroups??{}));Hn(r);let i=new Sn;return t?.engine&&i._setEngine(t.engine),i.setRoot(r),zn(r,n.connections??[],t?.declareConnectionSignals),new kn(n,r,i)}function jn(e,t){return Pn(e,t,[],``,void 0)}function Mn(e){if(e.format!==1)throw new N(`BAD_FORMAT`,`Unsupported scene format ${JSON.stringify(e.format)}; this engine reads format 1.`);if(e.type!==`scene`)throw new N(`BAD_FORMAT`,`Expected "type": "scene", got ${JSON.stringify(e.type)}.`);if(typeof e.name!=`string`||e.name===``)throw new N(`BAD_FORMAT`,`Scene "name" must be a non-empty string.`);if(e.dimension!==void 0&&e.dimension!==`2d`&&e.dimension!==`3d`)throw new N(`BAD_FORMAT`,`Scene "dimension" must be "2d" or "3d", got ${JSON.stringify(e.dimension)}.`);if(typeof e.root!=`object`||e.root===null)throw new N(`BAD_FORMAT`,`Scene "root" must be a node object.`);if(Tn(e.viewport),e.input!==void 0){if(typeof e.input!=`object`||e.input===null||Array.isArray(e.input))throw new N(`BAD_FORMAT`,`Scene "input" must be an object of action declarations.`);pt(e.input)}if(e.orderGroups!==void 0){let t=e.orderGroups;if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`BAD_FORMAT`,`Scene "orderGroups" must be an object of band name → base offset, e.g. { "ui-back": 2500 }.`);for(let[e,n]of Object.entries(t))if(typeof n!=`number`||!Number.isFinite(n))throw new N(`BAD_FORMAT`,`Order group '${e}' must be a finite number (its base draw offset), got ${JSON.stringify(n)}. A band is a NUMBER — a bare name would sort exactly like "default" and mean nothing.`,{prop:e})}if(e.assets!==void 0){if(typeof e.assets!=`object`||e.assets===null||Array.isArray(e.assets))throw new N(`BAD_FORMAT`,`Scene "assets" must be an object of asset declarations.`);for(let[t,n]of Object.entries(e.assets)){if(typeof n!=`object`||!n||Array.isArray(n))throw new N(`BAD_FORMAT`,`Asset '${t}' must be an object, got ${JSON.stringify(n)}.`);let e=n.url;if(typeof e!=`string`||e===``)throw new N(`BAD_FORMAT`,`Asset '${t}' needs a non-empty "url" string.`)}}}function Nn(e,t,n){return e instanceof N&&!e.details.path?new N(e.code,`${e.message} (at '${t}')`,{...e.details,path:t,...typeof n.uid==`string`&&n.uid!==``?{uid:n.uid}:{},...e.details.nodeType===void 0&&n.type?{nodeType:n.type}:{}}):e}function Pn(e,t,n,r,i,a=[]){let o=`${r}/${e.name}`;try{if(e.instance!==void 0&&e.type!==void 0)throw new N(`BAD_FORMAT`,`Node '${e.name}' declares both "type" and "instance" — they are mutually exclusive.`);if(e.instance!==void 0)return Fn(e,t,n,o,i,a);if(e.type===void 0)throw new N(`BAD_FORMAT`,`Node '${e.name}' must declare either "type" or "instance".`);let r=$e(e.type,xn(e.props,i),{orderGroup:a});Ln(r,e,t),r.constructor.validateJson?.(r);for(let s of e.children??[])r.addChild(Pn(s,t,n,o,i,a));return r}catch(t){throw Nn(t,o,e)}}function Fn(e,t,n,r,i,a){let o=e.instance;if(!t?.resolveScene)throw new N(`UNRESOLVED_INSTANCE`,`Node '${e.name}' references instance '${o}' but no resolveScene option was provided.`);if(n.includes(o))throw new N(`UNRESOLVED_INSTANCE`,`Instance cycle detected: ${[...n,o].join(` → `)}.`);let s=t.resolveScene(o);if(!s)throw new N(`UNRESOLVED_INSTANCE`,`resolveScene returned nothing for instance '${o}' (node '${e.name}').`);Mn(s);let c=xn(e.overrides??{},i),l=Pn({...s.root,name:e.name,props:Rn(s.root.props??{},c)},t,[...n,o],In(r),s.constants,Object.keys(s.orderGroups??{}));Ln(l,{...e,type:void 0,props:void 0},t);for(let o of e.children??[])l.addChild(Pn(o,t,n,r,i,a));return zn(l,s.connections??[],t?.declareConnectionSignals),l}function In(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function Ln(e,t,n){typeof t.uid==`string`&&t.uid!==``&&(e.uid=t.uid),e.name=t.name;for(let n of t.groups??[])e.addToGroup(n);if(t.tags&&(e.tags=He(t.tags)),t.script){e.script=He(t.script);let r=t.script.name;if(typeof r!=`string`||r===``)throw new N(`BAD_FORMAT`,`Node '${t.name}': "script" needs a non-empty "name" (a registered behavior).`);let i=n?.stubAllBehaviors||n?.stubMissingBehaviors&&!rt(r)?new class extends tt{}:ct(r,t.script.props);i.node=e,e.behavior=i;for(let t of Je(i.constructor))e.declareSignal(t)}t.network&&(e.network=He(t.network))}function Rn(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t!==null&&r!==null&&typeof t==`object`&&typeof r==`object`&&!Array.isArray(t)&&!Array.isArray(r)?n[e]=Rn(t,r):n[e]=r}return n}function zn(e,t,n=!1){for(let r of t){let t=Bn(e,r.from,r,`from`);(n||t.behavior instanceof tt)&&t.declareSignal(r.signal);let i=Bn(e,r.to,r,`to`),a=i[r.handler],o=i.behavior?i.behavior[r.handler]:void 0;if(typeof a!=`function`&&typeof o!=`function`&&!(i.behavior instanceof tt))throw new N(`UNKNOWN_HANDLER`,`Connection '${r.signal}' → '${r.to}' names handler '${r.handler}', but '${i.name}' has no such method`+(i.behavior?` (nor does its behavior '${i.script?.name}')`:``)+`.`);let s=(...e)=>{if(r.filter&&!Vn(e[0],r.filter))return;r.once&&t.off(r.signal,s);let n=i[r.handler];if(typeof n==`function`){n.apply(i,e);return}let a=i.behavior?i.behavior[r.handler]:void 0;typeof a==`function`&&a.apply(i.behavior,e)};try{t.on(r.signal,s)}catch(e){throw e instanceof N&&e.code===`UNKNOWN_SIGNAL`?new N(`UNKNOWN_SIGNAL`,`Connection from '${r.from}': ${e.message}`,e.details):e}}}function Bn(e,t,n,r){try{return e.getNode(t)}catch(e){throw e instanceof N?new N(`DANGLING_CONNECTION`,`Connection '${n.signal}' has a dangling '${r}' path '${t}': ${e.message}`):e}}function Vn(e,t){if(!(e instanceof Nt)||t.group&&!e.isInGroup(t.group))return!1;if(t.tag){for(let[n,r]of Object.entries(t.tag))if(JSON.stringify(e.tags[n])!==JSON.stringify(r))return!1}return!0}function Hn(e){let t=new Map,n=e=>{if(e.uid!==null){let n=t.get(e.uid);if(n)throw new N(`DUPLICATE_UID`,`duplicate uid '${e.uid}' on ${n.getPath()} and ${e.getPath()} — uids must be unique across the scene.`);t.set(e.uid,e)}for(let t of e.children)n(t)};n(e)}function Un(e){let{uid:t,...n}=e;return{...n,children:e.children?.map(Un)}}function Wn(e){return jn(Un(Dn(e)))}var Gn=.08;function Kn(e,t,n){let r=e/n,i=t/n,a=Math.hypot(r,i);return a<Gn?{x:0,y:0}:(a>1&&(r/=a,i/=a),{x:r,y:i})}function qn(e,t,n={}){let r=e.input.touchControls();if(r.length===0||!n.force&&!Jn())return null;let i=n.doc??(typeof document<`u`?document:null);return!i||typeof t.appendChild!=`function`?null:new Yn(e,t,r,i)}function Jn(){return typeof matchMedia<`u`&&matchMedia(`(pointer: coarse)`).matches}var Yn=class{elements=[];detachers=[];constructor(e,t,n,r){let i=0,a=0;for(let o of n)o.kind===`joystick`?(this.buildJoystick(e,t,o.action,a,r),a+=1):(this.buildButton(e,t,o.action,i,r),i+=1)}dispose(){for(let e of this.detachers)e();for(let e of this.elements)e.remove();this.elements.length=0,this.detachers.length=0}buildJoystick(e,t,n,r,i){let a=i.createElement(`div`);Zn(a,{position:`absolute`,left:`${24+r*140}px`,bottom:`24px`,width:`120px`,height:`120px`,borderRadius:`50%`,background:`rgba(255,255,255,0.10)`,border:`2px solid rgba(255,255,255,0.25)`,touchAction:`none`,pointerEvents:`auto`,zIndex:`20`});let o=i.createElement(`div`);Zn(o,{position:`absolute`,left:`50%`,top:`50%`,width:`48px`,height:`48px`,marginLeft:`-24px`,marginTop:`-24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.35)`,pointerEvents:`none`}),a.appendChild(o),t.appendChild(a),this.elements.push(a);let s=null,c=0,l=0,u=60,d=(t,r)=>{let i=Kn(t-c,r-l,u);Xn(()=>e.input.setActionVector(n,i.x,i.y)),o.style.transform=`translate(${i.x*u*.6}px, ${i.y*u*.6}px)`},f=e=>{s=e.pointerId;let t=a.getBoundingClientRect();c=t.left+t.width/2,l=t.top+t.height/2,u=t.width/2,a.setPointerCapture?.(e.pointerId),d(e.clientX,e.clientY)},p=e=>{e.pointerId===s&&d(e.clientX,e.clientY)},m=t=>{t.pointerId===s&&(s=null,o.style.transform=``,Xn(()=>e.input.setActionVector(n,0,0)))};a.addEventListener(`pointerdown`,f),a.addEventListener(`pointermove`,p),a.addEventListener(`pointerup`,m),a.addEventListener(`pointercancel`,m),this.detachers.push(()=>{a.removeEventListener(`pointerdown`,f),a.removeEventListener(`pointermove`,p),a.removeEventListener(`pointerup`,m),a.removeEventListener(`pointercancel`,m)})}buildButton(e,t,n,r,i){let a=i.createElement(`div`);a.textContent=n,Zn(a,{position:`absolute`,right:`24px`,bottom:`${24+r*80}px`,width:`64px`,height:`64px`,borderRadius:`50%`,background:`rgba(255,255,255,0.12)`,border:`2px solid rgba(255,255,255,0.3)`,color:`rgba(255,255,255,0.85)`,font:`600 12px system-ui, sans-serif`,display:`flex`,alignItems:`center`,justifyContent:`center`,userSelect:`none`,touchAction:`none`,pointerEvents:`auto`,zIndex:`20`}),t.appendChild(a),this.elements.push(a);let o=null,s=t=>{o=t.pointerId,a.setPointerCapture?.(t.pointerId),Xn(()=>e.input.pressAction(n)),a.style.background=`rgba(255,255,255,0.3)`},c=t=>{t.pointerId===o&&(o=null,Xn(()=>e.input.releaseAction(n)),a.style.background=`rgba(255,255,255,0.12)`)};a.addEventListener(`pointerdown`,s),a.addEventListener(`pointerup`,c),a.addEventListener(`pointercancel`,c),this.detachers.push(()=>{a.removeEventListener(`pointerdown`,s),a.removeEventListener(`pointerup`,c),a.removeEventListener(`pointercancel`,c)})}};function Xn(e){try{e()}catch{}}function Zn(e,t){for(let[n,r]of Object.entries(t))e.style[n]=r}function Qn(){let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);let t=``;for(let n of e)t+=(n%36).toString(36);return`n_${t.slice(0,16)}`}var $n=`attached`,er=1e3,tr=1001,nr=1002,rr=1003,ir=1004,ar=1005,or=1006,sr=1007,cr=1008,lr=1009,ur=1010,dr=1011,fr=1012,pr=1013,mr=1014,hr=1015,gr=1016,_r=1017,vr=1018,yr=1020,br=35902,xr=35899,Sr=1021,Cr=1022,wr=1023,Tr=1026,Er=1027,Dr=1028,Or=1029,kr=1030,Ar=1031,jr=1033,Mr=33776,Nr=33777,Pr=33778,Fr=33779,Ir=35840,Lr=35841,Rr=35842,zr=35843,Br=36196,Vr=37492,Hr=37496,Ur=37488,Wr=37489,Gr=37490,Kr=37491,qr=37808,Jr=37809,Yr=37810,Xr=37811,Zr=37812,Qr=37813,$r=37814,ei=37815,ti=37816,ni=37817,ri=37818,ii=37819,ai=37820,oi=37821,si=36492,ci=36494,li=36495,ui=36283,di=36284,fi=36285,pi=36286,mi=2200,hi=2201,gi=2202,_i=2300,vi=2301,yi=2302,bi=2303,xi=2400,Si=2401,Ci=2402,wi=2500,Ti=2501,Ei=3200,Di=3201,Oi=`srgb`,ki=`srgb-linear`,Ai=`linear`,ji=`srgb`,Mi=7680,Ni=35044,Pi=35048,Fi=2e3;function Ii(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Li(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Ri(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function zi(){let e=Ri(`canvas`);return e.style.display=`block`,e}var Bi={},Vi=null;function Hi(...e){let t=`THREE.`+e.shift();Vi?Vi(`log`,t,...e):console.log(t,...e)}function Ui(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function z(...e){e=Ui(e);let t=`THREE.`+e.shift();if(Vi)Vi(`warn`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function B(...e){e=Ui(e);let t=`THREE.`+e.shift();if(Vi)Vi(`error`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function Wi(...e){let t=e.join(` `);t in Bi||(Bi[t]=!0,z(...e))}function Gi(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var Ki={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},qi=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},Ji=`00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),Yi=1234567,Xi=Math.PI/180,Zi=180/Math.PI;function Qi(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(Ji[e&255]+Ji[e>>8&255]+Ji[e>>16&255]+Ji[e>>24&255]+`-`+Ji[t&255]+Ji[t>>8&255]+`-`+Ji[t>>16&15|64]+Ji[t>>24&255]+`-`+Ji[n&63|128]+Ji[n>>8&255]+`-`+Ji[n>>16&255]+Ji[n>>24&255]+Ji[r&255]+Ji[r>>8&255]+Ji[r>>16&255]+Ji[r>>24&255]).toLowerCase()}function $i(e,t,n){return Math.max(t,Math.min(n,e))}function ea(e,t){return(e%t+t)%t}function ta(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function na(e,t,n){return e===t?0:(n-e)/(t-e)}function ra(e,t,n){return(1-n)*e+n*t}function ia(e,t,n,r){return ra(e,t,1-Math.exp(-n*r))}function aa(e,t=1){return t-Math.abs(ea(e,t*2)-t)}function oa(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function sa(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function ca(e,t){return e+Math.floor(Math.random()*(t-e+1))}function la(e,t){return e+Math.random()*(t-e)}function ua(e){return e*(.5-Math.random())}function da(e){e!==void 0&&(Yi=e);let t=Yi+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function fa(e){return e*Xi}function pa(e){return e*Zi}function ma(e){return(e&e-1)==0&&e!==0}function ha(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function ga(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function _a(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:z(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function va(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`Invalid component type.`)}}function ya(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}var ba={DEG2RAD:Xi,RAD2DEG:Zi,generateUUID:Qi,clamp:$i,euclideanModulo:ea,mapLinear:ta,inverseLerp:na,lerp:ra,damp:ia,pingpong:aa,smoothstep:oa,smootherstep:sa,randInt:ca,randFloat:la,randFloatSpread:ua,seededRandom:da,degToRad:fa,radToDeg:pa,isPowerOfTwo:ma,ceilPowerOfTwo:ha,floorPowerOfTwo:ga,setQuaternionFromProperEuler:_a,normalize:ya,denormalize:va},V=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=$i(this.x,e.x,t.x),this.y=$i(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=$i(this.x,e,t),this.y=$i(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar($i(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos($i(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},H=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:z(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs($i(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},U=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Sa.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Sa.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=$i(this.x,e.x,t.x),this.y=$i(this.y,e.y,t.y),this.z=$i(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=$i(this.x,e,t),this.y=$i(this.y,e,t),this.z=$i(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar($i(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return xa.copy(this).projectOnVector(e),this.sub(xa)}reflect(e){return this.sub(xa.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos($i(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},xa=new U,Sa=new H,W=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Ca.makeScale(e,t)),this}rotate(e){return this.premultiply(Ca.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ca.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Ca=new W,wa=new W().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Ta=new W().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Ea(){let e={enabled:!0,workingColorSpace:ki,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=Oa(e.r),e.g=Oa(e.g),e.b=Oa(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=ka(e.r),e.g=ka(e.g),e.b=ka(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Ai:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return Wi(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Wi(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[ki]:{primaries:t,whitePoint:r,transfer:Ai,toXYZ:wa,fromXYZ:Ta,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Oi},outputColorSpaceConfig:{drawingBufferColorSpace:Oi}},[Oi]:{primaries:t,whitePoint:r,transfer:ji,toXYZ:wa,fromXYZ:Ta,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Oi}}}),e}var Da=Ea();function Oa(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function ka(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Aa,ja=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Aa===void 0&&(Aa=Ri(`canvas`)),Aa.width=e.width,Aa.height=e.height;let t=Aa.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Aa}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=Ri(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=Oa(i[e]/255)*255;return n.putImageData(r,0,0),t}else if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(Oa(t[e]/255)*255):t[e]=Oa(t[e]);return{data:t,width:e.width,height:e.height}}else return z(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},Ma=0,Na=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Ma++}),this.uuid=Qi(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<`u`&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(Pa(r[t].image)):e.push(Pa(r[t]))}else e=Pa(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function Pa(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?ja.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(z(`Texture: Unable to serialize Texture.`),{})}var Fa=0,Ia=new U,La=class e extends qi{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=tr,i=tr,a=or,o=cr,s=wr,c=lr,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Fa++}),this.uuid=Qi(),this.name=``,this.source=new Na(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new V(0,0),this.repeat=new V(1,1),this.center=new V(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new W,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Ia).x}get height(){return this.source.getSize(Ia).y}get depth(){return this.source.getSize(Ia).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){z(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){z(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case er:e.x-=Math.floor(e.x);break;case tr:e.x=e.x<0?0:1;break;case nr:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case er:e.y-=Math.floor(e.y);break;case tr:e.y=e.y<0?0:1;break;case nr:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};La.DEFAULT_IMAGE=null,La.DEFAULT_MAPPING=300,La.DEFAULT_ANISOTROPY=1;var Ra=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=$i(this.x,e.x,t.x),this.y=$i(this.y,e.y,t.y),this.z=$i(this.z,e.z,t.z),this.w=$i(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=$i(this.x,e,t),this.y=$i(this.y,e,t),this.z=$i(this.z,e,t),this.w=$i(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar($i(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},za=class extends qi{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:or,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Ra(0,0,e,t),this.scissorTest=!1,this.viewport=new Ra(0,0,e,t),this.textures=[];let r=new La({width:e,height:t,depth:n.depth}),i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){let t={minFilter:or,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new Na(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this.multiview=e.multiview,this}dispose(){this.dispatchEvent({type:`dispose`})}},Ba=class extends za{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},Va=class extends La{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=rr,this.minFilter=rr,this.wrapR=tr,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Ha=class extends La{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=rr,this.minFilter=rr,this.wrapR=tr,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},G=class e{static{e.prototype.isMatrix4=!0}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();let t=this.elements,n=e.elements,r=1/Ua.setFromMatrixColumn(e,0).length(),i=1/Ua.setFromMatrixColumn(e,1).length(),a=1/Ua.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Ga,e,Ka)}lookAt(e,t,n){let r=this.elements;return Ya.subVectors(e,t),Ya.lengthSq()===0&&(Ya.z=1),Ya.normalize(),qa.crossVectors(n,Ya),qa.lengthSq()===0&&(Math.abs(n.z)===1?Ya.x+=1e-4:Ya.z+=1e-4,Ya.normalize(),qa.crossVectors(n,Ya)),qa.normalize(),Ja.crossVectors(Ya,qa),r[0]=qa.x,r[4]=Ja.x,r[8]=Ya.x,r[1]=qa.y,r[5]=Ja.y,r[9]=Ya.y,r[2]=qa.z,r[6]=Ja.z,r[10]=Ya.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],k=r[2],A=r[6],ee=r[10],te=r[14],ne=r[3],re=r[7],j=r[11],ie=r[15];return i[0]=a*x+o*T+s*k+c*ne,i[4]=a*S+o*E+s*A+c*re,i[8]=a*C+o*D+s*ee+c*j,i[12]=a*w+o*O+s*te+c*ie,i[1]=l*x+u*T+d*k+f*ne,i[5]=l*S+u*E+d*A+f*re,i[9]=l*C+u*D+d*ee+f*j,i[13]=l*w+u*O+d*te+f*ie,i[2]=p*x+m*T+h*k+g*ne,i[6]=p*S+m*E+h*A+g*re,i[10]=p*C+m*D+h*ee+g*j,i[14]=p*w+m*O+h*te+g*ie,i[3]=_*x+v*T+y*k+b*ne,i[7]=_*S+v*E+y*A+b*re,i[11]=_*C+v*D+y*ee+b*j,i[15]=_*w+v*O+y*te+b*ie,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15],_=s*f-c*d,v=o*f-c*u,y=o*d-s*u,b=a*f-c*l,x=a*d-s*l,S=a*u-o*l;return t*(m*_-h*v+g*y)-n*(p*_-h*b+g*x)+r*(p*v-m*b+g*S)-i*(p*y-m*x+h*S)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=t*o-n*a,v=t*s-r*a,y=t*c-i*a,b=n*s-r*o,x=n*c-i*o,S=r*c-i*s,C=l*m-u*p,w=l*h-d*p,T=l*g-f*p,E=u*h-d*m,D=u*g-f*m,O=d*g-f*h,k=_*O-v*D+y*E+b*T-x*w+S*C;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let A=1/k;return e[0]=(o*O-s*D+c*E)*A,e[1]=(r*D-n*O-i*E)*A,e[2]=(m*S-h*x+g*b)*A,e[3]=(d*x-u*S-f*b)*A,e[4]=(s*T-a*O-c*w)*A,e[5]=(t*O-r*T+i*w)*A,e[6]=(h*y-p*S-g*v)*A,e[7]=(l*S-d*y+f*v)*A,e[8]=(a*D-o*T+c*C)*A,e[9]=(n*T-t*D-i*C)*A,e[10]=(p*x-m*y+g*_)*A,e[11]=(u*y-l*x-f*_)*A,e[12]=(o*w-a*E-s*C)*A,e[13]=(t*E-n*w+r*C)*A,e[14]=(m*v-p*b-h*_)*A,e[15]=(l*b-u*v+d*_)*A,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let i=this.determinant();if(i===0)return n.set(1,1,1),t.identity(),this;let a=Ua.set(r[0],r[1],r[2]).length(),o=Ua.set(r[4],r[5],r[6]).length(),s=Ua.set(r[8],r[9],r[10]).length();i<0&&(a=-a),Wa.copy(this);let c=1/a,l=1/o,u=1/s;return Wa.elements[0]*=c,Wa.elements[1]*=c,Wa.elements[2]*=c,Wa.elements[4]*=l,Wa.elements[5]*=l,Wa.elements[6]*=l,Wa.elements[8]*=u,Wa.elements[9]*=u,Wa.elements[10]*=u,t.setFromRotationMatrix(Wa),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=Fi,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=Fi,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},Ua=new U,Wa=new G,Ga=new U(0,0,0),Ka=new U(1,1,1),qa=new U,Ja=new U,Ya=new U,Xa=new G,Za=new H,Qa=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin($i(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-$i(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin($i(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-$i(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin($i(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-$i(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:z(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Xa.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Xa,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Za.setFromEuler(this),this.setFromQuaternion(Za,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};Qa.DEFAULT_ORDER=`XYZ`;var $a=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!=0}},eo=0,to=new U,no=new H,ro=new G,io=new U,ao=new U,oo=new U,so=new H,co=new U(1,0,0),lo=new U(0,1,0),uo=new U(0,0,1),fo={type:`added`},po={type:`removed`},mo={type:`childadded`,child:null},ho={type:`childremoved`,child:null},go=class e extends qi{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:eo++}),this.uuid=Qi(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new U,n=new Qa,r=new H,i=new U(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new G},normalMatrix:{value:new W}}),this.matrix=new G,this.matrixWorld=new G,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new $a,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return no.setFromAxisAngle(e,t),this.quaternion.multiply(no),this}rotateOnWorldAxis(e,t){return no.setFromAxisAngle(e,t),this.quaternion.premultiply(no),this}rotateX(e){return this.rotateOnAxis(co,e)}rotateY(e){return this.rotateOnAxis(lo,e)}rotateZ(e){return this.rotateOnAxis(uo,e)}translateOnAxis(e,t){return to.copy(e).applyQuaternion(this.quaternion),this.position.add(to.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(co,e)}translateY(e){return this.translateOnAxis(lo,e)}translateZ(e){return this.translateOnAxis(uo,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(ro.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?io.copy(e):io.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),ao.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?ro.lookAt(ao,io,this.up):ro.lookAt(io,ao,this.up),this.quaternion.setFromRotationMatrix(ro),r&&(ro.extractRotation(r.matrixWorld),no.setFromRotationMatrix(ro),this.quaternion.premultiply(no.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(B(`Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(fo),mo.child=e,this.dispatchEvent(mo),mo.child=null):B(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(po),ho.child=e,this.dispatchEvent(ho),ho.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),ro.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),ro.multiply(e.parent.matrixWorld)),e.applyMatrix4(ro),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(fo),mo.child=e,this.dispatchEvent(mo),mo.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ao,e,oo),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ao,so,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,r=e.z,i=this.matrix.elements;i[12]+=t-i[0]*t-i[4]*n-i[8]*r,i[13]+=n-i[1]*t-i[5]*n-i[9]*r,i[14]+=r-i[2]*t-i[6]*n-i[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let e=this.children;for(let t=0,n=e.length;t<n;t++)e[t].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,this.name!==``&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),this.static!==!1&&(r.static=this.static),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material);if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}};go.DEFAULT_UP=new U(0,1,0),go.DEFAULT_MATRIX_AUTO_UPDATE=!0,go.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var _o=class extends go{constructor(){super(),this.isGroup=!0,this.type=`Group`}},vo={type:`move`},yo=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new _o,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new _o,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new U,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new U),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new _o,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new U,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new U,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position);c.inputState.pinching&&o>.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(vo)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new _o;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},bo={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},xo={h:0,s:0,l:0},So={h:0,s:0,l:0};function Co(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var K=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Oi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Da.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=Da.workingColorSpace){return this.r=e,this.g=t,this.b=n,Da.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=Da.workingColorSpace){if(e=ea(e,1),t=$i(t,0,1),n=$i(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=Co(i,r,e+1/3),this.g=Co(i,r,e),this.b=Co(i,r,e-1/3)}return Da.colorSpaceToWorking(this,r),this}setStyle(e,t=Oi){function n(t){t!==void 0&&parseFloat(t)<1&&z(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:z(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);z(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Oi){let n=bo[e.toLowerCase()];return n===void 0?z(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Oa(e.r),this.g=Oa(e.g),this.b=Oa(e.b),this}copyLinearToSRGB(e){return this.r=ka(e.r),this.g=ka(e.g),this.b=ka(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Oi){return Da.workingToColorSpace(wo.copy(this),e),Math.round($i(wo.r*255,0,255))*65536+Math.round($i(wo.g*255,0,255))*256+Math.round($i(wo.b*255,0,255))}getHexString(e=Oi){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Da.workingColorSpace){Da.workingToColorSpace(wo.copy(this),t);let n=wo.r,r=wo.g,i=wo.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4;break}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=Da.workingColorSpace){return Da.workingToColorSpace(wo.copy(this),t),e.r=wo.r,e.g=wo.g,e.b=wo.b,e}getStyle(e=Oi){Da.workingToColorSpace(wo.copy(this),e);let t=wo.r,n=wo.g,r=wo.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(xo),this.setHSL(xo.h+e,xo.s+t,xo.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(xo),e.getHSL(So);let n=ra(xo.h,So.h,t),r=ra(xo.s,So.s,t),i=ra(xo.l,So.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},wo=new K;K.NAMES=bo;var To=class e{constructor(e,t=1,n=1e3){this.isFog=!0,this.name=``,this.color=new K(e),this.near=t,this.far=n}clone(){return new e(this.color,this.near,this.far)}toJSON(){return{type:`Fog`,name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}},Eo=class extends go{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Qa,this.environmentIntensity=1,this.environmentRotation=new Qa,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},Do=new U,Oo=new U,ko=new U,Ao=new U,jo=new U,Mo=new U,No=new U,Po=new U,Fo=new U,Io=new U,Lo=new Ra,Ro=new Ra,zo=new Ra,Bo=class e{constructor(e=new U,t=new U,n=new U){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),Do.subVectors(e,t),r.cross(Do);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){Do.subVectors(r,t),Oo.subVectors(n,t),ko.subVectors(e,t);let a=Do.dot(Do),o=Do.dot(Oo),s=Do.dot(ko),c=Oo.dot(Oo),l=Oo.dot(ko),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Ao)===null?!1:Ao.x>=0&&Ao.y>=0&&Ao.x+Ao.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Ao)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Ao.x),s.addScaledVector(a,Ao.y),s.addScaledVector(o,Ao.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Lo.setScalar(0),Ro.setScalar(0),zo.setScalar(0),Lo.fromBufferAttribute(e,t),Ro.fromBufferAttribute(e,n),zo.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Lo,i.x),a.addScaledVector(Ro,i.y),a.addScaledVector(zo,i.z),a}static isFrontFacing(e,t,n,r){return Do.subVectors(n,t),Oo.subVectors(e,t),Do.cross(Oo).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Do.subVectors(this.c,this.b),Oo.subVectors(this.a,this.b),Do.cross(Oo).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;jo.subVectors(r,n),Mo.subVectors(i,n),Po.subVectors(e,n);let s=jo.dot(Po),c=Mo.dot(Po);if(s<=0&&c<=0)return t.copy(n);Fo.subVectors(e,r);let l=jo.dot(Fo),u=Mo.dot(Fo);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(jo,a);Io.subVectors(e,i);let f=jo.dot(Io),p=Mo.dot(Io);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(Mo,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return No.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(No,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(jo,a).addScaledVector(Mo,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Vo=class{constructor(e=new U(1/0,1/0,1/0),t=new U(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Uo.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Uo.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=Uo.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,Uo):Uo.fromBufferAttribute(r,t),Uo.applyMatrix4(e.matrixWorld),this.expandByPoint(Uo);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Wo.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Wo.copy(e.boundingBox)),Wo.applyMatrix4(e.matrixWorld),this.union(Wo)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Uo),Uo.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Zo),Qo.subVectors(this.max,Zo),Go.subVectors(e.a,Zo),Ko.subVectors(e.b,Zo),qo.subVectors(e.c,Zo),Jo.subVectors(Ko,Go),Yo.subVectors(qo,Ko),Xo.subVectors(Go,qo);let t=[0,-Jo.z,Jo.y,0,-Yo.z,Yo.y,0,-Xo.z,Xo.y,Jo.z,0,-Jo.x,Yo.z,0,-Yo.x,Xo.z,0,-Xo.x,-Jo.y,Jo.x,0,-Yo.y,Yo.x,0,-Xo.y,Xo.x,0];return!ts(t,Go,Ko,qo,Qo)||(t=[1,0,0,0,1,0,0,0,1],!ts(t,Go,Ko,qo,Qo))?!1:($o.crossVectors(Jo,Yo),t=[$o.x,$o.y,$o.z],ts(t,Go,Ko,qo,Qo))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Uo).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Uo).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Ho[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ho[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ho[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ho[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ho[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ho[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ho[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ho[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ho),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},Ho=[new U,new U,new U,new U,new U,new U,new U,new U],Uo=new U,Wo=new Vo,Go=new U,Ko=new U,qo=new U,Jo=new U,Yo=new U,Xo=new U,Zo=new U,Qo=new U,$o=new U,es=new U;function ts(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){es.fromArray(e,a);let o=i.x*Math.abs(es.x)+i.y*Math.abs(es.y)+i.z*Math.abs(es.z),s=t.dot(es),c=n.dot(es),l=r.dot(es);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var ns=rs();function rs(){let e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),r=new Uint32Array(512),i=new Uint32Array(512);for(let e=0;e<256;++e){let t=e-127;t<-27?(r[e]=0,r[e|256]=32768,i[e]=24,i[e|256]=24):t<-14?(r[e]=1024>>-t-14,r[e|256]=1024>>-t-14|32768,i[e]=-t-1,i[e|256]=-t-1):t<=15?(r[e]=t+15<<10,r[e|256]=t+15<<10|32768,i[e]=13,i[e|256]=13):t<128?(r[e]=31744,r[e|256]=64512,i[e]=24,i[e|256]=24):(r[e]=31744,r[e|256]=64512,i[e]=13,i[e|256]=13)}let a=new Uint32Array(2048),o=new Uint32Array(64),s=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(t&8388608);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,a[e]=t|n}for(let e=1024;e<2048;++e)a[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)e!==32&&(s[e]=1024);return{floatView:t,uint32View:n,baseTable:r,shiftTable:i,mantissaTable:a,exponentTable:o,offsetTable:s}}function is(e){Math.abs(e)>65504&&z(`DataUtils.toHalfFloat(): Value out of range.`),e=$i(e,-65504,65504),ns.floatView[0]=e;let t=ns.uint32View[0],n=t>>23&511;return ns.baseTable[n]+((t&8388607)>>ns.shiftTable[n])}function as(e){let t=e>>10;return ns.uint32View[0]=ns.mantissaTable[ns.offsetTable[t]+(e&1023)]+ns.exponentTable[t],ns.floatView[0]}var os=class{static toHalfFloat(e){return is(e)}static fromHalfFloat(e){return as(e)}},ss=new U,cs=new V,ls=0,q=class extends qi{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:ls++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Ni,this.updateRanges=[],this.gpuType=hr,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)cs.fromBufferAttribute(this,t),cs.applyMatrix3(e),this.setXY(t,cs.x,cs.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)ss.fromBufferAttribute(this,t),ss.applyMatrix3(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)ss.fromBufferAttribute(this,t),ss.applyMatrix4(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)ss.fromBufferAttribute(this,t),ss.applyNormalMatrix(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)ss.fromBufferAttribute(this,t),ss.transformDirection(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=va(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ya(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=va(t,this.array)),t}setX(e,t){return this.normalized&&(t=ya(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=va(t,this.array)),t}setY(e,t){return this.normalized&&(t=ya(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=va(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ya(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=va(t,this.array)),t}setW(e,t){return this.normalized&&(t=ya(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array),r=ya(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array),r=ya(r,this.array),i=ya(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==``&&(e.name=this.name),this.usage!==35044&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:`dispose`})}},us=class extends q{constructor(e,t,n){super(new Uint16Array(e),t,n)}},ds=class extends q{constructor(e,t,n){super(new Uint32Array(e),t,n)}},fs=class extends q{constructor(e,t,n){super(new Float32Array(e),t,n)}},ps=new Vo,ms=new U,hs=new U,gs=class{constructor(e=new U,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?ps.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;ms.subVectors(e,this.center);let t=ms.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(ms,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(hs.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ms.copy(e.center).add(hs)),this.expandByPoint(ms.copy(e.center).sub(hs))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},_s=0,vs=new G,ys=new go,bs=new U,xs=new Vo,Ss=new Vo,Cs=new U,J=class e extends qi{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:_s++}),this.uuid=Qi(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Ii(e)?ds:us)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new W().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return vs.makeRotationFromQuaternion(e),this.applyMatrix4(vs),this}rotateX(e){return vs.makeRotationX(e),this.applyMatrix4(vs),this}rotateY(e){return vs.makeRotationY(e),this.applyMatrix4(vs),this}rotateZ(e){return vs.makeRotationZ(e),this.applyMatrix4(vs),this}translate(e,t,n){return vs.makeTranslation(e,t,n),this.applyMatrix4(vs),this}scale(e,t,n){return vs.makeScale(e,t,n),this.applyMatrix4(vs),this}lookAt(e){return ys.lookAt(e),ys.updateMatrix(),this.applyMatrix4(ys.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(bs).negate(),this.translate(bs.x,bs.y,bs.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new fs(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&z(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Vo);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){B(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new U(-1/0,-1/0,-1/0),new U(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];xs.setFromBufferAttribute(n),this.morphTargetsRelative?(Cs.addVectors(this.boundingBox.min,xs.min),this.boundingBox.expandByPoint(Cs),Cs.addVectors(this.boundingBox.max,xs.max),this.boundingBox.expandByPoint(Cs)):(this.boundingBox.expandByPoint(xs.min),this.boundingBox.expandByPoint(xs.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&B(`BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new gs);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){B(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new U,1/0);return}if(e){let n=this.boundingSphere.center;if(xs.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];Ss.setFromBufferAttribute(n),this.morphTargetsRelative?(Cs.addVectors(xs.min,Ss.min),xs.expandByPoint(Cs),Cs.addVectors(xs.max,Ss.max),xs.expandByPoint(Cs)):(xs.expandByPoint(Ss.min),xs.expandByPoint(Ss.max))}xs.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)Cs.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(Cs));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)Cs.fromBufferAttribute(a,t),o&&(bs.fromBufferAttribute(e,t),Cs.add(bs)),r=Math.max(r,n.distanceToSquared(Cs))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&B(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){B(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv;this.hasAttribute(`tangent`)===!1&&this.setAttribute(`tangent`,new q(new Float32Array(4*n.count),4));let a=this.getAttribute(`tangent`),o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new U,s[e]=new U;let c=new U,l=new U,u=new U,d=new V,f=new V,p=new V,m=new U,h=new U;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new U,y=new U,b=new U,x=new U;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0)n=new q(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new U,i=new U,a=new U,o=new U,s=new U,c=new U,l=new U,u=new U;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Cs.fromBufferAttribute(e,t),Cs.normalize(),e.setXYZ(t,Cs.x,Cs.y,Cs.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new q(a,r,i)}if(this.index===null)return z(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.type,this.name!==``&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:`dispose`})}},ws=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e===void 0?0:e.length/t,this.usage=Ni,this.updateRanges=[],this.version=0,this.uuid=Qi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let r=0,i=this.stride;r<i;r++)this.array[e+r]=t.array[n+r];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Qi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Qi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},Ts=new U,Es=class e{constructor(e,t,n,r=!1){this.isInterleavedBufferAttribute=!0,this.name=``,this.data=e,this.itemSize=t,this.offset=n,this.normalized=r}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)Ts.fromBufferAttribute(this,t),Ts.applyMatrix4(e),this.setXYZ(t,Ts.x,Ts.y,Ts.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ts.fromBufferAttribute(this,t),Ts.applyNormalMatrix(e),this.setXYZ(t,Ts.x,Ts.y,Ts.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ts.fromBufferAttribute(this,t),Ts.transformDirection(e),this.setXYZ(t,Ts.x,Ts.y,Ts.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=va(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ya(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=ya(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=ya(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=ya(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=ya(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=va(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=va(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=va(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=va(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array),r=ya(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=ya(t,this.array),n=ya(n,this.array),r=ya(r,this.array),i=ya(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this.data.array[e+3]=i,this}clone(t){if(t===void 0){Hi(`InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new q(new this.array.constructor(e),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new e(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){Hi(`InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},Ds=0,Os=class extends qi{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Ds++}),this.uuid=Qi(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new K(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Mi,this.stencilZFail=Mi,this.stencilZPass=Mi,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){z(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){z(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},ks=new U,As=new U,js=new U,Ms=new U,Ns=new U,Ps=new U,Fs=new U,Is=class{constructor(e=new U,t=new U(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,ks)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=ks.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(ks.copy(this.origin).addScaledVector(this.direction,t),ks.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){As.copy(e).add(t).multiplyScalar(.5),js.copy(t).sub(e).normalize(),Ms.copy(this.origin).sub(As);let i=e.distanceTo(t)*.5,a=-this.direction.dot(js),o=Ms.dot(this.direction),s=-Ms.dot(js),c=Ms.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0)if(u=a*s-o,d=a*o-s,p=i*l,u>=0)if(d>=-p)if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c);else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(As).addScaledVector(js,d),f}intersectSphere(e,t){ks.subVectors(e.center,this.origin);let n=ks.dot(this.direction),r=ks.dot(ks)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,ks)!==null}intersectTriangle(e,t,n,r,i){Ns.subVectors(t,e),Ps.subVectors(n,e),Fs.crossVectors(Ns,Ps);let a=this.direction.dot(Fs),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Ms.subVectors(this.origin,e);let s=o*this.direction.dot(Ps.crossVectors(Ms,Ps));if(s<0)return null;let c=o*this.direction.dot(Ns.cross(Ms));if(c<0||s+c>a)return null;let l=-o*Ms.dot(Fs);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Ls=class extends Os{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new K(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Qa,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Rs=new G,zs=new Is,Bs=new gs,Vs=new U,Hs=new U,Us=new U,Ws=new U,Gs=new U,Ks=new U,qs=new U,Js=new U,Ys=class extends go{constructor(e=new J,t=new Ls){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){Ks.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(Gs.fromBufferAttribute(s,e),a?Ks.addScaledVector(Gs,r):Ks.addScaledVector(Gs.sub(t),r))}t.add(Ks)}return t}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Bs.copy(n.boundingSphere),Bs.applyMatrix4(i),zs.copy(e.ray).recast(e.near),!(Bs.containsPoint(zs.origin)===!1&&(zs.intersectSphere(Bs,Vs)===null||zs.origin.distanceToSquared(Vs)>(e.far-e.near)**2))&&(Rs.copy(i).invert(),zs.copy(e.ray).applyMatrix4(Rs),!(n.boundingBox!==null&&zs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,zs)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null)if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=Zs(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=Zs(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}else if(s!==void 0)if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=Zs(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=Zs(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}};function Xs(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;Js.copy(s),Js.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(Js);return l<n.near||l>n.far?null:{distance:l,point:Js.clone(),object:e}}function Zs(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,Hs),e.getVertexPosition(c,Us),e.getVertexPosition(l,Ws);let u=Xs(e,t,n,r,Hs,Us,Ws,qs);if(u){let e=new U;Bo.getBarycoord(qs,Hs,Us,Ws,e),i&&(u.uv=Bo.getInterpolatedAttribute(i,s,c,l,e,new V)),a&&(u.uv1=Bo.getInterpolatedAttribute(a,s,c,l,e,new V)),o&&(u.normal=Bo.getInterpolatedAttribute(o,s,c,l,e,new U),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new U,materialIndex:0};Bo.getNormal(Hs,Us,Ws,t.normal),u.face=t,u.barycoord=e}return u}var Qs=new Ra,$s=new Ra,ec=new Ra,tc=new Ra,nc=new G,rc=new U,ic=new gs,ac=new G,oc=new Is,sc=class extends Ys{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type=`SkinnedMesh`,this.bindMode=$n,this.bindMatrix=new G,this.bindMatrixInverse=new G,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Vo),this.boundingBox.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,rc),this.boundingBox.expandByPoint(rc)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new gs),this.boundingSphere.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,rc),this.boundingSphere.expandByPoint(rc)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){let n=this.material,r=this.matrixWorld;n!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),ic.copy(this.boundingSphere),ic.applyMatrix4(r),e.ray.intersectsSphere(ic)!==!1&&(ac.copy(r).invert(),oc.copy(e.ray).applyMatrix4(ac),!(this.boundingBox!==null&&oc.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,oc)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let e=new Ra,t=this.geometry.attributes.skinWeight;for(let n=0,r=t.count;n<r;n++){e.fromBufferAttribute(t,n);let r=1/e.manhattanLength();r===1/0?e.set(1,0,0,0):e.multiplyScalar(r),t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===`attached`?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===`detached`?this.bindMatrixInverse.copy(this.bindMatrix).invert():z(`SkinnedMesh: Unrecognized bindMode: `+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,r=this.geometry;$s.fromBufferAttribute(r.attributes.skinIndex,e),ec.fromBufferAttribute(r.attributes.skinWeight,e),t.isVector4?(Qs.copy(t),t.set(0,0,0,0)):(Qs.set(...t,1),t.set(0,0,0)),Qs.applyMatrix4(this.bindMatrix);for(let e=0;e<4;e++){let r=ec.getComponent(e);if(r!==0){let i=$s.getComponent(e);nc.multiplyMatrices(n.bones[i].matrixWorld,n.boneInverses[i]),t.addScaledVector(tc.copy(Qs).applyMatrix4(nc),r)}}return t.isVector4&&(t.w=Qs.w),t.applyMatrix4(this.bindMatrixInverse)}},cc=class extends go{constructor(){super(),this.isBone=!0,this.type=`Bone`}},lc=class extends La{constructor(e=null,t=1,n=1,r,i,a,o,s,c=rr,l=rr,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},uc=new G,dc=new G,fc=class e{constructor(e=[],t=[]){this.uuid=Qi(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.previousBoneMatrices=null,this.boneTexture=null,this.init()}init(){let e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){z(`Skeleton: Number of inverse bone matrices does not match amount of bones.`),this.boneInverses=[];for(let e=0,t=this.bones.length;e<t;e++)this.boneInverses.push(new G)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let t=new G;this.bones[e]&&t.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(t)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){let t=this.bones[e];t&&t.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){let t=this.bones[e];t&&(t.parent&&t.parent.isBone?(t.matrix.copy(t.parent.matrixWorld).invert(),t.matrix.multiply(t.matrixWorld)):t.matrix.copy(t.matrixWorld),t.matrix.decompose(t.position,t.quaternion,t.scale))}}update(){let e=this.bones,t=this.boneInverses,n=this.boneMatrices,r=this.boneTexture;for(let r=0,i=e.length;r<i;r++){let i=e[r]?e[r].matrixWorld:dc;uc.multiplyMatrices(i,t[r]),uc.toArray(n,r*16)}r!==null&&(r.needsUpdate=!0)}clone(){return new e(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4);t.set(this.boneMatrices);let n=new lc(t,e,e,wr,hr);return n.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=n,this}getBoneByName(e){for(let t=0,n=this.bones.length;t<n;t++){let n=this.bones[t];if(n.name===e)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,r=e.bones.length;n<r;n++){let r=e.bones[n],i=t[r];i===void 0&&(z(`Skeleton: No bone found with UUID:`,r),i=new cc),this.bones.push(i),this.boneInverses.push(new G().fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){let e={metadata:{version:4.7,type:`Skeleton`,generator:`Skeleton.toJSON`},bones:[],boneInverses:[]};e.uuid=this.uuid;let t=this.bones,n=this.boneInverses;for(let r=0,i=t.length;r<i;r++){let i=t[r];e.bones.push(i.uuid);let a=n[r];e.boneInverses.push(a.toArray())}return e}},pc=class extends q{constructor(e,t,n,r=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},mc=new G,hc=new G,gc=[],_c=new Vo,vc=new G,yc=new Ys,bc=new gs,xc=class extends Ys{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new pc(new Float32Array(n*16),16),this.previousInstanceMatrix=null,this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let e=0;e<n;e++)this.setMatrixAt(e,vc)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Vo),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,mc),_c.copy(e.boundingBox).applyMatrix4(mc),this.boundingBox.union(_c)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new gs),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,mc),bc.copy(e.boundingSphere).applyMatrix4(mc),this.boundingSphere.union(bc)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.previousInstanceMatrix!==null&&(this.previousInstanceMatrix=e.previousInstanceMatrix.clone()),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){return this.instanceColor===null?t.setRGB(1,1,1):t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){return t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){let n=t.morphTargetInfluences,r=this.morphTexture.source.data.data,i=e*(n.length+1)+1;for(let e=0;e<n.length;e++)n[e]=r[i+e]}raycast(e,t){let n=this.matrixWorld,r=this.count;if(yc.geometry=this.geometry,yc.material=this.material,yc.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),bc.copy(this.boundingSphere),bc.applyMatrix4(n),e.ray.intersectsSphere(bc)!==!1))for(let i=0;i<r;i++){this.getMatrixAt(i,mc),hc.multiplyMatrices(n,mc),yc.matrixWorld=hc,yc.raycast(e,gc);for(let e=0,n=gc.length;e<n;e++){let n=gc[e];n.instanceId=i,n.object=this,t.push(n)}gc.length=0}}setColorAt(e,t){return this.instanceColor===null&&(this.instanceColor=new pc(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3),this}setMatrixAt(e,t){return t.toArray(this.instanceMatrix.array,e*16),this}setMorphAt(e,t){let n=t.morphTargetInfluences,r=n.length+1;this.morphTexture===null&&(this.morphTexture=new lc(new Float32Array(r*this.count),r,this.count,Dr,hr));let i=this.morphTexture.source.data.data,a=0;for(let e=0;e<n.length;e++)a+=n[e];let o=this.geometry.morphTargetsRelative?1:1-a,s=r*e;return i[s]=o,i.set(n,s+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:`dispose`}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}},Sc=new U,Cc=new U,wc=new W,Tc=class{constructor(e=new U(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=Sc.subVectors(n,t).cross(Cc.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(Sc),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||wc.getNormalMatrix(e),r=this.coplanarPoint(Sc).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Ec=new gs,Dc=new V(.5,.5),Oc=new U,kc=class{constructor(e=new Tc,t=new Tc,n=new Tc,r=new Tc,i=new Tc,a=new Tc){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Fi,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Ec.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Ec.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ec)}intersectsSprite(e){return Ec.center.set(0,0,0),Ec.radius=.7071067811865476+Dc.distanceTo(e.center),Ec.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ec)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(Oc.x=r.normal.x>0?e.max.x:e.min.x,Oc.y=r.normal.y>0?e.max.y:e.min.y,Oc.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Oc)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Ac=class extends Os{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new K(16777215),this.map=null,this.linewidth=1,this.linecap=`round`,this.linejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},jc=new U,Mc=new U,Nc=new G,Pc=new Is,Fc=new gs,Ic=new U,Lc=new U,Rc=class extends go{constructor(e=new J,t=new Ac){super(),this.isLine=!0,this.type=`Line`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let e=1,r=t.count;e<r;e++)jc.fromBufferAttribute(t,e-1),Mc.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=jc.distanceTo(Mc);e.setAttribute(`lineDistance`,new fs(n,1))}else z(`Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Line.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Fc.copy(n.boundingSphere),Fc.applyMatrix4(r),Fc.radius+=i,e.ray.intersectsSphere(Fc)===!1)return;Nc.copy(r).invert(),Pc.copy(e.ray).applyMatrix4(Nc);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=this.isLineSegments?2:1,l=n.index,u=n.attributes.position;if(l!==null){let n=Math.max(0,a.start),r=Math.min(l.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=l.getX(i),r=l.getX(i+1),a=zc(this,e,Pc,s,n,r,i);a&&t.push(a)}if(this.isLineLoop){let i=l.getX(r-1),a=l.getX(n),o=zc(this,e,Pc,s,i,a,r-1);o&&t.push(o)}}else{let n=Math.max(0,a.start),r=Math.min(u.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=zc(this,e,Pc,s,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){let i=zc(this,e,Pc,s,r-1,n,r-1);i&&t.push(i)}}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function zc(e,t,n,r,i,a,o){let s=e.geometry.attributes.position;if(jc.fromBufferAttribute(s,i),Mc.fromBufferAttribute(s,a),n.distanceSqToSegment(jc,Mc,Ic,Lc)>r)return;Ic.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(Ic);if(!(c<t.near||c>t.far))return{distance:c,point:Lc.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var Bc=new U,Vc=new U,Hc=class extends Rc{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type=`LineSegments`}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let e=0,r=t.count;e<r;e+=2)Bc.fromBufferAttribute(t,e),Vc.fromBufferAttribute(t,e+1),n[e]=e===0?0:n[e-1],n[e+1]=n[e]+Bc.distanceTo(Vc);e.setAttribute(`lineDistance`,new fs(n,1))}else z(`LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}},Uc=class extends Rc{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type=`LineLoop`}},Wc=class extends Os{constructor(e){super(),this.isPointsMaterial=!0,this.type=`PointsMaterial`,this.color=new K(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Gc=new G,Kc=new Is,qc=new gs,Jc=new U,Yc=class extends go{constructor(e=new J,t=new Wc){super(),this.isPoints=!0,this.type=`Points`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Points.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),qc.copy(n.boundingSphere),qc.applyMatrix4(r),qc.radius+=i,e.ray.intersectsSphere(qc)===!1)return;Gc.copy(r).invert(),Kc.copy(e.ray).applyMatrix4(Gc);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=n.index,l=n.attributes.position;if(c!==null){let n=Math.max(0,a.start),i=Math.min(c.count,a.start+a.count);for(let a=n,o=i;a<o;a++){let n=c.getX(a);Jc.fromBufferAttribute(l,n),Xc(Jc,n,s,r,e,t,this)}}else{let n=Math.max(0,a.start),i=Math.min(l.count,a.start+a.count);for(let a=n,o=i;a<o;a++)Jc.fromBufferAttribute(l,a),Xc(Jc,a,s,r,e,t,this)}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function Xc(e,t,n,r,i,a,o){let s=Kc.distanceSqToPoint(e);if(s<n){let n=new U;Kc.closestPointToPoint(e,n),n.applyMatrix4(r);let c=i.ray.origin.distanceTo(n);if(c<i.near||c>i.far)return;a.push({distance:c,distanceToRay:Math.sqrt(s),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}var Zc=class extends La{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},Qc=class extends La{constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isCanvasTexture=!0,this.needsUpdate=!0}},$c=class extends La{constructor(e,t,n=mr,r,i,a,o=rr,s=rr,c,l=Tr,u=1){if(l!==1026&&l!==1027)throw Error(`DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Na(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},el=class extends $c{constructor(e,t=mr,n=301,r,i,a=rr,o=rr,s,c=Tr){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},tl=class extends La{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},nl=class e extends J{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new fs(c,3)),this.setAttribute(`normal`,new fs(l,3)),this.setAttribute(`uv`,new fs(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new U;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}},rl=class e extends J{constructor(e=1,t=1,n=4,r=8,i=1){super(),this.type=`CapsuleGeometry`,this.parameters={radius:e,height:t,capSegments:n,radialSegments:r,heightSegments:i},t=Math.max(0,t),n=Math.max(1,Math.floor(n)),r=Math.max(3,Math.floor(r)),i=Math.max(1,Math.floor(i));let a=[],o=[],s=[],c=[],l=t/2,u=Math.PI/2*e,d=t,f=2*u+d,p=n*2+i,m=r+1,h=new U,g=new U;for(let _=0;_<=p;_++){let v=0,y=0,b=0,x=0;if(_<=n){let t=_/n,r=t*Math.PI/2;y=-l-e*Math.cos(r),b=e*Math.sin(r),x=-e*Math.cos(r),v=t*u}else if(_<=n+i){let r=(_-n)/i;y=-l+r*t,b=e,x=0,v=u+r*d}else{let t=(_-n-i)/n,r=t*Math.PI/2;y=l+e*Math.sin(r),b=e*Math.cos(r),x=e*Math.sin(r),v=u+d+t*u}let S=Math.max(0,Math.min(1,v/f)),C=0;_===0?C=.5/r:_===p&&(C=-.5/r);for(let e=0;e<=r;e++){let t=e/r,n=t*Math.PI*2,i=Math.sin(n),a=Math.cos(n);g.x=-b*a,g.y=y,g.z=b*i,o.push(g.x,g.y,g.z),h.set(-b*a,x,b*i),h.normalize(),s.push(h.x,h.y,h.z),c.push(t+C,S)}if(_>0){let e=(_-1)*m;for(let t=0;t<r;t++){let n=e+t,r=e+t+1,i=_*m+t,o=_*m+t+1;a.push(n,r,i),a.push(r,o,i)}}}this.setIndex(a),this.setAttribute(`position`,new fs(o,3)),this.setAttribute(`normal`,new fs(s,3)),this.setAttribute(`uv`,new fs(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radius,t.height,t.capSegments,t.radialSegments,t.heightSegments)}},il=class e extends J{constructor(e=1,t=1,n=1,r=32,i=1,a=!1,o=0,s=Math.PI*2){super(),this.type=`CylinderGeometry`,this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:r,heightSegments:i,openEnded:a,thetaStart:o,thetaLength:s};let c=this;r=Math.floor(r),i=Math.floor(i);let l=[],u=[],d=[],f=[],p=0,m=[],h=n/2,g=0;_(),a===!1&&(e>0&&v(!0),t>0&&v(!1)),this.setIndex(l),this.setAttribute(`position`,new fs(u,3)),this.setAttribute(`normal`,new fs(d,3)),this.setAttribute(`uv`,new fs(f,2));function _(){let a=new U,_=new U,v=0,y=(t-e)/n;for(let c=0;c<=i;c++){let l=[],g=c/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){let t=e/r,i=t*s+o,c=Math.sin(i),m=Math.cos(i);_.x=v*c,_.y=-g*n+h,_.z=v*m,u.push(_.x,_.y,_.z),a.set(c,y,m).normalize(),d.push(a.x,a.y,a.z),f.push(t,1-g),l.push(p++)}m.push(l)}for(let n=0;n<r;n++)for(let r=0;r<i;r++){let a=m[r][n],o=m[r+1][n],s=m[r+1][n+1],c=m[r][n+1];(e>0||r!==0)&&(l.push(a,o,c),v+=3),(t>0||r!==i-1)&&(l.push(o,s,c),v+=3)}c.addGroup(g,v,0),g+=v}function v(n){let i=p,a=new V,m=new U,_=0,v=n===!0?e:t,y=n===!0?1:-1;for(let e=1;e<=r;e++)u.push(0,h*y,0),d.push(0,y,0),f.push(.5,.5),p++;let b=p;for(let e=0;e<=r;e++){let t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=v*i,m.y=h*y,m.z=v*n,u.push(m.x,m.y,m.z),d.push(0,y,0),a.x=n*.5+.5,a.y=i*.5*y+.5,f.push(a.x,a.y),p++}for(let e=0;e<r;e++){let t=i+e,r=b+e;n===!0?l.push(r,r+1,t):l.push(r+1,r,t),_+=3}c.addGroup(g,_,n===!0?1:2),g+=_}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},al=class e extends il{constructor(e=1,t=1,n=32,r=1,i=!1,a=0,o=Math.PI*2){super(0,e,t,n,r,i,a,o),this.type=`ConeGeometry`,this.parameters={radius:e,height:t,radialSegments:n,heightSegments:r,openEnded:i,thetaStart:a,thetaLength:o}}static fromJSON(t){return new e(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},ol=class e extends J{constructor(e=[],t=[],n=1,r=0){super(),this.type=`PolyhedronGeometry`,this.parameters={vertices:e,indices:t,radius:n,detail:r};let i=[],a=[];o(r),c(n),l(),this.setAttribute(`position`,new fs(i,3)),this.setAttribute(`normal`,new fs(i.slice(),3)),this.setAttribute(`uv`,new fs(a,2)),r===0?this.computeVertexNormals():this.normalizeNormals();function o(e){let n=new U,r=new U,i=new U;for(let a=0;a<t.length;a+=3)f(t[a+0],n),f(t[a+1],r),f(t[a+2],i),s(n,r,i,e)}function s(e,t,n,r){let i=r+1,a=[];for(let r=0;r<=i;r++){a[r]=[];let o=e.clone().lerp(n,r/i),s=t.clone().lerp(n,r/i),c=i-r;for(let e=0;e<=c;e++)e===0&&r===i?a[r][e]=o:a[r][e]=o.clone().lerp(s,e/c)}for(let e=0;e<i;e++)for(let t=0;t<2*(i-e)-1;t++){let n=Math.floor(t/2);t%2==0?(d(a[e][n+1]),d(a[e+1][n]),d(a[e][n])):(d(a[e][n+1]),d(a[e+1][n+1]),d(a[e+1][n]))}}function c(e){let t=new U;for(let n=0;n<i.length;n+=3)t.x=i[n+0],t.y=i[n+1],t.z=i[n+2],t.normalize().multiplyScalar(e),i[n+0]=t.x,i[n+1]=t.y,i[n+2]=t.z}function l(){let e=new U;for(let t=0;t<i.length;t+=3){e.x=i[t+0],e.y=i[t+1],e.z=i[t+2];let n=h(e)/2/Math.PI+.5,r=g(e)/Math.PI+.5;a.push(n,1-r)}p(),u()}function u(){for(let e=0;e<a.length;e+=6){let t=a[e+0],n=a[e+2],r=a[e+4];Math.max(t,n,r)>.9&&Math.min(t,n,r)<.1&&(t<.2&&(a[e+0]+=1),n<.2&&(a[e+2]+=1),r<.2&&(a[e+4]+=1))}}function d(e){i.push(e.x,e.y,e.z)}function f(t,n){let r=t*3;n.x=e[r+0],n.y=e[r+1],n.z=e[r+2]}function p(){let e=new U,t=new U,n=new U,r=new U,o=new V,s=new V,c=new V;for(let l=0,u=0;l<i.length;l+=9,u+=6){e.set(i[l+0],i[l+1],i[l+2]),t.set(i[l+3],i[l+4],i[l+5]),n.set(i[l+6],i[l+7],i[l+8]),o.set(a[u+0],a[u+1]),s.set(a[u+2],a[u+3]),c.set(a[u+4],a[u+5]),r.copy(e).add(t).add(n).divideScalar(3);let d=h(r);m(o,u+0,e,d),m(s,u+2,t,d),m(c,u+4,n,d)}}function m(e,t,n,r){r<0&&e.x===1&&(a[t]=e.x-1),n.x===0&&n.z===0&&(a[t]=r/2/Math.PI+.5)}function h(e){return Math.atan2(e.z,-e.x)}function g(e){return Math.atan2(-e.y,Math.sqrt(e.x*e.x+e.z*e.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.vertices,t.indices,t.radius,t.detail)}},sl=class e extends ol{constructor(e=1,t=0){let n=(1+Math.sqrt(5))/2,r=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1];super(r,[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],e,t),this.type=`IcosahedronGeometry`,this.parameters={radius:e,detail:t}}static fromJSON(t){return new e(t.radius,t.detail)}},cl=class e extends J{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new fs(p,3)),this.setAttribute(`normal`,new fs(m,3)),this.setAttribute(`uv`,new fs(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}},ll=class e extends J{constructor(e=1,t=32,n=16,r=0,i=Math.PI*2,a=0,o=Math.PI){super(),this.type=`SphereGeometry`,this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:r,phiLength:i,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));let s=Math.min(a+o,Math.PI),c=0,l=[],u=new U,d=new U,f=[],p=[],m=[],h=[];for(let f=0;f<=n;f++){let g=[],_=f/n,v=0;f===0&&a===0?v=.5/t:f===n&&s===Math.PI&&(v=-.5/t);for(let n=0;n<=t;n++){let s=n/t;u.x=-e*Math.cos(r+s*i)*Math.sin(a+_*o),u.y=e*Math.cos(a+_*o),u.z=e*Math.sin(r+s*i)*Math.sin(a+_*o),p.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),h.push(s+v,1-_),g.push(c++)}l.push(g)}for(let e=0;e<n;e++)for(let r=0;r<t;r++){let t=l[e][r+1],i=l[e][r],o=l[e+1][r],c=l[e+1][r+1];(e!==0||a>0)&&f.push(t,i,c),(e!==n-1||s<Math.PI)&&f.push(i,o,c)}this.setIndex(f),this.setAttribute(`position`,new fs(p,3)),this.setAttribute(`normal`,new fs(m,3)),this.setAttribute(`uv`,new fs(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}};function ul(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(fl(i))i.isRenderTargetTexture?(z(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone();else if(Array.isArray(i))if(fl(i[0])){let e=[];for(let t=0,n=i.length;t<n;t++)e[t]=i[t].clone();t[n][r]=e}else t[n][r]=i.slice();else t[n][r]=i}}return t}function dl(e){let t={};for(let n=0;n<e.length;n++){let r=ul(e[n]);for(let e in r)t[e]=r[e]}return t}function fl(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function pl(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function ml(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:Da.workingColorSpace}var hl={clone:ul,merge:dl},gl=`void main() {
4
4
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
5
5
  }`,_l=`void main() {
6
6
  gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
@@ -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 km(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 Am(e){let t;try{t=await bm(()=>Promise.resolve().then(()=>QB),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 Tm(),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 km(t):e.scene,...e.save||r?{saveScene:async(t,n)=>{if(n)return a(n,t);if(e.save)return void await e.save(t);let i=Em(r,e.scene);if(i)return a(i,t);throw Error(Dm(r,e.scene))}}:{},scenes:async()=>{let e=await Tm();if(!e)throw Error(Om);return e},createScene:async e=>{let t=await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})});if(t.status===404)throw Error(Om);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 jm(async()=>{n?.dispose(),n=null,await e.play(r,i)},`starting the game…`)},...e.exit?{onExit:()=>jm(async()=>{n?.dispose(),n=null,await e.exit?.()},`back to the game…`)}:{}})}async function jm(e,t=``){let n=Sm(t);await Cm();try{await e()}finally{await Cm(0),n.lift()}}function Mm(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 Nm(e,t=Pm){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 Pm(e,t){console.error(`[incanto] teardown: ${e} failed (continuing)`,t)}var Fm=new kc,Im=new G,Lm=new gs;function Rm(e,t,n){return Im.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Fm.setFromProjectionMatrix(Im),Lm.center.set(t.x,t.y,t.z),Lm.radius=n,Fm.intersectsSphere(Lm)}function zm(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 Bm(e){return .55+Math.min(Math.max(e,0),12)/12*.45}function Vm(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 Hm(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 Um(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 Wm(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 Gm(e,t,n){let r=0;for(let i of n)r+=Wm(e,t,i);return r}function Km(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 qm=`
4111
+ It also validates every scene you save, before the page reloads into a broken one.`;async function km(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 Am(e){let t;try{t=await bm(()=>Promise.resolve().then(()=>ZB),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 Tm(),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 km(t):e.scene,...e.save||r?{saveScene:async(t,n)=>{if(n)return a(n,t);if(e.save)return void await e.save(t);let i=Em(r,e.scene);if(i)return a(i,t);throw Error(Dm(r,e.scene))}}:{},scenes:async()=>{let e=await Tm();if(!e)throw Error(Om);return e},createScene:async e=>{let t=await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})});if(t.status===404)throw Error(Om);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 jm(async()=>{n?.dispose(),n=null,await e.play(r,i)},`starting the game…`)},...e.exit?{onExit:()=>jm(async()=>{n?.dispose(),n=null,await e.exit?.()},`back to the game…`)}:{}})}async function jm(e,t=``){let n=Sm(t);await Cm();try{await e()}finally{await Cm(0),n.lift()}}function Mm(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 Nm(e,t=Pm){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 Pm(e,t){console.error(`[incanto] teardown: ${e} failed (continuing)`,t)}var Fm=new kc,Im=new G,Lm=new gs;function Rm(e,t,n){return Im.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Fm.setFromProjectionMatrix(Im),Lm.center.set(t.x,t.y,t.z),Lm.radius=n,Fm.intersectsSphere(Lm)}function zm(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 Bm(e){return .55+Math.min(Math.max(e,0),12)/12*.45}function Vm(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 Hm(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 Um(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 Wm(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 Gm(e,t,n){let r=0;for(let i of n)r+=Wm(e,t,i);return r}function Km(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 qm=`
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}),Zg=9.81,Qg=6,$g=.15,e_=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+=Zg*(1+this.stiffness*(r/Math.max(this.draft,$g)));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),Qg*Zg)*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 _g))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=t_(this.node.getRoot()),this.surface}};function t_(e){if(e instanceof _g)return e;for(let t of e.children){let e=t_(t);if(e)return e}return null}function n_(e){return Array.isArray(e.position)}function r_(e){let t=e.node;if(!n_(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 i_(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 a_(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 o_(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t)}function s_(e){let t=o_(e);return t===0?e.map(()=>0):e.map(e=>e/t)}function c_(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 l_(e,t){let n=Math.min(Math.max(e,0),.99);return n<=0?1:1-n**(t*60)}var u_=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||!n_(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 r_(this)}update(e){let t=this.moveParent?this.node.parent:this.node;if(!t||!n_(t))return;let n=this.node.getNodeOrNull(this.target);if(!n||!n_(n))return;let r=i_(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}=c_(t.position,n.position,Math.max(0,i));t.position=a}},d_=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}},f_=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)}},p_=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 m_(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 h_=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(){m_(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=g_(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 g_(e){let t=[e];for(;t.length>0;){let e=t.shift();if(e.behavior instanceof p_)return{health:e.behavior,owner:e};t.push(...e.children)}for(let t=e.parent;t;t=t.parent)if(t.behavior instanceof p_)return{health:t.behavior,owner:t};return null}var __=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=v_(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 v_(e){return e<5||e>=20?`night`:e<7.5?`dawn`:e<17.5?`day`:`dusk`}var y_=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`});r_(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(!n_(t))return;let n=t.getNodeOrNull(this.target);if(!n||!n_(n))return;let r=a_(n.position,this.offset);if(!(this.deadzone>0&&i_(t.position,r)<=this.deadzone)){let n=l_(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 b_(e){let t=e.scene?.source;t&&(e.timeScale=1,e.setScene(An(He(t))))}function x_(e,t,n){let r=n?.fadeSeconds??.4,i=()=>{e.timeScale=1,e.setScene(An(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 S_=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(),b_(this.engine)}goToScene(e,t){this.thaw(),x_(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 C_(e){return Array.isArray(e.position)}function w_(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 T_=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)||!C_(this.node))return;let t=this.node.position,n=null,r=1/0,i=this.node.tree?.getNodesInGroup(this.actorGroup)??E_(this.node.getRoot(),this.actorGroup);for(let e of i){if(!C_(e))continue;let i=w_(t,e.position);i<=this.range&&i<r&&(n=e,r=i)}n&&this.emit(`interacted`,n)}};function E_(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 D_=.28,O_=class extends et{static props={falloff:{default:D_}};falloff=D_;magnitude=0;t=0;prev=[];shake(e,t){this.magnitude=Math.max(this.magnitude,e),this.t=t??this.falloff}update(e){let t=r_(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}},k_=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()))}},A_=[`linear`,`easeIn`,`easeOut`,`easeInOut`];function j_(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 M_=class extends et{static props={to:{default:[]},duration:{default:1},ease:{default:`easeInOut`,options:[...A_]},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(!A_.includes(this.ease))throw new N(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "ease" must be one of [${A_.join(`, `)}], got '${this.ease}'.`,{prop:`ease`});let e=r_(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=j_(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`))}},N_=[`x`,`y`,`z`],P_=[`position`,`rotation`,`scale`],F_={x:0,y:1,z:2},I_=class extends et{static props={axis:{default:`y`,options:[...N_]},amplitude:{default:1},frequency:{default:1},mode:{default:`position`,options:[...P_]}};static signals=[];axis=`y`;amplitude=1;frequency=1;mode=`position`;base=0;time=0;onReady(){if(!N_.includes(this.axis))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "axis" must be one of [${N_.join(`, `)}], got '${this.axis}'.`,{prop:`axis`});if(!P_.includes(this.mode))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "mode" must be one of [${P_.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[F_[this.axis]]??0}writeChannel(e){if(this.isScalarRotation()){this.node.rotation=e;return}let t=[...this.node[this.mode]];t[F_[this.axis]]=e,this.node[this.mode]=t}},L_=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=r_(this),n=this.speed*e;for(;n>0&&this.index<this.waypoints.length;){let e=this.waypoints[this.index],r=c_(t.position,e,n),i=R_(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 R_(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 z_=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`});r_(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}=c_(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)}},B_=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(){m_(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())}},V_=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=r_(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 s_(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 s_([-Math.sin(t)*Math.cos(n),Math.sin(n),-Math.cos(t)*Math.cos(n)])}return[1,0]}},H_=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)}},U_=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=Wn(e),r=t?.at;return r&&r.length>0&&n_(n)&&(n.position=a_(n_(this.behavior.node)?this.behavior.node.position:[],r)),typeof n.visible==`boolean`&&(n.visible=!0),(t?.parent??this.behavior.node).addChild(n),n}},W_={CameraShake:O_,DayNight:__,GameFlow:S_,PathFollow:L_,Health:p_,Lifetime:k_,ScoreKeeper:H_,Pickup:B_,Collector:f_,DamageOnContact:h_,Interactable:T_,Clickable:d_,FollowCamera:y_,Patrol:z_,Chase:u_,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=r_(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}=c_(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(i_(t,this.origin)<=this.radius){this.goal=t;return}}this.goal=t.map((e,n)=>{let r=this.origin[n]??0,i=i_(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&&n_(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||!n_(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 r_(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&&n_(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}=c_(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 i_(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&&n_(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:M_,Oscillate:I_,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 U_(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 U_(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:V_,Buoyancy:e_};function G_(e){let t=e?.replace??!0;for(let[e,n]of Object.entries(W_))it(e,n,{replace:t})}function K_(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 q_=class extends Nt{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 _t(this.orderGroup,this.renderOrder,this.tree?.engine?.orderGroups)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new go}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-ba.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}},J_=class extends q_{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){K_(e.collider,e.name)}_physics=null},Y_=class extends J_{static typeName=`StaticBody2D`},X_=class extends J_{static typeName=`Area2D`},Z_=class extends J_{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]},Q_=class extends J_{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}},$_=new Set;function ev(e){return $_.add(e),()=>$_.delete(e)}function tv(e,t){return[...$_].filter(n=>n.dimension===e&&(t===void 0||n.engine===t))}var nv=class extends q_{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 J_))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 J_))throw new N(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},Z=100,rv=Math.PI/180;async function iv(e,t){let n=await bm(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await n.init({}),new av(n,e,t)}var av=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=ev(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]=fv(e);e.position=[n.x*Z-t,n.y*Z-r]}if(e instanceof Z_){e.fixedRotation||(e.rotation=t.body.rotation()/rv);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]=dv(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*rv);let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=dv(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+lv(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>uv(r)+cv))});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+lv(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&!(i.node instanceof Q_)){t.ground=i.node;let[e,n]=dv(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]=dv(e);t.body.setTranslation({x:n/Z,y:r/Z},!1),t.body.setRotation(e.rotation*rv,!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 J_&&(n?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof nv&&(t=!0);t&&(this.jointSet.clear(),ov(e.root,this.jointSet))}else this.bodySet.clear(),sv(e.root,this.bodySet),this.jointSet.clear(),ov(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]=dv(e),a=r/Z,o=i/Z,s;s=e instanceof Z_?n.RigidBodyDesc.dynamic():e instanceof Q_||e instanceof X_?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),s.setTranslation(a,o).setRotation(e.rotation*rv),e instanceof Z_&&(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=pv(n,e.collider,e.name);l.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof X_&&l.setSensor(!0),e instanceof Z_&&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]=dv(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 Z_){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 ov(e,t){e instanceof nv&&t.add(e);for(let n of e.children)ov(n,t)}function sv(e,t){e instanceof J_&&t.add(e);for(let n of e.children)sv(n,t)}var cv=4;function lv(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 uv(e){let[,t]=dv(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 dv(e){let t=0,n=0;for(let r=e;r;r=r.parent)r instanceof q_&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function fv(e){let t=0,n=0;for(let r=e.parent;r;r=r.parent)r instanceof q_&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function pv(e,t,n){K_(t,n);let r=mv(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Z,(i[1]??0)/Z),r}function mv(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 hv=new cl(1,1),gv=class extends q_{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 Ys(hv,new Ls({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}},_v=class extends gv{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=vv(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 vv(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 yv=class extends q_{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 q_))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=bv(n,i+c,o-c),r=bv(r,a+l,s-l)}return{x:n,y:r}}};function bv(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var xv=class extends Nt{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 Q_))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 Q_))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))}},Sv=new cl(1,1),Cv=class extends q_{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 Ys(Sv,new Ls({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}},wv=new cl(1,1),Tv=class extends q_{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 Ys(wv,new Ls({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 Qc(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)}},Ev=new cl(1,1),Dv=class e extends q_{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`,...pn]},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`&&!pn.includes(t.preset))throw new N(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${pn.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:pn});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){mn(this,this.preset,qe(e.typeName));let t=this.tree?.engine?.rng??new P(4660);this.sim=new gn({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 Ls({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new xc(Ev,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(Pi),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let n=this.mesh,r=this.refreshPalette(),i=r?null:kv.set(this.colorStart),a=Av.set(this.colorEnd),o=this.shimmer,s=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;Ov.makeScale(t,t,1),Ov.setPosition(e.x,-e.y,0),n.setMatrixAt(s,Ov);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))),jv.copy(c).lerp(a,e.t).multiplyScalar(l),n.setColorAt(s,jv),s+=1}),n.count=s,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),n.renderOrder=this.effectiveRenderOrder}},Ov=new G,kv=new K,Av=new K,jv=new K;function Mv(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 Nv(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 Pv=class extends q_{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;Mv(t._cells,t._legend)}grid(){return Mv(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;Nv(this.grid(),new Set(this._solid)).forEach((t,n)=>{let r=new Y_(`__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 Ys(new J,new Ls({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=rr,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()}},Fv=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],Iv=class extends Nt{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:Fv}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new _o,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!Fv.includes(t))throw new N(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${Fv.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:Fv})}_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 Lv(){_n(),R(q_),R(gv),R(Cv),R(Dv),R(_v),R(yv),R(Tv),R(Iv),R(Y_),R(Z_),R(X_),R(Q_),R(xv),R(nv),R(Pv)}function Rv(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function zv(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}var Bv=new Vo,Vv=new U,Hv=12,Uv=new Float32Array(16);function Wv(e){if(!(e instanceof q_))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),Bv.setFromObject(t),Bv.getSize(Vv);let n,r,i,a;if(!Number.isFinite(Vv.x)||Vv.x===0&&Vv.y===0){let e=new U().setFromMatrixPosition(t.matrixWorld);n=e.x-Hv,i=e.x+Hv,r=e.y-Hv,a=e.y+Hv}else n=Bv.min.x-2,i=Bv.max.x+2,r=Bv.min.y-2,a=Bv.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return Uv.set(o),Uv}function Gv(){return{visited:new Set,cameras:[]}}function Kv(e,t,n,r,i,a,o){let s=a??Gv();s.visited.clear(),s.cameras.length=0,qv(e,t,n,!1,s.visited,s.cameras,r,i,o?.ignoreStatic===!0),Jv(t,s.visited),Jv(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 qv(e,t,n,r,i,a,o,s,c){let l=t,u=r;if(e instanceof q_&&!(e instanceof Iv)){let t=e._ensureObject2D();if(e.static&&!c&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof Iv){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 q_){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(o),i.add(n),e instanceof yv&&!r&&a.push(e),l=n}for(let t of e.children)qv(t,l,n,u,i,a,o,s,c);if(e instanceof q_&&!(e instanceof Iv)){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 Jv(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&&Jv(i,t)}}var Yv=class{viewOverride=null;webgl;worldScene=new Eo;syncScratch=Gv();ignoreStatic=!1;uiScene=new Eo;worldCam=new vu(-1,1,1,-1,-1e3,1e3);uiCam=new vu(-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 gm(void 0,this.engine);let t=vn(e.engine.scene?.environment,{antialias:!0,pixelRatio:1,preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,e);this.webgl=new hm({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 Hc(new J,new Ac({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 Hc(new J,new Ac({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?Wv(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 tv(`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(Zv);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:Tn(e.viewport),o=a?En(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r,{activeCamera:l}=Kv(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)),Xv(this.worldCam,u.x,u.y,s/d,c/d),Xv(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 zv(this.lastView,e,t)}screenFromWorld(e,t){return Rv(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;$v.set((e-i)/o*2-1,-((t-a)/s*2-1)),ey.setFromCamera($v,this.worldCam);let c=ey.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||(ty.makeEmpty(),ty.expandByObject(t),ty.isEmpty())||(ty.getSize(Qv),Qv.x===0&&Qv.y===0))return null;let n=this.screenFromWorld(ty.min.x,-ty.max.y),r=this.screenFromWorld(ty.max.x,-ty.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 Xv(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 Zv=new V,Qv=new U,$v=new V,ey=new qu,ty=new Vo;async function ny(e){Lv(),(e.gameplay??!0)&&G_();for(let[t,n]of Object.entries(e.behaviors??{}))it(t,n,{replace:!0});let t=new kt({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),n=ry(e.scene),r=An(ry(n),{resolveScene:e.resolveScene,engine:t});t.setScene(r);let i=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&iy(r.root))&&(i=await iv(t));let a=[],o=e.keyboard??(typeof window<`u`?window:!1);o&&t.input.attachKeyboard(o),a.push(ay(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=qn(t,n,r),o=t.sceneChanged.connect(()=>{i?.dispose(),i=qn(t,n,r)});a.push(()=>{o(),i?.dispose()})}}let c=e._rendererFactory?e._rendererFactory(t,e.canvas):new Yv({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??Am,r=async t=>{await ny({...e,scene:t})};await jm(async()=>{p();try{await t({scene:n,play:r,exit:()=>r(n),...d.save?{save:d.save}:{},...d.library?{library:d.library===!0?wm():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 bm(async()=>{let{attachDebugOverlay:e}=await import(`./debug-BgAq55oC.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(){Nm([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 ry(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 iy(e){if(e instanceof J_)return!0;for(let t of e.children)if(iy(t))return!0;return!1}function ay(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 Rt&&(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 oy(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 sy=e({createGame2D:()=>ny,enablePhysics2D:()=>iv}),cy=(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())}),ly=(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())}),uy=class extends go{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 dy(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 fy(e,t){return ly(this,null,function*(){return dy(e,t,yield e.parser.getDependency(`node`,t))})}function py(e){return ly(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=dy(e,r,t);i!=null&&n.set(r,i)}),n})}var my={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 hy(e){return Math.max(Math.min(e,1),0)}var gy=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(my));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(my));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=hy(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}}},_y={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},vy={_Color:_y.Color,_EmissionColor:_y.EmissionColor,_ShadeColor:_y.ShadeColor,_RimColor:_y.RimColor,_OutlineColor:_y.OutlineColor},yy=new K,by=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(yy.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}};by._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 xy=by,Sy=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)})}},Cy=new V,wy=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(Cy.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(Cy.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))})}};wy._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var Ty=wy,Ey=new Set([`1.0`,`1.0-beta`]),Dy=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return ly(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return ly(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return ly(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(!Ey.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(my)),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 gy;return yield Promise.all(Array.from(o.entries()).map(t=>ly(this,[t],function*([t,n]){var r,i,a;let o=new uy(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=>ly(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield fy(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 Sy({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=>ly(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new xy({material:t,type:e.type,targetValue:new K().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>ly(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new Ty({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 ly(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 gy,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>ly(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 uy(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>ly(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=>ly(this,null,function*(){let i=yield fy(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 Sy({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 Ty({material:t,scale:n,offset:r}));return}let n=vy[r];if(n){c.addBind(new xy({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})}};Dy.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 Oy=Dy,ky=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 sc(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 Gu?[]: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 Gu?[]: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 fc(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 _o;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}};ky.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,ky.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var Ay=ky,jy=new Set([`1.0`,`1.0-beta`]),My=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return ly(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 ly(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return ly(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(!jy.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield py(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 Ay(t,o)})}_v0Import(e,t){return ly(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 py(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 Ay(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},Ny=new U,Py=new U,Fy=new H,Iy=class extends _o{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new Xu(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(Ny,Fy,Py);let n=Ny.set(.1,.1,.1).divide(Py);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},Ly=`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(`.`),Ry={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 zy(e){return e.invert?e.invert():e.inverse(),e}var By=new U,Vy=new H,Hy=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&&(By.copy(r.position),Vy.copy(r.quaternion),e[n]={position:By.toArray(),rotation:Vy.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;By.set(0,0,0),Vy.identity();let i=this.restPose[n];i?.position&&By.fromArray(i.position).negate(),i?.rotation&&zy(Vy.fromArray(i.rotation)),By.add(r.position),Vy.premultiply(r.quaternion),e[n]={position:By.toArray(),rotation:Vy.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(By.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(Vy.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}},Uy=new U,Wy=new H,Gy=new U,Ky=class e extends Hy{static _setupTransforms(e){let t=new go;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};Ly.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,Uy),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new H;(o=s.parent)==null||o.matrixWorld.decompose(Uy,l,Uy),a[t]=l}});let o={};return Ly.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=Ry[a],a!=null);)s=n[a];let c=new go;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(){Ly.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=Wy.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(Gy);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},qy=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 Hy(e),this._normalizedHumanBones=new Ky(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new Hy(e.humanBones),this._normalizedHumanBones=new Ky(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()}},Jy={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`},Yy=new Set([`1.0`,`1.0-beta`]),Xy={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},Zy=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return ly(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return ly(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return ly(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(!Yy.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=>ly(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=Xy[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 qy(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new Iy(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return ly(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=>ly(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=Xy[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 qy(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new Iy(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(Jy).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},Qy=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}},$y=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}},eb=new H,tb=new H,nb=new U,rb=new U,ib=Math.sqrt(2)/2,ab=new H(0,0,-ib,ib),ob=new U(0,1,0),sb=class extends _o{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new Qy;e.radius=.5;let t=new Ls({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new Ys(e,t),this.add(this._meshPitch)}{let e=new Qy;e.radius=.5;let t=new Ls({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new Ys(e,t),this.add(this._meshYaw)}{let e=new $y;e.radius=.1;let t=new Ac({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new Hc(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=ba.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=ba.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(nb),this.vrmLookAt.getLookAtWorldQuaternion(eb),eb.multiply(this.vrmLookAt.getFaceFrontQuaternion(tb)),this._meshYaw.position.copy(nb),this._meshYaw.quaternion.copy(eb),this._meshPitch.position.copy(nb),this._meshPitch.quaternion.copy(eb),this._meshPitch.quaternion.multiply(tb.setFromAxisAngle(ob,t)),this._meshPitch.quaternion.multiply(ab);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(rb).sub(nb),this._lineTarget.geometry.tail.copy(rb),this._lineTarget.geometry.update(),this._lineTarget.position.copy(nb)),super.updateMatrixWorld(e)}},cb=new U,lb=new U;function ub(e,t){return e.matrixWorld.decompose(cb,t,lb),t}function db(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function fb(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var pb=new U(0,0,1),mb=new U,hb=new U,gb=new U,_b=new H,vb=new H,yb=new H,bb=new H,xb=new Qa,Sb=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 Qa)}getEuler(e){return e.set(ba.DEG2RAD*this._pitch,ba.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 ub(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(pb)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=db(this.faceFront);return xb.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(xb).premultiply(bb.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(vb),this.getFaceFrontQuaternion(yb),e.copy(pb).applyQuaternion(vb).applyQuaternion(yb).applyEuler(this.getEuler(xb))}lookAt(e){let t=_b.copy(this._restHeadWorldQuaternion).multiply(zy(this.getLookAtWorldQuaternion(vb))),n=this.getLookAtWorldPosition(hb),r=gb.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=db(this.faceFront),[o,s]=db(r),c=fb(o-i),l=fb(a-s);this._yaw=ba.RAD2DEG*c,this._pitch=ba.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(mb)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};Sb.EULER_ORDER=`YXZ`;var Cb=Sb,wb=new U(0,0,1),Tb=new H,Eb=new H,Db=new Qa(0,0,0,`YXZ`),Ob=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),ub(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),ub(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?Db.x=-ba.DEG2RAD*this.rangeMapVerticalDown.map(-t):Db.x=ba.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?Db.y=-ba.DEG2RAD*this.rangeMapHorizontalInner.map(-e):Db.y=ba.DEG2RAD*this.rangeMapHorizontalOuter.map(e),Tb.setFromEuler(Db),this._getWorldFaceFrontQuat(Eb),i.quaternion.copy(Eb).multiply(Tb).multiply(Eb.invert()),Tb.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(Tb).premultiply(Tb.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?Db.x=-ba.DEG2RAD*this.rangeMapVerticalDown.map(-t):Db.x=ba.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?Db.y=-ba.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):Db.y=ba.DEG2RAD*this.rangeMapHorizontalInner.map(e),Tb.setFromEuler(Db),this._getWorldFaceFrontQuat(Eb),a.quaternion.copy(Eb).multiply(Tb).multiply(Eb.invert()),Tb.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(Tb).premultiply(Tb.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=ba.RAD2DEG*e.y,n=ba.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(wb)<.01)return e.identity();let[t,n]=db(this.faceFront);return Db.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(Db)}};Ob.type=`bone`;var kb=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=ba.RAD2DEG*e.y,n=ba.RAD2DEG*e.x;this.applyYawPitch(t,n)}};kb.type=`expression`;var Ab=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*hy(e/this.inputMaxValue)}},jb=new Set([`1.0`,`1.0-beta`]),Mb=.01,Nb=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return ly(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 ly(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 ly(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(!jb.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 kb(n,s,c,l,u):new Ob(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<Mb&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=Mb),new Ab(n,r)}_v0Import(e,t,n){return ly(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 kb(n,a,o,s,c):new Ob(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 Ob&&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<Mb&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=Mb),new Ab(r,i)}_importLookAt(e,t){let n=new Cb(e,t);if(this.helperRoot){let e=new sb(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function Pb(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 Fb=new Set([`1.0`,`1.0-beta`]),Ib=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 ly(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return ly(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return ly(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(!Fb.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 ly(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 ly(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 Ql().loadAsync(Pb(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},Lb=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()}},Rb=class extends Lb{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)})}},zb=Object.defineProperty,Bb=Object.getOwnPropertySymbols,Vb=Object.prototype.hasOwnProperty,Hb=Object.prototype.propertyIsEnumerable,Ub=(e,t,n)=>t in e?zb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Wb=(e,t)=>{for(var n in t||={})Vb.call(t,n)&&Ub(e,n,t[n]);if(Bb)for(var n of Bb(t))Hb.call(t,n)&&Ub(e,n,t[n]);return e},Gb=(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 Kb(e,t){e.colorSpace=t}var qb=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 Gb(this,null,function*(){let r=Gb(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&&Kb(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return Gb(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},Jb=`// #define PHONG
5756
+ `,colorWrite:!1,depthWrite:!0,depthTest:!1,side:2}),Zg=9.81,Qg=6,$g=.15,e_=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+=Zg*(1+this.stiffness*(r/Math.max(this.draft,$g)));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),Qg*Zg)*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 _g))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=t_(this.node.getRoot()),this.surface}};function t_(e){if(e instanceof _g)return e;for(let t of e.children){let e=t_(t);if(e)return e}return null}function n_(e){return Array.isArray(e.position)}function r_(e){let t=e.node;if(!n_(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 i_(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 a_(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 o_(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t)}function s_(e){let t=o_(e);return t===0?e.map(()=>0):e.map(e=>e/t)}function c_(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 l_(e,t){let n=Math.min(Math.max(e,0),.99);return n<=0?1:1-n**(t*60)}var u_=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||!n_(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 r_(this)}update(e){let t=this.moveParent?this.node.parent:this.node;if(!t||!n_(t))return;let n=this.node.getNodeOrNull(this.target);if(!n||!n_(n))return;let r=i_(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}=c_(t.position,n.position,Math.max(0,i));t.position=a}},d_=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}},f_=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)}},p_=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 m_(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 h_=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(){m_(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=g_(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 g_(e){let t=[e];for(;t.length>0;){let e=t.shift();if(e.behavior instanceof p_)return{health:e.behavior,owner:e};t.push(...e.children)}for(let t=e.parent;t;t=t.parent)if(t.behavior instanceof p_)return{health:t.behavior,owner:t};return null}var __=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=v_(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 v_(e){return e<5||e>=20?`night`:e<7.5?`dawn`:e<17.5?`day`:`dusk`}var y_=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`});r_(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(!n_(t))return;let n=t.getNodeOrNull(this.target);if(!n||!n_(n))return;let r=a_(n.position,this.offset);if(!(this.deadzone>0&&i_(t.position,r)<=this.deadzone)){let n=l_(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 b_(e){let t=e.scene?.source;t&&(e.timeScale=1,e.setScene(An(He(t))))}function x_(e,t,n){let r=n?.fadeSeconds??.4,i=()=>{e.timeScale=1,e.setScene(An(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 S_=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(),b_(this.engine)}goToScene(e,t){this.thaw(),x_(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 C_(e){return Array.isArray(e.position)}function w_(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 T_=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)||!C_(this.node))return;let t=this.node.position,n=null,r=1/0,i=this.node.tree?.getNodesInGroup(this.actorGroup)??E_(this.node.getRoot(),this.actorGroup);for(let e of i){if(!C_(e))continue;let i=w_(t,e.position);i<=this.range&&i<r&&(n=e,r=i)}n&&this.emit(`interacted`,n)}};function E_(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 D_=.28,O_=class extends et{static props={falloff:{default:D_}};falloff=D_;magnitude=0;t=0;prev=[];shake(e,t){this.magnitude=Math.max(this.magnitude,e),this.t=t??this.falloff}update(e){let t=r_(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}},k_=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()))}},A_=[`linear`,`easeIn`,`easeOut`,`easeInOut`];function j_(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 M_=class extends et{static props={to:{default:[]},duration:{default:1},ease:{default:`easeInOut`,options:[...A_]},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(!A_.includes(this.ease))throw new N(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "ease" must be one of [${A_.join(`, `)}], got '${this.ease}'.`,{prop:`ease`});let e=r_(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=j_(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`))}},N_=[`x`,`y`,`z`],P_=[`position`,`rotation`,`scale`],F_={x:0,y:1,z:2},I_=class extends et{static props={axis:{default:`y`,options:[...N_]},amplitude:{default:1},frequency:{default:1},mode:{default:`position`,options:[...P_]}};static signals=[];axis=`y`;amplitude=1;frequency=1;mode=`position`;base=0;time=0;onReady(){if(!N_.includes(this.axis))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "axis" must be one of [${N_.join(`, `)}], got '${this.axis}'.`,{prop:`axis`});if(!P_.includes(this.mode))throw new N(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "mode" must be one of [${P_.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[F_[this.axis]]??0}writeChannel(e){if(this.isScalarRotation()){this.node.rotation=e;return}let t=[...this.node[this.mode]];t[F_[this.axis]]=e,this.node[this.mode]=t}},L_=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=r_(this),n=this.speed*e;for(;n>0&&this.index<this.waypoints.length;){let e=this.waypoints[this.index],r=c_(t.position,e,n),i=R_(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 R_(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 z_=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`});r_(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}=c_(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)}},B_=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(){m_(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())}},V_=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=r_(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 s_(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 s_([-Math.sin(t)*Math.cos(n),Math.sin(n),-Math.cos(t)*Math.cos(n)])}return[1,0]}},H_=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)}},U_=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=Wn(e),r=t?.at;return r&&r.length>0&&n_(n)&&(n.position=a_(n_(this.behavior.node)?this.behavior.node.position:[],r)),typeof n.visible==`boolean`&&(n.visible=!0),(t?.parent??this.behavior.node).addChild(n),n}},W_={CameraShake:O_,DayNight:__,GameFlow:S_,PathFollow:L_,Health:p_,Lifetime:k_,ScoreKeeper:H_,Pickup:B_,Collector:f_,DamageOnContact:h_,Interactable:T_,Clickable:d_,FollowCamera:y_,Patrol:z_,Chase:u_,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=r_(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}=c_(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(i_(t,this.origin)<=this.radius){this.goal=t;return}}this.goal=t.map((e,n)=>{let r=this.origin[n]??0,i=i_(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&&n_(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||!n_(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 r_(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&&n_(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}=c_(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 i_(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&&n_(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:M_,Oscillate:I_,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 U_(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 U_(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:V_,Buoyancy:e_};function G_(e){let t=e?.replace??!0;for(let[e,n]of Object.entries(W_))it(e,n,{replace:t})}function K_(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 q_=class extends Nt{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 _t(this.orderGroup,this.renderOrder,this.tree?.engine?.orderGroups)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new go}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-ba.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}},J_=class extends q_{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){K_(e.collider,e.name)}_physics=null},Y_=class extends J_{static typeName=`StaticBody2D`},X_=class extends J_{static typeName=`Area2D`},Z_=class extends J_{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]},Q_=class extends J_{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}},$_=new Set;function ev(e){return $_.add(e),()=>$_.delete(e)}function tv(e,t){return[...$_].filter(n=>n.dimension===e&&(t===void 0||n.engine===t))}var nv=class extends q_{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 J_))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 J_))throw new N(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},Z=100,rv=Math.PI/180;async function iv(e,t){let n=await bm(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await n.init({}),new av(n,e,t)}var av=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=ev(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]=fv(e);e.position=[n.x*Z-t,n.y*Z-r]}if(e instanceof Z_){e.fixedRotation||(e.rotation=t.body.rotation()/rv);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]=dv(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*rv);let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=dv(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+lv(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>uv(r)+cv))});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+lv(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&!(i.node instanceof Q_)){t.ground=i.node;let[e,n]=dv(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]=dv(e);t.body.setTranslation({x:n/Z,y:r/Z},!1),t.body.setRotation(e.rotation*rv,!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 J_&&(n?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof nv&&(t=!0);t&&(this.jointSet.clear(),ov(e.root,this.jointSet))}else this.bodySet.clear(),sv(e.root,this.bodySet),this.jointSet.clear(),ov(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]=dv(e),a=r/Z,o=i/Z,s;s=e instanceof Z_?n.RigidBodyDesc.dynamic():e instanceof Q_||e instanceof X_?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),s.setTranslation(a,o).setRotation(e.rotation*rv),e instanceof Z_&&(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=pv(n,e.collider,e.name);l.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof X_&&l.setSensor(!0),e instanceof Z_&&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]=dv(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 Z_){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 ov(e,t){e instanceof nv&&t.add(e);for(let n of e.children)ov(n,t)}function sv(e,t){e instanceof J_&&t.add(e);for(let n of e.children)sv(n,t)}var cv=4;function lv(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 uv(e){let[,t]=dv(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 dv(e){let t=0,n=0;for(let r=e;r;r=r.parent)r instanceof q_&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function fv(e){let t=0,n=0;for(let r=e.parent;r;r=r.parent)r instanceof q_&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function pv(e,t,n){K_(t,n);let r=mv(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Z,(i[1]??0)/Z),r}function mv(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 hv=new cl(1,1),gv=class extends q_{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 Ys(hv,new Ls({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}},_v=class extends gv{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=vv(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 vv(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 yv=class extends q_{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 q_))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=bv(n,i+c,o-c),r=bv(r,a+l,s-l)}return{x:n,y:r}}};function bv(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var xv=class extends Nt{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 Q_))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 Q_))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))}},Sv=new cl(1,1),Cv=class extends q_{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 Ys(Sv,new Ls({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}},wv=new cl(1,1),Tv=class extends q_{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 Ys(wv,new Ls({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 Qc(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)}},Ev=new cl(1,1),Dv=class e extends q_{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`,...pn]},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`&&!pn.includes(t.preset))throw new N(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${pn.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:pn});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){mn(this,this.preset,qe(e.typeName));let t=this.tree?.engine?.rng??new P(4660);this.sim=new gn({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 Ls({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new xc(Ev,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(Pi),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let n=this.mesh,r=this.refreshPalette(),i=r?null:kv.set(this.colorStart),a=Av.set(this.colorEnd),o=this.shimmer,s=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;Ov.makeScale(t,t,1),Ov.setPosition(e.x,-e.y,0),n.setMatrixAt(s,Ov);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))),jv.copy(c).lerp(a,e.t).multiplyScalar(l),n.setColorAt(s,jv),s+=1}),n.count=s,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),n.renderOrder=this.effectiveRenderOrder}},Ov=new G,kv=new K,Av=new K,jv=new K;function Mv(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 Nv(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 Pv=class extends q_{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;Mv(t._cells,t._legend)}grid(){return Mv(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;Nv(this.grid(),new Set(this._solid)).forEach((t,n)=>{let r=new Y_(`__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 Ys(new J,new Ls({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=rr,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()}},Fv=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],Iv=class extends Nt{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:Fv}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new _o,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!Fv.includes(t))throw new N(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${Fv.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:Fv})}_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 Lv(){_n(),R(q_),R(gv),R(Cv),R(Dv),R(_v),R(yv),R(Tv),R(Iv),R(Y_),R(Z_),R(X_),R(Q_),R(xv),R(nv),R(Pv)}function Rv(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function zv(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}var Bv=new Vo,Vv=new U,Hv=12,Uv=new Float32Array(16);function Wv(e){if(!(e instanceof q_))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),Bv.setFromObject(t),Bv.getSize(Vv);let n,r,i,a;if(!Number.isFinite(Vv.x)||Vv.x===0&&Vv.y===0){let e=new U().setFromMatrixPosition(t.matrixWorld);n=e.x-Hv,i=e.x+Hv,r=e.y-Hv,a=e.y+Hv}else n=Bv.min.x-2,i=Bv.max.x+2,r=Bv.min.y-2,a=Bv.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return Uv.set(o),Uv}function Gv(){return{visited:new Set,cameras:[]}}function Kv(e,t,n,r,i,a,o){let s=a??Gv();s.visited.clear(),s.cameras.length=0,qv(e,t,n,!1,s.visited,s.cameras,r,i,o?.ignoreStatic===!0),Jv(t,s.visited),Jv(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 qv(e,t,n,r,i,a,o,s,c){let l=t,u=r;if(e instanceof q_&&!(e instanceof Iv)){let t=e._ensureObject2D();if(e.static&&!c&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof Iv){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 q_){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(o),i.add(n),e instanceof yv&&!r&&a.push(e),l=n}for(let t of e.children)qv(t,l,n,u,i,a,o,s,c);if(e instanceof q_&&!(e instanceof Iv)){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 Jv(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&&Jv(i,t)}}var Yv=class{viewOverride=null;webgl;worldScene=new Eo;syncScratch=Gv();ignoreStatic=!1;uiScene=new Eo;worldCam=new vu(-1,1,1,-1,-1e3,1e3);uiCam=new vu(-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 gm(void 0,this.engine);let t=vn(e.engine.scene?.environment,{antialias:!0,pixelRatio:1,preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,e);this.webgl=new hm({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 Hc(new J,new Ac({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 Hc(new J,new Ac({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?Wv(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 tv(`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(Zv);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:Tn(e.viewport),o=a?En(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r,{activeCamera:l}=Kv(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)),Xv(this.worldCam,u.x,u.y,s/d,c/d),Xv(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 zv(this.lastView,e,t)}screenFromWorld(e,t){return Rv(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;$v.set((e-i)/o*2-1,-((t-a)/s*2-1)),ey.setFromCamera($v,this.worldCam);let c=ey.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||(ty.makeEmpty(),ty.expandByObject(t),ty.isEmpty())||(ty.getSize(Qv),Qv.x===0&&Qv.y===0))return null;let n=this.screenFromWorld(ty.min.x,-ty.max.y),r=this.screenFromWorld(ty.max.x,-ty.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 Xv(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 Zv=new V,Qv=new U,$v=new V,ey=new qu,ty=new Vo;async function ny(e){Lv(),(e.gameplay??!0)&&G_();for(let[t,n]of Object.entries(e.behaviors??{}))it(t,n,{replace:!0});let t=new kt({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),n=ry(e.scene),r=An(ry(n),{resolveScene:e.resolveScene,engine:t});t.setScene(r);let i=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&iy(r.root))&&(i=await iv(t));let a=[],o=e.keyboard??(typeof window<`u`?window:!1);o&&t.input.attachKeyboard(o),a.push(ay(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=qn(t,n,r),o=t.sceneChanged.connect(()=>{i?.dispose(),i=qn(t,n,r)});a.push(()=>{o(),i?.dispose()})}}let c=e._rendererFactory?e._rendererFactory(t,e.canvas):new Yv({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??Am,r=async t=>{await ny({...e,scene:t})};await jm(async()=>{p();try{await t({scene:n,play:r,exit:()=>r(n),...d.save?{save:d.save}:{},...d.library?{library:d.library===!0?wm():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 bm(async()=>{let{attachDebugOverlay:e}=await import(`./debug-DN9X9G6z.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(){Nm([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 ry(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 iy(e){if(e instanceof J_)return!0;for(let t of e.children)if(iy(t))return!0;return!1}function ay(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 Rt&&(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 oy(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 sy=e({createGame2D:()=>ny,enablePhysics2D:()=>iv}),cy=(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())}),ly=(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())}),uy=class extends go{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 dy(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 fy(e,t){return ly(this,null,function*(){return dy(e,t,yield e.parser.getDependency(`node`,t))})}function py(e){return ly(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=dy(e,r,t);i!=null&&n.set(r,i)}),n})}var my={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 hy(e){return Math.max(Math.min(e,1),0)}var gy=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(my));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(my));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=hy(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}}},_y={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},vy={_Color:_y.Color,_EmissionColor:_y.EmissionColor,_ShadeColor:_y.ShadeColor,_RimColor:_y.RimColor,_OutlineColor:_y.OutlineColor},yy=new K,by=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(yy.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}};by._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 xy=by,Sy=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)})}},Cy=new V,wy=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(Cy.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(Cy.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))})}};wy._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var Ty=wy,Ey=new Set([`1.0`,`1.0-beta`]),Dy=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return ly(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return ly(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return ly(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(!Ey.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(my)),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 gy;return yield Promise.all(Array.from(o.entries()).map(t=>ly(this,[t],function*([t,n]){var r,i,a;let o=new uy(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=>ly(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield fy(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 Sy({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=>ly(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new xy({material:t,type:e.type,targetValue:new K().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>ly(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new Ty({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 ly(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 gy,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>ly(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 uy(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>ly(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=>ly(this,null,function*(){let i=yield fy(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 Sy({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 Ty({material:t,scale:n,offset:r}));return}let n=vy[r];if(n){c.addBind(new xy({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})}};Dy.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 Oy=Dy,ky=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 sc(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 Gu?[]: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 Gu?[]: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 fc(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 _o;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}};ky.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,ky.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var Ay=ky,jy=new Set([`1.0`,`1.0-beta`]),My=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return ly(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 ly(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return ly(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(!jy.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield py(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 Ay(t,o)})}_v0Import(e,t){return ly(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 py(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 Ay(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},Ny=new U,Py=new U,Fy=new H,Iy=class extends _o{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new Xu(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(Ny,Fy,Py);let n=Ny.set(.1,.1,.1).divide(Py);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},Ly=`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(`.`),Ry={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 zy(e){return e.invert?e.invert():e.inverse(),e}var By=new U,Vy=new H,Hy=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&&(By.copy(r.position),Vy.copy(r.quaternion),e[n]={position:By.toArray(),rotation:Vy.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;By.set(0,0,0),Vy.identity();let i=this.restPose[n];i?.position&&By.fromArray(i.position).negate(),i?.rotation&&zy(Vy.fromArray(i.rotation)),By.add(r.position),Vy.premultiply(r.quaternion),e[n]={position:By.toArray(),rotation:Vy.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(By.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(Vy.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}},Uy=new U,Wy=new H,Gy=new U,Ky=class e extends Hy{static _setupTransforms(e){let t=new go;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};Ly.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,Uy),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new H;(o=s.parent)==null||o.matrixWorld.decompose(Uy,l,Uy),a[t]=l}});let o={};return Ly.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=Ry[a],a!=null);)s=n[a];let c=new go;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(){Ly.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=Wy.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(Gy);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},qy=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 Hy(e),this._normalizedHumanBones=new Ky(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new Hy(e.humanBones),this._normalizedHumanBones=new Ky(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()}},Jy={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`},Yy=new Set([`1.0`,`1.0-beta`]),Xy={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},Zy=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return ly(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return ly(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return ly(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(!Yy.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=>ly(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=Xy[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 qy(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new Iy(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return ly(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=>ly(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=Xy[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 qy(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new Iy(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(Jy).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},Qy=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}},$y=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}},eb=new H,tb=new H,nb=new U,rb=new U,ib=Math.sqrt(2)/2,ab=new H(0,0,-ib,ib),ob=new U(0,1,0),sb=class extends _o{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new Qy;e.radius=.5;let t=new Ls({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new Ys(e,t),this.add(this._meshPitch)}{let e=new Qy;e.radius=.5;let t=new Ls({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new Ys(e,t),this.add(this._meshYaw)}{let e=new $y;e.radius=.1;let t=new Ac({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new Hc(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=ba.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=ba.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(nb),this.vrmLookAt.getLookAtWorldQuaternion(eb),eb.multiply(this.vrmLookAt.getFaceFrontQuaternion(tb)),this._meshYaw.position.copy(nb),this._meshYaw.quaternion.copy(eb),this._meshPitch.position.copy(nb),this._meshPitch.quaternion.copy(eb),this._meshPitch.quaternion.multiply(tb.setFromAxisAngle(ob,t)),this._meshPitch.quaternion.multiply(ab);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(rb).sub(nb),this._lineTarget.geometry.tail.copy(rb),this._lineTarget.geometry.update(),this._lineTarget.position.copy(nb)),super.updateMatrixWorld(e)}},cb=new U,lb=new U;function ub(e,t){return e.matrixWorld.decompose(cb,t,lb),t}function db(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function fb(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var pb=new U(0,0,1),mb=new U,hb=new U,gb=new U,_b=new H,vb=new H,yb=new H,bb=new H,xb=new Qa,Sb=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 Qa)}getEuler(e){return e.set(ba.DEG2RAD*this._pitch,ba.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 ub(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(pb)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=db(this.faceFront);return xb.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(xb).premultiply(bb.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(vb),this.getFaceFrontQuaternion(yb),e.copy(pb).applyQuaternion(vb).applyQuaternion(yb).applyEuler(this.getEuler(xb))}lookAt(e){let t=_b.copy(this._restHeadWorldQuaternion).multiply(zy(this.getLookAtWorldQuaternion(vb))),n=this.getLookAtWorldPosition(hb),r=gb.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=db(this.faceFront),[o,s]=db(r),c=fb(o-i),l=fb(a-s);this._yaw=ba.RAD2DEG*c,this._pitch=ba.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(mb)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};Sb.EULER_ORDER=`YXZ`;var Cb=Sb,wb=new U(0,0,1),Tb=new H,Eb=new H,Db=new Qa(0,0,0,`YXZ`),Ob=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),ub(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),ub(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?Db.x=-ba.DEG2RAD*this.rangeMapVerticalDown.map(-t):Db.x=ba.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?Db.y=-ba.DEG2RAD*this.rangeMapHorizontalInner.map(-e):Db.y=ba.DEG2RAD*this.rangeMapHorizontalOuter.map(e),Tb.setFromEuler(Db),this._getWorldFaceFrontQuat(Eb),i.quaternion.copy(Eb).multiply(Tb).multiply(Eb.invert()),Tb.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(Tb).premultiply(Tb.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?Db.x=-ba.DEG2RAD*this.rangeMapVerticalDown.map(-t):Db.x=ba.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?Db.y=-ba.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):Db.y=ba.DEG2RAD*this.rangeMapHorizontalInner.map(e),Tb.setFromEuler(Db),this._getWorldFaceFrontQuat(Eb),a.quaternion.copy(Eb).multiply(Tb).multiply(Eb.invert()),Tb.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(Tb).premultiply(Tb.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=ba.RAD2DEG*e.y,n=ba.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(wb)<.01)return e.identity();let[t,n]=db(this.faceFront);return Db.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(Db)}};Ob.type=`bone`;var kb=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=ba.RAD2DEG*e.y,n=ba.RAD2DEG*e.x;this.applyYawPitch(t,n)}};kb.type=`expression`;var Ab=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*hy(e/this.inputMaxValue)}},jb=new Set([`1.0`,`1.0-beta`]),Mb=.01,Nb=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return ly(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 ly(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 ly(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(!jb.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 kb(n,s,c,l,u):new Ob(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<Mb&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=Mb),new Ab(n,r)}_v0Import(e,t,n){return ly(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 kb(n,a,o,s,c):new Ob(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 Ob&&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<Mb&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=Mb),new Ab(r,i)}_importLookAt(e,t){let n=new Cb(e,t);if(this.helperRoot){let e=new sb(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function Pb(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 Fb=new Set([`1.0`,`1.0-beta`]),Ib=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 ly(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return ly(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return ly(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(!Fb.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 ly(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 ly(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 Ql().loadAsync(Pb(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},Lb=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()}},Rb=class extends Lb{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)})}},zb=Object.defineProperty,Bb=Object.getOwnPropertySymbols,Vb=Object.prototype.hasOwnProperty,Hb=Object.prototype.propertyIsEnumerable,Ub=(e,t,n)=>t in e?zb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Wb=(e,t)=>{for(var n in t||={})Vb.call(t,n)&&Ub(e,n,t[n]);if(Bb)for(var n of Bb(t))Hb.call(t,n)&&Ub(e,n,t[n]);return e},Gb=(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 Kb(e,t){e.colorSpace=t}var qb=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 Gb(this,null,function*(){let r=Gb(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&&Kb(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return Gb(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},Jb=`// #define PHONG
5757
5757
 
5758
5758
  varying vec3 vViewPosition;
5759
5759
 
@@ -6973,7 +6973,7 @@ if (splatDetailAmount > 0.001) {
6973
6973
 
6974
6974
  normal = perturbSplatNormal(normal, vViewPosition, vUvSplat, blendedNormalSample);
6975
6975
  #endif
6976
- `;function tT(e,t){for(let n=0;n<4;n++){let r=n+1;e.uniforms[`splatTexture${r}`]={value:t.textures[n]??t.textures[0]??null},e.uniforms[`splatNormalMap${r}`]={value:t.normalMaps[n]??null},e.uniforms[`splatTextureRepeat${r}`]={value:t.repeats[n]??1},e.uniforms[`splatRoughness${r}`]={value:t.roughness[n]??1},e.uniforms[`splatMetalness${r}`]={value:t.metalness[n]??0},e.uniforms[`uvNoiseIntensity${r}`]={value:t.uvNoiseIntensity[n]??.15}}e.uniforms.splatTextureCount={value:Math.min(4,t.layerCount)},e.uniforms.uWetlineY={value:-1e9},e.uniforms.uWetlineBand={value:1.1},e.uniforms.uWetTime={value:0},e.uniforms.splatEnvCut={value:t.envCut},e.vertexShader=Kw(e.vertexShader,`#include <common>`,qw),e.vertexShader=Kw(e.vertexShader,`#include <begin_vertex>`,Jw);let n=e.fragmentShader;n=Kw(n,`#include <common>`,Yw),n=Kw(n,`#include <color_fragment>`,Xw),n=Kw(n,`#include <roughnessmap_fragment>`,Zw),n=Kw(n,`#include <metalnessmap_fragment>`,$w),n=Kw(n,`#include <normal_fragment_maps>`,eT),n=Kw(n,`#include <lights_fragment_maps>`,Qw),t.hasNormalMaps&&(n=`#define USE_TERRAIN_NORMALMAP\n${n}`),e.fragmentShader=n}var nT=[`island`,`alpine`,`plains`,`desert`,`grassland`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`,`custom`],rT=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,iT=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground`,aT=1/3,oT=Math.PI/4;function sT(e,t,n){return{texture:`${e}/${t}.png`,normalMap:`${e}/${t}_normal.png`,...n}}function cT(e,t){let n=t.replace(/\/$/,``);switch(e){case`island`:return[sT(n,`sand`,{heightRange:[0,.12],slopeRange:[0,Math.PI/2],heightBlendRange:.05,roughness:.9}),sT(n,`grass`,{heightRange:[.1,.7],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),sT(n,`stone`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.5,roughness:.85}),sT(n,`snow`,{heightRange:[.8,1],slopeRange:[0,Math.PI/3],heightBlendRange:.1,roughness:.6})];case`alpine`:return[sT(n,`grass`,{heightRange:[0,.45],slopeRange:[0,Math.PI/5],heightBlendRange:.1,roughness:.8}),sT(n,`stone`,{heightRange:[.3,1],slopeRange:[0,Math.PI],heightBlendRange:.25,slopeBlendRange:.5,roughness:.85}),sT(n,`gravel`,{heightRange:[0,1],slopeRange:[Math.PI/5,Math.PI],heightBlendRange:.5,slopeBlendRange:.15,roughness:.9}),sT(n,`snow`,{heightRange:[.55,1],slopeRange:[0,Math.PI/3],heightBlendRange:.12,roughness:.55})];case`plains`:return[sT(n,`grass`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),sT(n,`dirt`,{heightRange:[.35,.65],slopeRange:[0,Math.PI/5],heightBlendRange:.2,roughness:.9}),sT(n,`gravel`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`desert`:return[sT(n,`sand`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),sT(n,`gravel`,{heightRange:[0,.15],slopeRange:[0,Math.PI/3],heightBlendRange:.08,roughness:.9}),sT(n,`stone`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.4,roughness:.85})];case`grassland`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${iT}/grass.jpg`,heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:1,repeat:aT,uvNoiseIntensity:0},{texture:`${iT}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:1,repeat:aT,uvNoiseIntensity:0}]:[sT(n,`grass`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:.8}),sT(n,`dirt`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`forest`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${iT}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:1,repeat:aT,uvNoiseIntensity:0},{texture:`${iT}/grass.jpg`,heightRange:[-2,-1],roughness:1,repeat:aT,uvNoiseIntensity:0}]:[sT(n,`dirt`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.9}),sT(n,`grass`,{heightRange:[-2,-1],roughness:.8})];case`savanna`:return[sT(n,`grass`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),sT(n,`sand`,{heightRange:[0,.22],slopeRange:[0,Math.PI/4],heightBlendRange:.12,roughness:.95}),sT(n,`dirt`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`snow`:return[sT(n,`snow`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.18,roughness:.55}),sT(n,`stone`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.35,roughness:.85})];case`wetland`:return[sT(n,`grass`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),sT(n,`dirt`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`volcanic`:return[sT(n,`stone`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.95}),sT(n,`gravel`,{heightRange:[0,.28],slopeRange:[0,Math.PI/3],heightBlendRange:.14,slopeBlendRange:.2,roughness:.95})];case`custom`:return[]}}var lT={scale:100,threshold:.7,blend:.1},uT={scale:55,threshold:.58,blend:.12},dT={scale:85,threshold:.62,blend:.12},fT={scale:48,threshold:.5,blend:.14};function pT(e,t){let n=dn(e+27927);return(e,r)=>{let i=(.5+.5*n(e/t.scale,r/t.scale)-(t.threshold-t.blend))/(2*t.blend),a=Math.min(1,Math.max(0,i));return a*a*(3-2*a)}}function mT(e,t){return e===`grassland`?pT(t,lT):e===`forest`?pT(t,uT):e===`savanna`?pT(t,dT):e===`wetland`?pT(t,fT):null}function hT(e){return e===`savanna`?{from:0,to:2}:e===`grassland`||e===`forest`||e===`wetland`?{from:0,to:1}:null}var gT=256,_T=class extends Ah{orderGroup=`terrain`;static typeName=`Terrain3D`;static props={orderGroup:{default:`terrain`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},size:{default:[200,200]},maxHeight:{default:28},seed:{default:1},resolution:{default:128},theme:{default:`island`,options:nT},roughness:{default:.5},detail:{default:4},flatThreshold:{default:.95},islandEdge:{default:null},layers:{default:[]},textureBase:{default:rT},basins:{default:[]},channels:{default:[]},wetline:{default:null}};size=[200,200];maxHeight=28;seed=1;resolution=128;theme=`island`;roughness=.5;detail=4;flatThreshold=.95;islandEdge=null;layers=[];textureBase=rT;basins=[];channels=[];externalChannels=new Map;externalRev=0;shapeStamp=null;wetline=null;splatUniforms=null;wetTime=0;update(e){this.wetTime+=e;let t=this.splatUniforms;if(!t)return;let n=this.wetline;t.uWetlineY&&(t.uWetlineY.value=typeof n?.y==`number`?n.y:-1e9),t.uWetlineBand&&(t.uWetlineBand.value=typeof n?.band==`number`?n.band:1.1),t.uWetTime&&(t.uWetTime.value=this.wetTime)}static validateJson(e){let t=e;if(!nT.includes(t.theme))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' theme must be one of [${nT.join(`, `)}], got '${t.theme}'.`,{prop:`theme`,validOptions:nT});if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' size must be positive [width, depth] meters, got ${JSON.stringify(t.size)}.`,{prop:`size`});if(!(t.maxHeight>0))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' maxHeight must be > 0, got ${t.maxHeight}.`,{prop:`maxHeight`});if(!Number.isInteger(t.resolution)||t.resolution<2||t.resolution>gT)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' resolution must be an integer in [2, ${gT}] (grid segments per side), got ${t.resolution}.`,{prop:`resolution`});if(!(t.roughness>0)||!Number.isFinite(t.roughness))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' roughness must be a finite number > 0, got ${t.roughness}.`,{prop:`roughness`});if(!Number.isInteger(t.detail)||t.detail<0)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' detail must be an integer ≥ 0 (octave count), got ${t.detail}.`,{prop:`detail`});if(!(t.flatThreshold>=0)||!Number.isFinite(t.flatThreshold))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' flatThreshold must be a finite number ≥ 0, got ${t.flatThreshold}.`,{prop:`flatThreshold`});if(t.islandEdge!==null&&typeof t.islandEdge!=`boolean`)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' islandEdge must be true, false or null (null = theme default), got ${JSON.stringify(t.islandEdge)}.`,{prop:`islandEdge`});let n=t.wetline;if(n!==null){if(typeof n!=`object`||Array.isArray(n)||!Number.isFinite(n.y))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' wetline must be null or { y, band? } with a finite y, got ${JSON.stringify(t.wetline)}.`,{prop:`wetline`});if(n.band!==void 0&&!(n.band>0))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' wetline.band must be > 0 meters, got ${JSON.stringify(n.band)}.`,{prop:`wetline`})}if(!Array.isArray(t.basins))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' basins must be an array of { x, z, radius, depth }, got ${JSON.stringify(t.basins)}.`,{prop:`basins`});if(t.basins.forEach((t,n)=>{if(!t||typeof t!=`object`||!Number.isFinite(t.x)||!Number.isFinite(t.z)||!(t.radius>0)||!Number.isFinite(t.depth)||t.depth===0)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' basins[${n}] needs finite x, z, positive radius and nonzero depth (negative = mound), got ${JSON.stringify(t)}.`,{prop:`basins`})}),!Array.isArray(t.channels))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' channels must be an array of { path, width, depth, taper? }, got ${JSON.stringify(t.channels)}.`,{prop:`channels`});if(t.channels.forEach((t,n)=>{let r=t.path;if(!(t&&typeof t==`object`&&Array.isArray(r)&&r.length>=2&&r.every(e=>Array.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1]))&&t.width>0&&t.depth>0&&(t.taper===void 0||t.taper>0)))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' channels[${n}] needs a path of 2+ [x, z] points plus positive width and depth, got ${JSON.stringify(t)}.`,{prop:`channels`})}),t.theme===`custom`){if(!Array.isArray(t.layers)||t.layers.length<1||t.layers.length>4)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' theme 'custom' needs 1–4 layers, got ${Array.isArray(t.layers)?t.layers.length:typeof t.layers}.`,{prop:`layers`});t.layers.forEach((t,n)=>{bT(e.name,t,n)})}else if(Array.isArray(t.layers)&&t.layers.length>0)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' layers is only read with theme 'custom' — preset theme '${t.theme}' defines its own. Drop layers or switch to theme: 'custom'.`,{prop:`layers`})}heightmap=null;heightmapKey=``;builtKey=``;_createObject3D(){let e=new J;return e.setAttribute(`position`,new q(new Float32Array,3)),new Ys(e,new bl({vertexColors:!0}))}heightAt(e,t){let n=0,r=0,i=0;for(let e=this;e;e=e.parent)e instanceof Ah&&(n+=e.position[0]??0,r+=e.position[1]??0,i+=e.position[2]??0);return this._heightmap().heightAt(e-n,t-i)+r}_setExternalChannel(e,t){t===null||t.length===0?this.externalChannels.delete(e):this.externalChannels.set(e,t),this.externalRev++}allChannels(){return this.externalChannels.size===0?this.channels:[...this.channels,...[...this.externalChannels.values()].flat()]}_heightmap(){if(this.heightmap&&this.shapeUnchanged())return this.heightmap;let e=this.segments(),t=JSON.stringify([this.size,this.maxHeight,this.seed,e,this.roughness,this.detail,this.flatThreshold,this.effectiveIslandEdge(),this.basins,this.allChannels()]);return(!this.heightmap||t!==this.heightmapKey)&&(this.heightmap=Uw({width:this.size[0]??1,depth:this.size[1]??1,segsX:e,segsZ:e,maxHeight:this.maxHeight,seed:this.seed,roughness:this.roughness,detail:this.detail,flatThreshold:this.flatThreshold,islandEdge:this.effectiveIslandEdge(),basins:this.basins,channels:this.allChannels()}),this.heightmapKey=t),this.rememberShape(),this.heightmap}shapeUnchanged(){let e=this.shapeStamp;return e!==null&&e.sizeX===(this.size[0]??0)&&e.sizeZ===(this.size[1]??0)&&e.maxHeight===this.maxHeight&&e.seed===this.seed&&e.segments===this.segments()&&e.roughness===this.roughness&&e.detail===this.detail&&e.flatThreshold===this.flatThreshold&&e.islandEdge===this.effectiveIslandEdge()&&e.basins===this.basins&&e.channels===this.channels&&e.externalRev===this.externalRev}rememberShape(){this.shapeStamp={sizeX:this.size[0]??0,sizeZ:this.size[1]??0,maxHeight:this.maxHeight,seed:this.seed,segments:this.segments(),roughness:this.roughness,detail:this.detail,flatThreshold:this.flatThreshold,islandEdge:this.effectiveIslandEdge(),basins:this.basins,channels:this.channels,externalRev:this.externalRev}}resolvedLayers(){return this.theme===`custom`?this.layers:cT(this.theme,this.textureBase)}_syncObject3D(e=1,t=null){super._syncObject3D(e,t),this.rebuildIfNeeded(t)}effectiveIslandEdge(){return this.islandEdge??this.theme===`island`}segments(){return Math.max(2,Math.min(Math.floor(this.resolution),gT))}rebuildIfNeeded(e){let t=JSON.stringify([this.size,this.maxHeight,this.seed,this.segments(),this.theme,this.roughness,this.detail,this.flatThreshold,this.islandEdge,this.layers,this.textureBase,this.basins,this.allChannels()]);if(t===this.builtKey)return;this.builtKey=t;let n=this._ensureObject3D();n.geometry.dispose(),n.geometry=this.buildGeometry(),n.material.dispose(),n.material=this.buildMaterial(e),n.receiveShadow=!0,n.castShadow=!0}buildGeometry(){let e=this._heightmap(),t=new cl(e.width,e.depth,e.segsX,e.segsZ);t.rotateX(-Math.PI/2);let n=t.getAttribute(`position`);for(let t=0;t<n.count;t++)n.setY(t,e.heights[t]);n.needsUpdate=!0,t.computeVertexNormals();let r=this.resolvedLayers(),i=e.maxHeight-e.minHeight||1,a=new Float32Array(n.count*3),o=this.theme===`custom`?null:hT(this.theme),s=o?mT(this.theme,this.seed):null;for(let t=0;t<n.count;t++){let c=n.getX(t),l=n.getZ(t),u=Gw(Math.min(1,Math.max(0,(n.getY(t)-e.minHeight)/i)),e.slopeAt(c,l),r);if(s&&o){let e=(u[o.from]??0)*s(c,l);u[o.from]=(u[o.from]??0)-e,u[o.to]=(u[o.to]??0)+e}a[t*3]=u[0],a[t*3+1]=u[1],a[t*3+2]=u[2]}return t.setAttribute(`color`,new q(a,3)),t}buildMaterial(e){let t=this.resolvedLayers(),n=new bl({vertexColors:!0}),r=(t,n)=>t?gw(e,t,{wrap:`repeat`,anisotropy:8,colorSpace:n?`srgb`:`linear`}):null,i=t.map(e=>r(e.texture,!0)),a=t.map(e=>r(e.normalMap,!1)),o=a.some(e=>e!==null);if(o)for(let e=0;e<a.length;e++)a[e]||(a[e]=yT());let s={textures:i,normalMaps:a,repeats:t.map(e=>e.repeat??2),roughness:t.map(e=>e.roughness??1),metalness:t.map(e=>e.metalness??0),uvNoiseIntensity:t.map(e=>e.uvNoiseIntensity??.15),envCut:.45,layerCount:Math.min(4,t.length),hasNormalMaps:o};return n.onBeforeCompile=e=>{tT(e,s),this.splatUniforms=e.uniforms},n.customProgramCacheKey=()=>`incanto-terrain-splat:${+!!o}`,n}free(){let e=this._ensureObject3D();e.geometry.dispose(),e.material.dispose(),this.heightmap=null,super.free()}},vT=null;function yT(){return vT||(vT=new lc(new Uint8Array([128,128,255,255]),1,1),vT.needsUpdate=!0),vT}function bT(e,t,n){let r=`layers[${n}]`;if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`BAD_FORMAT`,`Terrain3D '${e}' ${r} must be an object ({texture, heightRange?, slopeRange?, …}).`,{prop:`layers`});let i=t;if(typeof i.texture!=`string`||i.texture.length===0)throw new N(`BAD_FORMAT`,`Terrain3D '${e}' ${r} needs "texture": a texture URL string.`,{prop:`layers`});for(let t of[`heightRange`,`slopeRange`]){let n=i[t];if(n!==void 0&&(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`||!Number.isFinite(e))))throw new N(`BAD_FORMAT`,`Terrain3D '${e}' ${r}.${t} must be [min, max] numbers, got ${JSON.stringify(n)}.`,{prop:`layers`})}}var xT=16,ST=new U,CT=new H;function wT(e,t){let n=e.translation(),r=e.rotation();CT.set(r.x,r.y,r.z,r.w);let i=(e,r,i)=>{ST.set(e,r,i).applyQuaternion(CT),t.push(ST.x+n.x,ST.y+n.y,ST.z+n.z)};return(e,t,n,r,a,o)=>{i(e,t,n),i(r,a,o)}}function TT(e,t,n,r,i=Math.PI*2,a=0){let o=e=>{let i=Math.cos(e)*t,a=Math.sin(e)*t;return n===`xy`?[i,a,r]:n===`xz`?[i,r,a]:[r,i,a]},s=Math.max(3,Math.round(xT*i/(Math.PI*2)));for(let t=0;t<s;t++){let[n,r,c]=o(a+i*t/s),[l,u,d]=o(a+i*(t+1)/s);e(n,r,c,l,u,d)}}function ET(e,t,n){let r=e=>[t[e*3],t[e*3+1],t[e*3+2]];if(n){for(let t=0;t<n.length;t+=3){let i=r(n[t]),a=r(n[t+1]),o=r(n[t+2]);e(...i,...a),e(...a,...o),e(...o,...i)}return}for(let n=0;n+5<t.length;n+=9){let t=r(n/3),i=r(n/3+1),a=r(n/3+2);e(...t,...i),e(...i,...a),e(...a,...t)}}function DT(e,t){let{nrows:n,ncols:r,heights:i,scale:a}=t,o=n+1,s=r+1,c=(e,t)=>[(e/n-.5)*a.x,i[t*o+e]*a.y,(t/r-.5)*a.z];for(let t=0;t<s;t++)for(let n=0;n<o;n++)n+1<o&&e(...c(n,t),...c(n+1,t)),t+1<s&&e(...c(n,t),...c(n,t+1))}function OT(e,t){let n=wT(e,t),r=e.shape;switch(e.shape.type){case 0:{let e=r.radius;TT(n,e,`xy`,0),TT(n,e,`xz`,0),TT(n,e,`yz`,0);return}case 1:{let e=r.halfExtents;for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(-e.x,t*e.y,r*e.z,e.x,t*e.y,r*e.z);for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(t*e.x,-e.y,r*e.z,t*e.x,e.y,r*e.z);for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(t*e.x,r*e.y,-e.z,t*e.x,r*e.y,e.z);return}case 2:{let{radius:e,halfHeight:t}=r;for(let r of[-1,1]){TT(n,e,`xz`,r*t);for(let i of[`xy`,`yz`])TT((e,i,a,o,s,c)=>n(e,i+r*t,a,o,s+r*t,c),e,i,0,Math.PI,r>0?0:Math.PI)}for(let[r,i]of[[1,0],[-1,0],[0,1],[0,-1]])n(r*e,-t,i*e,r*e,t,i*e);return}case 3:{let e=r;n(e.a.x,e.a.y,e.a.z,e.b.x,e.b.y,e.b.z);return}case 6:case 9:case 16:{let e=r;ET(n,e.vertices,e.indices);return}case 7:DT(n,r);return;case 10:case 14:{let{radius:e,halfHeight:t}=r;TT(n,e,`xz`,-t),TT(n,e,`xz`,t);for(let[r,i]of[[1,0],[-1,0],[0,1],[0,-1]])n(r*e,-t,i*e,r*e,t,i*e);return}case 11:case 15:{let{radius:e,halfHeight:t}=r;TT(n,e,`xz`,-t);for(let r=0;r<4;r++){let i=r/4*Math.PI*2;n(Math.cos(i)*e,-t,Math.sin(i)*e,0,t,0)}return}default:if(e.shape.type===12||e.shape.type===13){let e=r.halfExtents;e&&n(-e.x,-e.y,-e.z,e.x,e.y,e.z)}return}}var kT=Math.PI/180;async function AT(e,t){let n=await bm(()=>import(`./rapier-DE6a0vmv.js`),[],import.meta.url);return await n.init({}),new jT(n,e,t)}var jT=class{R;engine;debugDraw=!1;debugScope=null;dimension=`3d`;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,-9.81,0];this.world=new e.World({x:i[0]??0,y:i[1]??0,z:i[2]??0}),this.kcc=this.world.createCharacterController(.01),this.events=new e.EventQueue(!0),this.unregisterDebug=ev(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,-9.81,0];this.world.gravity={x:e[0]??0,y:e[1]??0,z:e[2]??0}}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,i]=ZT(e),a=[n.x-t,n.y-r,n.z-i];e._interpPrev=e._interpCurr??a,e._interpCurr=a;let o=e.position;o[0]=a[0],o[1]=a[1],o[2]=a[2]}if(e instanceof Ph){if(!e.fixedRotation){let n=t.body.rotation();NT.setFromQuaternion(MT.set(n.x,n.y,n.z,n.w),`XYZ`);let r=e.rotation;r[0]=NT.x/kT,r[1]=NT.y/kT,r[2]=NT.z/kT}let n=t.body.linvel(),r=e.linearVelocity;r[0]=n.x,r[1]=n.y,r[2]=n.z,t.lastV[0]=n.x,t.lastV[1]=n.y,t.lastV[2]=n.z}let r=YT(e);t.last[0]=r[0],t.last[1]=r[1],t.last[2]=r[2]}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)}})}poseFromTree(){for(let[e,t]of this.entries){let[n,r,i]=YT(e);t.body.setTranslation({x:n,y:r,z:i},!1),MT.setFromEuler(NT.set((e.rotation[0]??0)*kT,(e.rotation[1]??0)*kT,(e.rotation[2]??0)*kT,`XYZ`)),t.body.setRotation({x:MT.x,y:MT.y,z:MT.z,w:MT.w},!1)}this.world.propagateModifiedBodyPositionsToColliders()}moveAndSlide(e){let t=this.ensureEntry(e);if(!t)return;let n=e.velocity[1]??0;e.snapToGround&&n<=0?this.kcc.enableSnapToGround(.1):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*kT);let r=0,i=0,a=0;if(t.ground&&t.ground._physics===this&&t.groundAt){let[e,n,o]=YT(t.ground);r=e-t.groundAt[0],i=n-t.groundAt[1],a=o-t.groundAt[2]}else t.ground=null;let o={x:(e.velocity[0]??0)*this.lastDt+r,y:n*this.lastDt+i,z:(e.velocity[2]??0)*this.lastDt+a};this.kcc.computeColliderMovement(t.collider,o,this.R.QueryFilterFlags.EXCLUDE_SENSORS);let s=this.kcc.computedMovement(),c=t.body.translation(),l=c.x+s.x,u=c.y+s.y,d=c.z+s.z;if(t.body.setNextKinematicTranslation({x:l,y:u,z:d}),e._grounded=this.kcc.computedGrounded(),e._grounded){let n=JT(e),r=this.castRay([l,u-n+.05,d],[0,-1,0],.4,e);if(r?.node&&!(r.node instanceof Fh)){t.ground=r.node;let e=YT(r.node);t.groundAt=[e[0],e[1],e[2]]}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope;if(!e)return this.world.debugRender().vertices;let t=this.scopedBodies(e),n=[];for(let e of t)for(let t=0;t<e.numColliders();t++){let r=e.collider(t);r&&OT(r,n)}return new Float32Array(n)}scopedBodies(e){let t=[],n=e=>{let r=this.entries.get(e);r&&t.push(r.body);let i=this.scatterBodies.get(e);i&&t.push(i);for(let t of e.children)n(t)};n(e);for(let n=e.parent;n&&t.length===0;n=n.parent){let e=this.entries.get(n);e&&t.push(e.body)}return t}dispose(){this.disconnect(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;scatterBodies=new Map;bodySet=new Set;syncScatters(e){for(let[,e]of this.scatterBodies)this.world.removeRigidBody(e);this.scatterBodies.clear();let t=new Set;KT(e,t);for(let e of t){let t=e.collider;if(!t)continue;let[n,r,i]=YT(e),a=this.world.createRigidBody(this.R.RigidBodyDesc.fixed().setTranslation(0,0,0)),[o,s,c]=e.size,l=null;for(let u of e.transforms){let d=u[4]??1,f=n+(u[0]??0),p=r+(u[1]??0),m=i+(u[2]??0),h=null;if(t.shape===`sphere`)h=this.R.ColliderDesc.ball(Math.max((t.radius??Math.max(o,c)/2)*d,.01));else if(t.shape===`box`){let e=t.size??[o,s,c];h=this.R.ColliderDesc.cuboid(Math.max((e[0]??1)*d/2,.01),Math.max((e[1]??1)*d/2,.01),Math.max((e[2]??1)*d/2,.01))}else{l??=LT(e.mesh,e.size);let t=new Float32Array(l.length);for(let e=0;e<t.length;e++)t[e]=l[e]*d;h=this.R.ColliderDesc.convexHull(t)}if(!h)continue;h.setTranslation(f,p,m);let g=(u[3]??0)*Math.PI/180;g!==0&&h.setRotation({x:0,y:Math.sin(g/2),z:0,w:Math.cos(g/2)}),this.world.createCollider(h,a)}this.scatterBodies.set(e,a)}}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,n=!1;for(let{node:e,added:i}of r)e instanceof jh&&(i?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof Rw&&(t=!0),e instanceof Mw&&(n=!0);t&&(this.jointSet.clear(),PT(e.root,this.jointSet)),n&&this.syncScatters(e.root)}else this.bodySet.clear(),FT(e.root,this.bodySet),this.jointSet.clear(),PT(e.root,this.jointSet),this.syncScatters(e.root)}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,e._interpPrev=e._interpCurr=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,e._interpPrev=e._interpCurr=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,e._interpPrev=e._interpCurr=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let r=QT(n,e);if(!r)return null;let i;i=e instanceof Ph?n.RigidBodyDesc.dynamic():e instanceof Fh||e instanceof Nh?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed();let[a,o,s]=YT(e);i.setTranslation(a,o,s),MT.setFromEuler(NT.set((e.rotation[0]??0)*kT,(e.rotation[1]??0)*kT,(e.rotation[2]??0)*kT,`XYZ`)),i.setRotation({x:MT.x,y:MT.y,z:MT.z,w:MT.w}),e instanceof Ph&&(i.setGravityScale(e.gravityScale),i.setLinvel(e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0),e.fixedRotation&&i.lockRotations());let c=this.world.createRigidBody(i);r.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof Nh&&r.setSensor(!0),e instanceof Ph&&r.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let l=this.world.createCollider(r,c);return t={body:c,collider:l,last:[a,o,s],lastV:[0,0,0]},this.entries.set(e,t),this.byColliderHandle.set(l.handle,e),e._colliderChanged=!1,e._physics=this,e instanceof Ph&&(e._physics3d=this),t}let r=YT(e);if((r[0]!==t.last[0]||r[1]!==t.last[1]||r[2]!==t.last[2])&&(t.body.setTranslation({x:r[0],y:r[1],z:r[2]},!0),t.last[0]=r[0],t.last[1]=r[1],t.last[2]=r[2],e._interpPrev=e._interpCurr=null),e instanceof Ph){let n=[e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0];(n[0]!==t.lastV[0]||n[1]!==t.lastV[1]||n[2]!==t.lastV[2])&&(t.body.setLinvel({x:n[0],y:n[1],z:n[2]},!0),t.lastV=n),e.gravityScale!==t.body.gravityScale()&&t.body.setGravityScale(e.gravityScale,!0)}return t}applyImpulse(e,t){this.entries.get(e)?.body.applyImpulse({x:t[0],y:t[1],z:t[2]},!0)}massOf(e){return this.entries.get(e)?.body.mass()??1}velocityOf(e){let t=this.entries.get(e)?.body.linvel();return t?[t.x,t.y,t.z]:[0,0,0]}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,y:e.anchor[1]??0,z:e.anchor[2]??0},s={x:e.targetAnchor[0]??0,y:e.targetAnchor[1]??0,z:e.targetAnchor[2]??0},c=e.length;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,t.z-e.z)}let l={x:0,y:0,z:0,w:1},u;u=e.type===`fixed`?t.JointData.fixed(o,l,s,l):e.type===`rope`?t.JointData.rope(c,o,s):e.type===`spring`?t.JointData.spring(c,e.stiffness,e.damping,o,s):t.JointData.spherical(o,s),this.joints.set(e,this.world.createImpulseJoint(u,i.body,a.body,!0))}}castRay(e,t,n,r,i){let a=new this.R.Ray({x:e[0],y:e[1],z:e[2]},{x:t[0],y:t[1],z:t[2]}),o=r?this.entries.get(r)?.collider:void 0,s=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,c=this.world.castRayAndGetNormal(a,n,!0,s,void 0,o,void 0,e=>!e.isSensor());return c?{distance:c.timeOfImpact,normal:[c.normal.x,c.normal.y,c.normal.z],node:this.byColliderHandle.get(c.collider.handle)??null}:null}castSphere(e,t,n,r,i,a){let o=this.R,s=i?this.entries.get(i):void 0,c=a?.staticOnly?o.QueryFilterFlags.EXCLUDE_DYNAMIC|o.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castShape({x:e[0],y:e[1],z:e[2]},{x:0,y:0,z:0,w:1},{x:t[0],y:t[1],z:t[2]},new o.Ball(n),0,r,!0,c,void 0,s?.collider,s?.body,e=>!e.isSensor());return l?{distance:l.time_of_impact,node:this.byColliderHandle.get(l.collider.handle)??null}:null}},MT=new H,NT=new Qa;function PT(e,t){e instanceof Rw&&t.add(e);for(let n of e.children)PT(n,t)}function FT(e,t){e instanceof jh&&t.add(e);for(let n of e.children)FT(n,t)}function IT(e,t,n,r){let i=(n[0]??1)*r,a=(n[1]??1)*r,o=(n[2]??1)*r;switch(t){case`box`:return e.ColliderDesc.cuboid(i/2,a/2,o/2);case`sphere`:return e.ColliderDesc.ball(i);case`capsule`:return e.ColliderDesc.capsule(a/2,i);case`cylinder`:return e.ColliderDesc.cylinder(a/2,i);case`plane`:return e.ColliderDesc.cuboid(i/2,.01,o/2);default:return e.ColliderDesc.convexHull(LT(t,[i,a,o]))}}function LT(e,t){let n=jw(e,t),r=n.getAttribute(`position`),i=new Float32Array(r.count*3);for(let e=0;e<r.count;e++)i[e*3]=r.getX(e),i[e*3+1]=r.getY(e),i[e*3+2]=r.getZ(e);return n.dispose(),i}function RT(e){return typeof e._mountedObject3D==`function`}var zT=new G,BT=new G,VT=new U;function HT(e,t){let n=t._mountedObject3D();if(!n)return null;let r=e._ensureObject3D();r.updateWorldMatrix(!0,!0),zT.copy(r.matrixWorld).invert();let i=[],a=[];return n.traverse(e=>{let t=e;if(!t.isMesh)return;let n=t.geometry?.getAttribute(`position`);if(!n)return;BT.multiplyMatrices(zT,t.matrixWorld);let r=i.length/3;for(let e=0;e<n.count;e++)VT.set(n.getX(e),n.getY(e),n.getZ(e)).applyMatrix4(BT),i.push(VT.x,VT.y,VT.z);let o=t.geometry.getIndex();if(o)for(let e=0;e<o.count;e++)a.push(r+o.getX(e));else for(let e=0;e<n.count;e++)a.push(r+e)}),a.length<3?null:{vertices:new Float32Array(i),indices:new Uint32Array(a),triangles:a.length/3}}var UT=2e4;function WT(e){return!(e instanceof Ph||e instanceof Fh)}function GT(e,t,n){if(RT(e))n.push(e);else{let n=e;typeof n.mesh==`string`&&Array.isArray(n.size)&&t.push({name:e.name,mesh:n.mesh,size:n.size})}for(let r of e.children)GT(r,t,n)}function KT(e,t){e instanceof Mw&&e.collider&&t.add(e);for(let n of e.children)KT(n,t)}var qT=[0,0,0];function JT(e){let t=e.collider;return t?t.shape===`capsule`&&typeof t.height==`number`?t.height/2+(t.radius??0):t.shape===`box`&&Array.isArray(t.size)?(t.size[1]??2)/2:t.shape===`sphere`&&typeof t.radius==`number`?t.radius:1:1}function YT(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Ah&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return qT[0]=t,qT[1]=n,qT[2]=r,qT}var XT=[0,0,0];function ZT(e){let t=0,n=0,r=0;for(let i=e.parent;i;i=i.parent)i instanceof Ah&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return XT[0]=t,XT[1]=n,XT[2]=r,XT}function QT(e,t){let n=t.collider;if(Oh(n,t.name),n.shape===`heightfield`)return $T(e,t);let r=eE(e,n,t.name,t);if(!r)return null;let i=n.offset;return Array.isArray(i)&&r.setTranslation(i[0]??0,i[1]??0,i[2]??0),r}function $T(e,t){let n=t.children.find(e=>e instanceof _T);if(!n)throw new N(`BAD_FORMAT`,`Collider on '${t.name}': heightfield needs a Terrain3D CHILD of this body — add { "type": "Terrain3D" } under the StaticBody3D; the collider reads its height grid.`,{prop:`collider`});let r=n._heightmap(),i=r.segsZ,a=r.segsX,o=new Float32Array((i+1)*(a+1));for(let e=0;e<=a;e++)for(let t=0;t<=i;t++)o[e*(i+1)+t]=r.heights[t*(a+1)+e];let s=e.ColliderDesc.heightfield(i,a,o,{x:r.width,y:1,z:r.depth}),c=Array.isArray(t.collider.offset)?t.collider.offset:[];return s.setTranslation((n.position[0]??0)+(c[0]??0),(n.position[1]??0)+(c[1]??0),(n.position[2]??0)+(c[2]??0)),s}function eE(e,t,n,r){let i=t.shape;if(i===`box`){let r=t.size;if(!Array.isArray(r)||r.length!==3||r.some(e=>typeof e!=`number`))throw new N(`BAD_FORMAT`,`Collider on '${n}': box needs "size": [x, y, z].`);return e.ColliderDesc.cuboid(r[0]/2,r[1]/2,r[2]/2)}if(i===`sphere`){if(typeof t.radius!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${n}': sphere needs "radius".`);return e.ColliderDesc.ball(t.radius)}if(i===`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,t.radius)}if(i===`auto`){let t=[],i=[];r&&GT(r,t,i);let a=t[0],o=i[0];if(!a&&!o)throw new N(`BAD_FORMAT`,`Collider on '${n}': shape 'auto' needs a MeshInstance3D or ModelInstance3D on the body (or as a child) to take its shape from.`);let s=t.length+i.length;if(s>1&&console.warn(`[incanto] Collider on '${n}': shape 'auto' fits ONE mesh and took '${(a??o)?.name}'; ${s-1} other mesh(es) here are not solid. Give each part its own body.`),a){let t=IT(e,a.mesh,a.size,1);if(t)return t}else if(o&&r){let t=HT(r,o);return t?WT(r)?(t.triangles>UT&&console.warn(`[incanto] Collider on '${n}': shape 'auto' built a ${t.triangles}-triangle mesh from '${o.name}'. Consider a low-poly collision model or an explicit box.`),e.ColliderDesc.trimesh(t.vertices,t.indices)):e.ColliderDesc.convexHull(t.vertices):null}}if(i===`trimesh`){let r=t.vertices,i=t.indices;if(!Array.isArray(r)||!Array.isArray(i))throw new N(`BAD_FORMAT`,`Collider on '${n}': trimesh needs "vertices" (flat xyz) and "indices" (triangles).`);return e.ColliderDesc.trimesh(new Float32Array(r),new Uint32Array(i))}throw new N(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'auto', 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(i)}.`)}var tE=new cl(1,1),nE=null;function rE(){if(nE)return nE;if(typeof document>`u`)return null;let e=document.createElement(`canvas`);e.width=64,e.height=64;let t=e.getContext(`2d`);if(!t)return null;let n=t.createRadialGradient(32,32,0,32,32,31);return n.addColorStop(0,`rgba(0,0,0,0.55)`),n.addColorStop(.55,`rgba(0,0,0,0.34)`),n.addColorStop(1,`rgba(0,0,0,0)`),t.fillStyle=n,t.fillRect(0,0,64,64),nE=new Qc(e),nE}var iE=new U(0,0,1),aE=new U,oE=new U,sE=new H,cE=new H,lE=new U,uE=.5,dE=class extends Ah{static typeName=`Sprite3D`;static props={texture:{default:``},size:{default:[1,1]},billboard:{default:`y`,options:[`y`,`full`,`none`]},anchor:{default:[.5,0]},tint:{default:`#ffffff`},opacity:{default:1},flipX:{default:!1},pixelArt:{default:!0},alphaTest:{default:.5},castShadow:{default:!1},shadowMode:{default:`silhouette`,options:[`silhouette`,`blob`]}};texture=``;size=[1,1];billboard=`y`;anchor=[.5,0];tint=`#ffffff`;opacity=1;flipX=!1;pixelArt=!0;alphaTest=.5;castShadow=!1;shadowMode=`silhouette`;quadMesh=null;textureRef=``;loadedTexture=null;shadowMesh=null;blobMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Ys(tE,new Ls({transparent:!1,depthWrite:!0,side:2})),this._ensureObject3D().add(this.quadMesh)),this.quadMesh}resolveTexture(e){return this.texture?(this.textureRef!==this.texture&&(this.textureRef=this.texture,this.loadedTexture=gw(e,this.texture,{filter:this.pixelArt?`nearest`:`linear`})),this.loadedTexture):null}_syncObject3D(e=1,t=null){super._syncObject3D(e,t);let n=this._quad(),r=n.material,i=this.size[0]??1,a=this.size[1]??1;n.scale.set(this.flipX?-i:i,a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??0;n.position.set((.5-o)*i,(.5-s)*a,0);let c=this.resolveTexture(t);r.map!==c&&(r.map=c,r.needsUpdate=!0),n.visible=c!==null,r.color.set(this.tint),r.opacity=this.opacity,r.transparent=this.opacity<1,r.alphaTest=this.alphaTest,n.renderOrder=this.renderOrder;let l=this.castShadow&&c!==null;if(n.castShadow=!1,l&&this.shadowMode===`silhouette`){let e=this._shadowCaster();e.visible=!0,e.castShadow=!0,e.scale.set(this.flipX?-i:i,a,1),e.position.set((.5-o)*i,(.5-s)*a,0);let t=e.material;t.map!==c&&(t.map=c,t.needsUpdate=!0);let n=e.customDepthMaterial;n.map!==c&&(n.map=c,n.needsUpdate=!0),t.alphaTest=this.alphaTest,n.alphaTest=this.alphaTest}else this.shadowMesh&&(this.shadowMesh.visible=!1,this.shadowMesh.castShadow=!1);if(l&&this.shadowMode===`blob`){let e=this._blob();e.visible=!0,e.scale.set(i*.52,i*.52,1)}else this.blobMesh&&(this.blobMesh.visible=!1)}_shadowCaster(){return this.shadowMesh||(this.shadowMesh=new Ys(tE,new Ls({colorWrite:!1,depthWrite:!1,side:2})),this.shadowMesh.customDepthMaterial=new Sl({depthPacking:Di,side:2}),this._ensureObject3D().add(this.shadowMesh)),this.shadowMesh}_blob(){return this.blobMesh||(this.blobMesh=new Ys(tE,new Ls({map:rE(),color:0,transparent:!0,depthWrite:!1})),this.blobMesh.rotation.x=-Math.PI/2,this.blobMesh.position.y=.02,this.blobMesh.renderOrder=-1,this._ensureObject3D().add(this.blobMesh)),this.blobMesh}_onRender3D(e){this.billboard===`y`?(e.camera.getWorldDirection(oE),oE.y=0,oE.lengthSq()>=1e-6&&this._faceDir(this._quad(),oE.negate())):this.billboard===`full`&&this._faceToward(this._quad(),e.camera.position);let t=this.shadowMesh;t?.castShadow&&e.sunDir&&(this._faceDir(t,e.sunDir),t.parent?.getWorldQuaternion(cE),lE.copy(e.sunDir).applyQuaternion(cE.invert()),t.position.addScaledVector(lE,uE))}_faceToward(e,t){e.getWorldPosition(aE),oE.copy(t).sub(aE),this.billboard===`y`&&(oE.y=0),!(oE.lengthSq()<1e-12)&&(oE.normalize(),sE.setFromUnitVectors(iE,oE),e.parent?.getWorldQuaternion(cE),e.quaternion.copy(cE.invert()).multiply(sE))}_faceDir(e,t){oE.copy(t),this.billboard===`y`&&(oE.y=0),!(oE.lengthSq()<1e-12)&&(oE.normalize(),sE.setFromUnitVectors(iE,oE),e.parent?.getWorldQuaternion(cE),e.quaternion.copy(cE.invert()).multiply(sE))}free(){this.loadedTexture?.dispose(),this.loadedTexture=null,this.shadowMesh&&(this.shadowMesh.material.dispose(),this.shadowMesh.customDepthMaterial?.dispose()),this.blobMesh&&this.blobMesh.material.dispose(),super.free()}},fE=class extends dE{static typeName=`AnimatedSprite3D`;static signals=[`animationFinished`];static props={sheet:{default:``},frameWidth:{default:0},frameHeight:{default:0},animations:{default:{}},autoplay:{default:``}};sheet=``;frameWidth=0;frameHeight=0;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;sheetTexture=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=pE(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||this.frameWidth<=0||this.frameHeight<=0)return null;this.loadedSheetRef!==this.sheet&&(this.sheetTexture?.dispose(),this.loadedSheetRef=this.sheet,this.sheetTexture=_w(e,this.sheet,{filter:this.pixelArt?`nearest`:`linear`}));let t=this.sheetTexture;if(!t)return null;let n=t.image;if(!n?.width||!n.height)return t;let r=Math.max(1,Math.floor(n.width/this.frameWidth)),i=this.currentFrame%r,a=Math.floor(this.currentFrame/r);return t.repeat.set(this.frameWidth/n.width,this.frameHeight/n.height),t.offset.set(i*this.frameWidth/n.width,1-(a+1)*this.frameHeight/n.height),t}free(){this.sheetTexture?.dispose(),this.sheetTexture=null,super.free()}};function pE(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 mE=new H,hE=new H,gE=new U,_E=new U(0,0,1),vE=[`screen`,`y`,`none`],yE=class extends Ah{static typeName=`Billboard3D`;static props={mode:{default:`screen`,options:vE}};mode=`screen`;_lastDesired=null;static validateJson(e){let t=e;if(!vE.includes(t.mode))throw new N(`BAD_FORMAT`,`Billboard3D '${e.name}' mode must be one of [${vE.join(`, `)}], got '${t.mode}'.`,{prop:`mode`,validOptions:vE})}_onRender3D(e){if(this.mode===`none`)return;let t=this._ensureObject3D();if(this.mode===`screen`)e.camera.getWorldQuaternion(hE);else if(e.camera.getWorldDirection(gE),gE.y=0,gE.lengthSq()>=1e-6)hE.setFromUnitVectors(_E,gE.negate().normalize());else if(this._lastDesired)hE.copy(this._lastDesired);else return;this._lastDesired||=new H,this._lastDesired.copy(hE),t.parent?.getWorldQuaternion(mE),t.parent?t.quaternion.copy(mE.invert()).multiply(hE):t.quaternion.copy(hE)}},bE=class extends Ah{static typeName=`BoneAttachment3D`;static props={target:{default:``,nodePath:!0},bone:{default:``}};target=``;bone=``;boneObj=null;lookedUpFor=``;get attachedBone(){return this.boneObj}_onRender3D(e){if(this.target===``||this.bone===``)return;let t=`${this.target} ${this.bone}`;if(this.lookedUpFor!==t||this.boneObj===null||!this.boneObj.parent){this.lookedUpFor=t,this.boneObj=null;let e=this.getNodeOrNull(this.target);e&&typeof e.findBone==`function`&&(this.boneObj=e.findBone(this.bone))}let n=this.boneObj;if(!n)return;let r=this._ensureObject3D(),i=r.parent;i&&(n.updateWorldMatrix(!0,!1),i.updateWorldMatrix(!0,!1),r.matrixAutoUpdate=!1,n.matrixWorld.decompose(CE,wE,TE),SE.compose(CE,wE,EE),r.updateMatrix(),xE.copy(r.matrix),r.matrix.copy(i.matrixWorld).invert().multiply(SE).multiply(xE))}free(){this.boneObj=null,super.free()}},xE=new G,SE=new G,CE=new U,wE=new H,TE=new U,EE=new U(1,1,1),DE=class extends Ah{static typeName=`BoneLookAt3D`;static props={target:{default:``,nodePath:!0},bone:{default:`Head`},lookAt:{default:``,nodePath:!0},maxAngleDeg:{default:75},weight:{default:.85},forwardAxis:{default:`+z`,options:[`+x`,`-x`,`+y`,`-y`,`+z`,`-z`]}};target=``;bone=`Head`;lookAt=``;maxAngleDeg=75;weight=.85;forwardAxis=`+z`;boneObj=null;lookedUpFor=``;engage=0;get attachedBone(){return this.boneObj}_onRender3D(e){if(this.target===``||this.bone===``)return;let t=`${this.target} ${this.bone}`;if(this.lookedUpFor!==t||this.boneObj===null||!this.boneObj.parent){this.lookedUpFor=t,this.boneObj=null;let e=this.getNodeOrNull(this.target);e&&typeof e.findBone==`function`&&(this.boneObj=e.findBone(this.bone))}let n=this.boneObj;if(!n?.parent)return;let r=this.lookAt===``?null:this.getNodeOrNull(this.lookAt),i=!1;if(r&&Array.isArray(r.position)&&(n.updateWorldMatrix(!0,!1),n.getWorldPosition(NE),PE.set(r.position[0]??0,r.position[1]??0,r.position[2]??0),FE.copy(PE).sub(NE),FE.lengthSq()>1e-6&&(FE.normalize(),IE.copy(kE[this.forwardAxis]??jE),LE.copy(IE).applyQuaternion(n.getWorldQuaternion(HE)),LE.angleTo(FE)<this.maxAngleDeg*Math.PI/180))){i=!0,RE.lookAt(NE,PE,AE),zE.setFromRotationMatrix(RE),BE.setFromUnitVectors(IE,ME),zE.multiply(BE),n.parent.getWorldQuaternion(VE).invert(),zE.premultiply(VE);let e=this.weight*this.engage;n.quaternion.slerp(zE,e)}this.engage+=(+!!i-this.engage)*OE}},OE=.18,kE={"+x":new U(1,0,0),"-x":new U(-1,0,0),"+y":new U(0,1,0),"-y":new U(0,-1,0),"+z":new U(0,0,1),"-z":new U(0,0,-1)},AE=new U(0,1,0),jE=new U(0,0,1),ME=new U(0,0,-1),NE=new U,PE=new U,FE=new U,IE=new U,LE=new U,RE=new G,zE=new H,BE=new H,VE=new H,HE=new H,UE=class extends Ah{static typeName=`Camera3D`;static props={fov:{default:60},near:{default:.1},far:{default:1e3},current:{default:!1}};fov=60;near=.1;far=1e3;current=!1;_createObject3D(){return new pu(this.fov,1,this.near,this.far)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();(e.fov!==this.fov||e.near!==this.near||e.far!==this.far)&&(e.fov=this.fov,e.near=this.near,e.far=this.far,e.updateProjectionMatrix())}},WE=8,GE=.2,KE=.15,qE=1.2,JE=.08,YE=2.5,XE=-20,ZE=.002,QE=180/Math.PI,$E=.3,eD=.4,tD=.3,nD=.25,rD=new Qa,iD=new H,aD=new G,oD=new U,sD=new U,cD=new U(0,1,0),lD=class extends Ah{static typeName=`CharacterController3D`;static signals=[`movementStateChanged`];static props={view:{default:`free`,options:[`free`,`firstPerson`,`quarter`,`side`]},camDistance:{default:4},eyeHeight:{default:.64},maxSpeed:{default:2.5},sprintMultiplier:{default:2},jumpVelocity:{default:4},sprintJumpMultiplier:{default:1.2},floatHeight:{default:.01},mouseLook:{default:!0},zoomMin:{default:0},zoomMax:{default:0},pitchMin:{default:-1.3},pitchMax:{default:1.5},cameraCollision:{default:!0},turnSpeed:{default:100},camLerp:{default:25},moveAction:{default:`move`},jumpAction:{default:`jump`},sprintAction:{default:`sprint`},skinPath:{default:`../Skin`,nodePath:!0},skinYawOffset:{default:0},animations:{default:{}}};view=`free`;camDistance=4;eyeHeight=.64;maxSpeed=2.5;sprintMultiplier=2;jumpVelocity=4;sprintJumpMultiplier=1.2;floatHeight=.01;mouseLook=!0;zoomMin=0;zoomMax=0;pitchMin=-1.3;pitchMax=1.5;cameraCollision=!0;turnSpeed=100;camLerp=25;moveAction=`move`;jumpAction=`jump`;sprintAction=`sprint`;skinPath=`../Skin`;skinYawOffset=0;animations={};yaw=0;pitch=0;state=`idle`;grounded=!1;get body(){let e=this.parent;if(!(e instanceof Ph))throw new N(`TREE_VIOLATION`,`CharacterController3D '${this.name}' must be a child of a RigidBody3D (parent is '${e?.name??`none`}').`);return e}onEnterTree(){if(this.body,this.skinPath!==``){let e=this.getNodeOrNull(this.skinPath);e&&(e.rotation=[e.rotation[0]??0,180+this.skinYawOffset,e.rotation[2]??0])}}fixedUpdate(e){let t=this.body,n=t._physics3d,r=this.tree?.engine?.input;if(!n||!r)return;let i=t.collider.radius??.32,a=(t.collider.height??1)/2,o=dD(t),s=n.velocityOf(t),c=n.massOf(t),l=i+this.floatHeight,u=i+2,d=o[1]-a,f=null;for(let[e,r]of[[0,0],[i,0],[-i,0],[0,i],[0,-i]]){let i=n.castRay([o[0]+e,d,o[2]+r],[0,-1,0],u,t);if(i){let t=i.distance;if(f=f===null?t:Math.min(f,t),e===0&&r===0)break}}this.grounded=f!==null&&f<l*2;let p=0,m=0,h=!1;try{let e=r.getVector(this.moveAction);h=e.x!==0||e.y!==0;let t=this.view===`free`||this.view===`firstPerson`?this.yaw:0,n=this.view===`side`?[e.x,0,0]:ww(e.x,-e.y,t),i=Math.hypot(n[0],n[2])||1;p=n[0]/i,m=n[2]/i}catch{}let g=fD(r,this.sprintAction),_=Tw(h,g),v=1+(this.sprintMultiplier-1)*_,y=h?this.maxSpeed*v:0,b=this.grounded?1:GE,x=(p*y-s[0])/WE*b,S=(m*y-s[2])/WE*b;if(t.applyImpulse([x*c,0,S*c]),!h&&this.grounded&&t.applyImpulse([-s[0]*KE*c,0,-s[2]*KE*c]),f!==null&&f<l*2){let e=qE*(l-f)-s[1]*JE;t.applyImpulse([0,e*c,0])}if(this.grounded&&fD(r,this.jumpAction)){let e=this.jumpVelocity*(1+(this.sprintJumpMultiplier-1)*_);t.linearVelocity=[s[0],e,s[2]],this.grounded=!1}s[1]<XE?t.gravityScale=0:s[1]<0&&!this.grounded?t.gravityScale=YE:t.gravityScale=1,this.view===`side`&&Math.abs(o[2])>.01&&(t.position=[t.position[0]??0,t.position[1]??0,0]);let C=Ew(this.grounded,h?_:0);if(C!==this.state){this.state=C;let e=this.animations[C];if(e&&this.skinPath!==``){let t=this.getNodeOrNull(this.skinPath);t&&`animation`in t&&(t.animation=e)}this.emit(`movementStateChanged`,C)}if(h&&this.skinPath!==``){let t=this.getNodeOrNull(this.skinPath);if(t){let n=Math.atan2(p,m)*QE+this.skinYawOffset,r=t.rotation[1]??0,i=(n-r+540)%360-180,a=this.turnSpeed*e*QE;Math.abs(i)>a&&(i=Math.sign(i)*a),t.rotation=[t.rotation[0]??0,r+i,t.rotation[2]??0]}}}update(e){let t=this.tree?.engine?.input;if(!t)return;if(this.mouseLook){let e=t.pointerDelta();this.yaw-=e.x*ZE,this.pitch=uD(this.pitch+e.y*ZE,-this.pitchMax,-this.pitchMin);let n=t.wheelDelta();n!==0&&this.zoomMax>this.zoomMin&&(this.camDistance=uD(this.camDistance+n*ZE,this.zoomMin,this.zoomMax))}let n=this.findCamera();if(!n)return;let r=this.parent instanceof Ph?this.parent:null;if(!r)return;let i=dD(r),a=this.view===`free`?11:1e3,o=1-Math.exp(-a*e),s=this.pivot??[i[0],i[1],i[2]];this.pivot=s,s[0]+=(i[0]-s[0])*o,s[1]+=(i[1]-s[1])*o,s[2]+=(i[2]-s[2])*o;let c=xw(this.view,s,this.eyeHeight,this.yaw,this.pitch,this.camDistance),l=[s[0],s[1]+this.eyeHeight,s[2]],u=[c.position[0],c.position[1],c.position[2]];if(this.cameraCollision&&this.view!==`firstPerson`){let e=r._physics3d;e&&(u=Sw(l,u,(t,n,i)=>e.castSphere(t,n,nD,i,r,{staticOnly:!0})?.distance??null,$E,eD),u=Cw(u,(t,n)=>e.castRay(t,[0,-1,0],n,r,{staticOnly:!0})?.distance??null,tD))}let d=this.view===`firstPerson`?1e3:this.camLerp,f=1-Math.exp(-d*e),p=n.position;n.position=[(p[0]??0)+(u[0]-(p[0]??0))*f,(p[1]??0)+(u[1]-(p[1]??0))*f,(p[2]??0)+(u[2]-(p[2]??0))*f],this.view===`free`?(oD.set(n.position[0]??0,n.position[1]??0,n.position[2]??0),sD.set(l[0],l[1],l[2]),aD.lookAt(oD,sD,cD),iD.setFromRotationMatrix(aD),rD.setFromQuaternion(iD,`XYZ`)):(rD.set(c.rotation[0],c.rotation[1],c.rotation[2],`YXZ`),iD.setFromEuler(rD),rD.setFromQuaternion(iD,`XYZ`)),n.rotation=[rD.x*QE,rD.y*QE,rD.z*QE]}pivot=null;cameraCache=null;findCamera(){if(this.cameraCache?.tree===this.tree&&this.cameraCache.current)return this.cameraCache;this.cameraCache=null;let e=this.tree?.root;if(!e)return null;let t=e=>{if(!this.cameraCache){if(e instanceof UE&&e.current){this.cameraCache=e;return}for(let n of e.children)t(n)}};return t(e),this.cameraCache}};function uD(e,t,n){return Math.min(n,Math.max(t,e))}function dD(e){let t=0,n=0,r=0;for(let i=e;i&&i instanceof Ah;i=i.parent)t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0;return[t,n,r]}function fD(e,t){try{return e.isPressed(t)}catch{return!1}}var pD=.15,mD=.7,hD=.5,gD=.7,_D=.5;function vD(e,t,n=3){let r=0,i=1,a=1,o=.65;for(let s=0;s<n;s++){let n=e*a,s=t*a,c=Math.sin(n*.1+s*.2)*.5+.5,l=Math.cos(n*.3+s*.1)*.5+.5,u=Math.sin((n+s)*.15)*.5+.5,d=Math.cos(n*n*.01+s*.2)*.5+.5,f=c*l*.7+u*d*.3;r+=f*i,i*=o,a*=2}return r/((1-o**n)/(1-o))}function yD(e,t){let n=vD(e*pD,t*pD,4),r=vD(e*pD*.2,t*pD*.2,2);return n>hD-mD*.5-r*_D}var bD=.9;function xD(e,t,n){let r=(Math.imul(e,2246822507)^Math.imul(t,3266489909)^Math.imul(n+1,668265263))>>>0;return r=Math.imul(r^r>>>15,739982445)>>>0,r=Math.imul(r^r>>>12,695872825)>>>0,r^=r>>>15,(r>>>0)/4294967296}function SD(e,t,n=bD){let r=Math.floor(e/n),i=Math.floor(t/n),a=1/0,o=r,s=i;for(let c=-1;c<=1;c++)for(let l=-1;l<=1;l++){let u=r+l,d=i+c,f=(u+xD(u,d,0))*n,p=(d+xD(u,d,1))*n,m=(e-f)*(e-f)+(t-p)*(t-p);m<a&&(a=m,o=u,s=d)}return{id:Math.imul(o,2654435761)^Math.imul(s,2246822519)|0,hue:xD(o,s,2)*2-1,leanDir:xD(o,s,3)*Math.PI*2,lean:xD(o,s,4)}}function CD(e,t,n,r){let i=e*r,a=t*r,o=Math.floor(i),s=Math.floor(a),c=i-o,l=a-s,u=c*c*(3-2*c),d=l*l*(3-2*l),f=xD(o,s,n),p=xD(o+1,s,n),m=xD(o,s+1,n),h=xD(o+1,s+1,n),g=f+(p-f)*u;return g+(m+(h-m)*u-g)*d}var wD=[.55,1.7],TD=.17,ED=.23,DD=.28;function OD(e,t,n){let r=CD(e,t,n^6877377|0,TD),i=r*r*(3-2*r);return wD[0]+(wD[1]-wD[0])*i}function kD(e,t,n){return CD(e,t,n^3001105|0,ED)}function AD(e,t,n){let r=CD(e,t,n^7840757|0,DD)*.72+CD(e,t,n^1688295|0,DD*3.1)*.28,i=Math.min(1,Math.max(0,(r-.18)/.64));return i*i*(3-2*i)}function jD(e){let{seed:t,areaX:n,areaZ:r,count:i,density:a}=e,o=new P(t),s=n/2,c=r/2,l=[],u=Math.floor(i*gD);for(let e=0;e<u&&l.length<i;e++){let e=o.range(-s,s),t=o.range(-c,c),n=o.next()<.3,r=yD(e,t);if(!n&&!r&&o.next()>.15)continue;let i=o.next()*Math.PI*2,a=.5+o.next()*.7,u=r?a*(1+o.next()*.2):a*(.9+o.next()*.2);l.push({x:e,z:t,rotY:i,scale:u})}let d=Math.min(3,Math.max(1,a*10)),f=Math.ceil(Math.sqrt(i*d)),p=n/f,m=r/f,h=Math.floor((i-l.length)*.8),g=0;for(let e=0;e<f&&l.length<i;e++)for(let t=0;t<f&&l.length<i;t++){let i=t/f*n-s+p/2,a=e/f*r-c+m/2,u=i+(o.next()-.5)*p*1.5,d=a+(o.next()-.5)*m*1.5;if(u<-s||u>s||d<-c||d>c)continue;let _=yD(u,d);if(g<h){if(!_&&o.next()>.05)continue}else if(_){if(o.next()>.2)continue}else if(o.next()>.4)continue;if(o.next()<.2)continue;let v=o.next()*Math.PI*2,y=_?.5:.3;l.push({x:u,z:d,rotY:v,scale:.5+o.next()*y}),g++}for(;l.length<i;)l.push({x:o.range(-s,s),z:o.range(-c,c),rotY:o.next()*Math.PI*2,scale:.4+o.next()*.6});return l.sort((e,t)=>t.z-e.z),l}var MD=[`daisy`,`cosmos`,`bellflower`],ND={daisy:{petals:8,blooms:3,leaves:3,petalLength:.1,petalWidth:.052,cupDeg:16,nodDeg:14,centerRadius:.024,centerColor:`#e0a72e`},cosmos:{petals:8,blooms:2,leaves:2,petalLength:.12,petalWidth:.064,cupDeg:26,nodDeg:18,centerRadius:.023,centerColor:`#d2941f`},bellflower:{petals:5,blooms:3,leaves:2,petalLength:.088,petalWidth:.058,cupDeg:46,nodDeg:52,centerRadius:.015,centerColor:`#cfe06a`}},PD=[1,.78,.62],FD=[0,.07,.11],ID=[.6,2.7,4.9],LD=.07,RD=.011,zD=.17,BD=.05,VD=[.12,.2,.28],HD=new K(`#3e6a26`),UD=new K(`#548331`);function WD(e){let t=ND[e],n=new GD(!0),r=new GD(!1),i=new K(t.centerColor);for(let e=0;e<t.blooms;e++){let a=PD[e],o=ID[e],s=FD[e]*Math.cos(o),c=FD[e]*Math.sin(o),l=LD*Math.cos(o),u=LD*Math.sin(o),d=new U(s,0,c),f=new U(s+l,a,c+u),p=new U(s+l*.25,a*.55,c+u*.25);n.addStem(d,p,f,RD,HD);let m=t.nodDeg*Math.PI/180,h=new U(Math.sin(m)*Math.cos(o),Math.cos(m),Math.sin(m)*Math.sin(o)),g=new U(-Math.sin(o),0,Math.cos(o)),_=new U().crossVectors(h,g).normalize(),v=f.clone().addScaledVector(h,.012),y=t.cupDeg*Math.PI/180,b=e*.45;for(let e=0;e<t.petals;e++){let n=e/t.petals*Math.PI*2+b,i=g.clone().multiplyScalar(Math.cos(n)).addScaledVector(_,Math.sin(n)).normalize();r.addPetal(v,i,h,t,y)}n.addDisc(v.clone().addScaledVector(h,.004),g,_,t.centerRadius,i)}for(let e=0;e<t.leaves;e++){let t=VD[e%VD.length],r=1.1+e*2.3;n.addLeaf(new U(0,t,0),r,UD)}return{structure:n.build(),petals:r.build()}}var GD=class{positions=[];colors;indices=[];constructor(e){this.colors=e?[]:null}vertex(e,t){let n=this.positions.length/3;return this.positions.push(e.x,e.y,e.z),this.colors&&t&&this.colors.push(t.r,t.g,t.b),n}addStem(e,t,n,r,i){for(let a of[0,Math.PI/2]){let o=new U(Math.cos(a),0,Math.sin(a)),s=[];for(let a=0;a<=5;a++){let c=a/5,l=1-c,u=new U(l*l*e.x+2*l*c*t.x+c*c*n.x,l*l*e.y+2*l*c*t.y+c*c*n.y,l*l*e.z+2*l*c*t.z+c*c*n.z),d=r/2*(1-.4*c);s.push(this.vertex(u.clone().addScaledVector(o,-d),i),this.vertex(u.clone().addScaledVector(o,d),i))}for(let e=0;e<5;e++){let t=s[e*2],n=s[e*2+1],r=s[e*2+2],i=s[e*2+3];this.indices.push(t,n,r,r,n,i)}}}addPetal(e,t,n,r,i){let a=new U().crossVectors(n,t).normalize(),o=r.centerRadius*.85,s=Math.sin(i)*r.petalLength*.45,c=Math.sin(i)*r.petalLength*.95,l=Math.cos(i),u=e.clone().addScaledVector(t,o),d=o+r.petalLength*l*.55,f=o+r.petalLength*l,p=e.clone().addScaledVector(t,d).addScaledVector(a,r.petalWidth/2).addScaledVector(n,s),m=e.clone().addScaledVector(t,d).addScaledVector(a,-r.petalWidth/2).addScaledVector(n,s),h=e.clone().addScaledVector(t,f).addScaledVector(n,c),g=this.vertex(u,null),_=this.vertex(p,null),v=this.vertex(m,null),y=this.vertex(h,null);this.indices.push(g,_,y,g,y,v)}addDisc(e,t,n,r,i){let a=this.vertex(e,i),o=[];for(let a=0;a<6;a++){let s=a/6*Math.PI*2;o.push(this.vertex(e.clone().addScaledVector(t,Math.cos(s)*r).addScaledVector(n,Math.sin(s)*r),i))}for(let e=0;e<6;e++)this.indices.push(a,o[e],o[(e+1)%6])}addLeaf(e,t,n){let r=new U(Math.cos(t),0,Math.sin(t)),i=new U(-Math.sin(t),0,Math.cos(t)),a=Math.sin(.6),o=Math.cos(.6),s=e.clone().addScaledVector(r,zD*o*.5).add(new U(0,zD*a*.5,0)),c=e.clone().addScaledVector(r,zD*o).add(new U(0,zD*a*.8,0)),l=this.vertex(e,n),u=this.vertex(s.clone().addScaledVector(i,BD/2),n),d=this.vertex(s.clone().addScaledVector(i,-.05/2),n),f=this.vertex(c,n);this.indices.push(l,u,f,l,f,d)}build(){let e=new J;return e.setAttribute(`position`,new q(new Float32Array(this.positions),3)),this.colors&&e.setAttribute(`color`,new q(new Float32Array(this.colors),3)),e.setIndex(this.indices),e.computeVertexNormals(),e}},KD=2.6;function qD(e){let{seed:t,areaX:n,areaZ:r,count:i,clustering:a}=e,o=new P(t),s=n/2,c=r/2,l=1-.74*Math.min(Math.max(a,0),1),u=[];for(let e=0;e<i*16&&u.length<i;e++){let e=o.range(-s,s),t=o.range(-c,c),n=SD(e,t,KD);n.lean>l&&o.next()>.06||u.push({x:e,z:t,rotY:o.next()*Math.PI*2,scale:.75+o.next()*.5,variety01:(n.hue+1)/2,color01:n.leanDir/(Math.PI*2)})}return u}var JD=1.05,YD=1;function XD(e,t=YD){e.computeBoundingSphere();let n=e.boundingSphere;n&&n.radius>=0&&(n.radius=n.radius*JD+t),e.frustumCulled=!0}function ZD(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Ah&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return[t,n,r]}function QD(e,t){if(t!==``){let n=e.getNodeOrNull(t);return n instanceof _T?n:null}return $D(e.getRoot())}function $D(e){if(e instanceof _T)return e;for(let t of e.children){let e=$D(t);if(e)return e}return null}function eO(e){return typeof e?._waterYAt==`function`}function tO(e){let t=e;for(;t.parent;)t=t.parent;let n=[],r=e=>{e.visible!==!1&&eO(e)&&n.push(e);for(let t of e.children)r(t)};return r(t),n}function nO(e,t,n,r,i=.06){for(let a=0;a<e.length;a++){let o=e[a]?._waterYAt(t,n);if(o!=null&&o-r>i)return!0}return!1}var rO={lush:2.2,sparse:.35,none:0},iO=[`lush`,`sparse`,`none`];function aO(e){if(typeof e==`number`)return e;let t=rO[e];if(t===void 0)throw new N(`BAD_FORMAT`,`Flowers3D density must be one of [${iO.join(`, `)}] or a number (plants/m²), got '${e}'.`,{prop:`density`,validOptions:iO});return t}var oO=1e4,sO=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],cO=/^#[0-9a-fA-F]{6}$/,lO=class extends Ah{static typeName=`Flowers3D`;static props={density:{default:`sparse`,options:iO},area:{default:[20,20]},seed:{default:1},varieties:{default:[]},palette:{default:[]},height:{default:.45},clustering:{default:.6},sway:{default:.5},drape:{default:null},avoidWater:{default:!0},terrain:{default:``,nodePath:!0}};density=`sparse`;area=[20,20];seed=1;varieties=[];palette=[];height=.45;clustering=.6;sway=.5;drape=null;avoidWater=!0;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(typeof t.density==`string`)aO(t.density);else if(!(Number.isFinite(t.density)&&t.density>=0))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' density must be one of [${iO.join(`, `)}] or a number >= 0 (plants/m²), got ${t.density}.`,{prop:`density`,validOptions:iO});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});let n=Math.floor((t.area[0]??0)*(t.area[1]??0)*aO(t.density));if(n>oO)throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' blows the plant budget: area ${t.area[0]}×${t.area[1]} m × density ${aO(t.density)} = ${n} plants > ${oO}. Lower the density or split the field into multiple nodes.`,{prop:`density`});if(!Array.isArray(t.varieties)||new Set(t.varieties).size!==t.varieties.length||!t.varieties.every(e=>MD.includes(e)))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' varieties must be a unique subset of [${MD.join(`, `)}] ([] = all three), got ${JSON.stringify(t.varieties)}.`,{prop:`varieties`,validOptions:[...MD]});if(!Array.isArray(t.palette)||!t.palette.every(e=>typeof e==`string`&&cO.test(e)))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' palette must be an array of '#rrggbb' head colors ([] = white/yellow/violet), got ${JSON.stringify(t.palette)}.`,{prop:`palette`});if(!(t.height>0))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!(t.clustering>=0)||!(t.clustering<=1))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' clustering must be in [0, 1] (0 uniform … 1 tight patches), got ${t.clustering}.`,{prop:`clustering`});if(!(t.sway>=0))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' sway must be >= 0, got ${t.sway}.`,{prop:`sway`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`})}time=0;field=null;varietyMeshes=[];fieldKey=``;timeUniform={value:0};swayUniform={value:.5};_createObject3D(){return new _o}_varietyMeshes(){return this.rebuildIfNeeded(),this.varietyMeshes}update(e){this.time+=e,this.timeUniform.value=this.time}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded(),this.swayUniform.value=this.sway}rebuildIfNeeded(){this.field||(this.field=new _o,this._ensureObject3D().add(this.field));let e=JSON.stringify([this.density,this.area,this.seed,this.varieties,this.palette,this.height,this.clustering,this.drape,this.terrain]);e!==this.fieldKey&&(this.fieldKey=e,this.disposeMeshes(),this.resolveDrape(),this.buildField())}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=QD(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=ZD(this);else if(this.terrain!==``)throw new N(`NODE_NOT_FOUND`,`Flowers3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}buildField(){let e=aO(this.density),t=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*e),oO);if(t<=0)return;let n=qD({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:t,clustering:this.clustering});if(this.avoidWater){let e=tO(this);if(e.length>0){let[t,r,i]=ZD(this);n=n.filter(n=>!nO(e,n.x+t,n.z+i,this.bedY(n.x,n.z)+r))}}let r=this.varieties.length>0?this.varieties:MD,i=r.map(()=>[]);for(let e of n)i[Math.min(Math.floor(e.variety01*r.length),r.length-1)].push(e);let a=this.palette.length>0?this.palette:sO,o=new P(this.seed+15797765);for(let e=0;e<r.length;e++){let t=i[e];if(t.length===0)continue;let{structure:n,petals:s}=WD(r[e]),c=new bl({vertexColors:!0,roughness:1,side:2}),l=new bl({roughness:.85,side:2});uO(c,this.timeUniform,this.swayUniform),uO(l,this.timeUniform,this.swayUniform);let u=new xc(n,c,t.length),d=new xc(s,l,t.length);u.receiveShadow=!0,d.receiveShadow=!0;for(let e=0;e<t.length;e++){let n=t[e];pO.set(n.x,this.bedY(n.x,n.z),n.z),mO.setFromAxisAngle(dO,n.rotY),hO.setScalar(this.height*n.scale),fO.compose(pO,mO,hO),u.setMatrixAt(e,fO),d.setMatrixAt(e,fO);let r=Math.min(Math.floor(n.color01*a.length),a.length-1);gO.set(a[r]).offsetHSL(o.range(-.02,.02),0,o.range(-.05,.05)),d.setColorAt(e,gO),gO.setRGB(1,1,1).offsetHSL(o.range(-.02,.02),0,o.range(-.06,.04)),u.setColorAt(e,gO)}u.instanceMatrix.needsUpdate=!0,d.instanceMatrix.needsUpdate=!0,u.instanceColor&&(u.instanceColor.needsUpdate=!0),d.instanceColor&&(d.instanceColor.needsUpdate=!0),XD(u),XD(d),this.varietyMeshes.push({variety:r[e],structure:u,petals:d}),this.field.add(u),this.field.add(d)}}disposeMeshes(){for(let{structure:e,petals:t}of this.varietyMeshes)for(let n of[e,t])n.removeFromParent(),n.geometry.dispose(),n.material.dispose(),n.dispose();this.varietyMeshes=[]}free(){this.disposeMeshes(),this.field=null,super.free()}};function uO(e,t,n){e.userData.sway=!0,e.userData.timeUniform=t,e.onBeforeCompile=e=>{e.uniforms.uFlowerTime=t,e.uniforms.uFlowerSway=n,e.vertexShader=`uniform float uFlowerTime;\nuniform float uFlowerSway;\n${e.vertexShader}`.replace(`#include <project_vertex>`,`
6976
+ `;function tT(e,t){for(let n=0;n<4;n++){let r=n+1;e.uniforms[`splatTexture${r}`]={value:t.textures[n]??t.textures[0]??null},e.uniforms[`splatNormalMap${r}`]={value:t.normalMaps[n]??null},e.uniforms[`splatTextureRepeat${r}`]={value:t.repeats[n]??1},e.uniforms[`splatRoughness${r}`]={value:t.roughness[n]??1},e.uniforms[`splatMetalness${r}`]={value:t.metalness[n]??0},e.uniforms[`uvNoiseIntensity${r}`]={value:t.uvNoiseIntensity[n]??.15}}e.uniforms.splatTextureCount={value:Math.min(4,t.layerCount)},e.uniforms.uWetlineY={value:-1e9},e.uniforms.uWetlineBand={value:1.1},e.uniforms.uWetTime={value:0},e.uniforms.splatEnvCut={value:t.envCut},e.vertexShader=Kw(e.vertexShader,`#include <common>`,qw),e.vertexShader=Kw(e.vertexShader,`#include <begin_vertex>`,Jw);let n=e.fragmentShader;n=Kw(n,`#include <common>`,Yw),n=Kw(n,`#include <color_fragment>`,Xw),n=Kw(n,`#include <roughnessmap_fragment>`,Zw),n=Kw(n,`#include <metalnessmap_fragment>`,$w),n=Kw(n,`#include <normal_fragment_maps>`,eT),n=Kw(n,`#include <lights_fragment_maps>`,Qw),t.hasNormalMaps&&(n=`#define USE_TERRAIN_NORMALMAP\n${n}`),e.fragmentShader=n}var nT=[`island`,`alpine`,`plains`,`desert`,`grassland`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`,`custom`],rT=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,iT=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground`,aT=1/3,oT=Math.PI/4;function sT(e,t,n){return{texture:`${e}/${t}.png`,normalMap:`${e}/${t}_normal.png`,...n}}function cT(e,t){let n=t.replace(/\/$/,``);switch(e){case`island`:return[sT(n,`sand`,{heightRange:[0,.12],slopeRange:[0,Math.PI/2],heightBlendRange:.05,roughness:.9}),sT(n,`grass`,{heightRange:[.1,.7],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),sT(n,`stone`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.5,roughness:.85}),sT(n,`snow`,{heightRange:[.8,1],slopeRange:[0,Math.PI/3],heightBlendRange:.1,roughness:.6})];case`alpine`:return[sT(n,`grass`,{heightRange:[0,.45],slopeRange:[0,Math.PI/5],heightBlendRange:.1,roughness:.8}),sT(n,`stone`,{heightRange:[.3,1],slopeRange:[0,Math.PI],heightBlendRange:.25,slopeBlendRange:.5,roughness:.85}),sT(n,`gravel`,{heightRange:[0,1],slopeRange:[Math.PI/5,Math.PI],heightBlendRange:.5,slopeBlendRange:.15,roughness:.9}),sT(n,`snow`,{heightRange:[.55,1],slopeRange:[0,Math.PI/3],heightBlendRange:.12,roughness:.55})];case`plains`:return[sT(n,`grass`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),sT(n,`dirt`,{heightRange:[.35,.65],slopeRange:[0,Math.PI/5],heightBlendRange:.2,roughness:.9}),sT(n,`gravel`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`desert`:return[sT(n,`sand`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),sT(n,`gravel`,{heightRange:[0,.15],slopeRange:[0,Math.PI/3],heightBlendRange:.08,roughness:.9}),sT(n,`stone`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.4,roughness:.85})];case`grassland`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${iT}/grass.jpg`,heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:1,repeat:aT,uvNoiseIntensity:0},{texture:`${iT}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:1,repeat:aT,uvNoiseIntensity:0}]:[sT(n,`grass`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:.8}),sT(n,`dirt`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`forest`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${iT}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:1,repeat:aT,uvNoiseIntensity:0},{texture:`${iT}/grass.jpg`,heightRange:[-2,-1],roughness:1,repeat:aT,uvNoiseIntensity:0}]:[sT(n,`dirt`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.9}),sT(n,`grass`,{heightRange:[-2,-1],roughness:.8})];case`savanna`:return[sT(n,`grass`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),sT(n,`sand`,{heightRange:[0,.22],slopeRange:[0,Math.PI/4],heightBlendRange:.12,roughness:.95}),sT(n,`dirt`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`snow`:return[sT(n,`snow`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.18,roughness:.55}),sT(n,`stone`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.35,roughness:.85})];case`wetland`:return[sT(n,`grass`,{heightRange:[0,1],slopeRange:[0,oT],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),sT(n,`dirt`,{heightRange:[0,1],slopeRange:[oT,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`volcanic`:return[sT(n,`stone`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.95}),sT(n,`gravel`,{heightRange:[0,.28],slopeRange:[0,Math.PI/3],heightBlendRange:.14,slopeBlendRange:.2,roughness:.95})];case`custom`:return[]}}var lT={scale:100,threshold:.7,blend:.1},uT={scale:55,threshold:.58,blend:.12},dT={scale:85,threshold:.62,blend:.12},fT={scale:48,threshold:.5,blend:.14};function pT(e,t){let n=dn(e+27927);return(e,r)=>{let i=(.5+.5*n(e/t.scale,r/t.scale)-(t.threshold-t.blend))/(2*t.blend),a=Math.min(1,Math.max(0,i));return a*a*(3-2*a)}}function mT(e,t){return e===`grassland`?pT(t,lT):e===`forest`?pT(t,uT):e===`savanna`?pT(t,dT):e===`wetland`?pT(t,fT):null}function hT(e){return e===`savanna`?{from:0,to:2}:e===`grassland`||e===`forest`||e===`wetland`?{from:0,to:1}:null}var gT=256,_T=class extends Ah{orderGroup=`terrain`;static typeName=`Terrain3D`;static props={orderGroup:{default:`terrain`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},size:{default:[200,200]},maxHeight:{default:28},seed:{default:1},resolution:{default:128},theme:{default:`island`,options:nT},roughness:{default:.5},detail:{default:4},flatThreshold:{default:.95},islandEdge:{default:null},layers:{default:[]},textureBase:{default:rT},basins:{default:[]},channels:{default:[]},wetline:{default:null}};size=[200,200];maxHeight=28;seed=1;resolution=128;theme=`island`;roughness=.5;detail=4;flatThreshold=.95;islandEdge=null;layers=[];textureBase=rT;basins=[];channels=[];externalChannels=new Map;externalRev=0;shapeStamp=null;wetline=null;splatUniforms=null;wetTime=0;update(e){this.wetTime+=e;let t=this.splatUniforms;if(!t)return;let n=this.wetline;t.uWetlineY&&(t.uWetlineY.value=typeof n?.y==`number`?n.y:-1e9),t.uWetlineBand&&(t.uWetlineBand.value=typeof n?.band==`number`?n.band:1.1),t.uWetTime&&(t.uWetTime.value=this.wetTime)}static validateJson(e){let t=e;if(!nT.includes(t.theme))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' theme must be one of [${nT.join(`, `)}], got '${t.theme}'.`,{prop:`theme`,validOptions:nT});if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' size must be positive [width, depth] meters, got ${JSON.stringify(t.size)}.`,{prop:`size`});if(!(t.maxHeight>0))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' maxHeight must be > 0, got ${t.maxHeight}.`,{prop:`maxHeight`});if(!Number.isInteger(t.resolution)||t.resolution<2||t.resolution>gT)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' resolution must be an integer in [2, ${gT}] (grid segments per side), got ${t.resolution}.`,{prop:`resolution`});if(!(t.roughness>0)||!Number.isFinite(t.roughness))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' roughness must be a finite number > 0, got ${t.roughness}.`,{prop:`roughness`});if(!Number.isInteger(t.detail)||t.detail<0)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' detail must be an integer ≥ 0 (octave count), got ${t.detail}.`,{prop:`detail`});if(!(t.flatThreshold>=0)||!Number.isFinite(t.flatThreshold))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' flatThreshold must be a finite number ≥ 0, got ${t.flatThreshold}.`,{prop:`flatThreshold`});if(t.islandEdge!==null&&typeof t.islandEdge!=`boolean`)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' islandEdge must be true, false or null (null = theme default), got ${JSON.stringify(t.islandEdge)}.`,{prop:`islandEdge`});let n=t.wetline;if(n!==null){if(typeof n!=`object`||Array.isArray(n)||!Number.isFinite(n.y))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' wetline must be null or { y, band? } with a finite y, got ${JSON.stringify(t.wetline)}.`,{prop:`wetline`});if(n.band!==void 0&&!(n.band>0))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' wetline.band must be > 0 meters, got ${JSON.stringify(n.band)}.`,{prop:`wetline`})}if(!Array.isArray(t.basins))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' basins must be an array of { x, z, radius, depth }, got ${JSON.stringify(t.basins)}.`,{prop:`basins`});if(t.basins.forEach((t,n)=>{if(!t||typeof t!=`object`||!Number.isFinite(t.x)||!Number.isFinite(t.z)||!(t.radius>0)||!Number.isFinite(t.depth)||t.depth===0)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' basins[${n}] needs finite x, z, positive radius and nonzero depth (negative = mound), got ${JSON.stringify(t)}.`,{prop:`basins`})}),!Array.isArray(t.channels))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' channels must be an array of { path, width, depth, taper? }, got ${JSON.stringify(t.channels)}.`,{prop:`channels`});if(t.channels.forEach((t,n)=>{let r=t.path;if(!(t&&typeof t==`object`&&Array.isArray(r)&&r.length>=2&&r.every(e=>Array.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1]))&&t.width>0&&t.depth>0&&(t.taper===void 0||t.taper>0)))throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' channels[${n}] needs a path of 2+ [x, z] points plus positive width and depth, got ${JSON.stringify(t)}.`,{prop:`channels`})}),t.theme===`custom`){if(!Array.isArray(t.layers)||t.layers.length<1||t.layers.length>4)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' theme 'custom' needs 1–4 layers, got ${Array.isArray(t.layers)?t.layers.length:typeof t.layers}.`,{prop:`layers`});t.layers.forEach((t,n)=>{bT(e.name,t,n)})}else if(Array.isArray(t.layers)&&t.layers.length>0)throw new N(`BAD_FORMAT`,`Terrain3D '${e.name}' layers is only read with theme 'custom' — preset theme '${t.theme}' defines its own. Drop layers or switch to theme: 'custom'.`,{prop:`layers`})}heightmap=null;heightmapKey=``;builtKey=``;_createObject3D(){let e=new J;return e.setAttribute(`position`,new q(new Float32Array,3)),new Ys(e,new bl({vertexColors:!0}))}heightAt(e,t){let n=0,r=0,i=0;for(let e=this;e;e=e.parent)e instanceof Ah&&(n+=e.position[0]??0,r+=e.position[1]??0,i+=e.position[2]??0);return this._heightmap().heightAt(e-n,t-i)+r}_setExternalChannel(e,t){t===null||t.length===0?this.externalChannels.delete(e):this.externalChannels.set(e,t),this.externalRev++}allChannels(){return this.externalChannels.size===0?this.channels:[...this.channels,...[...this.externalChannels.values()].flat()]}_heightmap(){if(this.heightmap&&this.shapeUnchanged())return this.heightmap;let e=this.segments(),t=JSON.stringify([this.size,this.maxHeight,this.seed,e,this.roughness,this.detail,this.flatThreshold,this.effectiveIslandEdge(),this.basins,this.allChannels()]);return(!this.heightmap||t!==this.heightmapKey)&&(this.heightmap=Uw({width:this.size[0]??1,depth:this.size[1]??1,segsX:e,segsZ:e,maxHeight:this.maxHeight,seed:this.seed,roughness:this.roughness,detail:this.detail,flatThreshold:this.flatThreshold,islandEdge:this.effectiveIslandEdge(),basins:this.basins,channels:this.allChannels()}),this.heightmapKey=t),this.rememberShape(),this.heightmap}shapeUnchanged(){let e=this.shapeStamp;return e!==null&&e.sizeX===(this.size[0]??0)&&e.sizeZ===(this.size[1]??0)&&e.maxHeight===this.maxHeight&&e.seed===this.seed&&e.segments===this.segments()&&e.roughness===this.roughness&&e.detail===this.detail&&e.flatThreshold===this.flatThreshold&&e.islandEdge===this.effectiveIslandEdge()&&e.basins===this.basins&&e.channels===this.channels&&e.externalRev===this.externalRev}rememberShape(){this.shapeStamp={sizeX:this.size[0]??0,sizeZ:this.size[1]??0,maxHeight:this.maxHeight,seed:this.seed,segments:this.segments(),roughness:this.roughness,detail:this.detail,flatThreshold:this.flatThreshold,islandEdge:this.effectiveIslandEdge(),basins:this.basins,channels:this.channels,externalRev:this.externalRev}}resolvedLayers(){return this.theme===`custom`?this.layers:cT(this.theme,this.textureBase)}_syncObject3D(e=1,t=null){super._syncObject3D(e,t),this.rebuildIfNeeded(t)}effectiveIslandEdge(){return this.islandEdge??this.theme===`island`}segments(){return Math.max(2,Math.min(Math.floor(this.resolution),gT))}rebuildIfNeeded(e){let t=JSON.stringify([this.size,this.maxHeight,this.seed,this.segments(),this.theme,this.roughness,this.detail,this.flatThreshold,this.islandEdge,this.layers,this.textureBase,this.basins,this.allChannels()]);if(t===this.builtKey)return;this.builtKey=t;let n=this._ensureObject3D();n.geometry.dispose(),n.geometry=this.buildGeometry(),n.material.dispose(),n.material=this.buildMaterial(e),n.receiveShadow=!0,n.castShadow=!0}buildGeometry(){let e=this._heightmap(),t=new cl(e.width,e.depth,e.segsX,e.segsZ);t.rotateX(-Math.PI/2);let n=t.getAttribute(`position`);for(let t=0;t<n.count;t++)n.setY(t,e.heights[t]);n.needsUpdate=!0,t.computeVertexNormals();let r=this.resolvedLayers(),i=e.maxHeight-e.minHeight||1,a=new Float32Array(n.count*3),o=this.theme===`custom`?null:hT(this.theme),s=o?mT(this.theme,this.seed):null;for(let t=0;t<n.count;t++){let c=n.getX(t),l=n.getZ(t),u=Gw(Math.min(1,Math.max(0,(n.getY(t)-e.minHeight)/i)),e.slopeAt(c,l),r);if(s&&o){let e=(u[o.from]??0)*s(c,l);u[o.from]=(u[o.from]??0)-e,u[o.to]=(u[o.to]??0)+e}a[t*3]=u[0],a[t*3+1]=u[1],a[t*3+2]=u[2]}return t.setAttribute(`color`,new q(a,3)),t}buildMaterial(e){let t=this.resolvedLayers(),n=new bl({vertexColors:!0}),r=(t,n)=>t?gw(e,t,{wrap:`repeat`,anisotropy:8,colorSpace:n?`srgb`:`linear`}):null,i=t.map(e=>r(e.texture,!0)),a=t.map(e=>r(e.normalMap,!1)),o=a.some(e=>e!==null);if(o)for(let e=0;e<a.length;e++)a[e]||(a[e]=yT());let s={textures:i,normalMaps:a,repeats:t.map(e=>e.repeat??2),roughness:t.map(e=>e.roughness??1),metalness:t.map(e=>e.metalness??0),uvNoiseIntensity:t.map(e=>e.uvNoiseIntensity??.15),envCut:.45,layerCount:Math.min(4,t.length),hasNormalMaps:o};return n.onBeforeCompile=e=>{tT(e,s),this.splatUniforms=e.uniforms},n.customProgramCacheKey=()=>`incanto-terrain-splat:${+!!o}`,n}free(){let e=this._ensureObject3D();e.geometry.dispose(),e.material.dispose(),this.heightmap=null,super.free()}},vT=null;function yT(){return vT||(vT=new lc(new Uint8Array([128,128,255,255]),1,1),vT.needsUpdate=!0),vT}function bT(e,t,n){let r=`layers[${n}]`;if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`BAD_FORMAT`,`Terrain3D '${e}' ${r} must be an object ({texture, heightRange?, slopeRange?, …}).`,{prop:`layers`});let i=t;if(typeof i.texture!=`string`||i.texture.length===0)throw new N(`BAD_FORMAT`,`Terrain3D '${e}' ${r} needs "texture": a texture URL string.`,{prop:`layers`});for(let t of[`heightRange`,`slopeRange`]){let n=i[t];if(n!==void 0&&(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`||!Number.isFinite(e))))throw new N(`BAD_FORMAT`,`Terrain3D '${e}' ${r}.${t} must be [min, max] numbers, got ${JSON.stringify(n)}.`,{prop:`layers`})}}var xT=16,ST=new U,CT=new H;function wT(e,t){let n=e.translation(),r=e.rotation();CT.set(r.x,r.y,r.z,r.w);let i=(e,r,i)=>{ST.set(e,r,i).applyQuaternion(CT),t.push(ST.x+n.x,ST.y+n.y,ST.z+n.z)};return(e,t,n,r,a,o)=>{i(e,t,n),i(r,a,o)}}function TT(e,t,n,r,i=Math.PI*2,a=0){let o=e=>{let i=Math.cos(e)*t,a=Math.sin(e)*t;return n===`xy`?[i,a,r]:n===`xz`?[i,r,a]:[r,i,a]},s=Math.max(3,Math.round(xT*i/(Math.PI*2)));for(let t=0;t<s;t++){let[n,r,c]=o(a+i*t/s),[l,u,d]=o(a+i*(t+1)/s);e(n,r,c,l,u,d)}}function ET(e,t,n){let r=e=>[t[e*3],t[e*3+1],t[e*3+2]];if(n){for(let t=0;t<n.length;t+=3){let i=r(n[t]),a=r(n[t+1]),o=r(n[t+2]);e(...i,...a),e(...a,...o),e(...o,...i)}return}for(let n=0;n+5<t.length;n+=9){let t=r(n/3),i=r(n/3+1),a=r(n/3+2);e(...t,...i),e(...i,...a),e(...a,...t)}}function DT(e,t){let{nrows:n,ncols:r,heights:i,scale:a}=t,o=n+1,s=r+1,c=(e,t)=>[(e/n-.5)*a.x,i[t*o+e]*a.y,(t/r-.5)*a.z];for(let t=0;t<s;t++)for(let n=0;n<o;n++)n+1<o&&e(...c(n,t),...c(n+1,t)),t+1<s&&e(...c(n,t),...c(n,t+1))}function OT(e,t){let n=wT(e,t),r=e.shape;switch(e.shape.type){case 0:{let e=r.radius;TT(n,e,`xy`,0),TT(n,e,`xz`,0),TT(n,e,`yz`,0);return}case 1:{let e=r.halfExtents;for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(-e.x,t*e.y,r*e.z,e.x,t*e.y,r*e.z);for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(t*e.x,-e.y,r*e.z,t*e.x,e.y,r*e.z);for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(t*e.x,r*e.y,-e.z,t*e.x,r*e.y,e.z);return}case 2:{let{radius:e,halfHeight:t}=r;for(let r of[-1,1]){TT(n,e,`xz`,r*t);for(let i of[`xy`,`yz`])TT((e,i,a,o,s,c)=>n(e,i+r*t,a,o,s+r*t,c),e,i,0,Math.PI,r>0?0:Math.PI)}for(let[r,i]of[[1,0],[-1,0],[0,1],[0,-1]])n(r*e,-t,i*e,r*e,t,i*e);return}case 3:{let e=r;n(e.a.x,e.a.y,e.a.z,e.b.x,e.b.y,e.b.z);return}case 6:case 9:case 16:{let e=r;ET(n,e.vertices,e.indices);return}case 7:DT(n,r);return;case 10:case 14:{let{radius:e,halfHeight:t}=r;TT(n,e,`xz`,-t),TT(n,e,`xz`,t);for(let[r,i]of[[1,0],[-1,0],[0,1],[0,-1]])n(r*e,-t,i*e,r*e,t,i*e);return}case 11:case 15:{let{radius:e,halfHeight:t}=r;TT(n,e,`xz`,-t);for(let r=0;r<4;r++){let i=r/4*Math.PI*2;n(Math.cos(i)*e,-t,Math.sin(i)*e,0,t,0)}return}default:if(e.shape.type===12||e.shape.type===13){let e=r.halfExtents;e&&n(-e.x,-e.y,-e.z,e.x,e.y,e.z)}return}}var kT=Math.PI/180;async function AT(e,t){let n=await bm(()=>import(`./rapier-DE6a0vmv.js`),[],import.meta.url);return await n.init({}),new jT(n,e,t)}var jT=class{R;engine;debugDraw=!1;debugScope=null;dimension=`3d`;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,-9.81,0];this.world=new e.World({x:i[0]??0,y:i[1]??0,z:i[2]??0}),this.kcc=this.world.createCharacterController(.01),this.events=new e.EventQueue(!0),this.unregisterDebug=ev(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,-9.81,0];this.world.gravity={x:e[0]??0,y:e[1]??0,z:e[2]??0}}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,i]=ZT(e),a=[n.x-t,n.y-r,n.z-i];e._interpPrev=e._interpCurr??a,e._interpCurr=a;let o=e.position;o[0]=a[0],o[1]=a[1],o[2]=a[2]}if(e instanceof Ph){if(!e.fixedRotation){let n=t.body.rotation();NT.setFromQuaternion(MT.set(n.x,n.y,n.z,n.w),`XYZ`);let r=e.rotation;r[0]=NT.x/kT,r[1]=NT.y/kT,r[2]=NT.z/kT}let n=t.body.linvel(),r=e.linearVelocity;r[0]=n.x,r[1]=n.y,r[2]=n.z,t.lastV[0]=n.x,t.lastV[1]=n.y,t.lastV[2]=n.z}let r=YT(e);t.last[0]=r[0],t.last[1]=r[1],t.last[2]=r[2]}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)}})}poseFromTree(){for(let[e,t]of this.entries){let[n,r,i]=YT(e);t.body.setTranslation({x:n,y:r,z:i},!1),MT.setFromEuler(NT.set((e.rotation[0]??0)*kT,(e.rotation[1]??0)*kT,(e.rotation[2]??0)*kT,`XYZ`)),t.body.setRotation({x:MT.x,y:MT.y,z:MT.z,w:MT.w},!1)}this.world.propagateModifiedBodyPositionsToColliders()}moveAndSlide(e){let t=this.ensureEntry(e);if(!t)return;let n=e.velocity[1]??0;e.snapToGround&&n<=0?this.kcc.enableSnapToGround(.1):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*kT);let r=0,i=0,a=0;if(t.ground&&t.ground._physics===this&&t.groundAt){let[e,n,o]=YT(t.ground);r=e-t.groundAt[0],i=n-t.groundAt[1],a=o-t.groundAt[2]}else t.ground=null;let o={x:(e.velocity[0]??0)*this.lastDt+r,y:n*this.lastDt+i,z:(e.velocity[2]??0)*this.lastDt+a};this.kcc.computeColliderMovement(t.collider,o,this.R.QueryFilterFlags.EXCLUDE_SENSORS);let s=this.kcc.computedMovement(),c=t.body.translation(),l=c.x+s.x,u=c.y+s.y,d=c.z+s.z;if(t.body.setNextKinematicTranslation({x:l,y:u,z:d}),e._grounded=this.kcc.computedGrounded(),e._grounded){let n=JT(e),r=this.castRay([l,u-n+.05,d],[0,-1,0],.4,e);if(r?.node&&!(r.node instanceof Fh)){t.ground=r.node;let e=YT(r.node);t.groundAt=[e[0],e[1],e[2]]}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope;if(!e)return this.world.debugRender().vertices;let t=this.scopedBodies(e),n=[];for(let e of t)for(let t=0;t<e.numColliders();t++){let r=e.collider(t);r&&OT(r,n)}return new Float32Array(n)}scopedBodies(e){let t=[],n=e=>{let r=this.entries.get(e);r&&t.push(r.body);let i=this.scatterBodies.get(e);i&&t.push(i);for(let t of e.children)n(t)};n(e);for(let n=e.parent;n&&t.length===0;n=n.parent){let e=this.entries.get(n);e&&t.push(e.body)}return t}dispose(){this.disconnect(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;scatterBodies=new Map;bodySet=new Set;syncScatters(e){for(let[,e]of this.scatterBodies)this.world.removeRigidBody(e);this.scatterBodies.clear();let t=new Set;KT(e,t);for(let e of t){let t=e.collider;if(!t)continue;let[n,r,i]=YT(e),a=this.world.createRigidBody(this.R.RigidBodyDesc.fixed().setTranslation(0,0,0)),[o,s,c]=e.size,l=null;for(let u of e.transforms){let d=u[4]??1,f=n+(u[0]??0),p=r+(u[1]??0),m=i+(u[2]??0),h=null;if(t.shape===`sphere`)h=this.R.ColliderDesc.ball(Math.max((t.radius??Math.max(o,c)/2)*d,.01));else if(t.shape===`box`){let e=t.size??[o,s,c];h=this.R.ColliderDesc.cuboid(Math.max((e[0]??1)*d/2,.01),Math.max((e[1]??1)*d/2,.01),Math.max((e[2]??1)*d/2,.01))}else{l??=LT(e.mesh,e.size);let t=new Float32Array(l.length);for(let e=0;e<t.length;e++)t[e]=l[e]*d;h=this.R.ColliderDesc.convexHull(t)}if(!h)continue;h.setTranslation(f,p,m);let g=(u[3]??0)*Math.PI/180;g!==0&&h.setRotation({x:0,y:Math.sin(g/2),z:0,w:Math.cos(g/2)}),this.world.createCollider(h,a)}this.scatterBodies.set(e,a)}}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,n=!1;for(let{node:e,added:i}of r)e instanceof jh&&(i?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof Rw&&(t=!0),e instanceof Mw&&(n=!0);t&&(this.jointSet.clear(),PT(e.root,this.jointSet)),n&&this.syncScatters(e.root)}else this.bodySet.clear(),FT(e.root,this.bodySet),this.jointSet.clear(),PT(e.root,this.jointSet),this.syncScatters(e.root)}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,e._interpPrev=e._interpCurr=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,e._interpPrev=e._interpCurr=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,e._interpPrev=e._interpCurr=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let r=QT(n,e);if(!r)return null;let i;i=e instanceof Ph?n.RigidBodyDesc.dynamic():e instanceof Fh||e instanceof Nh?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed();let[a,o,s]=YT(e);i.setTranslation(a,o,s),MT.setFromEuler(NT.set((e.rotation[0]??0)*kT,(e.rotation[1]??0)*kT,(e.rotation[2]??0)*kT,`XYZ`)),i.setRotation({x:MT.x,y:MT.y,z:MT.z,w:MT.w}),e instanceof Ph&&(i.setGravityScale(e.gravityScale),i.setLinvel(e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0),e.fixedRotation&&i.lockRotations());let c=this.world.createRigidBody(i);r.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof Nh&&r.setSensor(!0),e instanceof Ph&&r.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let l=this.world.createCollider(r,c);return t={body:c,collider:l,last:[a,o,s],lastV:[0,0,0]},this.entries.set(e,t),this.byColliderHandle.set(l.handle,e),e._colliderChanged=!1,e._physics=this,e instanceof Ph&&(e._physics3d=this),t}let r=YT(e);if((r[0]!==t.last[0]||r[1]!==t.last[1]||r[2]!==t.last[2])&&(t.body.setTranslation({x:r[0],y:r[1],z:r[2]},!0),t.last[0]=r[0],t.last[1]=r[1],t.last[2]=r[2],e._interpPrev=e._interpCurr=null),e instanceof Ph){let n=[e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0];(n[0]!==t.lastV[0]||n[1]!==t.lastV[1]||n[2]!==t.lastV[2])&&(t.body.setLinvel({x:n[0],y:n[1],z:n[2]},!0),t.lastV=n),e.gravityScale!==t.body.gravityScale()&&t.body.setGravityScale(e.gravityScale,!0)}return t}applyImpulse(e,t){this.entries.get(e)?.body.applyImpulse({x:t[0],y:t[1],z:t[2]},!0)}massOf(e){return this.entries.get(e)?.body.mass()??1}velocityOf(e){let t=this.entries.get(e)?.body.linvel();return t?[t.x,t.y,t.z]:[0,0,0]}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,y:e.anchor[1]??0,z:e.anchor[2]??0},s={x:e.targetAnchor[0]??0,y:e.targetAnchor[1]??0,z:e.targetAnchor[2]??0},c=e.length;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,t.z-e.z)}let l={x:0,y:0,z:0,w:1},u;u=e.type===`fixed`?t.JointData.fixed(o,l,s,l):e.type===`rope`?t.JointData.rope(c,o,s):e.type===`spring`?t.JointData.spring(c,e.stiffness,e.damping,o,s):t.JointData.spherical(o,s),this.joints.set(e,this.world.createImpulseJoint(u,i.body,a.body,!0))}}castRay(e,t,n,r,i){let a=new this.R.Ray({x:e[0],y:e[1],z:e[2]},{x:t[0],y:t[1],z:t[2]}),o=r?this.entries.get(r)?.collider:void 0,s=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,c=this.world.castRayAndGetNormal(a,n,!0,s,void 0,o,void 0,e=>!e.isSensor());return c?{distance:c.timeOfImpact,normal:[c.normal.x,c.normal.y,c.normal.z],node:this.byColliderHandle.get(c.collider.handle)??null}:null}castSphere(e,t,n,r,i,a){let o=this.R,s=i?this.entries.get(i):void 0,c=a?.staticOnly?o.QueryFilterFlags.EXCLUDE_DYNAMIC|o.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castShape({x:e[0],y:e[1],z:e[2]},{x:0,y:0,z:0,w:1},{x:t[0],y:t[1],z:t[2]},new o.Ball(n),0,r,!0,c,void 0,s?.collider,s?.body,e=>!e.isSensor());return l?{distance:l.time_of_impact,node:this.byColliderHandle.get(l.collider.handle)??null}:null}},MT=new H,NT=new Qa;function PT(e,t){e instanceof Rw&&t.add(e);for(let n of e.children)PT(n,t)}function FT(e,t){e instanceof jh&&t.add(e);for(let n of e.children)FT(n,t)}function IT(e,t,n,r){let i=(n[0]??1)*r,a=(n[1]??1)*r,o=(n[2]??1)*r;switch(t){case`box`:return e.ColliderDesc.cuboid(i/2,a/2,o/2);case`sphere`:return e.ColliderDesc.ball(i);case`capsule`:return e.ColliderDesc.capsule(a/2,i);case`cylinder`:return e.ColliderDesc.cylinder(a/2,i);case`plane`:return e.ColliderDesc.cuboid(i/2,.01,o/2);default:return e.ColliderDesc.convexHull(LT(t,[i,a,o]))}}function LT(e,t){let n=jw(e,t),r=n.getAttribute(`position`),i=new Float32Array(r.count*3);for(let e=0;e<r.count;e++)i[e*3]=r.getX(e),i[e*3+1]=r.getY(e),i[e*3+2]=r.getZ(e);return n.dispose(),i}function RT(e){return typeof e._mountedObject3D==`function`}var zT=new G,BT=new G,VT=new U;function HT(e,t){let n=t._mountedObject3D();if(!n)return null;let r=e._ensureObject3D();r.updateWorldMatrix(!0,!0),zT.copy(r.matrixWorld).invert();let i=[],a=[];return n.traverse(e=>{let t=e;if(!t.isMesh)return;let n=t.geometry?.getAttribute(`position`);if(!n)return;BT.multiplyMatrices(zT,t.matrixWorld);let r=i.length/3;for(let e=0;e<n.count;e++)VT.set(n.getX(e),n.getY(e),n.getZ(e)).applyMatrix4(BT),i.push(VT.x,VT.y,VT.z);let o=t.geometry.getIndex();if(o)for(let e=0;e<o.count;e++)a.push(r+o.getX(e));else for(let e=0;e<n.count;e++)a.push(r+e)}),a.length<3?null:{vertices:new Float32Array(i),indices:new Uint32Array(a),triangles:a.length/3}}var UT=2e4;function WT(e){return!(e instanceof Ph||e instanceof Fh)}function GT(e,t,n){if(RT(e))n.push(e);else{let n=e;typeof n.mesh==`string`&&Array.isArray(n.size)&&t.push({name:e.name,mesh:n.mesh,size:n.size})}for(let r of e.children)GT(r,t,n)}function KT(e,t){e instanceof Mw&&e.collider&&t.add(e);for(let n of e.children)KT(n,t)}var qT=[0,0,0];function JT(e){let t=e.collider;return t?t.shape===`capsule`&&typeof t.height==`number`?t.height/2+(t.radius??0):t.shape===`box`&&Array.isArray(t.size)?(t.size[1]??2)/2:t.shape===`sphere`&&typeof t.radius==`number`?t.radius:1:1}function YT(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Ah&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return qT[0]=t,qT[1]=n,qT[2]=r,qT}var XT=[0,0,0];function ZT(e){let t=0,n=0,r=0;for(let i=e.parent;i;i=i.parent)i instanceof Ah&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return XT[0]=t,XT[1]=n,XT[2]=r,XT}function QT(e,t){let n=t.collider;if(Oh(n,t.name),n.shape===`heightfield`)return $T(e,t);let r=eE(e,n,t.name,t);if(!r)return null;let i=n.offset;return Array.isArray(i)&&r.setTranslation(i[0]??0,i[1]??0,i[2]??0),r}function $T(e,t){let n=t.children.find(e=>e instanceof _T);if(!n)throw new N(`BAD_FORMAT`,`Collider on '${t.name}': heightfield needs a Terrain3D CHILD of this body — add { "type": "Terrain3D" } under the StaticBody3D; the collider reads its height grid.`,{prop:`collider`});let r=n._heightmap(),i=r.segsZ,a=r.segsX,o=new Float32Array((i+1)*(a+1));for(let e=0;e<=a;e++)for(let t=0;t<=i;t++)o[e*(i+1)+t]=r.heights[t*(a+1)+e];let s=e.ColliderDesc.heightfield(i,a,o,{x:r.width,y:1,z:r.depth}),c=Array.isArray(t.collider.offset)?t.collider.offset:[];return s.setTranslation((n.position[0]??0)+(c[0]??0),(n.position[1]??0)+(c[1]??0),(n.position[2]??0)+(c[2]??0)),s}function eE(e,t,n,r){let i=t.shape;if(i===`box`){let r=t.size;if(!Array.isArray(r)||r.length!==3||r.some(e=>typeof e!=`number`))throw new N(`BAD_FORMAT`,`Collider on '${n}': box needs "size": [x, y, z].`);return e.ColliderDesc.cuboid(r[0]/2,r[1]/2,r[2]/2)}if(i===`sphere`){if(typeof t.radius!=`number`)throw new N(`BAD_FORMAT`,`Collider on '${n}': sphere needs "radius".`);return e.ColliderDesc.ball(t.radius)}if(i===`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,t.radius)}if(i===`auto`){let t=[],i=[];r&&GT(r,t,i);let a=t[0],o=i[0];if(!a&&!o)throw new N(`BAD_FORMAT`,`Collider on '${n}': shape 'auto' needs a MeshInstance3D or ModelInstance3D on the body (or as a child) to take its shape from.`);let s=t.length+i.length;if(s>1&&console.warn(`[incanto] Collider on '${n}': shape 'auto' fits ONE mesh and took '${(a??o)?.name}'; ${s-1} other mesh(es) here are not solid. Give each part its own body.`),a){let t=IT(e,a.mesh,a.size,1);if(t)return t}else if(o&&r){let t=HT(r,o);return t?WT(r)?(t.triangles>UT&&console.warn(`[incanto] Collider on '${n}': shape 'auto' built a ${t.triangles}-triangle mesh from '${o.name}'. Consider a low-poly collision model or an explicit box.`),e.ColliderDesc.trimesh(t.vertices,t.indices)):e.ColliderDesc.convexHull(t.vertices):null}}if(i===`trimesh`){let r=t.vertices,i=t.indices;if(!Array.isArray(r)||!Array.isArray(i))throw new N(`BAD_FORMAT`,`Collider on '${n}': trimesh needs "vertices" (flat xyz) and "indices" (triangles).`);return e.ColliderDesc.trimesh(new Float32Array(r),new Uint32Array(i))}throw new N(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'auto', 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(i)}.`)}var tE=new cl(1,1),nE=null;function rE(){if(nE)return nE;if(typeof document>`u`)return null;let e=document.createElement(`canvas`);e.width=64,e.height=64;let t=e.getContext(`2d`);if(!t)return null;let n=t.createRadialGradient(32,32,0,32,32,31);return n.addColorStop(0,`rgba(0,0,0,0.55)`),n.addColorStop(.55,`rgba(0,0,0,0.34)`),n.addColorStop(1,`rgba(0,0,0,0)`),t.fillStyle=n,t.fillRect(0,0,64,64),nE=new Qc(e),nE}var iE=new U(0,0,1),aE=new U,oE=new U,sE=new H,cE=new H,lE=new U,uE=.5,dE=class extends Ah{static typeName=`Sprite3D`;static props={texture:{default:``},size:{default:[1,1]},billboard:{default:`y`,options:[`y`,`full`,`none`]},anchor:{default:[.5,0]},tint:{default:`#ffffff`},opacity:{default:1},flipX:{default:!1},pixelArt:{default:!0},alphaTest:{default:.5},castShadow:{default:!1},shadowMode:{default:`silhouette`,options:[`silhouette`,`blob`]}};texture=``;size=[1,1];billboard=`y`;anchor=[.5,0];tint=`#ffffff`;opacity=1;flipX=!1;pixelArt=!0;alphaTest=.5;castShadow=!1;shadowMode=`silhouette`;quadMesh=null;textureRef=``;loadedTexture=null;shadowMesh=null;blobMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Ys(tE,new Ls({transparent:!1,depthWrite:!0,side:2})),this._ensureObject3D().add(this.quadMesh)),this.quadMesh}resolveTexture(e){return this.texture?(this.textureRef!==this.texture&&(this.textureRef=this.texture,this.loadedTexture=gw(e,this.texture,{filter:this.pixelArt?`nearest`:`linear`})),this.loadedTexture):null}_syncObject3D(e=1,t=null){super._syncObject3D(e,t);let n=this._quad(),r=n.material,i=this.size[0]??1,a=this.size[1]??1;n.scale.set(this.flipX?-i:i,a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??0;n.position.set((.5-o)*i,(.5-s)*a,0);let c=this.resolveTexture(t);r.map!==c&&(r.map=c,r.needsUpdate=!0),n.visible=c!==null,r.color.set(this.tint),r.opacity=this.opacity,r.transparent=this.opacity<1,r.alphaTest=this.alphaTest,n.renderOrder=this.renderOrder;let l=this.castShadow&&c!==null;if(n.castShadow=!1,l&&this.shadowMode===`silhouette`){let e=this._shadowCaster();e.visible=!0,e.castShadow=!0,e.scale.set(this.flipX?-i:i,a,1),e.position.set((.5-o)*i,(.5-s)*a,0);let t=e.material;t.map!==c&&(t.map=c,t.needsUpdate=!0);let n=e.customDepthMaterial;n.map!==c&&(n.map=c,n.needsUpdate=!0),t.alphaTest=this.alphaTest,n.alphaTest=this.alphaTest}else this.shadowMesh&&(this.shadowMesh.visible=!1,this.shadowMesh.castShadow=!1);if(l&&this.shadowMode===`blob`){let e=this._blob();e.visible=!0,e.scale.set(i*.52,i*.52,1)}else this.blobMesh&&(this.blobMesh.visible=!1)}_shadowCaster(){return this.shadowMesh||(this.shadowMesh=new Ys(tE,new Ls({colorWrite:!1,depthWrite:!1,side:2})),this.shadowMesh.customDepthMaterial=new Sl({depthPacking:Di,side:2}),this._ensureObject3D().add(this.shadowMesh)),this.shadowMesh}_blob(){return this.blobMesh||(this.blobMesh=new Ys(tE,new Ls({map:rE(),color:0,transparent:!0,depthWrite:!1})),this.blobMesh.rotation.x=-Math.PI/2,this.blobMesh.position.y=.02,this.blobMesh.renderOrder=-1,this._ensureObject3D().add(this.blobMesh)),this.blobMesh}_onRender3D(e){this.billboard===`y`?(e.camera.getWorldDirection(oE),oE.y=0,oE.lengthSq()>=1e-6&&this._faceDir(this._quad(),oE.negate())):this.billboard===`full`&&this._faceToward(this._quad(),e.camera.position);let t=this.shadowMesh;t?.castShadow&&e.sunDir&&(this._faceDir(t,e.sunDir),t.parent?.getWorldQuaternion(cE),lE.copy(e.sunDir).applyQuaternion(cE.invert()),t.position.addScaledVector(lE,uE))}_faceToward(e,t){e.getWorldPosition(aE),oE.copy(t).sub(aE),this.billboard===`y`&&(oE.y=0),!(oE.lengthSq()<1e-12)&&(oE.normalize(),sE.setFromUnitVectors(iE,oE),e.parent?.getWorldQuaternion(cE),e.quaternion.copy(cE.invert()).multiply(sE))}_faceDir(e,t){oE.copy(t),this.billboard===`y`&&(oE.y=0),!(oE.lengthSq()<1e-12)&&(oE.normalize(),sE.setFromUnitVectors(iE,oE),e.parent?.getWorldQuaternion(cE),e.quaternion.copy(cE.invert()).multiply(sE))}free(){this.loadedTexture?.dispose(),this.loadedTexture=null,this.shadowMesh&&(this.shadowMesh.material.dispose(),this.shadowMesh.customDepthMaterial?.dispose()),this.blobMesh&&this.blobMesh.material.dispose(),super.free()}},fE=class extends dE{static typeName=`AnimatedSprite3D`;static signals=[`animationFinished`];static props={sheet:{default:``},frameWidth:{default:0},frameHeight:{default:0},animations:{default:{}},autoplay:{default:``}};sheet=``;frameWidth=0;frameHeight=0;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;sheetTexture=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=pE(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||this.frameWidth<=0||this.frameHeight<=0)return null;this.loadedSheetRef!==this.sheet&&(this.sheetTexture?.dispose(),this.loadedSheetRef=this.sheet,this.sheetTexture=_w(e,this.sheet,{filter:this.pixelArt?`nearest`:`linear`}));let t=this.sheetTexture;if(!t)return null;let n=t.image;if(!n?.width||!n.height)return t;let r=Math.max(1,Math.floor(n.width/this.frameWidth)),i=this.currentFrame%r,a=Math.floor(this.currentFrame/r);return t.repeat.set(this.frameWidth/n.width,this.frameHeight/n.height),t.offset.set(i*this.frameWidth/n.width,1-(a+1)*this.frameHeight/n.height),t}free(){this.sheetTexture?.dispose(),this.sheetTexture=null,super.free()}};function pE(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 mE=new H,hE=new H,gE=new U,_E=new U(0,0,1),vE=[`screen`,`y`,`none`],yE=class extends Ah{static typeName=`Billboard3D`;static props={mode:{default:`screen`,options:vE}};mode=`screen`;_lastDesired=null;static validateJson(e){let t=e;if(!vE.includes(t.mode))throw new N(`BAD_FORMAT`,`Billboard3D '${e.name}' mode must be one of [${vE.join(`, `)}], got '${t.mode}'.`,{prop:`mode`,validOptions:vE})}_onRender3D(e){if(this.mode===`none`)return;let t=this._ensureObject3D();if(this.mode===`screen`)e.camera.getWorldQuaternion(hE);else if(e.camera.getWorldDirection(gE),gE.y=0,gE.lengthSq()>=1e-6)hE.setFromUnitVectors(_E,gE.negate().normalize());else if(this._lastDesired)hE.copy(this._lastDesired);else return;this._lastDesired||=new H,this._lastDesired.copy(hE),t.parent?.getWorldQuaternion(mE),t.parent?t.quaternion.copy(mE.invert()).multiply(hE):t.quaternion.copy(hE)}},bE=class extends Ah{static typeName=`BoneAttachment3D`;static props={target:{default:``,nodePath:!0},bone:{default:``}};target=``;bone=``;boneObj=null;lookedUpFor=``;get attachedBone(){return this.boneObj}_onRender3D(e){if(this.target===``||this.bone===``)return;let t=`${this.target} ${this.bone}`;if(this.lookedUpFor!==t||this.boneObj===null||!this.boneObj.parent){this.lookedUpFor=t,this.boneObj=null;let e=this.getNodeOrNull(this.target);e&&typeof e.findBone==`function`&&(this.boneObj=e.findBone(this.bone))}let n=this.boneObj;if(!n)return;let r=this._ensureObject3D(),i=r.parent;i&&(n.updateWorldMatrix(!0,!1),i.updateWorldMatrix(!0,!1),r.matrixAutoUpdate=!1,n.matrixWorld.decompose(CE,wE,TE),SE.compose(CE,wE,EE),r.updateMatrix(),xE.copy(r.matrix),r.matrix.copy(i.matrixWorld).invert().multiply(SE).multiply(xE))}free(){this.boneObj=null,super.free()}},xE=new G,SE=new G,CE=new U,wE=new H,TE=new U,EE=new U(1,1,1),DE=class extends Ah{static typeName=`BoneLookAt3D`;static props={target:{default:``,nodePath:!0},bone:{default:`Head`},lookAt:{default:``,nodePath:!0},maxAngleDeg:{default:75},weight:{default:.85},forwardAxis:{default:`+z`,options:[`+x`,`-x`,`+y`,`-y`,`+z`,`-z`]}};target=``;bone=`Head`;lookAt=``;maxAngleDeg=75;weight=.85;forwardAxis=`+z`;boneObj=null;lookedUpFor=``;engage=0;get attachedBone(){return this.boneObj}_onRender3D(e){if(this.target===``||this.bone===``)return;let t=`${this.target} ${this.bone}`;if(this.lookedUpFor!==t||this.boneObj===null||!this.boneObj.parent){this.lookedUpFor=t,this.boneObj=null;let e=this.getNodeOrNull(this.target);e&&typeof e.findBone==`function`&&(this.boneObj=e.findBone(this.bone))}let n=this.boneObj;if(!n?.parent)return;let r=this.lookAt===``?null:this.getNodeOrNull(this.lookAt),i=!1;if(r&&Array.isArray(r.position)&&(n.updateWorldMatrix(!0,!1),n.getWorldPosition(NE),PE.set(r.position[0]??0,r.position[1]??0,r.position[2]??0),FE.copy(PE).sub(NE),FE.lengthSq()>1e-6&&(FE.normalize(),IE.copy(kE[this.forwardAxis]??jE),LE.copy(IE).applyQuaternion(n.getWorldQuaternion(HE)),LE.angleTo(FE)<this.maxAngleDeg*Math.PI/180))){i=!0,RE.lookAt(NE,PE,AE),zE.setFromRotationMatrix(RE),BE.setFromUnitVectors(IE,ME),zE.multiply(BE),n.parent.getWorldQuaternion(VE).invert(),zE.premultiply(VE);let e=this.weight*this.engage;n.quaternion.slerp(zE,e)}this.engage+=(+!!i-this.engage)*OE}},OE=.18,kE={"+x":new U(1,0,0),"-x":new U(-1,0,0),"+y":new U(0,1,0),"-y":new U(0,-1,0),"+z":new U(0,0,1),"-z":new U(0,0,-1)},AE=new U(0,1,0),jE=new U(0,0,1),ME=new U(0,0,-1),NE=new U,PE=new U,FE=new U,IE=new U,LE=new U,RE=new G,zE=new H,BE=new H,VE=new H,HE=new H,UE=class extends Ah{static typeName=`Camera3D`;static props={fov:{default:60},near:{default:.1},far:{default:1e3},current:{default:!1}};fov=60;near=.1;far=1e3;current=!1;_createObject3D(){return new pu(this.fov,1,this.near,this.far)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();(e.fov!==this.fov||e.near!==this.near||e.far!==this.far)&&(e.fov=this.fov,e.near=this.near,e.far=this.far,e.updateProjectionMatrix())}},WE=8,GE=.15,KE=1.2,qE=.08,JE=-20,YE=.002,XE=180/Math.PI,ZE=.3,QE=.4,$E=.3,eD=.25,tD=new Qa,nD=new H,rD=new G,iD=new U,aD=new U,oD=new U(0,1,0),sD=class extends Ah{static typeName=`CharacterController3D`;static signals=[`movementStateChanged`];static props={view:{default:`free`,options:[`free`,`firstPerson`,`quarter`,`side`]},camDistance:{default:4},eyeHeight:{default:.64},maxSpeed:{default:2.5},sprintMultiplier:{default:2},jumpVelocity:{default:4},sprintJumpMultiplier:{default:1.2},coyoteSeconds:{default:0},jumpBufferSeconds:{default:0},jumpCutMultiplier:{default:1},maxJumps:{default:1},airControl:{default:.2},fallGravity:{default:2.5},floatHeight:{default:.01},mouseLook:{default:!0},zoomMin:{default:0},zoomMax:{default:0},pitchMin:{default:-1.3},pitchMax:{default:1.5},cameraCollision:{default:!0},turnSpeed:{default:100},camLerp:{default:25},moveAction:{default:`move`},jumpAction:{default:`jump`},sprintAction:{default:`sprint`},skinPath:{default:`../Skin`,nodePath:!0},skinYawOffset:{default:0},animations:{default:{}}};view=`free`;camDistance=4;eyeHeight=.64;maxSpeed=2.5;sprintMultiplier=2;jumpVelocity=4;sprintJumpMultiplier=1.2;coyoteSeconds=0;jumpBufferSeconds=0;jumpCutMultiplier=1;maxJumps=1;airControl=.2;fallGravity=2.5;floatHeight=.01;mouseLook=!0;zoomMin=0;zoomMax=0;pitchMin=-1.3;pitchMax=1.5;cameraCollision=!0;turnSpeed=100;camLerp=25;moveAction=`move`;jumpAction=`jump`;sprintAction=`sprint`;skinPath=`../Skin`;skinYawOffset=0;animations={};yaw=0;pitch=0;state=`idle`;grounded=!1;coyoteLeft=0;bufferLeft=0;jumpsUsed=0;rising=!1;get body(){let e=this.parent;if(!(e instanceof Ph))throw new N(`TREE_VIOLATION`,`CharacterController3D '${this.name}' must be a child of a RigidBody3D (parent is '${e?.name??`none`}').`);return e}onEnterTree(){if(this.body,this.skinPath!==``){let e=this.getNodeOrNull(this.skinPath);e&&(e.rotation=[e.rotation[0]??0,180+this.skinYawOffset,e.rotation[2]??0])}}fixedUpdate(e){let t=this.body,n=t._physics3d,r=this.tree?.engine?.input;if(!n||!r)return;let i=t.collider.radius??.32,a=(t.collider.height??1)/2,o=lD(t),s=n.velocityOf(t),c=n.massOf(t),l=i+this.floatHeight,u=i+2,d=o[1]-a,f=null;for(let[e,r]of[[0,0],[i,0],[-i,0],[0,i],[0,-i]]){let i=n.castRay([o[0]+e,d,o[2]+r],[0,-1,0],u,t);if(i){let t=i.distance;if(f=f===null?t:Math.min(f,t),e===0&&r===0)break}}this.grounded=f!==null&&f<l*2;let p=f!==null&&f<l*1.3&&(s[1]??0)<=.5,m=0,h=0,g=!1;try{let e=r.getVector(this.moveAction);g=e.x!==0||e.y!==0;let t=this.view===`free`||this.view===`firstPerson`?this.yaw:0,n=this.view===`side`?[e.x,0,0]:ww(e.x,-e.y,t),i=Math.hypot(n[0],n[2])||1;m=n[0]/i,h=n[2]/i}catch{}let _=uD(r,this.sprintAction),v=Tw(g,_),y=1+(this.sprintMultiplier-1)*v,b=g?this.maxSpeed*y:0,x=this.grounded?1:this.airControl,S=(m*b-s[0])/WE*x,C=(h*b-s[2])/WE*x;if(t.applyImpulse([S*c,0,C*c]),!g&&this.grounded&&t.applyImpulse([-s[0]*GE*c,0,-s[2]*GE*c]),f!==null&&f<l*2){let e=KE*(l-f)-s[1]*qE;t.applyImpulse([0,e*c,0])}p?(this.coyoteLeft=this.coyoteSeconds,this.jumpsUsed=0,this.rising=!1):(this.coyoteLeft=Math.max(0,this.coyoteLeft-e),this.coyoteLeft<=0&&this.jumpsUsed===0&&(this.jumpsUsed=1));let w=dD(r,this.jumpAction);if(w?this.bufferLeft=Math.max(this.jumpBufferSeconds,0):this.bufferLeft=Math.max(0,this.bufferLeft-e),(this.bufferLeft>0||w)&&(p||this.coyoteLeft>0||this.jumpsUsed<this.maxJumps)){let e=this.jumpVelocity*(1+(this.sprintJumpMultiplier-1)*v);t.linearVelocity=[s[0],e,s[2]],this.grounded=!1,this.jumpsUsed+=1,this.bufferLeft=0,this.coyoteLeft=0,this.rising=!0,s[1]=e}if(this.rising){if((s[1]??0)<=0)this.rising=!1;else if(this.jumpCutMultiplier<1&&!uD(r,this.jumpAction)){let e=(s[1]??0)*this.jumpCutMultiplier;t.linearVelocity=[s[0],e,s[2]],s[1]=e,this.rising=!1}}(s[1]??0)<JE?t.gravityScale=0:(s[1]??0)<0&&!p?t.gravityScale=this.fallGravity:t.gravityScale=1,this.view===`side`&&Math.abs(o[2])>.01&&(t.position=[t.position[0]??0,t.position[1]??0,0]);let T=Ew(p,g?v:0);if(T!==this.state){this.state=T;let e=this.animations[T];if(e&&this.skinPath!==``){let t=this.getNodeOrNull(this.skinPath);t&&`animation`in t&&(t.animation=e)}this.emit(`movementStateChanged`,T)}if(g&&this.skinPath!==``){let t=this.getNodeOrNull(this.skinPath);if(t){let n=Math.atan2(m,h)*XE+this.skinYawOffset,r=t.rotation[1]??0,i=(n-r+540)%360-180,a=this.turnSpeed*e*XE;Math.abs(i)>a&&(i=Math.sign(i)*a),t.rotation=[t.rotation[0]??0,r+i,t.rotation[2]??0]}}}update(e){let t=this.tree?.engine?.input;if(!t)return;if(this.mouseLook){let e=t.pointerDelta();this.yaw-=e.x*YE,this.pitch=cD(this.pitch+e.y*YE,-this.pitchMax,-this.pitchMin);let n=t.wheelDelta();n!==0&&this.zoomMax>this.zoomMin&&(this.camDistance=cD(this.camDistance+n*YE,this.zoomMin,this.zoomMax))}let n=this.findCamera();if(!n)return;let r=this.parent instanceof Ph?this.parent:null;if(!r)return;let i=lD(r),a=this.view===`free`?11:1e3,o=1-Math.exp(-a*e),s=this.pivot??[i[0],i[1],i[2]];this.pivot=s,s[0]+=(i[0]-s[0])*o,s[1]+=(i[1]-s[1])*o,s[2]+=(i[2]-s[2])*o;let c=xw(this.view,s,this.eyeHeight,this.yaw,this.pitch,this.camDistance),l=[s[0],s[1]+this.eyeHeight,s[2]],u=[c.position[0],c.position[1],c.position[2]];if(this.cameraCollision&&this.view!==`firstPerson`){let e=r._physics3d;e&&(u=Sw(l,u,(t,n,i)=>e.castSphere(t,n,eD,i,r,{staticOnly:!0})?.distance??null,ZE,QE),u=Cw(u,(t,n)=>e.castRay(t,[0,-1,0],n,r,{staticOnly:!0})?.distance??null,$E))}let d=this.view===`firstPerson`?1e3:this.camLerp,f=1-Math.exp(-d*e),p=n.position;n.position=[(p[0]??0)+(u[0]-(p[0]??0))*f,(p[1]??0)+(u[1]-(p[1]??0))*f,(p[2]??0)+(u[2]-(p[2]??0))*f],this.view===`free`?(iD.set(n.position[0]??0,n.position[1]??0,n.position[2]??0),aD.set(l[0],l[1],l[2]),rD.lookAt(iD,aD,oD),nD.setFromRotationMatrix(rD),tD.setFromQuaternion(nD,`XYZ`)):(tD.set(c.rotation[0],c.rotation[1],c.rotation[2],`YXZ`),nD.setFromEuler(tD),tD.setFromQuaternion(nD,`XYZ`)),n.rotation=[tD.x*XE,tD.y*XE,tD.z*XE]}pivot=null;cameraCache=null;findCamera(){if(this.cameraCache?.tree===this.tree&&this.cameraCache.current)return this.cameraCache;this.cameraCache=null;let e=this.tree?.root;if(!e)return null;let t=e=>{if(!this.cameraCache){if(e instanceof UE&&e.current){this.cameraCache=e;return}for(let n of e.children)t(n)}};return t(e),this.cameraCache}};function cD(e,t,n){return Math.min(n,Math.max(t,e))}function lD(e){let t=0,n=0,r=0;for(let i=e;i&&i instanceof Ah;i=i.parent)t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0;return[t,n,r]}function uD(e,t){try{return e.isPressed(t)}catch{return!1}}function dD(e,t){try{return e.justPressed(t)}catch{return!1}}var fD=.15,pD=.7,mD=.5,hD=.7,gD=.5;function _D(e,t,n=3){let r=0,i=1,a=1,o=.65;for(let s=0;s<n;s++){let n=e*a,s=t*a,c=Math.sin(n*.1+s*.2)*.5+.5,l=Math.cos(n*.3+s*.1)*.5+.5,u=Math.sin((n+s)*.15)*.5+.5,d=Math.cos(n*n*.01+s*.2)*.5+.5,f=c*l*.7+u*d*.3;r+=f*i,i*=o,a*=2}return r/((1-o**n)/(1-o))}function vD(e,t){let n=_D(e*fD,t*fD,4),r=_D(e*fD*.2,t*fD*.2,2);return n>mD-pD*.5-r*gD}var yD=.9;function bD(e,t,n){let r=(Math.imul(e,2246822507)^Math.imul(t,3266489909)^Math.imul(n+1,668265263))>>>0;return r=Math.imul(r^r>>>15,739982445)>>>0,r=Math.imul(r^r>>>12,695872825)>>>0,r^=r>>>15,(r>>>0)/4294967296}function xD(e,t,n=yD){let r=Math.floor(e/n),i=Math.floor(t/n),a=1/0,o=r,s=i;for(let c=-1;c<=1;c++)for(let l=-1;l<=1;l++){let u=r+l,d=i+c,f=(u+bD(u,d,0))*n,p=(d+bD(u,d,1))*n,m=(e-f)*(e-f)+(t-p)*(t-p);m<a&&(a=m,o=u,s=d)}return{id:Math.imul(o,2654435761)^Math.imul(s,2246822519)|0,hue:bD(o,s,2)*2-1,leanDir:bD(o,s,3)*Math.PI*2,lean:bD(o,s,4)}}function SD(e,t,n,r){let i=e*r,a=t*r,o=Math.floor(i),s=Math.floor(a),c=i-o,l=a-s,u=c*c*(3-2*c),d=l*l*(3-2*l),f=bD(o,s,n),p=bD(o+1,s,n),m=bD(o,s+1,n),h=bD(o+1,s+1,n),g=f+(p-f)*u;return g+(m+(h-m)*u-g)*d}var CD=[.55,1.7],wD=.17,TD=.23,ED=.28;function DD(e,t,n){let r=SD(e,t,n^6877377|0,wD),i=r*r*(3-2*r);return CD[0]+(CD[1]-CD[0])*i}function OD(e,t,n){return SD(e,t,n^3001105|0,TD)}function kD(e,t,n){let r=SD(e,t,n^7840757|0,ED)*.72+SD(e,t,n^1688295|0,ED*3.1)*.28,i=Math.min(1,Math.max(0,(r-.18)/.64));return i*i*(3-2*i)}function AD(e){let{seed:t,areaX:n,areaZ:r,count:i,density:a}=e,o=new P(t),s=n/2,c=r/2,l=[],u=Math.floor(i*hD);for(let e=0;e<u&&l.length<i;e++){let e=o.range(-s,s),t=o.range(-c,c),n=o.next()<.3,r=vD(e,t);if(!n&&!r&&o.next()>.15)continue;let i=o.next()*Math.PI*2,a=.5+o.next()*.7,u=r?a*(1+o.next()*.2):a*(.9+o.next()*.2);l.push({x:e,z:t,rotY:i,scale:u})}let d=Math.min(3,Math.max(1,a*10)),f=Math.ceil(Math.sqrt(i*d)),p=n/f,m=r/f,h=Math.floor((i-l.length)*.8),g=0;for(let e=0;e<f&&l.length<i;e++)for(let t=0;t<f&&l.length<i;t++){let i=t/f*n-s+p/2,a=e/f*r-c+m/2,u=i+(o.next()-.5)*p*1.5,d=a+(o.next()-.5)*m*1.5;if(u<-s||u>s||d<-c||d>c)continue;let _=vD(u,d);if(g<h){if(!_&&o.next()>.05)continue}else if(_){if(o.next()>.2)continue}else if(o.next()>.4)continue;if(o.next()<.2)continue;let v=o.next()*Math.PI*2,y=_?.5:.3;l.push({x:u,z:d,rotY:v,scale:.5+o.next()*y}),g++}for(;l.length<i;)l.push({x:o.range(-s,s),z:o.range(-c,c),rotY:o.next()*Math.PI*2,scale:.4+o.next()*.6});return l.sort((e,t)=>t.z-e.z),l}var jD=[`daisy`,`cosmos`,`bellflower`],MD={daisy:{petals:8,blooms:3,leaves:3,petalLength:.1,petalWidth:.052,cupDeg:16,nodDeg:14,centerRadius:.024,centerColor:`#e0a72e`},cosmos:{petals:8,blooms:2,leaves:2,petalLength:.12,petalWidth:.064,cupDeg:26,nodDeg:18,centerRadius:.023,centerColor:`#d2941f`},bellflower:{petals:5,blooms:3,leaves:2,petalLength:.088,petalWidth:.058,cupDeg:46,nodDeg:52,centerRadius:.015,centerColor:`#cfe06a`}},ND=[1,.78,.62],PD=[0,.07,.11],FD=[.6,2.7,4.9],ID=.07,LD=.011,RD=.17,zD=.05,BD=[.12,.2,.28],VD=new K(`#3e6a26`),HD=new K(`#548331`);function UD(e){let t=MD[e],n=new WD(!0),r=new WD(!1),i=new K(t.centerColor);for(let e=0;e<t.blooms;e++){let a=ND[e],o=FD[e],s=PD[e]*Math.cos(o),c=PD[e]*Math.sin(o),l=ID*Math.cos(o),u=ID*Math.sin(o),d=new U(s,0,c),f=new U(s+l,a,c+u),p=new U(s+l*.25,a*.55,c+u*.25);n.addStem(d,p,f,LD,VD);let m=t.nodDeg*Math.PI/180,h=new U(Math.sin(m)*Math.cos(o),Math.cos(m),Math.sin(m)*Math.sin(o)),g=new U(-Math.sin(o),0,Math.cos(o)),_=new U().crossVectors(h,g).normalize(),v=f.clone().addScaledVector(h,.012),y=t.cupDeg*Math.PI/180,b=e*.45;for(let e=0;e<t.petals;e++){let n=e/t.petals*Math.PI*2+b,i=g.clone().multiplyScalar(Math.cos(n)).addScaledVector(_,Math.sin(n)).normalize();r.addPetal(v,i,h,t,y)}n.addDisc(v.clone().addScaledVector(h,.004),g,_,t.centerRadius,i)}for(let e=0;e<t.leaves;e++){let t=BD[e%BD.length],r=1.1+e*2.3;n.addLeaf(new U(0,t,0),r,HD)}return{structure:n.build(),petals:r.build()}}var WD=class{positions=[];colors;indices=[];constructor(e){this.colors=e?[]:null}vertex(e,t){let n=this.positions.length/3;return this.positions.push(e.x,e.y,e.z),this.colors&&t&&this.colors.push(t.r,t.g,t.b),n}addStem(e,t,n,r,i){for(let a of[0,Math.PI/2]){let o=new U(Math.cos(a),0,Math.sin(a)),s=[];for(let a=0;a<=5;a++){let c=a/5,l=1-c,u=new U(l*l*e.x+2*l*c*t.x+c*c*n.x,l*l*e.y+2*l*c*t.y+c*c*n.y,l*l*e.z+2*l*c*t.z+c*c*n.z),d=r/2*(1-.4*c);s.push(this.vertex(u.clone().addScaledVector(o,-d),i),this.vertex(u.clone().addScaledVector(o,d),i))}for(let e=0;e<5;e++){let t=s[e*2],n=s[e*2+1],r=s[e*2+2],i=s[e*2+3];this.indices.push(t,n,r,r,n,i)}}}addPetal(e,t,n,r,i){let a=new U().crossVectors(n,t).normalize(),o=r.centerRadius*.85,s=Math.sin(i)*r.petalLength*.45,c=Math.sin(i)*r.petalLength*.95,l=Math.cos(i),u=e.clone().addScaledVector(t,o),d=o+r.petalLength*l*.55,f=o+r.petalLength*l,p=e.clone().addScaledVector(t,d).addScaledVector(a,r.petalWidth/2).addScaledVector(n,s),m=e.clone().addScaledVector(t,d).addScaledVector(a,-r.petalWidth/2).addScaledVector(n,s),h=e.clone().addScaledVector(t,f).addScaledVector(n,c),g=this.vertex(u,null),_=this.vertex(p,null),v=this.vertex(m,null),y=this.vertex(h,null);this.indices.push(g,_,y,g,y,v)}addDisc(e,t,n,r,i){let a=this.vertex(e,i),o=[];for(let a=0;a<6;a++){let s=a/6*Math.PI*2;o.push(this.vertex(e.clone().addScaledVector(t,Math.cos(s)*r).addScaledVector(n,Math.sin(s)*r),i))}for(let e=0;e<6;e++)this.indices.push(a,o[e],o[(e+1)%6])}addLeaf(e,t,n){let r=new U(Math.cos(t),0,Math.sin(t)),i=new U(-Math.sin(t),0,Math.cos(t)),a=Math.sin(.6),o=Math.cos(.6),s=e.clone().addScaledVector(r,RD*o*.5).add(new U(0,RD*a*.5,0)),c=e.clone().addScaledVector(r,RD*o).add(new U(0,RD*a*.8,0)),l=this.vertex(e,n),u=this.vertex(s.clone().addScaledVector(i,zD/2),n),d=this.vertex(s.clone().addScaledVector(i,-.05/2),n),f=this.vertex(c,n);this.indices.push(l,u,f,l,f,d)}build(){let e=new J;return e.setAttribute(`position`,new q(new Float32Array(this.positions),3)),this.colors&&e.setAttribute(`color`,new q(new Float32Array(this.colors),3)),e.setIndex(this.indices),e.computeVertexNormals(),e}},GD=2.6;function KD(e){let{seed:t,areaX:n,areaZ:r,count:i,clustering:a}=e,o=new P(t),s=n/2,c=r/2,l=1-.74*Math.min(Math.max(a,0),1),u=[];for(let e=0;e<i*16&&u.length<i;e++){let e=o.range(-s,s),t=o.range(-c,c),n=xD(e,t,GD);n.lean>l&&o.next()>.06||u.push({x:e,z:t,rotY:o.next()*Math.PI*2,scale:.75+o.next()*.5,variety01:(n.hue+1)/2,color01:n.leanDir/(Math.PI*2)})}return u}var qD=1.05,JD=1;function YD(e,t=JD){e.computeBoundingSphere();let n=e.boundingSphere;n&&n.radius>=0&&(n.radius=n.radius*qD+t),e.frustumCulled=!0}function XD(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Ah&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return[t,n,r]}function ZD(e,t){if(t!==``){let n=e.getNodeOrNull(t);return n instanceof _T?n:null}return QD(e.getRoot())}function QD(e){if(e instanceof _T)return e;for(let t of e.children){let e=QD(t);if(e)return e}return null}function $D(e){return typeof e?._waterYAt==`function`}function eO(e){let t=e;for(;t.parent;)t=t.parent;let n=[],r=e=>{e.visible!==!1&&$D(e)&&n.push(e);for(let t of e.children)r(t)};return r(t),n}function tO(e,t,n,r,i=.06){for(let a=0;a<e.length;a++){let o=e[a]?._waterYAt(t,n);if(o!=null&&o-r>i)return!0}return!1}var nO={lush:2.2,sparse:.35,none:0},rO=[`lush`,`sparse`,`none`];function iO(e){if(typeof e==`number`)return e;let t=nO[e];if(t===void 0)throw new N(`BAD_FORMAT`,`Flowers3D density must be one of [${rO.join(`, `)}] or a number (plants/m²), got '${e}'.`,{prop:`density`,validOptions:rO});return t}var aO=1e4,oO=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],sO=/^#[0-9a-fA-F]{6}$/,cO=class extends Ah{static typeName=`Flowers3D`;static props={density:{default:`sparse`,options:rO},area:{default:[20,20]},seed:{default:1},varieties:{default:[]},palette:{default:[]},height:{default:.45},clustering:{default:.6},sway:{default:.5},drape:{default:null},avoidWater:{default:!0},terrain:{default:``,nodePath:!0}};density=`sparse`;area=[20,20];seed=1;varieties=[];palette=[];height=.45;clustering=.6;sway=.5;drape=null;avoidWater=!0;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(typeof t.density==`string`)iO(t.density);else if(!(Number.isFinite(t.density)&&t.density>=0))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' density must be one of [${rO.join(`, `)}] or a number >= 0 (plants/m²), got ${t.density}.`,{prop:`density`,validOptions:rO});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});let n=Math.floor((t.area[0]??0)*(t.area[1]??0)*iO(t.density));if(n>aO)throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' blows the plant budget: area ${t.area[0]}×${t.area[1]} m × density ${iO(t.density)} = ${n} plants > ${aO}. Lower the density or split the field into multiple nodes.`,{prop:`density`});if(!Array.isArray(t.varieties)||new Set(t.varieties).size!==t.varieties.length||!t.varieties.every(e=>jD.includes(e)))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' varieties must be a unique subset of [${jD.join(`, `)}] ([] = all three), got ${JSON.stringify(t.varieties)}.`,{prop:`varieties`,validOptions:[...jD]});if(!Array.isArray(t.palette)||!t.palette.every(e=>typeof e==`string`&&sO.test(e)))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' palette must be an array of '#rrggbb' head colors ([] = white/yellow/violet), got ${JSON.stringify(t.palette)}.`,{prop:`palette`});if(!(t.height>0))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!(t.clustering>=0)||!(t.clustering<=1))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' clustering must be in [0, 1] (0 uniform … 1 tight patches), got ${t.clustering}.`,{prop:`clustering`});if(!(t.sway>=0))throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' sway must be >= 0, got ${t.sway}.`,{prop:`sway`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new N(`BAD_FORMAT`,`Flowers3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`})}time=0;field=null;varietyMeshes=[];fieldKey=``;timeUniform={value:0};swayUniform={value:.5};_createObject3D(){return new _o}_varietyMeshes(){return this.rebuildIfNeeded(),this.varietyMeshes}update(e){this.time+=e,this.timeUniform.value=this.time}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded(),this.swayUniform.value=this.sway}rebuildIfNeeded(){this.field||(this.field=new _o,this._ensureObject3D().add(this.field));let e=JSON.stringify([this.density,this.area,this.seed,this.varieties,this.palette,this.height,this.clustering,this.drape,this.terrain]);e!==this.fieldKey&&(this.fieldKey=e,this.disposeMeshes(),this.resolveDrape(),this.buildField())}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=ZD(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=XD(this);else if(this.terrain!==``)throw new N(`NODE_NOT_FOUND`,`Flowers3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}buildField(){let e=iO(this.density),t=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*e),aO);if(t<=0)return;let n=KD({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:t,clustering:this.clustering});if(this.avoidWater){let e=eO(this);if(e.length>0){let[t,r,i]=XD(this);n=n.filter(n=>!tO(e,n.x+t,n.z+i,this.bedY(n.x,n.z)+r))}}let r=this.varieties.length>0?this.varieties:jD,i=r.map(()=>[]);for(let e of n)i[Math.min(Math.floor(e.variety01*r.length),r.length-1)].push(e);let a=this.palette.length>0?this.palette:oO,o=new P(this.seed+15797765);for(let e=0;e<r.length;e++){let t=i[e];if(t.length===0)continue;let{structure:n,petals:s}=UD(r[e]),c=new bl({vertexColors:!0,roughness:1,side:2}),l=new bl({roughness:.85,side:2});lO(c,this.timeUniform,this.swayUniform),lO(l,this.timeUniform,this.swayUniform);let u=new xc(n,c,t.length),d=new xc(s,l,t.length);u.receiveShadow=!0,d.receiveShadow=!0;for(let e=0;e<t.length;e++){let n=t[e];fO.set(n.x,this.bedY(n.x,n.z),n.z),pO.setFromAxisAngle(uO,n.rotY),mO.setScalar(this.height*n.scale),dO.compose(fO,pO,mO),u.setMatrixAt(e,dO),d.setMatrixAt(e,dO);let r=Math.min(Math.floor(n.color01*a.length),a.length-1);hO.set(a[r]).offsetHSL(o.range(-.02,.02),0,o.range(-.05,.05)),d.setColorAt(e,hO),hO.setRGB(1,1,1).offsetHSL(o.range(-.02,.02),0,o.range(-.06,.04)),u.setColorAt(e,hO)}u.instanceMatrix.needsUpdate=!0,d.instanceMatrix.needsUpdate=!0,u.instanceColor&&(u.instanceColor.needsUpdate=!0),d.instanceColor&&(d.instanceColor.needsUpdate=!0),YD(u),YD(d),this.varietyMeshes.push({variety:r[e],structure:u,petals:d}),this.field.add(u),this.field.add(d)}}disposeMeshes(){for(let{structure:e,petals:t}of this.varietyMeshes)for(let n of[e,t])n.removeFromParent(),n.geometry.dispose(),n.material.dispose(),n.dispose();this.varietyMeshes=[]}free(){this.disposeMeshes(),this.field=null,super.free()}};function lO(e,t,n){e.userData.sway=!0,e.userData.timeUniform=t,e.onBeforeCompile=e=>{e.uniforms.uFlowerTime=t,e.uniforms.uFlowerSway=n,e.vertexShader=`uniform float uFlowerTime;\nuniform float uFlowerSway;\n${e.vertexShader}`.replace(`#include <project_vertex>`,`
6977
6977
  vec4 mvPosition = vec4(transformed, 1.0);
6978
6978
  #ifdef USE_INSTANCING
6979
6979
  mvPosition = instanceMatrix * mvPosition;
@@ -6986,7 +6986,7 @@ normal = perturbSplatNormal(normal, vViewPosition, vUvSplat, blendedNormalSample
6986
6986
  mvPosition.z += uFlowerSway * swayW * 0.020 * cos(uFlowerTime * 1.3 + swayPhase * 1.4);
6987
6987
  mvPosition = modelViewMatrix * mvPosition;
6988
6988
  gl_Position = projectionMatrix * mvPosition;
6989
- `)},e.customProgramCacheKey=()=>`incanto-flowers-sway`}var dO=new U(0,1,0),fO=new G,pO=new U,mO=new H,hO=new U,gO=new K;function _O(e,t,n=4){let r=t.areaX/2,i=t.areaZ/2,a=e.filter(e=>Math.abs(e.x-t.x)<=r+e.radius&&Math.abs(e.z-t.z)<=i+e.radius);return a.sort((e,n)=>(e.x-t.x)**2+(e.z-t.z)**2-((n.x-t.x)**2+(n.z-t.z)**2)),a.slice(0,n)}var vO=[1,.78,.42];function yO(e){let t=new Float32Array(21),n=new Float32Array(14);for(let r=0;r<3;r++){let i=r/3,a=vO[r]*e/2;for(let e=0;e<2;e++){let o=r*2+e;t[o*3]=e===0?-a:a,t[o*3+1]=i,t[o*3+2]=0,n[o*2]=e,n[o*2+1]=i}}t[18]=0,t[19]=1,t[20]=0,n[12]=.5,n[13]=1;let r=new J;return r.setAttribute(`position`,new q(t,3)),r.setAttribute(`uv`,new q(n,2)),r.setIndex([0,1,2,2,1,3,2,3,4,4,3,5,4,5,6]),r}function bO(e){let t=new Float32Array([0,1.025,0,-e,.985,0,0,.985,e,e,.985,0,0,.985,-e]),n=new J;return n.setAttribute(`position`,new q(t,3)),n.setIndex([0,1,2,0,2,3,0,3,4,0,4,1]),n.computeVertexNormals(),n}var xO=`
6989
+ `)},e.customProgramCacheKey=()=>`incanto-flowers-sway`}var uO=new U(0,1,0),dO=new G,fO=new U,pO=new H,mO=new U,hO=new K;function gO(e,t,n=4){let r=t.areaX/2,i=t.areaZ/2,a=e.filter(e=>Math.abs(e.x-t.x)<=r+e.radius&&Math.abs(e.z-t.z)<=i+e.radius);return a.sort((e,n)=>(e.x-t.x)**2+(e.z-t.z)**2-((n.x-t.x)**2+(n.z-t.z)**2)),a.slice(0,n)}var _O=[1,.78,.42];function vO(e){let t=new Float32Array(21),n=new Float32Array(14);for(let r=0;r<3;r++){let i=r/3,a=_O[r]*e/2;for(let e=0;e<2;e++){let o=r*2+e;t[o*3]=e===0?-a:a,t[o*3+1]=i,t[o*3+2]=0,n[o*2]=e,n[o*2+1]=i}}t[18]=0,t[19]=1,t[20]=0,n[12]=.5,n[13]=1;let r=new J;return r.setAttribute(`position`,new q(t,3)),r.setAttribute(`uv`,new q(n,2)),r.setIndex([0,1,2,2,1,3,2,3,4,4,3,5,4,5,6]),r}function yO(e){let t=new Float32Array([0,1.025,0,-e,.985,0,0,.985,e,e,.985,0,0,.985,-e]),n=new J;return n.setAttribute(`position`,new q(t,3)),n.setIndex([0,1,2,0,2,3,0,3,4,0,4,1]),n.computeVertexNormals(),n}var bO=`
6990
6990
  uniform float time;
6991
6991
  uniform float windStrength;
6992
6992
  uniform float grassHeight;
@@ -7064,7 +7064,7 @@ void main() {
7064
7064
  gl_Position = projectionMatrix * mvPosition;
7065
7065
  #include <fog_vertex>
7066
7066
  }
7067
- `,SO=`
7067
+ `,xO=`
7068
7068
  uniform float time;
7069
7069
  varying vec2 vUv;
7070
7070
  varying float vHeight;
@@ -7222,7 +7222,7 @@ void main() {
7222
7222
  // patches melt into the same fog as the terrain instead of staying vivid.
7223
7223
  #include <fog_fragment>
7224
7224
  }
7225
- `,CO=`
7225
+ `,SO=`
7226
7226
  // incanto atmosphere: standard fog + shadow-receive chunks — both compile
7227
7227
  // out unless the scene declares fog / a light casts (USE_FOG, USE_SHADOWMAP)
7228
7228
  #include <common>
@@ -7326,7 +7326,7 @@ void main() {
7326
7326
  #include <fog_vertex>
7327
7327
  #include <shadowmap_vertex>
7328
7328
  }
7329
- `,wO=`
7329
+ `,CO=`
7330
7330
  // incanto atmosphere: fog + shadow-receive (grass RECEIVES, never casts —
7331
7331
  // per-blade casting would double the vertex bill for invisible gain).
7332
7332
  // receiveShadow is declared by lights_pars_begin in BUILT-IN materials; a
@@ -7398,7 +7398,7 @@ void main() {
7398
7398
  #include <colorspace_fragment>
7399
7399
  #include <fog_fragment>
7400
7400
  }
7401
- `,TO=.4;function EO(e){if(typeof e.radius==`number`)return e.radius;let t=e.size;if(Array.isArray(t)){let e=typeof t[0]==`number`?t[0]:0,n=typeof t[2]==`number`?t[2]:0;if(e>0||n>0)return Math.max(e,n)/2}return TO}function DO(e){let t=typeof e.radius==`number`?e.radius:0,n=typeof e.height==`number`?e.height:0;if(n>0)return n/2+t;if(t>0)return t;let r=e.size;return Array.isArray(r)&&typeof r[1]==`number`?r[1]/2:TO}function OO(e,t){t.length=0,kO(e,t)}function kO(e,t){if(e instanceof Fh||e instanceof Ph){let[n,r,i]=ZD(e);t.push({x:n,y:r,z:i,radius:EO(e.collider),footY:r-DO(e.collider)})}for(let n of e.children)kO(n,t)}function AO(e){let t=e.tree;if(!t){let t=[];return OO(e.getRoot(),t),t}let n=t._frameScratch;if(n&&n.frameId===t.frameId)return n.bodies;let r=n?.bodies??[],i=t.root;return i?OO(i,r):r.length=0,t._frameScratch={frameId:t.frameId,bodies:r},r}var jO=6,MO=512;function NO(e,t=`grass`){if(t===`fern`)return PO(e);let n=new P(e+28919),r=[];for(let e=0;e<180;e++){let e=.5+(n.next()+n.next()-1)*.17,t=(e>=.5?1:-1)*n.range(.04,.5)+n.range(-.1,.1),i=n.range(.45,1),a=Math.min(1,Math.max(0,e+t*(1.5-.9*i)));r.push({rootX:e,tipX:a,height:i,width:n.range(.0028,.0085),shade:n.range(.45,.98),bow:t*n.range(.25,.6)})}return r}function PO(e){let t=new P(e+65121),n=[];for(let e=0;e<56;e++){let r=.5+(t.next()+t.next()-1)*.1,i=(e%2==0?1:-1)*t.range(.12,.55)+t.range(-.06,.06),a=t.range(.32,.85),o=Math.min(1,Math.max(0,r+i*(1.6-.7*a)));n.push({rootX:r,tipX:o,height:a,width:t.range(.014,.03),shade:t.range(.4,.85),bow:i*t.range(.5,.85)})}return n}function FO(e,t=`grass`){let n=e.shade,r=Math.max(.3,e.shade*.62);if(t===`fern`){let e=[{offset:0,gray:r,alpha:0}],t=.14;for(let i=0;i<jO;i++){let a=t+(1-t)*i/jO,o=t+(1-t)*(i+1)/jO,s=r+(n-r)*((a+o)/2);e.push({offset:a+(o-a)*.12,gray:s,alpha:1}),e.push({offset:a+(o-a)*.74,gray:s,alpha:1}),i<jO-1&&e.push({offset:a+(o-a)*.92,gray:s,alpha:.2})}return e[e.length-1].offset<1&&e.push({offset:1,gray:n,alpha:1}),e}return[{offset:0,gray:r,alpha:0},{offset:.22,gray:r,alpha:1},{offset:1,gray:n,alpha:1}]}function IO(e,t=`grass`){if(typeof document>`u`)return null;let n=MO,r=document.createElement(`canvas`);r.width=n,r.height=n;let i=r.getContext(`2d`);if(!i)return null;i.clearRect(0,0,n,n);for(let r of NO(e,t)){let e=r.rootX*n,a=n,o=r.tipX*n,s=(1-r.height)*n,c=(e+o)/2+r.bow*n,l=(a+s)/2,u=Math.max(r.width*n,.75);i.beginPath(),i.moveTo(e-u,a),i.quadraticCurveTo(c-u*.55,l,o,s),i.quadraticCurveTo(c+u*.55,l,e+u,a),i.closePath();let d=i.createLinearGradient(e,a,o,s);for(let e of FO(r,t)){let t=Math.round(e.gray*255);d.addColorStop(e.offset,`rgba(${t},${t},${t},${e.alpha})`)}i.fillStyle=d,i.fill()}let a=new Qc(r);return a.colorSpace=Oi,a}var LO=.08,RO=.5,zO=12,BO=`
7401
+ `,wO=.4;function TO(e){if(typeof e.radius==`number`)return e.radius;let t=e.size;if(Array.isArray(t)){let e=typeof t[0]==`number`?t[0]:0,n=typeof t[2]==`number`?t[2]:0;if(e>0||n>0)return Math.max(e,n)/2}return wO}function EO(e){let t=typeof e.radius==`number`?e.radius:0,n=typeof e.height==`number`?e.height:0;if(n>0)return n/2+t;if(t>0)return t;let r=e.size;return Array.isArray(r)&&typeof r[1]==`number`?r[1]/2:wO}function DO(e,t){t.length=0,OO(e,t)}function OO(e,t){if(e instanceof Fh||e instanceof Ph){let[n,r,i]=XD(e);t.push({x:n,y:r,z:i,radius:TO(e.collider),footY:r-EO(e.collider)})}for(let n of e.children)OO(n,t)}function kO(e){let t=e.tree;if(!t){let t=[];return DO(e.getRoot(),t),t}let n=t._frameScratch;if(n&&n.frameId===t.frameId)return n.bodies;let r=n?.bodies??[],i=t.root;return i?DO(i,r):r.length=0,t._frameScratch={frameId:t.frameId,bodies:r},r}var AO=6,jO=512;function MO(e,t=`grass`){if(t===`fern`)return NO(e);let n=new P(e+28919),r=[];for(let e=0;e<180;e++){let e=.5+(n.next()+n.next()-1)*.17,t=(e>=.5?1:-1)*n.range(.04,.5)+n.range(-.1,.1),i=n.range(.45,1),a=Math.min(1,Math.max(0,e+t*(1.5-.9*i)));r.push({rootX:e,tipX:a,height:i,width:n.range(.0028,.0085),shade:n.range(.45,.98),bow:t*n.range(.25,.6)})}return r}function NO(e){let t=new P(e+65121),n=[];for(let e=0;e<56;e++){let r=.5+(t.next()+t.next()-1)*.1,i=(e%2==0?1:-1)*t.range(.12,.55)+t.range(-.06,.06),a=t.range(.32,.85),o=Math.min(1,Math.max(0,r+i*(1.6-.7*a)));n.push({rootX:r,tipX:o,height:a,width:t.range(.014,.03),shade:t.range(.4,.85),bow:i*t.range(.5,.85)})}return n}function PO(e,t=`grass`){let n=e.shade,r=Math.max(.3,e.shade*.62);if(t===`fern`){let e=[{offset:0,gray:r,alpha:0}],t=.14;for(let i=0;i<AO;i++){let a=t+(1-t)*i/AO,o=t+(1-t)*(i+1)/AO,s=r+(n-r)*((a+o)/2);e.push({offset:a+(o-a)*.12,gray:s,alpha:1}),e.push({offset:a+(o-a)*.74,gray:s,alpha:1}),i<AO-1&&e.push({offset:a+(o-a)*.92,gray:s,alpha:.2})}return e[e.length-1].offset<1&&e.push({offset:1,gray:n,alpha:1}),e}return[{offset:0,gray:r,alpha:0},{offset:.22,gray:r,alpha:1},{offset:1,gray:n,alpha:1}]}function FO(e,t=`grass`){if(typeof document>`u`)return null;let n=jO,r=document.createElement(`canvas`);r.width=n,r.height=n;let i=r.getContext(`2d`);if(!i)return null;i.clearRect(0,0,n,n);for(let r of MO(e,t)){let e=r.rootX*n,a=n,o=r.tipX*n,s=(1-r.height)*n,c=(e+o)/2+r.bow*n,l=(a+s)/2,u=Math.max(r.width*n,.75);i.beginPath(),i.moveTo(e-u,a),i.quadraticCurveTo(c-u*.55,l,o,s),i.quadraticCurveTo(c+u*.55,l,e+u,a),i.closePath();let d=i.createLinearGradient(e,a,o,s);for(let e of PO(r,t)){let t=Math.round(e.gray*255);d.addColorStop(e.offset,`rgba(${t},${t},${t},${e.alpha})`)}i.fillStyle=d,i.fill()}let a=new Qc(r);return a.colorSpace=Oi,a}var IO=.08,LO=.5,RO=12,zO=`
7402
7402
  // GLSL Simplex Noise 3D — https://github.com/ashima/webgl-noise (MIT)
7403
7403
  vec3 ezMod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
7404
7404
  vec4 ezMod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
@@ -7450,9 +7450,9 @@ float ezSimplex3(vec3 v) {
7450
7450
  m = m * m;
7451
7451
  return 42.0 * dot(m * m, vec4(dot(g0, x0), dot(g1, x1), dot(g2, x2), dot(g3, x3)));
7452
7452
  }
7453
- `;function VO(e){return`#include <lights_fragment_maps>
7453
+ `;function BO(e){return`#include <lights_fragment_maps>
7454
7454
  iblIrradiance *= ${e.toFixed(3)};
7455
- radiance *= ${e.toFixed(3)};`}function HO(e,t){e.userData.envCut=t,e.onBeforeCompile=e=>{e.fragmentShader=e.fragmentShader.replace(`#include <lights_fragment_maps>`,VO(t))},e.customProgramCacheKey=()=>`incanto-env-cut-${t.toFixed(3)}`}function UO(e,t,n=1,r){e.userData.sway=!0,e.userData.timeUniform=t,e.userData.envCut=n,r&&(e.userData.leafFade=r);let i=r?`uniform float uLeafFadeStart;
7455
+ radiance *= ${e.toFixed(3)};`}function VO(e,t){e.userData.envCut=t,e.onBeforeCompile=e=>{e.fragmentShader=e.fragmentShader.replace(`#include <lights_fragment_maps>`,BO(t))},e.customProgramCacheKey=()=>`incanto-env-cut-${t.toFixed(3)}`}function HO(e,t,n=1,r){e.userData.sway=!0,e.userData.timeUniform=t,e.userData.envCut=n,r&&(e.userData.leafFade=r);let i=r?`uniform float uLeafFadeStart;
7456
7456
  uniform float uLeafFadeEnd;
7457
7457
  attribute vec3 anchor;
7458
7458
  `:``,a=r?`
@@ -7462,16 +7462,16 @@ attribute vec3 anchor;
7462
7462
  #endif
7463
7463
  vec4 ezAnchorWorld = modelMatrix * ezAnchor;
7464
7464
  float ezFade = step(uLeafFadeStart + 1e-4, uLeafFadeEnd) * smoothstep(uLeafFadeStart, max(uLeafFadeEnd, uLeafFadeStart + 1e-4), distance(cameraPosition, ezAnchorWorld.xyz));
7465
- mvPosition.xyz = mix(mvPosition.xyz, ezAnchor.xyz, ezFade);`:``;e.onBeforeCompile=e=>{e.uniforms.uTreeTime=t,r&&(e.uniforms.uLeafFadeStart=r.start,e.uniforms.uLeafFadeEnd=r.end),e.vertexShader=`uniform float uTreeTime;\n${i}${e.vertexShader}`.replace(`void main() {`,`${BO}\nvoid main() {`).replace(`#include <project_vertex>`,`
7465
+ mvPosition.xyz = mix(mvPosition.xyz, ezAnchor.xyz, ezFade);`:``;e.onBeforeCompile=e=>{e.uniforms.uTreeTime=t,r&&(e.uniforms.uLeafFadeStart=r.start,e.uniforms.uLeafFadeEnd=r.end),e.vertexShader=`uniform float uTreeTime;\n${i}${e.vertexShader}`.replace(`void main() {`,`${zO}\nvoid main() {`).replace(`#include <project_vertex>`,`
7466
7466
  vec4 mvPosition = vec4(transformed, 1.0);
7467
7467
  #ifdef USE_INSTANCING
7468
7468
  mvPosition = instanceMatrix * mvPosition;
7469
7469
  #endif
7470
- float windOffset = 2.0 * 3.14 * ezSimplex3(mvPosition.xyz / ${zO.toFixed(1)});
7471
- mvPosition.xyz += uv.y * ${LO.toFixed(3)} * vec3(1.0, 0.0, 1.0) * (
7472
- 0.5 * sin(uTreeTime * ${RO.toFixed(2)} + windOffset) +
7473
- 0.3 * sin(2.0 * uTreeTime * ${RO.toFixed(2)} + 1.3 * windOffset) +
7474
- 0.2 * sin(5.0 * uTreeTime * ${RO.toFixed(2)} + 1.5 * windOffset)
7470
+ float windOffset = 2.0 * 3.14 * ezSimplex3(mvPosition.xyz / ${RO.toFixed(1)});
7471
+ mvPosition.xyz += uv.y * ${IO.toFixed(3)} * vec3(1.0, 0.0, 1.0) * (
7472
+ 0.5 * sin(uTreeTime * ${LO.toFixed(2)} + windOffset) +
7473
+ 0.3 * sin(2.0 * uTreeTime * ${LO.toFixed(2)} + 1.3 * windOffset) +
7474
+ 0.2 * sin(5.0 * uTreeTime * ${LO.toFixed(2)} + 1.5 * windOffset)
7475
7475
  );${a}
7476
7476
  mvPosition = modelViewMatrix * mvPosition;
7477
7477
  gl_Position = projectionMatrix * mvPosition;
@@ -7485,18 +7485,18 @@ attribute vec3 anchor;
7485
7485
  if (diffuseColor.a < ezCutoff) discard;
7486
7486
  #endif
7487
7487
  #endif
7488
- `).replace(`#include <lights_fragment_maps>`,VO(n))},e.customProgramCacheKey=r?()=>`incanto-eztree-leaf-wind-v5-fade-${n.toFixed(3)}`:()=>`incanto-eztree-leaf-wind-v4-${n.toFixed(3)}`}var WO=40,GO=1;function KO(e,t,n){e.userData.sway=!0,e.userData.timeUniform=t,e.userData.strengthUniform=n,e.onBeforeCompile=e=>{e.uniforms.uTuftTime=t,e.uniforms.uTuftWind=n,e.vertexShader=`uniform float uTuftTime;\nuniform float uTuftWind;\n${e.vertexShader}`.replace(`void main() {`,`${BO}\nvoid main() {`).replace(`#include <project_vertex>`,`
7488
+ `).replace(`#include <lights_fragment_maps>`,BO(n))},e.customProgramCacheKey=r?()=>`incanto-eztree-leaf-wind-v5-fade-${n.toFixed(3)}`:()=>`incanto-eztree-leaf-wind-v4-${n.toFixed(3)}`}var UO=40,WO=1;function GO(e,t,n){e.userData.sway=!0,e.userData.timeUniform=t,e.userData.strengthUniform=n,e.onBeforeCompile=e=>{e.uniforms.uTuftTime=t,e.uniforms.uTuftWind=n,e.vertexShader=`uniform float uTuftTime;\nuniform float uTuftWind;\n${e.vertexShader}`.replace(`void main() {`,`${zO}\nvoid main() {`).replace(`#include <project_vertex>`,`
7489
7489
  vec4 mvPosition = vec4(transformed, 1.0);
7490
7490
  #ifdef USE_INSTANCING
7491
7491
  mvPosition = instanceMatrix * mvPosition;
7492
7492
  #endif
7493
- float tuftPhase = 6.2832 * ezSimplex3(vec3(mvPosition.xz / ${WO.toFixed(1)}, 0.0));
7493
+ float tuftPhase = 6.2832 * ezSimplex3(vec3(mvPosition.xz / ${UO.toFixed(1)}, 0.0));
7494
7494
  mvPosition.xz += uv.y * uTuftWind *
7495
- sin(uTuftTime * ${GO.toFixed(1)} + tuftPhase) *
7496
- cos(uTuftTime * ${(1.4*GO).toFixed(1)} + tuftPhase) * vec2(1.0, 0.8);
7495
+ sin(uTuftTime * ${WO.toFixed(1)} + tuftPhase) *
7496
+ cos(uTuftTime * ${(1.4*WO).toFixed(1)} + tuftPhase) * vec2(1.0, 0.8);
7497
7497
  mvPosition = modelViewMatrix * mvPosition;
7498
7498
  gl_Position = projectionMatrix * mvPosition;
7499
- `)},e.customProgramCacheKey=()=>`incanto-tuft-wind`}var qO=[`grass`,`flowers`,`reeds`],JO=[`blades`,`simple`,`mesh`,`tufts`],YO=[`grass`,`fern`],XO={grass:.08,flowers:.14,reeds:.05},ZO=[.75,1.25],QO=.05,$O=.25,ek=2e5,tk=8,nk=.05,rk=.38,ik=[.75,1.3],ak=.1,ok=.42,sk=[.6,1.6],ck=.8,lk=.9,uk=.04,dk=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],fk=1/3,pk=1.5,mk=1.45,hk=.4,gk=.13,_k=[.85,1.2],vk=[.8,1.3],yk=`#b3a24e`,bk=.8,xk=.5,Sk=class e extends Ah{static typeName=`Foliage3D`;static props={kind:{default:`grass`,options:qO},style:{default:`mesh`,options:JO},tuftStyle:{default:`grass`,options:YO},area:{default:[20,20]},density:{default:12},maxInstances:{default:5e4},height:{default:.25},colorA:{default:`#4d7232`},colorB:{default:`#9aab55`},groundColor:{default:`#1f3015`},sunDirection:{default:[.5,.8,.3]},fadeStart:{default:60},fadeEnd:{default:90},sway:{default:.6},interaction:{default:!0},coverage:{default:.85},flowers:{default:0},seed:{default:1},drape:{default:null},avoidWater:{default:!0},terrain:{default:``,nodePath:!0},renderOrder:{default:2}};renderOrder=2;kind=`grass`;style=`mesh`;tuftStyle=`grass`;area=[20,20];density=12;maxInstances=5e4;height=.25;colorA=`#4d7232`;colorB=`#9aab55`;groundColor=`#1f3015`;sunDirection=[.5,.8,.3];fadeStart=60;fadeEnd=90;sway=.6;interaction=!0;coverage=.85;flowers=0;seed=1;drape=null;avoidWater=!0;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(!qO.includes(t.kind))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' kind must be one of [${qO.join(`, `)}], got '${t.kind}'.`,{prop:`kind`,validOptions:qO});if(!JO.includes(t.style))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' style must be one of [${JO.join(`, `)}], got '${t.style}'.`,{prop:`style`,validOptions:JO});if(!YO.includes(t.tuftStyle))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' tuftStyle must be one of [${YO.join(`, `)}], got '${t.tuftStyle}'.`,{prop:`tuftStyle`,validOptions:YO});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});if(!(t.density>0)||!(t.maxInstances>=1))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' needs density > 0 and maxInstances >= 1, got density ${t.density}, maxInstances ${t.maxInstances}.`,{prop:`density`});if(t.maxInstances>ek)throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' maxInstances is capped at ${ek} (got ${t.maxInstances}) — split giant fields into multiple nodes.`,{prop:`maxInstances`});if(!(t.fadeStart>=0)||!(t.fadeEnd>t.fadeStart))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' needs fadeStart >= 0 and fadeEnd > fadeStart (the LOD fade window), got fadeStart ${t.fadeStart}, fadeEnd ${t.fadeEnd}.`,{prop:`fadeStart`});let n=t.sunDirection;if(!Array.isArray(n)||n.length!==3||!n.every(e=>Number.isFinite(e))||Math.hypot(n[0]??0,n[1]??0,n[2]??0)===0)throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' sunDirection must be a non-zero [x, y, z] vector, got ${JSON.stringify(n)}.`,{prop:`sunDirection`});if(!(t.coverage>0)||!(t.coverage<=1))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' coverage must be in (0, 1] (carpet fill — 1 is solid, lower carves dirt patches), got ${t.coverage}.`,{prop:`coverage`});if(!(t.flowers>=0)||!(t.flowers<=.2))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' flowers must be in [0, 0.2] (fraction of instances rendered as flower heads — for a whole flower FIELD use kind: 'flowers'), got ${t.flowers}.`,{prop:`flowers`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`})}time=0;pivot=null;meshes=[];bladesMaterial=null;benderSlots=null;pickedBenders=[];fieldKey=``;tuftTime=null;tuftStrength=null;tuftTexture=null;_createObject3D(){return new _o}get isBlades(){return this.kind===`grass`&&this.style===`blades`}get isMesh(){return this.kind===`grass`&&this.style===`mesh`}get isTufts(){return this.kind===`grass`&&this.style===`tufts`}get isShaderField(){return this.isMesh||this.isBlades}_field(){return this.rebuildIfNeeded(),this.meshes[0]}_fields(){return this.rebuildIfNeeded(),this.meshes}update(e){this.time+=e,this.pickedBenders=this.computeBenders(),this.writeAnimationUniforms()}writeAnimationUniforms(){if(this.isShaderField&&this.bladesMaterial){let e=this.bladesMaterial.uniforms;e.time&&(e.time.value=this.time),e.windStrength&&(e.windStrength.value=this.sway*(this.isMesh?rk:$O));let t=this.benderSlots;if(t)for(let e=0;e<4;e++){let n=this.pickedBenders[e];n?t[e]?.set(n.x,n.y,n.z,n.radius):t[e]?.set(0,0,0,0)}}else this.isTufts&&(this.tuftTime&&(this.tuftTime.value=this.time),this.tuftStrength&&(this.tuftStrength.value=this.sway*gk))}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded();let e=this.pivot;if(this.writeAnimationUniforms(),this.isShaderField){e.matrix.identity();let t=this.bladesMaterial.uniforms;(t.bottomColor?.value).set(this.colorA),(t.topColor?.value).set(this.colorB),this.isMesh&&((t.groundColor?.value).set(this.groundColor),(t.sunDirection?.value).set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),t.fadeStart&&(t.fadeStart.value=this.fadeStart),t.fadeEnd&&(t.fadeEnd.value=this.fadeEnd))}else if(this.isTufts)e.matrix.identity();else if(this.sway>0){let t=Math.sin(this.time*1.7)*QO*this.sway,n=Math.sin(this.time*1.3+1.7)*QO*this.sway*.6;e.matrix.makeShear(0,0,t,n,0,0)}else e.matrix.identity();e.matrixWorldNeedsUpdate=!0}_applySunDirection(t){if(!this.isMesh||!this.bladesMaterial)return;let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this.bladesMaterial.uniforms.sunDirection?.value)?.set(t[0],t[1],t[2])}computeBenders(){if(!this.interaction||!this.isShaderField)return[];let[e,t,n]=ZD(this);this.drape===!0&&!this.drapeTerrain&&this.resolveDrape();let r=this.drapeTerrain,i=[];for(let e of AO(this)){let n=r?r.heightAt(e.x,e.z):t,a=e.footY-n;a<=xk&&a>=-2.5&&i.push({x:e.x,y:e.y,z:e.z,radius:e.radius+bk})}return _O(i,{x:e,z:n,areaX:this.area[0]??0,areaZ:this.area[1]??0})}rebuildIfNeeded(){this.pivot||(this.pivot=new _o,this.pivot.matrixAutoUpdate=!1,this._ensureObject3D().add(this.pivot));let e=JSON.stringify([this.kind,this.style,this.tuftStyle,this.area,this.density,this.maxInstances,this.height,this.colorA,this.colorB,this.coverage,this.flowers,this.seed,this.drape,this.terrain]);if(e===this.fieldKey&&this.meshes.length>0)return;this.fieldKey=e,this.disposeMeshes(),this.resolveDrape();let t=this.isMesh?tk:this.isTufts?fk:1,n=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*this.density*t),this.maxInstances);this.isMesh?this.buildMeshField(n):this.isTufts?this.buildTuftField(n):this.isBlades?this.buildBladesField(n):this.buildSimpleField(n);for(let e of this.meshes)XD(e),this.pivot.add(e)}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=QD(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=ZD(this);else if(this.terrain!==``)throw new N(`NODE_NOT_FOUND`,`Foliage3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}dryOnly(e){if(!this.avoidWater)return e;let t=tO(this);if(t.length===0)return e;let[n,,r]=ZD(this);return e.filter(e=>!nO(t,e.x+n,e.z+r,this.bedY(e.x,e.z)+this.worldY()))}worldY(){return ZD(this)[1]}buildMeshField(e){let t=jD({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*tk}),n=this.dryOnly(this.coverage>=1?t:t.filter(e=>AD(e.x,e.z,this.seed)<=this.coverage)),r=this.flowers>0?Math.floor(n.length*this.flowers):0,i=new Set;for(let e=0;e<r;e++)i.add(Math.floor((e+.5)*n.length/r));let a=n.filter((e,t)=>!i.has(t)),o=n.filter((e,t)=>i.has(t));this.benderSlots=Array.from({length:4},()=>new Ra(0,0,0,0));let s=hl.merge([X.lights,X.fog]);Object.assign(s,{time:{value:0},windStrength:{value:this.sway*rk},topColor:{value:new K(this.colorB)},bottomColor:{value:new K(this.colorA)},groundColor:{value:new K(this.groundColor)},sunDirection:{value:new U(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize()},fadeStart:{value:this.fadeStart},fadeEnd:{value:this.fadeEnd},benders:{value:this.benderSlots}}),this.bladesMaterial=new vl({vertexShader:CO,fragmentShader:wO,uniforms:s,fog:!0,lights:!0,side:2});let c=yO(nk),l=a.length,u=Math.max(l,1),d=new xc(c,this.bladesMaterial,u);d.count=l,d.receiveShadow=!0;let f=new P(this.seed+5352221),p=new Float32Array(u*4),m=new Float32Array(u),h=new Float32Array(u);for(let e=0;e<l;e++){let t=a[e],n=SD(t.x,t.z),r=OD(t.x,t.z,this.seed),i=(r-.55)/1.15,o=f.range(ik[0],ik[1]),s=this.height*r*(.55+t.scale*.6);Ok.set(t.x,this.bedY(t.x,t.z),t.z),kk.setFromAxisAngle(Ek,t.rotY),Ak.set(o,s,o),d.setMatrixAt(e,Dk.compose(Ok,kk,Ak));let c=n.leanDir+f.range(-.6,.6),l=(ak+ok*(.5*n.lean+.5*f.next()))*(1+ck*i);p[e*4]=Math.cos(c)*l,p[e*4+1]=Math.sin(c)*l,p[e*4+2]=f.range(sk[0],sk[1])*(1+lk*i),p[e*4+3]=f.next(),m[e]=n.hue;let u=kD(t.x,t.z,this.seed)*.85+(f.next()-.5)*.3;h[e]=Math.min(1,Math.max(0,u))}c.setAttribute(`aBlade`,new pc(p,4)),c.setAttribute(`aClumpHue`,new pc(m,1)),c.setAttribute(`aDry`,new pc(h,1)),d.instanceMatrix.needsUpdate=!0,this.meshes=[d],o.length>0&&this.meshes.push(this.buildFlowerMesh(o))}buildFlowerMesh(e){let t=new xc(bO(uk),new bl({roughness:1,side:2}),Math.max(e.length,1));t.count=e.length,t.receiveShadow=!0;let n=new P(this.seed+15797765);for(let r=0;r<e.length;r++){let i=e[r],a=OD(i.x,i.z,this.seed),o=this.height*a*(.85+n.next()*.35);Ok.set(i.x,this.bedY(i.x,i.z),i.z),kk.setFromAxisAngle(Ek,i.rotY),Ak.set(1,o,1),t.setMatrixAt(r,Dk.compose(Ok,kk,Ak));let s=n.next(),c=dk[s<.45?0:s<.75?1:2];t.setColorAt(r,Nk.set(c))}return t.instanceMatrix.needsUpdate=!0,t.instanceColor&&(t.instanceColor.needsUpdate=!0),t}buildTuftField(e){let t=jD({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*fk}),n=this.dryOnly(this.coverage>=1?t:t.filter(e=>AD(e.x,e.z,this.seed)<=this.coverage));this.tuftTime={value:this.time},this.tuftStrength={value:this.sway*gk};let r=new bl({alphaTest:.5,side:2,roughness:1}),i=IO(this.seed,this.tuftStyle);i&&(r.map=i,this.tuftTexture=i),KO(r,this.tuftTime,this.tuftStrength);let a=new xc(wk(),r,Math.max(n.length,1));a.count=n.length,a.castShadow=!1,a.receiveShadow=!0;let o=new P(this.seed+7403357),s=jk.set(this.colorA),c=Mk.set(this.colorB);for(let e=0;e<n.length;e++){let t=n[e],r=1+(OD(t.x,t.z,this.seed)-1)*hk,i=this.height*pk*r*o.range(_k[0],_k[1]),l=i*mk*o.range(vk[0],vk[1]);Ok.set(t.x,this.bedY(t.x,t.z),t.z),kk.setFromAxisAngle(Ek,t.rotY),Ak.set(l,i,l),a.setMatrixAt(e,Dk.compose(Ok,kk,Ak));let u=SD(t.x,t.z),d=Math.min(1,Math.max(0,.5+.35*u.hue+(o.next()-.5)*.3)),f=Math.min(1,Math.max(0,kD(t.x,t.z,this.seed)*.8-.1));Nk.copy(s).lerp(c,d).lerp(Pk.set(yk),f*.5).multiplyScalar(o.range(.62,1.18)),a.setColorAt(e,Nk)}a.instanceMatrix.needsUpdate=!0,a.instanceColor&&(a.instanceColor.needsUpdate=!0),this.meshes=[a]}buildBladesField(e){let t=jD({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density});this.benderSlots=Array.from({length:4},()=>new Ra(0,0,0,0));let n=hl.merge([X.fog]);Object.assign(n,{time:{value:0},windStrength:{value:this.sway*$O},topColor:{value:new K(this.colorB)},bottomColor:{value:new K(this.colorA)},grassHeight:{value:this.height},grassScale:{value:1},benders:{value:this.benderSlots}}),this.bladesMaterial=new vl({vertexShader:xO,fragmentShader:SO,uniforms:n,fog:!0,transparent:!0,side:2,depthWrite:!0,depthTest:!0,alphaTest:.1,blending:0});let r=Ck(this.height),i=new xc(r,this.bladesMaterial,Math.max(e,1)),a=new xc(r,this.bladesMaterial,Math.max(e,1));i.count=e,a.count=e,i.renderOrder=this.renderOrder,a.renderOrder=this.renderOrder;for(let n=0;n<e;n++){let e=t[n];Ok.set(e.x,this.bedY(e.x,e.z),e.z),Ak.setScalar(e.scale),kk.setFromAxisAngle(Ek,e.rotY),i.setMatrixAt(n,Dk.compose(Ok,kk,Ak)),kk.setFromAxisAngle(Ek,e.rotY+Math.PI/2),a.setMatrixAt(n,Dk.compose(Ok,kk,Ak))}i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,this.meshes=[i,a]}buildSimpleField(e){let t=new bl({side:2,roughness:1}),n=new xc(Tk(XO[this.kind]??.08),t,Math.max(e,1));n.receiveShadow=!0;let r=new P(this.seed),i=(this.area[0]??0)/2,a=(this.area[1]??0)/2,o=jk.set(this.colorA),s=Mk.set(this.colorB),c=this.avoidWater?tO(this):[],[l,u,d]=ZD(this),f=0;for(let t=0;t<e;t++){let e=r.range(-i,i),t=r.range(-a,a),p=r.range(0,Math.PI*2),m=r.range(ZO[0],ZO[1]),h=r.next(),g=this.bedY(e,t);c.length>0&&nO(c,e+l,t+d,g+u)||(Ok.set(e,g,t),kk.setFromAxisAngle(Ek,p),Ak.set(1,this.height*m,1),Dk.compose(Ok,kk,Ak),n.setMatrixAt(f,Dk),n.setColorAt(f,Nk.copy(o).lerp(s,h)),f++)}n.count=f,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),this.meshes=[n]}disposeMeshes(){let e=new Set(this.meshes.map(e=>e.geometry)),t=new Set(this.meshes.map(e=>e.material));for(let e of this.meshes)e.removeFromParent(),e.dispose();for(let t of e)t.dispose();for(let e of t)e.dispose?.();this.bladesMaterial?.dispose(),this.bladesMaterial=null,this.benderSlots=null,this.tuftTexture?.dispose(),this.tuftTexture=null,this.tuftTime=null,this.tuftStrength=null,this.meshes=[]}free(){this.disposeMeshes(),this.pivot=null,super.free()}};function Ck(e){let t=new cl(1,e,1,1);return t.translate(0,e/2,0),t}function wk(){let e=[],t=[],n=[],r=[];for(let i=0;i<3;i++){let a=i*Math.PI/3,o=Math.cos(a)/2,s=Math.sin(a)/2,c=-Math.sin(a),l=Math.cos(a),u=i*4;e.push(-o,0,-s,o,0,s,-o,1,-s,o,1,s);for(let e=0;e<4;e++)t.push(c,0,l);n.push(0,0,1,0,0,1,1,1),r.push(u,u+1,u+3,u,u+3,u+2)}let i=new J;return i.setAttribute(`position`,new q(new Float32Array(e),3)),i.setAttribute(`normal`,new q(new Float32Array(t),3)),i.setAttribute(`uv`,new q(new Float32Array(n),2)),i.setIndex(r),i}function Tk(e){let t=e/2,n=new Float32Array([-t,0,0,t,0,0,-t,1,0,t,1,0,0,0,-t,0,0,t,0,1,-t,0,1,t]),r=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0]),i=new J;return i.setAttribute(`position`,new q(n,3)),i.setAttribute(`normal`,new q(r,3)),i.setIndex([0,1,2,2,1,3,4,5,6,6,5,7]),i}var Ek=new U(0,1,0),Dk=new G,Ok=new U,kk=new H,Ak=new U,jk=new K,Mk=new K,Nk=new K,Pk=new K,Fk=class extends Ah{static typeName=`DirectionalLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},castShadow:{default:!1},shadowArea:{default:75},shadowMapSize:{default:2048},shadowFollowsCamera:{default:!1}};color=`#ffffff`;intensity=1;castShadow=!1;shadowArea=75;shadowMapSize=2048;shadowFollowsCamera=!1;_createObject3D(){return new bu}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();if(e.color.set(this.color),e.intensity=this.intensity,e.castShadow=this.castShadow,this.castShadow&&`shadow`in e){let t=e.shadow.camera;`left`in t&&(t.left=-this.shadowArea,t.right=this.shadowArea,t.top=this.shadowArea,t.bottom=-this.shadowArea,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.shadow.mapSize.set(this.shadowMapSize,this.shadowMapSize),e.shadow.bias=-2e-4,e.shadow.normalBias=.002}}},Ik=class extends Ah{static typeName=`OmniLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},range:{default:0}};color=`#ffffff`;intensity=1;range=0;_createObject3D(){return new _u}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();e.color.set(this.color),e.intensity=this.intensity,e.distance=this.range}},Lk=class extends Ah{static typeName=`LoftMesh3D`;static props={sections:{default:[]},slices:{default:24},smooth:{default:4},material:{default:{}},castShadow:{default:!1},receiveShadow:{default:!1}};sections=[];slices=24;smooth=4;material={};castShadow=!1;receiveShadow=!1;static validateJson(e){let t=e;Rk(t.sections,e.name),Aw(t.material,e.name,`LoftMesh3D`);for(let n of[`map`,`normalMap`,`repeat`])if(t.material[n]!==void 0)throw new N(`BAD_FORMAT`,`LoftMesh3D '${e.name}' material does not support '${n}' — a loft has no UVs; use color/metalness/roughness/clearcoat/envMapIntensity instead.`,{prop:`material`})}geometryKey=``;_createObject3D(){return new Ys(new J,new xl)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D(),t=JSON.stringify([this.sections,this.slices,this.smooth]);t!==this.geometryKey&&this.sections.length>=2&&(e.geometry.dispose(),e.geometry=Vk(this.sections,this.slices,this.smooth),this.geometryKey=t),kw(e.material,this.material),e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow}};function Rk(e,t){let n=e=>{throw new N(`BAD_FORMAT`,`LoftMesh3D '${t}' ${e}`,{prop:`sections`})};(!Array.isArray(e)||e.length<2)&&n(`sections needs at least 2 stations, got ${JSON.stringify(e)}.`);for(let[t,r]of e.entries()){(typeof r!=`object`||!r)&&n(`sections[${t}] must be an object.`);for(let e of[`z`,`width`,`height`,`y`])(typeof r[e]!=`number`||!Number.isFinite(r[e]))&&n(`sections[${t}].${e} must be a finite number, got ${JSON.stringify(r[e])}.`);(r.width<=0||r.height<=0)&&n(`sections[${t}] width/height must be positive, got ${r.width}×${r.height}.`),r.corner!==void 0&&!(typeof r.corner==`number`&&r.corner>=0&&r.corner<=1)&&n(`sections[${t}].corner must be in 0..1, got ${JSON.stringify(r.corner)}.`),t>0&&r.z<=e[t-1].z&&n(`sections[].z must be strictly ascending (sections[${t}].z=${r.z}).`)}}function zk(e,t,n,r,i){let a=i*i,o=a*i;return .5*(2*t+(n-e)*i+(2*e-5*t+4*n-r)*a+(-e+3*t-3*n+r)*o)}function Bk(e,t){let n=t=>{let n=e[Math.max(0,Math.min(e.length-1,t))];return{z:n.z,width:n.width,height:n.height,y:n.y,corner:n.corner??.7}},r=[];for(let i=0;i<e.length-1;i++){let a=n(i-1),o=n(i),s=n(i+1),c=n(i+2),l=i===e.length-2?t+1:t;for(let e=0;e<l;e++){let n=e/t;r.push({z:zk(a.z,o.z,s.z,c.z,n),width:Math.max(1e-4,zk(a.width,o.width,s.width,c.width,n)),height:Math.max(1e-4,zk(a.height,o.height,s.height,c.height,n)),y:zk(a.y,o.y,s.y,c.y,n),corner:Math.min(1,Math.max(0,zk(a.corner,o.corner,s.corner,c.corner,n)))})}}return r}function Vk(e,t,n){let r=Math.max(8,Math.min(64,Math.round(t))),i=Bk(e,Math.max(1,Math.min(16,Math.round(n)))),a=i.length,o=new Float32Array((a*r+2)*3),s=i[0],c=i[a-1];o.set([0,s.y,s.z],0),o.set([0,c.y,c.z],3);for(let e=0;e<a;e++){let t=i[e],n=8-6*t.corner,a=Math.max(n,5);for(let i=0;i<r;i++){let s=i/r*Math.PI*2,c=Math.cos(s),l=Math.sin(s),u=l>=0?n:a,d=t.width/2*Math.sign(c)*Math.abs(c)**(2/u),f=t.height/2*Math.sign(l)*Math.abs(l)**(2/u),p=(2+e*r+i)*3;o[p]=d,o[p+1]=t.y+f,o[p+2]=t.z}}let l=[],u=(e,t)=>2+e*r+t%r;for(let e=0;e<a-1;e++)for(let t=0;t<r;t++){let n=u(e,t),r=u(e,t+1),i=u(e+1,t),a=u(e+1,t+1);l.push(n,r,i,r,a,i)}for(let e=0;e<r;e++)l.push(0,u(0,e+1),u(0,e)),l.push(1,u(a-1,e),u(a-1,e+1));let d=new J;return d.setAttribute(`position`,new q(o,3)),d.setIndex(l),d.computeVertexNormals(),d}function Hk(e){let t=e.lastIndexOf(`.`);return t===-1?e:e.slice(0,t)}function Uk(e,t,n){let r=e.tracks.filter(e=>{let r=t.has(Hk(e.name));return n===`keep`?r:!r});return new Vl(`${e.name}#${n}`,e.duration,r)}function Wk(e){let t=new Set,n=e=>{t.add(e.name);for(let t of e.children)n(t)};return n(e),t}var Gk={Hips:`hips`,Spine:`spine`,Spine1:`chest`,Spine2:`upperChest`,Neck:`neck`,Head:`head`,LeftShoulder:`leftShoulder`,LeftArm:`leftUpperArm`,LeftForeArm:`leftLowerArm`,LeftHand:`leftHand`,RightShoulder:`rightShoulder`,RightArm:`rightUpperArm`,RightForeArm:`rightLowerArm`,RightHand:`rightHand`,LeftUpLeg:`leftUpperLeg`,LeftLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,LeftToeBase:`leftToes`,RightUpLeg:`rightUpperLeg`,RightLeg:`rightLowerLeg`,RightFoot:`rightFoot`,RightToeBase:`rightToes`,LeftHandThumb1:`leftThumbMetacarpal`,LeftHandThumb2:`leftThumbProximal`,LeftHandThumb3:`leftThumbDistal`,LeftHandIndex1:`leftIndexProximal`,LeftHandIndex2:`leftIndexIntermediate`,LeftHandIndex3:`leftIndexDistal`,LeftHandMiddle1:`leftMiddleProximal`,LeftHandMiddle2:`leftMiddleIntermediate`,LeftHandMiddle3:`leftMiddleDistal`,LeftHandRing1:`leftRingProximal`,LeftHandRing2:`leftRingIntermediate`,LeftHandRing3:`leftRingDistal`,LeftHandPinky1:`leftLittleProximal`,LeftHandPinky2:`leftLittleIntermediate`,LeftHandPinky3:`leftLittleDistal`,RightHandThumb1:`rightThumbMetacarpal`,RightHandThumb2:`rightThumbProximal`,RightHandThumb3:`rightThumbDistal`,RightHandIndex1:`rightIndexProximal`,RightHandIndex2:`rightIndexIntermediate`,RightHandIndex3:`rightIndexDistal`,RightHandMiddle1:`rightMiddleProximal`,RightHandMiddle2:`rightMiddleIntermediate`,RightHandMiddle3:`rightMiddleDistal`,RightHandRing1:`rightRingProximal`,RightHandRing2:`rightRingIntermediate`,RightHandRing3:`rightRingDistal`,RightHandPinky1:`rightLittleProximal`,RightHandPinky2:`rightLittleIntermediate`,RightHandPinky3:`rightLittleDistal`},Kk={};for(let[e,t]of Object.entries(Gk))Kk[`mixamorig${e}`]=t,Kk[`mixamorig:${e}`]=t;function qk(e,t,n){let r=[],i=new Set,a=new H,o=new H,s=new H,c=n.meta?.metaVersion===`0`,l=t.getObjectByName(`mixamorigHips`)??t.getObjectByName(`mixamorig:Hips`),u=n.humanoid?.getNormalizedBoneNode(`hips`),d=l&&u?Math.abs(u.getWorldPosition(new U).y)/Math.max(1e-6,Math.abs(l.getWorldPosition(new U).y)):1;for(let l of e.tracks){let e=l.name.lastIndexOf(`.`),u=l.name.slice(0,e),f=l.name.slice(e+1),p=Kk[u],m=p?n.humanoid?.getNormalizedBoneNode(p)?.name:void 0,h=t.getObjectByName(u);if(!m||!h){i.add(u);continue}if(h.getWorldQuaternion(a).invert(),h.parent?h.parent.getWorldQuaternion(o):o.identity(),l instanceof Rl&&f===`quaternion`){let e=Float32Array.from(l.values);for(let t=0;t<e.length;t+=4)s.set(e[t]??0,e[t+1]??0,e[t+2]??0,e[t+3]??1),s.premultiply(o).multiply(a),e[t]=c?-s.x:s.x,e[t+1]=s.y,e[t+2]=c?-s.z:s.z,e[t+3]=s.w;r.push(new Rl(`${m}.quaternion`,[...l.times],[...e]))}else if(l instanceof Bl&&f===`position`){let e=Float32Array.from(l.values);for(let t=0;t<e.length;t+=3)e[t]=(c?-(e[t]??0):e[t]??0)*d,e[t+1]=(e[t+1]??0)*d,e[t+2]=(c?-(e[t+2]??0):e[t+2]??0)*d;r.push(new Bl(`${m}.position`,[...l.times],[...e]))}}return{clip:new Vl(`${e.name} (VRM)`,e.duration,r),retargetedTracks:r.length,skippedBones:[...i]}}function Jk(e,t){let n=e.getClip().duration;if(!Number.isFinite(t)||t===0||n<=0)return 0;let r=t%n;return r<0?r+n:r}var Yk=.2,Xk=.12,Zk=class extends Ah{static typeName=`ModelInstance3D`;static signals=[`animationFinished`];static props={...Ah.props,model:{default:``},animation:{default:``},targetHeight:{default:0},castShadow:{default:!1},animationLoop:{default:!0},animationSpeed:{default:1},animationOffset:{default:0},animationUpper:{default:``},animationUpperLoop:{default:!1},upperBodyRoot:{default:`Spine`},receiveShadow:{default:!1},tint:{default:``},metalness:{default:-1},roughness:{default:-1}};model=``;animation=``;targetHeight=0;castShadow=!1;animationLoop=!0;animationSpeed=1;animationOffset=0;animationUpper=``;animationUpperLoop=!1;upperBodyRoot=`Spine`;receiveShadow=!1;tint=``;metalness=-1;roughness=-1;store=null;entry=null;mountedRef=``;fittedHeight=-1;fitGroup=null;_mountedObject3D(){return this.fitGroup}mixer=null;appliedOffset=0;get _mixer(){return this.mixer}get _playingClip(){return this.playing}get _currentActionTime(){return this.currentAction?.time??0}playing=``;currentAction=null;playingUpper=``;upperAction=null;baseMode=`full`;maskCache=new Map;actionKeys=new WeakMap;warnedClaim=!1;tintTargets=[];tintedClones=[];appliedMods=``;nodePoses=new Map;poseNode(e,t){this.nodePoses.set(e,t),this.applyPoses()}_createObject3D(){return new _o}findBone(e){let t=this.fitGroup;if(!t||e===``)return null;let n=t.getObjectByName(e)??t.getObjectByName(`mixamorig${e}`)??t.getObjectByName(`mixamorig:${e}`);if(n)return n;let r=e.toLowerCase(),i=null;return t.traverse(e=>{!i&&e.name.toLowerCase().endsWith(r)&&(i=e)}),i}boneNames(){let e=[];return this.fitGroup?.traverse(t=>{t.isBone&&e.push(t.name)}),e}availableAnimations(){let e=this.entry?.animations.map(e=>e.name)??[],t=this.store?.animationRefs()??[];return[...e,...t]}_syncModel(e){this.store=e;let t=this._ensureObject3D();if(this.model===``){this.fitGroup&&this.unmount(t);return}let n=e.getModel(this.model);if(!(n.status!==`ready`||!n.scene)){if(this.mountedRef!==this.model){this.unmount(t);let e;if(n.isVrm){if(n.claimedBy&&n.claimedBy!==this){this.warnedClaim||(this.warnedClaim=!0,this.diagnose(`warn`,`incanto: VRM '${this.model}' is already displayed by another node — a VRM asset can back only one ModelInstance3D.`));return}n.claimedBy=this,e=n.scene}else e=uC(n.scene);let r=new _o;r.add(e),t.add(r),this.fitGroup=r,this.entry=n,this.mountedRef=this.model,this.mixer=new Wu(e),this.mixer.addEventListener(`finished`,e=>{let t=e.action,n=(t&&this.actionKeys.get(t))??this.animation;t&&t===this.upperAction&&(t.fadeOut(Xk),this.upperAction=null,this.playingUpper=``,this.animationUpper=``),this.emit(`animationFinished`,n)}),this.playing=``,this.currentAction=null,this.fittedHeight=-1,e.traverse(e=>{e.userData.incantoModelShared=!0}),this.tintTargets=[],this.tintedClones=[],this.appliedMods=``,e.traverse(e=>{let t=e;t.isMesh&&t.material&&this.tintTargets.push({mesh:t,original:t.material})})}if(this.fitGroup&&this.fittedHeight!==this.targetHeight)if(this.fittedHeight=this.targetHeight,this.targetHeight>0){let e=this.fitGroup.scale.x;this.fitGroup.scale.setScalar(1);let t=Qk(this.fitGroup).getSize(new U),n=t.y>0?this.targetHeight/t.y:e;n<.05||n>20?(this.fitGroup.scale.setScalar(1),this.diagnose(`warn`,`[incanto] ModelInstance3D '${this.name}': targetHeight fit measured an implausible scale (${n.toFixed(2)}x) — skinned rigs defeat bounding-box measurement. Rendering at the model's authored scale instead.`)):this.fitGroup.scale.setScalar(n)}else this.fitGroup.scale.setScalar(1);this.fitGroup&&this.fitGroup.traverse(e=>{let t=e;t.isMesh&&(t.castShadow=this.castShadow,t.receiveShadow=this.receiveShadow)}),this.applyMaterialMods(),this.applyPoses(),this.syncAnimation(e),this.syncUpperAnimation(e)}}applyMaterialMods(){let e=`${this.tint}|${this.metalness}|${this.roughness}`;if(e===this.appliedMods)return;for(let e of this.tintedClones)e.dispose();this.tintedClones=[];let t=this.tint?new K(this.tint):null,n=t!==null||this.metalness>=0||this.roughness>=0;for(let e of this.tintTargets){if(!n){e.mesh.material=e.original;continue}let r=e=>{let n=e.clone();if(t){let r=n,i=e.color;r.color&&=i?i.clone().multiply(t):t.clone()}let r=n;return this.metalness>=0&&typeof r.metalness==`number`&&(r.metalness=this.metalness),this.roughness>=0&&typeof r.roughness==`number`&&(r.roughness=this.roughness),n.userData.incantoTinted=!0,this.tintedClones.push(n),n};e.mesh.material=Array.isArray(e.original)?e.original.map(r):r(e.original)}this.appliedMods=e}applyPoses(){if(!this.fitGroup||this.nodePoses.size===0)return;let e=Math.PI/180;for(let[t,n]of this.nodePoses){let r=this.fitGroup.getObjectByName(t);r&&r.rotation.set(n[0]*e,n[1]*e,n[2]*e)}}resolveClip(e,t){if(!this.entry)return null;let n=this.entry.animations.find(t=>t.name===e);if(n)return n;if(!(e.startsWith(`$`)||/\.(glb|gltf)$/i.test(e)))return null;let r=t.getAnimation(e);if(r.status===`loading`)return`loading`;if(r.status!==`ready`||!r.scene)return null;let i=(r.clip?r.clips.find(e=>e.name===r.clip):void 0)??r.clips[0];if(!i)return null;if(this.entry.isVrm&&this.entry.vrm){let t=this.entry.retargeted.get(e);if(t)return t;let n=qk(i,r.scene,this.entry.vrm);return n.skippedBones.length>0&&this.diagnose(`warn`,`incanto: retarget '${e}' skipped bones: ${n.skippedBones.join(`, `)}`),this.entry.retargeted.set(e,n.clip),n.clip}return i}layerVariants(e){let t=this.findBone(this.upperBodyRoot);if(!t)return null;let n=`${e.uuid} ${t.name}`,r=this.maskCache.get(n);if(!r){let i=Wk(t);r={upper:Uk(e,i,`keep`),lower:Uk(e,i,`drop`)},this.maskCache.set(n,r)}return r}upperLayerActive(){return this.animationUpper!==``||this.upperAction!==null}syncAnimation(e){if(!this.mixer||!this.entry)return;let t=this.upperLayerActive()?`lower`:`full`;if(this.playing===this.animation&&this.baseMode===t)return;if(this.animation===``){this.currentAction&&this.currentAction.fadeOut(Yk),this.currentAction=null,this.playing=``,this.baseMode=t;return}let n=this.resolveClip(this.animation,e);if(n===`loading`)return;let r=n;if(r&&t===`lower`){let e=this.layerVariants(r);e&&(r=e.lower)}let i=this.playing===this.animation;if(this.playing=this.animation,this.baseMode=t,r){let e=this.mixer.clipAction(r);if(e.reset(),this.animationLoop?e.setLoop(hi,1/0):(e.setLoop(mi,1),e.clampWhenFinished=!0),e.setEffectiveWeight(1),e.time=Jk(e,this.animationOffset),this.appliedOffset=this.animationOffset,e.play(),this.actionKeys.set(e,this.animation),this.currentAction&&this.currentAction!==e){i&&r.duration>0&&(e.time=this.currentAction.time%r.duration);let t=r.duration>0&&this.currentAction.getClip().duration>0;e.crossFadeFrom(this.currentAction,Yk,t)}this.currentAction=e}else this.diagnose(`warn`,`incanto: model '${this.model}' has no animation '${this.animation}' — embedded: ${this.entry.animations.map(e=>e.name).join(`, `)||`(none)`}; assets: ${e.animationRefs().join(`, `)||`(none)`}`)}syncUpperAnimation(e){if(!this.mixer||!this.entry||this.playingUpper===this.animationUpper)return;if(this.animationUpper===``){this.upperAction?.fadeOut(Xk),this.upperAction=null,this.playingUpper=``;return}let t=this.resolveClip(this.animationUpper,e);if(t===`loading`)return;if(!t){this.diagnose(`warn`,`incanto: model '${this.model}' has no animation '${this.animationUpper}' for the upper layer.`),this.playingUpper=this.animationUpper;return}let n=this.layerVariants(t);if(!n){this.diagnose(`warn`,`incanto: upperBodyRoot '${this.upperBodyRoot}' not found in '${this.model}' — upper layer skipped.`),this.playingUpper=this.animationUpper;return}let r=this.mixer.clipAction(n.upper);r.reset(),this.animationUpperLoop?r.setLoop(hi,1/0):(r.setLoop(mi,1),r.clampWhenFinished=!0),r.setEffectiveWeight(1),r.time=Jk(r,this.animationOffset),r.fadeIn(Xk),r.play(),this.actionKeys.set(r,this.animationUpper),this.upperAction&&this.upperAction!==r&&this.upperAction.fadeOut(Xk),this.upperAction=r,this.playingUpper=this.animationUpper}update(e){this.mixer&&this.mixer.timeScale!==this.animationSpeed&&(this.mixer.timeScale=this.animationSpeed),this.currentAction&&this.animationOffset!==this.appliedOffset&&(this.appliedOffset=this.animationOffset,this.currentAction.time=Jk(this.currentAction,this.animationOffset)),this.mixer?.update(e),this.entry?.isVrm&&this.entry.claimedBy===this&&this.entry.vrm?.update(e)}onExitTree(){this.unmount(this._ensureObject3D())}unmount(e){this.entry?.claimedBy===this&&(this.entry.claimedBy=null),this.fitGroup&&e.remove(this.fitGroup);for(let e of this.tintedClones)e.dispose();this.tintedClones=[],this.tintTargets=[],this.appliedMods=``,this.fitGroup=null,this.mixer=null,this.currentAction=null,this.upperAction=null,this.playingUpper=``,this.baseMode=`full`,this.maskCache.clear(),this.entry=null,this.mountedRef=``,this.playing=``,this.fittedHeight=-1}};function Qk(e){e.updateWorldMatrix(!0,!0);let t=new Vo,n=new Vo,r=e.matrixWorld.clone().invert(),i=new G,a=new U;return e.traverse(e=>{let o=e;if(o.isSkinnedMesh&&o.skeleton){for(let e of o.skeleton.boneInverses)i.copy(e).invert().premultiply(o.matrixWorld).premultiply(r),a.setFromMatrixPosition(i),t.expandByPoint(a);return}let s=e;s.isMesh&&s.geometry&&(s.geometry.computeBoundingBox(),s.geometry.boundingBox&&(n.copy(s.geometry.boundingBox).applyMatrix4(s.matrixWorld).applyMatrix4(r),t.union(n)))}),t}var $k=.01,eA=class e extends Ah{orderGroup=`effects`;static typeName=`Particles3D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...pn]},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`]},depthTest:{default:!0},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`;depthTest=!0;maxParticles=256;static validateJson(e){let t=e;if(t.preset!==`custom`&&!pn.includes(t.preset))throw new N(`BAD_FORMAT`,`Particles3D '${e.name}' preset must be 'custom' or one of [${pn.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:pn});if(t.blend!==`add`&&t.blend!==`normal`)throw new N(`BAD_FORMAT`,`Particles3D '${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){mn(this,this.preset,qe(e.typeName));let t=this.tree?.engine?.rng??new P(4660);this.sim=new gn({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[(this.speed[0]??0)*$k,(this.speed[1]??0)*$k],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[(this.gravity[0]??0)*$k,(this.gravity[1]??0)*$k,(this.gravity[2]??0)*$k],drag:this.drag,maxParticles:this.maxParticles,spreadZ:!0},t)}return this.sim}update(e){let t=this._ensureSim();t.setRate(this.emitting?this.rate:0),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}points=null;positions=null;colors=null;paletteCache=[];paletteCacheKey=``;_syncObject3D(){super._syncObject3D(),this.syncParticles()}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}syncParticles(){let e=this._ensureSim();if(!this.points||(this.positions?.length??0)!==this.maxParticles*3){this.points?.removeFromParent(),this.positions=new Float32Array(this.maxParticles*3),this.colors=new Float32Array(this.maxParticles*4);let e=new J;e.setAttribute(`position`,new q(this.positions,3)),e.setAttribute(`color`,new q(this.colors,4));let t=new Wc({size:(this.sizeStart+this.sizeEnd)/2*$k,map:aA(),vertexColors:!0,transparent:!0,depthWrite:!1,depthTest:this.depthTest,alphaTest:.02,sizeAttenuation:!0,blending:this.blend===`add`?2:1});this.points=new Yc(e,t),this.points.frustumCulled=!1,this._ensureObject3D().add(this.points)}this.points.renderOrder=this.renderOrder;let t=this.points.material;t.depthTest=this.depthTest,t.blending=this.blend===`add`?2:1;let n=this.positions,r=this.colors,i=this.refreshPalette(),a=i?null:tA.set(this.colorStart),o=nA.set(this.colorEnd),s=this.shimmer,c=0;e.forEach(e=>{n[c*3]=e.x,n[c*3+1]=-e.y,n[c*3+2]=e.z;let t=i?i[Math.floor(e.seed*i.length)]:a,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);s>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*s+e.seed))),rA.copy(t).lerp(o,e.t),r[c*4]=rA.r,r[c*4+1]=rA.g,r[c*4+2]=rA.b,r[c*4+3]=l,c+=1});let l=this.points.geometry;l.setDrawRange(0,c),l.getAttribute(`position`).needsUpdate=!0,l.getAttribute(`color`).needsUpdate=!0}},tA=new K,nA=new K,rA=new K,iA=null;function aA(){if(iA)return iA;let e=63/2,t=new Uint8Array(4096*4);for(let n=0;n<64;n++)for(let r=0;r<64;r++){let i=(r-e)/e,a=(n-e)/e,o=Math.hypot(i,a),s=.35,c;if(o<=s)c=1;else{let e=Math.max(0,1-(o-s)/(1-s));c=e*e}let l=Math.round(c*255),u=(n*64+r)*4;t[u]=255,t[u+1]=255,t[u+2]=255,t[u+3]=l}let n=new lc(t,64,64,wr);return n.magFilter=or,n.minFilter=or,n.generateMipmaps=!1,n.needsUpdate=!0,iA=n,n}var oA=2.2,sA=2,cA=.52,lA=.3,uA=1.5,dA=7,fA=.004;function pA(e){if(e.path.length<2)return[];let t=DA(e.path,Math.max(e.cell,e.depth));if(t.length<2)return[];let n=t[t.length-1].along||1,r=t.map(t=>Math.max(OA(e.widths,t.along/n),.05)/2);mA(t,r);let i=t.map(t=>e.groundAt(t.x,t.z)),a=e.depth*oA,o=e.depth*dA,s=Array(t.length);for(let e=0;e<t.length;e++){let n=i[e]-a;if(e===0){s[e]=n;continue}let r=t[e].along-t[e-1].along,c=s[e-1]-r*fA;s[e]=Math.max(Math.min(n,c),i[e]-o)}let c=[];for(let n=1;n<t.length;n++){let a=t[n-1],o=t[n],l=Math.max((i[n-1]+i[n])/2-(s[n-1]+s[n])/2,0);if(l<=.001)continue;let u=Math.min(r[n-1],r[n]),d=Math.max(e.depth*sA,e.cell*uA),f=Math.max(u-d*cA,u*lA,e.cell*.5);c.push({path:[[a.x,a.z],[o.x,o.z]],width:f*2,depth:l,taper:d})}return c}function mA(e,t){let n=e.length,r=Array(n).fill(1/0),i=Array(n).fill(1/0);if(n<3)return{left:r,right:i};let a=t=>e[t].along,o=Array(n).fill(0);for(let t=1;t<n-1;t++){let n=e[t-1],r=e[t],i=e[t+1],a=r.x-n.x,s=r.z-n.z,c=i.x-r.x,l=i.z-r.z,u=Math.hypot(a,s),d=Math.hypot(c,l);if(u<1e-4||d<1e-4)continue;let f=(a*l-s*c)/(u*d);o[t]=Math.asin(Math.max(-1,Math.min(1,f)))/((u+d)/2)}let s=(e,t)=>{let r=Array(n);for(let i=0;i<n;i++){let o=0,s=0;for(let n=i;n>=0&&a(i)-a(n)<=3;n--){let r=e(n);o=t===`max`?Math.max(o,r):o+r,s++}for(let r=i+1;r<n&&a(r)-a(i)<=3;r++){let n=e(r);o=t===`max`?Math.max(o,n):o+n,s++}r[i]=t===`max`?o:o/Math.max(s,1)}return r},c=s(e=>Math.max(o[e],0),`max`),l=s(e=>Math.max(-o[e],0),`max`),u=s(e=>c[e],`mean`),d=s(e=>l[e],`mean`),f=e=>e>1e-5?Math.min(1/e*kA,AA):AA;for(let e=0;e<n;e++)r[e]=f(Math.max(u[e],c[e]*.6)),i[e]=f(Math.max(d[e],l[e]*.6));for(let e=0;e<n;e++)t[e]=Math.min(t[e],Math.max(r[e],i[e]));return{left:r,right:i}}function hA(e,t=.6){let n=[];for(let r of e){let e=Math.max(r.wettedLeft??r.halfLeft,r.wettedRight??r.halfRight),i=Math.max(r.halfLeft,r.halfRight);e-i>t&&n.push({along:r.along,wettedHalfWidth:e,carriedHalfWidth:i})}return n}var gA=24,_A=3,vA=4,yA=.05,bA=12,xA=14,SA=3,CA=5,wA=.04,TA=2;function EA(e,t){return Math.max(e*SA,e+t*CA)}function DA(e,t){let n=e.map(e=>({x:e[0]??0,z:e[1]??0})).filter((e,t,n)=>t===0||Math.hypot(e.x-(n[t-1]?.x??0),e.z-(n[t-1]?.z??0))>1e-6);if(n.length<2||t<=0)return[];let r=[],i=0;for(let e=0;e<n.length-1;e++){let t=n[Math.max(0,e-1)],a=n[e],o=n[e+1],s=n[Math.min(n.length-1,e+2)];for(let e=0;e<gA;e++){let n=e/gA,c=HA(t.x,a.x,o.x,s.x,n),l=HA(t.z,a.z,o.z,s.z,n),u=r[r.length-1];u&&(i+=Math.hypot(c-u.x,l-u.z)),r.push({x:c,z:l,along:i})}}let a=n[n.length-1],o=r[r.length-1];o&&(i+=Math.hypot(a.x-o.x,a.z-o.z)),r.push({x:a.x,z:a.z,along:i});let s=i;if(s<1e-6)return[];let c=Math.max(1,Math.round(s/t)),l=s/c,u=[],d=0;for(let e=0;e<=c;e++){let t=Math.min(e*l,s);for(;d<r.length-2&&r[d+1].along<t;)d++;let n=r[d],i=r[Math.min(d+1,r.length-1)],a=i.along-n.along,o=a>1e-9?(t-n.along)/a:0;u.push({x:n.x+(i.x-n.x)*o,z:n.z+(i.z-n.z)*o,tx:1,tz:0,along:t})}for(let e=0;e<u.length;e++){let t=u[Math.max(0,e-1)],n=u[Math.min(u.length-1,e+1)],r=n.x-t.x,i=n.z-t.z,a=Math.hypot(r,i)||1,o=u[e];o.tx=r/a,o.tz=i/a}return u}function OA(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.min(Math.max(t,0),1)*(e.length-1),r=Math.min(Math.floor(n),e.length-2),i=n-r,a=e[r];return a+(e[r+1]-a)*i}var kA=.85,AA=1e4,jA=1.2,MA=.35,NA=.4;function PA(e,t){let n=Math.min(...e);return Math.min(Math.max(Math.min(n*.45,t*.45),.3),2.5)}function FA(e){let t=DA(e.path,e.step);if(t.length===0)return[];let n=t[t.length-1].along||1,r=t.map(t=>Math.max(OA(e.widths,t.along/n),.05)/2),i=mA(t,r),a=t.map(t=>e.bedAt(t.x,t.z)),o=Array(a.length);for(let e=0;e<a.length;e++){let t=a[e];o[e]=e===0?t:Math.min(t,o[e-1])}let s=Math.max(.5,e.depth*1.5),c=o.map((e,t)=>{let n=0,r=0;for(let i=-3;i<=_A;i++){let a=o[Math.min(Math.max(t+i,0),o.length-1)];Math.abs(a-e)>s||(n+=a,r++)}return r>0?n/r:e}),l=Array(c.length);for(let e=0;e<c.length;e++){let t=c[e];l[e]=e===0?t:Math.min(t,l[e-1])}let u=e.fit===!0,d=Array(t.length),f=Array(t.length);for(let n=0;n<t.length;n++){let i=t[n],a=l[n]+e.depth;if(!u){f[n]=[1/0,1/0],d[n]=a;continue}let o=EA(r[n],e.depth),s=-i.tz,c=i.tx,p=-1/0,m=-1/0;for(let t=1;t<=xA;t++){let n=t/xA*o;p=Math.max(p,e.bedAt(i.x+s*n,i.z+c*n)),m=Math.max(m,e.bedAt(i.x-s*n,i.z-c*n))}f[n]=[p,m],d[n]=Math.min(a,p,m)}for(let e=0;e<d.length;e++){let t=d[e];u&&(t=Math.max(t,a[e]+wA)),e>0&&(t=Math.min(t,d[e-1]));let n=f[e];t=Math.min(t,Math.max(Math.min(n[0],n[1]),a[e]+wA)),d[e]=t}let p=t.map((t,n)=>{let i=r[n];if(!u)return[i,i];let a=EA(i,e.depth),o=d[n],s=-t.tz,c=t.tx,l=n=>{for(let r=1;r<=xA;r++){let i=r/xA*a;if(e.bedAt(t.x+s*i*n,t.z+c*i*n)>=o)return i}return-i};return[l(1),l(-1)]}),m=p.map(e=>[Math.abs(e[0]),Math.abs(e[1])]);for(let e of[0,1]){for(let n=1;n<m.length;n++){let r=Math.max(t[n].along-t[n-1].along,1e-4),i=m[n-1][e],a=m[n][e];m[n][e]=Math.min(a,i+r*jA)}for(let n=m.length-2;n>=0;n--){let r=Math.max(t[n+1].along-t[n].along,1e-4),i=m[n+1][e],a=m[n][e];m[n][e]=Math.min(a,i+r*jA)}}let h=m.map((e,t)=>{let n=0,r=0,i=0;for(let e=-2;e<=TA;e++){let a=m[Math.min(Math.max(t+e,0),m.length-1)];n+=Math.abs(a[0]),r+=Math.abs(a[1]),i++}let a=m[t];return[Math.min(n/i,Math.abs(a[0])),Math.min(r/i,Math.abs(a[1]))]}),g=t.map((e,t)=>[Math.min(h[t][0],i.left[t]),Math.min(h[t][1],i.right[t])]),_=g.reduce((e,t)=>Math.max(e,t[0],t[1]),0);for(let e=0;e<t.length;e++){let n=g[e];for(let r=e+1;r<t.length;r++){let i=g[r],a=Math.max(n[0],n[1],i[0],i[1]);if(t[r].along-t[e].along<a*3)continue;let o=Math.hypot(t[e].x-t[r].x,t[e].z-t[r].z);if(!(o>_*2+MA))for(let e of[0,1]){if(o>=n[e]+i[e]+MA)continue;let t=Math.max((o-MA)/2,NA);n[e]>t&&(n[e]=t),i[e]>t&&(i[e]=t)}}}for(let e of[0,1]){for(let n=1;n<g.length;n++){let r=Math.max(t[n].along-t[n-1].along,1e-4),i=g[n-1][e],a=g[n][e];g[n][e]=Math.min(a,i+r*jA)}for(let n=g.length-2;n>=0;n--){let r=Math.max(t[n+1].along-t[n].along,1e-4),i=g[n+1][e],a=g[n][e];g[n][e]=Math.min(a,i+r*jA)}}let v=r.reduce((e,t)=>e+t,0)/r.length||1;return t.map((n,i)=>{let a=d[i],o=Math.max(0,i-1),s=Math.min(t.length-1,i+1),c=t[s].along-t[o].along,l=(d[o]-d[s])/(c||1),u=Math.max(0,l),f=r[i],m=h[i],_=Math.min(Math.max(e.flowSpeed*Math.sqrt(v/f)*(1+vA*u),yA),bA),y=p[i];return{...n,halfWidth:f,halfLeft:Math.max(g[i][0],.05),halfRight:Math.max(g[i][1],.05),wettedLeft:Math.max(m[0],.05),wettedRight:Math.max(m[1],.05),spillLeft:y[0]<0,spillRight:y[1]<0,surfaceY:a,slope:u,speed:_}})}function IA(e,t){let n=Math.max(1,Math.round(t.acrossSegments)),r=n+1,i=e.length*r,a=new Float32Array(i*3),o=new Float32Array(i*3),s=new Float32Array(i*2),c=new Float32Array(i*2),l=new Float32Array(i*4),u=Math.max(0,e.length-1)*n,d=new Uint32Array(u*6);for(let i=0;i<e.length;i++){let u=e[i],d=Math.max(u.surfaceY-LA(t,u.x,u.z),wA),f=-u.tz,p=u.tx,m=Math.hypot(u.slope,1),h=u.tx*u.slope/m,g=1/m,_=u.tz*u.slope/m;for(let e=0;e<=n;e++){let m=e/n*2-1,v=m*(m<0?u.halfRight:u.halfLeft)*t.bankOvershoot,y=u.x+f*v,b=u.z+p*v,x=i*r+e,S=LA(t,y,b),C=(m<0?u.spillRight:u.spillLeft)?d+(wA-d)*Math.abs(m):d,w=Math.min(u.surfaceY,S+C);a[x*3]=y,a[x*3+1]=w,a[x*3+2]=b,o[x*3]=h,o[x*3+1]=g,o[x*3+2]=_,s[x*2]=u.along,s[x*2+1]=v,c[x*2]=u.tx,c[x*2+1]=u.tz,l[x*4]=u.speed,l[x*4+1]=Math.max(0,w-S),l[x*4+2]=u.slope,l[x*4+3]=m*t.bankOvershoot}}let f=0;for(let t=0;t+1<e.length;t++)for(let e=0;e<n;e++){let n=t*r+e,i=n+1,a=n+r,o=a+1;d[f++]=n,d[f++]=i,d[f++]=a,d[f++]=i,d[f++]=o,d[f++]=a}return{positions:a,normals:o,uvs:s,flow:c,river:l,indices:d}}function LA(e,t,n){let r=e.bedBlur??0;return r<=0?e.bedAt(t,n):(e.bedAt(t,n)+e.bedAt(t+r,n)+e.bedAt(t-r,n)+e.bedAt(t,n+r)+e.bedAt(t,n-r))/5}function RA(e,t,n){if(e.length===0)return null;let r=0,i=1/0,a=Math.max(1,Math.floor(Math.sqrt(e.length)/2));if(a>1){for(let o=0;o<e.length;o+=a){let a=e[o],s=(a.x-t)**2+(a.z-n)**2;s<i&&(i=s,r=o)}let o=Math.max(0,r-a),s=Math.min(e.length-1,r+a);i=1/0;for(let a=o;a<=s;a++){let o=e[a],s=(o.x-t)**2+(o.z-n)**2;s<i&&(i=s,r=a)}return zA(e,r,t,n)}for(let a=0;a<e.length;a++){let o=e[a],s=(o.x-t)**2+(o.z-n)**2;s<i&&(i=s,r=a)}if(e.length===1){let r=e[0];return BA(r,r,0,t,n,!1)}return zA(e,r,t,n)}function zA(e,t,n,r){let i=null,a=1/0;for(let o of[t-1,t]){if(o<0||o+1>=e.length)continue;let t=e[o],s=e[o+1],c=s.x-t.x,l=s.z-t.z,u=c*c+l*l,d=u>1e-9?((n-t.x)*c+(r-t.z)*l)/u:0,f=Math.min(Math.max(d,0),1),p=o===0&&d<0||o+2===e.length&&d>1,m=t.x+c*f,h=t.z+l*f,g=(m-n)**2+(h-r)**2;g<a&&(a=g,i=BA(t,s,f,n,r,p))}return i}function BA(e,t,n,r,i,a){let o=e.x+(t.x-e.x)*n,s=e.z+(t.z-e.z)*n,c=e.tx+(t.tx-e.tx)*n,l=e.tz+(t.tz-e.tz)*n,u=Math.hypot(c,l)||1;c/=u,l/=u;let d=(r-o)*-l+(i-s)*c,f=(e,t)=>e+(t-e)*n,p=d<0?f(e.halfRight,t.halfRight):f(e.halfLeft,t.halfLeft),m=d/(p||1);return{inside:!a&&Math.abs(m)<=1,across:m,along:e.along+(t.along-e.along)*n,surfaceY:e.surfaceY+(t.surfaceY-e.surfaceY)*n,dirX:c,dirZ:l,speed:e.speed+(t.speed-e.speed)*n,halfWidth:p}}function VA(e,t={}){let n=t.minGrade??.45,r=t.minDrop??1.2,i=[],a=-1;for(let t=0;t<=e.length;t++){let o=t<e.length&&e[t].slope>=n;if(o&&a<0&&(a=t),o||a<0)continue;let s=e[Math.max(0,a-1)],c=e[Math.min(e.length-1,t)],l=s.surfaceY-c.surfaceY;l>=r&&i.push({x:c.x,z:c.z,lipX:s.x,lipZ:s.z,lipHalfWidth:Math.min((s.halfLeft+s.halfRight)/2,s.halfWidth),lipDirX:s.tx,lipDirZ:s.tz,lipSpeed:s.speed,topY:s.surfaceY,baseY:c.surfaceY,drop:l,halfWidth:(c.halfLeft+c.halfRight)/2,dirX:c.tx,dirZ:c.tz,speed:c.speed}),a=-1}return i}function HA(e,t,n,r,i){let a=i*i,o=a*i;return .5*(2*t+(-e+n)*i+(2*e-5*t+4*n-r)*a+(-e+3*t-3*n+r)*o)}var UA=`
7499
+ `)},e.customProgramCacheKey=()=>`incanto-tuft-wind`}var KO=[`grass`,`flowers`,`reeds`],qO=[`blades`,`simple`,`mesh`,`tufts`],JO=[`grass`,`fern`],YO={grass:.08,flowers:.14,reeds:.05},XO=[.75,1.25],ZO=.05,QO=.25,$O=2e5,ek=8,tk=.05,nk=.38,rk=[.75,1.3],ik=.1,ak=.42,ok=[.6,1.6],sk=.8,ck=.9,lk=.04,uk=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],dk=1/3,fk=1.5,pk=1.45,mk=.4,hk=.13,gk=[.85,1.2],_k=[.8,1.3],vk=`#b3a24e`,yk=.8,bk=.5,xk=class e extends Ah{static typeName=`Foliage3D`;static props={kind:{default:`grass`,options:KO},style:{default:`mesh`,options:qO},tuftStyle:{default:`grass`,options:JO},area:{default:[20,20]},density:{default:12},maxInstances:{default:5e4},height:{default:.25},colorA:{default:`#4d7232`},colorB:{default:`#9aab55`},groundColor:{default:`#1f3015`},sunDirection:{default:[.5,.8,.3]},fadeStart:{default:60},fadeEnd:{default:90},sway:{default:.6},interaction:{default:!0},coverage:{default:.85},flowers:{default:0},seed:{default:1},drape:{default:null},avoidWater:{default:!0},terrain:{default:``,nodePath:!0},renderOrder:{default:2}};renderOrder=2;kind=`grass`;style=`mesh`;tuftStyle=`grass`;area=[20,20];density=12;maxInstances=5e4;height=.25;colorA=`#4d7232`;colorB=`#9aab55`;groundColor=`#1f3015`;sunDirection=[.5,.8,.3];fadeStart=60;fadeEnd=90;sway=.6;interaction=!0;coverage=.85;flowers=0;seed=1;drape=null;avoidWater=!0;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(!KO.includes(t.kind))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' kind must be one of [${KO.join(`, `)}], got '${t.kind}'.`,{prop:`kind`,validOptions:KO});if(!qO.includes(t.style))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' style must be one of [${qO.join(`, `)}], got '${t.style}'.`,{prop:`style`,validOptions:qO});if(!JO.includes(t.tuftStyle))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' tuftStyle must be one of [${JO.join(`, `)}], got '${t.tuftStyle}'.`,{prop:`tuftStyle`,validOptions:JO});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});if(!(t.density>0)||!(t.maxInstances>=1))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' needs density > 0 and maxInstances >= 1, got density ${t.density}, maxInstances ${t.maxInstances}.`,{prop:`density`});if(t.maxInstances>$O)throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' maxInstances is capped at ${$O} (got ${t.maxInstances}) — split giant fields into multiple nodes.`,{prop:`maxInstances`});if(!(t.fadeStart>=0)||!(t.fadeEnd>t.fadeStart))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' needs fadeStart >= 0 and fadeEnd > fadeStart (the LOD fade window), got fadeStart ${t.fadeStart}, fadeEnd ${t.fadeEnd}.`,{prop:`fadeStart`});let n=t.sunDirection;if(!Array.isArray(n)||n.length!==3||!n.every(e=>Number.isFinite(e))||Math.hypot(n[0]??0,n[1]??0,n[2]??0)===0)throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' sunDirection must be a non-zero [x, y, z] vector, got ${JSON.stringify(n)}.`,{prop:`sunDirection`});if(!(t.coverage>0)||!(t.coverage<=1))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' coverage must be in (0, 1] (carpet fill — 1 is solid, lower carves dirt patches), got ${t.coverage}.`,{prop:`coverage`});if(!(t.flowers>=0)||!(t.flowers<=.2))throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' flowers must be in [0, 0.2] (fraction of instances rendered as flower heads — for a whole flower FIELD use kind: 'flowers'), got ${t.flowers}.`,{prop:`flowers`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new N(`BAD_FORMAT`,`Foliage3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`})}time=0;pivot=null;meshes=[];bladesMaterial=null;benderSlots=null;pickedBenders=[];fieldKey=``;tuftTime=null;tuftStrength=null;tuftTexture=null;_createObject3D(){return new _o}get isBlades(){return this.kind===`grass`&&this.style===`blades`}get isMesh(){return this.kind===`grass`&&this.style===`mesh`}get isTufts(){return this.kind===`grass`&&this.style===`tufts`}get isShaderField(){return this.isMesh||this.isBlades}_field(){return this.rebuildIfNeeded(),this.meshes[0]}_fields(){return this.rebuildIfNeeded(),this.meshes}update(e){this.time+=e,this.pickedBenders=this.computeBenders(),this.writeAnimationUniforms()}writeAnimationUniforms(){if(this.isShaderField&&this.bladesMaterial){let e=this.bladesMaterial.uniforms;e.time&&(e.time.value=this.time),e.windStrength&&(e.windStrength.value=this.sway*(this.isMesh?nk:QO));let t=this.benderSlots;if(t)for(let e=0;e<4;e++){let n=this.pickedBenders[e];n?t[e]?.set(n.x,n.y,n.z,n.radius):t[e]?.set(0,0,0,0)}}else this.isTufts&&(this.tuftTime&&(this.tuftTime.value=this.time),this.tuftStrength&&(this.tuftStrength.value=this.sway*hk))}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded();let e=this.pivot;if(this.writeAnimationUniforms(),this.isShaderField){e.matrix.identity();let t=this.bladesMaterial.uniforms;(t.bottomColor?.value).set(this.colorA),(t.topColor?.value).set(this.colorB),this.isMesh&&((t.groundColor?.value).set(this.groundColor),(t.sunDirection?.value).set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),t.fadeStart&&(t.fadeStart.value=this.fadeStart),t.fadeEnd&&(t.fadeEnd.value=this.fadeEnd))}else if(this.isTufts)e.matrix.identity();else if(this.sway>0){let t=Math.sin(this.time*1.7)*ZO*this.sway,n=Math.sin(this.time*1.3+1.7)*ZO*this.sway*.6;e.matrix.makeShear(0,0,t,n,0,0)}else e.matrix.identity();e.matrixWorldNeedsUpdate=!0}_applySunDirection(t){if(!this.isMesh||!this.bladesMaterial)return;let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this.bladesMaterial.uniforms.sunDirection?.value)?.set(t[0],t[1],t[2])}computeBenders(){if(!this.interaction||!this.isShaderField)return[];let[e,t,n]=XD(this);this.drape===!0&&!this.drapeTerrain&&this.resolveDrape();let r=this.drapeTerrain,i=[];for(let e of kO(this)){let n=r?r.heightAt(e.x,e.z):t,a=e.footY-n;a<=bk&&a>=-2.5&&i.push({x:e.x,y:e.y,z:e.z,radius:e.radius+yk})}return gO(i,{x:e,z:n,areaX:this.area[0]??0,areaZ:this.area[1]??0})}rebuildIfNeeded(){this.pivot||(this.pivot=new _o,this.pivot.matrixAutoUpdate=!1,this._ensureObject3D().add(this.pivot));let e=JSON.stringify([this.kind,this.style,this.tuftStyle,this.area,this.density,this.maxInstances,this.height,this.colorA,this.colorB,this.coverage,this.flowers,this.seed,this.drape,this.terrain]);if(e===this.fieldKey&&this.meshes.length>0)return;this.fieldKey=e,this.disposeMeshes(),this.resolveDrape();let t=this.isMesh?ek:this.isTufts?dk:1,n=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*this.density*t),this.maxInstances);this.isMesh?this.buildMeshField(n):this.isTufts?this.buildTuftField(n):this.isBlades?this.buildBladesField(n):this.buildSimpleField(n);for(let e of this.meshes)YD(e),this.pivot.add(e)}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=ZD(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=XD(this);else if(this.terrain!==``)throw new N(`NODE_NOT_FOUND`,`Foliage3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}dryOnly(e){if(!this.avoidWater)return e;let t=eO(this);if(t.length===0)return e;let[n,,r]=XD(this);return e.filter(e=>!tO(t,e.x+n,e.z+r,this.bedY(e.x,e.z)+this.worldY()))}worldY(){return XD(this)[1]}buildMeshField(e){let t=AD({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*ek}),n=this.dryOnly(this.coverage>=1?t:t.filter(e=>kD(e.x,e.z,this.seed)<=this.coverage)),r=this.flowers>0?Math.floor(n.length*this.flowers):0,i=new Set;for(let e=0;e<r;e++)i.add(Math.floor((e+.5)*n.length/r));let a=n.filter((e,t)=>!i.has(t)),o=n.filter((e,t)=>i.has(t));this.benderSlots=Array.from({length:4},()=>new Ra(0,0,0,0));let s=hl.merge([X.lights,X.fog]);Object.assign(s,{time:{value:0},windStrength:{value:this.sway*nk},topColor:{value:new K(this.colorB)},bottomColor:{value:new K(this.colorA)},groundColor:{value:new K(this.groundColor)},sunDirection:{value:new U(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize()},fadeStart:{value:this.fadeStart},fadeEnd:{value:this.fadeEnd},benders:{value:this.benderSlots}}),this.bladesMaterial=new vl({vertexShader:SO,fragmentShader:CO,uniforms:s,fog:!0,lights:!0,side:2});let c=vO(tk),l=a.length,u=Math.max(l,1),d=new xc(c,this.bladesMaterial,u);d.count=l,d.receiveShadow=!0;let f=new P(this.seed+5352221),p=new Float32Array(u*4),m=new Float32Array(u),h=new Float32Array(u);for(let e=0;e<l;e++){let t=a[e],n=xD(t.x,t.z),r=DD(t.x,t.z,this.seed),i=(r-.55)/1.15,o=f.range(rk[0],rk[1]),s=this.height*r*(.55+t.scale*.6);Dk.set(t.x,this.bedY(t.x,t.z),t.z),Ok.setFromAxisAngle(Tk,t.rotY),kk.set(o,s,o),d.setMatrixAt(e,Ek.compose(Dk,Ok,kk));let c=n.leanDir+f.range(-.6,.6),l=(ik+ak*(.5*n.lean+.5*f.next()))*(1+sk*i);p[e*4]=Math.cos(c)*l,p[e*4+1]=Math.sin(c)*l,p[e*4+2]=f.range(ok[0],ok[1])*(1+ck*i),p[e*4+3]=f.next(),m[e]=n.hue;let u=OD(t.x,t.z,this.seed)*.85+(f.next()-.5)*.3;h[e]=Math.min(1,Math.max(0,u))}c.setAttribute(`aBlade`,new pc(p,4)),c.setAttribute(`aClumpHue`,new pc(m,1)),c.setAttribute(`aDry`,new pc(h,1)),d.instanceMatrix.needsUpdate=!0,this.meshes=[d],o.length>0&&this.meshes.push(this.buildFlowerMesh(o))}buildFlowerMesh(e){let t=new xc(yO(lk),new bl({roughness:1,side:2}),Math.max(e.length,1));t.count=e.length,t.receiveShadow=!0;let n=new P(this.seed+15797765);for(let r=0;r<e.length;r++){let i=e[r],a=DD(i.x,i.z,this.seed),o=this.height*a*(.85+n.next()*.35);Dk.set(i.x,this.bedY(i.x,i.z),i.z),Ok.setFromAxisAngle(Tk,i.rotY),kk.set(1,o,1),t.setMatrixAt(r,Ek.compose(Dk,Ok,kk));let s=n.next(),c=uk[s<.45?0:s<.75?1:2];t.setColorAt(r,Mk.set(c))}return t.instanceMatrix.needsUpdate=!0,t.instanceColor&&(t.instanceColor.needsUpdate=!0),t}buildTuftField(e){let t=AD({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*dk}),n=this.dryOnly(this.coverage>=1?t:t.filter(e=>kD(e.x,e.z,this.seed)<=this.coverage));this.tuftTime={value:this.time},this.tuftStrength={value:this.sway*hk};let r=new bl({alphaTest:.5,side:2,roughness:1}),i=FO(this.seed,this.tuftStyle);i&&(r.map=i,this.tuftTexture=i),GO(r,this.tuftTime,this.tuftStrength);let a=new xc(Ck(),r,Math.max(n.length,1));a.count=n.length,a.castShadow=!1,a.receiveShadow=!0;let o=new P(this.seed+7403357),s=Ak.set(this.colorA),c=jk.set(this.colorB);for(let e=0;e<n.length;e++){let t=n[e],r=1+(DD(t.x,t.z,this.seed)-1)*mk,i=this.height*fk*r*o.range(gk[0],gk[1]),l=i*pk*o.range(_k[0],_k[1]);Dk.set(t.x,this.bedY(t.x,t.z),t.z),Ok.setFromAxisAngle(Tk,t.rotY),kk.set(l,i,l),a.setMatrixAt(e,Ek.compose(Dk,Ok,kk));let u=xD(t.x,t.z),d=Math.min(1,Math.max(0,.5+.35*u.hue+(o.next()-.5)*.3)),f=Math.min(1,Math.max(0,OD(t.x,t.z,this.seed)*.8-.1));Mk.copy(s).lerp(c,d).lerp(Nk.set(vk),f*.5).multiplyScalar(o.range(.62,1.18)),a.setColorAt(e,Mk)}a.instanceMatrix.needsUpdate=!0,a.instanceColor&&(a.instanceColor.needsUpdate=!0),this.meshes=[a]}buildBladesField(e){let t=AD({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density});this.benderSlots=Array.from({length:4},()=>new Ra(0,0,0,0));let n=hl.merge([X.fog]);Object.assign(n,{time:{value:0},windStrength:{value:this.sway*QO},topColor:{value:new K(this.colorB)},bottomColor:{value:new K(this.colorA)},grassHeight:{value:this.height},grassScale:{value:1},benders:{value:this.benderSlots}}),this.bladesMaterial=new vl({vertexShader:bO,fragmentShader:xO,uniforms:n,fog:!0,transparent:!0,side:2,depthWrite:!0,depthTest:!0,alphaTest:.1,blending:0});let r=Sk(this.height),i=new xc(r,this.bladesMaterial,Math.max(e,1)),a=new xc(r,this.bladesMaterial,Math.max(e,1));i.count=e,a.count=e,i.renderOrder=this.renderOrder,a.renderOrder=this.renderOrder;for(let n=0;n<e;n++){let e=t[n];Dk.set(e.x,this.bedY(e.x,e.z),e.z),kk.setScalar(e.scale),Ok.setFromAxisAngle(Tk,e.rotY),i.setMatrixAt(n,Ek.compose(Dk,Ok,kk)),Ok.setFromAxisAngle(Tk,e.rotY+Math.PI/2),a.setMatrixAt(n,Ek.compose(Dk,Ok,kk))}i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,this.meshes=[i,a]}buildSimpleField(e){let t=new bl({side:2,roughness:1}),n=new xc(wk(YO[this.kind]??.08),t,Math.max(e,1));n.receiveShadow=!0;let r=new P(this.seed),i=(this.area[0]??0)/2,a=(this.area[1]??0)/2,o=Ak.set(this.colorA),s=jk.set(this.colorB),c=this.avoidWater?eO(this):[],[l,u,d]=XD(this),f=0;for(let t=0;t<e;t++){let e=r.range(-i,i),t=r.range(-a,a),p=r.range(0,Math.PI*2),m=r.range(XO[0],XO[1]),h=r.next(),g=this.bedY(e,t);c.length>0&&tO(c,e+l,t+d,g+u)||(Dk.set(e,g,t),Ok.setFromAxisAngle(Tk,p),kk.set(1,this.height*m,1),Ek.compose(Dk,Ok,kk),n.setMatrixAt(f,Ek),n.setColorAt(f,Mk.copy(o).lerp(s,h)),f++)}n.count=f,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),this.meshes=[n]}disposeMeshes(){let e=new Set(this.meshes.map(e=>e.geometry)),t=new Set(this.meshes.map(e=>e.material));for(let e of this.meshes)e.removeFromParent(),e.dispose();for(let t of e)t.dispose();for(let e of t)e.dispose?.();this.bladesMaterial?.dispose(),this.bladesMaterial=null,this.benderSlots=null,this.tuftTexture?.dispose(),this.tuftTexture=null,this.tuftTime=null,this.tuftStrength=null,this.meshes=[]}free(){this.disposeMeshes(),this.pivot=null,super.free()}};function Sk(e){let t=new cl(1,e,1,1);return t.translate(0,e/2,0),t}function Ck(){let e=[],t=[],n=[],r=[];for(let i=0;i<3;i++){let a=i*Math.PI/3,o=Math.cos(a)/2,s=Math.sin(a)/2,c=-Math.sin(a),l=Math.cos(a),u=i*4;e.push(-o,0,-s,o,0,s,-o,1,-s,o,1,s);for(let e=0;e<4;e++)t.push(c,0,l);n.push(0,0,1,0,0,1,1,1),r.push(u,u+1,u+3,u,u+3,u+2)}let i=new J;return i.setAttribute(`position`,new q(new Float32Array(e),3)),i.setAttribute(`normal`,new q(new Float32Array(t),3)),i.setAttribute(`uv`,new q(new Float32Array(n),2)),i.setIndex(r),i}function wk(e){let t=e/2,n=new Float32Array([-t,0,0,t,0,0,-t,1,0,t,1,0,0,0,-t,0,0,t,0,1,-t,0,1,t]),r=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0]),i=new J;return i.setAttribute(`position`,new q(n,3)),i.setAttribute(`normal`,new q(r,3)),i.setIndex([0,1,2,2,1,3,4,5,6,6,5,7]),i}var Tk=new U(0,1,0),Ek=new G,Dk=new U,Ok=new H,kk=new U,Ak=new K,jk=new K,Mk=new K,Nk=new K,Pk=class extends Ah{static typeName=`DirectionalLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},castShadow:{default:!1},shadowArea:{default:75},shadowMapSize:{default:2048},shadowFollowsCamera:{default:!1}};color=`#ffffff`;intensity=1;castShadow=!1;shadowArea=75;shadowMapSize=2048;shadowFollowsCamera=!1;_createObject3D(){return new bu}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();if(e.color.set(this.color),e.intensity=this.intensity,e.castShadow=this.castShadow,this.castShadow&&`shadow`in e){let t=e.shadow.camera;`left`in t&&(t.left=-this.shadowArea,t.right=this.shadowArea,t.top=this.shadowArea,t.bottom=-this.shadowArea,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.shadow.mapSize.set(this.shadowMapSize,this.shadowMapSize),e.shadow.bias=-2e-4,e.shadow.normalBias=.002}}},Fk=class extends Ah{static typeName=`OmniLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},range:{default:0}};color=`#ffffff`;intensity=1;range=0;_createObject3D(){return new _u}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();e.color.set(this.color),e.intensity=this.intensity,e.distance=this.range}},Ik=class extends Ah{static typeName=`LoftMesh3D`;static props={sections:{default:[]},slices:{default:24},smooth:{default:4},material:{default:{}},castShadow:{default:!1},receiveShadow:{default:!1}};sections=[];slices=24;smooth=4;material={};castShadow=!1;receiveShadow=!1;static validateJson(e){let t=e;Lk(t.sections,e.name),Aw(t.material,e.name,`LoftMesh3D`);for(let n of[`map`,`normalMap`,`repeat`])if(t.material[n]!==void 0)throw new N(`BAD_FORMAT`,`LoftMesh3D '${e.name}' material does not support '${n}' — a loft has no UVs; use color/metalness/roughness/clearcoat/envMapIntensity instead.`,{prop:`material`})}geometryKey=``;_createObject3D(){return new Ys(new J,new xl)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D(),t=JSON.stringify([this.sections,this.slices,this.smooth]);t!==this.geometryKey&&this.sections.length>=2&&(e.geometry.dispose(),e.geometry=Bk(this.sections,this.slices,this.smooth),this.geometryKey=t),kw(e.material,this.material),e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow}};function Lk(e,t){let n=e=>{throw new N(`BAD_FORMAT`,`LoftMesh3D '${t}' ${e}`,{prop:`sections`})};(!Array.isArray(e)||e.length<2)&&n(`sections needs at least 2 stations, got ${JSON.stringify(e)}.`);for(let[t,r]of e.entries()){(typeof r!=`object`||!r)&&n(`sections[${t}] must be an object.`);for(let e of[`z`,`width`,`height`,`y`])(typeof r[e]!=`number`||!Number.isFinite(r[e]))&&n(`sections[${t}].${e} must be a finite number, got ${JSON.stringify(r[e])}.`);(r.width<=0||r.height<=0)&&n(`sections[${t}] width/height must be positive, got ${r.width}×${r.height}.`),r.corner!==void 0&&!(typeof r.corner==`number`&&r.corner>=0&&r.corner<=1)&&n(`sections[${t}].corner must be in 0..1, got ${JSON.stringify(r.corner)}.`),t>0&&r.z<=e[t-1].z&&n(`sections[].z must be strictly ascending (sections[${t}].z=${r.z}).`)}}function Rk(e,t,n,r,i){let a=i*i,o=a*i;return .5*(2*t+(n-e)*i+(2*e-5*t+4*n-r)*a+(-e+3*t-3*n+r)*o)}function zk(e,t){let n=t=>{let n=e[Math.max(0,Math.min(e.length-1,t))];return{z:n.z,width:n.width,height:n.height,y:n.y,corner:n.corner??.7}},r=[];for(let i=0;i<e.length-1;i++){let a=n(i-1),o=n(i),s=n(i+1),c=n(i+2),l=i===e.length-2?t+1:t;for(let e=0;e<l;e++){let n=e/t;r.push({z:Rk(a.z,o.z,s.z,c.z,n),width:Math.max(1e-4,Rk(a.width,o.width,s.width,c.width,n)),height:Math.max(1e-4,Rk(a.height,o.height,s.height,c.height,n)),y:Rk(a.y,o.y,s.y,c.y,n),corner:Math.min(1,Math.max(0,Rk(a.corner,o.corner,s.corner,c.corner,n)))})}}return r}function Bk(e,t,n){let r=Math.max(8,Math.min(64,Math.round(t))),i=zk(e,Math.max(1,Math.min(16,Math.round(n)))),a=i.length,o=new Float32Array((a*r+2)*3),s=i[0],c=i[a-1];o.set([0,s.y,s.z],0),o.set([0,c.y,c.z],3);for(let e=0;e<a;e++){let t=i[e],n=8-6*t.corner,a=Math.max(n,5);for(let i=0;i<r;i++){let s=i/r*Math.PI*2,c=Math.cos(s),l=Math.sin(s),u=l>=0?n:a,d=t.width/2*Math.sign(c)*Math.abs(c)**(2/u),f=t.height/2*Math.sign(l)*Math.abs(l)**(2/u),p=(2+e*r+i)*3;o[p]=d,o[p+1]=t.y+f,o[p+2]=t.z}}let l=[],u=(e,t)=>2+e*r+t%r;for(let e=0;e<a-1;e++)for(let t=0;t<r;t++){let n=u(e,t),r=u(e,t+1),i=u(e+1,t),a=u(e+1,t+1);l.push(n,r,i,r,a,i)}for(let e=0;e<r;e++)l.push(0,u(0,e+1),u(0,e)),l.push(1,u(a-1,e),u(a-1,e+1));let d=new J;return d.setAttribute(`position`,new q(o,3)),d.setIndex(l),d.computeVertexNormals(),d}function Vk(e){let t=e.lastIndexOf(`.`);return t===-1?e:e.slice(0,t)}function Hk(e,t,n){let r=e.tracks.filter(e=>{let r=t.has(Vk(e.name));return n===`keep`?r:!r});return new Vl(`${e.name}#${n}`,e.duration,r)}function Uk(e){let t=new Set,n=e=>{t.add(e.name);for(let t of e.children)n(t)};return n(e),t}var Wk={Hips:`hips`,Spine:`spine`,Spine1:`chest`,Spine2:`upperChest`,Neck:`neck`,Head:`head`,LeftShoulder:`leftShoulder`,LeftArm:`leftUpperArm`,LeftForeArm:`leftLowerArm`,LeftHand:`leftHand`,RightShoulder:`rightShoulder`,RightArm:`rightUpperArm`,RightForeArm:`rightLowerArm`,RightHand:`rightHand`,LeftUpLeg:`leftUpperLeg`,LeftLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,LeftToeBase:`leftToes`,RightUpLeg:`rightUpperLeg`,RightLeg:`rightLowerLeg`,RightFoot:`rightFoot`,RightToeBase:`rightToes`,LeftHandThumb1:`leftThumbMetacarpal`,LeftHandThumb2:`leftThumbProximal`,LeftHandThumb3:`leftThumbDistal`,LeftHandIndex1:`leftIndexProximal`,LeftHandIndex2:`leftIndexIntermediate`,LeftHandIndex3:`leftIndexDistal`,LeftHandMiddle1:`leftMiddleProximal`,LeftHandMiddle2:`leftMiddleIntermediate`,LeftHandMiddle3:`leftMiddleDistal`,LeftHandRing1:`leftRingProximal`,LeftHandRing2:`leftRingIntermediate`,LeftHandRing3:`leftRingDistal`,LeftHandPinky1:`leftLittleProximal`,LeftHandPinky2:`leftLittleIntermediate`,LeftHandPinky3:`leftLittleDistal`,RightHandThumb1:`rightThumbMetacarpal`,RightHandThumb2:`rightThumbProximal`,RightHandThumb3:`rightThumbDistal`,RightHandIndex1:`rightIndexProximal`,RightHandIndex2:`rightIndexIntermediate`,RightHandIndex3:`rightIndexDistal`,RightHandMiddle1:`rightMiddleProximal`,RightHandMiddle2:`rightMiddleIntermediate`,RightHandMiddle3:`rightMiddleDistal`,RightHandRing1:`rightRingProximal`,RightHandRing2:`rightRingIntermediate`,RightHandRing3:`rightRingDistal`,RightHandPinky1:`rightLittleProximal`,RightHandPinky2:`rightLittleIntermediate`,RightHandPinky3:`rightLittleDistal`},Gk={};for(let[e,t]of Object.entries(Wk))Gk[`mixamorig${e}`]=t,Gk[`mixamorig:${e}`]=t;function Kk(e,t,n){let r=[],i=new Set,a=new H,o=new H,s=new H,c=n.meta?.metaVersion===`0`,l=t.getObjectByName(`mixamorigHips`)??t.getObjectByName(`mixamorig:Hips`),u=n.humanoid?.getNormalizedBoneNode(`hips`),d=l&&u?Math.abs(u.getWorldPosition(new U).y)/Math.max(1e-6,Math.abs(l.getWorldPosition(new U).y)):1;for(let l of e.tracks){let e=l.name.lastIndexOf(`.`),u=l.name.slice(0,e),f=l.name.slice(e+1),p=Gk[u],m=p?n.humanoid?.getNormalizedBoneNode(p)?.name:void 0,h=t.getObjectByName(u);if(!m||!h){i.add(u);continue}if(h.getWorldQuaternion(a).invert(),h.parent?h.parent.getWorldQuaternion(o):o.identity(),l instanceof Rl&&f===`quaternion`){let e=Float32Array.from(l.values);for(let t=0;t<e.length;t+=4)s.set(e[t]??0,e[t+1]??0,e[t+2]??0,e[t+3]??1),s.premultiply(o).multiply(a),e[t]=c?-s.x:s.x,e[t+1]=s.y,e[t+2]=c?-s.z:s.z,e[t+3]=s.w;r.push(new Rl(`${m}.quaternion`,[...l.times],[...e]))}else if(l instanceof Bl&&f===`position`){let e=Float32Array.from(l.values);for(let t=0;t<e.length;t+=3)e[t]=(c?-(e[t]??0):e[t]??0)*d,e[t+1]=(e[t+1]??0)*d,e[t+2]=(c?-(e[t+2]??0):e[t+2]??0)*d;r.push(new Bl(`${m}.position`,[...l.times],[...e]))}}return{clip:new Vl(`${e.name} (VRM)`,e.duration,r),retargetedTracks:r.length,skippedBones:[...i]}}function qk(e,t){let n=e.getClip().duration;if(!Number.isFinite(t)||t===0||n<=0)return 0;let r=t%n;return r<0?r+n:r}var Jk=.2,Yk=.12,Xk=class extends Ah{static typeName=`ModelInstance3D`;static signals=[`animationFinished`];static props={...Ah.props,model:{default:``},animation:{default:``},targetHeight:{default:0},castShadow:{default:!1},animationLoop:{default:!0},animationSpeed:{default:1},animationOffset:{default:0},animationUpper:{default:``},animationUpperLoop:{default:!1},upperBodyRoot:{default:`Spine`},receiveShadow:{default:!1},tint:{default:``},metalness:{default:-1},roughness:{default:-1}};model=``;animation=``;targetHeight=0;castShadow=!1;animationLoop=!0;animationSpeed=1;animationOffset=0;animationUpper=``;animationUpperLoop=!1;upperBodyRoot=`Spine`;receiveShadow=!1;tint=``;metalness=-1;roughness=-1;store=null;entry=null;mountedRef=``;fittedHeight=-1;fitGroup=null;_mountedObject3D(){return this.fitGroup}mixer=null;appliedOffset=0;get _mixer(){return this.mixer}get _playingClip(){return this.playing}get _currentActionTime(){return this.currentAction?.time??0}playing=``;currentAction=null;playingUpper=``;upperAction=null;baseMode=`full`;maskCache=new Map;actionKeys=new WeakMap;warnedClaim=!1;tintTargets=[];tintedClones=[];appliedMods=``;nodePoses=new Map;poseNode(e,t){this.nodePoses.set(e,t),this.applyPoses()}_createObject3D(){return new _o}findBone(e){let t=this.fitGroup;if(!t||e===``)return null;let n=t.getObjectByName(e)??t.getObjectByName(`mixamorig${e}`)??t.getObjectByName(`mixamorig:${e}`);if(n)return n;let r=e.toLowerCase(),i=null;return t.traverse(e=>{!i&&e.name.toLowerCase().endsWith(r)&&(i=e)}),i}boneNames(){let e=[];return this.fitGroup?.traverse(t=>{t.isBone&&e.push(t.name)}),e}availableAnimations(){let e=this.entry?.animations.map(e=>e.name)??[],t=this.store?.animationRefs()??[];return[...e,...t]}_syncModel(e){this.store=e;let t=this._ensureObject3D();if(this.model===``){this.fitGroup&&this.unmount(t);return}let n=e.getModel(this.model);if(!(n.status!==`ready`||!n.scene)){if(this.mountedRef!==this.model){this.unmount(t);let e;if(n.isVrm){if(n.claimedBy&&n.claimedBy!==this){this.warnedClaim||(this.warnedClaim=!0,this.diagnose(`warn`,`incanto: VRM '${this.model}' is already displayed by another node — a VRM asset can back only one ModelInstance3D.`));return}n.claimedBy=this,e=n.scene}else e=uC(n.scene);let r=new _o;r.add(e),t.add(r),this.fitGroup=r,this.entry=n,this.mountedRef=this.model,this.mixer=new Wu(e),this.mixer.addEventListener(`finished`,e=>{let t=e.action,n=(t&&this.actionKeys.get(t))??this.animation;t&&t===this.upperAction&&(t.fadeOut(Yk),this.upperAction=null,this.playingUpper=``,this.animationUpper=``),this.emit(`animationFinished`,n)}),this.playing=``,this.currentAction=null,this.fittedHeight=-1,e.traverse(e=>{e.userData.incantoModelShared=!0}),this.tintTargets=[],this.tintedClones=[],this.appliedMods=``,e.traverse(e=>{let t=e;t.isMesh&&t.material&&this.tintTargets.push({mesh:t,original:t.material})})}if(this.fitGroup&&this.fittedHeight!==this.targetHeight)if(this.fittedHeight=this.targetHeight,this.targetHeight>0){let e=this.fitGroup.scale.x;this.fitGroup.scale.setScalar(1);let t=Zk(this.fitGroup).getSize(new U),n=t.y>0?this.targetHeight/t.y:e;n<.05||n>20?(this.fitGroup.scale.setScalar(1),this.diagnose(`warn`,`[incanto] ModelInstance3D '${this.name}': targetHeight fit measured an implausible scale (${n.toFixed(2)}x) — skinned rigs defeat bounding-box measurement. Rendering at the model's authored scale instead.`)):this.fitGroup.scale.setScalar(n)}else this.fitGroup.scale.setScalar(1);this.fitGroup&&this.fitGroup.traverse(e=>{let t=e;t.isMesh&&(t.castShadow=this.castShadow,t.receiveShadow=this.receiveShadow)}),this.applyMaterialMods(),this.applyPoses(),this.syncAnimation(e),this.syncUpperAnimation(e)}}applyMaterialMods(){let e=`${this.tint}|${this.metalness}|${this.roughness}`;if(e===this.appliedMods)return;for(let e of this.tintedClones)e.dispose();this.tintedClones=[];let t=this.tint?new K(this.tint):null,n=t!==null||this.metalness>=0||this.roughness>=0;for(let e of this.tintTargets){if(!n){e.mesh.material=e.original;continue}let r=e=>{let n=e.clone();if(t){let r=n,i=e.color;r.color&&=i?i.clone().multiply(t):t.clone()}let r=n;return this.metalness>=0&&typeof r.metalness==`number`&&(r.metalness=this.metalness),this.roughness>=0&&typeof r.roughness==`number`&&(r.roughness=this.roughness),n.userData.incantoTinted=!0,this.tintedClones.push(n),n};e.mesh.material=Array.isArray(e.original)?e.original.map(r):r(e.original)}this.appliedMods=e}applyPoses(){if(!this.fitGroup||this.nodePoses.size===0)return;let e=Math.PI/180;for(let[t,n]of this.nodePoses){let r=this.fitGroup.getObjectByName(t);r&&r.rotation.set(n[0]*e,n[1]*e,n[2]*e)}}resolveClip(e,t){if(!this.entry)return null;let n=this.entry.animations.find(t=>t.name===e);if(n)return n;if(!(e.startsWith(`$`)||/\.(glb|gltf)$/i.test(e)))return null;let r=t.getAnimation(e);if(r.status===`loading`)return`loading`;if(r.status!==`ready`||!r.scene)return null;let i=(r.clip?r.clips.find(e=>e.name===r.clip):void 0)??r.clips[0];if(!i)return null;if(this.entry.isVrm&&this.entry.vrm){let t=this.entry.retargeted.get(e);if(t)return t;let n=Kk(i,r.scene,this.entry.vrm);return n.skippedBones.length>0&&this.diagnose(`warn`,`incanto: retarget '${e}' skipped bones: ${n.skippedBones.join(`, `)}`),this.entry.retargeted.set(e,n.clip),n.clip}return i}layerVariants(e){let t=this.findBone(this.upperBodyRoot);if(!t)return null;let n=`${e.uuid} ${t.name}`,r=this.maskCache.get(n);if(!r){let i=Uk(t);r={upper:Hk(e,i,`keep`),lower:Hk(e,i,`drop`)},this.maskCache.set(n,r)}return r}upperLayerActive(){return this.animationUpper!==``||this.upperAction!==null}syncAnimation(e){if(!this.mixer||!this.entry)return;let t=this.upperLayerActive()?`lower`:`full`;if(this.playing===this.animation&&this.baseMode===t)return;if(this.animation===``){this.currentAction&&this.currentAction.fadeOut(Jk),this.currentAction=null,this.playing=``,this.baseMode=t;return}let n=this.resolveClip(this.animation,e);if(n===`loading`)return;let r=n;if(r&&t===`lower`){let e=this.layerVariants(r);e&&(r=e.lower)}let i=this.playing===this.animation;if(this.playing=this.animation,this.baseMode=t,r){let e=this.mixer.clipAction(r);if(e.reset(),this.animationLoop?e.setLoop(hi,1/0):(e.setLoop(mi,1),e.clampWhenFinished=!0),e.setEffectiveWeight(1),e.time=qk(e,this.animationOffset),this.appliedOffset=this.animationOffset,e.play(),this.actionKeys.set(e,this.animation),this.currentAction&&this.currentAction!==e){i&&r.duration>0&&(e.time=this.currentAction.time%r.duration);let t=r.duration>0&&this.currentAction.getClip().duration>0;e.crossFadeFrom(this.currentAction,Jk,t)}this.currentAction=e}else this.diagnose(`warn`,`incanto: model '${this.model}' has no animation '${this.animation}' — embedded: ${this.entry.animations.map(e=>e.name).join(`, `)||`(none)`}; assets: ${e.animationRefs().join(`, `)||`(none)`}`)}syncUpperAnimation(e){if(!this.mixer||!this.entry||this.playingUpper===this.animationUpper)return;if(this.animationUpper===``){this.upperAction?.fadeOut(Yk),this.upperAction=null,this.playingUpper=``;return}let t=this.resolveClip(this.animationUpper,e);if(t===`loading`)return;if(!t){this.diagnose(`warn`,`incanto: model '${this.model}' has no animation '${this.animationUpper}' for the upper layer.`),this.playingUpper=this.animationUpper;return}let n=this.layerVariants(t);if(!n){this.diagnose(`warn`,`incanto: upperBodyRoot '${this.upperBodyRoot}' not found in '${this.model}' — upper layer skipped.`),this.playingUpper=this.animationUpper;return}let r=this.mixer.clipAction(n.upper);r.reset(),this.animationUpperLoop?r.setLoop(hi,1/0):(r.setLoop(mi,1),r.clampWhenFinished=!0),r.setEffectiveWeight(1),r.time=qk(r,this.animationOffset),r.fadeIn(Yk),r.play(),this.actionKeys.set(r,this.animationUpper),this.upperAction&&this.upperAction!==r&&this.upperAction.fadeOut(Yk),this.upperAction=r,this.playingUpper=this.animationUpper}update(e){this.mixer&&this.mixer.timeScale!==this.animationSpeed&&(this.mixer.timeScale=this.animationSpeed),this.currentAction&&this.animationOffset!==this.appliedOffset&&(this.appliedOffset=this.animationOffset,this.currentAction.time=qk(this.currentAction,this.animationOffset)),this.mixer?.update(e),this.entry?.isVrm&&this.entry.claimedBy===this&&this.entry.vrm?.update(e)}onExitTree(){this.unmount(this._ensureObject3D())}unmount(e){this.entry?.claimedBy===this&&(this.entry.claimedBy=null),this.fitGroup&&e.remove(this.fitGroup);for(let e of this.tintedClones)e.dispose();this.tintedClones=[],this.tintTargets=[],this.appliedMods=``,this.fitGroup=null,this.mixer=null,this.currentAction=null,this.upperAction=null,this.playingUpper=``,this.baseMode=`full`,this.maskCache.clear(),this.entry=null,this.mountedRef=``,this.playing=``,this.fittedHeight=-1}};function Zk(e){e.updateWorldMatrix(!0,!0);let t=new Vo,n=new Vo,r=e.matrixWorld.clone().invert(),i=new G,a=new U;return e.traverse(e=>{let o=e;if(o.isSkinnedMesh&&o.skeleton){for(let e of o.skeleton.boneInverses)i.copy(e).invert().premultiply(o.matrixWorld).premultiply(r),a.setFromMatrixPosition(i),t.expandByPoint(a);return}let s=e;s.isMesh&&s.geometry&&(s.geometry.computeBoundingBox(),s.geometry.boundingBox&&(n.copy(s.geometry.boundingBox).applyMatrix4(s.matrixWorld).applyMatrix4(r),t.union(n)))}),t}var Qk=.01,$k=class e extends Ah{orderGroup=`effects`;static typeName=`Particles3D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...pn]},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`]},depthTest:{default:!0},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`;depthTest=!0;maxParticles=256;static validateJson(e){let t=e;if(t.preset!==`custom`&&!pn.includes(t.preset))throw new N(`BAD_FORMAT`,`Particles3D '${e.name}' preset must be 'custom' or one of [${pn.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:pn});if(t.blend!==`add`&&t.blend!==`normal`)throw new N(`BAD_FORMAT`,`Particles3D '${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){mn(this,this.preset,qe(e.typeName));let t=this.tree?.engine?.rng??new P(4660);this.sim=new gn({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[(this.speed[0]??0)*Qk,(this.speed[1]??0)*Qk],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[(this.gravity[0]??0)*Qk,(this.gravity[1]??0)*Qk,(this.gravity[2]??0)*Qk],drag:this.drag,maxParticles:this.maxParticles,spreadZ:!0},t)}return this.sim}update(e){let t=this._ensureSim();t.setRate(this.emitting?this.rate:0),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}points=null;positions=null;colors=null;paletteCache=[];paletteCacheKey=``;_syncObject3D(){super._syncObject3D(),this.syncParticles()}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}syncParticles(){let e=this._ensureSim();if(!this.points||(this.positions?.length??0)!==this.maxParticles*3){this.points?.removeFromParent(),this.positions=new Float32Array(this.maxParticles*3),this.colors=new Float32Array(this.maxParticles*4);let e=new J;e.setAttribute(`position`,new q(this.positions,3)),e.setAttribute(`color`,new q(this.colors,4));let t=new Wc({size:(this.sizeStart+this.sizeEnd)/2*Qk,map:iA(),vertexColors:!0,transparent:!0,depthWrite:!1,depthTest:this.depthTest,alphaTest:.02,sizeAttenuation:!0,blending:this.blend===`add`?2:1});this.points=new Yc(e,t),this.points.frustumCulled=!1,this._ensureObject3D().add(this.points)}this.points.renderOrder=this.renderOrder;let t=this.points.material;t.depthTest=this.depthTest,t.blending=this.blend===`add`?2:1;let n=this.positions,r=this.colors,i=this.refreshPalette(),a=i?null:eA.set(this.colorStart),o=tA.set(this.colorEnd),s=this.shimmer,c=0;e.forEach(e=>{n[c*3]=e.x,n[c*3+1]=-e.y,n[c*3+2]=e.z;let t=i?i[Math.floor(e.seed*i.length)]:a,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);s>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*s+e.seed))),nA.copy(t).lerp(o,e.t),r[c*4]=nA.r,r[c*4+1]=nA.g,r[c*4+2]=nA.b,r[c*4+3]=l,c+=1});let l=this.points.geometry;l.setDrawRange(0,c),l.getAttribute(`position`).needsUpdate=!0,l.getAttribute(`color`).needsUpdate=!0}},eA=new K,tA=new K,nA=new K,rA=null;function iA(){if(rA)return rA;let e=63/2,t=new Uint8Array(4096*4);for(let n=0;n<64;n++)for(let r=0;r<64;r++){let i=(r-e)/e,a=(n-e)/e,o=Math.hypot(i,a),s=.35,c;if(o<=s)c=1;else{let e=Math.max(0,1-(o-s)/(1-s));c=e*e}let l=Math.round(c*255),u=(n*64+r)*4;t[u]=255,t[u+1]=255,t[u+2]=255,t[u+3]=l}let n=new lc(t,64,64,wr);return n.magFilter=or,n.minFilter=or,n.generateMipmaps=!1,n.needsUpdate=!0,rA=n,n}var aA=2.2,oA=2,sA=.52,cA=.3,lA=1.5,uA=7,dA=.004;function fA(e){if(e.path.length<2)return[];let t=EA(e.path,Math.max(e.cell,e.depth));if(t.length<2)return[];let n=t[t.length-1].along||1,r=t.map(t=>Math.max(DA(e.widths,t.along/n),.05)/2);pA(t,r);let i=t.map(t=>e.groundAt(t.x,t.z)),a=e.depth*aA,o=e.depth*uA,s=Array(t.length);for(let e=0;e<t.length;e++){let n=i[e]-a;if(e===0){s[e]=n;continue}let r=t[e].along-t[e-1].along,c=s[e-1]-r*dA;s[e]=Math.max(Math.min(n,c),i[e]-o)}let c=[];for(let n=1;n<t.length;n++){let a=t[n-1],o=t[n],l=Math.max((i[n-1]+i[n])/2-(s[n-1]+s[n])/2,0);if(l<=.001)continue;let u=Math.min(r[n-1],r[n]),d=Math.max(e.depth*oA,e.cell*lA),f=Math.max(u-d*sA,u*cA,e.cell*.5);c.push({path:[[a.x,a.z],[o.x,o.z]],width:f*2,depth:l,taper:d})}return c}function pA(e,t){let n=e.length,r=Array(n).fill(1/0),i=Array(n).fill(1/0);if(n<3)return{left:r,right:i};let a=t=>e[t].along,o=Array(n).fill(0);for(let t=1;t<n-1;t++){let n=e[t-1],r=e[t],i=e[t+1],a=r.x-n.x,s=r.z-n.z,c=i.x-r.x,l=i.z-r.z,u=Math.hypot(a,s),d=Math.hypot(c,l);if(u<1e-4||d<1e-4)continue;let f=(a*l-s*c)/(u*d);o[t]=Math.asin(Math.max(-1,Math.min(1,f)))/((u+d)/2)}let s=(e,t)=>{let r=Array(n);for(let i=0;i<n;i++){let o=0,s=0;for(let n=i;n>=0&&a(i)-a(n)<=3;n--){let r=e(n);o=t===`max`?Math.max(o,r):o+r,s++}for(let r=i+1;r<n&&a(r)-a(i)<=3;r++){let n=e(r);o=t===`max`?Math.max(o,n):o+n,s++}r[i]=t===`max`?o:o/Math.max(s,1)}return r},c=s(e=>Math.max(o[e],0),`max`),l=s(e=>Math.max(-o[e],0),`max`),u=s(e=>c[e],`mean`),d=s(e=>l[e],`mean`),f=e=>e>1e-5?Math.min(1/e*OA,kA):kA;for(let e=0;e<n;e++)r[e]=f(Math.max(u[e],c[e]*.6)),i[e]=f(Math.max(d[e],l[e]*.6));for(let e=0;e<n;e++)t[e]=Math.min(t[e],Math.max(r[e],i[e]));return{left:r,right:i}}function mA(e,t=.6){let n=[];for(let r of e){let e=Math.max(r.wettedLeft??r.halfLeft,r.wettedRight??r.halfRight),i=Math.max(r.halfLeft,r.halfRight);e-i>t&&n.push({along:r.along,wettedHalfWidth:e,carriedHalfWidth:i})}return n}var hA=24,gA=3,_A=4,vA=.05,yA=12,bA=14,xA=3,SA=5,CA=.04,wA=2;function TA(e,t){return Math.max(e*xA,e+t*SA)}function EA(e,t){let n=e.map(e=>({x:e[0]??0,z:e[1]??0})).filter((e,t,n)=>t===0||Math.hypot(e.x-(n[t-1]?.x??0),e.z-(n[t-1]?.z??0))>1e-6);if(n.length<2||t<=0)return[];let r=[],i=0;for(let e=0;e<n.length-1;e++){let t=n[Math.max(0,e-1)],a=n[e],o=n[e+1],s=n[Math.min(n.length-1,e+2)];for(let e=0;e<hA;e++){let n=e/hA,c=VA(t.x,a.x,o.x,s.x,n),l=VA(t.z,a.z,o.z,s.z,n),u=r[r.length-1];u&&(i+=Math.hypot(c-u.x,l-u.z)),r.push({x:c,z:l,along:i})}}let a=n[n.length-1],o=r[r.length-1];o&&(i+=Math.hypot(a.x-o.x,a.z-o.z)),r.push({x:a.x,z:a.z,along:i});let s=i;if(s<1e-6)return[];let c=Math.max(1,Math.round(s/t)),l=s/c,u=[],d=0;for(let e=0;e<=c;e++){let t=Math.min(e*l,s);for(;d<r.length-2&&r[d+1].along<t;)d++;let n=r[d],i=r[Math.min(d+1,r.length-1)],a=i.along-n.along,o=a>1e-9?(t-n.along)/a:0;u.push({x:n.x+(i.x-n.x)*o,z:n.z+(i.z-n.z)*o,tx:1,tz:0,along:t})}for(let e=0;e<u.length;e++){let t=u[Math.max(0,e-1)],n=u[Math.min(u.length-1,e+1)],r=n.x-t.x,i=n.z-t.z,a=Math.hypot(r,i)||1,o=u[e];o.tx=r/a,o.tz=i/a}return u}function DA(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.min(Math.max(t,0),1)*(e.length-1),r=Math.min(Math.floor(n),e.length-2),i=n-r,a=e[r];return a+(e[r+1]-a)*i}var OA=.85,kA=1e4,AA=1.2,jA=.35,MA=.4;function NA(e,t){let n=Math.min(...e);return Math.min(Math.max(Math.min(n*.45,t*.45),.3),2.5)}function PA(e){let t=EA(e.path,e.step);if(t.length===0)return[];let n=t[t.length-1].along||1,r=t.map(t=>Math.max(DA(e.widths,t.along/n),.05)/2),i=pA(t,r),a=t.map(t=>e.bedAt(t.x,t.z)),o=Array(a.length);for(let e=0;e<a.length;e++){let t=a[e];o[e]=e===0?t:Math.min(t,o[e-1])}let s=Math.max(.5,e.depth*1.5),c=o.map((e,t)=>{let n=0,r=0;for(let i=-3;i<=gA;i++){let a=o[Math.min(Math.max(t+i,0),o.length-1)];Math.abs(a-e)>s||(n+=a,r++)}return r>0?n/r:e}),l=Array(c.length);for(let e=0;e<c.length;e++){let t=c[e];l[e]=e===0?t:Math.min(t,l[e-1])}let u=e.fit===!0,d=Array(t.length),f=Array(t.length);for(let n=0;n<t.length;n++){let i=t[n],a=l[n]+e.depth;if(!u){f[n]=[1/0,1/0],d[n]=a;continue}let o=TA(r[n],e.depth),s=-i.tz,c=i.tx,p=-1/0,m=-1/0;for(let t=1;t<=bA;t++){let n=t/bA*o;p=Math.max(p,e.bedAt(i.x+s*n,i.z+c*n)),m=Math.max(m,e.bedAt(i.x-s*n,i.z-c*n))}f[n]=[p,m],d[n]=Math.min(a,p,m)}for(let e=0;e<d.length;e++){let t=d[e];u&&(t=Math.max(t,a[e]+CA)),e>0&&(t=Math.min(t,d[e-1]));let n=f[e];t=Math.min(t,Math.max(Math.min(n[0],n[1]),a[e]+CA)),d[e]=t}let p=t.map((t,n)=>{let i=r[n];if(!u)return[i,i];let a=TA(i,e.depth),o=d[n],s=-t.tz,c=t.tx,l=n=>{for(let r=1;r<=bA;r++){let i=r/bA*a;if(e.bedAt(t.x+s*i*n,t.z+c*i*n)>=o)return i}return-i};return[l(1),l(-1)]}),m=p.map(e=>[Math.abs(e[0]),Math.abs(e[1])]);for(let e of[0,1]){for(let n=1;n<m.length;n++){let r=Math.max(t[n].along-t[n-1].along,1e-4),i=m[n-1][e],a=m[n][e];m[n][e]=Math.min(a,i+r*AA)}for(let n=m.length-2;n>=0;n--){let r=Math.max(t[n+1].along-t[n].along,1e-4),i=m[n+1][e],a=m[n][e];m[n][e]=Math.min(a,i+r*AA)}}let h=m.map((e,t)=>{let n=0,r=0,i=0;for(let e=-2;e<=wA;e++){let a=m[Math.min(Math.max(t+e,0),m.length-1)];n+=Math.abs(a[0]),r+=Math.abs(a[1]),i++}let a=m[t];return[Math.min(n/i,Math.abs(a[0])),Math.min(r/i,Math.abs(a[1]))]}),g=t.map((e,t)=>[Math.min(h[t][0],i.left[t]),Math.min(h[t][1],i.right[t])]),_=g.reduce((e,t)=>Math.max(e,t[0],t[1]),0);for(let e=0;e<t.length;e++){let n=g[e];for(let r=e+1;r<t.length;r++){let i=g[r],a=Math.max(n[0],n[1],i[0],i[1]);if(t[r].along-t[e].along<a*3)continue;let o=Math.hypot(t[e].x-t[r].x,t[e].z-t[r].z);if(!(o>_*2+jA))for(let e of[0,1]){if(o>=n[e]+i[e]+jA)continue;let t=Math.max((o-jA)/2,MA);n[e]>t&&(n[e]=t),i[e]>t&&(i[e]=t)}}}for(let e of[0,1]){for(let n=1;n<g.length;n++){let r=Math.max(t[n].along-t[n-1].along,1e-4),i=g[n-1][e],a=g[n][e];g[n][e]=Math.min(a,i+r*AA)}for(let n=g.length-2;n>=0;n--){let r=Math.max(t[n+1].along-t[n].along,1e-4),i=g[n+1][e],a=g[n][e];g[n][e]=Math.min(a,i+r*AA)}}let v=r.reduce((e,t)=>e+t,0)/r.length||1;return t.map((n,i)=>{let a=d[i],o=Math.max(0,i-1),s=Math.min(t.length-1,i+1),c=t[s].along-t[o].along,l=(d[o]-d[s])/(c||1),u=Math.max(0,l),f=r[i],m=h[i],_=Math.min(Math.max(e.flowSpeed*Math.sqrt(v/f)*(1+_A*u),vA),yA),y=p[i];return{...n,halfWidth:f,halfLeft:Math.max(g[i][0],.05),halfRight:Math.max(g[i][1],.05),wettedLeft:Math.max(m[0],.05),wettedRight:Math.max(m[1],.05),spillLeft:y[0]<0,spillRight:y[1]<0,surfaceY:a,slope:u,speed:_}})}function FA(e,t){let n=Math.max(1,Math.round(t.acrossSegments)),r=n+1,i=e.length*r,a=new Float32Array(i*3),o=new Float32Array(i*3),s=new Float32Array(i*2),c=new Float32Array(i*2),l=new Float32Array(i*4),u=Math.max(0,e.length-1)*n,d=new Uint32Array(u*6);for(let i=0;i<e.length;i++){let u=e[i],d=Math.max(u.surfaceY-IA(t,u.x,u.z),CA),f=-u.tz,p=u.tx,m=Math.hypot(u.slope,1),h=u.tx*u.slope/m,g=1/m,_=u.tz*u.slope/m;for(let e=0;e<=n;e++){let m=e/n*2-1,v=m*(m<0?u.halfRight:u.halfLeft)*t.bankOvershoot,y=u.x+f*v,b=u.z+p*v,x=i*r+e,S=IA(t,y,b),C=(m<0?u.spillRight:u.spillLeft)?d+(CA-d)*Math.abs(m):d,w=Math.min(u.surfaceY,S+C);a[x*3]=y,a[x*3+1]=w,a[x*3+2]=b,o[x*3]=h,o[x*3+1]=g,o[x*3+2]=_,s[x*2]=u.along,s[x*2+1]=v,c[x*2]=u.tx,c[x*2+1]=u.tz,l[x*4]=u.speed,l[x*4+1]=Math.max(0,w-S),l[x*4+2]=u.slope,l[x*4+3]=m*t.bankOvershoot}}let f=0;for(let t=0;t+1<e.length;t++)for(let e=0;e<n;e++){let n=t*r+e,i=n+1,a=n+r,o=a+1;d[f++]=n,d[f++]=i,d[f++]=a,d[f++]=i,d[f++]=o,d[f++]=a}return{positions:a,normals:o,uvs:s,flow:c,river:l,indices:d}}function IA(e,t,n){let r=e.bedBlur??0;return r<=0?e.bedAt(t,n):(e.bedAt(t,n)+e.bedAt(t+r,n)+e.bedAt(t-r,n)+e.bedAt(t,n+r)+e.bedAt(t,n-r))/5}function LA(e,t,n){if(e.length===0)return null;let r=0,i=1/0,a=Math.max(1,Math.floor(Math.sqrt(e.length)/2));if(a>1){for(let o=0;o<e.length;o+=a){let a=e[o],s=(a.x-t)**2+(a.z-n)**2;s<i&&(i=s,r=o)}let o=Math.max(0,r-a),s=Math.min(e.length-1,r+a);i=1/0;for(let a=o;a<=s;a++){let o=e[a],s=(o.x-t)**2+(o.z-n)**2;s<i&&(i=s,r=a)}return RA(e,r,t,n)}for(let a=0;a<e.length;a++){let o=e[a],s=(o.x-t)**2+(o.z-n)**2;s<i&&(i=s,r=a)}if(e.length===1){let r=e[0];return zA(r,r,0,t,n,!1)}return RA(e,r,t,n)}function RA(e,t,n,r){let i=null,a=1/0;for(let o of[t-1,t]){if(o<0||o+1>=e.length)continue;let t=e[o],s=e[o+1],c=s.x-t.x,l=s.z-t.z,u=c*c+l*l,d=u>1e-9?((n-t.x)*c+(r-t.z)*l)/u:0,f=Math.min(Math.max(d,0),1),p=o===0&&d<0||o+2===e.length&&d>1,m=t.x+c*f,h=t.z+l*f,g=(m-n)**2+(h-r)**2;g<a&&(a=g,i=zA(t,s,f,n,r,p))}return i}function zA(e,t,n,r,i,a){let o=e.x+(t.x-e.x)*n,s=e.z+(t.z-e.z)*n,c=e.tx+(t.tx-e.tx)*n,l=e.tz+(t.tz-e.tz)*n,u=Math.hypot(c,l)||1;c/=u,l/=u;let d=(r-o)*-l+(i-s)*c,f=(e,t)=>e+(t-e)*n,p=d<0?f(e.halfRight,t.halfRight):f(e.halfLeft,t.halfLeft),m=d/(p||1);return{inside:!a&&Math.abs(m)<=1,across:m,along:e.along+(t.along-e.along)*n,surfaceY:e.surfaceY+(t.surfaceY-e.surfaceY)*n,dirX:c,dirZ:l,speed:e.speed+(t.speed-e.speed)*n,halfWidth:p}}function BA(e,t={}){let n=t.minGrade??.45,r=t.minDrop??1.2,i=[],a=-1;for(let t=0;t<=e.length;t++){let o=t<e.length&&e[t].slope>=n;if(o&&a<0&&(a=t),o||a<0)continue;let s=e[Math.max(0,a-1)],c=e[Math.min(e.length-1,t)],l=s.surfaceY-c.surfaceY;l>=r&&i.push({x:c.x,z:c.z,lipX:s.x,lipZ:s.z,lipHalfWidth:Math.min((s.halfLeft+s.halfRight)/2,s.halfWidth),lipDirX:s.tx,lipDirZ:s.tz,lipSpeed:s.speed,topY:s.surfaceY,baseY:c.surfaceY,drop:l,halfWidth:(c.halfLeft+c.halfRight)/2,dirX:c.tx,dirZ:c.tz,speed:c.speed}),a=-1}return i}function VA(e,t,n,r,i){let a=i*i,o=a*i;return .5*(2*t+(-e+n)*i+(2*e-5*t+4*n-r)*a+(-e+3*t-3*n+r)*o)}var HA=`
7500
7500
  float riverHash(vec2 p) {
7501
7501
  p = fract(p * vec2(127.31, 311.7));
7502
7502
  p += dot(p, p + 34.23);
@@ -7513,7 +7513,7 @@ float riverNoise(vec2 p) {
7513
7513
  float d = riverHash(i + vec2(1.0, 1.0));
7514
7514
  return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
7515
7515
  }
7516
- `,WA=`
7516
+ `,UA=`
7517
7517
  precision highp float;
7518
7518
 
7519
7519
  #include <fog_pars_vertex>
@@ -7574,7 +7574,7 @@ void main() {
7574
7574
 
7575
7575
  #include <fog_vertex>
7576
7576
  }
7577
- `,GA=`
7577
+ `,WA=`
7578
7578
  precision highp float;
7579
7579
 
7580
7580
  #include <fog_pars_fragment>
@@ -7614,7 +7614,7 @@ varying vec2 vFlowUv;
7614
7614
  varying vec2 vFlow;
7615
7615
  varying vec4 vRiver;
7616
7616
 
7617
- ${UA}
7617
+ ${HA}
7618
7618
 
7619
7619
  /**
7620
7620
  * Ripple field in flow space: (height, d/d-downstream, d/d-across).
@@ -7894,7 +7894,7 @@ void main() {
7894
7894
  #include <colorspace_fragment>
7895
7895
  #include <fog_fragment>
7896
7896
  }
7897
- `,KA=1.25,qA=4,JA=12,YA=1.5,XA=.35,ZA=1.2,QA=8,$A=.5,ej=.35,tj=42,nj=26,rj=6,ij=.05,aj=1.5,oj={shallow:`#74b2a2`,deep:`#123f4b`,sky:`#8ab6d8`,horizon:`#9fb6c2`,bank:`#465447`},sj=`#e9f2ef`,cj=new U,lj={rippleScale:.85,rippleStrength:.09,flowRate:.42,fresnelScale:.95,standingAmp:.11,glideAmp:.025},uj=class e extends Ah{static typeName=`River3D`;static props={path:{default:[]},width:{default:6},widths:{default:[]},depth:{default:.8},flowSpeed:{default:1.6},colors:{default:{}},absorption:{default:.5},opacity:{default:.85},foam:{default:1},ripples:{default:1},sunDirection:{default:[.5,.8,.3]},sunColor:{default:`#fff6e0`},sunIntensity:{default:1},terrain:{default:``,nodePath:!0},carve:{default:!0},flowForce:{default:1},spray:{default:1}};path=[];width=6;widths=[];depth=.8;flowSpeed=1.6;colors={};absorption=.5;opacity=.85;foam=1;ripples=1;sunDirection=[.5,.8,.3];sunColor=`#fff6e0`;sunIntensity=1;terrain=``;carve=!0;flowForce=1;spray=1;renderOrder=1;time=0;rings=[];falls=[];sprayKey=``;courseKey=``;bedAt=null;fitted=!1;bounds=null;boundsKey=``;rocks=[];rockScanAt=-1;world=[0,0,0];_bodies=[];static validateJson(e){let t=e;if(!Array.isArray(t.path))throw new N(`BAD_FORMAT`,`River3D '${e.name}' path must be an array of [x, z] points, got ${JSON.stringify(t.path)}.`,{prop:`path`});if(t.path.length>0&&t.path.length<2)throw new N(`BAD_FORMAT`,`River3D '${e.name}' path needs at least 2 points (source → mouth), got ${t.path.length}.`,{prop:`path`});if(t.path.forEach((t,n)=>{if(!Array.isArray(t)||t.length<2||!Number.isFinite(t[0])||!Number.isFinite(t[1]))throw new N(`BAD_FORMAT`,`River3D '${e.name}' path[${n}] must be [x, z] with finite numbers, got ${JSON.stringify(t)}.`,{prop:`path`})}),!(typeof t.width==`number`&&t.width>0))throw new N(`BAD_FORMAT`,`River3D '${e.name}' width must be a positive number of meters, got ${JSON.stringify(t.width)}.`,{prop:`width`});if(!Array.isArray(t.widths)||t.widths.some(e=>!(typeof e==`number`&&e>0)))throw new N(`BAD_FORMAT`,`River3D '${e.name}' widths must be a list of positive meters (source→mouth), got ${JSON.stringify(t.widths)}.`,{prop:`widths`});if(!(t.depth>0))throw new N(`BAD_FORMAT`,`River3D '${e.name}' depth must be > 0 meters, got ${JSON.stringify(t.depth)}.`,{prop:`depth`});if(!(t.flowSpeed>=0))throw new N(`BAD_FORMAT`,`River3D '${e.name}' flowSpeed must be >= 0 m/s, got ${JSON.stringify(t.flowSpeed)}.`,{prop:`flowSpeed`});for(let n of[`absorption`,`foam`,`ripples`,`flowForce`,`spray`,`sunIntensity`]){let r=t[n];if(!(typeof r==`number`&&r>=0))throw new N(`BAD_FORMAT`,`River3D '${e.name}' ${n} must be a number >= 0, got ${JSON.stringify(r)}.`,{prop:n})}if(!(t.opacity>=0&&t.opacity<=1))throw new N(`BAD_FORMAT`,`River3D '${e.name}' opacity must be within [0, 1], got ${JSON.stringify(t.opacity)}.`,{prop:`opacity`});let n=t.colors;if(typeof n!=`object`||!n||Array.isArray(n))throw new N(`BAD_FORMAT`,`River3D '${e.name}' colors must be an object of { shallow, deep, sky, horizon, bank } hex strings.`,{prop:`colors`});for(let t of Object.keys(n)){if(!(t in oj))throw new N(`BAD_FORMAT`,`River3D '${e.name}' colors has unknown key '${t}' — expected shallow, deep, sky, horizon or bank.`,{prop:`colors`});if(typeof n[t]!=`string`)throw new N(`BAD_FORMAT`,`River3D '${e.name}' colors.${t} must be a hex string, got ${JSON.stringify(n[t])}.`,{prop:`colors`})}}_createObject3D(){return new Ys(new J,this.buildMaterial())}onReady(){this.ensureCourse()}onExitTree(){QD(this,this.terrain)?._setExternalChannel(this,null)}update(e){this.time+=e,this.ensureCourse(),this.syncSpray(),this.flowForce>0&&this.rings.length>1&&this.sweepBodies(e)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();this.rebuildIfNeeded(e),this.syncUniforms(e)}_onRender3D(e){if(this.rings.length===0)return;(this.rockScanAt<0||this.time-this.rockScanAt>$A)&&(this.rockScanAt=this.time,this.scanRocks());let t=this._ensureObject3D().material.uniforms;this.syncRocks(t,e.camera.getWorldPosition(cj))}_waterYAt(e,t){if(this.rings.length===0)return null;let[n,r,i]=this.world,a=e-n,o=t-i,s=this.ringBounds();if(a<s.minX||a>s.maxX||o<s.minZ||o>s.maxZ)return null;let c=RA(this.rings,a,o);return c?.inside?c.surfaceY+r:null}ringBounds(){if(this.boundsKey===this.courseKey&&this.bounds)return this.bounds;let e=1/0,t=-1/0,n=1/0,r=-1/0,i=0;for(let a of this.rings)a.x<e&&(e=a.x),a.x>t&&(t=a.x),a.z<n&&(n=a.z),a.z>r&&(r=a.z),i=Math.max(i,a.halfLeft,a.halfRight);return this.bounds={minX:e-i,maxX:t+i,minZ:n-i,maxZ:r+i},this.boundsKey=this.courseKey,this.bounds}sampleAt(e,t){if(this.ensureCourse(),this.rings.length===0)return null;let[n,r,i]=this.world,a=RA(this.rings,e-n,t-i);return a?{...a,surfaceY:a.surfaceY+r}:null}fallsAt(){this.ensureCourse();let[e,t,n]=this.world;return this.falls.map(r=>({...r,worldX:r.x+e,worldY:r.baseY+t,worldZ:r.z+n}))}_rings(){return this.rings}_applySunDirection(t){let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this._ensureObject3D().material.uniforms?.uSunDirection?.value)?.set(t[0],t[1],t[2])}free(){let e=this._ensureObject3D();e.geometry?.dispose(),e.material?.dispose?.(),super.free()}widthProfile(){return this.widths.length>0?this.widths:[this.width]}applyCarve(e){if(!e)return;if(!this.carve||this.path.length<2){e._setExternalChannel(this,null);return}e._setExternalChannel(this,null);let[t,,n]=ZD(this),[r,,i]=ZD(e),a=e._heightmap();e._setExternalChannel(this,pA({path:this.path.map(e=>[(e[0]??0)+t-r,(e[1]??0)+n-i]),widths:this.widthProfile(),depth:this.depth,cell:(e.size[0]??1)/Math.max(1,a.segsX),groundAt:(e,t)=>a.heightAt(e,t)}))}resolveTerrain(){let e=QD(this,this.terrain);if(!e&&this.terrain!==``)throw new N(`NODE_NOT_FOUND`,`River3D '${this.name}' terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`});return e}ensureCourse(){let e=this.resolveTerrain(),t=ZD(this),n=JSON.stringify([this.path,this.width,this.widths,this.depth,this.flowSpeed,this.carve,e?e.name:``,t]);if(n===this.courseKey)return!1;if(this.courseKey=n,this.world=t,this.bedAt=null,this.applyCarve(e),this.path.length<2)return this.rings=[],this.falls=[],!0;let[r,i,a]=t;this.bedAt=e?(t,n)=>e.heightAt(t+r,n+a)-i:()=>-this.depth,this.fitted=e!==null;let o=this.widthProfile();return this.rings=FA({path:this.path,widths:o,depth:this.depth,flowSpeed:this.flowSpeed,step:PA(o,this.depth),bedAt:this.bedAt,fit:this.fitted}),this.falls=VA(this.rings),this.warnUncoveredWater(),!0}warnUncoveredWater(){if(this.warnedCoverage)return;let e=hA(this.rings);if(e.length*3<this.rings.length)return;this.warnedCoverage=!0;let t=e.reduce((e,t)=>t.wettedHalfWidth-t.carriedHalfWidth>e.wettedHalfWidth-e.carriedHalfWidth?t:e);this.diagnose(`warn`,`[incanto] River3D '${this.name}': the course is too tight for the water it holds — ${e.length} of ${this.rings.length} stations leave bare channel beside the ribbon (worst at ${t.along.toFixed(0)} m: ground wet to ${t.wettedHalfWidth.toFixed(1)} m from the centre, a bend that can only carry ${t.carriedHalfWidth.toFixed(1)} m). Fix by EASING THE BENDS in \`path\` (fewer, straighter points), NARROWING \`widths\` there, or placing standing water (a Water3D) if that reach is really a pool.`)}warnedCoverage=!1;rebuildIfNeeded(e){if(!this.ensureCourse()&&e.geometry.getAttribute(`position`))return;if(this.rings.length===0||!this.bedAt){e.geometry.dispose();let t=new J;t.setAttribute(`position`,new q(new Float32Array,3)),e.geometry=t;return}let t=this.widthProfile(),n=Math.min(...t),r=Math.max(...t),i=IA(this.rings,{acrossSegments:Math.min(JA,Math.max(qA,Math.round(r/YA))),bankOvershoot:this.fitted?1:KA,bedBlur:Math.min(n/2*XA,ZA),bedAt:this.bedAt}),a=new J;a.setAttribute(`position`,new q(i.positions,3)),a.setAttribute(`normal`,new q(i.normals,3)),a.setAttribute(`aFlowUv`,new q(i.uvs,2)),a.setAttribute(`aFlow`,new q(i.flow,2)),a.setAttribute(`aRiver`,new q(i.river,4)),a.setIndex(new q(i.indices,1)),a.computeBoundingSphere(),e.geometry.dispose(),e.geometry=a}buildMaterial(){return new vl({vertexShader:WA,fragmentShader:GA,fog:!0,uniforms:{fogColor:{value:new K(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uShallowColor:{value:new K(oj.shallow)},uDeepColor:{value:new K(oj.deep)},uFoamColor:{value:new K(sj)},uSkyColor:{value:new K(oj.sky)},uHorizonColor:{value:new K(oj.horizon)},uBankColor:{value:new K(oj.bank)},uSunDirection:{value:new U(.5,.8,.3)},uSunColor:{value:new K(this.sunColor)},uSunIntensity:{value:this.sunIntensity},uMaxDepth:{value:this.depth},uAbsorption:{value:this.absorption},uOpacity:{value:this.opacity},uFoam:{value:this.foam},uRippleScale:{value:lj.rippleScale},uRippleStrength:{value:lj.rippleStrength*this.ripples},uFlowRate:{value:lj.flowRate},uSparkle:{value:this.ripples},uRockCount:{value:0},uRocks:{value:Array.from({length:QA},()=>new Ra)},uFresnelScale:{value:lj.fresnelScale},uStandingAmp:{value:lj.standingAmp},uGlideAmp:{value:lj.glideAmp}},transparent:!0,depthTest:!0,depthWrite:!1,side:2})}scanRocks(){let e=[],[t,n,r]=this.world,i=(i,a,o,s,c)=>{if(o<=.02)return;let l=RA(this.rings,i-t,a-r);if(!l?.inside)return;let u=l.surfaceY+n;if(s>u||c<u-this.depth)return;let d=(c-u)/Math.max(this.depth*ej,.02),f=Math.min(Math.max(d+1,0),1);e.push({x:i,z:a,radius:o,breaks:f})},a=this;for(;a.parent;)a=a.parent;let o=e=>{if(e instanceof Fh||e instanceof Ph){let t=e.collider,n=zm(t),[r,a,o]=ZD(e);i(r,o,t?.shape===`box`?Math.max(t.size?.[0]??.4,t.size?.[2]??.4)/2:t?.radius??.35,a-n,a+n)}else if(e instanceof Mw){let[t,n,r]=e.size,[a,o,s]=ZD(e);for(let c of e.transforms){let e=c[4]??1,l=a+(c[0]??0),u=o+(c[1]??0),d=s+(c[2]??0),f=(n??1)*e/2;i(l,d,Math.max(t,r)*e/2,u-f,u+f)}}else if(e instanceof Ow){let[t,n,r]=e.size,[a,o,s]=ZD(e),c=(n??1)/2;i(a,s,Math.max(t,r)/2,o-c,o+c)}for(let t of e.children)o(t)};o(a),this.rocks=e}syncRocks(e,t){let n=e.uRocks?.value,r=e.uRockCount;if(!n||!r)return;if(this.rocks.length===0){r.value=0;return}let i=[...this.rocks].map(e=>({r:e,d:(e.x-t.x)**2+(e.z-t.z)**2})).sort((e,t)=>e.d-t.d).slice(0,QA),a=0;for(let{r:e,d:t}of i){let r=Math.max(e.radius*tj,nj),i=Math.min(Math.sqrt(t)/r,1),o=Math.min(Math.max((i-.6)/.4,0),1),s=1-o*o*(3-2*o);s<=.01||(n[a]?.set(e.x,e.z,e.radius,e.breaks*s),a++)}r.value=a}syncUniforms(e){let t=e.material.uniforms,n=(e,n)=>{let r=t[e];r&&(r.value=n)},r=(e,n)=>{(t[e]?.value)?.set(n)},i=this.colors;n(`uTime`,this.time),r(`uShallowColor`,i.shallow??oj.shallow),r(`uDeepColor`,i.deep??oj.deep),r(`uSkyColor`,i.sky??oj.sky),r(`uHorizonColor`,i.horizon??oj.horizon),r(`uBankColor`,i.bank??oj.bank),r(`uSunColor`,this.sunColor),(t.uSunDirection?.value)?.set(this.sunDirection[0]??.5,this.sunDirection[1]??.8,this.sunDirection[2]??.3),n(`uSunIntensity`,this.sunIntensity),n(`uMaxDepth`,this.depth),n(`uAbsorption`,this.absorption),n(`uOpacity`,this.opacity),n(`uFoam`,this.foam),n(`uRippleStrength`,lj.rippleStrength*this.ripples),n(`uSparkle`,this.ripples)}syncSpray(){let e=this.spray>0?`${this.spray}|${JSON.stringify(this.falls)}`:``;if(e!==this.sprayKey){this.sprayKey=e;for(let e of[...this.children])e.name.startsWith(`__spray`)&&e.free();this.spray<=0||this.falls.forEach((e,t)=>{let n=new eA(`__spray${t}`);n.position=[e.x+e.dirX*.6,e.baseY+.15,e.z+e.dirZ*.6];let r=Math.min(1.6,.4+e.drop*.12)*this.spray;n.rate=Math.round(Math.min(22,5+e.drop*1.6)*this.spray),n.maxParticles=160,n.lifetime=[1,2.1],n.speed=[45*r,130*r],n.directionDeg=-90,n.spreadDeg=52,n.gravity=[0,-240,0],n.drag=1.2,n.sizeStart=7*r,n.sizeEnd=30*r,n.colorStart=`#ffffff`,n.colorEnd=`#dfe9ec`,n.alphaStart=.085,n.alphaEnd=0,n.blend=`normal`,n.depthTest=!0,this.addChild(n)})}}sweepBodies(e){let t=this;for(;t.parent;)t=t.parent;let n=this._bodies;if(n.length=0,dj(t,n),n.length===0)return;let[r,i,a]=this.world;for(let t of n){let n=ZD(t),o=RA(this.rings,n[0]-r,n[2]-a);if(!o?.inside)continue;let s=o.surfaceY+i,c=n[1]-zm(t.collider);if(c>s+ij||c<s-this.depth-aj)continue;let l=fj(t);if(!l)continue;let u=Math.min(1,this.flowForce*rj*e),d=(o.dirX*o.speed-(l[0]??0))*u,f=(o.dirZ*o.speed-(l[2]??0))*u;if(t instanceof Ph){let e=t.mass||1;t.applyImpulse([d*e,0,f*e])}else l[0]=(l[0]??0)+d,l[2]=(l[2]??0)+f}}};function dj(e,t){(e instanceof Fh||e instanceof Ph)&&t.push(e);for(let n of e.children)dj(n,t)}function fj(e){return e.velocity??e.linearVelocity}var pj=128,mj=class extends Ah{static typeName=`Trail3D`;static props={width:{default:.3},color:{default:`#ffffff`},opacity:{default:.8},seconds:{default:.6},emitting:{default:!0},additive:{default:!1},minDistance:{default:.05}};width=.3;color=`#ffffff`;opacity=.8;seconds=.6;emitting=!0;additive=!1;minDistance=.05;points=[];clock=0;mesh=null;lastColor=``;_createObject3D(){let e=new _o,t=new J;t.setAttribute(`position`,new q(new Float32Array(pj*2*3),3));let n=new Ls({color:this.color,transparent:!0,opacity:this.opacity,side:2,depthWrite:!1,blending:this.additive?2:1});return this.mesh=new Ys(t,n),this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrixWorld.identity(),this.mesh.updateMatrixWorld=()=>{},e.add(this.mesh),e}update(e){for(this.clock+=e;this.points.length>0&&this.clock-this.points[0].t>this.seconds;)this.points.shift()}_onRender3D(e){let t=this._ensureObject3D();if(this.emitting){t.getWorldPosition(hj);let e=this.points[this.points.length-1];(!e||(e.x-hj.x)**2+(e.y-hj.y)**2+(e.z-hj.z)**2>this.minDistance*this.minDistance)&&(this.points.push({x:hj.x,y:hj.y,z:hj.z,t:this.clock}),this.points.length>pj&&this.points.shift())}let n=this.mesh;if(!n)return;n.matrixWorld.identity();let r=n.material;this.color!==this.lastColor&&(this.lastColor=this.color,r.color=new K(this.color)),r.opacity=this.opacity;let i=this.points.length,a=n.geometry,o=a.getAttribute(`position`);if(i<2){a.setDrawRange(0,0);return}for(let t=0;t<i;t++){let n=this.points[t],r=this.points[Math.min(t+1,i-1)]??n;gj.set(r.x-n.x,r.y-n.y,r.z-n.z),gj.lengthSq()<1e-8&&gj.set(0,1,0),_j.set(e.camera.position.x-n.x,e.camera.position.y-n.y,e.camera.position.z-n.z),vj.crossVectors(gj,_j).normalize();let a=(this.clock-n.t)/this.seconds,s=this.width/2*Math.max(0,1-a);o.setXYZ(t*2,n.x+vj.x*s,n.y+vj.y*s,n.z+vj.z*s),o.setXYZ(t*2+1,n.x-vj.x*s,n.y-vj.y*s,n.z-vj.z*s)}if(o.needsUpdate=!0,!a.index||a.index.count<(pj-1)*6){let e=[];for(let t=0;t<pj-1;t++){let n=t*2;e.push(n,n+1,n+2,n+1,n+3,n+2)}a.setIndex(e)}a.setDrawRange(0,(i-1)*6)}get pointCount(){return this.points.length}},hj=new U,gj=new U,_j=new U,vj=new U;function yj(e){let{branch:t,leaves:n,type:r}=e,i=0,a=0,o=[{level:0,sections:t.sections[0],segments:t.segments[0]}];for(;o.length>0;){let e=o.shift();if(i+=e.sections*e.segments*2,e.level>=t.levels){a+=n.count===0?0:n.count+ +(r===`deciduous`);continue}r===`deciduous`&&o.push({level:e.level+1,sections:e.sections,segments:e.segments});let s=t.children[e.level]??0;for(let n=0;n<s;n++)o.push({level:e.level+1,sections:t.sections[e.level+1]??1,segments:t.segments[e.level+1]??3})}let s=n.billboard===`double`?2:1,c=a*s*2;return{branches:i,leaves:c,total:i+c}}var bj={ash:{type:`deciduous`,branch:{levels:3,angle:[0,48,75,60],children:[7,4,3,0],force:{direction:{x:0,y:1,z:0},strength:-.06},gnarliness:[.03,.25,.2,.09],length:[43.47,27.14,9.51,4.6],radius:[2,.63,.76,.7],sections:[12,8,6,4],segments:[12,6,4,3],start:[0,.23,.33,0],taper:[.7,.7,.7,.7],twist:[.09,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:16,start:0,size:2.67,sizeVariance:.72,alphaTest:.5}},aspen:{type:`deciduous`,branch:{levels:2,angle:[0,75,32,7],children:[10,3,3,0],force:{direction:{x:0,y:1,z:0},strength:.0148},gnarliness:[.05,.12,.12,.02],length:[50,6.07,11.19,1],radius:[.72,.41,.7,.7],sections:[12,10,8,6],segments:[8,6,4,3],start:[0,.59,.35,0],taper:[.37,.13,.7,.7],twist:[0,0,0,0]},leaves:{style:`aspen`,billboard:`double`,angle:30,count:11,start:.124,size:2.5,sizeVariance:.7,alphaTest:.5}},oak:{type:`deciduous`,branch:{levels:3,angle:[0,54,58,32],children:[6,4,3,0],force:{direction:{x:0,y:1,z:0},strength:-.01},gnarliness:[0,-.1,-.15,.09],length:[37.24,11.08,12.39,7.16],radius:[1.41,.9,.69,1.19],sections:[8,6,3,1],segments:[7,5,3,3],start:[0,.49,.06,.12],taper:[.73,.42,.69,.75],twist:[-.23,.42,0,0]},leaves:{style:`oak`,billboard:`double`,angle:42,count:18,start:.16,size:2.5,sizeVariance:.7,alphaTest:.5}},pine:{type:`evergreen`,branch:{levels:1,angle:[0,110,16,60],children:[82,3,5,0],force:{direction:{x:0,y:1,z:0},strength:-.003},gnarliness:[.05,.08,0,0],length:[50,23.87,14.08,1],radius:[1.05,.36,.7,.7],sections:[12,10,8,6],segments:[8,6,4,3],start:[0,.27,.14,.3],taper:[.7,.7,.7,.7],twist:[0,0,0,0]},leaves:{style:`pine`,billboard:`double`,angle:39,count:30,start:.09,size:1.435,sizeVariance:.201,alphaTest:.3}},bush:{type:`deciduous`,branch:{levels:3,angle:[0,21.5,62.6,60],children:[7,3,2,0],force:{direction:{x:0,y:1,z:0},strength:-.02},gnarliness:[.11,.09,.05,.09],length:[.1,15.3,5.59,4.6],radius:[.58,.95,.76,.7],sections:[6,6,4,3],segments:[4,4,4,3],start:[0,.53,.33,0],taper:[.7,.7,.7,.7],twist:[.3,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:8,start:0,size:2.45,sizeVariance:.717,alphaTest:.5}},"ash-forest":{type:`deciduous`,branch:{levels:2,angle:[0,48,75,60],children:[5,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.06},gnarliness:[.03,.25,.2,.09],length:[43.47,27.14,9.51,4.6],radius:[2,.63,.76,.7],sections:[6,5,4,4],segments:[6,4,3,3],start:[0,.3,.33,0],taper:[.7,.7,.7,.7],twist:[.09,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:15,start:0,size:3,sizeVariance:.6,alphaTest:.5}},"oak-forest":{type:`deciduous`,branch:{levels:2,angle:[0,54,58,32],children:[5,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.01},gnarliness:[0,-.1,-.15,.09],length:[37.24,11.08,12.39,7.16],radius:[1.41,.9,.69,1.19],sections:[6,4,3,1],segments:[6,4,3,3],start:[0,.49,.06,.12],taper:[.73,.42,.69,.75],twist:[-.23,.42,0,0]},leaves:{style:`oak`,billboard:`double`,angle:42,count:16,start:.1,size:2.9,sizeVariance:.7,alphaTest:.5}},"pine-forest":{type:`evergreen`,branch:{levels:1,angle:[0,110,16,60],children:[44,3,5,0],force:{direction:{x:0,y:1,z:0},strength:-.005},gnarliness:[.07,.09,0,0],length:[50,23.87,14.08,1],radius:[1.05,.36,.7,.7],sections:[6,5,8,6],segments:[6,3,4,3],start:[0,.27,.14,.3],taper:[.7,.7,.7,.7],twist:[0,0,0,0]},leaves:{style:`pine`,billboard:`double`,angle:39,count:9,start:.09,size:1.8,sizeVariance:.201,alphaTest:.3}},"bush-forest":{type:`deciduous`,branch:{levels:2,angle:[0,21.5,62.6,60],children:[6,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.02},gnarliness:[.11,.09,.05,.09],length:[.1,15.3,5.59,4.6],radius:[.58,.95,.76,.7],sections:[5,4,3,3],segments:[4,3,3,3],start:[0,.53,.33,0],taper:[.7,.7,.7,.7],twist:[.3,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:10,start:0,size:3.2,sizeVariance:.6,alphaTest:.5}}},xj=[`ash`,`aspen`,`oak`,`pine`,`bush`,`ash-forest`,`oak-forest`,`pine-forest`,`bush-forest`];function Sj(e){let t=bj[e];if(!t)throw new N(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${xj.join(`, `)}].`,{prop:`preset`,validOptions:xj});return structuredClone(t)}var Cj={ash:{texture:`oak`,tint:`#cecbbe`,repeat:[.5,1/5]},aspen:{texture:`birch`,tint:`#ffffff`,repeat:[1,1]},oak:{texture:`oak`,tint:`#fff3d1`,repeat:[1,1/10]},pine:{texture:`pine`,tint:`#ffffff`,repeat:[1,1]},bush:{texture:`oak`,tint:`#cecbbe`,repeat:[.5,1/5]}};function wj(e){if(!xj.includes(e))throw new N(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${xj.join(`, `)}].`,{prop:`preset`,validOptions:xj});return structuredClone(Cj[e.replace(/-forest$/,``)])}var Tj=.45,Ej=.45,Dj=.55,Oj=.15,kj=.07,Aj=.035;function jj(e,t){let n=Math.imul(e+1,374761393)+Math.imul(t+1,668265263)>>>0;return n=Math.imul(n^n>>>13,1274126177)>>>0,((n^n>>>16)>>>0)/4294967296}function Mj(e,t,n){let r=e.length/3,i=new Float32Array(e.length),a=new Float32Array(e.length),o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let t=0;t<r;t++){let n=e[t*3],r=e[t*3+1],i=e[t*3+2];n<o&&(o=n),n>l&&(l=n),r<s&&(s=r),r>u&&(u=r),i<c&&(c=i),i>d&&(d=i)}let f=(o+l)/2,p=(s+u)/2,m=(c+d)/2,h=Math.max((l-o)/2,.001),g=Math.max((u-s)/2,.001),_=Math.max((d-c)/2,.001),v=new Map;for(let n=0;n<r;n++){let r=t[n],i=v.get(r);i||(i={x:0,y:0,z:0,n:0},v.set(r,i)),i.x+=e[n*3],i.y+=e[n*3+1],i.z+=e[n*3+2],i.n++}for(let e of v.values())e.x/=e.n,e.y/=e.n,e.z/=e.n;for(let o=0;o<r;o++){let r=e[o*3],c=e[o*3+1],l=e[o*3+2],d=(r-f)/h,y=(c-p)/g,b=(l-m)/_,x,S,C,w;if(n===`evergreen`){let e=Math.hypot(r-f,l-m);if(e<1e-6)x=0,S=1,C=0;else{let t=1/Math.hypot(1,Ej);x=(r-f)/e*t,S=Ej*t,C=(l-m)/e*t}let t=(c-s)/Math.max(u-s,.001),n=Math.max(Oj,1-t);w=Math.min(1,Math.hypot(d,b)/n)}else{let e=d/h,t=y/g,n=b/_,r=Math.hypot(e,t,n);r<1e-6?(x=0,S=1,C=0):(x=e/r,S=t/r,C=n/r),w=Math.min(1,Math.hypot(d,y,b))}let T=v.get(t[o]);if(T){let e=r-T.x,t=c-T.y,n=l-T.z,i=Math.hypot(e,t,n);if(i>1e-6){x=x*(1-Dj)+e/i*Dj,S=S*(1-Dj)+t/i*Dj,C=C*(1-Dj)+n/i*Dj;let r=Math.hypot(x,S,C);r>1e-6?(x/=r,S/=r,C/=r):(x=0,S=1,C=0)}}i[o*3]=x,i[o*3+1]=S,i[o*3+2]=C;let E=Tj+(1-Tj)*w,D=t[o],O=E*(1-kj*jj(D,1)),k=(jj(D,2)-.5)*2*Aj;a[o*3]=O*(1+k),a[o*3+1]=O,a[o*3+2]=O*(1-k)}return{normals:i,colors:a}}var Nj=class e{static MASK=4294967295;mW;mZ;constructor(t){this.mW=123456789+t&e.MASK,this.mZ=987654321-t&e.MASK}random(t=1,n=0){this.mZ=36969*(this.mZ&65535)+(this.mZ>>16)&e.MASK,this.mW=18e3*(this.mW&65535)+(this.mW>>16)&e.MASK;let r=((this.mZ<<16)+(this.mW&65535)>>>0)/4294967296;return(t-n)*r+n}};function Pj(e,t,n){let r=new Nj(t),i={branchVerts:[],branchNormals:[],branchUvs:[],branchIndices:[],leafVerts:[],leafIndices:[],leafUvs:[],leafAnchors:[],leafClusters:[],leafClusterNext:0},a=[{origin:new U,orientation:new Qa,length:e.branch.length[0],radius:e.branch.radius[0],level:0,sectionCount:e.branch.sections[0],segmentCount:e.branch.segments[0]}];for(;a.length>0;)Fj(e,r,i,a,a.shift());Hj(i,n);let o=new J;o.setAttribute(`position`,new q(new Float32Array(i.branchVerts),3)),o.setAttribute(`normal`,new q(new Float32Array(i.branchNormals),3)),o.setAttribute(`uv`,new q(new Float32Array(i.branchUvs),2)),o.setIndex(new q(Uj(i.branchIndices,i.branchVerts),1)),o.computeBoundingSphere();let s=null;if(i.leafVerts.length>0){s=new J,s.setAttribute(`position`,new q(new Float32Array(i.leafVerts),3)),s.setAttribute(`anchor`,new q(new Float32Array(i.leafAnchors),3)),s.setAttribute(`uv`,new q(new Float32Array(i.leafUvs),2)),s.setIndex(new q(Uj(i.leafIndices,i.leafVerts),1));let t=Mj(i.leafVerts,i.leafClusters,e.type);s.setAttribute(`normal`,new q(t.normals,3)),s.setAttribute(`color`,new q(t.colors,3)),s.computeBoundingSphere()}return{branches:o,leaves:s}}function Fj(e,t,n,r,i){let a=n.branchVerts.length/3,o=i.orientation.clone(),s=i.origin.clone(),c=i.length/i.sectionCount,l=[];for(let r=0;r<=i.sectionCount;r++){let a=i.radius;r===i.sectionCount&&i.level===e.branch.levels?a=.001:e.type===`deciduous`?a*=1-(e.branch.taper[i.level]??0)*(r/i.sectionCount):a*=1-r/i.sectionCount;let u=new U,d=new U,f=0;for(let e=0;e<i.segmentCount;e++){let t=2*Math.PI*e/i.segmentCount,c=new U(Math.cos(t),0,Math.sin(t)).multiplyScalar(a).applyEuler(o).add(s),l=new U(Math.cos(t),0,Math.sin(t)).applyEuler(o).normalize(),p=r%2==0?0:1;n.branchVerts.push(c.x,c.y,c.z),n.branchNormals.push(l.x,l.y,l.z),n.branchUvs.push(e/i.segmentCount,p),e===0&&(u=c,d=l,f=p)}n.branchVerts.push(u.x,u.y,u.z),n.branchNormals.push(d.x,d.y,d.z),n.branchUvs.push(1,f),l.push({origin:s.clone(),orientation:o.clone(),radius:a}),s.add(new U(0,c,0).applyEuler(o));let p=Math.max(1,1/Math.sqrt(a))*(e.branch.gnarliness[i.level]??0);o.x+=t.random(p,-p),o.z+=t.random(p,-p);let m=new H().setFromEuler(o),h=new H().setFromAxisAngle(new U(0,1,0),e.branch.twist[i.level]??0),g=e.branch.force,_=new H().setFromUnitVectors(new U(0,1,0),new U(g.direction.x,g.direction.y,g.direction.z));m.multiply(h),m.rotateTowards(_,g.strength/a),o.setFromQuaternion(m)}Vj(n,a,i);let u=i.level===e.branch.levels?n.leafClusterNext++:0;if(e.type===`deciduous`){let a=l[l.length-1];i.level<e.branch.levels?r.push({origin:a.origin,orientation:a.orientation,length:e.branch.length[i.level+1]??0,radius:a.radius,level:i.level+1,sectionCount:i.sectionCount,segmentCount:i.segmentCount}):e.leaves.count>0&&Bj(e,t,n,a.origin,a.orientation,u)}i.level===e.branch.levels?zj(e,t,n,l,u):i.level<e.branch.levels&&Rj(e,t,r,e.branch.children[i.level]??0,i.level+1,l)}function Ij(e,t){let n=Math.floor(t*(e.length-1)),r=e[n],i=n===e.length-1?r:e[n+1],a=(t-n/(e.length-1))/(1/(e.length-1)),o=new U().lerpVectors(r.origin,i.origin,a),s=new H().setFromEuler(r.orientation),c=new H().setFromEuler(i.orientation);return{origin:o,orientation:new Qa().setFromQuaternion(c.slerp(s,a)),radius:{a:r.radius,b:i.radius,alpha:a}}}function Lj(e,t,n){let r=new H().setFromAxisAngle(new U(1,0,0),t/(180/Math.PI)),i=new H().setFromAxisAngle(new U(0,1,0),n),a=new H().setFromEuler(e);return new Qa().setFromQuaternion(a.multiply(i.multiply(r)))}function Rj(e,t,n,r,i,a){let o=t.random();for(let s=0;s<r;s++){let c=t.random(1,e.branch.start[i]??0),l=Ij(a,c),u=(e.branch.radius[i]??0)*((1-l.radius.alpha)*l.radius.a+l.radius.alpha*l.radius.b),d=2*Math.PI*(o+s/r),f=Lj(l.orientation,e.branch.angle[i]??0,d),p=(e.branch.length[i]??0)*(e.type===`evergreen`?1-c:1);n.push({origin:l.origin,orientation:f,length:p,radius:u,level:i,sectionCount:e.branch.sections[i]??1,segmentCount:e.branch.segments[i]??3})}}function zj(e,t,n,r,i){let a=t.random();for(let o=0;o<e.leaves.count;o++){let s=Ij(r,t.random(1,e.leaves.start)),c=2*Math.PI*(a+o/e.leaves.count),l=Lj(s.orientation,e.leaves.angle,c);Bj(e,t,n,s.origin,l,i)}}function Bj(e,t,n,r,i,a){let o=n.leafVerts.length/3,s=e.leaves.size*(1+t.random(e.leaves.sizeVariance,-e.leaves.sizeVariance)),c=e=>{let t=s/2,c=[new U(-t,s,0),new U(-t,0,0),new U(t,0,0),new U(t,s,0)];for(let t of c)t.applyEuler(new Qa(0,e,0)).applyEuler(i).add(r),n.leafVerts.push(t.x,t.y,t.z),n.leafAnchors.push(r.x,r.y,r.z),n.leafClusters.push(a);n.leafUvs.push(0,1,0,0,1,0,1,1),n.leafIndices.push(o,o+1,o+2,o,o+2,o+3),o+=4};c(0),e.leaves.billboard===`double`&&c(Math.PI/2)}function Vj(e,t,n){let r=n.segmentCount+1;for(let i=0;i<n.sectionCount;i++)for(let a=0;a<n.segmentCount;a++){let n=t+i*r+a,o=t+i*r+(a+1),s=n+r,c=o+r;e.branchIndices.push(n,s,o,o,s,c)}}function Hj(e,t){let n=0;for(let t=1;t<e.branchVerts.length;t+=3){let r=e.branchVerts[t];r>n&&(n=r)}for(let t=1;t<e.leafVerts.length;t+=3){let r=e.leafVerts[t];r>n&&(n=r)}if(n<=0)return;let r=t/n;for(let t=0;t<e.branchVerts.length;t++)e.branchVerts[t]=e.branchVerts[t]*r;for(let t=0;t<e.leafVerts.length;t++)e.leafVerts[t]=e.leafVerts[t]*r;for(let t=0;t<e.leafAnchors.length;t++)e.leafAnchors[t]=e.leafAnchors[t]*r}function Uj(e,t){return t.length/3>65535?new Uint32Array(e):new Uint16Array(e)}var Wj=[`simple`,`medium`,`high`],Gj=[`conifer`,`broadleaf`,`dead`,`bush`];function Kj(e,t,n){return new N(`BAD_FORMAT`,`Tree3D ${e} must be one of [${n.join(`, `)}], got '${t}'.`,{prop:e,validOptions:n})}var qj={simple:0,medium:1,high:2},Jj=[5,7,10],Yj=[2,3,4],Xj=[6,8,12],Zj=[2,3,3],Qj=[0,1,2],$j=[3,4,5],eM=3;function tM(e,t){if(!Wj.includes(e))throw Kj(`tier`,e,Wj);if(!Gj.includes(t))throw Kj(`type`,t,Gj);let n=e,r=t,i=qj[n];return{tier:n,type:r,trunkRadialSegments:Jj[i],canopyLayers:r===`conifer`?Yj[i]:0,canopySegments:Xj[i],blobCount:r===`broadleaf`||r===`bush`?Zj[i]:0,blobDetail:Qj[i],branchCount:r===`dead`?$j[i]:r===`conifer`&&n===`high`?eM:0,hasCanopy:r!==`dead`,canopySway:n!==`simple`}}var nM=.02,rM={conifer:{trunkHeight:.4,trunkRadiusBottom:.05,trunkRadiusTop:.035},broadleaf:{trunkHeight:.42,trunkRadiusBottom:.05,trunkRadiusTop:.032},dead:{trunkHeight:.72,trunkRadiusBottom:.045,trunkRadiusTop:.018},bush:{trunkHeight:.14,trunkRadiusBottom:.045,trunkRadiusTop:.035}};function iM(e,t,n){let{trunkHeight:r,trunkRadiusBottom:i,trunkRadiusTop:a}=rM[e.type],o=[],s=new il(a,i,r,e.trunkRadialSegments).toNonIndexed();if(s.translate(0,r/2,0),o.push(s),e.type===`dead`)for(let n=0;n<e.branchCount;n++){let r=.22+t.next()*.14,a=new il(.006,.02,r,5).toNonIndexed();a.translate(0,r/2,0);let s=.7+t.next()*.6,c=n/e.branchCount*Math.PI*2+t.next()*.8,l=.34+(n+t.next())/e.branchCount*.34;a.applyMatrix4(new G().makeRotationY(c).multiply(new G().makeRotationX(s)).setPosition(Math.sin(c)*i*.6,l,Math.cos(c)*i*.6)),o.push(a)}let c=oM(o);return cM(c,new K(n),.7,1.05,t),c}function aM(e,t,n){if(!e.hasCanopy)return null;let r=[];if(e.type===`conifer`){let n=.74;for(let i=0;i<e.canopyLayers;i++){let a=i/e.canopyLayers,o=.3*(1-a*.62)*(.92+t.next()*.16),s=n/e.canopyLayers*1.7,c=new al(o,s,e.canopySegments).toNonIndexed();sM(c,t,nM),c.translate(0,.26+n*a+s/2,0),r.push(c)}for(let n=0;n<e.branchCount;n++){let i=new al(.06,.2,5).toNonIndexed(),a=n/Math.max(e.branchCount,1)*Math.PI*2+t.next(),o=1.1+t.next()*.4;i.applyMatrix4(new G().makeRotationY(a).multiply(new G().makeRotationX(o)).setPosition(Math.sin(a)*.22,.34+t.next()*.18,Math.cos(a)*.22)),r.push(i)}}else{let{trunkHeight:n}=rM[e.type];for(let i=0;i<e.blobCount;i++){let a=new sl((i===0?.3:.24-i*.02)*(.92+t.next()*.16),e.blobDetail).toNonIndexed();a.scale(1,.72,1),sM(a,t,nM);let o=i===0?0:.13,s=t.next()*Math.PI*2;a.translate(Math.cos(s)*o,n+.16+i*.1+t.next()*.05,Math.sin(s)*o),r.push(a)}}let i=oM(r);return cM(i,new K(n),.62,1.18,t),i}function oM(e){let t=0;for(let n of e)t+=n.getAttribute(`position`).count;let n=new Float32Array(t*3),r=new Float32Array(t*3),i=0;for(let t of e)n.set(t.getAttribute(`position`).array,i),r.set(t.getAttribute(`normal`).array,i),i+=t.getAttribute(`position`).count*3,t.dispose();let a=new J;return a.setAttribute(`position`,new q(n,3)),a.setAttribute(`normal`,new q(r,3)),a}function sM(e,t,n){let r=e.getAttribute(`position`);for(let e=0;e<r.count;e++)r.setXYZ(e,r.getX(e)+t.range(-n,n),r.getY(e)+t.range(-n,n),r.getZ(e)+t.range(-n,n))}function cM(e,t,n,r,i){let a=e.getAttribute(`position`),o=new Float32Array(a.count*3),s=1/0,c=-1/0;for(let e=0;e<a.count;e++){let t=a.getY(e);t<s&&(s=t),t>c&&(c=t)}let l=Math.max(c-s,1e-6),u=new K;for(let e=0;e<a.count;e++){let c=(a.getY(e)-s)/l,d=(n+(r-n)*c)*(.96+i.next()*.08);u.copy(t).multiplyScalar(d),o[e*3]=u.r,o[e*3+1]=u.g,o[e*3+2]=u.b}e.setAttribute(`color`,new q(o,3))}var lM=500,uM=15e5,dM=[.8,1.2],fM=.28,pM=.12,mM=.055,hM=.11,gM=3,_M=101,vM=[.78,.7,.45],yM=.45,bM=.55,xM=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation`,SM=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark`,CM={high:{conifer:[`pine`,`pine`,`pine`],broadleaf:[`oak`,`ash`,`oak`],dead:[`ash`,`ash`,`ash`],bush:[`bush`,`bush`,`bush`]},medium:{conifer:[`pine-forest`,`pine-forest`,`pine-forest`],broadleaf:[`oak-forest`,`ash-forest`,`oak-forest`],dead:[`ash-forest`,`ash-forest`,`ash-forest`],bush:[`bush-forest`,`bush-forest`,`bush-forest`]}},wM=class e extends Ah{static typeName=`Tree3D`;static props={tier:{default:`medium`,options:Wj},type:{default:`conifer`,options:Gj},seed:{default:1},height:{default:6},count:{default:1},area:{default:[10,10]},trunkColor:{default:`#7a5a3a`},canopyColor:{default:`#4a7c3f`},leafTexture:{default:``},leafFadeStart:{default:0},leafFadeEnd:{default:0},leafShadows:{default:!0},drape:{default:null},terrain:{default:``,nodePath:!0}};tier=`medium`;type=`conifer`;seed=1;height=6;count=1;area=[10,10];trunkColor=`#7a5a3a`;canopyColor=`#4a7c3f`;leafTexture=``;leafFadeStart=0;leafFadeEnd=0;leafShadows=!0;drape=null;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(tM(t.tier,t.type),!(t.height>0))throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!Number.isInteger(t.count)||t.count<1||t.count>lM)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' count must be an integer in 1..${lM}, got ${t.count}.`,{prop:`count`});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});if(t.leafFadeEnd!==0&&!(t.leafFadeEnd>t.leafFadeStart&&t.leafFadeStart>=0))throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' needs leafFadeEnd > leafFadeStart >= 0 (the leaf LOD window) or 0/0 to disable, got start ${t.leafFadeStart}, end ${t.leafFadeEnd}.`,{prop:`leafFadeStart`});if(typeof t.leafShadows!=`boolean`)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' leafShadows must be a boolean, got ${JSON.stringify(t.leafShadows)}.`,{prop:`leafShadows`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`});if(t.tier===`simple`)return;let n=DM(t.tier,t.type),r=n*t.count;if(r>uM)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' blows the grove triangle budget: count ${t.count} × ${n} tris/tree (tier '${t.tier}', type '${t.type}') = ${r} > ${uM}. Lower count (max ${Math.floor(uM/n)} at this tier), drop tier to 'medium'/'simple', or split the grove into multiple nodes.`,{prop:`count`})}time=0;grove=null;variants=[];simpleTrunk=null;simpleCanopy=null;swayUniform=null;leafFadeUniform=null;loadedTextures=[];groveKey=``;_createObject3D(){return new _o}_trunk(){return this.rebuildIfNeeded(),this.simpleTrunk??this.variants[0]?.branches}_canopy(){return this.rebuildIfNeeded(),this.simpleTrunk?this.simpleCanopy:this.variants[0]?.leaves??null}_variantMeshes(){return this.rebuildIfNeeded(),this.variants}update(e){this.time+=e,this.swayUniform&&(this.swayUniform.value=this.time),this.leafFadeUniform&&(this.leafFadeUniform.start.value=this.leafFadeStart,this.leafFadeUniform.end.value=this.leafFadeEnd)}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded()}rebuildIfNeeded(){this.grove||(this.grove=new _o,this._ensureObject3D().add(this.grove));let e=JSON.stringify([this.tier,this.type,this.seed,this.height,this.count,this.area,this.trunkColor,this.canopyColor,this.leafTexture,this.leafShadows,this.leafFadeEnd>this.leafFadeStart,this.drape,this.terrain]);e===this.groveKey&&(this.simpleTrunk||this.variants.length>0)||(this.groveKey=e,this.disposeMeshes(),this.resolveDrape(),this.tier===`simple`?this.buildSimpleGrove():this.buildEzGrove())}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=QD(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=ZD(this);else if(this.terrain!==``)throw new N(`NODE_NOT_FOUND`,`Tree3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}buildSimpleGrove(){let e=tM(this.tier,this.type),t=new P(this.seed),n=iM(e,t,this.trunkColor),r=aM(e,t,this.canopyColor),i=new xc(n,NM(),this.count);FM(i);let a=null;r&&(a=new xc(r,NM(),this.count),FM(a)),this.scatter(t,(e,t,n)=>{i.setMatrixAt(e,t),i.setColorAt(e,n),a?.setMatrixAt(e,t),a?.setColorAt(e,n)}),PM(i),a&&PM(a),this.simpleTrunk=i,this.simpleCanopy=a,this.grove.add(i),a&&this.grove.add(a)}buildEzGrove(){let e=CM[this.tier][this.type],t=Math.min(gM,this.count),n=Array.from({length:t},(e,n)=>Math.floor(this.count/t)+ +(n<this.count%t));this.swayUniform={value:this.time},this.leafFadeUniform=this.leafFadeEnd>this.leafFadeStart?{start:{value:this.leafFadeStart},end:{value:this.leafFadeEnd}}:null;let r=AM(this.canopyColor),i=null;typeof document<`u`&&typeof createImageBitmap==`function`&&(i=new wu,i.setOptions({imageOrientation:`flipY`}));for(let a=0;a<t;a++){let t=n[a],o=e[a],s=Sj(o);this.type===`dead`&&(s.leaves.count=0);let c=Pj(s,this.seed+a*_M,1),l=this.buildBarkMaterial(o,i),u=new xc(c.branches,l,t);FM(u);let d=null;if(c.leaves){let e=new bl({color:r.clone().multiply(new K(vM[0],vM[1],vM[2])),roughness:1,side:2,vertexColors:!0,alphaTest:s.leaves.alphaTest}),n=this.leafTexture||OM(s.leaves.style);i&&(e.map=EM(i,n,e=>{e.colorSpace=Oi,e.flipY=!1},e=>kM(e))),UO(e,this.swayUniform,yM,this.leafFadeUniform??void 0),d=new xc(c.leaves,e,t),d.userData.incantoWaterPassSkip=!0,FM(d),this.leafShadows||(d.castShadow=!1)}this.variants.push({branches:u,leaves:d}),this.grove.add(u),d&&this.grove.add(d)}let a=Array(t).fill(0),o=new P(this.seed);this.scatter(o,(e,n,r)=>{let i=e%t,o=this.variants[i],s=a[i];a[i]=s+1,o.branches.setMatrixAt(s,n),o.branches.setColorAt(s,r),o.leaves?.setMatrixAt(s,n),o.leaves?.setColorAt(s,r)});for(let e of this.variants)PM(e.branches),e.leaves&&PM(e.leaves)}buildBarkMaterial(t,n){if(this.type===`dead`||!n)return new bl({color:new K(this.trunkColor),roughness:1});let r=wj(t),i=new bl({color:this.trunkColor===e.props.trunkColor?.default?new K(r.tint):MM(this.trunkColor),roughness:1});return HO(i,bM),i.map=this.loadBarkTexture(n,r,`color`,!0),i.normalMap=this.loadBarkTexture(n,r,`normal`,!1),i.roughnessMap=this.loadBarkTexture(n,r,`roughness`,!1),i}loadBarkTexture(e,t,n,r){return EM(e,`${SM}/${t.texture}_${n}_1k.jpg`,e=>{e.wrapS=er,e.wrapT=er,e.repeat.set(t.repeat[0],t.repeat[1]),e.anisotropy=4,e.flipY=!1,r&&(e.colorSpace=Oi)})}scatter(e,t){let n=(this.area[0]??0)/2,r=(this.area[1]??0)/2;for(let i=0;i<this.count;i++){let a=this.count===1?0:e.range(-n,n),o=this.count===1?0:e.range(-r,r);RM.set(a,this.drape?this.bedY(a,o):0,o),zM.setFromAxisAngle(IM,e.range(0,Math.PI*2));let s=this.height*e.range(dM[0],dM[1]),c=s*e.range(.9,1.1);BM.set(c,s,c),LM.compose(RM,zM,BM),VM.setHSL(fM,pM,.92).offsetHSL(e.range(-.055,mM),0,e.range(-.11,hM)),t(i,LM,VM)}}disposeMeshes(){let e=[this.simpleTrunk,this.simpleCanopy];for(let t of this.variants)e.push(t.branches,t.leaves);let t=new Set;for(let n of e)n&&(n.removeFromParent(),n.geometry.dispose(),t.add(n.material),n.dispose());for(let e of t)e.dispose();for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[],this.simpleTrunk=null,this.simpleCanopy=null,this.variants=[],this.swayUniform=null,this.leafFadeUniform=null}free(){this.disposeMeshes(),this.grove=null,super.free()}},TM=new Map;function EM(e,t,n,r){let i=TM.get(t);if(i)return i;let a=new La;return n(a),e.load(t,e=>{a.image=e,r?r(a):a.needsUpdate=!0}),TM.set(t,a),a}function DM(e,t){let n=0;for(let r of new Set(CM[e][t]??[])){let e=Sj(r);t===`dead`&&(e.leaves.count=0),n=Math.max(n,yj(e).total)}return n}function OM(e){return`${xM}/${e}_color.png`}function kM(e){let t=e.image;if(!t||typeof document>`u`)return;let n=document.createElement(`canvas`);n.width=t.naturalWidth||t.width,n.height=t.naturalHeight||t.height;let r=n.getContext(`2d`,{willReadFrequently:!0});if(!r)return;r.drawImage(t,0,0);let i;try{i=r.getImageData(0,0,n.width,n.height)}catch{return}let a=i.data,o=0,s=0,c=0,l=0;for(let e=0;e<a.length;e+=4)a[e+3]>240&&(o+=a[e],s+=a[e+1],c+=a[e+2],l++);if(l!==0){o=Math.round(o/l),s=Math.round(s/l),c=Math.round(c/l);for(let e=0;e<a.length;e+=4)a[e+3]<=240&&(a[e]=o,a[e+1]=s,a[e+2]=c);r.putImageData(i,0,0),e.image=n,e.needsUpdate=!0}}function AM(e){let t=new K(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t.lerp(jM,.18)}var jM=new K(1,1,1);function MM(e){let t=new K(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t}function NM(){return new bl({vertexColors:!0,roughness:1,flatShading:!0})}function PM(e){e.instanceMatrix.needsUpdate=!0,e.instanceColor&&(e.instanceColor.needsUpdate=!0),XD(e)}function FM(e){e.castShadow=!0,e.receiveShadow=!0}var IM=new U(0,1,0),LM=new G,RM=new U,zM=new H,BM=new U,VM=new K,HM=[[[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4]],[[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[0,.8,0],[.6,.3,0]],[[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0]],[[.6,.55,.5],[.55,.5,.45],[.5,.45,.4],[.55,.5,.45],[.65,.6,.55],[.5,.45,.4]],[[.45,.45,.4],[.4,.4,.35],[.35,.35,.3],[.4,.4,.35],[.5,.5,.45],[.35,.35,.3]],[[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2]],[[.8,.5,.2],[.75,.45,.15],[.7,.4,.1],[.75,.45,.15],[.85,.55,.25],[.7,.4,.1]],[[0,.7,.1],[0,.65,.1],[0,.6,.1],[0,.65,.1],[0,.75,.1],[0,.6,.1]],[[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3]],[[0,0,.7],[0,0,.7],[0,0,.7],[0,0,.7],[0,.2,.9],[0,0,.6]],[[.9,.3,0],[.9,.3,0],[.9,.3,0],[.9,.3,0],[1,.4,0],[.7,.2,0]],[[.9,.8,.2],[.85,.75,.18],[.85,.75,.18],[.85,.75,.18],[.95,.85,.25],[.85,.75,.18]],[[.6,.6,.6],[.55,.55,.55],[.5,.5,.5],[.55,.55,.55],[.65,.65,.65],[.5,.5,.5]],[[.7,.7,.4],[.65,.65,.35],[.6,.6,.3],[.65,.65,.35],[.75,.75,.45],[.6,.6,.3]],[[.7,.5,.5],[.65,.45,.45],[.6,.4,.4],[.65,.45,.45],[.75,.55,.55],[.6,.4,.4]],[[.35,.3,.25],[.3,.25,.2],[.25,.2,.15],[.3,.25,.2],[.4,.35,.3],[.25,.2,.15]],[[.5,.3,0],[.5,.3,0],[.5,.3,0],[.5,.3,0],[.7,.4,.1],[.7,.4,.1]],[[0,.5,0],[0,.45,0],[0,.45,0],[0,.45,0],[0,.6,0],[0,.4,0]],[[.2,.8,.8],[.15,.7,.7],[.1,.6,.6],[.15,.7,.7],[.3,.9,.9],[.1,.6,.6]],[[1,.5,.8],[.9,.4,.7],[.8,.3,.6],[.9,.4,.7],[1,.6,.9],[.8,.3,.6]],[[1,.9,.3],[.95,.85,.25],[.9,.8,.2],[.95,.85,.25],[1,1,.4],[.9,.8,.2]],[[1,0,0],[.9,0,0],[.8,0,0],[.9,0,0],[1,.2,.2],[.8,0,0]],[[.6,.4,.2],[.5,.3,.15],[.4,.25,.1],[.5,.3,.15],[.7,.45,.25],[.4,.25,.1]],[[.6,.2,.8],[.5,.15,.7],[.4,.1,.6],[.5,.15,.7],[.7,.25,.9],[.4,.1,.6]],[[1,.8,0],[.95,.75,0],[.95,.75,0],[.95,.75,0],[1,.9,0],[.9,.7,0]],[[.6,.65,.7],[.55,.6,.65],[.5,.55,.6],[.55,.6,.65],[.65,.7,.75],[.5,.55,.6]]],UM=2e5,WM=class extends Ah{static typeName=`VoxelGrid3D`;static signals=[`blocksChanged`];static props={voxels:{default:[]}};voxels=[];appliedVoxels=null;map=new Map;mesh=null;dirty=!1;blockCount(){return this.map.size}tileAt(e,t,n){return this.map.get(`${e},${t},${n}`)}setBlocks(e){this.map.clear();for(let t of e)this.map.set(`${t.x},${t.y},${t.z}`,t.tile);this.dirty=!0,this.emit(`blocksChanged`)}addBlock(e){this.map.set(`${e.x},${e.y},${e.z}`,e.tile),this.dirty=!0,this.emit(`blocksChanged`)}removeBlockAt(e,t,n){let r=this.map.delete(`${e},${t},${n}`);return r&&(this.dirty=!0,this.emit(`blocksChanged`)),r}blocks(){let e=[];for(let[t,n]of this.map){let[r,i,a]=t.split(`,`).map(Number);e.push({x:r,y:i,z:a,tile:n})}return e}_createObject3D(){let e=new nl(1,1,1),t=new vl({vertexShader:KM,fragmentShader:qM});this.mesh=new xc(e,t,UM),this.mesh.count=0,this.mesh.frustumCulled=!1;for(let e of GM)this.mesh.geometry.setAttribute(e,new pc(new Float32Array(UM*3),3));return this.dirty=!0,this.mesh}update(){if(this.voxels.length>0&&this.voxels!==this.appliedVoxels&&(this.appliedVoxels=this.voxels,this.setBlocks(this.voxels.map(e=>({x:e[0]??0,y:e[1]??0,z:e[2]??0,tile:e[3]??0})))),!this.dirty||!this.mesh)return;this.dirty=!1;let e=new G,t=0;for(let[n,r]of this.map){if(t>=UM)break;let[i,a,o]=n.split(`,`).map(Number);e.setPosition(i,a,o),this.mesh.setMatrixAt(t,e);let s=HM[r]??HM[0];for(let e=0;e<6;e++){let n=this.mesh.geometry.getAttribute(GM[e]),r=s[e];n.setXYZ(t,r[0],r[1],r[2]),n.needsUpdate=!0}t++}this.mesh.count=t,this.mesh.instanceMatrix.needsUpdate=!0}},GM=[`colorFront`,`colorRight`,`colorBack`,`colorLeft`,`colorTop`,`colorBottom`],KM=`
7897
+ `,GA=1.25,KA=4,qA=12,JA=1.5,YA=.35,XA=1.2,ZA=8,QA=.5,$A=.35,ej=42,tj=26,nj=6,rj=.05,ij=1.5,aj={shallow:`#74b2a2`,deep:`#123f4b`,sky:`#8ab6d8`,horizon:`#9fb6c2`,bank:`#465447`},oj=`#e9f2ef`,sj=new U,cj={rippleScale:.85,rippleStrength:.09,flowRate:.42,fresnelScale:.95,standingAmp:.11,glideAmp:.025},lj=class e extends Ah{static typeName=`River3D`;static props={path:{default:[]},width:{default:6},widths:{default:[]},depth:{default:.8},flowSpeed:{default:1.6},colors:{default:{}},absorption:{default:.5},opacity:{default:.85},foam:{default:1},ripples:{default:1},sunDirection:{default:[.5,.8,.3]},sunColor:{default:`#fff6e0`},sunIntensity:{default:1},terrain:{default:``,nodePath:!0},carve:{default:!0},flowForce:{default:1},spray:{default:1}};path=[];width=6;widths=[];depth=.8;flowSpeed=1.6;colors={};absorption=.5;opacity=.85;foam=1;ripples=1;sunDirection=[.5,.8,.3];sunColor=`#fff6e0`;sunIntensity=1;terrain=``;carve=!0;flowForce=1;spray=1;renderOrder=1;time=0;rings=[];falls=[];sprayKey=``;courseKey=``;bedAt=null;fitted=!1;bounds=null;boundsKey=``;rocks=[];rockScanAt=-1;world=[0,0,0];_bodies=[];static validateJson(e){let t=e;if(!Array.isArray(t.path))throw new N(`BAD_FORMAT`,`River3D '${e.name}' path must be an array of [x, z] points, got ${JSON.stringify(t.path)}.`,{prop:`path`});if(t.path.length>0&&t.path.length<2)throw new N(`BAD_FORMAT`,`River3D '${e.name}' path needs at least 2 points (source → mouth), got ${t.path.length}.`,{prop:`path`});if(t.path.forEach((t,n)=>{if(!Array.isArray(t)||t.length<2||!Number.isFinite(t[0])||!Number.isFinite(t[1]))throw new N(`BAD_FORMAT`,`River3D '${e.name}' path[${n}] must be [x, z] with finite numbers, got ${JSON.stringify(t)}.`,{prop:`path`})}),!(typeof t.width==`number`&&t.width>0))throw new N(`BAD_FORMAT`,`River3D '${e.name}' width must be a positive number of meters, got ${JSON.stringify(t.width)}.`,{prop:`width`});if(!Array.isArray(t.widths)||t.widths.some(e=>!(typeof e==`number`&&e>0)))throw new N(`BAD_FORMAT`,`River3D '${e.name}' widths must be a list of positive meters (source→mouth), got ${JSON.stringify(t.widths)}.`,{prop:`widths`});if(!(t.depth>0))throw new N(`BAD_FORMAT`,`River3D '${e.name}' depth must be > 0 meters, got ${JSON.stringify(t.depth)}.`,{prop:`depth`});if(!(t.flowSpeed>=0))throw new N(`BAD_FORMAT`,`River3D '${e.name}' flowSpeed must be >= 0 m/s, got ${JSON.stringify(t.flowSpeed)}.`,{prop:`flowSpeed`});for(let n of[`absorption`,`foam`,`ripples`,`flowForce`,`spray`,`sunIntensity`]){let r=t[n];if(!(typeof r==`number`&&r>=0))throw new N(`BAD_FORMAT`,`River3D '${e.name}' ${n} must be a number >= 0, got ${JSON.stringify(r)}.`,{prop:n})}if(!(t.opacity>=0&&t.opacity<=1))throw new N(`BAD_FORMAT`,`River3D '${e.name}' opacity must be within [0, 1], got ${JSON.stringify(t.opacity)}.`,{prop:`opacity`});let n=t.colors;if(typeof n!=`object`||!n||Array.isArray(n))throw new N(`BAD_FORMAT`,`River3D '${e.name}' colors must be an object of { shallow, deep, sky, horizon, bank } hex strings.`,{prop:`colors`});for(let t of Object.keys(n)){if(!(t in aj))throw new N(`BAD_FORMAT`,`River3D '${e.name}' colors has unknown key '${t}' — expected shallow, deep, sky, horizon or bank.`,{prop:`colors`});if(typeof n[t]!=`string`)throw new N(`BAD_FORMAT`,`River3D '${e.name}' colors.${t} must be a hex string, got ${JSON.stringify(n[t])}.`,{prop:`colors`})}}_createObject3D(){return new Ys(new J,this.buildMaterial())}onReady(){this.ensureCourse()}onExitTree(){ZD(this,this.terrain)?._setExternalChannel(this,null)}update(e){this.time+=e,this.ensureCourse(),this.syncSpray(),this.flowForce>0&&this.rings.length>1&&this.sweepBodies(e)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();this.rebuildIfNeeded(e),this.syncUniforms(e)}_onRender3D(e){if(this.rings.length===0)return;(this.rockScanAt<0||this.time-this.rockScanAt>QA)&&(this.rockScanAt=this.time,this.scanRocks());let t=this._ensureObject3D().material.uniforms;this.syncRocks(t,e.camera.getWorldPosition(sj))}_waterYAt(e,t){if(this.rings.length===0)return null;let[n,r,i]=this.world,a=e-n,o=t-i,s=this.ringBounds();if(a<s.minX||a>s.maxX||o<s.minZ||o>s.maxZ)return null;let c=LA(this.rings,a,o);return c?.inside?c.surfaceY+r:null}ringBounds(){if(this.boundsKey===this.courseKey&&this.bounds)return this.bounds;let e=1/0,t=-1/0,n=1/0,r=-1/0,i=0;for(let a of this.rings)a.x<e&&(e=a.x),a.x>t&&(t=a.x),a.z<n&&(n=a.z),a.z>r&&(r=a.z),i=Math.max(i,a.halfLeft,a.halfRight);return this.bounds={minX:e-i,maxX:t+i,minZ:n-i,maxZ:r+i},this.boundsKey=this.courseKey,this.bounds}sampleAt(e,t){if(this.ensureCourse(),this.rings.length===0)return null;let[n,r,i]=this.world,a=LA(this.rings,e-n,t-i);return a?{...a,surfaceY:a.surfaceY+r}:null}fallsAt(){this.ensureCourse();let[e,t,n]=this.world;return this.falls.map(r=>({...r,worldX:r.x+e,worldY:r.baseY+t,worldZ:r.z+n}))}_rings(){return this.rings}_applySunDirection(t){let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this._ensureObject3D().material.uniforms?.uSunDirection?.value)?.set(t[0],t[1],t[2])}free(){let e=this._ensureObject3D();e.geometry?.dispose(),e.material?.dispose?.(),super.free()}widthProfile(){return this.widths.length>0?this.widths:[this.width]}applyCarve(e){if(!e)return;if(!this.carve||this.path.length<2){e._setExternalChannel(this,null);return}e._setExternalChannel(this,null);let[t,,n]=XD(this),[r,,i]=XD(e),a=e._heightmap();e._setExternalChannel(this,fA({path:this.path.map(e=>[(e[0]??0)+t-r,(e[1]??0)+n-i]),widths:this.widthProfile(),depth:this.depth,cell:(e.size[0]??1)/Math.max(1,a.segsX),groundAt:(e,t)=>a.heightAt(e,t)}))}resolveTerrain(){let e=ZD(this,this.terrain);if(!e&&this.terrain!==``)throw new N(`NODE_NOT_FOUND`,`River3D '${this.name}' terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`});return e}ensureCourse(){let e=this.resolveTerrain(),t=XD(this),n=JSON.stringify([this.path,this.width,this.widths,this.depth,this.flowSpeed,this.carve,e?e.name:``,t]);if(n===this.courseKey)return!1;if(this.courseKey=n,this.world=t,this.bedAt=null,this.applyCarve(e),this.path.length<2)return this.rings=[],this.falls=[],!0;let[r,i,a]=t;this.bedAt=e?(t,n)=>e.heightAt(t+r,n+a)-i:()=>-this.depth,this.fitted=e!==null;let o=this.widthProfile();return this.rings=PA({path:this.path,widths:o,depth:this.depth,flowSpeed:this.flowSpeed,step:NA(o,this.depth),bedAt:this.bedAt,fit:this.fitted}),this.falls=BA(this.rings),this.warnUncoveredWater(),!0}warnUncoveredWater(){if(this.warnedCoverage)return;let e=mA(this.rings);if(e.length*3<this.rings.length)return;this.warnedCoverage=!0;let t=e.reduce((e,t)=>t.wettedHalfWidth-t.carriedHalfWidth>e.wettedHalfWidth-e.carriedHalfWidth?t:e);this.diagnose(`warn`,`[incanto] River3D '${this.name}': the course is too tight for the water it holds — ${e.length} of ${this.rings.length} stations leave bare channel beside the ribbon (worst at ${t.along.toFixed(0)} m: ground wet to ${t.wettedHalfWidth.toFixed(1)} m from the centre, a bend that can only carry ${t.carriedHalfWidth.toFixed(1)} m). Fix by EASING THE BENDS in \`path\` (fewer, straighter points), NARROWING \`widths\` there, or placing standing water (a Water3D) if that reach is really a pool.`)}warnedCoverage=!1;rebuildIfNeeded(e){if(!this.ensureCourse()&&e.geometry.getAttribute(`position`))return;if(this.rings.length===0||!this.bedAt){e.geometry.dispose();let t=new J;t.setAttribute(`position`,new q(new Float32Array,3)),e.geometry=t;return}let t=this.widthProfile(),n=Math.min(...t),r=Math.max(...t),i=FA(this.rings,{acrossSegments:Math.min(qA,Math.max(KA,Math.round(r/JA))),bankOvershoot:this.fitted?1:GA,bedBlur:Math.min(n/2*YA,XA),bedAt:this.bedAt}),a=new J;a.setAttribute(`position`,new q(i.positions,3)),a.setAttribute(`normal`,new q(i.normals,3)),a.setAttribute(`aFlowUv`,new q(i.uvs,2)),a.setAttribute(`aFlow`,new q(i.flow,2)),a.setAttribute(`aRiver`,new q(i.river,4)),a.setIndex(new q(i.indices,1)),a.computeBoundingSphere(),e.geometry.dispose(),e.geometry=a}buildMaterial(){return new vl({vertexShader:UA,fragmentShader:WA,fog:!0,uniforms:{fogColor:{value:new K(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uShallowColor:{value:new K(aj.shallow)},uDeepColor:{value:new K(aj.deep)},uFoamColor:{value:new K(oj)},uSkyColor:{value:new K(aj.sky)},uHorizonColor:{value:new K(aj.horizon)},uBankColor:{value:new K(aj.bank)},uSunDirection:{value:new U(.5,.8,.3)},uSunColor:{value:new K(this.sunColor)},uSunIntensity:{value:this.sunIntensity},uMaxDepth:{value:this.depth},uAbsorption:{value:this.absorption},uOpacity:{value:this.opacity},uFoam:{value:this.foam},uRippleScale:{value:cj.rippleScale},uRippleStrength:{value:cj.rippleStrength*this.ripples},uFlowRate:{value:cj.flowRate},uSparkle:{value:this.ripples},uRockCount:{value:0},uRocks:{value:Array.from({length:ZA},()=>new Ra)},uFresnelScale:{value:cj.fresnelScale},uStandingAmp:{value:cj.standingAmp},uGlideAmp:{value:cj.glideAmp}},transparent:!0,depthTest:!0,depthWrite:!1,side:2})}scanRocks(){let e=[],[t,n,r]=this.world,i=(i,a,o,s,c)=>{if(o<=.02)return;let l=LA(this.rings,i-t,a-r);if(!l?.inside)return;let u=l.surfaceY+n;if(s>u||c<u-this.depth)return;let d=(c-u)/Math.max(this.depth*$A,.02),f=Math.min(Math.max(d+1,0),1);e.push({x:i,z:a,radius:o,breaks:f})},a=this;for(;a.parent;)a=a.parent;let o=e=>{if(e instanceof Fh||e instanceof Ph){let t=e.collider,n=zm(t),[r,a,o]=XD(e);i(r,o,t?.shape===`box`?Math.max(t.size?.[0]??.4,t.size?.[2]??.4)/2:t?.radius??.35,a-n,a+n)}else if(e instanceof Mw){let[t,n,r]=e.size,[a,o,s]=XD(e);for(let c of e.transforms){let e=c[4]??1,l=a+(c[0]??0),u=o+(c[1]??0),d=s+(c[2]??0),f=(n??1)*e/2;i(l,d,Math.max(t,r)*e/2,u-f,u+f)}}else if(e instanceof Ow){let[t,n,r]=e.size,[a,o,s]=XD(e),c=(n??1)/2;i(a,s,Math.max(t,r)/2,o-c,o+c)}for(let t of e.children)o(t)};o(a),this.rocks=e}syncRocks(e,t){let n=e.uRocks?.value,r=e.uRockCount;if(!n||!r)return;if(this.rocks.length===0){r.value=0;return}let i=[...this.rocks].map(e=>({r:e,d:(e.x-t.x)**2+(e.z-t.z)**2})).sort((e,t)=>e.d-t.d).slice(0,ZA),a=0;for(let{r:e,d:t}of i){let r=Math.max(e.radius*ej,tj),i=Math.min(Math.sqrt(t)/r,1),o=Math.min(Math.max((i-.6)/.4,0),1),s=1-o*o*(3-2*o);s<=.01||(n[a]?.set(e.x,e.z,e.radius,e.breaks*s),a++)}r.value=a}syncUniforms(e){let t=e.material.uniforms,n=(e,n)=>{let r=t[e];r&&(r.value=n)},r=(e,n)=>{(t[e]?.value)?.set(n)},i=this.colors;n(`uTime`,this.time),r(`uShallowColor`,i.shallow??aj.shallow),r(`uDeepColor`,i.deep??aj.deep),r(`uSkyColor`,i.sky??aj.sky),r(`uHorizonColor`,i.horizon??aj.horizon),r(`uBankColor`,i.bank??aj.bank),r(`uSunColor`,this.sunColor),(t.uSunDirection?.value)?.set(this.sunDirection[0]??.5,this.sunDirection[1]??.8,this.sunDirection[2]??.3),n(`uSunIntensity`,this.sunIntensity),n(`uMaxDepth`,this.depth),n(`uAbsorption`,this.absorption),n(`uOpacity`,this.opacity),n(`uFoam`,this.foam),n(`uRippleStrength`,cj.rippleStrength*this.ripples),n(`uSparkle`,this.ripples)}syncSpray(){let e=this.spray>0?`${this.spray}|${JSON.stringify(this.falls)}`:``;if(e!==this.sprayKey){this.sprayKey=e;for(let e of[...this.children])e.name.startsWith(`__spray`)&&e.free();this.spray<=0||this.falls.forEach((e,t)=>{let n=new $k(`__spray${t}`);n.position=[e.x+e.dirX*.6,e.baseY+.15,e.z+e.dirZ*.6];let r=Math.min(1.6,.4+e.drop*.12)*this.spray;n.rate=Math.round(Math.min(22,5+e.drop*1.6)*this.spray),n.maxParticles=160,n.lifetime=[1,2.1],n.speed=[45*r,130*r],n.directionDeg=-90,n.spreadDeg=52,n.gravity=[0,-240,0],n.drag=1.2,n.sizeStart=7*r,n.sizeEnd=30*r,n.colorStart=`#ffffff`,n.colorEnd=`#dfe9ec`,n.alphaStart=.085,n.alphaEnd=0,n.blend=`normal`,n.depthTest=!0,this.addChild(n)})}}sweepBodies(e){let t=this;for(;t.parent;)t=t.parent;let n=this._bodies;if(n.length=0,uj(t,n),n.length===0)return;let[r,i,a]=this.world;for(let t of n){let n=XD(t),o=LA(this.rings,n[0]-r,n[2]-a);if(!o?.inside)continue;let s=o.surfaceY+i,c=n[1]-zm(t.collider);if(c>s+rj||c<s-this.depth-ij)continue;let l=dj(t);if(!l)continue;let u=Math.min(1,this.flowForce*nj*e),d=(o.dirX*o.speed-(l[0]??0))*u,f=(o.dirZ*o.speed-(l[2]??0))*u;if(t instanceof Ph){let e=t.mass||1;t.applyImpulse([d*e,0,f*e])}else l[0]=(l[0]??0)+d,l[2]=(l[2]??0)+f}}};function uj(e,t){(e instanceof Fh||e instanceof Ph)&&t.push(e);for(let n of e.children)uj(n,t)}function dj(e){return e.velocity??e.linearVelocity}var fj=128,pj=class extends Ah{static typeName=`Trail3D`;static props={width:{default:.3},color:{default:`#ffffff`},opacity:{default:.8},seconds:{default:.6},emitting:{default:!0},additive:{default:!1},minDistance:{default:.05}};width=.3;color=`#ffffff`;opacity=.8;seconds=.6;emitting=!0;additive=!1;minDistance=.05;points=[];clock=0;mesh=null;lastColor=``;_createObject3D(){let e=new _o,t=new J;t.setAttribute(`position`,new q(new Float32Array(fj*2*3),3));let n=new Ls({color:this.color,transparent:!0,opacity:this.opacity,side:2,depthWrite:!1,blending:this.additive?2:1});return this.mesh=new Ys(t,n),this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrixWorld.identity(),this.mesh.updateMatrixWorld=()=>{},e.add(this.mesh),e}update(e){for(this.clock+=e;this.points.length>0&&this.clock-this.points[0].t>this.seconds;)this.points.shift()}_onRender3D(e){let t=this._ensureObject3D();if(this.emitting){t.getWorldPosition(mj);let e=this.points[this.points.length-1];(!e||(e.x-mj.x)**2+(e.y-mj.y)**2+(e.z-mj.z)**2>this.minDistance*this.minDistance)&&(this.points.push({x:mj.x,y:mj.y,z:mj.z,t:this.clock}),this.points.length>fj&&this.points.shift())}let n=this.mesh;if(!n)return;n.matrixWorld.identity();let r=n.material;this.color!==this.lastColor&&(this.lastColor=this.color,r.color=new K(this.color)),r.opacity=this.opacity;let i=this.points.length,a=n.geometry,o=a.getAttribute(`position`);if(i<2){a.setDrawRange(0,0);return}for(let t=0;t<i;t++){let n=this.points[t],r=this.points[Math.min(t+1,i-1)]??n;hj.set(r.x-n.x,r.y-n.y,r.z-n.z),hj.lengthSq()<1e-8&&hj.set(0,1,0),gj.set(e.camera.position.x-n.x,e.camera.position.y-n.y,e.camera.position.z-n.z),_j.crossVectors(hj,gj).normalize();let a=(this.clock-n.t)/this.seconds,s=this.width/2*Math.max(0,1-a);o.setXYZ(t*2,n.x+_j.x*s,n.y+_j.y*s,n.z+_j.z*s),o.setXYZ(t*2+1,n.x-_j.x*s,n.y-_j.y*s,n.z-_j.z*s)}if(o.needsUpdate=!0,!a.index||a.index.count<(fj-1)*6){let e=[];for(let t=0;t<fj-1;t++){let n=t*2;e.push(n,n+1,n+2,n+1,n+3,n+2)}a.setIndex(e)}a.setDrawRange(0,(i-1)*6)}get pointCount(){return this.points.length}},mj=new U,hj=new U,gj=new U,_j=new U;function vj(e){let{branch:t,leaves:n,type:r}=e,i=0,a=0,o=[{level:0,sections:t.sections[0],segments:t.segments[0]}];for(;o.length>0;){let e=o.shift();if(i+=e.sections*e.segments*2,e.level>=t.levels){a+=n.count===0?0:n.count+ +(r===`deciduous`);continue}r===`deciduous`&&o.push({level:e.level+1,sections:e.sections,segments:e.segments});let s=t.children[e.level]??0;for(let n=0;n<s;n++)o.push({level:e.level+1,sections:t.sections[e.level+1]??1,segments:t.segments[e.level+1]??3})}let s=n.billboard===`double`?2:1,c=a*s*2;return{branches:i,leaves:c,total:i+c}}var yj={ash:{type:`deciduous`,branch:{levels:3,angle:[0,48,75,60],children:[7,4,3,0],force:{direction:{x:0,y:1,z:0},strength:-.06},gnarliness:[.03,.25,.2,.09],length:[43.47,27.14,9.51,4.6],radius:[2,.63,.76,.7],sections:[12,8,6,4],segments:[12,6,4,3],start:[0,.23,.33,0],taper:[.7,.7,.7,.7],twist:[.09,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:16,start:0,size:2.67,sizeVariance:.72,alphaTest:.5}},aspen:{type:`deciduous`,branch:{levels:2,angle:[0,75,32,7],children:[10,3,3,0],force:{direction:{x:0,y:1,z:0},strength:.0148},gnarliness:[.05,.12,.12,.02],length:[50,6.07,11.19,1],radius:[.72,.41,.7,.7],sections:[12,10,8,6],segments:[8,6,4,3],start:[0,.59,.35,0],taper:[.37,.13,.7,.7],twist:[0,0,0,0]},leaves:{style:`aspen`,billboard:`double`,angle:30,count:11,start:.124,size:2.5,sizeVariance:.7,alphaTest:.5}},oak:{type:`deciduous`,branch:{levels:3,angle:[0,54,58,32],children:[6,4,3,0],force:{direction:{x:0,y:1,z:0},strength:-.01},gnarliness:[0,-.1,-.15,.09],length:[37.24,11.08,12.39,7.16],radius:[1.41,.9,.69,1.19],sections:[8,6,3,1],segments:[7,5,3,3],start:[0,.49,.06,.12],taper:[.73,.42,.69,.75],twist:[-.23,.42,0,0]},leaves:{style:`oak`,billboard:`double`,angle:42,count:18,start:.16,size:2.5,sizeVariance:.7,alphaTest:.5}},pine:{type:`evergreen`,branch:{levels:1,angle:[0,110,16,60],children:[82,3,5,0],force:{direction:{x:0,y:1,z:0},strength:-.003},gnarliness:[.05,.08,0,0],length:[50,23.87,14.08,1],radius:[1.05,.36,.7,.7],sections:[12,10,8,6],segments:[8,6,4,3],start:[0,.27,.14,.3],taper:[.7,.7,.7,.7],twist:[0,0,0,0]},leaves:{style:`pine`,billboard:`double`,angle:39,count:30,start:.09,size:1.435,sizeVariance:.201,alphaTest:.3}},bush:{type:`deciduous`,branch:{levels:3,angle:[0,21.5,62.6,60],children:[7,3,2,0],force:{direction:{x:0,y:1,z:0},strength:-.02},gnarliness:[.11,.09,.05,.09],length:[.1,15.3,5.59,4.6],radius:[.58,.95,.76,.7],sections:[6,6,4,3],segments:[4,4,4,3],start:[0,.53,.33,0],taper:[.7,.7,.7,.7],twist:[.3,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:8,start:0,size:2.45,sizeVariance:.717,alphaTest:.5}},"ash-forest":{type:`deciduous`,branch:{levels:2,angle:[0,48,75,60],children:[5,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.06},gnarliness:[.03,.25,.2,.09],length:[43.47,27.14,9.51,4.6],radius:[2,.63,.76,.7],sections:[6,5,4,4],segments:[6,4,3,3],start:[0,.3,.33,0],taper:[.7,.7,.7,.7],twist:[.09,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:15,start:0,size:3,sizeVariance:.6,alphaTest:.5}},"oak-forest":{type:`deciduous`,branch:{levels:2,angle:[0,54,58,32],children:[5,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.01},gnarliness:[0,-.1,-.15,.09],length:[37.24,11.08,12.39,7.16],radius:[1.41,.9,.69,1.19],sections:[6,4,3,1],segments:[6,4,3,3],start:[0,.49,.06,.12],taper:[.73,.42,.69,.75],twist:[-.23,.42,0,0]},leaves:{style:`oak`,billboard:`double`,angle:42,count:16,start:.1,size:2.9,sizeVariance:.7,alphaTest:.5}},"pine-forest":{type:`evergreen`,branch:{levels:1,angle:[0,110,16,60],children:[44,3,5,0],force:{direction:{x:0,y:1,z:0},strength:-.005},gnarliness:[.07,.09,0,0],length:[50,23.87,14.08,1],radius:[1.05,.36,.7,.7],sections:[6,5,8,6],segments:[6,3,4,3],start:[0,.27,.14,.3],taper:[.7,.7,.7,.7],twist:[0,0,0,0]},leaves:{style:`pine`,billboard:`double`,angle:39,count:9,start:.09,size:1.8,sizeVariance:.201,alphaTest:.3}},"bush-forest":{type:`deciduous`,branch:{levels:2,angle:[0,21.5,62.6,60],children:[6,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.02},gnarliness:[.11,.09,.05,.09],length:[.1,15.3,5.59,4.6],radius:[.58,.95,.76,.7],sections:[5,4,3,3],segments:[4,3,3,3],start:[0,.53,.33,0],taper:[.7,.7,.7,.7],twist:[.3,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:10,start:0,size:3.2,sizeVariance:.6,alphaTest:.5}}},bj=[`ash`,`aspen`,`oak`,`pine`,`bush`,`ash-forest`,`oak-forest`,`pine-forest`,`bush-forest`];function xj(e){let t=yj[e];if(!t)throw new N(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${bj.join(`, `)}].`,{prop:`preset`,validOptions:bj});return structuredClone(t)}var Sj={ash:{texture:`oak`,tint:`#cecbbe`,repeat:[.5,1/5]},aspen:{texture:`birch`,tint:`#ffffff`,repeat:[1,1]},oak:{texture:`oak`,tint:`#fff3d1`,repeat:[1,1/10]},pine:{texture:`pine`,tint:`#ffffff`,repeat:[1,1]},bush:{texture:`oak`,tint:`#cecbbe`,repeat:[.5,1/5]}};function Cj(e){if(!bj.includes(e))throw new N(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${bj.join(`, `)}].`,{prop:`preset`,validOptions:bj});return structuredClone(Sj[e.replace(/-forest$/,``)])}var wj=.45,Tj=.45,Ej=.55,Dj=.15,Oj=.07,kj=.035;function Aj(e,t){let n=Math.imul(e+1,374761393)+Math.imul(t+1,668265263)>>>0;return n=Math.imul(n^n>>>13,1274126177)>>>0,((n^n>>>16)>>>0)/4294967296}function jj(e,t,n){let r=e.length/3,i=new Float32Array(e.length),a=new Float32Array(e.length),o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let t=0;t<r;t++){let n=e[t*3],r=e[t*3+1],i=e[t*3+2];n<o&&(o=n),n>l&&(l=n),r<s&&(s=r),r>u&&(u=r),i<c&&(c=i),i>d&&(d=i)}let f=(o+l)/2,p=(s+u)/2,m=(c+d)/2,h=Math.max((l-o)/2,.001),g=Math.max((u-s)/2,.001),_=Math.max((d-c)/2,.001),v=new Map;for(let n=0;n<r;n++){let r=t[n],i=v.get(r);i||(i={x:0,y:0,z:0,n:0},v.set(r,i)),i.x+=e[n*3],i.y+=e[n*3+1],i.z+=e[n*3+2],i.n++}for(let e of v.values())e.x/=e.n,e.y/=e.n,e.z/=e.n;for(let o=0;o<r;o++){let r=e[o*3],c=e[o*3+1],l=e[o*3+2],d=(r-f)/h,y=(c-p)/g,b=(l-m)/_,x,S,C,w;if(n===`evergreen`){let e=Math.hypot(r-f,l-m);if(e<1e-6)x=0,S=1,C=0;else{let t=1/Math.hypot(1,Tj);x=(r-f)/e*t,S=Tj*t,C=(l-m)/e*t}let t=(c-s)/Math.max(u-s,.001),n=Math.max(Dj,1-t);w=Math.min(1,Math.hypot(d,b)/n)}else{let e=d/h,t=y/g,n=b/_,r=Math.hypot(e,t,n);r<1e-6?(x=0,S=1,C=0):(x=e/r,S=t/r,C=n/r),w=Math.min(1,Math.hypot(d,y,b))}let T=v.get(t[o]);if(T){let e=r-T.x,t=c-T.y,n=l-T.z,i=Math.hypot(e,t,n);if(i>1e-6){x=x*(1-Ej)+e/i*Ej,S=S*(1-Ej)+t/i*Ej,C=C*(1-Ej)+n/i*Ej;let r=Math.hypot(x,S,C);r>1e-6?(x/=r,S/=r,C/=r):(x=0,S=1,C=0)}}i[o*3]=x,i[o*3+1]=S,i[o*3+2]=C;let E=wj+(1-wj)*w,D=t[o],O=E*(1-Oj*Aj(D,1)),k=(Aj(D,2)-.5)*2*kj;a[o*3]=O*(1+k),a[o*3+1]=O,a[o*3+2]=O*(1-k)}return{normals:i,colors:a}}var Mj=class e{static MASK=4294967295;mW;mZ;constructor(t){this.mW=123456789+t&e.MASK,this.mZ=987654321-t&e.MASK}random(t=1,n=0){this.mZ=36969*(this.mZ&65535)+(this.mZ>>16)&e.MASK,this.mW=18e3*(this.mW&65535)+(this.mW>>16)&e.MASK;let r=((this.mZ<<16)+(this.mW&65535)>>>0)/4294967296;return(t-n)*r+n}};function Nj(e,t,n){let r=new Mj(t),i={branchVerts:[],branchNormals:[],branchUvs:[],branchIndices:[],leafVerts:[],leafIndices:[],leafUvs:[],leafAnchors:[],leafClusters:[],leafClusterNext:0},a=[{origin:new U,orientation:new Qa,length:e.branch.length[0],radius:e.branch.radius[0],level:0,sectionCount:e.branch.sections[0],segmentCount:e.branch.segments[0]}];for(;a.length>0;)Pj(e,r,i,a,a.shift());Vj(i,n);let o=new J;o.setAttribute(`position`,new q(new Float32Array(i.branchVerts),3)),o.setAttribute(`normal`,new q(new Float32Array(i.branchNormals),3)),o.setAttribute(`uv`,new q(new Float32Array(i.branchUvs),2)),o.setIndex(new q(Hj(i.branchIndices,i.branchVerts),1)),o.computeBoundingSphere();let s=null;if(i.leafVerts.length>0){s=new J,s.setAttribute(`position`,new q(new Float32Array(i.leafVerts),3)),s.setAttribute(`anchor`,new q(new Float32Array(i.leafAnchors),3)),s.setAttribute(`uv`,new q(new Float32Array(i.leafUvs),2)),s.setIndex(new q(Hj(i.leafIndices,i.leafVerts),1));let t=jj(i.leafVerts,i.leafClusters,e.type);s.setAttribute(`normal`,new q(t.normals,3)),s.setAttribute(`color`,new q(t.colors,3)),s.computeBoundingSphere()}return{branches:o,leaves:s}}function Pj(e,t,n,r,i){let a=n.branchVerts.length/3,o=i.orientation.clone(),s=i.origin.clone(),c=i.length/i.sectionCount,l=[];for(let r=0;r<=i.sectionCount;r++){let a=i.radius;r===i.sectionCount&&i.level===e.branch.levels?a=.001:e.type===`deciduous`?a*=1-(e.branch.taper[i.level]??0)*(r/i.sectionCount):a*=1-r/i.sectionCount;let u=new U,d=new U,f=0;for(let e=0;e<i.segmentCount;e++){let t=2*Math.PI*e/i.segmentCount,c=new U(Math.cos(t),0,Math.sin(t)).multiplyScalar(a).applyEuler(o).add(s),l=new U(Math.cos(t),0,Math.sin(t)).applyEuler(o).normalize(),p=r%2==0?0:1;n.branchVerts.push(c.x,c.y,c.z),n.branchNormals.push(l.x,l.y,l.z),n.branchUvs.push(e/i.segmentCount,p),e===0&&(u=c,d=l,f=p)}n.branchVerts.push(u.x,u.y,u.z),n.branchNormals.push(d.x,d.y,d.z),n.branchUvs.push(1,f),l.push({origin:s.clone(),orientation:o.clone(),radius:a}),s.add(new U(0,c,0).applyEuler(o));let p=Math.max(1,1/Math.sqrt(a))*(e.branch.gnarliness[i.level]??0);o.x+=t.random(p,-p),o.z+=t.random(p,-p);let m=new H().setFromEuler(o),h=new H().setFromAxisAngle(new U(0,1,0),e.branch.twist[i.level]??0),g=e.branch.force,_=new H().setFromUnitVectors(new U(0,1,0),new U(g.direction.x,g.direction.y,g.direction.z));m.multiply(h),m.rotateTowards(_,g.strength/a),o.setFromQuaternion(m)}Bj(n,a,i);let u=i.level===e.branch.levels?n.leafClusterNext++:0;if(e.type===`deciduous`){let a=l[l.length-1];i.level<e.branch.levels?r.push({origin:a.origin,orientation:a.orientation,length:e.branch.length[i.level+1]??0,radius:a.radius,level:i.level+1,sectionCount:i.sectionCount,segmentCount:i.segmentCount}):e.leaves.count>0&&zj(e,t,n,a.origin,a.orientation,u)}i.level===e.branch.levels?Rj(e,t,n,l,u):i.level<e.branch.levels&&Lj(e,t,r,e.branch.children[i.level]??0,i.level+1,l)}function Fj(e,t){let n=Math.floor(t*(e.length-1)),r=e[n],i=n===e.length-1?r:e[n+1],a=(t-n/(e.length-1))/(1/(e.length-1)),o=new U().lerpVectors(r.origin,i.origin,a),s=new H().setFromEuler(r.orientation),c=new H().setFromEuler(i.orientation);return{origin:o,orientation:new Qa().setFromQuaternion(c.slerp(s,a)),radius:{a:r.radius,b:i.radius,alpha:a}}}function Ij(e,t,n){let r=new H().setFromAxisAngle(new U(1,0,0),t/(180/Math.PI)),i=new H().setFromAxisAngle(new U(0,1,0),n),a=new H().setFromEuler(e);return new Qa().setFromQuaternion(a.multiply(i.multiply(r)))}function Lj(e,t,n,r,i,a){let o=t.random();for(let s=0;s<r;s++){let c=t.random(1,e.branch.start[i]??0),l=Fj(a,c),u=(e.branch.radius[i]??0)*((1-l.radius.alpha)*l.radius.a+l.radius.alpha*l.radius.b),d=2*Math.PI*(o+s/r),f=Ij(l.orientation,e.branch.angle[i]??0,d),p=(e.branch.length[i]??0)*(e.type===`evergreen`?1-c:1);n.push({origin:l.origin,orientation:f,length:p,radius:u,level:i,sectionCount:e.branch.sections[i]??1,segmentCount:e.branch.segments[i]??3})}}function Rj(e,t,n,r,i){let a=t.random();for(let o=0;o<e.leaves.count;o++){let s=Fj(r,t.random(1,e.leaves.start)),c=2*Math.PI*(a+o/e.leaves.count),l=Ij(s.orientation,e.leaves.angle,c);zj(e,t,n,s.origin,l,i)}}function zj(e,t,n,r,i,a){let o=n.leafVerts.length/3,s=e.leaves.size*(1+t.random(e.leaves.sizeVariance,-e.leaves.sizeVariance)),c=e=>{let t=s/2,c=[new U(-t,s,0),new U(-t,0,0),new U(t,0,0),new U(t,s,0)];for(let t of c)t.applyEuler(new Qa(0,e,0)).applyEuler(i).add(r),n.leafVerts.push(t.x,t.y,t.z),n.leafAnchors.push(r.x,r.y,r.z),n.leafClusters.push(a);n.leafUvs.push(0,1,0,0,1,0,1,1),n.leafIndices.push(o,o+1,o+2,o,o+2,o+3),o+=4};c(0),e.leaves.billboard===`double`&&c(Math.PI/2)}function Bj(e,t,n){let r=n.segmentCount+1;for(let i=0;i<n.sectionCount;i++)for(let a=0;a<n.segmentCount;a++){let n=t+i*r+a,o=t+i*r+(a+1),s=n+r,c=o+r;e.branchIndices.push(n,s,o,o,s,c)}}function Vj(e,t){let n=0;for(let t=1;t<e.branchVerts.length;t+=3){let r=e.branchVerts[t];r>n&&(n=r)}for(let t=1;t<e.leafVerts.length;t+=3){let r=e.leafVerts[t];r>n&&(n=r)}if(n<=0)return;let r=t/n;for(let t=0;t<e.branchVerts.length;t++)e.branchVerts[t]=e.branchVerts[t]*r;for(let t=0;t<e.leafVerts.length;t++)e.leafVerts[t]=e.leafVerts[t]*r;for(let t=0;t<e.leafAnchors.length;t++)e.leafAnchors[t]=e.leafAnchors[t]*r}function Hj(e,t){return t.length/3>65535?new Uint32Array(e):new Uint16Array(e)}var Uj=[`simple`,`medium`,`high`],Wj=[`conifer`,`broadleaf`,`dead`,`bush`];function Gj(e,t,n){return new N(`BAD_FORMAT`,`Tree3D ${e} must be one of [${n.join(`, `)}], got '${t}'.`,{prop:e,validOptions:n})}var Kj={simple:0,medium:1,high:2},qj=[5,7,10],Jj=[2,3,4],Yj=[6,8,12],Xj=[2,3,3],Zj=[0,1,2],Qj=[3,4,5],$j=3;function eM(e,t){if(!Uj.includes(e))throw Gj(`tier`,e,Uj);if(!Wj.includes(t))throw Gj(`type`,t,Wj);let n=e,r=t,i=Kj[n];return{tier:n,type:r,trunkRadialSegments:qj[i],canopyLayers:r===`conifer`?Jj[i]:0,canopySegments:Yj[i],blobCount:r===`broadleaf`||r===`bush`?Xj[i]:0,blobDetail:Zj[i],branchCount:r===`dead`?Qj[i]:r===`conifer`&&n===`high`?$j:0,hasCanopy:r!==`dead`,canopySway:n!==`simple`}}var tM=.02,nM={conifer:{trunkHeight:.4,trunkRadiusBottom:.05,trunkRadiusTop:.035},broadleaf:{trunkHeight:.42,trunkRadiusBottom:.05,trunkRadiusTop:.032},dead:{trunkHeight:.72,trunkRadiusBottom:.045,trunkRadiusTop:.018},bush:{trunkHeight:.14,trunkRadiusBottom:.045,trunkRadiusTop:.035}};function rM(e,t,n){let{trunkHeight:r,trunkRadiusBottom:i,trunkRadiusTop:a}=nM[e.type],o=[],s=new il(a,i,r,e.trunkRadialSegments).toNonIndexed();if(s.translate(0,r/2,0),o.push(s),e.type===`dead`)for(let n=0;n<e.branchCount;n++){let r=.22+t.next()*.14,a=new il(.006,.02,r,5).toNonIndexed();a.translate(0,r/2,0);let s=.7+t.next()*.6,c=n/e.branchCount*Math.PI*2+t.next()*.8,l=.34+(n+t.next())/e.branchCount*.34;a.applyMatrix4(new G().makeRotationY(c).multiply(new G().makeRotationX(s)).setPosition(Math.sin(c)*i*.6,l,Math.cos(c)*i*.6)),o.push(a)}let c=aM(o);return sM(c,new K(n),.7,1.05,t),c}function iM(e,t,n){if(!e.hasCanopy)return null;let r=[];if(e.type===`conifer`){let n=.74;for(let i=0;i<e.canopyLayers;i++){let a=i/e.canopyLayers,o=.3*(1-a*.62)*(.92+t.next()*.16),s=n/e.canopyLayers*1.7,c=new al(o,s,e.canopySegments).toNonIndexed();oM(c,t,tM),c.translate(0,.26+n*a+s/2,0),r.push(c)}for(let n=0;n<e.branchCount;n++){let i=new al(.06,.2,5).toNonIndexed(),a=n/Math.max(e.branchCount,1)*Math.PI*2+t.next(),o=1.1+t.next()*.4;i.applyMatrix4(new G().makeRotationY(a).multiply(new G().makeRotationX(o)).setPosition(Math.sin(a)*.22,.34+t.next()*.18,Math.cos(a)*.22)),r.push(i)}}else{let{trunkHeight:n}=nM[e.type];for(let i=0;i<e.blobCount;i++){let a=new sl((i===0?.3:.24-i*.02)*(.92+t.next()*.16),e.blobDetail).toNonIndexed();a.scale(1,.72,1),oM(a,t,tM);let o=i===0?0:.13,s=t.next()*Math.PI*2;a.translate(Math.cos(s)*o,n+.16+i*.1+t.next()*.05,Math.sin(s)*o),r.push(a)}}let i=aM(r);return sM(i,new K(n),.62,1.18,t),i}function aM(e){let t=0;for(let n of e)t+=n.getAttribute(`position`).count;let n=new Float32Array(t*3),r=new Float32Array(t*3),i=0;for(let t of e)n.set(t.getAttribute(`position`).array,i),r.set(t.getAttribute(`normal`).array,i),i+=t.getAttribute(`position`).count*3,t.dispose();let a=new J;return a.setAttribute(`position`,new q(n,3)),a.setAttribute(`normal`,new q(r,3)),a}function oM(e,t,n){let r=e.getAttribute(`position`);for(let e=0;e<r.count;e++)r.setXYZ(e,r.getX(e)+t.range(-n,n),r.getY(e)+t.range(-n,n),r.getZ(e)+t.range(-n,n))}function sM(e,t,n,r,i){let a=e.getAttribute(`position`),o=new Float32Array(a.count*3),s=1/0,c=-1/0;for(let e=0;e<a.count;e++){let t=a.getY(e);t<s&&(s=t),t>c&&(c=t)}let l=Math.max(c-s,1e-6),u=new K;for(let e=0;e<a.count;e++){let c=(a.getY(e)-s)/l,d=(n+(r-n)*c)*(.96+i.next()*.08);u.copy(t).multiplyScalar(d),o[e*3]=u.r,o[e*3+1]=u.g,o[e*3+2]=u.b}e.setAttribute(`color`,new q(o,3))}var cM=500,lM=15e5,uM=[.8,1.2],dM=.28,fM=.12,pM=.055,mM=.11,hM=3,gM=101,_M=[.78,.7,.45],vM=.45,yM=.55,bM=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation`,xM=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark`,SM={high:{conifer:[`pine`,`pine`,`pine`],broadleaf:[`oak`,`ash`,`oak`],dead:[`ash`,`ash`,`ash`],bush:[`bush`,`bush`,`bush`]},medium:{conifer:[`pine-forest`,`pine-forest`,`pine-forest`],broadleaf:[`oak-forest`,`ash-forest`,`oak-forest`],dead:[`ash-forest`,`ash-forest`,`ash-forest`],bush:[`bush-forest`,`bush-forest`,`bush-forest`]}},CM=class e extends Ah{static typeName=`Tree3D`;static props={tier:{default:`medium`,options:Uj},type:{default:`conifer`,options:Wj},seed:{default:1},height:{default:6},count:{default:1},area:{default:[10,10]},trunkColor:{default:`#7a5a3a`},canopyColor:{default:`#4a7c3f`},leafTexture:{default:``},leafFadeStart:{default:0},leafFadeEnd:{default:0},leafShadows:{default:!0},drape:{default:null},terrain:{default:``,nodePath:!0}};tier=`medium`;type=`conifer`;seed=1;height=6;count=1;area=[10,10];trunkColor=`#7a5a3a`;canopyColor=`#4a7c3f`;leafTexture=``;leafFadeStart=0;leafFadeEnd=0;leafShadows=!0;drape=null;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(eM(t.tier,t.type),!(t.height>0))throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!Number.isInteger(t.count)||t.count<1||t.count>cM)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' count must be an integer in 1..${cM}, got ${t.count}.`,{prop:`count`});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});if(t.leafFadeEnd!==0&&!(t.leafFadeEnd>t.leafFadeStart&&t.leafFadeStart>=0))throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' needs leafFadeEnd > leafFadeStart >= 0 (the leaf LOD window) or 0/0 to disable, got start ${t.leafFadeStart}, end ${t.leafFadeEnd}.`,{prop:`leafFadeStart`});if(typeof t.leafShadows!=`boolean`)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' leafShadows must be a boolean, got ${JSON.stringify(t.leafShadows)}.`,{prop:`leafShadows`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`});if(t.tier===`simple`)return;let n=EM(t.tier,t.type),r=n*t.count;if(r>lM)throw new N(`BAD_FORMAT`,`Tree3D '${e.name}' blows the grove triangle budget: count ${t.count} × ${n} tris/tree (tier '${t.tier}', type '${t.type}') = ${r} > ${lM}. Lower count (max ${Math.floor(lM/n)} at this tier), drop tier to 'medium'/'simple', or split the grove into multiple nodes.`,{prop:`count`})}time=0;grove=null;variants=[];simpleTrunk=null;simpleCanopy=null;swayUniform=null;leafFadeUniform=null;loadedTextures=[];groveKey=``;_createObject3D(){return new _o}_trunk(){return this.rebuildIfNeeded(),this.simpleTrunk??this.variants[0]?.branches}_canopy(){return this.rebuildIfNeeded(),this.simpleTrunk?this.simpleCanopy:this.variants[0]?.leaves??null}_variantMeshes(){return this.rebuildIfNeeded(),this.variants}update(e){this.time+=e,this.swayUniform&&(this.swayUniform.value=this.time),this.leafFadeUniform&&(this.leafFadeUniform.start.value=this.leafFadeStart,this.leafFadeUniform.end.value=this.leafFadeEnd)}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded()}rebuildIfNeeded(){this.grove||(this.grove=new _o,this._ensureObject3D().add(this.grove));let e=JSON.stringify([this.tier,this.type,this.seed,this.height,this.count,this.area,this.trunkColor,this.canopyColor,this.leafTexture,this.leafShadows,this.leafFadeEnd>this.leafFadeStart,this.drape,this.terrain]);e===this.groveKey&&(this.simpleTrunk||this.variants.length>0)||(this.groveKey=e,this.disposeMeshes(),this.resolveDrape(),this.tier===`simple`?this.buildSimpleGrove():this.buildEzGrove())}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=ZD(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=XD(this);else if(this.terrain!==``)throw new N(`NODE_NOT_FOUND`,`Tree3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}buildSimpleGrove(){let e=eM(this.tier,this.type),t=new P(this.seed),n=rM(e,t,this.trunkColor),r=iM(e,t,this.canopyColor),i=new xc(n,MM(),this.count);PM(i);let a=null;r&&(a=new xc(r,MM(),this.count),PM(a)),this.scatter(t,(e,t,n)=>{i.setMatrixAt(e,t),i.setColorAt(e,n),a?.setMatrixAt(e,t),a?.setColorAt(e,n)}),NM(i),a&&NM(a),this.simpleTrunk=i,this.simpleCanopy=a,this.grove.add(i),a&&this.grove.add(a)}buildEzGrove(){let e=SM[this.tier][this.type],t=Math.min(hM,this.count),n=Array.from({length:t},(e,n)=>Math.floor(this.count/t)+ +(n<this.count%t));this.swayUniform={value:this.time},this.leafFadeUniform=this.leafFadeEnd>this.leafFadeStart?{start:{value:this.leafFadeStart},end:{value:this.leafFadeEnd}}:null;let r=kM(this.canopyColor),i=null;typeof document<`u`&&typeof createImageBitmap==`function`&&(i=new wu,i.setOptions({imageOrientation:`flipY`}));for(let a=0;a<t;a++){let t=n[a],o=e[a],s=xj(o);this.type===`dead`&&(s.leaves.count=0);let c=Nj(s,this.seed+a*gM,1),l=this.buildBarkMaterial(o,i),u=new xc(c.branches,l,t);PM(u);let d=null;if(c.leaves){let e=new bl({color:r.clone().multiply(new K(_M[0],_M[1],_M[2])),roughness:1,side:2,vertexColors:!0,alphaTest:s.leaves.alphaTest}),n=this.leafTexture||DM(s.leaves.style);i&&(e.map=TM(i,n,e=>{e.colorSpace=Oi,e.flipY=!1},e=>OM(e))),HO(e,this.swayUniform,vM,this.leafFadeUniform??void 0),d=new xc(c.leaves,e,t),d.userData.incantoWaterPassSkip=!0,PM(d),this.leafShadows||(d.castShadow=!1)}this.variants.push({branches:u,leaves:d}),this.grove.add(u),d&&this.grove.add(d)}let a=Array(t).fill(0),o=new P(this.seed);this.scatter(o,(e,n,r)=>{let i=e%t,o=this.variants[i],s=a[i];a[i]=s+1,o.branches.setMatrixAt(s,n),o.branches.setColorAt(s,r),o.leaves?.setMatrixAt(s,n),o.leaves?.setColorAt(s,r)});for(let e of this.variants)NM(e.branches),e.leaves&&NM(e.leaves)}buildBarkMaterial(t,n){if(this.type===`dead`||!n)return new bl({color:new K(this.trunkColor),roughness:1});let r=Cj(t),i=new bl({color:this.trunkColor===e.props.trunkColor?.default?new K(r.tint):jM(this.trunkColor),roughness:1});return VO(i,yM),i.map=this.loadBarkTexture(n,r,`color`,!0),i.normalMap=this.loadBarkTexture(n,r,`normal`,!1),i.roughnessMap=this.loadBarkTexture(n,r,`roughness`,!1),i}loadBarkTexture(e,t,n,r){return TM(e,`${xM}/${t.texture}_${n}_1k.jpg`,e=>{e.wrapS=er,e.wrapT=er,e.repeat.set(t.repeat[0],t.repeat[1]),e.anisotropy=4,e.flipY=!1,r&&(e.colorSpace=Oi)})}scatter(e,t){let n=(this.area[0]??0)/2,r=(this.area[1]??0)/2;for(let i=0;i<this.count;i++){let a=this.count===1?0:e.range(-n,n),o=this.count===1?0:e.range(-r,r);LM.set(a,this.drape?this.bedY(a,o):0,o),RM.setFromAxisAngle(FM,e.range(0,Math.PI*2));let s=this.height*e.range(uM[0],uM[1]),c=s*e.range(.9,1.1);zM.set(c,s,c),IM.compose(LM,RM,zM),BM.setHSL(dM,fM,.92).offsetHSL(e.range(-.055,pM),0,e.range(-.11,mM)),t(i,IM,BM)}}disposeMeshes(){let e=[this.simpleTrunk,this.simpleCanopy];for(let t of this.variants)e.push(t.branches,t.leaves);let t=new Set;for(let n of e)n&&(n.removeFromParent(),n.geometry.dispose(),t.add(n.material),n.dispose());for(let e of t)e.dispose();for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[],this.simpleTrunk=null,this.simpleCanopy=null,this.variants=[],this.swayUniform=null,this.leafFadeUniform=null}free(){this.disposeMeshes(),this.grove=null,super.free()}},wM=new Map;function TM(e,t,n,r){let i=wM.get(t);if(i)return i;let a=new La;return n(a),e.load(t,e=>{a.image=e,r?r(a):a.needsUpdate=!0}),wM.set(t,a),a}function EM(e,t){let n=0;for(let r of new Set(SM[e][t]??[])){let e=xj(r);t===`dead`&&(e.leaves.count=0),n=Math.max(n,vj(e).total)}return n}function DM(e){return`${bM}/${e}_color.png`}function OM(e){let t=e.image;if(!t||typeof document>`u`)return;let n=document.createElement(`canvas`);n.width=t.naturalWidth||t.width,n.height=t.naturalHeight||t.height;let r=n.getContext(`2d`,{willReadFrequently:!0});if(!r)return;r.drawImage(t,0,0);let i;try{i=r.getImageData(0,0,n.width,n.height)}catch{return}let a=i.data,o=0,s=0,c=0,l=0;for(let e=0;e<a.length;e+=4)a[e+3]>240&&(o+=a[e],s+=a[e+1],c+=a[e+2],l++);if(l!==0){o=Math.round(o/l),s=Math.round(s/l),c=Math.round(c/l);for(let e=0;e<a.length;e+=4)a[e+3]<=240&&(a[e]=o,a[e+1]=s,a[e+2]=c);r.putImageData(i,0,0),e.image=n,e.needsUpdate=!0}}function kM(e){let t=new K(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t.lerp(AM,.18)}var AM=new K(1,1,1);function jM(e){let t=new K(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t}function MM(){return new bl({vertexColors:!0,roughness:1,flatShading:!0})}function NM(e){e.instanceMatrix.needsUpdate=!0,e.instanceColor&&(e.instanceColor.needsUpdate=!0),YD(e)}function PM(e){e.castShadow=!0,e.receiveShadow=!0}var FM=new U(0,1,0),IM=new G,LM=new U,RM=new H,zM=new U,BM=new K,VM=[[[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4]],[[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[0,.8,0],[.6,.3,0]],[[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0]],[[.6,.55,.5],[.55,.5,.45],[.5,.45,.4],[.55,.5,.45],[.65,.6,.55],[.5,.45,.4]],[[.45,.45,.4],[.4,.4,.35],[.35,.35,.3],[.4,.4,.35],[.5,.5,.45],[.35,.35,.3]],[[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2]],[[.8,.5,.2],[.75,.45,.15],[.7,.4,.1],[.75,.45,.15],[.85,.55,.25],[.7,.4,.1]],[[0,.7,.1],[0,.65,.1],[0,.6,.1],[0,.65,.1],[0,.75,.1],[0,.6,.1]],[[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3]],[[0,0,.7],[0,0,.7],[0,0,.7],[0,0,.7],[0,.2,.9],[0,0,.6]],[[.9,.3,0],[.9,.3,0],[.9,.3,0],[.9,.3,0],[1,.4,0],[.7,.2,0]],[[.9,.8,.2],[.85,.75,.18],[.85,.75,.18],[.85,.75,.18],[.95,.85,.25],[.85,.75,.18]],[[.6,.6,.6],[.55,.55,.55],[.5,.5,.5],[.55,.55,.55],[.65,.65,.65],[.5,.5,.5]],[[.7,.7,.4],[.65,.65,.35],[.6,.6,.3],[.65,.65,.35],[.75,.75,.45],[.6,.6,.3]],[[.7,.5,.5],[.65,.45,.45],[.6,.4,.4],[.65,.45,.45],[.75,.55,.55],[.6,.4,.4]],[[.35,.3,.25],[.3,.25,.2],[.25,.2,.15],[.3,.25,.2],[.4,.35,.3],[.25,.2,.15]],[[.5,.3,0],[.5,.3,0],[.5,.3,0],[.5,.3,0],[.7,.4,.1],[.7,.4,.1]],[[0,.5,0],[0,.45,0],[0,.45,0],[0,.45,0],[0,.6,0],[0,.4,0]],[[.2,.8,.8],[.15,.7,.7],[.1,.6,.6],[.15,.7,.7],[.3,.9,.9],[.1,.6,.6]],[[1,.5,.8],[.9,.4,.7],[.8,.3,.6],[.9,.4,.7],[1,.6,.9],[.8,.3,.6]],[[1,.9,.3],[.95,.85,.25],[.9,.8,.2],[.95,.85,.25],[1,1,.4],[.9,.8,.2]],[[1,0,0],[.9,0,0],[.8,0,0],[.9,0,0],[1,.2,.2],[.8,0,0]],[[.6,.4,.2],[.5,.3,.15],[.4,.25,.1],[.5,.3,.15],[.7,.45,.25],[.4,.25,.1]],[[.6,.2,.8],[.5,.15,.7],[.4,.1,.6],[.5,.15,.7],[.7,.25,.9],[.4,.1,.6]],[[1,.8,0],[.95,.75,0],[.95,.75,0],[.95,.75,0],[1,.9,0],[.9,.7,0]],[[.6,.65,.7],[.55,.6,.65],[.5,.55,.6],[.55,.6,.65],[.65,.7,.75],[.5,.55,.6]]],HM=2e5,UM=class extends Ah{static typeName=`VoxelGrid3D`;static signals=[`blocksChanged`];static props={voxels:{default:[]}};voxels=[];appliedVoxels=null;map=new Map;mesh=null;dirty=!1;blockCount(){return this.map.size}tileAt(e,t,n){return this.map.get(`${e},${t},${n}`)}setBlocks(e){this.map.clear();for(let t of e)this.map.set(`${t.x},${t.y},${t.z}`,t.tile);this.dirty=!0,this.emit(`blocksChanged`)}addBlock(e){this.map.set(`${e.x},${e.y},${e.z}`,e.tile),this.dirty=!0,this.emit(`blocksChanged`)}removeBlockAt(e,t,n){let r=this.map.delete(`${e},${t},${n}`);return r&&(this.dirty=!0,this.emit(`blocksChanged`)),r}blocks(){let e=[];for(let[t,n]of this.map){let[r,i,a]=t.split(`,`).map(Number);e.push({x:r,y:i,z:a,tile:n})}return e}_createObject3D(){let e=new nl(1,1,1),t=new vl({vertexShader:GM,fragmentShader:KM});this.mesh=new xc(e,t,HM),this.mesh.count=0,this.mesh.frustumCulled=!1;for(let e of WM)this.mesh.geometry.setAttribute(e,new pc(new Float32Array(HM*3),3));return this.dirty=!0,this.mesh}update(){if(this.voxels.length>0&&this.voxels!==this.appliedVoxels&&(this.appliedVoxels=this.voxels,this.setBlocks(this.voxels.map(e=>({x:e[0]??0,y:e[1]??0,z:e[2]??0,tile:e[3]??0})))),!this.dirty||!this.mesh)return;this.dirty=!1;let e=new G,t=0;for(let[n,r]of this.map){if(t>=HM)break;let[i,a,o]=n.split(`,`).map(Number);e.setPosition(i,a,o),this.mesh.setMatrixAt(t,e);let s=VM[r]??VM[0];for(let e=0;e<6;e++){let n=this.mesh.geometry.getAttribute(WM[e]),r=s[e];n.setXYZ(t,r[0],r[1],r[2]),n.needsUpdate=!0}t++}this.mesh.count=t,this.mesh.instanceMatrix.needsUpdate=!0}},WM=[`colorFront`,`colorRight`,`colorBack`,`colorLeft`,`colorTop`,`colorBottom`],GM=`
7898
7898
  attribute vec3 colorFront;
7899
7899
  attribute vec3 colorRight;
7900
7900
  attribute vec3 colorBack;
@@ -7915,7 +7915,7 @@ void main() {
7915
7915
  if (abs(n.x) > 0.5) vUv2 = p.zy; else if (abs(n.y) > 0.5) vUv2 = p.xz; else vUv2 = p.xy;
7916
7916
  gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(position, 1.0);
7917
7917
  }
7918
- `,qM=`
7918
+ `,KM=`
7919
7919
  varying vec3 vColor;
7920
7920
  varying vec3 vNormal;
7921
7921
  varying vec2 vUv2;
@@ -7926,13 +7926,13 @@ void main() {
7926
7926
  if (vUv2.x < edge || vUv2.x > 1.0 - edge || vUv2.y < edge || vUv2.y > 1.0 - edge) color *= 0.75;
7927
7927
  gl_FragColor = vec4(color, 1.0);
7928
7928
  }
7929
- `;function JM(){_n(),R(Ah),R(eA),R(Ow),R(Lk),R(dE),R(fE),R(yE),R(lD),R(WM),R(Rw),R(mj),R(bE),R(DE),R(Mw),R(uj),R(_T),R(_g),R(Ih),R(Sk),R(lO),R(wM),R(Zk),R(UE),R(Fk),R(Ik),R(Mh),R(Ph),R(Nh),R(Fh)}var YM={slowMs:20,fastMs:13,minScale:.6,step:.15,window:45},XM=class{opts;samples=[];scale=1;constructor(e={}){this.opts={...YM,...e}}current(){return this.scale}push(e){if(!(e>0)||!Number.isFinite(e)||(this.samples.push(e),this.samples.length<this.opts.window))return null;let t=[...this.samples].sort((e,t)=>e-t),n=t[Math.floor(t.length/2)];this.samples=[];let r=this.scale;return n>this.opts.slowMs?this.scale=Math.max(this.opts.minScale,this.scale-this.opts.step):n<this.opts.fastMs&&this.scale<1&&(this.scale=Math.min(1,this.scale+this.opts.step)),this.scale===r?null:this.scale}reset(){this.samples=[]}},ZM=`
7929
+ `;function qM(){_n(),R(Ah),R($k),R(Ow),R(Ik),R(dE),R(fE),R(yE),R(sD),R(UM),R(Rw),R(pj),R(bE),R(DE),R(Mw),R(lj),R(_T),R(_g),R(Ih),R(xk),R(cO),R(CM),R(Xk),R(UE),R(Pk),R(Fk),R(Mh),R(Ph),R(Nh),R(Fh)}var JM={slowMs:20,fastMs:13,minScale:.6,step:.15,window:45},YM=class{opts;samples=[];scale=1;constructor(e={}){this.opts={...JM,...e}}current(){return this.scale}push(e){if(!(e>0)||!Number.isFinite(e)||(this.samples.push(e),this.samples.length<this.opts.window))return null;let t=[...this.samples].sort((e,t)=>e-t),n=t[Math.floor(t.length/2)];this.samples=[];let r=this.scale;return n>this.opts.slowMs?this.scale=Math.max(this.opts.minScale,this.scale-this.opts.step):n<this.opts.fastMs&&this.scale<1&&(this.scale=Math.min(1,this.scale+this.opts.step)),this.scale===r?null:this.scale}reset(){this.samples=[]}},XM=`
7930
7930
  varying vec2 vUv;
7931
7931
  void main() {
7932
7932
  vUv = uv;
7933
7933
  gl_Position = vec4(position.xy, 0.0, 1.0);
7934
7934
  }
7935
- `,QM=`
7935
+ `,ZM=`
7936
7936
  precision highp float;
7937
7937
  varying vec2 vUv;
7938
7938
  uniform sampler2D tScene;
@@ -7946,7 +7946,7 @@ void main() {
7946
7946
  float k = max(l - uThreshold, 0.0);
7947
7947
  gl_FragColor = vec4(c * (k / max(l, 1e-4)), 1.0);
7948
7948
  }
7949
- `,$M=`
7949
+ `,QM=`
7950
7950
  precision highp float;
7951
7951
  varying vec2 vUv;
7952
7952
  uniform sampler2D tTex;
@@ -7960,7 +7960,7 @@ void main() {
7960
7960
  sum += texture2D(tTex, vUv - uDir * 3.2308) * 0.0702703;
7961
7961
  gl_FragColor = sum;
7962
7962
  }
7963
- `,eN=`
7963
+ `,$M=`
7964
7964
  precision highp float;
7965
7965
  varying vec2 vUv;
7966
7966
  uniform sampler2D tScene;
@@ -7990,13 +7990,13 @@ void main() {
7990
7990
  gl_FragColor.rgb = max(graded, 0.0);
7991
7991
  #include <colorspace_fragment>
7992
7992
  }
7993
- `;function tN(e,t){let n=new vl({vertexShader:ZM,fragmentShader:e,depthTest:!1,depthWrite:!1,uniforms:t}),r=new Ys(new cl(2,2),n);return r.frustumCulled=!1,r}function nN(){let e=tN(QM,{tScene:{value:null},uThreshold:{value:1}});return{mesh:e,uniforms:e.material.uniforms}}function rN(){let e=tN($M,{tTex:{value:null},uDir:{value:new V}});return{mesh:e,uniforms:e.material.uniforms}}function iN(){let e=tN(eN,{tScene:{value:null},tBloom:{value:null},uStrength:{value:.85},uVignette:{value:0},uSaturation:{value:1},uContrast:{value:1}});return{mesh:e,uniforms:e.material.uniforms}}var aN=`
7993
+ `;function eN(e,t){let n=new vl({vertexShader:XM,fragmentShader:e,depthTest:!1,depthWrite:!1,uniforms:t}),r=new Ys(new cl(2,2),n);return r.frustumCulled=!1,r}function tN(){let e=eN(ZM,{tScene:{value:null},uThreshold:{value:1}});return{mesh:e,uniforms:e.material.uniforms}}function nN(){let e=eN(QM,{tTex:{value:null},uDir:{value:new V}});return{mesh:e,uniforms:e.material.uniforms}}function rN(){let e=eN($M,{tScene:{value:null},tBloom:{value:null},uStrength:{value:.85},uVignette:{value:0},uSaturation:{value:1},uContrast:{value:1}});return{mesh:e,uniforms:e.material.uniforms}}var iN=`
7994
7994
  varying vec2 vUv;
7995
7995
  void main() {
7996
7996
  vUv = uv;
7997
7997
  gl_Position = vec4(position.xy, 0.0, 1.0);
7998
7998
  }
7999
- `,oN=`
7999
+ `,aN=`
8000
8000
  precision highp float;
8001
8001
  varying vec2 vUv;
8002
8002
  uniform sampler2D tDepth;
@@ -8158,7 +8158,7 @@ void main() {
8158
8158
  // a separate full-res pass (this raymarch runs at HALF res for performance)
8159
8159
  gl_FragColor = vec4(accum, alpha);
8160
8160
  }
8161
- `,sN=`
8161
+ `,oN=`
8162
8162
  precision highp float;
8163
8163
  varying vec2 vUv;
8164
8164
  uniform sampler2D tTex;
@@ -8176,7 +8176,7 @@ void main() {
8176
8176
  c += texture2D(tTex, vUv - uDir * 4.0) * 0.015;
8177
8177
  gl_FragColor = c;
8178
8178
  }
8179
- `,cN=`
8179
+ `,sN=`
8180
8180
  precision highp float;
8181
8181
  varying vec2 vUv;
8182
8182
  uniform sampler2D tScene;
@@ -8186,11 +8186,11 @@ void main() {
8186
8186
  vec4 cloud = texture2D(tClouds, vUv); // already separable-blurred + premultiplied
8187
8187
  gl_FragColor = vec4(scene.rgb * (1.0 - cloud.a) + cloud.rgb, 1.0);
8188
8188
  }
8189
- `;function lN(){let e=new vl({vertexShader:aN,fragmentShader:sN,depthTest:!1,depthWrite:!1,uniforms:{tTex:{value:null},uDir:{value:new V}}}),t=new Ys(new cl(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}function uN(){let e=new vl({vertexShader:aN,fragmentShader:oN,depthTest:!1,depthWrite:!1,uniforms:{tDepth:{value:null},uInvViewProj:{value:new G},uCameraPos:{value:new U},uTime:{value:0},uSunDir:{value:new U(0,1,0)},uSunColor:{value:new K(`#fff3da`)},uCloudColor:{value:new K(`#ffffff`)},uShadeColor:{value:new K(`#9fb0c8`)},uHorizonColor:{value:new K(`#cdd9e6`)},uBase:{value:120},uTop:{value:320},uCoverage:{value:.5},uDensity:{value:1},uScale:{value:240},uWind:{value:new V(1,.3)},uFarFade:{value:6e3}}}),t=new Ys(new cl(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}function dN(){let e=new vl({vertexShader:aN,fragmentShader:cN,depthTest:!1,depthWrite:!1,uniforms:{tScene:{value:null},tClouds:{value:null}}}),t=new Ys(new cl(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}var fN=class extends $l{constructor(e){super(e),this.type=gr}parse(e){let t=function(e,t){switch(e){case 1:throw Error(`THREE.HDRLoader: Read Error: `+(t||``));case 2:throw Error(`THREE.HDRLoader: Write Error: `+(t||``));case 3:throw Error(`THREE.HDRLoader: Bad File Format: `+(t||``));default:case 4:throw Error(`THREE.HDRLoader: Memory Error: `+(t||``))}},n=function(e,t,n){t||=1024;let r=e.pos,i=-1,a=0,o=``,s=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));for(;0>(i=s.indexOf(`
8189
+ `;function cN(){let e=new vl({vertexShader:iN,fragmentShader:oN,depthTest:!1,depthWrite:!1,uniforms:{tTex:{value:null},uDir:{value:new V}}}),t=new Ys(new cl(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}function lN(){let e=new vl({vertexShader:iN,fragmentShader:aN,depthTest:!1,depthWrite:!1,uniforms:{tDepth:{value:null},uInvViewProj:{value:new G},uCameraPos:{value:new U},uTime:{value:0},uSunDir:{value:new U(0,1,0)},uSunColor:{value:new K(`#fff3da`)},uCloudColor:{value:new K(`#ffffff`)},uShadeColor:{value:new K(`#9fb0c8`)},uHorizonColor:{value:new K(`#cdd9e6`)},uBase:{value:120},uTop:{value:320},uCoverage:{value:.5},uDensity:{value:1},uScale:{value:240},uWind:{value:new V(1,.3)},uFarFade:{value:6e3}}}),t=new Ys(new cl(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}function uN(){let e=new vl({vertexShader:iN,fragmentShader:sN,depthTest:!1,depthWrite:!1,uniforms:{tScene:{value:null},tClouds:{value:null}}}),t=new Ys(new cl(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}var dN=class extends $l{constructor(e){super(e),this.type=gr}parse(e){let t=function(e,t){switch(e){case 1:throw Error(`THREE.HDRLoader: Read Error: `+(t||``));case 2:throw Error(`THREE.HDRLoader: Write Error: `+(t||``));case 3:throw Error(`THREE.HDRLoader: Bad File Format: `+(t||``));default:case 4:throw Error(`THREE.HDRLoader: Memory Error: `+(t||``))}},n=function(e,t,n){t||=1024;let r=e.pos,i=-1,a=0,o=``,s=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));for(;0>(i=s.indexOf(`
8190
8190
  `))&&a<t&&r<e.byteLength;)o+=s,a+=s.length,r+=128,s=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));return-1<i?(!1!==n&&(e.pos+=a+i+1),o+s.slice(0,i)):!1},r=function(e){let r=/^#\?(\S+)/,i=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,a=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,o=/^\s*FORMAT=(\S+)\s*$/,s=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,c={valid:0,string:``,comments:``,programtype:`RGBE`,format:``,gamma:1,exposure:1,width:0,height:0},l,u;for((e.pos>=e.byteLength||!(l=n(e)))&&t(1,`no header found`),(u=l.match(r))||t(3,`bad initial token`),c.valid|=1,c.programtype=u[1],c.string+=l+`
8191
8191
  `;l=n(e),!1!==l;){if(c.string+=l+`
8192
8192
  `,l.charAt(0)===`#`){c.comments+=l+`
8193
- `;continue}if((u=l.match(i))&&(c.gamma=parseFloat(u[1])),(u=l.match(a))&&(c.exposure=parseFloat(u[1])),(u=l.match(o))&&(c.valid|=2,c.format=u[1]),(u=l.match(s))&&(c.valid|=4,c.height=parseInt(u[1],10),c.width=parseInt(u[2],10)),c.valid&2&&c.valid&4)break}return c.valid&2||t(3,`missing format specifier`),c.valid&4||t(3,`missing image size specifier`),c},i=function(e,n,r){let i=n;if(i<8||i>32767||e[0]!==2||e[1]!==2||e[2]&128)return new Uint8Array(e);i!==(e[2]<<8|e[3])&&t(3,`wrong scanline width`);let a=new Uint8Array(4*n*r);a.length||t(4,`unable to allocate buffer space`);let o=0,s=0,c=4*i,l=new Uint8Array(4),u=new Uint8Array(c),d=r;for(;d>0&&s<e.byteLength;){s+4>e.byteLength&&t(1),l[0]=e[s++],l[1]=e[s++],l[2]=e[s++],l[3]=e[s++],(l[0]!=2||l[1]!=2||(l[2]<<8|l[3])!=i)&&t(3,`bad rgbe scanline format`);let n=0,r;for(;n<c&&s<e.byteLength;){r=e[s++];let i=r>128;if(i&&(r-=128),(r===0||n+r>c)&&t(3,`bad scanline data`),i){let t=e[s++];for(let e=0;e<r;e++)u[n++]=t}else u.set(e.subarray(s,s+r),n),n+=r,s+=r}let f=i;for(let e=0;e<f;e++){let t=0;a[o]=u[e+t],t+=i,a[o+1]=u[e+t],t+=i,a[o+2]=u[e+t],t+=i,a[o+3]=u[e+t],o+=4}d--}return a},a=function(e,t,n,r){let i=2**(e[t+3]-128)/255;n[r+0]=e[t+0]*i,n[r+1]=e[t+1]*i,n[r+2]=e[t+2]*i,n[r+3]=1},o=function(e,t,n,r){let i=2**(e[t+3]-128)/255;n[r+0]=os.toHalfFloat(Math.min(e[t+0]*i,65504)),n[r+1]=os.toHalfFloat(Math.min(e[t+1]*i,65504)),n[r+2]=os.toHalfFloat(Math.min(e[t+2]*i,65504)),n[r+3]=os.toHalfFloat(1)},s=new Uint8Array(e);s.pos=0;let c=r(s),l=c.width,u=c.height,d=i(s.subarray(s.pos),l,u),f,p,m;switch(this.type){case hr:m=d.length/4;let e=new Float32Array(m*4);for(let t=0;t<m;t++)a(d,t*4,e,t*4);f=e,p=hr;break;case gr:m=d.length/4;let t=new Uint16Array(m*4);for(let e=0;e<m;e++)o(d,e*4,t,e*4);f=t,p=gr;break;default:throw Error(`THREE.HDRLoader: Unsupported type: `+this.type)}return{width:l,height:u,data:f,header:c.string,gamma:c.gamma,exposure:c.exposure,type:p}}setDataType(e){return this.type=e,this}load(e,t,n,r){function i(e,n){switch(e.type){case hr:case gr:e.colorSpace=ki,e.minFilter=or,e.magFilter=or,e.generateMipmaps=!1,e.flipY=!0;break}t&&t(e,n)}return super.load(e,i,n,r)}},pN=class extends fN{constructor(e){console.warn(`RGBELoader has been deprecated. Please use HDRLoader instead.`),super(e)}},mN=class e extends Ys{constructor(){let t=e.SkyShader,n=new vl({name:t.name,uniforms:hl.clone(t.uniforms),vertexShader:t.vertexShader,fragmentShader:t.fragmentShader,side:1,depthWrite:!1});super(new nl(1,1,1),n),this.isSky=!0}};mN.SkyShader={name:`SkyShader`,uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new U},up:{value:new U(0,1,0)},cloudScale:{value:2e-4},cloudSpeed:{value:1e-4},cloudCoverage:{value:.4},cloudDensity:{value:.4},cloudElevation:{value:.5},showSunDisc:{value:1},time:{value:0}},vertexShader:`
8193
+ `;continue}if((u=l.match(i))&&(c.gamma=parseFloat(u[1])),(u=l.match(a))&&(c.exposure=parseFloat(u[1])),(u=l.match(o))&&(c.valid|=2,c.format=u[1]),(u=l.match(s))&&(c.valid|=4,c.height=parseInt(u[1],10),c.width=parseInt(u[2],10)),c.valid&2&&c.valid&4)break}return c.valid&2||t(3,`missing format specifier`),c.valid&4||t(3,`missing image size specifier`),c},i=function(e,n,r){let i=n;if(i<8||i>32767||e[0]!==2||e[1]!==2||e[2]&128)return new Uint8Array(e);i!==(e[2]<<8|e[3])&&t(3,`wrong scanline width`);let a=new Uint8Array(4*n*r);a.length||t(4,`unable to allocate buffer space`);let o=0,s=0,c=4*i,l=new Uint8Array(4),u=new Uint8Array(c),d=r;for(;d>0&&s<e.byteLength;){s+4>e.byteLength&&t(1),l[0]=e[s++],l[1]=e[s++],l[2]=e[s++],l[3]=e[s++],(l[0]!=2||l[1]!=2||(l[2]<<8|l[3])!=i)&&t(3,`bad rgbe scanline format`);let n=0,r;for(;n<c&&s<e.byteLength;){r=e[s++];let i=r>128;if(i&&(r-=128),(r===0||n+r>c)&&t(3,`bad scanline data`),i){let t=e[s++];for(let e=0;e<r;e++)u[n++]=t}else u.set(e.subarray(s,s+r),n),n+=r,s+=r}let f=i;for(let e=0;e<f;e++){let t=0;a[o]=u[e+t],t+=i,a[o+1]=u[e+t],t+=i,a[o+2]=u[e+t],t+=i,a[o+3]=u[e+t],o+=4}d--}return a},a=function(e,t,n,r){let i=2**(e[t+3]-128)/255;n[r+0]=e[t+0]*i,n[r+1]=e[t+1]*i,n[r+2]=e[t+2]*i,n[r+3]=1},o=function(e,t,n,r){let i=2**(e[t+3]-128)/255;n[r+0]=os.toHalfFloat(Math.min(e[t+0]*i,65504)),n[r+1]=os.toHalfFloat(Math.min(e[t+1]*i,65504)),n[r+2]=os.toHalfFloat(Math.min(e[t+2]*i,65504)),n[r+3]=os.toHalfFloat(1)},s=new Uint8Array(e);s.pos=0;let c=r(s),l=c.width,u=c.height,d=i(s.subarray(s.pos),l,u),f,p,m;switch(this.type){case hr:m=d.length/4;let e=new Float32Array(m*4);for(let t=0;t<m;t++)a(d,t*4,e,t*4);f=e,p=hr;break;case gr:m=d.length/4;let t=new Uint16Array(m*4);for(let e=0;e<m;e++)o(d,e*4,t,e*4);f=t,p=gr;break;default:throw Error(`THREE.HDRLoader: Unsupported type: `+this.type)}return{width:l,height:u,data:f,header:c.string,gamma:c.gamma,exposure:c.exposure,type:p}}setDataType(e){return this.type=e,this}load(e,t,n,r){function i(e,n){switch(e.type){case hr:case gr:e.colorSpace=ki,e.minFilter=or,e.magFilter=or,e.generateMipmaps=!1,e.flipY=!0;break}t&&t(e,n)}return super.load(e,i,n,r)}},fN=class extends dN{constructor(e){console.warn(`RGBELoader has been deprecated. Please use HDRLoader instead.`),super(e)}},pN=class e extends Ys{constructor(){let t=e.SkyShader,n=new vl({name:t.name,uniforms:hl.clone(t.uniforms),vertexShader:t.vertexShader,fragmentShader:t.fragmentShader,side:1,depthWrite:!1});super(new nl(1,1,1),n),this.isSky=!0}};pN.SkyShader={name:`SkyShader`,uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new U},up:{value:new U(0,1,0)},cloudScale:{value:2e-4},cloudSpeed:{value:1e-4},cloudCoverage:{value:.4},cloudDensity:{value:.4},cloudElevation:{value:.5},showSunDisc:{value:1},time:{value:0}},vertexShader:`
8194
8194
  uniform vec3 sunPosition;
8195
8195
  uniform float rayleigh;
8196
8196
  uniform float turbidity;
@@ -8410,7 +8410,7 @@ void main() {
8410
8410
  #include <tonemapping_fragment>
8411
8411
  #include <colorspace_fragment>
8412
8412
 
8413
- }`};var hN=[`type`,`sunPosition`,`elevationDeg`,`azimuthDeg`,`turbidity`,`rayleigh`],gN=[`color`,`near`,`far`],_N=[`coverage`,`density`,`base`,`top`,`color`,`shadeColor`,`speed`,`scale`],vN=[`threshold`,`strength`],yN=[`vignette`,`saturation`,`contrast`],bN=[`mapSize`,`radius`,`static`],xN=[1024,2048],SN=2,CN=1,wN=50,TN=800,EN=`#cfd8e0`,DN=Math.PI/180;function ON(e){return{exposure:MN(e?.exposure),sky:NN(e?.sky),fog:PN(e?.fog,e?.sky!==void 0),clouds:FN(e?.clouds),bloom:IN(e?.bloom),post:LN(e?.post),shadows:RN(e?.shadows)}}function kN(e,t){let n=(90-e)*DN,r=t*DN;return[Math.sin(n)*Math.sin(r),Math.cos(n),Math.sin(n)*Math.cos(r)]}function AN(e){let[t,n,r]=e.sunPosition,i=Math.hypot(t,n,r)||1;return[t/i,n/i,r/i]}function jN(e){let t=[191,213,232],n=[233,228,217],r=[242,201,150],i=VN((e.turbidity-SN)/8),a=AN(e),o=VN((18-Math.asin(BN(a[1],-1,1))/DN)/18)*.8,s=e=>Math.round(HN(HN(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 MN(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 NN(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(!hN.includes(e))throw new N(`BAD_FORMAT`,`environment.sky has unknown key '${e}'. Valid keys: [${hN.join(`, `)}].`,{prop:`sky`,validOptions:hN});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=zN(t.elevationDeg,32,`sky.elevationDeg`),n=zN(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=kN(e,n)}let i=zN(t.turbidity,SN,`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=zN(t.rayleigh,CN,`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 PN(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(!gN.includes(e))throw new N(`BAD_FORMAT`,`environment.fog has unknown key '${e}'. Valid keys: [${gN.join(`, `)}].`,{prop:`fog`,validOptions:gN});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=zN(n.near,wN,`fog.near`),i=zN(n.far,TN,`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?``:EN),near:r,far:i}}function FN(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(!_N.includes(e))throw new N(`BAD_FORMAT`,`environment.clouds has unknown key '${e}'. Valid keys: [${_N.join(`, `)}].`,{prop:`clouds`,validOptions:_N});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=zN(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=zN(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=zN(t.base,120,`clouds.base`),a=zN(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=zN(t.speed,1,`clouds.speed`),s=zN(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 IN(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(!vN.includes(e))throw new N(`BAD_FORMAT`,`environment.bloom has unknown key '${e}'. Valid keys: [${vN.join(`, `)}].`,{prop:`bloom`,validOptions:vN});let n=zN(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=zN(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 LN(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(!yN.includes(e))throw new N(`BAD_FORMAT`,`environment.post has unknown key '${e}'. Valid keys: [${yN.join(`, `)}].`,{prop:`post`,validOptions:yN});let n=zN(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=zN(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=zN(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 RN(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(!bN.includes(e))throw new N(`BAD_FORMAT`,`environment.shadows has unknown key '${e}'. Valid keys: [${bN.join(`, `)}].`,{prop:`shadows`,validOptions:bN});let n=t.mapSize===void 0?2048:t.mapSize;if(!xN.includes(n))throw new N(`BAD_FORMAT`,`environment.shadows.mapSize must be one of [${xN.join(`, `)}], got ${JSON.stringify(t.mapSize)}.`,{prop:`shadows`,validOptions:xN.map(String)});let r=zN(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 zN(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 BN(e,t,n){return Math.min(Math.max(e,t),n)}function VN(e){return BN(e,0,1)}function HN(e,t,n){return e+(t-e)*n}var UN=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,WN={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 GN(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=WN[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(WN).join(`, `)}.`);return`${UN}/${t}`}return null}var KN=75,qN=class{scene;ambient=new xu(`#ffffff`,0);envKey=null;config=ON(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new To(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new K;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?AN(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 To?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=ON(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)*JN(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=KN,t.top=KN,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 To(`#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=GN(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new pN().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 mN,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 xd(t),r=new Eo;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?jN(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 JN(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 YN=new Vo,XN=new Vo,ZN=new G,QN=new G,$N=new U,eP=Array.from({length:8},()=>new U),tP=.4,nP=new Float32Array(72),rP=[[0,0,0],[1,0,0],[1,0,1],[0,0,1],[0,1,0],[1,1,0],[1,1,1],[0,1,1]],iP=[[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 aP(e,t){t.makeEmpty(),ZN.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&&(XN.copy(r).applyMatrix4(QN.multiplyMatrices(ZN,e.matrixWorld)),t.union(XN))})}function oP(e){if(!(e instanceof Ah))return null;let t=e._ensureObject3D();t.updateWorldMatrix(!0,!0),aP(t,YN);let n=!0;YN.isEmpty()?(n=!1,$N.setFromMatrixPosition(t.matrixWorld),YN.min.set($N.x-tP,$N.y-tP,$N.z-tP),YN.max.set($N.x+tP,$N.y+tP,$N.z+tP)):YN.expandByScalar(.02);let{min:r,max:i}=YN;for(let e=0;e<8;e++){let[a,o,s]=rP[e],c=eP[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 iP){let n=eP[e],r=eP[t];nP[a++]=n.x,nP[a++]=n.y,nP[a++]=n.z,nP[a++]=r.x,nP[a++]=r.y,nP[a++]=r.z}return nP}function sP(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function cP(){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 lP(e,t,n,r,i){let a=i??cP();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,hP(e,t,o),vP(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 mP(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var uP=new U,dP=new U,fP=new U,pP=new U;function mP(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(dP),t.getWorldDirection(fP),pP.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[dP.x,dP.y,dP.z],forward:[fP.x,fP.y,fP.z],up:[pP.x,pP.y,pP.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(uP),t._setSpatialPose({position:[uP.x,uP.y,uP.z],listener:n})}function hP(e,t,n){let r=t;if(e instanceof Ah){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 Zk&&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 Fk&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof UE&&n.cameras.push(e),r=i}else sP(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)hP(t,r,n);if(e instanceof Ah){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,_P(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var gP=new WeakSet;function _P(e){if(gP.has(e))return;gP.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof UE)&&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 vP(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&&vP(i,t)}}var yP=class{viewOverride=null;overrideCam=new pu(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new Eo;environment=new qN(this.threeScene);engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;warmCamera=null;deferCompile=!1;syncScratch=cP();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 yw(this.engine);let t=vn(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 hm({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 XM,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new Hc(new J,new Ac({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new Hc(new J,new Ac({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?oP(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 tv(`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(bP,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}=lP(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(SP.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(OP),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(xP);(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=wP.setFromMatrixPosition(o.matrixWorld).sub(TP.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(xP),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 Ba(i,a,{type:gr,samples:4}),this.bloomBrightTarget=new Ba(o,s,{type:gr}),this.bloomBlurTarget=new Ba(o,s,{type:gr})),!this.bloomBrightScene){let e=nN();this.bloomBrightScene=new Eo,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=rN();this.bloomBlurScene=new Eo,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=iN();this.bloomCompositeScene=new Eo,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(xP),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 $c(i,a);e.type=hr,this.cloudsTarget=new Ba(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Ba(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Ba(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=uN();this.cloudsScene=new Eo,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=lN();this.cloudsBlurScene=new Eo,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=dN();this.cloudsCompositeScene=new Eo,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(xP),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 $c(r,i);e.type=hr,this.causticsTarget=new Ba(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=th();this.causticsScene=new Eo,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?(CP.set(e,t,n).project(r),{x:(CP.x+1)/2*this.lastSize.w,y:(1-CP.y)/2*this.lastSize.h,behind:CP.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;AP.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),kP.setFromCamera(AP,n);let r=kP.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(DP),{x:DP.x,y:DP.y,z:DP.z}):null}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(EP):EP.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()}},bP=12,xP=new V,SP=new U,CP=new U,wP=new U,TP=new U,EP=new H,DP=new U,OP=new U,kP=new qu,AP=new V;async function jP(e){let t=async(t,n)=>{e.onProgress&&(e.onProgress(t,n),typeof requestAnimationFrame==`function`&&await new Promise(e=>{requestAnimationFrame(()=>setTimeout(e,0))}))};JM(),(e.gameplay??!0)&&G_();for(let[t,n]of Object.entries(e.behaviors??{}))it(t,n,{replace:!0});let n=new kt({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),r=MP(e.scene),i=An(MP(r),{resolveScene:e.resolveScene,engine:n});n.setScene(i),await t(.06,`scene`);let a=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&NP(i.root))&&(a=await AT(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(PP(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=qn(n,t,r),a=n.sceneChanged.connect(()=>{i?.dispose(),i=qn(n,t,r)});o.push(()=>{a(),i?.dispose()})}}let l=e._rendererFactory?e._rendererFactory(n,e.canvas):new yP({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=Mm(l),n=f.open??Am,i=async t=>{await jP({...e,scene:t})};await jm(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?wm():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 bm(async()=>{let{attachDebugOverlay:e}=await import(`./debug-BgAq55oC.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(){Nm([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 MP(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 NP(e){if(e instanceof jh)return!0;for(let t of e.children)if(NP(t))return!0;return!1}function PP(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 Rt&&(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 FP=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>rT,WATER_CUTOUT_MAX:()=>4,WATER_MAX_RIPPLES:()=>8,createGame3D:()=>jP,enablePhysics3D:()=>AT}),IP=new WeakMap,LP=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 IP.get(e)??null}static async create(t,n={}){await IP.get(t)?.dispose();let r=n.transport??await HP(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 IP.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]),IP.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3;let n=RP(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=BP(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 RP(e,t=!1){let n=[];if(zP(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 zP(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)zP(n,t)}function BP(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 VP(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 HP(e){let{createAgent8Server:t}=await bm(async()=>{let{createAgent8Server:e}=await import(`./agent8-DMvBVhe4.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var UP=class extends Nt{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=LP.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=jn(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=WP(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=t.sync;i&&VP(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 WP(e){return e.replace(/[/%]/g,`_`)||`remote`}function GP(){_n(),R(UP)}function KP(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}var qP=KP()?.getItem(`incanto-editor-lang`)??`en`,JP=new Set;function YP(){return qP}function XP(e){qP=e,KP()?.setItem(`incanto-editor-lang`,e);for(let e of JP)e()}function ZP(e){JP.add(e)}function QP(e){return e[qP]}var $P={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`]}},eF={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 tF(e){let t=$P[eF[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 nF(){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 rF=[{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`]}],iF=new Set,aF=null,oF=null;function sF(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 cF(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 lF(e){let t=e.assets.length;for(let n of e.folders.values())t+=lF(n);return t}function uF(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(EF(i.type??``)),s.addEventListener(`click`,e=>{e.stopPropagation(),DF(s,i.type??``)}),aF===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;o.appendChild(sF(a,r=>{aF=null,t.renameAssetKey(e,n+r)},()=>{aF=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(),aF=e,t.selectAsset(e)}),o.append(s,c),o.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(o)},o=(e,n)=>{let r=iF.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(nF());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),oF===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,sF(e.name,n=>{oF=null,t.renameGroup(e.path,i+n)},()=>{oF=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(),oF=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${lF(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{iF.has(e.path)?iF.delete(e.path):iF.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=cF(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function dF(e,t,n,r){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(jF(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(xF(`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 hF(e,t,r);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(jF(`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(SF(`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(jF(`ASSET — ${String(a[i].type??`?`)}`)),e.appendChild(OF(i)),e.appendChild(kF(t,i)),e.appendChild(fF(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 fF(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=SF(`name`,o,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==o&&e.renameAssetKey(n,s+r)});AF(c.querySelector(`input`)),a.appendChild(c);let l=SF(`url`,String(i.url??``),t=>{e.mutate(()=>{i.url=t.trim()})}),u=l.querySelector(`input`);if(r&&u){let t=_F(String(i.type??``));l.appendChild(bF(()=>t,`asset url`,r,t=>{u.value=t,e.mutate(()=>{i.url=t})},()=>yF(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(pF(e,i,t,n));return a.appendChild(mF(e,i)),a}function pF(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]=CF(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 mF(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]=CF(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function hF(e,t,n){return e.appendChild(jF(`NEW ASSET`)),e.appendChild(gF(t,n)),!0}function gF(e,t){let n=document.createElement(`div`);n.className=`asset-editor`;let r=document.createElement(`select`);for(let e of rF){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,r.appendChild(t)}n.appendChild(xF(`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(xF(`group`,i)),n.appendChild(o);let c=document.createElement(`input`);c.placeholder=`coin`,c.className=`mono`,AF(c),n.appendChild(xF(`key`,c));let l=document.createElement(`input`);l.placeholder=`/textures/coin.png · https://… · data:…`,l.className=`mono`;let u=xF(`url`,l);t&&u.appendChild(bF(()=>_F(r.value),`new asset`,t,e=>{l.value=e,c.value.trim()||(c.value=vF(e))},()=>yF(_F(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 _F(e){return e===`model`||e===`animation`?`model`:e===`audio`?`audio`:e===`texture`||e===`spritesheet`?`image`:`any`}function vF(e){return((e.split(/[?#]/)[0]??``).split(`/`).pop()??``).replace(/\.[^.]+$/,``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function yF(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 bF(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 xF(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 SF(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),xF(e,r)}function CF(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 wF={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`},TF={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 EF(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`,wF[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function DF(e,t){document.querySelector(`.balloon`)?.remove();let n=TF[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=QP(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 OF(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 kF(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 AF(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function jF(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 MF=window.parent!==window,NF=new URLSearchParams(window.location.search).get(`parentOrigin`),PF=!1;function FF(e){if(MF){if(!NF){PF||(PF=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,NF)}}var IF={ready(e,t,n){FF({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){FF({type:`incanto-editor:open`,input:e,output:t})},change(e){FF({type:`incanto-editor:change`,dirty:e})},save(e,t,n){FF({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){FF({type:`incanto-editor:error`,message:e})}},LF=[[`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`]],RF=[...LF,[`Other`,e=>LF.every(([,t])=>!t(e))]],zF={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}),BF=[{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를 발산합니다.`})]}],VF=`overview`,HF=null;function UF(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),KF()}function WF(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function GF(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&WF()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,WF))}function KF(){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${VF===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{VF=t,HF=null,KF()}),e.appendChild(r)};n(`overview`,QP({en:`Overview`,ko:`개요`}));for(let e of BF)n(e.id,QP(e.label));if(t.textContent=``,VF===`overview`){qF(t);return}let r=BF.find(e=>e.id===VF);r&&JF(t,r)}function qF(e){let t=document.createElement(`h2`);t.textContent=QP(zF.title),e.appendChild(t);for(let t of zF.sections){let n=document.createElement(`h3`);n.textContent=QP(t.heading);let r=document.createElement(`p`);r.textContent=QP(t.text),e.append(n,r)}}function JF(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=QP(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${HF===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(tF(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=QP(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{HF=HF===n.type?null:n.type,KF()}),t.appendChild(r),HF===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=QP(t),e.appendChild(n)}e.appendChild(YF(n.type)),t.appendChild(e)}e.appendChild(t)}}function YF(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[QP({en:`prop`,ko:`prop`}),QP({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 XF(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 ZF(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??QF(r),roughness:1},castShadow:!0}}}function QF(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function $F(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 eI(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function tI(e,t,n){return Math.min(Math.max(e,t),n)}var nI=[`boxes`,`ruins`,`garden`],rI=.5,iI=.1,aI=2,oI={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 sI(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!nI.includes(o))throw new N(`BAD_FORMAT`,`generateArena theme must be one of [${nI.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...nI]});let s=oI[o],c=new P(t),l=[XF(`Floor`,[n,iI,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+rI*2,i,rI],f=[rI,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(XF(`Wall1`,d,[0,u,-(r+rI)/2],p),XF(`Wall2`,d,[0,u,(r+rI)/2],p),XF(`Wall3`,f,[-(n+rI)/2,u,0],p),XF(`Wall4`,f,[(n+rI)/2,u,0],p)),o===`ruins`?l.push(...lI(c,s,n,r,i,a)):l.push(...cI(c,s,n,r,i,a,o)),o===`garden`&&l.push(...uI(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 cI(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-aI),n/2-aI)),u=$(e.range(-(r/2-aI),r/2-aI));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(XF(`Obstacle${o}`,a,[l,$(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function lI(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-aI*2,u=r-aI*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(XF(`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 uI(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 dI=32,fI=[4,8],pI=`#332f3a`,mI=`#6b6357`;function hI(e){let{seed:t,rooms:n=5}=e,[r,i]=eI(e.size,[960,720]),a=Math.max(8,Math.floor(r/dI)),o=Math.max(8,Math.floor(i/dI)),s=new P(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(fI[0],fI[1]),t=s.int(fI[0],fI[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=>gI(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]=_I(c[e-1]),[r,i]=_I(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*dI)/2,m=-(o*dI)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*dI,m+(t.y+t.h/2)*dI],size:[t.w*dI,t.h*dI],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,pI));for(let e of d)g.push(h(e.name,e.rect,pI));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*dI,dI];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*dI,m+(e+.5)*dI],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:mI}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function gI(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 _I(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var vI=[[0,-1],[1,0],[0,1],[-1,0]];function yI(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 vI){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 bI=[`stone`,`hedge`,`canyon`],xI=.1,SI=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,CI=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,wI={stone:{wall:{color:`#e8e2d8`,map:`${SI}/blocks.png`,normalMap:`${SI}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${CI}/stone.png`,normalMap:`${CI}/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:`${CI}/grass.png`,normalMap:`${CI}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${CI}/grass.png`,normalMap:`${CI}/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:`${CI}/stone.png`,normalMap:`${CI}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${CI}/sand.png`,normalMap:`${CI}/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 TI(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 EI=10;function DI(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!bI.includes(o))throw new N(`BAD_FORMAT`,`generateMaze theme must be one of [${bI.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...bI]});let s=wI[o],c=new P(t),l=yI(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=[XF(`Floor`,[f,xI,p],[0,-.1/2,0],{material:TI(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(XF(`Wall${_}`,[r,a,i],[$((t+n/2)*i-f/2),$(a/2),$((e+.5)*i-p/2)],{material:TI(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...OI(g,i,a,f,p,s.cap)),h.push(...kI(c,l,i,a,m,s)),o===`hedge`?(h.push(...NI(c,g,i,a,m)),h.push(...PI(c,l,i,m,n,r))):o===`canyon`&&h.push(...FI(c,g,i,a,m)),h.push(...jI(l,i,a,m,s)),h.push(...$F(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 OI(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 kI(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(EI,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(AI(`Pillar${t}`,c,p,d,f,a))}return l}function AI(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,$(i/2),n],material:{...TI(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function jI(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 AI(`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:{...TI(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var MI=10;function NI(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,MI).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 PI(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 FI(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=ZF(s,c,l,e,[.3,$(n*.35)],`#8f7355`),d=u.props?.position;d[1]=$(d[1]+r),a.push(u)}return a}var II=`#23222b`,LI=`#5f6672`;function RI(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=yI(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:II}}],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:LI}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var zI=16,BI=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function VI(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(HI(e,u,d,l,s.pick(BI))),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 HI(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,zI]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,zI],color:i}}]}}var UI=[3,5],WI=3,GI={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function KI(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=eI(e.area,[60,60]),o=new P(t),s=[];for(let e=1;e<=n;e++){let t=o.int(UI[0],UI[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:GI}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[$(o.range(-i/2,i/2)),$(r+o.range(-3,WI)),$(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,children:s}}var qI=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],JI=128,YI=20,XI=.8,ZI=.12,QI={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 $I(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=QI[n];if(!a)throw new N(`BAD_FORMAT`,`generateTerrain theme must be one of [${qI.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...qI]});let o=Math.max(2,Math.round(e.resolution??JI)),s=e.maxHeight||a.maxHeight,c=new P(t),l=n===`island`,u=e=>Uw({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=tL(d)-YI,t=d.maxHeight-d.minHeight,n=d.minHeight+ZI*t;if(e+XI<=n)break;let r=YI-XI,i=tL(d)-d.minHeight-ZI*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===JI?{}:{resolution:o}}}]}],p=n===`wetland`;if(l)f.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,eL(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(..._L(n,c,d,r)),l&&f.push(KI({seed:c.int(1,1e9),count:6,area:r,altitude:Math.round(d.maxHeight+12)})),f.push(...$F(r).map((e,t)=>vL(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:f}}function eL(e){let t=tL(e)-YI,n=e.minHeight+ZI*(e.maxHeight-e.minHeight);return $(Math.max(Math.min(t+XI,n),t+.55))}function tL(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 nL(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 rL=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],iL=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],aL={canopy:`#9aa052`,trunk:`#8a6a44`},oL={canopy:`#39513f`,trunk:`#5a5650`};function sL(e,t){return e===`conifer`?t.pick(rL):e===`broadleaf`?t.pick(iL):null}function cL(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=sL(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 lL(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 uL(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 dL(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 fL(e,t,n,r){return e.map((e,i)=>{let a=ZF(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=$(o[1]+e.y),a})}function pL(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 mL(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 hL(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 gL=[`#6f5b41`,`#7a644a`,`#665439`];function _L(e,t,n,r){let i=[];switch(e){case`island`:{let e=nL(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>cL(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=nL(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>cL(`Tree${n+1}`,e,t,`conifer`)));let r=nL(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...fL(r,t,[.6,1.8]));break}case`plains`:{let e=nL(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>cL(`Tree${n+1}`,e,t,`broadleaf`)));let r=nL(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...fL(r,t,[.4,1.2]));break}case`desert`:{let e=nL(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>cL(`Tree${n+1}`,e,t,`dead`)));let r=nL(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...fL(r,t,[.5,1.6]));break}case`meadow`:{let e=$(r*.09),a=nL(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>lL(`Carpet${r+1}`,n,t,e,30)));let o=$(r*.07),s=nL(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>dL(`Flowers${n+1}`,e,t,o,`sparse`)));let c=nL(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>cL(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=nL(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...fL(l,t,[.3,.9]));break}case`forest`:{let e=$(r*.12),a=r/2-8,o=dn(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=nL(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)=>cL(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(cL(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=nL(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>cL(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=nL(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>cL(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=nL(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>cL(`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=$(tI(e.x+Math.cos(o)*s,-a,a)),u=$(tI(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=nL(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>lL(`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=$(tI(r.x+Math.cos(o)*s,-a,a)),l=$(tI(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))]}})}nL(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(gL),roughness:1},castShadow:!0}})});let _=nL(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...fL(_,t,[.3,1],pL));let v=$(e*.75),y=nL(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-$(v/Math.SQRT2)});i.push(...y.map((e,n)=>lL(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=$(e*.45),x=nL(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-$(b/Math.SQRT2)});i.push(...x.map((e,n)=>dL(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=nL(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>cL(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:aL})));let a=$(r*.09),o=nL(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>lL(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=nL(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...fL(s,t,[.4,1.4]));let c=nL(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>cL(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=nL(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>cL(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:oL})));let r=nL(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...fL(r,t,[.5,1.8],mL));break}case`wetland`:{let e=$(r*.08),a=nL(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>uL(`Reeds${r+1}`,n,t,e,4)));let o=$(r*.08),s=nL(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>lL(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=nL(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>cL(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=nL(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>cL(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=nL(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...fL(u,t,[.3,1],pL));break}case`volcanic`:{let e=nL(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>cL(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=nL(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...fL(r,t,[.4,1.8],hL)),nL(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 vL(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var yL={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:[...nI]},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:[...qI]},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:[...bI]},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}}}},bL={arena:sI,terrain:$I,maze:DI,maze2d:RI,dungeon2d:hI,platforms2d:VI};function xL(e,t){let n=bL[e];if(!n){let t=Object.keys(bL);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 SL(e){return Object.entries(yL).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function CL(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 wL(){return Math.floor(Math.random()*1e6)}var TL=[],EL=new Map,DL=null;function OL(e){let t=document.querySelector(`#generate`);t&&(jL(e),t.removeAttribute(`hidden`))}function kL(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function AL(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&kL()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,kL),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,kL),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>ML(e)))}function jL(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`;TL=SL(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=QP({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=NL(QP({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of TL){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=NL(`seed`);DL=document.createElement(`input`),DL.type=`number`,DL.step=`1`,DL.value=String(wL());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=QP({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{DL&&(DL.value=String(wL()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(DL,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=TL.find(e=>e.name===o.value)??TL[0];if(e){s.textContent=e.meta.description,c.textContent=``,EL=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=NL(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??``}`);EL.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function ML(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=TL.find(e=>e.name===n?.value);if(!r||!DL)return;let i={seed:CL({type:`number`,default:wL(),min:0},DL.value)};for(let[e,t]of EL){let n=r.meta.params[e];n&&(i[e]=CL(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=xL(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=QP({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),DL&&(DL.value=String(wL())),kL()}function NL(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var PL={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 mN=[`type`,`sunPosition`,`elevationDeg`,`azimuthDeg`,`turbidity`,`rayleigh`],hN=[`color`,`near`,`far`],gN=[`coverage`,`density`,`base`,`top`,`color`,`shadeColor`,`speed`,`scale`],_N=[`threshold`,`strength`],vN=[`vignette`,`saturation`,`contrast`],yN=[`mapSize`,`radius`,`static`],bN=[1024,2048],xN=2,SN=1,CN=50,wN=800,TN=`#cfd8e0`,EN=Math.PI/180;function DN(e){return{exposure:jN(e?.exposure),sky:MN(e?.sky),fog:NN(e?.fog,e?.sky!==void 0),clouds:PN(e?.clouds),bloom:FN(e?.bloom),post:IN(e?.post),shadows:LN(e?.shadows)}}function ON(e,t){let n=(90-e)*EN,r=t*EN;return[Math.sin(n)*Math.sin(r),Math.cos(n),Math.sin(n)*Math.cos(r)]}function kN(e){let[t,n,r]=e.sunPosition,i=Math.hypot(t,n,r)||1;return[t/i,n/i,r/i]}function AN(e){let t=[191,213,232],n=[233,228,217],r=[242,201,150],i=BN((e.turbidity-xN)/8),a=kN(e),o=BN((18-Math.asin(zN(a[1],-1,1))/EN)/18)*.8,s=e=>Math.round(VN(VN(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 jN(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 MN(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(!mN.includes(e))throw new N(`BAD_FORMAT`,`environment.sky has unknown key '${e}'. Valid keys: [${mN.join(`, `)}].`,{prop:`sky`,validOptions:mN});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=RN(t.elevationDeg,32,`sky.elevationDeg`),n=RN(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=ON(e,n)}let i=RN(t.turbidity,xN,`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=RN(t.rayleigh,SN,`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 NN(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(!hN.includes(e))throw new N(`BAD_FORMAT`,`environment.fog has unknown key '${e}'. Valid keys: [${hN.join(`, `)}].`,{prop:`fog`,validOptions:hN});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=RN(n.near,CN,`fog.near`),i=RN(n.far,wN,`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?``:TN),near:r,far:i}}function PN(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(!gN.includes(e))throw new N(`BAD_FORMAT`,`environment.clouds has unknown key '${e}'. Valid keys: [${gN.join(`, `)}].`,{prop:`clouds`,validOptions:gN});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=RN(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=RN(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=RN(t.base,120,`clouds.base`),a=RN(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=RN(t.speed,1,`clouds.speed`),s=RN(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 FN(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(!_N.includes(e))throw new N(`BAD_FORMAT`,`environment.bloom has unknown key '${e}'. Valid keys: [${_N.join(`, `)}].`,{prop:`bloom`,validOptions:_N});let n=RN(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=RN(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 IN(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(!vN.includes(e))throw new N(`BAD_FORMAT`,`environment.post has unknown key '${e}'. Valid keys: [${vN.join(`, `)}].`,{prop:`post`,validOptions:vN});let n=RN(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=RN(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=RN(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 LN(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(!yN.includes(e))throw new N(`BAD_FORMAT`,`environment.shadows has unknown key '${e}'. Valid keys: [${yN.join(`, `)}].`,{prop:`shadows`,validOptions:yN});let n=t.mapSize===void 0?2048:t.mapSize;if(!bN.includes(n))throw new N(`BAD_FORMAT`,`environment.shadows.mapSize must be one of [${bN.join(`, `)}], got ${JSON.stringify(t.mapSize)}.`,{prop:`shadows`,validOptions:bN.map(String)});let r=RN(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 RN(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 zN(e,t,n){return Math.min(Math.max(e,t),n)}function BN(e){return zN(e,0,1)}function VN(e,t,n){return e+(t-e)*n}var HN=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,UN={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 WN(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=UN[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(UN).join(`, `)}.`);return`${HN}/${t}`}return null}var GN=75,KN=class{scene;ambient=new xu(`#ffffff`,0);envKey=null;config=DN(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new To(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new K;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?kN(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 To?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=DN(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)*qN(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=GN,t.top=GN,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 To(`#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=WN(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new fN().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 pN,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 xd(t),r=new Eo;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?AN(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 qN(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 JN=new Vo,YN=new Vo,XN=new G,ZN=new G,QN=new U,$N=Array.from({length:8},()=>new U),eP=.4,tP=new Float32Array(72),nP=[[0,0,0],[1,0,0],[1,0,1],[0,0,1],[0,1,0],[1,1,0],[1,1,1],[0,1,1]],rP=[[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 iP(e,t){t.makeEmpty(),XN.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&&(YN.copy(r).applyMatrix4(ZN.multiplyMatrices(XN,e.matrixWorld)),t.union(YN))})}function aP(e){if(!(e instanceof Ah))return null;let t=e._ensureObject3D();t.updateWorldMatrix(!0,!0),iP(t,JN);let n=!0;JN.isEmpty()?(n=!1,QN.setFromMatrixPosition(t.matrixWorld),JN.min.set(QN.x-eP,QN.y-eP,QN.z-eP),JN.max.set(QN.x+eP,QN.y+eP,QN.z+eP)):JN.expandByScalar(.02);let{min:r,max:i}=JN;for(let e=0;e<8;e++){let[a,o,s]=nP[e],c=$N[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 rP){let n=$N[e],r=$N[t];tP[a++]=n.x,tP[a++]=n.y,tP[a++]=n.z,tP[a++]=r.x,tP[a++]=r.y,tP[a++]=r.z}return tP}function oP(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function sP(){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 cP(e,t,n,r,i){let a=i??sP();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,mP(e,t,o),_P(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 pP(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var lP=new U,uP=new U,dP=new U,fP=new U;function pP(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(uP),t.getWorldDirection(dP),fP.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[uP.x,uP.y,uP.z],forward:[dP.x,dP.y,dP.z],up:[fP.x,fP.y,fP.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(lP),t._setSpatialPose({position:[lP.x,lP.y,lP.z],listener:n})}function mP(e,t,n){let r=t;if(e instanceof Ah){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 Xk&&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 Pk&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof UE&&n.cameras.push(e),r=i}else oP(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)mP(t,r,n);if(e instanceof Ah){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,gP(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var hP=new WeakSet;function gP(e){if(hP.has(e))return;hP.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof UE)&&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 _P(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&&_P(i,t)}}var vP=class{viewOverride=null;overrideCam=new pu(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new Eo;environment=new KN(this.threeScene);engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;warmCamera=null;deferCompile=!1;syncScratch=sP();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 yw(this.engine);let t=vn(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 hm({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 YM,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new Hc(new J,new Ac({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new Hc(new J,new Ac({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?aP(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 tv(`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(yP,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}=cP(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(xP.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(DP),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(bP);(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=CP.setFromMatrixPosition(o.matrixWorld).sub(wP.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(bP),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 Ba(i,a,{type:gr,samples:4}),this.bloomBrightTarget=new Ba(o,s,{type:gr}),this.bloomBlurTarget=new Ba(o,s,{type:gr})),!this.bloomBrightScene){let e=tN();this.bloomBrightScene=new Eo,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=nN();this.bloomBlurScene=new Eo,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=rN();this.bloomCompositeScene=new Eo,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(bP),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 $c(i,a);e.type=hr,this.cloudsTarget=new Ba(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Ba(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Ba(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=lN();this.cloudsScene=new Eo,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=cN();this.cloudsBlurScene=new Eo,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=uN();this.cloudsCompositeScene=new Eo,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(bP),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 $c(r,i);e.type=hr,this.causticsTarget=new Ba(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=th();this.causticsScene=new Eo,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?(SP.set(e,t,n).project(r),{x:(SP.x+1)/2*this.lastSize.w,y:(1-SP.y)/2*this.lastSize.h,behind:SP.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;kP.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),OP.setFromCamera(kP,n);let r=OP.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(EP),{x:EP.x,y:EP.y,z:EP.z}):null}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(TP):TP.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()}},yP=12,bP=new V,xP=new U,SP=new U,CP=new U,wP=new U,TP=new H,EP=new U,DP=new U,OP=new qu,kP=new V;async function AP(e){let t=async(t,n)=>{e.onProgress&&(e.onProgress(t,n),typeof requestAnimationFrame==`function`&&await new Promise(e=>{requestAnimationFrame(()=>setTimeout(e,0))}))};qM(),(e.gameplay??!0)&&G_();for(let[t,n]of Object.entries(e.behaviors??{}))it(t,n,{replace:!0});let n=new kt({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),r=jP(e.scene),i=An(jP(r),{resolveScene:e.resolveScene,engine:n});n.setScene(i),await t(.06,`scene`);let a=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&MP(i.root))&&(a=await AT(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(NP(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=qn(n,t,r),a=n.sceneChanged.connect(()=>{i?.dispose(),i=qn(n,t,r)});o.push(()=>{a(),i?.dispose()})}}let l=e._rendererFactory?e._rendererFactory(n,e.canvas):new vP({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=Mm(l),n=f.open??Am,i=async t=>{await AP({...e,scene:t})};await jm(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?wm():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 bm(async()=>{let{attachDebugOverlay:e}=await import(`./debug-DN9X9G6z.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(){Nm([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 jP(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 MP(e){if(e instanceof jh)return!0;for(let t of e.children)if(MP(t))return!0;return!1}function NP(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 Rt&&(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 PP=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>rT,WATER_CUTOUT_MAX:()=>4,WATER_MAX_RIPPLES:()=>8,createGame3D:()=>AP,enablePhysics3D:()=>AT}),FP=new WeakMap,IP=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 FP.get(e)??null}static async create(t,n={}){await FP.get(t)?.dispose();let r=n.transport??await VP(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 FP.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]),FP.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3;let n=LP(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=zP(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 LP(e,t=!1){let n=[];if(RP(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 RP(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)RP(n,t)}function zP(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 BP(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 VP(e){let{createAgent8Server:t}=await bm(async()=>{let{createAgent8Server:e}=await import(`./agent8-CeeI7P_0.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var HP=class extends Nt{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=IP.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=jn(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=UP(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=t.sync;i&&BP(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 UP(e){return e.replace(/[/%]/g,`_`)||`remote`}function WP(){_n(),R(HP)}function GP(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}var KP=GP()?.getItem(`incanto-editor-lang`)??`en`,qP=new Set;function JP(){return KP}function YP(e){KP=e,GP()?.setItem(`incanto-editor-lang`,e);for(let e of qP)e()}function XP(e){qP.add(e)}function ZP(e){return e[KP]}var QP={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`]}},$P={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 eF(e){let t=QP[$P[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 tF(){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 nF=[{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`]}],rF=new Set,iF=null,aF=null;function oF(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 sF(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 cF(e){let t=e.assets.length;for(let n of e.folders.values())t+=cF(n);return t}function lF(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(TF(i.type??``)),s.addEventListener(`click`,e=>{e.stopPropagation(),EF(s,i.type??``)}),iF===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;o.appendChild(oF(a,r=>{iF=null,t.renameAssetKey(e,n+r)},()=>{iF=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(),iF=e,t.selectAsset(e)}),o.append(s,c),o.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(o)},o=(e,n)=>{let r=rF.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(tF());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),aF===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,oF(e.name,n=>{aF=null,t.renameGroup(e.path,i+n)},()=>{aF=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(),aF=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${cF(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{rF.has(e.path)?rF.delete(e.path):rF.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=sF(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function uF(e,t,n,r){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(AF(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(bF(`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 mF(e,t,r);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(AF(`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(xF(`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(AF(`ASSET — ${String(a[i].type??`?`)}`)),e.appendChild(DF(i)),e.appendChild(OF(t,i)),e.appendChild(dF(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 dF(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=xF(`name`,o,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==o&&e.renameAssetKey(n,s+r)});kF(c.querySelector(`input`)),a.appendChild(c);let l=xF(`url`,String(i.url??``),t=>{e.mutate(()=>{i.url=t.trim()})}),u=l.querySelector(`input`);if(r&&u){let t=gF(String(i.type??``));l.appendChild(yF(()=>t,`asset url`,r,t=>{u.value=t,e.mutate(()=>{i.url=t})},()=>vF(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(fF(e,i,t,n));return a.appendChild(pF(e,i)),a}function fF(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]=SF(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 pF(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]=SF(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function mF(e,t,n){return e.appendChild(AF(`NEW ASSET`)),e.appendChild(hF(t,n)),!0}function hF(e,t){let n=document.createElement(`div`);n.className=`asset-editor`;let r=document.createElement(`select`);for(let e of nF){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,r.appendChild(t)}n.appendChild(bF(`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(bF(`group`,i)),n.appendChild(o);let c=document.createElement(`input`);c.placeholder=`coin`,c.className=`mono`,kF(c),n.appendChild(bF(`key`,c));let l=document.createElement(`input`);l.placeholder=`/textures/coin.png · https://… · data:…`,l.className=`mono`;let u=bF(`url`,l);t&&u.appendChild(yF(()=>gF(r.value),`new asset`,t,e=>{l.value=e,c.value.trim()||(c.value=_F(e))},()=>vF(gF(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 gF(e){return e===`model`||e===`animation`?`model`:e===`audio`?`audio`:e===`texture`||e===`spritesheet`?`image`:`any`}function _F(e){return((e.split(/[?#]/)[0]??``).split(`/`).pop()??``).replace(/\.[^.]+$/,``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function vF(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 yF(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 bF(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 xF(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),bF(e,r)}function SF(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 CF={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`},wF={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 TF(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`,CF[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function EF(e,t){document.querySelector(`.balloon`)?.remove();let n=wF[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=ZP(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 DF(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 OF(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 kF(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function AF(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 jF=window.parent!==window,MF=new URLSearchParams(window.location.search).get(`parentOrigin`),NF=!1;function PF(e){if(jF){if(!MF){NF||(NF=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,MF)}}var FF={ready(e,t,n){PF({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){PF({type:`incanto-editor:open`,input:e,output:t})},change(e){PF({type:`incanto-editor:change`,dirty:e})},save(e,t,n){PF({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){PF({type:`incanto-editor:error`,message:e})}},IF=[[`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`]],LF=[...IF,[`Other`,e=>IF.every(([,t])=>!t(e))]],RF={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}),zF=[{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를 발산합니다.`})]}],BF=`overview`,VF=null;function HF(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),GF()}function UF(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function WF(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&UF()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,UF))}function GF(){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${BF===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{BF=t,VF=null,GF()}),e.appendChild(r)};n(`overview`,ZP({en:`Overview`,ko:`개요`}));for(let e of zF)n(e.id,ZP(e.label));if(t.textContent=``,BF===`overview`){KF(t);return}let r=zF.find(e=>e.id===BF);r&&qF(t,r)}function KF(e){let t=document.createElement(`h2`);t.textContent=ZP(RF.title),e.appendChild(t);for(let t of RF.sections){let n=document.createElement(`h3`);n.textContent=ZP(t.heading);let r=document.createElement(`p`);r.textContent=ZP(t.text),e.append(n,r)}}function qF(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=ZP(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${VF===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(eF(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=ZP(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{VF=VF===n.type?null:n.type,GF()}),t.appendChild(r),VF===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=ZP(t),e.appendChild(n)}e.appendChild(JF(n.type)),t.appendChild(e)}e.appendChild(t)}}function JF(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[ZP({en:`prop`,ko:`prop`}),ZP({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 YF(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 XF(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??ZF(r),roughness:1},castShadow:!0}}}function ZF(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function QF(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 $F(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function eI(e,t,n){return Math.min(Math.max(e,t),n)}var tI=[`boxes`,`ruins`,`garden`],nI=.5,rI=.1,iI=2,aI={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 oI(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!tI.includes(o))throw new N(`BAD_FORMAT`,`generateArena theme must be one of [${tI.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...tI]});let s=aI[o],c=new P(t),l=[YF(`Floor`,[n,rI,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+nI*2,i,nI],f=[nI,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(YF(`Wall1`,d,[0,u,-(r+nI)/2],p),YF(`Wall2`,d,[0,u,(r+nI)/2],p),YF(`Wall3`,f,[-(n+nI)/2,u,0],p),YF(`Wall4`,f,[(n+nI)/2,u,0],p)),o===`ruins`?l.push(...cI(c,s,n,r,i,a)):l.push(...sI(c,s,n,r,i,a,o)),o===`garden`&&l.push(...lI(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 sI(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-iI),n/2-iI)),u=$(e.range(-(r/2-iI),r/2-iI));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(YF(`Obstacle${o}`,a,[l,$(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function cI(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-iI*2,u=r-iI*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(YF(`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 lI(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 uI=32,dI=[4,8],fI=`#332f3a`,pI=`#6b6357`;function mI(e){let{seed:t,rooms:n=5}=e,[r,i]=$F(e.size,[960,720]),a=Math.max(8,Math.floor(r/uI)),o=Math.max(8,Math.floor(i/uI)),s=new P(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(dI[0],dI[1]),t=s.int(dI[0],dI[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=>hI(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]=gI(c[e-1]),[r,i]=gI(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*uI)/2,m=-(o*uI)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*uI,m+(t.y+t.h/2)*uI],size:[t.w*uI,t.h*uI],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,fI));for(let e of d)g.push(h(e.name,e.rect,fI));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*uI,uI];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*uI,m+(e+.5)*uI],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:pI}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function hI(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 gI(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var _I=[[0,-1],[1,0],[0,1],[-1,0]];function vI(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 _I){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 yI=[`stone`,`hedge`,`canyon`],bI=.1,xI=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,SI=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,CI={stone:{wall:{color:`#e8e2d8`,map:`${xI}/blocks.png`,normalMap:`${xI}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${SI}/stone.png`,normalMap:`${SI}/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:`${SI}/grass.png`,normalMap:`${SI}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${SI}/grass.png`,normalMap:`${SI}/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:`${SI}/stone.png`,normalMap:`${SI}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${SI}/sand.png`,normalMap:`${SI}/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 wI(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 TI=10;function EI(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!yI.includes(o))throw new N(`BAD_FORMAT`,`generateMaze theme must be one of [${yI.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...yI]});let s=CI[o],c=new P(t),l=vI(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=[YF(`Floor`,[f,bI,p],[0,-.1/2,0],{material:wI(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(YF(`Wall${_}`,[r,a,i],[$((t+n/2)*i-f/2),$(a/2),$((e+.5)*i-p/2)],{material:wI(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...DI(g,i,a,f,p,s.cap)),h.push(...OI(c,l,i,a,m,s)),o===`hedge`?(h.push(...MI(c,g,i,a,m)),h.push(...NI(c,l,i,m,n,r))):o===`canyon`&&h.push(...PI(c,g,i,a,m)),h.push(...AI(l,i,a,m,s)),h.push(...QF(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 DI(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 OI(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(TI,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(kI(`Pillar${t}`,c,p,d,f,a))}return l}function kI(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,$(i/2),n],material:{...wI(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function AI(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 kI(`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:{...wI(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var jI=10;function MI(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,jI).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 NI(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 PI(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=XF(s,c,l,e,[.3,$(n*.35)],`#8f7355`),d=u.props?.position;d[1]=$(d[1]+r),a.push(u)}return a}var FI=`#23222b`,II=`#5f6672`;function LI(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=vI(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:FI}}],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:II}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var RI=16,zI=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function BI(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(VI(e,u,d,l,s.pick(zI))),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 VI(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,RI]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,RI],color:i}}]}}var HI=[3,5],UI=3,WI={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function GI(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=$F(e.area,[60,60]),o=new P(t),s=[];for(let e=1;e<=n;e++){let t=o.int(HI[0],HI[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:WI}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[$(o.range(-i/2,i/2)),$(r+o.range(-3,UI)),$(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,children:s}}var KI=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],qI=128,JI=20,YI=.8,XI=.12,ZI={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 QI(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=ZI[n];if(!a)throw new N(`BAD_FORMAT`,`generateTerrain theme must be one of [${KI.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...KI]});let o=Math.max(2,Math.round(e.resolution??qI)),s=e.maxHeight||a.maxHeight,c=new P(t),l=n===`island`,u=e=>Uw({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=eL(d)-JI,t=d.maxHeight-d.minHeight,n=d.minHeight+XI*t;if(e+YI<=n)break;let r=JI-YI,i=eL(d)-d.minHeight-XI*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===qI?{}:{resolution:o}}}]}],p=n===`wetland`;if(l)f.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,$I(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(...gL(n,c,d,r)),l&&f.push(GI({seed:c.int(1,1e9),count:6,area:r,altitude:Math.round(d.maxHeight+12)})),f.push(...QF(r).map((e,t)=>_L(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:f}}function $I(e){let t=eL(e)-JI,n=e.minHeight+XI*(e.maxHeight-e.minHeight);return $(Math.max(Math.min(t+YI,n),t+.55))}function eL(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 tL(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 nL=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],rL=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],iL={canopy:`#9aa052`,trunk:`#8a6a44`},aL={canopy:`#39513f`,trunk:`#5a5650`};function oL(e,t){return e===`conifer`?t.pick(nL):e===`broadleaf`?t.pick(rL):null}function sL(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=oL(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 cL(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 lL(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 uL(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 dL(e,t,n,r){return e.map((e,i)=>{let a=XF(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=$(o[1]+e.y),a})}function fL(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 pL(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 mL(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 hL=[`#6f5b41`,`#7a644a`,`#665439`];function gL(e,t,n,r){let i=[];switch(e){case`island`:{let e=tL(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>sL(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=tL(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>sL(`Tree${n+1}`,e,t,`conifer`)));let r=tL(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...dL(r,t,[.6,1.8]));break}case`plains`:{let e=tL(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>sL(`Tree${n+1}`,e,t,`broadleaf`)));let r=tL(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...dL(r,t,[.4,1.2]));break}case`desert`:{let e=tL(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>sL(`Tree${n+1}`,e,t,`dead`)));let r=tL(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...dL(r,t,[.5,1.6]));break}case`meadow`:{let e=$(r*.09),a=tL(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>cL(`Carpet${r+1}`,n,t,e,30)));let o=$(r*.07),s=tL(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>uL(`Flowers${n+1}`,e,t,o,`sparse`)));let c=tL(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>sL(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=tL(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...dL(l,t,[.3,.9]));break}case`forest`:{let e=$(r*.12),a=r/2-8,o=dn(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=tL(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)=>sL(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(sL(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=tL(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>sL(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=tL(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>sL(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=tL(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>sL(`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=$(eI(e.x+Math.cos(o)*s,-a,a)),u=$(eI(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=tL(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>cL(`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=$(eI(r.x+Math.cos(o)*s,-a,a)),l=$(eI(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))]}})}tL(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(hL),roughness:1},castShadow:!0}})});let _=tL(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...dL(_,t,[.3,1],fL));let v=$(e*.75),y=tL(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-$(v/Math.SQRT2)});i.push(...y.map((e,n)=>cL(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=$(e*.45),x=tL(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-$(b/Math.SQRT2)});i.push(...x.map((e,n)=>uL(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=tL(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>sL(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:iL})));let a=$(r*.09),o=tL(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>cL(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=tL(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...dL(s,t,[.4,1.4]));let c=tL(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>sL(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=tL(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>sL(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:aL})));let r=tL(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...dL(r,t,[.5,1.8],pL));break}case`wetland`:{let e=$(r*.08),a=tL(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>lL(`Reeds${r+1}`,n,t,e,4)));let o=$(r*.08),s=tL(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>cL(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=tL(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>sL(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=tL(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>sL(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=tL(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...dL(u,t,[.3,1],fL));break}case`volcanic`:{let e=tL(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>sL(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=tL(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...dL(r,t,[.4,1.8],mL)),tL(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 _L(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var vL={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:[...tI]},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:[...KI]},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:[...yI]},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}}}},yL={arena:oI,terrain:QI,maze:EI,maze2d:LI,dungeon2d:mI,platforms2d:BI};function bL(e,t){let n=yL[e];if(!n){let t=Object.keys(yL);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 xL(e){return Object.entries(vL).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function SL(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 CL(){return Math.floor(Math.random()*1e6)}var wL=[],TL=new Map,EL=null;function DL(e){let t=document.querySelector(`#generate`);t&&(AL(e),t.removeAttribute(`hidden`))}function OL(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function kL(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&OL()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,OL),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,OL),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>jL(e)))}function AL(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`;wL=xL(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=ZP({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=ML(ZP({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of wL){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=ML(`seed`);EL=document.createElement(`input`),EL.type=`number`,EL.step=`1`,EL.value=String(CL());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=ZP({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{EL&&(EL.value=String(CL()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(EL,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=wL.find(e=>e.name===o.value)??wL[0];if(e){s.textContent=e.meta.description,c.textContent=``,TL=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=ML(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??``}`);TL.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function jL(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=wL.find(e=>e.name===n?.value);if(!r||!EL)return;let i={seed:SL({type:`number`,default:CL(),min:0},EL.value)};for(let[e,t]of TL){let n=r.meta.params[e];n&&(i[e]=SL(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=bL(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=ZP({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),EL&&(EL.value=String(CL())),OL()}function ML(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var NL={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,8 +8420,8 @@ 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] }`}},FL=null;function IL(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=PL[r.dataset.help??``];if(!i)return;if(!e.hidden&&FL===r){e.hidden=!0;return}FL=r,e.textContent=``;let a=document.createElement(`h4`);a.textContent=QP(i.title);let o=document.createElement(`div`);if(o.textContent=QP(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}=LL(r.getBoundingClientRect(),{width:s.width,height:s.height},{width:innerWidth,height:innerHeight});e.style.left=`${c}px`,e.style.top=`${l}px`})}function LL(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 RL(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 zL=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 BL(e){let t=e.connections;return Array.isArray(t)?t:[]}function VL(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=HL(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 HL(e,t){let n=e;for(let e of t)n=n?.children?.[e];return n??null}function UL(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 WL(e,t){let n=e.root,r=e=>{if(typeof e!=`string`)return!1;let r=VL(n,e);return r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n])},i=[],a=[];return BL(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 GL(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 KL(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 qL)r.delete(e);return[...r].sort()}var qL=new Set([`addChild`,`removeChild`,`addToGroup`,`removeFromGroup`,`isInGroup`,`getNode`,`getNodeOrNull`,`getPath`,`getRoot`,`find`,`findAll`,`on`,`off`,`once`,`emit`,`declareSignal`,`update`,`fixedUpdate`,`toJSON`,`diagnose`]);function JL(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:UL(e,o),label:UL(e,o)}),n(r,o)})};return n(e,[]),t}function YL(e,t){Array.isArray(e.connections)||(e.connections=[]);let n=e.connections;return n.push(t),n.length-1}function XL(e,t,n){let r=BL(e)[t];r&&Object.assign(r,n)}function ZL(e,t){let n=BL(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}=WL(e.working,t),s=UL(n,t);i.appendChild($L(QP({en:`emits (${a.length})`,ko:`보냄 (${a.length})`})));for(let t of a)i.appendChild(eR(e,t,`out`));if(i.appendChild(tR(e,r,s)),o.length>0){i.appendChild($L(QP({en:`receives (${o.length})`,ko:`받음 (${o.length})`})));for(let t of o)i.appendChild(eR(e,t,`in`))}return i}function $L(e){let t=document.createElement(`div`);return t.className=`conn-group`,t.textContent=e,t}function eR(e,{index:t,conn:n},r){let i=e.working.root,a=document.createElement(`div`);a.className=`conn-row`;let o=e.nodeAt(VL(i,String(n.from??``))??[-1]),s=r===`out`?`to`:`from`,c=String(n[s]??``),l=VL(i,c)===null,u=nR(GL(o),String(n.signal??``),n=>{e.mutate(()=>XL(e.working,t,{signal:n}))});u.title=QP({en:`signal`,ko:`시그널`});let d=document.createElement(`span`);d.className=`conn-arrow`,d.textContent=r===`out`?`→`:`←`;let f=nR(JL(i).map(e=>e.path),c,n=>{e.mutate(()=>XL(e.working,t,{[s]:n}))});f.title=QP({en:s,ko:s===`to`?`대상`:`출처`}),l&&f.classList.add(`dangling`);let p=KL(e.nodeAt(VL(i,String(n.to??``))??[-1])),m=n=>{e.mutate(()=>XL(e.working,t,{handler:n.trim()}))},h;if(p.length>0){let e=nR(p,String(n.handler??``),m);e.title=QP({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=QP({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=QP({en:`remove this connection`,ko:`이 연결 삭제`}),g.addEventListener(`click`,()=>{e.mutate(()=>ZL(e.working,t))}),a.append(u,d,f,h,g),l){let e=document.createElement(`div`);e.className=`conn-warn`,e.textContent=QP({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 tR(e,t,n){let r=GL(t),i=document.createElement(`div`);i.className=`conn-add`;let a=document.createElement(`button`);return a.type=`button`,a.textContent=QP({en:`+ connect`,ko:`+ 연결`}),a.disabled=r.length===0,r.length===0&&(a.title=QP({en:`this node declares no signals`,ko:`이 노드는 시그널을 선언하지 않습니다`})),a.addEventListener(`click`,()=>{let i=r[0]??``,a={from:n,signal:i,to:n,handler:KL(t)[0]??`on${i.charAt(0).toUpperCase()}${i.slice(1)}`};e.mutate(()=>{YL(e.working,a)})}),i.appendChild(a),i}function nR(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 rR(e,t,n,r){return{cx:Math.floor((n-e.x)/t),cy:Math.floor((r-e.y)/t)}}function iR(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 aR(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 oR=zL;function sR(e){return(e.kind===`foliage`||e.kind===`tile`)&&!e.animation}function cR(e,t,n){if(e.textContent=``,t.selection===null){uR(e,t,n);return}let r=t.nodeAt(t.selection);r&&yR(e,t,r,n)}var lR=[`connections`,`input`,`multiplayer`];function uR(e,t,n){e.appendChild(GR(`scene`)),e.appendChild(ZR(`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(qR(`dimension`,r)),e.appendChild(GR(`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($R(`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(GR(`environment`)),dR(e,t),e.appendChild(GR(`constants`)),zR(e,t,n),e.appendChild(GR(`draw order bands`)),RR(e,t),e.appendChild(GR(`advanced`));for(let n of lR)e.appendChild(tz(n,t.working[n],e=>{t.mutate(()=>{e===void 0?delete t.working[n]:t.working[n]=e})}))}function dR(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(fR(`background`,n.background??``,e=>{r({background:e===``?void 0:e})})),e.appendChild(fR(`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(QR(`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(qR(`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(qR(`pixel ratio`,s))}function fR(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),qR(e,r)}function pR(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(qR(`enabled`,l)),a){n.appendChild(fR(`murk color`,String(o.color??``),e=>c(`color`,e))),n.appendChild(QR(`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(qR(`caustics`,e))}return n}function mR(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(fR(`color`,String(a.color??``),e=>o(`color`,e))),r.appendChild(vR(`roughness`,Number(a.roughness??1),e=>o(`roughness`,e))),r.appendChild(vR(`metalness`,Number(a.metalness??0),e=>o(`metalness`,e))),r.appendChild(fR(`emissive`,String(a.emissive??``),e=>o(`emissive`,e))),r.appendChild(vR(`emissive power`,Number(a.emissiveIntensity??1),e=>o(`emissiveIntensity`,e===1?void 0:e),2)),r.appendChild(vR(`opacity`,Number(a.opacity??1),e=>o(`opacity`,e===1?void 0:e))),r.appendChild(vR(`clearcoat`,Number(a.clearcoat??0),e=>o(`clearcoat`,e===0?void 0:e))),r.appendChild(vR(`clearcoat rough`,Number(a.clearcoatRoughness??0),e=>o(`clearcoatRoughness`,e===0?void 0:e))),r.appendChild(vR(`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(qR(`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(qR(`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(qR(`draw on top (decal)`,l)),r.appendChild(kR(`map (texture)`,String(a.map??``),AR(e=>sR(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(kR(`normal map`,String(a.normalMap??``),AR(e=>sR(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=$R(`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 hR=new Set([`animationLoop`,`animationSpeed`,`animationOffset`,`animationUpper`,`animationUpperLoop`,`upperBodyRoot`]);function gR(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(kR(`clip`,s,n.animationsForSelection().map(e=>({label:e,value:e,hint:e.startsWith(`$`)?`scene asset`:`clip in this model`})),n=>TR(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(_R(e,t,n,r)),i}i.appendChild(VR(e,t,`animationLoop`,r.animationLoop?.default??!0,void 0,`loop`));let c=vR(`speed`,Number(t.props?.animationSpeed??1),n=>TR(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=VR(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(_R(e,t,n,r)),i}function _R(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(kR(`clip`,String(t.props?.animationUpper??``),n.animationsForSelection().map(e=>({label:e,value:e})),n=>TR(e,t,`animationUpper`,n.trim(),``),{placeholder:`empty = off`,ctx:n})),i.appendChild(VR(e,t,`animationUpperLoop`,r.animationUpperLoop?.default??!1,void 0,`loop`)),i.appendChild(VR(e,t,`upperBodyRoot`,r.upperBodyRoot?.default??`Spine`,void 0,`root bone`)),i}function vR(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),qR(e,a)}function yR(e,t,n,r){if(e.appendChild(GR(n.type??`instance`)),e.appendChild(bR(n)),e.appendChild(ZR(`name`,n.name??``,e=>{e.trim()===``||t.selection===null||t.renameNode(t.selection,e.trim())})),n.type===`TileMap2D`&&r?.paint&&e.appendChild(ez(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(wR(t,n,o.default));else if(a===`material`)e.appendChild(mR(t,n,r));else if(n.type===`ModelInstance3D`&&a===`model`&&r)e.appendChild(kR(`model`,String(n.props?.model??``),r.modelRefs().map(e=>({label:e,value:e,hint:`scene asset`})),e=>TR(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(DR(`bone`,String(n.props?.bone??``),r.bonesForSelection(String(n.props?.target??``)),e=>TR(t,n,`bone`,e,``)));else if(n.type===`ModelInstance3D`&&a===`animation`&&r)e.appendChild(gR(t,n,r,i));else if(!(n.type===`ModelInstance3D`&&hR.has(a)))if((n.type===`Sprite3D`||n.type===`AnimatedSprite3D`)&&(a===`texture`||a===`sheet`))e.appendChild(kR(a===`sheet`?`sheet (image URL)`:`texture (image URL)`,String(n.props?.[a]??``),AR(e=>e.kind===`character`||e.kind===`item`),e=>TR(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(kR(`texture (atlas $ref)`,String(n.props?.texture??``),(r?.assetRefs?.([`texture`,`spritesheet`])??[]).map(e=>({label:e,value:e,hint:`scene asset`})),e=>TR(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(kR(`leaf texture`,String(n.props?.leafTexture??``),AR(e=>e.name.startsWith(`leaves_`)),e=>TR(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(kR(`texture base`,String(n.props?.textureBase??o.default??``),MR,e=>TR(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(NR(t,n,a,r,i))}else n.type===`AudioPlayer`&&a===`src`?e.appendChild(kR(`src (audio file)`,String(n.props?.src??``),jR(),e=>TR(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(PR(t,n)):n.type===`Water3D`&&a===`underwater`?e.appendChild(pR(t,n)):e.appendChild(VR(t,n,a,o.default,o.options))}if(e.appendChild(GR(`structure`)),e.appendChild(xR(t,n)),e.appendChild(SR(t,n)),e.appendChild(CR(t,n)),t.selection){let n=QL(t,t.selection);n&&(e.appendChild(GR(`connections`,`connections`)),e.appendChild(n))}}function bR(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 xR(e,t){let n=document.createElement(`label`);n.className=`field wide`;let r=document.createElement(`span`);r.append(`groups `,RL(`groups`));let i=document.createElement(`div`);i.className=`chips`;for(let n of t.groups??[])i.appendChild(KR(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 SR(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`script `,RL(`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(ZR(`name`,a.name??``,n=>{e.mutate(()=>{t.script.name=n.trim()})})),n.appendChild(tz(`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 CR(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`network `,RL(`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(qR(`mode`,a)),i?.mode===`owner`){let r=document.createElement(`div`);r.className=`chips`;for(let n of i.sync??[])r.appendChild(KR(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(QR(`throttle ms`,i.throttleMs??50,n=>{e.mutate(()=>{t.network.throttleMs=n})}))}return n}function wR(e,t,n){let r=document.createElement(`div`);r.className=`subcard`;let i=document.createElement(`div`);i.className=`subcard-head`,i.append(`collider `,RL(`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(qR(`shape`,l)),a.shape===`rect`||a.shape===`box`?r.appendChild($R(`size`,a.size??(s?[1,1,1]:[32,32]),e=>o({...a,size:e}))):a.shape===`circle`||a.shape===`sphere`?r.appendChild(QR(`radius`,a.radius??(s?.5:16),e=>o({...a,radius:e}))):a.shape===`capsule`&&(r.appendChild(QR(`radius`,a.radius??12,e=>o({...a,radius:e}))),r.appendChild(QR(`height`,a.height??16,e=>o({...a,height:e})))),a.shape&&r.appendChild($R(`offset`,a.offset??(s?[0,0,0]:[0,0]),e=>o({...a,offset:e}))),r}function TR(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 ER=0;function DR(e,t,n,r){let i=document.createElement(`input`);i.type=`text`,i.value=t;let a=`suggest-${ER++}`;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=qR(e,i);return s.appendChild(o),s}var OR=0;function kR(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`,t.title=[e.label,e.full??e.hint,e.value===e.label?null:e.value].filter(Boolean).join(`
8424
- `);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-${OR++}`,a.htmlFor=s.id,a}function AR(e){return oR.filter(e).map(e=>({label:e.name,value:e.url,hint:`${e.kind} · ${e.description}`,full:`${e.kind} · ${e.description}`}))}function jR(){return oR.filter(e=>e.kind===`audio`).map(e=>({label:e.name,value:e.url,hint:`audio · ${e.description}`,full:`audio · ${e.description}`}))}var MR=[{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 NR(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=oR.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 kR(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)}TR(e,t,n,`$${r.addAsset(a.name,i).replace(/^\$/,``)}`,``);return}TR(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))TR(e,t,r,i,void 0)}},ctx:r})}function PR(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=MD.filter(e=>i.has(e));TR(e,t,`varieties`,n.length===0||n.length===MD.length?[]:n,[])};for(let e of MD){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 MD)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 FR=[[`number`,()=>0],[`text`,()=>``],[`boolean`,()=>!1],[`color`,()=>`#ffffff`],[`vec2`,()=>[0,0]],[`vec3`,()=>[0,0,0]]];function IR(e,t){let n=0,r=e=>{if(bn(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 LR(e,t,n){let r=e=>{if(bn(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 RR(e,t){let n=t.working.orderGroups??{},r=Object.keys(n),i=e=>{t.mutate(()=>{Object.keys(e).length===0?delete t.working.orderGroups:t.working.orderGroups=e})},a=document.createElement(`div`);if(a.className=`hint`,a.textContent=`Built in: ${Object.entries(ht).map(([e,t])=>`${e} ${t}`).join(` · `)}`,e.appendChild(a),r.length===0){let t=document.createElement(`div`);t.className=`hint`,t.textContent=`No extra bands. Add one to sort between (or beyond) the built-ins — a band is the base offset, not just a name.`,e.appendChild(t)}for(let t of r){let r=document.createElement(`div`);r.className=`const-row`,r.appendChild(QR(t,n[t]??0,e=>i({...n,[t]:e})));let a=document.createElement(`button`);a.type=`button`,a.className=`const-del`,a.textContent=`✕`,a.title=`delete band "${t}"`,a.addEventListener(`click`,()=>{let e={...n};delete e[t],i(e)}),r.appendChild(a),e.appendChild(r)}let o=document.createElement(`div`);o.className=`const-add`;let s=document.createElement(`input`);s.type=`text`,s.placeholder=`new band name`;let c=document.createElement(`input`);c.type=`number`,c.placeholder=`base`,c.className=`band-base`;let l=document.createElement(`button`);l.type=`button`,l.textContent=`add`,l.addEventListener(`click`,()=>{let e=s.value.trim(),t=Number(c.value);!e||n[e]!==void 0||!Number.isFinite(t)||(i({...n,[e]:t}),s.value=``,c.value=``)}),o.append(s,c,l),e.appendChild(o)}function zR(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&&LR(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=IR(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(BR(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 FR){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,(FR.find(([e])=>e===u.value)?.[1]??(()=>0))()),l.value=``)}),c.append(l,u,d),e.appendChild(c)}function BR(e,t,n){let r=Be(t);if(r===`number`)return QR(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)),qR(e,r)}return r===`array`&&Array.isArray(t)&&t.every(e=>typeof e==`number`)?$R(e,t,e=>n(e)):r===`string`?ZR(e,String(t),e=>n(e)):tz(e,t,e=>n(e??null),JSON.stringify(t))}function VR(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=bn(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=HR(e,s,r);if(bn(o))return UR(n,o[`@const`],u,l,r);let d=e=>u.length>0?WR(e,u,l):e;if(s===`number`)return d(QR(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(qR(a??n,e))}if(s===`string`){if(i&&i.length>0){let t=n===`orderGroup`?XR(e):[];return d(JR(a??n,String(o??``),t.length>0?[...i,...t]:i,e=>l(e),n===`orderGroup`?t=>YR(t,e):void 0))}return d(ZR(a??n,String(o??``),e=>l(e)))}return s===`array`&&Array.isArray(r)&&r.length>0&&r.every(e=>typeof e==`number`)?d($R(n,o??r,e=>l(e))):tz(n,o===r?void 0:o,e=>{l(e===void 0?r:e)},JSON.stringify(r))}function HR(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 UR(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=qR(`🔗 ${e}`,a);return c.classList.add(`const-bound`),c}function WR(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.classList.add(`has-const-picker`),e.appendChild(r),e}function GR(e,t){let n=document.createElement(`div`);n.className=`section-title`,n.textContent=e,t&&n.appendChild(RL(t));let r=document.createElement(`span`);return r.className=`rule`,n.appendChild(r),n}function KR(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 qR(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 JR(e,t,n,r,i){let a=document.createElement(`select`);for(let e of n.includes(t)?n:[t,...n]){let n=document.createElement(`option`);n.value=e;let r=i?.(e);n.textContent=r?`${e} (${r})`:e,e===t&&(n.selected=!0),a.appendChild(n)}return a.addEventListener(`change`,()=>r(a.value)),qR(e,a)}function YR(e,t){let n={...ht,...t.working.orderGroups??{}}[e];return n===void 0?`unknown — sorts as default`:String(n)}function XR(e){return Object.keys(e.working.orderGroups??{})}function ZR(e,t,n){let r=document.createElement(`input`);return r.type=`text`,r.value=t,r.addEventListener(`change`,()=>n(r.value)),qR(e,r)}function QR(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)}),qR(e,i)}function $R(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)}),qR(e,r)}function ez(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 aR(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 tz(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=qR(e,i);return a.className=`field wide`,a}var nz=2.4,rz=1.35,iz=[0,.5,0];function az(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,rz,nz]}},{name:`Sun`,type:`DirectionalLight3D`,props:{position:[3,6,4],intensity:2.2}},{name:`Model`,type:`ModelInstance3D`,props:{model:`$model`,targetHeight:1}}]}}}var oz=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 kt({scheduler:()=>()=>{}}),this.renderer=new yP({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(An(az(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)*nz,rz,Math.cos(this.angle)*nz],target:iz},this.engine?.tick(n))};this.raf=requestAnimationFrame(t)}stop(){this.raf&&cancelAnimationFrame(this.raf),this.raf=0}},sz=`incanto-editor-v8-token`,cz=24;async function lz(e,t,n){if(!C(e.url)||n!==`spritesheet`&&n!==`texture`)return null;try{let n=oy(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 uz(){try{return localStorage.getItem(sz)??``}catch{return``}}function dz(e){try{e?localStorage.setItem(sz,e):localStorage.removeItem(sz)}catch{}}function fz(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 oz,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 lz(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=tF(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=uz();let o=document.createElement(`button`);o.type=`button`,o.className=`primary`,o.textContent=`connect`,o.addEventListener(`click`,()=>{dz(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:cz},uz()||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 pz=`.scene.json`;function mz(e){let t=e.split(`/`).pop()??e;return t.endsWith(pz)?t.slice(0,-11):t}function hz(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function gz(e,t){return{path:e,name:t,dirs:new Map,files:[]}}function _z(e){let t=gz(``,``);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=gz(e,t),r.dirs.set(t,n)),r=n}r.files.push(n)}return t}function vz(e){let t=e.files.length;for(let n of e.dirs.values())t+=vz(n);return t}function yz(e){let t=e.files.filter(e=>e.scene).length;for(let n of e.dirs.values())t+=yz(n);return t}function bz(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 xz(e){let t=hz(e??``).split(`/`).filter(Boolean),n=[],r=``;for(let e of t)r=r?`${r}/${e}`:e,n.push(r);return n}function Sz(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}=bz(e),c=vz(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:yz(t),open:l}),l&&o(t,r+1)}let c=[...e.files].sort((e,t)=>mz(e.rel).localeCompare(mz(t.rel)));for(let e of c)a.push({kind:`scene`,entry:e,label:mz(e.rel),folder:hz(e.rel),depth:r,current:e.rel===t.current})};return o(_z(r),0),a}function Cz(e,t){let n=new Set(xz(t));if(e.length<=24)for(let t of e)for(let e of xz(t.rel))n.add(e);return n}function wz(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 Tz(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 Ez(e,t=`new-level`){let n=e?e.kind===`folder`?e.path:e.folder:``;return n?`${n}/${t}${pz}`:`${t}${pz}`}function Dz(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}function Oz(e,t,n=()=>Date.now()){let r=[],i=new Set,a=[],o=0,s=!0,c=()=>{let c=t.current();if(a=Sz(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=Dz(`scene-caret`,``);n.kind===`folder`?(a.classList.add(`chevron`),n.open||a.classList.add(`collapsed`),a.appendChild(nF())):a.textContent=`◇`,i.append(a,Dz(`scene-name`,n.label),Dz(`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`,Tz(n.entry.modified,u),wz(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=Ez(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=Cz(r,t.current());else for(let e of xz(t.current()))i.add(e);s=!0,c(),e.search.focus(),e.search.select()}}}var kz=`
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] }`}},PL=null;function FL(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=NL[r.dataset.help??``];if(!i)return;if(!e.hidden&&PL===r){e.hidden=!0;return}PL=r,e.textContent=``;let a=document.createElement(`h4`);a.textContent=ZP(i.title);let o=document.createElement(`div`);if(o.textContent=ZP(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}=IL(r.getBoundingClientRect(),{width:s.width,height:s.height},{width:innerWidth,height:innerHeight});e.style.left=`${c}px`,e.style.top=`${l}px`})}function IL(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 LL(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 RL=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 zL(e){let t=e.connections;return Array.isArray(t)?t:[]}function BL(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=VL(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 VL(e,t){let n=e;for(let e of t)n=n?.children?.[e];return n??null}function HL(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 UL(e,t){let n=e.root,r=e=>{if(typeof e!=`string`)return!1;let r=BL(n,e);return r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n])},i=[],a=[];return zL(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 WL(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 GL(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 KL)r.delete(e);return[...r].sort()}var KL=new Set([`addChild`,`removeChild`,`addToGroup`,`removeFromGroup`,`isInGroup`,`getNode`,`getNodeOrNull`,`getPath`,`getRoot`,`find`,`findAll`,`on`,`off`,`once`,`emit`,`declareSignal`,`update`,`fixedUpdate`,`toJSON`,`diagnose`]);function qL(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:HL(e,o),label:HL(e,o)}),n(r,o)})};return n(e,[]),t}function JL(e,t){Array.isArray(e.connections)||(e.connections=[]);let n=e.connections;return n.push(t),n.length-1}function YL(e,t,n){let r=zL(e)[t];r&&Object.assign(r,n)}function XL(e,t){let n=zL(e);t<0||t>=n.length||(n.splice(t,1),n.length===0&&delete e.connections)}function ZL(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}=UL(e.working,t),s=HL(n,t);i.appendChild(QL(ZP({en:`emits (${a.length})`,ko:`보냄 (${a.length})`})));for(let t of a)i.appendChild($L(e,t,`out`));if(i.appendChild(eR(e,r,s)),o.length>0){i.appendChild(QL(ZP({en:`receives (${o.length})`,ko:`받음 (${o.length})`})));for(let t of o)i.appendChild($L(e,t,`in`))}return i}function QL(e){let t=document.createElement(`div`);return t.className=`conn-group`,t.textContent=e,t}function $L(e,{index:t,conn:n},r){let i=e.working.root,a=document.createElement(`div`);a.className=`conn-row`;let o=e.nodeAt(BL(i,String(n.from??``))??[-1]),s=r===`out`?`to`:`from`,c=String(n[s]??``),l=BL(i,c)===null,u=tR(WL(o),String(n.signal??``),n=>{e.mutate(()=>YL(e.working,t,{signal:n}))});u.title=ZP({en:`signal`,ko:`시그널`});let d=document.createElement(`span`);d.className=`conn-arrow`,d.textContent=r===`out`?`→`:`←`;let f=tR(qL(i).map(e=>e.path),c,n=>{e.mutate(()=>YL(e.working,t,{[s]:n}))});f.title=ZP({en:s,ko:s===`to`?`대상`:`출처`}),l&&f.classList.add(`dangling`);let p=GL(e.nodeAt(BL(i,String(n.to??``))??[-1])),m=n=>{e.mutate(()=>YL(e.working,t,{handler:n.trim()}))},h;if(p.length>0){let e=tR(p,String(n.handler??``),m);e.title=ZP({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=ZP({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=ZP({en:`remove this connection`,ko:`이 연결 삭제`}),g.addEventListener(`click`,()=>{e.mutate(()=>XL(e.working,t))}),a.append(u,d,f,h,g),l){let e=document.createElement(`div`);e.className=`conn-warn`,e.textContent=ZP({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 eR(e,t,n){let r=WL(t),i=document.createElement(`div`);i.className=`conn-add`;let a=document.createElement(`button`);return a.type=`button`,a.textContent=ZP({en:`+ connect`,ko:`+ 연결`}),a.disabled=r.length===0,r.length===0&&(a.title=ZP({en:`this node declares no signals`,ko:`이 노드는 시그널을 선언하지 않습니다`})),a.addEventListener(`click`,()=>{let i=r[0]??``,a={from:n,signal:i,to:n,handler:GL(t)[0]??`on${i.charAt(0).toUpperCase()}${i.slice(1)}`};e.mutate(()=>{JL(e.working,a)})}),i.appendChild(a),i}function tR(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 nR(e,t,n,r){return{cx:Math.floor((n-e.x)/t),cy:Math.floor((r-e.y)/t)}}function rR(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 iR(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 aR=RL;function oR(e){return(e.kind===`foliage`||e.kind===`tile`)&&!e.animation}function sR(e,t,n){if(e.textContent=``,t.selection===null){lR(e,t,n);return}let r=t.nodeAt(t.selection);r&&vR(e,t,r,n)}var cR=[`connections`,`input`,`multiplayer`];function lR(e,t,n){e.appendChild(WR(`scene`)),e.appendChild(XR(`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(KR(`dimension`,r)),e.appendChild(WR(`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(WR(`environment`)),uR(e,t),e.appendChild(WR(`constants`)),RR(e,t,n),e.appendChild(WR(`draw order bands`)),LR(e,t),e.appendChild(WR(`advanced`));for(let n of cR)e.appendChild(ez(n,t.working[n],e=>{t.mutate(()=>{e===void 0?delete t.working[n]:t.working[n]=e})}))}function uR(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(dR(`background`,n.background??``,e=>{r({background:e===``?void 0:e})})),e.appendChild(dR(`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(ZR(`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(KR(`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(KR(`pixel ratio`,s))}function dR(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),KR(e,r)}function fR(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(KR(`enabled`,l)),a){n.appendChild(dR(`murk color`,String(o.color??``),e=>c(`color`,e))),n.appendChild(ZR(`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(KR(`caustics`,e))}return n}function pR(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(dR(`color`,String(a.color??``),e=>o(`color`,e))),r.appendChild(_R(`roughness`,Number(a.roughness??1),e=>o(`roughness`,e))),r.appendChild(_R(`metalness`,Number(a.metalness??0),e=>o(`metalness`,e))),r.appendChild(dR(`emissive`,String(a.emissive??``),e=>o(`emissive`,e))),r.appendChild(_R(`emissive power`,Number(a.emissiveIntensity??1),e=>o(`emissiveIntensity`,e===1?void 0:e),2)),r.appendChild(_R(`opacity`,Number(a.opacity??1),e=>o(`opacity`,e===1?void 0:e))),r.appendChild(_R(`clearcoat`,Number(a.clearcoat??0),e=>o(`clearcoat`,e===0?void 0:e))),r.appendChild(_R(`clearcoat rough`,Number(a.clearcoatRoughness??0),e=>o(`clearcoatRoughness`,e===0?void 0:e))),r.appendChild(_R(`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(KR(`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(KR(`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(KR(`draw on top (decal)`,l)),r.appendChild(OR(`map (texture)`,String(a.map??``),kR(e=>oR(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(OR(`normal map`,String(a.normalMap??``),kR(e=>oR(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 mR=new Set([`animationLoop`,`animationSpeed`,`animationOffset`,`animationUpper`,`animationUpperLoop`,`upperBodyRoot`]);function hR(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(OR(`clip`,s,n.animationsForSelection().map(e=>({label:e,value:e,hint:e.startsWith(`$`)?`scene asset`:`clip in this model`})),n=>wR(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(gR(e,t,n,r)),i}i.appendChild(BR(e,t,`animationLoop`,r.animationLoop?.default??!0,void 0,`loop`));let c=_R(`speed`,Number(t.props?.animationSpeed??1),n=>wR(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=BR(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(gR(e,t,n,r)),i}function gR(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(OR(`clip`,String(t.props?.animationUpper??``),n.animationsForSelection().map(e=>({label:e,value:e})),n=>wR(e,t,`animationUpper`,n.trim(),``),{placeholder:`empty = off`,ctx:n})),i.appendChild(BR(e,t,`animationUpperLoop`,r.animationUpperLoop?.default??!1,void 0,`loop`)),i.appendChild(BR(e,t,`upperBodyRoot`,r.upperBodyRoot?.default??`Spine`,void 0,`root bone`)),i}function _R(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),KR(e,a)}function vR(e,t,n,r){if(e.appendChild(WR(n.type??`instance`)),e.appendChild(yR(n)),e.appendChild(XR(`name`,n.name??``,e=>{e.trim()===``||t.selection===null||t.renameNode(t.selection,e.trim())})),n.type===`TileMap2D`&&r?.paint&&e.appendChild($R(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(CR(t,n,o.default));else if(a===`material`)e.appendChild(pR(t,n,r));else if(n.type===`ModelInstance3D`&&a===`model`&&r)e.appendChild(OR(`model`,String(n.props?.model??``),r.modelRefs().map(e=>({label:e,value:e,hint:`scene asset`})),e=>wR(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(ER(`bone`,String(n.props?.bone??``),r.bonesForSelection(String(n.props?.target??``)),e=>wR(t,n,`bone`,e,``)));else if(n.type===`ModelInstance3D`&&a===`animation`&&r)e.appendChild(hR(t,n,r,i));else if(!(n.type===`ModelInstance3D`&&mR.has(a)))if((n.type===`Sprite3D`||n.type===`AnimatedSprite3D`)&&(a===`texture`||a===`sheet`))e.appendChild(OR(a===`sheet`?`sheet (image URL)`:`texture (image URL)`,String(n.props?.[a]??``),kR(e=>e.kind===`character`||e.kind===`item`),e=>wR(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(OR(`texture (atlas $ref)`,String(n.props?.texture??``),(r?.assetRefs?.([`texture`,`spritesheet`])??[]).map(e=>({label:e,value:e,hint:`scene asset`})),e=>wR(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(OR(`leaf texture`,String(n.props?.leafTexture??``),kR(e=>e.name.startsWith(`leaves_`)),e=>wR(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(OR(`texture base`,String(n.props?.textureBase??o.default??``),jR,e=>wR(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(MR(t,n,a,r,i))}else n.type===`AudioPlayer`&&a===`src`?e.appendChild(OR(`src (audio file)`,String(n.props?.src??``),AR(),e=>wR(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(NR(t,n)):n.type===`Water3D`&&a===`underwater`?e.appendChild(fR(t,n)):e.appendChild(BR(t,n,a,o.default,o.options))}if(e.appendChild(WR(`structure`)),e.appendChild(bR(t,n)),e.appendChild(xR(t,n)),e.appendChild(SR(t,n)),t.selection){let n=ZL(t,t.selection);n&&(e.appendChild(WR(`connections`,`connections`)),e.appendChild(n))}}function yR(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 bR(e,t){let n=document.createElement(`label`);n.className=`field wide`;let r=document.createElement(`span`);r.append(`groups `,LL(`groups`));let i=document.createElement(`div`);i.className=`chips`;for(let n of t.groups??[])i.appendChild(GR(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 xR(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`script `,LL(`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(XR(`name`,a.name??``,n=>{e.mutate(()=>{t.script.name=n.trim()})})),n.appendChild(ez(`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 SR(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`network `,LL(`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(KR(`mode`,a)),i?.mode===`owner`){let r=document.createElement(`div`);r.className=`chips`;for(let n of i.sync??[])r.appendChild(GR(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(ZR(`throttle ms`,i.throttleMs??50,n=>{e.mutate(()=>{t.network.throttleMs=n})}))}return n}function CR(e,t,n){let r=document.createElement(`div`);r.className=`subcard`;let i=document.createElement(`div`);i.className=`subcard-head`,i.append(`collider `,LL(`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(KR(`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(ZR(`radius`,a.radius??(s?.5:16),e=>o({...a,radius:e}))):a.shape===`capsule`&&(r.appendChild(ZR(`radius`,a.radius??12,e=>o({...a,radius:e}))),r.appendChild(ZR(`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 wR(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 TR=0;function ER(e,t,n,r){let i=document.createElement(`input`);i.type=`text`,i.value=t;let a=`suggest-${TR++}`;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=KR(e,i);return s.appendChild(o),s}var DR=0;function OR(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`,t.title=[e.label,e.full??e.hint,e.value===e.label?null:e.value].filter(Boolean).join(`
8424
+ `);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-${DR++}`,a.htmlFor=s.id,a}function kR(e){return aR.filter(e).map(e=>({label:e.name,value:e.url,hint:`${e.kind} · ${e.description}`,full:`${e.kind} · ${e.description}`}))}function AR(){return aR.filter(e=>e.kind===`audio`).map(e=>({label:e.name,value:e.url,hint:`audio · ${e.description}`,full:`audio · ${e.description}`}))}var jR=[{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 MR(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=aR.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 OR(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)}wR(e,t,n,`$${r.addAsset(a.name,i).replace(/^\$/,``)}`,``);return}wR(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))wR(e,t,r,i,void 0)}},ctx:r})}function NR(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=jD.filter(e=>i.has(e));wR(e,t,`varieties`,n.length===0||n.length===jD.length?[]:n,[])};for(let e of jD){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 jD)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 PR=[[`number`,()=>0],[`text`,()=>``],[`boolean`,()=>!1],[`color`,()=>`#ffffff`],[`vec2`,()=>[0,0]],[`vec3`,()=>[0,0,0]]];function FR(e,t){let n=0,r=e=>{if(bn(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 IR(e,t,n){let r=e=>{if(bn(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 LR(e,t){let n=t.working.orderGroups??{},r=Object.keys(n),i=e=>{t.mutate(()=>{Object.keys(e).length===0?delete t.working.orderGroups:t.working.orderGroups=e})},a=document.createElement(`div`);if(a.className=`hint`,a.textContent=`Built in: ${Object.entries(ht).map(([e,t])=>`${e} ${t}`).join(` · `)}`,e.appendChild(a),r.length===0){let t=document.createElement(`div`);t.className=`hint`,t.textContent=`No extra bands. Add one to sort between (or beyond) the built-ins — a band is the base offset, not just a name.`,e.appendChild(t)}for(let t of r){let r=document.createElement(`div`);r.className=`const-row`,r.appendChild(ZR(t,n[t]??0,e=>i({...n,[t]:e})));let a=document.createElement(`button`);a.type=`button`,a.className=`const-del`,a.textContent=`✕`,a.title=`delete band "${t}"`,a.addEventListener(`click`,()=>{let e={...n};delete e[t],i(e)}),r.appendChild(a),e.appendChild(r)}let o=document.createElement(`div`);o.className=`const-add`;let s=document.createElement(`input`);s.type=`text`,s.placeholder=`new band name`;let c=document.createElement(`input`);c.type=`number`,c.placeholder=`base`,c.className=`band-base`;let l=document.createElement(`button`);l.type=`button`,l.textContent=`add`,l.addEventListener(`click`,()=>{let e=s.value.trim(),t=Number(c.value);!e||n[e]!==void 0||!Number.isFinite(t)||(i({...n,[e]:t}),s.value=``,c.value=``)}),o.append(s,c,l),e.appendChild(o)}function RR(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&&IR(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=FR(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(zR(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 PR){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,(PR.find(([e])=>e===u.value)?.[1]??(()=>0))()),l.value=``)}),c.append(l,u,d),e.appendChild(c)}function zR(e,t,n){let r=Be(t);if(r===`number`)return ZR(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)),KR(e,r)}return r===`array`&&Array.isArray(t)&&t.every(e=>typeof e==`number`)?QR(e,t,e=>n(e)):r===`string`?XR(e,String(t),e=>n(e)):ez(e,t,e=>n(e??null),JSON.stringify(t))}function BR(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=bn(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=VR(e,s,r);if(bn(o))return HR(n,o[`@const`],u,l,r);let d=e=>u.length>0?UR(e,u,l):e;if(s===`number`)return d(ZR(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(KR(a??n,e))}if(s===`string`){if(i&&i.length>0){let t=n===`orderGroup`?YR(e):[];return d(qR(a??n,String(o??``),t.length>0?[...i,...t]:i,e=>l(e),n===`orderGroup`?t=>JR(t,e):void 0))}return d(XR(a??n,String(o??``),e=>l(e)))}return s===`array`&&Array.isArray(r)&&r.length>0&&r.every(e=>typeof e==`number`)?d(QR(n,o??r,e=>l(e))):ez(n,o===r?void 0:o,e=>{l(e===void 0?r:e)},JSON.stringify(r))}function VR(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 HR(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=KR(`🔗 ${e}`,a);return c.classList.add(`const-bound`),c}function UR(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.classList.add(`has-const-picker`),e.appendChild(r),e}function WR(e,t){let n=document.createElement(`div`);n.className=`section-title`,n.textContent=e,t&&n.appendChild(LL(t));let r=document.createElement(`span`);return r.className=`rule`,n.appendChild(r),n}function GR(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 KR(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 qR(e,t,n,r,i){let a=document.createElement(`select`);for(let e of n.includes(t)?n:[t,...n]){let n=document.createElement(`option`);n.value=e;let r=i?.(e);n.textContent=r?`${e} (${r})`:e,e===t&&(n.selected=!0),a.appendChild(n)}return a.addEventListener(`change`,()=>r(a.value)),KR(e,a)}function JR(e,t){let n={...ht,...t.working.orderGroups??{}}[e];return n===void 0?`unknown — sorts as default`:String(n)}function YR(e){return Object.keys(e.working.orderGroups??{})}function XR(e,t,n){let r=document.createElement(`input`);return r.type=`text`,r.value=t,r.addEventListener(`change`,()=>n(r.value)),KR(e,r)}function ZR(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)}),KR(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)}),KR(e,r)}function $R(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 iR(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 ez(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=KR(e,i);return a.className=`field wide`,a}var tz=2.4,nz=1.35,rz=[0,.5,0];function iz(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,nz,tz]}},{name:`Sun`,type:`DirectionalLight3D`,props:{position:[3,6,4],intensity:2.2}},{name:`Model`,type:`ModelInstance3D`,props:{model:`$model`,targetHeight:1}}]}}}var az=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 kt({scheduler:()=>()=>{}}),this.renderer=new vP({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(An(iz(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)*tz,nz,Math.cos(this.angle)*tz],target:rz},this.engine?.tick(n))};this.raf=requestAnimationFrame(t)}stop(){this.raf&&cancelAnimationFrame(this.raf),this.raf=0}},oz=`incanto-editor-v8-token`,sz=24;async function cz(e,t,n){if(!C(e.url)||n!==`spritesheet`&&n!==`texture`)return null;try{let n=oy(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 lz(){try{return localStorage.getItem(oz)??``}catch{return``}}function uz(e){try{e?localStorage.setItem(oz,e):localStorage.removeItem(oz)}catch{}}function dz(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 az,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 cz(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=eF(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=lz();let o=document.createElement(`button`);o.type=`button`,o.className=`primary`,o.textContent=`connect`,o.addEventListener(`click`,()=>{uz(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:sz},lz()||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 fz=`.scene.json`;function pz(e){let t=e.split(`/`).pop()??e;return t.endsWith(fz)?t.slice(0,-11):t}function mz(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function hz(e,t){return{path:e,name:t,dirs:new Map,files:[]}}function gz(e){let t=hz(``,``);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=hz(e,t),r.dirs.set(t,n)),r=n}r.files.push(n)}return t}function _z(e){let t=e.files.length;for(let n of e.dirs.values())t+=_z(n);return t}function vz(e){let t=e.files.filter(e=>e.scene).length;for(let n of e.dirs.values())t+=vz(n);return t}function yz(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 bz(e){let t=mz(e??``).split(`/`).filter(Boolean),n=[],r=``;for(let e of t)r=r?`${r}/${e}`:e,n.push(r);return n}function xz(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}=yz(e),c=_z(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:vz(t),open:l}),l&&o(t,r+1)}let c=[...e.files].sort((e,t)=>pz(e.rel).localeCompare(pz(t.rel)));for(let e of c)a.push({kind:`scene`,entry:e,label:pz(e.rel),folder:mz(e.rel),depth:r,current:e.rel===t.current})};return o(gz(r),0),a}function Sz(e,t){let n=new Set(bz(t));if(e.length<=24)for(let t of e)for(let e of bz(t.rel))n.add(e);return n}function Cz(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 wz(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 Tz(e,t=`new-level`){let n=e?e.kind===`folder`?e.path:e.folder:``;return n?`${n}/${t}${fz}`:`${t}${fz}`}function Ez(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}function Dz(e,t,n=()=>Date.now()){let r=[],i=new Set,a=[],o=0,s=!0,c=()=>{let c=t.current();if(a=xz(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=Ez(`scene-caret`,``);n.kind===`folder`?(a.classList.add(`chevron`),n.open||a.classList.add(`collapsed`),a.appendChild(tF())):a.textContent=`◇`,i.append(a,Ez(`scene-name`,n.label),Ez(`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`,wz(n.entry.modified,u),Cz(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=Tz(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=Sz(r,t.current());else for(let e of bz(t.current()))i.add(e);s=!0,c(),e.search.focus(),e.search.select()}}}var Oz=`
8425
8425
  <header id="topbar">
8426
8426
  <div class="brand">
8427
8427
  <span class="brand-mark">in</span>
@@ -8585,7 +8585,7 @@ registerBehavior('MyBehavior', MyBehavior); // before loadScene()
8585
8585
  </div>
8586
8586
  </div>
8587
8587
  <div id="popover" hidden></div>
8588
- `;function Az(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 jz(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 Mz(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 Nz(e,t,n){let r=e.root;if(!r||t.length===0)return r&&t.length===0?Pz(e,r,n):[];let i=Az(r,t),a=Fz(r,t);if(!a)return[];let o=Iz(e,r,i,n);return a.name=n,o}function Pz(e,t,n){let r=Iz(e,t,[String(t.name??``)],n);return t.name=n,r}function Fz(e,t){let n=e;for(let e of t)if(n=n?.children?.[e],!n)return null;return n??null}function Iz(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=jz(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 Mz(a)){let a=c[s],l=`${o.join(`/`)}.${s}`;if(typeof a==`string`){let e=jz(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=jz(e,o,n,r);s!==null&&(a[t]=s,i.push({where:`${l}[${t}]`,from:e,to:s}))}):bn(a)&&Lz(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 Lz(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=jz(l,[String(t.name??``)],r,i);u!==null&&(c[s]=u,o.push({where:`constants.${s} (${a})`,from:l,to:u}))}var Rz=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.working.root&&zz(this.working.root),this.original=JSON.stringify(this.working)}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?Jz(r,t,n):t;return i===n.name?[]:this.transact(()=>Nz(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=Wz(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)Kz(i,e);let e,t;if(n===`into`)e=o,e.children||=[],t=e.children.length;else{let r=Gz(i,o);if(!r)return null;e=r.parent,t=r.index+ +(n===`after`)}let r=[];a.forEach((n,r)=>{n.name=Jz(e,n.name??`Node`),e.children?.splice(t+r,0,n)});for(let e of a){let t=qz(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=Jz(n,t.name??`Node`),Bz(r);let i=e[e.length-1]+1;return n.children?.splice(i,0,r),[...e.slice(0,-1),i]})}removeNodes(e){let t=Wz(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)Kz(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 Bz(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=Jz(n,r.name??`Node`),Bz(r),n.children||=[],n.children.push(r),[...t,n.children.length-1]}):null}findRemovalReferences(e){let t=Wz(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=Wz(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&&Vz(this.working,a,i);for(let e of i)Kz(r,e);return!0})===!0}reset(e){this.working=e,this.working.root&&zz(this.working.root),this.original=JSON.stringify(this.working),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],Hz(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],Hz(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(Uz)}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 zz(e){(typeof e.uid!=`string`||e.uid===``)&&(e.uid=Qn());for(let t of e.children??[])zz(t)}function Bz(e){e.uid=Qn();for(let t of e.children??[])Bz(t)}function Vz(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):Vz(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]:Vz(i,t,n))}}function Hz(e,t,n){if(Array.isArray(e)){e.forEach((r,i)=>{r===t?e[i]=n:Hz(r,t,n)});return}if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))i===t?e[r]=n:Hz(i,t,n)}function Uz(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 Wz(e){let t=[...e].sort(Uz),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 Gz(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=Gz(n,t);if(e)return e}return null}function Kz(e,t){let n=Gz(e,t);n?.parent.children?.splice(n.index,1)}function qz(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=qz(r,t);if(e)return[n,...e]}return null}function Jz(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 Yz=`
8588
+ `;function kz(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 Az(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 jz(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 Mz(e,t,n){let r=e.root;if(!r||t.length===0)return r&&t.length===0?Nz(e,r,n):[];let i=kz(r,t),a=Pz(r,t);if(!a)return[];let o=Fz(e,r,i,n);return a.name=n,o}function Nz(e,t,n){let r=Fz(e,t,[String(t.name??``)],n);return t.name=n,r}function Pz(e,t){let n=e;for(let e of t)if(n=n?.children?.[e],!n)return null;return n??null}function Fz(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=Az(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 jz(a)){let a=c[s],l=`${o.join(`/`)}.${s}`;if(typeof a==`string`){let e=Az(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=Az(e,o,n,r);s!==null&&(a[t]=s,i.push({where:`${l}[${t}]`,from:e,to:s}))}):bn(a)&&Iz(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 Iz(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=Az(l,[String(t.name??``)],r,i);u!==null&&(c[s]=u,o.push({where:`constants.${s} (${a})`,from:l,to:u}))}var Lz=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.working.root&&Rz(this.working.root),this.original=JSON.stringify(this.working)}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?qz(r,t,n):t;return i===n.name?[]:this.transact(()=>Mz(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=Uz(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)Gz(i,e);let e,t;if(n===`into`)e=o,e.children||=[],t=e.children.length;else{let r=Wz(i,o);if(!r)return null;e=r.parent,t=r.index+ +(n===`after`)}let r=[];a.forEach((n,r)=>{n.name=qz(e,n.name??`Node`),e.children?.splice(t+r,0,n)});for(let e of a){let t=Kz(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=qz(n,t.name??`Node`),zz(r);let i=e[e.length-1]+1;return n.children?.splice(i,0,r),[...e.slice(0,-1),i]})}removeNodes(e){let t=Uz(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)Gz(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 zz(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=qz(n,r.name??`Node`),zz(r),n.children||=[],n.children.push(r),[...t,n.children.length-1]}):null}findRemovalReferences(e){let t=Uz(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=Uz(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&&Bz(this.working,a,i);for(let e of i)Gz(r,e);return!0})===!0}reset(e){this.working=e,this.working.root&&Rz(this.working.root),this.original=JSON.stringify(this.working),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],Vz(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],Vz(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(Hz)}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 Rz(e){(typeof e.uid!=`string`||e.uid===``)&&(e.uid=Qn());for(let t of e.children??[])Rz(t)}function zz(e){e.uid=Qn();for(let t of e.children??[])zz(t)}function Bz(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):Bz(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]:Bz(i,t,n))}}function Vz(e,t,n){if(Array.isArray(e)){e.forEach((r,i)=>{r===t?e[i]=n:Vz(r,t,n)});return}if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))i===t?e[r]=n:Vz(i,t,n)}function Hz(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 Uz(e){let t=[...e].sort(Hz),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 Wz(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=Wz(n,t);if(e)return e}return null}function Gz(e,t){let n=Wz(e,t);n?.parent.children?.splice(n.index,1)}function Kz(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=Kz(r,t);if(e)return[n,...e]}return null}function qz(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 Jz=`
8589
8589
  /* ─── incanto editor · design system ──────────────────────────────────────── */
8590
8590
  :root {
8591
8591
  --bg-0: #0b0d14;
@@ -10855,4 +10855,4 @@ body.playing #gameview-btn {
10855
10855
  opacity: 0.4;
10856
10856
  cursor: default;
10857
10857
  }
10858
- `,Xz=new Map(BF.flatMap(e=>e.nodes.map(e=>[e.type,e.summary]))),Zz=new Set,Qz=null,$z=null,eB=null;function tB(e){$z=e}function nB(e){Qz=e}function rB(e){eB=e}var iB=null,aB=null,oB=null;function sB(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 cB(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}fB(r,t.selection),e.appendChild(pB(r,[],t,``)),uB(e,t.selection)}var lB=null;function uB(e,t){let n=JSON.stringify(t);n!==lB&&(lB=n,e.querySelector(`.tree-row.selected`)?.scrollIntoView?.({block:`nearest`,inline:`nearest`}))}function dB(){lB=null}function fB(e,t){if(!t)return;let n=e,r=``;for(let e of t){r=r?`${r}/${n.name}`:String(n.name),Zz.delete(r);let t=n.children?.[e];if(!t)return;n=t}}function pB(e,t,n,r){let i=r?`${r}/${e.name}`:String(e.name),a=(e.children?.length??0)>0,o=Zz.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&&oB!==i;let l=document.createElement(`span`);l.className=`chevron${a?``:` leaf`}${o?` collapsed`:``}`,a?l.appendChild(nF()):l.textContent=`·`,a&&l.addEventListener(`click`,e=>{e.stopPropagation(),o?Zz.delete(i):Zz.add(i),n.select(n.selection)});let u=document.createElement(`span`);if(u.className=`tree-icon ${sB(e.type)}`,u.appendChild(tF(e.type)),u.title=e.type??`instance`,u.addEventListener(`click`,t=>{t.stopPropagation(),mB(u,e.type??`instance`)}),c.append(l,u),oB===i){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e.name??``;let i=()=>{oB=null;let i=r.value.trim();if(i&&i!==e.name){let e=n.renameNode(t,i)??[];e.length>0&&eB?.(e)}else n.select(n.selection)};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`&&i(),e.key===`Escape`&&(oB=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(),oB=i,n.select(t)}),c.appendChild(r)}if(c.addEventListener(`click`,e=>{a&&!e.metaKey&&!e.ctrlKey&&(o?Zz.delete(i):Zz.add(i)),n.select(t,{toggle:e.metaKey||e.ctrlKey})}),c.addEventListener(`contextmenu`,e=>{e.preventDefault(),n.isSelected(t)||n.select(t),hB(e.clientX,e.clientY,n,t,i)}),wB(c,t,n),s.appendChild(c),a&&!o){let r=document.createElement(`div`);r.className=`tree-children`,(e.children??[]).forEach((e,a)=>{r.appendChild(pB(e,[...t,a],n,i))}),s.appendChild(r)}return s}function mB(e,t){bB();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=Xz.get(t);if(i){let e=document.createElement(`span`);e.textContent=QP(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`,xB(n)}function hB(e,t,n,r,i){bB();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`,()=>{bB(),t()}),s.appendChild(r)};c(`duplicate${a.length>1?` ×${a.length}`:``}`,()=>{for(let e of[...a].reverse())n.duplicateNode(e)}),c(`frame in view`,$z&&r.length>0?()=>{n.select(r),$z?.()}:null,{kbd:`F`}),c(`rename`,o?()=>{oB=i,n.select(r)}:null,{kbd:`dbl-click`}),s.appendChild(gB()),c(`cut`,r.length>0?()=>_B(n,!0):null),c(`copy`,r.length>0?()=>_B(n,!1):null),c(`paste as child${aB?` (${aB.nodes.length})`:``}`,aB?()=>vB(n,r):null),s.appendChild(gB()),c(`delete`,r.length>0?()=>(Qz??(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`,xB(s)}function gB(){let e=document.createElement(`div`);return e.className=`menu-divider`,e}function _B(e,t){let n=e.allSelections().filter(e=>e.length>0).map(t=>e.nodeAt(t)).filter(e=>e!==null);aB={nodes:n.map(e=>JSON.parse(JSON.stringify(e))),cut:t?n:null}}function vB(e,t){if(aB){for(let n of aB.nodes)e.insertNode(n,t);if(aB.cut){let t=e.working.root,n=aB.cut.map(e=>yB(t,e)).filter(e=>e!==null);n.length>0&&e.removeNodes(n),aB={nodes:aB.nodes,cut:null}}}}function yB(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=yB(r,t);if(e)return[n,...e]}return null}function bB(){for(let e of document.querySelectorAll(`.floating`))e.remove()}function xB(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 SB(e,t){let n=t.getBoundingClientRect(),r=(e.clientY-n.top)/n.height;return r<.25?`before`:r>.75?`after`:`into`}function CB(e){e.classList.remove(`drop-into`,`drop-before`,`drop-after`)}function wB(e,t,n){e.addEventListener(`dragstart`,r=>{iB=n.isSelected(t)?n.allSelections():[t],r.dataTransfer?.setData(`text/plain`,``),r.dataTransfer&&(r.dataTransfer.effectAllowed=`move`),e.classList.add(`dragging`)}),e.addEventListener(`dragend`,()=>{iB=null,e.classList.remove(`dragging`)}),e.addEventListener(`dragover`,n=>{if(!iB||iB.some(e=>e.length<=t.length&&e.every((e,n)=>e===t[n])))return;n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=`move`),CB(e);let r=t.length===0?`into`:SB(n,e);e.classList.add(`drop-${r}`)}),e.addEventListener(`dragleave`,()=>CB(e)),e.addEventListener(`drop`,r=>{if(CB(e),!iB)return;r.preventDefault();let i=t.length===0?`into`:SB(r,e),a=n.moveNodes(iB,t,i);iB=null,a?.[0]&&n.select(a[0])})}var TB={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`};function EB(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 DB(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 OB(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 kB(e,t,n){return Math.atan2(n-e.y,t-e.x)*180/Math.PI}function AB(e,t){let n=t-e;for(;n>180;)n-=360;for(;n<=-180;)n+=360;return n}function jB(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 MB(e,t,n){for(let r of t){if(r.points.length<2)continue;let t=n===r.axis;e.strokeStyle=TB[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 NB(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 PB=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 kt({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);ZB(t),n=An(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 Yv({canvas:this.editCanvas,engine:this.engine}),this.renderer2d.ignoreStatic=!0,this.renderer2d.viewOverride=this.defaultView(e);else{this.renderer3d=new yP({canvas:this.editCanvas,engine:this.engine}),this.renderer3d.ignoreStatic=!0;let t=qB(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 ZB(t),An(t,{stubAllBehaviors:!0}),null}catch(e){return e instanceof Error?e.message:String(e)}}defaultView(e){let t=JB(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 bm(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>sy);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 bm(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>FP);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=KB(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:TB.x},{axis:`y`,sx:0,sy:64,worldPerUnit:64/i,color:TB.y}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D,n=e.position;if(!t||!Array.isArray(n))return null;t.getWorldPosition(BB);let r=this.renderer3d.screenFromWorld(BB.x,BB.y,BB.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(BB.x+t[0]*o,BB.y+t[1]*o,BB.z+t[2]*o);n.behind||i.push({axis:e,sx:n.x-r.x,sy:n.y-r.y,worldPerUnit:o,color:TB[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=KB(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(BB);let n={x:BB.x,y:BB.y,z:BB.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,IB).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 UE&&(t.current||!e)&&(e=t,t.current))break;let t=e?e._ensureObject3D():null;if(t){t.getWorldPosition(LB),RB.set(0,0,-1).applyQuaternion(t.getWorldQuaternion(zB));let e=Math.min(40,Math.max(3,this.orbit.dist));this.orbit.target=[LB.x+RB.x*e,LB.y+RB.y*e,LB.z+RB.z*e],this.orbit.dist=e,this.orbit.yaw=Math.atan2(-RB.x,-RB.z),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,-RB.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 Zk||t instanceof Dv||t instanceof eA||t instanceof _g||t instanceof Sk)&&t.update(e)}modelAnimationsAt(e){let t=this.nodeAtPath.get(e.join(`.`));return t instanceof Zk?t.availableAnimations():[]}boneNamesAt(e,t){let n=this.nodeAtPath.get(e.join(`.`));if(!n||t===``)return[];let r=n.getNodeOrNull(t);return r instanceof Zk?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&&NB(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&&NB(e,this.readout.x,this.readout.y,this.readout.text)}drawModeGizmo(e){if(this.gizmoMode===`rotate`){let t=this.ringLayout();t&&MB(e,t.rings,this.activeRing);return}let t=this.gizmoLayout();t&&OB(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=KB(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=jB(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:kB(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=AB(i,kB(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=EB(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]]=FB(g((o[d[t.axis]]??1)*n));else for(let e=0;e<r.length;e++)r[e]=FB(g((o[e]??1)*n));i.scale=r,this.readout={x:e.offsetX,y:e.offsetY,text:`×${r.map(e=>FB(e)).join(`, `)}`};return}let _=[...a];if(t.kind===`axis`){let e=r.axes.find(e=>e.axis===t.axis);if(!e)return;let n=DB(e,c,l);if(u)_[d[t.axis]]=FB(h((a[d[t.axis]]??0)+n));else{let e=WB(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]=FB(h((a[0]??0)+(e.x*c-t.x*l)*n)),_[1]=FB(h((a[1]??0)+(e.y*c-t.y*l)*n)),_[2]=FB(h((a[2]??0)+(e.z*c-t.z*l)*n))}else if(this.renderer2d){let e=this.renderer2d.view(),t=WB(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=>FB(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=WB(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 Vo;for(let[n]of this.pathOf){if(e&&n!==e&&!GB(n,e))continue;let r=n._object3D;r&&(t.expandByObject(r),t.expandByPoint(r.getWorldPosition(BB)))}if(t.isEmpty()&&e){let t=e._object3D,n=t?t.getWorldPosition(BB):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&&!GB(t,e))continue;let n=t.position;if(!Array.isArray(n))continue;let s=KB(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);ZB(t);let n;try{n=An(t,{stubAllBehaviors:!0,declareConnectionSignals:!0})}catch(e){return e instanceof Error?e.message:String(e)}let r=new kt;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 Yv({canvas:this.playCanvas,engine:r});let{enablePhysics2D:e}=await bm(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>sy);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}else{this.playRenderer=new yP({canvas:this.playCanvas,engine:r,assets:this.renderer3d?.assets});let{enablePhysics3D:e}=await bm(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>FP);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 FB(e){return Math.round(e*100)/100}var IB=new U(0,1,0),LB=new U,RB=new U,zB=new H,BB=new U,VB=new G,HB=new U,UB=new U;function WB(e,t,n){let r=e._object2D?.parent;return r?(VB.copy(r.matrixWorld).invert(),HB.set(t,-n,0).applyMatrix4(VB),UB.set(0,0,0).applyMatrix4(VB),{x:HB.x-UB.x,y:-(HB.y-UB.y)}):{x:t,y:n}}function GB(e,t){for(let n=e.parent;n;n=n.parent)if(n===t)return!0;return!1}function KB(e){let t=e._object2D;if(t)return t.getWorldPosition(BB),{x:BB.x,y:-BB.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 qB(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=qB(t);if(e)return e}return null}function JB(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=JB(t);if(e)return e}return null}var YB=null;function XB(){if(YB)return YB;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 YB=e.toDataURL(),YB}function ZB(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=XB())}var QB=e({formatSceneJson:()=>r,httpEditorApi:()=>re,mountEditor:()=>$B});_n(),Lv(),JM(),GP(),G_();async function $B(e={}){let t=e.api??re,n=[],r=document.createElement(`style`);r.dataset.incantoEditor=`true`,r.textContent=Yz,document.head.appendChild(r),n.push(()=>r.remove());let i=document.createElement(`div`);i.className=`incanto-editor-root`,i.innerHTML=kz,(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}`,IL(a(`#popover`)),GF(),a(`#docs-btn`).addEventListener(`click`,()=>UF());let s=a(`#lang-btn`),c=[{code:`en`,label:`English`},{code:`ko`,label:`한국어`}],l=()=>{a(`#lang-current`).textContent=YP()===`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=YP()===t?`✓`:``,a.className=`lang-check`,r.append(i,a),r.addEventListener(`click`,()=>{e.remove(),XP(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)}),ZP(()=>{l(),KF(),u.select(u.selection)});let u=new Rz({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,IF.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}=rR(ne(r),Number(i.props?.tileSize??32),e,t),s=i.props?.cells??[],c=iR(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 PB(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 RF)t.includes(e)||t.push(e);for(let e of t){let t=RF.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=>fz(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)=>rV(u,n,t)}:{}}):void 0,de=!1,fe=()=>{if(!T)return;cB(d,u),uF(a(`#asset-tree`),u),f.textContent=``,dF(f,u,Se,ue)||cR(f,u,{modelRefs:()=>tV(u,`model`),animationsForSelection:()=>u.selection?M.modelAnimationsAt(u.selection):[],bonesForSelection:e=>u.selection?M.boneNamesAt(u.selection,e):[],assetRefs:e=>nV(u,e),addAsset:(e,t)=>rV(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,IF.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(),dB(),u.reset(i),o.mode===`project`&&n&&IF.open(n,r)},ge=Oz({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`);AL(u),a(`#generate-btn`).addEventListener(`click`,()=>OL(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=eV(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?eV(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()}),nB(F),rB(e=>{ee(`${QP({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()),tB(()=>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(),IF.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){WF();return}if(e.key===`Escape`&&!P.hidden){I();return}if(e.key===`Escape`&&!N.hidden){kL();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),IF.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 eV(e){let t=0;for(let n of e.children??[])t+=1+eV(n);return t}function tV(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>e?.type===t).map(([e])=>`$${e}`):[]}function nV(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 rV(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 iV=null,aV=null;function oV(){return aV||(aV=document.createElement(`canvas`),aV.style.cssText=`position:fixed; inset:0; width:100%; height:100%; display:block;`,document.body.appendChild(aV)),aV.style.visibility=``,aV}async function sV(e,t){return iV=await $B({api:re,...e?{camera:e}:{},onPlay:(e,t)=>{e===`debug`&&cV(t)},playHints:{debug:`this page becomes the game — needs a scene with no project behaviors`},...t?{onExit:()=>(iV?.dispose(),iV=null,oV(),t())}:{}}),iV}async function cV(e){let t=e.dimension??`2d`;iV?.dispose(),iV=null;let n=async e=>{aV&&(aV.style.visibility=`hidden`),await sV(e.camera,e.exit)};try{if(t===`3d`){let{createGame3D:t}=await bm(async()=>{let{createGame3D:e}=await Promise.resolve().then(()=>FP);return{createGame3D:e}},void 0,import.meta.url);await t({canvas:oV(),scene:e,debug:!0,editor:{open:n}})}else{let{createGame2D:t}=await bm(async()=>{let{createGame2D:e}=await Promise.resolve().then(()=>sy);return{createGame2D:e}},void 0,import.meta.url);await t({canvas:oV(),scene:e,debug:!0,editor:{open:n}})}}catch(e){aV&&(aV.style.visibility=`hidden`),(await sV()).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.`)}}sV().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,bm as n,Xe as r,tv as t};
10858
+ `,Yz=new Map(zF.flatMap(e=>e.nodes.map(e=>[e.type,e.summary]))),Xz=new Set,Zz=null,Qz=null,$z=null;function eB(e){Qz=e}function tB(e){Zz=e}function nB(e){$z=e}var rB=null,iB=null,aB=null;function oB(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 sB(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}dB(r,t.selection),e.appendChild(fB(r,[],t,``)),lB(e,t.selection)}var cB=null;function lB(e,t){let n=JSON.stringify(t);n!==cB&&(cB=n,e.querySelector(`.tree-row.selected`)?.scrollIntoView?.({block:`nearest`,inline:`nearest`}))}function uB(){cB=null}function dB(e,t){if(!t)return;let n=e,r=``;for(let e of t){r=r?`${r}/${n.name}`:String(n.name),Xz.delete(r);let t=n.children?.[e];if(!t)return;n=t}}function fB(e,t,n,r){let i=r?`${r}/${e.name}`:String(e.name),a=(e.children?.length??0)>0,o=Xz.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&&aB!==i;let l=document.createElement(`span`);l.className=`chevron${a?``:` leaf`}${o?` collapsed`:``}`,a?l.appendChild(tF()):l.textContent=`·`,a&&l.addEventListener(`click`,e=>{e.stopPropagation(),o?Xz.delete(i):Xz.add(i),n.select(n.selection)});let u=document.createElement(`span`);if(u.className=`tree-icon ${oB(e.type)}`,u.appendChild(eF(e.type)),u.title=e.type??`instance`,u.addEventListener(`click`,t=>{t.stopPropagation(),pB(u,e.type??`instance`)}),c.append(l,u),aB===i){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e.name??``;let i=()=>{aB=null;let i=r.value.trim();if(i&&i!==e.name){let e=n.renameNode(t,i)??[];e.length>0&&$z?.(e)}else n.select(n.selection)};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`&&i(),e.key===`Escape`&&(aB=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(),aB=i,n.select(t)}),c.appendChild(r)}if(c.addEventListener(`click`,e=>{a&&!e.metaKey&&!e.ctrlKey&&(o?Xz.delete(i):Xz.add(i)),n.select(t,{toggle:e.metaKey||e.ctrlKey})}),c.addEventListener(`contextmenu`,e=>{e.preventDefault(),n.isSelected(t)||n.select(t),mB(e.clientX,e.clientY,n,t,i)}),CB(c,t,n),s.appendChild(c),a&&!o){let r=document.createElement(`div`);r.className=`tree-children`,(e.children??[]).forEach((e,a)=>{r.appendChild(fB(e,[...t,a],n,i))}),s.appendChild(r)}return s}function pB(e,t){yB();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=Yz.get(t);if(i){let e=document.createElement(`span`);e.textContent=ZP(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`,bB(n)}function mB(e,t,n,r,i){yB();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`,()=>{yB(),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?()=>{aB=i,n.select(r)}:null,{kbd:`dbl-click`}),s.appendChild(hB()),c(`cut`,r.length>0?()=>gB(n,!0):null),c(`copy`,r.length>0?()=>gB(n,!1):null),c(`paste as child${iB?` (${iB.nodes.length})`:``}`,iB?()=>_B(n,r):null),s.appendChild(hB()),c(`delete`,r.length>0?()=>(Zz??(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`,bB(s)}function hB(){let e=document.createElement(`div`);return e.className=`menu-divider`,e}function gB(e,t){let n=e.allSelections().filter(e=>e.length>0).map(t=>e.nodeAt(t)).filter(e=>e!==null);iB={nodes:n.map(e=>JSON.parse(JSON.stringify(e))),cut:t?n:null}}function _B(e,t){if(iB){for(let n of iB.nodes)e.insertNode(n,t);if(iB.cut){let t=e.working.root,n=iB.cut.map(e=>vB(t,e)).filter(e=>e!==null);n.length>0&&e.removeNodes(n),iB={nodes:iB.nodes,cut:null}}}}function vB(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=vB(r,t);if(e)return[n,...e]}return null}function yB(){for(let e of document.querySelectorAll(`.floating`))e.remove()}function bB(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 xB(e,t){let n=t.getBoundingClientRect(),r=(e.clientY-n.top)/n.height;return r<.25?`before`:r>.75?`after`:`into`}function SB(e){e.classList.remove(`drop-into`,`drop-before`,`drop-after`)}function CB(e,t,n){e.addEventListener(`dragstart`,r=>{rB=n.isSelected(t)?n.allSelections():[t],r.dataTransfer?.setData(`text/plain`,``),r.dataTransfer&&(r.dataTransfer.effectAllowed=`move`),e.classList.add(`dragging`)}),e.addEventListener(`dragend`,()=>{rB=null,e.classList.remove(`dragging`)}),e.addEventListener(`dragover`,n=>{if(!rB||rB.some(e=>e.length<=t.length&&e.every((e,n)=>e===t[n])))return;n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=`move`),SB(e);let r=t.length===0?`into`:xB(n,e);e.classList.add(`drop-${r}`)}),e.addEventListener(`dragleave`,()=>SB(e)),e.addEventListener(`drop`,r=>{if(SB(e),!rB)return;r.preventDefault();let i=t.length===0?`into`:xB(r,e),a=n.moveNodes(rB,t,i);rB=null,a?.[0]&&n.select(a[0])})}var wB={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`};function TB(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 EB(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 DB(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 OB(e,t,n){return Math.atan2(n-e.y,t-e.x)*180/Math.PI}function kB(e,t){let n=t-e;for(;n>180;)n-=360;for(;n<=-180;)n+=360;return n}function AB(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 jB(e,t,n){for(let r of t){if(r.points.length<2)continue;let t=n===r.axis;e.strokeStyle=wB[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 MB(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 NB=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 kt({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);XB(t),n=An(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 Yv({canvas:this.editCanvas,engine:this.engine}),this.renderer2d.ignoreStatic=!0,this.renderer2d.viewOverride=this.defaultView(e);else{this.renderer3d=new vP({canvas:this.editCanvas,engine:this.engine}),this.renderer3d.ignoreStatic=!0;let t=KB(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 XB(t),An(t,{stubAllBehaviors:!0}),null}catch(e){return e instanceof Error?e.message:String(e)}}defaultView(e){let t=qB(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 bm(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>sy);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 bm(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>PP);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=GB(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:wB.x},{axis:`y`,sx:0,sy:64,worldPerUnit:64/i,color:wB.y}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D,n=e.position;if(!t||!Array.isArray(n))return null;t.getWorldPosition(zB);let r=this.renderer3d.screenFromWorld(zB.x,zB.y,zB.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(zB.x+t[0]*o,zB.y+t[1]*o,zB.z+t[2]*o);n.behind||i.push({axis:e,sx:n.x-r.x,sy:n.y-r.y,worldPerUnit:o,color:wB[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=GB(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(zB);let n={x:zB.x,y:zB.y,z:zB.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,FB).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 UE&&(t.current||!e)&&(e=t,t.current))break;let t=e?e._ensureObject3D():null;if(t){t.getWorldPosition(IB),LB.set(0,0,-1).applyQuaternion(t.getWorldQuaternion(RB));let e=Math.min(40,Math.max(3,this.orbit.dist));this.orbit.target=[IB.x+LB.x*e,IB.y+LB.y*e,IB.z+LB.z*e],this.orbit.dist=e,this.orbit.yaw=Math.atan2(-LB.x,-LB.z),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,-LB.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 Xk||t instanceof Dv||t instanceof $k||t instanceof _g||t instanceof xk)&&t.update(e)}modelAnimationsAt(e){let t=this.nodeAtPath.get(e.join(`.`));return t instanceof Xk?t.availableAnimations():[]}boneNamesAt(e,t){let n=this.nodeAtPath.get(e.join(`.`));if(!n||t===``)return[];let r=n.getNodeOrNull(t);return r instanceof Xk?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&&MB(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&&MB(e,this.readout.x,this.readout.y,this.readout.text)}drawModeGizmo(e){if(this.gizmoMode===`rotate`){let t=this.ringLayout();t&&jB(e,t.rings,this.activeRing);return}let t=this.gizmoLayout();t&&DB(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=GB(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=AB(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:OB(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=kB(i,OB(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=TB(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]]=PB(g((o[d[t.axis]]??1)*n));else for(let e=0;e<r.length;e++)r[e]=PB(g((o[e]??1)*n));i.scale=r,this.readout={x:e.offsetX,y:e.offsetY,text:`×${r.map(e=>PB(e)).join(`, `)}`};return}let _=[...a];if(t.kind===`axis`){let e=r.axes.find(e=>e.axis===t.axis);if(!e)return;let n=EB(e,c,l);if(u)_[d[t.axis]]=PB(h((a[d[t.axis]]??0)+n));else{let e=UB(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]=PB(h((a[0]??0)+(e.x*c-t.x*l)*n)),_[1]=PB(h((a[1]??0)+(e.y*c-t.y*l)*n)),_[2]=PB(h((a[2]??0)+(e.z*c-t.z*l)*n))}else if(this.renderer2d){let e=this.renderer2d.view(),t=UB(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=>PB(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=UB(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 Vo;for(let[n]of this.pathOf){if(e&&n!==e&&!WB(n,e))continue;let r=n._object3D;r&&(t.expandByObject(r),t.expandByPoint(r.getWorldPosition(zB)))}if(t.isEmpty()&&e){let t=e._object3D,n=t?t.getWorldPosition(zB):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&&!WB(t,e))continue;let n=t.position;if(!Array.isArray(n))continue;let s=GB(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);XB(t);let n;try{n=An(t,{stubAllBehaviors:!0,declareConnectionSignals:!0})}catch(e){return e instanceof Error?e.message:String(e)}let r=new kt;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 Yv({canvas:this.playCanvas,engine:r});let{enablePhysics2D:e}=await bm(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>sy);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}else{this.playRenderer=new vP({canvas:this.playCanvas,engine:r,assets:this.renderer3d?.assets});let{enablePhysics3D:e}=await bm(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>PP);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 PB(e){return Math.round(e*100)/100}var FB=new U(0,1,0),IB=new U,LB=new U,RB=new H,zB=new U,BB=new G,VB=new U,HB=new U;function UB(e,t,n){let r=e._object2D?.parent;return r?(BB.copy(r.matrixWorld).invert(),VB.set(t,-n,0).applyMatrix4(BB),HB.set(0,0,0).applyMatrix4(BB),{x:VB.x-HB.x,y:-(VB.y-HB.y)}):{x:t,y:n}}function WB(e,t){for(let n=e.parent;n;n=n.parent)if(n===t)return!0;return!1}function GB(e){let t=e._object2D;if(t)return t.getWorldPosition(zB),{x:zB.x,y:-zB.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 KB(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=KB(t);if(e)return e}return null}function qB(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=qB(t);if(e)return e}return null}var JB=null;function YB(){if(JB)return JB;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 JB=e.toDataURL(),JB}function XB(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=YB())}var ZB=e({formatSceneJson:()=>r,httpEditorApi:()=>re,mountEditor:()=>QB});_n(),Lv(),qM(),WP(),G_();async function QB(e={}){let t=e.api??re,n=[],r=document.createElement(`style`);r.dataset.incantoEditor=`true`,r.textContent=Jz,document.head.appendChild(r),n.push(()=>r.remove());let i=document.createElement(`div`);i.className=`incanto-editor-root`,i.innerHTML=Oz,(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}`,FL(a(`#popover`)),WF(),a(`#docs-btn`).addEventListener(`click`,()=>HF());let s=a(`#lang-btn`),c=[{code:`en`,label:`English`},{code:`ko`,label:`한국어`}],l=()=>{a(`#lang-current`).textContent=JP()===`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=JP()===t?`✓`:``,a.className=`lang-check`,r.append(i,a),r.addEventListener(`click`,()=>{e.remove(),YP(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)}),XP(()=>{l(),GF(),u.select(u.selection)});let u=new Lz({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,FF.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}=nR(ne(r),Number(i.props?.tileSize??32),e,t),s=i.props?.cells??[],c=rR(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 NB(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 LF)t.includes(e)||t.push(e);for(let e of t){let t=LF.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=>dz(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)=>nV(u,n,t)}:{}}):void 0,de=!1,fe=()=>{if(!T)return;sB(d,u),lF(a(`#asset-tree`),u),f.textContent=``,uF(f,u,Se,ue)||sR(f,u,{modelRefs:()=>eV(u,`model`),animationsForSelection:()=>u.selection?M.modelAnimationsAt(u.selection):[],bonesForSelection:e=>u.selection?M.boneNamesAt(u.selection,e):[],assetRefs:e=>tV(u,e),addAsset:(e,t)=>nV(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,FF.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(),uB(),u.reset(i),o.mode===`project`&&n&&FF.open(n,r)},ge=Dz({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`);kL(u),a(`#generate-btn`).addEventListener(`click`,()=>DL(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=$B(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?$B(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()}),tB(F),nB(e=>{ee(`${ZP({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()),eB(()=>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(),FF.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){UF();return}if(e.key===`Escape`&&!P.hidden){I();return}if(e.key===`Escape`&&!N.hidden){OL();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),FF.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 $B(e){let t=0;for(let n of e.children??[])t+=1+$B(n);return t}function eV(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>e?.type===t).map(([e])=>`$${e}`):[]}function tV(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 nV(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 rV=null,iV=null;function aV(){return iV||(iV=document.createElement(`canvas`),iV.style.cssText=`position:fixed; inset:0; width:100%; height:100%; display:block;`,document.body.appendChild(iV)),iV.style.visibility=``,iV}async function oV(e,t){return rV=await QB({api:re,...e?{camera:e}:{},onPlay:(e,t)=>{e===`debug`&&sV(t)},playHints:{debug:`this page becomes the game — needs a scene with no project behaviors`},...t?{onExit:()=>(rV?.dispose(),rV=null,aV(),t())}:{}}),rV}async function sV(e){let t=e.dimension??`2d`;rV?.dispose(),rV=null;let n=async e=>{iV&&(iV.style.visibility=`hidden`),await oV(e.camera,e.exit)};try{if(t===`3d`){let{createGame3D:t}=await bm(async()=>{let{createGame3D:e}=await Promise.resolve().then(()=>PP);return{createGame3D:e}},void 0,import.meta.url);await t({canvas:aV(),scene:e,debug:!0,editor:{open:n}})}else{let{createGame2D:t}=await bm(async()=>{let{createGame2D:e}=await Promise.resolve().then(()=>sy);return{createGame2D:e}},void 0,import.meta.url);await t({canvas:aV(),scene:e,debug:!0,editor:{open:n}})}}catch(e){iV&&(iV.style.visibility=`hidden`),(await oV()).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.`)}}oV().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,bm as n,Xe as r,tv as t};